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