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