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