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