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