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