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