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