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