Merge branch 'kvm-master' into kvm-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         __u8 *ptr, *aclptr;
2276         unsigned int acelen, acl_size, ace_count;
2277         unsigned int owner_offset = 0;
2278         unsigned int group_offset = 0;
2279         struct smb3_acl acl;
2280
2281         *len = roundup(sizeof(struct crt_sd_ctxt) + (sizeof(struct cifs_ace) * 4), 8);
2282
2283         if (set_owner) {
2284                 /* sizeof(struct owner_group_sids) is already multiple of 8 so no need to round */
2285                 *len += sizeof(struct owner_group_sids);
2286         }
2287
2288         buf = kzalloc(*len, GFP_KERNEL);
2289         if (buf == NULL)
2290                 return buf;
2291
2292         ptr = (__u8 *)&buf[1];
2293         if (set_owner) {
2294                 /* offset fields are from beginning of security descriptor not of create context */
2295                 owner_offset = ptr - (__u8 *)&buf->sd;
2296                 buf->sd.OffsetOwner = cpu_to_le32(owner_offset);
2297                 group_offset = owner_offset + offsetof(struct owner_group_sids, group);
2298                 buf->sd.OffsetGroup = cpu_to_le32(group_offset);
2299
2300                 setup_owner_group_sids(ptr);
2301                 ptr += sizeof(struct owner_group_sids);
2302         } else {
2303                 buf->sd.OffsetOwner = 0;
2304                 buf->sd.OffsetGroup = 0;
2305         }
2306
2307         buf->ccontext.DataOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, sd));
2308         buf->ccontext.NameOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, Name));
2309         buf->ccontext.NameLength = cpu_to_le16(4);
2310         /* SMB2_CREATE_SD_BUFFER_TOKEN is "SecD" */
2311         buf->Name[0] = 'S';
2312         buf->Name[1] = 'e';
2313         buf->Name[2] = 'c';
2314         buf->Name[3] = 'D';
2315         buf->sd.Revision = 1;  /* Must be one see MS-DTYP 2.4.6 */
2316
2317         /*
2318          * ACL is "self relative" ie ACL is stored in contiguous block of memory
2319          * and "DP" ie the DACL is present
2320          */
2321         buf->sd.Control = cpu_to_le16(ACL_CONTROL_SR | ACL_CONTROL_DP);
2322
2323         /* offset owner, group and Sbz1 and SACL are all zero */
2324         buf->sd.OffsetDacl = cpu_to_le32(ptr - (__u8 *)&buf->sd);
2325         /* Ship the ACL for now. we will copy it into buf later. */
2326         aclptr = ptr;
2327         ptr += sizeof(struct cifs_acl);
2328
2329         /* create one ACE to hold the mode embedded in reserved special SID */
2330         acelen = setup_special_mode_ACE((struct cifs_ace *)ptr, (__u64)mode);
2331         ptr += acelen;
2332         acl_size = acelen + sizeof(struct smb3_acl);
2333         ace_count = 1;
2334
2335         if (set_owner) {
2336                 /* we do not need to reallocate buffer to add the two more ACEs. plenty of space */
2337                 acelen = setup_special_user_owner_ACE((struct cifs_ace *)ptr);
2338                 ptr += acelen;
2339                 acl_size += acelen;
2340                 ace_count += 1;
2341         }
2342
2343         /* and one more ACE to allow access for authenticated users */
2344         acelen = setup_authusers_ACE((struct cifs_ace *)ptr);
2345         ptr += acelen;
2346         acl_size += acelen;
2347         ace_count += 1;
2348
2349         acl.AclRevision = ACL_REVISION; /* See 2.4.4.1 of MS-DTYP */
2350         acl.AclSize = cpu_to_le16(acl_size);
2351         acl.AceCount = cpu_to_le16(ace_count);
2352         memcpy(aclptr, &acl, sizeof(struct cifs_acl));
2353
2354         buf->ccontext.DataLength = cpu_to_le32(ptr - (__u8 *)&buf->sd);
2355         *len = ptr - (__u8 *)buf;
2356
2357         return buf;
2358 }
2359
2360 static int
2361 add_sd_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode, bool set_owner)
2362 {
2363         struct smb2_create_req *req = iov[0].iov_base;
2364         unsigned int num = *num_iovec;
2365         unsigned int len = 0;
2366
2367         iov[num].iov_base = create_sd_buf(mode, set_owner, &len);
2368         if (iov[num].iov_base == NULL)
2369                 return -ENOMEM;
2370         iov[num].iov_len = len;
2371         if (!req->CreateContextsOffset)
2372                 req->CreateContextsOffset = cpu_to_le32(
2373                                 sizeof(struct smb2_create_req) +
2374                                 iov[num - 1].iov_len);
2375         le32_add_cpu(&req->CreateContextsLength, len);
2376         *num_iovec = num + 1;
2377         return 0;
2378 }
2379
2380 static struct crt_query_id_ctxt *
2381 create_query_id_buf(void)
2382 {
2383         struct crt_query_id_ctxt *buf;
2384
2385         buf = kzalloc(sizeof(struct crt_query_id_ctxt), GFP_KERNEL);
2386         if (!buf)
2387                 return NULL;
2388
2389         buf->ccontext.DataOffset = cpu_to_le16(0);
2390         buf->ccontext.DataLength = cpu_to_le32(0);
2391         buf->ccontext.NameOffset = cpu_to_le16(offsetof
2392                                 (struct crt_query_id_ctxt, Name));
2393         buf->ccontext.NameLength = cpu_to_le16(4);
2394         /* SMB2_CREATE_QUERY_ON_DISK_ID is "QFid" */
2395         buf->Name[0] = 'Q';
2396         buf->Name[1] = 'F';
2397         buf->Name[2] = 'i';
2398         buf->Name[3] = 'd';
2399         return buf;
2400 }
2401
2402 /* See MS-SMB2 2.2.13.2.9 */
2403 static int
2404 add_query_id_context(struct kvec *iov, unsigned int *num_iovec)
2405 {
2406         struct smb2_create_req *req = iov[0].iov_base;
2407         unsigned int num = *num_iovec;
2408
2409         iov[num].iov_base = create_query_id_buf();
2410         if (iov[num].iov_base == NULL)
2411                 return -ENOMEM;
2412         iov[num].iov_len = sizeof(struct crt_query_id_ctxt);
2413         if (!req->CreateContextsOffset)
2414                 req->CreateContextsOffset = cpu_to_le32(
2415                                 sizeof(struct smb2_create_req) +
2416                                 iov[num - 1].iov_len);
2417         le32_add_cpu(&req->CreateContextsLength, sizeof(struct crt_query_id_ctxt));
2418         *num_iovec = num + 1;
2419         return 0;
2420 }
2421
2422 static int
2423 alloc_path_with_tree_prefix(__le16 **out_path, int *out_size, int *out_len,
2424                             const char *treename, const __le16 *path)
2425 {
2426         int treename_len, path_len;
2427         struct nls_table *cp;
2428         const __le16 sep[] = {cpu_to_le16('\\'), cpu_to_le16(0x0000)};
2429
2430         /*
2431          * skip leading "\\"
2432          */
2433         treename_len = strlen(treename);
2434         if (treename_len < 2 || !(treename[0] == '\\' && treename[1] == '\\'))
2435                 return -EINVAL;
2436
2437         treename += 2;
2438         treename_len -= 2;
2439
2440         path_len = UniStrnlen((wchar_t *)path, PATH_MAX);
2441
2442         /*
2443          * make room for one path separator between the treename and
2444          * path
2445          */
2446         *out_len = treename_len + 1 + path_len;
2447
2448         /*
2449          * final path needs to be null-terminated UTF16 with a
2450          * size aligned to 8
2451          */
2452
2453         *out_size = roundup((*out_len+1)*2, 8);
2454         *out_path = kzalloc(*out_size, GFP_KERNEL);
2455         if (!*out_path)
2456                 return -ENOMEM;
2457
2458         cp = load_nls_default();
2459         cifs_strtoUTF16(*out_path, treename, treename_len, cp);
2460         UniStrcat(*out_path, sep);
2461         UniStrcat(*out_path, path);
2462         unload_nls(cp);
2463
2464         return 0;
2465 }
2466
2467 int smb311_posix_mkdir(const unsigned int xid, struct inode *inode,
2468                                umode_t mode, struct cifs_tcon *tcon,
2469                                const char *full_path,
2470                                struct cifs_sb_info *cifs_sb)
2471 {
2472         struct smb_rqst rqst;
2473         struct smb2_create_req *req;
2474         struct smb2_create_rsp *rsp = NULL;
2475         struct cifs_ses *ses = tcon->ses;
2476         struct kvec iov[3]; /* make sure at least one for each open context */
2477         struct kvec rsp_iov = {NULL, 0};
2478         int resp_buftype;
2479         int uni_path_len;
2480         __le16 *copy_path = NULL;
2481         int copy_size;
2482         int rc = 0;
2483         unsigned int n_iov = 2;
2484         __u32 file_attributes = 0;
2485         char *pc_buf = NULL;
2486         int flags = 0;
2487         unsigned int total_len;
2488         __le16 *utf16_path = NULL;
2489         struct TCP_Server_Info *server = cifs_pick_channel(ses);
2490
2491         cifs_dbg(FYI, "mkdir\n");
2492
2493         /* resource #1: path allocation */
2494         utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
2495         if (!utf16_path)
2496                 return -ENOMEM;
2497
2498         if (!ses || !server) {
2499                 rc = -EIO;
2500                 goto err_free_path;
2501         }
2502
2503         /* resource #2: request */
2504         rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
2505                                  (void **) &req, &total_len);
2506         if (rc)
2507                 goto err_free_path;
2508
2509
2510         if (smb3_encryption_required(tcon))
2511                 flags |= CIFS_TRANSFORM_REQ;
2512
2513         req->ImpersonationLevel = IL_IMPERSONATION;
2514         req->DesiredAccess = cpu_to_le32(FILE_WRITE_ATTRIBUTES);
2515         /* File attributes ignored on open (used in create though) */
2516         req->FileAttributes = cpu_to_le32(file_attributes);
2517         req->ShareAccess = FILE_SHARE_ALL_LE;
2518         req->CreateDisposition = cpu_to_le32(FILE_CREATE);
2519         req->CreateOptions = cpu_to_le32(CREATE_NOT_FILE);
2520
2521         iov[0].iov_base = (char *)req;
2522         /* -1 since last byte is buf[0] which is sent below (path) */
2523         iov[0].iov_len = total_len - 1;
2524
2525         req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
2526
2527         /* [MS-SMB2] 2.2.13 NameOffset:
2528          * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
2529          * the SMB2 header, the file name includes a prefix that will
2530          * be processed during DFS name normalization as specified in
2531          * section 3.3.5.9. Otherwise, the file name is relative to
2532          * the share that is identified by the TreeId in the SMB2
2533          * header.
2534          */
2535         if (tcon->share_flags & SHI1005_FLAGS_DFS) {
2536                 int name_len;
2537
2538                 req->sync_hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
2539                 rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
2540                                                  &name_len,
2541                                                  tcon->treeName, utf16_path);
2542                 if (rc)
2543                         goto err_free_req;
2544
2545                 req->NameLength = cpu_to_le16(name_len * 2);
2546                 uni_path_len = copy_size;
2547                 /* free before overwriting resource */
2548                 kfree(utf16_path);
2549                 utf16_path = copy_path;
2550         } else {
2551                 uni_path_len = (2 * UniStrnlen((wchar_t *)utf16_path, PATH_MAX)) + 2;
2552                 /* MUST set path len (NameLength) to 0 opening root of share */
2553                 req->NameLength = cpu_to_le16(uni_path_len - 2);
2554                 if (uni_path_len % 8 != 0) {
2555                         copy_size = roundup(uni_path_len, 8);
2556                         copy_path = kzalloc(copy_size, GFP_KERNEL);
2557                         if (!copy_path) {
2558                                 rc = -ENOMEM;
2559                                 goto err_free_req;
2560                         }
2561                         memcpy((char *)copy_path, (const char *)utf16_path,
2562                                uni_path_len);
2563                         uni_path_len = copy_size;
2564                         /* free before overwriting resource */
2565                         kfree(utf16_path);
2566                         utf16_path = copy_path;
2567                 }
2568         }
2569
2570         iov[1].iov_len = uni_path_len;
2571         iov[1].iov_base = utf16_path;
2572         req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2573
2574         if (tcon->posix_extensions) {
2575                 /* resource #3: posix buf */
2576                 rc = add_posix_context(iov, &n_iov, mode);
2577                 if (rc)
2578                         goto err_free_req;
2579                 pc_buf = iov[n_iov-1].iov_base;
2580         }
2581
2582
2583         memset(&rqst, 0, sizeof(struct smb_rqst));
2584         rqst.rq_iov = iov;
2585         rqst.rq_nvec = n_iov;
2586
2587         /* no need to inc num_remote_opens because we close it just below */
2588         trace_smb3_posix_mkdir_enter(xid, tcon->tid, ses->Suid, CREATE_NOT_FILE,
2589                                     FILE_WRITE_ATTRIBUTES);
2590         /* resource #4: response buffer */
2591         rc = cifs_send_recv(xid, ses, server,
2592                             &rqst, &resp_buftype, flags, &rsp_iov);
2593         if (rc) {
2594                 cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
2595                 trace_smb3_posix_mkdir_err(xid, tcon->tid, ses->Suid,
2596                                            CREATE_NOT_FILE,
2597                                            FILE_WRITE_ATTRIBUTES, rc);
2598                 goto err_free_rsp_buf;
2599         }
2600
2601         rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
2602         trace_smb3_posix_mkdir_done(xid, rsp->PersistentFileId, tcon->tid,
2603                                     ses->Suid, CREATE_NOT_FILE,
2604                                     FILE_WRITE_ATTRIBUTES);
2605
2606         SMB2_close(xid, tcon, rsp->PersistentFileId, rsp->VolatileFileId);
2607
2608         /* Eventually save off posix specific response info and timestaps */
2609
2610 err_free_rsp_buf:
2611         free_rsp_buf(resp_buftype, rsp);
2612         kfree(pc_buf);
2613 err_free_req:
2614         cifs_small_buf_release(req);
2615 err_free_path:
2616         kfree(utf16_path);
2617         return rc;
2618 }
2619
2620 int
2621 SMB2_open_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
2622                struct smb_rqst *rqst, __u8 *oplock,
2623                struct cifs_open_parms *oparms, __le16 *path)
2624 {
2625         struct smb2_create_req *req;
2626         unsigned int n_iov = 2;
2627         __u32 file_attributes = 0;
2628         int copy_size;
2629         int uni_path_len;
2630         unsigned int total_len;
2631         struct kvec *iov = rqst->rq_iov;
2632         __le16 *copy_path;
2633         int rc;
2634
2635         rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
2636                                  (void **) &req, &total_len);
2637         if (rc)
2638                 return rc;
2639
2640         iov[0].iov_base = (char *)req;
2641         /* -1 since last byte is buf[0] which is sent below (path) */
2642         iov[0].iov_len = total_len - 1;
2643
2644         if (oparms->create_options & CREATE_OPTION_READONLY)
2645                 file_attributes |= ATTR_READONLY;
2646         if (oparms->create_options & CREATE_OPTION_SPECIAL)
2647                 file_attributes |= ATTR_SYSTEM;
2648
2649         req->ImpersonationLevel = IL_IMPERSONATION;
2650         req->DesiredAccess = cpu_to_le32(oparms->desired_access);
2651         /* File attributes ignored on open (used in create though) */
2652         req->FileAttributes = cpu_to_le32(file_attributes);
2653         req->ShareAccess = FILE_SHARE_ALL_LE;
2654
2655         req->CreateDisposition = cpu_to_le32(oparms->disposition);
2656         req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK);
2657         req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
2658
2659         /* [MS-SMB2] 2.2.13 NameOffset:
2660          * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
2661          * the SMB2 header, the file name includes a prefix that will
2662          * be processed during DFS name normalization as specified in
2663          * section 3.3.5.9. Otherwise, the file name is relative to
2664          * the share that is identified by the TreeId in the SMB2
2665          * header.
2666          */
2667         if (tcon->share_flags & SHI1005_FLAGS_DFS) {
2668                 int name_len;
2669
2670                 req->sync_hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
2671                 rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
2672                                                  &name_len,
2673                                                  tcon->treeName, path);
2674                 if (rc)
2675                         return rc;
2676                 req->NameLength = cpu_to_le16(name_len * 2);
2677                 uni_path_len = copy_size;
2678                 path = copy_path;
2679         } else {
2680                 uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
2681                 /* MUST set path len (NameLength) to 0 opening root of share */
2682                 req->NameLength = cpu_to_le16(uni_path_len - 2);
2683                 copy_size = uni_path_len;
2684                 if (copy_size % 8 != 0)
2685                         copy_size = roundup(copy_size, 8);
2686                 copy_path = kzalloc(copy_size, GFP_KERNEL);
2687                 if (!copy_path)
2688                         return -ENOMEM;
2689                 memcpy((char *)copy_path, (const char *)path,
2690                        uni_path_len);
2691                 uni_path_len = copy_size;
2692                 path = copy_path;
2693         }
2694
2695         iov[1].iov_len = uni_path_len;
2696         iov[1].iov_base = path;
2697
2698         if ((!server->oplocks) || (tcon->no_lease))
2699                 *oplock = SMB2_OPLOCK_LEVEL_NONE;
2700
2701         if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) ||
2702             *oplock == SMB2_OPLOCK_LEVEL_NONE)
2703                 req->RequestedOplockLevel = *oplock;
2704         else if (!(server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING) &&
2705                   (oparms->create_options & CREATE_NOT_FILE))
2706                 req->RequestedOplockLevel = *oplock; /* no srv lease support */
2707         else {
2708                 rc = add_lease_context(server, iov, &n_iov,
2709                                        oparms->fid->lease_key, oplock);
2710                 if (rc)
2711                         return rc;
2712         }
2713
2714         if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) {
2715                 /* need to set Next field of lease context if we request it */
2716                 if (server->capabilities & SMB2_GLOBAL_CAP_LEASING) {
2717                         struct create_context *ccontext =
2718                             (struct create_context *)iov[n_iov-1].iov_base;
2719                         ccontext->Next =
2720                                 cpu_to_le32(server->vals->create_lease_size);
2721                 }
2722
2723                 rc = add_durable_context(iov, &n_iov, oparms,
2724                                         tcon->use_persistent);
2725                 if (rc)
2726                         return rc;
2727         }
2728
2729         if (tcon->posix_extensions) {
2730                 if (n_iov > 2) {
2731                         struct create_context *ccontext =
2732                             (struct create_context *)iov[n_iov-1].iov_base;
2733                         ccontext->Next =
2734                                 cpu_to_le32(iov[n_iov-1].iov_len);
2735                 }
2736
2737                 rc = add_posix_context(iov, &n_iov, oparms->mode);
2738                 if (rc)
2739                         return rc;
2740         }
2741
2742         if (tcon->snapshot_time) {
2743                 cifs_dbg(FYI, "adding snapshot context\n");
2744                 if (n_iov > 2) {
2745                         struct create_context *ccontext =
2746                             (struct create_context *)iov[n_iov-1].iov_base;
2747                         ccontext->Next =
2748                                 cpu_to_le32(iov[n_iov-1].iov_len);
2749                 }
2750
2751                 rc = add_twarp_context(iov, &n_iov, tcon->snapshot_time);
2752                 if (rc)
2753                         return rc;
2754         }
2755
2756         if ((oparms->disposition != FILE_OPEN) && (oparms->cifs_sb)) {
2757                 bool set_mode;
2758                 bool set_owner;
2759
2760                 if ((oparms->cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MODE_FROM_SID) &&
2761                     (oparms->mode != ACL_NO_MODE))
2762                         set_mode = true;
2763                 else {
2764                         set_mode = false;
2765                         oparms->mode = ACL_NO_MODE;
2766                 }
2767
2768                 if (oparms->cifs_sb->mnt_cifs_flags & CIFS_MOUNT_UID_FROM_ACL)
2769                         set_owner = true;
2770                 else
2771                         set_owner = false;
2772
2773                 if (set_owner | set_mode) {
2774                         if (n_iov > 2) {
2775                                 struct create_context *ccontext =
2776                                     (struct create_context *)iov[n_iov-1].iov_base;
2777                                 ccontext->Next = cpu_to_le32(iov[n_iov-1].iov_len);
2778                         }
2779
2780                         cifs_dbg(FYI, "add sd with mode 0x%x\n", oparms->mode);
2781                         rc = add_sd_context(iov, &n_iov, oparms->mode, set_owner);
2782                         if (rc)
2783                                 return rc;
2784                 }
2785         }
2786
2787         if (n_iov > 2) {
2788                 struct create_context *ccontext =
2789                         (struct create_context *)iov[n_iov-1].iov_base;
2790                 ccontext->Next = cpu_to_le32(iov[n_iov-1].iov_len);
2791         }
2792         add_query_id_context(iov, &n_iov);
2793
2794         rqst->rq_nvec = n_iov;
2795         return 0;
2796 }
2797
2798 /* rq_iov[0] is the request and is released by cifs_small_buf_release().
2799  * All other vectors are freed by kfree().
2800  */
2801 void
2802 SMB2_open_free(struct smb_rqst *rqst)
2803 {
2804         int i;
2805
2806         if (rqst && rqst->rq_iov) {
2807                 cifs_small_buf_release(rqst->rq_iov[0].iov_base);
2808                 for (i = 1; i < rqst->rq_nvec; i++)
2809                         if (rqst->rq_iov[i].iov_base != smb2_padding)
2810                                 kfree(rqst->rq_iov[i].iov_base);
2811         }
2812 }
2813
2814 int
2815 SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
2816           __u8 *oplock, struct smb2_file_all_info *buf,
2817           struct create_posix_rsp *posix,
2818           struct kvec *err_iov, int *buftype)
2819 {
2820         struct smb_rqst rqst;
2821         struct smb2_create_rsp *rsp = NULL;
2822         struct cifs_tcon *tcon = oparms->tcon;
2823         struct cifs_ses *ses = tcon->ses;
2824         struct TCP_Server_Info *server = cifs_pick_channel(ses);
2825         struct kvec iov[SMB2_CREATE_IOV_SIZE];
2826         struct kvec rsp_iov = {NULL, 0};
2827         int resp_buftype = CIFS_NO_BUFFER;
2828         int rc = 0;
2829         int flags = 0;
2830
2831         cifs_dbg(FYI, "create/open\n");
2832         if (!ses || !server)
2833                 return -EIO;
2834
2835         if (smb3_encryption_required(tcon))
2836                 flags |= CIFS_TRANSFORM_REQ;
2837
2838         memset(&rqst, 0, sizeof(struct smb_rqst));
2839         memset(&iov, 0, sizeof(iov));
2840         rqst.rq_iov = iov;
2841         rqst.rq_nvec = SMB2_CREATE_IOV_SIZE;
2842
2843         rc = SMB2_open_init(tcon, server,
2844                             &rqst, oplock, oparms, path);
2845         if (rc)
2846                 goto creat_exit;
2847
2848         trace_smb3_open_enter(xid, tcon->tid, tcon->ses->Suid,
2849                 oparms->create_options, oparms->desired_access);
2850
2851         rc = cifs_send_recv(xid, ses, server,
2852                             &rqst, &resp_buftype, flags,
2853                             &rsp_iov);
2854         rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
2855
2856         if (rc != 0) {
2857                 cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
2858                 if (err_iov && rsp) {
2859                         *err_iov = rsp_iov;
2860                         *buftype = resp_buftype;
2861                         resp_buftype = CIFS_NO_BUFFER;
2862                         rsp = NULL;
2863                 }
2864                 trace_smb3_open_err(xid, tcon->tid, ses->Suid,
2865                                     oparms->create_options, oparms->desired_access, rc);
2866                 if (rc == -EREMCHG) {
2867                         pr_warn_once("server share %s deleted\n",
2868                                      tcon->treeName);
2869                         tcon->need_reconnect = true;
2870                 }
2871                 goto creat_exit;
2872         } else
2873                 trace_smb3_open_done(xid, rsp->PersistentFileId, tcon->tid,
2874                                      ses->Suid, oparms->create_options,
2875                                      oparms->desired_access);
2876
2877         atomic_inc(&tcon->num_remote_opens);
2878         oparms->fid->persistent_fid = rsp->PersistentFileId;
2879         oparms->fid->volatile_fid = rsp->VolatileFileId;
2880         oparms->fid->access = oparms->desired_access;
2881 #ifdef CONFIG_CIFS_DEBUG2
2882         oparms->fid->mid = le64_to_cpu(rsp->sync_hdr.MessageId);
2883 #endif /* CIFS_DEBUG2 */
2884
2885         if (buf) {
2886                 memcpy(buf, &rsp->CreationTime, 32);
2887                 buf->AllocationSize = rsp->AllocationSize;
2888                 buf->EndOfFile = rsp->EndofFile;
2889                 buf->Attributes = rsp->FileAttributes;
2890                 buf->NumberOfLinks = cpu_to_le32(1);
2891                 buf->DeletePending = 0;
2892         }
2893
2894
2895         smb2_parse_contexts(server, rsp, &oparms->fid->epoch,
2896                             oparms->fid->lease_key, oplock, buf, posix);
2897 creat_exit:
2898         SMB2_open_free(&rqst);
2899         free_rsp_buf(resp_buftype, rsp);
2900         return rc;
2901 }
2902
2903 int
2904 SMB2_ioctl_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
2905                 struct smb_rqst *rqst,
2906                 u64 persistent_fid, u64 volatile_fid, u32 opcode,
2907                 bool is_fsctl, char *in_data, u32 indatalen,
2908                 __u32 max_response_size)
2909 {
2910         struct smb2_ioctl_req *req;
2911         struct kvec *iov = rqst->rq_iov;
2912         unsigned int total_len;
2913         int rc;
2914         char *in_data_buf;
2915
2916         rc = smb2_ioctl_req_init(opcode, tcon, server,
2917                                  (void **) &req, &total_len);
2918         if (rc)
2919                 return rc;
2920
2921         if (indatalen) {
2922                 /*
2923                  * indatalen is usually small at a couple of bytes max, so
2924                  * just allocate through generic pool
2925                  */
2926                 in_data_buf = kmemdup(in_data, indatalen, GFP_NOFS);
2927                 if (!in_data_buf) {
2928                         cifs_small_buf_release(req);
2929                         return -ENOMEM;
2930                 }
2931         }
2932
2933         req->CtlCode = cpu_to_le32(opcode);
2934         req->PersistentFileId = persistent_fid;
2935         req->VolatileFileId = volatile_fid;
2936
2937         iov[0].iov_base = (char *)req;
2938         /*
2939          * If no input data, the size of ioctl struct in
2940          * protocol spec still includes a 1 byte data buffer,
2941          * but if input data passed to ioctl, we do not
2942          * want to double count this, so we do not send
2943          * the dummy one byte of data in iovec[0] if sending
2944          * input data (in iovec[1]).
2945          */
2946         if (indatalen) {
2947                 req->InputCount = cpu_to_le32(indatalen);
2948                 /* do not set InputOffset if no input data */
2949                 req->InputOffset =
2950                        cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer));
2951                 rqst->rq_nvec = 2;
2952                 iov[0].iov_len = total_len - 1;
2953                 iov[1].iov_base = in_data_buf;
2954                 iov[1].iov_len = indatalen;
2955         } else {
2956                 rqst->rq_nvec = 1;
2957                 iov[0].iov_len = total_len;
2958         }
2959
2960         req->OutputOffset = 0;
2961         req->OutputCount = 0; /* MBZ */
2962
2963         /*
2964          * In most cases max_response_size is set to 16K (CIFSMaxBufSize)
2965          * We Could increase default MaxOutputResponse, but that could require
2966          * more credits. Windows typically sets this smaller, but for some
2967          * ioctls it may be useful to allow server to send more. No point
2968          * limiting what the server can send as long as fits in one credit
2969          * We can not handle more than CIFS_MAX_BUF_SIZE yet but may want
2970          * to increase this limit up in the future.
2971          * Note that for snapshot queries that servers like Azure expect that
2972          * the first query be minimal size (and just used to get the number/size
2973          * of previous versions) so response size must be specified as EXACTLY
2974          * sizeof(struct snapshot_array) which is 16 when rounded up to multiple
2975          * of eight bytes.  Currently that is the only case where we set max
2976          * response size smaller.
2977          */
2978         req->MaxOutputResponse = cpu_to_le32(max_response_size);
2979         req->sync_hdr.CreditCharge =
2980                 cpu_to_le16(DIV_ROUND_UP(max(indatalen, max_response_size),
2981                                          SMB2_MAX_BUFFER_SIZE));
2982         if (is_fsctl)
2983                 req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL);
2984         else
2985                 req->Flags = 0;
2986
2987         /* validate negotiate request must be signed - see MS-SMB2 3.2.5.5 */
2988         if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO)
2989                 req->sync_hdr.Flags |= SMB2_FLAGS_SIGNED;
2990
2991         return 0;
2992 }
2993
2994 void
2995 SMB2_ioctl_free(struct smb_rqst *rqst)
2996 {
2997         int i;
2998         if (rqst && rqst->rq_iov) {
2999                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3000                 for (i = 1; i < rqst->rq_nvec; i++)
3001                         if (rqst->rq_iov[i].iov_base != smb2_padding)
3002                                 kfree(rqst->rq_iov[i].iov_base);
3003         }
3004 }
3005
3006
3007 /*
3008  *      SMB2 IOCTL is used for both IOCTLs and FSCTLs
3009  */
3010 int
3011 SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
3012            u64 volatile_fid, u32 opcode, bool is_fsctl,
3013            char *in_data, u32 indatalen, u32 max_out_data_len,
3014            char **out_data, u32 *plen /* returned data len */)
3015 {
3016         struct smb_rqst rqst;
3017         struct smb2_ioctl_rsp *rsp = NULL;
3018         struct cifs_ses *ses;
3019         struct TCP_Server_Info *server;
3020         struct kvec iov[SMB2_IOCTL_IOV_SIZE];
3021         struct kvec rsp_iov = {NULL, 0};
3022         int resp_buftype = CIFS_NO_BUFFER;
3023         int rc = 0;
3024         int flags = 0;
3025
3026         cifs_dbg(FYI, "SMB2 IOCTL\n");
3027
3028         if (out_data != NULL)
3029                 *out_data = NULL;
3030
3031         /* zero out returned data len, in case of error */
3032         if (plen)
3033                 *plen = 0;
3034
3035         if (!tcon)
3036                 return -EIO;
3037
3038         ses = tcon->ses;
3039         if (!ses)
3040                 return -EIO;
3041
3042         server = cifs_pick_channel(ses);
3043         if (!server)
3044                 return -EIO;
3045
3046         if (smb3_encryption_required(tcon))
3047                 flags |= CIFS_TRANSFORM_REQ;
3048
3049         memset(&rqst, 0, sizeof(struct smb_rqst));
3050         memset(&iov, 0, sizeof(iov));
3051         rqst.rq_iov = iov;
3052         rqst.rq_nvec = SMB2_IOCTL_IOV_SIZE;
3053
3054         rc = SMB2_ioctl_init(tcon, server,
3055                              &rqst, persistent_fid, volatile_fid, opcode,
3056                              is_fsctl, in_data, indatalen, max_out_data_len);
3057         if (rc)
3058                 goto ioctl_exit;
3059
3060         rc = cifs_send_recv(xid, ses, server,
3061                             &rqst, &resp_buftype, flags,
3062                             &rsp_iov);
3063         rsp = (struct smb2_ioctl_rsp *)rsp_iov.iov_base;
3064
3065         if (rc != 0)
3066                 trace_smb3_fsctl_err(xid, persistent_fid, tcon->tid,
3067                                 ses->Suid, 0, opcode, rc);
3068
3069         if ((rc != 0) && (rc != -EINVAL) && (rc != -E2BIG)) {
3070                 cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3071                 goto ioctl_exit;
3072         } else if (rc == -EINVAL) {
3073                 if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) &&
3074                     (opcode != FSCTL_SRV_COPYCHUNK)) {
3075                         cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3076                         goto ioctl_exit;
3077                 }
3078         } else if (rc == -E2BIG) {
3079                 if (opcode != FSCTL_QUERY_ALLOCATED_RANGES) {
3080                         cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3081                         goto ioctl_exit;
3082                 }
3083         }
3084
3085         /* check if caller wants to look at return data or just return rc */
3086         if ((plen == NULL) || (out_data == NULL))
3087                 goto ioctl_exit;
3088
3089         *plen = le32_to_cpu(rsp->OutputCount);
3090
3091         /* We check for obvious errors in the output buffer length and offset */
3092         if (*plen == 0)
3093                 goto ioctl_exit; /* server returned no data */
3094         else if (*plen > rsp_iov.iov_len || *plen > 0xFF00) {
3095                 cifs_tcon_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen);
3096                 *plen = 0;
3097                 rc = -EIO;
3098                 goto ioctl_exit;
3099         }
3100
3101         if (rsp_iov.iov_len - *plen < le32_to_cpu(rsp->OutputOffset)) {
3102                 cifs_tcon_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen,
3103                         le32_to_cpu(rsp->OutputOffset));
3104                 *plen = 0;
3105                 rc = -EIO;
3106                 goto ioctl_exit;
3107         }
3108
3109         *out_data = kmemdup((char *)rsp + le32_to_cpu(rsp->OutputOffset),
3110                             *plen, GFP_KERNEL);
3111         if (*out_data == NULL) {
3112                 rc = -ENOMEM;
3113                 goto ioctl_exit;
3114         }
3115
3116 ioctl_exit:
3117         SMB2_ioctl_free(&rqst);
3118         free_rsp_buf(resp_buftype, rsp);
3119         return rc;
3120 }
3121
3122 /*
3123  *   Individual callers to ioctl worker function follow
3124  */
3125
3126 int
3127 SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
3128                      u64 persistent_fid, u64 volatile_fid)
3129 {
3130         int rc;
3131         struct  compress_ioctl fsctl_input;
3132         char *ret_data = NULL;
3133
3134         fsctl_input.CompressionState =
3135                         cpu_to_le16(COMPRESSION_FORMAT_DEFAULT);
3136
3137         rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
3138                         FSCTL_SET_COMPRESSION, true /* is_fsctl */,
3139                         (char *)&fsctl_input /* data input */,
3140                         2 /* in data len */, CIFSMaxBufSize /* max out data */,
3141                         &ret_data /* out data */, NULL);
3142
3143         cifs_dbg(FYI, "set compression rc %d\n", rc);
3144
3145         return rc;
3146 }
3147
3148 int
3149 SMB2_close_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3150                 struct smb_rqst *rqst,
3151                 u64 persistent_fid, u64 volatile_fid, bool query_attrs)
3152 {
3153         struct smb2_close_req *req;
3154         struct kvec *iov = rqst->rq_iov;
3155         unsigned int total_len;
3156         int rc;
3157
3158         rc = smb2_plain_req_init(SMB2_CLOSE, tcon, server,
3159                                  (void **) &req, &total_len);
3160         if (rc)
3161                 return rc;
3162
3163         req->PersistentFileId = persistent_fid;
3164         req->VolatileFileId = volatile_fid;
3165         if (query_attrs)
3166                 req->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
3167         else
3168                 req->Flags = 0;
3169         iov[0].iov_base = (char *)req;
3170         iov[0].iov_len = total_len;
3171
3172         return 0;
3173 }
3174
3175 void
3176 SMB2_close_free(struct smb_rqst *rqst)
3177 {
3178         if (rqst && rqst->rq_iov)
3179                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3180 }
3181
3182 int
3183 __SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3184              u64 persistent_fid, u64 volatile_fid,
3185              struct smb2_file_network_open_info *pbuf)
3186 {
3187         struct smb_rqst rqst;
3188         struct smb2_close_rsp *rsp = NULL;
3189         struct cifs_ses *ses = tcon->ses;
3190         struct TCP_Server_Info *server = cifs_pick_channel(ses);
3191         struct kvec iov[1];
3192         struct kvec rsp_iov;
3193         int resp_buftype = CIFS_NO_BUFFER;
3194         int rc = 0;
3195         int flags = 0;
3196         bool query_attrs = false;
3197
3198         cifs_dbg(FYI, "Close\n");
3199
3200         if (!ses || !server)
3201                 return -EIO;
3202
3203         if (smb3_encryption_required(tcon))
3204                 flags |= CIFS_TRANSFORM_REQ;
3205
3206         memset(&rqst, 0, sizeof(struct smb_rqst));
3207         memset(&iov, 0, sizeof(iov));
3208         rqst.rq_iov = iov;
3209         rqst.rq_nvec = 1;
3210
3211         /* check if need to ask server to return timestamps in close response */
3212         if (pbuf)
3213                 query_attrs = true;
3214
3215         trace_smb3_close_enter(xid, persistent_fid, tcon->tid, ses->Suid);
3216         rc = SMB2_close_init(tcon, server,
3217                              &rqst, persistent_fid, volatile_fid,
3218                              query_attrs);
3219         if (rc)
3220                 goto close_exit;
3221
3222         rc = cifs_send_recv(xid, ses, server,
3223                             &rqst, &resp_buftype, flags, &rsp_iov);
3224         rsp = (struct smb2_close_rsp *)rsp_iov.iov_base;
3225
3226         if (rc != 0) {
3227                 cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
3228                 trace_smb3_close_err(xid, persistent_fid, tcon->tid, ses->Suid,
3229                                      rc);
3230                 goto close_exit;
3231         } else {
3232                 trace_smb3_close_done(xid, persistent_fid, tcon->tid,
3233                                       ses->Suid);
3234                 /*
3235                  * Note that have to subtract 4 since struct network_open_info
3236                  * has a final 4 byte pad that close response does not have
3237                  */
3238                 if (pbuf)
3239                         memcpy(pbuf, (char *)&rsp->CreationTime, sizeof(*pbuf) - 4);
3240         }
3241
3242         atomic_dec(&tcon->num_remote_opens);
3243 close_exit:
3244         SMB2_close_free(&rqst);
3245         free_rsp_buf(resp_buftype, rsp);
3246
3247         /* retry close in a worker thread if this one is interrupted */
3248         if (rc == -EINTR) {
3249                 int tmp_rc;
3250
3251                 tmp_rc = smb2_handle_cancelled_close(tcon, persistent_fid,
3252                                                      volatile_fid);
3253                 if (tmp_rc)
3254                         cifs_dbg(VFS, "handle cancelled close fid 0x%llx returned error %d\n",
3255                                  persistent_fid, tmp_rc);
3256         }
3257         return rc;
3258 }
3259
3260 int
3261 SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3262                 u64 persistent_fid, u64 volatile_fid)
3263 {
3264         return __SMB2_close(xid, tcon, persistent_fid, volatile_fid, NULL);
3265 }
3266
3267 int
3268 smb2_validate_iov(unsigned int offset, unsigned int buffer_length,
3269                   struct kvec *iov, unsigned int min_buf_size)
3270 {
3271         unsigned int smb_len = iov->iov_len;
3272         char *end_of_smb = smb_len + (char *)iov->iov_base;
3273         char *begin_of_buf = offset + (char *)iov->iov_base;
3274         char *end_of_buf = begin_of_buf + buffer_length;
3275
3276
3277         if (buffer_length < min_buf_size) {
3278                 cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n",
3279                          buffer_length, min_buf_size);
3280                 return -EINVAL;
3281         }
3282
3283         /* check if beyond RFC1001 maximum length */
3284         if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
3285                 cifs_dbg(VFS, "buffer length %d or smb length %d too large\n",
3286                          buffer_length, smb_len);
3287                 return -EINVAL;
3288         }
3289
3290         if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
3291                 cifs_dbg(VFS, "Invalid server response, bad offset to data\n");
3292                 return -EINVAL;
3293         }
3294
3295         return 0;
3296 }
3297
3298 /*
3299  * If SMB buffer fields are valid, copy into temporary buffer to hold result.
3300  * Caller must free buffer.
3301  */
3302 int
3303 smb2_validate_and_copy_iov(unsigned int offset, unsigned int buffer_length,
3304                            struct kvec *iov, unsigned int minbufsize,
3305                            char *data)
3306 {
3307         char *begin_of_buf = offset + (char *)iov->iov_base;
3308         int rc;
3309
3310         if (!data)
3311                 return -EINVAL;
3312
3313         rc = smb2_validate_iov(offset, buffer_length, iov, minbufsize);
3314         if (rc)
3315                 return rc;
3316
3317         memcpy(data, begin_of_buf, buffer_length);
3318
3319         return 0;
3320 }
3321
3322 int
3323 SMB2_query_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3324                      struct smb_rqst *rqst,
3325                      u64 persistent_fid, u64 volatile_fid,
3326                      u8 info_class, u8 info_type, u32 additional_info,
3327                      size_t output_len, size_t input_len, void *input)
3328 {
3329         struct smb2_query_info_req *req;
3330         struct kvec *iov = rqst->rq_iov;
3331         unsigned int total_len;
3332         int rc;
3333
3334         rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
3335                                  (void **) &req, &total_len);
3336         if (rc)
3337                 return rc;
3338
3339         req->InfoType = info_type;
3340         req->FileInfoClass = info_class;
3341         req->PersistentFileId = persistent_fid;
3342         req->VolatileFileId = volatile_fid;
3343         req->AdditionalInformation = cpu_to_le32(additional_info);
3344
3345         req->OutputBufferLength = cpu_to_le32(output_len);
3346         if (input_len) {
3347                 req->InputBufferLength = cpu_to_le32(input_len);
3348                 /* total_len for smb query request never close to le16 max */
3349                 req->InputBufferOffset = cpu_to_le16(total_len - 1);
3350                 memcpy(req->Buffer, input, input_len);
3351         }
3352
3353         iov[0].iov_base = (char *)req;
3354         /* 1 for Buffer */
3355         iov[0].iov_len = total_len - 1 + input_len;
3356         return 0;
3357 }
3358
3359 void
3360 SMB2_query_info_free(struct smb_rqst *rqst)
3361 {
3362         if (rqst && rqst->rq_iov)
3363                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3364 }
3365
3366 static int
3367 query_info(const unsigned int xid, struct cifs_tcon *tcon,
3368            u64 persistent_fid, u64 volatile_fid, u8 info_class, u8 info_type,
3369            u32 additional_info, size_t output_len, size_t min_len, void **data,
3370                 u32 *dlen)
3371 {
3372         struct smb_rqst rqst;
3373         struct smb2_query_info_rsp *rsp = NULL;
3374         struct kvec iov[1];
3375         struct kvec rsp_iov;
3376         int rc = 0;
3377         int resp_buftype = CIFS_NO_BUFFER;
3378         struct cifs_ses *ses = tcon->ses;
3379         struct TCP_Server_Info *server;
3380         int flags = 0;
3381         bool allocated = false;
3382
3383         cifs_dbg(FYI, "Query Info\n");
3384
3385         if (!ses)
3386                 return -EIO;
3387         server = cifs_pick_channel(ses);
3388         if (!server)
3389                 return -EIO;
3390
3391         if (smb3_encryption_required(tcon))
3392                 flags |= CIFS_TRANSFORM_REQ;
3393
3394         memset(&rqst, 0, sizeof(struct smb_rqst));
3395         memset(&iov, 0, sizeof(iov));
3396         rqst.rq_iov = iov;
3397         rqst.rq_nvec = 1;
3398
3399         rc = SMB2_query_info_init(tcon, server,
3400                                   &rqst, persistent_fid, volatile_fid,
3401                                   info_class, info_type, additional_info,
3402                                   output_len, 0, NULL);
3403         if (rc)
3404                 goto qinf_exit;
3405
3406         trace_smb3_query_info_enter(xid, persistent_fid, tcon->tid,
3407                                     ses->Suid, info_class, (__u32)info_type);
3408
3409         rc = cifs_send_recv(xid, ses, server,
3410                             &rqst, &resp_buftype, flags, &rsp_iov);
3411         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
3412
3413         if (rc) {
3414                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
3415                 trace_smb3_query_info_err(xid, persistent_fid, tcon->tid,
3416                                 ses->Suid, info_class, (__u32)info_type, rc);
3417                 goto qinf_exit;
3418         }
3419
3420         trace_smb3_query_info_done(xid, persistent_fid, tcon->tid,
3421                                 ses->Suid, info_class, (__u32)info_type);
3422
3423         if (dlen) {
3424                 *dlen = le32_to_cpu(rsp->OutputBufferLength);
3425                 if (!*data) {
3426                         *data = kmalloc(*dlen, GFP_KERNEL);
3427                         if (!*data) {
3428                                 cifs_tcon_dbg(VFS,
3429                                         "Error %d allocating memory for acl\n",
3430                                         rc);
3431                                 *dlen = 0;
3432                                 rc = -ENOMEM;
3433                                 goto qinf_exit;
3434                         }
3435                         allocated = true;
3436                 }
3437         }
3438
3439         rc = smb2_validate_and_copy_iov(le16_to_cpu(rsp->OutputBufferOffset),
3440                                         le32_to_cpu(rsp->OutputBufferLength),
3441                                         &rsp_iov, min_len, *data);
3442         if (rc && allocated) {
3443                 kfree(*data);
3444                 *data = NULL;
3445                 *dlen = 0;
3446         }
3447
3448 qinf_exit:
3449         SMB2_query_info_free(&rqst);
3450         free_rsp_buf(resp_buftype, rsp);
3451         return rc;
3452 }
3453
3454 int SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
3455         u64 persistent_fid, u64 volatile_fid, struct smb2_file_all_info *data)
3456 {
3457         return query_info(xid, tcon, persistent_fid, volatile_fid,
3458                           FILE_ALL_INFORMATION, SMB2_O_INFO_FILE, 0,
3459                           sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
3460                           sizeof(struct smb2_file_all_info), (void **)&data,
3461                           NULL);
3462 }
3463
3464 int
3465 SMB311_posix_query_info(const unsigned int xid, struct cifs_tcon *tcon,
3466                 u64 persistent_fid, u64 volatile_fid, struct smb311_posix_qinfo *data, u32 *plen)
3467 {
3468         size_t output_len = sizeof(struct smb311_posix_qinfo *) +
3469                         (sizeof(struct cifs_sid) * 2) + (PATH_MAX * 2);
3470         *plen = 0;
3471
3472         return query_info(xid, tcon, persistent_fid, volatile_fid,
3473                           SMB_FIND_FILE_POSIX_INFO, SMB2_O_INFO_FILE, 0,
3474                           output_len, sizeof(struct smb311_posix_qinfo), (void **)&data, plen);
3475 }
3476
3477 int
3478 SMB2_query_acl(const unsigned int xid, struct cifs_tcon *tcon,
3479                 u64 persistent_fid, u64 volatile_fid,
3480                 void **data, u32 *plen)
3481 {
3482         __u32 additional_info = OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO;
3483         *plen = 0;
3484
3485         return query_info(xid, tcon, persistent_fid, volatile_fid,
3486                           0, SMB2_O_INFO_SECURITY, additional_info,
3487                           SMB2_MAX_BUFFER_SIZE, MIN_SEC_DESC_LEN, data, plen);
3488 }
3489
3490 int
3491 SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
3492                  u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
3493 {
3494         return query_info(xid, tcon, persistent_fid, volatile_fid,
3495                           FILE_INTERNAL_INFORMATION, SMB2_O_INFO_FILE, 0,
3496                           sizeof(struct smb2_file_internal_info),
3497                           sizeof(struct smb2_file_internal_info),
3498                           (void **)&uniqueid, NULL);
3499 }
3500
3501 /*
3502  * CHANGE_NOTIFY Request is sent to get notifications on changes to a directory
3503  * See MS-SMB2 2.2.35 and 2.2.36
3504  */
3505
3506 static int
3507 SMB2_notify_init(const unsigned int xid, struct smb_rqst *rqst,
3508                  struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3509                  u64 persistent_fid, u64 volatile_fid,
3510                  u32 completion_filter, bool watch_tree)
3511 {
3512         struct smb2_change_notify_req *req;
3513         struct kvec *iov = rqst->rq_iov;
3514         unsigned int total_len;
3515         int rc;
3516
3517         rc = smb2_plain_req_init(SMB2_CHANGE_NOTIFY, tcon, server,
3518                                  (void **) &req, &total_len);
3519         if (rc)
3520                 return rc;
3521
3522         req->PersistentFileId = persistent_fid;
3523         req->VolatileFileId = volatile_fid;
3524         /* See note 354 of MS-SMB2, 64K max */
3525         req->OutputBufferLength =
3526                 cpu_to_le32(SMB2_MAX_BUFFER_SIZE - MAX_SMB2_HDR_SIZE);
3527         req->CompletionFilter = cpu_to_le32(completion_filter);
3528         if (watch_tree)
3529                 req->Flags = cpu_to_le16(SMB2_WATCH_TREE);
3530         else
3531                 req->Flags = 0;
3532
3533         iov[0].iov_base = (char *)req;
3534         iov[0].iov_len = total_len;
3535
3536         return 0;
3537 }
3538
3539 int
3540 SMB2_change_notify(const unsigned int xid, struct cifs_tcon *tcon,
3541                 u64 persistent_fid, u64 volatile_fid, bool watch_tree,
3542                 u32 completion_filter)
3543 {
3544         struct cifs_ses *ses = tcon->ses;
3545         struct TCP_Server_Info *server = cifs_pick_channel(ses);
3546         struct smb_rqst rqst;
3547         struct kvec iov[1];
3548         struct kvec rsp_iov = {NULL, 0};
3549         int resp_buftype = CIFS_NO_BUFFER;
3550         int flags = 0;
3551         int rc = 0;
3552
3553         cifs_dbg(FYI, "change notify\n");
3554         if (!ses || !server)
3555                 return -EIO;
3556
3557         if (smb3_encryption_required(tcon))
3558                 flags |= CIFS_TRANSFORM_REQ;
3559
3560         memset(&rqst, 0, sizeof(struct smb_rqst));
3561         memset(&iov, 0, sizeof(iov));
3562         rqst.rq_iov = iov;
3563         rqst.rq_nvec = 1;
3564
3565         rc = SMB2_notify_init(xid, &rqst, tcon, server,
3566                               persistent_fid, volatile_fid,
3567                               completion_filter, watch_tree);
3568         if (rc)
3569                 goto cnotify_exit;
3570
3571         trace_smb3_notify_enter(xid, persistent_fid, tcon->tid, ses->Suid,
3572                                 (u8)watch_tree, completion_filter);
3573         rc = cifs_send_recv(xid, ses, server,
3574                             &rqst, &resp_buftype, flags, &rsp_iov);
3575
3576         if (rc != 0) {
3577                 cifs_stats_fail_inc(tcon, SMB2_CHANGE_NOTIFY_HE);
3578                 trace_smb3_notify_err(xid, persistent_fid, tcon->tid, ses->Suid,
3579                                 (u8)watch_tree, completion_filter, rc);
3580         } else
3581                 trace_smb3_notify_done(xid, persistent_fid, tcon->tid,
3582                                 ses->Suid, (u8)watch_tree, completion_filter);
3583
3584  cnotify_exit:
3585         if (rqst.rq_iov)
3586                 cifs_small_buf_release(rqst.rq_iov[0].iov_base); /* request */
3587         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3588         return rc;
3589 }
3590
3591
3592
3593 /*
3594  * This is a no-op for now. We're not really interested in the reply, but
3595  * rather in the fact that the server sent one and that server->lstrp
3596  * gets updated.
3597  *
3598  * FIXME: maybe we should consider checking that the reply matches request?
3599  */
3600 static void
3601 smb2_echo_callback(struct mid_q_entry *mid)
3602 {
3603         struct TCP_Server_Info *server = mid->callback_data;
3604         struct smb2_echo_rsp *rsp = (struct smb2_echo_rsp *)mid->resp_buf;
3605         struct cifs_credits credits = { .value = 0, .instance = 0 };
3606
3607         if (mid->mid_state == MID_RESPONSE_RECEIVED
3608             || mid->mid_state == MID_RESPONSE_MALFORMED) {
3609                 credits.value = le16_to_cpu(rsp->sync_hdr.CreditRequest);
3610                 credits.instance = server->reconnect_instance;
3611         }
3612
3613         DeleteMidQEntry(mid);
3614         add_credits(server, &credits, CIFS_ECHO_OP);
3615 }
3616
3617 void smb2_reconnect_server(struct work_struct *work)
3618 {
3619         struct TCP_Server_Info *server = container_of(work,
3620                                         struct TCP_Server_Info, reconnect.work);
3621         struct cifs_ses *ses;
3622         struct cifs_tcon *tcon, *tcon2;
3623         struct list_head tmp_list;
3624         int tcon_exist = false;
3625         int rc;
3626         int resched = false;
3627
3628
3629         /* Prevent simultaneous reconnects that can corrupt tcon->rlist list */
3630         mutex_lock(&server->reconnect_mutex);
3631
3632         INIT_LIST_HEAD(&tmp_list);
3633         cifs_dbg(FYI, "Need negotiate, reconnecting tcons\n");
3634
3635         spin_lock(&cifs_tcp_ses_lock);
3636         list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
3637                 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
3638                         if (tcon->need_reconnect || tcon->need_reopen_files) {
3639                                 tcon->tc_count++;
3640                                 list_add_tail(&tcon->rlist, &tmp_list);
3641                                 tcon_exist = true;
3642                         }
3643                 }
3644                 /*
3645                  * IPC has the same lifetime as its session and uses its
3646                  * refcount.
3647                  */
3648                 if (ses->tcon_ipc && ses->tcon_ipc->need_reconnect) {
3649                         list_add_tail(&ses->tcon_ipc->rlist, &tmp_list);
3650                         tcon_exist = true;
3651                         ses->ses_count++;
3652                 }
3653         }
3654         /*
3655          * Get the reference to server struct to be sure that the last call of
3656          * cifs_put_tcon() in the loop below won't release the server pointer.
3657          */
3658         if (tcon_exist)
3659                 server->srv_count++;
3660
3661         spin_unlock(&cifs_tcp_ses_lock);
3662
3663         list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) {
3664                 rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server);
3665                 if (!rc)
3666                         cifs_reopen_persistent_handles(tcon);
3667                 else
3668                         resched = true;
3669                 list_del_init(&tcon->rlist);
3670                 if (tcon->ipc)
3671                         cifs_put_smb_ses(tcon->ses);
3672                 else
3673                         cifs_put_tcon(tcon);
3674         }
3675
3676         cifs_dbg(FYI, "Reconnecting tcons finished\n");
3677         if (resched)
3678                 queue_delayed_work(cifsiod_wq, &server->reconnect, 2 * HZ);
3679         mutex_unlock(&server->reconnect_mutex);
3680
3681         /* now we can safely release srv struct */
3682         if (tcon_exist)
3683                 cifs_put_tcp_session(server, 1);
3684 }
3685
3686 int
3687 SMB2_echo(struct TCP_Server_Info *server)
3688 {
3689         struct smb2_echo_req *req;
3690         int rc = 0;
3691         struct kvec iov[1];
3692         struct smb_rqst rqst = { .rq_iov = iov,
3693                                  .rq_nvec = 1 };
3694         unsigned int total_len;
3695
3696         cifs_dbg(FYI, "In echo request\n");
3697
3698         if (server->tcpStatus == CifsNeedNegotiate) {
3699                 /* No need to send echo on newly established connections */
3700                 mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
3701                 return rc;
3702         }
3703
3704         rc = smb2_plain_req_init(SMB2_ECHO, NULL, server,
3705                                  (void **)&req, &total_len);
3706         if (rc)
3707                 return rc;
3708
3709         req->sync_hdr.CreditRequest = cpu_to_le16(1);
3710
3711         iov[0].iov_len = total_len;
3712         iov[0].iov_base = (char *)req;
3713
3714         rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, NULL,
3715                              server, CIFS_ECHO_OP, NULL);
3716         if (rc)
3717                 cifs_dbg(FYI, "Echo request failed: %d\n", rc);
3718
3719         cifs_small_buf_release(req);
3720         return rc;
3721 }
3722
3723 void
3724 SMB2_flush_free(struct smb_rqst *rqst)
3725 {
3726         if (rqst && rqst->rq_iov)
3727                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3728 }
3729
3730 int
3731 SMB2_flush_init(const unsigned int xid, struct smb_rqst *rqst,
3732                 struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3733                 u64 persistent_fid, u64 volatile_fid)
3734 {
3735         struct smb2_flush_req *req;
3736         struct kvec *iov = rqst->rq_iov;
3737         unsigned int total_len;
3738         int rc;
3739
3740         rc = smb2_plain_req_init(SMB2_FLUSH, tcon, server,
3741                                  (void **) &req, &total_len);
3742         if (rc)
3743                 return rc;
3744
3745         req->PersistentFileId = persistent_fid;
3746         req->VolatileFileId = volatile_fid;
3747
3748         iov[0].iov_base = (char *)req;
3749         iov[0].iov_len = total_len;
3750
3751         return 0;
3752 }
3753
3754 int
3755 SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
3756            u64 volatile_fid)
3757 {
3758         struct cifs_ses *ses = tcon->ses;
3759         struct smb_rqst rqst;
3760         struct kvec iov[1];
3761         struct kvec rsp_iov = {NULL, 0};
3762         struct TCP_Server_Info *server = cifs_pick_channel(ses);
3763         int resp_buftype = CIFS_NO_BUFFER;
3764         int flags = 0;
3765         int rc = 0;
3766
3767         cifs_dbg(FYI, "flush\n");
3768         if (!ses || !(ses->server))
3769                 return -EIO;
3770
3771         if (smb3_encryption_required(tcon))
3772                 flags |= CIFS_TRANSFORM_REQ;
3773
3774         memset(&rqst, 0, sizeof(struct smb_rqst));
3775         memset(&iov, 0, sizeof(iov));
3776         rqst.rq_iov = iov;
3777         rqst.rq_nvec = 1;
3778
3779         rc = SMB2_flush_init(xid, &rqst, tcon, server,
3780                              persistent_fid, volatile_fid);
3781         if (rc)
3782                 goto flush_exit;
3783
3784         trace_smb3_flush_enter(xid, persistent_fid, tcon->tid, ses->Suid);
3785         rc = cifs_send_recv(xid, ses, server,
3786                             &rqst, &resp_buftype, flags, &rsp_iov);
3787
3788         if (rc != 0) {
3789                 cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
3790                 trace_smb3_flush_err(xid, persistent_fid, tcon->tid, ses->Suid,
3791                                      rc);
3792         } else
3793                 trace_smb3_flush_done(xid, persistent_fid, tcon->tid,
3794                                       ses->Suid);
3795
3796  flush_exit:
3797         SMB2_flush_free(&rqst);
3798         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3799         return rc;
3800 }
3801
3802 /*
3803  * To form a chain of read requests, any read requests after the first should
3804  * have the end_of_chain boolean set to true.
3805  */
3806 static int
3807 smb2_new_read_req(void **buf, unsigned int *total_len,
3808         struct cifs_io_parms *io_parms, struct cifs_readdata *rdata,
3809         unsigned int remaining_bytes, int request_type)
3810 {
3811         int rc = -EACCES;
3812         struct smb2_read_plain_req *req = NULL;
3813         struct smb2_sync_hdr *shdr;
3814         struct TCP_Server_Info *server = io_parms->server;
3815
3816         rc = smb2_plain_req_init(SMB2_READ, io_parms->tcon, server,
3817                                  (void **) &req, total_len);
3818         if (rc)
3819                 return rc;
3820
3821         if (server == NULL)
3822                 return -ECONNABORTED;
3823
3824         shdr = &req->sync_hdr;
3825         shdr->ProcessId = cpu_to_le32(io_parms->pid);
3826
3827         req->PersistentFileId = io_parms->persistent_fid;
3828         req->VolatileFileId = io_parms->volatile_fid;
3829         req->ReadChannelInfoOffset = 0; /* reserved */
3830         req->ReadChannelInfoLength = 0; /* reserved */
3831         req->Channel = 0; /* reserved */
3832         req->MinimumCount = 0;
3833         req->Length = cpu_to_le32(io_parms->length);
3834         req->Offset = cpu_to_le64(io_parms->offset);
3835
3836         trace_smb3_read_enter(0 /* xid */,
3837                         io_parms->persistent_fid,
3838                         io_parms->tcon->tid, io_parms->tcon->ses->Suid,
3839                         io_parms->offset, io_parms->length);
3840 #ifdef CONFIG_CIFS_SMB_DIRECT
3841         /*
3842          * If we want to do a RDMA write, fill in and append
3843          * smbd_buffer_descriptor_v1 to the end of read request
3844          */
3845         if (server->rdma && rdata && !server->sign &&
3846                 rdata->bytes >= server->smbd_conn->rdma_readwrite_threshold) {
3847
3848                 struct smbd_buffer_descriptor_v1 *v1;
3849                 bool need_invalidate = server->dialect == SMB30_PROT_ID;
3850
3851                 rdata->mr = smbd_register_mr(
3852                                 server->smbd_conn, rdata->pages,
3853                                 rdata->nr_pages, rdata->page_offset,
3854                                 rdata->tailsz, true, need_invalidate);
3855                 if (!rdata->mr)
3856                         return -EAGAIN;
3857
3858                 req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
3859                 if (need_invalidate)
3860                         req->Channel = SMB2_CHANNEL_RDMA_V1;
3861                 req->ReadChannelInfoOffset =
3862                         cpu_to_le16(offsetof(struct smb2_read_plain_req, Buffer));
3863                 req->ReadChannelInfoLength =
3864                         cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
3865                 v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
3866                 v1->offset = cpu_to_le64(rdata->mr->mr->iova);
3867                 v1->token = cpu_to_le32(rdata->mr->mr->rkey);
3868                 v1->length = cpu_to_le32(rdata->mr->mr->length);
3869
3870                 *total_len += sizeof(*v1) - 1;
3871         }
3872 #endif
3873         if (request_type & CHAINED_REQUEST) {
3874                 if (!(request_type & END_OF_CHAIN)) {
3875                         /* next 8-byte aligned request */
3876                         *total_len = DIV_ROUND_UP(*total_len, 8) * 8;
3877                         shdr->NextCommand = cpu_to_le32(*total_len);
3878                 } else /* END_OF_CHAIN */
3879                         shdr->NextCommand = 0;
3880                 if (request_type & RELATED_REQUEST) {
3881                         shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
3882                         /*
3883                          * Related requests use info from previous read request
3884                          * in chain.
3885                          */
3886                         shdr->SessionId = 0xFFFFFFFF;
3887                         shdr->TreeId = 0xFFFFFFFF;
3888                         req->PersistentFileId = 0xFFFFFFFF;
3889                         req->VolatileFileId = 0xFFFFFFFF;
3890                 }
3891         }
3892         if (remaining_bytes > io_parms->length)
3893                 req->RemainingBytes = cpu_to_le32(remaining_bytes);
3894         else
3895                 req->RemainingBytes = 0;
3896
3897         *buf = req;
3898         return rc;
3899 }
3900
3901 static void
3902 smb2_readv_callback(struct mid_q_entry *mid)
3903 {
3904         struct cifs_readdata *rdata = mid->callback_data;
3905         struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
3906         struct TCP_Server_Info *server = rdata->server;
3907         struct smb2_sync_hdr *shdr =
3908                                 (struct smb2_sync_hdr *)rdata->iov[0].iov_base;
3909         struct cifs_credits credits = { .value = 0, .instance = 0 };
3910         struct smb_rqst rqst = { .rq_iov = &rdata->iov[1],
3911                                  .rq_nvec = 1,
3912                                  .rq_pages = rdata->pages,
3913                                  .rq_offset = rdata->page_offset,
3914                                  .rq_npages = rdata->nr_pages,
3915                                  .rq_pagesz = rdata->pagesz,
3916                                  .rq_tailsz = rdata->tailsz };
3917
3918         WARN_ONCE(rdata->server != mid->server,
3919                   "rdata server %p != mid server %p",
3920                   rdata->server, mid->server);
3921
3922         cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%u\n",
3923                  __func__, mid->mid, mid->mid_state, rdata->result,
3924                  rdata->bytes);
3925
3926         switch (mid->mid_state) {
3927         case MID_RESPONSE_RECEIVED:
3928                 credits.value = le16_to_cpu(shdr->CreditRequest);
3929                 credits.instance = server->reconnect_instance;
3930                 /* result already set, check signature */
3931                 if (server->sign && !mid->decrypted) {
3932                         int rc;
3933
3934                         rc = smb2_verify_signature(&rqst, server);
3935                         if (rc)
3936                                 cifs_tcon_dbg(VFS, "SMB signature verification returned error = %d\n",
3937                                          rc);
3938                 }
3939                 /* FIXME: should this be counted toward the initiating task? */
3940                 task_io_account_read(rdata->got_bytes);
3941                 cifs_stats_bytes_read(tcon, rdata->got_bytes);
3942                 break;
3943         case MID_REQUEST_SUBMITTED:
3944         case MID_RETRY_NEEDED:
3945                 rdata->result = -EAGAIN;
3946                 if (server->sign && rdata->got_bytes)
3947                         /* reset bytes number since we can not check a sign */
3948                         rdata->got_bytes = 0;
3949                 /* FIXME: should this be counted toward the initiating task? */
3950                 task_io_account_read(rdata->got_bytes);
3951                 cifs_stats_bytes_read(tcon, rdata->got_bytes);
3952                 break;
3953         case MID_RESPONSE_MALFORMED:
3954                 credits.value = le16_to_cpu(shdr->CreditRequest);
3955                 credits.instance = server->reconnect_instance;
3956                 fallthrough;
3957         default:
3958                 rdata->result = -EIO;
3959         }
3960 #ifdef CONFIG_CIFS_SMB_DIRECT
3961         /*
3962          * If this rdata has a memmory registered, the MR can be freed
3963          * MR needs to be freed as soon as I/O finishes to prevent deadlock
3964          * because they have limited number and are used for future I/Os
3965          */
3966         if (rdata->mr) {
3967                 smbd_deregister_mr(rdata->mr);
3968                 rdata->mr = NULL;
3969         }
3970 #endif
3971         if (rdata->result && rdata->result != -ENODATA) {
3972                 cifs_stats_fail_inc(tcon, SMB2_READ_HE);
3973                 trace_smb3_read_err(0 /* xid */,
3974                                     rdata->cfile->fid.persistent_fid,
3975                                     tcon->tid, tcon->ses->Suid, rdata->offset,
3976                                     rdata->bytes, rdata->result);
3977         } else
3978                 trace_smb3_read_done(0 /* xid */,
3979                                      rdata->cfile->fid.persistent_fid,
3980                                      tcon->tid, tcon->ses->Suid,
3981                                      rdata->offset, rdata->got_bytes);
3982
3983         queue_work(cifsiod_wq, &rdata->work);
3984         DeleteMidQEntry(mid);
3985         add_credits(server, &credits, 0);
3986 }
3987
3988 /* smb2_async_readv - send an async read, and set up mid to handle result */
3989 int
3990 smb2_async_readv(struct cifs_readdata *rdata)
3991 {
3992         int rc, flags = 0;
3993         char *buf;
3994         struct smb2_sync_hdr *shdr;
3995         struct cifs_io_parms io_parms;
3996         struct smb_rqst rqst = { .rq_iov = rdata->iov,
3997                                  .rq_nvec = 1 };
3998         struct TCP_Server_Info *server;
3999         struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
4000         unsigned int total_len;
4001
4002         cifs_dbg(FYI, "%s: offset=%llu bytes=%u\n",
4003                  __func__, rdata->offset, rdata->bytes);
4004
4005         if (!rdata->server)
4006                 rdata->server = cifs_pick_channel(tcon->ses);
4007
4008         io_parms.tcon = tlink_tcon(rdata->cfile->tlink);
4009         io_parms.server = server = rdata->server;
4010         io_parms.offset = rdata->offset;
4011         io_parms.length = rdata->bytes;
4012         io_parms.persistent_fid = rdata->cfile->fid.persistent_fid;
4013         io_parms.volatile_fid = rdata->cfile->fid.volatile_fid;
4014         io_parms.pid = rdata->pid;
4015
4016         rc = smb2_new_read_req(
4017                 (void **) &buf, &total_len, &io_parms, rdata, 0, 0);
4018         if (rc)
4019                 return rc;
4020
4021         if (smb3_encryption_required(io_parms.tcon))
4022                 flags |= CIFS_TRANSFORM_REQ;
4023
4024         rdata->iov[0].iov_base = buf;
4025         rdata->iov[0].iov_len = total_len;
4026
4027         shdr = (struct smb2_sync_hdr *)buf;
4028
4029         if (rdata->credits.value > 0) {
4030                 shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(rdata->bytes,
4031                                                 SMB2_MAX_BUFFER_SIZE));
4032                 shdr->CreditRequest =
4033                         cpu_to_le16(le16_to_cpu(shdr->CreditCharge) + 1);
4034
4035                 rc = adjust_credits(server, &rdata->credits, rdata->bytes);
4036                 if (rc)
4037                         goto async_readv_out;
4038
4039                 flags |= CIFS_HAS_CREDITS;
4040         }
4041
4042         kref_get(&rdata->refcount);
4043         rc = cifs_call_async(server, &rqst,
4044                              cifs_readv_receive, smb2_readv_callback,
4045                              smb3_handle_read_data, rdata, flags,
4046                              &rdata->credits);
4047         if (rc) {
4048                 kref_put(&rdata->refcount, cifs_readdata_release);
4049                 cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE);
4050                 trace_smb3_read_err(0 /* xid */, io_parms.persistent_fid,
4051                                     io_parms.tcon->tid,
4052                                     io_parms.tcon->ses->Suid,
4053                                     io_parms.offset, io_parms.length, rc);
4054         }
4055
4056 async_readv_out:
4057         cifs_small_buf_release(buf);
4058         return rc;
4059 }
4060
4061 int
4062 SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
4063           unsigned int *nbytes, char **buf, int *buf_type)
4064 {
4065         struct smb_rqst rqst;
4066         int resp_buftype, rc;
4067         struct smb2_read_plain_req *req = NULL;
4068         struct smb2_read_rsp *rsp = NULL;
4069         struct kvec iov[1];
4070         struct kvec rsp_iov;
4071         unsigned int total_len;
4072         int flags = CIFS_LOG_ERROR;
4073         struct cifs_ses *ses = io_parms->tcon->ses;
4074
4075         if (!io_parms->server)
4076                 io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
4077
4078         *nbytes = 0;
4079         rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);
4080         if (rc)
4081                 return rc;
4082
4083         if (smb3_encryption_required(io_parms->tcon))
4084                 flags |= CIFS_TRANSFORM_REQ;
4085
4086         iov[0].iov_base = (char *)req;
4087         iov[0].iov_len = total_len;
4088
4089         memset(&rqst, 0, sizeof(struct smb_rqst));
4090         rqst.rq_iov = iov;
4091         rqst.rq_nvec = 1;
4092
4093         rc = cifs_send_recv(xid, ses, io_parms->server,
4094                             &rqst, &resp_buftype, flags, &rsp_iov);
4095         rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
4096
4097         if (rc) {
4098                 if (rc != -ENODATA) {
4099                         cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
4100                         cifs_dbg(VFS, "Send error in read = %d\n", rc);
4101                         trace_smb3_read_err(xid, req->PersistentFileId,
4102                                             io_parms->tcon->tid, ses->Suid,
4103                                             io_parms->offset, io_parms->length,
4104                                             rc);
4105                 } else
4106                         trace_smb3_read_done(xid, req->PersistentFileId,
4107                                     io_parms->tcon->tid, ses->Suid,
4108                                     io_parms->offset, 0);
4109                 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4110                 cifs_small_buf_release(req);
4111                 return rc == -ENODATA ? 0 : rc;
4112         } else
4113                 trace_smb3_read_done(xid, req->PersistentFileId,
4114                                     io_parms->tcon->tid, ses->Suid,
4115                                     io_parms->offset, io_parms->length);
4116
4117         cifs_small_buf_release(req);
4118
4119         *nbytes = le32_to_cpu(rsp->DataLength);
4120         if ((*nbytes > CIFS_MAX_MSGSIZE) ||
4121             (*nbytes > io_parms->length)) {
4122                 cifs_dbg(FYI, "bad length %d for count %d\n",
4123                          *nbytes, io_parms->length);
4124                 rc = -EIO;
4125                 *nbytes = 0;
4126         }
4127
4128         if (*buf) {
4129                 memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);
4130                 free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4131         } else if (resp_buftype != CIFS_NO_BUFFER) {
4132                 *buf = rsp_iov.iov_base;
4133                 if (resp_buftype == CIFS_SMALL_BUFFER)
4134                         *buf_type = CIFS_SMALL_BUFFER;
4135                 else if (resp_buftype == CIFS_LARGE_BUFFER)
4136                         *buf_type = CIFS_LARGE_BUFFER;
4137         }
4138         return rc;
4139 }
4140
4141 /*
4142  * Check the mid_state and signature on received buffer (if any), and queue the
4143  * workqueue completion task.
4144  */
4145 static void
4146 smb2_writev_callback(struct mid_q_entry *mid)
4147 {
4148         struct cifs_writedata *wdata = mid->callback_data;
4149         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
4150         struct TCP_Server_Info *server = wdata->server;
4151         unsigned int written;
4152         struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
4153         struct cifs_credits credits = { .value = 0, .instance = 0 };
4154
4155         WARN_ONCE(wdata->server != mid->server,
4156                   "wdata server %p != mid server %p",
4157                   wdata->server, mid->server);
4158
4159         switch (mid->mid_state) {
4160         case MID_RESPONSE_RECEIVED:
4161                 credits.value = le16_to_cpu(rsp->sync_hdr.CreditRequest);
4162                 credits.instance = server->reconnect_instance;
4163                 wdata->result = smb2_check_receive(mid, server, 0);
4164                 if (wdata->result != 0)
4165                         break;
4166
4167                 written = le32_to_cpu(rsp->DataLength);
4168                 /*
4169                  * Mask off high 16 bits when bytes written as returned
4170                  * by the server is greater than bytes requested by the
4171                  * client. OS/2 servers are known to set incorrect
4172                  * CountHigh values.
4173                  */
4174                 if (written > wdata->bytes)
4175                         written &= 0xFFFF;
4176
4177                 if (written < wdata->bytes)
4178                         wdata->result = -ENOSPC;
4179                 else
4180                         wdata->bytes = written;
4181                 break;
4182         case MID_REQUEST_SUBMITTED:
4183         case MID_RETRY_NEEDED:
4184                 wdata->result = -EAGAIN;
4185                 break;
4186         case MID_RESPONSE_MALFORMED:
4187                 credits.value = le16_to_cpu(rsp->sync_hdr.CreditRequest);
4188                 credits.instance = server->reconnect_instance;
4189                 fallthrough;
4190         default:
4191                 wdata->result = -EIO;
4192                 break;
4193         }
4194 #ifdef CONFIG_CIFS_SMB_DIRECT
4195         /*
4196          * If this wdata has a memory registered, the MR can be freed
4197          * The number of MRs available is limited, it's important to recover
4198          * used MR as soon as I/O is finished. Hold MR longer in the later
4199          * I/O process can possibly result in I/O deadlock due to lack of MR
4200          * to send request on I/O retry
4201          */
4202         if (wdata->mr) {
4203                 smbd_deregister_mr(wdata->mr);
4204                 wdata->mr = NULL;
4205         }
4206 #endif
4207         if (wdata->result) {
4208                 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
4209                 trace_smb3_write_err(0 /* no xid */,
4210                                      wdata->cfile->fid.persistent_fid,
4211                                      tcon->tid, tcon->ses->Suid, wdata->offset,
4212                                      wdata->bytes, wdata->result);
4213                 if (wdata->result == -ENOSPC)
4214                         pr_warn_once("Out of space writing to %s\n",
4215                                      tcon->treeName);
4216         } else
4217                 trace_smb3_write_done(0 /* no xid */,
4218                                       wdata->cfile->fid.persistent_fid,
4219                                       tcon->tid, tcon->ses->Suid,
4220                                       wdata->offset, wdata->bytes);
4221
4222         queue_work(cifsiod_wq, &wdata->work);
4223         DeleteMidQEntry(mid);
4224         add_credits(server, &credits, 0);
4225 }
4226
4227 /* smb2_async_writev - send an async write, and set up mid to handle result */
4228 int
4229 smb2_async_writev(struct cifs_writedata *wdata,
4230                   void (*release)(struct kref *kref))
4231 {
4232         int rc = -EACCES, flags = 0;
4233         struct smb2_write_req *req = NULL;
4234         struct smb2_sync_hdr *shdr;
4235         struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
4236         struct TCP_Server_Info *server = wdata->server;
4237         struct kvec iov[1];
4238         struct smb_rqst rqst = { };
4239         unsigned int total_len;
4240
4241         if (!wdata->server)
4242                 server = wdata->server = cifs_pick_channel(tcon->ses);
4243
4244         rc = smb2_plain_req_init(SMB2_WRITE, tcon, server,
4245                                  (void **) &req, &total_len);
4246         if (rc)
4247                 return rc;
4248
4249         if (smb3_encryption_required(tcon))
4250                 flags |= CIFS_TRANSFORM_REQ;
4251
4252         shdr = (struct smb2_sync_hdr *)req;
4253         shdr->ProcessId = cpu_to_le32(wdata->cfile->pid);
4254
4255         req->PersistentFileId = wdata->cfile->fid.persistent_fid;
4256         req->VolatileFileId = wdata->cfile->fid.volatile_fid;
4257         req->WriteChannelInfoOffset = 0;
4258         req->WriteChannelInfoLength = 0;
4259         req->Channel = 0;
4260         req->Offset = cpu_to_le64(wdata->offset);
4261         req->DataOffset = cpu_to_le16(
4262                                 offsetof(struct smb2_write_req, Buffer));
4263         req->RemainingBytes = 0;
4264
4265         trace_smb3_write_enter(0 /* xid */, wdata->cfile->fid.persistent_fid,
4266                 tcon->tid, tcon->ses->Suid, wdata->offset, wdata->bytes);
4267 #ifdef CONFIG_CIFS_SMB_DIRECT
4268         /*
4269          * If we want to do a server RDMA read, fill in and append
4270          * smbd_buffer_descriptor_v1 to the end of write request
4271          */
4272         if (server->rdma && !server->sign && wdata->bytes >=
4273                 server->smbd_conn->rdma_readwrite_threshold) {
4274
4275                 struct smbd_buffer_descriptor_v1 *v1;
4276                 bool need_invalidate = server->dialect == SMB30_PROT_ID;
4277
4278                 wdata->mr = smbd_register_mr(
4279                                 server->smbd_conn, wdata->pages,
4280                                 wdata->nr_pages, wdata->page_offset,
4281                                 wdata->tailsz, false, need_invalidate);
4282                 if (!wdata->mr) {
4283                         rc = -EAGAIN;
4284                         goto async_writev_out;
4285                 }
4286                 req->Length = 0;
4287                 req->DataOffset = 0;
4288                 if (wdata->nr_pages > 1)
4289                         req->RemainingBytes =
4290                                 cpu_to_le32(
4291                                         (wdata->nr_pages - 1) * wdata->pagesz -
4292                                         wdata->page_offset + wdata->tailsz
4293                                 );
4294                 else
4295                         req->RemainingBytes = cpu_to_le32(wdata->tailsz);
4296                 req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
4297                 if (need_invalidate)
4298                         req->Channel = SMB2_CHANNEL_RDMA_V1;
4299                 req->WriteChannelInfoOffset =
4300                         cpu_to_le16(offsetof(struct smb2_write_req, Buffer));
4301                 req->WriteChannelInfoLength =
4302                         cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
4303                 v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
4304                 v1->offset = cpu_to_le64(wdata->mr->mr->iova);
4305                 v1->token = cpu_to_le32(wdata->mr->mr->rkey);
4306                 v1->length = cpu_to_le32(wdata->mr->mr->length);
4307         }
4308 #endif
4309         iov[0].iov_len = total_len - 1;
4310         iov[0].iov_base = (char *)req;
4311
4312         rqst.rq_iov = iov;
4313         rqst.rq_nvec = 1;
4314         rqst.rq_pages = wdata->pages;
4315         rqst.rq_offset = wdata->page_offset;
4316         rqst.rq_npages = wdata->nr_pages;
4317         rqst.rq_pagesz = wdata->pagesz;
4318         rqst.rq_tailsz = wdata->tailsz;
4319 #ifdef CONFIG_CIFS_SMB_DIRECT
4320         if (wdata->mr) {
4321                 iov[0].iov_len += sizeof(struct smbd_buffer_descriptor_v1);
4322                 rqst.rq_npages = 0;
4323         }
4324 #endif
4325         cifs_dbg(FYI, "async write at %llu %u bytes\n",
4326                  wdata->offset, wdata->bytes);
4327
4328 #ifdef CONFIG_CIFS_SMB_DIRECT
4329         /* For RDMA read, I/O size is in RemainingBytes not in Length */
4330         if (!wdata->mr)
4331                 req->Length = cpu_to_le32(wdata->bytes);
4332 #else
4333         req->Length = cpu_to_le32(wdata->bytes);
4334 #endif
4335
4336         if (wdata->credits.value > 0) {
4337                 shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->bytes,
4338                                                     SMB2_MAX_BUFFER_SIZE));
4339                 shdr->CreditRequest =
4340                         cpu_to_le16(le16_to_cpu(shdr->CreditCharge) + 1);
4341
4342                 rc = adjust_credits(server, &wdata->credits, wdata->bytes);
4343                 if (rc)
4344                         goto async_writev_out;
4345
4346                 flags |= CIFS_HAS_CREDITS;
4347         }
4348
4349         kref_get(&wdata->refcount);
4350         rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, NULL,
4351                              wdata, flags, &wdata->credits);
4352
4353         if (rc) {
4354                 trace_smb3_write_err(0 /* no xid */, req->PersistentFileId,
4355                                      tcon->tid, tcon->ses->Suid, wdata->offset,
4356                                      wdata->bytes, rc);
4357                 kref_put(&wdata->refcount, release);
4358                 cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
4359         }
4360
4361 async_writev_out:
4362         cifs_small_buf_release(req);
4363         return rc;
4364 }
4365
4366 /*
4367  * SMB2_write function gets iov pointer to kvec array with n_vec as a length.
4368  * The length field from io_parms must be at least 1 and indicates a number of
4369  * elements with data to write that begins with position 1 in iov array. All
4370  * data length is specified by count.
4371  */
4372 int
4373 SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
4374            unsigned int *nbytes, struct kvec *iov, int n_vec)
4375 {
4376         struct smb_rqst rqst;
4377         int rc = 0;
4378         struct smb2_write_req *req = NULL;
4379         struct smb2_write_rsp *rsp = NULL;
4380         int resp_buftype;
4381         struct kvec rsp_iov;
4382         int flags = 0;
4383         unsigned int total_len;
4384         struct TCP_Server_Info *server;
4385
4386         *nbytes = 0;
4387
4388         if (n_vec < 1)
4389                 return rc;
4390
4391         if (!io_parms->server)
4392                 io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
4393         server = io_parms->server;
4394         if (server == NULL)
4395                 return -ECONNABORTED;
4396
4397         rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, server,
4398                                  (void **) &req, &total_len);
4399         if (rc)
4400                 return rc;
4401
4402         if (smb3_encryption_required(io_parms->tcon))
4403                 flags |= CIFS_TRANSFORM_REQ;
4404
4405         req->sync_hdr.ProcessId = cpu_to_le32(io_parms->pid);
4406
4407         req->PersistentFileId = io_parms->persistent_fid;
4408         req->VolatileFileId = io_parms->volatile_fid;
4409         req->WriteChannelInfoOffset = 0;
4410         req->WriteChannelInfoLength = 0;
4411         req->Channel = 0;
4412         req->Length = cpu_to_le32(io_parms->length);
4413         req->Offset = cpu_to_le64(io_parms->offset);
4414         req->DataOffset = cpu_to_le16(
4415                                 offsetof(struct smb2_write_req, Buffer));
4416         req->RemainingBytes = 0;
4417
4418         trace_smb3_write_enter(xid, io_parms->persistent_fid,
4419                 io_parms->tcon->tid, io_parms->tcon->ses->Suid,
4420                 io_parms->offset, io_parms->length);
4421
4422         iov[0].iov_base = (char *)req;
4423         /* 1 for Buffer */
4424         iov[0].iov_len = total_len - 1;
4425
4426         memset(&rqst, 0, sizeof(struct smb_rqst));
4427         rqst.rq_iov = iov;
4428         rqst.rq_nvec = n_vec + 1;
4429
4430         rc = cifs_send_recv(xid, io_parms->tcon->ses, server,
4431                             &rqst,
4432                             &resp_buftype, flags, &rsp_iov);
4433         rsp = (struct smb2_write_rsp *)rsp_iov.iov_base;
4434
4435         if (rc) {
4436                 trace_smb3_write_err(xid, req->PersistentFileId,
4437                                      io_parms->tcon->tid,
4438                                      io_parms->tcon->ses->Suid,
4439                                      io_parms->offset, io_parms->length, rc);
4440                 cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
4441                 cifs_dbg(VFS, "Send error in write = %d\n", rc);
4442         } else {
4443                 *nbytes = le32_to_cpu(rsp->DataLength);
4444                 trace_smb3_write_done(xid, req->PersistentFileId,
4445                                      io_parms->tcon->tid,
4446                                      io_parms->tcon->ses->Suid,
4447                                      io_parms->offset, *nbytes);
4448         }
4449
4450         cifs_small_buf_release(req);
4451         free_rsp_buf(resp_buftype, rsp);
4452         return rc;
4453 }
4454
4455 int posix_info_sid_size(const void *beg, const void *end)
4456 {
4457         size_t subauth;
4458         int total;
4459
4460         if (beg + 1 > end)
4461                 return -1;
4462
4463         subauth = *(u8 *)(beg+1);
4464         if (subauth < 1 || subauth > 15)
4465                 return -1;
4466
4467         total = 1 + 1 + 6 + 4*subauth;
4468         if (beg + total > end)
4469                 return -1;
4470
4471         return total;
4472 }
4473
4474 int posix_info_parse(const void *beg, const void *end,
4475                      struct smb2_posix_info_parsed *out)
4476
4477 {
4478         int total_len = 0;
4479         int sid_len;
4480         int name_len;
4481         const void *owner_sid;
4482         const void *group_sid;
4483         const void *name;
4484
4485         /* if no end bound given, assume payload to be correct */
4486         if (!end) {
4487                 const struct smb2_posix_info *p = beg;
4488
4489                 end = beg + le32_to_cpu(p->NextEntryOffset);
4490                 /* last element will have a 0 offset, pick a sensible bound */
4491                 if (end == beg)
4492                         end += 0xFFFF;
4493         }
4494
4495         /* check base buf */
4496         if (beg + sizeof(struct smb2_posix_info) > end)
4497                 return -1;
4498         total_len = sizeof(struct smb2_posix_info);
4499
4500         /* check owner sid */
4501         owner_sid = beg + total_len;
4502         sid_len = posix_info_sid_size(owner_sid, end);
4503         if (sid_len < 0)
4504                 return -1;
4505         total_len += sid_len;
4506
4507         /* check group sid */
4508         group_sid = beg + total_len;
4509         sid_len = posix_info_sid_size(group_sid, end);
4510         if (sid_len < 0)
4511                 return -1;
4512         total_len += sid_len;
4513
4514         /* check name len */
4515         if (beg + total_len + 4 > end)
4516                 return -1;
4517         name_len = le32_to_cpu(*(__le32 *)(beg + total_len));
4518         if (name_len < 1 || name_len > 0xFFFF)
4519                 return -1;
4520         total_len += 4;
4521
4522         /* check name */
4523         name = beg + total_len;
4524         if (name + name_len > end)
4525                 return -1;
4526         total_len += name_len;
4527
4528         if (out) {
4529                 out->base = beg;
4530                 out->size = total_len;
4531                 out->name_len = name_len;
4532                 out->name = name;
4533                 memcpy(&out->owner, owner_sid,
4534                        posix_info_sid_size(owner_sid, end));
4535                 memcpy(&out->group, group_sid,
4536                        posix_info_sid_size(group_sid, end));
4537         }
4538         return total_len;
4539 }
4540
4541 static int posix_info_extra_size(const void *beg, const void *end)
4542 {
4543         int len = posix_info_parse(beg, end, NULL);
4544
4545         if (len < 0)
4546                 return -1;
4547         return len - sizeof(struct smb2_posix_info);
4548 }
4549
4550 static unsigned int
4551 num_entries(int infotype, char *bufstart, char *end_of_buf, char **lastentry,
4552             size_t size)
4553 {
4554         int len;
4555         unsigned int entrycount = 0;
4556         unsigned int next_offset = 0;
4557         char *entryptr;
4558         FILE_DIRECTORY_INFO *dir_info;
4559
4560         if (bufstart == NULL)
4561                 return 0;
4562
4563         entryptr = bufstart;
4564
4565         while (1) {
4566                 if (entryptr + next_offset < entryptr ||
4567                     entryptr + next_offset > end_of_buf ||
4568                     entryptr + next_offset + size > end_of_buf) {
4569                         cifs_dbg(VFS, "malformed search entry would overflow\n");
4570                         break;
4571                 }
4572
4573                 entryptr = entryptr + next_offset;
4574                 dir_info = (FILE_DIRECTORY_INFO *)entryptr;
4575
4576                 if (infotype == SMB_FIND_FILE_POSIX_INFO)
4577                         len = posix_info_extra_size(entryptr, end_of_buf);
4578                 else
4579                         len = le32_to_cpu(dir_info->FileNameLength);
4580
4581                 if (len < 0 ||
4582                     entryptr + len < entryptr ||
4583                     entryptr + len > end_of_buf ||
4584                     entryptr + len + size > end_of_buf) {
4585                         cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
4586                                  end_of_buf);
4587                         break;
4588                 }
4589
4590                 *lastentry = entryptr;
4591                 entrycount++;
4592
4593                 next_offset = le32_to_cpu(dir_info->NextEntryOffset);
4594                 if (!next_offset)
4595                         break;
4596         }
4597
4598         return entrycount;
4599 }
4600
4601 /*
4602  * Readdir/FindFirst
4603  */
4604 int SMB2_query_directory_init(const unsigned int xid,
4605                               struct cifs_tcon *tcon,
4606                               struct TCP_Server_Info *server,
4607                               struct smb_rqst *rqst,
4608                               u64 persistent_fid, u64 volatile_fid,
4609                               int index, int info_level)
4610 {
4611         struct smb2_query_directory_req *req;
4612         unsigned char *bufptr;
4613         __le16 asteriks = cpu_to_le16('*');
4614         unsigned int output_size = CIFSMaxBufSize -
4615                 MAX_SMB2_CREATE_RESPONSE_SIZE -
4616                 MAX_SMB2_CLOSE_RESPONSE_SIZE;
4617         unsigned int total_len;
4618         struct kvec *iov = rqst->rq_iov;
4619         int len, rc;
4620
4621         rc = smb2_plain_req_init(SMB2_QUERY_DIRECTORY, tcon, server,
4622                                  (void **) &req, &total_len);
4623         if (rc)
4624                 return rc;
4625
4626         switch (info_level) {
4627         case SMB_FIND_FILE_DIRECTORY_INFO:
4628                 req->FileInformationClass = FILE_DIRECTORY_INFORMATION;
4629                 break;
4630         case SMB_FIND_FILE_ID_FULL_DIR_INFO:
4631                 req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION;
4632                 break;
4633         case SMB_FIND_FILE_POSIX_INFO:
4634                 req->FileInformationClass = SMB_FIND_FILE_POSIX_INFO;
4635                 break;
4636         default:
4637                 cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
4638                         info_level);
4639                 return -EINVAL;
4640         }
4641
4642         req->FileIndex = cpu_to_le32(index);
4643         req->PersistentFileId = persistent_fid;
4644         req->VolatileFileId = volatile_fid;
4645
4646         len = 0x2;
4647         bufptr = req->Buffer;
4648         memcpy(bufptr, &asteriks, len);
4649
4650         req->FileNameOffset =
4651                 cpu_to_le16(sizeof(struct smb2_query_directory_req) - 1);
4652         req->FileNameLength = cpu_to_le16(len);
4653         /*
4654          * BB could be 30 bytes or so longer if we used SMB2 specific
4655          * buffer lengths, but this is safe and close enough.
4656          */
4657         output_size = min_t(unsigned int, output_size, server->maxBuf);
4658         output_size = min_t(unsigned int, output_size, 2 << 15);
4659         req->OutputBufferLength = cpu_to_le32(output_size);
4660
4661         iov[0].iov_base = (char *)req;
4662         /* 1 for Buffer */
4663         iov[0].iov_len = total_len - 1;
4664
4665         iov[1].iov_base = (char *)(req->Buffer);
4666         iov[1].iov_len = len;
4667
4668         trace_smb3_query_dir_enter(xid, persistent_fid, tcon->tid,
4669                         tcon->ses->Suid, index, output_size);
4670
4671         return 0;
4672 }
4673
4674 void SMB2_query_directory_free(struct smb_rqst *rqst)
4675 {
4676         if (rqst && rqst->rq_iov) {
4677                 cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
4678         }
4679 }
4680
4681 int
4682 smb2_parse_query_directory(struct cifs_tcon *tcon,
4683                            struct kvec *rsp_iov,
4684                            int resp_buftype,
4685                            struct cifs_search_info *srch_inf)
4686 {
4687         struct smb2_query_directory_rsp *rsp;
4688         size_t info_buf_size;
4689         char *end_of_smb;
4690         int rc;
4691
4692         rsp = (struct smb2_query_directory_rsp *)rsp_iov->iov_base;
4693
4694         switch (srch_inf->info_level) {
4695         case SMB_FIND_FILE_DIRECTORY_INFO:
4696                 info_buf_size = sizeof(FILE_DIRECTORY_INFO) - 1;
4697                 break;
4698         case SMB_FIND_FILE_ID_FULL_DIR_INFO:
4699                 info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO) - 1;
4700                 break;
4701         case SMB_FIND_FILE_POSIX_INFO:
4702                 /* note that posix payload are variable size */
4703                 info_buf_size = sizeof(struct smb2_posix_info);
4704                 break;
4705         default:
4706                 cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
4707                          srch_inf->info_level);
4708                 return -EINVAL;
4709         }
4710
4711         rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
4712                                le32_to_cpu(rsp->OutputBufferLength), rsp_iov,
4713                                info_buf_size);
4714         if (rc) {
4715                 cifs_tcon_dbg(VFS, "bad info payload");
4716                 return rc;
4717         }
4718
4719         srch_inf->unicode = true;
4720
4721         if (srch_inf->ntwrk_buf_start) {
4722                 if (srch_inf->smallBuf)
4723                         cifs_small_buf_release(srch_inf->ntwrk_buf_start);
4724                 else
4725                         cifs_buf_release(srch_inf->ntwrk_buf_start);
4726         }
4727         srch_inf->ntwrk_buf_start = (char *)rsp;
4728         srch_inf->srch_entries_start = srch_inf->last_entry =
4729                 (char *)rsp + le16_to_cpu(rsp->OutputBufferOffset);
4730         end_of_smb = rsp_iov->iov_len + (char *)rsp;
4731
4732         srch_inf->entries_in_buffer = num_entries(
4733                 srch_inf->info_level,
4734                 srch_inf->srch_entries_start,
4735                 end_of_smb,
4736                 &srch_inf->last_entry,
4737                 info_buf_size);
4738
4739         srch_inf->index_of_last_entry += srch_inf->entries_in_buffer;
4740         cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n",
4741                  srch_inf->entries_in_buffer, srch_inf->index_of_last_entry,
4742                  srch_inf->srch_entries_start, srch_inf->last_entry);
4743         if (resp_buftype == CIFS_LARGE_BUFFER)
4744                 srch_inf->smallBuf = false;
4745         else if (resp_buftype == CIFS_SMALL_BUFFER)
4746                 srch_inf->smallBuf = true;
4747         else
4748                 cifs_tcon_dbg(VFS, "Invalid search buffer type\n");
4749
4750         return 0;
4751 }
4752
4753 int
4754 SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon,
4755                      u64 persistent_fid, u64 volatile_fid, int index,
4756                      struct cifs_search_info *srch_inf)
4757 {
4758         struct smb_rqst rqst;
4759         struct kvec iov[SMB2_QUERY_DIRECTORY_IOV_SIZE];
4760         struct smb2_query_directory_rsp *rsp = NULL;
4761         int resp_buftype = CIFS_NO_BUFFER;
4762         struct kvec rsp_iov;
4763         int rc = 0;
4764         struct cifs_ses *ses = tcon->ses;
4765         struct TCP_Server_Info *server = cifs_pick_channel(ses);
4766         int flags = 0;
4767
4768         if (!ses || !(ses->server))
4769                 return -EIO;
4770
4771         if (smb3_encryption_required(tcon))
4772                 flags |= CIFS_TRANSFORM_REQ;
4773
4774         memset(&rqst, 0, sizeof(struct smb_rqst));
4775         memset(&iov, 0, sizeof(iov));
4776         rqst.rq_iov = iov;
4777         rqst.rq_nvec = SMB2_QUERY_DIRECTORY_IOV_SIZE;
4778
4779         rc = SMB2_query_directory_init(xid, tcon, server,
4780                                        &rqst, persistent_fid,
4781                                        volatile_fid, index,
4782                                        srch_inf->info_level);
4783         if (rc)
4784                 goto qdir_exit;
4785
4786         rc = cifs_send_recv(xid, ses, server,
4787                             &rqst, &resp_buftype, flags, &rsp_iov);
4788         rsp = (struct smb2_query_directory_rsp *)rsp_iov.iov_base;
4789
4790         if (rc) {
4791                 if (rc == -ENODATA &&
4792                     rsp->sync_hdr.Status == STATUS_NO_MORE_FILES) {
4793                         trace_smb3_query_dir_done(xid, persistent_fid,
4794                                 tcon->tid, tcon->ses->Suid, index, 0);
4795                         srch_inf->endOfSearch = true;
4796                         rc = 0;
4797                 } else {
4798                         trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
4799                                 tcon->ses->Suid, index, 0, rc);
4800                         cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE);
4801                 }
4802                 goto qdir_exit;
4803         }
4804
4805         rc = smb2_parse_query_directory(tcon, &rsp_iov, resp_buftype,
4806                                         srch_inf);
4807         if (rc) {
4808                 trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
4809                         tcon->ses->Suid, index, 0, rc);
4810                 goto qdir_exit;
4811         }
4812         resp_buftype = CIFS_NO_BUFFER;
4813
4814         trace_smb3_query_dir_done(xid, persistent_fid, tcon->tid,
4815                         tcon->ses->Suid, index, srch_inf->entries_in_buffer);
4816
4817 qdir_exit:
4818         SMB2_query_directory_free(&rqst);
4819         free_rsp_buf(resp_buftype, rsp);
4820         return rc;
4821 }
4822
4823 int
4824 SMB2_set_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
4825                    struct smb_rqst *rqst,
4826                    u64 persistent_fid, u64 volatile_fid, u32 pid,
4827                    u8 info_class, u8 info_type, u32 additional_info,
4828                    void **data, unsigned int *size)
4829 {
4830         struct smb2_set_info_req *req;
4831         struct kvec *iov = rqst->rq_iov;
4832         unsigned int i, total_len;
4833         int rc;
4834
4835         rc = smb2_plain_req_init(SMB2_SET_INFO, tcon, server,
4836                                  (void **) &req, &total_len);
4837         if (rc)
4838                 return rc;
4839
4840         req->sync_hdr.ProcessId = cpu_to_le32(pid);
4841         req->InfoType = info_type;
4842         req->FileInfoClass = info_class;
4843         req->PersistentFileId = persistent_fid;
4844         req->VolatileFileId = volatile_fid;
4845         req->AdditionalInformation = cpu_to_le32(additional_info);
4846
4847         req->BufferOffset =
4848                         cpu_to_le16(sizeof(struct smb2_set_info_req) - 1);
4849         req->BufferLength = cpu_to_le32(*size);
4850
4851         memcpy(req->Buffer, *data, *size);
4852         total_len += *size;
4853
4854         iov[0].iov_base = (char *)req;
4855         /* 1 for Buffer */
4856         iov[0].iov_len = total_len - 1;
4857
4858         for (i = 1; i < rqst->rq_nvec; i++) {
4859                 le32_add_cpu(&req->BufferLength, size[i]);
4860                 iov[i].iov_base = (char *)data[i];
4861                 iov[i].iov_len = size[i];
4862         }
4863
4864         return 0;
4865 }
4866
4867 void
4868 SMB2_set_info_free(struct smb_rqst *rqst)
4869 {
4870         if (rqst && rqst->rq_iov)
4871                 cifs_buf_release(rqst->rq_iov[0].iov_base); /* request */
4872 }
4873
4874 static int
4875 send_set_info(const unsigned int xid, struct cifs_tcon *tcon,
4876                u64 persistent_fid, u64 volatile_fid, u32 pid, u8 info_class,
4877                u8 info_type, u32 additional_info, unsigned int num,
4878                 void **data, unsigned int *size)
4879 {
4880         struct smb_rqst rqst;
4881         struct smb2_set_info_rsp *rsp = NULL;
4882         struct kvec *iov;
4883         struct kvec rsp_iov;
4884         int rc = 0;
4885         int resp_buftype;
4886         struct cifs_ses *ses = tcon->ses;
4887         struct TCP_Server_Info *server = cifs_pick_channel(ses);
4888         int flags = 0;
4889
4890         if (!ses || !server)
4891                 return -EIO;
4892
4893         if (!num)
4894                 return -EINVAL;
4895
4896         if (smb3_encryption_required(tcon))
4897                 flags |= CIFS_TRANSFORM_REQ;
4898
4899         iov = kmalloc_array(num, sizeof(struct kvec), GFP_KERNEL);
4900         if (!iov)
4901                 return -ENOMEM;
4902
4903         memset(&rqst, 0, sizeof(struct smb_rqst));
4904         rqst.rq_iov = iov;
4905         rqst.rq_nvec = num;
4906
4907         rc = SMB2_set_info_init(tcon, server,
4908                                 &rqst, persistent_fid, volatile_fid, pid,
4909                                 info_class, info_type, additional_info,
4910                                 data, size);
4911         if (rc) {
4912                 kfree(iov);
4913                 return rc;
4914         }
4915
4916
4917         rc = cifs_send_recv(xid, ses, server,
4918                             &rqst, &resp_buftype, flags,
4919                             &rsp_iov);
4920         SMB2_set_info_free(&rqst);
4921         rsp = (struct smb2_set_info_rsp *)rsp_iov.iov_base;
4922
4923         if (rc != 0) {
4924                 cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE);
4925                 trace_smb3_set_info_err(xid, persistent_fid, tcon->tid,
4926                                 ses->Suid, info_class, (__u32)info_type, rc);
4927         }
4928
4929         free_rsp_buf(resp_buftype, rsp);
4930         kfree(iov);
4931         return rc;
4932 }
4933
4934 int
4935 SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
4936              u64 volatile_fid, u32 pid, __le64 *eof)
4937 {
4938         struct smb2_file_eof_info info;
4939         void *data;
4940         unsigned int size;
4941
4942         info.EndOfFile = *eof;
4943
4944         data = &info;
4945         size = sizeof(struct smb2_file_eof_info);
4946
4947         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
4948                         pid, FILE_END_OF_FILE_INFORMATION, SMB2_O_INFO_FILE,
4949                         0, 1, &data, &size);
4950 }
4951
4952 int
4953 SMB2_set_acl(const unsigned int xid, struct cifs_tcon *tcon,
4954                 u64 persistent_fid, u64 volatile_fid,
4955                 struct cifs_ntsd *pnntsd, int pacllen, int aclflag)
4956 {
4957         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
4958                         current->tgid, 0, SMB2_O_INFO_SECURITY, aclflag,
4959                         1, (void **)&pnntsd, &pacllen);
4960 }
4961
4962 int
4963 SMB2_set_ea(const unsigned int xid, struct cifs_tcon *tcon,
4964             u64 persistent_fid, u64 volatile_fid,
4965             struct smb2_file_full_ea_info *buf, int len)
4966 {
4967         return send_set_info(xid, tcon, persistent_fid, volatile_fid,
4968                 current->tgid, FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE,
4969                 0, 1, (void **)&buf, &len);
4970 }
4971
4972 int
4973 SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon,
4974                   const u64 persistent_fid, const u64 volatile_fid,
4975                   __u8 oplock_level)
4976 {
4977         struct smb_rqst rqst;
4978         int rc;
4979         struct smb2_oplock_break *req = NULL;
4980         struct cifs_ses *ses = tcon->ses;
4981         struct TCP_Server_Info *server = cifs_pick_channel(ses);
4982         int flags = CIFS_OBREAK_OP;
4983         unsigned int total_len;
4984         struct kvec iov[1];
4985         struct kvec rsp_iov;
4986         int resp_buf_type;
4987
4988         cifs_dbg(FYI, "SMB2_oplock_break\n");
4989         rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
4990                                  (void **) &req, &total_len);
4991         if (rc)
4992                 return rc;
4993
4994         if (smb3_encryption_required(tcon))
4995                 flags |= CIFS_TRANSFORM_REQ;
4996
4997         req->VolatileFid = volatile_fid;
4998         req->PersistentFid = persistent_fid;
4999         req->OplockLevel = oplock_level;
5000         req->sync_hdr.CreditRequest = cpu_to_le16(1);
5001
5002         flags |= CIFS_NO_RSP_BUF;
5003
5004         iov[0].iov_base = (char *)req;
5005         iov[0].iov_len = total_len;
5006
5007         memset(&rqst, 0, sizeof(struct smb_rqst));
5008         rqst.rq_iov = iov;
5009         rqst.rq_nvec = 1;
5010
5011         rc = cifs_send_recv(xid, ses, server,
5012                             &rqst, &resp_buf_type, flags, &rsp_iov);
5013         cifs_small_buf_release(req);
5014
5015         if (rc) {
5016                 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
5017                 cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc);
5018         }
5019
5020         return rc;
5021 }
5022
5023 void
5024 smb2_copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf,
5025                              struct kstatfs *kst)
5026 {
5027         kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) *
5028                           le32_to_cpu(pfs_inf->SectorsPerAllocationUnit);
5029         kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits);
5030         kst->f_bfree  = kst->f_bavail =
5031                         le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits);
5032         return;
5033 }
5034
5035 static void
5036 copy_posix_fs_info_to_kstatfs(FILE_SYSTEM_POSIX_INFO *response_data,
5037                         struct kstatfs *kst)
5038 {
5039         kst->f_bsize = le32_to_cpu(response_data->BlockSize);
5040         kst->f_blocks = le64_to_cpu(response_data->TotalBlocks);
5041         kst->f_bfree =  le64_to_cpu(response_data->BlocksAvail);
5042         if (response_data->UserBlocksAvail == cpu_to_le64(-1))
5043                 kst->f_bavail = kst->f_bfree;
5044         else
5045                 kst->f_bavail = le64_to_cpu(response_data->UserBlocksAvail);
5046         if (response_data->TotalFileNodes != cpu_to_le64(-1))
5047                 kst->f_files = le64_to_cpu(response_data->TotalFileNodes);
5048         if (response_data->FreeFileNodes != cpu_to_le64(-1))
5049                 kst->f_ffree = le64_to_cpu(response_data->FreeFileNodes);
5050
5051         return;
5052 }
5053
5054 static int
5055 build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon,
5056                    struct TCP_Server_Info *server,
5057                    int level, int outbuf_len, u64 persistent_fid,
5058                    u64 volatile_fid)
5059 {
5060         int rc;
5061         struct smb2_query_info_req *req;
5062         unsigned int total_len;
5063
5064         cifs_dbg(FYI, "Query FSInfo level %d\n", level);
5065
5066         if ((tcon->ses == NULL) || server == NULL)
5067                 return -EIO;
5068
5069         rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
5070                                  (void **) &req, &total_len);
5071         if (rc)
5072                 return rc;
5073
5074         req->InfoType = SMB2_O_INFO_FILESYSTEM;
5075         req->FileInfoClass = level;
5076         req->PersistentFileId = persistent_fid;
5077         req->VolatileFileId = volatile_fid;
5078         /* 1 for pad */
5079         req->InputBufferOffset =
5080                         cpu_to_le16(sizeof(struct smb2_query_info_req) - 1);
5081         req->OutputBufferLength = cpu_to_le32(
5082                 outbuf_len + sizeof(struct smb2_query_info_rsp) - 1);
5083
5084         iov->iov_base = (char *)req;
5085         iov->iov_len = total_len;
5086         return 0;
5087 }
5088
5089 int
5090 SMB311_posix_qfs_info(const unsigned int xid, struct cifs_tcon *tcon,
5091               u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
5092 {
5093         struct smb_rqst rqst;
5094         struct smb2_query_info_rsp *rsp = NULL;
5095         struct kvec iov;
5096         struct kvec rsp_iov;
5097         int rc = 0;
5098         int resp_buftype;
5099         struct cifs_ses *ses = tcon->ses;
5100         struct TCP_Server_Info *server = cifs_pick_channel(ses);
5101         FILE_SYSTEM_POSIX_INFO *info = NULL;
5102         int flags = 0;
5103
5104         rc = build_qfs_info_req(&iov, tcon, server,
5105                                 FS_POSIX_INFORMATION,
5106                                 sizeof(FILE_SYSTEM_POSIX_INFO),
5107                                 persistent_fid, volatile_fid);
5108         if (rc)
5109                 return rc;
5110
5111         if (smb3_encryption_required(tcon))
5112                 flags |= CIFS_TRANSFORM_REQ;
5113
5114         memset(&rqst, 0, sizeof(struct smb_rqst));
5115         rqst.rq_iov = &iov;
5116         rqst.rq_nvec = 1;
5117
5118         rc = cifs_send_recv(xid, ses, server,
5119                             &rqst, &resp_buftype, flags, &rsp_iov);
5120         cifs_small_buf_release(iov.iov_base);
5121         if (rc) {
5122                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5123                 goto posix_qfsinf_exit;
5124         }
5125         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5126
5127         info = (FILE_SYSTEM_POSIX_INFO *)(
5128                 le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
5129         rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5130                                le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
5131                                sizeof(FILE_SYSTEM_POSIX_INFO));
5132         if (!rc)
5133                 copy_posix_fs_info_to_kstatfs(info, fsdata);
5134
5135 posix_qfsinf_exit:
5136         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5137         return rc;
5138 }
5139
5140 int
5141 SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon,
5142               u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
5143 {
5144         struct smb_rqst rqst;
5145         struct smb2_query_info_rsp *rsp = NULL;
5146         struct kvec iov;
5147         struct kvec rsp_iov;
5148         int rc = 0;
5149         int resp_buftype;
5150         struct cifs_ses *ses = tcon->ses;
5151         struct TCP_Server_Info *server = cifs_pick_channel(ses);
5152         struct smb2_fs_full_size_info *info = NULL;
5153         int flags = 0;
5154
5155         rc = build_qfs_info_req(&iov, tcon, server,
5156                                 FS_FULL_SIZE_INFORMATION,
5157                                 sizeof(struct smb2_fs_full_size_info),
5158                                 persistent_fid, volatile_fid);
5159         if (rc)
5160                 return rc;
5161
5162         if (smb3_encryption_required(tcon))
5163                 flags |= CIFS_TRANSFORM_REQ;
5164
5165         memset(&rqst, 0, sizeof(struct smb_rqst));
5166         rqst.rq_iov = &iov;
5167         rqst.rq_nvec = 1;
5168
5169         rc = cifs_send_recv(xid, ses, server,
5170                             &rqst, &resp_buftype, flags, &rsp_iov);
5171         cifs_small_buf_release(iov.iov_base);
5172         if (rc) {
5173                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5174                 goto qfsinf_exit;
5175         }
5176         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5177
5178         info = (struct smb2_fs_full_size_info *)(
5179                 le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
5180         rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5181                                le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
5182                                sizeof(struct smb2_fs_full_size_info));
5183         if (!rc)
5184                 smb2_copy_fs_info_to_kstatfs(info, fsdata);
5185
5186 qfsinf_exit:
5187         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5188         return rc;
5189 }
5190
5191 int
5192 SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon,
5193               u64 persistent_fid, u64 volatile_fid, int level)
5194 {
5195         struct smb_rqst rqst;
5196         struct smb2_query_info_rsp *rsp = NULL;
5197         struct kvec iov;
5198         struct kvec rsp_iov;
5199         int rc = 0;
5200         int resp_buftype, max_len, min_len;
5201         struct cifs_ses *ses = tcon->ses;
5202         struct TCP_Server_Info *server = cifs_pick_channel(ses);
5203         unsigned int rsp_len, offset;
5204         int flags = 0;
5205
5206         if (level == FS_DEVICE_INFORMATION) {
5207                 max_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
5208                 min_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
5209         } else if (level == FS_ATTRIBUTE_INFORMATION) {
5210                 max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO);
5211                 min_len = MIN_FS_ATTR_INFO_SIZE;
5212         } else if (level == FS_SECTOR_SIZE_INFORMATION) {
5213                 max_len = sizeof(struct smb3_fs_ss_info);
5214                 min_len = sizeof(struct smb3_fs_ss_info);
5215         } else if (level == FS_VOLUME_INFORMATION) {
5216                 max_len = sizeof(struct smb3_fs_vol_info) + MAX_VOL_LABEL_LEN;
5217                 min_len = sizeof(struct smb3_fs_vol_info);
5218         } else {
5219                 cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level);
5220                 return -EINVAL;
5221         }
5222
5223         rc = build_qfs_info_req(&iov, tcon, server,
5224                                 level, max_len,
5225                                 persistent_fid, volatile_fid);
5226         if (rc)
5227                 return rc;
5228
5229         if (smb3_encryption_required(tcon))
5230                 flags |= CIFS_TRANSFORM_REQ;
5231
5232         memset(&rqst, 0, sizeof(struct smb_rqst));
5233         rqst.rq_iov = &iov;
5234         rqst.rq_nvec = 1;
5235
5236         rc = cifs_send_recv(xid, ses, server,
5237                             &rqst, &resp_buftype, flags, &rsp_iov);
5238         cifs_small_buf_release(iov.iov_base);
5239         if (rc) {
5240                 cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5241                 goto qfsattr_exit;
5242         }
5243         rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5244
5245         rsp_len = le32_to_cpu(rsp->OutputBufferLength);
5246         offset = le16_to_cpu(rsp->OutputBufferOffset);
5247         rc = smb2_validate_iov(offset, rsp_len, &rsp_iov, min_len);
5248         if (rc)
5249                 goto qfsattr_exit;
5250
5251         if (level == FS_ATTRIBUTE_INFORMATION)
5252                 memcpy(&tcon->fsAttrInfo, offset
5253                         + (char *)rsp, min_t(unsigned int,
5254                         rsp_len, max_len));
5255         else if (level == FS_DEVICE_INFORMATION)
5256                 memcpy(&tcon->fsDevInfo, offset
5257                         + (char *)rsp, sizeof(FILE_SYSTEM_DEVICE_INFO));
5258         else if (level == FS_SECTOR_SIZE_INFORMATION) {
5259                 struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *)
5260                         (offset + (char *)rsp);
5261                 tcon->ss_flags = le32_to_cpu(ss_info->Flags);
5262                 tcon->perf_sector_size =
5263                         le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf);
5264         } else if (level == FS_VOLUME_INFORMATION) {
5265                 struct smb3_fs_vol_info *vol_info = (struct smb3_fs_vol_info *)
5266                         (offset + (char *)rsp);
5267                 tcon->vol_serial_number = vol_info->VolumeSerialNumber;
5268                 tcon->vol_create_time = vol_info->VolumeCreationTime;
5269         }
5270
5271 qfsattr_exit:
5272         free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5273         return rc;
5274 }
5275
5276 int
5277 smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon,
5278            const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
5279            const __u32 num_lock, struct smb2_lock_element *buf)
5280 {
5281         struct smb_rqst rqst;
5282         int rc = 0;
5283         struct smb2_lock_req *req = NULL;
5284         struct kvec iov[2];
5285         struct kvec rsp_iov;
5286         int resp_buf_type;
5287         unsigned int count;
5288         int flags = CIFS_NO_RSP_BUF;
5289         unsigned int total_len;
5290         struct TCP_Server_Info *server = cifs_pick_channel(tcon->ses);
5291
5292         cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock);
5293
5294         rc = smb2_plain_req_init(SMB2_LOCK, tcon, server,
5295                                  (void **) &req, &total_len);
5296         if (rc)
5297                 return rc;
5298
5299         if (smb3_encryption_required(tcon))
5300                 flags |= CIFS_TRANSFORM_REQ;
5301
5302         req->sync_hdr.ProcessId = cpu_to_le32(pid);
5303         req->LockCount = cpu_to_le16(num_lock);
5304
5305         req->PersistentFileId = persist_fid;
5306         req->VolatileFileId = volatile_fid;
5307
5308         count = num_lock * sizeof(struct smb2_lock_element);
5309
5310         iov[0].iov_base = (char *)req;
5311         iov[0].iov_len = total_len - sizeof(struct smb2_lock_element);
5312         iov[1].iov_base = (char *)buf;
5313         iov[1].iov_len = count;
5314
5315         cifs_stats_inc(&tcon->stats.cifs_stats.num_locks);
5316
5317         memset(&rqst, 0, sizeof(struct smb_rqst));
5318         rqst.rq_iov = iov;
5319         rqst.rq_nvec = 2;
5320
5321         rc = cifs_send_recv(xid, tcon->ses, server,
5322                             &rqst, &resp_buf_type, flags,
5323                             &rsp_iov);
5324         cifs_small_buf_release(req);
5325         if (rc) {
5326                 cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc);
5327                 cifs_stats_fail_inc(tcon, SMB2_LOCK_HE);
5328                 trace_smb3_lock_err(xid, persist_fid, tcon->tid,
5329                                     tcon->ses->Suid, rc);
5330         }
5331
5332         return rc;
5333 }
5334
5335 int
5336 SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon,
5337           const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
5338           const __u64 length, const __u64 offset, const __u32 lock_flags,
5339           const bool wait)
5340 {
5341         struct smb2_lock_element lock;
5342
5343         lock.Offset = cpu_to_le64(offset);
5344         lock.Length = cpu_to_le64(length);
5345         lock.Flags = cpu_to_le32(lock_flags);
5346         if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK)
5347                 lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY);
5348
5349         return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock);
5350 }
5351
5352 int
5353 SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon,
5354                  __u8 *lease_key, const __le32 lease_state)
5355 {
5356         struct smb_rqst rqst;
5357         int rc;
5358         struct smb2_lease_ack *req = NULL;
5359         struct cifs_ses *ses = tcon->ses;
5360         int flags = CIFS_OBREAK_OP;
5361         unsigned int total_len;
5362         struct kvec iov[1];
5363         struct kvec rsp_iov;
5364         int resp_buf_type;
5365         __u64 *please_key_high;
5366         __u64 *please_key_low;
5367         struct TCP_Server_Info *server = cifs_pick_channel(tcon->ses);
5368
5369         cifs_dbg(FYI, "SMB2_lease_break\n");
5370         rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
5371                                  (void **) &req, &total_len);
5372         if (rc)
5373                 return rc;
5374
5375         if (smb3_encryption_required(tcon))
5376                 flags |= CIFS_TRANSFORM_REQ;
5377
5378         req->sync_hdr.CreditRequest = cpu_to_le16(1);
5379         req->StructureSize = cpu_to_le16(36);
5380         total_len += 12;
5381
5382         memcpy(req->LeaseKey, lease_key, 16);
5383         req->LeaseState = lease_state;
5384
5385         flags |= CIFS_NO_RSP_BUF;
5386
5387         iov[0].iov_base = (char *)req;
5388         iov[0].iov_len = total_len;
5389
5390         memset(&rqst, 0, sizeof(struct smb_rqst));
5391         rqst.rq_iov = iov;
5392         rqst.rq_nvec = 1;
5393
5394         rc = cifs_send_recv(xid, ses, server,
5395                             &rqst, &resp_buf_type, flags, &rsp_iov);
5396         cifs_small_buf_release(req);
5397
5398         please_key_low = (__u64 *)lease_key;
5399         please_key_high = (__u64 *)(lease_key+8);
5400         if (rc) {
5401                 cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
5402                 trace_smb3_lease_err(le32_to_cpu(lease_state), tcon->tid,
5403                         ses->Suid, *please_key_low, *please_key_high, rc);
5404                 cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc);
5405         } else
5406                 trace_smb3_lease_done(le32_to_cpu(lease_state), tcon->tid,
5407                         ses->Suid, *please_key_low, *please_key_high);
5408
5409         return rc;
5410 }