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