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