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