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