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