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