47d3e382ecaac269fd447a381dfa1fa56ca61e64
[linux-2.6-microblaze.git] / fs / cifs / smb2pdu.c
1 /*
2  *   fs/cifs/smb2pdu.c
3  *
4  *   Copyright (C) International Business Machines  Corp., 2009, 2013
5  *                 Etersoft, 2012
6  *   Author(s): Steve French (sfrench@us.ibm.com)
7  *              Pavel Shilovsky (pshilovsky@samba.org) 2012
8  *
9  *   Contains the routines for constructing the SMB2 PDUs themselves
10  *
11  *   This library is free software; you can redistribute it and/or modify
12  *   it under the terms of the GNU Lesser General Public License as published
13  *   by the Free Software Foundation; either version 2.1 of the License, or
14  *   (at your option) any later version.
15  *
16  *   This library is distributed in the hope that it will be useful,
17  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
18  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
19  *   the GNU Lesser General Public License for more details.
20  *
21  *   You should have received a copy of the GNU Lesser General Public License
22  *   along with this library; if not, write to the Free Software
23  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24  */
25
26  /* SMB2 PDU handling routines here - except for leftovers (eg session setup) */
27  /* Note that there are handle based routines which must be                   */
28  /* treated slightly differently for reconnection purposes since we never     */
29  /* want to reuse a stale file handle and only the caller knows the file info */
30
31 #include <linux/fs.h>
32 #include <linux/kernel.h>
33 #include <linux/vfs.h>
34 #include <linux/task_io_accounting_ops.h>
35 #include <linux/uaccess.h>
36 #include <linux/uuid.h>
37 #include <linux/pagemap.h>
38 #include <linux/xattr.h>
39 #include "smb2pdu.h"
40 #include "cifsglob.h"
41 #include "cifsacl.h"
42 #include "cifsproto.h"
43 #include "smb2proto.h"
44 #include "cifs_unicode.h"
45 #include "cifs_debug.h"
46 #include "ntlmssp.h"
47 #include "smb2status.h"
48 #include "smb2glob.h"
49 #include "cifspdu.h"
50 #include "cifs_spnego.h"
51 #include "smbdirect.h"
52 #include "trace.h"
53 #ifdef CONFIG_CIFS_DFS_UPCALL
54 #include "dfs_cache.h"
55 #endif
56
57 /*
58  *  The following table defines the expected "StructureSize" of SMB2 requests
59  *  in order by SMB2 command.  This is similar to "wct" in SMB/CIFS requests.
60  *
61  *  Note that commands are defined in smb2pdu.h in le16 but the array below is
62  *  indexed by command in host byte order.
63  */
64 static const int smb2_req_struct_sizes[NUMBER_OF_SMB2_COMMANDS] = {
65         /* SMB2_NEGOTIATE */ 36,
66         /* SMB2_SESSION_SETUP */ 25,
67         /* SMB2_LOGOFF */ 4,
68         /* SMB2_TREE_CONNECT */ 9,
69         /* SMB2_TREE_DISCONNECT */ 4,
70         /* SMB2_CREATE */ 57,
71         /* SMB2_CLOSE */ 24,
72         /* SMB2_FLUSH */ 24,
73         /* SMB2_READ */ 49,
74         /* SMB2_WRITE */ 49,
75         /* SMB2_LOCK */ 48,
76         /* SMB2_IOCTL */ 57,
77         /* SMB2_CANCEL */ 4,
78         /* SMB2_ECHO */ 4,
79         /* SMB2_QUERY_DIRECTORY */ 33,
80         /* SMB2_CHANGE_NOTIFY */ 32,
81         /* SMB2_QUERY_INFO */ 41,
82         /* SMB2_SET_INFO */ 33,
83         /* SMB2_OPLOCK_BREAK */ 24 /* BB this is 36 for LEASE_BREAK variant */
84 };
85
86 int smb3_encryption_required(const struct cifs_tcon *tcon)
87 {
88         if (!tcon)
89                 return 0;
90         if ((tcon->ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) ||
91             (tcon->share_flags & SHI1005_FLAGS_ENCRYPT_DATA))
92                 return 1;
93         if (tcon->seal &&
94             (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
95                 return 1;
96         return 0;
97 }
98
99 static void
100 smb2_hdr_assemble(struct smb2_sync_hdr *shdr, __le16 smb2_cmd,
101                   const struct cifs_tcon *tcon)
102 {
103         shdr->ProtocolId = SMB2_PROTO_NUMBER;
104         shdr->StructureSize = cpu_to_le16(64);
105         shdr->Command = smb2_cmd;
106         if (tcon && tcon->ses && tcon->ses->server) {
107                 struct TCP_Server_Info *server = tcon->ses->server;
108
109                 spin_lock(&server->req_lock);
110                 /* Request up to 10 credits but don't go over the limit. */
111                 if (server->credits >= server->max_credits)
112                         shdr->CreditRequest = cpu_to_le16(0);
113                 else
114                         shdr->CreditRequest = cpu_to_le16(
115                                 min_t(int, server->max_credits -
116                                                 server->credits, 10));
117                 spin_unlock(&server->req_lock);
118         } else {
119                 shdr->CreditRequest = cpu_to_le16(2);
120         }
121         shdr->ProcessId = cpu_to_le32((__u16)current->tgid);
122
123         if (!tcon)
124                 goto out;
125
126         /* GLOBAL_CAP_LARGE_MTU will only be set if dialect > SMB2.02 */
127         /* See sections 2.2.4 and 3.2.4.1.5 of MS-SMB2 */
128         if ((tcon->ses) && (tcon->ses->server) &&
129             (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
130                 shdr->CreditCharge = cpu_to_le16(1);
131         /* else CreditCharge MBZ */
132
133         shdr->TreeId = tcon->tid;
134         /* Uid is not converted */
135         if (tcon->ses)
136                 shdr->SessionId = tcon->ses->Suid;
137
138         /*
139          * If we would set SMB2_FLAGS_DFS_OPERATIONS on open we also would have
140          * to pass the path on the Open SMB prefixed by \\server\share.
141          * Not sure when we would need to do the augmented path (if ever) and
142          * setting this flag breaks the SMB2 open operation since it is
143          * illegal to send an empty path name (without \\server\share prefix)
144          * when the DFS flag is set in the SMB open header. We could
145          * consider setting the flag on all operations other than open
146          * but it is safer to net set it for now.
147          */
148 /*      if (tcon->share_flags & SHI1005_FLAGS_DFS)
149                 shdr->Flags |= SMB2_FLAGS_DFS_OPERATIONS; */
150
151         if (tcon->ses && tcon->ses->server && tcon->ses->server->sign &&
152             !smb3_encryption_required(tcon))
153                 shdr->Flags |= SMB2_FLAGS_SIGNED;
154 out:
155         return;
156 }
157
158 #ifdef CONFIG_CIFS_DFS_UPCALL
159 static int __smb2_reconnect(const struct nls_table *nlsc,
160                             struct cifs_tcon *tcon)
161 {
162         int rc;
163         struct dfs_cache_tgt_list tl;
164         struct dfs_cache_tgt_iterator *it = NULL;
165         char *tree;
166         const char *tcp_host;
167         size_t tcp_host_len;
168         const char *dfs_host;
169         size_t dfs_host_len;
170
171         tree = kzalloc(MAX_TREE_SIZE, GFP_KERNEL);
172         if (!tree)
173                 return -ENOMEM;
174
175         if (tcon->ipc) {
176                 scnprintf(tree, MAX_TREE_SIZE, "\\\\%s\\IPC$",
177                           tcon->ses->server->hostname);
178                 rc = SMB2_tcon(0, tcon->ses, tree, tcon, nlsc);
179                 goto out;
180         }
181
182         if (!tcon->dfs_path) {
183                 rc = SMB2_tcon(0, tcon->ses, tcon->treeName, tcon, nlsc);
184                 goto out;
185         }
186
187         rc = dfs_cache_noreq_find(tcon->dfs_path + 1, NULL, &tl);
188         if (rc)
189                 goto out;
190
191         extract_unc_hostname(tcon->ses->server->hostname, &tcp_host,
192                              &tcp_host_len);
193
194         for (it = dfs_cache_get_tgt_iterator(&tl); it;
195              it = dfs_cache_get_next_tgt(&tl, it)) {
196                 const char *share, *prefix;
197                 size_t share_len, prefix_len;
198
199                 rc = dfs_cache_get_tgt_share(it, &share, &share_len, &prefix,
200                                              &prefix_len);
201                 if (rc) {
202                         cifs_dbg(VFS, "%s: failed to parse target share %d\n",
203                                  __func__, rc);
204                         continue;
205                 }
206
207                 extract_unc_hostname(share, &dfs_host, &dfs_host_len);
208
209                 if (dfs_host_len != tcp_host_len
210                     || strncasecmp(dfs_host, tcp_host, dfs_host_len) != 0) {
211                         cifs_dbg(FYI, "%s: skipping %.*s, doesn't match %.*s",
212                                  __func__,
213                                  (int)dfs_host_len, dfs_host,
214                                  (int)tcp_host_len, tcp_host);
215                         continue;
216                 }
217
218                 scnprintf(tree, MAX_TREE_SIZE, "\\%.*s", (int)share_len, share);
219
220                 rc = SMB2_tcon(0, tcon->ses, tree, tcon, nlsc);
221                 if (!rc) {
222                         rc = update_super_prepath(tcon, prefix, prefix_len);
223                         break;
224                 }
225                 if (rc == -EREMOTE)
226                         break;
227         }
228
229         if (!rc) {
230                 if (it)
231                         rc = dfs_cache_noreq_update_tgthint(tcon->dfs_path + 1,
232                                                             it);
233                 else
234                         rc = -ENOENT;
235         }
236         dfs_cache_free_tgts(&tl);
237 out:
238         kfree(tree);
239         return rc;
240 }
241 #else
242 static inline int __smb2_reconnect(const struct nls_table *nlsc,
243                                    struct cifs_tcon *tcon)
244 {
245         return SMB2_tcon(0, tcon->ses, tcon->treeName, tcon, nlsc);
246 }
247 #endif
248
249 static int
250 smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon)
251 {
252         int rc;
253         struct nls_table *nls_codepage;
254         struct cifs_ses *ses;
255         struct TCP_Server_Info *server;
256         int retries;
257
258         /*
259          * SMB2s NegProt, SessSetup, Logoff do not have tcon yet so
260          * check for tcp and smb session status done differently
261          * for those three - in the calling routine.
262          */
263         if (tcon == NULL)
264                 return 0;
265
266         if (smb2_command == SMB2_TREE_CONNECT)
267                 return 0;
268
269         if (tcon->tidStatus == CifsExiting) {
270                 /*
271                  * only tree disconnect, open, and write,
272                  * (and ulogoff which does not have tcon)
273                  * are allowed as we start force umount.
274                  */
275                 if ((smb2_command != SMB2_WRITE) &&
276                    (smb2_command != SMB2_CREATE) &&
277                    (smb2_command != SMB2_TREE_DISCONNECT)) {
278                         cifs_dbg(FYI, "can not send cmd %d while umounting\n",
279                                  smb2_command);
280                         return -ENODEV;
281                 }
282         }
283         if ((!tcon->ses) || (tcon->ses->status == CifsExiting) ||
284             (!tcon->ses->server))
285                 return -EIO;
286
287         ses = tcon->ses;
288         server = ses->server;
289
290         retries = server->nr_targets;
291
292         /*
293          * Give demultiplex thread up to 10 seconds to each target available for
294          * reconnect -- should be greater than cifs socket timeout which is 7
295          * seconds.
296          */
297         while (server->tcpStatus == CifsNeedReconnect) {
298                 /*
299                  * Return to caller for TREE_DISCONNECT and LOGOFF and CLOSE
300                  * here since they are implicitly done when session drops.
301                  */
302                 switch (smb2_command) {
303                 /*
304                  * BB Should we keep oplock break and add flush to exceptions?
305                  */
306                 case SMB2_TREE_DISCONNECT:
307                 case SMB2_CANCEL:
308                 case SMB2_CLOSE:
309                 case SMB2_OPLOCK_BREAK:
310                         return -EAGAIN;
311                 }
312
313                 rc = wait_event_interruptible_timeout(server->response_q,
314                                                       (server->tcpStatus != CifsNeedReconnect),
315                                                       10 * HZ);
316                 if (rc < 0) {
317                         cifs_dbg(FYI, "%s: aborting reconnect due to a received"
318                                  " signal by the process\n", __func__);
319                         return -ERESTARTSYS;
320                 }
321
322                 /* are we still trying to reconnect? */
323                 if (server->tcpStatus != CifsNeedReconnect)
324                         break;
325
326                 if (retries && --retries)
327                         continue;
328
329                 /*
330                  * on "soft" mounts we wait once. Hard mounts keep
331                  * retrying until process is killed or server comes
332                  * back on-line
333                  */
334                 if (!tcon->retry) {
335                         cifs_dbg(FYI, "gave up waiting on reconnect in smb_init\n");
336                         return -EHOSTDOWN;
337                 }
338                 retries = server->nr_targets;
339         }
340
341         if (!tcon->ses->need_reconnect && !tcon->need_reconnect)
342                 return 0;
343
344         nls_codepage = load_nls_default();
345
346         /*
347          * need to prevent multiple threads trying to simultaneously reconnect
348          * the same SMB session
349          */
350         mutex_lock(&tcon->ses->session_mutex);
351
352         /*
353          * Recheck after acquire mutex. If another thread is negotiating
354          * and the server never sends an answer the socket will be closed
355          * and tcpStatus set to reconnect.
356          */
357         if (server->tcpStatus == CifsNeedReconnect) {
358                 rc = -EHOSTDOWN;
359                 mutex_unlock(&tcon->ses->session_mutex);
360                 goto out;
361         }
362
363         rc = cifs_negotiate_protocol(0, tcon->ses);
364         if (!rc && tcon->ses->need_reconnect) {
365                 rc = cifs_setup_session(0, tcon->ses, nls_codepage);
366                 if ((rc == -EACCES) && !tcon->retry) {
367                         rc = -EHOSTDOWN;
368                         mutex_unlock(&tcon->ses->session_mutex);
369                         goto failed;
370                 }
371         }
372         if (rc || !tcon->need_reconnect) {
373                 mutex_unlock(&tcon->ses->session_mutex);
374                 goto out;
375         }
376
377         cifs_mark_open_files_invalid(tcon);
378         if (tcon->use_persistent)
379                 tcon->need_reopen_files = true;
380
381         rc = __smb2_reconnect(nls_codepage, tcon);
382         mutex_unlock(&tcon->ses->session_mutex);
383
384         cifs_dbg(FYI, "reconnect tcon rc = %d\n", rc);
385         if (rc) {
386                 /* If sess reconnected but tcon didn't, something strange ... */
387                 printk_once(KERN_WARNING "reconnect tcon failed rc = %d\n", rc);
388                 goto out;
389         }
390
391         if (smb2_command != SMB2_INTERNAL_CMD)
392                 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
393
394         atomic_inc(&tconInfoReconnectCount);
395 out:
396         /*
397          * Check if handle based operation so we know whether we can continue
398          * or not without returning to caller to reset file handle.
399          */
400         /*
401          * BB Is flush done by server on drop of tcp session? Should we special
402          * case it and skip above?
403          */
404         switch (smb2_command) {
405         case SMB2_FLUSH:
406         case SMB2_READ:
407         case SMB2_WRITE:
408         case SMB2_LOCK:
409         case SMB2_IOCTL:
410         case SMB2_QUERY_DIRECTORY:
411         case SMB2_CHANGE_NOTIFY:
412         case SMB2_QUERY_INFO:
413         case SMB2_SET_INFO:
414                 rc = -EAGAIN;
415         }
416 failed:
417         unload_nls(nls_codepage);
418         return rc;
419 }
420
421 static void
422 fill_small_buf(__le16 smb2_command, struct cifs_tcon *tcon, void *buf,
423                unsigned int *total_len)
424 {
425         struct smb2_sync_pdu *spdu = (struct smb2_sync_pdu *)buf;
426         /* lookup word count ie StructureSize from table */
427         __u16 parmsize = smb2_req_struct_sizes[le16_to_cpu(smb2_command)];
428
429         /*
430          * smaller than SMALL_BUFFER_SIZE but bigger than fixed area of
431          * largest operations (Create)
432          */
433         memset(buf, 0, 256);
434
435         smb2_hdr_assemble(&spdu->sync_hdr, smb2_command, tcon);
436         spdu->StructureSize2 = cpu_to_le16(parmsize);
437
438         *total_len = parmsize + sizeof(struct smb2_sync_hdr);
439 }
440
441 /*
442  * Allocate and return pointer to an SMB request hdr, and set basic
443  * SMB information in the SMB header. If the return code is zero, this
444  * function must have filled in request_buf pointer.
445  */
446 static int __smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
447                                   void **request_buf, unsigned int *total_len)
448 {
449         /* BB eventually switch this to SMB2 specific small buf size */
450         if (smb2_command == SMB2_SET_INFO)
451                 *request_buf = cifs_buf_get();
452         else
453                 *request_buf = cifs_small_buf_get();
454         if (*request_buf == NULL) {
455                 /* BB should we add a retry in here if not a writepage? */
456                 return -ENOMEM;
457         }
458
459         fill_small_buf(smb2_command, tcon,
460                        (struct smb2_sync_hdr *)(*request_buf),
461                        total_len);
462
463         if (tcon != NULL) {
464                 uint16_t com_code = le16_to_cpu(smb2_command);
465                 cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]);
466                 cifs_stats_inc(&tcon->num_smbs_sent);
467         }
468
469         return 0;
470 }
471
472 static int smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
473                                void **request_buf, unsigned int *total_len)
474 {
475         int rc;
476
477         rc = smb2_reconnect(smb2_command, tcon);
478         if (rc)
479                 return rc;
480
481         return __smb2_plain_req_init(smb2_command, tcon, request_buf,
482                                      total_len);
483 }
484
485 static int smb2_ioctl_req_init(u32 opcode, struct cifs_tcon *tcon,
486                                void **request_buf, unsigned int *total_len)
487 {
488         /* Skip reconnect only for FSCTL_VALIDATE_NEGOTIATE_INFO IOCTLs */
489         if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO) {
490                 return __smb2_plain_req_init(SMB2_IOCTL, tcon, request_buf,
491                                              total_len);
492         }
493         return smb2_plain_req_init(SMB2_IOCTL, tcon, request_buf, total_len);
494 }
495
496 /* For explanation of negotiate contexts see MS-SMB2 section 2.2.3.1 */
497
498 static void
499 build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt)
500 {
501         pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
502         pneg_ctxt->DataLength = cpu_to_le16(38);
503         pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
504         pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
505         get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
506         pneg_ctxt->HashAlgorithms = SMB2_PREAUTH_INTEGRITY_SHA512;
507 }
508
509 static void
510 build_compression_ctxt(struct smb2_compression_capabilities_context *pneg_ctxt)
511 {
512         pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
513         pneg_ctxt->DataLength =
514                 cpu_to_le16(sizeof(struct smb2_compression_capabilities_context)
515                           - sizeof(struct smb2_neg_context));
516         pneg_ctxt->CompressionAlgorithmCount = cpu_to_le16(3);
517         pneg_ctxt->CompressionAlgorithms[0] = SMB3_COMPRESS_LZ77;
518         pneg_ctxt->CompressionAlgorithms[1] = SMB3_COMPRESS_LZ77_HUFF;
519         pneg_ctxt->CompressionAlgorithms[2] = SMB3_COMPRESS_LZNT1;
520 }
521
522 static void
523 build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt)
524 {
525         pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
526         pneg_ctxt->DataLength = cpu_to_le16(6); /* Cipher Count + two ciphers */
527         pneg_ctxt->CipherCount = cpu_to_le16(2);
528         pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;
529         pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES128_CCM;
530 }
531
532 static unsigned int
533 build_netname_ctxt(struct smb2_netname_neg_context *pneg_ctxt, char *hostname)
534 {
535         struct nls_table *cp = load_nls_default();
536
537         pneg_ctxt->ContextType = SMB2_NETNAME_NEGOTIATE_CONTEXT_ID;
538
539         /* copy up to max of first 100 bytes of server name to NetName field */
540         pneg_ctxt->DataLength = cpu_to_le16(2 * cifs_strtoUTF16(pneg_ctxt->NetName, hostname, 100, cp));
541         /* context size is DataLength + minimal smb2_neg_context */
542         return DIV_ROUND_UP(le16_to_cpu(pneg_ctxt->DataLength) +
543                         sizeof(struct smb2_neg_context), 8) * 8;
544 }
545
546 static void
547 build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
548 {
549         pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
550         pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
551         /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
552         pneg_ctxt->Name[0] = 0x93;
553         pneg_ctxt->Name[1] = 0xAD;
554         pneg_ctxt->Name[2] = 0x25;
555         pneg_ctxt->Name[3] = 0x50;
556         pneg_ctxt->Name[4] = 0x9C;
557         pneg_ctxt->Name[5] = 0xB4;
558         pneg_ctxt->Name[6] = 0x11;
559         pneg_ctxt->Name[7] = 0xE7;
560         pneg_ctxt->Name[8] = 0xB4;
561         pneg_ctxt->Name[9] = 0x23;
562         pneg_ctxt->Name[10] = 0x83;
563         pneg_ctxt->Name[11] = 0xDE;
564         pneg_ctxt->Name[12] = 0x96;
565         pneg_ctxt->Name[13] = 0x8B;
566         pneg_ctxt->Name[14] = 0xCD;
567         pneg_ctxt->Name[15] = 0x7C;
568 }
569
570 static void
571 assemble_neg_contexts(struct smb2_negotiate_req *req,
572                       struct TCP_Server_Info *server, unsigned int *total_len)
573 {
574         char *pneg_ctxt;
575         unsigned int ctxt_len;
576
577         if (*total_len > 200) {
578                 /* In case length corrupted don't want to overrun smb buffer */
579                 cifs_server_dbg(VFS, "Bad frame length assembling neg contexts\n");
580                 return;
581         }
582
583         /*
584          * round up total_len of fixed part of SMB3 negotiate request to 8
585          * byte boundary before adding negotiate contexts
586          */
587         *total_len = roundup(*total_len, 8);
588
589         pneg_ctxt = (*total_len) + (char *)req;
590         req->NegotiateContextOffset = cpu_to_le32(*total_len);
591
592         build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt);
593         ctxt_len = DIV_ROUND_UP(sizeof(struct smb2_preauth_neg_context), 8) * 8;
594         *total_len += ctxt_len;
595         pneg_ctxt += ctxt_len;
596
597         build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt);
598         ctxt_len = DIV_ROUND_UP(sizeof(struct smb2_encryption_neg_context), 8) * 8;
599         *total_len += ctxt_len;
600         pneg_ctxt += ctxt_len;
601
602         if (server->compress_algorithm) {
603                 build_compression_ctxt((struct smb2_compression_capabilities_context *)
604                                 pneg_ctxt);
605                 ctxt_len = DIV_ROUND_UP(
606                         sizeof(struct smb2_compression_capabilities_context),
607                                 8) * 8;
608                 *total_len += ctxt_len;
609                 pneg_ctxt += ctxt_len;
610                 req->NegotiateContextCount = cpu_to_le16(5);
611         } else
612                 req->NegotiateContextCount = cpu_to_le16(4);
613
614         ctxt_len = build_netname_ctxt((struct smb2_netname_neg_context *)pneg_ctxt,
615                                         server->hostname);
616         *total_len += ctxt_len;
617         pneg_ctxt += ctxt_len;
618
619         build_posix_ctxt((struct smb2_posix_neg_context *)pneg_ctxt);
620         *total_len += sizeof(struct smb2_posix_neg_context);
621 }
622
623 static void decode_preauth_context(struct smb2_preauth_neg_context *ctxt)
624 {
625         unsigned int len = le16_to_cpu(ctxt->DataLength);
626
627         /* If invalid preauth context warn but use what we requested, SHA-512 */
628         if (len < MIN_PREAUTH_CTXT_DATA_LEN) {
629                 printk_once(KERN_WARNING "server sent bad preauth context\n");
630                 return;
631         }
632         if (le16_to_cpu(ctxt->HashAlgorithmCount) != 1)
633                 printk_once(KERN_WARNING "illegal SMB3 hash algorithm count\n");
634         if (ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
635                 printk_once(KERN_WARNING "unknown SMB3 hash algorithm\n");
636 }
637
638 static void decode_compress_ctx(struct TCP_Server_Info *server,
639                          struct smb2_compression_capabilities_context *ctxt)
640 {
641         unsigned int len = le16_to_cpu(ctxt->DataLength);
642
643         /* sizeof compress context is a one element compression capbility struct */
644         if (len < 10) {
645                 printk_once(KERN_WARNING "server sent bad compression cntxt\n");
646                 return;
647         }
648         if (le16_to_cpu(ctxt->CompressionAlgorithmCount) != 1) {
649                 printk_once(KERN_WARNING "illegal SMB3 compress algorithm count\n");
650                 return;
651         }
652         if (le16_to_cpu(ctxt->CompressionAlgorithms[0]) > 3) {
653                 printk_once(KERN_WARNING "unknown compression algorithm\n");
654                 return;
655         }
656         server->compress_algorithm = ctxt->CompressionAlgorithms[0];
657 }
658
659 static int decode_encrypt_ctx(struct TCP_Server_Info *server,
660                               struct smb2_encryption_neg_context *ctxt)
661 {
662         unsigned int len = le16_to_cpu(ctxt->DataLength);
663
664         cifs_dbg(FYI, "decode SMB3.11 encryption neg context of len %d\n", len);
665         if (len < MIN_ENCRYPT_CTXT_DATA_LEN) {
666                 printk_once(KERN_WARNING "server sent bad crypto ctxt len\n");
667                 return -EINVAL;
668         }
669
670         if (le16_to_cpu(ctxt->CipherCount) != 1) {
671                 printk_once(KERN_WARNING "illegal SMB3.11 cipher count\n");
672                 return -EINVAL;
673         }
674         cifs_dbg(FYI, "SMB311 cipher type:%d\n", le16_to_cpu(ctxt->Ciphers[0]));
675         if ((ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES128_CCM) &&
676             (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES128_GCM)) {
677                 printk_once(KERN_WARNING "invalid SMB3.11 cipher returned\n");
678                 return -EINVAL;
679         }
680         server->cipher_type = ctxt->Ciphers[0];
681         server->capabilities |= SMB2_GLOBAL_CAP_ENCRYPTION;
682         return 0;
683 }
684
685 static int smb311_decode_neg_context(struct smb2_negotiate_rsp *rsp,
686                                      struct TCP_Server_Info *server,
687                                      unsigned int len_of_smb)
688 {
689         struct smb2_neg_context *pctx;
690         unsigned int offset = le32_to_cpu(rsp->NegotiateContextOffset);
691         unsigned int ctxt_cnt = le16_to_cpu(rsp->NegotiateContextCount);
692         unsigned int len_of_ctxts, i;
693         int rc = 0;
694
695         cifs_dbg(FYI, "decoding %d negotiate contexts\n", ctxt_cnt);
696         if (len_of_smb <= offset) {
697                 cifs_server_dbg(VFS, "Invalid response: negotiate context offset\n");
698                 return -EINVAL;
699         }
700
701         len_of_ctxts = len_of_smb - offset;
702
703         for (i = 0; i < ctxt_cnt; i++) {
704                 int clen;
705                 /* check that offset is not beyond end of SMB */
706                 if (len_of_ctxts == 0)
707                         break;
708
709                 if (len_of_ctxts < sizeof(struct smb2_neg_context))
710                         break;
711
712                 pctx = (struct smb2_neg_context *)(offset + (char *)rsp);
713                 clen = le16_to_cpu(pctx->DataLength);
714                 if (clen > len_of_ctxts)
715                         break;
716
717                 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES)
718                         decode_preauth_context(
719                                 (struct smb2_preauth_neg_context *)pctx);
720                 else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES)
721                         rc = decode_encrypt_ctx(server,
722                                 (struct smb2_encryption_neg_context *)pctx);
723                 else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES)
724                         decode_compress_ctx(server,
725                                 (struct smb2_compression_capabilities_context *)pctx);
726                 else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE)
727                         server->posix_ext_supported = true;
728                 else
729                         cifs_server_dbg(VFS, "unknown negcontext of type %d ignored\n",
730                                 le16_to_cpu(pctx->ContextType));
731
732                 if (rc)
733                         break;
734                 /* offsets must be 8 byte aligned */
735                 clen = (clen + 7) & ~0x7;
736                 offset += clen + sizeof(struct smb2_neg_context);
737                 len_of_ctxts -= clen;
738         }
739         return rc;
740 }
741
742 static struct create_posix *
743 create_posix_buf(umode_t mode)
744 {
745         struct create_posix *buf;
746
747         buf = kzalloc(sizeof(struct create_posix),
748                         GFP_KERNEL);
749         if (!buf)
750                 return NULL;
751
752         buf->ccontext.DataOffset =
753                 cpu_to_le16(offsetof(struct create_posix, Mode));
754         buf->ccontext.DataLength = cpu_to_le32(4);
755         buf->ccontext.NameOffset =
756                 cpu_to_le16(offsetof(struct create_posix, Name));
757         buf->ccontext.NameLength = cpu_to_le16(16);
758
759         /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
760         buf->Name[0] = 0x93;
761         buf->Name[1] = 0xAD;
762         buf->Name[2] = 0x25;
763         buf->Name[3] = 0x50;
764         buf->Name[4] = 0x9C;
765         buf->Name[5] = 0xB4;
766         buf->Name[6] = 0x11;
767         buf->Name[7] = 0xE7;
768         buf->Name[8] = 0xB4;
769         buf->Name[9] = 0x23;
770         buf->Name[10] = 0x83;
771         buf->Name[11] = 0xDE;
772         buf->Name[12] = 0x96;
773         buf->Name[13] = 0x8B;
774         buf->Name[14] = 0xCD;
775         buf->Name[15] = 0x7C;
776         buf->Mode = cpu_to_le32(mode);
777         cifs_dbg(FYI, "mode on posix create 0%o", mode);
778         return buf;
779 }
780
781 static int
782 add_posix_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode)
783 {
784         struct smb2_create_req *req = iov[0].iov_base;
785         unsigned int num = *num_iovec;
786
787         iov[num].iov_base = create_posix_buf(mode);
788         if (mode == ACL_NO_MODE)
789                 cifs_dbg(FYI, "illegal mode\n");
790         if (iov[num].iov_base == NULL)
791                 return -ENOMEM;
792         iov[num].iov_len = sizeof(struct create_posix);
793         if (!req->CreateContextsOffset)
794                 req->CreateContextsOffset = cpu_to_le32(
795                                 sizeof(struct smb2_create_req) +
796                                 iov[num - 1].iov_len);
797         le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_posix));
798         *num_iovec = num + 1;
799         return 0;
800 }
801
802
803 /*
804  *
805  *      SMB2 Worker functions follow:
806  *
807  *      The general structure of the worker functions is:
808  *      1) Call smb2_init (assembles SMB2 header)
809  *      2) Initialize SMB2 command specific fields in fixed length area of SMB
810  *      3) Call smb_sendrcv2 (sends request on socket and waits for response)
811  *      4) Decode SMB2 command specific fields in the fixed length area
812  *      5) Decode variable length data area (if any for this SMB2 command type)
813  *      6) Call free smb buffer
814  *      7) return
815  *
816  */
817
818 int
819 SMB2_negotiate(const unsigned int xid, struct cifs_ses *ses)
820 {
821         struct smb_rqst rqst;
822         struct smb2_negotiate_req *req;
823         struct smb2_negotiate_rsp *rsp;
824         struct kvec iov[1];
825         struct kvec rsp_iov;
826         int rc = 0;
827         int resp_buftype;
828         struct TCP_Server_Info *server = cifs_ses_server(ses);
829         int blob_offset, blob_length;
830         char *security_blob;
831         int flags = CIFS_NEG_OP;
832         unsigned int total_len;
833
834         cifs_dbg(FYI, "Negotiate protocol\n");
835
836         if (!server) {
837                 WARN(1, "%s: server is NULL!\n", __func__);
838                 return -EIO;
839         }
840
841         rc = smb2_plain_req_init(SMB2_NEGOTIATE, NULL, (void **) &req, &total_len);
842         if (rc)
843                 return rc;
844
845         req->sync_hdr.SessionId = 0;
846
847         memset(server->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
848         memset(ses->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
849
850         if (strcmp(server->vals->version_string,
851                    SMB3ANY_VERSION_STRING) == 0) {
852                 req->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
853                 req->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
854                 req->DialectCount = cpu_to_le16(2);
855                 total_len += 4;
856         } else if (strcmp(server->vals->version_string,
857                    SMBDEFAULT_VERSION_STRING) == 0) {
858                 req->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
859                 req->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
860                 req->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
861                 req->Dialects[3] = cpu_to_le16(SMB311_PROT_ID);
862                 req->DialectCount = cpu_to_le16(4);
863                 total_len += 8;
864         } else {
865                 /* otherwise send specific dialect */
866                 req->Dialects[0] = cpu_to_le16(server->vals->protocol_id);
867                 req->DialectCount = cpu_to_le16(1);
868                 total_len += 2;
869         }
870
871         /* only one of SMB2 signing flags may be set in SMB2 request */
872         if (ses->sign)
873                 req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
874         else if (global_secflags & CIFSSEC_MAY_SIGN)
875                 req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
876         else
877                 req->SecurityMode = 0;
878
879         req->Capabilities = cpu_to_le32(server->vals->req_capabilities);
880
881         /* ClientGUID must be zero for SMB2.02 dialect */
882         if (server->vals->protocol_id == SMB20_PROT_ID)
883                 memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE);
884         else {
885                 memcpy(req->ClientGUID, server->client_guid,
886                         SMB2_CLIENT_GUID_SIZE);
887                 if ((server->vals->protocol_id == SMB311_PROT_ID) ||
888                     (strcmp(server->vals->version_string,
889                      SMBDEFAULT_VERSION_STRING) == 0))
890                         assemble_neg_contexts(req, server, &total_len);
891         }
892         iov[0].iov_base = (char *)req;
893         iov[0].iov_len = total_len;
894
895         memset(&rqst, 0, sizeof(struct smb_rqst));
896         rqst.rq_iov = iov;
897         rqst.rq_nvec = 1;
898
899         rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
900         cifs_small_buf_release(req);
901         rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base;
902         /*
903          * No tcon so can't do
904          * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
905          */
906         if (rc == -EOPNOTSUPP) {
907                 cifs_server_dbg(VFS, "Dialect not supported by server. Consider "
908                         "specifying vers=1.0 or vers=2.0 on mount for accessing"
909                         " older servers\n");
910                 goto neg_exit;
911         } else if (rc != 0)
912                 goto neg_exit;
913
914         if (strcmp(server->vals->version_string,
915                    SMB3ANY_VERSION_STRING) == 0) {
916                 if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
917                         cifs_server_dbg(VFS,
918                                 "SMB2 dialect returned but not requested\n");
919                         return -EIO;
920                 } else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
921                         cifs_server_dbg(VFS,
922                                 "SMB2.1 dialect returned but not requested\n");
923                         return -EIO;
924                 }
925         } else if (strcmp(server->vals->version_string,
926                    SMBDEFAULT_VERSION_STRING) == 0) {
927                 if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
928                         cifs_server_dbg(VFS,
929                                 "SMB2 dialect returned but not requested\n");
930                         return -EIO;
931                 } else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
932                         /* ops set to 3.0 by default for default so update */
933                         server->ops = &smb21_operations;
934                         server->vals = &smb21_values;
935                 } else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
936                         server->ops = &smb311_operations;
937                         server->vals = &smb311_values;
938                 }
939         } else if (le16_to_cpu(rsp->DialectRevision) !=
940                                 server->vals->protocol_id) {
941                 /* if requested single dialect ensure returned dialect matched */
942                 cifs_server_dbg(VFS, "Illegal 0x%x dialect returned: not requested\n",
943                         le16_to_cpu(rsp->DialectRevision));
944                 return -EIO;
945         }
946
947         cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode);
948
949         if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID))
950                 cifs_dbg(FYI, "negotiated smb2.0 dialect\n");
951         else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID))
952                 cifs_dbg(FYI, "negotiated smb2.1 dialect\n");
953         else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID))
954                 cifs_dbg(FYI, "negotiated smb3.0 dialect\n");
955         else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID))
956                 cifs_dbg(FYI, "negotiated smb3.02 dialect\n");
957         else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))
958                 cifs_dbg(FYI, "negotiated smb3.1.1 dialect\n");
959         else {
960                 cifs_server_dbg(VFS, "Illegal dialect returned by server 0x%x\n",
961                          le16_to_cpu(rsp->DialectRevision));
962                 rc = -EIO;
963                 goto neg_exit;
964         }
965         server->dialect = le16_to_cpu(rsp->DialectRevision);
966
967         /*
968          * Keep a copy of the hash after negprot. This hash will be
969          * the starting hash value for all sessions made from this
970          * server.
971          */
972         memcpy(server->preauth_sha_hash, ses->preauth_sha_hash,
973                SMB2_PREAUTH_HASH_SIZE);
974
975         /* SMB2 only has an extended negflavor */
976         server->negflavor = CIFS_NEGFLAVOR_EXTENDED;
977         /* set it to the maximum buffer size value we can send with 1 credit */
978         server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize),
979                                SMB2_MAX_BUFFER_SIZE);
980         server->max_read = le32_to_cpu(rsp->MaxReadSize);
981         server->max_write = le32_to_cpu(rsp->MaxWriteSize);
982         server->sec_mode = le16_to_cpu(rsp->SecurityMode);
983         if ((server->sec_mode & SMB2_SEC_MODE_FLAGS_ALL) != server->sec_mode)
984                 cifs_dbg(FYI, "Server returned unexpected security mode 0x%x\n",
985                                 server->sec_mode);
986         server->capabilities = le32_to_cpu(rsp->Capabilities);
987         /* Internal types */
988         server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES;
989
990         security_blob = smb2_get_data_area_len(&blob_offset, &blob_length,
991                                                (struct smb2_sync_hdr *)rsp);
992         /*
993          * See MS-SMB2 section 2.2.4: if no blob, client picks default which
994          * for us will be
995          *      ses->sectype = RawNTLMSSP;
996          * but for time being this is our only auth choice so doesn't matter.
997          * We just found a server which sets blob length to zero expecting raw.
998          */
999         if (blob_length == 0) {
1000                 cifs_dbg(FYI, "missing security blob on negprot\n");
1001                 server->sec_ntlmssp = true;
1002         }
1003
1004         rc = cifs_enable_signing(server, ses->sign);
1005         if (rc)
1006                 goto neg_exit;
1007         if (blob_length) {
1008                 rc = decode_negTokenInit(security_blob, blob_length, server);
1009                 if (rc == 1)
1010                         rc = 0;
1011                 else if (rc == 0)
1012                         rc = -EIO;
1013         }
1014
1015         if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
1016                 if (rsp->NegotiateContextCount)
1017                         rc = smb311_decode_neg_context(rsp, server,
1018                                                        rsp_iov.iov_len);
1019                 else
1020                         cifs_server_dbg(VFS, "Missing expected negotiate contexts\n");
1021         }
1022 neg_exit:
1023         free_rsp_buf(resp_buftype, rsp);
1024         return rc;
1025 }
1026
1027 int smb3_validate_negotiate(const unsigned int xid, struct cifs_tcon *tcon)
1028 {
1029         int rc;
1030         struct validate_negotiate_info_req *pneg_inbuf;
1031         struct validate_negotiate_info_rsp *pneg_rsp = NULL;
1032         u32 rsplen;
1033         u32 inbuflen; /* max of 4 dialects */
1034         struct TCP_Server_Info *server = tcon->ses->server;
1035
1036         cifs_dbg(FYI, "validate negotiate\n");
1037
1038         /* In SMB3.11 preauth integrity supersedes validate negotiate */
1039         if (server->dialect == SMB311_PROT_ID)
1040                 return 0;
1041
1042         /*
1043          * validation ioctl must be signed, so no point sending this if we
1044          * can not sign it (ie are not known user).  Even if signing is not
1045          * required (enabled but not negotiated), in those cases we selectively
1046          * sign just this, the first and only signed request on a connection.
1047          * Having validation of negotiate info  helps reduce attack vectors.
1048          */
1049         if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST)
1050                 return 0; /* validation requires signing */
1051
1052         if (tcon->ses->user_name == NULL) {
1053                 cifs_dbg(FYI, "Can't validate negotiate: null user mount\n");
1054                 return 0; /* validation requires signing */
1055         }
1056
1057         if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_NULL)
1058                 cifs_tcon_dbg(VFS, "Unexpected null user (anonymous) auth flag sent by server\n");
1059
1060         pneg_inbuf = kmalloc(sizeof(*pneg_inbuf), GFP_NOFS);
1061         if (!pneg_inbuf)
1062                 return -ENOMEM;
1063
1064         pneg_inbuf->Capabilities =
1065                         cpu_to_le32(server->vals->req_capabilities);
1066         memcpy(pneg_inbuf->Guid, server->client_guid,
1067                                         SMB2_CLIENT_GUID_SIZE);
1068
1069         if (tcon->ses->sign)
1070                 pneg_inbuf->SecurityMode =
1071                         cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
1072         else if (global_secflags & CIFSSEC_MAY_SIGN)
1073                 pneg_inbuf->SecurityMode =
1074                         cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
1075         else
1076                 pneg_inbuf->SecurityMode = 0;
1077
1078
1079         if (strcmp(server->vals->version_string,
1080                 SMB3ANY_VERSION_STRING) == 0) {
1081                 pneg_inbuf->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
1082                 pneg_inbuf->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
1083                 pneg_inbuf->DialectCount = cpu_to_le16(2);
1084                 /* structure is big enough for 3 dialects, sending only 2 */
1085                 inbuflen = sizeof(*pneg_inbuf) -
1086                                 (2 * sizeof(pneg_inbuf->Dialects[0]));
1087         } else if (strcmp(server->vals->version_string,
1088                 SMBDEFAULT_VERSION_STRING) == 0) {
1089                 pneg_inbuf->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
1090                 pneg_inbuf->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
1091                 pneg_inbuf->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
1092                 pneg_inbuf->Dialects[3] = cpu_to_le16(SMB311_PROT_ID);
1093                 pneg_inbuf->DialectCount = cpu_to_le16(4);
1094                 /* structure is big enough for 3 dialects */
1095                 inbuflen = sizeof(*pneg_inbuf);
1096         } else {
1097                 /* otherwise specific dialect was requested */
1098                 pneg_inbuf->Dialects[0] =
1099                         cpu_to_le16(server->vals->protocol_id);
1100                 pneg_inbuf->DialectCount = cpu_to_le16(1);
1101                 /* structure is big enough for 3 dialects, sending only 1 */
1102                 inbuflen = sizeof(*pneg_inbuf) -
1103                                 sizeof(pneg_inbuf->Dialects[0]) * 2;
1104         }
1105
1106         rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
1107                 FSCTL_VALIDATE_NEGOTIATE_INFO, true /* is_fsctl */,
1108                 (char *)pneg_inbuf, inbuflen, CIFSMaxBufSize,
1109                 (char **)&pneg_rsp, &rsplen);
1110         if (rc == -EOPNOTSUPP) {
1111                 /*
1112                  * Old Windows versions or Netapp SMB server can return
1113                  * not supported error. Client should accept it.
1114                  */
1115                 cifs_tcon_dbg(VFS, "Server does not support validate negotiate\n");
1116                 rc = 0;
1117                 goto out_free_inbuf;
1118         } else if (rc != 0) {
1119                 cifs_tcon_dbg(VFS, "validate protocol negotiate failed: %d\n", rc);
1120                 rc = -EIO;
1121                 goto out_free_inbuf;
1122         }
1123
1124         rc = -EIO;
1125         if (rsplen != sizeof(*pneg_rsp)) {
1126                 cifs_tcon_dbg(VFS, "invalid protocol negotiate response size: %d\n",
1127                          rsplen);
1128
1129                 /* relax check since Mac returns max bufsize allowed on ioctl */
1130                 if (rsplen > CIFSMaxBufSize || rsplen < sizeof(*pneg_rsp))
1131                         goto out_free_rsp;
1132         }
1133
1134         /* check validate negotiate info response matches what we got earlier */
1135         if (pneg_rsp->Dialect != cpu_to_le16(server->dialect))
1136                 goto vneg_out;
1137
1138         if (pneg_rsp->SecurityMode != cpu_to_le16(server->sec_mode))
1139                 goto vneg_out;
1140
1141         /* do not validate server guid because not saved at negprot time yet */
1142
1143         if ((le32_to_cpu(pneg_rsp->Capabilities) | SMB2_NT_FIND |
1144               SMB2_LARGE_FILES) != server->capabilities)
1145                 goto vneg_out;
1146
1147         /* validate negotiate successful */
1148         rc = 0;
1149         cifs_dbg(FYI, "validate negotiate info successful\n");
1150         goto out_free_rsp;
1151
1152 vneg_out:
1153         cifs_tcon_dbg(VFS, "protocol revalidation - security settings mismatch\n");
1154 out_free_rsp:
1155         kfree(pneg_rsp);
1156 out_free_inbuf:
1157         kfree(pneg_inbuf);
1158         return rc;
1159 }
1160
1161 enum securityEnum
1162 smb2_select_sectype(struct TCP_Server_Info *server, enum securityEnum requested)
1163 {
1164         switch (requested) {
1165         case Kerberos:
1166         case RawNTLMSSP:
1167                 return requested;
1168         case NTLMv2:
1169                 return RawNTLMSSP;
1170         case Unspecified:
1171                 if (server->sec_ntlmssp &&
1172                         (global_secflags & CIFSSEC_MAY_NTLMSSP))
1173                         return RawNTLMSSP;
1174                 if ((server->sec_kerberos || server->sec_mskerberos) &&
1175                         (global_secflags & CIFSSEC_MAY_KRB5))
1176                         return Kerberos;
1177                 /* Fallthrough */
1178         default:
1179                 return Unspecified;
1180         }
1181 }
1182
1183 struct SMB2_sess_data {
1184         unsigned int xid;
1185         struct cifs_ses *ses;
1186         struct nls_table *nls_cp;
1187         void (*func)(struct SMB2_sess_data *);
1188         int result;
1189         u64 previous_session;
1190
1191         /* we will send the SMB in three pieces:
1192          * a fixed length beginning part, an optional
1193          * SPNEGO blob (which can be zero length), and a
1194          * last part which will include the strings
1195          * and rest of bcc area. This allows us to avoid
1196          * a large buffer 17K allocation
1197          */
1198         int buf0_type;
1199         struct kvec iov[2];
1200 };
1201
1202 static int
1203 SMB2_sess_alloc_buffer(struct SMB2_sess_data *sess_data)
1204 {
1205         int rc;
1206         struct cifs_ses *ses = sess_data->ses;
1207         struct smb2_sess_setup_req *req;
1208         struct TCP_Server_Info *server = cifs_ses_server(ses);
1209         unsigned int total_len;
1210
1211         rc = smb2_plain_req_init(SMB2_SESSION_SETUP, NULL, (void **) &req,
1212                              &total_len);
1213         if (rc)
1214                 return rc;
1215
1216         if (sess_data->ses->binding) {
1217                 req->sync_hdr.SessionId = sess_data->ses->Suid;
1218                 req->sync_hdr.Flags |= SMB2_FLAGS_SIGNED;
1219                 req->PreviousSessionId = 0;
1220                 req->Flags = SMB2_SESSION_REQ_FLAG_BINDING;
1221         } else {
1222                 /* First session, not a reauthenticate */
1223                 req->sync_hdr.SessionId = 0;
1224                 /*
1225                  * if reconnect, we need to send previous sess id
1226                  * otherwise it is 0
1227                  */
1228                 req->PreviousSessionId = sess_data->previous_session;
1229                 req->Flags = 0; /* MBZ */
1230         }
1231
1232         /* enough to enable echos and oplocks and one max size write */
1233         req->sync_hdr.CreditRequest = cpu_to_le16(130);
1234
1235         /* only one of SMB2 signing flags may be set in SMB2 request */
1236         if (server->sign)
1237                 req->SecurityMode = SMB2_NEGOTIATE_SIGNING_REQUIRED;
1238         else if (global_secflags & CIFSSEC_MAY_SIGN) /* one flag unlike MUST_ */
1239                 req->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED;
1240         else
1241                 req->SecurityMode = 0;
1242
1243 #ifdef CONFIG_CIFS_DFS_UPCALL
1244         req->Capabilities = cpu_to_le32(SMB2_GLOBAL_CAP_DFS);
1245 #else
1246         req->Capabilities = 0;
1247 #endif /* DFS_UPCALL */
1248
1249         req->Channel = 0; /* MBZ */
1250
1251         sess_data->iov[0].iov_base = (char *)req;
1252         /* 1 for pad */
1253         sess_data->iov[0].iov_len = total_len - 1;
1254         /*
1255          * This variable will be used to clear the buffer
1256          * allocated above in case of any error in the calling function.
1257          */
1258         sess_data->buf0_type = CIFS_SMALL_BUFFER;
1259
1260         return 0;
1261 }
1262
1263 static void
1264 SMB2_sess_free_buffer(struct SMB2_sess_data *sess_data)
1265 {
1266         free_rsp_buf(sess_data->buf0_type, sess_data->iov[0].iov_base);
1267         sess_data->buf0_type = CIFS_NO_BUFFER;
1268 }
1269
1270 static int
1271 SMB2_sess_sendreceive(struct SMB2_sess_data *sess_data)
1272 {
1273         int rc;
1274         struct smb_rqst rqst;
1275         struct smb2_sess_setup_req *req = sess_data->iov[0].iov_base;
1276         struct kvec rsp_iov = { NULL, 0 };
1277
1278         /* Testing shows that buffer offset must be at location of Buffer[0] */
1279         req->SecurityBufferOffset =
1280                 cpu_to_le16(sizeof(struct smb2_sess_setup_req) - 1 /* pad */);
1281         req->SecurityBufferLength = cpu_to_le16(sess_data->iov[1].iov_len);
1282
1283         memset(&rqst, 0, sizeof(struct smb_rqst));
1284         rqst.rq_iov = sess_data->iov;
1285         rqst.rq_nvec = 2;
1286
1287         /* BB add code to build os and lm fields */
1288         rc = cifs_send_recv(sess_data->xid, sess_data->ses,
1289                             &rqst,
1290                             &sess_data->buf0_type,
1291                             CIFS_LOG_ERROR | CIFS_NEG_OP, &rsp_iov);
1292         cifs_small_buf_release(sess_data->iov[0].iov_base);
1293         memcpy(&sess_data->iov[0], &rsp_iov, sizeof(struct kvec));
1294
1295         return rc;
1296 }
1297
1298 static int
1299 SMB2_sess_establish_session(struct SMB2_sess_data *sess_data)
1300 {
1301         int rc = 0;
1302         struct cifs_ses *ses = sess_data->ses;
1303         struct TCP_Server_Info *server = cifs_ses_server(ses);
1304
1305         mutex_lock(&server->srv_mutex);
1306         if (server->ops->generate_signingkey) {
1307                 rc = server->ops->generate_signingkey(ses);
1308                 if (rc) {
1309                         cifs_dbg(FYI,
1310                                 "SMB3 session key generation failed\n");
1311                         mutex_unlock(&server->srv_mutex);
1312                         return rc;
1313                 }
1314         }
1315         if (!server->session_estab) {
1316                 server->sequence_number = 0x2;
1317                 server->session_estab = true;
1318         }
1319         mutex_unlock(&server->srv_mutex);
1320
1321         cifs_dbg(FYI, "SMB2/3 session established successfully\n");
1322         /* keep existing ses state if binding */
1323         if (!ses->binding) {
1324                 spin_lock(&GlobalMid_Lock);
1325                 ses->status = CifsGood;
1326                 ses->need_reconnect = false;
1327                 spin_unlock(&GlobalMid_Lock);
1328         }
1329
1330         return rc;
1331 }
1332
1333 #ifdef CONFIG_CIFS_UPCALL
1334 static void
1335 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
1336 {
1337         int rc;
1338         struct cifs_ses *ses = sess_data->ses;
1339         struct cifs_spnego_msg *msg;
1340         struct key *spnego_key = NULL;
1341         struct smb2_sess_setup_rsp *rsp = NULL;
1342
1343         rc = SMB2_sess_alloc_buffer(sess_data);
1344         if (rc)
1345                 goto out;
1346
1347         spnego_key = cifs_get_spnego_key(ses);
1348         if (IS_ERR(spnego_key)) {
1349                 rc = PTR_ERR(spnego_key);
1350                 spnego_key = NULL;
1351                 goto out;
1352         }
1353
1354         msg = spnego_key->payload.data[0];
1355         /*
1356          * check version field to make sure that cifs.upcall is
1357          * sending us a response in an expected form
1358          */
1359         if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) {
1360                 cifs_dbg(VFS,
1361                           "bad cifs.upcall version. Expected %d got %d",
1362                           CIFS_SPNEGO_UPCALL_VERSION, msg->version);
1363                 rc = -EKEYREJECTED;
1364                 goto out_put_spnego_key;
1365         }
1366
1367         /* keep session key if binding */
1368         if (!ses->binding) {
1369                 ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len,
1370                                                  GFP_KERNEL);
1371                 if (!ses->auth_key.response) {
1372                         cifs_dbg(VFS,
1373                                  "Kerberos can't allocate (%u bytes) memory",
1374                                  msg->sesskey_len);
1375                         rc = -ENOMEM;
1376                         goto out_put_spnego_key;
1377                 }
1378                 ses->auth_key.len = msg->sesskey_len;
1379         }
1380
1381         sess_data->iov[1].iov_base = msg->data + msg->sesskey_len;
1382         sess_data->iov[1].iov_len = msg->secblob_len;
1383
1384         rc = SMB2_sess_sendreceive(sess_data);
1385         if (rc)
1386                 goto out_put_spnego_key;
1387
1388         rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1389         /* keep session id and flags if binding */
1390         if (!ses->binding) {
1391                 ses->Suid = rsp->sync_hdr.SessionId;
1392                 ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1393         }
1394
1395         rc = SMB2_sess_establish_session(sess_data);
1396 out_put_spnego_key:
1397         key_invalidate(spnego_key);
1398         key_put(spnego_key);
1399 out:
1400         sess_data->result = rc;
1401         sess_data->func = NULL;
1402         SMB2_sess_free_buffer(sess_data);
1403 }
1404 #else
1405 static void
1406 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
1407 {
1408         cifs_dbg(VFS, "Kerberos negotiated but upcall support disabled!\n");
1409         sess_data->result = -EOPNOTSUPP;
1410         sess_data->func = NULL;
1411 }
1412 #endif
1413
1414 static void
1415 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data);
1416
1417 static void
1418 SMB2_sess_auth_rawntlmssp_negotiate(struct SMB2_sess_data *sess_data)
1419 {
1420         int rc;
1421         struct cifs_ses *ses = sess_data->ses;
1422         struct smb2_sess_setup_rsp *rsp = NULL;
1423         char *ntlmssp_blob = NULL;
1424         bool use_spnego = false; /* else use raw ntlmssp */
1425         u16 blob_length = 0;
1426
1427         /*
1428          * If memory allocation is successful, caller of this function
1429          * frees it.
1430          */
1431         ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL);
1432         if (!ses->ntlmssp) {
1433                 rc = -ENOMEM;
1434                 goto out_err;
1435         }
1436         ses->ntlmssp->sesskey_per_smbsess = true;
1437
1438         rc = SMB2_sess_alloc_buffer(sess_data);
1439         if (rc)
1440                 goto out_err;
1441
1442         ntlmssp_blob = kmalloc(sizeof(struct _NEGOTIATE_MESSAGE),
1443                                GFP_KERNEL);
1444         if (ntlmssp_blob == NULL) {
1445                 rc = -ENOMEM;
1446                 goto out;
1447         }
1448
1449         build_ntlmssp_negotiate_blob(ntlmssp_blob, ses);
1450         if (use_spnego) {
1451                 /* BB eventually need to add this */
1452                 cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
1453                 rc = -EOPNOTSUPP;
1454                 goto out;
1455         } else {
1456                 blob_length = sizeof(struct _NEGOTIATE_MESSAGE);
1457                 /* with raw NTLMSSP we don't encapsulate in SPNEGO */
1458         }
1459         sess_data->iov[1].iov_base = ntlmssp_blob;
1460         sess_data->iov[1].iov_len = blob_length;
1461
1462         rc = SMB2_sess_sendreceive(sess_data);
1463         rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1464
1465         /* If true, rc here is expected and not an error */
1466         if (sess_data->buf0_type != CIFS_NO_BUFFER &&
1467                 rsp->sync_hdr.Status == STATUS_MORE_PROCESSING_REQUIRED)
1468                 rc = 0;
1469
1470         if (rc)
1471                 goto out;
1472
1473         if (offsetof(struct smb2_sess_setup_rsp, Buffer) !=
1474                         le16_to_cpu(rsp->SecurityBufferOffset)) {
1475                 cifs_dbg(VFS, "Invalid security buffer offset %d\n",
1476                         le16_to_cpu(rsp->SecurityBufferOffset));
1477                 rc = -EIO;
1478                 goto out;
1479         }
1480         rc = decode_ntlmssp_challenge(rsp->Buffer,
1481                         le16_to_cpu(rsp->SecurityBufferLength), ses);
1482         if (rc)
1483                 goto out;
1484
1485         cifs_dbg(FYI, "rawntlmssp session setup challenge phase\n");
1486
1487         /* keep existing ses id and flags if binding */
1488         if (!ses->binding) {
1489                 ses->Suid = rsp->sync_hdr.SessionId;
1490                 ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1491         }
1492
1493 out:
1494         kfree(ntlmssp_blob);
1495         SMB2_sess_free_buffer(sess_data);
1496         if (!rc) {
1497                 sess_data->result = 0;
1498                 sess_data->func = SMB2_sess_auth_rawntlmssp_authenticate;
1499                 return;
1500         }
1501 out_err:
1502         kfree(ses->ntlmssp);
1503         ses->ntlmssp = NULL;
1504         sess_data->result = rc;
1505         sess_data->func = NULL;
1506 }
1507
1508 static void
1509 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data)
1510 {
1511         int rc;
1512         struct cifs_ses *ses = sess_data->ses;
1513         struct smb2_sess_setup_req *req;
1514         struct smb2_sess_setup_rsp *rsp = NULL;
1515         unsigned char *ntlmssp_blob = NULL;
1516         bool use_spnego = false; /* else use raw ntlmssp */
1517         u16 blob_length = 0;
1518
1519         rc = SMB2_sess_alloc_buffer(sess_data);
1520         if (rc)
1521                 goto out;
1522
1523         req = (struct smb2_sess_setup_req *) sess_data->iov[0].iov_base;
1524         req->sync_hdr.SessionId = ses->Suid;
1525
1526         rc = build_ntlmssp_auth_blob(&ntlmssp_blob, &blob_length, ses,
1527                                         sess_data->nls_cp);
1528         if (rc) {
1529                 cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n", rc);
1530                 goto out;
1531         }
1532
1533         if (use_spnego) {
1534                 /* BB eventually need to add this */
1535                 cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
1536                 rc = -EOPNOTSUPP;
1537                 goto out;
1538         }
1539         sess_data->iov[1].iov_base = ntlmssp_blob;
1540         sess_data->iov[1].iov_len = blob_length;
1541
1542         rc = SMB2_sess_sendreceive(sess_data);
1543         if (rc)
1544                 goto out;
1545
1546         rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1547
1548         /* keep existing ses id and flags if binding */
1549         if (!ses->binding) {
1550                 ses->Suid = rsp->sync_hdr.SessionId;
1551                 ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1552         }
1553
1554         rc = SMB2_sess_establish_session(sess_data);
1555 out:
1556         kfree(ntlmssp_blob);
1557         SMB2_sess_free_buffer(sess_data);
1558         kfree(ses->ntlmssp);
1559         ses->ntlmssp = NULL;
1560         sess_data->result = rc;
1561         sess_data->func = NULL;
1562 }
1563
1564 static int
1565 SMB2_select_sec(struct cifs_ses *ses, struct SMB2_sess_data *sess_data)
1566 {
1567         int type;
1568
1569         type = smb2_select_sectype(cifs_ses_server(ses), ses->sectype);
1570         cifs_dbg(FYI, "sess setup type %d\n", type);
1571         if (type == Unspecified) {
1572                 cifs_dbg(VFS,
1573                         "Unable to select appropriate authentication method!");
1574                 return -EINVAL;
1575         }
1576
1577         switch (type) {
1578         case Kerberos:
1579                 sess_data->func = SMB2_auth_kerberos;
1580                 break;
1581         case RawNTLMSSP:
1582                 sess_data->func = SMB2_sess_auth_rawntlmssp_negotiate;
1583                 break;
1584         default:
1585                 cifs_dbg(VFS, "secType %d not supported!\n", type);
1586                 return -EOPNOTSUPP;
1587         }
1588
1589         return 0;
1590 }
1591
1592 int
1593 SMB2_sess_setup(const unsigned int xid, struct cifs_ses *ses,
1594                 const struct nls_table *nls_cp)
1595 {
1596         int rc = 0;
1597         struct TCP_Server_Info *server = cifs_ses_server(ses);
1598         struct SMB2_sess_data *sess_data;
1599
1600         cifs_dbg(FYI, "Session Setup\n");
1601
1602         if (!server) {
1603                 WARN(1, "%s: server is NULL!\n", __func__);
1604                 return -EIO;
1605         }
1606
1607         sess_data = kzalloc(sizeof(struct SMB2_sess_data), GFP_KERNEL);
1608         if (!sess_data)
1609                 return -ENOMEM;
1610
1611         rc = SMB2_select_sec(ses, sess_data);
1612         if (rc)
1613                 goto out;
1614         sess_data->xid = xid;
1615         sess_data->ses = ses;
1616         sess_data->buf0_type = CIFS_NO_BUFFER;
1617         sess_data->nls_cp = (struct nls_table *) nls_cp;
1618         sess_data->previous_session = ses->Suid;
1619
1620         /*
1621          * Initialize the session hash with the server one.
1622          */
1623         memcpy(ses->preauth_sha_hash, server->preauth_sha_hash,
1624                SMB2_PREAUTH_HASH_SIZE);
1625
1626         while (sess_data->func)
1627                 sess_data->func(sess_data);
1628
1629         if ((ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST) && (ses->sign))
1630                 cifs_server_dbg(VFS, "signing requested but authenticated as guest\n");
1631         rc = sess_data->result;
1632 out:
1633         kfree(sess_data);
1634         return rc;
1635 }
1636
1637 int
1638 SMB2_logoff(const unsigned int xid, struct cifs_ses *ses)
1639 {
1640         struct smb_rqst rqst;
1641         struct smb2_logoff_req *req; /* response is also trivial struct */
1642         int rc = 0;
1643         struct TCP_Server_Info *server;
1644         int flags = 0;
1645         unsigned int total_len;
1646         struct kvec iov[1];
1647         struct kvec rsp_iov;
1648         int resp_buf_type;
1649
1650         cifs_dbg(FYI, "disconnect session %p\n", ses);
1651
1652         if (ses && (ses->server))
1653                 server = ses->server;
1654         else
1655                 return -EIO;
1656
1657         /* no need to send SMB logoff if uid already closed due to reconnect */
1658         if (ses->need_reconnect)
1659                 goto smb2_session_already_dead;
1660
1661         rc = smb2_plain_req_init(SMB2_LOGOFF, NULL, (void **) &req, &total_len);
1662         if (rc)
1663                 return rc;
1664
1665          /* since no tcon, smb2_init can not do this, so do here */
1666         req->sync_hdr.SessionId = ses->Suid;
1667
1668         if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA)
1669                 flags |= CIFS_TRANSFORM_REQ;
1670         else if (server->sign)
1671                 req->sync_hdr.Flags |= SMB2_FLAGS_SIGNED;
1672
1673         flags |= CIFS_NO_RSP_BUF;
1674
1675         iov[0].iov_base = (char *)req;
1676         iov[0].iov_len = total_len;
1677
1678         memset(&rqst, 0, sizeof(struct smb_rqst));
1679         rqst.rq_iov = iov;
1680         rqst.rq_nvec = 1;
1681
1682         rc = cifs_send_recv(xid, ses, &rqst, &resp_buf_type, flags, &rsp_iov);
1683         cifs_small_buf_release(req);
1684         /*
1685          * No tcon so can't do
1686          * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
1687          */
1688
1689 smb2_session_already_dead:
1690         return rc;
1691 }
1692
1693 static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code)
1694 {
1695         cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]);
1696 }
1697
1698 #define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */)
1699
1700 /* These are similar values to what Windows uses */
1701 static inline void init_copy_chunk_defaults(struct cifs_tcon *tcon)
1702 {
1703         tcon->max_chunks = 256;
1704         tcon->max_bytes_chunk = 1048576;
1705         tcon->max_bytes_copy = 16777216;
1706 }
1707
1708 int
1709 SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
1710           struct cifs_tcon *tcon, const struct nls_table *cp)
1711 {
1712         struct smb_rqst rqst;
1713         struct smb2_tree_connect_req *req;
1714         struct smb2_tree_connect_rsp *rsp = NULL;
1715         struct kvec iov[2];
1716         struct kvec rsp_iov = { NULL, 0 };
1717         int rc = 0;
1718         int resp_buftype;
1719         int unc_path_len;
1720         __le16 *unc_path = NULL;
1721         int flags = 0;
1722         unsigned int total_len;
1723         struct TCP_Server_Info *server = ses->server;
1724
1725         cifs_dbg(FYI, "TCON\n");
1726
1727         if (!server || !tree)
1728                 return -EIO;
1729
1730         unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
1731         if (unc_path == NULL)
1732                 return -ENOMEM;
1733
1734         unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1;
1735         unc_path_len *= 2;
1736         if (unc_path_len < 2) {
1737                 kfree(unc_path);
1738                 return -EINVAL;
1739         }
1740
1741         /* SMB2 TREE_CONNECT request must be called with TreeId == 0 */
1742         tcon->tid = 0;
1743         atomic_set(&tcon->num_remote_opens, 0);
1744         rc = smb2_plain_req_init(SMB2_TREE_CONNECT, tcon, (void **) &req,
1745                              &total_len);
1746         if (rc) {
1747                 kfree(unc_path);
1748                 return rc;
1749         }
1750
1751         if (smb3_encryption_required(tcon))
1752                 flags |= CIFS_TRANSFORM_REQ;
1753
1754         iov[0].iov_base = (char *)req;
1755         /* 1 for pad */
1756         iov[0].iov_len = total_len - 1;
1757
1758         /* Testing shows that buffer offset must be at location of Buffer[0] */
1759         req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req)
1760                         - 1 /* pad */);
1761         req->PathLength = cpu_to_le16(unc_path_len - 2);
1762         iov[1].iov_base = unc_path;
1763         iov[1].iov_len = unc_path_len;
1764
1765         /*
1766          * 3.11 tcon req must be signed if not encrypted. See MS-SMB2 3.2.4.1.1
1767          * unless it is guest or anonymous user. See MS-SMB2 3.2.5.3.1
1768          * (Samba servers don't always set the flag so also check if null user)
1769          */
1770         if ((server->dialect == SMB311_PROT_ID) &&
1771             !smb3_encryption_required(tcon) &&
1772             !(ses->session_flags &
1773                     (SMB2_SESSION_FLAG_IS_GUEST|SMB2_SESSION_FLAG_IS_NULL)) &&
1774             ((ses->user_name != NULL) || (ses->sectype == Kerberos)))
1775                 req->sync_hdr.Flags |= SMB2_FLAGS_SIGNED;
1776
1777         memset(&rqst, 0, sizeof(struct smb_rqst));
1778         rqst.rq_iov = iov;
1779         rqst.rq_nvec = 2;
1780
1781         /* Need 64 for max size write so ask for more in case not there yet */
1782         req->sync_hdr.CreditRequest = cpu_to_le16(64);
1783
1784         rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
1785         cifs_small_buf_release(req);
1786         rsp = (struct smb2_tree_connect_rsp *)rsp_iov.iov_base;
1787         trace_smb3_tcon(xid, tcon->tid, ses->Suid, tree, rc);
1788         if (rc != 0) {
1789                 if (tcon) {
1790                         cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
1791                         tcon->need_reconnect = true;
1792                 }
1793                 goto tcon_error_exit;
1794         }
1795
1796         switch (rsp->ShareType) {
1797         case SMB2_SHARE_TYPE_DISK:
1798                 cifs_dbg(FYI, "connection to disk share\n");
1799                 break;
1800         case SMB2_SHARE_TYPE_PIPE:
1801                 tcon->pipe = true;
1802                 cifs_dbg(FYI, "connection to pipe share\n");
1803                 break;
1804         case SMB2_SHARE_TYPE_PRINT:
1805                 tcon->print = true;
1806                 cifs_dbg(FYI, "connection to printer\n");
1807                 break;
1808         default:
1809                 cifs_server_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
1810                 rc = -EOPNOTSUPP;
1811                 goto tcon_error_exit;
1812         }
1813
1814         tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
1815         tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
1816         tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1817         tcon->tidStatus = CifsGood;
1818         tcon->need_reconnect = false;
1819         tcon->tid = rsp->sync_hdr.TreeId;
1820         strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
1821
1822         if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
1823             ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
1824                 cifs_tcon_dbg(VFS, "DFS capability contradicts DFS flag\n");
1825
1826         if (tcon->seal &&
1827             !(server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
1828                 cifs_tcon_dbg(VFS, "Encryption is requested but not supported\n");
1829
1830         init_copy_chunk_defaults(tcon);
1831         if (server->ops->validate_negotiate)
1832                 rc = server->ops->validate_negotiate(xid, tcon);
1833 tcon_exit:
1834
1835         free_rsp_buf(resp_buftype, rsp);
1836         kfree(unc_path);
1837         return rc;
1838
1839 tcon_error_exit:
1840         if (rsp && rsp->sync_hdr.Status == STATUS_BAD_NETWORK_NAME) {
1841                 cifs_tcon_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree);
1842         }
1843         goto tcon_exit;
1844 }
1845
1846 int
1847 SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon)
1848 {
1849         struct smb_rqst rqst;
1850         struct smb2_tree_disconnect_req *req; /* response is trivial */
1851         int rc = 0;
1852         struct cifs_ses *ses = tcon->ses;
1853         int flags = 0;
1854         unsigned int total_len;
1855         struct kvec iov[1];
1856         struct kvec rsp_iov;
1857         int resp_buf_type;
1858
1859         cifs_dbg(FYI, "Tree Disconnect\n");
1860
1861         if (!ses || !(ses->server))
1862                 return -EIO;
1863
1864         if ((tcon->need_reconnect) || (tcon->ses->need_reconnect))
1865                 return 0;
1866
1867         close_shroot_lease(&tcon->crfid);
1868
1869         rc = smb2_plain_req_init(SMB2_TREE_DISCONNECT, tcon, (void **) &req,
1870                              &total_len);
1871         if (rc)
1872                 return rc;
1873
1874         if (smb3_encryption_required(tcon))
1875                 flags |= CIFS_TRANSFORM_REQ;
1876
1877         flags |= CIFS_NO_RSP_BUF;
1878
1879         iov[0].iov_base = (char *)req;
1880         iov[0].iov_len = total_len;
1881
1882         memset(&rqst, 0, sizeof(struct smb_rqst));
1883         rqst.rq_iov = iov;
1884         rqst.rq_nvec = 1;
1885
1886         rc = cifs_send_recv(xid, ses, &rqst, &resp_buf_type, flags, &rsp_iov);
1887         cifs_small_buf_release(req);
1888         if (rc)
1889                 cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE);
1890
1891         return rc;
1892 }
1893
1894
1895 static struct create_durable *
1896 create_durable_buf(void)
1897 {
1898         struct create_durable *buf;
1899
1900         buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
1901         if (!buf)
1902                 return NULL;
1903
1904         buf->ccontext.DataOffset = cpu_to_le16(offsetof
1905                                         (struct create_durable, Data));
1906         buf->ccontext.DataLength = cpu_to_le32(16);
1907         buf->ccontext.NameOffset = cpu_to_le16(offsetof
1908                                 (struct create_durable, Name));
1909         buf->ccontext.NameLength = cpu_to_le16(4);
1910         /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DHnQ" */
1911         buf->Name[0] = 'D';
1912         buf->Name[1] = 'H';
1913         buf->Name[2] = 'n';
1914         buf->Name[3] = 'Q';
1915         return buf;
1916 }
1917
1918 static struct create_durable *
1919 create_reconnect_durable_buf(struct cifs_fid *fid)
1920 {
1921         struct create_durable *buf;
1922
1923         buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
1924         if (!buf)
1925                 return NULL;
1926
1927         buf->ccontext.DataOffset = cpu_to_le16(offsetof
1928                                         (struct create_durable, Data));
1929         buf->ccontext.DataLength = cpu_to_le32(16);
1930         buf->ccontext.NameOffset = cpu_to_le16(offsetof
1931                                 (struct create_durable, Name));
1932         buf->ccontext.NameLength = cpu_to_le16(4);
1933         buf->Data.Fid.PersistentFileId = fid->persistent_fid;
1934         buf->Data.Fid.VolatileFileId = fid->volatile_fid;
1935         /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT is "DHnC" */
1936         buf->Name[0] = 'D';
1937         buf->Name[1] = 'H';
1938         buf->Name[2] = 'n';
1939         buf->Name[3] = 'C';
1940         return buf;
1941 }
1942
1943 static void
1944 parse_query_id_ctxt(struct create_context *cc, struct smb2_file_all_info *buf)
1945 {
1946         struct create_on_disk_id *pdisk_id = (struct create_on_disk_id *)cc;
1947
1948         cifs_dbg(FYI, "parse query id context 0x%llx 0x%llx\n",
1949                 pdisk_id->DiskFileId, pdisk_id->VolumeId);
1950         buf->IndexNumber = pdisk_id->DiskFileId;
1951 }
1952
1953 static void
1954 parse_posix_ctxt(struct create_context *cc, struct smb2_file_all_info *info,
1955                  struct create_posix_rsp *posix)
1956 {
1957         int sid_len;
1958         u8 *beg = (u8 *)cc + le16_to_cpu(cc->DataOffset);
1959         u8 *end = beg + le32_to_cpu(cc->DataLength);
1960         u8 *sid;
1961
1962         memset(posix, 0, sizeof(*posix));
1963
1964         posix->nlink = le32_to_cpu(*(__le32 *)(beg + 0));
1965         posix->reparse_tag = le32_to_cpu(*(__le32 *)(beg + 4));
1966         posix->mode = le32_to_cpu(*(__le32 *)(beg + 8));
1967
1968         sid = beg + 12;
1969         sid_len = posix_info_sid_size(sid, end);
1970         if (sid_len < 0) {
1971                 cifs_dbg(VFS, "bad owner sid in posix create response\n");
1972                 return;
1973         }
1974         memcpy(&posix->owner, sid, sid_len);
1975
1976         sid = sid + sid_len;
1977         sid_len = posix_info_sid_size(sid, end);
1978         if (sid_len < 0) {
1979                 cifs_dbg(VFS, "bad group sid in posix create response\n");
1980                 return;
1981         }
1982         memcpy(&posix->group, sid, sid_len);
1983
1984         cifs_dbg(FYI, "nlink=%d mode=%o reparse_tag=%x\n",
1985                  posix->nlink, posix->mode, posix->reparse_tag);
1986 }
1987
1988 void
1989 smb2_parse_contexts(struct TCP_Server_Info *server,
1990                     struct smb2_create_rsp *rsp,
1991                     unsigned int *epoch, char *lease_key, __u8 *oplock,
1992                     struct smb2_file_all_info *buf,
1993                     struct create_posix_rsp *posix)
1994 {
1995         char *data_offset;
1996         struct create_context *cc;
1997         unsigned int next;
1998         unsigned int remaining;
1999         char *name;
2000         const char smb3_create_tag_posix[] = {0x93, 0xAD, 0x25, 0x50, 0x9C,
2001                                         0xB4, 0x11, 0xE7, 0xB4, 0x23, 0x83,
2002                                         0xDE, 0x96, 0x8B, 0xCD, 0x7C};
2003
2004         *oplock = 0;
2005         data_offset = (char *)rsp + le32_to_cpu(rsp->CreateContextsOffset);
2006         remaining = le32_to_cpu(rsp->CreateContextsLength);
2007         cc = (struct create_context *)data_offset;
2008
2009         /* Initialize inode number to 0 in case no valid data in qfid context */
2010         if (buf)
2011                 buf->IndexNumber = 0;
2012
2013         while (remaining >= sizeof(struct create_context)) {
2014                 name = le16_to_cpu(cc->NameOffset) + (char *)cc;
2015                 if (le16_to_cpu(cc->NameLength) == 4 &&
2016                     strncmp(name, SMB2_CREATE_REQUEST_LEASE, 4) == 0)
2017                         *oplock = server->ops->parse_lease_buf(cc, epoch,
2018                                                            lease_key);
2019                 else if (buf && (le16_to_cpu(cc->NameLength) == 4) &&
2020                     strncmp(name, SMB2_CREATE_QUERY_ON_DISK_ID, 4) == 0)
2021                         parse_query_id_ctxt(cc, buf);
2022                 else if ((le16_to_cpu(cc->NameLength) == 16)) {
2023                         if (posix &&
2024                             memcmp(name, smb3_create_tag_posix, 16) == 0)
2025                                 parse_posix_ctxt(cc, buf, posix);
2026                 }
2027                 /* else {
2028                         cifs_dbg(FYI, "Context not matched with len %d\n",
2029                                 le16_to_cpu(cc->NameLength));
2030                         cifs_dump_mem("Cctxt name: ", name, 4);
2031                 } */
2032
2033                 next = le32_to_cpu(cc->Next);
2034                 if (!next)
2035                         break;
2036                 remaining -= next;
2037                 cc = (struct create_context *)((char *)cc + next);
2038         }
2039
2040         if (rsp->OplockLevel != SMB2_OPLOCK_LEVEL_LEASE)
2041                 *oplock = rsp->OplockLevel;
2042
2043         return;
2044 }
2045
2046 static int
2047 add_lease_context(struct TCP_Server_Info *server, struct kvec *iov,
2048                   unsigned int *num_iovec, u8 *lease_key, __u8 *oplock)
2049 {
2050         struct smb2_create_req *req = iov[0].iov_base;
2051         unsigned int num = *num_iovec;
2052
2053         iov[num].iov_base = server->ops->create_lease_buf(lease_key, *oplock);
2054         if (iov[num].iov_base == NULL)
2055                 return -ENOMEM;
2056         iov[num].iov_len = server->vals->create_lease_size;
2057         req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
2058         if (!req->CreateContextsOffset)
2059                 req->CreateContextsOffset = cpu_to_le32(
2060                                 sizeof(struct smb2_create_req) +
2061                                 iov[num - 1].iov_len);
2062         le32_add_cpu(&req->CreateContextsLength,
2063                      server->vals->create_lease_size);
2064         *num_iovec = num + 1;
2065         return 0;
2066 }
2067
2068 static struct create_durable_v2 *
2069 create_durable_v2_buf(struct cifs_open_parms *oparms)
2070 {
2071         struct cifs_fid *pfid = oparms->fid;
2072         struct create_durable_v2 *buf;
2073
2074         buf = kzalloc(sizeof(struct create_durable_v2), GFP_KERNEL);
2075         if (!buf)
2076                 return NULL;
2077
2078         buf->ccontext.DataOffset = cpu_to_le16(offsetof
2079                                         (struct create_durable_v2, dcontext));
2080         buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_context_v2));
2081         buf->ccontext.NameOffset = cpu_to_le16(offsetof
2082                                 (struct create_durable_v2, Name));
2083         buf->ccontext.NameLength = cpu_to_le16(4);
2084
2085         /*
2086          * NB: Handle timeout defaults to 0, which allows server to choose
2087          * (most servers default to 120 seconds) and most clients default to 0.
2088          * This can be overridden at mount ("handletimeout=") if the user wants
2089          * a different persistent (or resilient) handle timeout for all opens
2090          * opens on a particular SMB3 mount.
2091          */
2092         buf->dcontext.Timeout = cpu_to_le32(oparms->tcon->handle_timeout);
2093         buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2094         generate_random_uuid(buf->dcontext.CreateGuid);
2095         memcpy(pfid->create_guid, buf->dcontext.CreateGuid, 16);
2096
2097         /* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DH2Q" */
2098         buf->Name[0] = 'D';
2099         buf->Name[1] = 'H';
2100         buf->Name[2] = '2';
2101         buf->Name[3] = 'Q';
2102         return buf;
2103 }
2104
2105 static struct create_durable_handle_reconnect_v2 *
2106 create_reconnect_durable_v2_buf(struct cifs_fid *fid)
2107 {
2108         struct create_durable_handle_reconnect_v2 *buf;
2109
2110         buf = kzalloc(sizeof(struct create_durable_handle_reconnect_v2),
2111                         GFP_KERNEL);
2112         if (!buf)
2113                 return NULL;
2114
2115         buf->ccontext.DataOffset =
2116                 cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
2117                                      dcontext));
2118         buf->ccontext.DataLength =
2119                 cpu_to_le32(sizeof(struct durable_reconnect_context_v2));
2120         buf->ccontext.NameOffset =
2121                 cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
2122                             Name));
2123         buf->ccontext.NameLength = cpu_to_le16(4);
2124
2125         buf->dcontext.Fid.PersistentFileId = fid->persistent_fid;
2126         buf->dcontext.Fid.VolatileFileId = fid->volatile_fid;
2127         buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2128         memcpy(buf->dcontext.CreateGuid, fid->create_guid, 16);
2129
2130         /* SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 is "DH2C" */
2131         buf->Name[0] = 'D';
2132         buf->Name[1] = 'H';
2133         buf->Name[2] = '2';
2134         buf->Name[3] = 'C';
2135         return buf;
2136 }
2137
2138 static int
2139 add_durable_v2_context(struct kvec *iov, unsigned int *num_iovec,
2140                     struct cifs_open_parms *oparms)
2141 {
2142         struct smb2_create_req *req = iov[0].iov_base;
2143         unsigned int num = *num_iovec;
2144
2145         iov[num].iov_base = create_durable_v2_buf(oparms);
2146         if (iov[num].iov_base == NULL)
2147                 return -ENOMEM;
2148         iov[num].iov_len = sizeof(struct create_durable_v2);
2149         if (!req->CreateContextsOffset)
2150                 req->CreateContextsOffset =
2151                         cpu_to_le32(sizeof(struct smb2_create_req) +
2152                                                                 iov[1].iov_len);
2153         le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable_v2));
2154         *num_iovec = num + 1;
2155         return 0;
2156 }
2157
2158 static int
2159 add_durable_reconnect_v2_context(struct kvec *iov, unsigned int *num_iovec,
2160                     struct cifs_open_parms *oparms)
2161 {
2162         struct smb2_create_req *req = iov[0].iov_base;
2163         unsigned int num = *num_iovec;
2164
2165         /* indicate that we don't need to relock the file */
2166         oparms->reconnect = false;
2167
2168         iov[num].iov_base = create_reconnect_durable_v2_buf(oparms->fid);
2169         if (iov[num].iov_base == NULL)
2170                 return -ENOMEM;
2171         iov[num].iov_len = sizeof(struct create_durable_handle_reconnect_v2);
2172         if (!req->CreateContextsOffset)
2173                 req->CreateContextsOffset =
2174                         cpu_to_le32(sizeof(struct smb2_create_req) +
2175                                                                 iov[1].iov_len);
2176         le32_add_cpu(&req->CreateContextsLength,
2177                         sizeof(struct create_durable_handle_reconnect_v2));
2178         *num_iovec = num + 1;
2179         return 0;
2180 }
2181
2182 static int
2183 add_durable_context(struct kvec *iov, unsigned int *num_iovec,
2184                     struct cifs_open_parms *oparms, bool use_persistent)
2185 {
2186         struct smb2_create_req *req = iov[0].iov_base;
2187         unsigned int num = *num_iovec;
2188
2189         if (use_persistent) {
2190                 if (oparms->reconnect)
2191                         return add_durable_reconnect_v2_context(iov, num_iovec,
2192                                                                 oparms);
2193                 else
2194                         return add_durable_v2_context(iov, num_iovec, oparms);
2195         }
2196
2197         if (oparms->reconnect) {
2198                 iov[num].iov_base = create_reconnect_durable_buf(oparms->fid);
2199                 /* indicate that we don't need to relock the file */
2200                 oparms->reconnect = false;
2201         } else
2202                 iov[num].iov_base = create_durable_buf();
2203         if (iov[num].iov_base == NULL)
2204                 return -ENOMEM;
2205         iov[num].iov_len = sizeof(struct create_durable);
2206         if (!req->CreateContextsOffset)
2207                 req->CreateContextsOffset =
2208                         cpu_to_le32(sizeof(struct smb2_create_req) +
2209                                                                 iov[1].iov_len);
2210         le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable));
2211         *num_iovec = num + 1;
2212         return 0;
2213 }
2214
2215 /* See MS-SMB2 2.2.13.2.7 */
2216 static struct crt_twarp_ctxt *
2217 create_twarp_buf(__u64 timewarp)
2218 {
2219         struct crt_twarp_ctxt *buf;
2220
2221         buf = kzalloc(sizeof(struct crt_twarp_ctxt), GFP_KERNEL);
2222         if (!buf)
2223                 return NULL;
2224
2225         buf->ccontext.DataOffset = cpu_to_le16(offsetof
2226                                         (struct crt_twarp_ctxt, Timestamp));
2227         buf->ccontext.DataLength = cpu_to_le32(8);
2228         buf->ccontext.NameOffset = cpu_to_le16(offsetof
2229                                 (struct crt_twarp_ctxt, Name));
2230         buf->ccontext.NameLength = cpu_to_le16(4);
2231         /* SMB2_CREATE_TIMEWARP_TOKEN is "TWrp" */
2232         buf->Name[0] = 'T';
2233         buf->Name[1] = 'W';
2234         buf->Name[2] = 'r';
2235         buf->Name[3] = 'p';
2236         buf->Timestamp = cpu_to_le64(timewarp);
2237         return buf;
2238 }
2239
2240 /* See MS-SMB2 2.2.13.2.7 */
2241 static int
2242 add_twarp_context(struct kvec *iov, unsigned int *num_iovec, __u64 timewarp)
2243 {
2244         struct smb2_create_req *req = iov[0].iov_base;
2245         unsigned int num = *num_iovec;
2246
2247         iov[num].iov_base = create_twarp_buf(timewarp);
2248         if (iov[num].iov_base == NULL)
2249                 return -ENOMEM;
2250         iov[num].iov_len = sizeof(struct crt_twarp_ctxt);
2251         if (!req->CreateContextsOffset)
2252                 req->CreateContextsOffset = cpu_to_le32(
2253                                 sizeof(struct smb2_create_req) +
2254                                 iov[num - 1].iov_len);
2255         le32_add_cpu(&req->CreateContextsLength, sizeof(struct crt_twarp_ctxt));
2256         *num_iovec = num + 1;
2257         return 0;
2258 }
2259
2260 /* See MS-SMB2 2.2.13.2.2 and MS-DTYP 2.4.6 */
2261 static struct crt_sd_ctxt *
2262 create_sd_buf(umode_t mode, unsigned int *len)
2263 {
2264         struct crt_sd_ctxt *buf;
2265         struct cifs_ace *pace;
2266         unsigned int sdlen, acelen;
2267
2268         *len = roundup(sizeof(struct crt_sd_ctxt) + sizeof(struct cifs_ace) * 2,
2269                         8);
2270         buf = kzalloc(*len, GFP_KERNEL);
2271         if (buf == NULL)
2272                 return buf;
2273
2274         sdlen = sizeof(struct smb3_sd) + sizeof(struct smb3_acl) +
2275                  2 * sizeof(struct cifs_ace);
2276
2277         buf->ccontext.DataOffset = cpu_to_le16(offsetof
2278                                         (struct crt_sd_ctxt, sd));
2279         buf->ccontext.DataLength = cpu_to_le32(sdlen);
2280         buf->ccontext.NameOffset = cpu_to_le16(offsetof
2281                                 (struct crt_sd_ctxt, Name));
2282         buf->ccontext.NameLength = cpu_to_le16(4);
2283         /* SMB2_CREATE_SD_BUFFER_TOKEN is "SecD" */
2284         buf->Name[0] = 'S';
2285         buf->Name[1] = 'e';
2286         buf->Name[2] = 'c';
2287         buf->Name[3] = 'D';
2288         buf->sd.Revision = 1;  /* Must be one see MS-DTYP 2.4.6 */
2289         /*
2290          * ACL is "self relative" ie ACL is stored in contiguous block of memory
2291          * and "DP" ie the DACL is present
2292          */
2293         buf->sd.Control = cpu_to_le16(ACL_CONTROL_SR | ACL_CONTROL_DP);
2294
2295         /* offset owner, group and Sbz1 and SACL are all zero */
2296         buf->sd.OffsetDacl = cpu_to_le32(sizeof(struct smb3_sd));
2297         buf->acl.AclRevision = ACL_REVISION; /* See 2.4.4.1 of MS-DTYP */
2298
2299         /* create one ACE to hold the mode embedded in reserved special SID */
2300         pace = (struct cifs_ace *)(sizeof(struct crt_sd_ctxt) + (char *)buf);
2301         acelen = setup_special_mode_ACE(pace, (__u64)mode);
2302         /* and one more ACE to allow access for authenticated users */
2303         pace = (struct cifs_ace *)(acelen + (sizeof(struct crt_sd_ctxt) +
2304                 (char *)buf));
2305         acelen += setup_authusers_ACE(pace);
2306         buf->acl.AclSize = cpu_to_le16(sizeof(struct cifs_acl) + acelen);
2307         buf->acl.AceCount = cpu_to_le16(2);
2308         return buf;
2309 }
2310
2311 static int
2312 add_sd_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode)
2313 {
2314         struct smb2_create_req *req = iov[0].iov_base;
2315         unsigned int num = *num_iovec;
2316         unsigned int len = 0;
2317
2318         iov[num].iov_base = create_sd_buf(mode, &len);
2319         if (iov[num].iov_base == NULL)
2320                 return -ENOMEM;
2321         iov[num].iov_len = len;
2322         if (!req->CreateContextsOffset)
2323                 req->CreateContextsOffset = cpu_to_le32(
2324                                 sizeof(struct smb2_create_req) +
2325                                 iov[num - 1].iov_len);
2326         le32_add_cpu(&req->CreateContextsLength, len);
2327         *num_iovec = num + 1;
2328         return 0;
2329 }
2330
2331 static struct crt_query_id_ctxt *
2332 create_query_id_buf(void)
2333 {
2334         struct crt_query_id_ctxt *buf;
2335
2336         buf = kzalloc(sizeof(struct crt_query_id_ctxt), GFP_KERNEL);
2337         if (!buf)
2338                 return NULL;
2339
2340         buf->ccontext.DataOffset = cpu_to_le16(0);
2341         buf->ccontext.DataLength = cpu_to_le32(0);
2342         buf->ccontext.NameOffset = cpu_to_le16(offsetof
2343                                 (struct crt_query_id_ctxt, Name));
2344         buf->ccontext.NameLength = cpu_to_le16(4);
2345         /* SMB2_CREATE_QUERY_ON_DISK_ID is "QFid" */
2346         buf->Name[0] = 'Q';
2347         buf->Name[1] = 'F';
2348         buf->Name[2] = 'i';
2349         buf->Name[3] = 'd';
2350         return buf;
2351 }
2352
2353 /* See MS-SMB2 2.2.13.2.9 */
2354 static int
2355 add_query_id_context(struct kvec *iov, unsigned int *num_iovec)
2356 {
2357         struct smb2_create_req *req = iov[0].iov_base;
2358         unsigned int num = *num_iovec;
2359
2360         iov[num].iov_base = create_query_id_buf();
2361         if (iov[num].iov_base == NULL)
2362                 return -ENOMEM;
2363         iov[num].iov_len = sizeof(struct crt_query_id_ctxt);
2364         if (!req->CreateContextsOffset)
2365                 req->CreateContextsOffset = cpu_to_le32(
2366                                 sizeof(struct smb2_create_req) +
2367                                 iov[num - 1].iov_len);
2368         le32_add_cpu(&req->CreateContextsLength, sizeof(struct crt_query_id_ctxt));
2369         *num_iovec = num + 1;
2370         return 0;
2371 }
2372
2373 static int
2374 alloc_path_with_tree_prefix(__le16 **out_path, int *out_size, int *out_len,
2375                             const char *treename, const __le16 *path)
2376 {
2377         int treename_len, path_len;
2378         struct nls_table *cp;
2379         const __le16 sep[] = {cpu_to_le16('\\'), cpu_to_le16(0x0000)};
2380
2381         /*
2382          * skip leading "\\"
2383          */
2384         treename_len = strlen(treename);
2385         if (treename_len < 2 || !(treename[0] == '\\' && treename[1] == '\\'))
2386                 return -EINVAL;
2387
2388         treename += 2;
2389         treename_len -= 2;
2390
2391         path_len = UniStrnlen((wchar_t *)path, PATH_MAX);
2392
2393         /*
2394          * make room for one path separator between the treename and
2395          * path
2396          */
2397         *out_len = treename_len + 1 + path_len;
2398
2399         /*
2400          * final path needs to be null-terminated UTF16 with a
2401          * size aligned to 8
2402          */
2403
2404         *out_size = roundup((*out_len+1)*2, 8);
2405         *out_path = kzalloc(*out_size, GFP_KERNEL);
2406         if (!*out_path)
2407                 return -ENOMEM;
2408
2409         cp = load_nls_default();
2410         cifs_strtoUTF16(*out_path, treename, treename_len, cp);
2411         UniStrcat(*out_path, sep);
2412         UniStrcat(*out_path, path);
2413         unload_nls(cp);
2414
2415         return 0;
2416 }
2417
2418 int smb311_posix_mkdir(const unsigned int xid, struct inode *inode,
2419                                umode_t mode, struct cifs_tcon *tcon,
2420                                const char *full_path,
2421                                struct cifs_sb_info *cifs_sb)
2422 {
2423         struct smb_rqst rqst;
2424         struct smb2_create_req *req;
2425         struct smb2_create_rsp *rsp = NULL;
2426         struct cifs_ses *ses = tcon->ses;
2427         struct kvec iov[3]; /* make sure at least one for each open context */
2428         struct kvec rsp_iov = {NULL, 0};
2429         int resp_buftype;
2430         int uni_path_len;
2431         __le16 *copy_path = NULL;
2432         int copy_size;
2433         int rc = 0;
2434         unsigned int n_iov = 2;
2435         __u32 file_attributes = 0;
2436         char *pc_buf = NULL;
2437         int flags = 0;
2438         unsigned int total_len;
2439         __le16 *utf16_path = NULL;
2440
2441         cifs_dbg(FYI, "mkdir\n");
2442
2443         /* resource #1: path allocation */
2444         utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
2445         if (!utf16_path)
2446                 return -ENOMEM;
2447
2448         if (!ses || !(ses->server)) {
2449                 rc = -EIO;
2450                 goto err_free_path;
2451         }
2452
2453         /* resource #2: request */
2454         rc = smb2_plain_req_init(SMB2_CREATE, tcon, (void **) &req, &total_len);
2455         if (rc)
2456                 goto err_free_path;
2457
2458
2459         if (smb3_encryption_required(tcon))
2460                 flags |= CIFS_TRANSFORM_REQ;
2461
2462         req->ImpersonationLevel = IL_IMPERSONATION;
2463         req->DesiredAccess = cpu_to_le32(FILE_WRITE_ATTRIBUTES);
2464         /* File attributes ignored on open (used in create though) */
2465         req->FileAttributes = cpu_to_le32(file_attributes);
2466         req->ShareAccess = FILE_SHARE_ALL_LE;
2467         req->CreateDisposition = cpu_to_le32(FILE_CREATE);
2468         req->CreateOptions = cpu_to_le32(CREATE_NOT_FILE);
2469
2470         iov[0].iov_base = (char *)req;
2471         /* -1 since last byte is buf[0] which is sent below (path) */
2472         iov[0].iov_len = total_len - 1;
2473
2474         req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
2475
2476         /* [MS-SMB2] 2.2.13 NameOffset:
2477          * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
2478          * the SMB2 header, the file name includes a prefix that will
2479          * be processed during DFS name normalization as specified in
2480          * section 3.3.5.9. Otherwise, the file name is relative to
2481          * the share that is identified by the TreeId in the SMB2
2482          * header.
2483          */
2484         if (tcon->share_flags & SHI1005_FLAGS_DFS) {
2485                 int name_len;
2486
2487                 req->sync_hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
2488                 rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
2489                                                  &name_len,
2490                                                  tcon->treeName, utf16_path);
2491                 if (rc)
2492                         goto err_free_req;
2493
2494                 req->NameLength = cpu_to_le16(name_len * 2);
2495                 uni_path_len = copy_size;
2496                 /* free before overwriting resource */
2497                 kfree(utf16_path);
2498                 utf16_path = copy_path;
2499         } else {
2500                 uni_path_len = (2 * UniStrnlen((wchar_t *)utf16_path, PATH_MAX)) + 2;
2501                 /* MUST set path len (NameLength) to 0 opening root of share */
2502                 req->NameLength = cpu_to_le16(uni_path_len - 2);
2503                 if (uni_path_len % 8 != 0) {
2504                         copy_size = roundup(uni_path_len, 8);
2505                         copy_path = kzalloc(copy_size, GFP_KERNEL);
2506                         if (!copy_path) {
2507                                 rc = -ENOMEM;
2508                                 goto err_free_req;
2509                         }
2510                         memcpy((char *)copy_path, (const char *)utf16_path,
2511                                uni_path_len);
2512                         uni_path_len = copy_size;
2513                         /* free before overwriting resource */
2514                         kfree(utf16_path);
2515                         utf16_path = copy_path;
2516                 }
2517         }
2518
2519         iov[1].iov_len = uni_path_len;
2520         iov[1].iov_base = utf16_path;
2521         req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2522
2523         if (tcon->posix_extensions) {
2524                 /* resource #3: posix buf */
2525                 rc = add_posix_context(iov, &n_iov, mode);
2526                 if (rc)
2527                         goto err_free_req;
2528                 pc_buf = iov[n_iov-1].iov_base;
2529         }
2530
2531
2532         memset(&rqst, 0, sizeof(struct smb_rqst));
2533         rqst.rq_iov = iov;
2534         rqst.rq_nvec = n_iov;
2535
2536         /* no need to inc num_remote_opens because we close it just below */
2537         trace_smb3_posix_mkdir_enter(xid, tcon->tid, ses->Suid, CREATE_NOT_FILE,
2538                                     FILE_WRITE_ATTRIBUTES);
2539         /* resource #4: response buffer */
2540         rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
2541         if (rc) {
2542                 cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
2543                 trace_smb3_posix_mkdir_err(xid, tcon->tid, ses->Suid,
2544                                            CREATE_NOT_FILE,
2545                                            FILE_WRITE_ATTRIBUTES, rc);
2546                 goto err_free_rsp_buf;
2547         }
2548
2549         rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
2550         trace_smb3_posix_mkdir_done(xid, rsp->PersistentFileId, tcon->tid,
2551                                     ses->Suid, CREATE_NOT_FILE,
2552                                     FILE_WRITE_ATTRIBUTES);
2553
2554         SMB2_close(xid, tcon, rsp->PersistentFileId, rsp->VolatileFileId);
2555
2556         /* Eventually save off posix specific response info and timestaps */
2557
2558 err_free_rsp_buf:
2559         free_rsp_buf(resp_buftype, rsp);
2560         kfree(pc_buf);
2561 err_free_req:
2562         cifs_small_buf_release(req);
2563 err_free_path:
2564         kfree(utf16_path);
2565         return rc;
2566 }
2567
2568 int
2569 SMB2_open_init(struct cifs_tcon *tcon, struct smb_rqst *rqst, __u8 *oplock,
2570                struct cifs_open_parms *oparms, __le16 *path)
2571 {
2572         struct TCP_Server_Info *server = tcon->ses->server;
2573         struct smb2_create_req *req;
2574         unsigned int n_iov = 2;
2575         __u32 file_attributes = 0;
2576         int copy_size;
2577         int uni_path_len;
2578         unsigned int total_len;
2579         struct kvec *iov = rqst->rq_iov;
2580         __le16 *copy_path;
2581         int rc;
2582
2583         rc = smb2_plain_req_init(SMB2_CREATE, tcon, (void **) &req, &total_len);
2584         if (rc)
2585                 return rc;
2586
2587         iov[0].iov_base = (char *)req;
2588         /* -1 since last byte is buf[0] which is sent below (path) */
2589         iov[0].iov_len = total_len - 1;
2590
2591         if (oparms->create_options & CREATE_OPTION_READONLY)
2592                 file_attributes |= ATTR_READONLY;
2593         if (oparms->create_options & CREATE_OPTION_SPECIAL)
2594                 file_attributes |= ATTR_SYSTEM;
2595
2596         req->ImpersonationLevel = IL_IMPERSONATION;
2597         req->DesiredAccess = cpu_to_le32(oparms->desired_access);
2598         /* File attributes ignored on open (used in create though) */
2599         req->FileAttributes = cpu_to_le32(file_attributes);
2600         req->ShareAccess = FILE_SHARE_ALL_LE;
2601
2602         req->CreateDisposition = cpu_to_le32(oparms->disposition);
2603         req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK);
2604         req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
2605
2606         /* [MS-SMB2] 2.2.13 NameOffset:
2607          * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
2608          * the SMB2 header, the file name includes a prefix that will
2609          * be processed during DFS name normalization as specified in
2610          * section 3.3.5.9. Otherwise, the file name is relative to
2611          * the share that is identified by the TreeId in the SMB2
2612          * header.
2613          */
2614         if (tcon->share_flags & SHI1005_FLAGS_DFS) {
2615                 int name_len;
2616
2617                 req->sync_hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
2618                 rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
2619                                                  &name_len,
2620                                                  tcon->treeName, path);
2621                 if (rc)
2622                         return rc;
2623                 req->NameLength = cpu_to_le16(name_len * 2);
2624                 uni_path_len = copy_size;
2625                 path = copy_path;
2626         } else {
2627                 uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
2628                 /* MUST set path len (NameLength) to 0 opening root of share */
2629                 req->NameLength = cpu_to_le16(uni_path_len - 2);
2630                 copy_size = uni_path_len;
2631                 if (copy_size % 8 != 0)
2632                         copy_size = roundup(copy_size, 8);
2633                 copy_path = kzalloc(copy_size, GFP_KERNEL);
2634                 if (!copy_path)
2635                         return -ENOMEM;
2636                 memcpy((char *)copy_path, (const char *)path,
2637                        uni_path_len);
2638                 uni_path_len = copy_size;
2639                 path = copy_path;
2640         }
2641
2642         iov[1].iov_len = uni_path_len;
2643         iov[1].iov_base = path;
2644
2645         if ((!server->oplocks) || (tcon->no_lease))
2646                 *oplock = SMB2_OPLOCK_LEVEL_NONE;
2647
2648         if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) ||
2649             *oplock == SMB2_OPLOCK_LEVEL_NONE)
2650                 req->RequestedOplockLevel = *oplock;
2651         else if (!(server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING) &&
2652                   (oparms->create_options & CREATE_NOT_FILE))
2653                 req->RequestedOplockLevel = *oplock; /* no srv lease support */
2654         else {
2655                 rc = add_lease_context(server, iov, &n_iov,
2656                                        oparms->fid->lease_key, oplock);
2657                 if (rc)
2658                         return rc;
2659         }
2660
2661         if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) {
2662                 /* need to set Next field of lease context if we request it */
2663                 if (server->capabilities & SMB2_GLOBAL_CAP_LEASING) {
2664                         struct create_context *ccontext =
2665                             (struct create_context *)iov[n_iov-1].iov_base;
2666                         ccontext->Next =
2667                                 cpu_to_le32(server->vals->create_lease_size);
2668                 }
2669
2670                 rc = add_durable_context(iov, &n_iov, oparms,
2671                                         tcon->use_persistent);
2672                 if (rc)
2673                         return rc;
2674         }
2675
2676         if (tcon->posix_extensions) {
2677                 if (n_iov > 2) {
2678                         struct create_context *ccontext =
2679                             (struct create_context *)iov[n_iov-1].iov_base;
2680                         ccontext->Next =
2681                                 cpu_to_le32(iov[n_iov-1].iov_len);
2682                 }
2683
2684                 rc = add_posix_context(iov, &n_iov, oparms->mode);
2685                 if (rc)
2686                         return rc;
2687         }
2688
2689         if (tcon->snapshot_time) {
2690                 cifs_dbg(FYI, "adding snapshot context\n");
2691                 if (n_iov > 2) {
2692                         struct create_context *ccontext =
2693                             (struct create_context *)iov[n_iov-1].iov_base;
2694                         ccontext->Next =
2695                                 cpu_to_le32(iov[n_iov-1].iov_len);
2696                 }
2697
2698                 rc = add_twarp_context(iov, &n_iov, tcon->snapshot_time);
2699                 if (rc)
2700                         return rc;
2701         }
2702
2703         if ((oparms->disposition != FILE_OPEN) &&
2704             (oparms->cifs_sb) &&
2705             (oparms->cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MODE_FROM_SID) &&
2706             (oparms->mode != ACL_NO_MODE)) {
2707                 if (n_iov > 2) {
2708                         struct create_context *ccontext =
2709                             (struct create_context *)iov[n_iov-1].iov_base;
2710                         ccontext->Next =
2711                                 cpu_to_le32(iov[n_iov-1].iov_len);
2712                 }
2713
2714                 cifs_dbg(FYI, "add sd with mode 0x%x\n", oparms->mode);
2715                 rc = add_sd_context(iov, &n_iov, oparms->mode);
2716                 if (rc)
2717                         return rc;
2718         }
2719
2720         if (n_iov > 2) {
2721                 struct create_context *ccontext =
2722                         (struct create_context *)iov[n_iov-1].iov_base;
2723                 ccontext->Next = cpu_to_le32(iov[n_iov-1].iov_len);
2724         }
2725         add_query_id_context(iov, &n_iov);
2726
2727         rqst->rq_nvec = n_iov;
2728         return 0;
2729 }
2730
2731 /* rq_iov[0] is the request and is released by cifs_small_buf_release().
2732  * All other vectors are freed by kfree().
2733  */
2734 void
2735 SMB2_open_free(struct smb_rqst *rqst)
2736 {
2737         int i;
2738
2739         if (rqst && rqst->rq_iov) {
2740                 cifs_small_buf_release(rqst->rq_iov[0].iov_base);
2741                 for (i = 1; i < rqst->rq_nvec; i++)
2742                         if (rqst->rq_iov[i].iov_base != smb2_padding)
2743                                 kfree(rqst->rq_iov[i].iov_base);
2744         }
2745 }
2746
2747 int
2748 SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
2749           __u8 *oplock, struct smb2_file_all_info *buf,
2750           struct create_posix_rsp *posix,
2751           struct kvec *err_iov, int *buftype)
2752 {
2753         struct smb_rqst rqst;
2754         struct smb2_create_rsp *rsp = NULL;
2755         struct TCP_Server_Info *server;
2756         struct cifs_tcon *tcon = oparms->tcon;
2757         struct cifs_ses *ses = tcon->ses;
2758         struct kvec iov[SMB2_CREATE_IOV_SIZE];
2759         struct kvec rsp_iov = {NULL, 0};
2760         int resp_buftype = CIFS_NO_BUFFER;
2761         int rc = 0;
2762         int flags = 0;
2763
2764         cifs_dbg(FYI, "create/open\n");
2765         if (ses && (ses->server))
2766                 server = ses->server;
2767         else
2768                 return -EIO;
2769
2770         if (smb3_encryption_required(tcon))
2771                 flags |= CIFS_TRANSFORM_REQ;
2772
2773         memset(&rqst, 0, sizeof(struct smb_rqst));
2774         memset(&iov, 0, sizeof(iov));
2775         rqst.rq_iov = iov;
2776         rqst.rq_nvec = SMB2_CREATE_IOV_SIZE;
2777
2778         rc = SMB2_open_init(tcon, &rqst, oplock, oparms, path);
2779         if (rc)
2780                 goto creat_exit;
2781
2782         trace_smb3_open_enter(xid, tcon->tid, tcon->ses->Suid,
2783                 oparms->create_options, oparms->desired_access);
2784
2785         rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags,
2786                             &rsp_iov);
2787         rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
2788
2789         if (rc != 0) {
2790                 cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
2791                 if (err_iov && rsp) {
2792                         *err_iov = rsp_iov;
2793                         *buftype = resp_buftype;
2794                         resp_buftype = CIFS_NO_BUFFER;
2795                         rsp = NULL;
2796                 }
2797                 trace_smb3_open_err(xid, tcon->tid, ses->Suid,
2798                                     oparms->create_options, oparms->desired_access, rc);
2799                 if (rc == -EREMCHG) {
2800                         printk_once(KERN_WARNING "server share %s deleted\n",
2801                                     tcon->treeName);
2802                         tcon->need_reconnect = true;
2803                 }
2804                 goto creat_exit;
2805         } else
2806                 trace_smb3_open_done(xid, rsp->PersistentFileId, tcon->tid,
2807                                      ses->Suid, oparms->create_options,
2808                                      oparms->desired_access);
2809
2810         atomic_inc(&tcon->num_remote_opens);
2811         oparms->fid->persistent_fid = rsp->PersistentFileId;
2812         oparms->fid->volatile_fid = rsp->VolatileFileId;
2813         oparms->fid->access = oparms->desired_access;
2814 #ifdef CONFIG_CIFS_DEBUG2
2815         oparms->fid->mid = le64_to_cpu(rsp->sync_hdr.MessageId);
2816 #endif /* CIFS_DEBUG2 */
2817
2818         if (buf) {
2819                 memcpy(buf, &rsp->CreationTime, 32);
2820                 buf->AllocationSize = rsp->AllocationSize;
2821                 buf->EndOfFile = rsp->EndofFile;
2822                 buf->Attributes = rsp->FileAttributes;
2823                 buf->NumberOfLinks = cpu_to_le32(1);
2824                 buf->DeletePending = 0;
2825         }
2826
2827
2828         smb2_parse_contexts(server, rsp, &oparms->fid->epoch,
2829                             oparms->fid->lease_key, oplock, buf, posix);
2830 creat_exit:
2831         SMB2_open_free(&rqst);
2832         free_rsp_buf(resp_buftype, rsp);
2833         return rc;
2834 }
2835
2836 int
2837 SMB2_ioctl_init(struct cifs_tcon *tcon, struct smb_rqst *rqst,
2838                 u64 persistent_fid, u64 volatile_fid, u32 opcode,
2839                 bool is_fsctl, char *in_data, u32 indatalen,
2840                 __u32 max_response_size)
2841 {
2842         struct smb2_ioctl_req *req;
2843         struct kvec *iov = rqst->rq_iov;
2844         unsigned int total_len;
2845         int rc;
2846         char *in_data_buf;
2847
2848         rc = smb2_ioctl_req_init(opcode, tcon, (void **) &req, &total_len);
2849         if (rc)
2850                 return rc;
2851
2852         if (indatalen) {
2853                 /*
2854                  * indatalen is usually small at a couple of bytes max, so
2855                  * just allocate through generic pool
2856                  */
2857                 in_data_buf = kmemdup(in_data, indatalen, GFP_NOFS);
2858                 if (!in_data_buf) {
2859                         cifs_small_buf_release(req);
2860                         return -ENOMEM;
2861                 }
2862         }
2863
2864         req->CtlCode = cpu_to_le32(opcode);
2865         req->PersistentFileId = persistent_fid;
2866         req->VolatileFileId = volatile_fid;
2867
2868         iov[0].iov_base = (char *)req;
2869         /*
2870          * If no input data, the size of ioctl struct in
2871          * protocol spec still includes a 1 byte data buffer,
2872          * but if input data passed to ioctl, we do not
2873          * want to double count this, so we do not send
2874          * the dummy one byte of data in iovec[0] if sending
2875          * input data (in iovec[1]).
2876          */
2877         if (indatalen) {
2878                 req->InputCount = cpu_to_le32(indatalen);
2879                 /* do not set InputOffset if no input data */
2880                 req->InputOffset =
2881                        cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer));
2882                 rqst->rq_nvec = 2;
2883                 iov[0].iov_len = total_len - 1;
2884                 iov[1].iov_base = in_data_buf;
2885                 iov[1].iov_len = indatalen;
2886         } else {
2887                 rqst->rq_nvec = 1;
2888                 iov[0].iov_len = total_len;
2889         }
2890
2891         req->OutputOffset = 0;
2892         req->OutputCount = 0; /* MBZ */
2893
2894         /*
2895          * In most cases max_response_size is set to 16K (CIFSMaxBufSize)
2896          * We Could increase default MaxOutputResponse, but that could require
2897          * more credits. Windows typically sets this smaller, but for some
2898          * ioctls it may be useful to allow server to send more. No point
2899          * limiting what the server can send as long as fits in one credit
2900          * We can not handle more than CIFS_MAX_BUF_SIZE yet but may want
2901          * to increase this limit up in the future.
2902          * Note that for snapshot queries that servers like Azure expect that
2903          * the first query be minimal size (and just used to get the number/size
2904          * of previous versions) so response size must be specified as EXACTLY
2905          * sizeof(struct snapshot_array) which is 16 when rounded up to multiple
2906          * of eight bytes.  Currently that is the only case where we set max
2907          * response size smaller.
2908          */
2909         req->MaxOutputResponse = cpu_to_le32(max_response_size);
2910
2911         if (is_fsctl)
2912                 req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL);
2913         else
2914                 req->Flags = 0;
2915
2916         /* validate negotiate request must be signed - see MS-SMB2 3.2.5.5 */
2917         if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO)
2918                 req->sync_hdr.Flags |= SMB2_FLAGS_SIGNED;
2919
2920         return 0;
2921 }
2922
2923 void
2924 SMB2_ioctl_free(struct smb_rqst *rqst)
2925 {
2926         int i;
2927         if (rqst && rqst->rq_iov) {
2928                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
2929                 for (i = 1; i < rqst->rq_nvec; i++)
2930                         if (rqst->rq_iov[i].iov_base != smb2_padding)
2931                                 kfree(rqst->rq_iov[i].iov_base);
2932         }
2933 }
2934
2935
2936 /*
2937  *      SMB2 IOCTL is used for both IOCTLs and FSCTLs
2938  */
2939 int
2940 SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
2941            u64 volatile_fid, u32 opcode, bool is_fsctl,
2942            char *in_data, u32 indatalen, u32 max_out_data_len,
2943            char **out_data, u32 *plen /* returned data len */)
2944 {
2945         struct smb_rqst rqst;
2946         struct smb2_ioctl_rsp *rsp = NULL;
2947         struct cifs_ses *ses;
2948         struct kvec iov[SMB2_IOCTL_IOV_SIZE];
2949         struct kvec rsp_iov = {NULL, 0};
2950         int resp_buftype = CIFS_NO_BUFFER;
2951         int rc = 0;
2952         int flags = 0;
2953         struct TCP_Server_Info *server;
2954
2955         cifs_dbg(FYI, "SMB2 IOCTL\n");
2956
2957         if (out_data != NULL)
2958                 *out_data = NULL;
2959
2960         /* zero out returned data len, in case of error */
2961         if (plen)
2962                 *plen = 0;
2963
2964         if (tcon)
2965                 ses = tcon->ses;
2966         else
2967                 return -EIO;
2968
2969         if (!ses)
2970                 return -EIO;
2971         server = ses->server;
2972         if (!server)
2973                 return -EIO;
2974
2975         if (smb3_encryption_required(tcon))
2976                 flags |= CIFS_TRANSFORM_REQ;
2977
2978         memset(&rqst, 0, sizeof(struct smb_rqst));
2979         memset(&iov, 0, sizeof(iov));
2980         rqst.rq_iov = iov;
2981         rqst.rq_nvec = SMB2_IOCTL_IOV_SIZE;
2982
2983         rc = SMB2_ioctl_init(tcon, &rqst, persistent_fid, volatile_fid, opcode,
2984                              is_fsctl, in_data, indatalen, max_out_data_len);
2985         if (rc)
2986                 goto ioctl_exit;
2987
2988         rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags,
2989                             &rsp_iov);
2990         rsp = (struct smb2_ioctl_rsp *)rsp_iov.iov_base;
2991
2992         if (rc != 0)
2993                 trace_smb3_fsctl_err(xid, persistent_fid, tcon->tid,
2994                                 ses->Suid, 0, opcode, rc);
2995
2996         if ((rc != 0) && (rc != -EINVAL) && (rc != -E2BIG)) {
2997                 cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
2998                 goto ioctl_exit;
2999         } else if (rc == -EINVAL) {
3000                 if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) &&
3001                     (opcode != FSCTL_SRV_COPYCHUNK)) {
3002                         cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3003                         goto ioctl_exit;
3004                 }
3005         } else if (rc == -E2BIG) {
3006                 if (opcode != FSCTL_QUERY_ALLOCATED_RANGES) {
3007                         cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3008                         goto ioctl_exit;
3009                 }
3010         }
3011
3012         /* check if caller wants to look at return data or just return rc */
3013         if ((plen == NULL) || (out_data == NULL))
3014                 goto ioctl_exit;
3015
3016         *plen = le32_to_cpu(rsp->OutputCount);
3017
3018         /* We check for obvious errors in the output buffer length and offset */
3019         if (*plen == 0)
3020                 goto ioctl_exit; /* server returned no data */
3021         else if (*plen > rsp_iov.iov_len || *plen > 0xFF00) {
3022                 cifs_tcon_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen);
3023                 *plen = 0;
3024                 rc = -EIO;
3025                 goto ioctl_exit;
3026         }
3027
3028         if (rsp_iov.iov_len - *plen < le32_to_cpu(rsp->OutputOffset)) {
3029                 cifs_tcon_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen,
3030                         le32_to_cpu(rsp->OutputOffset));
3031                 *plen = 0;
3032                 rc = -EIO;
3033                 goto ioctl_exit;
3034         }
3035
3036         *out_data = kmemdup((char *)rsp + le32_to_cpu(rsp->OutputOffset),
3037                             *plen, GFP_KERNEL);
3038         if (*out_data == NULL) {
3039                 rc = -ENOMEM;
3040                 goto ioctl_exit;
3041         }
3042
3043 ioctl_exit:
3044         SMB2_ioctl_free(&rqst);
3045         free_rsp_buf(resp_buftype, rsp);
3046         return rc;
3047 }
3048
3049 /*
3050  *   Individual callers to ioctl worker function follow
3051  */
3052
3053 int
3054 SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
3055                      u64 persistent_fid, u64 volatile_fid)
3056 {
3057         int rc;
3058         struct  compress_ioctl fsctl_input;
3059         char *ret_data = NULL;
3060
3061         fsctl_input.CompressionState =
3062                         cpu_to_le16(COMPRESSION_FORMAT_DEFAULT);
3063
3064         rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
3065                         FSCTL_SET_COMPRESSION, true /* is_fsctl */,
3066                         (char *)&fsctl_input /* data input */,
3067                         2 /* in data len */, CIFSMaxBufSize /* max out data */,
3068                         &ret_data /* out data */, NULL);
3069
3070         cifs_dbg(FYI, "set compression rc %d\n", rc);
3071
3072         return rc;
3073 }
3074
3075 int
3076 SMB2_close_init(struct cifs_tcon *tcon, struct smb_rqst *rqst,
3077                 u64 persistent_fid, u64 volatile_fid, bool query_attrs)
3078 {
3079         struct smb2_close_req *req;
3080         struct kvec *iov = rqst->rq_iov;
3081         unsigned int total_len;
3082         int rc;
3083
3084         rc = smb2_plain_req_init(SMB2_CLOSE, tcon, (void **) &req, &total_len);
3085         if (rc)
3086                 return rc;
3087
3088         req->PersistentFileId = persistent_fid;
3089         req->VolatileFileId = volatile_fid;
3090         if (query_attrs)
3091                 req->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
3092         else
3093                 req->Flags = 0;
3094         iov[0].iov_base = (char *)req;
3095         iov[0].iov_len = total_len;
3096
3097         return 0;
3098 }
3099
3100 void
3101 SMB2_close_free(struct smb_rqst *rqst)
3102 {
3103         if (rqst && rqst->rq_iov)
3104                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3105 }
3106
3107 int
3108 __SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3109              u64 persistent_fid, u64 volatile_fid,
3110              struct smb2_file_network_open_info *pbuf)
3111 {
3112         struct smb_rqst rqst;
3113         struct smb2_close_rsp *rsp = NULL;
3114         struct cifs_ses *ses = tcon->ses;
3115         struct kvec iov[1];
3116         struct kvec rsp_iov;
3117         int resp_buftype = CIFS_NO_BUFFER;
3118         int rc = 0;
3119         int flags = 0;
3120         bool query_attrs = false;
3121
3122         cifs_dbg(FYI, "Close\n");
3123
3124         if (!ses || !(ses->server))
3125                 return -EIO;
3126
3127         if (smb3_encryption_required(tcon))
3128                 flags |= CIFS_TRANSFORM_REQ;
3129
3130         memset(&rqst, 0, sizeof(struct smb_rqst));
3131         memset(&iov, 0, sizeof(iov));
3132         rqst.rq_iov = iov;
3133         rqst.rq_nvec = 1;
3134
3135         /* check if need to ask server to return timestamps in close response */
3136         if (pbuf)
3137                 query_attrs = true;
3138
3139         trace_smb3_close_enter(xid, persistent_fid, tcon->tid, ses->Suid);
3140         rc = SMB2_close_init(tcon, &rqst, persistent_fid, volatile_fid,
3141                              query_attrs);
3142         if (rc)
3143                 goto close_exit;
3144
3145         rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
3146         rsp = (struct smb2_close_rsp *)rsp_iov.iov_base;
3147
3148         if (rc != 0) {
3149                 cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
3150                 trace_smb3_close_err(xid, persistent_fid, tcon->tid, ses->Suid,
3151                                      rc);
3152                 goto close_exit;
3153         } else {
3154                 trace_smb3_close_done(xid, persistent_fid, tcon->tid,
3155                                       ses->Suid);
3156                 /*
3157                  * Note that have to subtract 4 since struct network_open_info
3158                  * has a final 4 byte pad that close response does not have
3159                  */
3160                 if (pbuf)
3161                         memcpy(pbuf, (char *)&rsp->CreationTime, sizeof(*pbuf) - 4);
3162         }
3163
3164         atomic_dec(&tcon->num_remote_opens);
3165 close_exit:
3166         SMB2_close_free(&rqst);
3167         free_rsp_buf(resp_buftype, rsp);
3168
3169         /* retry close in a worker thread if this one is interrupted */
3170         if (rc == -EINTR) {
3171                 int tmp_rc;
3172
3173                 tmp_rc = smb2_handle_cancelled_close(tcon, persistent_fid,
3174                                                      volatile_fid);
3175                 if (tmp_rc)
3176                         cifs_dbg(VFS, "handle cancelled close fid 0x%llx returned error %d\n",
3177                                  persistent_fid, tmp_rc);
3178         }
3179         return rc;
3180 }
3181
3182 int
3183 SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3184                 u64 persistent_fid, u64 volatile_fid)
3185 {
3186         return __SMB2_close(xid, tcon, persistent_fid, volatile_fid, NULL);
3187 }
3188
3189 int
3190 smb2_validate_iov(unsigned int offset, unsigned int buffer_length,
3191                   struct kvec *iov, unsigned int min_buf_size)
3192 {
3193         unsigned int smb_len = iov->iov_len;
3194         char *end_of_smb = smb_len + (char *)iov->iov_base;
3195         char *begin_of_buf = offset + (char *)iov->iov_base;
3196         char *end_of_buf = begin_of_buf + buffer_length;
3197
3198
3199         if (buffer_length < min_buf_size) {
3200                 cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n",
3201                          buffer_length, min_buf_size);
3202                 return -EINVAL;
3203         }
3204
3205         /* check if beyond RFC1001 maximum length */
3206         if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
3207                 cifs_dbg(VFS, "buffer length %d or smb length %d too large\n",
3208                          buffer_length, smb_len);
3209                 return -EINVAL;
3210         }
3211
3212         if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
3213                 cifs_dbg(VFS, "illegal server response, bad offset to data\n");
3214                 return -EINVAL;
3215         }
3216
3217         return 0;
3218 }
3219
3220 /*
3221  * If SMB buffer fields are valid, copy into temporary buffer to hold result.
3222  * Caller must free buffer.
3223  */
3224 int
3225 smb2_validate_and_copy_iov(unsigned int offset, unsigned int buffer_length,
3226                            struct kvec *iov, unsigned int minbufsize,
3227                            char *data)
3228 {
3229         char *begin_of_buf = offset + (char *)iov->iov_base;
3230         int rc;
3231
3232         if (!data)
3233                 return -EINVAL;
3234
3235         rc = smb2_validate_iov(offset, buffer_length, iov, minbufsize);
3236         if (rc)
3237                 return rc;
3238
3239         memcpy(data, begin_of_buf, buffer_length);
3240
3241         return 0;
3242 }
3243
3244 int
3245 SMB2_query_info_init(struct cifs_tcon *tcon, struct smb_rqst *rqst,
3246                      u64 persistent_fid, u64 volatile_fid,
3247                      u8 info_class, u8 info_type, u32 additional_info,
3248                      size_t output_len, size_t input_len, void *input)
3249 {
3250         struct smb2_query_info_req *req;
3251         struct kvec *iov = rqst->rq_iov;
3252         unsigned int total_len;
3253         int rc;
3254
3255         rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, (void **) &req,
3256                              &total_len);
3257         if (rc)
3258                 return rc;
3259
3260         req->InfoType = info_type;
3261         req->FileInfoClass = info_class;
3262         req->PersistentFileId = persistent_fid;
3263         req->VolatileFileId = volatile_fid;
3264         req->AdditionalInformation = cpu_to_le32(additional_info);
3265
3266         req->OutputBufferLength = cpu_to_le32(output_len);
3267         if (input_len) {
3268                 req->InputBufferLength = cpu_to_le32(input_len);
3269                 /* total_len for smb query request never close to le16 max */
3270                 req->InputBufferOffset = cpu_to_le16(total_len - 1);
3271                 memcpy(req->Buffer, input, input_len);
3272         }
3273
3274         iov[0].iov_base = (char *)req;
3275         /* 1 for Buffer */
3276         iov[0].iov_len = total_len - 1 + input_len;
3277         return 0;
3278 }
3279
3280 void
3281 SMB2_query_info_free(struct smb_rqst *rqst)
3282 {
3283         if (rqst && rqst->rq_iov)
3284                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3285 }
3286
3287 static int
3288 query_info(const unsigned int xid, struct cifs_tcon *tcon,
3289            u64 persistent_fid, u64 volatile_fid, u8 info_class, u8 info_type,
3290            u32 additional_info, size_t output_len, size_t min_len, void **data,
3291                 u32 *dlen)
3292 {
3293         struct smb_rqst rqst;
3294         struct smb2_query_info_rsp *rsp = NULL;
3295         struct kvec iov[1];
3296         struct kvec rsp_iov;
3297         int rc = 0;
3298         int resp_buftype = CIFS_NO_BUFFER;
3299         struct cifs_ses *ses = tcon->ses;
3300         struct TCP_Server_Info *server;
3301         int flags = 0;
3302         bool allocated = false;
3303
3304         cifs_dbg(FYI, "Query Info\n");
3305
3306         if (!ses)
3307                 return -EIO;
3308         server = ses->server;
3309         if (!server)
3310                 return -EIO;
3311
3312         if (smb3_encryption_required(tcon))
3313                 flags |= CIFS_TRANSFORM_REQ;
3314
3315         memset(&rqst, 0, sizeof(struct smb_rqst));
3316         memset(&iov, 0, sizeof(iov));
3317         rqst.rq_iov = iov;
3318         rqst.rq_nvec = 1;
3319
3320         rc = SMB2_query_info_init(tcon, &rqst, persistent_fid, volatile_fid,
3321                                   info_class, info_type, additional_info,
3322                                   output_len, 0, NULL);
3323         if (rc)
3324                 goto qinf_exit;
3325
3326         trace_smb3_query_info_enter(xid, persistent_fid, tcon->tid,
3327                                     ses->Suid, info_class, (__u32)info_type);
3328
3329         rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
3330         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
3331
3332         if (rc) {
3333                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
3334                 trace_smb3_query_info_err(xid, persistent_fid, tcon->tid,
3335                                 ses->Suid, info_class, (__u32)info_type, rc);
3336                 goto qinf_exit;
3337         }
3338
3339         trace_smb3_query_info_done(xid, persistent_fid, tcon->tid,
3340                                 ses->Suid, info_class, (__u32)info_type);
3341
3342         if (dlen) {
3343                 *dlen = le32_to_cpu(rsp->OutputBufferLength);
3344                 if (!*data) {
3345                         *data = kmalloc(*dlen, GFP_KERNEL);
3346                         if (!*data) {
3347                                 cifs_tcon_dbg(VFS,
3348                                         "Error %d allocating memory for acl\n",
3349                                         rc);
3350                                 *dlen = 0;
3351                                 rc = -ENOMEM;
3352                                 goto qinf_exit;
3353                         }
3354                         allocated = true;
3355                 }
3356         }
3357
3358         rc = smb2_validate_and_copy_iov(le16_to_cpu(rsp->OutputBufferOffset),
3359                                         le32_to_cpu(rsp->OutputBufferLength),
3360                                         &rsp_iov, min_len, *data);
3361         if (rc && allocated) {
3362                 kfree(*data);
3363                 *data = NULL;
3364                 *dlen = 0;
3365         }
3366
3367 qinf_exit:
3368         SMB2_query_info_free(&rqst);
3369         free_rsp_buf(resp_buftype, rsp);
3370         return rc;
3371 }
3372
3373 int SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
3374         u64 persistent_fid, u64 volatile_fid, struct smb2_file_all_info *data)
3375 {
3376         return query_info(xid, tcon, persistent_fid, volatile_fid,
3377                           FILE_ALL_INFORMATION, SMB2_O_INFO_FILE, 0,
3378                           sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
3379                           sizeof(struct smb2_file_all_info), (void **)&data,
3380                           NULL);
3381 }
3382
3383 int
3384 SMB2_query_acl(const unsigned int xid, struct cifs_tcon *tcon,
3385                 u64 persistent_fid, u64 volatile_fid,
3386                 void **data, u32 *plen)
3387 {
3388         __u32 additional_info = OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO;
3389         *plen = 0;
3390
3391         return query_info(xid, tcon, persistent_fid, volatile_fid,
3392                           0, SMB2_O_INFO_SECURITY, additional_info,
3393                           SMB2_MAX_BUFFER_SIZE, MIN_SEC_DESC_LEN, data, plen);
3394 }
3395
3396 int
3397 SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
3398                  u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
3399 {
3400         return query_info(xid, tcon, persistent_fid, volatile_fid,
3401                           FILE_INTERNAL_INFORMATION, SMB2_O_INFO_FILE, 0,
3402                           sizeof(struct smb2_file_internal_info),
3403                           sizeof(struct smb2_file_internal_info),
3404                           (void **)&uniqueid, NULL);
3405 }
3406
3407 /*
3408  * CHANGE_NOTIFY Request is sent to get notifications on changes to a directory
3409  * See MS-SMB2 2.2.35 and 2.2.36
3410  */
3411
3412 static int
3413 SMB2_notify_init(const unsigned int xid, struct smb_rqst *rqst,
3414                 struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid,
3415                 u32 completion_filter, bool watch_tree)
3416 {
3417         struct smb2_change_notify_req *req;
3418         struct kvec *iov = rqst->rq_iov;
3419         unsigned int total_len;
3420         int rc;
3421
3422         rc = smb2_plain_req_init(SMB2_CHANGE_NOTIFY, tcon, (void **) &req, &total_len);
3423         if (rc)
3424                 return rc;
3425
3426         req->PersistentFileId = persistent_fid;
3427         req->VolatileFileId = volatile_fid;
3428         /* See note 354 of MS-SMB2, 64K max */
3429         req->OutputBufferLength =
3430                 cpu_to_le32(SMB2_MAX_BUFFER_SIZE - MAX_SMB2_HDR_SIZE);
3431         req->CompletionFilter = cpu_to_le32(completion_filter);
3432         if (watch_tree)
3433                 req->Flags = cpu_to_le16(SMB2_WATCH_TREE);
3434         else
3435                 req->Flags = 0;
3436
3437         iov[0].iov_base = (char *)req;
3438         iov[0].iov_len = total_len;
3439
3440         return 0;
3441 }
3442
3443 int
3444 SMB2_change_notify(const unsigned int xid, struct cifs_tcon *tcon,
3445                 u64 persistent_fid, u64 volatile_fid, bool watch_tree,
3446                 u32 completion_filter)
3447 {
3448         struct cifs_ses *ses = tcon->ses;
3449         struct smb_rqst rqst;
3450         struct kvec iov[1];
3451         struct kvec rsp_iov = {NULL, 0};
3452         int resp_buftype = CIFS_NO_BUFFER;
3453         int flags = 0;
3454         int rc = 0;
3455
3456         cifs_dbg(FYI, "change notify\n");
3457         if (!ses || !(ses->server))
3458                 return -EIO;
3459
3460         if (smb3_encryption_required(tcon))
3461                 flags |= CIFS_TRANSFORM_REQ;
3462
3463         memset(&rqst, 0, sizeof(struct smb_rqst));
3464         memset(&iov, 0, sizeof(iov));
3465         rqst.rq_iov = iov;
3466         rqst.rq_nvec = 1;
3467
3468         rc = SMB2_notify_init(xid, &rqst, tcon, persistent_fid, volatile_fid,
3469                               completion_filter, watch_tree);
3470         if (rc)
3471                 goto cnotify_exit;
3472
3473         trace_smb3_notify_enter(xid, persistent_fid, tcon->tid, ses->Suid,
3474                                 (u8)watch_tree, completion_filter);
3475         rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
3476
3477         if (rc != 0) {
3478                 cifs_stats_fail_inc(tcon, SMB2_CHANGE_NOTIFY_HE);
3479                 trace_smb3_notify_err(xid, persistent_fid, tcon->tid, ses->Suid,
3480                                 (u8)watch_tree, completion_filter, rc);
3481         } else
3482                 trace_smb3_notify_done(xid, persistent_fid, tcon->tid,
3483                                 ses->Suid, (u8)watch_tree, completion_filter);
3484
3485  cnotify_exit:
3486         if (rqst.rq_iov)
3487                 cifs_small_buf_release(rqst.rq_iov[0].iov_base); /* request */
3488         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3489         return rc;
3490 }
3491
3492
3493
3494 /*
3495  * This is a no-op for now. We're not really interested in the reply, but
3496  * rather in the fact that the server sent one and that server->lstrp
3497  * gets updated.
3498  *
3499  * FIXME: maybe we should consider checking that the reply matches request?
3500  */
3501 static void
3502 smb2_echo_callback(struct mid_q_entry *mid)
3503 {
3504         struct TCP_Server_Info *server = mid->callback_data;
3505         struct smb2_echo_rsp *rsp = (struct smb2_echo_rsp *)mid->resp_buf;
3506         struct cifs_credits credits = { .value = 0, .instance = 0 };
3507
3508         if (mid->mid_state == MID_RESPONSE_RECEIVED
3509             || mid->mid_state == MID_RESPONSE_MALFORMED) {
3510                 credits.value = le16_to_cpu(rsp->sync_hdr.CreditRequest);
3511                 credits.instance = server->reconnect_instance;
3512         }
3513
3514         DeleteMidQEntry(mid);
3515         add_credits(server, &credits, CIFS_ECHO_OP);
3516 }
3517
3518 void smb2_reconnect_server(struct work_struct *work)
3519 {
3520         struct TCP_Server_Info *server = container_of(work,
3521                                         struct TCP_Server_Info, reconnect.work);
3522         struct cifs_ses *ses;
3523         struct cifs_tcon *tcon, *tcon2;
3524         struct list_head tmp_list;
3525         int tcon_exist = false;
3526         int rc;
3527         int resched = false;
3528
3529
3530         /* Prevent simultaneous reconnects that can corrupt tcon->rlist list */
3531         mutex_lock(&server->reconnect_mutex);
3532
3533         INIT_LIST_HEAD(&tmp_list);
3534         cifs_dbg(FYI, "Need negotiate, reconnecting tcons\n");
3535
3536         spin_lock(&cifs_tcp_ses_lock);
3537         list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
3538                 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
3539                         if (tcon->need_reconnect || tcon->need_reopen_files) {
3540                                 tcon->tc_count++;
3541                                 list_add_tail(&tcon->rlist, &tmp_list);
3542                                 tcon_exist = true;
3543                         }
3544                 }
3545                 /*
3546                  * IPC has the same lifetime as its session and uses its
3547                  * refcount.
3548                  */
3549                 if (ses->tcon_ipc && ses->tcon_ipc->need_reconnect) {
3550                         list_add_tail(&ses->tcon_ipc->rlist, &tmp_list);
3551                         tcon_exist = true;
3552                         ses->ses_count++;
3553                 }
3554         }
3555         /*
3556          * Get the reference to server struct to be sure that the last call of
3557          * cifs_put_tcon() in the loop below won't release the server pointer.
3558          */
3559         if (tcon_exist)
3560                 server->srv_count++;
3561
3562         spin_unlock(&cifs_tcp_ses_lock);
3563
3564         list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) {
3565                 rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon);
3566                 if (!rc)
3567                         cifs_reopen_persistent_handles(tcon);
3568                 else
3569                         resched = true;
3570                 list_del_init(&tcon->rlist);
3571                 if (tcon->ipc)
3572                         cifs_put_smb_ses(tcon->ses);
3573                 else
3574                         cifs_put_tcon(tcon);
3575         }
3576
3577         cifs_dbg(FYI, "Reconnecting tcons finished\n");
3578         if (resched)
3579                 queue_delayed_work(cifsiod_wq, &server->reconnect, 2 * HZ);
3580         mutex_unlock(&server->reconnect_mutex);
3581
3582         /* now we can safely release srv struct */
3583         if (tcon_exist)
3584                 cifs_put_tcp_session(server, 1);
3585 }
3586
3587 int
3588 SMB2_echo(struct TCP_Server_Info *server)
3589 {
3590         struct smb2_echo_req *req;
3591         int rc = 0;
3592         struct kvec iov[1];
3593         struct smb_rqst rqst = { .rq_iov = iov,
3594                                  .rq_nvec = 1 };
3595         unsigned int total_len;
3596
3597         cifs_dbg(FYI, "In echo request\n");
3598
3599         if (server->tcpStatus == CifsNeedNegotiate) {
3600                 /* No need to send echo on newly established connections */
3601                 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
3602                 return rc;
3603         }
3604
3605         rc = smb2_plain_req_init(SMB2_ECHO, NULL, (void **)&req, &total_len);
3606         if (rc)
3607                 return rc;
3608
3609         req->sync_hdr.CreditRequest = cpu_to_le16(1);
3610
3611         iov[0].iov_len = total_len;
3612         iov[0].iov_base = (char *)req;
3613
3614         rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, NULL,
3615                              server, CIFS_ECHO_OP, NULL);
3616         if (rc)
3617                 cifs_dbg(FYI, "Echo request failed: %d\n", rc);
3618
3619         cifs_small_buf_release(req);
3620         return rc;
3621 }
3622
3623 void
3624 SMB2_flush_free(struct smb_rqst *rqst)
3625 {
3626         if (rqst && rqst->rq_iov)
3627                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3628 }
3629
3630 int
3631 SMB2_flush_init(const unsigned int xid, struct smb_rqst *rqst,
3632                 struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid)
3633 {
3634         struct smb2_flush_req *req;
3635         struct kvec *iov = rqst->rq_iov;
3636         unsigned int total_len;
3637         int rc;
3638
3639         rc = smb2_plain_req_init(SMB2_FLUSH, tcon, (void **) &req, &total_len);
3640         if (rc)
3641                 return rc;
3642
3643         req->PersistentFileId = persistent_fid;
3644         req->VolatileFileId = volatile_fid;
3645
3646         iov[0].iov_base = (char *)req;
3647         iov[0].iov_len = total_len;
3648
3649         return 0;
3650 }
3651
3652 int
3653 SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
3654            u64 volatile_fid)
3655 {
3656         struct cifs_ses *ses = tcon->ses;
3657         struct smb_rqst rqst;
3658         struct kvec iov[1];
3659         struct kvec rsp_iov = {NULL, 0};
3660         int resp_buftype = CIFS_NO_BUFFER;
3661         int flags = 0;
3662         int rc = 0;
3663
3664         cifs_dbg(FYI, "flush\n");
3665         if (!ses || !(ses->server))
3666                 return -EIO;
3667
3668         if (smb3_encryption_required(tcon))
3669                 flags |= CIFS_TRANSFORM_REQ;
3670
3671         memset(&rqst, 0, sizeof(struct smb_rqst));
3672         memset(&iov, 0, sizeof(iov));
3673         rqst.rq_iov = iov;
3674         rqst.rq_nvec = 1;
3675
3676         rc = SMB2_flush_init(xid, &rqst, tcon, persistent_fid, volatile_fid);
3677         if (rc)
3678                 goto flush_exit;
3679
3680         trace_smb3_flush_enter(xid, persistent_fid, tcon->tid, ses->Suid);
3681         rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
3682
3683         if (rc != 0) {
3684                 cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
3685                 trace_smb3_flush_err(xid, persistent_fid, tcon->tid, ses->Suid,
3686                                      rc);
3687         } else
3688                 trace_smb3_flush_done(xid, persistent_fid, tcon->tid,
3689                                       ses->Suid);
3690
3691  flush_exit:
3692         SMB2_flush_free(&rqst);
3693         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3694         return rc;
3695 }
3696
3697 /*
3698  * To form a chain of read requests, any read requests after the first should
3699  * have the end_of_chain boolean set to true.
3700  */
3701 static int
3702 smb2_new_read_req(void **buf, unsigned int *total_len,
3703         struct cifs_io_parms *io_parms, struct cifs_readdata *rdata,
3704         unsigned int remaining_bytes, int request_type)
3705 {
3706         int rc = -EACCES;
3707         struct smb2_read_plain_req *req = NULL;
3708         struct smb2_sync_hdr *shdr;
3709         struct TCP_Server_Info *server;
3710
3711         rc = smb2_plain_req_init(SMB2_READ, io_parms->tcon, (void **) &req,
3712                                  total_len);
3713         if (rc)
3714                 return rc;
3715
3716         server = io_parms->tcon->ses->server;
3717         if (server == NULL)
3718                 return -ECONNABORTED;
3719
3720         shdr = &req->sync_hdr;
3721         shdr->ProcessId = cpu_to_le32(io_parms->pid);
3722
3723         req->PersistentFileId = io_parms->persistent_fid;
3724         req->VolatileFileId = io_parms->volatile_fid;
3725         req->ReadChannelInfoOffset = 0; /* reserved */
3726         req->ReadChannelInfoLength = 0; /* reserved */
3727         req->Channel = 0; /* reserved */
3728         req->MinimumCount = 0;
3729         req->Length = cpu_to_le32(io_parms->length);
3730         req->Offset = cpu_to_le64(io_parms->offset);
3731
3732         trace_smb3_read_enter(0 /* xid */,
3733                         io_parms->persistent_fid,
3734                         io_parms->tcon->tid, io_parms->tcon->ses->Suid,
3735                         io_parms->offset, io_parms->length);
3736 #ifdef CONFIG_CIFS_SMB_DIRECT
3737         /*
3738          * If we want to do a RDMA write, fill in and append
3739          * smbd_buffer_descriptor_v1 to the end of read request
3740          */
3741         if (server->rdma && rdata && !server->sign &&
3742                 rdata->bytes >= server->smbd_conn->rdma_readwrite_threshold) {
3743
3744                 struct smbd_buffer_descriptor_v1 *v1;
3745                 bool need_invalidate =
3746                         io_parms->tcon->ses->server->dialect == SMB30_PROT_ID;
3747
3748                 rdata->mr = smbd_register_mr(
3749                                 server->smbd_conn, rdata->pages,
3750                                 rdata->nr_pages, rdata->page_offset,
3751                                 rdata->tailsz, true, need_invalidate);
3752                 if (!rdata->mr)
3753                         return -EAGAIN;
3754
3755                 req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
3756                 if (need_invalidate)
3757                         req->Channel = SMB2_CHANNEL_RDMA_V1;
3758                 req->ReadChannelInfoOffset =
3759                         cpu_to_le16(offsetof(struct smb2_read_plain_req, Buffer));
3760                 req->ReadChannelInfoLength =
3761                         cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
3762                 v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
3763                 v1->offset = cpu_to_le64(rdata->mr->mr->iova);
3764                 v1->token = cpu_to_le32(rdata->mr->mr->rkey);
3765                 v1->length = cpu_to_le32(rdata->mr->mr->length);
3766
3767                 *total_len += sizeof(*v1) - 1;
3768         }
3769 #endif
3770         if (request_type & CHAINED_REQUEST) {
3771                 if (!(request_type & END_OF_CHAIN)) {
3772                         /* next 8-byte aligned request */
3773                         *total_len = DIV_ROUND_UP(*total_len, 8) * 8;
3774                         shdr->NextCommand = cpu_to_le32(*total_len);
3775                 } else /* END_OF_CHAIN */
3776                         shdr->NextCommand = 0;
3777                 if (request_type & RELATED_REQUEST) {
3778                         shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
3779                         /*
3780                          * Related requests use info from previous read request
3781                          * in chain.
3782                          */
3783                         shdr->SessionId = 0xFFFFFFFF;
3784                         shdr->TreeId = 0xFFFFFFFF;
3785                         req->PersistentFileId = 0xFFFFFFFF;
3786                         req->VolatileFileId = 0xFFFFFFFF;
3787                 }
3788         }
3789         if (remaining_bytes > io_parms->length)
3790                 req->RemainingBytes = cpu_to_le32(remaining_bytes);
3791         else
3792                 req->RemainingBytes = 0;
3793
3794         *buf = req;
3795         return rc;
3796 }
3797
3798 static void
3799 smb2_readv_callback(struct mid_q_entry *mid)
3800 {
3801         struct cifs_readdata *rdata = mid->callback_data;
3802         struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
3803         struct TCP_Server_Info *server = tcon->ses->server;
3804         struct smb2_sync_hdr *shdr =
3805                                 (struct smb2_sync_hdr *)rdata->iov[0].iov_base;
3806         struct cifs_credits credits = { .value = 0, .instance = 0 };
3807         struct smb_rqst rqst = { .rq_iov = &rdata->iov[1],
3808                                  .rq_nvec = 1,
3809                                  .rq_pages = rdata->pages,
3810                                  .rq_offset = rdata->page_offset,
3811                                  .rq_npages = rdata->nr_pages,
3812                                  .rq_pagesz = rdata->pagesz,
3813                                  .rq_tailsz = rdata->tailsz };
3814
3815         cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%u\n",
3816                  __func__, mid->mid, mid->mid_state, rdata->result,
3817                  rdata->bytes);
3818
3819         switch (mid->mid_state) {
3820         case MID_RESPONSE_RECEIVED:
3821                 credits.value = le16_to_cpu(shdr->CreditRequest);
3822                 credits.instance = server->reconnect_instance;
3823                 /* result already set, check signature */
3824                 if (server->sign && !mid->decrypted) {
3825                         int rc;
3826
3827                         rc = smb2_verify_signature(&rqst, server);
3828                         if (rc)
3829                                 cifs_tcon_dbg(VFS, "SMB signature verification returned error = %d\n",
3830                                          rc);
3831                 }
3832                 /* FIXME: should this be counted toward the initiating task? */
3833                 task_io_account_read(rdata->got_bytes);
3834                 cifs_stats_bytes_read(tcon, rdata->got_bytes);
3835                 break;
3836         case MID_REQUEST_SUBMITTED:
3837         case MID_RETRY_NEEDED:
3838                 rdata->result = -EAGAIN;
3839                 if (server->sign && rdata->got_bytes)
3840                         /* reset bytes number since we can not check a sign */
3841                         rdata->got_bytes = 0;
3842                 /* FIXME: should this be counted toward the initiating task? */
3843                 task_io_account_read(rdata->got_bytes);
3844                 cifs_stats_bytes_read(tcon, rdata->got_bytes);
3845                 break;
3846         case MID_RESPONSE_MALFORMED:
3847                 credits.value = le16_to_cpu(shdr->CreditRequest);
3848                 credits.instance = server->reconnect_instance;
3849                 /* fall through */
3850         default:
3851                 rdata->result = -EIO;
3852         }
3853 #ifdef CONFIG_CIFS_SMB_DIRECT
3854         /*
3855          * If this rdata has a memmory registered, the MR can be freed
3856          * MR needs to be freed as soon as I/O finishes to prevent deadlock
3857          * because they have limited number and are used for future I/Os
3858          */
3859         if (rdata->mr) {
3860                 smbd_deregister_mr(rdata->mr);
3861                 rdata->mr = NULL;
3862         }
3863 #endif
3864         if (rdata->result && rdata->result != -ENODATA) {
3865                 cifs_stats_fail_inc(tcon, SMB2_READ_HE);
3866                 trace_smb3_read_err(0 /* xid */,
3867                                     rdata->cfile->fid.persistent_fid,
3868                                     tcon->tid, tcon->ses->Suid, rdata->offset,
3869                                     rdata->bytes, rdata->result);
3870         } else
3871                 trace_smb3_read_done(0 /* xid */,
3872                                      rdata->cfile->fid.persistent_fid,
3873                                      tcon->tid, tcon->ses->Suid,
3874                                      rdata->offset, rdata->got_bytes);
3875
3876         queue_work(cifsiod_wq, &rdata->work);
3877         DeleteMidQEntry(mid);
3878         add_credits(server, &credits, 0);
3879 }
3880
3881 /* smb2_async_readv - send an async read, and set up mid to handle result */
3882 int
3883 smb2_async_readv(struct cifs_readdata *rdata)
3884 {
3885         int rc, flags = 0;
3886         char *buf;
3887         struct smb2_sync_hdr *shdr;
3888         struct cifs_io_parms io_parms;
3889         struct smb_rqst rqst = { .rq_iov = rdata->iov,
3890                                  .rq_nvec = 1 };
3891         struct TCP_Server_Info *server;
3892         unsigned int total_len;
3893
3894         cifs_dbg(FYI, "%s: offset=%llu bytes=%u\n",
3895                  __func__, rdata->offset, rdata->bytes);
3896
3897         io_parms.tcon = tlink_tcon(rdata->cfile->tlink);
3898         io_parms.offset = rdata->offset;
3899         io_parms.length = rdata->bytes;
3900         io_parms.persistent_fid = rdata->cfile->fid.persistent_fid;
3901         io_parms.volatile_fid = rdata->cfile->fid.volatile_fid;
3902         io_parms.pid = rdata->pid;
3903
3904         server = io_parms.tcon->ses->server;
3905
3906         rc = smb2_new_read_req(
3907                 (void **) &buf, &total_len, &io_parms, rdata, 0, 0);
3908         if (rc)
3909                 return rc;
3910
3911         if (smb3_encryption_required(io_parms.tcon))
3912                 flags |= CIFS_TRANSFORM_REQ;
3913
3914         rdata->iov[0].iov_base = buf;
3915         rdata->iov[0].iov_len = total_len;
3916
3917         shdr = (struct smb2_sync_hdr *)buf;
3918
3919         if (rdata->credits.value > 0) {
3920                 shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(rdata->bytes,
3921                                                 SMB2_MAX_BUFFER_SIZE));
3922                 shdr->CreditRequest =
3923                         cpu_to_le16(le16_to_cpu(shdr->CreditCharge) + 1);
3924
3925                 rc = adjust_credits(server, &rdata->credits, rdata->bytes);
3926                 if (rc)
3927                         goto async_readv_out;
3928
3929                 flags |= CIFS_HAS_CREDITS;
3930         }
3931
3932         kref_get(&rdata->refcount);
3933         rc = cifs_call_async(io_parms.tcon->ses->server, &rqst,
3934                              cifs_readv_receive, smb2_readv_callback,
3935                              smb3_handle_read_data, rdata, flags,
3936                              &rdata->credits);
3937         if (rc) {
3938                 kref_put(&rdata->refcount, cifs_readdata_release);
3939                 cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE);
3940                 trace_smb3_read_err(0 /* xid */, io_parms.persistent_fid,
3941                                     io_parms.tcon->tid,
3942                                     io_parms.tcon->ses->Suid,
3943                                     io_parms.offset, io_parms.length, rc);
3944         }
3945
3946 async_readv_out:
3947         cifs_small_buf_release(buf);
3948         return rc;
3949 }
3950
3951 int
3952 SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
3953           unsigned int *nbytes, char **buf, int *buf_type)
3954 {
3955         struct smb_rqst rqst;
3956         int resp_buftype, rc;
3957         struct smb2_read_plain_req *req = NULL;
3958         struct smb2_read_rsp *rsp = NULL;
3959         struct kvec iov[1];
3960         struct kvec rsp_iov;
3961         unsigned int total_len;
3962         int flags = CIFS_LOG_ERROR;
3963         struct cifs_ses *ses = io_parms->tcon->ses;
3964
3965         *nbytes = 0;
3966         rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);
3967         if (rc)
3968                 return rc;
3969
3970         if (smb3_encryption_required(io_parms->tcon))
3971                 flags |= CIFS_TRANSFORM_REQ;
3972
3973         iov[0].iov_base = (char *)req;
3974         iov[0].iov_len = total_len;
3975
3976         memset(&rqst, 0, sizeof(struct smb_rqst));
3977         rqst.rq_iov = iov;
3978         rqst.rq_nvec = 1;
3979
3980         rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
3981         rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
3982
3983         if (rc) {
3984                 if (rc != -ENODATA) {
3985                         cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
3986                         cifs_dbg(VFS, "Send error in read = %d\n", rc);
3987                         trace_smb3_read_err(xid, req->PersistentFileId,
3988                                             io_parms->tcon->tid, ses->Suid,
3989                                             io_parms->offset, io_parms->length,
3990                                             rc);
3991                 } else
3992                         trace_smb3_read_done(xid, req->PersistentFileId,
3993                                     io_parms->tcon->tid, ses->Suid,
3994                                     io_parms->offset, 0);
3995                 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3996                 cifs_small_buf_release(req);
3997                 return rc == -ENODATA ? 0 : rc;
3998         } else
3999                 trace_smb3_read_done(xid, req->PersistentFileId,
4000                                     io_parms->tcon->tid, ses->Suid,
4001                                     io_parms->offset, io_parms->length);
4002
4003         cifs_small_buf_release(req);
4004
4005         *nbytes = le32_to_cpu(rsp->DataLength);
4006         if ((*nbytes > CIFS_MAX_MSGSIZE) ||
4007             (*nbytes > io_parms->length)) {
4008                 cifs_dbg(FYI, "bad length %d for count %d\n",
4009                          *nbytes, io_parms->length);
4010                 rc = -EIO;
4011                 *nbytes = 0;
4012         }
4013
4014         if (*buf) {
4015                 memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);
4016                 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4017         } else if (resp_buftype != CIFS_NO_BUFFER) {
4018                 *buf = rsp_iov.iov_base;
4019                 if (resp_buftype == CIFS_SMALL_BUFFER)
4020                         *buf_type = CIFS_SMALL_BUFFER;
4021                 else if (resp_buftype == CIFS_LARGE_BUFFER)
4022                         *buf_type = CIFS_LARGE_BUFFER;
4023         }
4024         return rc;
4025 }
4026
4027 /*
4028  * Check the mid_state and signature on received buffer (if any), and queue the
4029  * workqueue completion task.
4030  */
4031 static void
4032 smb2_writev_callback(struct mid_q_entry *mid)
4033 {
4034         struct cifs_writedata *wdata = mid->callback_data;
4035         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
4036         struct TCP_Server_Info *server = tcon->ses->server;
4037         unsigned int written;
4038         struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
4039         struct cifs_credits credits = { .value = 0, .instance = 0 };
4040
4041         switch (mid->mid_state) {
4042         case MID_RESPONSE_RECEIVED:
4043                 credits.value = le16_to_cpu(rsp->sync_hdr.CreditRequest);
4044                 credits.instance = server->reconnect_instance;
4045                 wdata->result = smb2_check_receive(mid, server, 0);
4046                 if (wdata->result != 0)
4047                         break;
4048
4049                 written = le32_to_cpu(rsp->DataLength);
4050                 /*
4051                  * Mask off high 16 bits when bytes written as returned
4052                  * by the server is greater than bytes requested by the
4053                  * client. OS/2 servers are known to set incorrect
4054                  * CountHigh values.
4055                  */
4056                 if (written > wdata->bytes)
4057                         written &= 0xFFFF;
4058
4059                 if (written < wdata->bytes)
4060                         wdata->result = -ENOSPC;
4061                 else
4062                         wdata->bytes = written;
4063                 break;
4064         case MID_REQUEST_SUBMITTED:
4065         case MID_RETRY_NEEDED:
4066                 wdata->result = -EAGAIN;
4067                 break;
4068         case MID_RESPONSE_MALFORMED:
4069                 credits.value = le16_to_cpu(rsp->sync_hdr.CreditRequest);
4070                 credits.instance = server->reconnect_instance;
4071                 /* fall through */
4072         default:
4073                 wdata->result = -EIO;
4074                 break;
4075         }
4076 #ifdef CONFIG_CIFS_SMB_DIRECT
4077         /*
4078          * If this wdata has a memory registered, the MR can be freed
4079          * The number of MRs available is limited, it's important to recover
4080          * used MR as soon as I/O is finished. Hold MR longer in the later
4081          * I/O process can possibly result in I/O deadlock due to lack of MR
4082          * to send request on I/O retry
4083          */
4084         if (wdata->mr) {
4085                 smbd_deregister_mr(wdata->mr);
4086                 wdata->mr = NULL;
4087         }
4088 #endif
4089         if (wdata->result) {
4090                 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
4091                 trace_smb3_write_err(0 /* no xid */,
4092                                      wdata->cfile->fid.persistent_fid,
4093                                      tcon->tid, tcon->ses->Suid, wdata->offset,
4094                                      wdata->bytes, wdata->result);
4095                 if (wdata->result == -ENOSPC)
4096                         printk_once(KERN_WARNING "Out of space writing to %s\n",
4097                                     tcon->treeName);
4098         } else
4099                 trace_smb3_write_done(0 /* no xid */,
4100                                       wdata->cfile->fid.persistent_fid,
4101                                       tcon->tid, tcon->ses->Suid,
4102                                       wdata->offset, wdata->bytes);
4103
4104         queue_work(cifsiod_wq, &wdata->work);
4105         DeleteMidQEntry(mid);
4106         add_credits(server, &credits, 0);
4107 }
4108
4109 /* smb2_async_writev - send an async write, and set up mid to handle result */
4110 int
4111 smb2_async_writev(struct cifs_writedata *wdata,
4112                   void (*release)(struct kref *kref))
4113 {
4114         int rc = -EACCES, flags = 0;
4115         struct smb2_write_req *req = NULL;
4116         struct smb2_sync_hdr *shdr;
4117         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
4118         struct TCP_Server_Info *server = tcon->ses->server;
4119         struct kvec iov[1];
4120         struct smb_rqst rqst = { };
4121         unsigned int total_len;
4122
4123         rc = smb2_plain_req_init(SMB2_WRITE, tcon, (void **) &req, &total_len);
4124         if (rc)
4125                 return rc;
4126
4127         if (smb3_encryption_required(tcon))
4128                 flags |= CIFS_TRANSFORM_REQ;
4129
4130         shdr = (struct smb2_sync_hdr *)req;
4131         shdr->ProcessId = cpu_to_le32(wdata->cfile->pid);
4132
4133         req->PersistentFileId = wdata->cfile->fid.persistent_fid;
4134         req->VolatileFileId = wdata->cfile->fid.volatile_fid;
4135         req->WriteChannelInfoOffset = 0;
4136         req->WriteChannelInfoLength = 0;
4137         req->Channel = 0;
4138         req->Offset = cpu_to_le64(wdata->offset);
4139         req->DataOffset = cpu_to_le16(
4140                                 offsetof(struct smb2_write_req, Buffer));
4141         req->RemainingBytes = 0;
4142
4143         trace_smb3_write_enter(0 /* xid */, wdata->cfile->fid.persistent_fid,
4144                 tcon->tid, tcon->ses->Suid, wdata->offset, wdata->bytes);
4145 #ifdef CONFIG_CIFS_SMB_DIRECT
4146         /*
4147          * If we want to do a server RDMA read, fill in and append
4148          * smbd_buffer_descriptor_v1 to the end of write request
4149          */
4150         if (server->rdma && !server->sign && wdata->bytes >=
4151                 server->smbd_conn->rdma_readwrite_threshold) {
4152
4153                 struct smbd_buffer_descriptor_v1 *v1;
4154                 bool need_invalidate = server->dialect == SMB30_PROT_ID;
4155
4156                 wdata->mr = smbd_register_mr(
4157                                 server->smbd_conn, wdata->pages,
4158                                 wdata->nr_pages, wdata->page_offset,
4159                                 wdata->tailsz, false, need_invalidate);
4160                 if (!wdata->mr) {
4161                         rc = -EAGAIN;
4162                         goto async_writev_out;
4163                 }
4164                 req->Length = 0;
4165                 req->DataOffset = 0;
4166                 if (wdata->nr_pages > 1)
4167                         req->RemainingBytes =
4168                                 cpu_to_le32(
4169                                         (wdata->nr_pages - 1) * wdata->pagesz -
4170                                         wdata->page_offset + wdata->tailsz
4171                                 );
4172                 else
4173                         req->RemainingBytes = cpu_to_le32(wdata->tailsz);
4174                 req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
4175                 if (need_invalidate)
4176                         req->Channel = SMB2_CHANNEL_RDMA_V1;
4177                 req->WriteChannelInfoOffset =
4178                         cpu_to_le16(offsetof(struct smb2_write_req, Buffer));
4179                 req->WriteChannelInfoLength =
4180                         cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
4181                 v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
4182                 v1->offset = cpu_to_le64(wdata->mr->mr->iova);
4183                 v1->token = cpu_to_le32(wdata->mr->mr->rkey);
4184                 v1->length = cpu_to_le32(wdata->mr->mr->length);
4185         }
4186 #endif
4187         iov[0].iov_len = total_len - 1;
4188         iov[0].iov_base = (char *)req;
4189
4190         rqst.rq_iov = iov;
4191         rqst.rq_nvec = 1;
4192         rqst.rq_pages = wdata->pages;
4193         rqst.rq_offset = wdata->page_offset;
4194         rqst.rq_npages = wdata->nr_pages;
4195         rqst.rq_pagesz = wdata->pagesz;
4196         rqst.rq_tailsz = wdata->tailsz;
4197 #ifdef CONFIG_CIFS_SMB_DIRECT
4198         if (wdata->mr) {
4199                 iov[0].iov_len += sizeof(struct smbd_buffer_descriptor_v1);
4200                 rqst.rq_npages = 0;
4201         }
4202 #endif
4203         cifs_dbg(FYI, "async write at %llu %u bytes\n",
4204                  wdata->offset, wdata->bytes);
4205
4206 #ifdef CONFIG_CIFS_SMB_DIRECT
4207         /* For RDMA read, I/O size is in RemainingBytes not in Length */
4208         if (!wdata->mr)
4209                 req->Length = cpu_to_le32(wdata->bytes);
4210 #else
4211         req->Length = cpu_to_le32(wdata->bytes);
4212 #endif
4213
4214         if (wdata->credits.value > 0) {
4215                 shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->bytes,
4216                                                     SMB2_MAX_BUFFER_SIZE));
4217                 shdr->CreditRequest =
4218                         cpu_to_le16(le16_to_cpu(shdr->CreditCharge) + 1);
4219
4220                 rc = adjust_credits(server, &wdata->credits, wdata->bytes);
4221                 if (rc)
4222                         goto async_writev_out;
4223
4224                 flags |= CIFS_HAS_CREDITS;
4225         }
4226
4227         kref_get(&wdata->refcount);
4228         rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, NULL,
4229                              wdata, flags, &wdata->credits);
4230
4231         if (rc) {
4232                 trace_smb3_write_err(0 /* no xid */, req->PersistentFileId,
4233                                      tcon->tid, tcon->ses->Suid, wdata->offset,
4234                                      wdata->bytes, rc);
4235                 kref_put(&wdata->refcount, release);
4236                 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
4237         }
4238
4239 async_writev_out:
4240         cifs_small_buf_release(req);
4241         return rc;
4242 }
4243
4244 /*
4245  * SMB2_write function gets iov pointer to kvec array with n_vec as a length.
4246  * The length field from io_parms must be at least 1 and indicates a number of
4247  * elements with data to write that begins with position 1 in iov array. All
4248  * data length is specified by count.
4249  */
4250 int
4251 SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
4252            unsigned int *nbytes, struct kvec *iov, int n_vec)
4253 {
4254         struct smb_rqst rqst;
4255         int rc = 0;
4256         struct smb2_write_req *req = NULL;
4257         struct smb2_write_rsp *rsp = NULL;
4258         int resp_buftype;
4259         struct kvec rsp_iov;
4260         int flags = 0;
4261         unsigned int total_len;
4262
4263         *nbytes = 0;
4264
4265         if (n_vec < 1)
4266                 return rc;
4267
4268         rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, (void **) &req,
4269                              &total_len);
4270         if (rc)
4271                 return rc;
4272
4273         if (io_parms->tcon->ses->server == NULL)
4274                 return -ECONNABORTED;
4275
4276         if (smb3_encryption_required(io_parms->tcon))
4277                 flags |= CIFS_TRANSFORM_REQ;
4278
4279         req->sync_hdr.ProcessId = cpu_to_le32(io_parms->pid);
4280
4281         req->PersistentFileId = io_parms->persistent_fid;
4282         req->VolatileFileId = io_parms->volatile_fid;
4283         req->WriteChannelInfoOffset = 0;
4284         req->WriteChannelInfoLength = 0;
4285         req->Channel = 0;
4286         req->Length = cpu_to_le32(io_parms->length);
4287         req->Offset = cpu_to_le64(io_parms->offset);
4288         req->DataOffset = cpu_to_le16(
4289                                 offsetof(struct smb2_write_req, Buffer));
4290         req->RemainingBytes = 0;
4291
4292         trace_smb3_write_enter(xid, io_parms->persistent_fid,
4293                 io_parms->tcon->tid, io_parms->tcon->ses->Suid,
4294                 io_parms->offset, io_parms->length);
4295
4296         iov[0].iov_base = (char *)req;
4297         /* 1 for Buffer */
4298         iov[0].iov_len = total_len - 1;
4299
4300         memset(&rqst, 0, sizeof(struct smb_rqst));
4301         rqst.rq_iov = iov;
4302         rqst.rq_nvec = n_vec + 1;
4303
4304         rc = cifs_send_recv(xid, io_parms->tcon->ses, &rqst,
4305                             &resp_buftype, flags, &rsp_iov);
4306         rsp = (struct smb2_write_rsp *)rsp_iov.iov_base;
4307
4308         if (rc) {
4309                 trace_smb3_write_err(xid, req->PersistentFileId,
4310                                      io_parms->tcon->tid,
4311                                      io_parms->tcon->ses->Suid,
4312                                      io_parms->offset, io_parms->length, rc);
4313                 cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
4314                 cifs_dbg(VFS, "Send error in write = %d\n", rc);
4315         } else {
4316                 *nbytes = le32_to_cpu(rsp->DataLength);
4317                 trace_smb3_write_done(xid, req->PersistentFileId,
4318                                      io_parms->tcon->tid,
4319                                      io_parms->tcon->ses->Suid,
4320                                      io_parms->offset, *nbytes);
4321         }
4322
4323         cifs_small_buf_release(req);
4324         free_rsp_buf(resp_buftype, rsp);
4325         return rc;
4326 }
4327
4328 int posix_info_sid_size(const void *beg, const void *end)
4329 {
4330         size_t subauth;
4331         int total;
4332
4333         if (beg + 1 > end)
4334                 return -1;
4335
4336         subauth = *(u8 *)(beg+1);
4337         if (subauth < 1 || subauth > 15)
4338                 return -1;
4339
4340         total = 1 + 1 + 6 + 4*subauth;
4341         if (beg + total > end)
4342                 return -1;
4343
4344         return total;
4345 }
4346
4347 int posix_info_parse(const void *beg, const void *end,
4348                      struct smb2_posix_info_parsed *out)
4349
4350 {
4351         int total_len = 0;
4352         int sid_len;
4353         int name_len;
4354         const void *owner_sid;
4355         const void *group_sid;
4356         const void *name;
4357
4358         /* if no end bound given, assume payload to be correct */
4359         if (!end) {
4360                 const struct smb2_posix_info *p = beg;
4361
4362                 end = beg + le32_to_cpu(p->NextEntryOffset);
4363                 /* last element will have a 0 offset, pick a sensible bound */
4364                 if (end == beg)
4365                         end += 0xFFFF;
4366         }
4367
4368         /* check base buf */
4369         if (beg + sizeof(struct smb2_posix_info) > end)
4370                 return -1;
4371         total_len = sizeof(struct smb2_posix_info);
4372
4373         /* check owner sid */
4374         owner_sid = beg + total_len;
4375         sid_len = posix_info_sid_size(owner_sid, end);
4376         if (sid_len < 0)
4377                 return -1;
4378         total_len += sid_len;
4379
4380         /* check group sid */
4381         group_sid = beg + total_len;
4382         sid_len = posix_info_sid_size(group_sid, end);
4383         if (sid_len < 0)
4384                 return -1;
4385         total_len += sid_len;
4386
4387         /* check name len */
4388         if (beg + total_len + 4 > end)
4389                 return -1;
4390         name_len = le32_to_cpu(*(__le32 *)(beg + total_len));
4391         if (name_len < 1 || name_len > 0xFFFF)
4392                 return -1;
4393         total_len += 4;
4394
4395         /* check name */
4396         name = beg + total_len;
4397         if (name + name_len > end)
4398                 return -1;
4399         total_len += name_len;
4400
4401         if (out) {
4402                 out->base = beg;
4403                 out->size = total_len;
4404                 out->name_len = name_len;
4405                 out->name = name;
4406                 memcpy(&out->owner, owner_sid,
4407                        posix_info_sid_size(owner_sid, end));
4408                 memcpy(&out->group, group_sid,
4409                        posix_info_sid_size(group_sid, end));
4410         }
4411         return total_len;
4412 }
4413
4414 static int posix_info_extra_size(const void *beg, const void *end)
4415 {
4416         int len = posix_info_parse(beg, end, NULL);
4417
4418         if (len < 0)
4419                 return -1;
4420         return len - sizeof(struct smb2_posix_info);
4421 }
4422
4423 static unsigned int
4424 num_entries(int infotype, char *bufstart, char *end_of_buf, char **lastentry,
4425             size_t size)
4426 {
4427         int len;
4428         unsigned int entrycount = 0;
4429         unsigned int next_offset = 0;
4430         char *entryptr;
4431         FILE_DIRECTORY_INFO *dir_info;
4432
4433         if (bufstart == NULL)
4434                 return 0;
4435
4436         entryptr = bufstart;
4437
4438         while (1) {
4439                 if (entryptr + next_offset < entryptr ||
4440                     entryptr + next_offset > end_of_buf ||
4441                     entryptr + next_offset + size > end_of_buf) {
4442                         cifs_dbg(VFS, "malformed search entry would overflow\n");
4443                         break;
4444                 }
4445
4446                 entryptr = entryptr + next_offset;
4447                 dir_info = (FILE_DIRECTORY_INFO *)entryptr;
4448
4449                 if (infotype == SMB_FIND_FILE_POSIX_INFO)
4450                         len = posix_info_extra_size(entryptr, end_of_buf);
4451                 else
4452                         len = le32_to_cpu(dir_info->FileNameLength);
4453
4454                 if (len < 0 ||
4455                     entryptr + len < entryptr ||
4456                     entryptr + len > end_of_buf ||
4457                     entryptr + len + size > end_of_buf) {
4458                         cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
4459                                  end_of_buf);
4460                         break;
4461                 }
4462
4463                 *lastentry = entryptr;
4464                 entrycount++;
4465
4466                 next_offset = le32_to_cpu(dir_info->NextEntryOffset);
4467                 if (!next_offset)
4468                         break;
4469         }
4470
4471         return entrycount;
4472 }
4473
4474 /*
4475  * Readdir/FindFirst
4476  */
4477 int SMB2_query_directory_init(const unsigned int xid,
4478                               struct cifs_tcon *tcon, struct smb_rqst *rqst,
4479                               u64 persistent_fid, u64 volatile_fid,
4480                               int index, int info_level)
4481 {
4482         struct TCP_Server_Info *server = tcon->ses->server;
4483         struct smb2_query_directory_req *req;
4484         unsigned char *bufptr;
4485         __le16 asteriks = cpu_to_le16('*');
4486         unsigned int output_size = CIFSMaxBufSize -
4487                 MAX_SMB2_CREATE_RESPONSE_SIZE -
4488                 MAX_SMB2_CLOSE_RESPONSE_SIZE;
4489         unsigned int total_len;
4490         struct kvec *iov = rqst->rq_iov;
4491         int len, rc;
4492
4493         rc = smb2_plain_req_init(SMB2_QUERY_DIRECTORY, tcon, (void **) &req,
4494                              &total_len);
4495         if (rc)
4496                 return rc;
4497
4498         switch (info_level) {
4499         case SMB_FIND_FILE_DIRECTORY_INFO:
4500                 req->FileInformationClass = FILE_DIRECTORY_INFORMATION;
4501                 break;
4502         case SMB_FIND_FILE_ID_FULL_DIR_INFO:
4503                 req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION;
4504                 break;
4505         case SMB_FIND_FILE_POSIX_INFO:
4506                 req->FileInformationClass = SMB_FIND_FILE_POSIX_INFO;
4507                 break;
4508         default:
4509                 cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
4510                         info_level);
4511                 return -EINVAL;
4512         }
4513
4514         req->FileIndex = cpu_to_le32(index);
4515         req->PersistentFileId = persistent_fid;
4516         req->VolatileFileId = volatile_fid;
4517
4518         len = 0x2;
4519         bufptr = req->Buffer;
4520         memcpy(bufptr, &asteriks, len);
4521
4522         req->FileNameOffset =
4523                 cpu_to_le16(sizeof(struct smb2_query_directory_req) - 1);
4524         req->FileNameLength = cpu_to_le16(len);
4525         /*
4526          * BB could be 30 bytes or so longer if we used SMB2 specific
4527          * buffer lengths, but this is safe and close enough.
4528          */
4529         output_size = min_t(unsigned int, output_size, server->maxBuf);
4530         output_size = min_t(unsigned int, output_size, 2 << 15);
4531         req->OutputBufferLength = cpu_to_le32(output_size);
4532
4533         iov[0].iov_base = (char *)req;
4534         /* 1 for Buffer */
4535         iov[0].iov_len = total_len - 1;
4536
4537         iov[1].iov_base = (char *)(req->Buffer);
4538         iov[1].iov_len = len;
4539
4540         trace_smb3_query_dir_enter(xid, persistent_fid, tcon->tid,
4541                         tcon->ses->Suid, index, output_size);
4542
4543         return 0;
4544 }
4545
4546 void SMB2_query_directory_free(struct smb_rqst *rqst)
4547 {
4548         if (rqst && rqst->rq_iov) {
4549                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
4550         }
4551 }
4552
4553 int
4554 smb2_parse_query_directory(struct cifs_tcon *tcon,
4555                            struct kvec *rsp_iov,
4556                            int resp_buftype,
4557                            struct cifs_search_info *srch_inf)
4558 {
4559         struct smb2_query_directory_rsp *rsp;
4560         size_t info_buf_size;
4561         char *end_of_smb;
4562         int rc;
4563
4564         rsp = (struct smb2_query_directory_rsp *)rsp_iov->iov_base;
4565
4566         switch (srch_inf->info_level) {
4567         case SMB_FIND_FILE_DIRECTORY_INFO:
4568                 info_buf_size = sizeof(FILE_DIRECTORY_INFO) - 1;
4569                 break;
4570         case SMB_FIND_FILE_ID_FULL_DIR_INFO:
4571                 info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO) - 1;
4572                 break;
4573         case SMB_FIND_FILE_POSIX_INFO:
4574                 /* note that posix payload are variable size */
4575                 info_buf_size = sizeof(struct smb2_posix_info);
4576                 break;
4577         default:
4578                 cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
4579                          srch_inf->info_level);
4580                 return -EINVAL;
4581         }
4582
4583         rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
4584                                le32_to_cpu(rsp->OutputBufferLength), rsp_iov,
4585                                info_buf_size);
4586         if (rc) {
4587                 cifs_tcon_dbg(VFS, "bad info payload");
4588                 return rc;
4589         }
4590
4591         srch_inf->unicode = true;
4592
4593         if (srch_inf->ntwrk_buf_start) {
4594                 if (srch_inf->smallBuf)
4595                         cifs_small_buf_release(srch_inf->ntwrk_buf_start);
4596                 else
4597                         cifs_buf_release(srch_inf->ntwrk_buf_start);
4598         }
4599         srch_inf->ntwrk_buf_start = (char *)rsp;
4600         srch_inf->srch_entries_start = srch_inf->last_entry =
4601                 (char *)rsp + le16_to_cpu(rsp->OutputBufferOffset);
4602         end_of_smb = rsp_iov->iov_len + (char *)rsp;
4603
4604         srch_inf->entries_in_buffer = num_entries(
4605                 srch_inf->info_level,
4606                 srch_inf->srch_entries_start,
4607                 end_of_smb,
4608                 &srch_inf->last_entry,
4609                 info_buf_size);
4610
4611         srch_inf->index_of_last_entry += srch_inf->entries_in_buffer;
4612         cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n",
4613                  srch_inf->entries_in_buffer, srch_inf->index_of_last_entry,
4614                  srch_inf->srch_entries_start, srch_inf->last_entry);
4615         if (resp_buftype == CIFS_LARGE_BUFFER)
4616                 srch_inf->smallBuf = false;
4617         else if (resp_buftype == CIFS_SMALL_BUFFER)
4618                 srch_inf->smallBuf = true;
4619         else
4620                 cifs_tcon_dbg(VFS, "illegal search buffer type\n");
4621
4622         return 0;
4623 }
4624
4625 int
4626 SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon,
4627                      u64 persistent_fid, u64 volatile_fid, int index,
4628                      struct cifs_search_info *srch_inf)
4629 {
4630         struct smb_rqst rqst;
4631         struct kvec iov[SMB2_QUERY_DIRECTORY_IOV_SIZE];
4632         struct smb2_query_directory_rsp *rsp = NULL;
4633         int resp_buftype = CIFS_NO_BUFFER;
4634         struct kvec rsp_iov;
4635         int rc = 0;
4636         struct cifs_ses *ses = tcon->ses;
4637         int flags = 0;
4638
4639         if (!ses || !(ses->server))
4640                 return -EIO;
4641
4642         if (smb3_encryption_required(tcon))
4643                 flags |= CIFS_TRANSFORM_REQ;
4644
4645         memset(&rqst, 0, sizeof(struct smb_rqst));
4646         memset(&iov, 0, sizeof(iov));
4647         rqst.rq_iov = iov;
4648         rqst.rq_nvec = SMB2_QUERY_DIRECTORY_IOV_SIZE;
4649
4650         rc = SMB2_query_directory_init(xid, tcon, &rqst, persistent_fid,
4651                                        volatile_fid, index,
4652                                        srch_inf->info_level);
4653         if (rc)
4654                 goto qdir_exit;
4655
4656         rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
4657         rsp = (struct smb2_query_directory_rsp *)rsp_iov.iov_base;
4658
4659         if (rc) {
4660                 if (rc == -ENODATA &&
4661                     rsp->sync_hdr.Status == STATUS_NO_MORE_FILES) {
4662                         trace_smb3_query_dir_done(xid, persistent_fid,
4663                                 tcon->tid, tcon->ses->Suid, index, 0);
4664                         srch_inf->endOfSearch = true;
4665                         rc = 0;
4666                 } else {
4667                         trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
4668                                 tcon->ses->Suid, index, 0, rc);
4669                         cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE);
4670                 }
4671                 goto qdir_exit;
4672         }
4673
4674         rc = smb2_parse_query_directory(tcon, &rsp_iov, resp_buftype,
4675                                         srch_inf);
4676         if (rc) {
4677                 trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
4678                         tcon->ses->Suid, index, 0, rc);
4679                 goto qdir_exit;
4680         }
4681         resp_buftype = CIFS_NO_BUFFER;
4682
4683         trace_smb3_query_dir_done(xid, persistent_fid, tcon->tid,
4684                         tcon->ses->Suid, index, srch_inf->entries_in_buffer);
4685
4686 qdir_exit:
4687         SMB2_query_directory_free(&rqst);
4688         free_rsp_buf(resp_buftype, rsp);
4689         return rc;
4690 }
4691
4692 int
4693 SMB2_set_info_init(struct cifs_tcon *tcon, struct smb_rqst *rqst,
4694                u64 persistent_fid, u64 volatile_fid, u32 pid, u8 info_class,
4695                u8 info_type, u32 additional_info,
4696                 void **data, unsigned int *size)
4697 {
4698         struct smb2_set_info_req *req;
4699         struct kvec *iov = rqst->rq_iov;
4700         unsigned int i, total_len;
4701         int rc;
4702
4703         rc = smb2_plain_req_init(SMB2_SET_INFO, tcon, (void **) &req, &total_len);
4704         if (rc)
4705                 return rc;
4706
4707         req->sync_hdr.ProcessId = cpu_to_le32(pid);
4708         req->InfoType = info_type;
4709         req->FileInfoClass = info_class;
4710         req->PersistentFileId = persistent_fid;
4711         req->VolatileFileId = volatile_fid;
4712         req->AdditionalInformation = cpu_to_le32(additional_info);
4713
4714         req->BufferOffset =
4715                         cpu_to_le16(sizeof(struct smb2_set_info_req) - 1);
4716         req->BufferLength = cpu_to_le32(*size);
4717
4718         memcpy(req->Buffer, *data, *size);
4719         total_len += *size;
4720
4721         iov[0].iov_base = (char *)req;
4722         /* 1 for Buffer */
4723         iov[0].iov_len = total_len - 1;
4724
4725         for (i = 1; i < rqst->rq_nvec; i++) {
4726                 le32_add_cpu(&req->BufferLength, size[i]);
4727                 iov[i].iov_base = (char *)data[i];
4728                 iov[i].iov_len = size[i];
4729         }
4730
4731         return 0;
4732 }
4733
4734 void
4735 SMB2_set_info_free(struct smb_rqst *rqst)
4736 {
4737         if (rqst && rqst->rq_iov)
4738                 cifs_buf_release(rqst->rq_iov[0].iov_base); /* request */
4739 }
4740
4741 static int
4742 send_set_info(const unsigned int xid, struct cifs_tcon *tcon,
4743                u64 persistent_fid, u64 volatile_fid, u32 pid, u8 info_class,
4744                u8 info_type, u32 additional_info, unsigned int num,
4745                 void **data, unsigned int *size)
4746 {
4747         struct smb_rqst rqst;
4748         struct smb2_set_info_rsp *rsp = NULL;
4749         struct kvec *iov;
4750         struct kvec rsp_iov;
4751         int rc = 0;
4752         int resp_buftype;
4753         struct cifs_ses *ses = tcon->ses;
4754         int flags = 0;
4755
4756         if (!ses || !(ses->server))
4757                 return -EIO;
4758
4759         if (!num)
4760                 return -EINVAL;
4761
4762         if (smb3_encryption_required(tcon))
4763                 flags |= CIFS_TRANSFORM_REQ;
4764
4765         iov = kmalloc_array(num, sizeof(struct kvec), GFP_KERNEL);
4766         if (!iov)
4767                 return -ENOMEM;
4768
4769         memset(&rqst, 0, sizeof(struct smb_rqst));
4770         rqst.rq_iov = iov;
4771         rqst.rq_nvec = num;
4772
4773         rc = SMB2_set_info_init(tcon, &rqst, persistent_fid, volatile_fid, pid,
4774                                 info_class, info_type, additional_info,
4775                                 data, size);
4776         if (rc) {
4777                 kfree(iov);
4778                 return rc;
4779         }
4780
4781
4782         rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags,
4783                             &rsp_iov);
4784         SMB2_set_info_free(&rqst);
4785         rsp = (struct smb2_set_info_rsp *)rsp_iov.iov_base;
4786
4787         if (rc != 0) {
4788                 cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE);
4789                 trace_smb3_set_info_err(xid, persistent_fid, tcon->tid,
4790                                 ses->Suid, info_class, (__u32)info_type, rc);
4791         }
4792
4793         free_rsp_buf(resp_buftype, rsp);
4794         kfree(iov);
4795         return rc;
4796 }
4797
4798 int
4799 SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
4800              u64 volatile_fid, u32 pid, __le64 *eof)
4801 {
4802         struct smb2_file_eof_info info;
4803         void *data;
4804         unsigned int size;
4805
4806         info.EndOfFile = *eof;
4807
4808         data = &info;
4809         size = sizeof(struct smb2_file_eof_info);
4810
4811         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
4812                         pid, FILE_END_OF_FILE_INFORMATION, SMB2_O_INFO_FILE,
4813                         0, 1, &data, &size);
4814 }
4815
4816 int
4817 SMB2_set_acl(const unsigned int xid, struct cifs_tcon *tcon,
4818                 u64 persistent_fid, u64 volatile_fid,
4819                 struct cifs_ntsd *pnntsd, int pacllen, int aclflag)
4820 {
4821         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
4822                         current->tgid, 0, SMB2_O_INFO_SECURITY, aclflag,
4823                         1, (void **)&pnntsd, &pacllen);
4824 }
4825
4826 int
4827 SMB2_set_ea(const unsigned int xid, struct cifs_tcon *tcon,
4828             u64 persistent_fid, u64 volatile_fid,
4829             struct smb2_file_full_ea_info *buf, int len)
4830 {
4831         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
4832                 current->tgid, FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE,
4833                 0, 1, (void **)&buf, &len);
4834 }
4835
4836 int
4837 SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon,
4838                   const u64 persistent_fid, const u64 volatile_fid,
4839                   __u8 oplock_level)
4840 {
4841         struct smb_rqst rqst;
4842         int rc;
4843         struct smb2_oplock_break *req = NULL;
4844         struct cifs_ses *ses = tcon->ses;
4845         int flags = CIFS_OBREAK_OP;
4846         unsigned int total_len;
4847         struct kvec iov[1];
4848         struct kvec rsp_iov;
4849         int resp_buf_type;
4850
4851         cifs_dbg(FYI, "SMB2_oplock_break\n");
4852         rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req,
4853                              &total_len);
4854         if (rc)
4855                 return rc;
4856
4857         if (smb3_encryption_required(tcon))
4858                 flags |= CIFS_TRANSFORM_REQ;
4859
4860         req->VolatileFid = volatile_fid;
4861         req->PersistentFid = persistent_fid;
4862         req->OplockLevel = oplock_level;
4863         req->sync_hdr.CreditRequest = cpu_to_le16(1);
4864
4865         flags |= CIFS_NO_RSP_BUF;
4866
4867         iov[0].iov_base = (char *)req;
4868         iov[0].iov_len = total_len;
4869
4870         memset(&rqst, 0, sizeof(struct smb_rqst));
4871         rqst.rq_iov = iov;
4872         rqst.rq_nvec = 1;
4873
4874         rc = cifs_send_recv(xid, ses, &rqst, &resp_buf_type, flags, &rsp_iov);
4875         cifs_small_buf_release(req);
4876
4877         if (rc) {
4878                 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
4879                 cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc);
4880         }
4881
4882         return rc;
4883 }
4884
4885 void
4886 smb2_copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf,
4887                              struct kstatfs *kst)
4888 {
4889         kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) *
4890                           le32_to_cpu(pfs_inf->SectorsPerAllocationUnit);
4891         kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits);
4892         kst->f_bfree  = kst->f_bavail =
4893                         le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits);
4894         return;
4895 }
4896
4897 static void
4898 copy_posix_fs_info_to_kstatfs(FILE_SYSTEM_POSIX_INFO *response_data,
4899                         struct kstatfs *kst)
4900 {
4901         kst->f_bsize = le32_to_cpu(response_data->BlockSize);
4902         kst->f_blocks = le64_to_cpu(response_data->TotalBlocks);
4903         kst->f_bfree =  le64_to_cpu(response_data->BlocksAvail);
4904         if (response_data->UserBlocksAvail == cpu_to_le64(-1))
4905                 kst->f_bavail = kst->f_bfree;
4906         else
4907                 kst->f_bavail = le64_to_cpu(response_data->UserBlocksAvail);
4908         if (response_data->TotalFileNodes != cpu_to_le64(-1))
4909                 kst->f_files = le64_to_cpu(response_data->TotalFileNodes);
4910         if (response_data->FreeFileNodes != cpu_to_le64(-1))
4911                 kst->f_ffree = le64_to_cpu(response_data->FreeFileNodes);
4912
4913         return;
4914 }
4915
4916 static int
4917 build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon, int level,
4918                    int outbuf_len, u64 persistent_fid, u64 volatile_fid)
4919 {
4920         int rc;
4921         struct smb2_query_info_req *req;
4922         unsigned int total_len;
4923
4924         cifs_dbg(FYI, "Query FSInfo level %d\n", level);
4925
4926         if ((tcon->ses == NULL) || (tcon->ses->server == NULL))
4927                 return -EIO;
4928
4929         rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, (void **) &req,
4930                              &total_len);
4931         if (rc)
4932                 return rc;
4933
4934         req->InfoType = SMB2_O_INFO_FILESYSTEM;
4935         req->FileInfoClass = level;
4936         req->PersistentFileId = persistent_fid;
4937         req->VolatileFileId = volatile_fid;
4938         /* 1 for pad */
4939         req->InputBufferOffset =
4940                         cpu_to_le16(sizeof(struct smb2_query_info_req) - 1);
4941         req->OutputBufferLength = cpu_to_le32(
4942                 outbuf_len + sizeof(struct smb2_query_info_rsp) - 1);
4943
4944         iov->iov_base = (char *)req;
4945         iov->iov_len = total_len;
4946         return 0;
4947 }
4948
4949 int
4950 SMB311_posix_qfs_info(const unsigned int xid, struct cifs_tcon *tcon,
4951               u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
4952 {
4953         struct smb_rqst rqst;
4954         struct smb2_query_info_rsp *rsp = NULL;
4955         struct kvec iov;
4956         struct kvec rsp_iov;
4957         int rc = 0;
4958         int resp_buftype;
4959         struct cifs_ses *ses = tcon->ses;
4960         FILE_SYSTEM_POSIX_INFO *info = NULL;
4961         int flags = 0;
4962
4963         rc = build_qfs_info_req(&iov, tcon, FS_POSIX_INFORMATION,
4964                                 sizeof(FILE_SYSTEM_POSIX_INFO),
4965                                 persistent_fid, volatile_fid);
4966         if (rc)
4967                 return rc;
4968
4969         if (smb3_encryption_required(tcon))
4970                 flags |= CIFS_TRANSFORM_REQ;
4971
4972         memset(&rqst, 0, sizeof(struct smb_rqst));
4973         rqst.rq_iov = &iov;
4974         rqst.rq_nvec = 1;
4975
4976         rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
4977         cifs_small_buf_release(iov.iov_base);
4978         if (rc) {
4979                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
4980                 goto posix_qfsinf_exit;
4981         }
4982         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
4983
4984         info = (FILE_SYSTEM_POSIX_INFO *)(
4985                 le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
4986         rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
4987                                le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
4988                                sizeof(FILE_SYSTEM_POSIX_INFO));
4989         if (!rc)
4990                 copy_posix_fs_info_to_kstatfs(info, fsdata);
4991
4992 posix_qfsinf_exit:
4993         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4994         return rc;
4995 }
4996
4997 int
4998 SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon,
4999               u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
5000 {
5001         struct smb_rqst rqst;
5002         struct smb2_query_info_rsp *rsp = NULL;
5003         struct kvec iov;
5004         struct kvec rsp_iov;
5005         int rc = 0;
5006         int resp_buftype;
5007         struct cifs_ses *ses = tcon->ses;
5008         struct smb2_fs_full_size_info *info = NULL;
5009         int flags = 0;
5010
5011         rc = build_qfs_info_req(&iov, tcon, FS_FULL_SIZE_INFORMATION,
5012                                 sizeof(struct smb2_fs_full_size_info),
5013                                 persistent_fid, volatile_fid);
5014         if (rc)
5015                 return rc;
5016
5017         if (smb3_encryption_required(tcon))
5018                 flags |= CIFS_TRANSFORM_REQ;
5019
5020         memset(&rqst, 0, sizeof(struct smb_rqst));
5021         rqst.rq_iov = &iov;
5022         rqst.rq_nvec = 1;
5023
5024         rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
5025         cifs_small_buf_release(iov.iov_base);
5026         if (rc) {
5027                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5028                 goto qfsinf_exit;
5029         }
5030         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5031
5032         info = (struct smb2_fs_full_size_info *)(
5033                 le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
5034         rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5035                                le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
5036                                sizeof(struct smb2_fs_full_size_info));
5037         if (!rc)
5038                 smb2_copy_fs_info_to_kstatfs(info, fsdata);
5039
5040 qfsinf_exit:
5041         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5042         return rc;
5043 }
5044
5045 int
5046 SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon,
5047               u64 persistent_fid, u64 volatile_fid, int level)
5048 {
5049         struct smb_rqst rqst;
5050         struct smb2_query_info_rsp *rsp = NULL;
5051         struct kvec iov;
5052         struct kvec rsp_iov;
5053         int rc = 0;
5054         int resp_buftype, max_len, min_len;
5055         struct cifs_ses *ses = tcon->ses;
5056         unsigned int rsp_len, offset;
5057         int flags = 0;
5058
5059         if (level == FS_DEVICE_INFORMATION) {
5060                 max_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
5061                 min_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
5062         } else if (level == FS_ATTRIBUTE_INFORMATION) {
5063                 max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO);
5064                 min_len = MIN_FS_ATTR_INFO_SIZE;
5065         } else if (level == FS_SECTOR_SIZE_INFORMATION) {
5066                 max_len = sizeof(struct smb3_fs_ss_info);
5067                 min_len = sizeof(struct smb3_fs_ss_info);
5068         } else if (level == FS_VOLUME_INFORMATION) {
5069                 max_len = sizeof(struct smb3_fs_vol_info) + MAX_VOL_LABEL_LEN;
5070                 min_len = sizeof(struct smb3_fs_vol_info);
5071         } else {
5072                 cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level);
5073                 return -EINVAL;
5074         }
5075
5076         rc = build_qfs_info_req(&iov, tcon, level, max_len,
5077                                 persistent_fid, volatile_fid);
5078         if (rc)
5079                 return rc;
5080
5081         if (smb3_encryption_required(tcon))
5082                 flags |= CIFS_TRANSFORM_REQ;
5083
5084         memset(&rqst, 0, sizeof(struct smb_rqst));
5085         rqst.rq_iov = &iov;
5086         rqst.rq_nvec = 1;
5087
5088         rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
5089         cifs_small_buf_release(iov.iov_base);
5090         if (rc) {
5091                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5092                 goto qfsattr_exit;
5093         }
5094         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5095
5096         rsp_len = le32_to_cpu(rsp->OutputBufferLength);
5097         offset = le16_to_cpu(rsp->OutputBufferOffset);
5098         rc = smb2_validate_iov(offset, rsp_len, &rsp_iov, min_len);
5099         if (rc)
5100                 goto qfsattr_exit;
5101
5102         if (level == FS_ATTRIBUTE_INFORMATION)
5103                 memcpy(&tcon->fsAttrInfo, offset
5104                         + (char *)rsp, min_t(unsigned int,
5105                         rsp_len, max_len));
5106         else if (level == FS_DEVICE_INFORMATION)
5107                 memcpy(&tcon->fsDevInfo, offset
5108                         + (char *)rsp, sizeof(FILE_SYSTEM_DEVICE_INFO));
5109         else if (level == FS_SECTOR_SIZE_INFORMATION) {
5110                 struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *)
5111                         (offset + (char *)rsp);
5112                 tcon->ss_flags = le32_to_cpu(ss_info->Flags);
5113                 tcon->perf_sector_size =
5114                         le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf);
5115         } else if (level == FS_VOLUME_INFORMATION) {
5116                 struct smb3_fs_vol_info *vol_info = (struct smb3_fs_vol_info *)
5117                         (offset + (char *)rsp);
5118                 tcon->vol_serial_number = vol_info->VolumeSerialNumber;
5119                 tcon->vol_create_time = vol_info->VolumeCreationTime;
5120         }
5121
5122 qfsattr_exit:
5123         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5124         return rc;
5125 }
5126
5127 int
5128 smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon,
5129            const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
5130            const __u32 num_lock, struct smb2_lock_element *buf)
5131 {
5132         struct smb_rqst rqst;
5133         int rc = 0;
5134         struct smb2_lock_req *req = NULL;
5135         struct kvec iov[2];
5136         struct kvec rsp_iov;
5137         int resp_buf_type;
5138         unsigned int count;
5139         int flags = CIFS_NO_RSP_BUF;
5140         unsigned int total_len;
5141
5142         cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock);
5143
5144         rc = smb2_plain_req_init(SMB2_LOCK, tcon, (void **) &req, &total_len);
5145         if (rc)
5146                 return rc;
5147
5148         if (smb3_encryption_required(tcon))
5149                 flags |= CIFS_TRANSFORM_REQ;
5150
5151         req->sync_hdr.ProcessId = cpu_to_le32(pid);
5152         req->LockCount = cpu_to_le16(num_lock);
5153
5154         req->PersistentFileId = persist_fid;
5155         req->VolatileFileId = volatile_fid;
5156
5157         count = num_lock * sizeof(struct smb2_lock_element);
5158
5159         iov[0].iov_base = (char *)req;
5160         iov[0].iov_len = total_len - sizeof(struct smb2_lock_element);
5161         iov[1].iov_base = (char *)buf;
5162         iov[1].iov_len = count;
5163
5164         cifs_stats_inc(&tcon->stats.cifs_stats.num_locks);
5165
5166         memset(&rqst, 0, sizeof(struct smb_rqst));
5167         rqst.rq_iov = iov;
5168         rqst.rq_nvec = 2;
5169
5170         rc = cifs_send_recv(xid, tcon->ses, &rqst, &resp_buf_type, flags,
5171                             &rsp_iov);
5172         cifs_small_buf_release(req);
5173         if (rc) {
5174                 cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc);
5175                 cifs_stats_fail_inc(tcon, SMB2_LOCK_HE);
5176                 trace_smb3_lock_err(xid, persist_fid, tcon->tid,
5177                                     tcon->ses->Suid, rc);
5178         }
5179
5180         return rc;
5181 }
5182
5183 int
5184 SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon,
5185           const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
5186           const __u64 length, const __u64 offset, const __u32 lock_flags,
5187           const bool wait)
5188 {
5189         struct smb2_lock_element lock;
5190
5191         lock.Offset = cpu_to_le64(offset);
5192         lock.Length = cpu_to_le64(length);
5193         lock.Flags = cpu_to_le32(lock_flags);
5194         if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK)
5195                 lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY);
5196
5197         return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock);
5198 }
5199
5200 int
5201 SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon,
5202                  __u8 *lease_key, const __le32 lease_state)
5203 {
5204         struct smb_rqst rqst;
5205         int rc;
5206         struct smb2_lease_ack *req = NULL;
5207         struct cifs_ses *ses = tcon->ses;
5208         int flags = CIFS_OBREAK_OP;
5209         unsigned int total_len;
5210         struct kvec iov[1];
5211         struct kvec rsp_iov;
5212         int resp_buf_type;
5213         __u64 *please_key_high;
5214         __u64 *please_key_low;
5215
5216         cifs_dbg(FYI, "SMB2_lease_break\n");
5217         rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req,
5218                              &total_len);
5219         if (rc)
5220                 return rc;
5221
5222         if (smb3_encryption_required(tcon))
5223                 flags |= CIFS_TRANSFORM_REQ;
5224
5225         req->sync_hdr.CreditRequest = cpu_to_le16(1);
5226         req->StructureSize = cpu_to_le16(36);
5227         total_len += 12;
5228
5229         memcpy(req->LeaseKey, lease_key, 16);
5230         req->LeaseState = lease_state;
5231
5232         flags |= CIFS_NO_RSP_BUF;
5233
5234         iov[0].iov_base = (char *)req;
5235         iov[0].iov_len = total_len;
5236
5237         memset(&rqst, 0, sizeof(struct smb_rqst));
5238         rqst.rq_iov = iov;
5239         rqst.rq_nvec = 1;
5240
5241         rc = cifs_send_recv(xid, ses, &rqst, &resp_buf_type, flags, &rsp_iov);
5242         cifs_small_buf_release(req);
5243
5244         please_key_low = (__u64 *)lease_key;
5245         please_key_high = (__u64 *)(lease_key+8);
5246         if (rc) {
5247                 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
5248                 trace_smb3_lease_err(le32_to_cpu(lease_state), tcon->tid,
5249                         ses->Suid, *please_key_low, *please_key_high, rc);
5250                 cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc);
5251         } else
5252                 trace_smb3_lease_done(le32_to_cpu(lease_state), tcon->tid,
5253                         ses->Suid, *please_key_low, *please_key_high);
5254
5255         return rc;
5256 }