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