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