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