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