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