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