GNU Linux-libre 4.19.242-gnu1
[releases.git] / fs / cifs / smb2ops.c
1 /*
2  *  SMB2 version specific operations
3  *
4  *  Copyright (c) 2012, Jeff Layton <jlayton@redhat.com>
5  *
6  *  This library is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License v2 as published
8  *  by the Free Software Foundation.
9  *
10  *  This library is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
13  *  the GNU Lesser General Public License for more details.
14  *
15  *  You should have received a copy of the GNU Lesser General Public License
16  *  along with this library; if not, write to the Free Software
17  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18  */
19
20 #include <linux/pagemap.h>
21 #include <linux/vfs.h>
22 #include <linux/falloc.h>
23 #include <linux/scatterlist.h>
24 #include <linux/uuid.h>
25 #include <crypto/aead.h>
26 #include "cifsglob.h"
27 #include "smb2pdu.h"
28 #include "smb2proto.h"
29 #include "cifsproto.h"
30 #include "cifs_debug.h"
31 #include "cifs_unicode.h"
32 #include "smb2status.h"
33 #include "smb2glob.h"
34 #include "cifs_ioctl.h"
35 #include "smbdirect.h"
36
37 /* Change credits for different ops and return the total number of credits */
38 static int
39 change_conf(struct TCP_Server_Info *server)
40 {
41         server->credits += server->echo_credits + server->oplock_credits;
42         server->oplock_credits = server->echo_credits = 0;
43         switch (server->credits) {
44         case 0:
45                 return 0;
46         case 1:
47                 server->echoes = false;
48                 server->oplocks = false;
49                 break;
50         case 2:
51                 server->echoes = true;
52                 server->oplocks = false;
53                 server->echo_credits = 1;
54                 break;
55         default:
56                 server->echoes = true;
57                 if (enable_oplocks) {
58                         server->oplocks = true;
59                         server->oplock_credits = 1;
60                 } else
61                         server->oplocks = false;
62
63                 server->echo_credits = 1;
64         }
65         server->credits -= server->echo_credits + server->oplock_credits;
66         return server->credits + server->echo_credits + server->oplock_credits;
67 }
68
69 static void
70 smb2_add_credits(struct TCP_Server_Info *server, const unsigned int add,
71                  const int optype)
72 {
73         int *val, rc = -1;
74
75         spin_lock(&server->req_lock);
76         val = server->ops->get_credits_field(server, optype);
77         *val += add;
78         if (*val > 65000) {
79                 *val = 65000; /* Don't get near 64K credits, avoid srv bugs */
80                 printk_once(KERN_WARNING "server overflowed SMB3 credits\n");
81         }
82         server->in_flight--;
83         if (server->in_flight == 0 && (optype & CIFS_OP_MASK) != CIFS_NEG_OP)
84                 rc = change_conf(server);
85         /*
86          * Sometimes server returns 0 credits on oplock break ack - we need to
87          * rebalance credits in this case.
88          */
89         else if (server->in_flight > 0 && server->oplock_credits == 0 &&
90                  server->oplocks) {
91                 if (server->credits > 1) {
92                         server->credits--;
93                         server->oplock_credits++;
94                 }
95         }
96         spin_unlock(&server->req_lock);
97         wake_up(&server->request_q);
98
99         if (server->tcpStatus == CifsNeedReconnect)
100                 return;
101
102         switch (rc) {
103         case -1:
104                 /* change_conf hasn't been executed */
105                 break;
106         case 0:
107                 cifs_dbg(VFS, "Possible client or server bug - zero credits\n");
108                 break;
109         case 1:
110                 cifs_dbg(VFS, "disabling echoes and oplocks\n");
111                 break;
112         case 2:
113                 cifs_dbg(FYI, "disabling oplocks\n");
114                 break;
115         default:
116                 cifs_dbg(FYI, "add %u credits total=%d\n", add, rc);
117         }
118 }
119
120 static void
121 smb2_set_credits(struct TCP_Server_Info *server, const int val)
122 {
123         spin_lock(&server->req_lock);
124         server->credits = val;
125         spin_unlock(&server->req_lock);
126 }
127
128 static int *
129 smb2_get_credits_field(struct TCP_Server_Info *server, const int optype)
130 {
131         switch (optype) {
132         case CIFS_ECHO_OP:
133                 return &server->echo_credits;
134         case CIFS_OBREAK_OP:
135                 return &server->oplock_credits;
136         default:
137                 return &server->credits;
138         }
139 }
140
141 static unsigned int
142 smb2_get_credits(struct mid_q_entry *mid)
143 {
144         struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)mid->resp_buf;
145
146         return le16_to_cpu(shdr->CreditRequest);
147 }
148
149 static int
150 smb2_wait_mtu_credits(struct TCP_Server_Info *server, unsigned int size,
151                       unsigned int *num, unsigned int *credits)
152 {
153         int rc = 0;
154         unsigned int scredits;
155
156         spin_lock(&server->req_lock);
157         while (1) {
158                 if (server->credits <= 0) {
159                         spin_unlock(&server->req_lock);
160                         cifs_num_waiters_inc(server);
161                         rc = wait_event_killable(server->request_q,
162                                         has_credits(server, &server->credits));
163                         cifs_num_waiters_dec(server);
164                         if (rc)
165                                 return rc;
166                         spin_lock(&server->req_lock);
167                 } else {
168                         if (server->tcpStatus == CifsExiting) {
169                                 spin_unlock(&server->req_lock);
170                                 return -ENOENT;
171                         }
172
173                         scredits = server->credits;
174                         /* can deadlock with reopen */
175                         if (scredits <= 8) {
176                                 *num = SMB2_MAX_BUFFER_SIZE;
177                                 *credits = 0;
178                                 break;
179                         }
180
181                         /* leave some credits for reopen and other ops */
182                         scredits -= 8;
183                         *num = min_t(unsigned int, size,
184                                      scredits * SMB2_MAX_BUFFER_SIZE);
185
186                         *credits = DIV_ROUND_UP(*num, SMB2_MAX_BUFFER_SIZE);
187                         server->credits -= *credits;
188                         server->in_flight++;
189                         break;
190                 }
191         }
192         spin_unlock(&server->req_lock);
193         return rc;
194 }
195
196 static __u64
197 smb2_get_next_mid(struct TCP_Server_Info *server)
198 {
199         __u64 mid;
200         /* for SMB2 we need the current value */
201         spin_lock(&GlobalMid_Lock);
202         mid = server->CurrentMid++;
203         spin_unlock(&GlobalMid_Lock);
204         return mid;
205 }
206
207 static void
208 smb2_revert_current_mid(struct TCP_Server_Info *server, const unsigned int val)
209 {
210         spin_lock(&GlobalMid_Lock);
211         if (server->CurrentMid >= val)
212                 server->CurrentMid -= val;
213         spin_unlock(&GlobalMid_Lock);
214 }
215
216 static struct mid_q_entry *
217 smb2_find_mid(struct TCP_Server_Info *server, char *buf)
218 {
219         struct mid_q_entry *mid;
220         struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)buf;
221         __u64 wire_mid = le64_to_cpu(shdr->MessageId);
222
223         if (shdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM) {
224                 cifs_dbg(VFS, "encrypted frame parsing not supported yet");
225                 return NULL;
226         }
227
228         spin_lock(&GlobalMid_Lock);
229         list_for_each_entry(mid, &server->pending_mid_q, qhead) {
230                 if ((mid->mid == wire_mid) &&
231                     (mid->mid_state == MID_REQUEST_SUBMITTED) &&
232                     (mid->command == shdr->Command)) {
233                         kref_get(&mid->refcount);
234                         spin_unlock(&GlobalMid_Lock);
235                         return mid;
236                 }
237         }
238         spin_unlock(&GlobalMid_Lock);
239         return NULL;
240 }
241
242 static void
243 smb2_dump_detail(void *buf, struct TCP_Server_Info *server)
244 {
245 #ifdef CONFIG_CIFS_DEBUG2
246         struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)buf;
247
248         cifs_dbg(VFS, "Cmd: %d Err: 0x%x Flags: 0x%x Mid: %llu Pid: %d\n",
249                  shdr->Command, shdr->Status, shdr->Flags, shdr->MessageId,
250                  shdr->ProcessId);
251         cifs_dbg(VFS, "smb buf %p len %u\n", buf,
252                  server->ops->calc_smb_size(buf, server));
253 #endif
254 }
255
256 static bool
257 smb2_need_neg(struct TCP_Server_Info *server)
258 {
259         return server->max_read == 0;
260 }
261
262 static int
263 smb2_negotiate(const unsigned int xid, struct cifs_ses *ses)
264 {
265         int rc;
266         ses->server->CurrentMid = 0;
267         rc = SMB2_negotiate(xid, ses);
268         /* BB we probably don't need to retry with modern servers */
269         if (rc == -EAGAIN)
270                 rc = -EHOSTDOWN;
271         return rc;
272 }
273
274 static unsigned int
275 smb2_negotiate_wsize(struct cifs_tcon *tcon, struct smb_vol *volume_info)
276 {
277         struct TCP_Server_Info *server = tcon->ses->server;
278         unsigned int wsize;
279
280         /* start with specified wsize, or default */
281         wsize = volume_info->wsize ? volume_info->wsize : CIFS_DEFAULT_IOSIZE;
282         wsize = min_t(unsigned int, wsize, server->max_write);
283 #ifdef CONFIG_CIFS_SMB_DIRECT
284         if (server->rdma) {
285                 if (server->sign)
286                         wsize = min_t(unsigned int,
287                                 wsize, server->smbd_conn->max_fragmented_send_size);
288                 else
289                         wsize = min_t(unsigned int,
290                                 wsize, server->smbd_conn->max_readwrite_size);
291         }
292 #endif
293         if (!(server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
294                 wsize = min_t(unsigned int, wsize, SMB2_MAX_BUFFER_SIZE);
295
296         return wsize;
297 }
298
299 static unsigned int
300 smb2_negotiate_rsize(struct cifs_tcon *tcon, struct smb_vol *volume_info)
301 {
302         struct TCP_Server_Info *server = tcon->ses->server;
303         unsigned int rsize;
304
305         /* start with specified rsize, or default */
306         rsize = volume_info->rsize ? volume_info->rsize : CIFS_DEFAULT_IOSIZE;
307         rsize = min_t(unsigned int, rsize, server->max_read);
308 #ifdef CONFIG_CIFS_SMB_DIRECT
309         if (server->rdma) {
310                 if (server->sign)
311                         rsize = min_t(unsigned int,
312                                 rsize, server->smbd_conn->max_fragmented_recv_size);
313                 else
314                         rsize = min_t(unsigned int,
315                                 rsize, server->smbd_conn->max_readwrite_size);
316         }
317 #endif
318
319         if (!(server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
320                 rsize = min_t(unsigned int, rsize, SMB2_MAX_BUFFER_SIZE);
321
322         return rsize;
323 }
324
325
326 static int
327 parse_server_interfaces(struct network_interface_info_ioctl_rsp *buf,
328                         size_t buf_len,
329                         struct cifs_server_iface **iface_list,
330                         size_t *iface_count)
331 {
332         struct network_interface_info_ioctl_rsp *p;
333         struct sockaddr_in *addr4;
334         struct sockaddr_in6 *addr6;
335         struct iface_info_ipv4 *p4;
336         struct iface_info_ipv6 *p6;
337         struct cifs_server_iface *info;
338         ssize_t bytes_left;
339         size_t next = 0;
340         int nb_iface = 0;
341         int rc = 0;
342
343         *iface_list = NULL;
344         *iface_count = 0;
345
346         /*
347          * Fist pass: count and sanity check
348          */
349
350         bytes_left = buf_len;
351         p = buf;
352         while (bytes_left >= sizeof(*p)) {
353                 nb_iface++;
354                 next = le32_to_cpu(p->Next);
355                 if (!next) {
356                         bytes_left -= sizeof(*p);
357                         break;
358                 }
359                 p = (struct network_interface_info_ioctl_rsp *)((u8 *)p+next);
360                 bytes_left -= next;
361         }
362
363         if (!nb_iface) {
364                 cifs_dbg(VFS, "%s: malformed interface info\n", __func__);
365                 rc = -EINVAL;
366                 goto out;
367         }
368
369         /* Azure rounds the buffer size up 8, to a 16 byte boundary */
370         if ((bytes_left > 8) || p->Next)
371                 cifs_dbg(VFS, "%s: incomplete interface info\n", __func__);
372
373
374         /*
375          * Second pass: extract info to internal structure
376          */
377
378         *iface_list = kcalloc(nb_iface, sizeof(**iface_list), GFP_KERNEL);
379         if (!*iface_list) {
380                 rc = -ENOMEM;
381                 goto out;
382         }
383
384         info = *iface_list;
385         bytes_left = buf_len;
386         p = buf;
387         while (bytes_left >= sizeof(*p)) {
388                 info->speed = le64_to_cpu(p->LinkSpeed);
389                 info->rdma_capable = le32_to_cpu(p->Capability & RDMA_CAPABLE) ? 1 : 0;
390                 info->rss_capable = le32_to_cpu(p->Capability & RSS_CAPABLE) ? 1 : 0;
391
392                 cifs_dbg(FYI, "%s: adding iface %zu\n", __func__, *iface_count);
393                 cifs_dbg(FYI, "%s: speed %zu bps\n", __func__, info->speed);
394                 cifs_dbg(FYI, "%s: capabilities 0x%08x\n", __func__,
395                          le32_to_cpu(p->Capability));
396
397                 switch (p->Family) {
398                 /*
399                  * The kernel and wire socket structures have the same
400                  * layout and use network byte order but make the
401                  * conversion explicit in case either one changes.
402                  */
403                 case INTERNETWORK:
404                         addr4 = (struct sockaddr_in *)&info->sockaddr;
405                         p4 = (struct iface_info_ipv4 *)p->Buffer;
406                         addr4->sin_family = AF_INET;
407                         memcpy(&addr4->sin_addr, &p4->IPv4Address, 4);
408
409                         /* [MS-SMB2] 2.2.32.5.1.1 Clients MUST ignore these */
410                         addr4->sin_port = cpu_to_be16(CIFS_PORT);
411
412                         cifs_dbg(FYI, "%s: ipv4 %pI4\n", __func__,
413                                  &addr4->sin_addr);
414                         break;
415                 case INTERNETWORKV6:
416                         addr6 = (struct sockaddr_in6 *)&info->sockaddr;
417                         p6 = (struct iface_info_ipv6 *)p->Buffer;
418                         addr6->sin6_family = AF_INET6;
419                         memcpy(&addr6->sin6_addr, &p6->IPv6Address, 16);
420
421                         /* [MS-SMB2] 2.2.32.5.1.2 Clients MUST ignore these */
422                         addr6->sin6_flowinfo = 0;
423                         addr6->sin6_scope_id = 0;
424                         addr6->sin6_port = cpu_to_be16(CIFS_PORT);
425
426                         cifs_dbg(FYI, "%s: ipv6 %pI6\n", __func__,
427                                  &addr6->sin6_addr);
428                         break;
429                 default:
430                         cifs_dbg(VFS,
431                                  "%s: skipping unsupported socket family\n",
432                                  __func__);
433                         goto next_iface;
434                 }
435
436                 (*iface_count)++;
437                 info++;
438 next_iface:
439                 next = le32_to_cpu(p->Next);
440                 if (!next)
441                         break;
442                 p = (struct network_interface_info_ioctl_rsp *)((u8 *)p+next);
443                 bytes_left -= next;
444         }
445
446         if (!*iface_count) {
447                 rc = -EINVAL;
448                 goto out;
449         }
450
451 out:
452         if (rc) {
453                 kfree(*iface_list);
454                 *iface_count = 0;
455                 *iface_list = NULL;
456         }
457         return rc;
458 }
459
460
461 static int
462 SMB3_request_interfaces(const unsigned int xid, struct cifs_tcon *tcon)
463 {
464         int rc;
465         unsigned int ret_data_len = 0;
466         struct network_interface_info_ioctl_rsp *out_buf = NULL;
467         struct cifs_server_iface *iface_list;
468         size_t iface_count;
469         struct cifs_ses *ses = tcon->ses;
470
471         rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
472                         FSCTL_QUERY_NETWORK_INTERFACE_INFO, true /* is_fsctl */,
473                         NULL /* no data input */, 0 /* no data input */,
474                         (char **)&out_buf, &ret_data_len);
475         if (rc == -EOPNOTSUPP) {
476                 cifs_dbg(FYI,
477                          "server does not support query network interfaces\n");
478                 goto out;
479         } else if (rc != 0) {
480                 cifs_dbg(VFS, "error %d on ioctl to get interface list\n", rc);
481                 goto out;
482         }
483
484         rc = parse_server_interfaces(out_buf, ret_data_len,
485                                      &iface_list, &iface_count);
486         if (rc)
487                 goto out;
488
489         spin_lock(&ses->iface_lock);
490         kfree(ses->iface_list);
491         ses->iface_list = iface_list;
492         ses->iface_count = iface_count;
493         ses->iface_last_update = jiffies;
494         spin_unlock(&ses->iface_lock);
495
496 out:
497         kfree(out_buf);
498         return rc;
499 }
500
501 static void
502 smb2_close_cached_fid(struct kref *ref)
503 {
504         struct cached_fid *cfid = container_of(ref, struct cached_fid,
505                                                refcount);
506
507         if (cfid->is_valid) {
508                 cifs_dbg(FYI, "clear cached root file handle\n");
509                 SMB2_close(0, cfid->tcon, cfid->fid->persistent_fid,
510                            cfid->fid->volatile_fid);
511                 cfid->is_valid = false;
512         }
513 }
514
515 void close_shroot(struct cached_fid *cfid)
516 {
517         mutex_lock(&cfid->fid_mutex);
518         kref_put(&cfid->refcount, smb2_close_cached_fid);
519         mutex_unlock(&cfid->fid_mutex);
520 }
521
522 void
523 smb2_cached_lease_break(struct work_struct *work)
524 {
525         struct cached_fid *cfid = container_of(work,
526                                 struct cached_fid, lease_break);
527
528         close_shroot(cfid);
529 }
530
531 /*
532  * Open the directory at the root of a share
533  */
534 int open_shroot(unsigned int xid, struct cifs_tcon *tcon, struct cifs_fid *pfid)
535 {
536         struct cifs_open_parms oparams;
537         int rc;
538         __le16 srch_path = 0; /* Null - since an open of top of share */
539         u8 oplock = SMB2_OPLOCK_LEVEL_II;
540
541         mutex_lock(&tcon->crfid.fid_mutex);
542         if (tcon->crfid.is_valid) {
543                 cifs_dbg(FYI, "found a cached root file handle\n");
544                 memcpy(pfid, tcon->crfid.fid, sizeof(struct cifs_fid));
545                 kref_get(&tcon->crfid.refcount);
546                 mutex_unlock(&tcon->crfid.fid_mutex);
547                 return 0;
548         }
549
550         oparams.tcon = tcon;
551         oparams.create_options = 0;
552         oparams.desired_access = FILE_READ_ATTRIBUTES;
553         oparams.disposition = FILE_OPEN;
554         oparams.fid = pfid;
555         oparams.reconnect = false;
556
557         /*
558          * We do not hold the lock for the open because in case
559          * SMB2_open needs to reconnect, it will end up calling
560          * cifs_mark_open_files_invalid() which takes the lock again
561          * thus causing a deadlock
562          */
563         mutex_unlock(&tcon->crfid.fid_mutex);
564         rc = SMB2_open(xid, &oparams, &srch_path, &oplock, NULL, NULL, NULL);
565         mutex_lock(&tcon->crfid.fid_mutex);
566
567         /*
568          * Now we need to check again as the cached root might have
569          * been successfully re-opened from a concurrent process
570          */
571
572         if (tcon->crfid.is_valid) {
573                 /* work was already done */
574
575                 /* stash fids for close() later */
576                 struct cifs_fid fid = {
577                         .persistent_fid = pfid->persistent_fid,
578                         .volatile_fid = pfid->volatile_fid,
579                 };
580
581                 /*
582                  * Caller expects this func to set pfid to a valid
583                  * cached root, so we copy the existing one and get a
584                  * reference
585                  */
586                 memcpy(pfid, tcon->crfid.fid, sizeof(*pfid));
587                 kref_get(&tcon->crfid.refcount);
588
589                 mutex_unlock(&tcon->crfid.fid_mutex);
590
591                 if (rc == 0) {
592                         /* close extra handle outside of critical section */
593                         SMB2_close(xid, tcon, fid.persistent_fid,
594                                    fid.volatile_fid);
595                 }
596                 return 0;
597         }
598
599         /* Cached root is still invalid, continue normaly */
600
601         if (rc == 0) {
602                 memcpy(tcon->crfid.fid, pfid, sizeof(struct cifs_fid));
603                 tcon->crfid.tcon = tcon;
604                 tcon->crfid.is_valid = true;
605                 kref_init(&tcon->crfid.refcount);
606                 kref_get(&tcon->crfid.refcount);
607         }
608
609         mutex_unlock(&tcon->crfid.fid_mutex);
610         return rc;
611 }
612
613 static void
614 smb3_qfs_tcon(const unsigned int xid, struct cifs_tcon *tcon)
615 {
616         int rc;
617         __le16 srch_path = 0; /* Null - open root of share */
618         u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
619         struct cifs_open_parms oparms;
620         struct cifs_fid fid;
621         bool no_cached_open = tcon->nohandlecache;
622
623         oparms.tcon = tcon;
624         oparms.desired_access = FILE_READ_ATTRIBUTES;
625         oparms.disposition = FILE_OPEN;
626         oparms.create_options = 0;
627         oparms.fid = &fid;
628         oparms.reconnect = false;
629
630         if (no_cached_open)
631                 rc = SMB2_open(xid, &oparms, &srch_path, &oplock, NULL, NULL,
632                                NULL);
633         else
634                 rc = open_shroot(xid, tcon, &fid);
635
636         if (rc)
637                 return;
638
639         SMB3_request_interfaces(xid, tcon);
640
641         SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
642                         FS_ATTRIBUTE_INFORMATION);
643         SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
644                         FS_DEVICE_INFORMATION);
645         SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
646                         FS_VOLUME_INFORMATION);
647         SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
648                         FS_SECTOR_SIZE_INFORMATION); /* SMB3 specific */
649         if (no_cached_open)
650                 SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
651         else
652                 close_shroot(&tcon->crfid);
653
654         return;
655 }
656
657 static void
658 smb2_qfs_tcon(const unsigned int xid, struct cifs_tcon *tcon)
659 {
660         int rc;
661         __le16 srch_path = 0; /* Null - open root of share */
662         u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
663         struct cifs_open_parms oparms;
664         struct cifs_fid fid;
665
666         oparms.tcon = tcon;
667         oparms.desired_access = FILE_READ_ATTRIBUTES;
668         oparms.disposition = FILE_OPEN;
669         oparms.create_options = 0;
670         oparms.fid = &fid;
671         oparms.reconnect = false;
672
673         rc = SMB2_open(xid, &oparms, &srch_path, &oplock, NULL, NULL, NULL);
674         if (rc)
675                 return;
676
677         SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
678                         FS_ATTRIBUTE_INFORMATION);
679         SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
680                         FS_DEVICE_INFORMATION);
681         SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
682         return;
683 }
684
685 static int
686 smb2_is_path_accessible(const unsigned int xid, struct cifs_tcon *tcon,
687                         struct cifs_sb_info *cifs_sb, const char *full_path)
688 {
689         int rc;
690         __le16 *utf16_path;
691         __u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
692         struct cifs_open_parms oparms;
693         struct cifs_fid fid;
694
695         if ((*full_path == 0) && tcon->crfid.is_valid)
696                 return 0;
697
698         utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
699         if (!utf16_path)
700                 return -ENOMEM;
701
702         oparms.tcon = tcon;
703         oparms.desired_access = FILE_READ_ATTRIBUTES;
704         oparms.disposition = FILE_OPEN;
705         if (backup_cred(cifs_sb))
706                 oparms.create_options = CREATE_OPEN_BACKUP_INTENT;
707         else
708                 oparms.create_options = 0;
709         oparms.fid = &fid;
710         oparms.reconnect = false;
711
712         rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, NULL, NULL);
713         if (rc) {
714                 kfree(utf16_path);
715                 return rc;
716         }
717
718         rc = SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
719         kfree(utf16_path);
720         return rc;
721 }
722
723 static int
724 smb2_get_srv_inum(const unsigned int xid, struct cifs_tcon *tcon,
725                   struct cifs_sb_info *cifs_sb, const char *full_path,
726                   u64 *uniqueid, FILE_ALL_INFO *data)
727 {
728         *uniqueid = le64_to_cpu(data->IndexNumber);
729         return 0;
730 }
731
732 static int
733 smb2_query_file_info(const unsigned int xid, struct cifs_tcon *tcon,
734                      struct cifs_fid *fid, FILE_ALL_INFO *data)
735 {
736         int rc;
737         struct smb2_file_all_info *smb2_data;
738
739         smb2_data = kzalloc(sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
740                             GFP_KERNEL);
741         if (smb2_data == NULL)
742                 return -ENOMEM;
743
744         rc = SMB2_query_info(xid, tcon, fid->persistent_fid, fid->volatile_fid,
745                              smb2_data);
746         if (!rc)
747                 move_smb2_info_to_cifs(data, smb2_data);
748         kfree(smb2_data);
749         return rc;
750 }
751
752 #ifdef CONFIG_CIFS_XATTR
753 static ssize_t
754 move_smb2_ea_to_cifs(char *dst, size_t dst_size,
755                      struct smb2_file_full_ea_info *src, size_t src_size,
756                      const unsigned char *ea_name)
757 {
758         int rc = 0;
759         unsigned int ea_name_len = ea_name ? strlen(ea_name) : 0;
760         char *name, *value;
761         size_t buf_size = dst_size;
762         size_t name_len, value_len, user_name_len;
763
764         while (src_size > 0) {
765                 name = &src->ea_data[0];
766                 name_len = (size_t)src->ea_name_length;
767                 value = &src->ea_data[src->ea_name_length + 1];
768                 value_len = (size_t)le16_to_cpu(src->ea_value_length);
769
770                 if (name_len == 0) {
771                         break;
772                 }
773
774                 if (src_size < 8 + name_len + 1 + value_len) {
775                         cifs_dbg(FYI, "EA entry goes beyond length of list\n");
776                         rc = -EIO;
777                         goto out;
778                 }
779
780                 if (ea_name) {
781                         if (ea_name_len == name_len &&
782                             memcmp(ea_name, name, name_len) == 0) {
783                                 rc = value_len;
784                                 if (dst_size == 0)
785                                         goto out;
786                                 if (dst_size < value_len) {
787                                         rc = -ERANGE;
788                                         goto out;
789                                 }
790                                 memcpy(dst, value, value_len);
791                                 goto out;
792                         }
793                 } else {
794                         /* 'user.' plus a terminating null */
795                         user_name_len = 5 + 1 + name_len;
796
797                         if (buf_size == 0) {
798                                 /* skip copy - calc size only */
799                                 rc += user_name_len;
800                         } else if (dst_size >= user_name_len) {
801                                 dst_size -= user_name_len;
802                                 memcpy(dst, "user.", 5);
803                                 dst += 5;
804                                 memcpy(dst, src->ea_data, name_len);
805                                 dst += name_len;
806                                 *dst = 0;
807                                 ++dst;
808                                 rc += user_name_len;
809                         } else {
810                                 /* stop before overrun buffer */
811                                 rc = -ERANGE;
812                                 break;
813                         }
814                 }
815
816                 if (!src->next_entry_offset)
817                         break;
818
819                 if (src_size < le32_to_cpu(src->next_entry_offset)) {
820                         /* stop before overrun buffer */
821                         rc = -ERANGE;
822                         break;
823                 }
824                 src_size -= le32_to_cpu(src->next_entry_offset);
825                 src = (void *)((char *)src +
826                                le32_to_cpu(src->next_entry_offset));
827         }
828
829         /* didn't find the named attribute */
830         if (ea_name)
831                 rc = -ENODATA;
832
833 out:
834         return (ssize_t)rc;
835 }
836
837 static ssize_t
838 smb2_query_eas(const unsigned int xid, struct cifs_tcon *tcon,
839                const unsigned char *path, const unsigned char *ea_name,
840                char *ea_data, size_t buf_size,
841                struct cifs_sb_info *cifs_sb)
842 {
843         int rc;
844         __le16 *utf16_path;
845         __u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
846         struct cifs_open_parms oparms;
847         struct cifs_fid fid;
848         struct smb2_file_full_ea_info *smb2_data;
849         int ea_buf_size = SMB2_MIN_EA_BUF;
850
851         utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
852         if (!utf16_path)
853                 return -ENOMEM;
854
855         oparms.tcon = tcon;
856         oparms.desired_access = FILE_READ_EA;
857         oparms.disposition = FILE_OPEN;
858         if (backup_cred(cifs_sb))
859                 oparms.create_options = CREATE_OPEN_BACKUP_INTENT;
860         else
861                 oparms.create_options = 0;
862         oparms.fid = &fid;
863         oparms.reconnect = false;
864
865         rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, NULL, NULL);
866         kfree(utf16_path);
867         if (rc) {
868                 cifs_dbg(FYI, "open failed rc=%d\n", rc);
869                 return rc;
870         }
871
872         while (1) {
873                 smb2_data = kzalloc(ea_buf_size, GFP_KERNEL);
874                 if (smb2_data == NULL) {
875                         SMB2_close(xid, tcon, fid.persistent_fid,
876                                    fid.volatile_fid);
877                         return -ENOMEM;
878                 }
879
880                 rc = SMB2_query_eas(xid, tcon, fid.persistent_fid,
881                                     fid.volatile_fid,
882                                     ea_buf_size, smb2_data);
883
884                 if (rc != -E2BIG)
885                         break;
886
887                 kfree(smb2_data);
888                 ea_buf_size <<= 1;
889
890                 if (ea_buf_size > SMB2_MAX_EA_BUF) {
891                         cifs_dbg(VFS, "EA size is too large\n");
892                         SMB2_close(xid, tcon, fid.persistent_fid,
893                                    fid.volatile_fid);
894                         return -ENOMEM;
895                 }
896         }
897
898         SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
899
900         /*
901          * If ea_name is NULL (listxattr) and there are no EAs, return 0 as it's
902          * not an error. Otherwise, the specified ea_name was not found.
903          */
904         if (!rc)
905                 rc = move_smb2_ea_to_cifs(ea_data, buf_size, smb2_data,
906                                           SMB2_MAX_EA_BUF, ea_name);
907         else if (!ea_name && rc == -ENODATA)
908                 rc = 0;
909
910         kfree(smb2_data);
911         return rc;
912 }
913
914
915 static int
916 smb2_set_ea(const unsigned int xid, struct cifs_tcon *tcon,
917             const char *path, const char *ea_name, const void *ea_value,
918             const __u16 ea_value_len, const struct nls_table *nls_codepage,
919             struct cifs_sb_info *cifs_sb)
920 {
921         int rc;
922         __le16 *utf16_path;
923         __u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
924         struct cifs_open_parms oparms;
925         struct cifs_fid fid;
926         struct smb2_file_full_ea_info *ea;
927         int ea_name_len = strlen(ea_name);
928         int len;
929
930         if (ea_name_len > 255)
931                 return -EINVAL;
932
933         utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
934         if (!utf16_path)
935                 return -ENOMEM;
936
937         oparms.tcon = tcon;
938         oparms.desired_access = FILE_WRITE_EA;
939         oparms.disposition = FILE_OPEN;
940         if (backup_cred(cifs_sb))
941                 oparms.create_options = CREATE_OPEN_BACKUP_INTENT;
942         else
943                 oparms.create_options = 0;
944         oparms.fid = &fid;
945         oparms.reconnect = false;
946
947         rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, NULL, NULL);
948         kfree(utf16_path);
949         if (rc) {
950                 cifs_dbg(FYI, "open failed rc=%d\n", rc);
951                 return rc;
952         }
953
954         len = sizeof(*ea) + ea_name_len + ea_value_len + 1;
955         ea = kzalloc(len, GFP_KERNEL);
956         if (ea == NULL) {
957                 SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
958                 return -ENOMEM;
959         }
960
961         ea->ea_name_length = ea_name_len;
962         ea->ea_value_length = cpu_to_le16(ea_value_len);
963         memcpy(ea->ea_data, ea_name, ea_name_len + 1);
964         memcpy(ea->ea_data + ea_name_len + 1, ea_value, ea_value_len);
965
966         rc = SMB2_set_ea(xid, tcon, fid.persistent_fid, fid.volatile_fid, ea,
967                          len);
968         kfree(ea);
969
970         SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
971
972         return rc;
973 }
974 #endif
975
976 static bool
977 smb2_can_echo(struct TCP_Server_Info *server)
978 {
979         return server->echoes;
980 }
981
982 static void
983 smb2_clear_stats(struct cifs_tcon *tcon)
984 {
985         int i;
986         for (i = 0; i < NUMBER_OF_SMB2_COMMANDS; i++) {
987                 atomic_set(&tcon->stats.smb2_stats.smb2_com_sent[i], 0);
988                 atomic_set(&tcon->stats.smb2_stats.smb2_com_failed[i], 0);
989         }
990 }
991
992 static void
993 smb2_dump_share_caps(struct seq_file *m, struct cifs_tcon *tcon)
994 {
995         seq_puts(m, "\n\tShare Capabilities:");
996         if (tcon->capabilities & SMB2_SHARE_CAP_DFS)
997                 seq_puts(m, " DFS,");
998         if (tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
999                 seq_puts(m, " CONTINUOUS AVAILABILITY,");
1000         if (tcon->capabilities & SMB2_SHARE_CAP_SCALEOUT)
1001                 seq_puts(m, " SCALEOUT,");
1002         if (tcon->capabilities & SMB2_SHARE_CAP_CLUSTER)
1003                 seq_puts(m, " CLUSTER,");
1004         if (tcon->capabilities & SMB2_SHARE_CAP_ASYMMETRIC)
1005                 seq_puts(m, " ASYMMETRIC,");
1006         if (tcon->capabilities == 0)
1007                 seq_puts(m, " None");
1008         if (tcon->ss_flags & SSINFO_FLAGS_ALIGNED_DEVICE)
1009                 seq_puts(m, " Aligned,");
1010         if (tcon->ss_flags & SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE)
1011                 seq_puts(m, " Partition Aligned,");
1012         if (tcon->ss_flags & SSINFO_FLAGS_NO_SEEK_PENALTY)
1013                 seq_puts(m, " SSD,");
1014         if (tcon->ss_flags & SSINFO_FLAGS_TRIM_ENABLED)
1015                 seq_puts(m, " TRIM-support,");
1016
1017         seq_printf(m, "\tShare Flags: 0x%x", tcon->share_flags);
1018         seq_printf(m, "\n\ttid: 0x%x", tcon->tid);
1019         if (tcon->perf_sector_size)
1020                 seq_printf(m, "\tOptimal sector size: 0x%x",
1021                            tcon->perf_sector_size);
1022         seq_printf(m, "\tMaximal Access: 0x%x", tcon->maximal_access);
1023 }
1024
1025 static void
1026 smb2_print_stats(struct seq_file *m, struct cifs_tcon *tcon)
1027 {
1028         atomic_t *sent = tcon->stats.smb2_stats.smb2_com_sent;
1029         atomic_t *failed = tcon->stats.smb2_stats.smb2_com_failed;
1030
1031         /*
1032          *  Can't display SMB2_NEGOTIATE, SESSION_SETUP, LOGOFF, CANCEL and ECHO
1033          *  totals (requests sent) since those SMBs are per-session not per tcon
1034          */
1035         seq_printf(m, "\nBytes read: %llu  Bytes written: %llu",
1036                    (long long)(tcon->bytes_read),
1037                    (long long)(tcon->bytes_written));
1038         seq_printf(m, "\nTreeConnects: %d total %d failed",
1039                    atomic_read(&sent[SMB2_TREE_CONNECT_HE]),
1040                    atomic_read(&failed[SMB2_TREE_CONNECT_HE]));
1041         seq_printf(m, "\nTreeDisconnects: %d total %d failed",
1042                    atomic_read(&sent[SMB2_TREE_DISCONNECT_HE]),
1043                    atomic_read(&failed[SMB2_TREE_DISCONNECT_HE]));
1044         seq_printf(m, "\nCreates: %d total %d failed",
1045                    atomic_read(&sent[SMB2_CREATE_HE]),
1046                    atomic_read(&failed[SMB2_CREATE_HE]));
1047         seq_printf(m, "\nCloses: %d total %d failed",
1048                    atomic_read(&sent[SMB2_CLOSE_HE]),
1049                    atomic_read(&failed[SMB2_CLOSE_HE]));
1050         seq_printf(m, "\nFlushes: %d total %d failed",
1051                    atomic_read(&sent[SMB2_FLUSH_HE]),
1052                    atomic_read(&failed[SMB2_FLUSH_HE]));
1053         seq_printf(m, "\nReads: %d total %d failed",
1054                    atomic_read(&sent[SMB2_READ_HE]),
1055                    atomic_read(&failed[SMB2_READ_HE]));
1056         seq_printf(m, "\nWrites: %d total %d failed",
1057                    atomic_read(&sent[SMB2_WRITE_HE]),
1058                    atomic_read(&failed[SMB2_WRITE_HE]));
1059         seq_printf(m, "\nLocks: %d total %d failed",
1060                    atomic_read(&sent[SMB2_LOCK_HE]),
1061                    atomic_read(&failed[SMB2_LOCK_HE]));
1062         seq_printf(m, "\nIOCTLs: %d total %d failed",
1063                    atomic_read(&sent[SMB2_IOCTL_HE]),
1064                    atomic_read(&failed[SMB2_IOCTL_HE]));
1065         seq_printf(m, "\nQueryDirectories: %d total %d failed",
1066                    atomic_read(&sent[SMB2_QUERY_DIRECTORY_HE]),
1067                    atomic_read(&failed[SMB2_QUERY_DIRECTORY_HE]));
1068         seq_printf(m, "\nChangeNotifies: %d total %d failed",
1069                    atomic_read(&sent[SMB2_CHANGE_NOTIFY_HE]),
1070                    atomic_read(&failed[SMB2_CHANGE_NOTIFY_HE]));
1071         seq_printf(m, "\nQueryInfos: %d total %d failed",
1072                    atomic_read(&sent[SMB2_QUERY_INFO_HE]),
1073                    atomic_read(&failed[SMB2_QUERY_INFO_HE]));
1074         seq_printf(m, "\nSetInfos: %d total %d failed",
1075                    atomic_read(&sent[SMB2_SET_INFO_HE]),
1076                    atomic_read(&failed[SMB2_SET_INFO_HE]));
1077         seq_printf(m, "\nOplockBreaks: %d sent %d failed",
1078                    atomic_read(&sent[SMB2_OPLOCK_BREAK_HE]),
1079                    atomic_read(&failed[SMB2_OPLOCK_BREAK_HE]));
1080 }
1081
1082 static void
1083 smb2_set_fid(struct cifsFileInfo *cfile, struct cifs_fid *fid, __u32 oplock)
1084 {
1085         struct cifsInodeInfo *cinode = CIFS_I(d_inode(cfile->dentry));
1086         struct TCP_Server_Info *server = tlink_tcon(cfile->tlink)->ses->server;
1087
1088         cfile->fid.persistent_fid = fid->persistent_fid;
1089         cfile->fid.volatile_fid = fid->volatile_fid;
1090         server->ops->set_oplock_level(cinode, oplock, fid->epoch,
1091                                       &fid->purge_cache);
1092         cinode->can_cache_brlcks = CIFS_CACHE_WRITE(cinode);
1093         memcpy(cfile->fid.create_guid, fid->create_guid, 16);
1094 }
1095
1096 static void
1097 smb2_close_file(const unsigned int xid, struct cifs_tcon *tcon,
1098                 struct cifs_fid *fid)
1099 {
1100         SMB2_close(xid, tcon, fid->persistent_fid, fid->volatile_fid);
1101 }
1102
1103 static int
1104 SMB2_request_res_key(const unsigned int xid, struct cifs_tcon *tcon,
1105                      u64 persistent_fid, u64 volatile_fid,
1106                      struct copychunk_ioctl *pcchunk)
1107 {
1108         int rc;
1109         unsigned int ret_data_len;
1110         struct resume_key_req *res_key;
1111
1112         rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
1113                         FSCTL_SRV_REQUEST_RESUME_KEY, true /* is_fsctl */,
1114                         NULL, 0 /* no input */,
1115                         (char **)&res_key, &ret_data_len);
1116
1117         if (rc) {
1118                 cifs_dbg(VFS, "refcpy ioctl error %d getting resume key\n", rc);
1119                 goto req_res_key_exit;
1120         }
1121         if (ret_data_len < sizeof(struct resume_key_req)) {
1122                 cifs_dbg(VFS, "Invalid refcopy resume key length\n");
1123                 rc = -EINVAL;
1124                 goto req_res_key_exit;
1125         }
1126         memcpy(pcchunk->SourceKey, res_key->ResumeKey, COPY_CHUNK_RES_KEY_SIZE);
1127
1128 req_res_key_exit:
1129         kfree(res_key);
1130         return rc;
1131 }
1132
1133 static ssize_t
1134 smb2_copychunk_range(const unsigned int xid,
1135                         struct cifsFileInfo *srcfile,
1136                         struct cifsFileInfo *trgtfile, u64 src_off,
1137                         u64 len, u64 dest_off)
1138 {
1139         int rc;
1140         unsigned int ret_data_len;
1141         struct copychunk_ioctl *pcchunk;
1142         struct copychunk_ioctl_rsp *retbuf = NULL;
1143         struct cifs_tcon *tcon;
1144         int chunks_copied = 0;
1145         bool chunk_sizes_updated = false;
1146         ssize_t bytes_written, total_bytes_written = 0;
1147         struct inode *inode;
1148
1149         pcchunk = kmalloc(sizeof(struct copychunk_ioctl), GFP_KERNEL);
1150
1151         /*
1152          * We need to flush all unwritten data before we can send the
1153          * copychunk ioctl to the server.
1154          */
1155         inode = d_inode(trgtfile->dentry);
1156         filemap_write_and_wait(inode->i_mapping);
1157
1158         if (pcchunk == NULL)
1159                 return -ENOMEM;
1160
1161         cifs_dbg(FYI, "in smb2_copychunk_range - about to call request res key\n");
1162         /* Request a key from the server to identify the source of the copy */
1163         rc = SMB2_request_res_key(xid, tlink_tcon(srcfile->tlink),
1164                                 srcfile->fid.persistent_fid,
1165                                 srcfile->fid.volatile_fid, pcchunk);
1166
1167         /* Note: request_res_key sets res_key null only if rc !=0 */
1168         if (rc)
1169                 goto cchunk_out;
1170
1171         /* For now array only one chunk long, will make more flexible later */
1172         pcchunk->ChunkCount = cpu_to_le32(1);
1173         pcchunk->Reserved = 0;
1174         pcchunk->Reserved2 = 0;
1175
1176         tcon = tlink_tcon(trgtfile->tlink);
1177
1178         while (len > 0) {
1179                 pcchunk->SourceOffset = cpu_to_le64(src_off);
1180                 pcchunk->TargetOffset = cpu_to_le64(dest_off);
1181                 pcchunk->Length =
1182                         cpu_to_le32(min_t(u32, len, tcon->max_bytes_chunk));
1183
1184                 /* Request server copy to target from src identified by key */
1185                 kfree(retbuf);
1186                 retbuf = NULL;
1187                 rc = SMB2_ioctl(xid, tcon, trgtfile->fid.persistent_fid,
1188                         trgtfile->fid.volatile_fid, FSCTL_SRV_COPYCHUNK_WRITE,
1189                         true /* is_fsctl */, (char *)pcchunk,
1190                         sizeof(struct copychunk_ioctl), (char **)&retbuf,
1191                         &ret_data_len);
1192                 if (rc == 0) {
1193                         if (ret_data_len !=
1194                                         sizeof(struct copychunk_ioctl_rsp)) {
1195                                 cifs_dbg(VFS, "invalid cchunk response size\n");
1196                                 rc = -EIO;
1197                                 goto cchunk_out;
1198                         }
1199                         if (retbuf->TotalBytesWritten == 0) {
1200                                 cifs_dbg(FYI, "no bytes copied\n");
1201                                 rc = -EIO;
1202                                 goto cchunk_out;
1203                         }
1204                         /*
1205                          * Check if server claimed to write more than we asked
1206                          */
1207                         if (le32_to_cpu(retbuf->TotalBytesWritten) >
1208                             le32_to_cpu(pcchunk->Length)) {
1209                                 cifs_dbg(VFS, "invalid copy chunk response\n");
1210                                 rc = -EIO;
1211                                 goto cchunk_out;
1212                         }
1213                         if (le32_to_cpu(retbuf->ChunksWritten) != 1) {
1214                                 cifs_dbg(VFS, "invalid num chunks written\n");
1215                                 rc = -EIO;
1216                                 goto cchunk_out;
1217                         }
1218                         chunks_copied++;
1219
1220                         bytes_written = le32_to_cpu(retbuf->TotalBytesWritten);
1221                         src_off += bytes_written;
1222                         dest_off += bytes_written;
1223                         len -= bytes_written;
1224                         total_bytes_written += bytes_written;
1225
1226                         cifs_dbg(FYI, "Chunks %d PartialChunk %d Total %zu\n",
1227                                 le32_to_cpu(retbuf->ChunksWritten),
1228                                 le32_to_cpu(retbuf->ChunkBytesWritten),
1229                                 bytes_written);
1230                 } else if (rc == -EINVAL) {
1231                         if (ret_data_len != sizeof(struct copychunk_ioctl_rsp))
1232                                 goto cchunk_out;
1233
1234                         cifs_dbg(FYI, "MaxChunks %d BytesChunk %d MaxCopy %d\n",
1235                                 le32_to_cpu(retbuf->ChunksWritten),
1236                                 le32_to_cpu(retbuf->ChunkBytesWritten),
1237                                 le32_to_cpu(retbuf->TotalBytesWritten));
1238
1239                         /*
1240                          * Check if this is the first request using these sizes,
1241                          * (ie check if copy succeed once with original sizes
1242                          * and check if the server gave us different sizes after
1243                          * we already updated max sizes on previous request).
1244                          * if not then why is the server returning an error now
1245                          */
1246                         if ((chunks_copied != 0) || chunk_sizes_updated)
1247                                 goto cchunk_out;
1248
1249                         /* Check that server is not asking us to grow size */
1250                         if (le32_to_cpu(retbuf->ChunkBytesWritten) <
1251                                         tcon->max_bytes_chunk)
1252                                 tcon->max_bytes_chunk =
1253                                         le32_to_cpu(retbuf->ChunkBytesWritten);
1254                         else
1255                                 goto cchunk_out; /* server gave us bogus size */
1256
1257                         /* No need to change MaxChunks since already set to 1 */
1258                         chunk_sizes_updated = true;
1259                 } else
1260                         goto cchunk_out;
1261         }
1262
1263 cchunk_out:
1264         kfree(pcchunk);
1265         kfree(retbuf);
1266         if (rc)
1267                 return rc;
1268         else
1269                 return total_bytes_written;
1270 }
1271
1272 static int
1273 smb2_flush_file(const unsigned int xid, struct cifs_tcon *tcon,
1274                 struct cifs_fid *fid)
1275 {
1276         return SMB2_flush(xid, tcon, fid->persistent_fid, fid->volatile_fid);
1277 }
1278
1279 static unsigned int
1280 smb2_read_data_offset(char *buf)
1281 {
1282         struct smb2_read_rsp *rsp = (struct smb2_read_rsp *)buf;
1283         return rsp->DataOffset;
1284 }
1285
1286 static unsigned int
1287 smb2_read_data_length(char *buf, bool in_remaining)
1288 {
1289         struct smb2_read_rsp *rsp = (struct smb2_read_rsp *)buf;
1290
1291         if (in_remaining)
1292                 return le32_to_cpu(rsp->DataRemaining);
1293
1294         return le32_to_cpu(rsp->DataLength);
1295 }
1296
1297
1298 static int
1299 smb2_sync_read(const unsigned int xid, struct cifs_fid *pfid,
1300                struct cifs_io_parms *parms, unsigned int *bytes_read,
1301                char **buf, int *buf_type)
1302 {
1303         parms->persistent_fid = pfid->persistent_fid;
1304         parms->volatile_fid = pfid->volatile_fid;
1305         return SMB2_read(xid, parms, bytes_read, buf, buf_type);
1306 }
1307
1308 static int
1309 smb2_sync_write(const unsigned int xid, struct cifs_fid *pfid,
1310                 struct cifs_io_parms *parms, unsigned int *written,
1311                 struct kvec *iov, unsigned long nr_segs)
1312 {
1313
1314         parms->persistent_fid = pfid->persistent_fid;
1315         parms->volatile_fid = pfid->volatile_fid;
1316         return SMB2_write(xid, parms, written, iov, nr_segs);
1317 }
1318
1319 /* Set or clear the SPARSE_FILE attribute based on value passed in setsparse */
1320 static bool smb2_set_sparse(const unsigned int xid, struct cifs_tcon *tcon,
1321                 struct cifsFileInfo *cfile, struct inode *inode, __u8 setsparse)
1322 {
1323         struct cifsInodeInfo *cifsi;
1324         int rc;
1325
1326         cifsi = CIFS_I(inode);
1327
1328         /* if file already sparse don't bother setting sparse again */
1329         if ((cifsi->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE) && setsparse)
1330                 return true; /* already sparse */
1331
1332         if (!(cifsi->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE) && !setsparse)
1333                 return true; /* already not sparse */
1334
1335         /*
1336          * Can't check for sparse support on share the usual way via the
1337          * FS attribute info (FILE_SUPPORTS_SPARSE_FILES) on the share
1338          * since Samba server doesn't set the flag on the share, yet
1339          * supports the set sparse FSCTL and returns sparse correctly
1340          * in the file attributes. If we fail setting sparse though we
1341          * mark that server does not support sparse files for this share
1342          * to avoid repeatedly sending the unsupported fsctl to server
1343          * if the file is repeatedly extended.
1344          */
1345         if (tcon->broken_sparse_sup)
1346                 return false;
1347
1348         rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
1349                         cfile->fid.volatile_fid, FSCTL_SET_SPARSE,
1350                         true /* is_fctl */,
1351                         &setsparse, 1, NULL, NULL);
1352         if (rc) {
1353                 tcon->broken_sparse_sup = true;
1354                 cifs_dbg(FYI, "set sparse rc = %d\n", rc);
1355                 return false;
1356         }
1357
1358         if (setsparse)
1359                 cifsi->cifsAttrs |= FILE_ATTRIBUTE_SPARSE_FILE;
1360         else
1361                 cifsi->cifsAttrs &= (~FILE_ATTRIBUTE_SPARSE_FILE);
1362
1363         return true;
1364 }
1365
1366 static int
1367 smb2_set_file_size(const unsigned int xid, struct cifs_tcon *tcon,
1368                    struct cifsFileInfo *cfile, __u64 size, bool set_alloc)
1369 {
1370         __le64 eof = cpu_to_le64(size);
1371         struct inode *inode;
1372
1373         /*
1374          * If extending file more than one page make sparse. Many Linux fs
1375          * make files sparse by default when extending via ftruncate
1376          */
1377         inode = d_inode(cfile->dentry);
1378
1379         if (!set_alloc && (size > inode->i_size + 8192)) {
1380                 __u8 set_sparse = 1;
1381
1382                 /* whether set sparse succeeds or not, extend the file */
1383                 smb2_set_sparse(xid, tcon, cfile, inode, set_sparse);
1384         }
1385
1386         return SMB2_set_eof(xid, tcon, cfile->fid.persistent_fid,
1387                             cfile->fid.volatile_fid, cfile->pid, &eof, false);
1388 }
1389
1390 static int
1391 smb2_duplicate_extents(const unsigned int xid,
1392                         struct cifsFileInfo *srcfile,
1393                         struct cifsFileInfo *trgtfile, u64 src_off,
1394                         u64 len, u64 dest_off)
1395 {
1396         int rc;
1397         unsigned int ret_data_len;
1398         struct duplicate_extents_to_file dup_ext_buf;
1399         struct cifs_tcon *tcon = tlink_tcon(trgtfile->tlink);
1400
1401         /* server fileays advertise duplicate extent support with this flag */
1402         if ((le32_to_cpu(tcon->fsAttrInfo.Attributes) &
1403              FILE_SUPPORTS_BLOCK_REFCOUNTING) == 0)
1404                 return -EOPNOTSUPP;
1405
1406         dup_ext_buf.VolatileFileHandle = srcfile->fid.volatile_fid;
1407         dup_ext_buf.PersistentFileHandle = srcfile->fid.persistent_fid;
1408         dup_ext_buf.SourceFileOffset = cpu_to_le64(src_off);
1409         dup_ext_buf.TargetFileOffset = cpu_to_le64(dest_off);
1410         dup_ext_buf.ByteCount = cpu_to_le64(len);
1411         cifs_dbg(FYI, "duplicate extents: src off %lld dst off %lld len %lld",
1412                 src_off, dest_off, len);
1413
1414         rc = smb2_set_file_size(xid, tcon, trgtfile, dest_off + len, false);
1415         if (rc)
1416                 goto duplicate_extents_out;
1417
1418         rc = SMB2_ioctl(xid, tcon, trgtfile->fid.persistent_fid,
1419                         trgtfile->fid.volatile_fid,
1420                         FSCTL_DUPLICATE_EXTENTS_TO_FILE,
1421                         true /* is_fsctl */,
1422                         (char *)&dup_ext_buf,
1423                         sizeof(struct duplicate_extents_to_file),
1424                         NULL,
1425                         &ret_data_len);
1426
1427         if (ret_data_len > 0)
1428                 cifs_dbg(FYI, "non-zero response length in duplicate extents");
1429
1430 duplicate_extents_out:
1431         return rc;
1432 }
1433
1434 static int
1435 smb2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
1436                    struct cifsFileInfo *cfile)
1437 {
1438         return SMB2_set_compression(xid, tcon, cfile->fid.persistent_fid,
1439                             cfile->fid.volatile_fid);
1440 }
1441
1442 static int
1443 smb3_set_integrity(const unsigned int xid, struct cifs_tcon *tcon,
1444                    struct cifsFileInfo *cfile)
1445 {
1446         struct fsctl_set_integrity_information_req integr_info;
1447         unsigned int ret_data_len;
1448
1449         integr_info.ChecksumAlgorithm = cpu_to_le16(CHECKSUM_TYPE_UNCHANGED);
1450         integr_info.Flags = 0;
1451         integr_info.Reserved = 0;
1452
1453         return SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
1454                         cfile->fid.volatile_fid,
1455                         FSCTL_SET_INTEGRITY_INFORMATION,
1456                         true /* is_fsctl */,
1457                         (char *)&integr_info,
1458                         sizeof(struct fsctl_set_integrity_information_req),
1459                         NULL,
1460                         &ret_data_len);
1461
1462 }
1463
1464 /* GMT Token is @GMT-YYYY.MM.DD-HH.MM.SS Unicode which is 48 bytes + null */
1465 #define GMT_TOKEN_SIZE 50
1466
1467 /*
1468  * Input buffer contains (empty) struct smb_snapshot array with size filled in
1469  * For output see struct SRV_SNAPSHOT_ARRAY in MS-SMB2 section 2.2.32.2
1470  */
1471 static int
1472 smb3_enum_snapshots(const unsigned int xid, struct cifs_tcon *tcon,
1473                    struct cifsFileInfo *cfile, void __user *ioc_buf)
1474 {
1475         char *retbuf = NULL;
1476         unsigned int ret_data_len = 0;
1477         int rc;
1478         struct smb_snapshot_array snapshot_in;
1479
1480         rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
1481                         cfile->fid.volatile_fid,
1482                         FSCTL_SRV_ENUMERATE_SNAPSHOTS,
1483                         true /* is_fsctl */,
1484                         NULL, 0 /* no input data */,
1485                         (char **)&retbuf,
1486                         &ret_data_len);
1487         cifs_dbg(FYI, "enum snaphots ioctl returned %d and ret buflen is %d\n",
1488                         rc, ret_data_len);
1489         if (rc)
1490                 return rc;
1491
1492         if (ret_data_len && (ioc_buf != NULL) && (retbuf != NULL)) {
1493                 /* Fixup buffer */
1494                 if (copy_from_user(&snapshot_in, ioc_buf,
1495                     sizeof(struct smb_snapshot_array))) {
1496                         rc = -EFAULT;
1497                         kfree(retbuf);
1498                         return rc;
1499                 }
1500
1501                 /*
1502                  * Check for min size, ie not large enough to fit even one GMT
1503                  * token (snapshot).  On the first ioctl some users may pass in
1504                  * smaller size (or zero) to simply get the size of the array
1505                  * so the user space caller can allocate sufficient memory
1506                  * and retry the ioctl again with larger array size sufficient
1507                  * to hold all of the snapshot GMT tokens on the second try.
1508                  */
1509                 if (snapshot_in.snapshot_array_size < GMT_TOKEN_SIZE)
1510                         ret_data_len = sizeof(struct smb_snapshot_array);
1511
1512                 /*
1513                  * We return struct SRV_SNAPSHOT_ARRAY, followed by
1514                  * the snapshot array (of 50 byte GMT tokens) each
1515                  * representing an available previous version of the data
1516                  */
1517                 if (ret_data_len > (snapshot_in.snapshot_array_size +
1518                                         sizeof(struct smb_snapshot_array)))
1519                         ret_data_len = snapshot_in.snapshot_array_size +
1520                                         sizeof(struct smb_snapshot_array);
1521
1522                 if (copy_to_user(ioc_buf, retbuf, ret_data_len))
1523                         rc = -EFAULT;
1524         }
1525
1526         kfree(retbuf);
1527         return rc;
1528 }
1529
1530 static int
1531 smb2_query_dir_first(const unsigned int xid, struct cifs_tcon *tcon,
1532                      const char *path, struct cifs_sb_info *cifs_sb,
1533                      struct cifs_fid *fid, __u16 search_flags,
1534                      struct cifs_search_info *srch_inf)
1535 {
1536         __le16 *utf16_path;
1537         int rc;
1538         __u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
1539         struct cifs_open_parms oparms;
1540
1541         utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
1542         if (!utf16_path)
1543                 return -ENOMEM;
1544
1545         oparms.tcon = tcon;
1546         oparms.desired_access = FILE_READ_ATTRIBUTES | FILE_READ_DATA;
1547         oparms.disposition = FILE_OPEN;
1548         if (backup_cred(cifs_sb))
1549                 oparms.create_options = CREATE_OPEN_BACKUP_INTENT;
1550         else
1551                 oparms.create_options = 0;
1552         oparms.fid = fid;
1553         oparms.reconnect = false;
1554
1555         rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, NULL, NULL);
1556         kfree(utf16_path);
1557         if (rc) {
1558                 cifs_dbg(FYI, "open dir failed rc=%d\n", rc);
1559                 return rc;
1560         }
1561
1562         srch_inf->entries_in_buffer = 0;
1563         srch_inf->index_of_last_entry = 2;
1564
1565         rc = SMB2_query_directory(xid, tcon, fid->persistent_fid,
1566                                   fid->volatile_fid, 0, srch_inf);
1567         if (rc) {
1568                 cifs_dbg(FYI, "query directory failed rc=%d\n", rc);
1569                 SMB2_close(xid, tcon, fid->persistent_fid, fid->volatile_fid);
1570         }
1571         return rc;
1572 }
1573
1574 static int
1575 smb2_query_dir_next(const unsigned int xid, struct cifs_tcon *tcon,
1576                     struct cifs_fid *fid, __u16 search_flags,
1577                     struct cifs_search_info *srch_inf)
1578 {
1579         return SMB2_query_directory(xid, tcon, fid->persistent_fid,
1580                                     fid->volatile_fid, 0, srch_inf);
1581 }
1582
1583 static int
1584 smb2_close_dir(const unsigned int xid, struct cifs_tcon *tcon,
1585                struct cifs_fid *fid)
1586 {
1587         return SMB2_close(xid, tcon, fid->persistent_fid, fid->volatile_fid);
1588 }
1589
1590 /*
1591 * If we negotiate SMB2 protocol and get STATUS_PENDING - update
1592 * the number of credits and return true. Otherwise - return false.
1593 */
1594 static bool
1595 smb2_is_status_pending(char *buf, struct TCP_Server_Info *server, int length)
1596 {
1597         struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)buf;
1598
1599         if (shdr->Status != STATUS_PENDING)
1600                 return false;
1601
1602         if (!length) {
1603                 spin_lock(&server->req_lock);
1604                 server->credits += le16_to_cpu(shdr->CreditRequest);
1605                 spin_unlock(&server->req_lock);
1606                 wake_up(&server->request_q);
1607         }
1608
1609         return true;
1610 }
1611
1612 static bool
1613 smb2_is_session_expired(char *buf)
1614 {
1615         struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)buf;
1616
1617         if (shdr->Status != STATUS_NETWORK_SESSION_EXPIRED &&
1618             shdr->Status != STATUS_USER_SESSION_DELETED)
1619                 return false;
1620
1621         trace_smb3_ses_expired(shdr->TreeId, shdr->SessionId,
1622                                le16_to_cpu(shdr->Command),
1623                                le64_to_cpu(shdr->MessageId));
1624         cifs_dbg(FYI, "Session expired or deleted\n");
1625
1626         return true;
1627 }
1628
1629 static int
1630 smb2_oplock_response(struct cifs_tcon *tcon, struct cifs_fid *fid,
1631                      struct cifsInodeInfo *cinode)
1632 {
1633         if (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_LEASING)
1634                 return SMB2_lease_break(0, tcon, cinode->lease_key,
1635                                         smb2_get_lease_state(cinode));
1636
1637         return SMB2_oplock_break(0, tcon, fid->persistent_fid,
1638                                  fid->volatile_fid,
1639                                  CIFS_CACHE_READ(cinode) ? 1 : 0);
1640 }
1641
1642 static void
1643 smb2_set_related(struct smb_rqst *rqst)
1644 {
1645         struct smb2_sync_hdr *shdr;
1646
1647         shdr = (struct smb2_sync_hdr *)(rqst->rq_iov[0].iov_base);
1648         shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
1649 }
1650
1651 char smb2_padding[7] = {0, 0, 0, 0, 0, 0, 0};
1652
1653 static void
1654 smb2_set_next_command(struct TCP_Server_Info *server, struct smb_rqst *rqst)
1655 {
1656         struct smb2_sync_hdr *shdr;
1657         unsigned long len = smb_rqst_len(server, rqst);
1658
1659         /* SMB headers in a compound are 8 byte aligned. */
1660         if (len & 7) {
1661                 rqst->rq_iov[rqst->rq_nvec].iov_base = smb2_padding;
1662                 rqst->rq_iov[rqst->rq_nvec].iov_len = 8 - (len & 7);
1663                 rqst->rq_nvec++;
1664                 len = smb_rqst_len(server, rqst);
1665         }
1666
1667         shdr = (struct smb2_sync_hdr *)(rqst->rq_iov[0].iov_base);
1668         shdr->NextCommand = cpu_to_le32(len);
1669 }
1670
1671 static int
1672 smb2_queryfs(const unsigned int xid, struct cifs_tcon *tcon,
1673              struct kstatfs *buf)
1674 {
1675         struct smb2_query_info_rsp *rsp;
1676         struct smb2_fs_full_size_info *info = NULL;
1677         struct smb_rqst rqst[3];
1678         int resp_buftype[3];
1679         struct kvec rsp_iov[3];
1680         struct kvec open_iov[SMB2_CREATE_IOV_SIZE];
1681         struct kvec qi_iov[1];
1682         struct kvec close_iov[1];
1683         struct cifs_ses *ses = tcon->ses;
1684         struct TCP_Server_Info *server = ses->server;
1685         __le16 srch_path = 0; /* Null - open root of share */
1686         u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
1687         struct cifs_open_parms oparms;
1688         struct cifs_fid fid;
1689         int flags = 0;
1690         int rc;
1691
1692         if (smb3_encryption_required(tcon))
1693                 flags |= CIFS_TRANSFORM_REQ;
1694
1695         memset(rqst, 0, sizeof(rqst));
1696         memset(resp_buftype, 0, sizeof(resp_buftype));
1697         memset(rsp_iov, 0, sizeof(rsp_iov));
1698
1699         memset(&open_iov, 0, sizeof(open_iov));
1700         rqst[0].rq_iov = open_iov;
1701         rqst[0].rq_nvec = SMB2_CREATE_IOV_SIZE;
1702
1703         oparms.tcon = tcon;
1704         oparms.desired_access = FILE_READ_ATTRIBUTES;
1705         oparms.disposition = FILE_OPEN;
1706         oparms.create_options = 0;
1707         oparms.fid = &fid;
1708         oparms.reconnect = false;
1709
1710         rc = SMB2_open_init(tcon, &rqst[0], &oplock, &oparms, &srch_path);
1711         if (rc)
1712                 goto qfs_exit;
1713         smb2_set_next_command(server, &rqst[0]);
1714
1715         memset(&qi_iov, 0, sizeof(qi_iov));
1716         rqst[1].rq_iov = qi_iov;
1717         rqst[1].rq_nvec = 1;
1718
1719         rc = SMB2_query_info_init(tcon, &rqst[1], COMPOUND_FID, COMPOUND_FID,
1720                                   FS_FULL_SIZE_INFORMATION,
1721                                   SMB2_O_INFO_FILESYSTEM, 0,
1722                                   sizeof(struct smb2_fs_full_size_info));
1723         if (rc)
1724                 goto qfs_exit;
1725         smb2_set_next_command(server, &rqst[1]);
1726         smb2_set_related(&rqst[1]);
1727
1728         memset(&close_iov, 0, sizeof(close_iov));
1729         rqst[2].rq_iov = close_iov;
1730         rqst[2].rq_nvec = 1;
1731
1732         rc = SMB2_close_init(tcon, &rqst[2], COMPOUND_FID, COMPOUND_FID);
1733         if (rc)
1734                 goto qfs_exit;
1735         smb2_set_related(&rqst[2]);
1736
1737         rc = compound_send_recv(xid, ses, flags, 3, rqst,
1738                                 resp_buftype, rsp_iov);
1739         if (rc)
1740                 goto qfs_exit;
1741
1742         rsp = (struct smb2_query_info_rsp *)rsp_iov[1].iov_base;
1743         buf->f_type = SMB2_MAGIC_NUMBER;
1744         info = (struct smb2_fs_full_size_info *)(
1745                 le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
1746         rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
1747                                le32_to_cpu(rsp->OutputBufferLength),
1748                                &rsp_iov[1],
1749                                sizeof(struct smb2_fs_full_size_info));
1750         if (!rc)
1751                 smb2_copy_fs_info_to_kstatfs(info, buf);
1752
1753 qfs_exit:
1754         SMB2_open_free(&rqst[0]);
1755         SMB2_query_info_free(&rqst[1]);
1756         SMB2_close_free(&rqst[2]);
1757         free_rsp_buf(resp_buftype[0], rsp_iov[0].iov_base);
1758         free_rsp_buf(resp_buftype[1], rsp_iov[1].iov_base);
1759         free_rsp_buf(resp_buftype[2], rsp_iov[2].iov_base);
1760         return rc;
1761 }
1762
1763 static int
1764 smb311_queryfs(const unsigned int xid, struct cifs_tcon *tcon,
1765              struct kstatfs *buf)
1766 {
1767         int rc;
1768         __le16 srch_path = 0; /* Null - open root of share */
1769         u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
1770         struct cifs_open_parms oparms;
1771         struct cifs_fid fid;
1772
1773         if (!tcon->posix_extensions)
1774                 return smb2_queryfs(xid, tcon, buf);
1775
1776         oparms.tcon = tcon;
1777         oparms.desired_access = FILE_READ_ATTRIBUTES;
1778         oparms.disposition = FILE_OPEN;
1779         oparms.create_options = 0;
1780         oparms.fid = &fid;
1781         oparms.reconnect = false;
1782
1783         rc = SMB2_open(xid, &oparms, &srch_path, &oplock, NULL, NULL, NULL);
1784         if (rc)
1785                 return rc;
1786
1787         rc = SMB311_posix_qfs_info(xid, tcon, fid.persistent_fid,
1788                                    fid.volatile_fid, buf);
1789         buf->f_type = SMB2_MAGIC_NUMBER;
1790         SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
1791         return rc;
1792 }
1793
1794 static bool
1795 smb2_compare_fids(struct cifsFileInfo *ob1, struct cifsFileInfo *ob2)
1796 {
1797         return ob1->fid.persistent_fid == ob2->fid.persistent_fid &&
1798                ob1->fid.volatile_fid == ob2->fid.volatile_fid;
1799 }
1800
1801 static int
1802 smb2_mand_lock(const unsigned int xid, struct cifsFileInfo *cfile, __u64 offset,
1803                __u64 length, __u32 type, int lock, int unlock, bool wait)
1804 {
1805         if (unlock && !lock)
1806                 type = SMB2_LOCKFLAG_UNLOCK;
1807         return SMB2_lock(xid, tlink_tcon(cfile->tlink),
1808                          cfile->fid.persistent_fid, cfile->fid.volatile_fid,
1809                          current->tgid, length, offset, type, wait);
1810 }
1811
1812 static void
1813 smb2_get_lease_key(struct inode *inode, struct cifs_fid *fid)
1814 {
1815         memcpy(fid->lease_key, CIFS_I(inode)->lease_key, SMB2_LEASE_KEY_SIZE);
1816 }
1817
1818 static void
1819 smb2_set_lease_key(struct inode *inode, struct cifs_fid *fid)
1820 {
1821         memcpy(CIFS_I(inode)->lease_key, fid->lease_key, SMB2_LEASE_KEY_SIZE);
1822 }
1823
1824 static void
1825 smb2_new_lease_key(struct cifs_fid *fid)
1826 {
1827         generate_random_uuid(fid->lease_key);
1828 }
1829
1830 static int
1831 smb2_get_dfs_refer(const unsigned int xid, struct cifs_ses *ses,
1832                    const char *search_name,
1833                    struct dfs_info3_param **target_nodes,
1834                    unsigned int *num_of_nodes,
1835                    const struct nls_table *nls_codepage, int remap)
1836 {
1837         int rc;
1838         __le16 *utf16_path = NULL;
1839         int utf16_path_len = 0;
1840         struct cifs_tcon *tcon;
1841         struct fsctl_get_dfs_referral_req *dfs_req = NULL;
1842         struct get_dfs_referral_rsp *dfs_rsp = NULL;
1843         u32 dfs_req_size = 0, dfs_rsp_size = 0;
1844
1845         cifs_dbg(FYI, "smb2_get_dfs_refer path <%s>\n", search_name);
1846
1847         /*
1848          * Try to use the IPC tcon, otherwise just use any
1849          */
1850         tcon = ses->tcon_ipc;
1851         if (tcon == NULL) {
1852                 spin_lock(&cifs_tcp_ses_lock);
1853                 tcon = list_first_entry_or_null(&ses->tcon_list,
1854                                                 struct cifs_tcon,
1855                                                 tcon_list);
1856                 if (tcon)
1857                         tcon->tc_count++;
1858                 spin_unlock(&cifs_tcp_ses_lock);
1859         }
1860
1861         if (tcon == NULL) {
1862                 cifs_dbg(VFS, "session %p has no tcon available for a dfs referral request\n",
1863                          ses);
1864                 rc = -ENOTCONN;
1865                 goto out;
1866         }
1867
1868         utf16_path = cifs_strndup_to_utf16(search_name, PATH_MAX,
1869                                            &utf16_path_len,
1870                                            nls_codepage, remap);
1871         if (!utf16_path) {
1872                 rc = -ENOMEM;
1873                 goto out;
1874         }
1875
1876         dfs_req_size = sizeof(*dfs_req) + utf16_path_len;
1877         dfs_req = kzalloc(dfs_req_size, GFP_KERNEL);
1878         if (!dfs_req) {
1879                 rc = -ENOMEM;
1880                 goto out;
1881         }
1882
1883         /* Highest DFS referral version understood */
1884         dfs_req->MaxReferralLevel = DFS_VERSION;
1885
1886         /* Path to resolve in an UTF-16 null-terminated string */
1887         memcpy(dfs_req->RequestFileName, utf16_path, utf16_path_len);
1888
1889         do {
1890                 rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
1891                                 FSCTL_DFS_GET_REFERRALS,
1892                                 true /* is_fsctl */,
1893                                 (char *)dfs_req, dfs_req_size,
1894                                 (char **)&dfs_rsp, &dfs_rsp_size);
1895         } while (rc == -EAGAIN);
1896
1897         if (rc) {
1898                 if ((rc != -ENOENT) && (rc != -EOPNOTSUPP))
1899                         cifs_dbg(VFS, "ioctl error in smb2_get_dfs_refer rc=%d\n", rc);
1900                 goto out;
1901         }
1902
1903         rc = parse_dfs_referrals(dfs_rsp, dfs_rsp_size,
1904                                  num_of_nodes, target_nodes,
1905                                  nls_codepage, remap, search_name,
1906                                  true /* is_unicode */);
1907         if (rc) {
1908                 cifs_dbg(VFS, "parse error in smb2_get_dfs_refer rc=%d\n", rc);
1909                 goto out;
1910         }
1911
1912  out:
1913         if (tcon && !tcon->ipc) {
1914                 /* ipc tcons are not refcounted */
1915                 spin_lock(&cifs_tcp_ses_lock);
1916                 tcon->tc_count--;
1917                 spin_unlock(&cifs_tcp_ses_lock);
1918         }
1919         kfree(utf16_path);
1920         kfree(dfs_req);
1921         kfree(dfs_rsp);
1922         return rc;
1923 }
1924 #define SMB2_SYMLINK_STRUCT_SIZE \
1925         (sizeof(struct smb2_err_rsp) - 1 + sizeof(struct smb2_symlink_err_rsp))
1926
1927 static int
1928 smb2_query_symlink(const unsigned int xid, struct cifs_tcon *tcon,
1929                    const char *full_path, char **target_path,
1930                    struct cifs_sb_info *cifs_sb)
1931 {
1932         int rc;
1933         __le16 *utf16_path;
1934         __u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
1935         struct cifs_open_parms oparms;
1936         struct cifs_fid fid;
1937         struct kvec err_iov = {NULL, 0};
1938         struct smb2_err_rsp *err_buf = NULL;
1939         int resp_buftype;
1940         struct smb2_symlink_err_rsp *symlink;
1941         unsigned int sub_len;
1942         unsigned int sub_offset;
1943         unsigned int print_len;
1944         unsigned int print_offset;
1945
1946         cifs_dbg(FYI, "%s: path: %s\n", __func__, full_path);
1947
1948         utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
1949         if (!utf16_path)
1950                 return -ENOMEM;
1951
1952         oparms.tcon = tcon;
1953         oparms.desired_access = FILE_READ_ATTRIBUTES;
1954         oparms.disposition = FILE_OPEN;
1955         if (backup_cred(cifs_sb))
1956                 oparms.create_options = CREATE_OPEN_BACKUP_INTENT;
1957         else
1958                 oparms.create_options = 0;
1959         oparms.fid = &fid;
1960         oparms.reconnect = false;
1961
1962         rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, &err_iov,
1963                        &resp_buftype);
1964         if (!rc)
1965                 SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
1966         if (!rc || !err_iov.iov_base) {
1967                 rc = -ENOENT;
1968                 goto free_path;
1969         }
1970
1971         err_buf = err_iov.iov_base;
1972         if (le32_to_cpu(err_buf->ByteCount) < sizeof(struct smb2_symlink_err_rsp) ||
1973             err_iov.iov_len < SMB2_SYMLINK_STRUCT_SIZE) {
1974                 rc = -ENOENT;
1975                 goto querty_exit;
1976         }
1977
1978         /* open must fail on symlink - reset rc */
1979         rc = 0;
1980         symlink = (struct smb2_symlink_err_rsp *)err_buf->ErrorData;
1981         sub_len = le16_to_cpu(symlink->SubstituteNameLength);
1982         sub_offset = le16_to_cpu(symlink->SubstituteNameOffset);
1983         print_len = le16_to_cpu(symlink->PrintNameLength);
1984         print_offset = le16_to_cpu(symlink->PrintNameOffset);
1985
1986         if (err_iov.iov_len < SMB2_SYMLINK_STRUCT_SIZE + sub_offset + sub_len) {
1987                 rc = -ENOENT;
1988                 goto querty_exit;
1989         }
1990
1991         if (err_iov.iov_len <
1992             SMB2_SYMLINK_STRUCT_SIZE + print_offset + print_len) {
1993                 rc = -ENOENT;
1994                 goto querty_exit;
1995         }
1996
1997         *target_path = cifs_strndup_from_utf16(
1998                                 (char *)symlink->PathBuffer + sub_offset,
1999                                 sub_len, true, cifs_sb->local_nls);
2000         if (!(*target_path)) {
2001                 rc = -ENOMEM;
2002                 goto querty_exit;
2003         }
2004         convert_delimiter(*target_path, '/');
2005         cifs_dbg(FYI, "%s: target path: %s\n", __func__, *target_path);
2006
2007  querty_exit:
2008         free_rsp_buf(resp_buftype, err_buf);
2009  free_path:
2010         kfree(utf16_path);
2011         return rc;
2012 }
2013
2014 #ifdef CONFIG_CIFS_ACL
2015 static struct cifs_ntsd *
2016 get_smb2_acl_by_fid(struct cifs_sb_info *cifs_sb,
2017                 const struct cifs_fid *cifsfid, u32 *pacllen)
2018 {
2019         struct cifs_ntsd *pntsd = NULL;
2020         unsigned int xid;
2021         int rc = -EOPNOTSUPP;
2022         struct tcon_link *tlink = cifs_sb_tlink(cifs_sb);
2023
2024         if (IS_ERR(tlink))
2025                 return ERR_CAST(tlink);
2026
2027         xid = get_xid();
2028         cifs_dbg(FYI, "trying to get acl\n");
2029
2030         rc = SMB2_query_acl(xid, tlink_tcon(tlink), cifsfid->persistent_fid,
2031                             cifsfid->volatile_fid, (void **)&pntsd, pacllen);
2032         free_xid(xid);
2033
2034         cifs_put_tlink(tlink);
2035
2036         cifs_dbg(FYI, "%s: rc = %d ACL len %d\n", __func__, rc, *pacllen);
2037         if (rc)
2038                 return ERR_PTR(rc);
2039         return pntsd;
2040
2041 }
2042
2043 static struct cifs_ntsd *
2044 get_smb2_acl_by_path(struct cifs_sb_info *cifs_sb,
2045                 const char *path, u32 *pacllen)
2046 {
2047         struct cifs_ntsd *pntsd = NULL;
2048         u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
2049         unsigned int xid;
2050         int rc;
2051         struct cifs_tcon *tcon;
2052         struct tcon_link *tlink = cifs_sb_tlink(cifs_sb);
2053         struct cifs_fid fid;
2054         struct cifs_open_parms oparms;
2055         __le16 *utf16_path;
2056
2057         cifs_dbg(FYI, "get smb3 acl for path %s\n", path);
2058         if (IS_ERR(tlink))
2059                 return ERR_CAST(tlink);
2060
2061         tcon = tlink_tcon(tlink);
2062         xid = get_xid();
2063
2064         if (backup_cred(cifs_sb))
2065                 oparms.create_options = CREATE_OPEN_BACKUP_INTENT;
2066         else
2067                 oparms.create_options = 0;
2068
2069         utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
2070         if (!utf16_path) {
2071                 rc = -ENOMEM;
2072                 free_xid(xid);
2073                 return ERR_PTR(rc);
2074         }
2075
2076         oparms.tcon = tcon;
2077         oparms.desired_access = READ_CONTROL;
2078         oparms.disposition = FILE_OPEN;
2079         oparms.fid = &fid;
2080         oparms.reconnect = false;
2081
2082         rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, NULL, NULL);
2083         kfree(utf16_path);
2084         if (!rc) {
2085                 rc = SMB2_query_acl(xid, tlink_tcon(tlink), fid.persistent_fid,
2086                             fid.volatile_fid, (void **)&pntsd, pacllen);
2087                 SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
2088         }
2089
2090         cifs_put_tlink(tlink);
2091         free_xid(xid);
2092
2093         cifs_dbg(FYI, "%s: rc = %d ACL len %d\n", __func__, rc, *pacllen);
2094         if (rc)
2095                 return ERR_PTR(rc);
2096         return pntsd;
2097 }
2098
2099 #ifdef CONFIG_CIFS_ACL
2100 static int
2101 set_smb2_acl(struct cifs_ntsd *pnntsd, __u32 acllen,
2102                 struct inode *inode, const char *path, int aclflag)
2103 {
2104         u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
2105         unsigned int xid;
2106         int rc, access_flags = 0;
2107         struct cifs_tcon *tcon;
2108         struct cifs_sb_info *cifs_sb = CIFS_SB(inode->i_sb);
2109         struct tcon_link *tlink = cifs_sb_tlink(cifs_sb);
2110         struct cifs_fid fid;
2111         struct cifs_open_parms oparms;
2112         __le16 *utf16_path;
2113
2114         cifs_dbg(FYI, "set smb3 acl for path %s\n", path);
2115         if (IS_ERR(tlink))
2116                 return PTR_ERR(tlink);
2117
2118         tcon = tlink_tcon(tlink);
2119         xid = get_xid();
2120
2121         if (backup_cred(cifs_sb))
2122                 oparms.create_options = CREATE_OPEN_BACKUP_INTENT;
2123         else
2124                 oparms.create_options = 0;
2125
2126         if (aclflag == CIFS_ACL_OWNER || aclflag == CIFS_ACL_GROUP)
2127                 access_flags = WRITE_OWNER;
2128         else
2129                 access_flags = WRITE_DAC;
2130
2131         utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
2132         if (!utf16_path) {
2133                 rc = -ENOMEM;
2134                 free_xid(xid);
2135                 return rc;
2136         }
2137
2138         oparms.tcon = tcon;
2139         oparms.desired_access = access_flags;
2140         oparms.disposition = FILE_OPEN;
2141         oparms.path = path;
2142         oparms.fid = &fid;
2143         oparms.reconnect = false;
2144
2145         rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, NULL, NULL);
2146         kfree(utf16_path);
2147         if (!rc) {
2148                 rc = SMB2_set_acl(xid, tlink_tcon(tlink), fid.persistent_fid,
2149                             fid.volatile_fid, pnntsd, acllen, aclflag);
2150                 SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
2151         }
2152
2153         cifs_put_tlink(tlink);
2154         free_xid(xid);
2155         return rc;
2156 }
2157 #endif /* CIFS_ACL */
2158
2159 /* Retrieve an ACL from the server */
2160 static struct cifs_ntsd *
2161 get_smb2_acl(struct cifs_sb_info *cifs_sb,
2162                                       struct inode *inode, const char *path,
2163                                       u32 *pacllen)
2164 {
2165         struct cifs_ntsd *pntsd = NULL;
2166         struct cifsFileInfo *open_file = NULL;
2167
2168         if (inode)
2169                 open_file = find_readable_file(CIFS_I(inode), true);
2170         if (!open_file)
2171                 return get_smb2_acl_by_path(cifs_sb, path, pacllen);
2172
2173         pntsd = get_smb2_acl_by_fid(cifs_sb, &open_file->fid, pacllen);
2174         cifsFileInfo_put(open_file);
2175         return pntsd;
2176 }
2177 #endif
2178
2179 static long smb3_zero_range(struct file *file, struct cifs_tcon *tcon,
2180                             loff_t offset, loff_t len, bool keep_size)
2181 {
2182         struct inode *inode;
2183         struct cifsInodeInfo *cifsi;
2184         struct cifsFileInfo *cfile = file->private_data;
2185         struct file_zero_data_information fsctl_buf;
2186         long rc;
2187         unsigned int xid;
2188
2189         xid = get_xid();
2190
2191         inode = d_inode(cfile->dentry);
2192         cifsi = CIFS_I(inode);
2193
2194         /*
2195          * We zero the range through ioctl, so we need remove the page caches
2196          * first, otherwise the data may be inconsistent with the server.
2197          */
2198         truncate_pagecache_range(inode, offset, offset + len - 1);
2199
2200         /* if file not oplocked can't be sure whether asking to extend size */
2201         if (!CIFS_CACHE_READ(cifsi))
2202                 if (keep_size == false) {
2203                         rc = -EOPNOTSUPP;
2204                         free_xid(xid);
2205                         return rc;
2206                 }
2207
2208         /*
2209          * Must check if file sparse since fallocate -z (zero range) assumes
2210          * non-sparse allocation
2211          */
2212         if (!(cifsi->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE)) {
2213                 rc = -EOPNOTSUPP;
2214                 free_xid(xid);
2215                 return rc;
2216         }
2217
2218         /*
2219          * need to make sure we are not asked to extend the file since the SMB3
2220          * fsctl does not change the file size. In the future we could change
2221          * this to zero the first part of the range then set the file size
2222          * which for a non sparse file would zero the newly extended range
2223          */
2224         if (keep_size == false)
2225                 if (i_size_read(inode) < offset + len) {
2226                         rc = -EOPNOTSUPP;
2227                         free_xid(xid);
2228                         return rc;
2229                 }
2230
2231         cifs_dbg(FYI, "offset %lld len %lld", offset, len);
2232
2233         fsctl_buf.FileOffset = cpu_to_le64(offset);
2234         fsctl_buf.BeyondFinalZero = cpu_to_le64(offset + len);
2235
2236         rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
2237                         cfile->fid.volatile_fid, FSCTL_SET_ZERO_DATA,
2238                         true /* is_fctl */, (char *)&fsctl_buf,
2239                         sizeof(struct file_zero_data_information), NULL, NULL);
2240         free_xid(xid);
2241         return rc;
2242 }
2243
2244 static long smb3_punch_hole(struct file *file, struct cifs_tcon *tcon,
2245                             loff_t offset, loff_t len)
2246 {
2247         struct inode *inode;
2248         struct cifsInodeInfo *cifsi;
2249         struct cifsFileInfo *cfile = file->private_data;
2250         struct file_zero_data_information fsctl_buf;
2251         long rc;
2252         unsigned int xid;
2253         __u8 set_sparse = 1;
2254
2255         xid = get_xid();
2256
2257         inode = d_inode(cfile->dentry);
2258         cifsi = CIFS_I(inode);
2259
2260         /* Need to make file sparse, if not already, before freeing range. */
2261         /* Consider adding equivalent for compressed since it could also work */
2262         if (!smb2_set_sparse(xid, tcon, cfile, inode, set_sparse)) {
2263                 rc = -EOPNOTSUPP;
2264                 free_xid(xid);
2265                 return rc;
2266         }
2267
2268         /*
2269          * We implement the punch hole through ioctl, so we need remove the page
2270          * caches first, otherwise the data may be inconsistent with the server.
2271          */
2272         truncate_pagecache_range(inode, offset, offset + len - 1);
2273
2274         cifs_dbg(FYI, "offset %lld len %lld", offset, len);
2275
2276         fsctl_buf.FileOffset = cpu_to_le64(offset);
2277         fsctl_buf.BeyondFinalZero = cpu_to_le64(offset + len);
2278
2279         rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
2280                         cfile->fid.volatile_fid, FSCTL_SET_ZERO_DATA,
2281                         true /* is_fctl */, (char *)&fsctl_buf,
2282                         sizeof(struct file_zero_data_information), NULL, NULL);
2283         free_xid(xid);
2284         return rc;
2285 }
2286
2287 static long smb3_simple_falloc(struct file *file, struct cifs_tcon *tcon,
2288                             loff_t off, loff_t len, bool keep_size)
2289 {
2290         struct inode *inode;
2291         struct cifsInodeInfo *cifsi;
2292         struct cifsFileInfo *cfile = file->private_data;
2293         long rc = -EOPNOTSUPP;
2294         unsigned int xid;
2295
2296         xid = get_xid();
2297
2298         inode = d_inode(cfile->dentry);
2299         cifsi = CIFS_I(inode);
2300
2301         /* if file not oplocked can't be sure whether asking to extend size */
2302         if (!CIFS_CACHE_READ(cifsi))
2303                 if (keep_size == false) {
2304                         free_xid(xid);
2305                         return rc;
2306                 }
2307
2308         /*
2309          * Files are non-sparse by default so falloc may be a no-op
2310          * Must check if file sparse. If not sparse, and not extending
2311          * then no need to do anything since file already allocated
2312          */
2313         if ((cifsi->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE) == 0) {
2314                 if (keep_size == true)
2315                         rc = 0;
2316                 /* check if extending file */
2317                 else if (i_size_read(inode) >= off + len)
2318                         /* not extending file and already not sparse */
2319                         rc = 0;
2320                 /* BB: in future add else clause to extend file */
2321                 else
2322                         rc = -EOPNOTSUPP;
2323                 free_xid(xid);
2324                 return rc;
2325         }
2326
2327         if ((keep_size == true) || (i_size_read(inode) >= off + len)) {
2328                 /*
2329                  * Check if falloc starts within first few pages of file
2330                  * and ends within a few pages of the end of file to
2331                  * ensure that most of file is being forced to be
2332                  * fallocated now. If so then setting whole file sparse
2333                  * ie potentially making a few extra pages at the beginning
2334                  * or end of the file non-sparse via set_sparse is harmless.
2335                  */
2336                 if ((off > 8192) || (off + len + 8192 < i_size_read(inode))) {
2337                         rc = -EOPNOTSUPP;
2338                         free_xid(xid);
2339                         return rc;
2340                 }
2341
2342                 rc = smb2_set_sparse(xid, tcon, cfile, inode, false);
2343         }
2344         /* BB: else ... in future add code to extend file and set sparse */
2345
2346
2347         free_xid(xid);
2348         return rc;
2349 }
2350
2351
2352 static long smb3_fallocate(struct file *file, struct cifs_tcon *tcon, int mode,
2353                            loff_t off, loff_t len)
2354 {
2355         /* KEEP_SIZE already checked for by do_fallocate */
2356         if (mode & FALLOC_FL_PUNCH_HOLE)
2357                 return smb3_punch_hole(file, tcon, off, len);
2358         else if (mode & FALLOC_FL_ZERO_RANGE) {
2359                 if (mode & FALLOC_FL_KEEP_SIZE)
2360                         return smb3_zero_range(file, tcon, off, len, true);
2361                 return smb3_zero_range(file, tcon, off, len, false);
2362         } else if (mode == FALLOC_FL_KEEP_SIZE)
2363                 return smb3_simple_falloc(file, tcon, off, len, true);
2364         else if (mode == 0)
2365                 return smb3_simple_falloc(file, tcon, off, len, false);
2366
2367         return -EOPNOTSUPP;
2368 }
2369
2370 static void
2371 smb2_downgrade_oplock(struct TCP_Server_Info *server,
2372                       struct cifsInodeInfo *cinode, __u32 oplock,
2373                       unsigned int epoch, bool *purge_cache)
2374 {
2375         server->ops->set_oplock_level(cinode, oplock, 0, NULL);
2376 }
2377
2378 static void
2379 smb21_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
2380                        unsigned int epoch, bool *purge_cache);
2381
2382 static void
2383 smb3_downgrade_oplock(struct TCP_Server_Info *server,
2384                        struct cifsInodeInfo *cinode, __u32 oplock,
2385                        unsigned int epoch, bool *purge_cache)
2386 {
2387         unsigned int old_state = cinode->oplock;
2388         unsigned int old_epoch = cinode->epoch;
2389         unsigned int new_state;
2390
2391         if (epoch > old_epoch) {
2392                 smb21_set_oplock_level(cinode, oplock, 0, NULL);
2393                 cinode->epoch = epoch;
2394         }
2395
2396         new_state = cinode->oplock;
2397         *purge_cache = false;
2398
2399         if ((old_state & CIFS_CACHE_READ_FLG) != 0 &&
2400             (new_state & CIFS_CACHE_READ_FLG) == 0)
2401                 *purge_cache = true;
2402         else if (old_state == new_state && (epoch - old_epoch > 1))
2403                 *purge_cache = true;
2404 }
2405
2406 static void
2407 smb2_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
2408                       unsigned int epoch, bool *purge_cache)
2409 {
2410         oplock &= 0xFF;
2411         if (oplock == SMB2_OPLOCK_LEVEL_NOCHANGE)
2412                 return;
2413         if (oplock == SMB2_OPLOCK_LEVEL_BATCH) {
2414                 cinode->oplock = CIFS_CACHE_RHW_FLG;
2415                 cifs_dbg(FYI, "Batch Oplock granted on inode %p\n",
2416                          &cinode->vfs_inode);
2417         } else if (oplock == SMB2_OPLOCK_LEVEL_EXCLUSIVE) {
2418                 cinode->oplock = CIFS_CACHE_RW_FLG;
2419                 cifs_dbg(FYI, "Exclusive Oplock granted on inode %p\n",
2420                          &cinode->vfs_inode);
2421         } else if (oplock == SMB2_OPLOCK_LEVEL_II) {
2422                 cinode->oplock = CIFS_CACHE_READ_FLG;
2423                 cifs_dbg(FYI, "Level II Oplock granted on inode %p\n",
2424                          &cinode->vfs_inode);
2425         } else
2426                 cinode->oplock = 0;
2427 }
2428
2429 static void
2430 smb21_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
2431                        unsigned int epoch, bool *purge_cache)
2432 {
2433         char message[5] = {0};
2434         unsigned int new_oplock = 0;
2435
2436         oplock &= 0xFF;
2437         if (oplock == SMB2_OPLOCK_LEVEL_NOCHANGE)
2438                 return;
2439
2440         /* Check if the server granted an oplock rather than a lease */
2441         if (oplock & SMB2_OPLOCK_LEVEL_EXCLUSIVE)
2442                 return smb2_set_oplock_level(cinode, oplock, epoch,
2443                                              purge_cache);
2444
2445         if (oplock & SMB2_LEASE_READ_CACHING_HE) {
2446                 new_oplock |= CIFS_CACHE_READ_FLG;
2447                 strcat(message, "R");
2448         }
2449         if (oplock & SMB2_LEASE_HANDLE_CACHING_HE) {
2450                 new_oplock |= CIFS_CACHE_HANDLE_FLG;
2451                 strcat(message, "H");
2452         }
2453         if (oplock & SMB2_LEASE_WRITE_CACHING_HE) {
2454                 new_oplock |= CIFS_CACHE_WRITE_FLG;
2455                 strcat(message, "W");
2456         }
2457         if (!new_oplock)
2458                 strncpy(message, "None", sizeof(message));
2459
2460         cinode->oplock = new_oplock;
2461         cifs_dbg(FYI, "%s Lease granted on inode %p\n", message,
2462                  &cinode->vfs_inode);
2463 }
2464
2465 static void
2466 smb3_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
2467                       unsigned int epoch, bool *purge_cache)
2468 {
2469         unsigned int old_oplock = cinode->oplock;
2470
2471         smb21_set_oplock_level(cinode, oplock, epoch, purge_cache);
2472
2473         if (purge_cache) {
2474                 *purge_cache = false;
2475                 if (old_oplock == CIFS_CACHE_READ_FLG) {
2476                         if (cinode->oplock == CIFS_CACHE_READ_FLG &&
2477                             (epoch - cinode->epoch > 0))
2478                                 *purge_cache = true;
2479                         else if (cinode->oplock == CIFS_CACHE_RH_FLG &&
2480                                  (epoch - cinode->epoch > 1))
2481                                 *purge_cache = true;
2482                         else if (cinode->oplock == CIFS_CACHE_RHW_FLG &&
2483                                  (epoch - cinode->epoch > 1))
2484                                 *purge_cache = true;
2485                         else if (cinode->oplock == 0 &&
2486                                  (epoch - cinode->epoch > 0))
2487                                 *purge_cache = true;
2488                 } else if (old_oplock == CIFS_CACHE_RH_FLG) {
2489                         if (cinode->oplock == CIFS_CACHE_RH_FLG &&
2490                             (epoch - cinode->epoch > 0))
2491                                 *purge_cache = true;
2492                         else if (cinode->oplock == CIFS_CACHE_RHW_FLG &&
2493                                  (epoch - cinode->epoch > 1))
2494                                 *purge_cache = true;
2495                 }
2496                 cinode->epoch = epoch;
2497         }
2498 }
2499
2500 static bool
2501 smb2_is_read_op(__u32 oplock)
2502 {
2503         return oplock == SMB2_OPLOCK_LEVEL_II;
2504 }
2505
2506 static bool
2507 smb21_is_read_op(__u32 oplock)
2508 {
2509         return (oplock & SMB2_LEASE_READ_CACHING_HE) &&
2510                !(oplock & SMB2_LEASE_WRITE_CACHING_HE);
2511 }
2512
2513 static __le32
2514 map_oplock_to_lease(u8 oplock)
2515 {
2516         if (oplock == SMB2_OPLOCK_LEVEL_EXCLUSIVE)
2517                 return SMB2_LEASE_WRITE_CACHING | SMB2_LEASE_READ_CACHING;
2518         else if (oplock == SMB2_OPLOCK_LEVEL_II)
2519                 return SMB2_LEASE_READ_CACHING;
2520         else if (oplock == SMB2_OPLOCK_LEVEL_BATCH)
2521                 return SMB2_LEASE_HANDLE_CACHING | SMB2_LEASE_READ_CACHING |
2522                        SMB2_LEASE_WRITE_CACHING;
2523         return 0;
2524 }
2525
2526 static char *
2527 smb2_create_lease_buf(u8 *lease_key, u8 oplock)
2528 {
2529         struct create_lease *buf;
2530
2531         buf = kzalloc(sizeof(struct create_lease), GFP_KERNEL);
2532         if (!buf)
2533                 return NULL;
2534
2535         memcpy(&buf->lcontext.LeaseKey, lease_key, SMB2_LEASE_KEY_SIZE);
2536         buf->lcontext.LeaseState = map_oplock_to_lease(oplock);
2537
2538         buf->ccontext.DataOffset = cpu_to_le16(offsetof
2539                                         (struct create_lease, lcontext));
2540         buf->ccontext.DataLength = cpu_to_le32(sizeof(struct lease_context));
2541         buf->ccontext.NameOffset = cpu_to_le16(offsetof
2542                                 (struct create_lease, Name));
2543         buf->ccontext.NameLength = cpu_to_le16(4);
2544         /* SMB2_CREATE_REQUEST_LEASE is "RqLs" */
2545         buf->Name[0] = 'R';
2546         buf->Name[1] = 'q';
2547         buf->Name[2] = 'L';
2548         buf->Name[3] = 's';
2549         return (char *)buf;
2550 }
2551
2552 static char *
2553 smb3_create_lease_buf(u8 *lease_key, u8 oplock)
2554 {
2555         struct create_lease_v2 *buf;
2556
2557         buf = kzalloc(sizeof(struct create_lease_v2), GFP_KERNEL);
2558         if (!buf)
2559                 return NULL;
2560
2561         memcpy(&buf->lcontext.LeaseKey, lease_key, SMB2_LEASE_KEY_SIZE);
2562         buf->lcontext.LeaseState = map_oplock_to_lease(oplock);
2563
2564         buf->ccontext.DataOffset = cpu_to_le16(offsetof
2565                                         (struct create_lease_v2, lcontext));
2566         buf->ccontext.DataLength = cpu_to_le32(sizeof(struct lease_context_v2));
2567         buf->ccontext.NameOffset = cpu_to_le16(offsetof
2568                                 (struct create_lease_v2, Name));
2569         buf->ccontext.NameLength = cpu_to_le16(4);
2570         /* SMB2_CREATE_REQUEST_LEASE is "RqLs" */
2571         buf->Name[0] = 'R';
2572         buf->Name[1] = 'q';
2573         buf->Name[2] = 'L';
2574         buf->Name[3] = 's';
2575         return (char *)buf;
2576 }
2577
2578 static __u8
2579 smb2_parse_lease_buf(void *buf, unsigned int *epoch, char *lease_key)
2580 {
2581         struct create_lease *lc = (struct create_lease *)buf;
2582
2583         *epoch = 0; /* not used */
2584         if (lc->lcontext.LeaseFlags & SMB2_LEASE_FLAG_BREAK_IN_PROGRESS)
2585                 return SMB2_OPLOCK_LEVEL_NOCHANGE;
2586         return le32_to_cpu(lc->lcontext.LeaseState);
2587 }
2588
2589 static __u8
2590 smb3_parse_lease_buf(void *buf, unsigned int *epoch, char *lease_key)
2591 {
2592         struct create_lease_v2 *lc = (struct create_lease_v2 *)buf;
2593
2594         *epoch = le16_to_cpu(lc->lcontext.Epoch);
2595         if (lc->lcontext.LeaseFlags & SMB2_LEASE_FLAG_BREAK_IN_PROGRESS)
2596                 return SMB2_OPLOCK_LEVEL_NOCHANGE;
2597         if (lease_key)
2598                 memcpy(lease_key, &lc->lcontext.LeaseKey, SMB2_LEASE_KEY_SIZE);
2599         return le32_to_cpu(lc->lcontext.LeaseState);
2600 }
2601
2602 static unsigned int
2603 smb2_wp_retry_size(struct inode *inode)
2604 {
2605         return min_t(unsigned int, CIFS_SB(inode->i_sb)->wsize,
2606                      SMB2_MAX_BUFFER_SIZE);
2607 }
2608
2609 static bool
2610 smb2_dir_needs_close(struct cifsFileInfo *cfile)
2611 {
2612         return !cfile->invalidHandle;
2613 }
2614
2615 static void
2616 fill_transform_hdr(struct smb2_transform_hdr *tr_hdr, unsigned int orig_len,
2617                    struct smb_rqst *old_rq)
2618 {
2619         struct smb2_sync_hdr *shdr =
2620                         (struct smb2_sync_hdr *)old_rq->rq_iov[0].iov_base;
2621
2622         memset(tr_hdr, 0, sizeof(struct smb2_transform_hdr));
2623         tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
2624         tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
2625         tr_hdr->Flags = cpu_to_le16(0x01);
2626         get_random_bytes(&tr_hdr->Nonce, SMB3_AES128CMM_NONCE);
2627         memcpy(&tr_hdr->SessionId, &shdr->SessionId, 8);
2628 }
2629
2630 /* We can not use the normal sg_set_buf() as we will sometimes pass a
2631  * stack object as buf.
2632  */
2633 static inline void smb2_sg_set_buf(struct scatterlist *sg, const void *buf,
2634                                    unsigned int buflen)
2635 {
2636         void *addr;
2637         /*
2638          * VMAP_STACK (at least) puts stack into the vmalloc address space
2639          */
2640         if (is_vmalloc_addr(buf))
2641                 addr = vmalloc_to_page(buf);
2642         else
2643                 addr = virt_to_page(buf);
2644         sg_set_page(sg, addr, buflen, offset_in_page(buf));
2645 }
2646
2647 /* Assumes the first rqst has a transform header as the first iov.
2648  * I.e.
2649  * rqst[0].rq_iov[0]  is transform header
2650  * rqst[0].rq_iov[1+] data to be encrypted/decrypted
2651  * rqst[1+].rq_iov[0+] data to be encrypted/decrypted
2652  */
2653 static struct scatterlist *
2654 init_sg(int num_rqst, struct smb_rqst *rqst, u8 *sign)
2655 {
2656         unsigned int sg_len;
2657         struct scatterlist *sg;
2658         unsigned int i;
2659         unsigned int j;
2660         unsigned int idx = 0;
2661         int skip;
2662
2663         sg_len = 1;
2664         for (i = 0; i < num_rqst; i++)
2665                 sg_len += rqst[i].rq_nvec + rqst[i].rq_npages;
2666
2667         sg = kmalloc_array(sg_len, sizeof(struct scatterlist), GFP_KERNEL);
2668         if (!sg)
2669                 return NULL;
2670
2671         sg_init_table(sg, sg_len);
2672         for (i = 0; i < num_rqst; i++) {
2673                 for (j = 0; j < rqst[i].rq_nvec; j++) {
2674                         /*
2675                          * The first rqst has a transform header where the
2676                          * first 20 bytes are not part of the encrypted blob
2677                          */
2678                         skip = (i == 0) && (j == 0) ? 20 : 0;
2679                         smb2_sg_set_buf(&sg[idx++],
2680                                         rqst[i].rq_iov[j].iov_base + skip,
2681                                         rqst[i].rq_iov[j].iov_len - skip);
2682                 }
2683
2684                 for (j = 0; j < rqst[i].rq_npages; j++) {
2685                         unsigned int len, offset;
2686
2687                         rqst_page_get_length(&rqst[i], j, &len, &offset);
2688                         sg_set_page(&sg[idx++], rqst[i].rq_pages[j], len, offset);
2689                 }
2690         }
2691         smb2_sg_set_buf(&sg[idx], sign, SMB2_SIGNATURE_SIZE);
2692         return sg;
2693 }
2694
2695 static int
2696 smb2_get_enc_key(struct TCP_Server_Info *server, __u64 ses_id, int enc, u8 *key)
2697 {
2698         struct cifs_ses *ses;
2699         u8 *ses_enc_key;
2700
2701         spin_lock(&cifs_tcp_ses_lock);
2702         list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
2703                 if (ses->Suid != ses_id)
2704                         continue;
2705                 ses_enc_key = enc ? ses->smb3encryptionkey :
2706                                                         ses->smb3decryptionkey;
2707                 memcpy(key, ses_enc_key, SMB3_SIGN_KEY_SIZE);
2708                 spin_unlock(&cifs_tcp_ses_lock);
2709                 return 0;
2710         }
2711         spin_unlock(&cifs_tcp_ses_lock);
2712
2713         return -EAGAIN;
2714 }
2715 /*
2716  * Encrypt or decrypt @rqst message. @rqst[0] has the following format:
2717  * iov[0]   - transform header (associate data),
2718  * iov[1-N] - SMB2 header and pages - data to encrypt.
2719  * On success return encrypted data in iov[1-N] and pages, leave iov[0]
2720  * untouched.
2721  */
2722 static int
2723 crypt_message(struct TCP_Server_Info *server, int num_rqst,
2724               struct smb_rqst *rqst, int enc)
2725 {
2726         struct smb2_transform_hdr *tr_hdr =
2727                 (struct smb2_transform_hdr *)rqst[0].rq_iov[0].iov_base;
2728         unsigned int assoc_data_len = sizeof(struct smb2_transform_hdr) - 20;
2729         int rc = 0;
2730         struct scatterlist *sg;
2731         u8 sign[SMB2_SIGNATURE_SIZE] = {};
2732         u8 key[SMB3_SIGN_KEY_SIZE];
2733         struct aead_request *req;
2734         char *iv;
2735         unsigned int iv_len;
2736         DECLARE_CRYPTO_WAIT(wait);
2737         struct crypto_aead *tfm;
2738         unsigned int crypt_len = le32_to_cpu(tr_hdr->OriginalMessageSize);
2739
2740         rc = smb2_get_enc_key(server, tr_hdr->SessionId, enc, key);
2741         if (rc) {
2742                 cifs_dbg(VFS, "%s: Could not get %scryption key\n", __func__,
2743                          enc ? "en" : "de");
2744                 return rc;
2745         }
2746
2747         rc = smb3_crypto_aead_allocate(server);
2748         if (rc) {
2749                 cifs_dbg(VFS, "%s: crypto alloc failed\n", __func__);
2750                 return rc;
2751         }
2752
2753         tfm = enc ? server->secmech.ccmaesencrypt :
2754                                                 server->secmech.ccmaesdecrypt;
2755         rc = crypto_aead_setkey(tfm, key, SMB3_SIGN_KEY_SIZE);
2756         if (rc) {
2757                 cifs_dbg(VFS, "%s: Failed to set aead key %d\n", __func__, rc);
2758                 return rc;
2759         }
2760
2761         rc = crypto_aead_setauthsize(tfm, SMB2_SIGNATURE_SIZE);
2762         if (rc) {
2763                 cifs_dbg(VFS, "%s: Failed to set authsize %d\n", __func__, rc);
2764                 return rc;
2765         }
2766
2767         req = aead_request_alloc(tfm, GFP_KERNEL);
2768         if (!req) {
2769                 cifs_dbg(VFS, "%s: Failed to alloc aead request", __func__);
2770                 return -ENOMEM;
2771         }
2772
2773         if (!enc) {
2774                 memcpy(sign, &tr_hdr->Signature, SMB2_SIGNATURE_SIZE);
2775                 crypt_len += SMB2_SIGNATURE_SIZE;
2776         }
2777
2778         sg = init_sg(num_rqst, rqst, sign);
2779         if (!sg) {
2780                 cifs_dbg(VFS, "%s: Failed to init sg", __func__);
2781                 rc = -ENOMEM;
2782                 goto free_req;
2783         }
2784
2785         iv_len = crypto_aead_ivsize(tfm);
2786         iv = kzalloc(iv_len, GFP_KERNEL);
2787         if (!iv) {
2788                 cifs_dbg(VFS, "%s: Failed to alloc IV", __func__);
2789                 rc = -ENOMEM;
2790                 goto free_sg;
2791         }
2792         iv[0] = 3;
2793         memcpy(iv + 1, (char *)tr_hdr->Nonce, SMB3_AES128CMM_NONCE);
2794
2795         aead_request_set_crypt(req, sg, sg, crypt_len, iv);
2796         aead_request_set_ad(req, assoc_data_len);
2797
2798         aead_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
2799                                   crypto_req_done, &wait);
2800
2801         rc = crypto_wait_req(enc ? crypto_aead_encrypt(req)
2802                                 : crypto_aead_decrypt(req), &wait);
2803
2804         if (!rc && enc)
2805                 memcpy(&tr_hdr->Signature, sign, SMB2_SIGNATURE_SIZE);
2806
2807         kfree(iv);
2808 free_sg:
2809         kfree(sg);
2810 free_req:
2811         kfree(req);
2812         return rc;
2813 }
2814
2815 void
2816 smb3_free_compound_rqst(int num_rqst, struct smb_rqst *rqst)
2817 {
2818         int i, j;
2819
2820         for (i = 0; i < num_rqst; i++) {
2821                 if (rqst[i].rq_pages) {
2822                         for (j = rqst[i].rq_npages - 1; j >= 0; j--)
2823                                 put_page(rqst[i].rq_pages[j]);
2824                         kfree(rqst[i].rq_pages);
2825                 }
2826         }
2827 }
2828
2829 /*
2830  * This function will initialize new_rq and encrypt the content.
2831  * The first entry, new_rq[0], only contains a single iov which contains
2832  * a smb2_transform_hdr and is pre-allocated by the caller.
2833  * This function then populates new_rq[1+] with the content from olq_rq[0+].
2834  *
2835  * The end result is an array of smb_rqst structures where the first structure
2836  * only contains a single iov for the transform header which we then can pass
2837  * to crypt_message().
2838  *
2839  * new_rq[0].rq_iov[0] :  smb2_transform_hdr pre-allocated by the caller
2840  * new_rq[1+].rq_iov[*] == old_rq[0+].rq_iov[*] : SMB2/3 requests
2841  */
2842 static int
2843 smb3_init_transform_rq(struct TCP_Server_Info *server, int num_rqst,
2844                        struct smb_rqst *new_rq, struct smb_rqst *old_rq)
2845 {
2846         struct page **pages;
2847         struct smb2_transform_hdr *tr_hdr = new_rq[0].rq_iov[0].iov_base;
2848         unsigned int npages;
2849         unsigned int orig_len = 0;
2850         int i, j;
2851         int rc = -ENOMEM;
2852
2853         for (i = 1; i < num_rqst; i++) {
2854                 npages = old_rq[i - 1].rq_npages;
2855                 pages = kmalloc_array(npages, sizeof(struct page *),
2856                                       GFP_KERNEL);
2857                 if (!pages)
2858                         goto err_free;
2859
2860                 new_rq[i].rq_pages = pages;
2861                 new_rq[i].rq_npages = npages;
2862                 new_rq[i].rq_offset = old_rq[i - 1].rq_offset;
2863                 new_rq[i].rq_pagesz = old_rq[i - 1].rq_pagesz;
2864                 new_rq[i].rq_tailsz = old_rq[i - 1].rq_tailsz;
2865                 new_rq[i].rq_iov = old_rq[i - 1].rq_iov;
2866                 new_rq[i].rq_nvec = old_rq[i - 1].rq_nvec;
2867
2868                 orig_len += smb_rqst_len(server, &old_rq[i - 1]);
2869
2870                 for (j = 0; j < npages; j++) {
2871                         pages[j] = alloc_page(GFP_KERNEL|__GFP_HIGHMEM);
2872                         if (!pages[j])
2873                                 goto err_free;
2874                 }
2875
2876                 /* copy pages form the old */
2877                 for (j = 0; j < npages; j++) {
2878                         char *dst, *src;
2879                         unsigned int offset, len;
2880
2881                         rqst_page_get_length(&new_rq[i], j, &len, &offset);
2882
2883                         dst = (char *) kmap(new_rq[i].rq_pages[j]) + offset;
2884                         src = (char *) kmap(old_rq[i - 1].rq_pages[j]) + offset;
2885
2886                         memcpy(dst, src, len);
2887                         kunmap(new_rq[i].rq_pages[j]);
2888                         kunmap(old_rq[i - 1].rq_pages[j]);
2889                 }
2890         }
2891
2892         /* fill the 1st iov with a transform header */
2893         fill_transform_hdr(tr_hdr, orig_len, old_rq);
2894
2895         rc = crypt_message(server, num_rqst, new_rq, 1);
2896         cifs_dbg(FYI, "encrypt message returned %d", rc);
2897         if (rc)
2898                 goto err_free;
2899
2900         return rc;
2901
2902 err_free:
2903         smb3_free_compound_rqst(num_rqst - 1, &new_rq[1]);
2904         return rc;
2905 }
2906
2907 static int
2908 smb3_is_transform_hdr(void *buf)
2909 {
2910         struct smb2_transform_hdr *trhdr = buf;
2911
2912         return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
2913 }
2914
2915 static int
2916 decrypt_raw_data(struct TCP_Server_Info *server, char *buf,
2917                  unsigned int buf_data_size, struct page **pages,
2918                  unsigned int npages, unsigned int page_data_size)
2919 {
2920         struct kvec iov[2];
2921         struct smb_rqst rqst = {NULL};
2922         int rc;
2923
2924         iov[0].iov_base = buf;
2925         iov[0].iov_len = sizeof(struct smb2_transform_hdr);
2926         iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr);
2927         iov[1].iov_len = buf_data_size;
2928
2929         rqst.rq_iov = iov;
2930         rqst.rq_nvec = 2;
2931         rqst.rq_pages = pages;
2932         rqst.rq_npages = npages;
2933         rqst.rq_pagesz = PAGE_SIZE;
2934         rqst.rq_tailsz = (page_data_size % PAGE_SIZE) ? : PAGE_SIZE;
2935
2936         rc = crypt_message(server, 1, &rqst, 0);
2937         cifs_dbg(FYI, "decrypt message returned %d\n", rc);
2938
2939         if (rc)
2940                 return rc;
2941
2942         memmove(buf, iov[1].iov_base, buf_data_size);
2943
2944         server->total_read = buf_data_size + page_data_size;
2945
2946         return rc;
2947 }
2948
2949 static int
2950 read_data_into_pages(struct TCP_Server_Info *server, struct page **pages,
2951                      unsigned int npages, unsigned int len)
2952 {
2953         int i;
2954         int length;
2955
2956         for (i = 0; i < npages; i++) {
2957                 struct page *page = pages[i];
2958                 size_t n;
2959
2960                 n = len;
2961                 if (len >= PAGE_SIZE) {
2962                         /* enough data to fill the page */
2963                         n = PAGE_SIZE;
2964                         len -= n;
2965                 } else {
2966                         zero_user(page, len, PAGE_SIZE - len);
2967                         len = 0;
2968                 }
2969                 length = cifs_read_page_from_socket(server, page, 0, n);
2970                 if (length < 0)
2971                         return length;
2972                 server->total_read += length;
2973         }
2974
2975         return 0;
2976 }
2977
2978 static int
2979 init_read_bvec(struct page **pages, unsigned int npages, unsigned int data_size,
2980                unsigned int cur_off, struct bio_vec **page_vec)
2981 {
2982         struct bio_vec *bvec;
2983         int i;
2984
2985         bvec = kcalloc(npages, sizeof(struct bio_vec), GFP_KERNEL);
2986         if (!bvec)
2987                 return -ENOMEM;
2988
2989         for (i = 0; i < npages; i++) {
2990                 bvec[i].bv_page = pages[i];
2991                 bvec[i].bv_offset = (i == 0) ? cur_off : 0;
2992                 bvec[i].bv_len = min_t(unsigned int, PAGE_SIZE, data_size);
2993                 data_size -= bvec[i].bv_len;
2994         }
2995
2996         if (data_size != 0) {
2997                 cifs_dbg(VFS, "%s: something went wrong\n", __func__);
2998                 kfree(bvec);
2999                 return -EIO;
3000         }
3001
3002         *page_vec = bvec;
3003         return 0;
3004 }
3005
3006 static int
3007 handle_read_data(struct TCP_Server_Info *server, struct mid_q_entry *mid,
3008                  char *buf, unsigned int buf_len, struct page **pages,
3009                  unsigned int npages, unsigned int page_data_size)
3010 {
3011         unsigned int data_offset;
3012         unsigned int data_len;
3013         unsigned int cur_off;
3014         unsigned int cur_page_idx;
3015         unsigned int pad_len;
3016         struct cifs_readdata *rdata = mid->callback_data;
3017         struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)buf;
3018         struct bio_vec *bvec = NULL;
3019         struct iov_iter iter;
3020         struct kvec iov;
3021         int length;
3022         bool use_rdma_mr = false;
3023
3024         if (shdr->Command != SMB2_READ) {
3025                 cifs_dbg(VFS, "only big read responses are supported\n");
3026                 return -ENOTSUPP;
3027         }
3028
3029         if (server->ops->is_session_expired &&
3030             server->ops->is_session_expired(buf)) {
3031                 cifs_reconnect(server);
3032                 wake_up(&server->response_q);
3033                 return -1;
3034         }
3035
3036         if (server->ops->is_status_pending &&
3037                         server->ops->is_status_pending(buf, server, 0))
3038                 return -1;
3039
3040         /* set up first two iov to get credits */
3041         rdata->iov[0].iov_base = buf;
3042         rdata->iov[0].iov_len = 0;
3043         rdata->iov[1].iov_base = buf;
3044         rdata->iov[1].iov_len =
3045                 min_t(unsigned int, buf_len, server->vals->read_rsp_size);
3046         cifs_dbg(FYI, "0: iov_base=%p iov_len=%zu\n",
3047                  rdata->iov[0].iov_base, rdata->iov[0].iov_len);
3048         cifs_dbg(FYI, "1: iov_base=%p iov_len=%zu\n",
3049                  rdata->iov[1].iov_base, rdata->iov[1].iov_len);
3050
3051         rdata->result = server->ops->map_error(buf, true);
3052         if (rdata->result != 0) {
3053                 cifs_dbg(FYI, "%s: server returned error %d\n",
3054                          __func__, rdata->result);
3055                 /* normal error on read response */
3056                 dequeue_mid(mid, false);
3057                 return 0;
3058         }
3059
3060         data_offset = server->ops->read_data_offset(buf);
3061 #ifdef CONFIG_CIFS_SMB_DIRECT
3062         use_rdma_mr = rdata->mr;
3063 #endif
3064         data_len = server->ops->read_data_length(buf, use_rdma_mr);
3065
3066         if (data_offset < server->vals->read_rsp_size) {
3067                 /*
3068                  * win2k8 sometimes sends an offset of 0 when the read
3069                  * is beyond the EOF. Treat it as if the data starts just after
3070                  * the header.
3071                  */
3072                 cifs_dbg(FYI, "%s: data offset (%u) inside read response header\n",
3073                          __func__, data_offset);
3074                 data_offset = server->vals->read_rsp_size;
3075         } else if (data_offset > MAX_CIFS_SMALL_BUFFER_SIZE) {
3076                 /* data_offset is beyond the end of smallbuf */
3077                 cifs_dbg(FYI, "%s: data offset (%u) beyond end of smallbuf\n",
3078                          __func__, data_offset);
3079                 rdata->result = -EIO;
3080                 dequeue_mid(mid, rdata->result);
3081                 return 0;
3082         }
3083
3084         pad_len = data_offset - server->vals->read_rsp_size;
3085
3086         if (buf_len <= data_offset) {
3087                 /* read response payload is in pages */
3088                 cur_page_idx = pad_len / PAGE_SIZE;
3089                 cur_off = pad_len % PAGE_SIZE;
3090
3091                 if (cur_page_idx != 0) {
3092                         /* data offset is beyond the 1st page of response */
3093                         cifs_dbg(FYI, "%s: data offset (%u) beyond 1st page of response\n",
3094                                  __func__, data_offset);
3095                         rdata->result = -EIO;
3096                         dequeue_mid(mid, rdata->result);
3097                         return 0;
3098                 }
3099
3100                 if (data_len > page_data_size - pad_len) {
3101                         /* data_len is corrupt -- discard frame */
3102                         rdata->result = -EIO;
3103                         dequeue_mid(mid, rdata->result);
3104                         return 0;
3105                 }
3106
3107                 rdata->result = init_read_bvec(pages, npages, page_data_size,
3108                                                cur_off, &bvec);
3109                 if (rdata->result != 0) {
3110                         dequeue_mid(mid, rdata->result);
3111                         return 0;
3112                 }
3113
3114                 iov_iter_bvec(&iter, WRITE | ITER_BVEC, bvec, npages, data_len);
3115         } else if (buf_len >= data_offset + data_len) {
3116                 /* read response payload is in buf */
3117                 WARN_ONCE(npages > 0, "read data can be either in buf or in pages");
3118                 iov.iov_base = buf + data_offset;
3119                 iov.iov_len = data_len;
3120                 iov_iter_kvec(&iter, WRITE | ITER_KVEC, &iov, 1, data_len);
3121         } else {
3122                 /* read response payload cannot be in both buf and pages */
3123                 WARN_ONCE(1, "buf can not contain only a part of read data");
3124                 rdata->result = -EIO;
3125                 dequeue_mid(mid, rdata->result);
3126                 return 0;
3127         }
3128
3129         length = rdata->copy_into_pages(server, rdata, &iter);
3130
3131         kfree(bvec);
3132
3133         if (length < 0)
3134                 return length;
3135
3136         dequeue_mid(mid, false);
3137         return length;
3138 }
3139
3140 static int
3141 receive_encrypted_read(struct TCP_Server_Info *server, struct mid_q_entry **mid)
3142 {
3143         char *buf = server->smallbuf;
3144         struct smb2_transform_hdr *tr_hdr = (struct smb2_transform_hdr *)buf;
3145         unsigned int npages;
3146         struct page **pages;
3147         unsigned int len;
3148         unsigned int buflen = server->pdu_size;
3149         int rc;
3150         int i = 0;
3151
3152         len = min_t(unsigned int, buflen, server->vals->read_rsp_size +
3153                 sizeof(struct smb2_transform_hdr)) - HEADER_SIZE(server) + 1;
3154
3155         rc = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1, len);
3156         if (rc < 0)
3157                 return rc;
3158         server->total_read += rc;
3159
3160         len = le32_to_cpu(tr_hdr->OriginalMessageSize) -
3161                 server->vals->read_rsp_size;
3162         npages = DIV_ROUND_UP(len, PAGE_SIZE);
3163
3164         pages = kmalloc_array(npages, sizeof(struct page *), GFP_KERNEL);
3165         if (!pages) {
3166                 rc = -ENOMEM;
3167                 goto discard_data;
3168         }
3169
3170         for (; i < npages; i++) {
3171                 pages[i] = alloc_page(GFP_KERNEL|__GFP_HIGHMEM);
3172                 if (!pages[i]) {
3173                         rc = -ENOMEM;
3174                         goto discard_data;
3175                 }
3176         }
3177
3178         /* read read data into pages */
3179         rc = read_data_into_pages(server, pages, npages, len);
3180         if (rc)
3181                 goto free_pages;
3182
3183         rc = cifs_discard_remaining_data(server);
3184         if (rc)
3185                 goto free_pages;
3186
3187         rc = decrypt_raw_data(server, buf, server->vals->read_rsp_size,
3188                               pages, npages, len);
3189         if (rc)
3190                 goto free_pages;
3191
3192         *mid = smb2_find_mid(server, buf);
3193         if (*mid == NULL)
3194                 cifs_dbg(FYI, "mid not found\n");
3195         else {
3196                 cifs_dbg(FYI, "mid found\n");
3197                 (*mid)->decrypted = true;
3198                 rc = handle_read_data(server, *mid, buf,
3199                                       server->vals->read_rsp_size,
3200                                       pages, npages, len);
3201         }
3202
3203 free_pages:
3204         for (i = i - 1; i >= 0; i--)
3205                 put_page(pages[i]);
3206         kfree(pages);
3207         return rc;
3208 discard_data:
3209         cifs_discard_remaining_data(server);
3210         goto free_pages;
3211 }
3212
3213 static int
3214 receive_encrypted_standard(struct TCP_Server_Info *server,
3215                            struct mid_q_entry **mids, char **bufs,
3216                            int *num_mids)
3217 {
3218         int ret, length;
3219         char *buf = server->smallbuf;
3220         struct smb2_sync_hdr *shdr;
3221         unsigned int pdu_length = server->pdu_size;
3222         unsigned int buf_size;
3223         struct mid_q_entry *mid_entry;
3224         int next_is_large;
3225         char *next_buffer = NULL;
3226
3227         *num_mids = 0;
3228
3229         /* switch to large buffer if too big for a small one */
3230         if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE) {
3231                 server->large_buf = true;
3232                 memcpy(server->bigbuf, buf, server->total_read);
3233                 buf = server->bigbuf;
3234         }
3235
3236         /* now read the rest */
3237         length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
3238                                 pdu_length - HEADER_SIZE(server) + 1);
3239         if (length < 0)
3240                 return length;
3241         server->total_read += length;
3242
3243         buf_size = pdu_length - sizeof(struct smb2_transform_hdr);
3244         length = decrypt_raw_data(server, buf, buf_size, NULL, 0, 0);
3245         if (length)
3246                 return length;
3247
3248         next_is_large = server->large_buf;
3249 one_more:
3250         shdr = (struct smb2_sync_hdr *)buf;
3251         if (shdr->NextCommand) {
3252                 if (next_is_large)
3253                         next_buffer = (char *)cifs_buf_get();
3254                 else
3255                         next_buffer = (char *)cifs_small_buf_get();
3256                 memcpy(next_buffer,
3257                        buf + le32_to_cpu(shdr->NextCommand),
3258                        pdu_length - le32_to_cpu(shdr->NextCommand));
3259         }
3260
3261         mid_entry = smb2_find_mid(server, buf);
3262         if (mid_entry == NULL)
3263                 cifs_dbg(FYI, "mid not found\n");
3264         else {
3265                 cifs_dbg(FYI, "mid found\n");
3266                 mid_entry->decrypted = true;
3267                 mid_entry->resp_buf_size = server->pdu_size;
3268         }
3269
3270         if (*num_mids >= MAX_COMPOUND) {
3271                 cifs_dbg(VFS, "too many PDUs in compound\n");
3272                 return -1;
3273         }
3274         bufs[*num_mids] = buf;
3275         mids[(*num_mids)++] = mid_entry;
3276
3277         if (mid_entry && mid_entry->handle)
3278                 ret = mid_entry->handle(server, mid_entry);
3279         else
3280                 ret = cifs_handle_standard(server, mid_entry);
3281
3282         if (ret == 0 && shdr->NextCommand) {
3283                 pdu_length -= le32_to_cpu(shdr->NextCommand);
3284                 server->large_buf = next_is_large;
3285                 if (next_is_large)
3286                         server->bigbuf = buf = next_buffer;
3287                 else
3288                         server->smallbuf = buf = next_buffer;
3289                 goto one_more;
3290         } else if (ret != 0) {
3291                 /*
3292                  * ret != 0 here means that we didn't get to handle_mid() thus
3293                  * server->smallbuf and server->bigbuf are still valid. We need
3294                  * to free next_buffer because it is not going to be used
3295                  * anywhere.
3296                  */
3297                 if (next_is_large)
3298                         free_rsp_buf(CIFS_LARGE_BUFFER, next_buffer);
3299                 else
3300                         free_rsp_buf(CIFS_SMALL_BUFFER, next_buffer);
3301         }
3302
3303         return ret;
3304 }
3305
3306 static int
3307 smb3_receive_transform(struct TCP_Server_Info *server,
3308                        struct mid_q_entry **mids, char **bufs, int *num_mids)
3309 {
3310         char *buf = server->smallbuf;
3311         unsigned int pdu_length = server->pdu_size;
3312         struct smb2_transform_hdr *tr_hdr = (struct smb2_transform_hdr *)buf;
3313         unsigned int orig_len = le32_to_cpu(tr_hdr->OriginalMessageSize);
3314
3315         if (pdu_length < sizeof(struct smb2_transform_hdr) +
3316                                                 sizeof(struct smb2_sync_hdr)) {
3317                 cifs_dbg(VFS, "Transform message is too small (%u)\n",
3318                          pdu_length);
3319                 cifs_reconnect(server);
3320                 wake_up(&server->response_q);
3321                 return -ECONNABORTED;
3322         }
3323
3324         if (pdu_length < orig_len + sizeof(struct smb2_transform_hdr)) {
3325                 cifs_dbg(VFS, "Transform message is broken\n");
3326                 cifs_reconnect(server);
3327                 wake_up(&server->response_q);
3328                 return -ECONNABORTED;
3329         }
3330
3331         /* TODO: add support for compounds containing READ. */
3332         if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server)) {
3333                 *num_mids = 1;
3334                 return receive_encrypted_read(server, &mids[0]);
3335         }
3336
3337         return receive_encrypted_standard(server, mids, bufs, num_mids);
3338 }
3339
3340 int
3341 smb3_handle_read_data(struct TCP_Server_Info *server, struct mid_q_entry *mid)
3342 {
3343         char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
3344
3345         return handle_read_data(server, mid, buf, server->pdu_size,
3346                                 NULL, 0, 0);
3347 }
3348
3349 static int
3350 smb2_next_header(char *buf)
3351 {
3352         struct smb2_sync_hdr *hdr = (struct smb2_sync_hdr *)buf;
3353         struct smb2_transform_hdr *t_hdr = (struct smb2_transform_hdr *)buf;
3354
3355         if (hdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM)
3356                 return sizeof(struct smb2_transform_hdr) +
3357                   le32_to_cpu(t_hdr->OriginalMessageSize);
3358
3359         return le32_to_cpu(hdr->NextCommand);
3360 }
3361
3362 struct smb_version_operations smb20_operations = {
3363         .compare_fids = smb2_compare_fids,
3364         .setup_request = smb2_setup_request,
3365         .setup_async_request = smb2_setup_async_request,
3366         .check_receive = smb2_check_receive,
3367         .add_credits = smb2_add_credits,
3368         .set_credits = smb2_set_credits,
3369         .get_credits_field = smb2_get_credits_field,
3370         .get_credits = smb2_get_credits,
3371         .wait_mtu_credits = cifs_wait_mtu_credits,
3372         .get_next_mid = smb2_get_next_mid,
3373         .revert_current_mid = smb2_revert_current_mid,
3374         .read_data_offset = smb2_read_data_offset,
3375         .read_data_length = smb2_read_data_length,
3376         .map_error = map_smb2_to_linux_error,
3377         .find_mid = smb2_find_mid,
3378         .check_message = smb2_check_message,
3379         .dump_detail = smb2_dump_detail,
3380         .clear_stats = smb2_clear_stats,
3381         .print_stats = smb2_print_stats,
3382         .is_oplock_break = smb2_is_valid_oplock_break,
3383         .handle_cancelled_mid = smb2_handle_cancelled_mid,
3384         .downgrade_oplock = smb2_downgrade_oplock,
3385         .need_neg = smb2_need_neg,
3386         .negotiate = smb2_negotiate,
3387         .negotiate_wsize = smb2_negotiate_wsize,
3388         .negotiate_rsize = smb2_negotiate_rsize,
3389         .sess_setup = SMB2_sess_setup,
3390         .logoff = SMB2_logoff,
3391         .tree_connect = SMB2_tcon,
3392         .tree_disconnect = SMB2_tdis,
3393         .qfs_tcon = smb2_qfs_tcon,
3394         .is_path_accessible = smb2_is_path_accessible,
3395         .can_echo = smb2_can_echo,
3396         .echo = SMB2_echo,
3397         .query_path_info = smb2_query_path_info,
3398         .get_srv_inum = smb2_get_srv_inum,
3399         .query_file_info = smb2_query_file_info,
3400         .set_path_size = smb2_set_path_size,
3401         .set_file_size = smb2_set_file_size,
3402         .set_file_info = smb2_set_file_info,
3403         .set_compression = smb2_set_compression,
3404         .mkdir = smb2_mkdir,
3405         .mkdir_setinfo = smb2_mkdir_setinfo,
3406         .rmdir = smb2_rmdir,
3407         .unlink = smb2_unlink,
3408         .rename = smb2_rename_path,
3409         .create_hardlink = smb2_create_hardlink,
3410         .query_symlink = smb2_query_symlink,
3411         .query_mf_symlink = smb3_query_mf_symlink,
3412         .create_mf_symlink = smb3_create_mf_symlink,
3413         .open = smb2_open_file,
3414         .set_fid = smb2_set_fid,
3415         .close = smb2_close_file,
3416         .flush = smb2_flush_file,
3417         .async_readv = smb2_async_readv,
3418         .async_writev = smb2_async_writev,
3419         .sync_read = smb2_sync_read,
3420         .sync_write = smb2_sync_write,
3421         .query_dir_first = smb2_query_dir_first,
3422         .query_dir_next = smb2_query_dir_next,
3423         .close_dir = smb2_close_dir,
3424         .calc_smb_size = smb2_calc_size,
3425         .is_status_pending = smb2_is_status_pending,
3426         .is_session_expired = smb2_is_session_expired,
3427         .oplock_response = smb2_oplock_response,
3428         .queryfs = smb2_queryfs,
3429         .mand_lock = smb2_mand_lock,
3430         .mand_unlock_range = smb2_unlock_range,
3431         .push_mand_locks = smb2_push_mandatory_locks,
3432         .get_lease_key = smb2_get_lease_key,
3433         .set_lease_key = smb2_set_lease_key,
3434         .new_lease_key = smb2_new_lease_key,
3435         .calc_signature = smb2_calc_signature,
3436         .is_read_op = smb2_is_read_op,
3437         .set_oplock_level = smb2_set_oplock_level,
3438         .create_lease_buf = smb2_create_lease_buf,
3439         .parse_lease_buf = smb2_parse_lease_buf,
3440         .copychunk_range = smb2_copychunk_range,
3441         .wp_retry_size = smb2_wp_retry_size,
3442         .dir_needs_close = smb2_dir_needs_close,
3443         .get_dfs_refer = smb2_get_dfs_refer,
3444         .select_sectype = smb2_select_sectype,
3445 #ifdef CONFIG_CIFS_XATTR
3446         .query_all_EAs = smb2_query_eas,
3447         .set_EA = smb2_set_ea,
3448 #endif /* CIFS_XATTR */
3449 #ifdef CONFIG_CIFS_ACL
3450         .get_acl = get_smb2_acl,
3451         .get_acl_by_fid = get_smb2_acl_by_fid,
3452         .set_acl = set_smb2_acl,
3453 #endif /* CIFS_ACL */
3454         .next_header = smb2_next_header,
3455 };
3456
3457 struct smb_version_operations smb21_operations = {
3458         .compare_fids = smb2_compare_fids,
3459         .setup_request = smb2_setup_request,
3460         .setup_async_request = smb2_setup_async_request,
3461         .check_receive = smb2_check_receive,
3462         .add_credits = smb2_add_credits,
3463         .set_credits = smb2_set_credits,
3464         .get_credits_field = smb2_get_credits_field,
3465         .get_credits = smb2_get_credits,
3466         .wait_mtu_credits = smb2_wait_mtu_credits,
3467         .get_next_mid = smb2_get_next_mid,
3468         .revert_current_mid = smb2_revert_current_mid,
3469         .read_data_offset = smb2_read_data_offset,
3470         .read_data_length = smb2_read_data_length,
3471         .map_error = map_smb2_to_linux_error,
3472         .find_mid = smb2_find_mid,
3473         .check_message = smb2_check_message,
3474         .dump_detail = smb2_dump_detail,
3475         .clear_stats = smb2_clear_stats,
3476         .print_stats = smb2_print_stats,
3477         .is_oplock_break = smb2_is_valid_oplock_break,
3478         .handle_cancelled_mid = smb2_handle_cancelled_mid,
3479         .downgrade_oplock = smb2_downgrade_oplock,
3480         .need_neg = smb2_need_neg,
3481         .negotiate = smb2_negotiate,
3482         .negotiate_wsize = smb2_negotiate_wsize,
3483         .negotiate_rsize = smb2_negotiate_rsize,
3484         .sess_setup = SMB2_sess_setup,
3485         .logoff = SMB2_logoff,
3486         .tree_connect = SMB2_tcon,
3487         .tree_disconnect = SMB2_tdis,
3488         .qfs_tcon = smb2_qfs_tcon,
3489         .is_path_accessible = smb2_is_path_accessible,
3490         .can_echo = smb2_can_echo,
3491         .echo = SMB2_echo,
3492         .query_path_info = smb2_query_path_info,
3493         .get_srv_inum = smb2_get_srv_inum,
3494         .query_file_info = smb2_query_file_info,
3495         .set_path_size = smb2_set_path_size,
3496         .set_file_size = smb2_set_file_size,
3497         .set_file_info = smb2_set_file_info,
3498         .set_compression = smb2_set_compression,
3499         .mkdir = smb2_mkdir,
3500         .mkdir_setinfo = smb2_mkdir_setinfo,
3501         .rmdir = smb2_rmdir,
3502         .unlink = smb2_unlink,
3503         .rename = smb2_rename_path,
3504         .create_hardlink = smb2_create_hardlink,
3505         .query_symlink = smb2_query_symlink,
3506         .query_mf_symlink = smb3_query_mf_symlink,
3507         .create_mf_symlink = smb3_create_mf_symlink,
3508         .open = smb2_open_file,
3509         .set_fid = smb2_set_fid,
3510         .close = smb2_close_file,
3511         .flush = smb2_flush_file,
3512         .async_readv = smb2_async_readv,
3513         .async_writev = smb2_async_writev,
3514         .sync_read = smb2_sync_read,
3515         .sync_write = smb2_sync_write,
3516         .query_dir_first = smb2_query_dir_first,
3517         .query_dir_next = smb2_query_dir_next,
3518         .close_dir = smb2_close_dir,
3519         .calc_smb_size = smb2_calc_size,
3520         .is_status_pending = smb2_is_status_pending,
3521         .is_session_expired = smb2_is_session_expired,
3522         .oplock_response = smb2_oplock_response,
3523         .queryfs = smb2_queryfs,
3524         .mand_lock = smb2_mand_lock,
3525         .mand_unlock_range = smb2_unlock_range,
3526         .push_mand_locks = smb2_push_mandatory_locks,
3527         .get_lease_key = smb2_get_lease_key,
3528         .set_lease_key = smb2_set_lease_key,
3529         .new_lease_key = smb2_new_lease_key,
3530         .calc_signature = smb2_calc_signature,
3531         .is_read_op = smb21_is_read_op,
3532         .set_oplock_level = smb21_set_oplock_level,
3533         .create_lease_buf = smb2_create_lease_buf,
3534         .parse_lease_buf = smb2_parse_lease_buf,
3535         .copychunk_range = smb2_copychunk_range,
3536         .wp_retry_size = smb2_wp_retry_size,
3537         .dir_needs_close = smb2_dir_needs_close,
3538         .enum_snapshots = smb3_enum_snapshots,
3539         .get_dfs_refer = smb2_get_dfs_refer,
3540         .select_sectype = smb2_select_sectype,
3541 #ifdef CONFIG_CIFS_XATTR
3542         .query_all_EAs = smb2_query_eas,
3543         .set_EA = smb2_set_ea,
3544 #endif /* CIFS_XATTR */
3545 #ifdef CONFIG_CIFS_ACL
3546         .get_acl = get_smb2_acl,
3547         .get_acl_by_fid = get_smb2_acl_by_fid,
3548         .set_acl = set_smb2_acl,
3549 #endif /* CIFS_ACL */
3550         .next_header = smb2_next_header,
3551 };
3552
3553 struct smb_version_operations smb30_operations = {
3554         .compare_fids = smb2_compare_fids,
3555         .setup_request = smb2_setup_request,
3556         .setup_async_request = smb2_setup_async_request,
3557         .check_receive = smb2_check_receive,
3558         .add_credits = smb2_add_credits,
3559         .set_credits = smb2_set_credits,
3560         .get_credits_field = smb2_get_credits_field,
3561         .get_credits = smb2_get_credits,
3562         .wait_mtu_credits = smb2_wait_mtu_credits,
3563         .get_next_mid = smb2_get_next_mid,
3564         .revert_current_mid = smb2_revert_current_mid,
3565         .read_data_offset = smb2_read_data_offset,
3566         .read_data_length = smb2_read_data_length,
3567         .map_error = map_smb2_to_linux_error,
3568         .find_mid = smb2_find_mid,
3569         .check_message = smb2_check_message,
3570         .dump_detail = smb2_dump_detail,
3571         .clear_stats = smb2_clear_stats,
3572         .print_stats = smb2_print_stats,
3573         .dump_share_caps = smb2_dump_share_caps,
3574         .is_oplock_break = smb2_is_valid_oplock_break,
3575         .handle_cancelled_mid = smb2_handle_cancelled_mid,
3576         .downgrade_oplock = smb3_downgrade_oplock,
3577         .need_neg = smb2_need_neg,
3578         .negotiate = smb2_negotiate,
3579         .negotiate_wsize = smb2_negotiate_wsize,
3580         .negotiate_rsize = smb2_negotiate_rsize,
3581         .sess_setup = SMB2_sess_setup,
3582         .logoff = SMB2_logoff,
3583         .tree_connect = SMB2_tcon,
3584         .tree_disconnect = SMB2_tdis,
3585         .qfs_tcon = smb3_qfs_tcon,
3586         .is_path_accessible = smb2_is_path_accessible,
3587         .can_echo = smb2_can_echo,
3588         .echo = SMB2_echo,
3589         .query_path_info = smb2_query_path_info,
3590         .get_srv_inum = smb2_get_srv_inum,
3591         .query_file_info = smb2_query_file_info,
3592         .set_path_size = smb2_set_path_size,
3593         .set_file_size = smb2_set_file_size,
3594         .set_file_info = smb2_set_file_info,
3595         .set_compression = smb2_set_compression,
3596         .mkdir = smb2_mkdir,
3597         .mkdir_setinfo = smb2_mkdir_setinfo,
3598         .rmdir = smb2_rmdir,
3599         .unlink = smb2_unlink,
3600         .rename = smb2_rename_path,
3601         .create_hardlink = smb2_create_hardlink,
3602         .query_symlink = smb2_query_symlink,
3603         .query_mf_symlink = smb3_query_mf_symlink,
3604         .create_mf_symlink = smb3_create_mf_symlink,
3605         .open = smb2_open_file,
3606         .set_fid = smb2_set_fid,
3607         .close = smb2_close_file,
3608         .flush = smb2_flush_file,
3609         .async_readv = smb2_async_readv,
3610         .async_writev = smb2_async_writev,
3611         .sync_read = smb2_sync_read,
3612         .sync_write = smb2_sync_write,
3613         .query_dir_first = smb2_query_dir_first,
3614         .query_dir_next = smb2_query_dir_next,
3615         .close_dir = smb2_close_dir,
3616         .calc_smb_size = smb2_calc_size,
3617         .is_status_pending = smb2_is_status_pending,
3618         .is_session_expired = smb2_is_session_expired,
3619         .oplock_response = smb2_oplock_response,
3620         .queryfs = smb2_queryfs,
3621         .mand_lock = smb2_mand_lock,
3622         .mand_unlock_range = smb2_unlock_range,
3623         .push_mand_locks = smb2_push_mandatory_locks,
3624         .get_lease_key = smb2_get_lease_key,
3625         .set_lease_key = smb2_set_lease_key,
3626         .new_lease_key = smb2_new_lease_key,
3627         .generate_signingkey = generate_smb30signingkey,
3628         .calc_signature = smb3_calc_signature,
3629         .set_integrity  = smb3_set_integrity,
3630         .is_read_op = smb21_is_read_op,
3631         .set_oplock_level = smb3_set_oplock_level,
3632         .create_lease_buf = smb3_create_lease_buf,
3633         .parse_lease_buf = smb3_parse_lease_buf,
3634         .copychunk_range = smb2_copychunk_range,
3635         .duplicate_extents = smb2_duplicate_extents,
3636         .validate_negotiate = smb3_validate_negotiate,
3637         .wp_retry_size = smb2_wp_retry_size,
3638         .dir_needs_close = smb2_dir_needs_close,
3639         .fallocate = smb3_fallocate,
3640         .enum_snapshots = smb3_enum_snapshots,
3641         .init_transform_rq = smb3_init_transform_rq,
3642         .is_transform_hdr = smb3_is_transform_hdr,
3643         .receive_transform = smb3_receive_transform,
3644         .get_dfs_refer = smb2_get_dfs_refer,
3645         .select_sectype = smb2_select_sectype,
3646 #ifdef CONFIG_CIFS_XATTR
3647         .query_all_EAs = smb2_query_eas,
3648         .set_EA = smb2_set_ea,
3649 #endif /* CIFS_XATTR */
3650 #ifdef CONFIG_CIFS_ACL
3651         .get_acl = get_smb2_acl,
3652         .get_acl_by_fid = get_smb2_acl_by_fid,
3653         .set_acl = set_smb2_acl,
3654 #endif /* CIFS_ACL */
3655         .next_header = smb2_next_header,
3656 };
3657
3658 struct smb_version_operations smb311_operations = {
3659         .compare_fids = smb2_compare_fids,
3660         .setup_request = smb2_setup_request,
3661         .setup_async_request = smb2_setup_async_request,
3662         .check_receive = smb2_check_receive,
3663         .add_credits = smb2_add_credits,
3664         .set_credits = smb2_set_credits,
3665         .get_credits_field = smb2_get_credits_field,
3666         .get_credits = smb2_get_credits,
3667         .wait_mtu_credits = smb2_wait_mtu_credits,
3668         .get_next_mid = smb2_get_next_mid,
3669         .revert_current_mid = smb2_revert_current_mid,
3670         .read_data_offset = smb2_read_data_offset,
3671         .read_data_length = smb2_read_data_length,
3672         .map_error = map_smb2_to_linux_error,
3673         .find_mid = smb2_find_mid,
3674         .check_message = smb2_check_message,
3675         .dump_detail = smb2_dump_detail,
3676         .clear_stats = smb2_clear_stats,
3677         .print_stats = smb2_print_stats,
3678         .dump_share_caps = smb2_dump_share_caps,
3679         .is_oplock_break = smb2_is_valid_oplock_break,
3680         .handle_cancelled_mid = smb2_handle_cancelled_mid,
3681         .downgrade_oplock = smb3_downgrade_oplock,
3682         .need_neg = smb2_need_neg,
3683         .negotiate = smb2_negotiate,
3684         .negotiate_wsize = smb2_negotiate_wsize,
3685         .negotiate_rsize = smb2_negotiate_rsize,
3686         .sess_setup = SMB2_sess_setup,
3687         .logoff = SMB2_logoff,
3688         .tree_connect = SMB2_tcon,
3689         .tree_disconnect = SMB2_tdis,
3690         .qfs_tcon = smb3_qfs_tcon,
3691         .is_path_accessible = smb2_is_path_accessible,
3692         .can_echo = smb2_can_echo,
3693         .echo = SMB2_echo,
3694         .query_path_info = smb2_query_path_info,
3695         .get_srv_inum = smb2_get_srv_inum,
3696         .query_file_info = smb2_query_file_info,
3697         .set_path_size = smb2_set_path_size,
3698         .set_file_size = smb2_set_file_size,
3699         .set_file_info = smb2_set_file_info,
3700         .set_compression = smb2_set_compression,
3701         .mkdir = smb2_mkdir,
3702         .mkdir_setinfo = smb2_mkdir_setinfo,
3703         .posix_mkdir = smb311_posix_mkdir,
3704         .rmdir = smb2_rmdir,
3705         .unlink = smb2_unlink,
3706         .rename = smb2_rename_path,
3707         .create_hardlink = smb2_create_hardlink,
3708         .query_symlink = smb2_query_symlink,
3709         .query_mf_symlink = smb3_query_mf_symlink,
3710         .create_mf_symlink = smb3_create_mf_symlink,
3711         .open = smb2_open_file,
3712         .set_fid = smb2_set_fid,
3713         .close = smb2_close_file,
3714         .flush = smb2_flush_file,
3715         .async_readv = smb2_async_readv,
3716         .async_writev = smb2_async_writev,
3717         .sync_read = smb2_sync_read,
3718         .sync_write = smb2_sync_write,
3719         .query_dir_first = smb2_query_dir_first,
3720         .query_dir_next = smb2_query_dir_next,
3721         .close_dir = smb2_close_dir,
3722         .calc_smb_size = smb2_calc_size,
3723         .is_status_pending = smb2_is_status_pending,
3724         .is_session_expired = smb2_is_session_expired,
3725         .oplock_response = smb2_oplock_response,
3726         .queryfs = smb311_queryfs,
3727         .mand_lock = smb2_mand_lock,
3728         .mand_unlock_range = smb2_unlock_range,
3729         .push_mand_locks = smb2_push_mandatory_locks,
3730         .get_lease_key = smb2_get_lease_key,
3731         .set_lease_key = smb2_set_lease_key,
3732         .new_lease_key = smb2_new_lease_key,
3733         .generate_signingkey = generate_smb311signingkey,
3734         .calc_signature = smb3_calc_signature,
3735         .set_integrity  = smb3_set_integrity,
3736         .is_read_op = smb21_is_read_op,
3737         .set_oplock_level = smb3_set_oplock_level,
3738         .create_lease_buf = smb3_create_lease_buf,
3739         .parse_lease_buf = smb3_parse_lease_buf,
3740         .copychunk_range = smb2_copychunk_range,
3741         .duplicate_extents = smb2_duplicate_extents,
3742 /*      .validate_negotiate = smb3_validate_negotiate, */ /* not used in 3.11 */
3743         .wp_retry_size = smb2_wp_retry_size,
3744         .dir_needs_close = smb2_dir_needs_close,
3745         .fallocate = smb3_fallocate,
3746         .enum_snapshots = smb3_enum_snapshots,
3747         .init_transform_rq = smb3_init_transform_rq,
3748         .is_transform_hdr = smb3_is_transform_hdr,
3749         .receive_transform = smb3_receive_transform,
3750         .get_dfs_refer = smb2_get_dfs_refer,
3751         .select_sectype = smb2_select_sectype,
3752 #ifdef CONFIG_CIFS_XATTR
3753         .query_all_EAs = smb2_query_eas,
3754         .set_EA = smb2_set_ea,
3755 #endif /* CIFS_XATTR */
3756 #ifdef CONFIG_CIFS_ACL
3757         .get_acl = get_smb2_acl,
3758         .get_acl_by_fid = get_smb2_acl_by_fid,
3759         .set_acl = set_smb2_acl,
3760 #endif /* CIFS_ACL */
3761         .next_header = smb2_next_header,
3762 };
3763
3764 struct smb_version_values smb20_values = {
3765         .version_string = SMB20_VERSION_STRING,
3766         .protocol_id = SMB20_PROT_ID,
3767         .req_capabilities = 0, /* MBZ */
3768         .large_lock_type = 0,
3769         .exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
3770         .shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
3771         .unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
3772         .header_size = sizeof(struct smb2_sync_hdr),
3773         .header_preamble_size = 0,
3774         .max_header_size = MAX_SMB2_HDR_SIZE,
3775         .read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
3776         .lock_cmd = SMB2_LOCK,
3777         .cap_unix = 0,
3778         .cap_nt_find = SMB2_NT_FIND,
3779         .cap_large_files = SMB2_LARGE_FILES,
3780         .signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
3781         .signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
3782         .create_lease_size = sizeof(struct create_lease),
3783 };
3784
3785 struct smb_version_values smb21_values = {
3786         .version_string = SMB21_VERSION_STRING,
3787         .protocol_id = SMB21_PROT_ID,
3788         .req_capabilities = 0, /* MBZ on negotiate req until SMB3 dialect */
3789         .large_lock_type = 0,
3790         .exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
3791         .shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
3792         .unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
3793         .header_size = sizeof(struct smb2_sync_hdr),
3794         .header_preamble_size = 0,
3795         .max_header_size = MAX_SMB2_HDR_SIZE,
3796         .read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
3797         .lock_cmd = SMB2_LOCK,
3798         .cap_unix = 0,
3799         .cap_nt_find = SMB2_NT_FIND,
3800         .cap_large_files = SMB2_LARGE_FILES,
3801         .signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
3802         .signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
3803         .create_lease_size = sizeof(struct create_lease),
3804 };
3805
3806 struct smb_version_values smb3any_values = {
3807         .version_string = SMB3ANY_VERSION_STRING,
3808         .protocol_id = SMB302_PROT_ID, /* doesn't matter, send protocol array */
3809         .req_capabilities = SMB2_GLOBAL_CAP_DFS | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_PERSISTENT_HANDLES | SMB2_GLOBAL_CAP_ENCRYPTION | SMB2_GLOBAL_CAP_DIRECTORY_LEASING,
3810         .large_lock_type = 0,
3811         .exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
3812         .shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
3813         .unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
3814         .header_size = sizeof(struct smb2_sync_hdr),
3815         .header_preamble_size = 0,
3816         .max_header_size = MAX_SMB2_HDR_SIZE,
3817         .read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
3818         .lock_cmd = SMB2_LOCK,
3819         .cap_unix = 0,
3820         .cap_nt_find = SMB2_NT_FIND,
3821         .cap_large_files = SMB2_LARGE_FILES,
3822         .signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
3823         .signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
3824         .create_lease_size = sizeof(struct create_lease_v2),
3825 };
3826
3827 struct smb_version_values smbdefault_values = {
3828         .version_string = SMBDEFAULT_VERSION_STRING,
3829         .protocol_id = SMB302_PROT_ID, /* doesn't matter, send protocol array */
3830         .req_capabilities = SMB2_GLOBAL_CAP_DFS | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_PERSISTENT_HANDLES | SMB2_GLOBAL_CAP_ENCRYPTION | SMB2_GLOBAL_CAP_DIRECTORY_LEASING,
3831         .large_lock_type = 0,
3832         .exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
3833         .shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
3834         .unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
3835         .header_size = sizeof(struct smb2_sync_hdr),
3836         .header_preamble_size = 0,
3837         .max_header_size = MAX_SMB2_HDR_SIZE,
3838         .read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
3839         .lock_cmd = SMB2_LOCK,
3840         .cap_unix = 0,
3841         .cap_nt_find = SMB2_NT_FIND,
3842         .cap_large_files = SMB2_LARGE_FILES,
3843         .signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
3844         .signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
3845         .create_lease_size = sizeof(struct create_lease_v2),
3846 };
3847
3848 struct smb_version_values smb30_values = {
3849         .version_string = SMB30_VERSION_STRING,
3850         .protocol_id = SMB30_PROT_ID,
3851         .req_capabilities = SMB2_GLOBAL_CAP_DFS | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_PERSISTENT_HANDLES | SMB2_GLOBAL_CAP_ENCRYPTION | SMB2_GLOBAL_CAP_DIRECTORY_LEASING,
3852         .large_lock_type = 0,
3853         .exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
3854         .shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
3855         .unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
3856         .header_size = sizeof(struct smb2_sync_hdr),
3857         .header_preamble_size = 0,
3858         .max_header_size = MAX_SMB2_HDR_SIZE,
3859         .read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
3860         .lock_cmd = SMB2_LOCK,
3861         .cap_unix = 0,
3862         .cap_nt_find = SMB2_NT_FIND,
3863         .cap_large_files = SMB2_LARGE_FILES,
3864         .signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
3865         .signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
3866         .create_lease_size = sizeof(struct create_lease_v2),
3867 };
3868
3869 struct smb_version_values smb302_values = {
3870         .version_string = SMB302_VERSION_STRING,
3871         .protocol_id = SMB302_PROT_ID,
3872         .req_capabilities = SMB2_GLOBAL_CAP_DFS | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_PERSISTENT_HANDLES | SMB2_GLOBAL_CAP_ENCRYPTION | SMB2_GLOBAL_CAP_DIRECTORY_LEASING,
3873         .large_lock_type = 0,
3874         .exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
3875         .shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
3876         .unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
3877         .header_size = sizeof(struct smb2_sync_hdr),
3878         .header_preamble_size = 0,
3879         .max_header_size = MAX_SMB2_HDR_SIZE,
3880         .read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
3881         .lock_cmd = SMB2_LOCK,
3882         .cap_unix = 0,
3883         .cap_nt_find = SMB2_NT_FIND,
3884         .cap_large_files = SMB2_LARGE_FILES,
3885         .signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
3886         .signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
3887         .create_lease_size = sizeof(struct create_lease_v2),
3888 };
3889
3890 struct smb_version_values smb311_values = {
3891         .version_string = SMB311_VERSION_STRING,
3892         .protocol_id = SMB311_PROT_ID,
3893         .req_capabilities = SMB2_GLOBAL_CAP_DFS | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_PERSISTENT_HANDLES | SMB2_GLOBAL_CAP_ENCRYPTION | SMB2_GLOBAL_CAP_DIRECTORY_LEASING,
3894         .large_lock_type = 0,
3895         .exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
3896         .shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
3897         .unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
3898         .header_size = sizeof(struct smb2_sync_hdr),
3899         .header_preamble_size = 0,
3900         .max_header_size = MAX_SMB2_HDR_SIZE,
3901         .read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
3902         .lock_cmd = SMB2_LOCK,
3903         .cap_unix = 0,
3904         .cap_nt_find = SMB2_NT_FIND,
3905         .cap_large_files = SMB2_LARGE_FILES,
3906         .signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
3907         .signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
3908         .create_lease_size = sizeof(struct create_lease_v2),
3909 };