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