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