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