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