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