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