xref: /linux/fs/smb/client/smb2pdu.c (revision 75aa4b4d557114276bb72e19a9bce5cb27b5e4b8)
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 	u16 doff = le16_to_cpu(cc->DataOffset);
2383 	u32 dlen = le32_to_cpu(cc->DataLength);
2384 	u8 *beg;
2385 
2386 	if (dlen < sizeof(__le64))
2387 		return;
2388 
2389 	beg = (u8 *)cc + doff;
2390 	memcpy(&buf->IndexNumber, beg, sizeof(__le64));
2391 	cifs_dbg(FYI, "parse query id context 0x%llx\n",
2392 		 le64_to_cpu(buf->IndexNumber));
2393 }
2394 
2395 static void
2396 parse_posix_ctxt(struct create_context *cc, struct smb2_file_all_info *info,
2397 		 struct create_posix_rsp *posix)
2398 {
2399 	u8 *beg = (u8 *)cc + le16_to_cpu(cc->DataOffset);
2400 	u32 dlen = le32_to_cpu(cc->DataLength);
2401 	u8 *end = beg + dlen;
2402 	int sid_len;
2403 	u8 *sid;
2404 
2405 	memset(posix, 0, sizeof(*posix));
2406 	if (dlen < 3 * sizeof(__le32))
2407 		return;
2408 
2409 	posix->nlink = get_unaligned_le32(beg);
2410 	posix->reparse_tag = get_unaligned_le32(beg + 4);
2411 	posix->mode = get_unaligned_le32(beg + 8);
2412 
2413 	sid = beg + 12;
2414 	sid_len = posix_info_sid_size(sid, end);
2415 	if (sid_len < 0) {
2416 		cifs_dbg(VFS, "bad owner sid in posix create response\n");
2417 		return;
2418 	}
2419 	memcpy(&posix->owner, sid, sid_len);
2420 
2421 	sid = sid + sid_len;
2422 	sid_len = posix_info_sid_size(sid, end);
2423 	if (sid_len < 0) {
2424 		cifs_dbg(VFS, "bad group sid in posix create response\n");
2425 		return;
2426 	}
2427 	memcpy(&posix->group, sid, sid_len);
2428 
2429 	cifs_dbg(FYI, "nlink=%d mode=%o reparse_tag=%x\n",
2430 		 posix->nlink, posix->mode, posix->reparse_tag);
2431 }
2432 
2433 int smb2_parse_contexts(struct TCP_Server_Info *server,
2434 			struct kvec *rsp_iov,
2435 			__u16 *epoch,
2436 			char *lease_key, __u8 *oplock,
2437 			struct smb2_file_all_info *buf,
2438 			struct create_posix_rsp *posix)
2439 {
2440 	struct smb2_create_rsp *rsp = rsp_iov->iov_base;
2441 	struct create_context *cc;
2442 	size_t rem, off, len;
2443 	size_t cc_len;
2444 	size_t doff, dlen;
2445 	size_t noff, nlen;
2446 	char *name;
2447 	static const char smb3_create_tag_posix[] = {
2448 		0x93, 0xAD, 0x25, 0x50, 0x9C,
2449 		0xB4, 0x11, 0xE7, 0xB4, 0x23, 0x83,
2450 		0xDE, 0x96, 0x8B, 0xCD, 0x7C
2451 	};
2452 
2453 	*oplock = 0;
2454 
2455 	off = le32_to_cpu(rsp->CreateContextsOffset);
2456 	rem = le32_to_cpu(rsp->CreateContextsLength);
2457 	if (check_add_overflow(off, rem, &len) || len > rsp_iov->iov_len)
2458 		return -EINVAL;
2459 	cc = (struct create_context *)((u8 *)rsp + off);
2460 
2461 	/* Initialize inode number to 0 in case no valid data in qfid context */
2462 	if (buf)
2463 		buf->IndexNumber = 0;
2464 
2465 	while (rem >= sizeof(*cc)) {
2466 		off = le32_to_cpu(cc->Next);
2467 		if (off) {
2468 			if ((off & 0x7) || off >= rem || off < sizeof(*cc))
2469 				return -EINVAL;
2470 			cc_len = off;
2471 		} else {
2472 			cc_len = rem;
2473 		}
2474 
2475 		doff = le16_to_cpu(cc->DataOffset);
2476 		dlen = le32_to_cpu(cc->DataLength);
2477 		if (doff < sizeof(*cc) ||
2478 		    check_add_overflow(doff, dlen, &len) || len > cc_len)
2479 			return -EINVAL;
2480 
2481 		noff = le16_to_cpu(cc->NameOffset);
2482 		nlen = le16_to_cpu(cc->NameLength);
2483 		if (noff < sizeof(*cc) ||
2484 		    check_add_overflow(noff, nlen, &len) || len > cc_len ||
2485 		    (dlen && len > doff))
2486 			return -EINVAL;
2487 
2488 		name = (char *)cc + noff;
2489 		switch (nlen) {
2490 		case 4:
2491 			if (dlen && !strncmp(name, SMB2_CREATE_REQUEST_LEASE, 4)) {
2492 				*oplock = server->ops->parse_lease_buf(cc, epoch,
2493 								       lease_key);
2494 			} else if (dlen && buf &&
2495 				   !strncmp(name, SMB2_CREATE_QUERY_ON_DISK_ID, 4)) {
2496 				parse_query_id_ctxt(cc, buf);
2497 			}
2498 			break;
2499 		case 16:
2500 			if (dlen && posix && !memcmp(name, smb3_create_tag_posix, 16))
2501 				parse_posix_ctxt(cc, buf, posix);
2502 			break;
2503 		default:
2504 			cifs_dbg(FYI, "%s: unhandled context (nlen=%zu dlen=%zu)\n",
2505 				 __func__, nlen, dlen);
2506 			if (IS_ENABLED(CONFIG_CIFS_DEBUG2))
2507 				cifs_dump_mem("context data: ", cc, dlen);
2508 			break;
2509 		}
2510 
2511 		off = le32_to_cpu(cc->Next);
2512 		if (!off) {
2513 			rem = 0;
2514 			break;
2515 		}
2516 		if (check_sub_overflow(rem, off, &rem))
2517 			return -EINVAL;
2518 		cc = (struct create_context *)((u8 *)cc + off);
2519 	}
2520 
2521 	if (rem)
2522 		return -EINVAL;
2523 
2524 	if (rsp->OplockLevel != SMB2_OPLOCK_LEVEL_LEASE)
2525 		*oplock = rsp->OplockLevel;
2526 
2527 	return 0;
2528 }
2529 
2530 static int
2531 add_lease_context(struct TCP_Server_Info *server,
2532 		  struct smb2_create_req *req,
2533 		  struct kvec *iov,
2534 		  unsigned int *num_iovec,
2535 		  u8 *lease_key,
2536 		  __u8 *oplock,
2537 		  u8 *parent_lease_key,
2538 		  __le32 flags)
2539 {
2540 	unsigned int num = *num_iovec;
2541 
2542 	iov[num].iov_base = server->ops->create_lease_buf(lease_key, *oplock,
2543 							  parent_lease_key, flags);
2544 	if (iov[num].iov_base == NULL)
2545 		return -ENOMEM;
2546 	iov[num].iov_len = server->vals->create_lease_size;
2547 	req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
2548 	*num_iovec = num + 1;
2549 	return 0;
2550 }
2551 
2552 static struct create_durable_req_v2 *
2553 create_durable_v2_buf(struct cifs_open_parms *oparms)
2554 {
2555 	struct cifs_fid *pfid = oparms->fid;
2556 	struct create_durable_req_v2 *buf;
2557 
2558 	buf = kzalloc_obj(struct create_durable_req_v2);
2559 	if (!buf)
2560 		return NULL;
2561 
2562 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2563 					(struct create_durable_req_v2, dcontext));
2564 	buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_context_v2_req));
2565 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2566 				(struct create_durable_req_v2, Name));
2567 	buf->ccontext.NameLength = cpu_to_le16(4);
2568 
2569 	/*
2570 	 * NB: Handle timeout defaults to 0, which allows server to choose
2571 	 * (most servers default to 120 seconds) and most clients default to 0.
2572 	 * This can be overridden at mount ("handletimeout=") if the user wants
2573 	 * a different persistent (or resilient) handle timeout for all opens
2574 	 * on a particular SMB3 mount.
2575 	 */
2576 	buf->dcontext.Timeout = cpu_to_le32(oparms->tcon->handle_timeout);
2577 	buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2578 
2579 	/* for replay, we should not overwrite the existing create guid */
2580 	if (!oparms->replay) {
2581 		generate_random_uuid(buf->dcontext.CreateGuid);
2582 		memcpy(pfid->create_guid, buf->dcontext.CreateGuid, 16);
2583 	} else
2584 		memcpy(buf->dcontext.CreateGuid, pfid->create_guid, 16);
2585 
2586 	/* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DH2Q" */
2587 	buf->Name[0] = 'D';
2588 	buf->Name[1] = 'H';
2589 	buf->Name[2] = '2';
2590 	buf->Name[3] = 'Q';
2591 	return buf;
2592 }
2593 
2594 static struct create_durable_handle_reconnect_v2 *
2595 create_reconnect_durable_v2_buf(struct cifs_fid *fid)
2596 {
2597 	struct create_durable_handle_reconnect_v2 *buf;
2598 
2599 	buf = kzalloc_obj(struct create_durable_handle_reconnect_v2);
2600 	if (!buf)
2601 		return NULL;
2602 
2603 	buf->ccontext.DataOffset =
2604 		cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
2605 				     dcontext));
2606 	buf->ccontext.DataLength =
2607 		cpu_to_le32(sizeof(struct durable_reconnect_context_v2));
2608 	buf->ccontext.NameOffset =
2609 		cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
2610 			    Name));
2611 	buf->ccontext.NameLength = cpu_to_le16(4);
2612 
2613 	buf->dcontext.Fid.PersistentFileId = fid->persistent_fid;
2614 	buf->dcontext.Fid.VolatileFileId = fid->volatile_fid;
2615 	buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2616 	memcpy(buf->dcontext.CreateGuid, fid->create_guid, 16);
2617 
2618 	/* SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 is "DH2C" */
2619 	buf->Name[0] = 'D';
2620 	buf->Name[1] = 'H';
2621 	buf->Name[2] = '2';
2622 	buf->Name[3] = 'C';
2623 	return buf;
2624 }
2625 
2626 static int
2627 add_durable_v2_context(struct kvec *iov, unsigned int *num_iovec,
2628 		    struct cifs_open_parms *oparms)
2629 {
2630 	unsigned int num = *num_iovec;
2631 
2632 	iov[num].iov_base = create_durable_v2_buf(oparms);
2633 	if (iov[num].iov_base == NULL)
2634 		return -ENOMEM;
2635 	iov[num].iov_len = sizeof(struct create_durable_req_v2);
2636 	*num_iovec = num + 1;
2637 	return 0;
2638 }
2639 
2640 static int
2641 add_durable_reconnect_v2_context(struct kvec *iov, unsigned int *num_iovec,
2642 		    struct cifs_open_parms *oparms)
2643 {
2644 	unsigned int num = *num_iovec;
2645 
2646 	/* indicate that we don't need to relock the file */
2647 	oparms->reconnect = false;
2648 
2649 	iov[num].iov_base = create_reconnect_durable_v2_buf(oparms->fid);
2650 	if (iov[num].iov_base == NULL)
2651 		return -ENOMEM;
2652 	iov[num].iov_len = sizeof(struct create_durable_handle_reconnect_v2);
2653 	*num_iovec = num + 1;
2654 	return 0;
2655 }
2656 
2657 static int
2658 add_durable_context(struct kvec *iov, unsigned int *num_iovec,
2659 		    struct cifs_open_parms *oparms, bool use_persistent)
2660 {
2661 	unsigned int num = *num_iovec;
2662 
2663 	if (use_persistent) {
2664 		if (oparms->reconnect)
2665 			return add_durable_reconnect_v2_context(iov, num_iovec,
2666 								oparms);
2667 		else
2668 			return add_durable_v2_context(iov, num_iovec, oparms);
2669 	}
2670 
2671 	if (oparms->reconnect) {
2672 		iov[num].iov_base = create_reconnect_durable_buf(oparms->fid);
2673 		/* indicate that we don't need to relock the file */
2674 		oparms->reconnect = false;
2675 	} else
2676 		iov[num].iov_base = create_durable_buf();
2677 	if (iov[num].iov_base == NULL)
2678 		return -ENOMEM;
2679 	iov[num].iov_len = sizeof(create_durable_req_t);
2680 	*num_iovec = num + 1;
2681 	return 0;
2682 }
2683 
2684 /* See MS-SMB2 2.2.13.2.7 */
2685 static struct crt_twarp_ctxt *
2686 create_twarp_buf(__u64 timewarp)
2687 {
2688 	struct crt_twarp_ctxt *buf;
2689 
2690 	buf = kzalloc_obj(struct crt_twarp_ctxt);
2691 	if (!buf)
2692 		return NULL;
2693 
2694 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2695 					(struct crt_twarp_ctxt, Timestamp));
2696 	buf->ccontext.DataLength = cpu_to_le32(8);
2697 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2698 				(struct crt_twarp_ctxt, Name));
2699 	buf->ccontext.NameLength = cpu_to_le16(4);
2700 	/* SMB2_CREATE_TIMEWARP_TOKEN is "TWrp" */
2701 	buf->Name[0] = 'T';
2702 	buf->Name[1] = 'W';
2703 	buf->Name[2] = 'r';
2704 	buf->Name[3] = 'p';
2705 	buf->Timestamp = cpu_to_le64(timewarp);
2706 	return buf;
2707 }
2708 
2709 /* See MS-SMB2 2.2.13.2.7 */
2710 static int
2711 add_twarp_context(struct kvec *iov, unsigned int *num_iovec, __u64 timewarp)
2712 {
2713 	unsigned int num = *num_iovec;
2714 
2715 	iov[num].iov_base = create_twarp_buf(timewarp);
2716 	if (iov[num].iov_base == NULL)
2717 		return -ENOMEM;
2718 	iov[num].iov_len = sizeof(struct crt_twarp_ctxt);
2719 	*num_iovec = num + 1;
2720 	return 0;
2721 }
2722 
2723 /* See http://technet.microsoft.com/en-us/library/hh509017(v=ws.10).aspx */
2724 static void setup_owner_group_sids(char *buf)
2725 {
2726 	struct owner_group_sids *sids = (struct owner_group_sids *)buf;
2727 
2728 	/* Populate the user ownership fields S-1-5-88-1 */
2729 	sids->owner.Revision = 1;
2730 	sids->owner.NumAuth = 3;
2731 	sids->owner.Authority[5] = 5;
2732 	sids->owner.SubAuthorities[0] = cpu_to_le32(88);
2733 	sids->owner.SubAuthorities[1] = cpu_to_le32(1);
2734 	sids->owner.SubAuthorities[2] = cpu_to_le32(current_fsuid().val);
2735 
2736 	/* Populate the group ownership fields S-1-5-88-2 */
2737 	sids->group.Revision = 1;
2738 	sids->group.NumAuth = 3;
2739 	sids->group.Authority[5] = 5;
2740 	sids->group.SubAuthorities[0] = cpu_to_le32(88);
2741 	sids->group.SubAuthorities[1] = cpu_to_le32(2);
2742 	sids->group.SubAuthorities[2] = cpu_to_le32(current_fsgid().val);
2743 
2744 	cifs_dbg(FYI, "owner S-1-5-88-1-%d, group S-1-5-88-2-%d\n", current_fsuid().val, current_fsgid().val);
2745 }
2746 
2747 /* See MS-SMB2 2.2.13.2.2 and MS-DTYP 2.4.6 */
2748 static struct crt_sd_ctxt *
2749 create_sd_buf(umode_t mode, bool set_owner, unsigned int *len)
2750 {
2751 	struct crt_sd_ctxt *buf;
2752 	__u8 *ptr, *aclptr;
2753 	unsigned int acelen, acl_size, ace_count;
2754 	unsigned int owner_offset = 0;
2755 	unsigned int group_offset = 0;
2756 	struct smb3_acl acl = {};
2757 
2758 	*len = round_up(sizeof(struct crt_sd_ctxt) + (sizeof(struct smb_ace) * 4), 8);
2759 
2760 	if (set_owner) {
2761 		/* sizeof(struct owner_group_sids) is already multiple of 8 so no need to round */
2762 		*len += sizeof(struct owner_group_sids);
2763 	}
2764 
2765 	buf = kzalloc(*len, GFP_KERNEL);
2766 	if (buf == NULL)
2767 		return buf;
2768 
2769 	ptr = (__u8 *)&buf[1];
2770 	if (set_owner) {
2771 		/* offset fields are from beginning of security descriptor not of create context */
2772 		owner_offset = ptr - (__u8 *)&buf->sd;
2773 		buf->sd.OffsetOwner = cpu_to_le32(owner_offset);
2774 		group_offset = owner_offset + offsetof(struct owner_group_sids, group);
2775 		buf->sd.OffsetGroup = cpu_to_le32(group_offset);
2776 
2777 		setup_owner_group_sids(ptr);
2778 		ptr += sizeof(struct owner_group_sids);
2779 	} else {
2780 		buf->sd.OffsetOwner = 0;
2781 		buf->sd.OffsetGroup = 0;
2782 	}
2783 
2784 	buf->ccontext.DataOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, sd));
2785 	buf->ccontext.NameOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, Name));
2786 	buf->ccontext.NameLength = cpu_to_le16(4);
2787 	/* SMB2_CREATE_SD_BUFFER_TOKEN is "SecD" */
2788 	buf->Name[0] = 'S';
2789 	buf->Name[1] = 'e';
2790 	buf->Name[2] = 'c';
2791 	buf->Name[3] = 'D';
2792 	buf->sd.Revision = 1;  /* Must be one see MS-DTYP 2.4.6 */
2793 
2794 	/*
2795 	 * ACL is "self relative" ie ACL is stored in contiguous block of memory
2796 	 * and "DP" ie the DACL is present
2797 	 */
2798 	buf->sd.Control = cpu_to_le16(ACL_CONTROL_SR | ACL_CONTROL_DP);
2799 
2800 	/* offset owner, group and Sbz1 and SACL are all zero */
2801 	buf->sd.OffsetDacl = cpu_to_le32(ptr - (__u8 *)&buf->sd);
2802 	/* Ship the ACL for now. we will copy it into buf later. */
2803 	aclptr = ptr;
2804 	ptr += sizeof(struct smb3_acl);
2805 
2806 	/* create one ACE to hold the mode embedded in reserved special SID */
2807 	acelen = setup_special_mode_ACE((struct smb_ace *)ptr, false, (__u64)mode);
2808 	ptr += acelen;
2809 	acl_size = acelen + sizeof(struct smb3_acl);
2810 	ace_count = 1;
2811 
2812 	if (set_owner) {
2813 		/* we do not need to reallocate buffer to add the two more ACEs. plenty of space */
2814 		acelen = setup_special_user_owner_ACE((struct smb_ace *)ptr);
2815 		ptr += acelen;
2816 		acl_size += acelen;
2817 		ace_count += 1;
2818 	}
2819 
2820 	/* and one more ACE to allow access for authenticated users */
2821 	acelen = setup_authusers_ACE((struct smb_ace *)ptr);
2822 	ptr += acelen;
2823 	acl_size += acelen;
2824 	ace_count += 1;
2825 
2826 	acl.AclRevision = ACL_REVISION; /* See 2.4.4.1 of MS-DTYP */
2827 	acl.AclSize = cpu_to_le16(acl_size);
2828 	acl.AceCount = cpu_to_le16(ace_count);
2829 	/* acl.Sbz1 and Sbz2 MBZ so are not set here, but initialized above */
2830 	memcpy(aclptr, &acl, sizeof(struct smb3_acl));
2831 
2832 	buf->ccontext.DataLength = cpu_to_le32(ptr - (__u8 *)&buf->sd);
2833 	*len = round_up((unsigned int)(ptr - (__u8 *)buf), 8);
2834 
2835 	return buf;
2836 }
2837 
2838 static int
2839 add_sd_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode, bool set_owner)
2840 {
2841 	unsigned int num = *num_iovec;
2842 	unsigned int len = 0;
2843 
2844 	iov[num].iov_base = create_sd_buf(mode, set_owner, &len);
2845 	if (iov[num].iov_base == NULL)
2846 		return -ENOMEM;
2847 	iov[num].iov_len = len;
2848 	*num_iovec = num + 1;
2849 	return 0;
2850 }
2851 
2852 static struct crt_query_id_ctxt *
2853 create_query_id_buf(void)
2854 {
2855 	struct crt_query_id_ctxt *buf;
2856 
2857 	buf = kzalloc_obj(struct crt_query_id_ctxt);
2858 	if (!buf)
2859 		return NULL;
2860 
2861 	buf->ccontext.DataOffset = cpu_to_le16(0);
2862 	buf->ccontext.DataLength = cpu_to_le32(0);
2863 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2864 				(struct crt_query_id_ctxt, Name));
2865 	buf->ccontext.NameLength = cpu_to_le16(4);
2866 	/* SMB2_CREATE_QUERY_ON_DISK_ID is "QFid" */
2867 	buf->Name[0] = 'Q';
2868 	buf->Name[1] = 'F';
2869 	buf->Name[2] = 'i';
2870 	buf->Name[3] = 'd';
2871 	return buf;
2872 }
2873 
2874 /* See MS-SMB2 2.2.13.2.9 */
2875 static int
2876 add_query_id_context(struct kvec *iov, unsigned int *num_iovec)
2877 {
2878 	unsigned int num = *num_iovec;
2879 
2880 	iov[num].iov_base = create_query_id_buf();
2881 	if (iov[num].iov_base == NULL)
2882 		return -ENOMEM;
2883 	iov[num].iov_len = sizeof(struct crt_query_id_ctxt);
2884 	*num_iovec = num + 1;
2885 	return 0;
2886 }
2887 
2888 static void add_ea_context(struct cifs_open_parms *oparms,
2889 			   struct kvec *rq_iov, unsigned int *num_iovs)
2890 {
2891 	struct kvec *iov = oparms->ea_cctx;
2892 
2893 	if (iov && iov->iov_base && iov->iov_len) {
2894 		rq_iov[(*num_iovs)++] = *iov;
2895 		memset(iov, 0, sizeof(*iov));
2896 	}
2897 }
2898 
2899 static int
2900 alloc_path_with_tree_prefix(__le16 **out_path, int *out_size, int *out_len,
2901 			    const char *treename, const __le16 *path)
2902 {
2903 	int treename_len, path_len;
2904 	struct nls_table *cp;
2905 	const __le16 sep[] = {cpu_to_le16('\\'), cpu_to_le16(0x0000)};
2906 
2907 	/*
2908 	 * skip leading "\\"
2909 	 */
2910 	treename_len = strlen(treename);
2911 	if (treename_len < 2 || !(treename[0] == '\\' && treename[1] == '\\'))
2912 		return -EINVAL;
2913 
2914 	treename += 2;
2915 	treename_len -= 2;
2916 
2917 	path_len = UniStrnlen((wchar_t *)path, PATH_MAX);
2918 
2919 	/* make room for one path separator only if @path isn't empty */
2920 	*out_len = treename_len + (path[0] ? 1 : 0) + path_len;
2921 
2922 	/*
2923 	 * final path needs to be 8-byte aligned as specified in
2924 	 * MS-SMB2 2.2.13 SMB2 CREATE Request.
2925 	 */
2926 	*out_size = round_up(*out_len * sizeof(__le16), 8);
2927 	*out_path = kzalloc(*out_size + sizeof(__le16) /* null */, GFP_KERNEL);
2928 	if (!*out_path)
2929 		return -ENOMEM;
2930 
2931 	cp = load_nls_default();
2932 	cifs_strtoUTF16(*out_path, treename, treename_len, cp);
2933 
2934 	/* Do not append the separator if the path is empty */
2935 	if (path[0] != cpu_to_le16(0x0000)) {
2936 		UniStrcat((wchar_t *)*out_path, (wchar_t *)sep);
2937 		UniStrcat((wchar_t *)*out_path, (wchar_t *)path);
2938 	}
2939 
2940 	unload_nls(cp);
2941 
2942 	return 0;
2943 }
2944 
2945 int smb311_posix_mkdir(const unsigned int xid, struct inode *inode,
2946 			       umode_t mode, struct cifs_tcon *tcon,
2947 			       const char *full_path,
2948 			       struct cifs_sb_info *cifs_sb)
2949 {
2950 	struct smb_rqst rqst;
2951 	struct smb2_create_req *req;
2952 	struct smb2_create_rsp *rsp = NULL;
2953 	struct cifs_ses *ses = tcon->ses;
2954 	struct kvec iov[3]; /* make sure at least one for each open context */
2955 	struct kvec rsp_iov = {NULL, 0};
2956 	int resp_buftype;
2957 	int uni_path_len;
2958 	__le16 *copy_path = NULL;
2959 	int copy_size;
2960 	int rc = 0;
2961 	unsigned int n_iov = 2;
2962 	__u32 file_attributes = 0;
2963 	char *pc_buf = NULL;
2964 	int flags = 0;
2965 	unsigned int total_len;
2966 	__le16 *utf16_path = NULL;
2967 	struct TCP_Server_Info *server;
2968 	int retries = 0, cur_sleep = 0;
2969 
2970 replay_again:
2971 	/* reinitialize for possible replay */
2972 	pc_buf = NULL;
2973 	flags = 0;
2974 	n_iov = 2;
2975 	server = cifs_pick_channel(ses);
2976 
2977 	cifs_dbg(FYI, "mkdir\n");
2978 
2979 	/* resource #1: path allocation */
2980 	utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
2981 	if (!utf16_path)
2982 		return -ENOMEM;
2983 
2984 	if (!ses || !server) {
2985 		rc = smb_EIO(smb_eio_trace_null_pointers);
2986 		goto err_free_path;
2987 	}
2988 
2989 	/* resource #2: request */
2990 	rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
2991 				 (void **) &req, &total_len);
2992 	if (rc)
2993 		goto err_free_path;
2994 
2995 
2996 	if (smb3_encryption_required(tcon))
2997 		flags |= CIFS_TRANSFORM_REQ;
2998 
2999 	req->ImpersonationLevel = IL_IMPERSONATION;
3000 	req->DesiredAccess = cpu_to_le32(FILE_WRITE_ATTRIBUTES);
3001 	/* File attributes ignored on open (used in create though) */
3002 	req->FileAttributes = cpu_to_le32(file_attributes);
3003 	req->ShareAccess = FILE_SHARE_ALL_LE;
3004 	req->CreateDisposition = cpu_to_le32(FILE_CREATE);
3005 	req->CreateOptions = cpu_to_le32(CREATE_NOT_FILE);
3006 
3007 	iov[0].iov_base = (char *)req;
3008 	/* -1 since last byte is buf[0] which is sent below (path) */
3009 	iov[0].iov_len = total_len - 1;
3010 
3011 	req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
3012 
3013 	/* [MS-SMB2] 2.2.13 NameOffset:
3014 	 * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
3015 	 * the SMB2 header, the file name includes a prefix that will
3016 	 * be processed during DFS name normalization as specified in
3017 	 * section 3.3.5.9. Otherwise, the file name is relative to
3018 	 * the share that is identified by the TreeId in the SMB2
3019 	 * header.
3020 	 */
3021 	if (tcon->share_flags & SHI1005_FLAGS_DFS) {
3022 		int name_len;
3023 
3024 		req->hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
3025 		rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
3026 						 &name_len,
3027 						 tcon->tree_name, utf16_path);
3028 		if (rc)
3029 			goto err_free_req;
3030 
3031 		req->NameLength = cpu_to_le16(name_len * 2);
3032 		uni_path_len = copy_size;
3033 		/* free before overwriting resource */
3034 		kfree(utf16_path);
3035 		utf16_path = copy_path;
3036 	} else {
3037 		uni_path_len = (2 * UniStrnlen((wchar_t *)utf16_path, PATH_MAX)) + 2;
3038 		/* MUST set path len (NameLength) to 0 opening root of share */
3039 		req->NameLength = cpu_to_le16(uni_path_len - 2);
3040 		if (uni_path_len % 8 != 0) {
3041 			copy_size = roundup(uni_path_len, 8);
3042 			copy_path = kzalloc(copy_size, GFP_KERNEL);
3043 			if (!copy_path) {
3044 				rc = -ENOMEM;
3045 				goto err_free_req;
3046 			}
3047 			memcpy((char *)copy_path, (const char *)utf16_path,
3048 			       uni_path_len);
3049 			uni_path_len = copy_size;
3050 			/* free before overwriting resource */
3051 			kfree(utf16_path);
3052 			utf16_path = copy_path;
3053 		}
3054 	}
3055 
3056 	iov[1].iov_len = uni_path_len;
3057 	iov[1].iov_base = utf16_path;
3058 	req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_NONE;
3059 
3060 	if (tcon->posix_extensions) {
3061 		/* resource #3: posix buf */
3062 		rc = add_posix_context(iov, &n_iov, mode);
3063 		if (rc)
3064 			goto err_free_req;
3065 		req->CreateContextsOffset = cpu_to_le32(
3066 			sizeof(struct smb2_create_req) +
3067 			iov[1].iov_len);
3068 		le32_add_cpu(&req->CreateContextsLength, iov[n_iov-1].iov_len);
3069 		pc_buf = iov[n_iov-1].iov_base;
3070 	}
3071 
3072 
3073 	memset(&rqst, 0, sizeof(struct smb_rqst));
3074 	rqst.rq_iov = iov;
3075 	rqst.rq_nvec = n_iov;
3076 
3077 	/* no need to inc num_remote_opens because we close it just below */
3078 	trace_smb3_posix_mkdir_enter(xid, tcon->tid, ses->Suid, full_path, CREATE_NOT_FILE,
3079 				    FILE_WRITE_ATTRIBUTES);
3080 
3081 	if (retries) {
3082 		/* Back-off before retry */
3083 		if (cur_sleep)
3084 			msleep(cur_sleep);
3085 		smb2_set_replay(server, &rqst);
3086 	}
3087 
3088 	/* resource #4: response buffer */
3089 	rc = cifs_send_recv(xid, ses, server,
3090 			    &rqst, &resp_buftype, flags, &rsp_iov);
3091 	if (rc) {
3092 		cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
3093 		trace_smb3_posix_mkdir_err(xid, tcon->tid, ses->Suid,
3094 					   CREATE_NOT_FILE,
3095 					   FILE_WRITE_ATTRIBUTES, rc);
3096 		goto err_free_rsp_buf;
3097 	}
3098 
3099 	/*
3100 	 * Although unlikely to be possible for rsp to be null and rc not set,
3101 	 * adding check below is slightly safer long term (and quiets Coverity
3102 	 * warning)
3103 	 */
3104 	rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
3105 	if (rsp == NULL) {
3106 		rc = smb_EIO(smb_eio_trace_mkdir_no_rsp);
3107 		kfree(pc_buf);
3108 		goto err_free_req;
3109 	}
3110 
3111 	trace_smb3_posix_mkdir_done(xid, rsp->PersistentFileId, tcon->tid, ses->Suid,
3112 				    CREATE_NOT_FILE, FILE_WRITE_ATTRIBUTES,
3113 				    rsp->OplockLevel);
3114 
3115 	SMB2_close(xid, tcon, rsp->PersistentFileId, rsp->VolatileFileId);
3116 
3117 	/* Eventually save off posix specific response info and timestamps */
3118 
3119 err_free_rsp_buf:
3120 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3121 	kfree(pc_buf);
3122 err_free_req:
3123 	cifs_small_buf_release(req);
3124 err_free_path:
3125 	kfree(utf16_path);
3126 
3127 	if (is_replayable_error(rc) &&
3128 	    smb2_should_replay(tcon, &retries, &cur_sleep))
3129 		goto replay_again;
3130 
3131 	return rc;
3132 }
3133 
3134 int
3135 SMB2_open_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3136 	       struct smb_rqst *rqst, __u8 *oplock,
3137 	       struct cifs_open_parms *oparms, __le16 *path)
3138 {
3139 	struct smb2_create_req *req;
3140 	unsigned int n_iov = 2;
3141 	__u32 file_attributes = 0;
3142 	int copy_size;
3143 	int uni_path_len;
3144 	unsigned int total_len;
3145 	struct kvec *iov = rqst->rq_iov;
3146 	__le16 *copy_path;
3147 	int rc;
3148 
3149 	rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
3150 				 (void **) &req, &total_len);
3151 	if (rc)
3152 		return rc;
3153 
3154 	iov[0].iov_base = (char *)req;
3155 	/* -1 since last byte is buf[0] which is sent below (path) */
3156 	iov[0].iov_len = total_len - 1;
3157 
3158 	if (oparms->create_options & CREATE_OPTION_READONLY)
3159 		file_attributes |= ATTR_READONLY;
3160 	if (oparms->create_options & CREATE_OPTION_SPECIAL)
3161 		file_attributes |= ATTR_SYSTEM;
3162 
3163 	req->ImpersonationLevel = IL_IMPERSONATION;
3164 	req->DesiredAccess = cpu_to_le32(oparms->desired_access);
3165 	/* File attributes ignored on open (used in create though) */
3166 	req->FileAttributes = cpu_to_le32(file_attributes);
3167 	req->ShareAccess = FILE_SHARE_ALL_LE;
3168 
3169 	req->CreateDisposition = cpu_to_le32(oparms->disposition);
3170 	req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK);
3171 	req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
3172 
3173 	/* [MS-SMB2] 2.2.13 NameOffset:
3174 	 * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
3175 	 * the SMB2 header, the file name includes a prefix that will
3176 	 * be processed during DFS name normalization as specified in
3177 	 * section 3.3.5.9. Otherwise, the file name is relative to
3178 	 * the share that is identified by the TreeId in the SMB2
3179 	 * header.
3180 	 */
3181 	if (tcon->share_flags & SHI1005_FLAGS_DFS) {
3182 		int name_len;
3183 
3184 		req->hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
3185 		rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
3186 						 &name_len,
3187 						 tcon->tree_name, path);
3188 		if (rc)
3189 			return rc;
3190 		req->NameLength = cpu_to_le16(name_len * 2);
3191 		uni_path_len = copy_size;
3192 		path = copy_path;
3193 	} else {
3194 		uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
3195 		/* MUST set path len (NameLength) to 0 opening root of share */
3196 		req->NameLength = cpu_to_le16(uni_path_len - 2);
3197 		copy_size = round_up(uni_path_len, 8);
3198 		copy_path = kzalloc(copy_size, GFP_KERNEL);
3199 		if (!copy_path)
3200 			return -ENOMEM;
3201 		memcpy((char *)copy_path, (const char *)path,
3202 		       uni_path_len);
3203 		uni_path_len = copy_size;
3204 		path = copy_path;
3205 	}
3206 
3207 	iov[1].iov_len = uni_path_len;
3208 	iov[1].iov_base = path;
3209 
3210 	if ((!server->oplocks) || (tcon->no_lease))
3211 		*oplock = SMB2_OPLOCK_LEVEL_NONE;
3212 
3213 	if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) ||
3214 	    *oplock == SMB2_OPLOCK_LEVEL_NONE)
3215 		req->RequestedOplockLevel = *oplock;
3216 	else if (!(server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING) &&
3217 		  (oparms->create_options & CREATE_NOT_FILE))
3218 		req->RequestedOplockLevel = *oplock; /* no srv lease support */
3219 	else {
3220 		rc = add_lease_context(server, req, iov, &n_iov,
3221 				       oparms->fid->lease_key, oplock,
3222 				       oparms->fid->parent_lease_key,
3223 				       oparms->lease_flags);
3224 		if (rc)
3225 			return rc;
3226 	}
3227 
3228 	if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) {
3229 		rc = add_durable_context(iov, &n_iov, oparms,
3230 					tcon->use_persistent);
3231 		if (rc)
3232 			return rc;
3233 	}
3234 
3235 	if (tcon->posix_extensions) {
3236 		rc = add_posix_context(iov, &n_iov, oparms->mode);
3237 		if (rc)
3238 			return rc;
3239 	}
3240 
3241 	if (tcon->snapshot_time) {
3242 		cifs_dbg(FYI, "adding snapshot context\n");
3243 		rc = add_twarp_context(iov, &n_iov, tcon->snapshot_time);
3244 		if (rc)
3245 			return rc;
3246 	}
3247 
3248 	if ((oparms->disposition != FILE_OPEN) && (oparms->cifs_sb)) {
3249 		unsigned int sbflags = cifs_sb_flags(oparms->cifs_sb);
3250 		bool set_mode;
3251 		bool set_owner;
3252 
3253 		if ((sbflags & CIFS_MOUNT_MODE_FROM_SID) &&
3254 		    oparms->mode != ACL_NO_MODE) {
3255 			set_mode = true;
3256 		} else {
3257 			set_mode = false;
3258 			oparms->mode = ACL_NO_MODE;
3259 		}
3260 
3261 		set_owner = sbflags & CIFS_MOUNT_UID_FROM_ACL;
3262 		if (set_owner | set_mode) {
3263 			cifs_dbg(FYI, "add sd with mode 0x%x\n", oparms->mode);
3264 			rc = add_sd_context(iov, &n_iov, oparms->mode, set_owner);
3265 			if (rc)
3266 				return rc;
3267 		}
3268 	}
3269 
3270 	add_query_id_context(iov, &n_iov);
3271 	add_ea_context(oparms, iov, &n_iov);
3272 
3273 	if (n_iov > 2) {
3274 		/*
3275 		 * We have create contexts behind iov[1] (the file
3276 		 * name), point at them from the main create request
3277 		 */
3278 		req->CreateContextsOffset = cpu_to_le32(
3279 			sizeof(struct smb2_create_req) +
3280 			iov[1].iov_len);
3281 		req->CreateContextsLength = 0;
3282 
3283 		for (unsigned int i = 2; i < (n_iov-1); i++) {
3284 			struct kvec *v = &iov[i];
3285 			size_t len = v->iov_len;
3286 			struct create_context *cctx =
3287 				(struct create_context *)v->iov_base;
3288 
3289 			cctx->Next = cpu_to_le32(len);
3290 			le32_add_cpu(&req->CreateContextsLength, len);
3291 		}
3292 		le32_add_cpu(&req->CreateContextsLength,
3293 			     iov[n_iov-1].iov_len);
3294 	}
3295 
3296 	rqst->rq_nvec = n_iov;
3297 	return 0;
3298 }
3299 
3300 /* rq_iov[0] is the request and is released by cifs_small_buf_release().
3301  * All other vectors are freed by kfree().
3302  */
3303 void
3304 SMB2_open_free(struct smb_rqst *rqst)
3305 {
3306 	int i;
3307 
3308 	if (rqst && rqst->rq_iov) {
3309 		cifs_small_buf_release(rqst->rq_iov[0].iov_base);
3310 		for (i = 1; i < rqst->rq_nvec; i++)
3311 			if (rqst->rq_iov[i].iov_base != smb2_padding)
3312 				kfree(rqst->rq_iov[i].iov_base);
3313 	}
3314 }
3315 
3316 int
3317 SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
3318 	  __u8 *oplock, struct cifs_open_info_data *buf,
3319 	  struct create_posix_rsp *posix,
3320 	  struct kvec *err_iov, int *buftype)
3321 {
3322 	struct smb_rqst rqst;
3323 	struct smb2_create_rsp *rsp = NULL;
3324 	struct cifs_tcon *tcon = oparms->tcon;
3325 	struct cifs_ses *ses = tcon->ses;
3326 	struct TCP_Server_Info *server;
3327 	struct kvec iov[SMB2_CREATE_IOV_SIZE];
3328 	struct kvec rsp_iov = {NULL, 0};
3329 	int resp_buftype = CIFS_NO_BUFFER;
3330 	int rc = 0;
3331 	int flags = 0;
3332 	int retries = 0, cur_sleep = 0;
3333 	struct smb2_file_all_info *file_info = buf ? &buf->fi : NULL;
3334 
3335 replay_again:
3336 	/* reinitialize for possible replay */
3337 	resp_buftype = CIFS_NO_BUFFER;
3338 	memset(&rsp_iov, 0, sizeof(rsp_iov));
3339 	flags = 0;
3340 	server = cifs_pick_channel(ses);
3341 	oparms->replay = !!(retries);
3342 
3343 	cifs_dbg(FYI, "create/open\n");
3344 	if (!ses || !server)
3345 		return smb_EIO(smb_eio_trace_null_pointers);
3346 
3347 	if (smb3_encryption_required(tcon))
3348 		flags |= CIFS_TRANSFORM_REQ;
3349 
3350 	memset(&rqst, 0, sizeof(struct smb_rqst));
3351 	memset(&iov, 0, sizeof(iov));
3352 	rqst.rq_iov = iov;
3353 	rqst.rq_nvec = SMB2_CREATE_IOV_SIZE;
3354 
3355 	rc = SMB2_open_init(tcon, server,
3356 			    &rqst, oplock, oparms, path);
3357 	if (rc)
3358 		goto creat_exit;
3359 
3360 	trace_smb3_open_enter(xid, tcon->tid, tcon->ses->Suid, oparms->path,
3361 		oparms->create_options, oparms->desired_access);
3362 
3363 	if (retries) {
3364 		/* Back-off before retry */
3365 		if (cur_sleep)
3366 			msleep(cur_sleep);
3367 		smb2_set_replay(server, &rqst);
3368 	}
3369 
3370 	rc = cifs_send_recv(xid, ses, server,
3371 			    &rqst, &resp_buftype, flags,
3372 			    &rsp_iov);
3373 	rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
3374 
3375 	if (rc != 0) {
3376 		cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
3377 		if (err_iov && rsp) {
3378 			*err_iov = rsp_iov;
3379 			*buftype = resp_buftype;
3380 			resp_buftype = CIFS_NO_BUFFER;
3381 			rsp = NULL;
3382 		}
3383 		trace_smb3_open_err(xid, tcon->tid, ses->Suid,
3384 				    oparms->create_options, oparms->desired_access, rc);
3385 		if (rc == -EREMCHG) {
3386 			pr_warn_once("server share %s deleted\n",
3387 				     tcon->tree_name);
3388 			tcon->need_reconnect = true;
3389 		}
3390 		goto creat_exit;
3391 	} else if (rsp == NULL) /* unlikely to happen, but safer to check */
3392 		goto creat_exit;
3393 
3394 	atomic_inc(&tcon->num_remote_opens);
3395 	oparms->fid->persistent_fid = rsp->PersistentFileId;
3396 	oparms->fid->volatile_fid = rsp->VolatileFileId;
3397 	oparms->fid->access = oparms->desired_access;
3398 #ifdef CONFIG_CIFS_DEBUG2
3399 	oparms->fid->mid = le64_to_cpu(rsp->hdr.MessageId);
3400 #endif /* CIFS_DEBUG2 */
3401 
3402 	if (file_info) {
3403 		buf->contains_posix_file_info = false;
3404 		file_info->CreationTime = rsp->CreationTime;
3405 		file_info->LastAccessTime = rsp->LastAccessTime;
3406 		file_info->LastWriteTime = rsp->LastWriteTime;
3407 		file_info->ChangeTime = rsp->ChangeTime;
3408 		file_info->AllocationSize = rsp->AllocationSize;
3409 		file_info->EndOfFile = rsp->EndofFile;
3410 		file_info->Attributes = rsp->FileAttributes;
3411 		file_info->NumberOfLinks = cpu_to_le32(1);
3412 		buf->unknown_nlink = true;
3413 		file_info->DeletePending = 0; /* successful open = not delete pending */
3414 	}
3415 
3416 
3417 	rc = smb2_parse_contexts(server, &rsp_iov, &oparms->fid->epoch,
3418 				 oparms->fid->lease_key, oplock, file_info, posix);
3419 	if (rc)
3420 		SMB2_close(xid, tcon, oparms->fid->persistent_fid,
3421 			   oparms->fid->volatile_fid);
3422 
3423 	trace_smb3_open_done(xid, rsp->PersistentFileId, tcon->tid, ses->Suid,
3424 			     oparms->create_options, oparms->desired_access,
3425 			     *oplock);
3426 creat_exit:
3427 	SMB2_open_free(&rqst);
3428 	free_rsp_buf(resp_buftype, rsp);
3429 
3430 	if (is_replayable_error(rc) &&
3431 	    smb2_should_replay(tcon, &retries, &cur_sleep))
3432 		goto replay_again;
3433 
3434 	return rc;
3435 }
3436 
3437 int
3438 SMB2_ioctl_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3439 		struct smb_rqst *rqst,
3440 		u64 persistent_fid, u64 volatile_fid, u32 opcode,
3441 		char *in_data, u32 indatalen,
3442 		__u32 max_response_size)
3443 {
3444 	struct smb2_ioctl_req *req;
3445 	struct kvec *iov = rqst->rq_iov;
3446 	unsigned int total_len;
3447 	int rc;
3448 	char *in_data_buf;
3449 
3450 	rc = smb2_ioctl_req_init(opcode, tcon, server,
3451 				 (void **) &req, &total_len);
3452 	if (rc)
3453 		return rc;
3454 
3455 	if (indatalen) {
3456 		/*
3457 		 * indatalen is usually small at a couple of bytes max, so
3458 		 * just allocate through generic pool
3459 		 */
3460 		in_data_buf = kmemdup(in_data, indatalen, GFP_NOFS);
3461 		if (!in_data_buf) {
3462 			cifs_small_buf_release(req);
3463 			return -ENOMEM;
3464 		}
3465 	}
3466 
3467 	req->CtlCode = cpu_to_le32(opcode);
3468 	req->PersistentFileId = persistent_fid;
3469 	req->VolatileFileId = volatile_fid;
3470 
3471 	iov[0].iov_base = (char *)req;
3472 	/*
3473 	 * If no input data, the size of ioctl struct in
3474 	 * protocol spec still includes a 1 byte data buffer,
3475 	 * but if input data passed to ioctl, we do not
3476 	 * want to double count this, so we do not send
3477 	 * the dummy one byte of data in iovec[0] if sending
3478 	 * input data (in iovec[1]).
3479 	 */
3480 	if (indatalen) {
3481 		req->InputCount = cpu_to_le32(indatalen);
3482 		/* do not set InputOffset if no input data */
3483 		req->InputOffset =
3484 		       cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer));
3485 		rqst->rq_nvec = 2;
3486 		iov[0].iov_len = total_len - 1;
3487 		iov[1].iov_base = in_data_buf;
3488 		iov[1].iov_len = indatalen;
3489 	} else {
3490 		rqst->rq_nvec = 1;
3491 		iov[0].iov_len = total_len;
3492 	}
3493 
3494 	req->OutputOffset = 0;
3495 	req->OutputCount = 0; /* MBZ */
3496 
3497 	/*
3498 	 * In most cases max_response_size is set to 16K (CIFSMaxBufSize)
3499 	 * We Could increase default MaxOutputResponse, but that could require
3500 	 * more credits. Windows typically sets this smaller, but for some
3501 	 * ioctls it may be useful to allow server to send more. No point
3502 	 * limiting what the server can send as long as fits in one credit
3503 	 * We can not handle more than CIFS_MAX_BUF_SIZE yet but may want
3504 	 * to increase this limit up in the future.
3505 	 * Note that for snapshot queries that servers like Azure expect that
3506 	 * the first query be minimal size (and just used to get the number/size
3507 	 * of previous versions) so response size must be specified as EXACTLY
3508 	 * sizeof(struct snapshot_array) which is 16 when rounded up to multiple
3509 	 * of eight bytes.  Currently that is the only case where we set max
3510 	 * response size smaller.
3511 	 */
3512 	req->MaxOutputResponse = cpu_to_le32(max_response_size);
3513 	req->hdr.CreditCharge =
3514 		cpu_to_le16(DIV_ROUND_UP(max(indatalen, max_response_size),
3515 					 SMB2_MAX_BUFFER_SIZE));
3516 	/* always an FSCTL (for now) */
3517 	req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL);
3518 
3519 	/* validate negotiate request must be signed - see MS-SMB2 3.2.5.5 */
3520 	if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO)
3521 		req->hdr.Flags |= SMB2_FLAGS_SIGNED;
3522 
3523 	return 0;
3524 }
3525 
3526 void
3527 SMB2_ioctl_free(struct smb_rqst *rqst)
3528 {
3529 	int i;
3530 
3531 	if (rqst && rqst->rq_iov) {
3532 		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3533 		for (i = 1; i < rqst->rq_nvec; i++)
3534 			if (rqst->rq_iov[i].iov_base != smb2_padding)
3535 				kfree(rqst->rq_iov[i].iov_base);
3536 	}
3537 }
3538 
3539 
3540 /*
3541  *	SMB2 IOCTL is used for both IOCTLs and FSCTLs
3542  */
3543 int
3544 SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
3545 	   u64 volatile_fid, u32 opcode, char *in_data, u32 indatalen,
3546 	   u32 max_out_data_len, char **out_data,
3547 	   u32 *plen /* returned data len */)
3548 {
3549 	struct smb_rqst rqst;
3550 	struct smb2_ioctl_rsp *rsp = NULL;
3551 	struct cifs_ses *ses;
3552 	struct TCP_Server_Info *server;
3553 	struct kvec iov[SMB2_IOCTL_IOV_SIZE];
3554 	struct kvec rsp_iov = {NULL, 0};
3555 	int resp_buftype = CIFS_NO_BUFFER;
3556 	int rc = 0;
3557 	int flags = 0;
3558 	int retries = 0, cur_sleep = 0;
3559 
3560 	if (!tcon)
3561 		return smb_EIO(smb_eio_trace_null_pointers);
3562 
3563 	ses = tcon->ses;
3564 	if (!ses)
3565 		return smb_EIO(smb_eio_trace_null_pointers);
3566 
3567 replay_again:
3568 	/* reinitialize for possible replay */
3569 	resp_buftype = CIFS_NO_BUFFER;
3570 	memset(&rsp_iov, 0, sizeof(rsp_iov));
3571 	flags = 0;
3572 	server = cifs_pick_channel(ses);
3573 
3574 	if (!server)
3575 		return smb_EIO(smb_eio_trace_null_pointers);
3576 
3577 	cifs_dbg(FYI, "SMB2 IOCTL\n");
3578 
3579 	if (out_data != NULL)
3580 		*out_data = NULL;
3581 
3582 	/* zero out returned data len, in case of error */
3583 	if (plen)
3584 		*plen = 0;
3585 
3586 	if (smb3_encryption_required(tcon))
3587 		flags |= CIFS_TRANSFORM_REQ;
3588 
3589 	memset(&rqst, 0, sizeof(struct smb_rqst));
3590 	memset(&iov, 0, sizeof(iov));
3591 	rqst.rq_iov = iov;
3592 	rqst.rq_nvec = SMB2_IOCTL_IOV_SIZE;
3593 
3594 	rc = SMB2_ioctl_init(tcon, server,
3595 			     &rqst, persistent_fid, volatile_fid, opcode,
3596 			     in_data, indatalen, max_out_data_len);
3597 	if (rc)
3598 		goto ioctl_exit;
3599 
3600 	if (retries) {
3601 		/* Back-off before retry */
3602 		if (cur_sleep)
3603 			msleep(cur_sleep);
3604 		smb2_set_replay(server, &rqst);
3605 	}
3606 
3607 	rc = cifs_send_recv(xid, ses, server,
3608 			    &rqst, &resp_buftype, flags,
3609 			    &rsp_iov);
3610 	rsp = (struct smb2_ioctl_rsp *)rsp_iov.iov_base;
3611 
3612 	if (rc != 0)
3613 		trace_smb3_fsctl_err(xid, persistent_fid, tcon->tid,
3614 				ses->Suid, 0, opcode, rc);
3615 
3616 	if ((rc != 0) && (rc != -EINVAL) && (rc != -E2BIG)) {
3617 		cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3618 		goto ioctl_exit;
3619 	} else if (rc == -EINVAL) {
3620 		if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) &&
3621 		    (opcode != FSCTL_SRV_COPYCHUNK)) {
3622 			cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3623 			goto ioctl_exit;
3624 		}
3625 	} else if (rc == -E2BIG) {
3626 		if (opcode != FSCTL_QUERY_ALLOCATED_RANGES) {
3627 			cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3628 			goto ioctl_exit;
3629 		}
3630 	}
3631 
3632 	/* check if caller wants to look at return data or just return rc */
3633 	if ((plen == NULL) || (out_data == NULL))
3634 		goto ioctl_exit;
3635 
3636 	/*
3637 	 * Although unlikely to be possible for rsp to be null and rc not set,
3638 	 * adding check below is slightly safer long term (and quiets Coverity
3639 	 * warning)
3640 	 */
3641 	if (rsp == NULL) {
3642 		rc = smb_EIO(smb_eio_trace_ioctl_no_rsp);
3643 		goto ioctl_exit;
3644 	}
3645 
3646 	*plen = le32_to_cpu(rsp->OutputCount);
3647 
3648 	/* We check for obvious errors in the output buffer length and offset */
3649 	if (*plen == 0)
3650 		goto ioctl_exit; /* server returned no data */
3651 	else if (*plen > rsp_iov.iov_len || *plen > 0xFF00) {
3652 		cifs_tcon_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen);
3653 		rc = smb_EIO2(smb_eio_trace_ioctl_data_len, *plen, rsp_iov.iov_len);
3654 		*plen = 0;
3655 		goto ioctl_exit;
3656 	}
3657 
3658 	u32 outoff = le32_to_cpu(rsp->OutputOffset);
3659 
3660 	if (rsp_iov.iov_len - *plen < outoff) {
3661 		cifs_tcon_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n",
3662 			      *plen, outoff);
3663 		rc = smb_EIO2(smb_eio_trace_ioctl_out_off, rsp_iov.iov_len - *plen, outoff);
3664 		*plen = 0;
3665 		goto ioctl_exit;
3666 	}
3667 
3668 	*out_data = kmemdup((char *)rsp + le32_to_cpu(rsp->OutputOffset),
3669 			    *plen, GFP_KERNEL);
3670 	if (*out_data == NULL) {
3671 		rc = -ENOMEM;
3672 		goto ioctl_exit;
3673 	}
3674 
3675 ioctl_exit:
3676 	SMB2_ioctl_free(&rqst);
3677 	free_rsp_buf(resp_buftype, rsp);
3678 
3679 	if (is_replayable_error(rc) &&
3680 	    smb2_should_replay(tcon, &retries, &cur_sleep))
3681 		goto replay_again;
3682 
3683 	return rc;
3684 }
3685 
3686 /*
3687  *   Individual callers to ioctl worker function follow
3688  */
3689 
3690 int
3691 SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
3692 		     u64 persistent_fid, u64 volatile_fid,
3693 		     __u16 compression_state)
3694 {
3695 	int rc;
3696 	struct  compress_ioctl fsctl_input;
3697 	char *ret_data = NULL;
3698 
3699 	fsctl_input.CompressionState = cpu_to_le16(compression_state);
3700 
3701 	rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
3702 			FSCTL_SET_COMPRESSION,
3703 			(char *)&fsctl_input /* data input */,
3704 			2 /* in data len */, CIFSMaxBufSize /* max out data */,
3705 			&ret_data /* out data */, NULL);
3706 
3707 	cifs_dbg(FYI, "set compression rc %d\n", rc);
3708 
3709 	return rc;
3710 }
3711 
3712 int
3713 SMB2_close_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3714 		struct smb_rqst *rqst,
3715 		u64 persistent_fid, u64 volatile_fid, bool query_attrs)
3716 {
3717 	struct smb2_close_req *req;
3718 	struct kvec *iov = rqst->rq_iov;
3719 	unsigned int total_len;
3720 	int rc;
3721 
3722 	rc = smb2_plain_req_init(SMB2_CLOSE, tcon, server,
3723 				 (void **) &req, &total_len);
3724 	if (rc)
3725 		return rc;
3726 
3727 	req->PersistentFileId = persistent_fid;
3728 	req->VolatileFileId = volatile_fid;
3729 	if (query_attrs)
3730 		req->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
3731 	else
3732 		req->Flags = 0;
3733 	iov[0].iov_base = (char *)req;
3734 	iov[0].iov_len = total_len;
3735 
3736 	return 0;
3737 }
3738 
3739 void
3740 SMB2_close_free(struct smb_rqst *rqst)
3741 {
3742 	if (rqst && rqst->rq_iov)
3743 		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3744 }
3745 
3746 int
3747 __SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3748 	     u64 persistent_fid, u64 volatile_fid,
3749 	     struct smb2_file_network_open_info *pbuf)
3750 {
3751 	struct smb_rqst rqst;
3752 	struct smb2_close_rsp *rsp = NULL;
3753 	struct cifs_ses *ses = tcon->ses;
3754 	struct TCP_Server_Info *server;
3755 	struct kvec iov[1];
3756 	struct kvec rsp_iov;
3757 	int resp_buftype = CIFS_NO_BUFFER;
3758 	int rc = 0;
3759 	int flags = 0;
3760 	bool query_attrs = false;
3761 	int retries = 0, cur_sleep = 0;
3762 
3763 replay_again:
3764 	/* reinitialize for possible replay */
3765 	resp_buftype = CIFS_NO_BUFFER;
3766 	memset(&rsp_iov, 0, sizeof(rsp_iov));
3767 	flags = 0;
3768 	query_attrs = false;
3769 	server = cifs_pick_channel(ses);
3770 
3771 	cifs_dbg(FYI, "Close\n");
3772 
3773 	if (!ses || !server)
3774 		return smb_EIO(smb_eio_trace_null_pointers);
3775 
3776 	if (smb3_encryption_required(tcon))
3777 		flags |= CIFS_TRANSFORM_REQ;
3778 
3779 	memset(&rqst, 0, sizeof(struct smb_rqst));
3780 	memset(&iov, 0, sizeof(iov));
3781 	rqst.rq_iov = iov;
3782 	rqst.rq_nvec = 1;
3783 
3784 	/* check if need to ask server to return timestamps in close response */
3785 	if (pbuf)
3786 		query_attrs = true;
3787 
3788 	trace_smb3_close_enter(xid, persistent_fid, tcon->tid, ses->Suid);
3789 	rc = SMB2_close_init(tcon, server,
3790 			     &rqst, persistent_fid, volatile_fid,
3791 			     query_attrs);
3792 	if (rc)
3793 		goto close_exit;
3794 
3795 	if (retries) {
3796 		/* Back-off before retry */
3797 		if (cur_sleep)
3798 			msleep(cur_sleep);
3799 		smb2_set_replay(server, &rqst);
3800 	}
3801 
3802 	rc = cifs_send_recv(xid, ses, server,
3803 			    &rqst, &resp_buftype, flags, &rsp_iov);
3804 	rsp = (struct smb2_close_rsp *)rsp_iov.iov_base;
3805 
3806 	if (rc != 0) {
3807 		cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
3808 		trace_smb3_close_err(xid, persistent_fid, tcon->tid, ses->Suid,
3809 				     rc);
3810 		goto close_exit;
3811 	} else {
3812 		trace_smb3_close_done(xid, persistent_fid, tcon->tid,
3813 				      ses->Suid);
3814 		if (pbuf)
3815 			memcpy(&pbuf->network_open_info,
3816 			       &rsp->network_open_info,
3817 			       sizeof(pbuf->network_open_info));
3818 		atomic_dec(&tcon->num_remote_opens);
3819 	}
3820 
3821 close_exit:
3822 	SMB2_close_free(&rqst);
3823 	free_rsp_buf(resp_buftype, rsp);
3824 
3825 	/* retry close in a worker thread if this one is interrupted */
3826 	if (is_interrupt_error(rc)) {
3827 		int tmp_rc;
3828 
3829 		tmp_rc = smb2_handle_cancelled_close(tcon, persistent_fid,
3830 						     volatile_fid);
3831 		if (tmp_rc)
3832 			cifs_dbg(VFS, "handle cancelled close fid 0x%llx returned error %d\n",
3833 				 persistent_fid, tmp_rc);
3834 	}
3835 
3836 	if (is_replayable_error(rc) &&
3837 	    smb2_should_replay(tcon, &retries, &cur_sleep))
3838 		goto replay_again;
3839 
3840 	return rc;
3841 }
3842 
3843 int
3844 SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3845 		u64 persistent_fid, u64 volatile_fid)
3846 {
3847 	return __SMB2_close(xid, tcon, persistent_fid, volatile_fid, NULL);
3848 }
3849 
3850 int
3851 smb2_validate_iov(unsigned int offset, unsigned int buffer_length,
3852 		  struct kvec *iov, unsigned int min_buf_size)
3853 {
3854 	unsigned int smb_len = iov->iov_len;
3855 	char *end_of_smb = smb_len + (char *)iov->iov_base;
3856 	char *begin_of_buf = offset + (char *)iov->iov_base;
3857 	char *end_of_buf = begin_of_buf + buffer_length;
3858 
3859 
3860 	if (buffer_length < min_buf_size) {
3861 		cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n",
3862 			 buffer_length, min_buf_size);
3863 		return -EINVAL;
3864 	}
3865 
3866 	/* check if beyond RFC1001 maximum length */
3867 	if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
3868 		cifs_dbg(VFS, "buffer length %d or smb length %d too large\n",
3869 			 buffer_length, smb_len);
3870 		return -EINVAL;
3871 	}
3872 
3873 	if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
3874 		cifs_dbg(VFS, "Invalid server response, bad offset to data\n");
3875 		return -EINVAL;
3876 	}
3877 
3878 	return 0;
3879 }
3880 
3881 /*
3882  * If SMB buffer fields are valid, copy into temporary buffer to hold result.
3883  * Caller must free buffer.
3884  */
3885 int
3886 smb2_validate_and_copy_iov(unsigned int offset, unsigned int buffer_length,
3887 			   struct kvec *iov, unsigned int minbufsize,
3888 			   char *data)
3889 {
3890 	char *begin_of_buf = offset + (char *)iov->iov_base;
3891 	int rc;
3892 
3893 	if (!data)
3894 		return -EINVAL;
3895 
3896 	rc = smb2_validate_iov(offset, buffer_length, iov, minbufsize);
3897 	if (rc)
3898 		return rc;
3899 
3900 	memcpy(data, begin_of_buf, minbufsize);
3901 
3902 	return 0;
3903 }
3904 
3905 int
3906 SMB2_query_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3907 		     struct smb_rqst *rqst,
3908 		     u64 persistent_fid, u64 volatile_fid,
3909 		     u8 info_class, u8 info_type, u32 additional_info,
3910 		     size_t output_len, size_t input_len, void *input)
3911 {
3912 	struct smb2_query_info_req *req;
3913 	struct kvec *iov = rqst->rq_iov;
3914 	unsigned int total_len;
3915 	size_t len;
3916 	int rc;
3917 
3918 	if (unlikely(check_add_overflow(input_len, sizeof(*req), &len) ||
3919 		     len > CIFSMaxBufSize))
3920 		return -EINVAL;
3921 
3922 	rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
3923 				 (void **) &req, &total_len);
3924 	if (rc)
3925 		return rc;
3926 
3927 	req->InfoType = info_type;
3928 	req->FileInfoClass = info_class;
3929 	req->PersistentFileId = persistent_fid;
3930 	req->VolatileFileId = volatile_fid;
3931 	req->AdditionalInformation = cpu_to_le32(additional_info);
3932 
3933 	req->OutputBufferLength = cpu_to_le32(output_len);
3934 	if (input_len) {
3935 		req->InputBufferLength = cpu_to_le32(input_len);
3936 		/* total_len for smb query request never close to le16 max */
3937 		req->InputBufferOffset = cpu_to_le16(total_len - 1);
3938 		memcpy(req->Buffer, input, input_len);
3939 	}
3940 
3941 	iov[0].iov_base = (char *)req;
3942 	/* 1 for Buffer */
3943 	iov[0].iov_len = len;
3944 	return 0;
3945 }
3946 
3947 void
3948 SMB2_query_info_free(struct smb_rqst *rqst)
3949 {
3950 	if (rqst && rqst->rq_iov)
3951 		cifs_buf_release(rqst->rq_iov[0].iov_base); /* request */
3952 }
3953 
3954 static int
3955 query_info(const unsigned int xid, struct cifs_tcon *tcon,
3956 	   u64 persistent_fid, u64 volatile_fid, u8 info_class, u8 info_type,
3957 	   u32 additional_info, size_t output_len, size_t min_len, void **data,
3958 		u32 *dlen)
3959 {
3960 	struct smb_rqst rqst;
3961 	struct smb2_query_info_rsp *rsp = NULL;
3962 	struct kvec iov[1];
3963 	struct kvec rsp_iov;
3964 	int rc = 0;
3965 	int resp_buftype = CIFS_NO_BUFFER;
3966 	struct cifs_ses *ses = tcon->ses;
3967 	struct TCP_Server_Info *server;
3968 	int flags = 0;
3969 	bool allocated = false;
3970 	int retries = 0, cur_sleep = 0;
3971 
3972 	cifs_dbg(FYI, "Query Info\n");
3973 
3974 	if (!ses)
3975 		return smb_EIO(smb_eio_trace_null_pointers);
3976 
3977 replay_again:
3978 	/* reinitialize for possible replay */
3979 	resp_buftype = CIFS_NO_BUFFER;
3980 	memset(&rsp_iov, 0, sizeof(rsp_iov));
3981 	flags = 0;
3982 	allocated = false;
3983 	server = cifs_pick_channel(ses);
3984 
3985 	if (!server)
3986 		return smb_EIO(smb_eio_trace_null_pointers);
3987 
3988 	if (smb3_encryption_required(tcon))
3989 		flags |= CIFS_TRANSFORM_REQ;
3990 
3991 	memset(&rqst, 0, sizeof(struct smb_rqst));
3992 	memset(&iov, 0, sizeof(iov));
3993 	rqst.rq_iov = iov;
3994 	rqst.rq_nvec = 1;
3995 
3996 	rc = SMB2_query_info_init(tcon, server,
3997 				  &rqst, persistent_fid, volatile_fid,
3998 				  info_class, info_type, additional_info,
3999 				  output_len, 0, NULL);
4000 	if (rc)
4001 		goto qinf_exit;
4002 
4003 	trace_smb3_query_info_enter(xid, persistent_fid, tcon->tid,
4004 				    ses->Suid, info_class, (__u32)info_type);
4005 
4006 	if (retries) {
4007 		/* Back-off before retry */
4008 		if (cur_sleep)
4009 			msleep(cur_sleep);
4010 		smb2_set_replay(server, &rqst);
4011 	}
4012 
4013 	rc = cifs_send_recv(xid, ses, server,
4014 			    &rqst, &resp_buftype, flags, &rsp_iov);
4015 	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
4016 
4017 	if (rc) {
4018 		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
4019 		trace_smb3_query_info_err(xid, persistent_fid, tcon->tid,
4020 				ses->Suid, info_class, (__u32)info_type, rc);
4021 		goto qinf_exit;
4022 	}
4023 
4024 	trace_smb3_query_info_done(xid, persistent_fid, tcon->tid,
4025 				ses->Suid, info_class, (__u32)info_type);
4026 
4027 	if (dlen) {
4028 		*dlen = le32_to_cpu(rsp->OutputBufferLength);
4029 		if (!*data) {
4030 			*data = kmalloc(*dlen, GFP_KERNEL);
4031 			if (!*data) {
4032 				cifs_tcon_dbg(VFS,
4033 					"Error %d allocating memory for acl\n",
4034 					rc);
4035 				*dlen = 0;
4036 				rc = -ENOMEM;
4037 				goto qinf_exit;
4038 			}
4039 			allocated = true;
4040 		}
4041 	}
4042 
4043 	rc = smb2_validate_and_copy_iov(le16_to_cpu(rsp->OutputBufferOffset),
4044 					le32_to_cpu(rsp->OutputBufferLength),
4045 					&rsp_iov, dlen ? *dlen : min_len, *data);
4046 	if (rc && allocated) {
4047 		kfree(*data);
4048 		*data = NULL;
4049 		*dlen = 0;
4050 	}
4051 
4052 qinf_exit:
4053 	SMB2_query_info_free(&rqst);
4054 	free_rsp_buf(resp_buftype, rsp);
4055 
4056 	if (is_replayable_error(rc) &&
4057 	    smb2_should_replay(tcon, &retries, &cur_sleep))
4058 		goto replay_again;
4059 
4060 	return rc;
4061 }
4062 
4063 int SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
4064 	u64 persistent_fid, u64 volatile_fid, struct smb2_file_all_info *data)
4065 {
4066 	return query_info(xid, tcon, persistent_fid, volatile_fid,
4067 			  FILE_ALL_INFORMATION, SMB2_O_INFO_FILE, 0,
4068 			  sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
4069 			  sizeof(struct smb2_file_all_info), (void **)&data,
4070 			  NULL);
4071 }
4072 
4073 int
4074 SMB2_query_acl(const unsigned int xid, struct cifs_tcon *tcon,
4075 	       u64 persistent_fid, u64 volatile_fid,
4076 	       void **data, u32 *plen, u32 extra_info)
4077 {
4078 	*plen = 0;
4079 
4080 	return query_info(xid, tcon, persistent_fid, volatile_fid,
4081 			  0, SMB2_O_INFO_SECURITY, extra_info,
4082 			  SMB2_MAX_BUFFER_SIZE, MIN_SEC_DESC_LEN, data, plen);
4083 }
4084 
4085 int
4086 SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
4087 		 u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
4088 {
4089 	return query_info(xid, tcon, persistent_fid, volatile_fid,
4090 			  FILE_INTERNAL_INFORMATION, SMB2_O_INFO_FILE, 0,
4091 			  sizeof(struct smb2_file_internal_info),
4092 			  sizeof(struct smb2_file_internal_info),
4093 			  (void **)&uniqueid, NULL);
4094 }
4095 
4096 /*
4097  * CHANGE_NOTIFY Request is sent to get notifications on changes to a directory
4098  * See MS-SMB2 2.2.35 and 2.2.36
4099  */
4100 
4101 static int
4102 SMB2_notify_init(const unsigned int xid, struct smb_rqst *rqst,
4103 		 struct cifs_tcon *tcon, struct TCP_Server_Info *server,
4104 		 u64 persistent_fid, u64 volatile_fid,
4105 		 u32 completion_filter, bool watch_tree)
4106 {
4107 	struct smb2_change_notify_req *req;
4108 	struct kvec *iov = rqst->rq_iov;
4109 	unsigned int total_len;
4110 	int rc;
4111 
4112 	rc = smb2_plain_req_init(SMB2_CHANGE_NOTIFY, tcon, server,
4113 				 (void **) &req, &total_len);
4114 	if (rc)
4115 		return rc;
4116 
4117 	req->PersistentFileId = persistent_fid;
4118 	req->VolatileFileId = volatile_fid;
4119 	/* See note 354 of MS-SMB2, 64K max */
4120 	req->OutputBufferLength =
4121 		cpu_to_le32(SMB2_MAX_BUFFER_SIZE - MAX_SMB2_HDR_SIZE);
4122 	req->CompletionFilter = cpu_to_le32(completion_filter);
4123 	if (watch_tree)
4124 		req->Flags = cpu_to_le16(SMB2_WATCH_TREE);
4125 	else
4126 		req->Flags = 0;
4127 
4128 	iov[0].iov_base = (char *)req;
4129 	iov[0].iov_len = total_len;
4130 
4131 	return 0;
4132 }
4133 
4134 int
4135 SMB2_change_notify(const unsigned int xid, struct cifs_tcon *tcon,
4136 		u64 persistent_fid, u64 volatile_fid, bool watch_tree,
4137 		u32 completion_filter, u32 max_out_data_len, char **out_data,
4138 		u32 *plen /* returned data len */)
4139 {
4140 	struct cifs_ses *ses = tcon->ses;
4141 	struct TCP_Server_Info *server;
4142 	struct smb_rqst rqst;
4143 	struct smb2_change_notify_rsp *smb_rsp;
4144 	struct kvec iov[1];
4145 	struct kvec rsp_iov = {NULL, 0};
4146 	int resp_buftype = CIFS_NO_BUFFER;
4147 	int flags = 0;
4148 	int rc = 0;
4149 	int retries = 0, cur_sleep = 0;
4150 
4151 replay_again:
4152 	/* reinitialize for possible replay */
4153 	resp_buftype = CIFS_NO_BUFFER;
4154 	memset(&rsp_iov, 0, sizeof(rsp_iov));
4155 	flags = 0;
4156 	server = cifs_pick_channel(ses);
4157 
4158 	cifs_dbg(FYI, "change notify\n");
4159 	if (!ses || !server)
4160 		return smb_EIO(smb_eio_trace_null_pointers);
4161 
4162 	if (smb3_encryption_required(tcon))
4163 		flags |= CIFS_TRANSFORM_REQ;
4164 
4165 	memset(&rqst, 0, sizeof(struct smb_rqst));
4166 	memset(&iov, 0, sizeof(iov));
4167 	if (plen)
4168 		*plen = 0;
4169 
4170 	rqst.rq_iov = iov;
4171 	rqst.rq_nvec = 1;
4172 
4173 	rc = SMB2_notify_init(xid, &rqst, tcon, server,
4174 			      persistent_fid, volatile_fid,
4175 			      completion_filter, watch_tree);
4176 	if (rc)
4177 		goto cnotify_exit;
4178 
4179 	trace_smb3_notify_enter(xid, persistent_fid, tcon->tid, ses->Suid,
4180 				(u8)watch_tree, completion_filter);
4181 
4182 	if (retries) {
4183 		/* Back-off before retry */
4184 		if (cur_sleep)
4185 			msleep(cur_sleep);
4186 		smb2_set_replay(server, &rqst);
4187 	}
4188 
4189 	rc = cifs_send_recv(xid, ses, server,
4190 			    &rqst, &resp_buftype, flags, &rsp_iov);
4191 
4192 	if (rc != 0) {
4193 		cifs_stats_fail_inc(tcon, SMB2_CHANGE_NOTIFY_HE);
4194 		trace_smb3_notify_err(xid, persistent_fid, tcon->tid, ses->Suid,
4195 				(u8)watch_tree, completion_filter, rc);
4196 	} else {
4197 		trace_smb3_notify_done(xid, persistent_fid, tcon->tid,
4198 			ses->Suid, (u8)watch_tree, completion_filter);
4199 		/* validate that notify information is plausible */
4200 		if ((rsp_iov.iov_base == NULL) ||
4201 		    (rsp_iov.iov_len < sizeof(struct smb2_change_notify_rsp) + 1))
4202 			goto cnotify_exit;
4203 
4204 		smb_rsp = (struct smb2_change_notify_rsp *)rsp_iov.iov_base;
4205 
4206 		rc = smb2_validate_iov(le16_to_cpu(smb_rsp->OutputBufferOffset),
4207 				le32_to_cpu(smb_rsp->OutputBufferLength),
4208 				&rsp_iov,
4209 				sizeof(struct file_notify_information));
4210 		if (rc)
4211 			goto cnotify_exit;
4212 
4213 		*out_data = kmemdup((char *)smb_rsp + le16_to_cpu(smb_rsp->OutputBufferOffset),
4214 				le32_to_cpu(smb_rsp->OutputBufferLength), GFP_KERNEL);
4215 		if (*out_data == NULL) {
4216 			rc = -ENOMEM;
4217 			goto cnotify_exit;
4218 		} else if (plen)
4219 			*plen = le32_to_cpu(smb_rsp->OutputBufferLength);
4220 	}
4221 
4222  cnotify_exit:
4223 	if (rqst.rq_iov)
4224 		cifs_small_buf_release(rqst.rq_iov[0].iov_base); /* request */
4225 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4226 
4227 	if (is_replayable_error(rc) &&
4228 	    smb2_should_replay(tcon, &retries, &cur_sleep))
4229 		goto replay_again;
4230 
4231 	return rc;
4232 }
4233 
4234 
4235 
4236 /*
4237  * This is a no-op for now. We're not really interested in the reply, but
4238  * rather in the fact that the server sent one and that server->lstrp
4239  * gets updated.
4240  *
4241  * FIXME: maybe we should consider checking that the reply matches request?
4242  */
4243 static void
4244 smb2_echo_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid)
4245 {
4246 	struct smb2_echo_rsp *rsp = (struct smb2_echo_rsp *)mid->resp_buf;
4247 	struct cifs_credits credits = { .value = 0, .instance = 0 };
4248 
4249 	if (mid->mid_state == MID_RESPONSE_RECEIVED
4250 	    || mid->mid_state == MID_RESPONSE_MALFORMED) {
4251 		credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4252 		credits.instance = server->reconnect_instance;
4253 	}
4254 
4255 	release_mid(server, mid);
4256 	add_credits(server, &credits, CIFS_ECHO_OP);
4257 }
4258 
4259 static void cifs_renegotiate_iosize(struct TCP_Server_Info *server,
4260 				    struct cifs_tcon *tcon)
4261 {
4262 	struct cifs_sb_info *cifs_sb;
4263 
4264 	if (server == NULL || tcon == NULL)
4265 		return;
4266 
4267 	spin_lock(&tcon->sb_list_lock);
4268 	list_for_each_entry(cifs_sb, &tcon->cifs_sb_list, tcon_sb_link)
4269 		cifs_negotiate_iosize(server, cifs_sb->ctx, tcon);
4270 	spin_unlock(&tcon->sb_list_lock);
4271 }
4272 
4273 void smb2_reconnect_server(struct work_struct *work)
4274 {
4275 	struct TCP_Server_Info *server = container_of(work,
4276 					struct TCP_Server_Info, reconnect.work);
4277 	struct TCP_Server_Info *pserver;
4278 	struct cifs_ses *ses, *ses2;
4279 	struct cifs_tcon *tcon, *tcon2;
4280 	struct list_head tmp_list, tmp_ses_list;
4281 	bool ses_exist = false;
4282 	bool tcon_selected = false;
4283 	int rc;
4284 	bool resched = false;
4285 
4286 	/* first check if ref count has reached 0, if not inc ref count */
4287 	spin_lock(&cifs_tcp_ses_lock);
4288 	if (!server->srv_count) {
4289 		spin_unlock(&cifs_tcp_ses_lock);
4290 		return;
4291 	}
4292 	server->srv_count++;
4293 	spin_unlock(&cifs_tcp_ses_lock);
4294 
4295 	/* If server is a channel, select the primary channel */
4296 	pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
4297 
4298 	/* Prevent simultaneous reconnects that can corrupt tcon->rlist list */
4299 	mutex_lock(&pserver->reconnect_mutex);
4300 
4301 	/* if the server is marked for termination, drop the ref count here */
4302 	if (server->terminate) {
4303 		cifs_put_tcp_session(server, true);
4304 		mutex_unlock(&pserver->reconnect_mutex);
4305 		return;
4306 	}
4307 
4308 	INIT_LIST_HEAD(&tmp_list);
4309 	INIT_LIST_HEAD(&tmp_ses_list);
4310 	cifs_dbg(FYI, "Reconnecting tcons and channels\n");
4311 
4312 	spin_lock(&cifs_tcp_ses_lock);
4313 	list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
4314 		spin_lock(&ses->ses_lock);
4315 		if (ses->ses_status == SES_EXITING) {
4316 			spin_unlock(&ses->ses_lock);
4317 			continue;
4318 		}
4319 		spin_unlock(&ses->ses_lock);
4320 
4321 		tcon_selected = false;
4322 
4323 		list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
4324 			if (tcon->need_reconnect || tcon->need_reopen_files) {
4325 				spin_lock(&tcon->tc_lock);
4326 				tcon->tc_count++;
4327 				spin_unlock(&tcon->tc_lock);
4328 				trace_smb3_tcon_ref(tcon->debug_id, tcon->tc_count,
4329 						    netfs_trace_tcon_ref_get_reconnect_server);
4330 				list_add_tail(&tcon->rlist, &tmp_list);
4331 				tcon_selected = true;
4332 			}
4333 		}
4334 		/*
4335 		 * IPC has the same lifetime as its session and uses its
4336 		 * refcount.
4337 		 */
4338 		if (ses->tcon_ipc && ses->tcon_ipc->need_reconnect) {
4339 			list_add_tail(&ses->tcon_ipc->rlist, &tmp_list);
4340 			tcon_selected = true;
4341 			cifs_smb_ses_inc_refcount(ses);
4342 		}
4343 		/*
4344 		 * handle the case where channel needs to reconnect
4345 		 * binding session, but tcon is healthy (some other channel
4346 		 * is active)
4347 		 */
4348 		spin_lock(&ses->chan_lock);
4349 		if (!tcon_selected && cifs_chan_needs_reconnect(ses, server)) {
4350 			list_add_tail(&ses->rlist, &tmp_ses_list);
4351 			ses_exist = true;
4352 			cifs_smb_ses_inc_refcount(ses);
4353 		}
4354 		spin_unlock(&ses->chan_lock);
4355 	}
4356 	spin_unlock(&cifs_tcp_ses_lock);
4357 
4358 	list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) {
4359 		rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server, true);
4360 		if (!rc) {
4361 			cifs_renegotiate_iosize(server, tcon);
4362 			cifs_reopen_persistent_handles(tcon);
4363 		} else
4364 			resched = true;
4365 		list_del_init(&tcon->rlist);
4366 		if (tcon->ipc)
4367 			cifs_put_smb_ses(tcon->ses);
4368 		else
4369 			cifs_put_tcon(tcon, netfs_trace_tcon_ref_put_reconnect_server);
4370 	}
4371 
4372 	if (!ses_exist)
4373 		goto done;
4374 
4375 	/* allocate a dummy tcon struct used for reconnect */
4376 	tcon = tcon_info_alloc(false, netfs_trace_tcon_ref_new_reconnect_server);
4377 	if (!tcon) {
4378 		resched = true;
4379 		list_for_each_entry_safe(ses, ses2, &tmp_ses_list, rlist) {
4380 			list_del_init(&ses->rlist);
4381 			cifs_put_smb_ses(ses);
4382 		}
4383 		goto done;
4384 	}
4385 	tcon->status = TID_GOOD;
4386 	tcon->dummy = true;
4387 
4388 	/* now reconnect sessions for necessary channels */
4389 	list_for_each_entry_safe(ses, ses2, &tmp_ses_list, rlist) {
4390 		tcon->ses = ses;
4391 		rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server, true);
4392 		if (rc)
4393 			resched = true;
4394 		list_del_init(&ses->rlist);
4395 		cifs_put_smb_ses(ses);
4396 	}
4397 	tconInfoFree(tcon, netfs_trace_tcon_ref_free_reconnect_server);
4398 
4399 done:
4400 	cifs_dbg(FYI, "Reconnecting tcons and channels finished\n");
4401 	if (resched)
4402 		cifs_requeue_server_reconn(server);
4403 	mutex_unlock(&pserver->reconnect_mutex);
4404 
4405 	/* now we can safely release srv struct */
4406 	cifs_put_tcp_session(server, true);
4407 }
4408 
4409 int
4410 SMB2_echo(struct TCP_Server_Info *server)
4411 {
4412 	struct smb2_echo_req *req;
4413 	int rc = 0;
4414 	struct kvec iov[1];
4415 	struct smb_rqst rqst = { .rq_iov = iov,
4416 				 .rq_nvec = 1 };
4417 	unsigned int total_len;
4418 
4419 	cifs_dbg(FYI, "In echo request for conn_id %lld\n", server->conn_id);
4420 
4421 	spin_lock(&server->srv_lock);
4422 	if (server->ops->need_neg &&
4423 	    server->ops->need_neg(server)) {
4424 		spin_unlock(&server->srv_lock);
4425 		/* No need to send echo on newly established connections */
4426 		cifs_queue_server_reconn(server);
4427 		return rc;
4428 	}
4429 	spin_unlock(&server->srv_lock);
4430 
4431 	rc = smb2_plain_req_init(SMB2_ECHO, NULL, server,
4432 				 (void **)&req, &total_len);
4433 	if (rc)
4434 		return rc;
4435 
4436 	req->hdr.CreditRequest = cpu_to_le16(1);
4437 
4438 	iov[0].iov_len = total_len;
4439 	iov[0].iov_base = (char *)req;
4440 
4441 	rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, NULL,
4442 			     server, CIFS_ECHO_OP, NULL);
4443 	if (rc)
4444 		cifs_dbg(FYI, "Echo request failed: %d\n", rc);
4445 
4446 	cifs_small_buf_release(req);
4447 	return rc;
4448 }
4449 
4450 void
4451 SMB2_flush_free(struct smb_rqst *rqst)
4452 {
4453 	if (rqst && rqst->rq_iov)
4454 		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
4455 }
4456 
4457 int
4458 SMB2_flush_init(const unsigned int xid, struct smb_rqst *rqst,
4459 		struct cifs_tcon *tcon, struct TCP_Server_Info *server,
4460 		u64 persistent_fid, u64 volatile_fid)
4461 {
4462 	struct smb2_flush_req *req;
4463 	struct kvec *iov = rqst->rq_iov;
4464 	unsigned int total_len;
4465 	int rc;
4466 
4467 	rc = smb2_plain_req_init(SMB2_FLUSH, tcon, server,
4468 				 (void **) &req, &total_len);
4469 	if (rc)
4470 		return rc;
4471 
4472 	req->PersistentFileId = persistent_fid;
4473 	req->VolatileFileId = volatile_fid;
4474 
4475 	iov[0].iov_base = (char *)req;
4476 	iov[0].iov_len = total_len;
4477 
4478 	return 0;
4479 }
4480 
4481 int
4482 SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
4483 	   u64 volatile_fid)
4484 {
4485 	struct cifs_ses *ses = tcon->ses;
4486 	struct smb_rqst rqst;
4487 	struct kvec iov[1];
4488 	struct kvec rsp_iov = {NULL, 0};
4489 	struct TCP_Server_Info *server;
4490 	int resp_buftype = CIFS_NO_BUFFER;
4491 	int flags = 0;
4492 	int rc = 0;
4493 	int retries = 0, cur_sleep = 0;
4494 
4495 replay_again:
4496 	/* reinitialize for possible replay */
4497 	resp_buftype = CIFS_NO_BUFFER;
4498 	memset(&rsp_iov, 0, sizeof(rsp_iov));
4499 	flags = 0;
4500 	server = cifs_pick_channel(ses);
4501 
4502 	cifs_dbg(FYI, "flush\n");
4503 	if (!ses || !(ses->server))
4504 		return smb_EIO(smb_eio_trace_null_pointers);
4505 
4506 	if (smb3_encryption_required(tcon))
4507 		flags |= CIFS_TRANSFORM_REQ;
4508 
4509 	memset(&rqst, 0, sizeof(struct smb_rqst));
4510 	memset(&iov, 0, sizeof(iov));
4511 	rqst.rq_iov = iov;
4512 	rqst.rq_nvec = 1;
4513 
4514 	rc = SMB2_flush_init(xid, &rqst, tcon, server,
4515 			     persistent_fid, volatile_fid);
4516 	if (rc)
4517 		goto flush_exit;
4518 
4519 	trace_smb3_flush_enter(xid, persistent_fid, tcon->tid, ses->Suid);
4520 
4521 	if (retries) {
4522 		/* Back-off before retry */
4523 		if (cur_sleep)
4524 			msleep(cur_sleep);
4525 		smb2_set_replay(server, &rqst);
4526 	}
4527 
4528 	rc = cifs_send_recv(xid, ses, server,
4529 			    &rqst, &resp_buftype, flags, &rsp_iov);
4530 
4531 	if (rc != 0) {
4532 		cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
4533 		trace_smb3_flush_err(xid, persistent_fid, tcon->tid, ses->Suid,
4534 				     rc);
4535 	} else
4536 		trace_smb3_flush_done(xid, persistent_fid, tcon->tid,
4537 				      ses->Suid);
4538 
4539  flush_exit:
4540 	SMB2_flush_free(&rqst);
4541 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4542 
4543 	if (is_replayable_error(rc) &&
4544 	    smb2_should_replay(tcon, &retries, &cur_sleep))
4545 		goto replay_again;
4546 
4547 	return rc;
4548 }
4549 
4550 #ifdef CONFIG_CIFS_SMB_DIRECT
4551 static inline bool smb3_use_rdma_offload(struct cifs_io_parms *io_parms)
4552 {
4553 	struct TCP_Server_Info *server = io_parms->server;
4554 	struct cifs_tcon *tcon = io_parms->tcon;
4555 
4556 	/* we can only offload if we're connected */
4557 	if (!server || !tcon)
4558 		return false;
4559 
4560 	/* we can only offload on an rdma connection */
4561 	if (!server->rdma || !server->smbd_conn)
4562 		return false;
4563 
4564 	/* we don't support signed offload yet */
4565 	if (server->sign)
4566 		return false;
4567 
4568 	/* we don't support encrypted offload yet */
4569 	if (smb3_encryption_required(tcon))
4570 		return false;
4571 
4572 	/* offload also has its overhead, so only do it if desired */
4573 	if (io_parms->length < server->rdma_readwrite_threshold)
4574 		return false;
4575 
4576 	return true;
4577 }
4578 #endif /* CONFIG_CIFS_SMB_DIRECT */
4579 
4580 /*
4581  * To form a chain of read requests, any read requests after the first should
4582  * have the end_of_chain boolean set to true.
4583  */
4584 static int
4585 smb2_new_read_req(void **buf, unsigned int *total_len,
4586 	struct cifs_io_parms *io_parms, struct cifs_io_subrequest *rdata,
4587 	unsigned int remaining_bytes, int request_type)
4588 {
4589 	int rc = -EACCES;
4590 	struct smb2_read_req *req = NULL;
4591 	struct smb2_hdr *shdr;
4592 	struct TCP_Server_Info *server = io_parms->server;
4593 
4594 	rc = smb2_plain_req_init(SMB2_READ, io_parms->tcon, server,
4595 				 (void **) &req, total_len);
4596 	if (rc)
4597 		return rc;
4598 
4599 	if (!server) {
4600 		rc = -ECONNABORTED;
4601 		goto free_req;
4602 	}
4603 
4604 	shdr = &req->hdr;
4605 	shdr->Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
4606 
4607 	req->PersistentFileId = io_parms->persistent_fid;
4608 	req->VolatileFileId = io_parms->volatile_fid;
4609 	req->ReadChannelInfoOffset = 0; /* reserved */
4610 	req->ReadChannelInfoLength = 0; /* reserved */
4611 	req->Channel = 0; /* reserved */
4612 	req->MinimumCount = 0;
4613 	req->Length = cpu_to_le32(io_parms->length);
4614 	req->Offset = cpu_to_le64(io_parms->offset);
4615 
4616 	trace_smb3_read_enter(rdata ? rdata->rreq->debug_id : 0,
4617 			      rdata ? rdata->subreq.debug_index : 0,
4618 			      rdata ? rdata->xid : 0,
4619 			      io_parms->persistent_fid,
4620 			      io_parms->tcon->tid, io_parms->tcon->ses->Suid,
4621 			      io_parms->offset, io_parms->length);
4622 #ifdef CONFIG_CIFS_SMB_DIRECT
4623 	/*
4624 	 * If we want to do a RDMA write, fill in and append
4625 	 * smbdirect_buffer_descriptor_v1 to the end of read request
4626 	 */
4627 	if (rdata && smb3_use_rdma_offload(io_parms)) {
4628 		struct smbdirect_buffer_descriptor_v1 *v1;
4629 		bool need_invalidate = server->dialect == SMB30_PROT_ID;
4630 
4631 		rdata->mr = smbd_register_mr(server->smbd_conn, &rdata->subreq.io_iter,
4632 					     true, need_invalidate);
4633 		if (!rdata->mr) {
4634 			rc = -EAGAIN;
4635 			goto free_req;
4636 		}
4637 
4638 		req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
4639 		if (need_invalidate)
4640 			req->Channel = SMB2_CHANNEL_RDMA_V1;
4641 		req->ReadChannelInfoOffset =
4642 			cpu_to_le16(offsetof(struct smb2_read_req, Buffer));
4643 		req->ReadChannelInfoLength =
4644 			cpu_to_le16(sizeof(struct smbdirect_buffer_descriptor_v1));
4645 		v1 = (struct smbdirect_buffer_descriptor_v1 *) &req->Buffer[0];
4646 		smbd_mr_fill_buffer_descriptor(rdata->mr, v1);
4647 
4648 		*total_len += sizeof(*v1) - 1;
4649 	}
4650 #endif
4651 	if (request_type & CHAINED_REQUEST) {
4652 		if (!(request_type & END_OF_CHAIN)) {
4653 			/* next 8-byte aligned request */
4654 			*total_len = ALIGN(*total_len, 8);
4655 			shdr->NextCommand = cpu_to_le32(*total_len);
4656 		} else /* END_OF_CHAIN */
4657 			shdr->NextCommand = 0;
4658 		if (request_type & RELATED_REQUEST) {
4659 			shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
4660 			/*
4661 			 * Related requests use info from previous read request
4662 			 * in chain.
4663 			 */
4664 			shdr->SessionId = cpu_to_le64(0xFFFFFFFFFFFFFFFF);
4665 			shdr->Id.SyncId.TreeId = cpu_to_le32(0xFFFFFFFF);
4666 			req->PersistentFileId = (u64)-1;
4667 			req->VolatileFileId = (u64)-1;
4668 		}
4669 	}
4670 	if (remaining_bytes > io_parms->length)
4671 		req->RemainingBytes = cpu_to_le32(remaining_bytes);
4672 	else
4673 		req->RemainingBytes = 0;
4674 
4675 	*buf = req;
4676 	return rc;
4677 
4678 free_req:
4679 	cifs_small_buf_release(req);
4680 	return rc;
4681 }
4682 
4683 static void
4684 smb2_readv_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid)
4685 {
4686 	struct cifs_io_subrequest *rdata = mid->callback_data;
4687 	struct netfs_inode *ictx = netfs_inode(rdata->rreq->inode);
4688 	struct cifs_tcon *tcon = tlink_tcon(rdata->req->cfile->tlink);
4689 	struct smb2_hdr *shdr = (struct smb2_hdr *)rdata->iov[0].iov_base;
4690 	struct inode *inode = &ictx->inode;
4691 	struct cifs_credits credits = {
4692 		.value = 0,
4693 		.instance = 0,
4694 		.rreq_debug_id = rdata->rreq->debug_id,
4695 		.rreq_debug_index = rdata->subreq.debug_index,
4696 	};
4697 	struct smb_rqst rqst = { .rq_iov = &rdata->iov[0], .rq_nvec = 1 };
4698 	unsigned int rreq_debug_id = rdata->rreq->debug_id;
4699 	unsigned int subreq_debug_index = rdata->subreq.debug_index;
4700 
4701 	if (rdata->got_bytes) {
4702 		rqst.rq_iter	  = rdata->subreq.io_iter;
4703 	}
4704 
4705 	WARN_ONCE(rdata->server != server,
4706 		  "rdata server %p != mid server %p",
4707 		  rdata->server, server);
4708 
4709 	cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%zu/%zu\n",
4710 		 __func__, mid->mid, mid->mid_state, rdata->result,
4711 		 rdata->got_bytes, rdata->subreq.len - rdata->subreq.transferred);
4712 
4713 	switch (mid->mid_state) {
4714 	case MID_RESPONSE_RECEIVED:
4715 		credits.value = le16_to_cpu(shdr->CreditRequest);
4716 		credits.instance = server->reconnect_instance;
4717 		/* result already set, check signature */
4718 		if (server->sign && !mid->decrypted) {
4719 			int rc;
4720 
4721 			iov_iter_truncate(&rqst.rq_iter, rdata->got_bytes);
4722 			rc = smb2_verify_signature(&rqst, server);
4723 			if (rc) {
4724 				cifs_tcon_dbg(VFS, "SMB signature verification returned error = %d\n",
4725 					      rc);
4726 				rdata->subreq.error = rc;
4727 				rdata->result = rc;
4728 
4729 				if (is_replayable_error(rc)) {
4730 					trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_retry_needed);
4731 					__set_bit(NETFS_SREQ_NEED_RETRY, &rdata->subreq.flags);
4732 				} else
4733 					trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_bad);
4734 			} else
4735 				trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_progress);
4736 		}
4737 		/* FIXME: should this be counted toward the initiating task? */
4738 		task_io_account_read(rdata->got_bytes);
4739 		cifs_stats_bytes_read(tcon, rdata->got_bytes);
4740 		break;
4741 	case MID_REQUEST_SUBMITTED:
4742 		trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_req_submitted);
4743 		goto do_retry;
4744 	case MID_RETRY_NEEDED:
4745 		trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_retry_needed);
4746 do_retry:
4747 		__set_bit(NETFS_SREQ_NEED_RETRY, &rdata->subreq.flags);
4748 		rdata->result = -EAGAIN;
4749 		if (server->sign && rdata->got_bytes)
4750 			/* reset bytes number since we can not check a sign */
4751 			rdata->got_bytes = 0;
4752 		/* FIXME: should this be counted toward the initiating task? */
4753 		task_io_account_read(rdata->got_bytes);
4754 		cifs_stats_bytes_read(tcon, rdata->got_bytes);
4755 		break;
4756 	case MID_RESPONSE_MALFORMED:
4757 		trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_malformed);
4758 		credits.value = le16_to_cpu(shdr->CreditRequest);
4759 		credits.instance = server->reconnect_instance;
4760 		rdata->result = smb_EIO(smb_eio_trace_read_rsp_malformed);
4761 		break;
4762 	default:
4763 		trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_unknown);
4764 		rdata->result = smb_EIO1(smb_eio_trace_read_mid_state_unknown,
4765 					 mid->mid_state);
4766 		break;
4767 	}
4768 #ifdef CONFIG_CIFS_SMB_DIRECT
4769 	/*
4770 	 * If this rdata has a memory registered, the MR can be freed
4771 	 * MR needs to be freed as soon as I/O finishes to prevent deadlock
4772 	 * because they have limited number and are used for future I/Os
4773 	 */
4774 	if (rdata->mr) {
4775 		smbd_deregister_mr(rdata->mr);
4776 		rdata->mr = NULL;
4777 	}
4778 #endif
4779 	if (rdata->result && rdata->result != -ENODATA) {
4780 		cifs_stats_fail_inc(tcon, SMB2_READ_HE);
4781 		trace_smb3_read_err(rdata->rreq->debug_id,
4782 				    rdata->subreq.debug_index,
4783 				    rdata->xid,
4784 				    rdata->req->cfile->fid.persistent_fid,
4785 				    tcon->tid, tcon->ses->Suid,
4786 				    rdata->subreq.start + rdata->subreq.transferred,
4787 				    rdata->subreq.len   - rdata->subreq.transferred,
4788 				    rdata->result);
4789 	} else
4790 		trace_smb3_read_done(rdata->rreq->debug_id,
4791 				     rdata->subreq.debug_index,
4792 				     rdata->xid,
4793 				     rdata->req->cfile->fid.persistent_fid,
4794 				     tcon->tid, tcon->ses->Suid,
4795 				     rdata->subreq.start + rdata->subreq.transferred,
4796 				     rdata->got_bytes);
4797 
4798 	if (rdata->result == -ENODATA) {
4799 		rdata->result = 0;
4800 		if (rdata->subreq.start + rdata->subreq.transferred >= i_size_read(inode))
4801 			__set_bit(NETFS_SREQ_HIT_EOF, &rdata->subreq.flags);
4802 		else
4803 			__set_bit(NETFS_SREQ_CLEAR_TAIL, &rdata->subreq.flags);
4804 	} else {
4805 		size_t trans = rdata->subreq.transferred + rdata->got_bytes;
4806 		if (trans < rdata->subreq.len &&
4807 		    rdata->subreq.start + trans >= netfs_read_remote_i_size(inode)) {
4808 			rdata->result = 0;
4809 			if (rdata->subreq.start + trans >= i_size_read(inode))
4810 				__set_bit(NETFS_SREQ_HIT_EOF, &rdata->subreq.flags);
4811 			else
4812 				__set_bit(NETFS_SREQ_CLEAR_TAIL, &rdata->subreq.flags);
4813 		}
4814 		if (rdata->got_bytes)
4815 			__set_bit(NETFS_SREQ_MADE_PROGRESS, &rdata->subreq.flags);
4816 	}
4817 
4818 	/* see if we need to retry */
4819 	if (is_replayable_error(rdata->result) &&
4820 	    smb2_should_replay(tcon,
4821 			       &rdata->retries,
4822 			       &rdata->cur_sleep))
4823 		rdata->replay = true;
4824 
4825 	trace_smb3_rw_credits(rreq_debug_id, subreq_debug_index, rdata->credits.value,
4826 			      server->credits, server->in_flight,
4827 			      0, cifs_trace_rw_credits_read_response_clear);
4828 	rdata->credits.value = 0;
4829 	rdata->subreq.error = rdata->result;
4830 	rdata->subreq.transferred += rdata->got_bytes;
4831 	trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_progress);
4832 	netfs_read_subreq_terminated(&rdata->subreq);
4833 	release_mid(server, mid);
4834 	trace_smb3_rw_credits(rreq_debug_id, subreq_debug_index, 0,
4835 			      server->credits, server->in_flight,
4836 			      credits.value, cifs_trace_rw_credits_read_response_add);
4837 	add_credits(server, &credits, 0);
4838 }
4839 
4840 /* smb2_async_readv - send an async read, and set up mid to handle result */
4841 int
4842 smb2_async_readv(struct cifs_io_subrequest *rdata)
4843 {
4844 	int rc, flags = 0;
4845 	char *buf;
4846 	struct netfs_io_subrequest *subreq = &rdata->subreq;
4847 	struct smb2_hdr *shdr;
4848 	struct cifs_io_parms io_parms;
4849 	struct smb_rqst rqst = { .rq_iov = rdata->iov,
4850 				 .rq_nvec = 1 };
4851 	struct TCP_Server_Info *server;
4852 	struct cifs_tcon *tcon = tlink_tcon(rdata->req->cfile->tlink);
4853 	unsigned int total_len;
4854 	int credit_request;
4855 
4856 	cifs_dbg(FYI, "%s: offset=%llu bytes=%zu\n",
4857 		 __func__, subreq->start, subreq->len);
4858 
4859 	if (!rdata->server)
4860 		rdata->server = cifs_pick_channel(tcon->ses);
4861 
4862 	io_parms.tcon = tlink_tcon(rdata->req->cfile->tlink);
4863 	io_parms.server = server = rdata->server;
4864 	io_parms.offset = subreq->start + subreq->transferred;
4865 	io_parms.length = subreq->len   - subreq->transferred;
4866 	io_parms.persistent_fid = rdata->req->cfile->fid.persistent_fid;
4867 	io_parms.volatile_fid = rdata->req->cfile->fid.volatile_fid;
4868 	io_parms.pid = rdata->req->pid;
4869 
4870 	rc = smb2_new_read_req(
4871 		(void **) &buf, &total_len, &io_parms, rdata, 0, 0);
4872 	if (rc)
4873 		goto out;
4874 
4875 	if (smb3_encryption_required(io_parms.tcon))
4876 		flags |= CIFS_TRANSFORM_REQ;
4877 
4878 	rdata->iov[0].iov_base = buf;
4879 	rdata->iov[0].iov_len = total_len;
4880 	rdata->got_bytes = 0;
4881 	rdata->result = 0;
4882 
4883 	shdr = (struct smb2_hdr *)buf;
4884 
4885 	if (rdata->replay) {
4886 		/* Back-off before retry */
4887 		if (rdata->cur_sleep)
4888 			msleep(rdata->cur_sleep);
4889 		smb2_set_replay(server, &rqst);
4890 	}
4891 
4892 	if (rdata->credits.value > 0) {
4893 		shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(io_parms.length,
4894 						SMB2_MAX_BUFFER_SIZE));
4895 		credit_request = le16_to_cpu(shdr->CreditCharge) + 8;
4896 		if (server->credits >= server->max_credits)
4897 			shdr->CreditRequest = cpu_to_le16(0);
4898 		else
4899 			shdr->CreditRequest = cpu_to_le16(
4900 				min_t(int, server->max_credits -
4901 						server->credits, credit_request));
4902 
4903 		rc = adjust_credits(server, rdata, cifs_trace_rw_credits_call_readv_adjust);
4904 		if (rc)
4905 			goto async_readv_out;
4906 
4907 		flags |= CIFS_HAS_CREDITS;
4908 	}
4909 
4910 	rc = cifs_call_async(server, &rqst,
4911 			     cifs_readv_receive, smb2_readv_callback,
4912 			     smb3_handle_read_data, rdata, flags,
4913 			     &rdata->credits);
4914 	if (rc) {
4915 		cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE);
4916 		trace_smb3_read_err(rdata->rreq->debug_id,
4917 				    subreq->debug_index,
4918 				    rdata->xid, io_parms.persistent_fid,
4919 				    io_parms.tcon->tid,
4920 				    io_parms.tcon->ses->Suid,
4921 				    io_parms.offset,
4922 				    subreq->len - subreq->transferred, rc);
4923 	}
4924 
4925 async_readv_out:
4926 	cifs_small_buf_release(buf);
4927 
4928 out:
4929 	/* if the send error is retryable, let netfs know about it */
4930 	if (is_replayable_error(rc) &&
4931 	    smb2_should_replay(tcon,
4932 			       &rdata->retries,
4933 			       &rdata->cur_sleep)) {
4934 		rdata->replay = true;
4935 		trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_retry_needed);
4936 		__set_bit(NETFS_SREQ_NEED_RETRY, &rdata->subreq.flags);
4937 	}
4938 
4939 	return rc;
4940 }
4941 
4942 int
4943 SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
4944 	  unsigned int *nbytes, char **buf, int *buf_type)
4945 {
4946 	struct smb_rqst rqst;
4947 	int resp_buftype, rc;
4948 	struct smb2_read_req *req = NULL;
4949 	struct smb2_read_rsp *rsp = NULL;
4950 	struct kvec iov[1];
4951 	struct kvec rsp_iov;
4952 	unsigned int total_len;
4953 	int flags = CIFS_LOG_ERROR;
4954 	struct cifs_ses *ses = io_parms->tcon->ses;
4955 
4956 	if (!io_parms->server)
4957 		io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
4958 
4959 	*nbytes = 0;
4960 	rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);
4961 	if (rc)
4962 		return rc;
4963 
4964 	if (smb3_encryption_required(io_parms->tcon))
4965 		flags |= CIFS_TRANSFORM_REQ;
4966 
4967 	iov[0].iov_base = (char *)req;
4968 	iov[0].iov_len = total_len;
4969 
4970 	memset(&rqst, 0, sizeof(struct smb_rqst));
4971 	rqst.rq_iov = iov;
4972 	rqst.rq_nvec = 1;
4973 
4974 	rc = cifs_send_recv(xid, ses, io_parms->server,
4975 			    &rqst, &resp_buftype, flags, &rsp_iov);
4976 	rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
4977 
4978 	if (rc) {
4979 		if (rc != -ENODATA) {
4980 			cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
4981 			cifs_dbg(VFS, "Send error in read = %d\n", rc);
4982 			trace_smb3_read_err(0, 0, xid,
4983 					    req->PersistentFileId,
4984 					    io_parms->tcon->tid, ses->Suid,
4985 					    io_parms->offset, io_parms->length,
4986 					    rc);
4987 		} else
4988 			trace_smb3_read_done(0, 0, xid,
4989 					     req->PersistentFileId, io_parms->tcon->tid,
4990 					     ses->Suid, io_parms->offset, 0);
4991 		free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4992 		cifs_small_buf_release(req);
4993 		return rc == -ENODATA ? 0 : rc;
4994 	} else
4995 		trace_smb3_read_done(0, 0, xid,
4996 				     req->PersistentFileId,
4997 				     io_parms->tcon->tid, ses->Suid,
4998 				     io_parms->offset, io_parms->length);
4999 
5000 	cifs_small_buf_release(req);
5001 
5002 	*nbytes = le32_to_cpu(rsp->DataLength);
5003 	if ((*nbytes > CIFS_MAX_MSGSIZE) ||
5004 	    (*nbytes > io_parms->length)) {
5005 		cifs_dbg(FYI, "bad length %d for count %d\n",
5006 			 *nbytes, io_parms->length);
5007 		rc = smb_EIO2(smb_eio_trace_read_overlarge,
5008 			      *nbytes, io_parms->length);
5009 		*nbytes = 0;
5010 	}
5011 
5012 	if (*buf) {
5013 		memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);
5014 		free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5015 	} else if (resp_buftype != CIFS_NO_BUFFER) {
5016 		*buf = rsp_iov.iov_base;
5017 		if (resp_buftype == CIFS_SMALL_BUFFER)
5018 			*buf_type = CIFS_SMALL_BUFFER;
5019 		else if (resp_buftype == CIFS_LARGE_BUFFER)
5020 			*buf_type = CIFS_LARGE_BUFFER;
5021 	}
5022 	return rc;
5023 }
5024 
5025 /*
5026  * Check the mid_state and signature on received buffer (if any), and queue the
5027  * workqueue completion task.
5028  */
5029 static void
5030 smb2_writev_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid)
5031 {
5032 	struct cifs_io_subrequest *wdata = mid->callback_data;
5033 	struct cifs_tcon *tcon = tlink_tcon(wdata->req->cfile->tlink);
5034 	struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
5035 	struct cifs_credits credits = {
5036 		.value = 0,
5037 		.instance = 0,
5038 		.rreq_debug_id = wdata->rreq->debug_id,
5039 		.rreq_debug_index = wdata->subreq.debug_index,
5040 	};
5041 	unsigned int rreq_debug_id = wdata->rreq->debug_id;
5042 	unsigned int subreq_debug_index = wdata->subreq.debug_index;
5043 	ssize_t result = 0;
5044 	size_t written = 0;
5045 
5046 	WARN_ONCE(wdata->server != server,
5047 		  "wdata server %p != mid server %p",
5048 		  wdata->server, server);
5049 
5050 	switch (mid->mid_state) {
5051 	case MID_RESPONSE_RECEIVED:
5052 		credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
5053 		credits.instance = server->reconnect_instance;
5054 		result = smb2_check_receive(mid, server, 0);
5055 		if (result != 0) {
5056 			if (is_replayable_error(result)) {
5057 				trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_retry_needed);
5058 				__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
5059 			} else {
5060 				wdata->subreq.error = result;
5061 				trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_bad);
5062 			}
5063 			break;
5064 		}
5065 		trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_progress);
5066 
5067 		written = le32_to_cpu(rsp->DataLength);
5068 		/*
5069 		 * Mask off high 16 bits when bytes written as returned
5070 		 * by the server is greater than bytes requested by the
5071 		 * client. OS/2 servers are known to set incorrect
5072 		 * CountHigh values.
5073 		 */
5074 		if (written > wdata->subreq.len)
5075 			written &= 0xFFFF;
5076 
5077 		cifs_stats_bytes_written(tcon, written);
5078 
5079 		if (written < wdata->subreq.len) {
5080 			result = -ENOSPC;
5081 		} else if (written > 0) {
5082 			wdata->subreq.len = written;
5083 			__set_bit(NETFS_SREQ_MADE_PROGRESS, &wdata->subreq.flags);
5084 		}
5085 		break;
5086 	case MID_REQUEST_SUBMITTED:
5087 		trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_req_submitted);
5088 		__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
5089 		result = -EAGAIN;
5090 		break;
5091 	case MID_RETRY_NEEDED:
5092 		trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_retry_needed);
5093 		__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
5094 		result = -EAGAIN;
5095 		break;
5096 	case MID_RESPONSE_MALFORMED:
5097 		trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_malformed);
5098 		credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
5099 		credits.instance = server->reconnect_instance;
5100 		result = smb_EIO(smb_eio_trace_write_rsp_malformed);
5101 		break;
5102 	default:
5103 		trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_unknown);
5104 		result = smb_EIO1(smb_eio_trace_write_mid_state_unknown,
5105 				  mid->mid_state);
5106 		break;
5107 	}
5108 #ifdef CONFIG_CIFS_SMB_DIRECT
5109 	/*
5110 	 * If this wdata has a memory registered, the MR can be freed
5111 	 * The number of MRs available is limited, it's important to recover
5112 	 * used MR as soon as I/O is finished. Hold MR longer in the later
5113 	 * I/O process can possibly result in I/O deadlock due to lack of MR
5114 	 * to send request on I/O retry
5115 	 */
5116 	if (wdata->mr) {
5117 		smbd_deregister_mr(wdata->mr);
5118 		wdata->mr = NULL;
5119 	}
5120 #endif
5121 	if (result) {
5122 		wdata->result = result;
5123 		cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
5124 		trace_smb3_write_err(wdata->rreq->debug_id,
5125 				     wdata->subreq.debug_index,
5126 				     wdata->xid,
5127 				     wdata->req->cfile->fid.persistent_fid,
5128 				     tcon->tid, tcon->ses->Suid, wdata->subreq.start,
5129 				     wdata->subreq.len, wdata->result);
5130 		if (wdata->result == -ENOSPC)
5131 			pr_warn_once("Out of space writing to %s\n",
5132 				     tcon->tree_name);
5133 	} else
5134 		trace_smb3_write_done(wdata->rreq->debug_id,
5135 				      wdata->subreq.debug_index,
5136 				      wdata->xid,
5137 				      wdata->req->cfile->fid.persistent_fid,
5138 				      tcon->tid, tcon->ses->Suid,
5139 				      wdata->subreq.start, wdata->subreq.len);
5140 
5141 	trace_smb3_rw_credits(rreq_debug_id, subreq_debug_index, wdata->credits.value,
5142 			      server->credits, server->in_flight,
5143 			      0, cifs_trace_rw_credits_write_response_clear);
5144 	wdata->credits.value = 0;
5145 
5146 	/* see if we need to retry */
5147 	if (is_replayable_error(wdata->result) &&
5148 	    smb2_should_replay(tcon,
5149 			       &wdata->retries,
5150 			       &wdata->cur_sleep))
5151 		wdata->replay = true;
5152 
5153 	cifs_write_subrequest_terminated(wdata, result ?: written);
5154 	release_mid(server, mid);
5155 	trace_smb3_rw_credits(rreq_debug_id, subreq_debug_index, 0,
5156 			      server->credits, server->in_flight,
5157 			      credits.value, cifs_trace_rw_credits_write_response_add);
5158 	add_credits(server, &credits, 0);
5159 }
5160 
5161 /* smb2_async_writev - send an async write, and set up mid to handle result */
5162 void
5163 smb2_async_writev(struct cifs_io_subrequest *wdata)
5164 {
5165 	int rc = -EACCES, flags = 0;
5166 	struct smb2_write_req *req = NULL;
5167 	struct smb2_hdr *shdr;
5168 	struct cifs_tcon *tcon = tlink_tcon(wdata->req->cfile->tlink);
5169 	struct TCP_Server_Info *server = wdata->server;
5170 	struct kvec iov[1];
5171 	struct smb_rqst rqst = { };
5172 	unsigned int total_len, xid = wdata->xid;
5173 	struct cifs_io_parms _io_parms;
5174 	struct cifs_io_parms *io_parms = NULL;
5175 	int credit_request;
5176 
5177 	/*
5178 	 * in future we may get cifs_io_parms passed in from the caller,
5179 	 * but for now we construct it here...
5180 	 */
5181 	_io_parms = (struct cifs_io_parms) {
5182 		.tcon = tcon,
5183 		.server = server,
5184 		.offset = wdata->subreq.start,
5185 		.length = wdata->subreq.len,
5186 		.persistent_fid = wdata->req->cfile->fid.persistent_fid,
5187 		.volatile_fid = wdata->req->cfile->fid.volatile_fid,
5188 		.pid = wdata->req->pid,
5189 	};
5190 	io_parms = &_io_parms;
5191 
5192 	rc = smb2_plain_req_init(SMB2_WRITE, tcon, server,
5193 				 (void **) &req, &total_len);
5194 	if (rc)
5195 		goto out;
5196 
5197 	rqst.rq_iov = iov;
5198 	rqst.rq_iter = wdata->subreq.io_iter;
5199 
5200 	rqst.rq_iov[0].iov_len = total_len - 1;
5201 	rqst.rq_iov[0].iov_base = (char *)req;
5202 	rqst.rq_nvec += 1;
5203 
5204 	if (smb3_encryption_required(tcon))
5205 		flags |= CIFS_TRANSFORM_REQ;
5206 
5207 	shdr = (struct smb2_hdr *)req;
5208 	shdr->Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
5209 
5210 	req->PersistentFileId = io_parms->persistent_fid;
5211 	req->VolatileFileId = io_parms->volatile_fid;
5212 	req->WriteChannelInfoOffset = 0;
5213 	req->WriteChannelInfoLength = 0;
5214 	req->Channel = SMB2_CHANNEL_NONE;
5215 	req->Length = cpu_to_le32(io_parms->length);
5216 	req->Offset = cpu_to_le64(io_parms->offset);
5217 	req->DataOffset = cpu_to_le16(
5218 				offsetof(struct smb2_write_req, Buffer));
5219 	req->RemainingBytes = 0;
5220 
5221 	trace_smb3_write_enter(wdata->rreq->debug_id,
5222 			       wdata->subreq.debug_index,
5223 			       wdata->xid,
5224 			       io_parms->persistent_fid,
5225 			       io_parms->tcon->tid,
5226 			       io_parms->tcon->ses->Suid,
5227 			       io_parms->offset,
5228 			       io_parms->length);
5229 
5230 #ifdef CONFIG_CIFS_SMB_DIRECT
5231 	/*
5232 	 * If we want to do a server RDMA read, fill in and append
5233 	 * smbdirect_buffer_descriptor_v1 to the end of write request
5234 	 */
5235 	if (smb3_use_rdma_offload(io_parms)) {
5236 		struct smbdirect_buffer_descriptor_v1 *v1;
5237 		bool need_invalidate = server->dialect == SMB30_PROT_ID;
5238 
5239 		wdata->mr = smbd_register_mr(server->smbd_conn, &wdata->subreq.io_iter,
5240 					     false, need_invalidate);
5241 		if (!wdata->mr) {
5242 			rc = -EAGAIN;
5243 			goto async_writev_out;
5244 		}
5245 		/* For RDMA read, I/O size is in RemainingBytes not in Length */
5246 		req->RemainingBytes = req->Length;
5247 		req->Length = 0;
5248 		req->DataOffset = 0;
5249 		req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
5250 		if (need_invalidate)
5251 			req->Channel = SMB2_CHANNEL_RDMA_V1;
5252 		req->WriteChannelInfoOffset =
5253 			cpu_to_le16(offsetof(struct smb2_write_req, Buffer));
5254 		req->WriteChannelInfoLength =
5255 			cpu_to_le16(sizeof(struct smbdirect_buffer_descriptor_v1));
5256 		v1 = (struct smbdirect_buffer_descriptor_v1 *) &req->Buffer[0];
5257 		smbd_mr_fill_buffer_descriptor(wdata->mr, v1);
5258 
5259 		rqst.rq_iov[0].iov_len += sizeof(*v1);
5260 
5261 		/*
5262 		 * We keep wdata->subreq.io_iter,
5263 		 * but we have to truncate rqst.rq_iter
5264 		 */
5265 		iov_iter_truncate(&rqst.rq_iter, 0);
5266 	}
5267 #endif
5268 
5269 	if (wdata->replay) {
5270 		/* Back-off before retry */
5271 		if (wdata->cur_sleep)
5272 			msleep(wdata->cur_sleep);
5273 		smb2_set_replay(server, &rqst);
5274 	}
5275 
5276 	cifs_dbg(FYI, "async write at %llu %u bytes iter=%zx\n",
5277 		 io_parms->offset, io_parms->length, iov_iter_count(&wdata->subreq.io_iter));
5278 
5279 	if (wdata->credits.value > 0) {
5280 		shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->subreq.len,
5281 						    SMB2_MAX_BUFFER_SIZE));
5282 		credit_request = le16_to_cpu(shdr->CreditCharge) + 8;
5283 		if (server->credits >= server->max_credits)
5284 			shdr->CreditRequest = cpu_to_le16(0);
5285 		else
5286 			shdr->CreditRequest = cpu_to_le16(
5287 				min_t(int, server->max_credits -
5288 						server->credits, credit_request));
5289 
5290 		rc = adjust_credits(server, wdata, cifs_trace_rw_credits_call_writev_adjust);
5291 		if (rc)
5292 			goto async_writev_out;
5293 
5294 		flags |= CIFS_HAS_CREDITS;
5295 	}
5296 
5297 	/* XXX: compression + encryption is unsupported for now */
5298 	if (((flags & CIFS_TRANSFORM_REQ) != CIFS_TRANSFORM_REQ) && should_compress(tcon, &rqst))
5299 		flags |= CIFS_COMPRESS_REQ;
5300 
5301 	rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, NULL,
5302 			     wdata, flags, &wdata->credits);
5303 	/* Can't touch wdata if rc == 0 */
5304 	if (rc) {
5305 		trace_smb3_write_err(wdata->rreq->debug_id,
5306 				     wdata->subreq.debug_index,
5307 				     xid,
5308 				     io_parms->persistent_fid,
5309 				     io_parms->tcon->tid,
5310 				     io_parms->tcon->ses->Suid,
5311 				     io_parms->offset,
5312 				     io_parms->length,
5313 				     rc);
5314 		cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
5315 	}
5316 
5317 async_writev_out:
5318 	cifs_small_buf_release(req);
5319 out:
5320 	/* if the send error is retryable, let netfs know about it */
5321 	if (is_replayable_error(rc) &&
5322 	    smb2_should_replay(tcon,
5323 			       &wdata->retries,
5324 			       &wdata->cur_sleep)) {
5325 		wdata->replay = true;
5326 		trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_retry_needed);
5327 		__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
5328 	}
5329 
5330 	if (rc) {
5331 		trace_smb3_rw_credits(wdata->rreq->debug_id,
5332 				      wdata->subreq.debug_index,
5333 				      wdata->credits.value,
5334 				      server->credits, server->in_flight,
5335 				      -(int)wdata->credits.value,
5336 				      cifs_trace_rw_credits_write_response_clear);
5337 		add_credits_and_wake_if(wdata->server, &wdata->credits, 0);
5338 		cifs_write_subrequest_terminated(wdata, rc);
5339 	}
5340 }
5341 
5342 /*
5343  * SMB2_write function gets iov pointer to kvec array with n_vec as a length.
5344  * The length field from io_parms must be at least 1 and indicates a number of
5345  * elements with data to write that begins with position 1 in iov array. All
5346  * data length is specified by count.
5347  */
5348 int
5349 SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
5350 	   unsigned int *nbytes, struct kvec *iov, int n_vec)
5351 {
5352 	struct smb_rqst rqst;
5353 	int rc = 0;
5354 	struct smb2_write_req *req = NULL;
5355 	struct smb2_write_rsp *rsp = NULL;
5356 	int resp_buftype;
5357 	struct kvec rsp_iov;
5358 	int flags = 0;
5359 	unsigned int total_len;
5360 	struct TCP_Server_Info *server;
5361 	int retries = 0, cur_sleep = 0;
5362 
5363 replay_again:
5364 	/* reinitialize for possible replay */
5365 	flags = 0;
5366 	*nbytes = 0;
5367 	if (!io_parms->server)
5368 		io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
5369 	server = io_parms->server;
5370 	if (server == NULL)
5371 		return -ECONNABORTED;
5372 
5373 	if (n_vec < 1)
5374 		return rc;
5375 
5376 	rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, server,
5377 				 (void **) &req, &total_len);
5378 	if (rc)
5379 		return rc;
5380 
5381 	if (smb3_encryption_required(io_parms->tcon))
5382 		flags |= CIFS_TRANSFORM_REQ;
5383 
5384 	req->hdr.Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
5385 
5386 	req->PersistentFileId = io_parms->persistent_fid;
5387 	req->VolatileFileId = io_parms->volatile_fid;
5388 	req->WriteChannelInfoOffset = 0;
5389 	req->WriteChannelInfoLength = 0;
5390 	req->Channel = 0;
5391 	req->Length = cpu_to_le32(io_parms->length);
5392 	req->Offset = cpu_to_le64(io_parms->offset);
5393 	req->DataOffset = cpu_to_le16(
5394 				offsetof(struct smb2_write_req, Buffer));
5395 	req->RemainingBytes = 0;
5396 
5397 	trace_smb3_write_enter(0, 0, xid, io_parms->persistent_fid,
5398 		io_parms->tcon->tid, io_parms->tcon->ses->Suid,
5399 		io_parms->offset, io_parms->length);
5400 
5401 	iov[0].iov_base = (char *)req;
5402 	/* 1 for Buffer */
5403 	iov[0].iov_len = total_len - 1;
5404 
5405 	memset(&rqst, 0, sizeof(struct smb_rqst));
5406 	rqst.rq_iov = iov;
5407 	/* iov[0] is the SMB header; move payload to rq_iter for encryption safety */
5408 	rqst.rq_nvec = 1;
5409 	iov_iter_kvec(&rqst.rq_iter, ITER_SOURCE, &iov[1], n_vec,
5410 		      io_parms->length);
5411 
5412 	if (retries) {
5413 		/* Back-off before retry */
5414 		if (cur_sleep)
5415 			msleep(cur_sleep);
5416 		smb2_set_replay(server, &rqst);
5417 	}
5418 
5419 	rc = cifs_send_recv(xid, io_parms->tcon->ses, server,
5420 			    &rqst,
5421 			    &resp_buftype, flags, &rsp_iov);
5422 	rsp = (struct smb2_write_rsp *)rsp_iov.iov_base;
5423 
5424 	if (rc) {
5425 		trace_smb3_write_err(0, 0, xid,
5426 				     req->PersistentFileId,
5427 				     io_parms->tcon->tid,
5428 				     io_parms->tcon->ses->Suid,
5429 				     io_parms->offset, io_parms->length, rc);
5430 		cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
5431 		cifs_dbg(VFS, "Send error in write = %d\n", rc);
5432 	} else {
5433 		*nbytes = le32_to_cpu(rsp->DataLength);
5434 		cifs_stats_bytes_written(io_parms->tcon, *nbytes);
5435 		trace_smb3_write_done(0, 0, xid,
5436 				      req->PersistentFileId,
5437 				      io_parms->tcon->tid,
5438 				      io_parms->tcon->ses->Suid,
5439 				      io_parms->offset, *nbytes);
5440 	}
5441 
5442 	cifs_small_buf_release(req);
5443 	free_rsp_buf(resp_buftype, rsp);
5444 
5445 	if (is_replayable_error(rc) &&
5446 	    smb2_should_replay(io_parms->tcon, &retries, &cur_sleep))
5447 		goto replay_again;
5448 
5449 	return rc;
5450 }
5451 
5452 int posix_info_sid_size(const void *beg, const void *end)
5453 {
5454 	size_t subauth;
5455 	int total;
5456 
5457 	if (beg + 2 > end)
5458 		return -1;
5459 
5460 	subauth = *(u8 *)(beg+1);
5461 	if (subauth < 1 || subauth > 15)
5462 		return -1;
5463 
5464 	total = 1 + 1 + 6 + 4*subauth;
5465 	if (beg + total > end)
5466 		return -1;
5467 
5468 	return total;
5469 }
5470 
5471 int posix_info_parse(const void *beg, const void *end,
5472 		     struct smb2_posix_info_parsed *out)
5473 
5474 {
5475 	int total_len = 0;
5476 	int owner_len, group_len;
5477 	int name_len;
5478 	const void *owner_sid;
5479 	const void *group_sid;
5480 	const void *name;
5481 
5482 	/* if no end bound given, assume payload to be correct */
5483 	if (!end) {
5484 		const struct smb2_posix_info *p = beg;
5485 
5486 		end = beg + le32_to_cpu(p->NextEntryOffset);
5487 		/* last element will have a 0 offset, pick a sensible bound */
5488 		if (end == beg)
5489 			end += 0xFFFF;
5490 	}
5491 
5492 	/* check base buf */
5493 	if (beg + sizeof(struct smb2_posix_info) > end)
5494 		return -1;
5495 	total_len = sizeof(struct smb2_posix_info);
5496 
5497 	/* check owner sid */
5498 	owner_sid = beg + total_len;
5499 	owner_len = posix_info_sid_size(owner_sid, end);
5500 	if (owner_len < 0)
5501 		return -1;
5502 	total_len += owner_len;
5503 
5504 	/* check group sid */
5505 	group_sid = beg + total_len;
5506 	group_len = posix_info_sid_size(group_sid, end);
5507 	if (group_len < 0)
5508 		return -1;
5509 	total_len += group_len;
5510 
5511 	/* check name len */
5512 	if (beg + total_len + 4 > end)
5513 		return -1;
5514 	name_len = le32_to_cpu(*(__le32 *)(beg + total_len));
5515 	if (name_len < 1 || name_len > 0xFFFF)
5516 		return -1;
5517 	total_len += 4;
5518 
5519 	/* check name */
5520 	name = beg + total_len;
5521 	if (name + name_len > end)
5522 		return -1;
5523 	total_len += name_len;
5524 
5525 	if (out) {
5526 		out->base = beg;
5527 		out->size = total_len;
5528 		out->name_len = name_len;
5529 		out->name = name;
5530 		memcpy(&out->owner, owner_sid, owner_len);
5531 		memcpy(&out->group, group_sid, group_len);
5532 	}
5533 	return total_len;
5534 }
5535 
5536 static int posix_info_extra_size(const void *beg, const void *end)
5537 {
5538 	int len = posix_info_parse(beg, end, NULL);
5539 
5540 	if (len < 0)
5541 		return -1;
5542 	return len - sizeof(struct smb2_posix_info);
5543 }
5544 
5545 static unsigned int
5546 num_entries(int infotype, char *bufstart, char *end_of_buf, char **lastentry,
5547 	    size_t size)
5548 {
5549 	int len;
5550 	unsigned int entrycount = 0;
5551 	unsigned int next_offset = 0;
5552 	char *entryptr;
5553 	FILE_DIRECTORY_INFO *dir_info;
5554 
5555 	if (bufstart == NULL)
5556 		return 0;
5557 
5558 	entryptr = bufstart;
5559 
5560 	while (1) {
5561 		if (entryptr + next_offset < entryptr ||
5562 		    entryptr + next_offset > end_of_buf ||
5563 		    entryptr + next_offset + size > end_of_buf) {
5564 			cifs_dbg(VFS, "malformed search entry would overflow\n");
5565 			break;
5566 		}
5567 
5568 		entryptr = entryptr + next_offset;
5569 		dir_info = (FILE_DIRECTORY_INFO *)entryptr;
5570 
5571 		if (infotype == SMB_FIND_FILE_POSIX_INFO)
5572 			len = posix_info_extra_size(entryptr, end_of_buf);
5573 		else
5574 			len = le32_to_cpu(dir_info->FileNameLength);
5575 
5576 		if (len < 0 ||
5577 		    entryptr + len < entryptr ||
5578 		    entryptr + len > end_of_buf ||
5579 		    entryptr + len + size > end_of_buf) {
5580 			cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
5581 				 end_of_buf);
5582 			break;
5583 		}
5584 
5585 		*lastentry = entryptr;
5586 		entrycount++;
5587 
5588 		next_offset = le32_to_cpu(dir_info->NextEntryOffset);
5589 		if (!next_offset)
5590 			break;
5591 	}
5592 
5593 	return entrycount;
5594 }
5595 
5596 /*
5597  * Readdir/FindFirst
5598  */
5599 int SMB2_query_directory_init(const unsigned int xid,
5600 			      struct cifs_tcon *tcon,
5601 			      struct TCP_Server_Info *server,
5602 			      struct smb_rqst *rqst,
5603 			      u64 persistent_fid, u64 volatile_fid,
5604 			      int index, int info_level)
5605 {
5606 	struct smb2_query_directory_req *req;
5607 	unsigned char *bufptr;
5608 	__le16 asteriks = cpu_to_le16('*');
5609 	unsigned int output_size = CIFSMaxBufSize -
5610 		MAX_SMB2_CREATE_RESPONSE_SIZE -
5611 		MAX_SMB2_CLOSE_RESPONSE_SIZE;
5612 	unsigned int total_len;
5613 	struct kvec *iov = rqst->rq_iov;
5614 	int len, rc;
5615 
5616 	rc = smb2_plain_req_init(SMB2_QUERY_DIRECTORY, tcon, server,
5617 				 (void **) &req, &total_len);
5618 	if (rc)
5619 		return rc;
5620 
5621 	switch (info_level) {
5622 	case SMB_FIND_FILE_DIRECTORY_INFO:
5623 		req->FileInformationClass = FILE_DIRECTORY_INFORMATION;
5624 		break;
5625 	case SMB_FIND_FILE_ID_FULL_DIR_INFO:
5626 		req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION;
5627 		break;
5628 	case SMB_FIND_FILE_POSIX_INFO:
5629 		req->FileInformationClass = SMB_FIND_FILE_POSIX_INFO;
5630 		break;
5631 	case SMB_FIND_FILE_FULL_DIRECTORY_INFO:
5632 		req->FileInformationClass = FILE_FULL_DIRECTORY_INFORMATION;
5633 		break;
5634 	default:
5635 		cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
5636 			info_level);
5637 		return -EINVAL;
5638 	}
5639 
5640 	req->FileIndex = cpu_to_le32(index);
5641 	req->PersistentFileId = persistent_fid;
5642 	req->VolatileFileId = volatile_fid;
5643 
5644 	len = 0x2;
5645 	bufptr = req->Buffer;
5646 	memcpy(bufptr, &asteriks, len);
5647 
5648 	req->FileNameOffset =
5649 		cpu_to_le16(sizeof(struct smb2_query_directory_req));
5650 	req->FileNameLength = cpu_to_le16(len);
5651 	/*
5652 	 * BB could be 30 bytes or so longer if we used SMB2 specific
5653 	 * buffer lengths, but this is safe and close enough.
5654 	 */
5655 	output_size = min_t(unsigned int, output_size, server->maxBuf);
5656 	output_size = min_t(unsigned int, output_size, 2 << 15);
5657 	req->OutputBufferLength = cpu_to_le32(output_size);
5658 
5659 	iov[0].iov_base = (char *)req;
5660 	/* 1 for Buffer */
5661 	iov[0].iov_len = total_len - 1;
5662 
5663 	iov[1].iov_base = (char *)(req->Buffer);
5664 	iov[1].iov_len = len;
5665 
5666 	trace_smb3_query_dir_enter(xid, persistent_fid, tcon->tid,
5667 			tcon->ses->Suid, index, output_size);
5668 
5669 	return 0;
5670 }
5671 
5672 void SMB2_query_directory_free(struct smb_rqst *rqst)
5673 {
5674 	if (rqst && rqst->rq_iov) {
5675 		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
5676 	}
5677 }
5678 
5679 int
5680 smb2_parse_query_directory(struct cifs_tcon *tcon,
5681 			   struct kvec *rsp_iov,
5682 			   int resp_buftype,
5683 			   struct cifs_search_info *srch_inf)
5684 {
5685 	struct smb2_query_directory_rsp *rsp;
5686 	size_t info_buf_size;
5687 	char *end_of_smb;
5688 	int rc;
5689 
5690 	rsp = (struct smb2_query_directory_rsp *)rsp_iov->iov_base;
5691 
5692 	switch (srch_inf->info_level) {
5693 	case SMB_FIND_FILE_DIRECTORY_INFO:
5694 		info_buf_size = sizeof(FILE_DIRECTORY_INFO);
5695 		break;
5696 	case SMB_FIND_FILE_ID_FULL_DIR_INFO:
5697 		info_buf_size = sizeof(FILE_ID_FULL_DIR_INFO);
5698 		break;
5699 	case SMB_FIND_FILE_POSIX_INFO:
5700 		/* note that posix payload are variable size */
5701 		info_buf_size = sizeof(struct smb2_posix_info);
5702 		break;
5703 	case SMB_FIND_FILE_FULL_DIRECTORY_INFO:
5704 		info_buf_size = sizeof(FILE_FULL_DIRECTORY_INFO);
5705 		break;
5706 	default:
5707 		cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
5708 			 srch_inf->info_level);
5709 		return -EINVAL;
5710 	}
5711 
5712 	rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5713 			       le32_to_cpu(rsp->OutputBufferLength), rsp_iov,
5714 			       info_buf_size);
5715 	if (rc) {
5716 		cifs_tcon_dbg(VFS, "bad info payload");
5717 		return rc;
5718 	}
5719 
5720 	srch_inf->unicode = true;
5721 
5722 	if (srch_inf->ntwrk_buf_start) {
5723 		if (srch_inf->smallBuf)
5724 			cifs_small_buf_release(srch_inf->ntwrk_buf_start);
5725 		else if (srch_inf->is_dynamic_buf)
5726 			kfree(srch_inf->ntwrk_buf_start);
5727 		else
5728 			cifs_buf_release(srch_inf->ntwrk_buf_start);
5729 	}
5730 	srch_inf->ntwrk_buf_start = (char *)rsp;
5731 	srch_inf->srch_entries_start = srch_inf->last_entry =
5732 		(char *)rsp + le16_to_cpu(rsp->OutputBufferOffset);
5733 	end_of_smb = rsp_iov->iov_len + (char *)rsp;
5734 
5735 	srch_inf->entries_in_buffer = num_entries(
5736 		srch_inf->info_level,
5737 		srch_inf->srch_entries_start,
5738 		end_of_smb,
5739 		&srch_inf->last_entry,
5740 		info_buf_size);
5741 
5742 	srch_inf->index_of_last_entry += srch_inf->entries_in_buffer;
5743 	cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n",
5744 		 srch_inf->entries_in_buffer, srch_inf->index_of_last_entry,
5745 		 srch_inf->srch_entries_start, srch_inf->last_entry);
5746 	if (resp_buftype == CIFS_LARGE_BUFFER) {
5747 		srch_inf->smallBuf = false;
5748 		srch_inf->is_dynamic_buf = false;
5749 	} else if (resp_buftype == CIFS_SMALL_BUFFER) {
5750 		srch_inf->smallBuf = true;
5751 		srch_inf->is_dynamic_buf = false;
5752 	} else if (resp_buftype == CIFS_DYNAMIC_BUFFER) {
5753 		srch_inf->smallBuf = false;
5754 		srch_inf->is_dynamic_buf = true;
5755 	} else {
5756 		cifs_tcon_dbg(VFS, "Invalid search buffer type\n");
5757 	}
5758 
5759 	return 0;
5760 }
5761 
5762 int
5763 SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon,
5764 		     u64 persistent_fid, u64 volatile_fid, int index,
5765 		     struct cifs_search_info *srch_inf)
5766 {
5767 	struct smb_rqst rqst;
5768 	struct kvec iov[SMB2_QUERY_DIRECTORY_IOV_SIZE];
5769 	struct smb2_query_directory_rsp *rsp = NULL;
5770 	int resp_buftype = CIFS_NO_BUFFER;
5771 	struct kvec rsp_iov;
5772 	int rc = 0;
5773 	struct cifs_ses *ses = tcon->ses;
5774 	struct TCP_Server_Info *server;
5775 	int flags = 0;
5776 	int retries = 0, cur_sleep = 0;
5777 
5778 replay_again:
5779 	/* reinitialize for possible replay */
5780 	resp_buftype = CIFS_NO_BUFFER;
5781 	memset(&rsp_iov, 0, sizeof(rsp_iov));
5782 	flags = 0;
5783 	server = cifs_pick_channel(ses);
5784 
5785 	if (!ses || !(ses->server))
5786 		return smb_EIO(smb_eio_trace_null_pointers);
5787 
5788 	if (smb3_encryption_required(tcon))
5789 		flags |= CIFS_TRANSFORM_REQ;
5790 
5791 	memset(&rqst, 0, sizeof(struct smb_rqst));
5792 	memset(&iov, 0, sizeof(iov));
5793 	rqst.rq_iov = iov;
5794 	rqst.rq_nvec = SMB2_QUERY_DIRECTORY_IOV_SIZE;
5795 
5796 	rc = SMB2_query_directory_init(xid, tcon, server,
5797 				       &rqst, persistent_fid,
5798 				       volatile_fid, index,
5799 				       srch_inf->info_level);
5800 	if (rc)
5801 		goto qdir_exit;
5802 
5803 	if (retries) {
5804 		/* Back-off before retry */
5805 		if (cur_sleep)
5806 			msleep(cur_sleep);
5807 		smb2_set_replay(server, &rqst);
5808 	}
5809 
5810 	rc = cifs_send_recv(xid, ses, server,
5811 			    &rqst, &resp_buftype, flags, &rsp_iov);
5812 	rsp = (struct smb2_query_directory_rsp *)rsp_iov.iov_base;
5813 
5814 	if (rc) {
5815 		if (rc == -ENODATA &&
5816 		    rsp->hdr.Status == STATUS_NO_MORE_FILES) {
5817 			trace_smb3_query_dir_done(xid, persistent_fid,
5818 				tcon->tid, tcon->ses->Suid, index, 0);
5819 			srch_inf->endOfSearch = true;
5820 			rc = 0;
5821 		} else {
5822 			trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
5823 				tcon->ses->Suid, index, 0, rc);
5824 			cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE);
5825 		}
5826 		goto qdir_exit;
5827 	}
5828 
5829 	rc = smb2_parse_query_directory(tcon, &rsp_iov,	resp_buftype,
5830 					srch_inf);
5831 	if (rc) {
5832 		trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
5833 			tcon->ses->Suid, index, 0, rc);
5834 		goto qdir_exit;
5835 	}
5836 	resp_buftype = CIFS_NO_BUFFER;
5837 
5838 	trace_smb3_query_dir_done(xid, persistent_fid, tcon->tid,
5839 			tcon->ses->Suid, index, srch_inf->entries_in_buffer);
5840 
5841 qdir_exit:
5842 	SMB2_query_directory_free(&rqst);
5843 	free_rsp_buf(resp_buftype, rsp);
5844 
5845 	if (is_replayable_error(rc) &&
5846 	    smb2_should_replay(tcon, &retries, &cur_sleep))
5847 		goto replay_again;
5848 
5849 	return rc;
5850 }
5851 
5852 int
5853 SMB2_set_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
5854 		   struct smb_rqst *rqst,
5855 		   u64 persistent_fid, u64 volatile_fid, u32 pid,
5856 		   u8 info_class, u8 info_type, u32 additional_info,
5857 		   void **data, unsigned int *size)
5858 {
5859 	struct smb2_set_info_req *req;
5860 	struct kvec *iov = rqst->rq_iov;
5861 	unsigned int i, total_len;
5862 	int rc;
5863 
5864 	rc = smb2_plain_req_init(SMB2_SET_INFO, tcon, server,
5865 				 (void **) &req, &total_len);
5866 	if (rc)
5867 		return rc;
5868 
5869 	req->hdr.Id.SyncId.ProcessId = cpu_to_le32(pid);
5870 	req->InfoType = info_type;
5871 	req->FileInfoClass = info_class;
5872 	req->PersistentFileId = persistent_fid;
5873 	req->VolatileFileId = volatile_fid;
5874 	req->AdditionalInformation = cpu_to_le32(additional_info);
5875 
5876 	req->BufferOffset = cpu_to_le16(sizeof(struct smb2_set_info_req));
5877 	req->BufferLength = cpu_to_le32(*size);
5878 
5879 	memcpy(req->Buffer, *data, *size);
5880 	total_len += *size;
5881 
5882 	iov[0].iov_base = (char *)req;
5883 	/* 1 for Buffer */
5884 	iov[0].iov_len = total_len - 1;
5885 
5886 	for (i = 1; i < rqst->rq_nvec; i++) {
5887 		le32_add_cpu(&req->BufferLength, size[i]);
5888 		iov[i].iov_base = (char *)data[i];
5889 		iov[i].iov_len = size[i];
5890 	}
5891 
5892 	return 0;
5893 }
5894 
5895 void
5896 SMB2_set_info_free(struct smb_rqst *rqst)
5897 {
5898 	if (rqst && rqst->rq_iov)
5899 		cifs_buf_release(rqst->rq_iov[0].iov_base); /* request */
5900 }
5901 
5902 static int
5903 send_set_info(const unsigned int xid, struct cifs_tcon *tcon,
5904 	       u64 persistent_fid, u64 volatile_fid, u32 pid, u8 info_class,
5905 	       u8 info_type, u32 additional_info, unsigned int num,
5906 		void **data, unsigned int *size)
5907 {
5908 	struct smb_rqst rqst;
5909 	struct smb2_set_info_rsp *rsp = NULL;
5910 	struct kvec *iov;
5911 	struct kvec rsp_iov;
5912 	int rc = 0;
5913 	int resp_buftype;
5914 	struct cifs_ses *ses = tcon->ses;
5915 	struct TCP_Server_Info *server;
5916 	int flags = 0;
5917 	int retries = 0, cur_sleep = 0;
5918 
5919 replay_again:
5920 	/* reinitialize for possible replay */
5921 	flags = 0;
5922 	server = cifs_pick_channel(ses);
5923 
5924 	if (!ses || !server)
5925 		return smb_EIO(smb_eio_trace_null_pointers);
5926 
5927 	if (!num)
5928 		return -EINVAL;
5929 
5930 	if (smb3_encryption_required(tcon))
5931 		flags |= CIFS_TRANSFORM_REQ;
5932 
5933 	iov = kmalloc_objs(struct kvec, num);
5934 	if (!iov)
5935 		return -ENOMEM;
5936 
5937 	memset(&rqst, 0, sizeof(struct smb_rqst));
5938 	rqst.rq_iov = iov;
5939 	rqst.rq_nvec = num;
5940 
5941 	rc = SMB2_set_info_init(tcon, server,
5942 				&rqst, persistent_fid, volatile_fid, pid,
5943 				info_class, info_type, additional_info,
5944 				data, size);
5945 	if (rc) {
5946 		kfree(iov);
5947 		return rc;
5948 	}
5949 
5950 	if (retries) {
5951 		/* Back-off before retry */
5952 		if (cur_sleep)
5953 			msleep(cur_sleep);
5954 		smb2_set_replay(server, &rqst);
5955 	}
5956 
5957 	rc = cifs_send_recv(xid, ses, server,
5958 			    &rqst, &resp_buftype, flags,
5959 			    &rsp_iov);
5960 	SMB2_set_info_free(&rqst);
5961 	rsp = (struct smb2_set_info_rsp *)rsp_iov.iov_base;
5962 
5963 	if (rc != 0) {
5964 		cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE);
5965 		trace_smb3_set_info_err(xid, persistent_fid, tcon->tid,
5966 				ses->Suid, info_class, (__u32)info_type, rc);
5967 	}
5968 
5969 	free_rsp_buf(resp_buftype, rsp);
5970 	kfree(iov);
5971 
5972 	if (is_replayable_error(rc) &&
5973 	    smb2_should_replay(tcon, &retries, &cur_sleep))
5974 		goto replay_again;
5975 
5976 	return rc;
5977 }
5978 
5979 int
5980 SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
5981 	     u64 volatile_fid, u32 pid, loff_t new_eof)
5982 {
5983 	struct smb2_file_eof_info info;
5984 	void *data;
5985 	unsigned int size;
5986 
5987 	info.EndOfFile = cpu_to_le64(new_eof);
5988 
5989 	data = &info;
5990 	size = sizeof(struct smb2_file_eof_info);
5991 
5992 	trace_smb3_set_eof(xid, persistent_fid, tcon->tid, tcon->ses->Suid, new_eof);
5993 
5994 	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5995 			pid, FILE_END_OF_FILE_INFORMATION, SMB2_O_INFO_FILE,
5996 			0, 1, &data, &size);
5997 }
5998 
5999 int
6000 SMB2_set_allocation(const unsigned int xid, struct cifs_tcon *tcon,
6001 		    u64 persistent_fid, u64 volatile_fid, u32 pid,
6002 		    loff_t allocation_size)
6003 {
6004 	struct smb2_file_alloc_info info;
6005 	void *data;
6006 	unsigned int size;
6007 
6008 	info.AllocationSize = cpu_to_le64(allocation_size);
6009 
6010 	data = &info;
6011 	size = sizeof(struct smb2_file_alloc_info);
6012 
6013 	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
6014 			pid, FILE_ALLOCATION_INFORMATION, SMB2_O_INFO_FILE,
6015 			0, 1, &data, &size);
6016 }
6017 
6018 int
6019 SMB2_set_acl(const unsigned int xid, struct cifs_tcon *tcon,
6020 		u64 persistent_fid, u64 volatile_fid,
6021 		struct smb_ntsd *pnntsd, int pacllen, int aclflag)
6022 {
6023 	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
6024 			current->tgid, 0, SMB2_O_INFO_SECURITY, aclflag,
6025 			1, (void **)&pnntsd, &pacllen);
6026 }
6027 
6028 int
6029 SMB2_set_ea(const unsigned int xid, struct cifs_tcon *tcon,
6030 	    u64 persistent_fid, u64 volatile_fid,
6031 	    struct smb2_file_full_ea_info *buf, int len)
6032 {
6033 	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
6034 		current->tgid, FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE,
6035 		0, 1, (void **)&buf, &len);
6036 }
6037 
6038 int
6039 SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon,
6040 		  const u64 persistent_fid, const u64 volatile_fid,
6041 		  __u8 oplock_level)
6042 {
6043 	struct smb_rqst rqst;
6044 	int rc;
6045 	struct smb2_oplock_break *req = NULL;
6046 	struct cifs_ses *ses = tcon->ses;
6047 	struct TCP_Server_Info *server;
6048 	int flags = CIFS_OBREAK_OP;
6049 	unsigned int total_len;
6050 	struct kvec iov[1];
6051 	struct kvec rsp_iov;
6052 	int resp_buf_type;
6053 	int retries = 0, cur_sleep = 0;
6054 
6055 replay_again:
6056 	/* reinitialize for possible replay */
6057 	flags = CIFS_OBREAK_OP;
6058 	server = cifs_pick_channel(ses);
6059 
6060 	cifs_dbg(FYI, "SMB2_oplock_break\n");
6061 	rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
6062 				 (void **) &req, &total_len);
6063 	if (rc)
6064 		return rc;
6065 
6066 	if (smb3_encryption_required(tcon))
6067 		flags |= CIFS_TRANSFORM_REQ;
6068 
6069 	req->VolatileFid = volatile_fid;
6070 	req->PersistentFid = persistent_fid;
6071 	req->OplockLevel = oplock_level;
6072 	req->hdr.CreditRequest = cpu_to_le16(1);
6073 
6074 	flags |= CIFS_NO_RSP_BUF;
6075 
6076 	iov[0].iov_base = (char *)req;
6077 	iov[0].iov_len = total_len;
6078 
6079 	memset(&rqst, 0, sizeof(struct smb_rqst));
6080 	rqst.rq_iov = iov;
6081 	rqst.rq_nvec = 1;
6082 
6083 	if (retries) {
6084 		/* Back-off before retry */
6085 		if (cur_sleep)
6086 			msleep(cur_sleep);
6087 		smb2_set_replay(server, &rqst);
6088 	}
6089 
6090 	rc = cifs_send_recv(xid, ses, server,
6091 			    &rqst, &resp_buf_type, flags, &rsp_iov);
6092 	cifs_small_buf_release(req);
6093 	if (rc) {
6094 		cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
6095 		cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc);
6096 	}
6097 
6098 	if (is_replayable_error(rc) &&
6099 	    smb2_should_replay(tcon, &retries, &cur_sleep))
6100 		goto replay_again;
6101 
6102 	return rc;
6103 }
6104 
6105 void
6106 smb2_copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf,
6107 			     struct kstatfs *kst)
6108 {
6109 	kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) *
6110 			  le32_to_cpu(pfs_inf->SectorsPerAllocationUnit);
6111 	kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits);
6112 	kst->f_bfree  = kst->f_bavail =
6113 			le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits);
6114 	return;
6115 }
6116 
6117 static void
6118 copy_posix_fs_info_to_kstatfs(FILE_SYSTEM_POSIX_INFO *response_data,
6119 			struct kstatfs *kst)
6120 {
6121 	kst->f_bsize = le32_to_cpu(response_data->BlockSize);
6122 	kst->f_blocks = le64_to_cpu(response_data->TotalBlocks);
6123 	kst->f_bfree =  le64_to_cpu(response_data->BlocksAvail);
6124 	if (response_data->UserBlocksAvail == cpu_to_le64(-1))
6125 		kst->f_bavail = kst->f_bfree;
6126 	else
6127 		kst->f_bavail = le64_to_cpu(response_data->UserBlocksAvail);
6128 	if (response_data->TotalFileNodes != cpu_to_le64(-1))
6129 		kst->f_files = le64_to_cpu(response_data->TotalFileNodes);
6130 	if (response_data->FreeFileNodes != cpu_to_le64(-1))
6131 		kst->f_ffree = le64_to_cpu(response_data->FreeFileNodes);
6132 
6133 	return;
6134 }
6135 
6136 static int
6137 build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon,
6138 		   struct TCP_Server_Info *server,
6139 		   int level, int outbuf_len, u64 persistent_fid,
6140 		   u64 volatile_fid)
6141 {
6142 	int rc;
6143 	struct smb2_query_info_req *req;
6144 	unsigned int total_len;
6145 
6146 	cifs_dbg(FYI, "Query FSInfo level %d\n", level);
6147 
6148 	if ((tcon->ses == NULL) || server == NULL)
6149 		return smb_EIO(smb_eio_trace_null_pointers);
6150 
6151 	rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
6152 				 (void **) &req, &total_len);
6153 	if (rc)
6154 		return rc;
6155 
6156 	req->InfoType = SMB2_O_INFO_FILESYSTEM;
6157 	req->FileInfoClass = level;
6158 	req->PersistentFileId = persistent_fid;
6159 	req->VolatileFileId = volatile_fid;
6160 	/* 1 for pad */
6161 	req->InputBufferOffset =
6162 			cpu_to_le16(sizeof(struct smb2_query_info_req));
6163 	req->OutputBufferLength = cpu_to_le32(
6164 		outbuf_len + sizeof(struct smb2_query_info_rsp));
6165 
6166 	iov->iov_base = (char *)req;
6167 	iov->iov_len = total_len;
6168 	return 0;
6169 }
6170 
6171 static inline void free_qfs_info_req(struct kvec *iov)
6172 {
6173 	cifs_buf_release(iov->iov_base);
6174 }
6175 
6176 int
6177 SMB311_posix_qfs_info(const unsigned int xid, struct cifs_tcon *tcon,
6178 	      u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
6179 {
6180 	struct smb_rqst rqst;
6181 	struct smb2_query_info_rsp *rsp = NULL;
6182 	struct kvec iov;
6183 	struct kvec rsp_iov;
6184 	int rc = 0;
6185 	int resp_buftype;
6186 	struct cifs_ses *ses = tcon->ses;
6187 	struct TCP_Server_Info *server;
6188 	FILE_SYSTEM_POSIX_INFO *info = NULL;
6189 	int flags = 0;
6190 	int retries = 0, cur_sleep = 0;
6191 
6192 replay_again:
6193 	/* reinitialize for possible replay */
6194 	flags = 0;
6195 	server = cifs_pick_channel(ses);
6196 
6197 	rc = build_qfs_info_req(&iov, tcon, server,
6198 				FS_POSIX_INFORMATION,
6199 				sizeof(FILE_SYSTEM_POSIX_INFO),
6200 				persistent_fid, volatile_fid);
6201 	if (rc)
6202 		return rc;
6203 
6204 	if (smb3_encryption_required(tcon))
6205 		flags |= CIFS_TRANSFORM_REQ;
6206 
6207 	memset(&rqst, 0, sizeof(struct smb_rqst));
6208 	rqst.rq_iov = &iov;
6209 	rqst.rq_nvec = 1;
6210 
6211 	if (retries) {
6212 		/* Back-off before retry */
6213 		if (cur_sleep)
6214 			msleep(cur_sleep);
6215 		smb2_set_replay(server, &rqst);
6216 	}
6217 
6218 	rc = cifs_send_recv(xid, ses, server,
6219 			    &rqst, &resp_buftype, flags, &rsp_iov);
6220 	free_qfs_info_req(&iov);
6221 	if (rc) {
6222 		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
6223 		goto posix_qfsinf_exit;
6224 	}
6225 	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
6226 
6227 	info = (FILE_SYSTEM_POSIX_INFO *)(
6228 		le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
6229 	rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
6230 			       le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
6231 			       sizeof(FILE_SYSTEM_POSIX_INFO));
6232 	if (!rc)
6233 		copy_posix_fs_info_to_kstatfs(info, fsdata);
6234 
6235 posix_qfsinf_exit:
6236 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
6237 
6238 	if (is_replayable_error(rc) &&
6239 	    smb2_should_replay(tcon, &retries, &cur_sleep))
6240 		goto replay_again;
6241 
6242 	return rc;
6243 }
6244 
6245 int
6246 SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon,
6247 	      u64 persistent_fid, u64 volatile_fid, int level)
6248 {
6249 	struct smb_rqst rqst;
6250 	struct smb2_query_info_rsp *rsp = NULL;
6251 	struct kvec iov;
6252 	struct kvec rsp_iov;
6253 	int rc = 0;
6254 	int resp_buftype, max_len, min_len;
6255 	struct cifs_ses *ses = tcon->ses;
6256 	struct TCP_Server_Info *server;
6257 	unsigned int rsp_len, offset;
6258 	int flags = 0;
6259 	int retries = 0, cur_sleep = 0;
6260 
6261 replay_again:
6262 	/* reinitialize for possible replay */
6263 	flags = 0;
6264 	server = cifs_pick_channel(ses);
6265 
6266 	if (level == FS_DEVICE_INFORMATION) {
6267 		max_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
6268 		min_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
6269 	} else if (level == FS_ATTRIBUTE_INFORMATION) {
6270 		max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO) + MAX_FS_NAME_LEN;
6271 		min_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO);
6272 	} else if (level == FS_SECTOR_SIZE_INFORMATION) {
6273 		max_len = sizeof(struct smb3_fs_ss_info);
6274 		min_len = sizeof(struct smb3_fs_ss_info);
6275 	} else if (level == FS_VOLUME_INFORMATION) {
6276 		max_len = sizeof(struct filesystem_vol_info) + MAX_VOL_LABEL_LEN;
6277 		min_len = sizeof(struct filesystem_vol_info);
6278 	} else {
6279 		cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level);
6280 		return -EINVAL;
6281 	}
6282 
6283 	rc = build_qfs_info_req(&iov, tcon, server,
6284 				level, max_len,
6285 				persistent_fid, volatile_fid);
6286 	if (rc)
6287 		return rc;
6288 
6289 	if (smb3_encryption_required(tcon))
6290 		flags |= CIFS_TRANSFORM_REQ;
6291 
6292 	memset(&rqst, 0, sizeof(struct smb_rqst));
6293 	rqst.rq_iov = &iov;
6294 	rqst.rq_nvec = 1;
6295 
6296 	if (retries) {
6297 		/* Back-off before retry */
6298 		if (cur_sleep)
6299 			msleep(cur_sleep);
6300 		smb2_set_replay(server, &rqst);
6301 	}
6302 
6303 	rc = cifs_send_recv(xid, ses, server,
6304 			    &rqst, &resp_buftype, flags, &rsp_iov);
6305 	free_qfs_info_req(&iov);
6306 	if (rc) {
6307 		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
6308 		goto qfsattr_exit;
6309 	}
6310 	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
6311 
6312 	rsp_len = le32_to_cpu(rsp->OutputBufferLength);
6313 	offset = le16_to_cpu(rsp->OutputBufferOffset);
6314 	rc = smb2_validate_iov(offset, rsp_len, &rsp_iov, min_len);
6315 	if (rc)
6316 		goto qfsattr_exit;
6317 
6318 	if (level == FS_ATTRIBUTE_INFORMATION)
6319 		memcpy(&tcon->fsAttrInfo, offset
6320 			+ (char *)rsp, min_t(unsigned int,
6321 			rsp_len, min_len));
6322 	else if (level == FS_DEVICE_INFORMATION)
6323 		memcpy(&tcon->fsDevInfo, offset
6324 			+ (char *)rsp, sizeof(FILE_SYSTEM_DEVICE_INFO));
6325 	else if (level == FS_SECTOR_SIZE_INFORMATION) {
6326 		struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *)
6327 			(offset + (char *)rsp);
6328 		tcon->ss_flags = le32_to_cpu(ss_info->Flags);
6329 		tcon->perf_sector_size =
6330 			le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf);
6331 	} else if (level == FS_VOLUME_INFORMATION) {
6332 		struct filesystem_vol_info *vol_info = (struct filesystem_vol_info *)
6333 			(offset + (char *)rsp);
6334 		tcon->vol_serial_number = le32_to_cpu(vol_info->VolumeSerialNumber);
6335 		tcon->vol_create_time = vol_info->VolumeCreationTime;
6336 	}
6337 
6338 qfsattr_exit:
6339 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
6340 
6341 	if (is_replayable_error(rc) &&
6342 	    smb2_should_replay(tcon, &retries, &cur_sleep))
6343 		goto replay_again;
6344 
6345 	return rc;
6346 }
6347 
6348 int
6349 smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon,
6350 	   const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
6351 	   const __u32 num_lock, struct smb2_lock_element *buf)
6352 {
6353 	struct smb_rqst rqst;
6354 	int rc = 0;
6355 	struct smb2_lock_req *req = NULL;
6356 	struct kvec iov[2];
6357 	struct kvec rsp_iov;
6358 	int resp_buf_type;
6359 	unsigned int count;
6360 	int flags = CIFS_NO_RSP_BUF;
6361 	unsigned int total_len;
6362 	struct TCP_Server_Info *server;
6363 	int retries = 0, cur_sleep = 0;
6364 
6365 replay_again:
6366 	/* reinitialize for possible replay */
6367 	flags = CIFS_NO_RSP_BUF;
6368 	server = cifs_pick_channel(tcon->ses);
6369 
6370 	cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock);
6371 
6372 	rc = smb2_plain_req_init(SMB2_LOCK, tcon, server,
6373 				 (void **) &req, &total_len);
6374 	if (rc)
6375 		return rc;
6376 
6377 	if (smb3_encryption_required(tcon))
6378 		flags |= CIFS_TRANSFORM_REQ;
6379 
6380 	req->hdr.Id.SyncId.ProcessId = cpu_to_le32(pid);
6381 	req->LockCount = cpu_to_le16(num_lock);
6382 
6383 	req->PersistentFileId = persist_fid;
6384 	req->VolatileFileId = volatile_fid;
6385 
6386 	count = num_lock * sizeof(struct smb2_lock_element);
6387 
6388 	iov[0].iov_base = (char *)req;
6389 	iov[0].iov_len = total_len - sizeof(struct smb2_lock_element);
6390 	iov[1].iov_base = (char *)buf;
6391 	iov[1].iov_len = count;
6392 
6393 	cifs_stats_inc(&tcon->stats.cifs_stats.num_locks);
6394 
6395 	memset(&rqst, 0, sizeof(struct smb_rqst));
6396 	rqst.rq_iov = iov;
6397 	rqst.rq_nvec = 2;
6398 
6399 	if (retries) {
6400 		/* Back-off before retry */
6401 		if (cur_sleep)
6402 			msleep(cur_sleep);
6403 		smb2_set_replay(server, &rqst);
6404 	}
6405 
6406 	trace_smb3_lock_enter(xid, persist_fid, tcon->tid, tcon->ses->Suid,
6407 			      le64_to_cpu(buf[0].Offset),
6408 			      le64_to_cpu(buf[0].Length),
6409 			      le32_to_cpu(buf[0].Flags), num_lock, 0);
6410 
6411 	rc = cifs_send_recv(xid, tcon->ses, server,
6412 			    &rqst, &resp_buf_type, flags,
6413 			    &rsp_iov);
6414 	cifs_small_buf_release(req);
6415 	if (rc) {
6416 		cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc);
6417 		cifs_stats_fail_inc(tcon, SMB2_LOCK_HE);
6418 		trace_smb3_lock_err(xid, persist_fid, tcon->tid,
6419 				    tcon->ses->Suid,
6420 				    le64_to_cpu(buf[0].Offset),
6421 				    le64_to_cpu(buf[0].Length),
6422 				    le32_to_cpu(buf[0].Flags), num_lock, rc);
6423 	} else {
6424 		trace_smb3_lock_done(xid, persist_fid, tcon->tid, tcon->ses->Suid,
6425 				     le64_to_cpu(buf[0].Offset),
6426 				     le64_to_cpu(buf[0].Length),
6427 				     le32_to_cpu(buf[0].Flags), num_lock, 0);
6428 	}
6429 
6430 	if (is_replayable_error(rc) &&
6431 	    smb2_should_replay(tcon, &retries, &cur_sleep))
6432 		goto replay_again;
6433 
6434 	return rc;
6435 }
6436 
6437 int
6438 SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon,
6439 	  const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
6440 	  const __u64 length, const __u64 offset, const __u32 lock_flags,
6441 	  const bool wait)
6442 {
6443 	struct smb2_lock_element lock;
6444 
6445 	lock.Offset = cpu_to_le64(offset);
6446 	lock.Length = cpu_to_le64(length);
6447 	lock.Flags = cpu_to_le32(lock_flags);
6448 	if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK)
6449 		lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY);
6450 
6451 	return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock);
6452 }
6453 
6454 int
6455 SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon,
6456 		 __u8 *lease_key, const __le32 lease_state)
6457 {
6458 	struct smb_rqst rqst;
6459 	int rc;
6460 	struct smb2_lease_ack *req = NULL;
6461 	struct cifs_ses *ses = tcon->ses;
6462 	int flags = CIFS_OBREAK_OP;
6463 	unsigned int total_len;
6464 	struct kvec iov[1];
6465 	struct kvec rsp_iov;
6466 	int resp_buf_type;
6467 	__u64 *please_key_high;
6468 	__u64 *please_key_low;
6469 	struct TCP_Server_Info *server = cifs_pick_channel(tcon->ses);
6470 
6471 	cifs_dbg(FYI, "SMB2_lease_break\n");
6472 	rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
6473 				 (void **) &req, &total_len);
6474 	if (rc)
6475 		return rc;
6476 
6477 	if (smb3_encryption_required(tcon))
6478 		flags |= CIFS_TRANSFORM_REQ;
6479 
6480 	req->hdr.CreditRequest = cpu_to_le16(1);
6481 	req->StructureSize = cpu_to_le16(36);
6482 	total_len += 12;
6483 
6484 	memcpy(req->LeaseKey, lease_key, SMB2_LEASE_KEY_SIZE);
6485 	req->LeaseState = lease_state;
6486 
6487 	flags |= CIFS_NO_RSP_BUF;
6488 
6489 	iov[0].iov_base = (char *)req;
6490 	iov[0].iov_len = total_len;
6491 
6492 	memset(&rqst, 0, sizeof(struct smb_rqst));
6493 	rqst.rq_iov = iov;
6494 	rqst.rq_nvec = 1;
6495 
6496 	rc = cifs_send_recv(xid, ses, server,
6497 			    &rqst, &resp_buf_type, flags, &rsp_iov);
6498 	cifs_small_buf_release(req);
6499 
6500 	please_key_low = (__u64 *)lease_key;
6501 	please_key_high = (__u64 *)(lease_key+8);
6502 	if (rc) {
6503 		cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
6504 		trace_smb3_lease_ack_err(le32_to_cpu(lease_state), tcon->tid,
6505 			ses->Suid, *please_key_low, *please_key_high, rc);
6506 		cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc);
6507 	} else
6508 		trace_smb3_lease_ack_done(le32_to_cpu(lease_state), tcon->tid,
6509 			ses->Suid, *please_key_low, *please_key_high);
6510 
6511 	return rc;
6512 }
6513