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