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