xref: /openbmc/linux/fs/smb/client/smb2pdu.c (revision b96ea433)
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 = cifs_pick_channel(ses);
2023 
2024 	cifs_dbg(FYI, "TCON\n");
2025 
2026 	if (!server || !tree)
2027 		return -EIO;
2028 
2029 	unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
2030 	if (unc_path == NULL)
2031 		return -ENOMEM;
2032 
2033 	unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp);
2034 	if (unc_path_len <= 0) {
2035 		kfree(unc_path);
2036 		return -EINVAL;
2037 	}
2038 	unc_path_len *= 2;
2039 
2040 	/* SMB2 TREE_CONNECT request must be called with TreeId == 0 */
2041 	tcon->tid = 0;
2042 	atomic_set(&tcon->num_remote_opens, 0);
2043 	rc = smb2_plain_req_init(SMB2_TREE_CONNECT, tcon, server,
2044 				 (void **) &req, &total_len);
2045 	if (rc) {
2046 		kfree(unc_path);
2047 		return rc;
2048 	}
2049 
2050 	if (smb3_encryption_required(tcon))
2051 		flags |= CIFS_TRANSFORM_REQ;
2052 
2053 	iov[0].iov_base = (char *)req;
2054 	/* 1 for pad */
2055 	iov[0].iov_len = total_len - 1;
2056 
2057 	/* Testing shows that buffer offset must be at location of Buffer[0] */
2058 	req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req));
2059 	req->PathLength = cpu_to_le16(unc_path_len);
2060 	iov[1].iov_base = unc_path;
2061 	iov[1].iov_len = unc_path_len;
2062 
2063 	/*
2064 	 * 3.11 tcon req must be signed if not encrypted. See MS-SMB2 3.2.4.1.1
2065 	 * unless it is guest or anonymous user. See MS-SMB2 3.2.5.3.1
2066 	 * (Samba servers don't always set the flag so also check if null user)
2067 	 */
2068 	if ((server->dialect == SMB311_PROT_ID) &&
2069 	    !smb3_encryption_required(tcon) &&
2070 	    !(ses->session_flags &
2071 		    (SMB2_SESSION_FLAG_IS_GUEST|SMB2_SESSION_FLAG_IS_NULL)) &&
2072 	    ((ses->user_name != NULL) || (ses->sectype == Kerberos)))
2073 		req->hdr.Flags |= SMB2_FLAGS_SIGNED;
2074 
2075 	memset(&rqst, 0, sizeof(struct smb_rqst));
2076 	rqst.rq_iov = iov;
2077 	rqst.rq_nvec = 2;
2078 
2079 	/* Need 64 for max size write so ask for more in case not there yet */
2080 	if (server->credits >= server->max_credits)
2081 		req->hdr.CreditRequest = cpu_to_le16(0);
2082 	else
2083 		req->hdr.CreditRequest = cpu_to_le16(
2084 			min_t(int, server->max_credits -
2085 			      server->credits, 64));
2086 
2087 	rc = cifs_send_recv(xid, ses, server,
2088 			    &rqst, &resp_buftype, flags, &rsp_iov);
2089 	cifs_small_buf_release(req);
2090 	rsp = (struct smb2_tree_connect_rsp *)rsp_iov.iov_base;
2091 	trace_smb3_tcon(xid, tcon->tid, ses->Suid, tree, rc);
2092 	if ((rc != 0) || (rsp == NULL)) {
2093 		cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
2094 		tcon->need_reconnect = true;
2095 		goto tcon_error_exit;
2096 	}
2097 
2098 	switch (rsp->ShareType) {
2099 	case SMB2_SHARE_TYPE_DISK:
2100 		cifs_dbg(FYI, "connection to disk share\n");
2101 		break;
2102 	case SMB2_SHARE_TYPE_PIPE:
2103 		tcon->pipe = true;
2104 		cifs_dbg(FYI, "connection to pipe share\n");
2105 		break;
2106 	case SMB2_SHARE_TYPE_PRINT:
2107 		tcon->print = true;
2108 		cifs_dbg(FYI, "connection to printer\n");
2109 		break;
2110 	default:
2111 		cifs_server_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
2112 		rc = -EOPNOTSUPP;
2113 		goto tcon_error_exit;
2114 	}
2115 
2116 	tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
2117 	tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
2118 	tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
2119 	tcon->tid = le32_to_cpu(rsp->hdr.Id.SyncId.TreeId);
2120 	strscpy(tcon->tree_name, tree, sizeof(tcon->tree_name));
2121 
2122 	if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
2123 	    ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
2124 		cifs_tcon_dbg(VFS, "DFS capability contradicts DFS flag\n");
2125 
2126 	if (tcon->seal &&
2127 	    !(server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
2128 		cifs_tcon_dbg(VFS, "Encryption is requested but not supported\n");
2129 
2130 	init_copy_chunk_defaults(tcon);
2131 	if (server->ops->validate_negotiate)
2132 		rc = server->ops->validate_negotiate(xid, tcon);
2133 	if (rc == 0) /* See MS-SMB2 2.2.10 and 3.2.5.5 */
2134 		if (tcon->share_flags & SMB2_SHAREFLAG_ISOLATED_TRANSPORT)
2135 			server->nosharesock = true;
2136 tcon_exit:
2137 
2138 	free_rsp_buf(resp_buftype, rsp);
2139 	kfree(unc_path);
2140 	return rc;
2141 
2142 tcon_error_exit:
2143 	if (rsp && rsp->hdr.Status == STATUS_BAD_NETWORK_NAME)
2144 		cifs_tcon_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree);
2145 	goto tcon_exit;
2146 }
2147 
2148 int
2149 SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon)
2150 {
2151 	struct smb_rqst rqst;
2152 	struct smb2_tree_disconnect_req *req; /* response is trivial */
2153 	int rc = 0;
2154 	struct cifs_ses *ses = tcon->ses;
2155 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
2156 	int flags = 0;
2157 	unsigned int total_len;
2158 	struct kvec iov[1];
2159 	struct kvec rsp_iov;
2160 	int resp_buf_type;
2161 
2162 	cifs_dbg(FYI, "Tree Disconnect\n");
2163 
2164 	if (!ses || !(ses->server))
2165 		return -EIO;
2166 
2167 	trace_smb3_tdis_enter(xid, tcon->tid, ses->Suid, tcon->tree_name);
2168 	spin_lock(&ses->chan_lock);
2169 	if ((tcon->need_reconnect) ||
2170 	    (CIFS_ALL_CHANS_NEED_RECONNECT(tcon->ses))) {
2171 		spin_unlock(&ses->chan_lock);
2172 		return 0;
2173 	}
2174 	spin_unlock(&ses->chan_lock);
2175 
2176 	invalidate_all_cached_dirs(tcon);
2177 
2178 	rc = smb2_plain_req_init(SMB2_TREE_DISCONNECT, tcon, server,
2179 				 (void **) &req,
2180 				 &total_len);
2181 	if (rc)
2182 		return rc;
2183 
2184 	if (smb3_encryption_required(tcon))
2185 		flags |= CIFS_TRANSFORM_REQ;
2186 
2187 	flags |= CIFS_NO_RSP_BUF;
2188 
2189 	iov[0].iov_base = (char *)req;
2190 	iov[0].iov_len = total_len;
2191 
2192 	memset(&rqst, 0, sizeof(struct smb_rqst));
2193 	rqst.rq_iov = iov;
2194 	rqst.rq_nvec = 1;
2195 
2196 	rc = cifs_send_recv(xid, ses, server,
2197 			    &rqst, &resp_buf_type, flags, &rsp_iov);
2198 	cifs_small_buf_release(req);
2199 	if (rc) {
2200 		cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE);
2201 		trace_smb3_tdis_err(xid, tcon->tid, ses->Suid, rc);
2202 	}
2203 	trace_smb3_tdis_done(xid, tcon->tid, ses->Suid);
2204 
2205 	return rc;
2206 }
2207 
2208 
2209 static struct create_durable *
2210 create_durable_buf(void)
2211 {
2212 	struct create_durable *buf;
2213 
2214 	buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
2215 	if (!buf)
2216 		return NULL;
2217 
2218 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2219 					(struct create_durable, Data));
2220 	buf->ccontext.DataLength = cpu_to_le32(16);
2221 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2222 				(struct create_durable, Name));
2223 	buf->ccontext.NameLength = cpu_to_le16(4);
2224 	/* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DHnQ" */
2225 	buf->Name[0] = 'D';
2226 	buf->Name[1] = 'H';
2227 	buf->Name[2] = 'n';
2228 	buf->Name[3] = 'Q';
2229 	return buf;
2230 }
2231 
2232 static struct create_durable *
2233 create_reconnect_durable_buf(struct cifs_fid *fid)
2234 {
2235 	struct create_durable *buf;
2236 
2237 	buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
2238 	if (!buf)
2239 		return NULL;
2240 
2241 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2242 					(struct create_durable, Data));
2243 	buf->ccontext.DataLength = cpu_to_le32(16);
2244 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2245 				(struct create_durable, Name));
2246 	buf->ccontext.NameLength = cpu_to_le16(4);
2247 	buf->Data.Fid.PersistentFileId = fid->persistent_fid;
2248 	buf->Data.Fid.VolatileFileId = fid->volatile_fid;
2249 	/* SMB2_CREATE_DURABLE_HANDLE_RECONNECT is "DHnC" */
2250 	buf->Name[0] = 'D';
2251 	buf->Name[1] = 'H';
2252 	buf->Name[2] = 'n';
2253 	buf->Name[3] = 'C';
2254 	return buf;
2255 }
2256 
2257 static void
2258 parse_query_id_ctxt(struct create_context *cc, struct smb2_file_all_info *buf)
2259 {
2260 	struct create_disk_id_rsp *pdisk_id = (struct create_disk_id_rsp *)cc;
2261 
2262 	cifs_dbg(FYI, "parse query id context 0x%llx 0x%llx\n",
2263 		pdisk_id->DiskFileId, pdisk_id->VolumeId);
2264 	buf->IndexNumber = pdisk_id->DiskFileId;
2265 }
2266 
2267 static void
2268 parse_posix_ctxt(struct create_context *cc, struct smb2_file_all_info *info,
2269 		 struct create_posix_rsp *posix)
2270 {
2271 	int sid_len;
2272 	u8 *beg = (u8 *)cc + le16_to_cpu(cc->DataOffset);
2273 	u8 *end = beg + le32_to_cpu(cc->DataLength);
2274 	u8 *sid;
2275 
2276 	memset(posix, 0, sizeof(*posix));
2277 
2278 	posix->nlink = le32_to_cpu(*(__le32 *)(beg + 0));
2279 	posix->reparse_tag = le32_to_cpu(*(__le32 *)(beg + 4));
2280 	posix->mode = le32_to_cpu(*(__le32 *)(beg + 8));
2281 
2282 	sid = beg + 12;
2283 	sid_len = posix_info_sid_size(sid, end);
2284 	if (sid_len < 0) {
2285 		cifs_dbg(VFS, "bad owner sid in posix create response\n");
2286 		return;
2287 	}
2288 	memcpy(&posix->owner, sid, sid_len);
2289 
2290 	sid = sid + sid_len;
2291 	sid_len = posix_info_sid_size(sid, end);
2292 	if (sid_len < 0) {
2293 		cifs_dbg(VFS, "bad group sid in posix create response\n");
2294 		return;
2295 	}
2296 	memcpy(&posix->group, sid, sid_len);
2297 
2298 	cifs_dbg(FYI, "nlink=%d mode=%o reparse_tag=%x\n",
2299 		 posix->nlink, posix->mode, posix->reparse_tag);
2300 }
2301 
2302 int smb2_parse_contexts(struct TCP_Server_Info *server,
2303 			struct kvec *rsp_iov,
2304 			unsigned int *epoch,
2305 			char *lease_key, __u8 *oplock,
2306 			struct smb2_file_all_info *buf,
2307 			struct create_posix_rsp *posix)
2308 {
2309 	struct smb2_create_rsp *rsp = rsp_iov->iov_base;
2310 	struct create_context *cc;
2311 	size_t rem, off, len;
2312 	size_t doff, dlen;
2313 	size_t noff, nlen;
2314 	char *name;
2315 	static const char smb3_create_tag_posix[] = {
2316 		0x93, 0xAD, 0x25, 0x50, 0x9C,
2317 		0xB4, 0x11, 0xE7, 0xB4, 0x23, 0x83,
2318 		0xDE, 0x96, 0x8B, 0xCD, 0x7C
2319 	};
2320 
2321 	*oplock = 0;
2322 
2323 	off = le32_to_cpu(rsp->CreateContextsOffset);
2324 	rem = le32_to_cpu(rsp->CreateContextsLength);
2325 	if (check_add_overflow(off, rem, &len) || len > rsp_iov->iov_len)
2326 		return -EINVAL;
2327 	cc = (struct create_context *)((u8 *)rsp + off);
2328 
2329 	/* Initialize inode number to 0 in case no valid data in qfid context */
2330 	if (buf)
2331 		buf->IndexNumber = 0;
2332 
2333 	while (rem >= sizeof(*cc)) {
2334 		doff = le16_to_cpu(cc->DataOffset);
2335 		dlen = le32_to_cpu(cc->DataLength);
2336 		if (check_add_overflow(doff, dlen, &len) || len > rem)
2337 			return -EINVAL;
2338 
2339 		noff = le16_to_cpu(cc->NameOffset);
2340 		nlen = le16_to_cpu(cc->NameLength);
2341 		if (noff + nlen > doff)
2342 			return -EINVAL;
2343 
2344 		name = (char *)cc + noff;
2345 		switch (nlen) {
2346 		case 4:
2347 			if (!strncmp(name, SMB2_CREATE_REQUEST_LEASE, 4)) {
2348 				*oplock = server->ops->parse_lease_buf(cc, epoch,
2349 								       lease_key);
2350 			} else if (buf &&
2351 				   !strncmp(name, SMB2_CREATE_QUERY_ON_DISK_ID, 4)) {
2352 				parse_query_id_ctxt(cc, buf);
2353 			}
2354 			break;
2355 		case 16:
2356 			if (posix && !memcmp(name, smb3_create_tag_posix, 16))
2357 				parse_posix_ctxt(cc, buf, posix);
2358 			break;
2359 		default:
2360 			cifs_dbg(FYI, "%s: unhandled context (nlen=%zu dlen=%zu)\n",
2361 				 __func__, nlen, dlen);
2362 			if (IS_ENABLED(CONFIG_CIFS_DEBUG2))
2363 				cifs_dump_mem("context data: ", cc, dlen);
2364 			break;
2365 		}
2366 
2367 		off = le32_to_cpu(cc->Next);
2368 		if (!off)
2369 			break;
2370 		if (check_sub_overflow(rem, off, &rem))
2371 			return -EINVAL;
2372 		cc = (struct create_context *)((u8 *)cc + off);
2373 	}
2374 
2375 	if (rsp->OplockLevel != SMB2_OPLOCK_LEVEL_LEASE)
2376 		*oplock = rsp->OplockLevel;
2377 
2378 	return 0;
2379 }
2380 
2381 static int
2382 add_lease_context(struct TCP_Server_Info *server,
2383 		  struct smb2_create_req *req,
2384 		  struct kvec *iov,
2385 		  unsigned int *num_iovec, u8 *lease_key, __u8 *oplock)
2386 {
2387 	unsigned int num = *num_iovec;
2388 
2389 	iov[num].iov_base = server->ops->create_lease_buf(lease_key, *oplock);
2390 	if (iov[num].iov_base == NULL)
2391 		return -ENOMEM;
2392 	iov[num].iov_len = server->vals->create_lease_size;
2393 	req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
2394 	*num_iovec = num + 1;
2395 	return 0;
2396 }
2397 
2398 static struct create_durable_v2 *
2399 create_durable_v2_buf(struct cifs_open_parms *oparms)
2400 {
2401 	struct cifs_fid *pfid = oparms->fid;
2402 	struct create_durable_v2 *buf;
2403 
2404 	buf = kzalloc(sizeof(struct create_durable_v2), GFP_KERNEL);
2405 	if (!buf)
2406 		return NULL;
2407 
2408 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2409 					(struct create_durable_v2, dcontext));
2410 	buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_context_v2));
2411 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2412 				(struct create_durable_v2, Name));
2413 	buf->ccontext.NameLength = cpu_to_le16(4);
2414 
2415 	/*
2416 	 * NB: Handle timeout defaults to 0, which allows server to choose
2417 	 * (most servers default to 120 seconds) and most clients default to 0.
2418 	 * This can be overridden at mount ("handletimeout=") if the user wants
2419 	 * a different persistent (or resilient) handle timeout for all opens
2420 	 * on a particular SMB3 mount.
2421 	 */
2422 	buf->dcontext.Timeout = cpu_to_le32(oparms->tcon->handle_timeout);
2423 	buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2424 	generate_random_uuid(buf->dcontext.CreateGuid);
2425 	memcpy(pfid->create_guid, buf->dcontext.CreateGuid, 16);
2426 
2427 	/* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DH2Q" */
2428 	buf->Name[0] = 'D';
2429 	buf->Name[1] = 'H';
2430 	buf->Name[2] = '2';
2431 	buf->Name[3] = 'Q';
2432 	return buf;
2433 }
2434 
2435 static struct create_durable_handle_reconnect_v2 *
2436 create_reconnect_durable_v2_buf(struct cifs_fid *fid)
2437 {
2438 	struct create_durable_handle_reconnect_v2 *buf;
2439 
2440 	buf = kzalloc(sizeof(struct create_durable_handle_reconnect_v2),
2441 			GFP_KERNEL);
2442 	if (!buf)
2443 		return NULL;
2444 
2445 	buf->ccontext.DataOffset =
2446 		cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
2447 				     dcontext));
2448 	buf->ccontext.DataLength =
2449 		cpu_to_le32(sizeof(struct durable_reconnect_context_v2));
2450 	buf->ccontext.NameOffset =
2451 		cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
2452 			    Name));
2453 	buf->ccontext.NameLength = cpu_to_le16(4);
2454 
2455 	buf->dcontext.Fid.PersistentFileId = fid->persistent_fid;
2456 	buf->dcontext.Fid.VolatileFileId = fid->volatile_fid;
2457 	buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2458 	memcpy(buf->dcontext.CreateGuid, fid->create_guid, 16);
2459 
2460 	/* SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 is "DH2C" */
2461 	buf->Name[0] = 'D';
2462 	buf->Name[1] = 'H';
2463 	buf->Name[2] = '2';
2464 	buf->Name[3] = 'C';
2465 	return buf;
2466 }
2467 
2468 static int
2469 add_durable_v2_context(struct kvec *iov, unsigned int *num_iovec,
2470 		    struct cifs_open_parms *oparms)
2471 {
2472 	unsigned int num = *num_iovec;
2473 
2474 	iov[num].iov_base = create_durable_v2_buf(oparms);
2475 	if (iov[num].iov_base == NULL)
2476 		return -ENOMEM;
2477 	iov[num].iov_len = sizeof(struct create_durable_v2);
2478 	*num_iovec = num + 1;
2479 	return 0;
2480 }
2481 
2482 static int
2483 add_durable_reconnect_v2_context(struct kvec *iov, unsigned int *num_iovec,
2484 		    struct cifs_open_parms *oparms)
2485 {
2486 	unsigned int num = *num_iovec;
2487 
2488 	/* indicate that we don't need to relock the file */
2489 	oparms->reconnect = false;
2490 
2491 	iov[num].iov_base = create_reconnect_durable_v2_buf(oparms->fid);
2492 	if (iov[num].iov_base == NULL)
2493 		return -ENOMEM;
2494 	iov[num].iov_len = sizeof(struct create_durable_handle_reconnect_v2);
2495 	*num_iovec = num + 1;
2496 	return 0;
2497 }
2498 
2499 static int
2500 add_durable_context(struct kvec *iov, unsigned int *num_iovec,
2501 		    struct cifs_open_parms *oparms, bool use_persistent)
2502 {
2503 	unsigned int num = *num_iovec;
2504 
2505 	if (use_persistent) {
2506 		if (oparms->reconnect)
2507 			return add_durable_reconnect_v2_context(iov, num_iovec,
2508 								oparms);
2509 		else
2510 			return add_durable_v2_context(iov, num_iovec, oparms);
2511 	}
2512 
2513 	if (oparms->reconnect) {
2514 		iov[num].iov_base = create_reconnect_durable_buf(oparms->fid);
2515 		/* indicate that we don't need to relock the file */
2516 		oparms->reconnect = false;
2517 	} else
2518 		iov[num].iov_base = create_durable_buf();
2519 	if (iov[num].iov_base == NULL)
2520 		return -ENOMEM;
2521 	iov[num].iov_len = sizeof(struct create_durable);
2522 	*num_iovec = num + 1;
2523 	return 0;
2524 }
2525 
2526 /* See MS-SMB2 2.2.13.2.7 */
2527 static struct crt_twarp_ctxt *
2528 create_twarp_buf(__u64 timewarp)
2529 {
2530 	struct crt_twarp_ctxt *buf;
2531 
2532 	buf = kzalloc(sizeof(struct crt_twarp_ctxt), GFP_KERNEL);
2533 	if (!buf)
2534 		return NULL;
2535 
2536 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2537 					(struct crt_twarp_ctxt, Timestamp));
2538 	buf->ccontext.DataLength = cpu_to_le32(8);
2539 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2540 				(struct crt_twarp_ctxt, Name));
2541 	buf->ccontext.NameLength = cpu_to_le16(4);
2542 	/* SMB2_CREATE_TIMEWARP_TOKEN is "TWrp" */
2543 	buf->Name[0] = 'T';
2544 	buf->Name[1] = 'W';
2545 	buf->Name[2] = 'r';
2546 	buf->Name[3] = 'p';
2547 	buf->Timestamp = cpu_to_le64(timewarp);
2548 	return buf;
2549 }
2550 
2551 /* See MS-SMB2 2.2.13.2.7 */
2552 static int
2553 add_twarp_context(struct kvec *iov, unsigned int *num_iovec, __u64 timewarp)
2554 {
2555 	unsigned int num = *num_iovec;
2556 
2557 	iov[num].iov_base = create_twarp_buf(timewarp);
2558 	if (iov[num].iov_base == NULL)
2559 		return -ENOMEM;
2560 	iov[num].iov_len = sizeof(struct crt_twarp_ctxt);
2561 	*num_iovec = num + 1;
2562 	return 0;
2563 }
2564 
2565 /* See http://technet.microsoft.com/en-us/library/hh509017(v=ws.10).aspx */
2566 static void setup_owner_group_sids(char *buf)
2567 {
2568 	struct owner_group_sids *sids = (struct owner_group_sids *)buf;
2569 
2570 	/* Populate the user ownership fields S-1-5-88-1 */
2571 	sids->owner.Revision = 1;
2572 	sids->owner.NumAuth = 3;
2573 	sids->owner.Authority[5] = 5;
2574 	sids->owner.SubAuthorities[0] = cpu_to_le32(88);
2575 	sids->owner.SubAuthorities[1] = cpu_to_le32(1);
2576 	sids->owner.SubAuthorities[2] = cpu_to_le32(current_fsuid().val);
2577 
2578 	/* Populate the group ownership fields S-1-5-88-2 */
2579 	sids->group.Revision = 1;
2580 	sids->group.NumAuth = 3;
2581 	sids->group.Authority[5] = 5;
2582 	sids->group.SubAuthorities[0] = cpu_to_le32(88);
2583 	sids->group.SubAuthorities[1] = cpu_to_le32(2);
2584 	sids->group.SubAuthorities[2] = cpu_to_le32(current_fsgid().val);
2585 
2586 	cifs_dbg(FYI, "owner S-1-5-88-1-%d, group S-1-5-88-2-%d\n", current_fsuid().val, current_fsgid().val);
2587 }
2588 
2589 /* See MS-SMB2 2.2.13.2.2 and MS-DTYP 2.4.6 */
2590 static struct crt_sd_ctxt *
2591 create_sd_buf(umode_t mode, bool set_owner, unsigned int *len)
2592 {
2593 	struct crt_sd_ctxt *buf;
2594 	__u8 *ptr, *aclptr;
2595 	unsigned int acelen, acl_size, ace_count;
2596 	unsigned int owner_offset = 0;
2597 	unsigned int group_offset = 0;
2598 	struct smb3_acl acl = {};
2599 
2600 	*len = round_up(sizeof(struct crt_sd_ctxt) + (sizeof(struct cifs_ace) * 4), 8);
2601 
2602 	if (set_owner) {
2603 		/* sizeof(struct owner_group_sids) is already multiple of 8 so no need to round */
2604 		*len += sizeof(struct owner_group_sids);
2605 	}
2606 
2607 	buf = kzalloc(*len, GFP_KERNEL);
2608 	if (buf == NULL)
2609 		return buf;
2610 
2611 	ptr = (__u8 *)&buf[1];
2612 	if (set_owner) {
2613 		/* offset fields are from beginning of security descriptor not of create context */
2614 		owner_offset = ptr - (__u8 *)&buf->sd;
2615 		buf->sd.OffsetOwner = cpu_to_le32(owner_offset);
2616 		group_offset = owner_offset + offsetof(struct owner_group_sids, group);
2617 		buf->sd.OffsetGroup = cpu_to_le32(group_offset);
2618 
2619 		setup_owner_group_sids(ptr);
2620 		ptr += sizeof(struct owner_group_sids);
2621 	} else {
2622 		buf->sd.OffsetOwner = 0;
2623 		buf->sd.OffsetGroup = 0;
2624 	}
2625 
2626 	buf->ccontext.DataOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, sd));
2627 	buf->ccontext.NameOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, Name));
2628 	buf->ccontext.NameLength = cpu_to_le16(4);
2629 	/* SMB2_CREATE_SD_BUFFER_TOKEN is "SecD" */
2630 	buf->Name[0] = 'S';
2631 	buf->Name[1] = 'e';
2632 	buf->Name[2] = 'c';
2633 	buf->Name[3] = 'D';
2634 	buf->sd.Revision = 1;  /* Must be one see MS-DTYP 2.4.6 */
2635 
2636 	/*
2637 	 * ACL is "self relative" ie ACL is stored in contiguous block of memory
2638 	 * and "DP" ie the DACL is present
2639 	 */
2640 	buf->sd.Control = cpu_to_le16(ACL_CONTROL_SR | ACL_CONTROL_DP);
2641 
2642 	/* offset owner, group and Sbz1 and SACL are all zero */
2643 	buf->sd.OffsetDacl = cpu_to_le32(ptr - (__u8 *)&buf->sd);
2644 	/* Ship the ACL for now. we will copy it into buf later. */
2645 	aclptr = ptr;
2646 	ptr += sizeof(struct smb3_acl);
2647 
2648 	/* create one ACE to hold the mode embedded in reserved special SID */
2649 	acelen = setup_special_mode_ACE((struct cifs_ace *)ptr, (__u64)mode);
2650 	ptr += acelen;
2651 	acl_size = acelen + sizeof(struct smb3_acl);
2652 	ace_count = 1;
2653 
2654 	if (set_owner) {
2655 		/* we do not need to reallocate buffer to add the two more ACEs. plenty of space */
2656 		acelen = setup_special_user_owner_ACE((struct cifs_ace *)ptr);
2657 		ptr += acelen;
2658 		acl_size += acelen;
2659 		ace_count += 1;
2660 	}
2661 
2662 	/* and one more ACE to allow access for authenticated users */
2663 	acelen = setup_authusers_ACE((struct cifs_ace *)ptr);
2664 	ptr += acelen;
2665 	acl_size += acelen;
2666 	ace_count += 1;
2667 
2668 	acl.AclRevision = ACL_REVISION; /* See 2.4.4.1 of MS-DTYP */
2669 	acl.AclSize = cpu_to_le16(acl_size);
2670 	acl.AceCount = cpu_to_le16(ace_count);
2671 	/* acl.Sbz1 and Sbz2 MBZ so are not set here, but initialized above */
2672 	memcpy(aclptr, &acl, sizeof(struct smb3_acl));
2673 
2674 	buf->ccontext.DataLength = cpu_to_le32(ptr - (__u8 *)&buf->sd);
2675 	*len = round_up((unsigned int)(ptr - (__u8 *)buf), 8);
2676 
2677 	return buf;
2678 }
2679 
2680 static int
2681 add_sd_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode, bool set_owner)
2682 {
2683 	unsigned int num = *num_iovec;
2684 	unsigned int len = 0;
2685 
2686 	iov[num].iov_base = create_sd_buf(mode, set_owner, &len);
2687 	if (iov[num].iov_base == NULL)
2688 		return -ENOMEM;
2689 	iov[num].iov_len = len;
2690 	*num_iovec = num + 1;
2691 	return 0;
2692 }
2693 
2694 static struct crt_query_id_ctxt *
2695 create_query_id_buf(void)
2696 {
2697 	struct crt_query_id_ctxt *buf;
2698 
2699 	buf = kzalloc(sizeof(struct crt_query_id_ctxt), GFP_KERNEL);
2700 	if (!buf)
2701 		return NULL;
2702 
2703 	buf->ccontext.DataOffset = cpu_to_le16(0);
2704 	buf->ccontext.DataLength = cpu_to_le32(0);
2705 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2706 				(struct crt_query_id_ctxt, Name));
2707 	buf->ccontext.NameLength = cpu_to_le16(4);
2708 	/* SMB2_CREATE_QUERY_ON_DISK_ID is "QFid" */
2709 	buf->Name[0] = 'Q';
2710 	buf->Name[1] = 'F';
2711 	buf->Name[2] = 'i';
2712 	buf->Name[3] = 'd';
2713 	return buf;
2714 }
2715 
2716 /* See MS-SMB2 2.2.13.2.9 */
2717 static int
2718 add_query_id_context(struct kvec *iov, unsigned int *num_iovec)
2719 {
2720 	unsigned int num = *num_iovec;
2721 
2722 	iov[num].iov_base = create_query_id_buf();
2723 	if (iov[num].iov_base == NULL)
2724 		return -ENOMEM;
2725 	iov[num].iov_len = sizeof(struct crt_query_id_ctxt);
2726 	*num_iovec = num + 1;
2727 	return 0;
2728 }
2729 
2730 static int
2731 alloc_path_with_tree_prefix(__le16 **out_path, int *out_size, int *out_len,
2732 			    const char *treename, const __le16 *path)
2733 {
2734 	int treename_len, path_len;
2735 	struct nls_table *cp;
2736 	const __le16 sep[] = {cpu_to_le16('\\'), cpu_to_le16(0x0000)};
2737 
2738 	/*
2739 	 * skip leading "\\"
2740 	 */
2741 	treename_len = strlen(treename);
2742 	if (treename_len < 2 || !(treename[0] == '\\' && treename[1] == '\\'))
2743 		return -EINVAL;
2744 
2745 	treename += 2;
2746 	treename_len -= 2;
2747 
2748 	path_len = UniStrnlen((wchar_t *)path, PATH_MAX);
2749 
2750 	/* make room for one path separator only if @path isn't empty */
2751 	*out_len = treename_len + (path[0] ? 1 : 0) + path_len;
2752 
2753 	/*
2754 	 * final path needs to be 8-byte aligned as specified in
2755 	 * MS-SMB2 2.2.13 SMB2 CREATE Request.
2756 	 */
2757 	*out_size = round_up(*out_len * sizeof(__le16), 8);
2758 	*out_path = kzalloc(*out_size + sizeof(__le16) /* null */, GFP_KERNEL);
2759 	if (!*out_path)
2760 		return -ENOMEM;
2761 
2762 	cp = load_nls_default();
2763 	cifs_strtoUTF16(*out_path, treename, treename_len, cp);
2764 
2765 	/* Do not append the separator if the path is empty */
2766 	if (path[0] != cpu_to_le16(0x0000)) {
2767 		UniStrcat((wchar_t *)*out_path, (wchar_t *)sep);
2768 		UniStrcat((wchar_t *)*out_path, (wchar_t *)path);
2769 	}
2770 
2771 	unload_nls(cp);
2772 
2773 	return 0;
2774 }
2775 
2776 int smb311_posix_mkdir(const unsigned int xid, struct inode *inode,
2777 			       umode_t mode, struct cifs_tcon *tcon,
2778 			       const char *full_path,
2779 			       struct cifs_sb_info *cifs_sb)
2780 {
2781 	struct smb_rqst rqst;
2782 	struct smb2_create_req *req;
2783 	struct smb2_create_rsp *rsp = NULL;
2784 	struct cifs_ses *ses = tcon->ses;
2785 	struct kvec iov[3]; /* make sure at least one for each open context */
2786 	struct kvec rsp_iov = {NULL, 0};
2787 	int resp_buftype;
2788 	int uni_path_len;
2789 	__le16 *copy_path = NULL;
2790 	int copy_size;
2791 	int rc = 0;
2792 	unsigned int n_iov = 2;
2793 	__u32 file_attributes = 0;
2794 	char *pc_buf = NULL;
2795 	int flags = 0;
2796 	unsigned int total_len;
2797 	__le16 *utf16_path = NULL;
2798 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
2799 
2800 	cifs_dbg(FYI, "mkdir\n");
2801 
2802 	/* resource #1: path allocation */
2803 	utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
2804 	if (!utf16_path)
2805 		return -ENOMEM;
2806 
2807 	if (!ses || !server) {
2808 		rc = -EIO;
2809 		goto err_free_path;
2810 	}
2811 
2812 	/* resource #2: request */
2813 	rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
2814 				 (void **) &req, &total_len);
2815 	if (rc)
2816 		goto err_free_path;
2817 
2818 
2819 	if (smb3_encryption_required(tcon))
2820 		flags |= CIFS_TRANSFORM_REQ;
2821 
2822 	req->ImpersonationLevel = IL_IMPERSONATION;
2823 	req->DesiredAccess = cpu_to_le32(FILE_WRITE_ATTRIBUTES);
2824 	/* File attributes ignored on open (used in create though) */
2825 	req->FileAttributes = cpu_to_le32(file_attributes);
2826 	req->ShareAccess = FILE_SHARE_ALL_LE;
2827 	req->CreateDisposition = cpu_to_le32(FILE_CREATE);
2828 	req->CreateOptions = cpu_to_le32(CREATE_NOT_FILE);
2829 
2830 	iov[0].iov_base = (char *)req;
2831 	/* -1 since last byte is buf[0] which is sent below (path) */
2832 	iov[0].iov_len = total_len - 1;
2833 
2834 	req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
2835 
2836 	/* [MS-SMB2] 2.2.13 NameOffset:
2837 	 * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
2838 	 * the SMB2 header, the file name includes a prefix that will
2839 	 * be processed during DFS name normalization as specified in
2840 	 * section 3.3.5.9. Otherwise, the file name is relative to
2841 	 * the share that is identified by the TreeId in the SMB2
2842 	 * header.
2843 	 */
2844 	if (tcon->share_flags & SHI1005_FLAGS_DFS) {
2845 		int name_len;
2846 
2847 		req->hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
2848 		rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
2849 						 &name_len,
2850 						 tcon->tree_name, utf16_path);
2851 		if (rc)
2852 			goto err_free_req;
2853 
2854 		req->NameLength = cpu_to_le16(name_len * 2);
2855 		uni_path_len = copy_size;
2856 		/* free before overwriting resource */
2857 		kfree(utf16_path);
2858 		utf16_path = copy_path;
2859 	} else {
2860 		uni_path_len = (2 * UniStrnlen((wchar_t *)utf16_path, PATH_MAX)) + 2;
2861 		/* MUST set path len (NameLength) to 0 opening root of share */
2862 		req->NameLength = cpu_to_le16(uni_path_len - 2);
2863 		if (uni_path_len % 8 != 0) {
2864 			copy_size = roundup(uni_path_len, 8);
2865 			copy_path = kzalloc(copy_size, GFP_KERNEL);
2866 			if (!copy_path) {
2867 				rc = -ENOMEM;
2868 				goto err_free_req;
2869 			}
2870 			memcpy((char *)copy_path, (const char *)utf16_path,
2871 			       uni_path_len);
2872 			uni_path_len = copy_size;
2873 			/* free before overwriting resource */
2874 			kfree(utf16_path);
2875 			utf16_path = copy_path;
2876 		}
2877 	}
2878 
2879 	iov[1].iov_len = uni_path_len;
2880 	iov[1].iov_base = utf16_path;
2881 	req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2882 
2883 	if (tcon->posix_extensions) {
2884 		/* resource #3: posix buf */
2885 		rc = add_posix_context(iov, &n_iov, mode);
2886 		if (rc)
2887 			goto err_free_req;
2888 		req->CreateContextsOffset = cpu_to_le32(
2889 			sizeof(struct smb2_create_req) +
2890 			iov[1].iov_len);
2891 		pc_buf = iov[n_iov-1].iov_base;
2892 	}
2893 
2894 
2895 	memset(&rqst, 0, sizeof(struct smb_rqst));
2896 	rqst.rq_iov = iov;
2897 	rqst.rq_nvec = n_iov;
2898 
2899 	/* no need to inc num_remote_opens because we close it just below */
2900 	trace_smb3_posix_mkdir_enter(xid, tcon->tid, ses->Suid, full_path, CREATE_NOT_FILE,
2901 				    FILE_WRITE_ATTRIBUTES);
2902 	/* resource #4: response buffer */
2903 	rc = cifs_send_recv(xid, ses, server,
2904 			    &rqst, &resp_buftype, flags, &rsp_iov);
2905 	if (rc) {
2906 		cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
2907 		trace_smb3_posix_mkdir_err(xid, tcon->tid, ses->Suid,
2908 					   CREATE_NOT_FILE,
2909 					   FILE_WRITE_ATTRIBUTES, rc);
2910 		goto err_free_rsp_buf;
2911 	}
2912 
2913 	/*
2914 	 * Although unlikely to be possible for rsp to be null and rc not set,
2915 	 * adding check below is slightly safer long term (and quiets Coverity
2916 	 * warning)
2917 	 */
2918 	rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
2919 	if (rsp == NULL) {
2920 		rc = -EIO;
2921 		kfree(pc_buf);
2922 		goto err_free_req;
2923 	}
2924 
2925 	trace_smb3_posix_mkdir_done(xid, rsp->PersistentFileId, tcon->tid, ses->Suid,
2926 				    CREATE_NOT_FILE, FILE_WRITE_ATTRIBUTES);
2927 
2928 	SMB2_close(xid, tcon, rsp->PersistentFileId, rsp->VolatileFileId);
2929 
2930 	/* Eventually save off posix specific response info and timestaps */
2931 
2932 err_free_rsp_buf:
2933 	free_rsp_buf(resp_buftype, rsp);
2934 	kfree(pc_buf);
2935 err_free_req:
2936 	cifs_small_buf_release(req);
2937 err_free_path:
2938 	kfree(utf16_path);
2939 	return rc;
2940 }
2941 
2942 int
2943 SMB2_open_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
2944 	       struct smb_rqst *rqst, __u8 *oplock,
2945 	       struct cifs_open_parms *oparms, __le16 *path)
2946 {
2947 	struct smb2_create_req *req;
2948 	unsigned int n_iov = 2;
2949 	__u32 file_attributes = 0;
2950 	int copy_size;
2951 	int uni_path_len;
2952 	unsigned int total_len;
2953 	struct kvec *iov = rqst->rq_iov;
2954 	__le16 *copy_path;
2955 	int rc;
2956 
2957 	rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
2958 				 (void **) &req, &total_len);
2959 	if (rc)
2960 		return rc;
2961 
2962 	iov[0].iov_base = (char *)req;
2963 	/* -1 since last byte is buf[0] which is sent below (path) */
2964 	iov[0].iov_len = total_len - 1;
2965 
2966 	if (oparms->create_options & CREATE_OPTION_READONLY)
2967 		file_attributes |= ATTR_READONLY;
2968 	if (oparms->create_options & CREATE_OPTION_SPECIAL)
2969 		file_attributes |= ATTR_SYSTEM;
2970 
2971 	req->ImpersonationLevel = IL_IMPERSONATION;
2972 	req->DesiredAccess = cpu_to_le32(oparms->desired_access);
2973 	/* File attributes ignored on open (used in create though) */
2974 	req->FileAttributes = cpu_to_le32(file_attributes);
2975 	req->ShareAccess = FILE_SHARE_ALL_LE;
2976 
2977 	req->CreateDisposition = cpu_to_le32(oparms->disposition);
2978 	req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK);
2979 	req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
2980 
2981 	/* [MS-SMB2] 2.2.13 NameOffset:
2982 	 * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
2983 	 * the SMB2 header, the file name includes a prefix that will
2984 	 * be processed during DFS name normalization as specified in
2985 	 * section 3.3.5.9. Otherwise, the file name is relative to
2986 	 * the share that is identified by the TreeId in the SMB2
2987 	 * header.
2988 	 */
2989 	if (tcon->share_flags & SHI1005_FLAGS_DFS) {
2990 		int name_len;
2991 
2992 		req->hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
2993 		rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
2994 						 &name_len,
2995 						 tcon->tree_name, path);
2996 		if (rc)
2997 			return rc;
2998 		req->NameLength = cpu_to_le16(name_len * 2);
2999 		uni_path_len = copy_size;
3000 		path = copy_path;
3001 	} else {
3002 		uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
3003 		/* MUST set path len (NameLength) to 0 opening root of share */
3004 		req->NameLength = cpu_to_le16(uni_path_len - 2);
3005 		copy_size = round_up(uni_path_len, 8);
3006 		copy_path = kzalloc(copy_size, GFP_KERNEL);
3007 		if (!copy_path)
3008 			return -ENOMEM;
3009 		memcpy((char *)copy_path, (const char *)path,
3010 		       uni_path_len);
3011 		uni_path_len = copy_size;
3012 		path = copy_path;
3013 	}
3014 
3015 	iov[1].iov_len = uni_path_len;
3016 	iov[1].iov_base = path;
3017 
3018 	if ((!server->oplocks) || (tcon->no_lease))
3019 		*oplock = SMB2_OPLOCK_LEVEL_NONE;
3020 
3021 	if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) ||
3022 	    *oplock == SMB2_OPLOCK_LEVEL_NONE)
3023 		req->RequestedOplockLevel = *oplock;
3024 	else if (!(server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING) &&
3025 		  (oparms->create_options & CREATE_NOT_FILE))
3026 		req->RequestedOplockLevel = *oplock; /* no srv lease support */
3027 	else {
3028 		rc = add_lease_context(server, req, iov, &n_iov,
3029 				       oparms->fid->lease_key, oplock);
3030 		if (rc)
3031 			return rc;
3032 	}
3033 
3034 	if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) {
3035 		rc = add_durable_context(iov, &n_iov, oparms,
3036 					tcon->use_persistent);
3037 		if (rc)
3038 			return rc;
3039 	}
3040 
3041 	if (tcon->posix_extensions) {
3042 		rc = add_posix_context(iov, &n_iov, oparms->mode);
3043 		if (rc)
3044 			return rc;
3045 	}
3046 
3047 	if (tcon->snapshot_time) {
3048 		cifs_dbg(FYI, "adding snapshot context\n");
3049 		rc = add_twarp_context(iov, &n_iov, tcon->snapshot_time);
3050 		if (rc)
3051 			return rc;
3052 	}
3053 
3054 	if ((oparms->disposition != FILE_OPEN) && (oparms->cifs_sb)) {
3055 		bool set_mode;
3056 		bool set_owner;
3057 
3058 		if ((oparms->cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MODE_FROM_SID) &&
3059 		    (oparms->mode != ACL_NO_MODE))
3060 			set_mode = true;
3061 		else {
3062 			set_mode = false;
3063 			oparms->mode = ACL_NO_MODE;
3064 		}
3065 
3066 		if (oparms->cifs_sb->mnt_cifs_flags & CIFS_MOUNT_UID_FROM_ACL)
3067 			set_owner = true;
3068 		else
3069 			set_owner = false;
3070 
3071 		if (set_owner | set_mode) {
3072 			cifs_dbg(FYI, "add sd with mode 0x%x\n", oparms->mode);
3073 			rc = add_sd_context(iov, &n_iov, oparms->mode, set_owner);
3074 			if (rc)
3075 				return rc;
3076 		}
3077 	}
3078 
3079 	add_query_id_context(iov, &n_iov);
3080 
3081 	if (n_iov > 2) {
3082 		/*
3083 		 * We have create contexts behind iov[1] (the file
3084 		 * name), point at them from the main create request
3085 		 */
3086 		req->CreateContextsOffset = cpu_to_le32(
3087 			sizeof(struct smb2_create_req) +
3088 			iov[1].iov_len);
3089 		req->CreateContextsLength = 0;
3090 
3091 		for (unsigned int i = 2; i < (n_iov-1); i++) {
3092 			struct kvec *v = &iov[i];
3093 			size_t len = v->iov_len;
3094 			struct create_context *cctx =
3095 				(struct create_context *)v->iov_base;
3096 
3097 			cctx->Next = cpu_to_le32(len);
3098 			le32_add_cpu(&req->CreateContextsLength, len);
3099 		}
3100 		le32_add_cpu(&req->CreateContextsLength,
3101 			     iov[n_iov-1].iov_len);
3102 	}
3103 
3104 	rqst->rq_nvec = n_iov;
3105 	return 0;
3106 }
3107 
3108 /* rq_iov[0] is the request and is released by cifs_small_buf_release().
3109  * All other vectors are freed by kfree().
3110  */
3111 void
3112 SMB2_open_free(struct smb_rqst *rqst)
3113 {
3114 	int i;
3115 
3116 	if (rqst && rqst->rq_iov) {
3117 		cifs_small_buf_release(rqst->rq_iov[0].iov_base);
3118 		for (i = 1; i < rqst->rq_nvec; i++)
3119 			if (rqst->rq_iov[i].iov_base != smb2_padding)
3120 				kfree(rqst->rq_iov[i].iov_base);
3121 	}
3122 }
3123 
3124 int
3125 SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
3126 	  __u8 *oplock, struct smb2_file_all_info *buf,
3127 	  struct create_posix_rsp *posix,
3128 	  struct kvec *err_iov, int *buftype)
3129 {
3130 	struct smb_rqst rqst;
3131 	struct smb2_create_rsp *rsp = NULL;
3132 	struct cifs_tcon *tcon = oparms->tcon;
3133 	struct cifs_ses *ses = tcon->ses;
3134 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
3135 	struct kvec iov[SMB2_CREATE_IOV_SIZE];
3136 	struct kvec rsp_iov = {NULL, 0};
3137 	int resp_buftype = CIFS_NO_BUFFER;
3138 	int rc = 0;
3139 	int flags = 0;
3140 
3141 	cifs_dbg(FYI, "create/open\n");
3142 	if (!ses || !server)
3143 		return -EIO;
3144 
3145 	if (smb3_encryption_required(tcon))
3146 		flags |= CIFS_TRANSFORM_REQ;
3147 
3148 	memset(&rqst, 0, sizeof(struct smb_rqst));
3149 	memset(&iov, 0, sizeof(iov));
3150 	rqst.rq_iov = iov;
3151 	rqst.rq_nvec = SMB2_CREATE_IOV_SIZE;
3152 
3153 	rc = SMB2_open_init(tcon, server,
3154 			    &rqst, oplock, oparms, path);
3155 	if (rc)
3156 		goto creat_exit;
3157 
3158 	trace_smb3_open_enter(xid, tcon->tid, tcon->ses->Suid, oparms->path,
3159 		oparms->create_options, oparms->desired_access);
3160 
3161 	rc = cifs_send_recv(xid, ses, server,
3162 			    &rqst, &resp_buftype, flags,
3163 			    &rsp_iov);
3164 	rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
3165 
3166 	if (rc != 0) {
3167 		cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
3168 		if (err_iov && rsp) {
3169 			*err_iov = rsp_iov;
3170 			*buftype = resp_buftype;
3171 			resp_buftype = CIFS_NO_BUFFER;
3172 			rsp = NULL;
3173 		}
3174 		trace_smb3_open_err(xid, tcon->tid, ses->Suid,
3175 				    oparms->create_options, oparms->desired_access, rc);
3176 		if (rc == -EREMCHG) {
3177 			pr_warn_once("server share %s deleted\n",
3178 				     tcon->tree_name);
3179 			tcon->need_reconnect = true;
3180 		}
3181 		goto creat_exit;
3182 	} else if (rsp == NULL) /* unlikely to happen, but safer to check */
3183 		goto creat_exit;
3184 	else
3185 		trace_smb3_open_done(xid, rsp->PersistentFileId, tcon->tid, ses->Suid,
3186 				     oparms->create_options, oparms->desired_access);
3187 
3188 	atomic_inc(&tcon->num_remote_opens);
3189 	oparms->fid->persistent_fid = rsp->PersistentFileId;
3190 	oparms->fid->volatile_fid = rsp->VolatileFileId;
3191 	oparms->fid->access = oparms->desired_access;
3192 #ifdef CONFIG_CIFS_DEBUG2
3193 	oparms->fid->mid = le64_to_cpu(rsp->hdr.MessageId);
3194 #endif /* CIFS_DEBUG2 */
3195 
3196 	if (buf) {
3197 		buf->CreationTime = rsp->CreationTime;
3198 		buf->LastAccessTime = rsp->LastAccessTime;
3199 		buf->LastWriteTime = rsp->LastWriteTime;
3200 		buf->ChangeTime = rsp->ChangeTime;
3201 		buf->AllocationSize = rsp->AllocationSize;
3202 		buf->EndOfFile = rsp->EndofFile;
3203 		buf->Attributes = rsp->FileAttributes;
3204 		buf->NumberOfLinks = cpu_to_le32(1);
3205 		buf->DeletePending = 0;
3206 	}
3207 
3208 
3209 	rc = smb2_parse_contexts(server, &rsp_iov, &oparms->fid->epoch,
3210 				 oparms->fid->lease_key, oplock, buf, posix);
3211 creat_exit:
3212 	SMB2_open_free(&rqst);
3213 	free_rsp_buf(resp_buftype, rsp);
3214 	return rc;
3215 }
3216 
3217 int
3218 SMB2_ioctl_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3219 		struct smb_rqst *rqst,
3220 		u64 persistent_fid, u64 volatile_fid, u32 opcode,
3221 		char *in_data, u32 indatalen,
3222 		__u32 max_response_size)
3223 {
3224 	struct smb2_ioctl_req *req;
3225 	struct kvec *iov = rqst->rq_iov;
3226 	unsigned int total_len;
3227 	int rc;
3228 	char *in_data_buf;
3229 
3230 	rc = smb2_ioctl_req_init(opcode, tcon, server,
3231 				 (void **) &req, &total_len);
3232 	if (rc)
3233 		return rc;
3234 
3235 	if (indatalen) {
3236 		/*
3237 		 * indatalen is usually small at a couple of bytes max, so
3238 		 * just allocate through generic pool
3239 		 */
3240 		in_data_buf = kmemdup(in_data, indatalen, GFP_NOFS);
3241 		if (!in_data_buf) {
3242 			cifs_small_buf_release(req);
3243 			return -ENOMEM;
3244 		}
3245 	}
3246 
3247 	req->CtlCode = cpu_to_le32(opcode);
3248 	req->PersistentFileId = persistent_fid;
3249 	req->VolatileFileId = volatile_fid;
3250 
3251 	iov[0].iov_base = (char *)req;
3252 	/*
3253 	 * If no input data, the size of ioctl struct in
3254 	 * protocol spec still includes a 1 byte data buffer,
3255 	 * but if input data passed to ioctl, we do not
3256 	 * want to double count this, so we do not send
3257 	 * the dummy one byte of data in iovec[0] if sending
3258 	 * input data (in iovec[1]).
3259 	 */
3260 	if (indatalen) {
3261 		req->InputCount = cpu_to_le32(indatalen);
3262 		/* do not set InputOffset if no input data */
3263 		req->InputOffset =
3264 		       cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer));
3265 		rqst->rq_nvec = 2;
3266 		iov[0].iov_len = total_len - 1;
3267 		iov[1].iov_base = in_data_buf;
3268 		iov[1].iov_len = indatalen;
3269 	} else {
3270 		rqst->rq_nvec = 1;
3271 		iov[0].iov_len = total_len;
3272 	}
3273 
3274 	req->OutputOffset = 0;
3275 	req->OutputCount = 0; /* MBZ */
3276 
3277 	/*
3278 	 * In most cases max_response_size is set to 16K (CIFSMaxBufSize)
3279 	 * We Could increase default MaxOutputResponse, but that could require
3280 	 * more credits. Windows typically sets this smaller, but for some
3281 	 * ioctls it may be useful to allow server to send more. No point
3282 	 * limiting what the server can send as long as fits in one credit
3283 	 * We can not handle more than CIFS_MAX_BUF_SIZE yet but may want
3284 	 * to increase this limit up in the future.
3285 	 * Note that for snapshot queries that servers like Azure expect that
3286 	 * the first query be minimal size (and just used to get the number/size
3287 	 * of previous versions) so response size must be specified as EXACTLY
3288 	 * sizeof(struct snapshot_array) which is 16 when rounded up to multiple
3289 	 * of eight bytes.  Currently that is the only case where we set max
3290 	 * response size smaller.
3291 	 */
3292 	req->MaxOutputResponse = cpu_to_le32(max_response_size);
3293 	req->hdr.CreditCharge =
3294 		cpu_to_le16(DIV_ROUND_UP(max(indatalen, max_response_size),
3295 					 SMB2_MAX_BUFFER_SIZE));
3296 	/* always an FSCTL (for now) */
3297 	req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL);
3298 
3299 	/* validate negotiate request must be signed - see MS-SMB2 3.2.5.5 */
3300 	if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO)
3301 		req->hdr.Flags |= SMB2_FLAGS_SIGNED;
3302 
3303 	return 0;
3304 }
3305 
3306 void
3307 SMB2_ioctl_free(struct smb_rqst *rqst)
3308 {
3309 	int i;
3310 
3311 	if (rqst && rqst->rq_iov) {
3312 		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3313 		for (i = 1; i < rqst->rq_nvec; i++)
3314 			if (rqst->rq_iov[i].iov_base != smb2_padding)
3315 				kfree(rqst->rq_iov[i].iov_base);
3316 	}
3317 }
3318 
3319 
3320 /*
3321  *	SMB2 IOCTL is used for both IOCTLs and FSCTLs
3322  */
3323 int
3324 SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
3325 	   u64 volatile_fid, u32 opcode, char *in_data, u32 indatalen,
3326 	   u32 max_out_data_len, char **out_data,
3327 	   u32 *plen /* returned data len */)
3328 {
3329 	struct smb_rqst rqst;
3330 	struct smb2_ioctl_rsp *rsp = NULL;
3331 	struct cifs_ses *ses;
3332 	struct TCP_Server_Info *server;
3333 	struct kvec iov[SMB2_IOCTL_IOV_SIZE];
3334 	struct kvec rsp_iov = {NULL, 0};
3335 	int resp_buftype = CIFS_NO_BUFFER;
3336 	int rc = 0;
3337 	int flags = 0;
3338 
3339 	cifs_dbg(FYI, "SMB2 IOCTL\n");
3340 
3341 	if (out_data != NULL)
3342 		*out_data = NULL;
3343 
3344 	/* zero out returned data len, in case of error */
3345 	if (plen)
3346 		*plen = 0;
3347 
3348 	if (!tcon)
3349 		return -EIO;
3350 
3351 	ses = tcon->ses;
3352 	if (!ses)
3353 		return -EIO;
3354 
3355 	server = cifs_pick_channel(ses);
3356 	if (!server)
3357 		return -EIO;
3358 
3359 	if (smb3_encryption_required(tcon))
3360 		flags |= CIFS_TRANSFORM_REQ;
3361 
3362 	memset(&rqst, 0, sizeof(struct smb_rqst));
3363 	memset(&iov, 0, sizeof(iov));
3364 	rqst.rq_iov = iov;
3365 	rqst.rq_nvec = SMB2_IOCTL_IOV_SIZE;
3366 
3367 	rc = SMB2_ioctl_init(tcon, server,
3368 			     &rqst, persistent_fid, volatile_fid, opcode,
3369 			     in_data, indatalen, max_out_data_len);
3370 	if (rc)
3371 		goto ioctl_exit;
3372 
3373 	rc = cifs_send_recv(xid, ses, server,
3374 			    &rqst, &resp_buftype, flags,
3375 			    &rsp_iov);
3376 	rsp = (struct smb2_ioctl_rsp *)rsp_iov.iov_base;
3377 
3378 	if (rc != 0)
3379 		trace_smb3_fsctl_err(xid, persistent_fid, tcon->tid,
3380 				ses->Suid, 0, opcode, rc);
3381 
3382 	if ((rc != 0) && (rc != -EINVAL) && (rc != -E2BIG)) {
3383 		cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3384 		goto ioctl_exit;
3385 	} else if (rc == -EINVAL) {
3386 		if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) &&
3387 		    (opcode != FSCTL_SRV_COPYCHUNK)) {
3388 			cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3389 			goto ioctl_exit;
3390 		}
3391 	} else if (rc == -E2BIG) {
3392 		if (opcode != FSCTL_QUERY_ALLOCATED_RANGES) {
3393 			cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3394 			goto ioctl_exit;
3395 		}
3396 	}
3397 
3398 	/* check if caller wants to look at return data or just return rc */
3399 	if ((plen == NULL) || (out_data == NULL))
3400 		goto ioctl_exit;
3401 
3402 	/*
3403 	 * Although unlikely to be possible for rsp to be null and rc not set,
3404 	 * adding check below is slightly safer long term (and quiets Coverity
3405 	 * warning)
3406 	 */
3407 	if (rsp == NULL) {
3408 		rc = -EIO;
3409 		goto ioctl_exit;
3410 	}
3411 
3412 	*plen = le32_to_cpu(rsp->OutputCount);
3413 
3414 	/* We check for obvious errors in the output buffer length and offset */
3415 	if (*plen == 0)
3416 		goto ioctl_exit; /* server returned no data */
3417 	else if (*plen > rsp_iov.iov_len || *plen > 0xFF00) {
3418 		cifs_tcon_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen);
3419 		*plen = 0;
3420 		rc = -EIO;
3421 		goto ioctl_exit;
3422 	}
3423 
3424 	if (rsp_iov.iov_len - *plen < le32_to_cpu(rsp->OutputOffset)) {
3425 		cifs_tcon_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen,
3426 			le32_to_cpu(rsp->OutputOffset));
3427 		*plen = 0;
3428 		rc = -EIO;
3429 		goto ioctl_exit;
3430 	}
3431 
3432 	*out_data = kmemdup((char *)rsp + le32_to_cpu(rsp->OutputOffset),
3433 			    *plen, GFP_KERNEL);
3434 	if (*out_data == NULL) {
3435 		rc = -ENOMEM;
3436 		goto ioctl_exit;
3437 	}
3438 
3439 ioctl_exit:
3440 	SMB2_ioctl_free(&rqst);
3441 	free_rsp_buf(resp_buftype, rsp);
3442 	return rc;
3443 }
3444 
3445 /*
3446  *   Individual callers to ioctl worker function follow
3447  */
3448 
3449 int
3450 SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
3451 		     u64 persistent_fid, u64 volatile_fid)
3452 {
3453 	int rc;
3454 	struct  compress_ioctl fsctl_input;
3455 	char *ret_data = NULL;
3456 
3457 	fsctl_input.CompressionState =
3458 			cpu_to_le16(COMPRESSION_FORMAT_DEFAULT);
3459 
3460 	rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
3461 			FSCTL_SET_COMPRESSION,
3462 			(char *)&fsctl_input /* data input */,
3463 			2 /* in data len */, CIFSMaxBufSize /* max out data */,
3464 			&ret_data /* out data */, NULL);
3465 
3466 	cifs_dbg(FYI, "set compression rc %d\n", rc);
3467 
3468 	return rc;
3469 }
3470 
3471 int
3472 SMB2_close_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3473 		struct smb_rqst *rqst,
3474 		u64 persistent_fid, u64 volatile_fid, bool query_attrs)
3475 {
3476 	struct smb2_close_req *req;
3477 	struct kvec *iov = rqst->rq_iov;
3478 	unsigned int total_len;
3479 	int rc;
3480 
3481 	rc = smb2_plain_req_init(SMB2_CLOSE, tcon, server,
3482 				 (void **) &req, &total_len);
3483 	if (rc)
3484 		return rc;
3485 
3486 	req->PersistentFileId = persistent_fid;
3487 	req->VolatileFileId = volatile_fid;
3488 	if (query_attrs)
3489 		req->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
3490 	else
3491 		req->Flags = 0;
3492 	iov[0].iov_base = (char *)req;
3493 	iov[0].iov_len = total_len;
3494 
3495 	return 0;
3496 }
3497 
3498 void
3499 SMB2_close_free(struct smb_rqst *rqst)
3500 {
3501 	if (rqst && rqst->rq_iov)
3502 		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3503 }
3504 
3505 int
3506 __SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3507 	     u64 persistent_fid, u64 volatile_fid,
3508 	     struct smb2_file_network_open_info *pbuf)
3509 {
3510 	struct smb_rqst rqst;
3511 	struct smb2_close_rsp *rsp = NULL;
3512 	struct cifs_ses *ses = tcon->ses;
3513 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
3514 	struct kvec iov[1];
3515 	struct kvec rsp_iov;
3516 	int resp_buftype = CIFS_NO_BUFFER;
3517 	int rc = 0;
3518 	int flags = 0;
3519 	bool query_attrs = false;
3520 
3521 	cifs_dbg(FYI, "Close\n");
3522 
3523 	if (!ses || !server)
3524 		return -EIO;
3525 
3526 	if (smb3_encryption_required(tcon))
3527 		flags |= CIFS_TRANSFORM_REQ;
3528 
3529 	memset(&rqst, 0, sizeof(struct smb_rqst));
3530 	memset(&iov, 0, sizeof(iov));
3531 	rqst.rq_iov = iov;
3532 	rqst.rq_nvec = 1;
3533 
3534 	/* check if need to ask server to return timestamps in close response */
3535 	if (pbuf)
3536 		query_attrs = true;
3537 
3538 	trace_smb3_close_enter(xid, persistent_fid, tcon->tid, ses->Suid);
3539 	rc = SMB2_close_init(tcon, server,
3540 			     &rqst, persistent_fid, volatile_fid,
3541 			     query_attrs);
3542 	if (rc)
3543 		goto close_exit;
3544 
3545 	rc = cifs_send_recv(xid, ses, server,
3546 			    &rqst, &resp_buftype, flags, &rsp_iov);
3547 	rsp = (struct smb2_close_rsp *)rsp_iov.iov_base;
3548 
3549 	if (rc != 0) {
3550 		cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
3551 		trace_smb3_close_err(xid, persistent_fid, tcon->tid, ses->Suid,
3552 				     rc);
3553 		goto close_exit;
3554 	} else {
3555 		trace_smb3_close_done(xid, persistent_fid, tcon->tid,
3556 				      ses->Suid);
3557 		if (pbuf)
3558 			memcpy(&pbuf->network_open_info,
3559 			       &rsp->network_open_info,
3560 			       sizeof(pbuf->network_open_info));
3561 		atomic_dec(&tcon->num_remote_opens);
3562 	}
3563 
3564 close_exit:
3565 	SMB2_close_free(&rqst);
3566 	free_rsp_buf(resp_buftype, rsp);
3567 
3568 	/* retry close in a worker thread if this one is interrupted */
3569 	if (is_interrupt_error(rc)) {
3570 		int tmp_rc;
3571 
3572 		tmp_rc = smb2_handle_cancelled_close(tcon, persistent_fid,
3573 						     volatile_fid);
3574 		if (tmp_rc)
3575 			cifs_dbg(VFS, "handle cancelled close fid 0x%llx returned error %d\n",
3576 				 persistent_fid, tmp_rc);
3577 	}
3578 	return rc;
3579 }
3580 
3581 int
3582 SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3583 		u64 persistent_fid, u64 volatile_fid)
3584 {
3585 	return __SMB2_close(xid, tcon, persistent_fid, volatile_fid, NULL);
3586 }
3587 
3588 int
3589 smb2_validate_iov(unsigned int offset, unsigned int buffer_length,
3590 		  struct kvec *iov, unsigned int min_buf_size)
3591 {
3592 	unsigned int smb_len = iov->iov_len;
3593 	char *end_of_smb = smb_len + (char *)iov->iov_base;
3594 	char *begin_of_buf = offset + (char *)iov->iov_base;
3595 	char *end_of_buf = begin_of_buf + buffer_length;
3596 
3597 
3598 	if (buffer_length < min_buf_size) {
3599 		cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n",
3600 			 buffer_length, min_buf_size);
3601 		return -EINVAL;
3602 	}
3603 
3604 	/* check if beyond RFC1001 maximum length */
3605 	if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
3606 		cifs_dbg(VFS, "buffer length %d or smb length %d too large\n",
3607 			 buffer_length, smb_len);
3608 		return -EINVAL;
3609 	}
3610 
3611 	if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
3612 		cifs_dbg(VFS, "Invalid server response, bad offset to data\n");
3613 		return -EINVAL;
3614 	}
3615 
3616 	return 0;
3617 }
3618 
3619 /*
3620  * If SMB buffer fields are valid, copy into temporary buffer to hold result.
3621  * Caller must free buffer.
3622  */
3623 int
3624 smb2_validate_and_copy_iov(unsigned int offset, unsigned int buffer_length,
3625 			   struct kvec *iov, unsigned int minbufsize,
3626 			   char *data)
3627 {
3628 	char *begin_of_buf = offset + (char *)iov->iov_base;
3629 	int rc;
3630 
3631 	if (!data)
3632 		return -EINVAL;
3633 
3634 	rc = smb2_validate_iov(offset, buffer_length, iov, minbufsize);
3635 	if (rc)
3636 		return rc;
3637 
3638 	memcpy(data, begin_of_buf, minbufsize);
3639 
3640 	return 0;
3641 }
3642 
3643 int
3644 SMB2_query_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3645 		     struct smb_rqst *rqst,
3646 		     u64 persistent_fid, u64 volatile_fid,
3647 		     u8 info_class, u8 info_type, u32 additional_info,
3648 		     size_t output_len, size_t input_len, void *input)
3649 {
3650 	struct smb2_query_info_req *req;
3651 	struct kvec *iov = rqst->rq_iov;
3652 	unsigned int total_len;
3653 	size_t len;
3654 	int rc;
3655 
3656 	if (unlikely(check_add_overflow(input_len, sizeof(*req), &len) ||
3657 		     len > CIFSMaxBufSize))
3658 		return -EINVAL;
3659 
3660 	rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
3661 				 (void **) &req, &total_len);
3662 	if (rc)
3663 		return rc;
3664 
3665 	req->InfoType = info_type;
3666 	req->FileInfoClass = info_class;
3667 	req->PersistentFileId = persistent_fid;
3668 	req->VolatileFileId = volatile_fid;
3669 	req->AdditionalInformation = cpu_to_le32(additional_info);
3670 
3671 	req->OutputBufferLength = cpu_to_le32(output_len);
3672 	if (input_len) {
3673 		req->InputBufferLength = cpu_to_le32(input_len);
3674 		/* total_len for smb query request never close to le16 max */
3675 		req->InputBufferOffset = cpu_to_le16(total_len - 1);
3676 		memcpy(req->Buffer, input, input_len);
3677 	}
3678 
3679 	iov[0].iov_base = (char *)req;
3680 	/* 1 for Buffer */
3681 	iov[0].iov_len = len;
3682 	return 0;
3683 }
3684 
3685 void
3686 SMB2_query_info_free(struct smb_rqst *rqst)
3687 {
3688 	if (rqst && rqst->rq_iov)
3689 		cifs_buf_release(rqst->rq_iov[0].iov_base); /* request */
3690 }
3691 
3692 static int
3693 query_info(const unsigned int xid, struct cifs_tcon *tcon,
3694 	   u64 persistent_fid, u64 volatile_fid, u8 info_class, u8 info_type,
3695 	   u32 additional_info, size_t output_len, size_t min_len, void **data,
3696 		u32 *dlen)
3697 {
3698 	struct smb_rqst rqst;
3699 	struct smb2_query_info_rsp *rsp = NULL;
3700 	struct kvec iov[1];
3701 	struct kvec rsp_iov;
3702 	int rc = 0;
3703 	int resp_buftype = CIFS_NO_BUFFER;
3704 	struct cifs_ses *ses = tcon->ses;
3705 	struct TCP_Server_Info *server;
3706 	int flags = 0;
3707 	bool allocated = false;
3708 
3709 	cifs_dbg(FYI, "Query Info\n");
3710 
3711 	if (!ses)
3712 		return -EIO;
3713 	server = cifs_pick_channel(ses);
3714 	if (!server)
3715 		return -EIO;
3716 
3717 	if (smb3_encryption_required(tcon))
3718 		flags |= CIFS_TRANSFORM_REQ;
3719 
3720 	memset(&rqst, 0, sizeof(struct smb_rqst));
3721 	memset(&iov, 0, sizeof(iov));
3722 	rqst.rq_iov = iov;
3723 	rqst.rq_nvec = 1;
3724 
3725 	rc = SMB2_query_info_init(tcon, server,
3726 				  &rqst, persistent_fid, volatile_fid,
3727 				  info_class, info_type, additional_info,
3728 				  output_len, 0, NULL);
3729 	if (rc)
3730 		goto qinf_exit;
3731 
3732 	trace_smb3_query_info_enter(xid, persistent_fid, tcon->tid,
3733 				    ses->Suid, info_class, (__u32)info_type);
3734 
3735 	rc = cifs_send_recv(xid, ses, server,
3736 			    &rqst, &resp_buftype, flags, &rsp_iov);
3737 	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
3738 
3739 	if (rc) {
3740 		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
3741 		trace_smb3_query_info_err(xid, persistent_fid, tcon->tid,
3742 				ses->Suid, info_class, (__u32)info_type, rc);
3743 		goto qinf_exit;
3744 	}
3745 
3746 	trace_smb3_query_info_done(xid, persistent_fid, tcon->tid,
3747 				ses->Suid, info_class, (__u32)info_type);
3748 
3749 	if (dlen) {
3750 		*dlen = le32_to_cpu(rsp->OutputBufferLength);
3751 		if (!*data) {
3752 			*data = kmalloc(*dlen, GFP_KERNEL);
3753 			if (!*data) {
3754 				cifs_tcon_dbg(VFS,
3755 					"Error %d allocating memory for acl\n",
3756 					rc);
3757 				*dlen = 0;
3758 				rc = -ENOMEM;
3759 				goto qinf_exit;
3760 			}
3761 			allocated = true;
3762 		}
3763 	}
3764 
3765 	rc = smb2_validate_and_copy_iov(le16_to_cpu(rsp->OutputBufferOffset),
3766 					le32_to_cpu(rsp->OutputBufferLength),
3767 					&rsp_iov, dlen ? *dlen : min_len, *data);
3768 	if (rc && allocated) {
3769 		kfree(*data);
3770 		*data = NULL;
3771 		*dlen = 0;
3772 	}
3773 
3774 qinf_exit:
3775 	SMB2_query_info_free(&rqst);
3776 	free_rsp_buf(resp_buftype, rsp);
3777 	return rc;
3778 }
3779 
3780 int SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
3781 	u64 persistent_fid, u64 volatile_fid, struct smb2_file_all_info *data)
3782 {
3783 	return query_info(xid, tcon, persistent_fid, volatile_fid,
3784 			  FILE_ALL_INFORMATION, SMB2_O_INFO_FILE, 0,
3785 			  sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
3786 			  sizeof(struct smb2_file_all_info), (void **)&data,
3787 			  NULL);
3788 }
3789 
3790 #if 0
3791 /* currently unused, as now we are doing compounding instead (see smb311_posix_query_path_info) */
3792 int
3793 SMB311_posix_query_info(const unsigned int xid, struct cifs_tcon *tcon,
3794 		u64 persistent_fid, u64 volatile_fid, struct smb311_posix_qinfo *data, u32 *plen)
3795 {
3796 	size_t output_len = sizeof(struct smb311_posix_qinfo *) +
3797 			(sizeof(struct cifs_sid) * 2) + (PATH_MAX * 2);
3798 	*plen = 0;
3799 
3800 	return query_info(xid, tcon, persistent_fid, volatile_fid,
3801 			  SMB_FIND_FILE_POSIX_INFO, SMB2_O_INFO_FILE, 0,
3802 			  output_len, sizeof(struct smb311_posix_qinfo), (void **)&data, plen);
3803 	/* Note caller must free "data" (passed in above). It may be allocated in query_info call */
3804 }
3805 #endif
3806 
3807 int
3808 SMB2_query_acl(const unsigned int xid, struct cifs_tcon *tcon,
3809 	       u64 persistent_fid, u64 volatile_fid,
3810 	       void **data, u32 *plen, u32 extra_info)
3811 {
3812 	__u32 additional_info = OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
3813 				extra_info;
3814 	*plen = 0;
3815 
3816 	return query_info(xid, tcon, persistent_fid, volatile_fid,
3817 			  0, SMB2_O_INFO_SECURITY, additional_info,
3818 			  SMB2_MAX_BUFFER_SIZE, MIN_SEC_DESC_LEN, data, plen);
3819 }
3820 
3821 int
3822 SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
3823 		 u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
3824 {
3825 	return query_info(xid, tcon, persistent_fid, volatile_fid,
3826 			  FILE_INTERNAL_INFORMATION, SMB2_O_INFO_FILE, 0,
3827 			  sizeof(struct smb2_file_internal_info),
3828 			  sizeof(struct smb2_file_internal_info),
3829 			  (void **)&uniqueid, NULL);
3830 }
3831 
3832 /*
3833  * CHANGE_NOTIFY Request is sent to get notifications on changes to a directory
3834  * See MS-SMB2 2.2.35 and 2.2.36
3835  */
3836 
3837 static int
3838 SMB2_notify_init(const unsigned int xid, struct smb_rqst *rqst,
3839 		 struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3840 		 u64 persistent_fid, u64 volatile_fid,
3841 		 u32 completion_filter, bool watch_tree)
3842 {
3843 	struct smb2_change_notify_req *req;
3844 	struct kvec *iov = rqst->rq_iov;
3845 	unsigned int total_len;
3846 	int rc;
3847 
3848 	rc = smb2_plain_req_init(SMB2_CHANGE_NOTIFY, tcon, server,
3849 				 (void **) &req, &total_len);
3850 	if (rc)
3851 		return rc;
3852 
3853 	req->PersistentFileId = persistent_fid;
3854 	req->VolatileFileId = volatile_fid;
3855 	/* See note 354 of MS-SMB2, 64K max */
3856 	req->OutputBufferLength =
3857 		cpu_to_le32(SMB2_MAX_BUFFER_SIZE - MAX_SMB2_HDR_SIZE);
3858 	req->CompletionFilter = cpu_to_le32(completion_filter);
3859 	if (watch_tree)
3860 		req->Flags = cpu_to_le16(SMB2_WATCH_TREE);
3861 	else
3862 		req->Flags = 0;
3863 
3864 	iov[0].iov_base = (char *)req;
3865 	iov[0].iov_len = total_len;
3866 
3867 	return 0;
3868 }
3869 
3870 int
3871 SMB2_change_notify(const unsigned int xid, struct cifs_tcon *tcon,
3872 		u64 persistent_fid, u64 volatile_fid, bool watch_tree,
3873 		u32 completion_filter, u32 max_out_data_len, char **out_data,
3874 		u32 *plen /* returned data len */)
3875 {
3876 	struct cifs_ses *ses = tcon->ses;
3877 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
3878 	struct smb_rqst rqst;
3879 	struct smb2_change_notify_rsp *smb_rsp;
3880 	struct kvec iov[1];
3881 	struct kvec rsp_iov = {NULL, 0};
3882 	int resp_buftype = CIFS_NO_BUFFER;
3883 	int flags = 0;
3884 	int rc = 0;
3885 
3886 	cifs_dbg(FYI, "change notify\n");
3887 	if (!ses || !server)
3888 		return -EIO;
3889 
3890 	if (smb3_encryption_required(tcon))
3891 		flags |= CIFS_TRANSFORM_REQ;
3892 
3893 	memset(&rqst, 0, sizeof(struct smb_rqst));
3894 	memset(&iov, 0, sizeof(iov));
3895 	if (plen)
3896 		*plen = 0;
3897 
3898 	rqst.rq_iov = iov;
3899 	rqst.rq_nvec = 1;
3900 
3901 	rc = SMB2_notify_init(xid, &rqst, tcon, server,
3902 			      persistent_fid, volatile_fid,
3903 			      completion_filter, watch_tree);
3904 	if (rc)
3905 		goto cnotify_exit;
3906 
3907 	trace_smb3_notify_enter(xid, persistent_fid, tcon->tid, ses->Suid,
3908 				(u8)watch_tree, completion_filter);
3909 	rc = cifs_send_recv(xid, ses, server,
3910 			    &rqst, &resp_buftype, flags, &rsp_iov);
3911 
3912 	if (rc != 0) {
3913 		cifs_stats_fail_inc(tcon, SMB2_CHANGE_NOTIFY_HE);
3914 		trace_smb3_notify_err(xid, persistent_fid, tcon->tid, ses->Suid,
3915 				(u8)watch_tree, completion_filter, rc);
3916 	} else {
3917 		trace_smb3_notify_done(xid, persistent_fid, tcon->tid,
3918 			ses->Suid, (u8)watch_tree, completion_filter);
3919 		/* validate that notify information is plausible */
3920 		if ((rsp_iov.iov_base == NULL) ||
3921 		    (rsp_iov.iov_len < sizeof(struct smb2_change_notify_rsp) + 1))
3922 			goto cnotify_exit;
3923 
3924 		smb_rsp = (struct smb2_change_notify_rsp *)rsp_iov.iov_base;
3925 
3926 		smb2_validate_iov(le16_to_cpu(smb_rsp->OutputBufferOffset),
3927 				le32_to_cpu(smb_rsp->OutputBufferLength), &rsp_iov,
3928 				sizeof(struct file_notify_information));
3929 
3930 		*out_data = kmemdup((char *)smb_rsp + le16_to_cpu(smb_rsp->OutputBufferOffset),
3931 				le32_to_cpu(smb_rsp->OutputBufferLength), GFP_KERNEL);
3932 		if (*out_data == NULL) {
3933 			rc = -ENOMEM;
3934 			goto cnotify_exit;
3935 		} else if (plen)
3936 			*plen = le32_to_cpu(smb_rsp->OutputBufferLength);
3937 	}
3938 
3939  cnotify_exit:
3940 	if (rqst.rq_iov)
3941 		cifs_small_buf_release(rqst.rq_iov[0].iov_base); /* request */
3942 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3943 	return rc;
3944 }
3945 
3946 
3947 
3948 /*
3949  * This is a no-op for now. We're not really interested in the reply, but
3950  * rather in the fact that the server sent one and that server->lstrp
3951  * gets updated.
3952  *
3953  * FIXME: maybe we should consider checking that the reply matches request?
3954  */
3955 static void
3956 smb2_echo_callback(struct mid_q_entry *mid)
3957 {
3958 	struct TCP_Server_Info *server = mid->callback_data;
3959 	struct smb2_echo_rsp *rsp = (struct smb2_echo_rsp *)mid->resp_buf;
3960 	struct cifs_credits credits = { .value = 0, .instance = 0 };
3961 
3962 	if (mid->mid_state == MID_RESPONSE_RECEIVED
3963 	    || mid->mid_state == MID_RESPONSE_MALFORMED) {
3964 		credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
3965 		credits.instance = server->reconnect_instance;
3966 	}
3967 
3968 	release_mid(mid);
3969 	add_credits(server, &credits, CIFS_ECHO_OP);
3970 }
3971 
3972 void smb2_reconnect_server(struct work_struct *work)
3973 {
3974 	struct TCP_Server_Info *server = container_of(work,
3975 					struct TCP_Server_Info, reconnect.work);
3976 	struct TCP_Server_Info *pserver;
3977 	struct cifs_ses *ses, *ses2;
3978 	struct cifs_tcon *tcon, *tcon2;
3979 	struct list_head tmp_list, tmp_ses_list;
3980 	bool ses_exist = false;
3981 	bool tcon_selected = false;
3982 	int rc;
3983 	bool resched = false;
3984 
3985 	/* first check if ref count has reached 0, if not inc ref count */
3986 	spin_lock(&cifs_tcp_ses_lock);
3987 	if (!server->srv_count) {
3988 		spin_unlock(&cifs_tcp_ses_lock);
3989 		return;
3990 	}
3991 	server->srv_count++;
3992 	spin_unlock(&cifs_tcp_ses_lock);
3993 
3994 	/* If server is a channel, select the primary channel */
3995 	pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
3996 
3997 	/* Prevent simultaneous reconnects that can corrupt tcon->rlist list */
3998 	mutex_lock(&pserver->reconnect_mutex);
3999 
4000 	/* if the server is marked for termination, drop the ref count here */
4001 	if (server->terminate) {
4002 		cifs_put_tcp_session(server, true);
4003 		mutex_unlock(&pserver->reconnect_mutex);
4004 		return;
4005 	}
4006 
4007 	INIT_LIST_HEAD(&tmp_list);
4008 	INIT_LIST_HEAD(&tmp_ses_list);
4009 	cifs_dbg(FYI, "Reconnecting tcons and channels\n");
4010 
4011 	spin_lock(&cifs_tcp_ses_lock);
4012 	list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
4013 		spin_lock(&ses->ses_lock);
4014 		if (ses->ses_status == SES_EXITING) {
4015 			spin_unlock(&ses->ses_lock);
4016 			continue;
4017 		}
4018 		spin_unlock(&ses->ses_lock);
4019 
4020 		tcon_selected = false;
4021 
4022 		list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
4023 			if (tcon->need_reconnect || tcon->need_reopen_files) {
4024 				tcon->tc_count++;
4025 				list_add_tail(&tcon->rlist, &tmp_list);
4026 				tcon_selected = true;
4027 			}
4028 		}
4029 		/*
4030 		 * IPC has the same lifetime as its session and uses its
4031 		 * refcount.
4032 		 */
4033 		if (ses->tcon_ipc && ses->tcon_ipc->need_reconnect) {
4034 			list_add_tail(&ses->tcon_ipc->rlist, &tmp_list);
4035 			tcon_selected = true;
4036 			cifs_smb_ses_inc_refcount(ses);
4037 		}
4038 		/*
4039 		 * handle the case where channel needs to reconnect
4040 		 * binding session, but tcon is healthy (some other channel
4041 		 * is active)
4042 		 */
4043 		spin_lock(&ses->chan_lock);
4044 		if (!tcon_selected && cifs_chan_needs_reconnect(ses, server)) {
4045 			list_add_tail(&ses->rlist, &tmp_ses_list);
4046 			ses_exist = true;
4047 			cifs_smb_ses_inc_refcount(ses);
4048 		}
4049 		spin_unlock(&ses->chan_lock);
4050 	}
4051 	spin_unlock(&cifs_tcp_ses_lock);
4052 
4053 	list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) {
4054 		rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server, true);
4055 		if (!rc)
4056 			cifs_reopen_persistent_handles(tcon);
4057 		else
4058 			resched = true;
4059 		list_del_init(&tcon->rlist);
4060 		if (tcon->ipc)
4061 			cifs_put_smb_ses(tcon->ses);
4062 		else
4063 			cifs_put_tcon(tcon);
4064 	}
4065 
4066 	if (!ses_exist)
4067 		goto done;
4068 
4069 	/* allocate a dummy tcon struct used for reconnect */
4070 	tcon = tcon_info_alloc(false);
4071 	if (!tcon) {
4072 		resched = true;
4073 		list_for_each_entry_safe(ses, ses2, &tmp_ses_list, rlist) {
4074 			list_del_init(&ses->rlist);
4075 			cifs_put_smb_ses(ses);
4076 		}
4077 		goto done;
4078 	}
4079 
4080 	tcon->status = TID_GOOD;
4081 	tcon->retry = false;
4082 	tcon->need_reconnect = false;
4083 
4084 	/* now reconnect sessions for necessary channels */
4085 	list_for_each_entry_safe(ses, ses2, &tmp_ses_list, rlist) {
4086 		tcon->ses = ses;
4087 		rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server, true);
4088 		if (rc)
4089 			resched = true;
4090 		list_del_init(&ses->rlist);
4091 		cifs_put_smb_ses(ses);
4092 	}
4093 	tconInfoFree(tcon);
4094 
4095 done:
4096 	cifs_dbg(FYI, "Reconnecting tcons and channels finished\n");
4097 	if (resched)
4098 		queue_delayed_work(cifsiod_wq, &server->reconnect, 2 * HZ);
4099 	mutex_unlock(&pserver->reconnect_mutex);
4100 
4101 	/* now we can safely release srv struct */
4102 	cifs_put_tcp_session(server, true);
4103 }
4104 
4105 int
4106 SMB2_echo(struct TCP_Server_Info *server)
4107 {
4108 	struct smb2_echo_req *req;
4109 	int rc = 0;
4110 	struct kvec iov[1];
4111 	struct smb_rqst rqst = { .rq_iov = iov,
4112 				 .rq_nvec = 1 };
4113 	unsigned int total_len;
4114 
4115 	cifs_dbg(FYI, "In echo request for conn_id %lld\n", server->conn_id);
4116 
4117 	spin_lock(&server->srv_lock);
4118 	if (server->ops->need_neg &&
4119 	    server->ops->need_neg(server)) {
4120 		spin_unlock(&server->srv_lock);
4121 		/* No need to send echo on newly established connections */
4122 		mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
4123 		return rc;
4124 	}
4125 	spin_unlock(&server->srv_lock);
4126 
4127 	rc = smb2_plain_req_init(SMB2_ECHO, NULL, server,
4128 				 (void **)&req, &total_len);
4129 	if (rc)
4130 		return rc;
4131 
4132 	req->hdr.CreditRequest = cpu_to_le16(1);
4133 
4134 	iov[0].iov_len = total_len;
4135 	iov[0].iov_base = (char *)req;
4136 
4137 	rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, NULL,
4138 			     server, CIFS_ECHO_OP, NULL);
4139 	if (rc)
4140 		cifs_dbg(FYI, "Echo request failed: %d\n", rc);
4141 
4142 	cifs_small_buf_release(req);
4143 	return rc;
4144 }
4145 
4146 void
4147 SMB2_flush_free(struct smb_rqst *rqst)
4148 {
4149 	if (rqst && rqst->rq_iov)
4150 		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
4151 }
4152 
4153 int
4154 SMB2_flush_init(const unsigned int xid, struct smb_rqst *rqst,
4155 		struct cifs_tcon *tcon, struct TCP_Server_Info *server,
4156 		u64 persistent_fid, u64 volatile_fid)
4157 {
4158 	struct smb2_flush_req *req;
4159 	struct kvec *iov = rqst->rq_iov;
4160 	unsigned int total_len;
4161 	int rc;
4162 
4163 	rc = smb2_plain_req_init(SMB2_FLUSH, tcon, server,
4164 				 (void **) &req, &total_len);
4165 	if (rc)
4166 		return rc;
4167 
4168 	req->PersistentFileId = persistent_fid;
4169 	req->VolatileFileId = volatile_fid;
4170 
4171 	iov[0].iov_base = (char *)req;
4172 	iov[0].iov_len = total_len;
4173 
4174 	return 0;
4175 }
4176 
4177 int
4178 SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
4179 	   u64 volatile_fid)
4180 {
4181 	struct cifs_ses *ses = tcon->ses;
4182 	struct smb_rqst rqst;
4183 	struct kvec iov[1];
4184 	struct kvec rsp_iov = {NULL, 0};
4185 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
4186 	int resp_buftype = CIFS_NO_BUFFER;
4187 	int flags = 0;
4188 	int rc = 0;
4189 
4190 	cifs_dbg(FYI, "flush\n");
4191 	if (!ses || !(ses->server))
4192 		return -EIO;
4193 
4194 	if (smb3_encryption_required(tcon))
4195 		flags |= CIFS_TRANSFORM_REQ;
4196 
4197 	memset(&rqst, 0, sizeof(struct smb_rqst));
4198 	memset(&iov, 0, sizeof(iov));
4199 	rqst.rq_iov = iov;
4200 	rqst.rq_nvec = 1;
4201 
4202 	rc = SMB2_flush_init(xid, &rqst, tcon, server,
4203 			     persistent_fid, volatile_fid);
4204 	if (rc)
4205 		goto flush_exit;
4206 
4207 	trace_smb3_flush_enter(xid, persistent_fid, tcon->tid, ses->Suid);
4208 	rc = cifs_send_recv(xid, ses, server,
4209 			    &rqst, &resp_buftype, flags, &rsp_iov);
4210 
4211 	if (rc != 0) {
4212 		cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
4213 		trace_smb3_flush_err(xid, persistent_fid, tcon->tid, ses->Suid,
4214 				     rc);
4215 	} else
4216 		trace_smb3_flush_done(xid, persistent_fid, tcon->tid,
4217 				      ses->Suid);
4218 
4219  flush_exit:
4220 	SMB2_flush_free(&rqst);
4221 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4222 	return rc;
4223 }
4224 
4225 #ifdef CONFIG_CIFS_SMB_DIRECT
4226 static inline bool smb3_use_rdma_offload(struct cifs_io_parms *io_parms)
4227 {
4228 	struct TCP_Server_Info *server = io_parms->server;
4229 	struct cifs_tcon *tcon = io_parms->tcon;
4230 
4231 	/* we can only offload if we're connected */
4232 	if (!server || !tcon)
4233 		return false;
4234 
4235 	/* we can only offload on an rdma connection */
4236 	if (!server->rdma || !server->smbd_conn)
4237 		return false;
4238 
4239 	/* we don't support signed offload yet */
4240 	if (server->sign)
4241 		return false;
4242 
4243 	/* we don't support encrypted offload yet */
4244 	if (smb3_encryption_required(tcon))
4245 		return false;
4246 
4247 	/* offload also has its overhead, so only do it if desired */
4248 	if (io_parms->length < server->smbd_conn->rdma_readwrite_threshold)
4249 		return false;
4250 
4251 	return true;
4252 }
4253 #endif /* CONFIG_CIFS_SMB_DIRECT */
4254 
4255 /*
4256  * To form a chain of read requests, any read requests after the first should
4257  * have the end_of_chain boolean set to true.
4258  */
4259 static int
4260 smb2_new_read_req(void **buf, unsigned int *total_len,
4261 	struct cifs_io_parms *io_parms, struct cifs_readdata *rdata,
4262 	unsigned int remaining_bytes, int request_type)
4263 {
4264 	int rc = -EACCES;
4265 	struct smb2_read_req *req = NULL;
4266 	struct smb2_hdr *shdr;
4267 	struct TCP_Server_Info *server = io_parms->server;
4268 
4269 	rc = smb2_plain_req_init(SMB2_READ, io_parms->tcon, server,
4270 				 (void **) &req, total_len);
4271 	if (rc)
4272 		return rc;
4273 
4274 	if (server == NULL)
4275 		return -ECONNABORTED;
4276 
4277 	shdr = &req->hdr;
4278 	shdr->Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
4279 
4280 	req->PersistentFileId = io_parms->persistent_fid;
4281 	req->VolatileFileId = io_parms->volatile_fid;
4282 	req->ReadChannelInfoOffset = 0; /* reserved */
4283 	req->ReadChannelInfoLength = 0; /* reserved */
4284 	req->Channel = 0; /* reserved */
4285 	req->MinimumCount = 0;
4286 	req->Length = cpu_to_le32(io_parms->length);
4287 	req->Offset = cpu_to_le64(io_parms->offset);
4288 
4289 	trace_smb3_read_enter(0 /* xid */,
4290 			io_parms->persistent_fid,
4291 			io_parms->tcon->tid, io_parms->tcon->ses->Suid,
4292 			io_parms->offset, io_parms->length);
4293 #ifdef CONFIG_CIFS_SMB_DIRECT
4294 	/*
4295 	 * If we want to do a RDMA write, fill in and append
4296 	 * smbd_buffer_descriptor_v1 to the end of read request
4297 	 */
4298 	if (smb3_use_rdma_offload(io_parms)) {
4299 		struct smbd_buffer_descriptor_v1 *v1;
4300 		bool need_invalidate = server->dialect == SMB30_PROT_ID;
4301 
4302 		rdata->mr = smbd_register_mr(server->smbd_conn, &rdata->iter,
4303 					     true, need_invalidate);
4304 		if (!rdata->mr)
4305 			return -EAGAIN;
4306 
4307 		req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
4308 		if (need_invalidate)
4309 			req->Channel = SMB2_CHANNEL_RDMA_V1;
4310 		req->ReadChannelInfoOffset =
4311 			cpu_to_le16(offsetof(struct smb2_read_req, Buffer));
4312 		req->ReadChannelInfoLength =
4313 			cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
4314 		v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
4315 		v1->offset = cpu_to_le64(rdata->mr->mr->iova);
4316 		v1->token = cpu_to_le32(rdata->mr->mr->rkey);
4317 		v1->length = cpu_to_le32(rdata->mr->mr->length);
4318 
4319 		*total_len += sizeof(*v1) - 1;
4320 	}
4321 #endif
4322 	if (request_type & CHAINED_REQUEST) {
4323 		if (!(request_type & END_OF_CHAIN)) {
4324 			/* next 8-byte aligned request */
4325 			*total_len = ALIGN(*total_len, 8);
4326 			shdr->NextCommand = cpu_to_le32(*total_len);
4327 		} else /* END_OF_CHAIN */
4328 			shdr->NextCommand = 0;
4329 		if (request_type & RELATED_REQUEST) {
4330 			shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
4331 			/*
4332 			 * Related requests use info from previous read request
4333 			 * in chain.
4334 			 */
4335 			shdr->SessionId = cpu_to_le64(0xFFFFFFFFFFFFFFFF);
4336 			shdr->Id.SyncId.TreeId = cpu_to_le32(0xFFFFFFFF);
4337 			req->PersistentFileId = (u64)-1;
4338 			req->VolatileFileId = (u64)-1;
4339 		}
4340 	}
4341 	if (remaining_bytes > io_parms->length)
4342 		req->RemainingBytes = cpu_to_le32(remaining_bytes);
4343 	else
4344 		req->RemainingBytes = 0;
4345 
4346 	*buf = req;
4347 	return rc;
4348 }
4349 
4350 static void
4351 smb2_readv_callback(struct mid_q_entry *mid)
4352 {
4353 	struct cifs_readdata *rdata = mid->callback_data;
4354 	struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
4355 	struct TCP_Server_Info *server = rdata->server;
4356 	struct smb2_hdr *shdr =
4357 				(struct smb2_hdr *)rdata->iov[0].iov_base;
4358 	struct cifs_credits credits = { .value = 0, .instance = 0 };
4359 	struct smb_rqst rqst = { .rq_iov = &rdata->iov[1], .rq_nvec = 1 };
4360 
4361 	if (rdata->got_bytes) {
4362 		rqst.rq_iter	  = rdata->iter;
4363 		rqst.rq_iter_size = iov_iter_count(&rdata->iter);
4364 	}
4365 
4366 	WARN_ONCE(rdata->server != mid->server,
4367 		  "rdata server %p != mid server %p",
4368 		  rdata->server, mid->server);
4369 
4370 	cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%u\n",
4371 		 __func__, mid->mid, mid->mid_state, rdata->result,
4372 		 rdata->bytes);
4373 
4374 	switch (mid->mid_state) {
4375 	case MID_RESPONSE_RECEIVED:
4376 		credits.value = le16_to_cpu(shdr->CreditRequest);
4377 		credits.instance = server->reconnect_instance;
4378 		/* result already set, check signature */
4379 		if (server->sign && !mid->decrypted) {
4380 			int rc;
4381 
4382 			iov_iter_revert(&rqst.rq_iter, rdata->got_bytes);
4383 			iov_iter_truncate(&rqst.rq_iter, rdata->got_bytes);
4384 			rc = smb2_verify_signature(&rqst, server);
4385 			if (rc)
4386 				cifs_tcon_dbg(VFS, "SMB signature verification returned error = %d\n",
4387 					 rc);
4388 		}
4389 		/* FIXME: should this be counted toward the initiating task? */
4390 		task_io_account_read(rdata->got_bytes);
4391 		cifs_stats_bytes_read(tcon, rdata->got_bytes);
4392 		break;
4393 	case MID_REQUEST_SUBMITTED:
4394 	case MID_RETRY_NEEDED:
4395 		rdata->result = -EAGAIN;
4396 		if (server->sign && rdata->got_bytes)
4397 			/* reset bytes number since we can not check a sign */
4398 			rdata->got_bytes = 0;
4399 		/* FIXME: should this be counted toward the initiating task? */
4400 		task_io_account_read(rdata->got_bytes);
4401 		cifs_stats_bytes_read(tcon, rdata->got_bytes);
4402 		break;
4403 	case MID_RESPONSE_MALFORMED:
4404 		credits.value = le16_to_cpu(shdr->CreditRequest);
4405 		credits.instance = server->reconnect_instance;
4406 		fallthrough;
4407 	default:
4408 		rdata->result = -EIO;
4409 	}
4410 #ifdef CONFIG_CIFS_SMB_DIRECT
4411 	/*
4412 	 * If this rdata has a memmory registered, the MR can be freed
4413 	 * MR needs to be freed as soon as I/O finishes to prevent deadlock
4414 	 * because they have limited number and are used for future I/Os
4415 	 */
4416 	if (rdata->mr) {
4417 		smbd_deregister_mr(rdata->mr);
4418 		rdata->mr = NULL;
4419 	}
4420 #endif
4421 	if (rdata->result && rdata->result != -ENODATA) {
4422 		cifs_stats_fail_inc(tcon, SMB2_READ_HE);
4423 		trace_smb3_read_err(0 /* xid */,
4424 				    rdata->cfile->fid.persistent_fid,
4425 				    tcon->tid, tcon->ses->Suid, rdata->offset,
4426 				    rdata->bytes, rdata->result);
4427 	} else
4428 		trace_smb3_read_done(0 /* xid */,
4429 				     rdata->cfile->fid.persistent_fid,
4430 				     tcon->tid, tcon->ses->Suid,
4431 				     rdata->offset, rdata->got_bytes);
4432 
4433 	queue_work(cifsiod_wq, &rdata->work);
4434 	release_mid(mid);
4435 	add_credits(server, &credits, 0);
4436 }
4437 
4438 /* smb2_async_readv - send an async read, and set up mid to handle result */
4439 int
4440 smb2_async_readv(struct cifs_readdata *rdata)
4441 {
4442 	int rc, flags = 0;
4443 	char *buf;
4444 	struct smb2_hdr *shdr;
4445 	struct cifs_io_parms io_parms;
4446 	struct smb_rqst rqst = { .rq_iov = rdata->iov,
4447 				 .rq_nvec = 1 };
4448 	struct TCP_Server_Info *server;
4449 	struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
4450 	unsigned int total_len;
4451 	int credit_request;
4452 
4453 	cifs_dbg(FYI, "%s: offset=%llu bytes=%u\n",
4454 		 __func__, rdata->offset, rdata->bytes);
4455 
4456 	if (!rdata->server)
4457 		rdata->server = cifs_pick_channel(tcon->ses);
4458 
4459 	io_parms.tcon = tlink_tcon(rdata->cfile->tlink);
4460 	io_parms.server = server = rdata->server;
4461 	io_parms.offset = rdata->offset;
4462 	io_parms.length = rdata->bytes;
4463 	io_parms.persistent_fid = rdata->cfile->fid.persistent_fid;
4464 	io_parms.volatile_fid = rdata->cfile->fid.volatile_fid;
4465 	io_parms.pid = rdata->pid;
4466 
4467 	rc = smb2_new_read_req(
4468 		(void **) &buf, &total_len, &io_parms, rdata, 0, 0);
4469 	if (rc)
4470 		return rc;
4471 
4472 	if (smb3_encryption_required(io_parms.tcon))
4473 		flags |= CIFS_TRANSFORM_REQ;
4474 
4475 	rdata->iov[0].iov_base = buf;
4476 	rdata->iov[0].iov_len = total_len;
4477 
4478 	shdr = (struct smb2_hdr *)buf;
4479 
4480 	if (rdata->credits.value > 0) {
4481 		shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(rdata->bytes,
4482 						SMB2_MAX_BUFFER_SIZE));
4483 		credit_request = le16_to_cpu(shdr->CreditCharge) + 8;
4484 		if (server->credits >= server->max_credits)
4485 			shdr->CreditRequest = cpu_to_le16(0);
4486 		else
4487 			shdr->CreditRequest = cpu_to_le16(
4488 				min_t(int, server->max_credits -
4489 						server->credits, credit_request));
4490 
4491 		rc = adjust_credits(server, &rdata->credits, rdata->bytes);
4492 		if (rc)
4493 			goto async_readv_out;
4494 
4495 		flags |= CIFS_HAS_CREDITS;
4496 	}
4497 
4498 	kref_get(&rdata->refcount);
4499 	rc = cifs_call_async(server, &rqst,
4500 			     cifs_readv_receive, smb2_readv_callback,
4501 			     smb3_handle_read_data, rdata, flags,
4502 			     &rdata->credits);
4503 	if (rc) {
4504 		kref_put(&rdata->refcount, cifs_readdata_release);
4505 		cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE);
4506 		trace_smb3_read_err(0 /* xid */, io_parms.persistent_fid,
4507 				    io_parms.tcon->tid,
4508 				    io_parms.tcon->ses->Suid,
4509 				    io_parms.offset, io_parms.length, rc);
4510 	}
4511 
4512 async_readv_out:
4513 	cifs_small_buf_release(buf);
4514 	return rc;
4515 }
4516 
4517 int
4518 SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
4519 	  unsigned int *nbytes, char **buf, int *buf_type)
4520 {
4521 	struct smb_rqst rqst;
4522 	int resp_buftype, rc;
4523 	struct smb2_read_req *req = NULL;
4524 	struct smb2_read_rsp *rsp = NULL;
4525 	struct kvec iov[1];
4526 	struct kvec rsp_iov;
4527 	unsigned int total_len;
4528 	int flags = CIFS_LOG_ERROR;
4529 	struct cifs_ses *ses = io_parms->tcon->ses;
4530 
4531 	if (!io_parms->server)
4532 		io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
4533 
4534 	*nbytes = 0;
4535 	rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);
4536 	if (rc)
4537 		return rc;
4538 
4539 	if (smb3_encryption_required(io_parms->tcon))
4540 		flags |= CIFS_TRANSFORM_REQ;
4541 
4542 	iov[0].iov_base = (char *)req;
4543 	iov[0].iov_len = total_len;
4544 
4545 	memset(&rqst, 0, sizeof(struct smb_rqst));
4546 	rqst.rq_iov = iov;
4547 	rqst.rq_nvec = 1;
4548 
4549 	rc = cifs_send_recv(xid, ses, io_parms->server,
4550 			    &rqst, &resp_buftype, flags, &rsp_iov);
4551 	rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
4552 
4553 	if (rc) {
4554 		if (rc != -ENODATA) {
4555 			cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
4556 			cifs_dbg(VFS, "Send error in read = %d\n", rc);
4557 			trace_smb3_read_err(xid,
4558 					    req->PersistentFileId,
4559 					    io_parms->tcon->tid, ses->Suid,
4560 					    io_parms->offset, io_parms->length,
4561 					    rc);
4562 		} else
4563 			trace_smb3_read_done(xid, req->PersistentFileId, io_parms->tcon->tid,
4564 					     ses->Suid, io_parms->offset, 0);
4565 		free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4566 		cifs_small_buf_release(req);
4567 		return rc == -ENODATA ? 0 : rc;
4568 	} else
4569 		trace_smb3_read_done(xid,
4570 				    req->PersistentFileId,
4571 				    io_parms->tcon->tid, ses->Suid,
4572 				    io_parms->offset, io_parms->length);
4573 
4574 	cifs_small_buf_release(req);
4575 
4576 	*nbytes = le32_to_cpu(rsp->DataLength);
4577 	if ((*nbytes > CIFS_MAX_MSGSIZE) ||
4578 	    (*nbytes > io_parms->length)) {
4579 		cifs_dbg(FYI, "bad length %d for count %d\n",
4580 			 *nbytes, io_parms->length);
4581 		rc = -EIO;
4582 		*nbytes = 0;
4583 	}
4584 
4585 	if (*buf) {
4586 		memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);
4587 		free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4588 	} else if (resp_buftype != CIFS_NO_BUFFER) {
4589 		*buf = rsp_iov.iov_base;
4590 		if (resp_buftype == CIFS_SMALL_BUFFER)
4591 			*buf_type = CIFS_SMALL_BUFFER;
4592 		else if (resp_buftype == CIFS_LARGE_BUFFER)
4593 			*buf_type = CIFS_LARGE_BUFFER;
4594 	}
4595 	return rc;
4596 }
4597 
4598 /*
4599  * Check the mid_state and signature on received buffer (if any), and queue the
4600  * workqueue completion task.
4601  */
4602 static void
4603 smb2_writev_callback(struct mid_q_entry *mid)
4604 {
4605 	struct cifs_writedata *wdata = mid->callback_data;
4606 	struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
4607 	struct TCP_Server_Info *server = wdata->server;
4608 	unsigned int written;
4609 	struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
4610 	struct cifs_credits credits = { .value = 0, .instance = 0 };
4611 
4612 	WARN_ONCE(wdata->server != mid->server,
4613 		  "wdata server %p != mid server %p",
4614 		  wdata->server, mid->server);
4615 
4616 	switch (mid->mid_state) {
4617 	case MID_RESPONSE_RECEIVED:
4618 		credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4619 		credits.instance = server->reconnect_instance;
4620 		wdata->result = smb2_check_receive(mid, server, 0);
4621 		if (wdata->result != 0)
4622 			break;
4623 
4624 		written = le32_to_cpu(rsp->DataLength);
4625 		/*
4626 		 * Mask off high 16 bits when bytes written as returned
4627 		 * by the server is greater than bytes requested by the
4628 		 * client. OS/2 servers are known to set incorrect
4629 		 * CountHigh values.
4630 		 */
4631 		if (written > wdata->bytes)
4632 			written &= 0xFFFF;
4633 
4634 		if (written < wdata->bytes)
4635 			wdata->result = -ENOSPC;
4636 		else
4637 			wdata->bytes = written;
4638 		break;
4639 	case MID_REQUEST_SUBMITTED:
4640 	case MID_RETRY_NEEDED:
4641 		wdata->result = -EAGAIN;
4642 		break;
4643 	case MID_RESPONSE_MALFORMED:
4644 		credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4645 		credits.instance = server->reconnect_instance;
4646 		fallthrough;
4647 	default:
4648 		wdata->result = -EIO;
4649 		break;
4650 	}
4651 #ifdef CONFIG_CIFS_SMB_DIRECT
4652 	/*
4653 	 * If this wdata has a memory registered, the MR can be freed
4654 	 * The number of MRs available is limited, it's important to recover
4655 	 * used MR as soon as I/O is finished. Hold MR longer in the later
4656 	 * I/O process can possibly result in I/O deadlock due to lack of MR
4657 	 * to send request on I/O retry
4658 	 */
4659 	if (wdata->mr) {
4660 		smbd_deregister_mr(wdata->mr);
4661 		wdata->mr = NULL;
4662 	}
4663 #endif
4664 	if (wdata->result) {
4665 		cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
4666 		trace_smb3_write_err(0 /* no xid */,
4667 				     wdata->cfile->fid.persistent_fid,
4668 				     tcon->tid, tcon->ses->Suid, wdata->offset,
4669 				     wdata->bytes, wdata->result);
4670 		if (wdata->result == -ENOSPC)
4671 			pr_warn_once("Out of space writing to %s\n",
4672 				     tcon->tree_name);
4673 	} else
4674 		trace_smb3_write_done(0 /* no xid */,
4675 				      wdata->cfile->fid.persistent_fid,
4676 				      tcon->tid, tcon->ses->Suid,
4677 				      wdata->offset, wdata->bytes);
4678 
4679 	queue_work(cifsiod_wq, &wdata->work);
4680 	release_mid(mid);
4681 	add_credits(server, &credits, 0);
4682 }
4683 
4684 /* smb2_async_writev - send an async write, and set up mid to handle result */
4685 int
4686 smb2_async_writev(struct cifs_writedata *wdata,
4687 		  void (*release)(struct kref *kref))
4688 {
4689 	int rc = -EACCES, flags = 0;
4690 	struct smb2_write_req *req = NULL;
4691 	struct smb2_hdr *shdr;
4692 	struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
4693 	struct TCP_Server_Info *server = wdata->server;
4694 	struct kvec iov[1];
4695 	struct smb_rqst rqst = { };
4696 	unsigned int total_len;
4697 	struct cifs_io_parms _io_parms;
4698 	struct cifs_io_parms *io_parms = NULL;
4699 	int credit_request;
4700 
4701 	if (!wdata->server)
4702 		server = wdata->server = cifs_pick_channel(tcon->ses);
4703 
4704 	/*
4705 	 * in future we may get cifs_io_parms passed in from the caller,
4706 	 * but for now we construct it here...
4707 	 */
4708 	_io_parms = (struct cifs_io_parms) {
4709 		.tcon = tcon,
4710 		.server = server,
4711 		.offset = wdata->offset,
4712 		.length = wdata->bytes,
4713 		.persistent_fid = wdata->cfile->fid.persistent_fid,
4714 		.volatile_fid = wdata->cfile->fid.volatile_fid,
4715 		.pid = wdata->pid,
4716 	};
4717 	io_parms = &_io_parms;
4718 
4719 	rc = smb2_plain_req_init(SMB2_WRITE, tcon, server,
4720 				 (void **) &req, &total_len);
4721 	if (rc)
4722 		return rc;
4723 
4724 	if (smb3_encryption_required(tcon))
4725 		flags |= CIFS_TRANSFORM_REQ;
4726 
4727 	shdr = (struct smb2_hdr *)req;
4728 	shdr->Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
4729 
4730 	req->PersistentFileId = io_parms->persistent_fid;
4731 	req->VolatileFileId = io_parms->volatile_fid;
4732 	req->WriteChannelInfoOffset = 0;
4733 	req->WriteChannelInfoLength = 0;
4734 	req->Channel = SMB2_CHANNEL_NONE;
4735 	req->Offset = cpu_to_le64(io_parms->offset);
4736 	req->DataOffset = cpu_to_le16(
4737 				offsetof(struct smb2_write_req, Buffer));
4738 	req->RemainingBytes = 0;
4739 
4740 	trace_smb3_write_enter(0 /* xid */,
4741 			       io_parms->persistent_fid,
4742 			       io_parms->tcon->tid,
4743 			       io_parms->tcon->ses->Suid,
4744 			       io_parms->offset,
4745 			       io_parms->length);
4746 
4747 #ifdef CONFIG_CIFS_SMB_DIRECT
4748 	/*
4749 	 * If we want to do a server RDMA read, fill in and append
4750 	 * smbd_buffer_descriptor_v1 to the end of write request
4751 	 */
4752 	if (smb3_use_rdma_offload(io_parms)) {
4753 		struct smbd_buffer_descriptor_v1 *v1;
4754 		size_t data_size = iov_iter_count(&wdata->iter);
4755 		bool need_invalidate = server->dialect == SMB30_PROT_ID;
4756 
4757 		wdata->mr = smbd_register_mr(server->smbd_conn, &wdata->iter,
4758 					     false, need_invalidate);
4759 		if (!wdata->mr) {
4760 			rc = -EAGAIN;
4761 			goto async_writev_out;
4762 		}
4763 		req->Length = 0;
4764 		req->DataOffset = 0;
4765 		req->RemainingBytes = cpu_to_le32(data_size);
4766 		req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
4767 		if (need_invalidate)
4768 			req->Channel = SMB2_CHANNEL_RDMA_V1;
4769 		req->WriteChannelInfoOffset =
4770 			cpu_to_le16(offsetof(struct smb2_write_req, Buffer));
4771 		req->WriteChannelInfoLength =
4772 			cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
4773 		v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
4774 		v1->offset = cpu_to_le64(wdata->mr->mr->iova);
4775 		v1->token = cpu_to_le32(wdata->mr->mr->rkey);
4776 		v1->length = cpu_to_le32(wdata->mr->mr->length);
4777 	}
4778 #endif
4779 	iov[0].iov_len = total_len - 1;
4780 	iov[0].iov_base = (char *)req;
4781 
4782 	rqst.rq_iov = iov;
4783 	rqst.rq_nvec = 1;
4784 	rqst.rq_iter = wdata->iter;
4785 	rqst.rq_iter_size = iov_iter_count(&rqst.rq_iter);
4786 #ifdef CONFIG_CIFS_SMB_DIRECT
4787 	if (wdata->mr)
4788 		iov[0].iov_len += sizeof(struct smbd_buffer_descriptor_v1);
4789 #endif
4790 	cifs_dbg(FYI, "async write at %llu %u bytes iter=%zx\n",
4791 		 io_parms->offset, io_parms->length, iov_iter_count(&rqst.rq_iter));
4792 
4793 #ifdef CONFIG_CIFS_SMB_DIRECT
4794 	/* For RDMA read, I/O size is in RemainingBytes not in Length */
4795 	if (!wdata->mr)
4796 		req->Length = cpu_to_le32(io_parms->length);
4797 #else
4798 	req->Length = cpu_to_le32(io_parms->length);
4799 #endif
4800 
4801 	if (wdata->credits.value > 0) {
4802 		shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->bytes,
4803 						    SMB2_MAX_BUFFER_SIZE));
4804 		credit_request = le16_to_cpu(shdr->CreditCharge) + 8;
4805 		if (server->credits >= server->max_credits)
4806 			shdr->CreditRequest = cpu_to_le16(0);
4807 		else
4808 			shdr->CreditRequest = cpu_to_le16(
4809 				min_t(int, server->max_credits -
4810 						server->credits, credit_request));
4811 
4812 		rc = adjust_credits(server, &wdata->credits, io_parms->length);
4813 		if (rc)
4814 			goto async_writev_out;
4815 
4816 		flags |= CIFS_HAS_CREDITS;
4817 	}
4818 
4819 	kref_get(&wdata->refcount);
4820 	rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, NULL,
4821 			     wdata, flags, &wdata->credits);
4822 
4823 	if (rc) {
4824 		trace_smb3_write_err(0 /* no xid */,
4825 				     io_parms->persistent_fid,
4826 				     io_parms->tcon->tid,
4827 				     io_parms->tcon->ses->Suid,
4828 				     io_parms->offset,
4829 				     io_parms->length,
4830 				     rc);
4831 		kref_put(&wdata->refcount, release);
4832 		cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
4833 	}
4834 
4835 async_writev_out:
4836 	cifs_small_buf_release(req);
4837 	return rc;
4838 }
4839 
4840 /*
4841  * SMB2_write function gets iov pointer to kvec array with n_vec as a length.
4842  * The length field from io_parms must be at least 1 and indicates a number of
4843  * elements with data to write that begins with position 1 in iov array. All
4844  * data length is specified by count.
4845  */
4846 int
4847 SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
4848 	   unsigned int *nbytes, struct kvec *iov, int n_vec)
4849 {
4850 	struct smb_rqst rqst;
4851 	int rc = 0;
4852 	struct smb2_write_req *req = NULL;
4853 	struct smb2_write_rsp *rsp = NULL;
4854 	int resp_buftype;
4855 	struct kvec rsp_iov;
4856 	int flags = 0;
4857 	unsigned int total_len;
4858 	struct TCP_Server_Info *server;
4859 
4860 	*nbytes = 0;
4861 
4862 	if (n_vec < 1)
4863 		return rc;
4864 
4865 	if (!io_parms->server)
4866 		io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
4867 	server = io_parms->server;
4868 	if (server == NULL)
4869 		return -ECONNABORTED;
4870 
4871 	rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, server,
4872 				 (void **) &req, &total_len);
4873 	if (rc)
4874 		return rc;
4875 
4876 	if (smb3_encryption_required(io_parms->tcon))
4877 		flags |= CIFS_TRANSFORM_REQ;
4878 
4879 	req->hdr.Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
4880 
4881 	req->PersistentFileId = io_parms->persistent_fid;
4882 	req->VolatileFileId = io_parms->volatile_fid;
4883 	req->WriteChannelInfoOffset = 0;
4884 	req->WriteChannelInfoLength = 0;
4885 	req->Channel = 0;
4886 	req->Length = cpu_to_le32(io_parms->length);
4887 	req->Offset = cpu_to_le64(io_parms->offset);
4888 	req->DataOffset = cpu_to_le16(
4889 				offsetof(struct smb2_write_req, Buffer));
4890 	req->RemainingBytes = 0;
4891 
4892 	trace_smb3_write_enter(xid, io_parms->persistent_fid,
4893 		io_parms->tcon->tid, io_parms->tcon->ses->Suid,
4894 		io_parms->offset, io_parms->length);
4895 
4896 	iov[0].iov_base = (char *)req;
4897 	/* 1 for Buffer */
4898 	iov[0].iov_len = total_len - 1;
4899 
4900 	memset(&rqst, 0, sizeof(struct smb_rqst));
4901 	rqst.rq_iov = iov;
4902 	rqst.rq_nvec = n_vec + 1;
4903 
4904 	rc = cifs_send_recv(xid, io_parms->tcon->ses, server,
4905 			    &rqst,
4906 			    &resp_buftype, flags, &rsp_iov);
4907 	rsp = (struct smb2_write_rsp *)rsp_iov.iov_base;
4908 
4909 	if (rc) {
4910 		trace_smb3_write_err(xid,
4911 				     req->PersistentFileId,
4912 				     io_parms->tcon->tid,
4913 				     io_parms->tcon->ses->Suid,
4914 				     io_parms->offset, io_parms->length, rc);
4915 		cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
4916 		cifs_dbg(VFS, "Send error in write = %d\n", rc);
4917 	} else {
4918 		*nbytes = le32_to_cpu(rsp->DataLength);
4919 		trace_smb3_write_done(xid,
4920 				      req->PersistentFileId,
4921 				      io_parms->tcon->tid,
4922 				      io_parms->tcon->ses->Suid,
4923 				      io_parms->offset, *nbytes);
4924 	}
4925 
4926 	cifs_small_buf_release(req);
4927 	free_rsp_buf(resp_buftype, rsp);
4928 	return rc;
4929 }
4930 
4931 int posix_info_sid_size(const void *beg, const void *end)
4932 {
4933 	size_t subauth;
4934 	int total;
4935 
4936 	if (beg + 1 > end)
4937 		return -1;
4938 
4939 	subauth = *(u8 *)(beg+1);
4940 	if (subauth < 1 || subauth > 15)
4941 		return -1;
4942 
4943 	total = 1 + 1 + 6 + 4*subauth;
4944 	if (beg + total > end)
4945 		return -1;
4946 
4947 	return total;
4948 }
4949 
4950 int posix_info_parse(const void *beg, const void *end,
4951 		     struct smb2_posix_info_parsed *out)
4952 
4953 {
4954 	int total_len = 0;
4955 	int owner_len, group_len;
4956 	int name_len;
4957 	const void *owner_sid;
4958 	const void *group_sid;
4959 	const void *name;
4960 
4961 	/* if no end bound given, assume payload to be correct */
4962 	if (!end) {
4963 		const struct smb2_posix_info *p = beg;
4964 
4965 		end = beg + le32_to_cpu(p->NextEntryOffset);
4966 		/* last element will have a 0 offset, pick a sensible bound */
4967 		if (end == beg)
4968 			end += 0xFFFF;
4969 	}
4970 
4971 	/* check base buf */
4972 	if (beg + sizeof(struct smb2_posix_info) > end)
4973 		return -1;
4974 	total_len = sizeof(struct smb2_posix_info);
4975 
4976 	/* check owner sid */
4977 	owner_sid = beg + total_len;
4978 	owner_len = posix_info_sid_size(owner_sid, end);
4979 	if (owner_len < 0)
4980 		return -1;
4981 	total_len += owner_len;
4982 
4983 	/* check group sid */
4984 	group_sid = beg + total_len;
4985 	group_len = posix_info_sid_size(group_sid, end);
4986 	if (group_len < 0)
4987 		return -1;
4988 	total_len += group_len;
4989 
4990 	/* check name len */
4991 	if (beg + total_len + 4 > end)
4992 		return -1;
4993 	name_len = le32_to_cpu(*(__le32 *)(beg + total_len));
4994 	if (name_len < 1 || name_len > 0xFFFF)
4995 		return -1;
4996 	total_len += 4;
4997 
4998 	/* check name */
4999 	name = beg + total_len;
5000 	if (name + name_len > end)
5001 		return -1;
5002 	total_len += name_len;
5003 
5004 	if (out) {
5005 		out->base = beg;
5006 		out->size = total_len;
5007 		out->name_len = name_len;
5008 		out->name = name;
5009 		memcpy(&out->owner, owner_sid, owner_len);
5010 		memcpy(&out->group, group_sid, group_len);
5011 	}
5012 	return total_len;
5013 }
5014 
5015 static int posix_info_extra_size(const void *beg, const void *end)
5016 {
5017 	int len = posix_info_parse(beg, end, NULL);
5018 
5019 	if (len < 0)
5020 		return -1;
5021 	return len - sizeof(struct smb2_posix_info);
5022 }
5023 
5024 static unsigned int
5025 num_entries(int infotype, char *bufstart, char *end_of_buf, char **lastentry,
5026 	    size_t size)
5027 {
5028 	int len;
5029 	unsigned int entrycount = 0;
5030 	unsigned int next_offset = 0;
5031 	char *entryptr;
5032 	FILE_DIRECTORY_INFO *dir_info;
5033 
5034 	if (bufstart == NULL)
5035 		return 0;
5036 
5037 	entryptr = bufstart;
5038 
5039 	while (1) {
5040 		if (entryptr + next_offset < entryptr ||
5041 		    entryptr + next_offset > end_of_buf ||
5042 		    entryptr + next_offset + size > end_of_buf) {
5043 			cifs_dbg(VFS, "malformed search entry would overflow\n");
5044 			break;
5045 		}
5046 
5047 		entryptr = entryptr + next_offset;
5048 		dir_info = (FILE_DIRECTORY_INFO *)entryptr;
5049 
5050 		if (infotype == SMB_FIND_FILE_POSIX_INFO)
5051 			len = posix_info_extra_size(entryptr, end_of_buf);
5052 		else
5053 			len = le32_to_cpu(dir_info->FileNameLength);
5054 
5055 		if (len < 0 ||
5056 		    entryptr + len < entryptr ||
5057 		    entryptr + len > end_of_buf ||
5058 		    entryptr + len + size > end_of_buf) {
5059 			cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
5060 				 end_of_buf);
5061 			break;
5062 		}
5063 
5064 		*lastentry = entryptr;
5065 		entrycount++;
5066 
5067 		next_offset = le32_to_cpu(dir_info->NextEntryOffset);
5068 		if (!next_offset)
5069 			break;
5070 	}
5071 
5072 	return entrycount;
5073 }
5074 
5075 /*
5076  * Readdir/FindFirst
5077  */
5078 int SMB2_query_directory_init(const unsigned int xid,
5079 			      struct cifs_tcon *tcon,
5080 			      struct TCP_Server_Info *server,
5081 			      struct smb_rqst *rqst,
5082 			      u64 persistent_fid, u64 volatile_fid,
5083 			      int index, int info_level)
5084 {
5085 	struct smb2_query_directory_req *req;
5086 	unsigned char *bufptr;
5087 	__le16 asteriks = cpu_to_le16('*');
5088 	unsigned int output_size = CIFSMaxBufSize -
5089 		MAX_SMB2_CREATE_RESPONSE_SIZE -
5090 		MAX_SMB2_CLOSE_RESPONSE_SIZE;
5091 	unsigned int total_len;
5092 	struct kvec *iov = rqst->rq_iov;
5093 	int len, rc;
5094 
5095 	rc = smb2_plain_req_init(SMB2_QUERY_DIRECTORY, tcon, server,
5096 				 (void **) &req, &total_len);
5097 	if (rc)
5098 		return rc;
5099 
5100 	switch (info_level) {
5101 	case SMB_FIND_FILE_DIRECTORY_INFO:
5102 		req->FileInformationClass = FILE_DIRECTORY_INFORMATION;
5103 		break;
5104 	case SMB_FIND_FILE_ID_FULL_DIR_INFO:
5105 		req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION;
5106 		break;
5107 	case SMB_FIND_FILE_POSIX_INFO:
5108 		req->FileInformationClass = SMB_FIND_FILE_POSIX_INFO;
5109 		break;
5110 	case SMB_FIND_FILE_FULL_DIRECTORY_INFO:
5111 		req->FileInformationClass = FILE_FULL_DIRECTORY_INFORMATION;
5112 		break;
5113 	default:
5114 		cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
5115 			info_level);
5116 		return -EINVAL;
5117 	}
5118 
5119 	req->FileIndex = cpu_to_le32(index);
5120 	req->PersistentFileId = persistent_fid;
5121 	req->VolatileFileId = volatile_fid;
5122 
5123 	len = 0x2;
5124 	bufptr = req->Buffer;
5125 	memcpy(bufptr, &asteriks, len);
5126 
5127 	req->FileNameOffset =
5128 		cpu_to_le16(sizeof(struct smb2_query_directory_req));
5129 	req->FileNameLength = cpu_to_le16(len);
5130 	/*
5131 	 * BB could be 30 bytes or so longer if we used SMB2 specific
5132 	 * buffer lengths, but this is safe and close enough.
5133 	 */
5134 	output_size = min_t(unsigned int, output_size, server->maxBuf);
5135 	output_size = min_t(unsigned int, output_size, 2 << 15);
5136 	req->OutputBufferLength = cpu_to_le32(output_size);
5137 
5138 	iov[0].iov_base = (char *)req;
5139 	/* 1 for Buffer */
5140 	iov[0].iov_len = total_len - 1;
5141 
5142 	iov[1].iov_base = (char *)(req->Buffer);
5143 	iov[1].iov_len = len;
5144 
5145 	trace_smb3_query_dir_enter(xid, persistent_fid, tcon->tid,
5146 			tcon->ses->Suid, index, output_size);
5147 
5148 	return 0;
5149 }
5150 
5151 void SMB2_query_directory_free(struct smb_rqst *rqst)
5152 {
5153 	if (rqst && rqst->rq_iov) {
5154 		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
5155 	}
5156 }
5157 
5158 int
5159 smb2_parse_query_directory(struct cifs_tcon *tcon,
5160 			   struct kvec *rsp_iov,
5161 			   int resp_buftype,
5162 			   struct cifs_search_info *srch_inf)
5163 {
5164 	struct smb2_query_directory_rsp *rsp;
5165 	size_t info_buf_size;
5166 	char *end_of_smb;
5167 	int rc;
5168 
5169 	rsp = (struct smb2_query_directory_rsp *)rsp_iov->iov_base;
5170 
5171 	switch (srch_inf->info_level) {
5172 	case SMB_FIND_FILE_DIRECTORY_INFO:
5173 		info_buf_size = sizeof(FILE_DIRECTORY_INFO);
5174 		break;
5175 	case SMB_FIND_FILE_ID_FULL_DIR_INFO:
5176 		info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO);
5177 		break;
5178 	case SMB_FIND_FILE_POSIX_INFO:
5179 		/* note that posix payload are variable size */
5180 		info_buf_size = sizeof(struct smb2_posix_info);
5181 		break;
5182 	case SMB_FIND_FILE_FULL_DIRECTORY_INFO:
5183 		info_buf_size = sizeof(FILE_FULL_DIRECTORY_INFO);
5184 		break;
5185 	default:
5186 		cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
5187 			 srch_inf->info_level);
5188 		return -EINVAL;
5189 	}
5190 
5191 	rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5192 			       le32_to_cpu(rsp->OutputBufferLength), rsp_iov,
5193 			       info_buf_size);
5194 	if (rc) {
5195 		cifs_tcon_dbg(VFS, "bad info payload");
5196 		return rc;
5197 	}
5198 
5199 	srch_inf->unicode = true;
5200 
5201 	if (srch_inf->ntwrk_buf_start) {
5202 		if (srch_inf->smallBuf)
5203 			cifs_small_buf_release(srch_inf->ntwrk_buf_start);
5204 		else
5205 			cifs_buf_release(srch_inf->ntwrk_buf_start);
5206 	}
5207 	srch_inf->ntwrk_buf_start = (char *)rsp;
5208 	srch_inf->srch_entries_start = srch_inf->last_entry =
5209 		(char *)rsp + le16_to_cpu(rsp->OutputBufferOffset);
5210 	end_of_smb = rsp_iov->iov_len + (char *)rsp;
5211 
5212 	srch_inf->entries_in_buffer = num_entries(
5213 		srch_inf->info_level,
5214 		srch_inf->srch_entries_start,
5215 		end_of_smb,
5216 		&srch_inf->last_entry,
5217 		info_buf_size);
5218 
5219 	srch_inf->index_of_last_entry += srch_inf->entries_in_buffer;
5220 	cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n",
5221 		 srch_inf->entries_in_buffer, srch_inf->index_of_last_entry,
5222 		 srch_inf->srch_entries_start, srch_inf->last_entry);
5223 	if (resp_buftype == CIFS_LARGE_BUFFER)
5224 		srch_inf->smallBuf = false;
5225 	else if (resp_buftype == CIFS_SMALL_BUFFER)
5226 		srch_inf->smallBuf = true;
5227 	else
5228 		cifs_tcon_dbg(VFS, "Invalid search buffer type\n");
5229 
5230 	return 0;
5231 }
5232 
5233 int
5234 SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon,
5235 		     u64 persistent_fid, u64 volatile_fid, int index,
5236 		     struct cifs_search_info *srch_inf)
5237 {
5238 	struct smb_rqst rqst;
5239 	struct kvec iov[SMB2_QUERY_DIRECTORY_IOV_SIZE];
5240 	struct smb2_query_directory_rsp *rsp = NULL;
5241 	int resp_buftype = CIFS_NO_BUFFER;
5242 	struct kvec rsp_iov;
5243 	int rc = 0;
5244 	struct cifs_ses *ses = tcon->ses;
5245 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
5246 	int flags = 0;
5247 
5248 	if (!ses || !(ses->server))
5249 		return -EIO;
5250 
5251 	if (smb3_encryption_required(tcon))
5252 		flags |= CIFS_TRANSFORM_REQ;
5253 
5254 	memset(&rqst, 0, sizeof(struct smb_rqst));
5255 	memset(&iov, 0, sizeof(iov));
5256 	rqst.rq_iov = iov;
5257 	rqst.rq_nvec = SMB2_QUERY_DIRECTORY_IOV_SIZE;
5258 
5259 	rc = SMB2_query_directory_init(xid, tcon, server,
5260 				       &rqst, persistent_fid,
5261 				       volatile_fid, index,
5262 				       srch_inf->info_level);
5263 	if (rc)
5264 		goto qdir_exit;
5265 
5266 	rc = cifs_send_recv(xid, ses, server,
5267 			    &rqst, &resp_buftype, flags, &rsp_iov);
5268 	rsp = (struct smb2_query_directory_rsp *)rsp_iov.iov_base;
5269 
5270 	if (rc) {
5271 		if (rc == -ENODATA &&
5272 		    rsp->hdr.Status == STATUS_NO_MORE_FILES) {
5273 			trace_smb3_query_dir_done(xid, persistent_fid,
5274 				tcon->tid, tcon->ses->Suid, index, 0);
5275 			srch_inf->endOfSearch = true;
5276 			rc = 0;
5277 		} else {
5278 			trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
5279 				tcon->ses->Suid, index, 0, rc);
5280 			cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE);
5281 		}
5282 		goto qdir_exit;
5283 	}
5284 
5285 	rc = smb2_parse_query_directory(tcon, &rsp_iov,	resp_buftype,
5286 					srch_inf);
5287 	if (rc) {
5288 		trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
5289 			tcon->ses->Suid, index, 0, rc);
5290 		goto qdir_exit;
5291 	}
5292 	resp_buftype = CIFS_NO_BUFFER;
5293 
5294 	trace_smb3_query_dir_done(xid, persistent_fid, tcon->tid,
5295 			tcon->ses->Suid, index, srch_inf->entries_in_buffer);
5296 
5297 qdir_exit:
5298 	SMB2_query_directory_free(&rqst);
5299 	free_rsp_buf(resp_buftype, rsp);
5300 	return rc;
5301 }
5302 
5303 int
5304 SMB2_set_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
5305 		   struct smb_rqst *rqst,
5306 		   u64 persistent_fid, u64 volatile_fid, u32 pid,
5307 		   u8 info_class, u8 info_type, u32 additional_info,
5308 		   void **data, unsigned int *size)
5309 {
5310 	struct smb2_set_info_req *req;
5311 	struct kvec *iov = rqst->rq_iov;
5312 	unsigned int i, total_len;
5313 	int rc;
5314 
5315 	rc = smb2_plain_req_init(SMB2_SET_INFO, tcon, server,
5316 				 (void **) &req, &total_len);
5317 	if (rc)
5318 		return rc;
5319 
5320 	req->hdr.Id.SyncId.ProcessId = cpu_to_le32(pid);
5321 	req->InfoType = info_type;
5322 	req->FileInfoClass = info_class;
5323 	req->PersistentFileId = persistent_fid;
5324 	req->VolatileFileId = volatile_fid;
5325 	req->AdditionalInformation = cpu_to_le32(additional_info);
5326 
5327 	req->BufferOffset = cpu_to_le16(sizeof(struct smb2_set_info_req));
5328 	req->BufferLength = cpu_to_le32(*size);
5329 
5330 	memcpy(req->Buffer, *data, *size);
5331 	total_len += *size;
5332 
5333 	iov[0].iov_base = (char *)req;
5334 	/* 1 for Buffer */
5335 	iov[0].iov_len = total_len - 1;
5336 
5337 	for (i = 1; i < rqst->rq_nvec; i++) {
5338 		le32_add_cpu(&req->BufferLength, size[i]);
5339 		iov[i].iov_base = (char *)data[i];
5340 		iov[i].iov_len = size[i];
5341 	}
5342 
5343 	return 0;
5344 }
5345 
5346 void
5347 SMB2_set_info_free(struct smb_rqst *rqst)
5348 {
5349 	if (rqst && rqst->rq_iov)
5350 		cifs_buf_release(rqst->rq_iov[0].iov_base); /* request */
5351 }
5352 
5353 static int
5354 send_set_info(const unsigned int xid, struct cifs_tcon *tcon,
5355 	       u64 persistent_fid, u64 volatile_fid, u32 pid, u8 info_class,
5356 	       u8 info_type, u32 additional_info, unsigned int num,
5357 		void **data, unsigned int *size)
5358 {
5359 	struct smb_rqst rqst;
5360 	struct smb2_set_info_rsp *rsp = NULL;
5361 	struct kvec *iov;
5362 	struct kvec rsp_iov;
5363 	int rc = 0;
5364 	int resp_buftype;
5365 	struct cifs_ses *ses = tcon->ses;
5366 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
5367 	int flags = 0;
5368 
5369 	if (!ses || !server)
5370 		return -EIO;
5371 
5372 	if (!num)
5373 		return -EINVAL;
5374 
5375 	if (smb3_encryption_required(tcon))
5376 		flags |= CIFS_TRANSFORM_REQ;
5377 
5378 	iov = kmalloc_array(num, sizeof(struct kvec), GFP_KERNEL);
5379 	if (!iov)
5380 		return -ENOMEM;
5381 
5382 	memset(&rqst, 0, sizeof(struct smb_rqst));
5383 	rqst.rq_iov = iov;
5384 	rqst.rq_nvec = num;
5385 
5386 	rc = SMB2_set_info_init(tcon, server,
5387 				&rqst, persistent_fid, volatile_fid, pid,
5388 				info_class, info_type, additional_info,
5389 				data, size);
5390 	if (rc) {
5391 		kfree(iov);
5392 		return rc;
5393 	}
5394 
5395 
5396 	rc = cifs_send_recv(xid, ses, server,
5397 			    &rqst, &resp_buftype, flags,
5398 			    &rsp_iov);
5399 	SMB2_set_info_free(&rqst);
5400 	rsp = (struct smb2_set_info_rsp *)rsp_iov.iov_base;
5401 
5402 	if (rc != 0) {
5403 		cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE);
5404 		trace_smb3_set_info_err(xid, persistent_fid, tcon->tid,
5405 				ses->Suid, info_class, (__u32)info_type, rc);
5406 	}
5407 
5408 	free_rsp_buf(resp_buftype, rsp);
5409 	kfree(iov);
5410 	return rc;
5411 }
5412 
5413 int
5414 SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
5415 	     u64 volatile_fid, u32 pid, loff_t new_eof)
5416 {
5417 	struct smb2_file_eof_info info;
5418 	void *data;
5419 	unsigned int size;
5420 
5421 	info.EndOfFile = cpu_to_le64(new_eof);
5422 
5423 	data = &info;
5424 	size = sizeof(struct smb2_file_eof_info);
5425 
5426 	trace_smb3_set_eof(xid, persistent_fid, tcon->tid, tcon->ses->Suid, new_eof);
5427 
5428 	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5429 			pid, FILE_END_OF_FILE_INFORMATION, SMB2_O_INFO_FILE,
5430 			0, 1, &data, &size);
5431 }
5432 
5433 int
5434 SMB2_set_acl(const unsigned int xid, struct cifs_tcon *tcon,
5435 		u64 persistent_fid, u64 volatile_fid,
5436 		struct cifs_ntsd *pnntsd, int pacllen, int aclflag)
5437 {
5438 	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5439 			current->tgid, 0, SMB2_O_INFO_SECURITY, aclflag,
5440 			1, (void **)&pnntsd, &pacllen);
5441 }
5442 
5443 int
5444 SMB2_set_ea(const unsigned int xid, struct cifs_tcon *tcon,
5445 	    u64 persistent_fid, u64 volatile_fid,
5446 	    struct smb2_file_full_ea_info *buf, int len)
5447 {
5448 	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5449 		current->tgid, FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE,
5450 		0, 1, (void **)&buf, &len);
5451 }
5452 
5453 int
5454 SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon,
5455 		  const u64 persistent_fid, const u64 volatile_fid,
5456 		  __u8 oplock_level)
5457 {
5458 	struct smb_rqst rqst;
5459 	int rc;
5460 	struct smb2_oplock_break *req = NULL;
5461 	struct cifs_ses *ses = tcon->ses;
5462 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
5463 	int flags = CIFS_OBREAK_OP;
5464 	unsigned int total_len;
5465 	struct kvec iov[1];
5466 	struct kvec rsp_iov;
5467 	int resp_buf_type;
5468 
5469 	cifs_dbg(FYI, "SMB2_oplock_break\n");
5470 	rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
5471 				 (void **) &req, &total_len);
5472 	if (rc)
5473 		return rc;
5474 
5475 	if (smb3_encryption_required(tcon))
5476 		flags |= CIFS_TRANSFORM_REQ;
5477 
5478 	req->VolatileFid = volatile_fid;
5479 	req->PersistentFid = persistent_fid;
5480 	req->OplockLevel = oplock_level;
5481 	req->hdr.CreditRequest = cpu_to_le16(1);
5482 
5483 	flags |= CIFS_NO_RSP_BUF;
5484 
5485 	iov[0].iov_base = (char *)req;
5486 	iov[0].iov_len = total_len;
5487 
5488 	memset(&rqst, 0, sizeof(struct smb_rqst));
5489 	rqst.rq_iov = iov;
5490 	rqst.rq_nvec = 1;
5491 
5492 	rc = cifs_send_recv(xid, ses, server,
5493 			    &rqst, &resp_buf_type, flags, &rsp_iov);
5494 	cifs_small_buf_release(req);
5495 
5496 	if (rc) {
5497 		cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
5498 		cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc);
5499 	}
5500 
5501 	return rc;
5502 }
5503 
5504 void
5505 smb2_copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf,
5506 			     struct kstatfs *kst)
5507 {
5508 	kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) *
5509 			  le32_to_cpu(pfs_inf->SectorsPerAllocationUnit);
5510 	kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits);
5511 	kst->f_bfree  = kst->f_bavail =
5512 			le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits);
5513 	return;
5514 }
5515 
5516 static void
5517 copy_posix_fs_info_to_kstatfs(FILE_SYSTEM_POSIX_INFO *response_data,
5518 			struct kstatfs *kst)
5519 {
5520 	kst->f_bsize = le32_to_cpu(response_data->BlockSize);
5521 	kst->f_blocks = le64_to_cpu(response_data->TotalBlocks);
5522 	kst->f_bfree =  le64_to_cpu(response_data->BlocksAvail);
5523 	if (response_data->UserBlocksAvail == cpu_to_le64(-1))
5524 		kst->f_bavail = kst->f_bfree;
5525 	else
5526 		kst->f_bavail = le64_to_cpu(response_data->UserBlocksAvail);
5527 	if (response_data->TotalFileNodes != cpu_to_le64(-1))
5528 		kst->f_files = le64_to_cpu(response_data->TotalFileNodes);
5529 	if (response_data->FreeFileNodes != cpu_to_le64(-1))
5530 		kst->f_ffree = le64_to_cpu(response_data->FreeFileNodes);
5531 
5532 	return;
5533 }
5534 
5535 static int
5536 build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon,
5537 		   struct TCP_Server_Info *server,
5538 		   int level, int outbuf_len, u64 persistent_fid,
5539 		   u64 volatile_fid)
5540 {
5541 	int rc;
5542 	struct smb2_query_info_req *req;
5543 	unsigned int total_len;
5544 
5545 	cifs_dbg(FYI, "Query FSInfo level %d\n", level);
5546 
5547 	if ((tcon->ses == NULL) || server == NULL)
5548 		return -EIO;
5549 
5550 	rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
5551 				 (void **) &req, &total_len);
5552 	if (rc)
5553 		return rc;
5554 
5555 	req->InfoType = SMB2_O_INFO_FILESYSTEM;
5556 	req->FileInfoClass = level;
5557 	req->PersistentFileId = persistent_fid;
5558 	req->VolatileFileId = volatile_fid;
5559 	/* 1 for pad */
5560 	req->InputBufferOffset =
5561 			cpu_to_le16(sizeof(struct smb2_query_info_req));
5562 	req->OutputBufferLength = cpu_to_le32(
5563 		outbuf_len + sizeof(struct smb2_query_info_rsp));
5564 
5565 	iov->iov_base = (char *)req;
5566 	iov->iov_len = total_len;
5567 	return 0;
5568 }
5569 
5570 static inline void free_qfs_info_req(struct kvec *iov)
5571 {
5572 	cifs_buf_release(iov->iov_base);
5573 }
5574 
5575 int
5576 SMB311_posix_qfs_info(const unsigned int xid, struct cifs_tcon *tcon,
5577 	      u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
5578 {
5579 	struct smb_rqst rqst;
5580 	struct smb2_query_info_rsp *rsp = NULL;
5581 	struct kvec iov;
5582 	struct kvec rsp_iov;
5583 	int rc = 0;
5584 	int resp_buftype;
5585 	struct cifs_ses *ses = tcon->ses;
5586 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
5587 	FILE_SYSTEM_POSIX_INFO *info = NULL;
5588 	int flags = 0;
5589 
5590 	rc = build_qfs_info_req(&iov, tcon, server,
5591 				FS_POSIX_INFORMATION,
5592 				sizeof(FILE_SYSTEM_POSIX_INFO),
5593 				persistent_fid, volatile_fid);
5594 	if (rc)
5595 		return rc;
5596 
5597 	if (smb3_encryption_required(tcon))
5598 		flags |= CIFS_TRANSFORM_REQ;
5599 
5600 	memset(&rqst, 0, sizeof(struct smb_rqst));
5601 	rqst.rq_iov = &iov;
5602 	rqst.rq_nvec = 1;
5603 
5604 	rc = cifs_send_recv(xid, ses, server,
5605 			    &rqst, &resp_buftype, flags, &rsp_iov);
5606 	free_qfs_info_req(&iov);
5607 	if (rc) {
5608 		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5609 		goto posix_qfsinf_exit;
5610 	}
5611 	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5612 
5613 	info = (FILE_SYSTEM_POSIX_INFO *)(
5614 		le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
5615 	rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5616 			       le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
5617 			       sizeof(FILE_SYSTEM_POSIX_INFO));
5618 	if (!rc)
5619 		copy_posix_fs_info_to_kstatfs(info, fsdata);
5620 
5621 posix_qfsinf_exit:
5622 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5623 	return rc;
5624 }
5625 
5626 int
5627 SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon,
5628 	      u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
5629 {
5630 	struct smb_rqst rqst;
5631 	struct smb2_query_info_rsp *rsp = NULL;
5632 	struct kvec iov;
5633 	struct kvec rsp_iov;
5634 	int rc = 0;
5635 	int resp_buftype;
5636 	struct cifs_ses *ses = tcon->ses;
5637 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
5638 	struct smb2_fs_full_size_info *info = NULL;
5639 	int flags = 0;
5640 
5641 	rc = build_qfs_info_req(&iov, tcon, server,
5642 				FS_FULL_SIZE_INFORMATION,
5643 				sizeof(struct smb2_fs_full_size_info),
5644 				persistent_fid, volatile_fid);
5645 	if (rc)
5646 		return rc;
5647 
5648 	if (smb3_encryption_required(tcon))
5649 		flags |= CIFS_TRANSFORM_REQ;
5650 
5651 	memset(&rqst, 0, sizeof(struct smb_rqst));
5652 	rqst.rq_iov = &iov;
5653 	rqst.rq_nvec = 1;
5654 
5655 	rc = cifs_send_recv(xid, ses, server,
5656 			    &rqst, &resp_buftype, flags, &rsp_iov);
5657 	free_qfs_info_req(&iov);
5658 	if (rc) {
5659 		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5660 		goto qfsinf_exit;
5661 	}
5662 	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5663 
5664 	info = (struct smb2_fs_full_size_info *)(
5665 		le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
5666 	rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5667 			       le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
5668 			       sizeof(struct smb2_fs_full_size_info));
5669 	if (!rc)
5670 		smb2_copy_fs_info_to_kstatfs(info, fsdata);
5671 
5672 qfsinf_exit:
5673 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5674 	return rc;
5675 }
5676 
5677 int
5678 SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon,
5679 	      u64 persistent_fid, u64 volatile_fid, int level)
5680 {
5681 	struct smb_rqst rqst;
5682 	struct smb2_query_info_rsp *rsp = NULL;
5683 	struct kvec iov;
5684 	struct kvec rsp_iov;
5685 	int rc = 0;
5686 	int resp_buftype, max_len, min_len;
5687 	struct cifs_ses *ses = tcon->ses;
5688 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
5689 	unsigned int rsp_len, offset;
5690 	int flags = 0;
5691 
5692 	if (level == FS_DEVICE_INFORMATION) {
5693 		max_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
5694 		min_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
5695 	} else if (level == FS_ATTRIBUTE_INFORMATION) {
5696 		max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO);
5697 		min_len = MIN_FS_ATTR_INFO_SIZE;
5698 	} else if (level == FS_SECTOR_SIZE_INFORMATION) {
5699 		max_len = sizeof(struct smb3_fs_ss_info);
5700 		min_len = sizeof(struct smb3_fs_ss_info);
5701 	} else if (level == FS_VOLUME_INFORMATION) {
5702 		max_len = sizeof(struct smb3_fs_vol_info) + MAX_VOL_LABEL_LEN;
5703 		min_len = sizeof(struct smb3_fs_vol_info);
5704 	} else {
5705 		cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level);
5706 		return -EINVAL;
5707 	}
5708 
5709 	rc = build_qfs_info_req(&iov, tcon, server,
5710 				level, max_len,
5711 				persistent_fid, volatile_fid);
5712 	if (rc)
5713 		return rc;
5714 
5715 	if (smb3_encryption_required(tcon))
5716 		flags |= CIFS_TRANSFORM_REQ;
5717 
5718 	memset(&rqst, 0, sizeof(struct smb_rqst));
5719 	rqst.rq_iov = &iov;
5720 	rqst.rq_nvec = 1;
5721 
5722 	rc = cifs_send_recv(xid, ses, server,
5723 			    &rqst, &resp_buftype, flags, &rsp_iov);
5724 	free_qfs_info_req(&iov);
5725 	if (rc) {
5726 		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5727 		goto qfsattr_exit;
5728 	}
5729 	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5730 
5731 	rsp_len = le32_to_cpu(rsp->OutputBufferLength);
5732 	offset = le16_to_cpu(rsp->OutputBufferOffset);
5733 	rc = smb2_validate_iov(offset, rsp_len, &rsp_iov, min_len);
5734 	if (rc)
5735 		goto qfsattr_exit;
5736 
5737 	if (level == FS_ATTRIBUTE_INFORMATION)
5738 		memcpy(&tcon->fsAttrInfo, offset
5739 			+ (char *)rsp, min_t(unsigned int,
5740 			rsp_len, max_len));
5741 	else if (level == FS_DEVICE_INFORMATION)
5742 		memcpy(&tcon->fsDevInfo, offset
5743 			+ (char *)rsp, sizeof(FILE_SYSTEM_DEVICE_INFO));
5744 	else if (level == FS_SECTOR_SIZE_INFORMATION) {
5745 		struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *)
5746 			(offset + (char *)rsp);
5747 		tcon->ss_flags = le32_to_cpu(ss_info->Flags);
5748 		tcon->perf_sector_size =
5749 			le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf);
5750 	} else if (level == FS_VOLUME_INFORMATION) {
5751 		struct smb3_fs_vol_info *vol_info = (struct smb3_fs_vol_info *)
5752 			(offset + (char *)rsp);
5753 		tcon->vol_serial_number = vol_info->VolumeSerialNumber;
5754 		tcon->vol_create_time = vol_info->VolumeCreationTime;
5755 	}
5756 
5757 qfsattr_exit:
5758 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5759 	return rc;
5760 }
5761 
5762 int
5763 smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon,
5764 	   const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
5765 	   const __u32 num_lock, struct smb2_lock_element *buf)
5766 {
5767 	struct smb_rqst rqst;
5768 	int rc = 0;
5769 	struct smb2_lock_req *req = NULL;
5770 	struct kvec iov[2];
5771 	struct kvec rsp_iov;
5772 	int resp_buf_type;
5773 	unsigned int count;
5774 	int flags = CIFS_NO_RSP_BUF;
5775 	unsigned int total_len;
5776 	struct TCP_Server_Info *server = cifs_pick_channel(tcon->ses);
5777 
5778 	cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock);
5779 
5780 	rc = smb2_plain_req_init(SMB2_LOCK, tcon, server,
5781 				 (void **) &req, &total_len);
5782 	if (rc)
5783 		return rc;
5784 
5785 	if (smb3_encryption_required(tcon))
5786 		flags |= CIFS_TRANSFORM_REQ;
5787 
5788 	req->hdr.Id.SyncId.ProcessId = cpu_to_le32(pid);
5789 	req->LockCount = cpu_to_le16(num_lock);
5790 
5791 	req->PersistentFileId = persist_fid;
5792 	req->VolatileFileId = volatile_fid;
5793 
5794 	count = num_lock * sizeof(struct smb2_lock_element);
5795 
5796 	iov[0].iov_base = (char *)req;
5797 	iov[0].iov_len = total_len - sizeof(struct smb2_lock_element);
5798 	iov[1].iov_base = (char *)buf;
5799 	iov[1].iov_len = count;
5800 
5801 	cifs_stats_inc(&tcon->stats.cifs_stats.num_locks);
5802 
5803 	memset(&rqst, 0, sizeof(struct smb_rqst));
5804 	rqst.rq_iov = iov;
5805 	rqst.rq_nvec = 2;
5806 
5807 	rc = cifs_send_recv(xid, tcon->ses, server,
5808 			    &rqst, &resp_buf_type, flags,
5809 			    &rsp_iov);
5810 	cifs_small_buf_release(req);
5811 	if (rc) {
5812 		cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc);
5813 		cifs_stats_fail_inc(tcon, SMB2_LOCK_HE);
5814 		trace_smb3_lock_err(xid, persist_fid, tcon->tid,
5815 				    tcon->ses->Suid, rc);
5816 	}
5817 
5818 	return rc;
5819 }
5820 
5821 int
5822 SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon,
5823 	  const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
5824 	  const __u64 length, const __u64 offset, const __u32 lock_flags,
5825 	  const bool wait)
5826 {
5827 	struct smb2_lock_element lock;
5828 
5829 	lock.Offset = cpu_to_le64(offset);
5830 	lock.Length = cpu_to_le64(length);
5831 	lock.Flags = cpu_to_le32(lock_flags);
5832 	if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK)
5833 		lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY);
5834 
5835 	return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock);
5836 }
5837 
5838 int
5839 SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon,
5840 		 __u8 *lease_key, const __le32 lease_state)
5841 {
5842 	struct smb_rqst rqst;
5843 	int rc;
5844 	struct smb2_lease_ack *req = NULL;
5845 	struct cifs_ses *ses = tcon->ses;
5846 	int flags = CIFS_OBREAK_OP;
5847 	unsigned int total_len;
5848 	struct kvec iov[1];
5849 	struct kvec rsp_iov;
5850 	int resp_buf_type;
5851 	__u64 *please_key_high;
5852 	__u64 *please_key_low;
5853 	struct TCP_Server_Info *server = cifs_pick_channel(tcon->ses);
5854 
5855 	cifs_dbg(FYI, "SMB2_lease_break\n");
5856 	rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
5857 				 (void **) &req, &total_len);
5858 	if (rc)
5859 		return rc;
5860 
5861 	if (smb3_encryption_required(tcon))
5862 		flags |= CIFS_TRANSFORM_REQ;
5863 
5864 	req->hdr.CreditRequest = cpu_to_le16(1);
5865 	req->StructureSize = cpu_to_le16(36);
5866 	total_len += 12;
5867 
5868 	memcpy(req->LeaseKey, lease_key, 16);
5869 	req->LeaseState = lease_state;
5870 
5871 	flags |= CIFS_NO_RSP_BUF;
5872 
5873 	iov[0].iov_base = (char *)req;
5874 	iov[0].iov_len = total_len;
5875 
5876 	memset(&rqst, 0, sizeof(struct smb_rqst));
5877 	rqst.rq_iov = iov;
5878 	rqst.rq_nvec = 1;
5879 
5880 	rc = cifs_send_recv(xid, ses, server,
5881 			    &rqst, &resp_buf_type, flags, &rsp_iov);
5882 	cifs_small_buf_release(req);
5883 
5884 	please_key_low = (__u64 *)lease_key;
5885 	please_key_high = (__u64 *)(lease_key+8);
5886 	if (rc) {
5887 		cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
5888 		trace_smb3_lease_err(le32_to_cpu(lease_state), tcon->tid,
5889 			ses->Suid, *please_key_low, *please_key_high, rc);
5890 		cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc);
5891 	} else
5892 		trace_smb3_lease_done(le32_to_cpu(lease_state), tcon->tid,
5893 			ses->Suid, *please_key_low, *please_key_high);
5894 
5895 	return rc;
5896 }
5897