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