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