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