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