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