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