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