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