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