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