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