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