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