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