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