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