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