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