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