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