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