OSDN Git Service

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