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