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