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