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