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