Merge tag 'for-linus' of git://git.armlinux.org.uk/~rmk/linux-arm
[linux-2.6-microblaze.git] / fs / cifs / smb2ops.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  SMB2 version specific operations
4  *
5  *  Copyright (c) 2012, Jeff Layton <jlayton@redhat.com>
6  */
7
8 #include <linux/pagemap.h>
9 #include <linux/vfs.h>
10 #include <linux/falloc.h>
11 #include <linux/scatterlist.h>
12 #include <linux/uuid.h>
13 #include <linux/sort.h>
14 #include <crypto/aead.h>
15 #include "cifsglob.h"
16 #include "smb2pdu.h"
17 #include "smb2proto.h"
18 #include "cifsproto.h"
19 #include "cifs_debug.h"
20 #include "cifs_unicode.h"
21 #include "smb2status.h"
22 #include "smb2glob.h"
23 #include "cifs_ioctl.h"
24 #include "smbdirect.h"
25
26 /* Change credits for different ops and return the total number of credits */
27 static int
28 change_conf(struct TCP_Server_Info *server)
29 {
30         server->credits += server->echo_credits + server->oplock_credits;
31         server->oplock_credits = server->echo_credits = 0;
32         switch (server->credits) {
33         case 0:
34                 return 0;
35         case 1:
36                 server->echoes = false;
37                 server->oplocks = false;
38                 break;
39         case 2:
40                 server->echoes = true;
41                 server->oplocks = false;
42                 server->echo_credits = 1;
43                 break;
44         default:
45                 server->echoes = true;
46                 if (enable_oplocks) {
47                         server->oplocks = true;
48                         server->oplock_credits = 1;
49                 } else
50                         server->oplocks = false;
51
52                 server->echo_credits = 1;
53         }
54         server->credits -= server->echo_credits + server->oplock_credits;
55         return server->credits + server->echo_credits + server->oplock_credits;
56 }
57
58 static void
59 smb2_add_credits(struct TCP_Server_Info *server,
60                  const struct cifs_credits *credits, const int optype)
61 {
62         int *val, rc = -1;
63         unsigned int add = credits->value;
64         unsigned int instance = credits->instance;
65         bool reconnect_detected = false;
66
67         spin_lock(&server->req_lock);
68         val = server->ops->get_credits_field(server, optype);
69
70         /* eg found case where write overlapping reconnect messed up credits */
71         if (((optype & CIFS_OP_MASK) == CIFS_NEG_OP) && (*val != 0))
72                 trace_smb3_reconnect_with_invalid_credits(server->CurrentMid,
73                         server->hostname, *val);
74         if ((instance == 0) || (instance == server->reconnect_instance))
75                 *val += add;
76         else
77                 reconnect_detected = true;
78
79         if (*val > 65000) {
80                 *val = 65000; /* Don't get near 64K credits, avoid srv bugs */
81                 printk_once(KERN_WARNING "server overflowed SMB3 credits\n");
82         }
83         server->in_flight--;
84         if (server->in_flight == 0 && (optype & CIFS_OP_MASK) != CIFS_NEG_OP)
85                 rc = change_conf(server);
86         /*
87          * Sometimes server returns 0 credits on oplock break ack - we need to
88          * rebalance credits in this case.
89          */
90         else if (server->in_flight > 0 && server->oplock_credits == 0 &&
91                  server->oplocks) {
92                 if (server->credits > 1) {
93                         server->credits--;
94                         server->oplock_credits++;
95                 }
96         }
97         spin_unlock(&server->req_lock);
98         wake_up(&server->request_q);
99
100         if (reconnect_detected)
101                 cifs_dbg(FYI, "trying to put %d credits from the old server instance %d\n",
102                          add, instance);
103
104         if (server->tcpStatus == CifsNeedReconnect
105             || server->tcpStatus == CifsExiting)
106                 return;
107
108         switch (rc) {
109         case -1:
110                 /* change_conf hasn't been executed */
111                 break;
112         case 0:
113                 cifs_server_dbg(VFS, "Possible client or server bug - zero credits\n");
114                 break;
115         case 1:
116                 cifs_server_dbg(VFS, "disabling echoes and oplocks\n");
117                 break;
118         case 2:
119                 cifs_dbg(FYI, "disabling oplocks\n");
120                 break;
121         default:
122                 cifs_dbg(FYI, "add %u credits total=%d\n", add, rc);
123         }
124 }
125
126 static void
127 smb2_set_credits(struct TCP_Server_Info *server, const int val)
128 {
129         spin_lock(&server->req_lock);
130         server->credits = val;
131         if (val == 1)
132                 server->reconnect_instance++;
133         spin_unlock(&server->req_lock);
134         /* don't log while holding the lock */
135         if (val == 1)
136                 cifs_dbg(FYI, "set credits to 1 due to smb2 reconnect\n");
137 }
138
139 static int *
140 smb2_get_credits_field(struct TCP_Server_Info *server, const int optype)
141 {
142         switch (optype) {
143         case CIFS_ECHO_OP:
144                 return &server->echo_credits;
145         case CIFS_OBREAK_OP:
146                 return &server->oplock_credits;
147         default:
148                 return &server->credits;
149         }
150 }
151
152 static unsigned int
153 smb2_get_credits(struct mid_q_entry *mid)
154 {
155         return mid->credits_received;
156 }
157
158 static int
159 smb2_wait_mtu_credits(struct TCP_Server_Info *server, unsigned int size,
160                       unsigned int *num, struct cifs_credits *credits)
161 {
162         int rc = 0;
163         unsigned int scredits;
164
165         spin_lock(&server->req_lock);
166         while (1) {
167                 if (server->credits <= 0) {
168                         spin_unlock(&server->req_lock);
169                         cifs_num_waiters_inc(server);
170                         rc = wait_event_killable(server->request_q,
171                                 has_credits(server, &server->credits, 1));
172                         cifs_num_waiters_dec(server);
173                         if (rc)
174                                 return rc;
175                         spin_lock(&server->req_lock);
176                 } else {
177                         if (server->tcpStatus == CifsExiting) {
178                                 spin_unlock(&server->req_lock);
179                                 return -ENOENT;
180                         }
181
182                         scredits = server->credits;
183                         /* can deadlock with reopen */
184                         if (scredits <= 8) {
185                                 *num = SMB2_MAX_BUFFER_SIZE;
186                                 credits->value = 0;
187                                 credits->instance = 0;
188                                 break;
189                         }
190
191                         /* leave some credits for reopen and other ops */
192                         scredits -= 8;
193                         *num = min_t(unsigned int, size,
194                                      scredits * SMB2_MAX_BUFFER_SIZE);
195
196                         credits->value =
197                                 DIV_ROUND_UP(*num, SMB2_MAX_BUFFER_SIZE);
198                         credits->instance = server->reconnect_instance;
199                         server->credits -= credits->value;
200                         server->in_flight++;
201                         if (server->in_flight > server->max_in_flight)
202                                 server->max_in_flight = server->in_flight;
203                         break;
204                 }
205         }
206         spin_unlock(&server->req_lock);
207         return rc;
208 }
209
210 static int
211 smb2_adjust_credits(struct TCP_Server_Info *server,
212                     struct cifs_credits *credits,
213                     const unsigned int payload_size)
214 {
215         int new_val = DIV_ROUND_UP(payload_size, SMB2_MAX_BUFFER_SIZE);
216
217         if (!credits->value || credits->value == new_val)
218                 return 0;
219
220         if (credits->value < new_val) {
221                 WARN_ONCE(1, "request has less credits (%d) than required (%d)",
222                           credits->value, new_val);
223                 return -ENOTSUPP;
224         }
225
226         spin_lock(&server->req_lock);
227
228         if (server->reconnect_instance != credits->instance) {
229                 spin_unlock(&server->req_lock);
230                 cifs_server_dbg(VFS, "trying to return %d credits to old session\n",
231                          credits->value - new_val);
232                 return -EAGAIN;
233         }
234
235         server->credits += credits->value - new_val;
236         spin_unlock(&server->req_lock);
237         wake_up(&server->request_q);
238         credits->value = new_val;
239         return 0;
240 }
241
242 static __u64
243 smb2_get_next_mid(struct TCP_Server_Info *server)
244 {
245         __u64 mid;
246         /* for SMB2 we need the current value */
247         spin_lock(&GlobalMid_Lock);
248         mid = server->CurrentMid++;
249         spin_unlock(&GlobalMid_Lock);
250         return mid;
251 }
252
253 static void
254 smb2_revert_current_mid(struct TCP_Server_Info *server, const unsigned int val)
255 {
256         spin_lock(&GlobalMid_Lock);
257         if (server->CurrentMid >= val)
258                 server->CurrentMid -= val;
259         spin_unlock(&GlobalMid_Lock);
260 }
261
262 static struct mid_q_entry *
263 smb2_find_mid(struct TCP_Server_Info *server, char *buf)
264 {
265         struct mid_q_entry *mid;
266         struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)buf;
267         __u64 wire_mid = le64_to_cpu(shdr->MessageId);
268
269         if (shdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM) {
270                 cifs_server_dbg(VFS, "Encrypted frame parsing not supported yet\n");
271                 return NULL;
272         }
273
274         spin_lock(&GlobalMid_Lock);
275         list_for_each_entry(mid, &server->pending_mid_q, qhead) {
276                 if ((mid->mid == wire_mid) &&
277                     (mid->mid_state == MID_REQUEST_SUBMITTED) &&
278                     (mid->command == shdr->Command)) {
279                         kref_get(&mid->refcount);
280                         spin_unlock(&GlobalMid_Lock);
281                         return mid;
282                 }
283         }
284         spin_unlock(&GlobalMid_Lock);
285         return NULL;
286 }
287
288 static void
289 smb2_dump_detail(void *buf, struct TCP_Server_Info *server)
290 {
291 #ifdef CONFIG_CIFS_DEBUG2
292         struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)buf;
293
294         cifs_server_dbg(VFS, "Cmd: %d Err: 0x%x Flags: 0x%x Mid: %llu Pid: %d\n",
295                  shdr->Command, shdr->Status, shdr->Flags, shdr->MessageId,
296                  shdr->ProcessId);
297         cifs_server_dbg(VFS, "smb buf %p len %u\n", buf,
298                  server->ops->calc_smb_size(buf, server));
299 #endif
300 }
301
302 static bool
303 smb2_need_neg(struct TCP_Server_Info *server)
304 {
305         return server->max_read == 0;
306 }
307
308 static int
309 smb2_negotiate(const unsigned int xid, struct cifs_ses *ses)
310 {
311         int rc;
312
313         cifs_ses_server(ses)->CurrentMid = 0;
314         rc = SMB2_negotiate(xid, ses);
315         /* BB we probably don't need to retry with modern servers */
316         if (rc == -EAGAIN)
317                 rc = -EHOSTDOWN;
318         return rc;
319 }
320
321 static unsigned int
322 smb2_negotiate_wsize(struct cifs_tcon *tcon, struct smb_vol *volume_info)
323 {
324         struct TCP_Server_Info *server = tcon->ses->server;
325         unsigned int wsize;
326
327         /* start with specified wsize, or default */
328         wsize = volume_info->wsize ? volume_info->wsize : CIFS_DEFAULT_IOSIZE;
329         wsize = min_t(unsigned int, wsize, server->max_write);
330 #ifdef CONFIG_CIFS_SMB_DIRECT
331         if (server->rdma) {
332                 if (server->sign)
333                         wsize = min_t(unsigned int,
334                                 wsize, server->smbd_conn->max_fragmented_send_size);
335                 else
336                         wsize = min_t(unsigned int,
337                                 wsize, server->smbd_conn->max_readwrite_size);
338         }
339 #endif
340         if (!(server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
341                 wsize = min_t(unsigned int, wsize, SMB2_MAX_BUFFER_SIZE);
342
343         return wsize;
344 }
345
346 static unsigned int
347 smb3_negotiate_wsize(struct cifs_tcon *tcon, struct smb_vol *volume_info)
348 {
349         struct TCP_Server_Info *server = tcon->ses->server;
350         unsigned int wsize;
351
352         /* start with specified wsize, or default */
353         wsize = volume_info->wsize ? volume_info->wsize : SMB3_DEFAULT_IOSIZE;
354         wsize = min_t(unsigned int, wsize, server->max_write);
355 #ifdef CONFIG_CIFS_SMB_DIRECT
356         if (server->rdma) {
357                 if (server->sign)
358                         wsize = min_t(unsigned int,
359                                 wsize, server->smbd_conn->max_fragmented_send_size);
360                 else
361                         wsize = min_t(unsigned int,
362                                 wsize, server->smbd_conn->max_readwrite_size);
363         }
364 #endif
365         if (!(server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
366                 wsize = min_t(unsigned int, wsize, SMB2_MAX_BUFFER_SIZE);
367
368         return wsize;
369 }
370
371 static unsigned int
372 smb2_negotiate_rsize(struct cifs_tcon *tcon, struct smb_vol *volume_info)
373 {
374         struct TCP_Server_Info *server = tcon->ses->server;
375         unsigned int rsize;
376
377         /* start with specified rsize, or default */
378         rsize = volume_info->rsize ? volume_info->rsize : CIFS_DEFAULT_IOSIZE;
379         rsize = min_t(unsigned int, rsize, server->max_read);
380 #ifdef CONFIG_CIFS_SMB_DIRECT
381         if (server->rdma) {
382                 if (server->sign)
383                         rsize = min_t(unsigned int,
384                                 rsize, server->smbd_conn->max_fragmented_recv_size);
385                 else
386                         rsize = min_t(unsigned int,
387                                 rsize, server->smbd_conn->max_readwrite_size);
388         }
389 #endif
390
391         if (!(server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
392                 rsize = min_t(unsigned int, rsize, SMB2_MAX_BUFFER_SIZE);
393
394         return rsize;
395 }
396
397 static unsigned int
398 smb3_negotiate_rsize(struct cifs_tcon *tcon, struct smb_vol *volume_info)
399 {
400         struct TCP_Server_Info *server = tcon->ses->server;
401         unsigned int rsize;
402
403         /* start with specified rsize, or default */
404         rsize = volume_info->rsize ? volume_info->rsize : SMB3_DEFAULT_IOSIZE;
405         rsize = min_t(unsigned int, rsize, server->max_read);
406 #ifdef CONFIG_CIFS_SMB_DIRECT
407         if (server->rdma) {
408                 if (server->sign)
409                         rsize = min_t(unsigned int,
410                                 rsize, server->smbd_conn->max_fragmented_recv_size);
411                 else
412                         rsize = min_t(unsigned int,
413                                 rsize, server->smbd_conn->max_readwrite_size);
414         }
415 #endif
416
417         if (!(server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
418                 rsize = min_t(unsigned int, rsize, SMB2_MAX_BUFFER_SIZE);
419
420         return rsize;
421 }
422
423 static int
424 parse_server_interfaces(struct network_interface_info_ioctl_rsp *buf,
425                         size_t buf_len,
426                         struct cifs_server_iface **iface_list,
427                         size_t *iface_count)
428 {
429         struct network_interface_info_ioctl_rsp *p;
430         struct sockaddr_in *addr4;
431         struct sockaddr_in6 *addr6;
432         struct iface_info_ipv4 *p4;
433         struct iface_info_ipv6 *p6;
434         struct cifs_server_iface *info;
435         ssize_t bytes_left;
436         size_t next = 0;
437         int nb_iface = 0;
438         int rc = 0;
439
440         *iface_list = NULL;
441         *iface_count = 0;
442
443         /*
444          * Fist pass: count and sanity check
445          */
446
447         bytes_left = buf_len;
448         p = buf;
449         while (bytes_left >= sizeof(*p)) {
450                 nb_iface++;
451                 next = le32_to_cpu(p->Next);
452                 if (!next) {
453                         bytes_left -= sizeof(*p);
454                         break;
455                 }
456                 p = (struct network_interface_info_ioctl_rsp *)((u8 *)p+next);
457                 bytes_left -= next;
458         }
459
460         if (!nb_iface) {
461                 cifs_dbg(VFS, "%s: malformed interface info\n", __func__);
462                 rc = -EINVAL;
463                 goto out;
464         }
465
466         if (bytes_left || p->Next)
467                 cifs_dbg(VFS, "%s: incomplete interface info\n", __func__);
468
469
470         /*
471          * Second pass: extract info to internal structure
472          */
473
474         *iface_list = kcalloc(nb_iface, sizeof(**iface_list), GFP_KERNEL);
475         if (!*iface_list) {
476                 rc = -ENOMEM;
477                 goto out;
478         }
479
480         info = *iface_list;
481         bytes_left = buf_len;
482         p = buf;
483         while (bytes_left >= sizeof(*p)) {
484                 info->speed = le64_to_cpu(p->LinkSpeed);
485                 info->rdma_capable = le32_to_cpu(p->Capability & RDMA_CAPABLE);
486                 info->rss_capable = le32_to_cpu(p->Capability & RSS_CAPABLE);
487
488                 cifs_dbg(FYI, "%s: adding iface %zu\n", __func__, *iface_count);
489                 cifs_dbg(FYI, "%s: speed %zu bps\n", __func__, info->speed);
490                 cifs_dbg(FYI, "%s: capabilities 0x%08x\n", __func__,
491                          le32_to_cpu(p->Capability));
492
493                 switch (p->Family) {
494                 /*
495                  * The kernel and wire socket structures have the same
496                  * layout and use network byte order but make the
497                  * conversion explicit in case either one changes.
498                  */
499                 case INTERNETWORK:
500                         addr4 = (struct sockaddr_in *)&info->sockaddr;
501                         p4 = (struct iface_info_ipv4 *)p->Buffer;
502                         addr4->sin_family = AF_INET;
503                         memcpy(&addr4->sin_addr, &p4->IPv4Address, 4);
504
505                         /* [MS-SMB2] 2.2.32.5.1.1 Clients MUST ignore these */
506                         addr4->sin_port = cpu_to_be16(CIFS_PORT);
507
508                         cifs_dbg(FYI, "%s: ipv4 %pI4\n", __func__,
509                                  &addr4->sin_addr);
510                         break;
511                 case INTERNETWORKV6:
512                         addr6 = (struct sockaddr_in6 *)&info->sockaddr;
513                         p6 = (struct iface_info_ipv6 *)p->Buffer;
514                         addr6->sin6_family = AF_INET6;
515                         memcpy(&addr6->sin6_addr, &p6->IPv6Address, 16);
516
517                         /* [MS-SMB2] 2.2.32.5.1.2 Clients MUST ignore these */
518                         addr6->sin6_flowinfo = 0;
519                         addr6->sin6_scope_id = 0;
520                         addr6->sin6_port = cpu_to_be16(CIFS_PORT);
521
522                         cifs_dbg(FYI, "%s: ipv6 %pI6\n", __func__,
523                                  &addr6->sin6_addr);
524                         break;
525                 default:
526                         cifs_dbg(VFS,
527                                  "%s: skipping unsupported socket family\n",
528                                  __func__);
529                         goto next_iface;
530                 }
531
532                 (*iface_count)++;
533                 info++;
534 next_iface:
535                 next = le32_to_cpu(p->Next);
536                 if (!next)
537                         break;
538                 p = (struct network_interface_info_ioctl_rsp *)((u8 *)p+next);
539                 bytes_left -= next;
540         }
541
542         if (!*iface_count) {
543                 rc = -EINVAL;
544                 goto out;
545         }
546
547 out:
548         if (rc) {
549                 kfree(*iface_list);
550                 *iface_count = 0;
551                 *iface_list = NULL;
552         }
553         return rc;
554 }
555
556 static int compare_iface(const void *ia, const void *ib)
557 {
558         const struct cifs_server_iface *a = (struct cifs_server_iface *)ia;
559         const struct cifs_server_iface *b = (struct cifs_server_iface *)ib;
560
561         return a->speed == b->speed ? 0 : (a->speed > b->speed ? -1 : 1);
562 }
563
564 static int
565 SMB3_request_interfaces(const unsigned int xid, struct cifs_tcon *tcon)
566 {
567         int rc;
568         unsigned int ret_data_len = 0;
569         struct network_interface_info_ioctl_rsp *out_buf = NULL;
570         struct cifs_server_iface *iface_list;
571         size_t iface_count;
572         struct cifs_ses *ses = tcon->ses;
573
574         rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
575                         FSCTL_QUERY_NETWORK_INTERFACE_INFO, true /* is_fsctl */,
576                         NULL /* no data input */, 0 /* no data input */,
577                         CIFSMaxBufSize, (char **)&out_buf, &ret_data_len);
578         if (rc == -EOPNOTSUPP) {
579                 cifs_dbg(FYI,
580                          "server does not support query network interfaces\n");
581                 goto out;
582         } else if (rc != 0) {
583                 cifs_tcon_dbg(VFS, "error %d on ioctl to get interface list\n", rc);
584                 goto out;
585         }
586
587         rc = parse_server_interfaces(out_buf, ret_data_len,
588                                      &iface_list, &iface_count);
589         if (rc)
590                 goto out;
591
592         /* sort interfaces from fastest to slowest */
593         sort(iface_list, iface_count, sizeof(*iface_list), compare_iface, NULL);
594
595         spin_lock(&ses->iface_lock);
596         kfree(ses->iface_list);
597         ses->iface_list = iface_list;
598         ses->iface_count = iface_count;
599         ses->iface_last_update = jiffies;
600         spin_unlock(&ses->iface_lock);
601
602 out:
603         kfree(out_buf);
604         return rc;
605 }
606
607 static void
608 smb2_close_cached_fid(struct kref *ref)
609 {
610         struct cached_fid *cfid = container_of(ref, struct cached_fid,
611                                                refcount);
612
613         if (cfid->is_valid) {
614                 cifs_dbg(FYI, "clear cached root file handle\n");
615                 SMB2_close(0, cfid->tcon, cfid->fid->persistent_fid,
616                            cfid->fid->volatile_fid);
617                 cfid->is_valid = false;
618                 cfid->file_all_info_is_valid = false;
619                 cfid->has_lease = false;
620         }
621 }
622
623 void close_shroot(struct cached_fid *cfid)
624 {
625         mutex_lock(&cfid->fid_mutex);
626         kref_put(&cfid->refcount, smb2_close_cached_fid);
627         mutex_unlock(&cfid->fid_mutex);
628 }
629
630 void close_shroot_lease_locked(struct cached_fid *cfid)
631 {
632         if (cfid->has_lease) {
633                 cfid->has_lease = false;
634                 kref_put(&cfid->refcount, smb2_close_cached_fid);
635         }
636 }
637
638 void close_shroot_lease(struct cached_fid *cfid)
639 {
640         mutex_lock(&cfid->fid_mutex);
641         close_shroot_lease_locked(cfid);
642         mutex_unlock(&cfid->fid_mutex);
643 }
644
645 void
646 smb2_cached_lease_break(struct work_struct *work)
647 {
648         struct cached_fid *cfid = container_of(work,
649                                 struct cached_fid, lease_break);
650
651         close_shroot_lease(cfid);
652 }
653
654 /*
655  * Open the directory at the root of a share
656  */
657 int open_shroot(unsigned int xid, struct cifs_tcon *tcon, struct cifs_fid *pfid)
658 {
659         struct cifs_ses *ses = tcon->ses;
660         struct TCP_Server_Info *server = ses->server;
661         struct cifs_open_parms oparms;
662         struct smb2_create_rsp *o_rsp = NULL;
663         struct smb2_query_info_rsp *qi_rsp = NULL;
664         int resp_buftype[2];
665         struct smb_rqst rqst[2];
666         struct kvec rsp_iov[2];
667         struct kvec open_iov[SMB2_CREATE_IOV_SIZE];
668         struct kvec qi_iov[1];
669         int rc, flags = 0;
670         __le16 utf16_path = 0; /* Null - since an open of top of share */
671         u8 oplock = SMB2_OPLOCK_LEVEL_II;
672
673         mutex_lock(&tcon->crfid.fid_mutex);
674         if (tcon->crfid.is_valid) {
675                 cifs_dbg(FYI, "found a cached root file handle\n");
676                 memcpy(pfid, tcon->crfid.fid, sizeof(struct cifs_fid));
677                 kref_get(&tcon->crfid.refcount);
678                 mutex_unlock(&tcon->crfid.fid_mutex);
679                 return 0;
680         }
681
682         /*
683          * We do not hold the lock for the open because in case
684          * SMB2_open needs to reconnect, it will end up calling
685          * cifs_mark_open_files_invalid() which takes the lock again
686          * thus causing a deadlock
687          */
688
689         mutex_unlock(&tcon->crfid.fid_mutex);
690
691         if (smb3_encryption_required(tcon))
692                 flags |= CIFS_TRANSFORM_REQ;
693
694         memset(rqst, 0, sizeof(rqst));
695         resp_buftype[0] = resp_buftype[1] = CIFS_NO_BUFFER;
696         memset(rsp_iov, 0, sizeof(rsp_iov));
697
698         /* Open */
699         memset(&open_iov, 0, sizeof(open_iov));
700         rqst[0].rq_iov = open_iov;
701         rqst[0].rq_nvec = SMB2_CREATE_IOV_SIZE;
702
703         oparms.tcon = tcon;
704         oparms.create_options = 0;
705         oparms.desired_access = FILE_READ_ATTRIBUTES;
706         oparms.disposition = FILE_OPEN;
707         oparms.fid = pfid;
708         oparms.reconnect = false;
709
710         rc = SMB2_open_init(tcon, &rqst[0], &oplock, &oparms, &utf16_path);
711         if (rc)
712                 goto oshr_free;
713         smb2_set_next_command(tcon, &rqst[0]);
714
715         memset(&qi_iov, 0, sizeof(qi_iov));
716         rqst[1].rq_iov = qi_iov;
717         rqst[1].rq_nvec = 1;
718
719         rc = SMB2_query_info_init(tcon, &rqst[1], COMPOUND_FID,
720                                   COMPOUND_FID, FILE_ALL_INFORMATION,
721                                   SMB2_O_INFO_FILE, 0,
722                                   sizeof(struct smb2_file_all_info) +
723                                   PATH_MAX * 2, 0, NULL);
724         if (rc)
725                 goto oshr_free;
726
727         smb2_set_related(&rqst[1]);
728
729         rc = compound_send_recv(xid, ses, flags, 2, rqst,
730                                 resp_buftype, rsp_iov);
731         mutex_lock(&tcon->crfid.fid_mutex);
732
733         /*
734          * Now we need to check again as the cached root might have
735          * been successfully re-opened from a concurrent process
736          */
737
738         if (tcon->crfid.is_valid) {
739                 /* work was already done */
740
741                 /* stash fids for close() later */
742                 struct cifs_fid fid = {
743                         .persistent_fid = pfid->persistent_fid,
744                         .volatile_fid = pfid->volatile_fid,
745                 };
746
747                 /*
748                  * caller expects this func to set pfid to a valid
749                  * cached root, so we copy the existing one and get a
750                  * reference.
751                  */
752                 memcpy(pfid, tcon->crfid.fid, sizeof(*pfid));
753                 kref_get(&tcon->crfid.refcount);
754
755                 mutex_unlock(&tcon->crfid.fid_mutex);
756
757                 if (rc == 0) {
758                         /* close extra handle outside of crit sec */
759                         SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
760                 }
761                 goto oshr_free;
762         }
763
764         /* Cached root is still invalid, continue normaly */
765
766         if (rc) {
767                 if (rc == -EREMCHG) {
768                         tcon->need_reconnect = true;
769                         printk_once(KERN_WARNING "server share %s deleted\n",
770                                     tcon->treeName);
771                 }
772                 goto oshr_exit;
773         }
774
775         atomic_inc(&tcon->num_remote_opens);
776
777         o_rsp = (struct smb2_create_rsp *)rsp_iov[0].iov_base;
778         oparms.fid->persistent_fid = o_rsp->PersistentFileId;
779         oparms.fid->volatile_fid = o_rsp->VolatileFileId;
780 #ifdef CONFIG_CIFS_DEBUG2
781         oparms.fid->mid = le64_to_cpu(o_rsp->sync_hdr.MessageId);
782 #endif /* CIFS_DEBUG2 */
783
784         memcpy(tcon->crfid.fid, pfid, sizeof(struct cifs_fid));
785         tcon->crfid.tcon = tcon;
786         tcon->crfid.is_valid = true;
787         kref_init(&tcon->crfid.refcount);
788
789         /* BB TBD check to see if oplock level check can be removed below */
790         if (o_rsp->OplockLevel == SMB2_OPLOCK_LEVEL_LEASE) {
791                 kref_get(&tcon->crfid.refcount);
792                 tcon->crfid.has_lease = true;
793                 smb2_parse_contexts(server, o_rsp,
794                                 &oparms.fid->epoch,
795                                 oparms.fid->lease_key, &oplock, NULL);
796         } else
797                 goto oshr_exit;
798
799         qi_rsp = (struct smb2_query_info_rsp *)rsp_iov[1].iov_base;
800         if (le32_to_cpu(qi_rsp->OutputBufferLength) < sizeof(struct smb2_file_all_info))
801                 goto oshr_exit;
802         if (!smb2_validate_and_copy_iov(
803                                 le16_to_cpu(qi_rsp->OutputBufferOffset),
804                                 sizeof(struct smb2_file_all_info),
805                                 &rsp_iov[1], sizeof(struct smb2_file_all_info),
806                                 (char *)&tcon->crfid.file_all_info))
807                 tcon->crfid.file_all_info_is_valid = 1;
808
809 oshr_exit:
810         mutex_unlock(&tcon->crfid.fid_mutex);
811 oshr_free:
812         SMB2_open_free(&rqst[0]);
813         SMB2_query_info_free(&rqst[1]);
814         free_rsp_buf(resp_buftype[0], rsp_iov[0].iov_base);
815         free_rsp_buf(resp_buftype[1], rsp_iov[1].iov_base);
816         return rc;
817 }
818
819 static void
820 smb3_qfs_tcon(const unsigned int xid, struct cifs_tcon *tcon)
821 {
822         int rc;
823         __le16 srch_path = 0; /* Null - open root of share */
824         u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
825         struct cifs_open_parms oparms;
826         struct cifs_fid fid;
827         bool no_cached_open = tcon->nohandlecache;
828
829         oparms.tcon = tcon;
830         oparms.desired_access = FILE_READ_ATTRIBUTES;
831         oparms.disposition = FILE_OPEN;
832         oparms.create_options = 0;
833         oparms.fid = &fid;
834         oparms.reconnect = false;
835
836         if (no_cached_open)
837                 rc = SMB2_open(xid, &oparms, &srch_path, &oplock, NULL, NULL,
838                                NULL);
839         else
840                 rc = open_shroot(xid, tcon, &fid);
841
842         if (rc)
843                 return;
844
845         SMB3_request_interfaces(xid, tcon);
846
847         SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
848                         FS_ATTRIBUTE_INFORMATION);
849         SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
850                         FS_DEVICE_INFORMATION);
851         SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
852                         FS_VOLUME_INFORMATION);
853         SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
854                         FS_SECTOR_SIZE_INFORMATION); /* SMB3 specific */
855         if (no_cached_open)
856                 SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
857         else
858                 close_shroot(&tcon->crfid);
859 }
860
861 static void
862 smb2_qfs_tcon(const unsigned int xid, struct cifs_tcon *tcon)
863 {
864         int rc;
865         __le16 srch_path = 0; /* Null - open root of share */
866         u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
867         struct cifs_open_parms oparms;
868         struct cifs_fid fid;
869
870         oparms.tcon = tcon;
871         oparms.desired_access = FILE_READ_ATTRIBUTES;
872         oparms.disposition = FILE_OPEN;
873         oparms.create_options = 0;
874         oparms.fid = &fid;
875         oparms.reconnect = false;
876
877         rc = SMB2_open(xid, &oparms, &srch_path, &oplock, NULL, NULL, NULL);
878         if (rc)
879                 return;
880
881         SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
882                         FS_ATTRIBUTE_INFORMATION);
883         SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
884                         FS_DEVICE_INFORMATION);
885         SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
886 }
887
888 static int
889 smb2_is_path_accessible(const unsigned int xid, struct cifs_tcon *tcon,
890                         struct cifs_sb_info *cifs_sb, const char *full_path)
891 {
892         int rc;
893         __le16 *utf16_path;
894         __u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
895         struct cifs_open_parms oparms;
896         struct cifs_fid fid;
897
898         if ((*full_path == 0) && tcon->crfid.is_valid)
899                 return 0;
900
901         utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
902         if (!utf16_path)
903                 return -ENOMEM;
904
905         oparms.tcon = tcon;
906         oparms.desired_access = FILE_READ_ATTRIBUTES;
907         oparms.disposition = FILE_OPEN;
908         if (backup_cred(cifs_sb))
909                 oparms.create_options = CREATE_OPEN_BACKUP_INTENT;
910         else
911                 oparms.create_options = 0;
912         oparms.fid = &fid;
913         oparms.reconnect = false;
914
915         rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, NULL, NULL);
916         if (rc) {
917                 kfree(utf16_path);
918                 return rc;
919         }
920
921         rc = SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
922         kfree(utf16_path);
923         return rc;
924 }
925
926 static int
927 smb2_get_srv_inum(const unsigned int xid, struct cifs_tcon *tcon,
928                   struct cifs_sb_info *cifs_sb, const char *full_path,
929                   u64 *uniqueid, FILE_ALL_INFO *data)
930 {
931         *uniqueid = le64_to_cpu(data->IndexNumber);
932         return 0;
933 }
934
935 static int
936 smb2_query_file_info(const unsigned int xid, struct cifs_tcon *tcon,
937                      struct cifs_fid *fid, FILE_ALL_INFO *data)
938 {
939         int rc;
940         struct smb2_file_all_info *smb2_data;
941
942         smb2_data = kzalloc(sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
943                             GFP_KERNEL);
944         if (smb2_data == NULL)
945                 return -ENOMEM;
946
947         rc = SMB2_query_info(xid, tcon, fid->persistent_fid, fid->volatile_fid,
948                              smb2_data);
949         if (!rc)
950                 move_smb2_info_to_cifs(data, smb2_data);
951         kfree(smb2_data);
952         return rc;
953 }
954
955 #ifdef CONFIG_CIFS_XATTR
956 static ssize_t
957 move_smb2_ea_to_cifs(char *dst, size_t dst_size,
958                      struct smb2_file_full_ea_info *src, size_t src_size,
959                      const unsigned char *ea_name)
960 {
961         int rc = 0;
962         unsigned int ea_name_len = ea_name ? strlen(ea_name) : 0;
963         char *name, *value;
964         size_t buf_size = dst_size;
965         size_t name_len, value_len, user_name_len;
966
967         while (src_size > 0) {
968                 name = &src->ea_data[0];
969                 name_len = (size_t)src->ea_name_length;
970                 value = &src->ea_data[src->ea_name_length + 1];
971                 value_len = (size_t)le16_to_cpu(src->ea_value_length);
972
973                 if (name_len == 0)
974                         break;
975
976                 if (src_size < 8 + name_len + 1 + value_len) {
977                         cifs_dbg(FYI, "EA entry goes beyond length of list\n");
978                         rc = -EIO;
979                         goto out;
980                 }
981
982                 if (ea_name) {
983                         if (ea_name_len == name_len &&
984                             memcmp(ea_name, name, name_len) == 0) {
985                                 rc = value_len;
986                                 if (dst_size == 0)
987                                         goto out;
988                                 if (dst_size < value_len) {
989                                         rc = -ERANGE;
990                                         goto out;
991                                 }
992                                 memcpy(dst, value, value_len);
993                                 goto out;
994                         }
995                 } else {
996                         /* 'user.' plus a terminating null */
997                         user_name_len = 5 + 1 + name_len;
998
999                         if (buf_size == 0) {
1000                                 /* skip copy - calc size only */
1001                                 rc += user_name_len;
1002                         } else if (dst_size >= user_name_len) {
1003                                 dst_size -= user_name_len;
1004                                 memcpy(dst, "user.", 5);
1005                                 dst += 5;
1006                                 memcpy(dst, src->ea_data, name_len);
1007                                 dst += name_len;
1008                                 *dst = 0;
1009                                 ++dst;
1010                                 rc += user_name_len;
1011                         } else {
1012                                 /* stop before overrun buffer */
1013                                 rc = -ERANGE;
1014                                 break;
1015                         }
1016                 }
1017
1018                 if (!src->next_entry_offset)
1019                         break;
1020
1021                 if (src_size < le32_to_cpu(src->next_entry_offset)) {
1022                         /* stop before overrun buffer */
1023                         rc = -ERANGE;
1024                         break;
1025                 }
1026                 src_size -= le32_to_cpu(src->next_entry_offset);
1027                 src = (void *)((char *)src +
1028                                le32_to_cpu(src->next_entry_offset));
1029         }
1030
1031         /* didn't find the named attribute */
1032         if (ea_name)
1033                 rc = -ENODATA;
1034
1035 out:
1036         return (ssize_t)rc;
1037 }
1038
1039 static ssize_t
1040 smb2_query_eas(const unsigned int xid, struct cifs_tcon *tcon,
1041                const unsigned char *path, const unsigned char *ea_name,
1042                char *ea_data, size_t buf_size,
1043                struct cifs_sb_info *cifs_sb)
1044 {
1045         int rc;
1046         __le16 *utf16_path;
1047         struct kvec rsp_iov = {NULL, 0};
1048         int buftype = CIFS_NO_BUFFER;
1049         struct smb2_query_info_rsp *rsp;
1050         struct smb2_file_full_ea_info *info = NULL;
1051
1052         utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
1053         if (!utf16_path)
1054                 return -ENOMEM;
1055
1056         rc = smb2_query_info_compound(xid, tcon, utf16_path,
1057                                       FILE_READ_EA,
1058                                       FILE_FULL_EA_INFORMATION,
1059                                       SMB2_O_INFO_FILE,
1060                                       CIFSMaxBufSize -
1061                                       MAX_SMB2_CREATE_RESPONSE_SIZE -
1062                                       MAX_SMB2_CLOSE_RESPONSE_SIZE,
1063                                       &rsp_iov, &buftype, cifs_sb);
1064         if (rc) {
1065                 /*
1066                  * If ea_name is NULL (listxattr) and there are no EAs,
1067                  * return 0 as it's not an error. Otherwise, the specified
1068                  * ea_name was not found.
1069                  */
1070                 if (!ea_name && rc == -ENODATA)
1071                         rc = 0;
1072                 goto qeas_exit;
1073         }
1074
1075         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
1076         rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
1077                                le32_to_cpu(rsp->OutputBufferLength),
1078                                &rsp_iov,
1079                                sizeof(struct smb2_file_full_ea_info));
1080         if (rc)
1081                 goto qeas_exit;
1082
1083         info = (struct smb2_file_full_ea_info *)(
1084                         le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
1085         rc = move_smb2_ea_to_cifs(ea_data, buf_size, info,
1086                         le32_to_cpu(rsp->OutputBufferLength), ea_name);
1087
1088  qeas_exit:
1089         kfree(utf16_path);
1090         free_rsp_buf(buftype, rsp_iov.iov_base);
1091         return rc;
1092 }
1093
1094
1095 static int
1096 smb2_set_ea(const unsigned int xid, struct cifs_tcon *tcon,
1097             const char *path, const char *ea_name, const void *ea_value,
1098             const __u16 ea_value_len, const struct nls_table *nls_codepage,
1099             struct cifs_sb_info *cifs_sb)
1100 {
1101         struct cifs_ses *ses = tcon->ses;
1102         __le16 *utf16_path = NULL;
1103         int ea_name_len = strlen(ea_name);
1104         int flags = 0;
1105         int len;
1106         struct smb_rqst rqst[3];
1107         int resp_buftype[3];
1108         struct kvec rsp_iov[3];
1109         struct kvec open_iov[SMB2_CREATE_IOV_SIZE];
1110         struct cifs_open_parms oparms;
1111         __u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
1112         struct cifs_fid fid;
1113         struct kvec si_iov[SMB2_SET_INFO_IOV_SIZE];
1114         unsigned int size[1];
1115         void *data[1];
1116         struct smb2_file_full_ea_info *ea = NULL;
1117         struct kvec close_iov[1];
1118         int rc;
1119
1120         if (smb3_encryption_required(tcon))
1121                 flags |= CIFS_TRANSFORM_REQ;
1122
1123         if (ea_name_len > 255)
1124                 return -EINVAL;
1125
1126         utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
1127         if (!utf16_path)
1128                 return -ENOMEM;
1129
1130         memset(rqst, 0, sizeof(rqst));
1131         resp_buftype[0] = resp_buftype[1] = resp_buftype[2] = CIFS_NO_BUFFER;
1132         memset(rsp_iov, 0, sizeof(rsp_iov));
1133
1134         if (ses->server->ops->query_all_EAs) {
1135                 if (!ea_value) {
1136                         rc = ses->server->ops->query_all_EAs(xid, tcon, path,
1137                                                              ea_name, NULL, 0,
1138                                                              cifs_sb);
1139                         if (rc == -ENODATA)
1140                                 goto sea_exit;
1141                 }
1142         }
1143
1144         /* Open */
1145         memset(&open_iov, 0, sizeof(open_iov));
1146         rqst[0].rq_iov = open_iov;
1147         rqst[0].rq_nvec = SMB2_CREATE_IOV_SIZE;
1148
1149         memset(&oparms, 0, sizeof(oparms));
1150         oparms.tcon = tcon;
1151         oparms.desired_access = FILE_WRITE_EA;
1152         oparms.disposition = FILE_OPEN;
1153         if (backup_cred(cifs_sb))
1154                 oparms.create_options = CREATE_OPEN_BACKUP_INTENT;
1155         else
1156                 oparms.create_options = 0;
1157         oparms.fid = &fid;
1158         oparms.reconnect = false;
1159
1160         rc = SMB2_open_init(tcon, &rqst[0], &oplock, &oparms, utf16_path);
1161         if (rc)
1162                 goto sea_exit;
1163         smb2_set_next_command(tcon, &rqst[0]);
1164
1165
1166         /* Set Info */
1167         memset(&si_iov, 0, sizeof(si_iov));
1168         rqst[1].rq_iov = si_iov;
1169         rqst[1].rq_nvec = 1;
1170
1171         len = sizeof(ea) + ea_name_len + ea_value_len + 1;
1172         ea = kzalloc(len, GFP_KERNEL);
1173         if (ea == NULL) {
1174                 rc = -ENOMEM;
1175                 goto sea_exit;
1176         }
1177
1178         ea->ea_name_length = ea_name_len;
1179         ea->ea_value_length = cpu_to_le16(ea_value_len);
1180         memcpy(ea->ea_data, ea_name, ea_name_len + 1);
1181         memcpy(ea->ea_data + ea_name_len + 1, ea_value, ea_value_len);
1182
1183         size[0] = len;
1184         data[0] = ea;
1185
1186         rc = SMB2_set_info_init(tcon, &rqst[1], COMPOUND_FID,
1187                                 COMPOUND_FID, current->tgid,
1188                                 FILE_FULL_EA_INFORMATION,
1189                                 SMB2_O_INFO_FILE, 0, data, size);
1190         smb2_set_next_command(tcon, &rqst[1]);
1191         smb2_set_related(&rqst[1]);
1192
1193
1194         /* Close */
1195         memset(&close_iov, 0, sizeof(close_iov));
1196         rqst[2].rq_iov = close_iov;
1197         rqst[2].rq_nvec = 1;
1198         rc = SMB2_close_init(tcon, &rqst[2], COMPOUND_FID, COMPOUND_FID, false);
1199         smb2_set_related(&rqst[2]);
1200
1201         rc = compound_send_recv(xid, ses, flags, 3, rqst,
1202                                 resp_buftype, rsp_iov);
1203         /* no need to bump num_remote_opens because handle immediately closed */
1204
1205  sea_exit:
1206         kfree(ea);
1207         kfree(utf16_path);
1208         SMB2_open_free(&rqst[0]);
1209         SMB2_set_info_free(&rqst[1]);
1210         SMB2_close_free(&rqst[2]);
1211         free_rsp_buf(resp_buftype[0], rsp_iov[0].iov_base);
1212         free_rsp_buf(resp_buftype[1], rsp_iov[1].iov_base);
1213         free_rsp_buf(resp_buftype[2], rsp_iov[2].iov_base);
1214         return rc;
1215 }
1216 #endif
1217
1218 static bool
1219 smb2_can_echo(struct TCP_Server_Info *server)
1220 {
1221         return server->echoes;
1222 }
1223
1224 static void
1225 smb2_clear_stats(struct cifs_tcon *tcon)
1226 {
1227         int i;
1228
1229         for (i = 0; i < NUMBER_OF_SMB2_COMMANDS; i++) {
1230                 atomic_set(&tcon->stats.smb2_stats.smb2_com_sent[i], 0);
1231                 atomic_set(&tcon->stats.smb2_stats.smb2_com_failed[i], 0);
1232         }
1233 }
1234
1235 static void
1236 smb2_dump_share_caps(struct seq_file *m, struct cifs_tcon *tcon)
1237 {
1238         seq_puts(m, "\n\tShare Capabilities:");
1239         if (tcon->capabilities & SMB2_SHARE_CAP_DFS)
1240                 seq_puts(m, " DFS,");
1241         if (tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
1242                 seq_puts(m, " CONTINUOUS AVAILABILITY,");
1243         if (tcon->capabilities & SMB2_SHARE_CAP_SCALEOUT)
1244                 seq_puts(m, " SCALEOUT,");
1245         if (tcon->capabilities & SMB2_SHARE_CAP_CLUSTER)
1246                 seq_puts(m, " CLUSTER,");
1247         if (tcon->capabilities & SMB2_SHARE_CAP_ASYMMETRIC)
1248                 seq_puts(m, " ASYMMETRIC,");
1249         if (tcon->capabilities == 0)
1250                 seq_puts(m, " None");
1251         if (tcon->ss_flags & SSINFO_FLAGS_ALIGNED_DEVICE)
1252                 seq_puts(m, " Aligned,");
1253         if (tcon->ss_flags & SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE)
1254                 seq_puts(m, " Partition Aligned,");
1255         if (tcon->ss_flags & SSINFO_FLAGS_NO_SEEK_PENALTY)
1256                 seq_puts(m, " SSD,");
1257         if (tcon->ss_flags & SSINFO_FLAGS_TRIM_ENABLED)
1258                 seq_puts(m, " TRIM-support,");
1259
1260         seq_printf(m, "\tShare Flags: 0x%x", tcon->share_flags);
1261         seq_printf(m, "\n\ttid: 0x%x", tcon->tid);
1262         if (tcon->perf_sector_size)
1263                 seq_printf(m, "\tOptimal sector size: 0x%x",
1264                            tcon->perf_sector_size);
1265         seq_printf(m, "\tMaximal Access: 0x%x", tcon->maximal_access);
1266 }
1267
1268 static void
1269 smb2_print_stats(struct seq_file *m, struct cifs_tcon *tcon)
1270 {
1271         atomic_t *sent = tcon->stats.smb2_stats.smb2_com_sent;
1272         atomic_t *failed = tcon->stats.smb2_stats.smb2_com_failed;
1273
1274         /*
1275          *  Can't display SMB2_NEGOTIATE, SESSION_SETUP, LOGOFF, CANCEL and ECHO
1276          *  totals (requests sent) since those SMBs are per-session not per tcon
1277          */
1278         seq_printf(m, "\nBytes read: %llu  Bytes written: %llu",
1279                    (long long)(tcon->bytes_read),
1280                    (long long)(tcon->bytes_written));
1281         seq_printf(m, "\nOpen files: %d total (local), %d open on server",
1282                    atomic_read(&tcon->num_local_opens),
1283                    atomic_read(&tcon->num_remote_opens));
1284         seq_printf(m, "\nTreeConnects: %d total %d failed",
1285                    atomic_read(&sent[SMB2_TREE_CONNECT_HE]),
1286                    atomic_read(&failed[SMB2_TREE_CONNECT_HE]));
1287         seq_printf(m, "\nTreeDisconnects: %d total %d failed",
1288                    atomic_read(&sent[SMB2_TREE_DISCONNECT_HE]),
1289                    atomic_read(&failed[SMB2_TREE_DISCONNECT_HE]));
1290         seq_printf(m, "\nCreates: %d total %d failed",
1291                    atomic_read(&sent[SMB2_CREATE_HE]),
1292                    atomic_read(&failed[SMB2_CREATE_HE]));
1293         seq_printf(m, "\nCloses: %d total %d failed",
1294                    atomic_read(&sent[SMB2_CLOSE_HE]),
1295                    atomic_read(&failed[SMB2_CLOSE_HE]));
1296         seq_printf(m, "\nFlushes: %d total %d failed",
1297                    atomic_read(&sent[SMB2_FLUSH_HE]),
1298                    atomic_read(&failed[SMB2_FLUSH_HE]));
1299         seq_printf(m, "\nReads: %d total %d failed",
1300                    atomic_read(&sent[SMB2_READ_HE]),
1301                    atomic_read(&failed[SMB2_READ_HE]));
1302         seq_printf(m, "\nWrites: %d total %d failed",
1303                    atomic_read(&sent[SMB2_WRITE_HE]),
1304                    atomic_read(&failed[SMB2_WRITE_HE]));
1305         seq_printf(m, "\nLocks: %d total %d failed",
1306                    atomic_read(&sent[SMB2_LOCK_HE]),
1307                    atomic_read(&failed[SMB2_LOCK_HE]));
1308         seq_printf(m, "\nIOCTLs: %d total %d failed",
1309                    atomic_read(&sent[SMB2_IOCTL_HE]),
1310                    atomic_read(&failed[SMB2_IOCTL_HE]));
1311         seq_printf(m, "\nQueryDirectories: %d total %d failed",
1312                    atomic_read(&sent[SMB2_QUERY_DIRECTORY_HE]),
1313                    atomic_read(&failed[SMB2_QUERY_DIRECTORY_HE]));
1314         seq_printf(m, "\nChangeNotifies: %d total %d failed",
1315                    atomic_read(&sent[SMB2_CHANGE_NOTIFY_HE]),
1316                    atomic_read(&failed[SMB2_CHANGE_NOTIFY_HE]));
1317         seq_printf(m, "\nQueryInfos: %d total %d failed",
1318                    atomic_read(&sent[SMB2_QUERY_INFO_HE]),
1319                    atomic_read(&failed[SMB2_QUERY_INFO_HE]));
1320         seq_printf(m, "\nSetInfos: %d total %d failed",
1321                    atomic_read(&sent[SMB2_SET_INFO_HE]),
1322                    atomic_read(&failed[SMB2_SET_INFO_HE]));
1323         seq_printf(m, "\nOplockBreaks: %d sent %d failed",
1324                    atomic_read(&sent[SMB2_OPLOCK_BREAK_HE]),
1325                    atomic_read(&failed[SMB2_OPLOCK_BREAK_HE]));
1326 }
1327
1328 static void
1329 smb2_set_fid(struct cifsFileInfo *cfile, struct cifs_fid *fid, __u32 oplock)
1330 {
1331         struct cifsInodeInfo *cinode = CIFS_I(d_inode(cfile->dentry));
1332         struct TCP_Server_Info *server = tlink_tcon(cfile->tlink)->ses->server;
1333
1334         cfile->fid.persistent_fid = fid->persistent_fid;
1335         cfile->fid.volatile_fid = fid->volatile_fid;
1336 #ifdef CONFIG_CIFS_DEBUG2
1337         cfile->fid.mid = fid->mid;
1338 #endif /* CIFS_DEBUG2 */
1339         server->ops->set_oplock_level(cinode, oplock, fid->epoch,
1340                                       &fid->purge_cache);
1341         cinode->can_cache_brlcks = CIFS_CACHE_WRITE(cinode);
1342         memcpy(cfile->fid.create_guid, fid->create_guid, 16);
1343 }
1344
1345 static void
1346 smb2_close_file(const unsigned int xid, struct cifs_tcon *tcon,
1347                 struct cifs_fid *fid)
1348 {
1349         SMB2_close(xid, tcon, fid->persistent_fid, fid->volatile_fid);
1350 }
1351
1352 static void
1353 smb2_close_getattr(const unsigned int xid, struct cifs_tcon *tcon,
1354                    struct cifsFileInfo *cfile)
1355 {
1356         struct smb2_file_network_open_info file_inf;
1357         struct inode *inode;
1358         int rc;
1359
1360         rc = __SMB2_close(xid, tcon, cfile->fid.persistent_fid,
1361                    cfile->fid.volatile_fid, &file_inf);
1362         if (rc)
1363                 return;
1364
1365         inode = d_inode(cfile->dentry);
1366
1367         spin_lock(&inode->i_lock);
1368         CIFS_I(inode)->time = jiffies;
1369
1370         /* Creation time should not need to be updated on close */
1371         if (file_inf.LastWriteTime)
1372                 inode->i_mtime = cifs_NTtimeToUnix(file_inf.LastWriteTime);
1373         if (file_inf.ChangeTime)
1374                 inode->i_ctime = cifs_NTtimeToUnix(file_inf.ChangeTime);
1375         if (file_inf.LastAccessTime)
1376                 inode->i_atime = cifs_NTtimeToUnix(file_inf.LastAccessTime);
1377
1378         /*
1379          * i_blocks is not related to (i_size / i_blksize),
1380          * but instead 512 byte (2**9) size is required for
1381          * calculating num blocks.
1382          */
1383         if (le64_to_cpu(file_inf.AllocationSize) > 4096)
1384                 inode->i_blocks =
1385                         (512 - 1 + le64_to_cpu(file_inf.AllocationSize)) >> 9;
1386
1387         /* End of file and Attributes should not have to be updated on close */
1388         spin_unlock(&inode->i_lock);
1389 }
1390
1391 static int
1392 SMB2_request_res_key(const unsigned int xid, struct cifs_tcon *tcon,
1393                      u64 persistent_fid, u64 volatile_fid,
1394                      struct copychunk_ioctl *pcchunk)
1395 {
1396         int rc;
1397         unsigned int ret_data_len;
1398         struct resume_key_req *res_key;
1399
1400         rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
1401                         FSCTL_SRV_REQUEST_RESUME_KEY, true /* is_fsctl */,
1402                         NULL, 0 /* no input */, CIFSMaxBufSize,
1403                         (char **)&res_key, &ret_data_len);
1404
1405         if (rc) {
1406                 cifs_tcon_dbg(VFS, "refcpy ioctl error %d getting resume key\n", rc);
1407                 goto req_res_key_exit;
1408         }
1409         if (ret_data_len < sizeof(struct resume_key_req)) {
1410                 cifs_tcon_dbg(VFS, "Invalid refcopy resume key length\n");
1411                 rc = -EINVAL;
1412                 goto req_res_key_exit;
1413         }
1414         memcpy(pcchunk->SourceKey, res_key->ResumeKey, COPY_CHUNK_RES_KEY_SIZE);
1415
1416 req_res_key_exit:
1417         kfree(res_key);
1418         return rc;
1419 }
1420
1421 static int
1422 smb2_ioctl_query_info(const unsigned int xid,
1423                       struct cifs_tcon *tcon,
1424                       __le16 *path, int is_dir,
1425                       unsigned long p)
1426 {
1427         struct cifs_ses *ses = tcon->ses;
1428         char __user *arg = (char __user *)p;
1429         struct smb_query_info qi;
1430         struct smb_query_info __user *pqi;
1431         int rc = 0;
1432         int flags = 0;
1433         struct smb2_query_info_rsp *qi_rsp = NULL;
1434         struct smb2_ioctl_rsp *io_rsp = NULL;
1435         void *buffer = NULL;
1436         struct smb_rqst rqst[3];
1437         int resp_buftype[3];
1438         struct kvec rsp_iov[3];
1439         struct kvec open_iov[SMB2_CREATE_IOV_SIZE];
1440         struct cifs_open_parms oparms;
1441         u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
1442         struct cifs_fid fid;
1443         struct kvec qi_iov[1];
1444         struct kvec io_iov[SMB2_IOCTL_IOV_SIZE];
1445         struct kvec si_iov[SMB2_SET_INFO_IOV_SIZE];
1446         struct kvec close_iov[1];
1447         unsigned int size[2];
1448         void *data[2];
1449
1450         memset(rqst, 0, sizeof(rqst));
1451         resp_buftype[0] = resp_buftype[1] = resp_buftype[2] = CIFS_NO_BUFFER;
1452         memset(rsp_iov, 0, sizeof(rsp_iov));
1453
1454         if (copy_from_user(&qi, arg, sizeof(struct smb_query_info)))
1455                 return -EFAULT;
1456
1457         if (qi.output_buffer_length > 1024)
1458                 return -EINVAL;
1459
1460         if (!ses || !(ses->server))
1461                 return -EIO;
1462
1463         if (smb3_encryption_required(tcon))
1464                 flags |= CIFS_TRANSFORM_REQ;
1465
1466         buffer = memdup_user(arg + sizeof(struct smb_query_info),
1467                              qi.output_buffer_length);
1468         if (IS_ERR(buffer))
1469                 return PTR_ERR(buffer);
1470
1471         /* Open */
1472         memset(&open_iov, 0, sizeof(open_iov));
1473         rqst[0].rq_iov = open_iov;
1474         rqst[0].rq_nvec = SMB2_CREATE_IOV_SIZE;
1475
1476         memset(&oparms, 0, sizeof(oparms));
1477         oparms.tcon = tcon;
1478         oparms.disposition = FILE_OPEN;
1479         if (is_dir)
1480                 oparms.create_options = CREATE_NOT_FILE;
1481         else
1482                 oparms.create_options = CREATE_NOT_DIR;
1483         oparms.fid = &fid;
1484         oparms.reconnect = false;
1485
1486         if (qi.flags & PASSTHRU_FSCTL) {
1487                 switch (qi.info_type & FSCTL_DEVICE_ACCESS_MASK) {
1488                 case FSCTL_DEVICE_ACCESS_FILE_READ_WRITE_ACCESS:
1489                         oparms.desired_access = FILE_READ_DATA | FILE_WRITE_DATA | FILE_READ_ATTRIBUTES | SYNCHRONIZE;
1490                         break;
1491                 case FSCTL_DEVICE_ACCESS_FILE_ANY_ACCESS:
1492                         oparms.desired_access = GENERIC_ALL;
1493                         break;
1494                 case FSCTL_DEVICE_ACCESS_FILE_READ_ACCESS:
1495                         oparms.desired_access = GENERIC_READ;
1496                         break;
1497                 case FSCTL_DEVICE_ACCESS_FILE_WRITE_ACCESS:
1498                         oparms.desired_access = GENERIC_WRITE;
1499                         break;
1500                 }
1501         } else if (qi.flags & PASSTHRU_SET_INFO) {
1502                 oparms.desired_access = GENERIC_WRITE;
1503         } else {
1504                 oparms.desired_access = FILE_READ_ATTRIBUTES | READ_CONTROL;
1505         }
1506
1507         rc = SMB2_open_init(tcon, &rqst[0], &oplock, &oparms, path);
1508         if (rc)
1509                 goto iqinf_exit;
1510         smb2_set_next_command(tcon, &rqst[0]);
1511
1512         /* Query */
1513         if (qi.flags & PASSTHRU_FSCTL) {
1514                 /* Can eventually relax perm check since server enforces too */
1515                 if (!capable(CAP_SYS_ADMIN))
1516                         rc = -EPERM;
1517                 else  {
1518                         memset(&io_iov, 0, sizeof(io_iov));
1519                         rqst[1].rq_iov = io_iov;
1520                         rqst[1].rq_nvec = SMB2_IOCTL_IOV_SIZE;
1521
1522                         rc = SMB2_ioctl_init(tcon, &rqst[1],
1523                                              COMPOUND_FID, COMPOUND_FID,
1524                                              qi.info_type, true, buffer,
1525                                              qi.output_buffer_length,
1526                                              CIFSMaxBufSize);
1527                 }
1528         } else if (qi.flags == PASSTHRU_SET_INFO) {
1529                 /* Can eventually relax perm check since server enforces too */
1530                 if (!capable(CAP_SYS_ADMIN))
1531                         rc = -EPERM;
1532                 else  {
1533                         memset(&si_iov, 0, sizeof(si_iov));
1534                         rqst[1].rq_iov = si_iov;
1535                         rqst[1].rq_nvec = 1;
1536
1537                         size[0] = 8;
1538                         data[0] = buffer;
1539
1540                         rc = SMB2_set_info_init(tcon, &rqst[1],
1541                                         COMPOUND_FID, COMPOUND_FID,
1542                                         current->tgid,
1543                                         FILE_END_OF_FILE_INFORMATION,
1544                                         SMB2_O_INFO_FILE, 0, data, size);
1545                 }
1546         } else if (qi.flags == PASSTHRU_QUERY_INFO) {
1547                 memset(&qi_iov, 0, sizeof(qi_iov));
1548                 rqst[1].rq_iov = qi_iov;
1549                 rqst[1].rq_nvec = 1;
1550
1551                 rc = SMB2_query_info_init(tcon, &rqst[1], COMPOUND_FID,
1552                                   COMPOUND_FID, qi.file_info_class,
1553                                   qi.info_type, qi.additional_information,
1554                                   qi.input_buffer_length,
1555                                   qi.output_buffer_length, buffer);
1556         } else { /* unknown flags */
1557                 cifs_tcon_dbg(VFS, "invalid passthru query flags: 0x%x\n", qi.flags);
1558                 rc = -EINVAL;
1559         }
1560
1561         if (rc)
1562                 goto iqinf_exit;
1563         smb2_set_next_command(tcon, &rqst[1]);
1564         smb2_set_related(&rqst[1]);
1565
1566         /* Close */
1567         memset(&close_iov, 0, sizeof(close_iov));
1568         rqst[2].rq_iov = close_iov;
1569         rqst[2].rq_nvec = 1;
1570
1571         rc = SMB2_close_init(tcon, &rqst[2], COMPOUND_FID, COMPOUND_FID, false);
1572         if (rc)
1573                 goto iqinf_exit;
1574         smb2_set_related(&rqst[2]);
1575
1576         rc = compound_send_recv(xid, ses, flags, 3, rqst,
1577                                 resp_buftype, rsp_iov);
1578         if (rc)
1579                 goto iqinf_exit;
1580
1581         /* No need to bump num_remote_opens since handle immediately closed */
1582         if (qi.flags & PASSTHRU_FSCTL) {
1583                 pqi = (struct smb_query_info __user *)arg;
1584                 io_rsp = (struct smb2_ioctl_rsp *)rsp_iov[1].iov_base;
1585                 if (le32_to_cpu(io_rsp->OutputCount) < qi.input_buffer_length)
1586                         qi.input_buffer_length = le32_to_cpu(io_rsp->OutputCount);
1587                 if (qi.input_buffer_length > 0 &&
1588                     le32_to_cpu(io_rsp->OutputOffset) + qi.input_buffer_length
1589                     > rsp_iov[1].iov_len)
1590                         goto e_fault;
1591
1592                 if (copy_to_user(&pqi->input_buffer_length,
1593                                  &qi.input_buffer_length,
1594                                  sizeof(qi.input_buffer_length)))
1595                         goto e_fault;
1596
1597                 if (copy_to_user((void __user *)pqi + sizeof(struct smb_query_info),
1598                                  (const void *)io_rsp + le32_to_cpu(io_rsp->OutputOffset),
1599                                  qi.input_buffer_length))
1600                         goto e_fault;
1601         } else {
1602                 pqi = (struct smb_query_info __user *)arg;
1603                 qi_rsp = (struct smb2_query_info_rsp *)rsp_iov[1].iov_base;
1604                 if (le32_to_cpu(qi_rsp->OutputBufferLength) < qi.input_buffer_length)
1605                         qi.input_buffer_length = le32_to_cpu(qi_rsp->OutputBufferLength);
1606                 if (copy_to_user(&pqi->input_buffer_length,
1607                                  &qi.input_buffer_length,
1608                                  sizeof(qi.input_buffer_length)))
1609                         goto e_fault;
1610
1611                 if (copy_to_user(pqi + 1, qi_rsp->Buffer,
1612                                  qi.input_buffer_length))
1613                         goto e_fault;
1614         }
1615
1616  iqinf_exit:
1617         kfree(buffer);
1618         SMB2_open_free(&rqst[0]);
1619         if (qi.flags & PASSTHRU_FSCTL)
1620                 SMB2_ioctl_free(&rqst[1]);
1621         else
1622                 SMB2_query_info_free(&rqst[1]);
1623
1624         SMB2_close_free(&rqst[2]);
1625         free_rsp_buf(resp_buftype[0], rsp_iov[0].iov_base);
1626         free_rsp_buf(resp_buftype[1], rsp_iov[1].iov_base);
1627         free_rsp_buf(resp_buftype[2], rsp_iov[2].iov_base);
1628         return rc;
1629
1630 e_fault:
1631         rc = -EFAULT;
1632         goto iqinf_exit;
1633 }
1634
1635 static ssize_t
1636 smb2_copychunk_range(const unsigned int xid,
1637                         struct cifsFileInfo *srcfile,
1638                         struct cifsFileInfo *trgtfile, u64 src_off,
1639                         u64 len, u64 dest_off)
1640 {
1641         int rc;
1642         unsigned int ret_data_len;
1643         struct copychunk_ioctl *pcchunk;
1644         struct copychunk_ioctl_rsp *retbuf = NULL;
1645         struct cifs_tcon *tcon;
1646         int chunks_copied = 0;
1647         bool chunk_sizes_updated = false;
1648         ssize_t bytes_written, total_bytes_written = 0;
1649
1650         pcchunk = kmalloc(sizeof(struct copychunk_ioctl), GFP_KERNEL);
1651
1652         if (pcchunk == NULL)
1653                 return -ENOMEM;
1654
1655         cifs_dbg(FYI, "%s: about to call request res key\n", __func__);
1656         /* Request a key from the server to identify the source of the copy */
1657         rc = SMB2_request_res_key(xid, tlink_tcon(srcfile->tlink),
1658                                 srcfile->fid.persistent_fid,
1659                                 srcfile->fid.volatile_fid, pcchunk);
1660
1661         /* Note: request_res_key sets res_key null only if rc !=0 */
1662         if (rc)
1663                 goto cchunk_out;
1664
1665         /* For now array only one chunk long, will make more flexible later */
1666         pcchunk->ChunkCount = cpu_to_le32(1);
1667         pcchunk->Reserved = 0;
1668         pcchunk->Reserved2 = 0;
1669
1670         tcon = tlink_tcon(trgtfile->tlink);
1671
1672         while (len > 0) {
1673                 pcchunk->SourceOffset = cpu_to_le64(src_off);
1674                 pcchunk->TargetOffset = cpu_to_le64(dest_off);
1675                 pcchunk->Length =
1676                         cpu_to_le32(min_t(u32, len, tcon->max_bytes_chunk));
1677
1678                 /* Request server copy to target from src identified by key */
1679                 rc = SMB2_ioctl(xid, tcon, trgtfile->fid.persistent_fid,
1680                         trgtfile->fid.volatile_fid, FSCTL_SRV_COPYCHUNK_WRITE,
1681                         true /* is_fsctl */, (char *)pcchunk,
1682                         sizeof(struct copychunk_ioctl), CIFSMaxBufSize,
1683                         (char **)&retbuf, &ret_data_len);
1684                 if (rc == 0) {
1685                         if (ret_data_len !=
1686                                         sizeof(struct copychunk_ioctl_rsp)) {
1687                                 cifs_tcon_dbg(VFS, "invalid cchunk response size\n");
1688                                 rc = -EIO;
1689                                 goto cchunk_out;
1690                         }
1691                         if (retbuf->TotalBytesWritten == 0) {
1692                                 cifs_dbg(FYI, "no bytes copied\n");
1693                                 rc = -EIO;
1694                                 goto cchunk_out;
1695                         }
1696                         /*
1697                          * Check if server claimed to write more than we asked
1698                          */
1699                         if (le32_to_cpu(retbuf->TotalBytesWritten) >
1700                             le32_to_cpu(pcchunk->Length)) {
1701                                 cifs_tcon_dbg(VFS, "invalid copy chunk response\n");
1702                                 rc = -EIO;
1703                                 goto cchunk_out;
1704                         }
1705                         if (le32_to_cpu(retbuf->ChunksWritten) != 1) {
1706                                 cifs_tcon_dbg(VFS, "invalid num chunks written\n");
1707                                 rc = -EIO;
1708                                 goto cchunk_out;
1709                         }
1710                         chunks_copied++;
1711
1712                         bytes_written = le32_to_cpu(retbuf->TotalBytesWritten);
1713                         src_off += bytes_written;
1714                         dest_off += bytes_written;
1715                         len -= bytes_written;
1716                         total_bytes_written += bytes_written;
1717
1718                         cifs_dbg(FYI, "Chunks %d PartialChunk %d Total %zu\n",
1719                                 le32_to_cpu(retbuf->ChunksWritten),
1720                                 le32_to_cpu(retbuf->ChunkBytesWritten),
1721                                 bytes_written);
1722                 } else if (rc == -EINVAL) {
1723                         if (ret_data_len != sizeof(struct copychunk_ioctl_rsp))
1724                                 goto cchunk_out;
1725
1726                         cifs_dbg(FYI, "MaxChunks %d BytesChunk %d MaxCopy %d\n",
1727                                 le32_to_cpu(retbuf->ChunksWritten),
1728                                 le32_to_cpu(retbuf->ChunkBytesWritten),
1729                                 le32_to_cpu(retbuf->TotalBytesWritten));
1730
1731                         /*
1732                          * Check if this is the first request using these sizes,
1733                          * (ie check if copy succeed once with original sizes
1734                          * and check if the server gave us different sizes after
1735                          * we already updated max sizes on previous request).
1736                          * if not then why is the server returning an error now
1737                          */
1738                         if ((chunks_copied != 0) || chunk_sizes_updated)
1739                                 goto cchunk_out;
1740
1741                         /* Check that server is not asking us to grow size */
1742                         if (le32_to_cpu(retbuf->ChunkBytesWritten) <
1743                                         tcon->max_bytes_chunk)
1744                                 tcon->max_bytes_chunk =
1745                                         le32_to_cpu(retbuf->ChunkBytesWritten);
1746                         else
1747                                 goto cchunk_out; /* server gave us bogus size */
1748
1749                         /* No need to change MaxChunks since already set to 1 */
1750                         chunk_sizes_updated = true;
1751                 } else
1752                         goto cchunk_out;
1753         }
1754
1755 cchunk_out:
1756         kfree(pcchunk);
1757         kfree(retbuf);
1758         if (rc)
1759                 return rc;
1760         else
1761                 return total_bytes_written;
1762 }
1763
1764 static int
1765 smb2_flush_file(const unsigned int xid, struct cifs_tcon *tcon,
1766                 struct cifs_fid *fid)
1767 {
1768         return SMB2_flush(xid, tcon, fid->persistent_fid, fid->volatile_fid);
1769 }
1770
1771 static unsigned int
1772 smb2_read_data_offset(char *buf)
1773 {
1774         struct smb2_read_rsp *rsp = (struct smb2_read_rsp *)buf;
1775
1776         return rsp->DataOffset;
1777 }
1778
1779 static unsigned int
1780 smb2_read_data_length(char *buf, bool in_remaining)
1781 {
1782         struct smb2_read_rsp *rsp = (struct smb2_read_rsp *)buf;
1783
1784         if (in_remaining)
1785                 return le32_to_cpu(rsp->DataRemaining);
1786
1787         return le32_to_cpu(rsp->DataLength);
1788 }
1789
1790
1791 static int
1792 smb2_sync_read(const unsigned int xid, struct cifs_fid *pfid,
1793                struct cifs_io_parms *parms, unsigned int *bytes_read,
1794                char **buf, int *buf_type)
1795 {
1796         parms->persistent_fid = pfid->persistent_fid;
1797         parms->volatile_fid = pfid->volatile_fid;
1798         return SMB2_read(xid, parms, bytes_read, buf, buf_type);
1799 }
1800
1801 static int
1802 smb2_sync_write(const unsigned int xid, struct cifs_fid *pfid,
1803                 struct cifs_io_parms *parms, unsigned int *written,
1804                 struct kvec *iov, unsigned long nr_segs)
1805 {
1806
1807         parms->persistent_fid = pfid->persistent_fid;
1808         parms->volatile_fid = pfid->volatile_fid;
1809         return SMB2_write(xid, parms, written, iov, nr_segs);
1810 }
1811
1812 /* Set or clear the SPARSE_FILE attribute based on value passed in setsparse */
1813 static bool smb2_set_sparse(const unsigned int xid, struct cifs_tcon *tcon,
1814                 struct cifsFileInfo *cfile, struct inode *inode, __u8 setsparse)
1815 {
1816         struct cifsInodeInfo *cifsi;
1817         int rc;
1818
1819         cifsi = CIFS_I(inode);
1820
1821         /* if file already sparse don't bother setting sparse again */
1822         if ((cifsi->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE) && setsparse)
1823                 return true; /* already sparse */
1824
1825         if (!(cifsi->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE) && !setsparse)
1826                 return true; /* already not sparse */
1827
1828         /*
1829          * Can't check for sparse support on share the usual way via the
1830          * FS attribute info (FILE_SUPPORTS_SPARSE_FILES) on the share
1831          * since Samba server doesn't set the flag on the share, yet
1832          * supports the set sparse FSCTL and returns sparse correctly
1833          * in the file attributes. If we fail setting sparse though we
1834          * mark that server does not support sparse files for this share
1835          * to avoid repeatedly sending the unsupported fsctl to server
1836          * if the file is repeatedly extended.
1837          */
1838         if (tcon->broken_sparse_sup)
1839                 return false;
1840
1841         rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
1842                         cfile->fid.volatile_fid, FSCTL_SET_SPARSE,
1843                         true /* is_fctl */,
1844                         &setsparse, 1, CIFSMaxBufSize, NULL, NULL);
1845         if (rc) {
1846                 tcon->broken_sparse_sup = true;
1847                 cifs_dbg(FYI, "set sparse rc = %d\n", rc);
1848                 return false;
1849         }
1850
1851         if (setsparse)
1852                 cifsi->cifsAttrs |= FILE_ATTRIBUTE_SPARSE_FILE;
1853         else
1854                 cifsi->cifsAttrs &= (~FILE_ATTRIBUTE_SPARSE_FILE);
1855
1856         return true;
1857 }
1858
1859 static int
1860 smb2_set_file_size(const unsigned int xid, struct cifs_tcon *tcon,
1861                    struct cifsFileInfo *cfile, __u64 size, bool set_alloc)
1862 {
1863         __le64 eof = cpu_to_le64(size);
1864         struct inode *inode;
1865
1866         /*
1867          * If extending file more than one page make sparse. Many Linux fs
1868          * make files sparse by default when extending via ftruncate
1869          */
1870         inode = d_inode(cfile->dentry);
1871
1872         if (!set_alloc && (size > inode->i_size + 8192)) {
1873                 __u8 set_sparse = 1;
1874
1875                 /* whether set sparse succeeds or not, extend the file */
1876                 smb2_set_sparse(xid, tcon, cfile, inode, set_sparse);
1877         }
1878
1879         return SMB2_set_eof(xid, tcon, cfile->fid.persistent_fid,
1880                             cfile->fid.volatile_fid, cfile->pid, &eof);
1881 }
1882
1883 static int
1884 smb2_duplicate_extents(const unsigned int xid,
1885                         struct cifsFileInfo *srcfile,
1886                         struct cifsFileInfo *trgtfile, u64 src_off,
1887                         u64 len, u64 dest_off)
1888 {
1889         int rc;
1890         unsigned int ret_data_len;
1891         struct duplicate_extents_to_file dup_ext_buf;
1892         struct cifs_tcon *tcon = tlink_tcon(trgtfile->tlink);
1893
1894         /* server fileays advertise duplicate extent support with this flag */
1895         if ((le32_to_cpu(tcon->fsAttrInfo.Attributes) &
1896              FILE_SUPPORTS_BLOCK_REFCOUNTING) == 0)
1897                 return -EOPNOTSUPP;
1898
1899         dup_ext_buf.VolatileFileHandle = srcfile->fid.volatile_fid;
1900         dup_ext_buf.PersistentFileHandle = srcfile->fid.persistent_fid;
1901         dup_ext_buf.SourceFileOffset = cpu_to_le64(src_off);
1902         dup_ext_buf.TargetFileOffset = cpu_to_le64(dest_off);
1903         dup_ext_buf.ByteCount = cpu_to_le64(len);
1904         cifs_dbg(FYI, "Duplicate extents: src off %lld dst off %lld len %lld\n",
1905                 src_off, dest_off, len);
1906
1907         rc = smb2_set_file_size(xid, tcon, trgtfile, dest_off + len, false);
1908         if (rc)
1909                 goto duplicate_extents_out;
1910
1911         rc = SMB2_ioctl(xid, tcon, trgtfile->fid.persistent_fid,
1912                         trgtfile->fid.volatile_fid,
1913                         FSCTL_DUPLICATE_EXTENTS_TO_FILE,
1914                         true /* is_fsctl */,
1915                         (char *)&dup_ext_buf,
1916                         sizeof(struct duplicate_extents_to_file),
1917                         CIFSMaxBufSize, NULL,
1918                         &ret_data_len);
1919
1920         if (ret_data_len > 0)
1921                 cifs_dbg(FYI, "Non-zero response length in duplicate extents\n");
1922
1923 duplicate_extents_out:
1924         return rc;
1925 }
1926
1927 static int
1928 smb2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
1929                    struct cifsFileInfo *cfile)
1930 {
1931         return SMB2_set_compression(xid, tcon, cfile->fid.persistent_fid,
1932                             cfile->fid.volatile_fid);
1933 }
1934
1935 static int
1936 smb3_set_integrity(const unsigned int xid, struct cifs_tcon *tcon,
1937                    struct cifsFileInfo *cfile)
1938 {
1939         struct fsctl_set_integrity_information_req integr_info;
1940         unsigned int ret_data_len;
1941
1942         integr_info.ChecksumAlgorithm = cpu_to_le16(CHECKSUM_TYPE_UNCHANGED);
1943         integr_info.Flags = 0;
1944         integr_info.Reserved = 0;
1945
1946         return SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
1947                         cfile->fid.volatile_fid,
1948                         FSCTL_SET_INTEGRITY_INFORMATION,
1949                         true /* is_fsctl */,
1950                         (char *)&integr_info,
1951                         sizeof(struct fsctl_set_integrity_information_req),
1952                         CIFSMaxBufSize, NULL,
1953                         &ret_data_len);
1954
1955 }
1956
1957 /* GMT Token is @GMT-YYYY.MM.DD-HH.MM.SS Unicode which is 48 bytes + null */
1958 #define GMT_TOKEN_SIZE 50
1959
1960 #define MIN_SNAPSHOT_ARRAY_SIZE 16 /* See MS-SMB2 section 3.3.5.15.1 */
1961
1962 /*
1963  * Input buffer contains (empty) struct smb_snapshot array with size filled in
1964  * For output see struct SRV_SNAPSHOT_ARRAY in MS-SMB2 section 2.2.32.2
1965  */
1966 static int
1967 smb3_enum_snapshots(const unsigned int xid, struct cifs_tcon *tcon,
1968                    struct cifsFileInfo *cfile, void __user *ioc_buf)
1969 {
1970         char *retbuf = NULL;
1971         unsigned int ret_data_len = 0;
1972         int rc;
1973         u32 max_response_size;
1974         struct smb_snapshot_array snapshot_in;
1975
1976         /*
1977          * On the first query to enumerate the list of snapshots available
1978          * for this volume the buffer begins with 0 (number of snapshots
1979          * which can be returned is zero since at that point we do not know
1980          * how big the buffer needs to be). On the second query,
1981          * it (ret_data_len) is set to number of snapshots so we can
1982          * know to set the maximum response size larger (see below).
1983          */
1984         if (get_user(ret_data_len, (unsigned int __user *)ioc_buf))
1985                 return -EFAULT;
1986
1987         /*
1988          * Note that for snapshot queries that servers like Azure expect that
1989          * the first query be minimal size (and just used to get the number/size
1990          * of previous versions) so response size must be specified as EXACTLY
1991          * sizeof(struct snapshot_array) which is 16 when rounded up to multiple
1992          * of eight bytes.
1993          */
1994         if (ret_data_len == 0)
1995                 max_response_size = MIN_SNAPSHOT_ARRAY_SIZE;
1996         else
1997                 max_response_size = CIFSMaxBufSize;
1998
1999         rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
2000                         cfile->fid.volatile_fid,
2001                         FSCTL_SRV_ENUMERATE_SNAPSHOTS,
2002                         true /* is_fsctl */,
2003                         NULL, 0 /* no input data */, max_response_size,
2004                         (char **)&retbuf,
2005                         &ret_data_len);
2006         cifs_dbg(FYI, "enum snaphots ioctl returned %d and ret buflen is %d\n",
2007                         rc, ret_data_len);
2008         if (rc)
2009                 return rc;
2010
2011         if (ret_data_len && (ioc_buf != NULL) && (retbuf != NULL)) {
2012                 /* Fixup buffer */
2013                 if (copy_from_user(&snapshot_in, ioc_buf,
2014                     sizeof(struct smb_snapshot_array))) {
2015                         rc = -EFAULT;
2016                         kfree(retbuf);
2017                         return rc;
2018                 }
2019
2020                 /*
2021                  * Check for min size, ie not large enough to fit even one GMT
2022                  * token (snapshot).  On the first ioctl some users may pass in
2023                  * smaller size (or zero) to simply get the size of the array
2024                  * so the user space caller can allocate sufficient memory
2025                  * and retry the ioctl again with larger array size sufficient
2026                  * to hold all of the snapshot GMT tokens on the second try.
2027                  */
2028                 if (snapshot_in.snapshot_array_size < GMT_TOKEN_SIZE)
2029                         ret_data_len = sizeof(struct smb_snapshot_array);
2030
2031                 /*
2032                  * We return struct SRV_SNAPSHOT_ARRAY, followed by
2033                  * the snapshot array (of 50 byte GMT tokens) each
2034                  * representing an available previous version of the data
2035                  */
2036                 if (ret_data_len > (snapshot_in.snapshot_array_size +
2037                                         sizeof(struct smb_snapshot_array)))
2038                         ret_data_len = snapshot_in.snapshot_array_size +
2039                                         sizeof(struct smb_snapshot_array);
2040
2041                 if (copy_to_user(ioc_buf, retbuf, ret_data_len))
2042                         rc = -EFAULT;
2043         }
2044
2045         kfree(retbuf);
2046         return rc;
2047 }
2048
2049 static int
2050 smb2_query_dir_first(const unsigned int xid, struct cifs_tcon *tcon,
2051                      const char *path, struct cifs_sb_info *cifs_sb,
2052                      struct cifs_fid *fid, __u16 search_flags,
2053                      struct cifs_search_info *srch_inf)
2054 {
2055         __le16 *utf16_path;
2056         int rc;
2057         __u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
2058         struct cifs_open_parms oparms;
2059
2060         utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
2061         if (!utf16_path)
2062                 return -ENOMEM;
2063
2064         oparms.tcon = tcon;
2065         oparms.desired_access = FILE_READ_ATTRIBUTES | FILE_READ_DATA;
2066         oparms.disposition = FILE_OPEN;
2067         if (backup_cred(cifs_sb))
2068                 oparms.create_options = CREATE_OPEN_BACKUP_INTENT;
2069         else
2070                 oparms.create_options = 0;
2071         oparms.fid = fid;
2072         oparms.reconnect = false;
2073
2074         rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, NULL, NULL);
2075         kfree(utf16_path);
2076         if (rc) {
2077                 cifs_dbg(FYI, "open dir failed rc=%d\n", rc);
2078                 return rc;
2079         }
2080
2081         srch_inf->entries_in_buffer = 0;
2082         srch_inf->index_of_last_entry = 2;
2083
2084         rc = SMB2_query_directory(xid, tcon, fid->persistent_fid,
2085                                   fid->volatile_fid, 0, srch_inf);
2086         if (rc) {
2087                 cifs_dbg(FYI, "query directory failed rc=%d\n", rc);
2088                 SMB2_close(xid, tcon, fid->persistent_fid, fid->volatile_fid);
2089         }
2090         return rc;
2091 }
2092
2093 static int
2094 smb2_query_dir_next(const unsigned int xid, struct cifs_tcon *tcon,
2095                     struct cifs_fid *fid, __u16 search_flags,
2096                     struct cifs_search_info *srch_inf)
2097 {
2098         return SMB2_query_directory(xid, tcon, fid->persistent_fid,
2099                                     fid->volatile_fid, 0, srch_inf);
2100 }
2101
2102 static int
2103 smb2_close_dir(const unsigned int xid, struct cifs_tcon *tcon,
2104                struct cifs_fid *fid)
2105 {
2106         return SMB2_close(xid, tcon, fid->persistent_fid, fid->volatile_fid);
2107 }
2108
2109 /*
2110  * If we negotiate SMB2 protocol and get STATUS_PENDING - update
2111  * the number of credits and return true. Otherwise - return false.
2112  */
2113 static bool
2114 smb2_is_status_pending(char *buf, struct TCP_Server_Info *server)
2115 {
2116         struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)buf;
2117
2118         if (shdr->Status != STATUS_PENDING)
2119                 return false;
2120
2121         if (shdr->CreditRequest) {
2122                 spin_lock(&server->req_lock);
2123                 server->credits += le16_to_cpu(shdr->CreditRequest);
2124                 spin_unlock(&server->req_lock);
2125                 wake_up(&server->request_q);
2126         }
2127
2128         return true;
2129 }
2130
2131 static bool
2132 smb2_is_session_expired(char *buf)
2133 {
2134         struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)buf;
2135
2136         if (shdr->Status != STATUS_NETWORK_SESSION_EXPIRED &&
2137             shdr->Status != STATUS_USER_SESSION_DELETED)
2138                 return false;
2139
2140         trace_smb3_ses_expired(shdr->TreeId, shdr->SessionId,
2141                                le16_to_cpu(shdr->Command),
2142                                le64_to_cpu(shdr->MessageId));
2143         cifs_dbg(FYI, "Session expired or deleted\n");
2144
2145         return true;
2146 }
2147
2148 static int
2149 smb2_oplock_response(struct cifs_tcon *tcon, struct cifs_fid *fid,
2150                      struct cifsInodeInfo *cinode)
2151 {
2152         if (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_LEASING)
2153                 return SMB2_lease_break(0, tcon, cinode->lease_key,
2154                                         smb2_get_lease_state(cinode));
2155
2156         return SMB2_oplock_break(0, tcon, fid->persistent_fid,
2157                                  fid->volatile_fid,
2158                                  CIFS_CACHE_READ(cinode) ? 1 : 0);
2159 }
2160
2161 void
2162 smb2_set_related(struct smb_rqst *rqst)
2163 {
2164         struct smb2_sync_hdr *shdr;
2165
2166         shdr = (struct smb2_sync_hdr *)(rqst->rq_iov[0].iov_base);
2167         if (shdr == NULL) {
2168                 cifs_dbg(FYI, "shdr NULL in smb2_set_related\n");
2169                 return;
2170         }
2171         shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
2172 }
2173
2174 char smb2_padding[7] = {0, 0, 0, 0, 0, 0, 0};
2175
2176 void
2177 smb2_set_next_command(struct cifs_tcon *tcon, struct smb_rqst *rqst)
2178 {
2179         struct smb2_sync_hdr *shdr;
2180         struct cifs_ses *ses = tcon->ses;
2181         struct TCP_Server_Info *server = ses->server;
2182         unsigned long len = smb_rqst_len(server, rqst);
2183         int i, num_padding;
2184
2185         shdr = (struct smb2_sync_hdr *)(rqst->rq_iov[0].iov_base);
2186         if (shdr == NULL) {
2187                 cifs_dbg(FYI, "shdr NULL in smb2_set_next_command\n");
2188                 return;
2189         }
2190
2191         /* SMB headers in a compound are 8 byte aligned. */
2192
2193         /* No padding needed */
2194         if (!(len & 7))
2195                 goto finished;
2196
2197         num_padding = 8 - (len & 7);
2198         if (!smb3_encryption_required(tcon)) {
2199                 /*
2200                  * If we do not have encryption then we can just add an extra
2201                  * iov for the padding.
2202                  */
2203                 rqst->rq_iov[rqst->rq_nvec].iov_base = smb2_padding;
2204                 rqst->rq_iov[rqst->rq_nvec].iov_len = num_padding;
2205                 rqst->rq_nvec++;
2206                 len += num_padding;
2207         } else {
2208                 /*
2209                  * We can not add a small padding iov for the encryption case
2210                  * because the encryption framework can not handle the padding
2211                  * iovs.
2212                  * We have to flatten this into a single buffer and add
2213                  * the padding to it.
2214                  */
2215                 for (i = 1; i < rqst->rq_nvec; i++) {
2216                         memcpy(rqst->rq_iov[0].iov_base +
2217                                rqst->rq_iov[0].iov_len,
2218                                rqst->rq_iov[i].iov_base,
2219                                rqst->rq_iov[i].iov_len);
2220                         rqst->rq_iov[0].iov_len += rqst->rq_iov[i].iov_len;
2221                 }
2222                 memset(rqst->rq_iov[0].iov_base + rqst->rq_iov[0].iov_len,
2223                        0, num_padding);
2224                 rqst->rq_iov[0].iov_len += num_padding;
2225                 len += num_padding;
2226                 rqst->rq_nvec = 1;
2227         }
2228
2229  finished:
2230         shdr->NextCommand = cpu_to_le32(len);
2231 }
2232
2233 /*
2234  * Passes the query info response back to the caller on success.
2235  * Caller need to free this with free_rsp_buf().
2236  */
2237 int
2238 smb2_query_info_compound(const unsigned int xid, struct cifs_tcon *tcon,
2239                          __le16 *utf16_path, u32 desired_access,
2240                          u32 class, u32 type, u32 output_len,
2241                          struct kvec *rsp, int *buftype,
2242                          struct cifs_sb_info *cifs_sb)
2243 {
2244         struct cifs_ses *ses = tcon->ses;
2245         int flags = 0;
2246         struct smb_rqst rqst[3];
2247         int resp_buftype[3];
2248         struct kvec rsp_iov[3];
2249         struct kvec open_iov[SMB2_CREATE_IOV_SIZE];
2250         struct kvec qi_iov[1];
2251         struct kvec close_iov[1];
2252         u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
2253         struct cifs_open_parms oparms;
2254         struct cifs_fid fid;
2255         int rc;
2256
2257         if (smb3_encryption_required(tcon))
2258                 flags |= CIFS_TRANSFORM_REQ;
2259
2260         memset(rqst, 0, sizeof(rqst));
2261         resp_buftype[0] = resp_buftype[1] = resp_buftype[2] = CIFS_NO_BUFFER;
2262         memset(rsp_iov, 0, sizeof(rsp_iov));
2263
2264         memset(&open_iov, 0, sizeof(open_iov));
2265         rqst[0].rq_iov = open_iov;
2266         rqst[0].rq_nvec = SMB2_CREATE_IOV_SIZE;
2267
2268         oparms.tcon = tcon;
2269         oparms.desired_access = desired_access;
2270         oparms.disposition = FILE_OPEN;
2271         if (cifs_sb && backup_cred(cifs_sb))
2272                 oparms.create_options = CREATE_OPEN_BACKUP_INTENT;
2273         else
2274                 oparms.create_options = 0;
2275         oparms.fid = &fid;
2276         oparms.reconnect = false;
2277
2278         rc = SMB2_open_init(tcon, &rqst[0], &oplock, &oparms, utf16_path);
2279         if (rc)
2280                 goto qic_exit;
2281         smb2_set_next_command(tcon, &rqst[0]);
2282
2283         memset(&qi_iov, 0, sizeof(qi_iov));
2284         rqst[1].rq_iov = qi_iov;
2285         rqst[1].rq_nvec = 1;
2286
2287         rc = SMB2_query_info_init(tcon, &rqst[1], COMPOUND_FID, COMPOUND_FID,
2288                                   class, type, 0,
2289                                   output_len, 0,
2290                                   NULL);
2291         if (rc)
2292                 goto qic_exit;
2293         smb2_set_next_command(tcon, &rqst[1]);
2294         smb2_set_related(&rqst[1]);
2295
2296         memset(&close_iov, 0, sizeof(close_iov));
2297         rqst[2].rq_iov = close_iov;
2298         rqst[2].rq_nvec = 1;
2299
2300         rc = SMB2_close_init(tcon, &rqst[2], COMPOUND_FID, COMPOUND_FID, false);
2301         if (rc)
2302                 goto qic_exit;
2303         smb2_set_related(&rqst[2]);
2304
2305         rc = compound_send_recv(xid, ses, flags, 3, rqst,
2306                                 resp_buftype, rsp_iov);
2307         if (rc) {
2308                 free_rsp_buf(resp_buftype[1], rsp_iov[1].iov_base);
2309                 if (rc == -EREMCHG) {
2310                         tcon->need_reconnect = true;
2311                         printk_once(KERN_WARNING "server share %s deleted\n",
2312                                     tcon->treeName);
2313                 }
2314                 goto qic_exit;
2315         }
2316         *rsp = rsp_iov[1];
2317         *buftype = resp_buftype[1];
2318
2319  qic_exit:
2320         SMB2_open_free(&rqst[0]);
2321         SMB2_query_info_free(&rqst[1]);
2322         SMB2_close_free(&rqst[2]);
2323         free_rsp_buf(resp_buftype[0], rsp_iov[0].iov_base);
2324         free_rsp_buf(resp_buftype[2], rsp_iov[2].iov_base);
2325         return rc;
2326 }
2327
2328 static int
2329 smb2_queryfs(const unsigned int xid, struct cifs_tcon *tcon,
2330              struct kstatfs *buf)
2331 {
2332         struct smb2_query_info_rsp *rsp;
2333         struct smb2_fs_full_size_info *info = NULL;
2334         __le16 utf16_path = 0; /* Null - open root of share */
2335         struct kvec rsp_iov = {NULL, 0};
2336         int buftype = CIFS_NO_BUFFER;
2337         int rc;
2338
2339
2340         rc = smb2_query_info_compound(xid, tcon, &utf16_path,
2341                                       FILE_READ_ATTRIBUTES,
2342                                       FS_FULL_SIZE_INFORMATION,
2343                                       SMB2_O_INFO_FILESYSTEM,
2344                                       sizeof(struct smb2_fs_full_size_info),
2345                                       &rsp_iov, &buftype, NULL);
2346         if (rc)
2347                 goto qfs_exit;
2348
2349         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
2350         buf->f_type = SMB2_MAGIC_NUMBER;
2351         info = (struct smb2_fs_full_size_info *)(
2352                 le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
2353         rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
2354                                le32_to_cpu(rsp->OutputBufferLength),
2355                                &rsp_iov,
2356                                sizeof(struct smb2_fs_full_size_info));
2357         if (!rc)
2358                 smb2_copy_fs_info_to_kstatfs(info, buf);
2359
2360 qfs_exit:
2361         free_rsp_buf(buftype, rsp_iov.iov_base);
2362         return rc;
2363 }
2364
2365 static int
2366 smb311_queryfs(const unsigned int xid, struct cifs_tcon *tcon,
2367              struct kstatfs *buf)
2368 {
2369         int rc;
2370         __le16 srch_path = 0; /* Null - open root of share */
2371         u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
2372         struct cifs_open_parms oparms;
2373         struct cifs_fid fid;
2374
2375         if (!tcon->posix_extensions)
2376                 return smb2_queryfs(xid, tcon, buf);
2377
2378         oparms.tcon = tcon;
2379         oparms.desired_access = FILE_READ_ATTRIBUTES;
2380         oparms.disposition = FILE_OPEN;
2381         oparms.create_options = 0;
2382         oparms.fid = &fid;
2383         oparms.reconnect = false;
2384
2385         rc = SMB2_open(xid, &oparms, &srch_path, &oplock, NULL, NULL, NULL);
2386         if (rc)
2387                 return rc;
2388
2389         rc = SMB311_posix_qfs_info(xid, tcon, fid.persistent_fid,
2390                                    fid.volatile_fid, buf);
2391         buf->f_type = SMB2_MAGIC_NUMBER;
2392         SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
2393         return rc;
2394 }
2395
2396 static bool
2397 smb2_compare_fids(struct cifsFileInfo *ob1, struct cifsFileInfo *ob2)
2398 {
2399         return ob1->fid.persistent_fid == ob2->fid.persistent_fid &&
2400                ob1->fid.volatile_fid == ob2->fid.volatile_fid;
2401 }
2402
2403 static int
2404 smb2_mand_lock(const unsigned int xid, struct cifsFileInfo *cfile, __u64 offset,
2405                __u64 length, __u32 type, int lock, int unlock, bool wait)
2406 {
2407         if (unlock && !lock)
2408                 type = SMB2_LOCKFLAG_UNLOCK;
2409         return SMB2_lock(xid, tlink_tcon(cfile->tlink),
2410                          cfile->fid.persistent_fid, cfile->fid.volatile_fid,
2411                          current->tgid, length, offset, type, wait);
2412 }
2413
2414 static void
2415 smb2_get_lease_key(struct inode *inode, struct cifs_fid *fid)
2416 {
2417         memcpy(fid->lease_key, CIFS_I(inode)->lease_key, SMB2_LEASE_KEY_SIZE);
2418 }
2419
2420 static void
2421 smb2_set_lease_key(struct inode *inode, struct cifs_fid *fid)
2422 {
2423         memcpy(CIFS_I(inode)->lease_key, fid->lease_key, SMB2_LEASE_KEY_SIZE);
2424 }
2425
2426 static void
2427 smb2_new_lease_key(struct cifs_fid *fid)
2428 {
2429         generate_random_uuid(fid->lease_key);
2430 }
2431
2432 static int
2433 smb2_get_dfs_refer(const unsigned int xid, struct cifs_ses *ses,
2434                    const char *search_name,
2435                    struct dfs_info3_param **target_nodes,
2436                    unsigned int *num_of_nodes,
2437                    const struct nls_table *nls_codepage, int remap)
2438 {
2439         int rc;
2440         __le16 *utf16_path = NULL;
2441         int utf16_path_len = 0;
2442         struct cifs_tcon *tcon;
2443         struct fsctl_get_dfs_referral_req *dfs_req = NULL;
2444         struct get_dfs_referral_rsp *dfs_rsp = NULL;
2445         u32 dfs_req_size = 0, dfs_rsp_size = 0;
2446
2447         cifs_dbg(FYI, "%s: path: %s\n", __func__, search_name);
2448
2449         /*
2450          * Try to use the IPC tcon, otherwise just use any
2451          */
2452         tcon = ses->tcon_ipc;
2453         if (tcon == NULL) {
2454                 spin_lock(&cifs_tcp_ses_lock);
2455                 tcon = list_first_entry_or_null(&ses->tcon_list,
2456                                                 struct cifs_tcon,
2457                                                 tcon_list);
2458                 if (tcon)
2459                         tcon->tc_count++;
2460                 spin_unlock(&cifs_tcp_ses_lock);
2461         }
2462
2463         if (tcon == NULL) {
2464                 cifs_dbg(VFS, "session %p has no tcon available for a dfs referral request\n",
2465                          ses);
2466                 rc = -ENOTCONN;
2467                 goto out;
2468         }
2469
2470         utf16_path = cifs_strndup_to_utf16(search_name, PATH_MAX,
2471                                            &utf16_path_len,
2472                                            nls_codepage, remap);
2473         if (!utf16_path) {
2474                 rc = -ENOMEM;
2475                 goto out;
2476         }
2477
2478         dfs_req_size = sizeof(*dfs_req) + utf16_path_len;
2479         dfs_req = kzalloc(dfs_req_size, GFP_KERNEL);
2480         if (!dfs_req) {
2481                 rc = -ENOMEM;
2482                 goto out;
2483         }
2484
2485         /* Highest DFS referral version understood */
2486         dfs_req->MaxReferralLevel = DFS_VERSION;
2487
2488         /* Path to resolve in an UTF-16 null-terminated string */
2489         memcpy(dfs_req->RequestFileName, utf16_path, utf16_path_len);
2490
2491         do {
2492                 rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
2493                                 FSCTL_DFS_GET_REFERRALS,
2494                                 true /* is_fsctl */,
2495                                 (char *)dfs_req, dfs_req_size, CIFSMaxBufSize,
2496                                 (char **)&dfs_rsp, &dfs_rsp_size);
2497         } while (rc == -EAGAIN);
2498
2499         if (rc) {
2500                 if ((rc != -ENOENT) && (rc != -EOPNOTSUPP))
2501                         cifs_tcon_dbg(VFS, "ioctl error in %s rc=%d\n", __func__, rc);
2502                 goto out;
2503         }
2504
2505         rc = parse_dfs_referrals(dfs_rsp, dfs_rsp_size,
2506                                  num_of_nodes, target_nodes,
2507                                  nls_codepage, remap, search_name,
2508                                  true /* is_unicode */);
2509         if (rc) {
2510                 cifs_tcon_dbg(VFS, "parse error in %s rc=%d\n", __func__, rc);
2511                 goto out;
2512         }
2513
2514  out:
2515         if (tcon && !tcon->ipc) {
2516                 /* ipc tcons are not refcounted */
2517                 spin_lock(&cifs_tcp_ses_lock);
2518                 tcon->tc_count--;
2519                 spin_unlock(&cifs_tcp_ses_lock);
2520         }
2521         kfree(utf16_path);
2522         kfree(dfs_req);
2523         kfree(dfs_rsp);
2524         return rc;
2525 }
2526
2527 static int
2528 parse_reparse_posix(struct reparse_posix_data *symlink_buf,
2529                       u32 plen, char **target_path,
2530                       struct cifs_sb_info *cifs_sb)
2531 {
2532         unsigned int len;
2533
2534         /* See MS-FSCC 2.1.2.6 for the 'NFS' style reparse tags */
2535         len = le16_to_cpu(symlink_buf->ReparseDataLength);
2536
2537         if (le64_to_cpu(symlink_buf->InodeType) != NFS_SPECFILE_LNK) {
2538                 cifs_dbg(VFS, "%lld not a supported symlink type\n",
2539                         le64_to_cpu(symlink_buf->InodeType));
2540                 return -EOPNOTSUPP;
2541         }
2542
2543         *target_path = cifs_strndup_from_utf16(
2544                                 symlink_buf->PathBuffer,
2545                                 len, true, cifs_sb->local_nls);
2546         if (!(*target_path))
2547                 return -ENOMEM;
2548
2549         convert_delimiter(*target_path, '/');
2550         cifs_dbg(FYI, "%s: target path: %s\n", __func__, *target_path);
2551
2552         return 0;
2553 }
2554
2555 static int
2556 parse_reparse_symlink(struct reparse_symlink_data_buffer *symlink_buf,
2557                       u32 plen, char **target_path,
2558                       struct cifs_sb_info *cifs_sb)
2559 {
2560         unsigned int sub_len;
2561         unsigned int sub_offset;
2562
2563         /* We handle Symbolic Link reparse tag here. See: MS-FSCC 2.1.2.4 */
2564
2565         sub_offset = le16_to_cpu(symlink_buf->SubstituteNameOffset);
2566         sub_len = le16_to_cpu(symlink_buf->SubstituteNameLength);
2567         if (sub_offset + 20 > plen ||
2568             sub_offset + sub_len + 20 > plen) {
2569                 cifs_dbg(VFS, "srv returned malformed symlink buffer\n");
2570                 return -EIO;
2571         }
2572
2573         *target_path = cifs_strndup_from_utf16(
2574                                 symlink_buf->PathBuffer + sub_offset,
2575                                 sub_len, true, cifs_sb->local_nls);
2576         if (!(*target_path))
2577                 return -ENOMEM;
2578
2579         convert_delimiter(*target_path, '/');
2580         cifs_dbg(FYI, "%s: target path: %s\n", __func__, *target_path);
2581
2582         return 0;
2583 }
2584
2585 static int
2586 parse_reparse_point(struct reparse_data_buffer *buf,
2587                     u32 plen, char **target_path,
2588                     struct cifs_sb_info *cifs_sb)
2589 {
2590         if (plen < sizeof(struct reparse_data_buffer)) {
2591                 cifs_dbg(VFS, "reparse buffer is too small. Must be "
2592                          "at least 8 bytes but was %d\n", plen);
2593                 return -EIO;
2594         }
2595
2596         if (plen < le16_to_cpu(buf->ReparseDataLength) +
2597             sizeof(struct reparse_data_buffer)) {
2598                 cifs_dbg(VFS, "srv returned invalid reparse buf "
2599                          "length: %d\n", plen);
2600                 return -EIO;
2601         }
2602
2603         /* See MS-FSCC 2.1.2 */
2604         switch (le32_to_cpu(buf->ReparseTag)) {
2605         case IO_REPARSE_TAG_NFS:
2606                 return parse_reparse_posix(
2607                         (struct reparse_posix_data *)buf,
2608                         plen, target_path, cifs_sb);
2609         case IO_REPARSE_TAG_SYMLINK:
2610                 return parse_reparse_symlink(
2611                         (struct reparse_symlink_data_buffer *)buf,
2612                         plen, target_path, cifs_sb);
2613         default:
2614                 cifs_dbg(VFS, "srv returned unknown symlink buffer "
2615                          "tag:0x%08x\n", le32_to_cpu(buf->ReparseTag));
2616                 return -EOPNOTSUPP;
2617         }
2618 }
2619
2620 #define SMB2_SYMLINK_STRUCT_SIZE \
2621         (sizeof(struct smb2_err_rsp) - 1 + sizeof(struct smb2_symlink_err_rsp))
2622
2623 static int
2624 smb2_query_symlink(const unsigned int xid, struct cifs_tcon *tcon,
2625                    struct cifs_sb_info *cifs_sb, const char *full_path,
2626                    char **target_path, bool is_reparse_point)
2627 {
2628         int rc;
2629         __le16 *utf16_path = NULL;
2630         __u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
2631         struct cifs_open_parms oparms;
2632         struct cifs_fid fid;
2633         struct kvec err_iov = {NULL, 0};
2634         struct smb2_err_rsp *err_buf = NULL;
2635         struct smb2_symlink_err_rsp *symlink;
2636         unsigned int sub_len;
2637         unsigned int sub_offset;
2638         unsigned int print_len;
2639         unsigned int print_offset;
2640         int flags = 0;
2641         struct smb_rqst rqst[3];
2642         int resp_buftype[3];
2643         struct kvec rsp_iov[3];
2644         struct kvec open_iov[SMB2_CREATE_IOV_SIZE];
2645         struct kvec io_iov[SMB2_IOCTL_IOV_SIZE];
2646         struct kvec close_iov[1];
2647         struct smb2_create_rsp *create_rsp;
2648         struct smb2_ioctl_rsp *ioctl_rsp;
2649         struct reparse_data_buffer *reparse_buf;
2650         u32 plen;
2651
2652         cifs_dbg(FYI, "%s: path: %s\n", __func__, full_path);
2653
2654         *target_path = NULL;
2655
2656         if (smb3_encryption_required(tcon))
2657                 flags |= CIFS_TRANSFORM_REQ;
2658
2659         memset(rqst, 0, sizeof(rqst));
2660         resp_buftype[0] = resp_buftype[1] = resp_buftype[2] = CIFS_NO_BUFFER;
2661         memset(rsp_iov, 0, sizeof(rsp_iov));
2662
2663         utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
2664         if (!utf16_path)
2665                 return -ENOMEM;
2666
2667         /* Open */
2668         memset(&open_iov, 0, sizeof(open_iov));
2669         rqst[0].rq_iov = open_iov;
2670         rqst[0].rq_nvec = SMB2_CREATE_IOV_SIZE;
2671
2672         memset(&oparms, 0, sizeof(oparms));
2673         oparms.tcon = tcon;
2674         oparms.desired_access = FILE_READ_ATTRIBUTES;
2675         oparms.disposition = FILE_OPEN;
2676
2677         if (backup_cred(cifs_sb))
2678                 oparms.create_options = CREATE_OPEN_BACKUP_INTENT;
2679         else
2680                 oparms.create_options = 0;
2681         if (is_reparse_point)
2682                 oparms.create_options = OPEN_REPARSE_POINT;
2683
2684         oparms.fid = &fid;
2685         oparms.reconnect = false;
2686
2687         rc = SMB2_open_init(tcon, &rqst[0], &oplock, &oparms, utf16_path);
2688         if (rc)
2689                 goto querty_exit;
2690         smb2_set_next_command(tcon, &rqst[0]);
2691
2692
2693         /* IOCTL */
2694         memset(&io_iov, 0, sizeof(io_iov));
2695         rqst[1].rq_iov = io_iov;
2696         rqst[1].rq_nvec = SMB2_IOCTL_IOV_SIZE;
2697
2698         rc = SMB2_ioctl_init(tcon, &rqst[1], fid.persistent_fid,
2699                              fid.volatile_fid, FSCTL_GET_REPARSE_POINT,
2700                              true /* is_fctl */, NULL, 0, CIFSMaxBufSize);
2701         if (rc)
2702                 goto querty_exit;
2703
2704         smb2_set_next_command(tcon, &rqst[1]);
2705         smb2_set_related(&rqst[1]);
2706
2707
2708         /* Close */
2709         memset(&close_iov, 0, sizeof(close_iov));
2710         rqst[2].rq_iov = close_iov;
2711         rqst[2].rq_nvec = 1;
2712
2713         rc = SMB2_close_init(tcon, &rqst[2], COMPOUND_FID, COMPOUND_FID, false);
2714         if (rc)
2715                 goto querty_exit;
2716
2717         smb2_set_related(&rqst[2]);
2718
2719         rc = compound_send_recv(xid, tcon->ses, flags, 3, rqst,
2720                                 resp_buftype, rsp_iov);
2721
2722         create_rsp = rsp_iov[0].iov_base;
2723         if (create_rsp && create_rsp->sync_hdr.Status)
2724                 err_iov = rsp_iov[0];
2725         ioctl_rsp = rsp_iov[1].iov_base;
2726
2727         /*
2728          * Open was successful and we got an ioctl response.
2729          */
2730         if ((rc == 0) && (is_reparse_point)) {
2731                 /* See MS-FSCC 2.3.23 */
2732
2733                 reparse_buf = (struct reparse_data_buffer *)
2734                         ((char *)ioctl_rsp +
2735                          le32_to_cpu(ioctl_rsp->OutputOffset));
2736                 plen = le32_to_cpu(ioctl_rsp->OutputCount);
2737
2738                 if (plen + le32_to_cpu(ioctl_rsp->OutputOffset) >
2739                     rsp_iov[1].iov_len) {
2740                         cifs_tcon_dbg(VFS, "srv returned invalid ioctl len: %d\n",
2741                                  plen);
2742                         rc = -EIO;
2743                         goto querty_exit;
2744                 }
2745
2746                 rc = parse_reparse_point(reparse_buf, plen, target_path,
2747                                          cifs_sb);
2748                 goto querty_exit;
2749         }
2750
2751         if (!rc || !err_iov.iov_base) {
2752                 rc = -ENOENT;
2753                 goto querty_exit;
2754         }
2755
2756         err_buf = err_iov.iov_base;
2757         if (le32_to_cpu(err_buf->ByteCount) < sizeof(struct smb2_symlink_err_rsp) ||
2758             err_iov.iov_len < SMB2_SYMLINK_STRUCT_SIZE) {
2759                 rc = -EINVAL;
2760                 goto querty_exit;
2761         }
2762
2763         symlink = (struct smb2_symlink_err_rsp *)err_buf->ErrorData;
2764         if (le32_to_cpu(symlink->SymLinkErrorTag) != SYMLINK_ERROR_TAG ||
2765             le32_to_cpu(symlink->ReparseTag) != IO_REPARSE_TAG_SYMLINK) {
2766                 rc = -EINVAL;
2767                 goto querty_exit;
2768         }
2769
2770         /* open must fail on symlink - reset rc */
2771         rc = 0;
2772         sub_len = le16_to_cpu(symlink->SubstituteNameLength);
2773         sub_offset = le16_to_cpu(symlink->SubstituteNameOffset);
2774         print_len = le16_to_cpu(symlink->PrintNameLength);
2775         print_offset = le16_to_cpu(symlink->PrintNameOffset);
2776
2777         if (err_iov.iov_len < SMB2_SYMLINK_STRUCT_SIZE + sub_offset + sub_len) {
2778                 rc = -EINVAL;
2779                 goto querty_exit;
2780         }
2781
2782         if (err_iov.iov_len <
2783             SMB2_SYMLINK_STRUCT_SIZE + print_offset + print_len) {
2784                 rc = -EINVAL;
2785                 goto querty_exit;
2786         }
2787
2788         *target_path = cifs_strndup_from_utf16(
2789                                 (char *)symlink->PathBuffer + sub_offset,
2790                                 sub_len, true, cifs_sb->local_nls);
2791         if (!(*target_path)) {
2792                 rc = -ENOMEM;
2793                 goto querty_exit;
2794         }
2795         convert_delimiter(*target_path, '/');
2796         cifs_dbg(FYI, "%s: target path: %s\n", __func__, *target_path);
2797
2798  querty_exit:
2799         cifs_dbg(FYI, "query symlink rc %d\n", rc);
2800         kfree(utf16_path);
2801         SMB2_open_free(&rqst[0]);
2802         SMB2_ioctl_free(&rqst[1]);
2803         SMB2_close_free(&rqst[2]);
2804         free_rsp_buf(resp_buftype[0], rsp_iov[0].iov_base);
2805         free_rsp_buf(resp_buftype[1], rsp_iov[1].iov_base);
2806         free_rsp_buf(resp_buftype[2], rsp_iov[2].iov_base);
2807         return rc;
2808 }
2809
2810 static struct cifs_ntsd *
2811 get_smb2_acl_by_fid(struct cifs_sb_info *cifs_sb,
2812                 const struct cifs_fid *cifsfid, u32 *pacllen)
2813 {
2814         struct cifs_ntsd *pntsd = NULL;
2815         unsigned int xid;
2816         int rc = -EOPNOTSUPP;
2817         struct tcon_link *tlink = cifs_sb_tlink(cifs_sb);
2818
2819         if (IS_ERR(tlink))
2820                 return ERR_CAST(tlink);
2821
2822         xid = get_xid();
2823         cifs_dbg(FYI, "trying to get acl\n");
2824
2825         rc = SMB2_query_acl(xid, tlink_tcon(tlink), cifsfid->persistent_fid,
2826                             cifsfid->volatile_fid, (void **)&pntsd, pacllen);
2827         free_xid(xid);
2828
2829         cifs_put_tlink(tlink);
2830
2831         cifs_dbg(FYI, "%s: rc = %d ACL len %d\n", __func__, rc, *pacllen);
2832         if (rc)
2833                 return ERR_PTR(rc);
2834         return pntsd;
2835
2836 }
2837
2838 static struct cifs_ntsd *
2839 get_smb2_acl_by_path(struct cifs_sb_info *cifs_sb,
2840                 const char *path, u32 *pacllen)
2841 {
2842         struct cifs_ntsd *pntsd = NULL;
2843         u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
2844         unsigned int xid;
2845         int rc;
2846         struct cifs_tcon *tcon;
2847         struct tcon_link *tlink = cifs_sb_tlink(cifs_sb);
2848         struct cifs_fid fid;
2849         struct cifs_open_parms oparms;
2850         __le16 *utf16_path;
2851
2852         cifs_dbg(FYI, "get smb3 acl for path %s\n", path);
2853         if (IS_ERR(tlink))
2854                 return ERR_CAST(tlink);
2855
2856         tcon = tlink_tcon(tlink);
2857         xid = get_xid();
2858
2859         if (backup_cred(cifs_sb))
2860                 oparms.create_options = CREATE_OPEN_BACKUP_INTENT;
2861         else
2862                 oparms.create_options = 0;
2863
2864         utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
2865         if (!utf16_path) {
2866                 rc = -ENOMEM;
2867                 free_xid(xid);
2868                 return ERR_PTR(rc);
2869         }
2870
2871         oparms.tcon = tcon;
2872         oparms.desired_access = READ_CONTROL;
2873         oparms.disposition = FILE_OPEN;
2874         oparms.fid = &fid;
2875         oparms.reconnect = false;
2876
2877         rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, NULL, NULL);
2878         kfree(utf16_path);
2879         if (!rc) {
2880                 rc = SMB2_query_acl(xid, tlink_tcon(tlink), fid.persistent_fid,
2881                             fid.volatile_fid, (void **)&pntsd, pacllen);
2882                 SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
2883         }
2884
2885         cifs_put_tlink(tlink);
2886         free_xid(xid);
2887
2888         cifs_dbg(FYI, "%s: rc = %d ACL len %d\n", __func__, rc, *pacllen);
2889         if (rc)
2890                 return ERR_PTR(rc);
2891         return pntsd;
2892 }
2893
2894 static int
2895 set_smb2_acl(struct cifs_ntsd *pnntsd, __u32 acllen,
2896                 struct inode *inode, const char *path, int aclflag)
2897 {
2898         u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
2899         unsigned int xid;
2900         int rc, access_flags = 0;
2901         struct cifs_tcon *tcon;
2902         struct cifs_sb_info *cifs_sb = CIFS_SB(inode->i_sb);
2903         struct tcon_link *tlink = cifs_sb_tlink(cifs_sb);
2904         struct cifs_fid fid;
2905         struct cifs_open_parms oparms;
2906         __le16 *utf16_path;
2907
2908         cifs_dbg(FYI, "set smb3 acl for path %s\n", path);
2909         if (IS_ERR(tlink))
2910                 return PTR_ERR(tlink);
2911
2912         tcon = tlink_tcon(tlink);
2913         xid = get_xid();
2914
2915         if (backup_cred(cifs_sb))
2916                 oparms.create_options = CREATE_OPEN_BACKUP_INTENT;
2917         else
2918                 oparms.create_options = 0;
2919
2920         if (aclflag == CIFS_ACL_OWNER || aclflag == CIFS_ACL_GROUP)
2921                 access_flags = WRITE_OWNER;
2922         else
2923                 access_flags = WRITE_DAC;
2924
2925         utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
2926         if (!utf16_path) {
2927                 rc = -ENOMEM;
2928                 free_xid(xid);
2929                 return rc;
2930         }
2931
2932         oparms.tcon = tcon;
2933         oparms.desired_access = access_flags;
2934         oparms.disposition = FILE_OPEN;
2935         oparms.path = path;
2936         oparms.fid = &fid;
2937         oparms.reconnect = false;
2938
2939         rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, NULL, NULL);
2940         kfree(utf16_path);
2941         if (!rc) {
2942                 rc = SMB2_set_acl(xid, tlink_tcon(tlink), fid.persistent_fid,
2943                             fid.volatile_fid, pnntsd, acllen, aclflag);
2944                 SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
2945         }
2946
2947         cifs_put_tlink(tlink);
2948         free_xid(xid);
2949         return rc;
2950 }
2951
2952 /* Retrieve an ACL from the server */
2953 static struct cifs_ntsd *
2954 get_smb2_acl(struct cifs_sb_info *cifs_sb,
2955                                       struct inode *inode, const char *path,
2956                                       u32 *pacllen)
2957 {
2958         struct cifs_ntsd *pntsd = NULL;
2959         struct cifsFileInfo *open_file = NULL;
2960
2961         if (inode)
2962                 open_file = find_readable_file(CIFS_I(inode), true);
2963         if (!open_file)
2964                 return get_smb2_acl_by_path(cifs_sb, path, pacllen);
2965
2966         pntsd = get_smb2_acl_by_fid(cifs_sb, &open_file->fid, pacllen);
2967         cifsFileInfo_put(open_file);
2968         return pntsd;
2969 }
2970
2971 static long smb3_zero_range(struct file *file, struct cifs_tcon *tcon,
2972                             loff_t offset, loff_t len, bool keep_size)
2973 {
2974         struct cifs_ses *ses = tcon->ses;
2975         struct inode *inode;
2976         struct cifsInodeInfo *cifsi;
2977         struct cifsFileInfo *cfile = file->private_data;
2978         struct file_zero_data_information fsctl_buf;
2979         long rc;
2980         unsigned int xid;
2981         __le64 eof;
2982
2983         xid = get_xid();
2984
2985         inode = d_inode(cfile->dentry);
2986         cifsi = CIFS_I(inode);
2987
2988         trace_smb3_zero_enter(xid, cfile->fid.persistent_fid, tcon->tid,
2989                               ses->Suid, offset, len);
2990
2991
2992         /* if file not oplocked can't be sure whether asking to extend size */
2993         if (!CIFS_CACHE_READ(cifsi))
2994                 if (keep_size == false) {
2995                         rc = -EOPNOTSUPP;
2996                         trace_smb3_zero_err(xid, cfile->fid.persistent_fid,
2997                                 tcon->tid, ses->Suid, offset, len, rc);
2998                         free_xid(xid);
2999                         return rc;
3000                 }
3001
3002         cifs_dbg(FYI, "Offset %lld len %lld\n", offset, len);
3003
3004         fsctl_buf.FileOffset = cpu_to_le64(offset);
3005         fsctl_buf.BeyondFinalZero = cpu_to_le64(offset + len);
3006
3007         rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
3008                         cfile->fid.volatile_fid, FSCTL_SET_ZERO_DATA, true,
3009                         (char *)&fsctl_buf,
3010                         sizeof(struct file_zero_data_information),
3011                         0, NULL, NULL);
3012         if (rc)
3013                 goto zero_range_exit;
3014
3015         /*
3016          * do we also need to change the size of the file?
3017          */
3018         if (keep_size == false && i_size_read(inode) < offset + len) {
3019                 eof = cpu_to_le64(offset + len);
3020                 rc = SMB2_set_eof(xid, tcon, cfile->fid.persistent_fid,
3021                                   cfile->fid.volatile_fid, cfile->pid, &eof);
3022         }
3023
3024  zero_range_exit:
3025         free_xid(xid);
3026         if (rc)
3027                 trace_smb3_zero_err(xid, cfile->fid.persistent_fid, tcon->tid,
3028                               ses->Suid, offset, len, rc);
3029         else
3030                 trace_smb3_zero_done(xid, cfile->fid.persistent_fid, tcon->tid,
3031                               ses->Suid, offset, len);
3032         return rc;
3033 }
3034
3035 static long smb3_punch_hole(struct file *file, struct cifs_tcon *tcon,
3036                             loff_t offset, loff_t len)
3037 {
3038         struct inode *inode;
3039         struct cifsFileInfo *cfile = file->private_data;
3040         struct file_zero_data_information fsctl_buf;
3041         long rc;
3042         unsigned int xid;
3043         __u8 set_sparse = 1;
3044
3045         xid = get_xid();
3046
3047         inode = d_inode(cfile->dentry);
3048
3049         /* Need to make file sparse, if not already, before freeing range. */
3050         /* Consider adding equivalent for compressed since it could also work */
3051         if (!smb2_set_sparse(xid, tcon, cfile, inode, set_sparse)) {
3052                 rc = -EOPNOTSUPP;
3053                 free_xid(xid);
3054                 return rc;
3055         }
3056
3057         cifs_dbg(FYI, "Offset %lld len %lld\n", offset, len);
3058
3059         fsctl_buf.FileOffset = cpu_to_le64(offset);
3060         fsctl_buf.BeyondFinalZero = cpu_to_le64(offset + len);
3061
3062         rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
3063                         cfile->fid.volatile_fid, FSCTL_SET_ZERO_DATA,
3064                         true /* is_fctl */, (char *)&fsctl_buf,
3065                         sizeof(struct file_zero_data_information),
3066                         CIFSMaxBufSize, NULL, NULL);
3067         free_xid(xid);
3068         return rc;
3069 }
3070
3071 static long smb3_simple_falloc(struct file *file, struct cifs_tcon *tcon,
3072                             loff_t off, loff_t len, bool keep_size)
3073 {
3074         struct inode *inode;
3075         struct cifsInodeInfo *cifsi;
3076         struct cifsFileInfo *cfile = file->private_data;
3077         long rc = -EOPNOTSUPP;
3078         unsigned int xid;
3079         __le64 eof;
3080
3081         xid = get_xid();
3082
3083         inode = d_inode(cfile->dentry);
3084         cifsi = CIFS_I(inode);
3085
3086         trace_smb3_falloc_enter(xid, cfile->fid.persistent_fid, tcon->tid,
3087                                 tcon->ses->Suid, off, len);
3088         /* if file not oplocked can't be sure whether asking to extend size */
3089         if (!CIFS_CACHE_READ(cifsi))
3090                 if (keep_size == false) {
3091                         trace_smb3_falloc_err(xid, cfile->fid.persistent_fid,
3092                                 tcon->tid, tcon->ses->Suid, off, len, rc);
3093                         free_xid(xid);
3094                         return rc;
3095                 }
3096
3097         /*
3098          * Files are non-sparse by default so falloc may be a no-op
3099          * Must check if file sparse. If not sparse, and not extending
3100          * then no need to do anything since file already allocated
3101          */
3102         if ((cifsi->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE) == 0) {
3103                 if (keep_size == true)
3104                         rc = 0;
3105                 /* check if extending file */
3106                 else if (i_size_read(inode) >= off + len)
3107                         /* not extending file and already not sparse */
3108                         rc = 0;
3109                 /* BB: in future add else clause to extend file */
3110                 else
3111                         rc = -EOPNOTSUPP;
3112                 if (rc)
3113                         trace_smb3_falloc_err(xid, cfile->fid.persistent_fid,
3114                                 tcon->tid, tcon->ses->Suid, off, len, rc);
3115                 else
3116                         trace_smb3_falloc_done(xid, cfile->fid.persistent_fid,
3117                                 tcon->tid, tcon->ses->Suid, off, len);
3118                 free_xid(xid);
3119                 return rc;
3120         }
3121
3122         if ((keep_size == true) || (i_size_read(inode) >= off + len)) {
3123                 /*
3124                  * Check if falloc starts within first few pages of file
3125                  * and ends within a few pages of the end of file to
3126                  * ensure that most of file is being forced to be
3127                  * fallocated now. If so then setting whole file sparse
3128                  * ie potentially making a few extra pages at the beginning
3129                  * or end of the file non-sparse via set_sparse is harmless.
3130                  */
3131                 if ((off > 8192) || (off + len + 8192 < i_size_read(inode))) {
3132                         rc = -EOPNOTSUPP;
3133                         trace_smb3_falloc_err(xid, cfile->fid.persistent_fid,
3134                                 tcon->tid, tcon->ses->Suid, off, len, rc);
3135                         free_xid(xid);
3136                         return rc;
3137                 }
3138
3139                 smb2_set_sparse(xid, tcon, cfile, inode, false);
3140                 rc = 0;
3141         } else {
3142                 smb2_set_sparse(xid, tcon, cfile, inode, false);
3143                 rc = 0;
3144                 if (i_size_read(inode) < off + len) {
3145                         eof = cpu_to_le64(off + len);
3146                         rc = SMB2_set_eof(xid, tcon, cfile->fid.persistent_fid,
3147                                           cfile->fid.volatile_fid, cfile->pid,
3148                                           &eof);
3149                 }
3150         }
3151
3152         if (rc)
3153                 trace_smb3_falloc_err(xid, cfile->fid.persistent_fid, tcon->tid,
3154                                 tcon->ses->Suid, off, len, rc);
3155         else
3156                 trace_smb3_falloc_done(xid, cfile->fid.persistent_fid, tcon->tid,
3157                                 tcon->ses->Suid, off, len);
3158
3159         free_xid(xid);
3160         return rc;
3161 }
3162
3163 static loff_t smb3_llseek(struct file *file, struct cifs_tcon *tcon, loff_t offset, int whence)
3164 {
3165         struct cifsFileInfo *wrcfile, *cfile = file->private_data;
3166         struct cifsInodeInfo *cifsi;
3167         struct inode *inode;
3168         int rc = 0;
3169         struct file_allocated_range_buffer in_data, *out_data = NULL;
3170         u32 out_data_len;
3171         unsigned int xid;
3172
3173         if (whence != SEEK_HOLE && whence != SEEK_DATA)
3174                 return generic_file_llseek(file, offset, whence);
3175
3176         inode = d_inode(cfile->dentry);
3177         cifsi = CIFS_I(inode);
3178
3179         if (offset < 0 || offset >= i_size_read(inode))
3180                 return -ENXIO;
3181
3182         xid = get_xid();
3183         /*
3184          * We need to be sure that all dirty pages are written as they
3185          * might fill holes on the server.
3186          * Note that we also MUST flush any written pages since at least
3187          * some servers (Windows2016) will not reflect recent writes in
3188          * QUERY_ALLOCATED_RANGES until SMB2_flush is called.
3189          */
3190         wrcfile = find_writable_file(cifsi, false);
3191         if (wrcfile) {
3192                 filemap_write_and_wait(inode->i_mapping);
3193                 smb2_flush_file(xid, tcon, &wrcfile->fid);
3194                 cifsFileInfo_put(wrcfile);
3195         }
3196
3197         if (!(cifsi->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE)) {
3198                 if (whence == SEEK_HOLE)
3199                         offset = i_size_read(inode);
3200                 goto lseek_exit;
3201         }
3202
3203         in_data.file_offset = cpu_to_le64(offset);
3204         in_data.length = cpu_to_le64(i_size_read(inode));
3205
3206         rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
3207                         cfile->fid.volatile_fid,
3208                         FSCTL_QUERY_ALLOCATED_RANGES, true,
3209                         (char *)&in_data, sizeof(in_data),
3210                         sizeof(struct file_allocated_range_buffer),
3211                         (char **)&out_data, &out_data_len);
3212         if (rc == -E2BIG)
3213                 rc = 0;
3214         if (rc)
3215                 goto lseek_exit;
3216
3217         if (whence == SEEK_HOLE && out_data_len == 0)
3218                 goto lseek_exit;
3219
3220         if (whence == SEEK_DATA && out_data_len == 0) {
3221                 rc = -ENXIO;
3222                 goto lseek_exit;
3223         }
3224
3225         if (out_data_len < sizeof(struct file_allocated_range_buffer)) {
3226                 rc = -EINVAL;
3227                 goto lseek_exit;
3228         }
3229         if (whence == SEEK_DATA) {
3230                 offset = le64_to_cpu(out_data->file_offset);
3231                 goto lseek_exit;
3232         }
3233         if (offset < le64_to_cpu(out_data->file_offset))
3234                 goto lseek_exit;
3235
3236         offset = le64_to_cpu(out_data->file_offset) + le64_to_cpu(out_data->length);
3237
3238  lseek_exit:
3239         free_xid(xid);
3240         kfree(out_data);
3241         if (!rc)
3242                 return vfs_setpos(file, offset, inode->i_sb->s_maxbytes);
3243         else
3244                 return rc;
3245 }
3246
3247 static int smb3_fiemap(struct cifs_tcon *tcon,
3248                        struct cifsFileInfo *cfile,
3249                        struct fiemap_extent_info *fei, u64 start, u64 len)
3250 {
3251         unsigned int xid;
3252         struct file_allocated_range_buffer in_data, *out_data;
3253         u32 out_data_len;
3254         int i, num, rc, flags, last_blob;
3255         u64 next;
3256
3257         if (fiemap_check_flags(fei, FIEMAP_FLAG_SYNC))
3258                 return -EBADR;
3259
3260         xid = get_xid();
3261  again:
3262         in_data.file_offset = cpu_to_le64(start);
3263         in_data.length = cpu_to_le64(len);
3264
3265         rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
3266                         cfile->fid.volatile_fid,
3267                         FSCTL_QUERY_ALLOCATED_RANGES, true,
3268                         (char *)&in_data, sizeof(in_data),
3269                         1024 * sizeof(struct file_allocated_range_buffer),
3270                         (char **)&out_data, &out_data_len);
3271         if (rc == -E2BIG) {
3272                 last_blob = 0;
3273                 rc = 0;
3274         } else
3275                 last_blob = 1;
3276         if (rc)
3277                 goto out;
3278
3279         if (out_data_len < sizeof(struct file_allocated_range_buffer)) {
3280                 rc = -EINVAL;
3281                 goto out;
3282         }
3283         if (out_data_len % sizeof(struct file_allocated_range_buffer)) {
3284                 rc = -EINVAL;
3285                 goto out;
3286         }
3287
3288         num = out_data_len / sizeof(struct file_allocated_range_buffer);
3289         for (i = 0; i < num; i++) {
3290                 flags = 0;
3291                 if (i == num - 1 && last_blob)
3292                         flags |= FIEMAP_EXTENT_LAST;
3293
3294                 rc = fiemap_fill_next_extent(fei,
3295                                 le64_to_cpu(out_data[i].file_offset),
3296                                 le64_to_cpu(out_data[i].file_offset),
3297                                 le64_to_cpu(out_data[i].length),
3298                                 flags);
3299                 if (rc < 0)
3300                         goto out;
3301                 if (rc == 1) {
3302                         rc = 0;
3303                         goto out;
3304                 }
3305         }
3306
3307         if (!last_blob) {
3308                 next = le64_to_cpu(out_data[num - 1].file_offset) +
3309                   le64_to_cpu(out_data[num - 1].length);
3310                 len = len - (next - start);
3311                 start = next;
3312                 goto again;
3313         }
3314
3315  out:
3316         free_xid(xid);
3317         kfree(out_data);
3318         return rc;
3319 }
3320
3321 static long smb3_fallocate(struct file *file, struct cifs_tcon *tcon, int mode,
3322                            loff_t off, loff_t len)
3323 {
3324         /* KEEP_SIZE already checked for by do_fallocate */
3325         if (mode & FALLOC_FL_PUNCH_HOLE)
3326                 return smb3_punch_hole(file, tcon, off, len);
3327         else if (mode & FALLOC_FL_ZERO_RANGE) {
3328                 if (mode & FALLOC_FL_KEEP_SIZE)
3329                         return smb3_zero_range(file, tcon, off, len, true);
3330                 return smb3_zero_range(file, tcon, off, len, false);
3331         } else if (mode == FALLOC_FL_KEEP_SIZE)
3332                 return smb3_simple_falloc(file, tcon, off, len, true);
3333         else if (mode == 0)
3334                 return smb3_simple_falloc(file, tcon, off, len, false);
3335
3336         return -EOPNOTSUPP;
3337 }
3338
3339 static void
3340 smb2_downgrade_oplock(struct TCP_Server_Info *server,
3341                       struct cifsInodeInfo *cinode, __u32 oplock,
3342                       unsigned int epoch, bool *purge_cache)
3343 {
3344         server->ops->set_oplock_level(cinode, oplock, 0, NULL);
3345 }
3346
3347 static void
3348 smb21_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
3349                        unsigned int epoch, bool *purge_cache);
3350
3351 static void
3352 smb3_downgrade_oplock(struct TCP_Server_Info *server,
3353                        struct cifsInodeInfo *cinode, __u32 oplock,
3354                        unsigned int epoch, bool *purge_cache)
3355 {
3356         unsigned int old_state = cinode->oplock;
3357         unsigned int old_epoch = cinode->epoch;
3358         unsigned int new_state;
3359
3360         if (epoch > old_epoch) {
3361                 smb21_set_oplock_level(cinode, oplock, 0, NULL);
3362                 cinode->epoch = epoch;
3363         }
3364
3365         new_state = cinode->oplock;
3366         *purge_cache = false;
3367
3368         if ((old_state & CIFS_CACHE_READ_FLG) != 0 &&
3369             (new_state & CIFS_CACHE_READ_FLG) == 0)
3370                 *purge_cache = true;
3371         else if (old_state == new_state && (epoch - old_epoch > 1))
3372                 *purge_cache = true;
3373 }
3374
3375 static void
3376 smb2_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
3377                       unsigned int epoch, bool *purge_cache)
3378 {
3379         oplock &= 0xFF;
3380         if (oplock == SMB2_OPLOCK_LEVEL_NOCHANGE)
3381                 return;
3382         if (oplock == SMB2_OPLOCK_LEVEL_BATCH) {
3383                 cinode->oplock = CIFS_CACHE_RHW_FLG;
3384                 cifs_dbg(FYI, "Batch Oplock granted on inode %p\n",
3385                          &cinode->vfs_inode);
3386         } else if (oplock == SMB2_OPLOCK_LEVEL_EXCLUSIVE) {
3387                 cinode->oplock = CIFS_CACHE_RW_FLG;
3388                 cifs_dbg(FYI, "Exclusive Oplock granted on inode %p\n",
3389                          &cinode->vfs_inode);
3390         } else if (oplock == SMB2_OPLOCK_LEVEL_II) {
3391                 cinode->oplock = CIFS_CACHE_READ_FLG;
3392                 cifs_dbg(FYI, "Level II Oplock granted on inode %p\n",
3393                          &cinode->vfs_inode);
3394         } else
3395                 cinode->oplock = 0;
3396 }
3397
3398 static void
3399 smb21_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
3400                        unsigned int epoch, bool *purge_cache)
3401 {
3402         char message[5] = {0};
3403         unsigned int new_oplock = 0;
3404
3405         oplock &= 0xFF;
3406         if (oplock == SMB2_OPLOCK_LEVEL_NOCHANGE)
3407                 return;
3408
3409         /* Check if the server granted an oplock rather than a lease */
3410         if (oplock & SMB2_OPLOCK_LEVEL_EXCLUSIVE)
3411                 return smb2_set_oplock_level(cinode, oplock, epoch,
3412                                              purge_cache);
3413
3414         if (oplock & SMB2_LEASE_READ_CACHING_HE) {
3415                 new_oplock |= CIFS_CACHE_READ_FLG;
3416                 strcat(message, "R");
3417         }
3418         if (oplock & SMB2_LEASE_HANDLE_CACHING_HE) {
3419                 new_oplock |= CIFS_CACHE_HANDLE_FLG;
3420                 strcat(message, "H");
3421         }
3422         if (oplock & SMB2_LEASE_WRITE_CACHING_HE) {
3423                 new_oplock |= CIFS_CACHE_WRITE_FLG;
3424                 strcat(message, "W");
3425         }
3426         if (!new_oplock)
3427                 strncpy(message, "None", sizeof(message));
3428
3429         cinode->oplock = new_oplock;
3430         cifs_dbg(FYI, "%s Lease granted on inode %p\n", message,
3431                  &cinode->vfs_inode);
3432 }
3433
3434 static void
3435 smb3_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
3436                       unsigned int epoch, bool *purge_cache)
3437 {
3438         unsigned int old_oplock = cinode->oplock;
3439
3440         smb21_set_oplock_level(cinode, oplock, epoch, purge_cache);
3441
3442         if (purge_cache) {
3443                 *purge_cache = false;
3444                 if (old_oplock == CIFS_CACHE_READ_FLG) {
3445                         if (cinode->oplock == CIFS_CACHE_READ_FLG &&
3446                             (epoch - cinode->epoch > 0))
3447                                 *purge_cache = true;
3448                         else if (cinode->oplock == CIFS_CACHE_RH_FLG &&
3449                                  (epoch - cinode->epoch > 1))
3450                                 *purge_cache = true;
3451                         else if (cinode->oplock == CIFS_CACHE_RHW_FLG &&
3452                                  (epoch - cinode->epoch > 1))
3453                                 *purge_cache = true;
3454                         else if (cinode->oplock == 0 &&
3455                                  (epoch - cinode->epoch > 0))
3456                                 *purge_cache = true;
3457                 } else if (old_oplock == CIFS_CACHE_RH_FLG) {
3458                         if (cinode->oplock == CIFS_CACHE_RH_FLG &&
3459                             (epoch - cinode->epoch > 0))
3460                                 *purge_cache = true;
3461                         else if (cinode->oplock == CIFS_CACHE_RHW_FLG &&
3462                                  (epoch - cinode->epoch > 1))
3463                                 *purge_cache = true;
3464                 }
3465                 cinode->epoch = epoch;
3466         }
3467 }
3468
3469 static bool
3470 smb2_is_read_op(__u32 oplock)
3471 {
3472         return oplock == SMB2_OPLOCK_LEVEL_II;
3473 }
3474
3475 static bool
3476 smb21_is_read_op(__u32 oplock)
3477 {
3478         return (oplock & SMB2_LEASE_READ_CACHING_HE) &&
3479                !(oplock & SMB2_LEASE_WRITE_CACHING_HE);
3480 }
3481
3482 static __le32
3483 map_oplock_to_lease(u8 oplock)
3484 {
3485         if (oplock == SMB2_OPLOCK_LEVEL_EXCLUSIVE)
3486                 return SMB2_LEASE_WRITE_CACHING | SMB2_LEASE_READ_CACHING;
3487         else if (oplock == SMB2_OPLOCK_LEVEL_II)
3488                 return SMB2_LEASE_READ_CACHING;
3489         else if (oplock == SMB2_OPLOCK_LEVEL_BATCH)
3490                 return SMB2_LEASE_HANDLE_CACHING | SMB2_LEASE_READ_CACHING |
3491                        SMB2_LEASE_WRITE_CACHING;
3492         return 0;
3493 }
3494
3495 static char *
3496 smb2_create_lease_buf(u8 *lease_key, u8 oplock)
3497 {
3498         struct create_lease *buf;
3499
3500         buf = kzalloc(sizeof(struct create_lease), GFP_KERNEL);
3501         if (!buf)
3502                 return NULL;
3503
3504         memcpy(&buf->lcontext.LeaseKey, lease_key, SMB2_LEASE_KEY_SIZE);
3505         buf->lcontext.LeaseState = map_oplock_to_lease(oplock);
3506
3507         buf->ccontext.DataOffset = cpu_to_le16(offsetof
3508                                         (struct create_lease, lcontext));
3509         buf->ccontext.DataLength = cpu_to_le32(sizeof(struct lease_context));
3510         buf->ccontext.NameOffset = cpu_to_le16(offsetof
3511                                 (struct create_lease, Name));
3512         buf->ccontext.NameLength = cpu_to_le16(4);
3513         /* SMB2_CREATE_REQUEST_LEASE is "RqLs" */
3514         buf->Name[0] = 'R';
3515         buf->Name[1] = 'q';
3516         buf->Name[2] = 'L';
3517         buf->Name[3] = 's';
3518         return (char *)buf;
3519 }
3520
3521 static char *
3522 smb3_create_lease_buf(u8 *lease_key, u8 oplock)
3523 {
3524         struct create_lease_v2 *buf;
3525
3526         buf = kzalloc(sizeof(struct create_lease_v2), GFP_KERNEL);
3527         if (!buf)
3528                 return NULL;
3529
3530         memcpy(&buf->lcontext.LeaseKey, lease_key, SMB2_LEASE_KEY_SIZE);
3531         buf->lcontext.LeaseState = map_oplock_to_lease(oplock);
3532
3533         buf->ccontext.DataOffset = cpu_to_le16(offsetof
3534                                         (struct create_lease_v2, lcontext));
3535         buf->ccontext.DataLength = cpu_to_le32(sizeof(struct lease_context_v2));
3536         buf->ccontext.NameOffset = cpu_to_le16(offsetof
3537                                 (struct create_lease_v2, Name));
3538         buf->ccontext.NameLength = cpu_to_le16(4);
3539         /* SMB2_CREATE_REQUEST_LEASE is "RqLs" */
3540         buf->Name[0] = 'R';
3541         buf->Name[1] = 'q';
3542         buf->Name[2] = 'L';
3543         buf->Name[3] = 's';
3544         return (char *)buf;
3545 }
3546
3547 static __u8
3548 smb2_parse_lease_buf(void *buf, unsigned int *epoch, char *lease_key)
3549 {
3550         struct create_lease *lc = (struct create_lease *)buf;
3551
3552         *epoch = 0; /* not used */
3553         if (lc->lcontext.LeaseFlags & SMB2_LEASE_FLAG_BREAK_IN_PROGRESS)
3554                 return SMB2_OPLOCK_LEVEL_NOCHANGE;
3555         return le32_to_cpu(lc->lcontext.LeaseState);
3556 }
3557
3558 static __u8
3559 smb3_parse_lease_buf(void *buf, unsigned int *epoch, char *lease_key)
3560 {
3561         struct create_lease_v2 *lc = (struct create_lease_v2 *)buf;
3562
3563         *epoch = le16_to_cpu(lc->lcontext.Epoch);
3564         if (lc->lcontext.LeaseFlags & SMB2_LEASE_FLAG_BREAK_IN_PROGRESS)
3565                 return SMB2_OPLOCK_LEVEL_NOCHANGE;
3566         if (lease_key)
3567                 memcpy(lease_key, &lc->lcontext.LeaseKey, SMB2_LEASE_KEY_SIZE);
3568         return le32_to_cpu(lc->lcontext.LeaseState);
3569 }
3570
3571 static unsigned int
3572 smb2_wp_retry_size(struct inode *inode)
3573 {
3574         return min_t(unsigned int, CIFS_SB(inode->i_sb)->wsize,
3575                      SMB2_MAX_BUFFER_SIZE);
3576 }
3577
3578 static bool
3579 smb2_dir_needs_close(struct cifsFileInfo *cfile)
3580 {
3581         return !cfile->invalidHandle;
3582 }
3583
3584 static void
3585 fill_transform_hdr(struct smb2_transform_hdr *tr_hdr, unsigned int orig_len,
3586                    struct smb_rqst *old_rq, __le16 cipher_type)
3587 {
3588         struct smb2_sync_hdr *shdr =
3589                         (struct smb2_sync_hdr *)old_rq->rq_iov[0].iov_base;
3590
3591         memset(tr_hdr, 0, sizeof(struct smb2_transform_hdr));
3592         tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
3593         tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
3594         tr_hdr->Flags = cpu_to_le16(0x01);
3595         if (cipher_type == SMB2_ENCRYPTION_AES128_GCM)
3596                 get_random_bytes(&tr_hdr->Nonce, SMB3_AES128GCM_NONCE);
3597         else
3598                 get_random_bytes(&tr_hdr->Nonce, SMB3_AES128CCM_NONCE);
3599         memcpy(&tr_hdr->SessionId, &shdr->SessionId, 8);
3600 }
3601
3602 /* We can not use the normal sg_set_buf() as we will sometimes pass a
3603  * stack object as buf.
3604  */
3605 static inline void smb2_sg_set_buf(struct scatterlist *sg, const void *buf,
3606                                    unsigned int buflen)
3607 {
3608         void *addr;
3609         /*
3610          * VMAP_STACK (at least) puts stack into the vmalloc address space
3611          */
3612         if (is_vmalloc_addr(buf))
3613                 addr = vmalloc_to_page(buf);
3614         else
3615                 addr = virt_to_page(buf);
3616         sg_set_page(sg, addr, buflen, offset_in_page(buf));
3617 }
3618
3619 /* Assumes the first rqst has a transform header as the first iov.
3620  * I.e.
3621  * rqst[0].rq_iov[0]  is transform header
3622  * rqst[0].rq_iov[1+] data to be encrypted/decrypted
3623  * rqst[1+].rq_iov[0+] data to be encrypted/decrypted
3624  */
3625 static struct scatterlist *
3626 init_sg(int num_rqst, struct smb_rqst *rqst, u8 *sign)
3627 {
3628         unsigned int sg_len;
3629         struct scatterlist *sg;
3630         unsigned int i;
3631         unsigned int j;
3632         unsigned int idx = 0;
3633         int skip;
3634
3635         sg_len = 1;
3636         for (i = 0; i < num_rqst; i++)
3637                 sg_len += rqst[i].rq_nvec + rqst[i].rq_npages;
3638
3639         sg = kmalloc_array(sg_len, sizeof(struct scatterlist), GFP_KERNEL);
3640         if (!sg)
3641                 return NULL;
3642
3643         sg_init_table(sg, sg_len);
3644         for (i = 0; i < num_rqst; i++) {
3645                 for (j = 0; j < rqst[i].rq_nvec; j++) {
3646                         /*
3647                          * The first rqst has a transform header where the
3648                          * first 20 bytes are not part of the encrypted blob
3649                          */
3650                         skip = (i == 0) && (j == 0) ? 20 : 0;
3651                         smb2_sg_set_buf(&sg[idx++],
3652                                         rqst[i].rq_iov[j].iov_base + skip,
3653                                         rqst[i].rq_iov[j].iov_len - skip);
3654                         }
3655
3656                 for (j = 0; j < rqst[i].rq_npages; j++) {
3657                         unsigned int len, offset;
3658
3659                         rqst_page_get_length(&rqst[i], j, &len, &offset);
3660                         sg_set_page(&sg[idx++], rqst[i].rq_pages[j], len, offset);
3661                 }
3662         }
3663         smb2_sg_set_buf(&sg[idx], sign, SMB2_SIGNATURE_SIZE);
3664         return sg;
3665 }
3666
3667 static int
3668 smb2_get_enc_key(struct TCP_Server_Info *server, __u64 ses_id, int enc, u8 *key)
3669 {
3670         struct cifs_ses *ses;
3671         u8 *ses_enc_key;
3672
3673         spin_lock(&cifs_tcp_ses_lock);
3674         list_for_each_entry(server, &cifs_tcp_ses_list, tcp_ses_list) {
3675                 list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
3676                         if (ses->Suid == ses_id) {
3677                                 ses_enc_key = enc ? ses->smb3encryptionkey :
3678                                         ses->smb3decryptionkey;
3679                                 memcpy(key, ses_enc_key, SMB3_SIGN_KEY_SIZE);
3680                                 spin_unlock(&cifs_tcp_ses_lock);
3681                                 return 0;
3682                         }
3683                 }
3684         }
3685         spin_unlock(&cifs_tcp_ses_lock);
3686
3687         return 1;
3688 }
3689 /*
3690  * Encrypt or decrypt @rqst message. @rqst[0] has the following format:
3691  * iov[0]   - transform header (associate data),
3692  * iov[1-N] - SMB2 header and pages - data to encrypt.
3693  * On success return encrypted data in iov[1-N] and pages, leave iov[0]
3694  * untouched.
3695  */
3696 static int
3697 crypt_message(struct TCP_Server_Info *server, int num_rqst,
3698               struct smb_rqst *rqst, int enc)
3699 {
3700         struct smb2_transform_hdr *tr_hdr =
3701                 (struct smb2_transform_hdr *)rqst[0].rq_iov[0].iov_base;
3702         unsigned int assoc_data_len = sizeof(struct smb2_transform_hdr) - 20;
3703         int rc = 0;
3704         struct scatterlist *sg;
3705         u8 sign[SMB2_SIGNATURE_SIZE] = {};
3706         u8 key[SMB3_SIGN_KEY_SIZE];
3707         struct aead_request *req;
3708         char *iv;
3709         unsigned int iv_len;
3710         DECLARE_CRYPTO_WAIT(wait);
3711         struct crypto_aead *tfm;
3712         unsigned int crypt_len = le32_to_cpu(tr_hdr->OriginalMessageSize);
3713
3714         rc = smb2_get_enc_key(server, tr_hdr->SessionId, enc, key);
3715         if (rc) {
3716                 cifs_server_dbg(VFS, "%s: Could not get %scryption key\n", __func__,
3717                          enc ? "en" : "de");
3718                 return 0;
3719         }
3720
3721         rc = smb3_crypto_aead_allocate(server);
3722         if (rc) {
3723                 cifs_server_dbg(VFS, "%s: crypto alloc failed\n", __func__);
3724                 return rc;
3725         }
3726
3727         tfm = enc ? server->secmech.ccmaesencrypt :
3728                                                 server->secmech.ccmaesdecrypt;
3729         rc = crypto_aead_setkey(tfm, key, SMB3_SIGN_KEY_SIZE);
3730         if (rc) {
3731                 cifs_server_dbg(VFS, "%s: Failed to set aead key %d\n", __func__, rc);
3732                 return rc;
3733         }
3734
3735         rc = crypto_aead_setauthsize(tfm, SMB2_SIGNATURE_SIZE);
3736         if (rc) {
3737                 cifs_server_dbg(VFS, "%s: Failed to set authsize %d\n", __func__, rc);
3738                 return rc;
3739         }
3740
3741         req = aead_request_alloc(tfm, GFP_KERNEL);
3742         if (!req) {
3743                 cifs_server_dbg(VFS, "%s: Failed to alloc aead request\n", __func__);
3744                 return -ENOMEM;
3745         }
3746
3747         if (!enc) {
3748                 memcpy(sign, &tr_hdr->Signature, SMB2_SIGNATURE_SIZE);
3749                 crypt_len += SMB2_SIGNATURE_SIZE;
3750         }
3751
3752         sg = init_sg(num_rqst, rqst, sign);
3753         if (!sg) {
3754                 cifs_server_dbg(VFS, "%s: Failed to init sg\n", __func__);
3755                 rc = -ENOMEM;
3756                 goto free_req;
3757         }
3758
3759         iv_len = crypto_aead_ivsize(tfm);
3760         iv = kzalloc(iv_len, GFP_KERNEL);
3761         if (!iv) {
3762                 cifs_server_dbg(VFS, "%s: Failed to alloc iv\n", __func__);
3763                 rc = -ENOMEM;
3764                 goto free_sg;
3765         }
3766
3767         if (server->cipher_type == SMB2_ENCRYPTION_AES128_GCM)
3768                 memcpy(iv, (char *)tr_hdr->Nonce, SMB3_AES128GCM_NONCE);
3769         else {
3770                 iv[0] = 3;
3771                 memcpy(iv + 1, (char *)tr_hdr->Nonce, SMB3_AES128CCM_NONCE);
3772         }
3773
3774         aead_request_set_crypt(req, sg, sg, crypt_len, iv);
3775         aead_request_set_ad(req, assoc_data_len);
3776
3777         aead_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
3778                                   crypto_req_done, &wait);
3779
3780         rc = crypto_wait_req(enc ? crypto_aead_encrypt(req)
3781                                 : crypto_aead_decrypt(req), &wait);
3782
3783         if (!rc && enc)
3784                 memcpy(&tr_hdr->Signature, sign, SMB2_SIGNATURE_SIZE);
3785
3786         kfree(iv);
3787 free_sg:
3788         kfree(sg);
3789 free_req:
3790         kfree(req);
3791         return rc;
3792 }
3793
3794 void
3795 smb3_free_compound_rqst(int num_rqst, struct smb_rqst *rqst)
3796 {
3797         int i, j;
3798
3799         for (i = 0; i < num_rqst; i++) {
3800                 if (rqst[i].rq_pages) {
3801                         for (j = rqst[i].rq_npages - 1; j >= 0; j--)
3802                                 put_page(rqst[i].rq_pages[j]);
3803                         kfree(rqst[i].rq_pages);
3804                 }
3805         }
3806 }
3807
3808 /*
3809  * This function will initialize new_rq and encrypt the content.
3810  * The first entry, new_rq[0], only contains a single iov which contains
3811  * a smb2_transform_hdr and is pre-allocated by the caller.
3812  * This function then populates new_rq[1+] with the content from olq_rq[0+].
3813  *
3814  * The end result is an array of smb_rqst structures where the first structure
3815  * only contains a single iov for the transform header which we then can pass
3816  * to crypt_message().
3817  *
3818  * new_rq[0].rq_iov[0] :  smb2_transform_hdr pre-allocated by the caller
3819  * new_rq[1+].rq_iov[*] == old_rq[0+].rq_iov[*] : SMB2/3 requests
3820  */
3821 static int
3822 smb3_init_transform_rq(struct TCP_Server_Info *server, int num_rqst,
3823                        struct smb_rqst *new_rq, struct smb_rqst *old_rq)
3824 {
3825         struct page **pages;
3826         struct smb2_transform_hdr *tr_hdr = new_rq[0].rq_iov[0].iov_base;
3827         unsigned int npages;
3828         unsigned int orig_len = 0;
3829         int i, j;
3830         int rc = -ENOMEM;
3831
3832         for (i = 1; i < num_rqst; i++) {
3833                 npages = old_rq[i - 1].rq_npages;
3834                 pages = kmalloc_array(npages, sizeof(struct page *),
3835                                       GFP_KERNEL);
3836                 if (!pages)
3837                         goto err_free;
3838
3839                 new_rq[i].rq_pages = pages;
3840                 new_rq[i].rq_npages = npages;
3841                 new_rq[i].rq_offset = old_rq[i - 1].rq_offset;
3842                 new_rq[i].rq_pagesz = old_rq[i - 1].rq_pagesz;
3843                 new_rq[i].rq_tailsz = old_rq[i - 1].rq_tailsz;
3844                 new_rq[i].rq_iov = old_rq[i - 1].rq_iov;
3845                 new_rq[i].rq_nvec = old_rq[i - 1].rq_nvec;
3846
3847                 orig_len += smb_rqst_len(server, &old_rq[i - 1]);
3848
3849                 for (j = 0; j < npages; j++) {
3850                         pages[j] = alloc_page(GFP_KERNEL|__GFP_HIGHMEM);
3851                         if (!pages[j])
3852                                 goto err_free;
3853                 }
3854
3855                 /* copy pages form the old */
3856                 for (j = 0; j < npages; j++) {
3857                         char *dst, *src;
3858                         unsigned int offset, len;
3859
3860                         rqst_page_get_length(&new_rq[i], j, &len, &offset);
3861
3862                         dst = (char *) kmap(new_rq[i].rq_pages[j]) + offset;
3863                         src = (char *) kmap(old_rq[i - 1].rq_pages[j]) + offset;
3864
3865                         memcpy(dst, src, len);
3866                         kunmap(new_rq[i].rq_pages[j]);
3867                         kunmap(old_rq[i - 1].rq_pages[j]);
3868                 }
3869         }
3870
3871         /* fill the 1st iov with a transform header */
3872         fill_transform_hdr(tr_hdr, orig_len, old_rq, server->cipher_type);
3873
3874         rc = crypt_message(server, num_rqst, new_rq, 1);
3875         cifs_dbg(FYI, "Encrypt message returned %d\n", rc);
3876         if (rc)
3877                 goto err_free;
3878
3879         return rc;
3880
3881 err_free:
3882         smb3_free_compound_rqst(num_rqst - 1, &new_rq[1]);
3883         return rc;
3884 }
3885
3886 static int
3887 smb3_is_transform_hdr(void *buf)
3888 {
3889         struct smb2_transform_hdr *trhdr = buf;
3890
3891         return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
3892 }
3893
3894 static int
3895 decrypt_raw_data(struct TCP_Server_Info *server, char *buf,
3896                  unsigned int buf_data_size, struct page **pages,
3897                  unsigned int npages, unsigned int page_data_size)
3898 {
3899         struct kvec iov[2];
3900         struct smb_rqst rqst = {NULL};
3901         int rc;
3902
3903         iov[0].iov_base = buf;
3904         iov[0].iov_len = sizeof(struct smb2_transform_hdr);
3905         iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr);
3906         iov[1].iov_len = buf_data_size;
3907
3908         rqst.rq_iov = iov;
3909         rqst.rq_nvec = 2;
3910         rqst.rq_pages = pages;
3911         rqst.rq_npages = npages;
3912         rqst.rq_pagesz = PAGE_SIZE;
3913         rqst.rq_tailsz = (page_data_size % PAGE_SIZE) ? : PAGE_SIZE;
3914
3915         rc = crypt_message(server, 1, &rqst, 0);
3916         cifs_dbg(FYI, "Decrypt message returned %d\n", rc);
3917
3918         if (rc)
3919                 return rc;
3920
3921         memmove(buf, iov[1].iov_base, buf_data_size);
3922
3923         server->total_read = buf_data_size + page_data_size;
3924
3925         return rc;
3926 }
3927
3928 static int
3929 read_data_into_pages(struct TCP_Server_Info *server, struct page **pages,
3930                      unsigned int npages, unsigned int len)
3931 {
3932         int i;
3933         int length;
3934
3935         for (i = 0; i < npages; i++) {
3936                 struct page *page = pages[i];
3937                 size_t n;
3938
3939                 n = len;
3940                 if (len >= PAGE_SIZE) {
3941                         /* enough data to fill the page */
3942                         n = PAGE_SIZE;
3943                         len -= n;
3944                 } else {
3945                         zero_user(page, len, PAGE_SIZE - len);
3946                         len = 0;
3947                 }
3948                 length = cifs_read_page_from_socket(server, page, 0, n);
3949                 if (length < 0)
3950                         return length;
3951                 server->total_read += length;
3952         }
3953
3954         return 0;
3955 }
3956
3957 static int
3958 init_read_bvec(struct page **pages, unsigned int npages, unsigned int data_size,
3959                unsigned int cur_off, struct bio_vec **page_vec)
3960 {
3961         struct bio_vec *bvec;
3962         int i;
3963
3964         bvec = kcalloc(npages, sizeof(struct bio_vec), GFP_KERNEL);
3965         if (!bvec)
3966                 return -ENOMEM;
3967
3968         for (i = 0; i < npages; i++) {
3969                 bvec[i].bv_page = pages[i];
3970                 bvec[i].bv_offset = (i == 0) ? cur_off : 0;
3971                 bvec[i].bv_len = min_t(unsigned int, PAGE_SIZE, data_size);
3972                 data_size -= bvec[i].bv_len;
3973         }
3974
3975         if (data_size != 0) {
3976                 cifs_dbg(VFS, "%s: something went wrong\n", __func__);
3977                 kfree(bvec);
3978                 return -EIO;
3979         }
3980
3981         *page_vec = bvec;
3982         return 0;
3983 }
3984
3985 static int
3986 handle_read_data(struct TCP_Server_Info *server, struct mid_q_entry *mid,
3987                  char *buf, unsigned int buf_len, struct page **pages,
3988                  unsigned int npages, unsigned int page_data_size)
3989 {
3990         unsigned int data_offset;
3991         unsigned int data_len;
3992         unsigned int cur_off;
3993         unsigned int cur_page_idx;
3994         unsigned int pad_len;
3995         struct cifs_readdata *rdata = mid->callback_data;
3996         struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)buf;
3997         struct bio_vec *bvec = NULL;
3998         struct iov_iter iter;
3999         struct kvec iov;
4000         int length;
4001         bool use_rdma_mr = false;
4002
4003         if (shdr->Command != SMB2_READ) {
4004                 cifs_server_dbg(VFS, "only big read responses are supported\n");
4005                 return -ENOTSUPP;
4006         }
4007
4008         if (server->ops->is_session_expired &&
4009             server->ops->is_session_expired(buf)) {
4010                 cifs_reconnect(server);
4011                 wake_up(&server->response_q);
4012                 return -1;
4013         }
4014
4015         if (server->ops->is_status_pending &&
4016                         server->ops->is_status_pending(buf, server))
4017                 return -1;
4018
4019         /* set up first two iov to get credits */
4020         rdata->iov[0].iov_base = buf;
4021         rdata->iov[0].iov_len = 0;
4022         rdata->iov[1].iov_base = buf;
4023         rdata->iov[1].iov_len =
4024                 min_t(unsigned int, buf_len, server->vals->read_rsp_size);
4025         cifs_dbg(FYI, "0: iov_base=%p iov_len=%zu\n",
4026                  rdata->iov[0].iov_base, rdata->iov[0].iov_len);
4027         cifs_dbg(FYI, "1: iov_base=%p iov_len=%zu\n",
4028                  rdata->iov[1].iov_base, rdata->iov[1].iov_len);
4029
4030         rdata->result = server->ops->map_error(buf, true);
4031         if (rdata->result != 0) {
4032                 cifs_dbg(FYI, "%s: server returned error %d\n",
4033                          __func__, rdata->result);
4034                 /* normal error on read response */
4035                 dequeue_mid(mid, false);
4036                 return 0;
4037         }
4038
4039         data_offset = server->ops->read_data_offset(buf);
4040 #ifdef CONFIG_CIFS_SMB_DIRECT
4041         use_rdma_mr = rdata->mr;
4042 #endif
4043         data_len = server->ops->read_data_length(buf, use_rdma_mr);
4044
4045         if (data_offset < server->vals->read_rsp_size) {
4046                 /*
4047                  * win2k8 sometimes sends an offset of 0 when the read
4048                  * is beyond the EOF. Treat it as if the data starts just after
4049                  * the header.
4050                  */
4051                 cifs_dbg(FYI, "%s: data offset (%u) inside read response header\n",
4052                          __func__, data_offset);
4053                 data_offset = server->vals->read_rsp_size;
4054         } else if (data_offset > MAX_CIFS_SMALL_BUFFER_SIZE) {
4055                 /* data_offset is beyond the end of smallbuf */
4056                 cifs_dbg(FYI, "%s: data offset (%u) beyond end of smallbuf\n",
4057                          __func__, data_offset);
4058                 rdata->result = -EIO;
4059                 dequeue_mid(mid, rdata->result);
4060                 return 0;
4061         }
4062
4063         pad_len = data_offset - server->vals->read_rsp_size;
4064
4065         if (buf_len <= data_offset) {
4066                 /* read response payload is in pages */
4067                 cur_page_idx = pad_len / PAGE_SIZE;
4068                 cur_off = pad_len % PAGE_SIZE;
4069
4070                 if (cur_page_idx != 0) {
4071                         /* data offset is beyond the 1st page of response */
4072                         cifs_dbg(FYI, "%s: data offset (%u) beyond 1st page of response\n",
4073                                  __func__, data_offset);
4074                         rdata->result = -EIO;
4075                         dequeue_mid(mid, rdata->result);
4076                         return 0;
4077                 }
4078
4079                 if (data_len > page_data_size - pad_len) {
4080                         /* data_len is corrupt -- discard frame */
4081                         rdata->result = -EIO;
4082                         dequeue_mid(mid, rdata->result);
4083                         return 0;
4084                 }
4085
4086                 rdata->result = init_read_bvec(pages, npages, page_data_size,
4087                                                cur_off, &bvec);
4088                 if (rdata->result != 0) {
4089                         dequeue_mid(mid, rdata->result);
4090                         return 0;
4091                 }
4092
4093                 iov_iter_bvec(&iter, WRITE, bvec, npages, data_len);
4094         } else if (buf_len >= data_offset + data_len) {
4095                 /* read response payload is in buf */
4096                 WARN_ONCE(npages > 0, "read data can be either in buf or in pages");
4097                 iov.iov_base = buf + data_offset;
4098                 iov.iov_len = data_len;
4099                 iov_iter_kvec(&iter, WRITE, &iov, 1, data_len);
4100         } else {
4101                 /* read response payload cannot be in both buf and pages */
4102                 WARN_ONCE(1, "buf can not contain only a part of read data");
4103                 rdata->result = -EIO;
4104                 dequeue_mid(mid, rdata->result);
4105                 return 0;
4106         }
4107
4108         length = rdata->copy_into_pages(server, rdata, &iter);
4109
4110         kfree(bvec);
4111
4112         if (length < 0)
4113                 return length;
4114
4115         dequeue_mid(mid, false);
4116         return length;
4117 }
4118
4119 struct smb2_decrypt_work {
4120         struct work_struct decrypt;
4121         struct TCP_Server_Info *server;
4122         struct page **ppages;
4123         char *buf;
4124         unsigned int npages;
4125         unsigned int len;
4126 };
4127
4128
4129 static void smb2_decrypt_offload(struct work_struct *work)
4130 {
4131         struct smb2_decrypt_work *dw = container_of(work,
4132                                 struct smb2_decrypt_work, decrypt);
4133         int i, rc;
4134         struct mid_q_entry *mid;
4135
4136         rc = decrypt_raw_data(dw->server, dw->buf, dw->server->vals->read_rsp_size,
4137                               dw->ppages, dw->npages, dw->len);
4138         if (rc) {
4139                 cifs_dbg(VFS, "error decrypting rc=%d\n", rc);
4140                 goto free_pages;
4141         }
4142
4143         dw->server->lstrp = jiffies;
4144         mid = smb2_find_mid(dw->server, dw->buf);
4145         if (mid == NULL)
4146                 cifs_dbg(FYI, "mid not found\n");
4147         else {
4148                 mid->decrypted = true;
4149                 rc = handle_read_data(dw->server, mid, dw->buf,
4150                                       dw->server->vals->read_rsp_size,
4151                                       dw->ppages, dw->npages, dw->len);
4152                 mid->callback(mid);
4153                 cifs_mid_q_entry_release(mid);
4154         }
4155
4156 free_pages:
4157         for (i = dw->npages-1; i >= 0; i--)
4158                 put_page(dw->ppages[i]);
4159
4160         kfree(dw->ppages);
4161         cifs_small_buf_release(dw->buf);
4162         kfree(dw);
4163 }
4164
4165
4166 static int
4167 receive_encrypted_read(struct TCP_Server_Info *server, struct mid_q_entry **mid,
4168                        int *num_mids)
4169 {
4170         char *buf = server->smallbuf;
4171         struct smb2_transform_hdr *tr_hdr = (struct smb2_transform_hdr *)buf;
4172         unsigned int npages;
4173         struct page **pages;
4174         unsigned int len;
4175         unsigned int buflen = server->pdu_size;
4176         int rc;
4177         int i = 0;
4178         struct smb2_decrypt_work *dw;
4179
4180         *num_mids = 1;
4181         len = min_t(unsigned int, buflen, server->vals->read_rsp_size +
4182                 sizeof(struct smb2_transform_hdr)) - HEADER_SIZE(server) + 1;
4183
4184         rc = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1, len);
4185         if (rc < 0)
4186                 return rc;
4187         server->total_read += rc;
4188
4189         len = le32_to_cpu(tr_hdr->OriginalMessageSize) -
4190                 server->vals->read_rsp_size;
4191         npages = DIV_ROUND_UP(len, PAGE_SIZE);
4192
4193         pages = kmalloc_array(npages, sizeof(struct page *), GFP_KERNEL);
4194         if (!pages) {
4195                 rc = -ENOMEM;
4196                 goto discard_data;
4197         }
4198
4199         for (; i < npages; i++) {
4200                 pages[i] = alloc_page(GFP_KERNEL|__GFP_HIGHMEM);
4201                 if (!pages[i]) {
4202                         rc = -ENOMEM;
4203                         goto discard_data;
4204                 }
4205         }
4206
4207         /* read read data into pages */
4208         rc = read_data_into_pages(server, pages, npages, len);
4209         if (rc)
4210                 goto free_pages;
4211
4212         rc = cifs_discard_remaining_data(server);
4213         if (rc)
4214                 goto free_pages;
4215
4216         /*
4217          * For large reads, offload to different thread for better performance,
4218          * use more cores decrypting which can be expensive
4219          */
4220
4221         if ((server->min_offload) && (server->in_flight > 1) &&
4222             (server->pdu_size >= server->min_offload)) {
4223                 dw = kmalloc(sizeof(struct smb2_decrypt_work), GFP_KERNEL);
4224                 if (dw == NULL)
4225                         goto non_offloaded_decrypt;
4226
4227                 dw->buf = server->smallbuf;
4228                 server->smallbuf = (char *)cifs_small_buf_get();
4229
4230                 INIT_WORK(&dw->decrypt, smb2_decrypt_offload);
4231
4232                 dw->npages = npages;
4233                 dw->server = server;
4234                 dw->ppages = pages;
4235                 dw->len = len;
4236                 queue_work(decrypt_wq, &dw->decrypt);
4237                 *num_mids = 0; /* worker thread takes care of finding mid */
4238                 return -1;
4239         }
4240
4241 non_offloaded_decrypt:
4242         rc = decrypt_raw_data(server, buf, server->vals->read_rsp_size,
4243                               pages, npages, len);
4244         if (rc)
4245                 goto free_pages;
4246
4247         *mid = smb2_find_mid(server, buf);
4248         if (*mid == NULL)
4249                 cifs_dbg(FYI, "mid not found\n");
4250         else {
4251                 cifs_dbg(FYI, "mid found\n");
4252                 (*mid)->decrypted = true;
4253                 rc = handle_read_data(server, *mid, buf,
4254                                       server->vals->read_rsp_size,
4255                                       pages, npages, len);
4256         }
4257
4258 free_pages:
4259         for (i = i - 1; i >= 0; i--)
4260                 put_page(pages[i]);
4261         kfree(pages);
4262         return rc;
4263 discard_data:
4264         cifs_discard_remaining_data(server);
4265         goto free_pages;
4266 }
4267
4268 static int
4269 receive_encrypted_standard(struct TCP_Server_Info *server,
4270                            struct mid_q_entry **mids, char **bufs,
4271                            int *num_mids)
4272 {
4273         int ret, length;
4274         char *buf = server->smallbuf;
4275         struct smb2_sync_hdr *shdr;
4276         unsigned int pdu_length = server->pdu_size;
4277         unsigned int buf_size;
4278         struct mid_q_entry *mid_entry;
4279         int next_is_large;
4280         char *next_buffer = NULL;
4281
4282         *num_mids = 0;
4283
4284         /* switch to large buffer if too big for a small one */
4285         if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE) {
4286                 server->large_buf = true;
4287                 memcpy(server->bigbuf, buf, server->total_read);
4288                 buf = server->bigbuf;
4289         }
4290
4291         /* now read the rest */
4292         length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
4293                                 pdu_length - HEADER_SIZE(server) + 1);
4294         if (length < 0)
4295                 return length;
4296         server->total_read += length;
4297
4298         buf_size = pdu_length - sizeof(struct smb2_transform_hdr);
4299         length = decrypt_raw_data(server, buf, buf_size, NULL, 0, 0);
4300         if (length)
4301                 return length;
4302
4303         next_is_large = server->large_buf;
4304 one_more:
4305         shdr = (struct smb2_sync_hdr *)buf;
4306         if (shdr->NextCommand) {
4307                 if (next_is_large)
4308                         next_buffer = (char *)cifs_buf_get();
4309                 else
4310                         next_buffer = (char *)cifs_small_buf_get();
4311                 memcpy(next_buffer,
4312                        buf + le32_to_cpu(shdr->NextCommand),
4313                        pdu_length - le32_to_cpu(shdr->NextCommand));
4314         }
4315
4316         mid_entry = smb2_find_mid(server, buf);
4317         if (mid_entry == NULL)
4318                 cifs_dbg(FYI, "mid not found\n");
4319         else {
4320                 cifs_dbg(FYI, "mid found\n");
4321                 mid_entry->decrypted = true;
4322                 mid_entry->resp_buf_size = server->pdu_size;
4323         }
4324
4325         if (*num_mids >= MAX_COMPOUND) {
4326                 cifs_server_dbg(VFS, "too many PDUs in compound\n");
4327                 return -1;
4328         }
4329         bufs[*num_mids] = buf;
4330         mids[(*num_mids)++] = mid_entry;
4331
4332         if (mid_entry && mid_entry->handle)
4333                 ret = mid_entry->handle(server, mid_entry);
4334         else
4335                 ret = cifs_handle_standard(server, mid_entry);
4336
4337         if (ret == 0 && shdr->NextCommand) {
4338                 pdu_length -= le32_to_cpu(shdr->NextCommand);
4339                 server->large_buf = next_is_large;
4340                 if (next_is_large)
4341                         server->bigbuf = buf = next_buffer;
4342                 else
4343                         server->smallbuf = buf = next_buffer;
4344                 goto one_more;
4345         } else if (ret != 0) {
4346                 /*
4347                  * ret != 0 here means that we didn't get to handle_mid() thus
4348                  * server->smallbuf and server->bigbuf are still valid. We need
4349                  * to free next_buffer because it is not going to be used
4350                  * anywhere.
4351                  */
4352                 if (next_is_large)
4353                         free_rsp_buf(CIFS_LARGE_BUFFER, next_buffer);
4354                 else
4355                         free_rsp_buf(CIFS_SMALL_BUFFER, next_buffer);
4356         }
4357
4358         return ret;
4359 }
4360
4361 static int
4362 smb3_receive_transform(struct TCP_Server_Info *server,
4363                        struct mid_q_entry **mids, char **bufs, int *num_mids)
4364 {
4365         char *buf = server->smallbuf;
4366         unsigned int pdu_length = server->pdu_size;
4367         struct smb2_transform_hdr *tr_hdr = (struct smb2_transform_hdr *)buf;
4368         unsigned int orig_len = le32_to_cpu(tr_hdr->OriginalMessageSize);
4369
4370         if (pdu_length < sizeof(struct smb2_transform_hdr) +
4371                                                 sizeof(struct smb2_sync_hdr)) {
4372                 cifs_server_dbg(VFS, "Transform message is too small (%u)\n",
4373                          pdu_length);
4374                 cifs_reconnect(server);
4375                 wake_up(&server->response_q);
4376                 return -ECONNABORTED;
4377         }
4378
4379         if (pdu_length < orig_len + sizeof(struct smb2_transform_hdr)) {
4380                 cifs_server_dbg(VFS, "Transform message is broken\n");
4381                 cifs_reconnect(server);
4382                 wake_up(&server->response_q);
4383                 return -ECONNABORTED;
4384         }
4385
4386         /* TODO: add support for compounds containing READ. */
4387         if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server)) {
4388                 return receive_encrypted_read(server, &mids[0], num_mids);
4389         }
4390
4391         return receive_encrypted_standard(server, mids, bufs, num_mids);
4392 }
4393
4394 int
4395 smb3_handle_read_data(struct TCP_Server_Info *server, struct mid_q_entry *mid)
4396 {
4397         char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
4398
4399         return handle_read_data(server, mid, buf, server->pdu_size,
4400                                 NULL, 0, 0);
4401 }
4402
4403 static int
4404 smb2_next_header(char *buf)
4405 {
4406         struct smb2_sync_hdr *hdr = (struct smb2_sync_hdr *)buf;
4407         struct smb2_transform_hdr *t_hdr = (struct smb2_transform_hdr *)buf;
4408
4409         if (hdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM)
4410                 return sizeof(struct smb2_transform_hdr) +
4411                   le32_to_cpu(t_hdr->OriginalMessageSize);
4412
4413         return le32_to_cpu(hdr->NextCommand);
4414 }
4415
4416 static int
4417 smb2_make_node(unsigned int xid, struct inode *inode,
4418                struct dentry *dentry, struct cifs_tcon *tcon,
4419                char *full_path, umode_t mode, dev_t dev)
4420 {
4421         struct cifs_sb_info *cifs_sb = CIFS_SB(inode->i_sb);
4422         int rc = -EPERM;
4423         int create_options = CREATE_NOT_DIR | CREATE_OPTION_SPECIAL;
4424         FILE_ALL_INFO *buf = NULL;
4425         struct cifs_io_parms io_parms;
4426         __u32 oplock = 0;
4427         struct cifs_fid fid;
4428         struct cifs_open_parms oparms;
4429         unsigned int bytes_written;
4430         struct win_dev *pdev;
4431         struct kvec iov[2];
4432
4433         /*
4434          * Check if mounted with mount parm 'sfu' mount parm.
4435          * SFU emulation should work with all servers, but only
4436          * supports block and char device (no socket & fifo),
4437          * and was used by default in earlier versions of Windows
4438          */
4439         if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_UNX_EMUL))
4440                 goto out;
4441
4442         /*
4443          * TODO: Add ability to create instead via reparse point. Windows (e.g.
4444          * their current NFS server) uses this approach to expose special files
4445          * over SMB2/SMB3 and Samba will do this with SMB3.1.1 POSIX Extensions
4446          */
4447
4448         if (!S_ISCHR(mode) && !S_ISBLK(mode))
4449                 goto out;
4450
4451         cifs_dbg(FYI, "sfu compat create special file\n");
4452
4453         buf = kmalloc(sizeof(FILE_ALL_INFO), GFP_KERNEL);
4454         if (buf == NULL) {
4455                 rc = -ENOMEM;
4456                 goto out;
4457         }
4458
4459         if (backup_cred(cifs_sb))
4460                 create_options |= CREATE_OPEN_BACKUP_INTENT;
4461
4462         oparms.tcon = tcon;
4463         oparms.cifs_sb = cifs_sb;
4464         oparms.desired_access = GENERIC_WRITE;
4465         oparms.create_options = create_options;
4466         oparms.disposition = FILE_CREATE;
4467         oparms.path = full_path;
4468         oparms.fid = &fid;
4469         oparms.reconnect = false;
4470
4471         if (tcon->ses->server->oplocks)
4472                 oplock = REQ_OPLOCK;
4473         else
4474                 oplock = 0;
4475         rc = tcon->ses->server->ops->open(xid, &oparms, &oplock, buf);
4476         if (rc)
4477                 goto out;
4478
4479         /*
4480          * BB Do not bother to decode buf since no local inode yet to put
4481          * timestamps in, but we can reuse it safely.
4482          */
4483
4484         pdev = (struct win_dev *)buf;
4485         io_parms.pid = current->tgid;
4486         io_parms.tcon = tcon;
4487         io_parms.offset = 0;
4488         io_parms.length = sizeof(struct win_dev);
4489         iov[1].iov_base = buf;
4490         iov[1].iov_len = sizeof(struct win_dev);
4491         if (S_ISCHR(mode)) {
4492                 memcpy(pdev->type, "IntxCHR", 8);
4493                 pdev->major = cpu_to_le64(MAJOR(dev));
4494                 pdev->minor = cpu_to_le64(MINOR(dev));
4495                 rc = tcon->ses->server->ops->sync_write(xid, &fid, &io_parms,
4496                                                         &bytes_written, iov, 1);
4497         } else if (S_ISBLK(mode)) {
4498                 memcpy(pdev->type, "IntxBLK", 8);
4499                 pdev->major = cpu_to_le64(MAJOR(dev));
4500                 pdev->minor = cpu_to_le64(MINOR(dev));
4501                 rc = tcon->ses->server->ops->sync_write(xid, &fid, &io_parms,
4502                                                         &bytes_written, iov, 1);
4503         }
4504         tcon->ses->server->ops->close(xid, tcon, &fid);
4505         d_drop(dentry);
4506
4507         /* FIXME: add code here to set EAs */
4508 out:
4509         kfree(buf);
4510         return rc;
4511 }
4512
4513
4514 struct smb_version_operations smb20_operations = {
4515         .compare_fids = smb2_compare_fids,
4516         .setup_request = smb2_setup_request,
4517         .setup_async_request = smb2_setup_async_request,
4518         .check_receive = smb2_check_receive,
4519         .add_credits = smb2_add_credits,
4520         .set_credits = smb2_set_credits,
4521         .get_credits_field = smb2_get_credits_field,
4522         .get_credits = smb2_get_credits,
4523         .wait_mtu_credits = cifs_wait_mtu_credits,
4524         .get_next_mid = smb2_get_next_mid,
4525         .revert_current_mid = smb2_revert_current_mid,
4526         .read_data_offset = smb2_read_data_offset,
4527         .read_data_length = smb2_read_data_length,
4528         .map_error = map_smb2_to_linux_error,
4529         .find_mid = smb2_find_mid,
4530         .check_message = smb2_check_message,
4531         .dump_detail = smb2_dump_detail,
4532         .clear_stats = smb2_clear_stats,
4533         .print_stats = smb2_print_stats,
4534         .is_oplock_break = smb2_is_valid_oplock_break,
4535         .handle_cancelled_mid = smb2_handle_cancelled_mid,
4536         .downgrade_oplock = smb2_downgrade_oplock,
4537         .need_neg = smb2_need_neg,
4538         .negotiate = smb2_negotiate,
4539         .negotiate_wsize = smb2_negotiate_wsize,
4540         .negotiate_rsize = smb2_negotiate_rsize,
4541         .sess_setup = SMB2_sess_setup,
4542         .logoff = SMB2_logoff,
4543         .tree_connect = SMB2_tcon,
4544         .tree_disconnect = SMB2_tdis,
4545         .qfs_tcon = smb2_qfs_tcon,
4546         .is_path_accessible = smb2_is_path_accessible,
4547         .can_echo = smb2_can_echo,
4548         .echo = SMB2_echo,
4549         .query_path_info = smb2_query_path_info,
4550         .get_srv_inum = smb2_get_srv_inum,
4551         .query_file_info = smb2_query_file_info,
4552         .set_path_size = smb2_set_path_size,
4553         .set_file_size = smb2_set_file_size,
4554         .set_file_info = smb2_set_file_info,
4555         .set_compression = smb2_set_compression,
4556         .mkdir = smb2_mkdir,
4557         .mkdir_setinfo = smb2_mkdir_setinfo,
4558         .rmdir = smb2_rmdir,
4559         .unlink = smb2_unlink,
4560         .rename = smb2_rename_path,
4561         .create_hardlink = smb2_create_hardlink,
4562         .query_symlink = smb2_query_symlink,
4563         .query_mf_symlink = smb3_query_mf_symlink,
4564         .create_mf_symlink = smb3_create_mf_symlink,
4565         .open = smb2_open_file,
4566         .set_fid = smb2_set_fid,
4567         .close = smb2_close_file,
4568         .flush = smb2_flush_file,
4569         .async_readv = smb2_async_readv,
4570         .async_writev = smb2_async_writev,
4571         .sync_read = smb2_sync_read,
4572         .sync_write = smb2_sync_write,
4573         .query_dir_first = smb2_query_dir_first,
4574         .query_dir_next = smb2_query_dir_next,
4575         .close_dir = smb2_close_dir,
4576         .calc_smb_size = smb2_calc_size,
4577         .is_status_pending = smb2_is_status_pending,
4578         .is_session_expired = smb2_is_session_expired,
4579         .oplock_response = smb2_oplock_response,
4580         .queryfs = smb2_queryfs,
4581         .mand_lock = smb2_mand_lock,
4582         .mand_unlock_range = smb2_unlock_range,
4583         .push_mand_locks = smb2_push_mandatory_locks,
4584         .get_lease_key = smb2_get_lease_key,
4585         .set_lease_key = smb2_set_lease_key,
4586         .new_lease_key = smb2_new_lease_key,
4587         .calc_signature = smb2_calc_signature,
4588         .is_read_op = smb2_is_read_op,
4589         .set_oplock_level = smb2_set_oplock_level,
4590         .create_lease_buf = smb2_create_lease_buf,
4591         .parse_lease_buf = smb2_parse_lease_buf,
4592         .copychunk_range = smb2_copychunk_range,
4593         .wp_retry_size = smb2_wp_retry_size,
4594         .dir_needs_close = smb2_dir_needs_close,
4595         .get_dfs_refer = smb2_get_dfs_refer,
4596         .select_sectype = smb2_select_sectype,
4597 #ifdef CONFIG_CIFS_XATTR
4598         .query_all_EAs = smb2_query_eas,
4599         .set_EA = smb2_set_ea,
4600 #endif /* CIFS_XATTR */
4601         .get_acl = get_smb2_acl,
4602         .get_acl_by_fid = get_smb2_acl_by_fid,
4603         .set_acl = set_smb2_acl,
4604         .next_header = smb2_next_header,
4605         .ioctl_query_info = smb2_ioctl_query_info,
4606         .make_node = smb2_make_node,
4607         .fiemap = smb3_fiemap,
4608         .llseek = smb3_llseek,
4609 };
4610
4611 struct smb_version_operations smb21_operations = {
4612         .compare_fids = smb2_compare_fids,
4613         .setup_request = smb2_setup_request,
4614         .setup_async_request = smb2_setup_async_request,
4615         .check_receive = smb2_check_receive,
4616         .add_credits = smb2_add_credits,
4617         .set_credits = smb2_set_credits,
4618         .get_credits_field = smb2_get_credits_field,
4619         .get_credits = smb2_get_credits,
4620         .wait_mtu_credits = smb2_wait_mtu_credits,
4621         .adjust_credits = smb2_adjust_credits,
4622         .get_next_mid = smb2_get_next_mid,
4623         .revert_current_mid = smb2_revert_current_mid,
4624         .read_data_offset = smb2_read_data_offset,
4625         .read_data_length = smb2_read_data_length,
4626         .map_error = map_smb2_to_linux_error,
4627         .find_mid = smb2_find_mid,
4628         .check_message = smb2_check_message,
4629         .dump_detail = smb2_dump_detail,
4630         .clear_stats = smb2_clear_stats,
4631         .print_stats = smb2_print_stats,
4632         .is_oplock_break = smb2_is_valid_oplock_break,
4633         .handle_cancelled_mid = smb2_handle_cancelled_mid,
4634         .downgrade_oplock = smb2_downgrade_oplock,
4635         .need_neg = smb2_need_neg,
4636         .negotiate = smb2_negotiate,
4637         .negotiate_wsize = smb2_negotiate_wsize,
4638         .negotiate_rsize = smb2_negotiate_rsize,
4639         .sess_setup = SMB2_sess_setup,
4640         .logoff = SMB2_logoff,
4641         .tree_connect = SMB2_tcon,
4642         .tree_disconnect = SMB2_tdis,
4643         .qfs_tcon = smb2_qfs_tcon,
4644         .is_path_accessible = smb2_is_path_accessible,
4645         .can_echo = smb2_can_echo,
4646         .echo = SMB2_echo,
4647         .query_path_info = smb2_query_path_info,
4648         .get_srv_inum = smb2_get_srv_inum,
4649         .query_file_info = smb2_query_file_info,
4650         .set_path_size = smb2_set_path_size,
4651         .set_file_size = smb2_set_file_size,
4652         .set_file_info = smb2_set_file_info,
4653         .set_compression = smb2_set_compression,
4654         .mkdir = smb2_mkdir,
4655         .mkdir_setinfo = smb2_mkdir_setinfo,
4656         .rmdir = smb2_rmdir,
4657         .unlink = smb2_unlink,
4658         .rename = smb2_rename_path,
4659         .create_hardlink = smb2_create_hardlink,
4660         .query_symlink = smb2_query_symlink,
4661         .query_mf_symlink = smb3_query_mf_symlink,
4662         .create_mf_symlink = smb3_create_mf_symlink,
4663         .open = smb2_open_file,
4664         .set_fid = smb2_set_fid,
4665         .close = smb2_close_file,
4666         .flush = smb2_flush_file,
4667         .async_readv = smb2_async_readv,
4668         .async_writev = smb2_async_writev,
4669         .sync_read = smb2_sync_read,
4670         .sync_write = smb2_sync_write,
4671         .query_dir_first = smb2_query_dir_first,
4672         .query_dir_next = smb2_query_dir_next,
4673         .close_dir = smb2_close_dir,
4674         .calc_smb_size = smb2_calc_size,
4675         .is_status_pending = smb2_is_status_pending,
4676         .is_session_expired = smb2_is_session_expired,
4677         .oplock_response = smb2_oplock_response,
4678         .queryfs = smb2_queryfs,
4679         .mand_lock = smb2_mand_lock,
4680         .mand_unlock_range = smb2_unlock_range,
4681         .push_mand_locks = smb2_push_mandatory_locks,
4682         .get_lease_key = smb2_get_lease_key,
4683         .set_lease_key = smb2_set_lease_key,
4684         .new_lease_key = smb2_new_lease_key,
4685         .calc_signature = smb2_calc_signature,
4686         .is_read_op = smb21_is_read_op,
4687         .set_oplock_level = smb21_set_oplock_level,
4688         .create_lease_buf = smb2_create_lease_buf,
4689         .parse_lease_buf = smb2_parse_lease_buf,
4690         .copychunk_range = smb2_copychunk_range,
4691         .wp_retry_size = smb2_wp_retry_size,
4692         .dir_needs_close = smb2_dir_needs_close,
4693         .enum_snapshots = smb3_enum_snapshots,
4694         .get_dfs_refer = smb2_get_dfs_refer,
4695         .select_sectype = smb2_select_sectype,
4696 #ifdef CONFIG_CIFS_XATTR
4697         .query_all_EAs = smb2_query_eas,
4698         .set_EA = smb2_set_ea,
4699 #endif /* CIFS_XATTR */
4700         .get_acl = get_smb2_acl,
4701         .get_acl_by_fid = get_smb2_acl_by_fid,
4702         .set_acl = set_smb2_acl,
4703         .next_header = smb2_next_header,
4704         .ioctl_query_info = smb2_ioctl_query_info,
4705         .make_node = smb2_make_node,
4706         .fiemap = smb3_fiemap,
4707         .llseek = smb3_llseek,
4708 };
4709
4710 struct smb_version_operations smb30_operations = {
4711         .compare_fids = smb2_compare_fids,
4712         .setup_request = smb2_setup_request,
4713         .setup_async_request = smb2_setup_async_request,
4714         .check_receive = smb2_check_receive,
4715         .add_credits = smb2_add_credits,
4716         .set_credits = smb2_set_credits,
4717         .get_credits_field = smb2_get_credits_field,
4718         .get_credits = smb2_get_credits,
4719         .wait_mtu_credits = smb2_wait_mtu_credits,
4720         .adjust_credits = smb2_adjust_credits,
4721         .get_next_mid = smb2_get_next_mid,
4722         .revert_current_mid = smb2_revert_current_mid,
4723         .read_data_offset = smb2_read_data_offset,
4724         .read_data_length = smb2_read_data_length,
4725         .map_error = map_smb2_to_linux_error,
4726         .find_mid = smb2_find_mid,
4727         .check_message = smb2_check_message,
4728         .dump_detail = smb2_dump_detail,
4729         .clear_stats = smb2_clear_stats,
4730         .print_stats = smb2_print_stats,
4731         .dump_share_caps = smb2_dump_share_caps,
4732         .is_oplock_break = smb2_is_valid_oplock_break,
4733         .handle_cancelled_mid = smb2_handle_cancelled_mid,
4734         .downgrade_oplock = smb3_downgrade_oplock,
4735         .need_neg = smb2_need_neg,
4736         .negotiate = smb2_negotiate,
4737         .negotiate_wsize = smb3_negotiate_wsize,
4738         .negotiate_rsize = smb3_negotiate_rsize,
4739         .sess_setup = SMB2_sess_setup,
4740         .logoff = SMB2_logoff,
4741         .tree_connect = SMB2_tcon,
4742         .tree_disconnect = SMB2_tdis,
4743         .qfs_tcon = smb3_qfs_tcon,
4744         .is_path_accessible = smb2_is_path_accessible,
4745         .can_echo = smb2_can_echo,
4746         .echo = SMB2_echo,
4747         .query_path_info = smb2_query_path_info,
4748         .get_srv_inum = smb2_get_srv_inum,
4749         .query_file_info = smb2_query_file_info,
4750         .set_path_size = smb2_set_path_size,
4751         .set_file_size = smb2_set_file_size,
4752         .set_file_info = smb2_set_file_info,
4753         .set_compression = smb2_set_compression,
4754         .mkdir = smb2_mkdir,
4755         .mkdir_setinfo = smb2_mkdir_setinfo,
4756         .rmdir = smb2_rmdir,
4757         .unlink = smb2_unlink,
4758         .rename = smb2_rename_path,
4759         .create_hardlink = smb2_create_hardlink,
4760         .query_symlink = smb2_query_symlink,
4761         .query_mf_symlink = smb3_query_mf_symlink,
4762         .create_mf_symlink = smb3_create_mf_symlink,
4763         .open = smb2_open_file,
4764         .set_fid = smb2_set_fid,
4765         .close = smb2_close_file,
4766         .close_getattr = smb2_close_getattr,
4767         .flush = smb2_flush_file,
4768         .async_readv = smb2_async_readv,
4769         .async_writev = smb2_async_writev,
4770         .sync_read = smb2_sync_read,
4771         .sync_write = smb2_sync_write,
4772         .query_dir_first = smb2_query_dir_first,
4773         .query_dir_next = smb2_query_dir_next,
4774         .close_dir = smb2_close_dir,
4775         .calc_smb_size = smb2_calc_size,
4776         .is_status_pending = smb2_is_status_pending,
4777         .is_session_expired = smb2_is_session_expired,
4778         .oplock_response = smb2_oplock_response,
4779         .queryfs = smb2_queryfs,
4780         .mand_lock = smb2_mand_lock,
4781         .mand_unlock_range = smb2_unlock_range,
4782         .push_mand_locks = smb2_push_mandatory_locks,
4783         .get_lease_key = smb2_get_lease_key,
4784         .set_lease_key = smb2_set_lease_key,
4785         .new_lease_key = smb2_new_lease_key,
4786         .generate_signingkey = generate_smb30signingkey,
4787         .calc_signature = smb3_calc_signature,
4788         .set_integrity  = smb3_set_integrity,
4789         .is_read_op = smb21_is_read_op,
4790         .set_oplock_level = smb3_set_oplock_level,
4791         .create_lease_buf = smb3_create_lease_buf,
4792         .parse_lease_buf = smb3_parse_lease_buf,
4793         .copychunk_range = smb2_copychunk_range,
4794         .duplicate_extents = smb2_duplicate_extents,
4795         .validate_negotiate = smb3_validate_negotiate,
4796         .wp_retry_size = smb2_wp_retry_size,
4797         .dir_needs_close = smb2_dir_needs_close,
4798         .fallocate = smb3_fallocate,
4799         .enum_snapshots = smb3_enum_snapshots,
4800         .init_transform_rq = smb3_init_transform_rq,
4801         .is_transform_hdr = smb3_is_transform_hdr,
4802         .receive_transform = smb3_receive_transform,
4803         .get_dfs_refer = smb2_get_dfs_refer,
4804         .select_sectype = smb2_select_sectype,
4805 #ifdef CONFIG_CIFS_XATTR
4806         .query_all_EAs = smb2_query_eas,
4807         .set_EA = smb2_set_ea,
4808 #endif /* CIFS_XATTR */
4809         .get_acl = get_smb2_acl,
4810         .get_acl_by_fid = get_smb2_acl_by_fid,
4811         .set_acl = set_smb2_acl,
4812         .next_header = smb2_next_header,
4813         .ioctl_query_info = smb2_ioctl_query_info,
4814         .make_node = smb2_make_node,
4815         .fiemap = smb3_fiemap,
4816         .llseek = smb3_llseek,
4817 };
4818
4819 struct smb_version_operations smb311_operations = {
4820         .compare_fids = smb2_compare_fids,
4821         .setup_request = smb2_setup_request,
4822         .setup_async_request = smb2_setup_async_request,
4823         .check_receive = smb2_check_receive,
4824         .add_credits = smb2_add_credits,
4825         .set_credits = smb2_set_credits,
4826         .get_credits_field = smb2_get_credits_field,
4827         .get_credits = smb2_get_credits,
4828         .wait_mtu_credits = smb2_wait_mtu_credits,
4829         .adjust_credits = smb2_adjust_credits,
4830         .get_next_mid = smb2_get_next_mid,
4831         .revert_current_mid = smb2_revert_current_mid,
4832         .read_data_offset = smb2_read_data_offset,
4833         .read_data_length = smb2_read_data_length,
4834         .map_error = map_smb2_to_linux_error,
4835         .find_mid = smb2_find_mid,
4836         .check_message = smb2_check_message,
4837         .dump_detail = smb2_dump_detail,
4838         .clear_stats = smb2_clear_stats,
4839         .print_stats = smb2_print_stats,
4840         .dump_share_caps = smb2_dump_share_caps,
4841         .is_oplock_break = smb2_is_valid_oplock_break,
4842         .handle_cancelled_mid = smb2_handle_cancelled_mid,
4843         .downgrade_oplock = smb3_downgrade_oplock,
4844         .need_neg = smb2_need_neg,
4845         .negotiate = smb2_negotiate,
4846         .negotiate_wsize = smb3_negotiate_wsize,
4847         .negotiate_rsize = smb3_negotiate_rsize,
4848         .sess_setup = SMB2_sess_setup,
4849         .logoff = SMB2_logoff,
4850         .tree_connect = SMB2_tcon,
4851         .tree_disconnect = SMB2_tdis,
4852         .qfs_tcon = smb3_qfs_tcon,
4853         .is_path_accessible = smb2_is_path_accessible,
4854         .can_echo = smb2_can_echo,
4855         .echo = SMB2_echo,
4856         .query_path_info = smb2_query_path_info,
4857         .get_srv_inum = smb2_get_srv_inum,
4858         .query_file_info = smb2_query_file_info,
4859         .set_path_size = smb2_set_path_size,
4860         .set_file_size = smb2_set_file_size,
4861         .set_file_info = smb2_set_file_info,
4862         .set_compression = smb2_set_compression,
4863         .mkdir = smb2_mkdir,
4864         .mkdir_setinfo = smb2_mkdir_setinfo,
4865         .posix_mkdir = smb311_posix_mkdir,
4866         .rmdir = smb2_rmdir,
4867         .unlink = smb2_unlink,
4868         .rename = smb2_rename_path,
4869         .create_hardlink = smb2_create_hardlink,
4870         .query_symlink = smb2_query_symlink,
4871         .query_mf_symlink = smb3_query_mf_symlink,
4872         .create_mf_symlink = smb3_create_mf_symlink,
4873         .open = smb2_open_file,
4874         .set_fid = smb2_set_fid,
4875         .close = smb2_close_file,
4876         .close_getattr = smb2_close_getattr,
4877         .flush = smb2_flush_file,
4878         .async_readv = smb2_async_readv,
4879         .async_writev = smb2_async_writev,
4880         .sync_read = smb2_sync_read,
4881         .sync_write = smb2_sync_write,
4882         .query_dir_first = smb2_query_dir_first,
4883         .query_dir_next = smb2_query_dir_next,
4884         .close_dir = smb2_close_dir,
4885         .calc_smb_size = smb2_calc_size,
4886         .is_status_pending = smb2_is_status_pending,
4887         .is_session_expired = smb2_is_session_expired,
4888         .oplock_response = smb2_oplock_response,
4889         .queryfs = smb311_queryfs,
4890         .mand_lock = smb2_mand_lock,
4891         .mand_unlock_range = smb2_unlock_range,
4892         .push_mand_locks = smb2_push_mandatory_locks,
4893         .get_lease_key = smb2_get_lease_key,
4894         .set_lease_key = smb2_set_lease_key,
4895         .new_lease_key = smb2_new_lease_key,
4896         .generate_signingkey = generate_smb311signingkey,
4897         .calc_signature = smb3_calc_signature,
4898         .set_integrity  = smb3_set_integrity,
4899         .is_read_op = smb21_is_read_op,
4900         .set_oplock_level = smb3_set_oplock_level,
4901         .create_lease_buf = smb3_create_lease_buf,
4902         .parse_lease_buf = smb3_parse_lease_buf,
4903         .copychunk_range = smb2_copychunk_range,
4904         .duplicate_extents = smb2_duplicate_extents,
4905 /*      .validate_negotiate = smb3_validate_negotiate, */ /* not used in 3.11 */
4906         .wp_retry_size = smb2_wp_retry_size,
4907         .dir_needs_close = smb2_dir_needs_close,
4908         .fallocate = smb3_fallocate,
4909         .enum_snapshots = smb3_enum_snapshots,
4910         .init_transform_rq = smb3_init_transform_rq,
4911         .is_transform_hdr = smb3_is_transform_hdr,
4912         .receive_transform = smb3_receive_transform,
4913         .get_dfs_refer = smb2_get_dfs_refer,
4914         .select_sectype = smb2_select_sectype,
4915 #ifdef CONFIG_CIFS_XATTR
4916         .query_all_EAs = smb2_query_eas,
4917         .set_EA = smb2_set_ea,
4918 #endif /* CIFS_XATTR */
4919         .get_acl = get_smb2_acl,
4920         .get_acl_by_fid = get_smb2_acl_by_fid,
4921         .set_acl = set_smb2_acl,
4922         .next_header = smb2_next_header,
4923         .ioctl_query_info = smb2_ioctl_query_info,
4924         .make_node = smb2_make_node,
4925         .fiemap = smb3_fiemap,
4926         .llseek = smb3_llseek,
4927 };
4928
4929 struct smb_version_values smb20_values = {
4930         .version_string = SMB20_VERSION_STRING,
4931         .protocol_id = SMB20_PROT_ID,
4932         .req_capabilities = 0, /* MBZ */
4933         .large_lock_type = 0,
4934         .exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
4935         .shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
4936         .unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
4937         .header_size = sizeof(struct smb2_sync_hdr),
4938         .header_preamble_size = 0,
4939         .max_header_size = MAX_SMB2_HDR_SIZE,
4940         .read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
4941         .lock_cmd = SMB2_LOCK,
4942         .cap_unix = 0,
4943         .cap_nt_find = SMB2_NT_FIND,
4944         .cap_large_files = SMB2_LARGE_FILES,
4945         .signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
4946         .signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
4947         .create_lease_size = sizeof(struct create_lease),
4948 };
4949
4950 struct smb_version_values smb21_values = {
4951         .version_string = SMB21_VERSION_STRING,
4952         .protocol_id = SMB21_PROT_ID,
4953         .req_capabilities = 0, /* MBZ on negotiate req until SMB3 dialect */
4954         .large_lock_type = 0,
4955         .exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
4956         .shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
4957         .unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
4958         .header_size = sizeof(struct smb2_sync_hdr),
4959         .header_preamble_size = 0,
4960         .max_header_size = MAX_SMB2_HDR_SIZE,
4961         .read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
4962         .lock_cmd = SMB2_LOCK,
4963         .cap_unix = 0,
4964         .cap_nt_find = SMB2_NT_FIND,
4965         .cap_large_files = SMB2_LARGE_FILES,
4966         .signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
4967         .signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
4968         .create_lease_size = sizeof(struct create_lease),
4969 };
4970
4971 struct smb_version_values smb3any_values = {
4972         .version_string = SMB3ANY_VERSION_STRING,
4973         .protocol_id = SMB302_PROT_ID, /* doesn't matter, send protocol array */
4974         .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,
4975         .large_lock_type = 0,
4976         .exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
4977         .shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
4978         .unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
4979         .header_size = sizeof(struct smb2_sync_hdr),
4980         .header_preamble_size = 0,
4981         .max_header_size = MAX_SMB2_HDR_SIZE,
4982         .read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
4983         .lock_cmd = SMB2_LOCK,
4984         .cap_unix = 0,
4985         .cap_nt_find = SMB2_NT_FIND,
4986         .cap_large_files = SMB2_LARGE_FILES,
4987         .signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
4988         .signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
4989         .create_lease_size = sizeof(struct create_lease_v2),
4990 };
4991
4992 struct smb_version_values smbdefault_values = {
4993         .version_string = SMBDEFAULT_VERSION_STRING,
4994         .protocol_id = SMB302_PROT_ID, /* doesn't matter, send protocol array */
4995         .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,
4996         .large_lock_type = 0,
4997         .exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
4998         .shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
4999         .unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
5000         .header_size = sizeof(struct smb2_sync_hdr),
5001         .header_preamble_size = 0,
5002         .max_header_size = MAX_SMB2_HDR_SIZE,
5003         .read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
5004         .lock_cmd = SMB2_LOCK,
5005         .cap_unix = 0,
5006         .cap_nt_find = SMB2_NT_FIND,
5007         .cap_large_files = SMB2_LARGE_FILES,
5008         .signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
5009         .signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
5010         .create_lease_size = sizeof(struct create_lease_v2),
5011 };
5012
5013 struct smb_version_values smb30_values = {
5014         .version_string = SMB30_VERSION_STRING,
5015         .protocol_id = SMB30_PROT_ID,
5016         .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,
5017         .large_lock_type = 0,
5018         .exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
5019         .shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
5020         .unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
5021         .header_size = sizeof(struct smb2_sync_hdr),
5022         .header_preamble_size = 0,
5023         .max_header_size = MAX_SMB2_HDR_SIZE,
5024         .read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
5025         .lock_cmd = SMB2_LOCK,
5026         .cap_unix = 0,
5027         .cap_nt_find = SMB2_NT_FIND,
5028         .cap_large_files = SMB2_LARGE_FILES,
5029         .signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
5030         .signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
5031         .create_lease_size = sizeof(struct create_lease_v2),
5032 };
5033
5034 struct smb_version_values smb302_values = {
5035         .version_string = SMB302_VERSION_STRING,
5036         .protocol_id = SMB302_PROT_ID,
5037         .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,
5038         .large_lock_type = 0,
5039         .exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
5040         .shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
5041         .unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
5042         .header_size = sizeof(struct smb2_sync_hdr),
5043         .header_preamble_size = 0,
5044         .max_header_size = MAX_SMB2_HDR_SIZE,
5045         .read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
5046         .lock_cmd = SMB2_LOCK,
5047         .cap_unix = 0,
5048         .cap_nt_find = SMB2_NT_FIND,
5049         .cap_large_files = SMB2_LARGE_FILES,
5050         .signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
5051         .signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
5052         .create_lease_size = sizeof(struct create_lease_v2),
5053 };
5054
5055 struct smb_version_values smb311_values = {
5056         .version_string = SMB311_VERSION_STRING,
5057         .protocol_id = SMB311_PROT_ID,
5058         .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,
5059         .large_lock_type = 0,
5060         .exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
5061         .shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
5062         .unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
5063         .header_size = sizeof(struct smb2_sync_hdr),
5064         .header_preamble_size = 0,
5065         .max_header_size = MAX_SMB2_HDR_SIZE,
5066         .read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
5067         .lock_cmd = SMB2_LOCK,
5068         .cap_unix = 0,
5069         .cap_nt_find = SMB2_NT_FIND,
5070         .cap_large_files = SMB2_LARGE_FILES,
5071         .signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
5072         .signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
5073         .create_lease_size = sizeof(struct create_lease_v2),
5074 };