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