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