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