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