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