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