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