smb2pdu.c 158 KB
Newer Older
1
// SPDX-License-Identifier: LGPL-2.1
2 3
/*
 *
4
 *   Copyright (C) International Business Machines  Corp., 2009, 2013
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 *                 Etersoft, 2012
 *   Author(s): Steve French (sfrench@us.ibm.com)
 *              Pavel Shilovsky (pshilovsky@samba.org) 2012
 *
 *   Contains the routines for constructing the SMB2 PDUs themselves
 *
 */

 /* SMB2 PDU handling routines here - except for leftovers (eg session setup) */
 /* Note that there are handle based routines which must be		      */
 /* treated slightly differently for reconnection purposes since we never     */
 /* want to reuse a stale file handle and only the caller knows the file info */

#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/vfs.h>
21
#include <linux/task_io_accounting_ops.h>
22
#include <linux/uaccess.h>
23
#include <linux/uuid.h>
24
#include <linux/pagemap.h>
25 26 27 28 29 30 31 32 33
#include <linux/xattr.h>
#include "cifsglob.h"
#include "cifsacl.h"
#include "cifsproto.h"
#include "smb2proto.h"
#include "cifs_unicode.h"
#include "cifs_debug.h"
#include "ntlmssp.h"
#include "smb2status.h"
34
#include "smb2glob.h"
35
#include "cifspdu.h"
36
#include "cifs_spnego.h"
37
#include "smbdirect.h"
38
#include "trace.h"
39 40 41
#ifdef CONFIG_CIFS_DFS_UPCALL
#include "dfs_cache.h"
#endif
42
#include "cached_dir.h"
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

/*
 *  The following table defines the expected "StructureSize" of SMB2 requests
 *  in order by SMB2 command.  This is similar to "wct" in SMB/CIFS requests.
 *
 *  Note that commands are defined in smb2pdu.h in le16 but the array below is
 *  indexed by command in host byte order.
 */
static const int smb2_req_struct_sizes[NUMBER_OF_SMB2_COMMANDS] = {
	/* SMB2_NEGOTIATE */ 36,
	/* SMB2_SESSION_SETUP */ 25,
	/* SMB2_LOGOFF */ 4,
	/* SMB2_TREE_CONNECT */	9,
	/* SMB2_TREE_DISCONNECT */ 4,
	/* SMB2_CREATE */ 57,
	/* SMB2_CLOSE */ 24,
	/* SMB2_FLUSH */ 24,
	/* SMB2_READ */	49,
	/* SMB2_WRITE */ 49,
	/* SMB2_LOCK */	48,
	/* SMB2_IOCTL */ 57,
	/* SMB2_CANCEL */ 4,
	/* SMB2_ECHO */ 4,
	/* SMB2_QUERY_DIRECTORY */ 33,
	/* SMB2_CHANGE_NOTIFY */ 32,
	/* SMB2_QUERY_INFO */ 41,
	/* SMB2_SET_INFO */ 33,
	/* SMB2_OPLOCK_BREAK */ 24 /* BB this is 36 for LEASE_BREAK variant */
};

73
int smb3_encryption_required(const struct cifs_tcon *tcon)
74
{
75
	if (!tcon || !tcon->ses)
76
		return 0;
77 78 79
	if ((tcon->ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) ||
	    (tcon->share_flags & SHI1005_FLAGS_ENCRYPT_DATA))
		return 1;
80 81 82
	if (tcon->seal &&
	    (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
		return 1;
83 84
	return 0;
}
85 86

static void
87
smb2_hdr_assemble(struct smb2_hdr *shdr, __le16 smb2_cmd,
88 89
		  const struct cifs_tcon *tcon,
		  struct TCP_Server_Info *server)
90
{
91
	struct smb3_hdr_req *smb3_hdr;
92

93 94 95
	shdr->ProtocolId = SMB2_PROTO_NUMBER;
	shdr->StructureSize = cpu_to_le16(64);
	shdr->Command = smb2_cmd;
96

97
	if (server) {
98 99 100 101 102 103 104 105 106 107 108 109 110 111
		/* After reconnect SMB3 must set ChannelSequence on subsequent reqs */
		if (server->dialect >= SMB30_PROT_ID) {
			smb3_hdr = (struct smb3_hdr_req *)shdr;
			/*
			 * if primary channel is not set yet, use default
			 * channel for chan sequence num
			 */
			if (SERVER_IS_CHAN(server))
				smb3_hdr->ChannelSequence =
					cpu_to_le16(server->primary_server->channel_sequence_num);
			else
				smb3_hdr->ChannelSequence =
					cpu_to_le16(server->channel_sequence_num);
		}
112
		spin_lock(&server->req_lock);
113
		/* Request up to 10 credits but don't go over the limit. */
114
		if (server->credits >= server->max_credits)
115
			shdr->CreditRequest = cpu_to_le16(0);
116
		else
117
			shdr->CreditRequest = cpu_to_le16(
118
				min_t(int, server->max_credits -
119
						server->credits, 10));
120 121
		spin_unlock(&server->req_lock);
	} else {
122
		shdr->CreditRequest = cpu_to_le16(2);
123
	}
124
	shdr->Id.SyncId.ProcessId = cpu_to_le32((__u16)current->tgid);
125 126 127 128

	if (!tcon)
		goto out;

129 130
	/* GLOBAL_CAP_LARGE_MTU will only be set if dialect > SMB2.02 */
	/* See sections 2.2.4 and 3.2.4.1.5 of MS-SMB2 */
131
	if (server && (server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
132
		shdr->CreditCharge = cpu_to_le16(1);
133 134
	/* else CreditCharge MBZ */

135
	shdr->Id.SyncId.TreeId = cpu_to_le32(tcon->tid);
136 137
	/* Uid is not converted */
	if (tcon->ses)
138
		shdr->SessionId = cpu_to_le64(tcon->ses->Suid);
139 140 141 142 143 144 145 146 147 148 149 150

	/*
	 * If we would set SMB2_FLAGS_DFS_OPERATIONS on open we also would have
	 * to pass the path on the Open SMB prefixed by \\server\share.
	 * Not sure when we would need to do the augmented path (if ever) and
	 * setting this flag breaks the SMB2 open operation since it is
	 * illegal to send an empty path name (without \\server\share prefix)
	 * when the DFS flag is set in the SMB open header. We could
	 * consider setting the flag on all operations other than open
	 * but it is safer to net set it for now.
	 */
/*	if (tcon->share_flags & SHI1005_FLAGS_DFS)
151
		shdr->Flags |= SMB2_FLAGS_DFS_OPERATIONS; */
152

153
	if (server && server->sign && !smb3_encryption_required(tcon))
154
		shdr->Flags |= SMB2_FLAGS_SIGNED;
155 156 157 158 159
out:
	return;
}

static int
160 161
smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon,
	       struct TCP_Server_Info *server)
162
{
163
	int rc = 0;
164
	struct nls_table *nls_codepage = NULL;
165 166 167 168 169 170 171 172
	struct cifs_ses *ses;

	/*
	 * SMB2s NegProt, SessSetup, Logoff do not have tcon yet so
	 * check for tcp and smb session status done differently
	 * for those three - in the calling routine.
	 */
	if (tcon == NULL)
173
		return 0;
174

175 176 177 178 179
	/*
	 * Need to also skip SMB2_IOCTL because it is used for checking nested dfs links in
	 * cifs_tree_connect().
	 */
	if (smb2_command == SMB2_TREE_CONNECT || smb2_command == SMB2_IOCTL)
180
		return 0;
181

182
	spin_lock(&tcon->tc_lock);
183
	if (tcon->status == TID_EXITING) {
184
		/*
185
		 * only tree disconnect allowed when disconnecting ...
186
		 */
187
		if (smb2_command != SMB2_TREE_DISCONNECT) {
188
			spin_unlock(&tcon->tc_lock);
189 190
			cifs_dbg(FYI, "can not send cmd %d while umounting\n",
				 smb2_command);
191 192 193
			return -ENODEV;
		}
	}
194
	spin_unlock(&tcon->tc_lock);
195 196 197 198 199 200 201 202 203 204 205

	ses = tcon->ses;
	if (!ses)
		return -EIO;
	spin_lock(&ses->ses_lock);
	if (ses->ses_status == SES_EXITING) {
		spin_unlock(&ses->ses_lock);
		return -EIO;
	}
	spin_unlock(&ses->ses_lock);
	if (!ses->server || !server)
206 207
		return -EIO;

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
	spin_lock(&server->srv_lock);
	if (server->tcpStatus == CifsNeedReconnect) {
		/*
		 * Return to caller for TREE_DISCONNECT and LOGOFF and CLOSE
		 * here since they are implicitly done when session drops.
		 */
		switch (smb2_command) {
		/*
		 * BB Should we keep oplock break and add flush to exceptions?
		 */
		case SMB2_TREE_DISCONNECT:
		case SMB2_CANCEL:
		case SMB2_CLOSE:
		case SMB2_OPLOCK_BREAK:
			spin_unlock(&server->srv_lock);
			return -EAGAIN;
		}
	}
	spin_unlock(&server->srv_lock);

228
again:
229
	rc = cifs_wait_for_server_reconnect(server, tcon->retry);
230 231
	if (rc)
		return rc;
232

233 234 235
	spin_lock(&ses->chan_lock);
	if (!cifs_chan_needs_reconnect(ses, server) && !tcon->need_reconnect) {
		spin_unlock(&ses->chan_lock);
236
		return 0;
237
	}
238
	spin_unlock(&ses->chan_lock);
239 240 241
	cifs_dbg(FYI, "sess reconnect mask: 0x%lx, tcon reconnect: %d",
		 tcon->ses->chans_need_reconnect,
		 tcon->need_reconnect);
242

243
	mutex_lock(&ses->session_mutex);
244 245 246 247 248
	/*
	 * Recheck after acquire mutex. If another thread is negotiating
	 * and the server never sends an answer the socket will be closed
	 * and tcpStatus set to reconnect.
	 */
249
	spin_lock(&server->srv_lock);
250
	if (server->tcpStatus == CifsNeedReconnect) {
251
		spin_unlock(&server->srv_lock);
252 253 254 255 256
		mutex_unlock(&ses->session_mutex);

		if (tcon->retry)
			goto again;

257 258 259
		rc = -EHOSTDOWN;
		goto out;
	}
260
	spin_unlock(&server->srv_lock);
261

262
	nls_codepage = ses->local_nls;
263

264 265 266 267
	/*
	 * need to prevent multiple threads trying to simultaneously
	 * reconnect the same SMB session
	 */
268
	spin_lock(&ses->ses_lock);
269
	spin_lock(&ses->chan_lock);
270 271
	if (!cifs_chan_needs_reconnect(ses, server) &&
	    ses->ses_status == SES_GOOD) {
272
		spin_unlock(&ses->chan_lock);
273
		spin_unlock(&ses->ses_lock);
274
		/* this means that we only need to tree connect */
275 276 277
		if (tcon->need_reconnect)
			goto skip_sess_setup;

278
		mutex_unlock(&ses->session_mutex);
279 280 281
		goto out;
	}
	spin_unlock(&ses->chan_lock);
282
	spin_unlock(&ses->ses_lock);
283

284
	rc = cifs_negotiate_protocol(0, ses, server);
285
	if (!rc) {
286
		rc = cifs_setup_session(0, ses, server, nls_codepage);
287
		if ((rc == -EACCES) && !tcon->retry) {
288
			mutex_unlock(&ses->session_mutex);
289
			rc = -EHOSTDOWN;
290
			goto failed;
291 292 293
		} else if (rc) {
			mutex_unlock(&ses->session_mutex);
			goto out;
294
		}
295
	} else {
296
		mutex_unlock(&ses->session_mutex);
297 298 299
		goto out;
	}

300
skip_sess_setup:
301 302 303 304
	if (!tcon->need_reconnect) {
		mutex_unlock(&ses->session_mutex);
		goto out;
	}
305
	cifs_mark_open_files_invalid(tcon);
306 307
	if (tcon->use_persistent)
		tcon->need_reopen_files = true;
308

309
	rc = cifs_tree_connect(0, tcon, nls_codepage);
310
	mutex_unlock(&ses->session_mutex);
311

312
	cifs_dbg(FYI, "reconnect tcon rc = %d\n", rc);
313 314
	if (rc) {
		/* If sess reconnected but tcon didn't, something strange ... */
315
		cifs_dbg(VFS, "reconnect tcon failed rc = %d\n", rc);
316
		goto out;
317
	}
318 319

	if (smb2_command != SMB2_INTERNAL_CMD)
320
		mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
321

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
	atomic_inc(&tconInfoReconnectCount);
out:
	/*
	 * Check if handle based operation so we know whether we can continue
	 * or not without returning to caller to reset file handle.
	 */
	/*
	 * BB Is flush done by server on drop of tcp session? Should we special
	 * case it and skip above?
	 */
	switch (smb2_command) {
	case SMB2_FLUSH:
	case SMB2_READ:
	case SMB2_WRITE:
	case SMB2_LOCK:
	case SMB2_QUERY_DIRECTORY:
	case SMB2_CHANGE_NOTIFY:
	case SMB2_QUERY_INFO:
	case SMB2_SET_INFO:
341
		rc = -EAGAIN;
342
	}
343
failed:
344 345 346
	return rc;
}

347
static void
348 349 350
fill_small_buf(__le16 smb2_command, struct cifs_tcon *tcon,
	       struct TCP_Server_Info *server,
	       void *buf,
351 352
	       unsigned int *total_len)
{
353
	struct smb2_pdu *spdu = buf;
354 355 356 357 358 359 360 361 362
	/* lookup word count ie StructureSize from table */
	__u16 parmsize = smb2_req_struct_sizes[le16_to_cpu(smb2_command)];

	/*
	 * smaller than SMALL_BUFFER_SIZE but bigger than fixed area of
	 * largest operations (Create)
	 */
	memset(buf, 0, 256);

363
	smb2_hdr_assemble(&spdu->hdr, smb2_command, tcon, server);
364 365
	spdu->StructureSize2 = cpu_to_le16(parmsize);

366
	*total_len = parmsize + sizeof(struct smb2_hdr);
367 368
}

369 370 371
/*
 * Allocate and return pointer to an SMB request hdr, and set basic
 * SMB information in the SMB header. If the return code is zero, this
372
 * function must have filled in request_buf pointer.
373
 */
374
static int __smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
375 376
				 struct TCP_Server_Info *server,
				 void **request_buf, unsigned int *total_len)
377 378
{
	/* BB eventually switch this to SMB2 specific small buf size */
379 380 381 382
	if (smb2_command == SMB2_SET_INFO)
		*request_buf = cifs_buf_get();
	else
		*request_buf = cifs_small_buf_get();
383 384 385 386 387
	if (*request_buf == NULL) {
		/* BB should we add a retry in here if not a writepage? */
		return -ENOMEM;
	}

388
	fill_small_buf(smb2_command, tcon, server,
389
		       (struct smb2_hdr *)(*request_buf),
390
		       total_len);
391 392 393 394 395 396 397

	if (tcon != NULL) {
		uint16_t com_code = le16_to_cpu(smb2_command);
		cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]);
		cifs_stats_inc(&tcon->num_smbs_sent);
	}

398 399 400 401
	return 0;
}

static int smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
402
			       struct TCP_Server_Info *server,
403 404 405 406
			       void **request_buf, unsigned int *total_len)
{
	int rc;

407
	rc = smb2_reconnect(smb2_command, tcon, server);
408 409 410
	if (rc)
		return rc;

411
	return __smb2_plain_req_init(smb2_command, tcon, server, request_buf,
412 413 414 415
				     total_len);
}

static int smb2_ioctl_req_init(u32 opcode, struct cifs_tcon *tcon,
416
			       struct TCP_Server_Info *server,
417 418 419 420
			       void **request_buf, unsigned int *total_len)
{
	/* Skip reconnect only for FSCTL_VALIDATE_NEGOTIATE_INFO IOCTLs */
	if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO) {
421 422
		return __smb2_plain_req_init(SMB2_IOCTL, tcon, server,
					     request_buf, total_len);
423
	}
424 425
	return smb2_plain_req_init(SMB2_IOCTL, tcon, server,
				   request_buf, total_len);
426 427
}

428
/* For explanation of negotiate contexts see MS-SMB2 section 2.2.3.1 */
429 430 431 432 433 434 435

static void
build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt)
{
	pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
	pneg_ctxt->DataLength = cpu_to_le16(38);
	pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
436 437
	pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
	get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
438 439 440
	pneg_ctxt->HashAlgorithms = SMB2_PREAUTH_INTEGRITY_SHA512;
}

441 442 443 444 445 446 447 448 449 450 451 452 453
static void
build_compression_ctxt(struct smb2_compression_capabilities_context *pneg_ctxt)
{
	pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
	pneg_ctxt->DataLength =
		cpu_to_le16(sizeof(struct smb2_compression_capabilities_context)
			  - sizeof(struct smb2_neg_context));
	pneg_ctxt->CompressionAlgorithmCount = cpu_to_le16(3);
	pneg_ctxt->CompressionAlgorithms[0] = SMB3_COMPRESS_LZ77;
	pneg_ctxt->CompressionAlgorithms[1] = SMB3_COMPRESS_LZ77_HUFF;
	pneg_ctxt->CompressionAlgorithms[2] = SMB3_COMPRESS_LZNT1;
}

454 455 456 457 458 459 460 461 462 463
static unsigned int
build_signing_ctxt(struct smb2_signing_capabilities *pneg_ctxt)
{
	unsigned int ctxt_len = sizeof(struct smb2_signing_capabilities);
	unsigned short num_algs = 1; /* number of signing algorithms sent */

	pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
	/*
	 * Context Data length must be rounded to multiple of 8 for some servers
	 */
464 465 466
	pneg_ctxt->DataLength = cpu_to_le16(ALIGN(sizeof(struct smb2_signing_capabilities) -
					    sizeof(struct smb2_neg_context) +
					    (num_algs * sizeof(u16)), 8));
467 468 469
	pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(num_algs);
	pneg_ctxt->SigningAlgorithms[0] = cpu_to_le16(SIGNING_ALG_AES_CMAC);

470 471
	ctxt_len += sizeof(__le16) * num_algs;
	ctxt_len = ALIGN(ctxt_len, 8);
472 473 474 475
	return ctxt_len;
	/* TBD add SIGNING_ALG_AES_GMAC and/or SIGNING_ALG_HMAC_SHA256 */
}

476 477 478 479
static void
build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt)
{
	pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
480 481 482 483
	if (require_gcm_256) {
		pneg_ctxt->DataLength = cpu_to_le16(4); /* Cipher Count + 1 cipher */
		pneg_ctxt->CipherCount = cpu_to_le16(1);
		pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES256_GCM;
484 485 486 487 488 489
	} else if (enable_gcm_256) {
		pneg_ctxt->DataLength = cpu_to_le16(8); /* Cipher Count + 3 ciphers */
		pneg_ctxt->CipherCount = cpu_to_le16(3);
		pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;
		pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES256_GCM;
		pneg_ctxt->Ciphers[2] = SMB2_ENCRYPTION_AES128_CCM;
490 491 492 493 494 495
	} else {
		pneg_ctxt->DataLength = cpu_to_le16(6); /* Cipher Count + 2 ciphers */
		pneg_ctxt->CipherCount = cpu_to_le16(2);
		pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;
		pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES128_CCM;
	}
496 497
}

498 499 500 501 502 503 504 505
static unsigned int
build_netname_ctxt(struct smb2_netname_neg_context *pneg_ctxt, char *hostname)
{
	struct nls_table *cp = load_nls_default();

	pneg_ctxt->ContextType = SMB2_NETNAME_NEGOTIATE_CONTEXT_ID;

	/* copy up to max of first 100 bytes of server name to NetName field */
506
	pneg_ctxt->DataLength = cpu_to_le16(2 * cifs_strtoUTF16(pneg_ctxt->NetName, hostname, 100, cp));
507
	/* context size is DataLength + minimal smb2_neg_context */
508
	return ALIGN(le16_to_cpu(pneg_ctxt->DataLength) + sizeof(struct smb2_neg_context), 8);
509 510
}

511 512 513 514 515
static void
build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
{
	pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
	pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
	/* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
	pneg_ctxt->Name[0] = 0x93;
	pneg_ctxt->Name[1] = 0xAD;
	pneg_ctxt->Name[2] = 0x25;
	pneg_ctxt->Name[3] = 0x50;
	pneg_ctxt->Name[4] = 0x9C;
	pneg_ctxt->Name[5] = 0xB4;
	pneg_ctxt->Name[6] = 0x11;
	pneg_ctxt->Name[7] = 0xE7;
	pneg_ctxt->Name[8] = 0xB4;
	pneg_ctxt->Name[9] = 0x23;
	pneg_ctxt->Name[10] = 0x83;
	pneg_ctxt->Name[11] = 0xDE;
	pneg_ctxt->Name[12] = 0x96;
	pneg_ctxt->Name[13] = 0x8B;
	pneg_ctxt->Name[14] = 0xCD;
	pneg_ctxt->Name[15] = 0x7C;
533 534
}

535
static void
536
assemble_neg_contexts(struct smb2_negotiate_req *req,
537
		      struct TCP_Server_Info *server, unsigned int *total_len)
538
{
539
	unsigned int ctxt_len, neg_context_count;
540 541 542
	struct TCP_Server_Info *pserver;
	char *pneg_ctxt;
	char *hostname;
543

544 545
	if (*total_len > 200) {
		/* In case length corrupted don't want to overrun smb buffer */
546
		cifs_server_dbg(VFS, "Bad frame length assembling neg contexts\n");
547 548 549 550 551 552 553
		return;
	}

	/*
	 * round up total_len of fixed part of SMB3 negotiate request to 8
	 * byte boundary before adding negotiate contexts
	 */
554
	*total_len = ALIGN(*total_len, 8);
555 556 557 558

	pneg_ctxt = (*total_len) + (char *)req;
	req->NegotiateContextOffset = cpu_to_le32(*total_len);

559
	build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt);
560
	ctxt_len = ALIGN(sizeof(struct smb2_preauth_neg_context), 8);
561 562
	*total_len += ctxt_len;
	pneg_ctxt += ctxt_len;
563

564
	build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt);
565
	ctxt_len = ALIGN(sizeof(struct smb2_encryption_neg_context), 8);
566 567 568
	*total_len += ctxt_len;
	pneg_ctxt += ctxt_len;

569 570 571 572
	/*
	 * secondary channels don't have the hostname field populated
	 * use the hostname field in the primary channel instead
	 */
573
	pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
574 575
	cifs_server_lock(pserver);
	hostname = pserver->hostname;
576
	if (hostname && (hostname[0] != 0)) {
577
		ctxt_len = build_netname_ctxt((struct smb2_netname_neg_context *)pneg_ctxt,
578
					      hostname);
579 580 581
		*total_len += ctxt_len;
		pneg_ctxt += ctxt_len;
		neg_context_count = 3;
582 583
	} else
		neg_context_count = 2;
584
	cifs_server_unlock(pserver);
585 586 587 588 589

	build_posix_ctxt((struct smb2_posix_neg_context *)pneg_ctxt);
	*total_len += sizeof(struct smb2_posix_neg_context);
	pneg_ctxt += sizeof(struct smb2_posix_neg_context);
	neg_context_count++;
590

591 592
	if (server->compress_algorithm) {
		build_compression_ctxt((struct smb2_compression_capabilities_context *)
593
				pneg_ctxt);
594
		ctxt_len = ALIGN(sizeof(struct smb2_compression_capabilities_context), 8);
595 596
		*total_len += ctxt_len;
		pneg_ctxt += ctxt_len;
597 598
		neg_context_count++;
	}
599

600 601 602 603 604 605 606 607 608 609
	if (enable_negotiate_signing) {
		ctxt_len = build_signing_ctxt((struct smb2_signing_capabilities *)
				pneg_ctxt);
		*total_len += ctxt_len;
		pneg_ctxt += ctxt_len;
		neg_context_count++;
	}

	/* check for and add transport_capabilities and signing capabilities */
	req->NegotiateContextCount = cpu_to_le16(neg_context_count);
610

611
}
612

613
/* If invalid preauth context warn but use what we requested, SHA-512 */
614 615 616 617
static void decode_preauth_context(struct smb2_preauth_neg_context *ctxt)
{
	unsigned int len = le16_to_cpu(ctxt->DataLength);

618 619 620 621
	/*
	 * Caller checked that DataLength remains within SMB boundary. We still
	 * need to confirm that one HashAlgorithms member is accounted for.
	 */
622
	if (len < MIN_PREAUTH_CTXT_DATA_LEN) {
623
		pr_warn_once("server sent bad preauth context\n");
624
		return;
625 626 627
	} else if (len < MIN_PREAUTH_CTXT_DATA_LEN + le16_to_cpu(ctxt->SaltLength)) {
		pr_warn_once("server sent invalid SaltLength\n");
		return;
628 629
	}
	if (le16_to_cpu(ctxt->HashAlgorithmCount) != 1)
630
		pr_warn_once("Invalid SMB3 hash algorithm count\n");
631
	if (ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
632
		pr_warn_once("unknown SMB3 hash algorithm\n");
633 634
}

635 636 637 638 639
static void decode_compress_ctx(struct TCP_Server_Info *server,
			 struct smb2_compression_capabilities_context *ctxt)
{
	unsigned int len = le16_to_cpu(ctxt->DataLength);

640 641 642 643 644
	/*
	 * Caller checked that DataLength remains within SMB boundary. We still
	 * need to confirm that one CompressionAlgorithms member is accounted
	 * for.
	 */
645
	if (len < 10) {
646
		pr_warn_once("server sent bad compression cntxt\n");
647 648 649
		return;
	}
	if (le16_to_cpu(ctxt->CompressionAlgorithmCount) != 1) {
650
		pr_warn_once("Invalid SMB3 compress algorithm count\n");
651 652 653
		return;
	}
	if (le16_to_cpu(ctxt->CompressionAlgorithms[0]) > 3) {
654
		pr_warn_once("unknown compression algorithm\n");
655 656 657 658 659
		return;
	}
	server->compress_algorithm = ctxt->CompressionAlgorithms[0];
}

660 661 662 663 664 665
static int decode_encrypt_ctx(struct TCP_Server_Info *server,
			      struct smb2_encryption_neg_context *ctxt)
{
	unsigned int len = le16_to_cpu(ctxt->DataLength);

	cifs_dbg(FYI, "decode SMB3.11 encryption neg context of len %d\n", len);
666 667 668 669 670
	/*
	 * Caller checked that DataLength remains within SMB boundary. We still
	 * need to confirm that one Cipher flexible array member is accounted
	 * for.
	 */
671
	if (len < MIN_ENCRYPT_CTXT_DATA_LEN) {
672
		pr_warn_once("server sent bad crypto ctxt len\n");
673 674 675 676
		return -EINVAL;
	}

	if (le16_to_cpu(ctxt->CipherCount) != 1) {
677
		pr_warn_once("Invalid SMB3.11 cipher count\n");
678 679 680
		return -EINVAL;
	}
	cifs_dbg(FYI, "SMB311 cipher type:%d\n", le16_to_cpu(ctxt->Ciphers[0]));
681 682 683 684 685 686
	if (require_gcm_256) {
		if (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES256_GCM) {
			cifs_dbg(VFS, "Server does not support requested encryption type (AES256 GCM)\n");
			return -EOPNOTSUPP;
		}
	} else if (ctxt->Ciphers[0] == 0) {
687 688 689 690 691 692 693 694 695 696 697 698 699
		/*
		 * e.g. if server only supported AES256_CCM (very unlikely)
		 * or server supported no encryption types or had all disabled.
		 * Since GLOBAL_CAP_ENCRYPTION will be not set, in the case
		 * in which mount requested encryption ("seal") checks later
		 * on during tree connection will return proper rc, but if
		 * seal not requested by client, since server is allowed to
		 * return 0 to indicate no supported cipher, we can't fail here
		 */
		server->cipher_type = 0;
		server->capabilities &= ~SMB2_GLOBAL_CAP_ENCRYPTION;
		pr_warn_once("Server does not support requested encryption types\n");
		return 0;
700 701 702 703
	} else if ((ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES128_CCM) &&
		   (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES128_GCM) &&
		   (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES256_GCM)) {
		/* server returned a cipher we didn't ask for */
704
		pr_warn_once("Invalid SMB3.11 cipher returned\n");
705 706 707
		return -EINVAL;
	}
	server->cipher_type = ctxt->Ciphers[0];
708
	server->capabilities |= SMB2_GLOBAL_CAP_ENCRYPTION;
709 710 711
	return 0;
}

712 713 714 715 716
static void decode_signing_ctx(struct TCP_Server_Info *server,
			       struct smb2_signing_capabilities *pctxt)
{
	unsigned int len = le16_to_cpu(pctxt->DataLength);

717 718 719 720 721
	/*
	 * Caller checked that DataLength remains within SMB boundary. We still
	 * need to confirm that one SigningAlgorithms flexible array member is
	 * accounted for.
	 */
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
	if ((len < 4) || (len > 16)) {
		pr_warn_once("server sent bad signing negcontext\n");
		return;
	}
	if (le16_to_cpu(pctxt->SigningAlgorithmCount) != 1) {
		pr_warn_once("Invalid signing algorithm count\n");
		return;
	}
	if (le16_to_cpu(pctxt->SigningAlgorithms[0]) > 2) {
		pr_warn_once("unknown signing algorithm\n");
		return;
	}

	server->signing_negotiated = true;
	server->signing_algorithm = le16_to_cpu(pctxt->SigningAlgorithms[0]);
	cifs_dbg(FYI, "signing algorithm %d chosen\n",
		     server->signing_algorithm);
}


742
static int smb311_decode_neg_context(struct smb2_negotiate_rsp *rsp,
743 744
				     struct TCP_Server_Info *server,
				     unsigned int len_of_smb)
745 746 747 748 749 750 751 752 753
{
	struct smb2_neg_context *pctx;
	unsigned int offset = le32_to_cpu(rsp->NegotiateContextOffset);
	unsigned int ctxt_cnt = le16_to_cpu(rsp->NegotiateContextCount);
	unsigned int len_of_ctxts, i;
	int rc = 0;

	cifs_dbg(FYI, "decoding %d negotiate contexts\n", ctxt_cnt);
	if (len_of_smb <= offset) {
754
		cifs_server_dbg(VFS, "Invalid response: negotiate context offset\n");
755 756 757 758 759 760 761 762 763 764 765
		return -EINVAL;
	}

	len_of_ctxts = len_of_smb - offset;

	for (i = 0; i < ctxt_cnt; i++) {
		int clen;
		/* check that offset is not beyond end of SMB */
		if (len_of_ctxts < sizeof(struct smb2_neg_context))
			break;

766
		pctx = (struct smb2_neg_context *)(offset + (char *)rsp);
767 768 769 770 771 772 773 774 775
		clen = sizeof(struct smb2_neg_context)
			+ le16_to_cpu(pctx->DataLength);
		/*
		 * 2.2.4 SMB2 NEGOTIATE Response
		 * Subsequent negotiate contexts MUST appear at the first 8-byte
		 * aligned offset following the previous negotiate context.
		 */
		if (i + 1 != ctxt_cnt)
			clen = ALIGN(clen, 8);
776 777 778 779 780 781 782 783 784
		if (clen > len_of_ctxts)
			break;

		if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES)
			decode_preauth_context(
				(struct smb2_preauth_neg_context *)pctx);
		else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES)
			rc = decode_encrypt_ctx(server,
				(struct smb2_encryption_neg_context *)pctx);
785 786 787
		else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES)
			decode_compress_ctx(server,
				(struct smb2_compression_capabilities_context *)pctx);
788 789
		else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE)
			server->posix_ext_supported = true;
790 791 792
		else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES)
			decode_signing_ctx(server,
				(struct smb2_signing_capabilities *)pctx);
793
		else
794
			cifs_server_dbg(VFS, "unknown negcontext of type %d ignored\n",
795 796 797
				le16_to_cpu(pctx->ContextType));
		if (rc)
			break;
798 799

		offset += clen;
800 801 802 803 804
		len_of_ctxts -= clen;
	}
	return rc;
}

805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
static struct create_posix *
create_posix_buf(umode_t mode)
{
	struct create_posix *buf;

	buf = kzalloc(sizeof(struct create_posix),
			GFP_KERNEL);
	if (!buf)
		return NULL;

	buf->ccontext.DataOffset =
		cpu_to_le16(offsetof(struct create_posix, Mode));
	buf->ccontext.DataLength = cpu_to_le32(4);
	buf->ccontext.NameOffset =
		cpu_to_le16(offsetof(struct create_posix, Name));
	buf->ccontext.NameLength = cpu_to_le16(16);

	/* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
	buf->Name[0] = 0x93;
	buf->Name[1] = 0xAD;
	buf->Name[2] = 0x25;
	buf->Name[3] = 0x50;
	buf->Name[4] = 0x9C;
	buf->Name[5] = 0xB4;
	buf->Name[6] = 0x11;
	buf->Name[7] = 0xE7;
	buf->Name[8] = 0xB4;
	buf->Name[9] = 0x23;
	buf->Name[10] = 0x83;
	buf->Name[11] = 0xDE;
	buf->Name[12] = 0x96;
	buf->Name[13] = 0x8B;
	buf->Name[14] = 0xCD;
	buf->Name[15] = 0x7C;
	buf->Mode = cpu_to_le32(mode);
840
	cifs_dbg(FYI, "mode on posix create 0%o\n", mode);
841 842 843 844 845 846 847 848 849
	return buf;
}

static int
add_posix_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode)
{
	unsigned int num = *num_iovec;

	iov[num].iov_base = create_posix_buf(mode);
850
	if (mode == ACL_NO_MODE)
851
		cifs_dbg(FYI, "%s: no mode\n", __func__);
852 853 854 855 856 857 858
	if (iov[num].iov_base == NULL)
		return -ENOMEM;
	iov[num].iov_len = sizeof(struct create_posix);
	*num_iovec = num + 1;
	return 0;
}

859

860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
/*
 *
 *	SMB2 Worker functions follow:
 *
 *	The general structure of the worker functions is:
 *	1) Call smb2_init (assembles SMB2 header)
 *	2) Initialize SMB2 command specific fields in fixed length area of SMB
 *	3) Call smb_sendrcv2 (sends request on socket and waits for response)
 *	4) Decode SMB2 command specific fields in the fixed length area
 *	5) Decode variable length data area (if any for this SMB2 command type)
 *	6) Call free smb buffer
 *	7) return
 *
 */

int
876 877 878
SMB2_negotiate(const unsigned int xid,
	       struct cifs_ses *ses,
	       struct TCP_Server_Info *server)
879
{
880
	struct smb_rqst rqst;
881 882 883
	struct smb2_negotiate_req *req;
	struct smb2_negotiate_rsp *rsp;
	struct kvec iov[1];
884
	struct kvec rsp_iov;
885
	int rc;
886 887 888 889
	int resp_buftype;
	int blob_offset, blob_length;
	char *security_blob;
	int flags = CIFS_NEG_OP;
890
	unsigned int total_len;
891

892
	cifs_dbg(FYI, "Negotiate protocol\n");
893

894 895 896
	if (!server) {
		WARN(1, "%s: server is NULL!\n", __func__);
		return -EIO;
897 898
	}

899 900
	rc = smb2_plain_req_init(SMB2_NEGOTIATE, NULL, server,
				 (void **) &req, &total_len);
901 902 903
	if (rc)
		return rc;

904
	req->hdr.SessionId = 0;
905

906 907
	memset(server->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
	memset(ses->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
908

909
	if (strcmp(server->vals->version_string,
910 911 912
		   SMB3ANY_VERSION_STRING) == 0) {
		req->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
		req->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
913 914 915
		req->Dialects[2] = cpu_to_le16(SMB311_PROT_ID);
		req->DialectCount = cpu_to_le16(3);
		total_len += 6;
916
	} else if (strcmp(server->vals->version_string,
917 918 919 920
		   SMBDEFAULT_VERSION_STRING) == 0) {
		req->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
		req->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
		req->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
921 922 923
		req->Dialects[3] = cpu_to_le16(SMB311_PROT_ID);
		req->DialectCount = cpu_to_le16(4);
		total_len += 8;
924 925
	} else {
		/* otherwise send specific dialect */
926
		req->Dialects[0] = cpu_to_le16(server->vals->protocol_id);
927
		req->DialectCount = cpu_to_le16(1);
928
		total_len += 2;
929
	}
930 931

	/* only one of SMB2 signing flags may be set in SMB2 request */
932
	if (ses->sign)
933
		req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
934
	else if (global_secflags & CIFSSEC_MAY_SIGN)
935
		req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
936 937
	else
		req->SecurityMode = 0;
938

939
	req->Capabilities = cpu_to_le32(server->vals->req_capabilities);
940 941
	if (ses->chan_max > 1)
		req->Capabilities |= cpu_to_le32(SMB2_GLOBAL_CAP_MULTI_CHANNEL);
942

943
	/* ClientGUID must be zero for SMB2.02 dialect */
944
	if (server->vals->protocol_id == SMB20_PROT_ID)
945
		memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE);
946
	else {
947 948
		memcpy(req->ClientGUID, server->client_guid,
			SMB2_CLIENT_GUID_SIZE);
949
		if ((server->vals->protocol_id == SMB311_PROT_ID) ||
950 951
		    (strcmp(server->vals->version_string,
		     SMB3ANY_VERSION_STRING) == 0) ||
952
		    (strcmp(server->vals->version_string,
953
		     SMBDEFAULT_VERSION_STRING) == 0))
954
			assemble_neg_contexts(req, server, &total_len);
955
	}
956
	iov[0].iov_base = (char *)req;
957
	iov[0].iov_len = total_len;
958

959 960 961 962
	memset(&rqst, 0, sizeof(struct smb_rqst));
	rqst.rq_iov = iov;
	rqst.rq_nvec = 1;

963 964
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
965 966
	cifs_small_buf_release(req);
	rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base;
967 968 969 970
	/*
	 * No tcon so can't do
	 * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
	 */
971
	if (rc == -EOPNOTSUPP) {
972
		cifs_server_dbg(VFS, "Dialect not supported by server. Consider  specifying vers=1.0 or vers=2.0 on mount for accessing older servers\n");
973 974
		goto neg_exit;
	} else if (rc != 0)
975 976
		goto neg_exit;

977
	rc = -EIO;
978
	if (strcmp(server->vals->version_string,
979 980
		   SMB3ANY_VERSION_STRING) == 0) {
		if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
981
			cifs_server_dbg(VFS,
982
				"SMB2 dialect returned but not requested\n");
983
			goto neg_exit;
984
		} else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
985
			cifs_server_dbg(VFS,
986
				"SMB2.1 dialect returned but not requested\n");
987
			goto neg_exit;
988 989 990 991
		} else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
			/* ops set to 3.0 by default for default so update */
			server->ops = &smb311_operations;
			server->vals = &smb311_values;
992
		}
993
	} else if (strcmp(server->vals->version_string,
994 995
		   SMBDEFAULT_VERSION_STRING) == 0) {
		if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
996
			cifs_server_dbg(VFS,
997
				"SMB2 dialect returned but not requested\n");
998
			goto neg_exit;
999 1000
		} else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
			/* ops set to 3.0 by default for default so update */
1001 1002
			server->ops = &smb21_operations;
			server->vals = &smb21_values;
1003
		} else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
1004 1005
			server->ops = &smb311_operations;
			server->vals = &smb311_values;
1006
		}
Steve French's avatar
Steve French committed
1007
	} else if (le16_to_cpu(rsp->DialectRevision) !=
1008
				server->vals->protocol_id) {
1009
		/* if requested single dialect ensure returned dialect matched */
1010 1011
		cifs_server_dbg(VFS, "Invalid 0x%x dialect returned: not requested\n",
				le16_to_cpu(rsp->DialectRevision));
1012
		goto neg_exit;
1013 1014
	}

1015
	cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode);
1016

1017
	if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID))
1018
		cifs_dbg(FYI, "negotiated smb2.0 dialect\n");
1019
	else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID))
1020
		cifs_dbg(FYI, "negotiated smb2.1 dialect\n");
1021
	else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID))
1022
		cifs_dbg(FYI, "negotiated smb3.0 dialect\n");
Steve French's avatar
Steve French committed
1023 1024
	else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID))
		cifs_dbg(FYI, "negotiated smb3.02 dialect\n");
1025 1026
	else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))
		cifs_dbg(FYI, "negotiated smb3.1.1 dialect\n");
1027
	else {
1028 1029
		cifs_server_dbg(VFS, "Invalid dialect returned by server 0x%x\n",
				le16_to_cpu(rsp->DialectRevision));
1030 1031
		goto neg_exit;
	}
1032 1033

	rc = 0;
1034 1035
	server->dialect = le16_to_cpu(rsp->DialectRevision);

1036 1037 1038 1039 1040 1041 1042
	/*
	 * Keep a copy of the hash after negprot. This hash will be
	 * the starting hash value for all sessions made from this
	 * server.
	 */
	memcpy(server->preauth_sha_hash, ses->preauth_sha_hash,
	       SMB2_PREAUTH_HASH_SIZE);
1043

1044 1045
	/* SMB2 only has an extended negflavor */
	server->negflavor = CIFS_NEGFLAVOR_EXTENDED;
1046 1047 1048
	/* set it to the maximum buffer size value we can send with 1 credit */
	server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize),
			       SMB2_MAX_BUFFER_SIZE);
1049 1050 1051
	server->max_read = le32_to_cpu(rsp->MaxReadSize);
	server->max_write = le32_to_cpu(rsp->MaxWriteSize);
	server->sec_mode = le16_to_cpu(rsp->SecurityMode);
1052 1053 1054
	if ((server->sec_mode & SMB2_SEC_MODE_FLAGS_ALL) != server->sec_mode)
		cifs_dbg(FYI, "Server returned unexpected security mode 0x%x\n",
				server->sec_mode);
1055
	server->capabilities = le32_to_cpu(rsp->Capabilities);
1056 1057
	/* Internal types */
	server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES;
1058

1059 1060 1061 1062 1063 1064 1065
	/*
	 * SMB3.0 supports only 1 cipher and doesn't have a encryption neg context
	 * Set the cipher type manually.
	 */
	if (server->dialect == SMB30_PROT_ID && (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
		server->cipher_type = SMB2_ENCRYPTION_AES128_CCM;

1066
	security_blob = smb2_get_data_area_len(&blob_offset, &blob_length,
1067
					       (struct smb2_hdr *)rsp);
1068 1069 1070 1071 1072 1073 1074
	/*
	 * See MS-SMB2 section 2.2.4: if no blob, client picks default which
	 * for us will be
	 *	ses->sectype = RawNTLMSSP;
	 * but for time being this is our only auth choice so doesn't matter.
	 * We just found a server which sets blob length to zero expecting raw.
	 */
1075
	if (blob_length == 0) {
1076
		cifs_dbg(FYI, "missing security blob on negprot\n");
1077 1078
		server->sec_ntlmssp = true;
	}
Pavel Shilovsky's avatar
Pavel Shilovsky committed
1079

1080
	rc = cifs_enable_signing(server, ses->sign);
1081 1082
	if (rc)
		goto neg_exit;
1083
	if (blob_length) {
1084
		rc = decode_negTokenInit(security_blob, blob_length, server);
1085 1086 1087 1088
		if (rc == 1)
			rc = 0;
		else if (rc == 0)
			rc = -EIO;
1089
	}
1090 1091 1092

	if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
		if (rsp->NegotiateContextCount)
1093 1094
			rc = smb311_decode_neg_context(rsp, server,
						       rsp_iov.iov_len);
1095
		else
1096
			cifs_server_dbg(VFS, "Missing expected negotiate contexts\n");
1097
	}
1098 1099 1100 1101
neg_exit:
	free_rsp_buf(resp_buftype, rsp);
	return rc;
}
1102

1103 1104
int smb3_validate_negotiate(const unsigned int xid, struct cifs_tcon *tcon)
{
1105 1106
	int rc;
	struct validate_negotiate_info_req *pneg_inbuf;
1107
	struct validate_negotiate_info_rsp *pneg_rsp = NULL;
1108
	u32 rsplen;
1109
	u32 inbuflen; /* max of 4 dialects */
1110
	struct TCP_Server_Info *server = tcon->ses->server;
1111 1112 1113

	cifs_dbg(FYI, "validate negotiate\n");

1114
	/* In SMB3.11 preauth integrity supersedes validate negotiate */
1115
	if (server->dialect == SMB311_PROT_ID)
1116 1117
		return 0;

1118 1119
	/*
	 * validation ioctl must be signed, so no point sending this if we
1120 1121
	 * can not sign it (ie are not known user).  Even if signing is not
	 * required (enabled but not negotiated), in those cases we selectively
1122
	 * sign just this, the first and only signed request on a connection.
1123
	 * Having validation of negotiate info  helps reduce attack vectors.
1124
	 */
1125
	if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST)
1126 1127
		return 0; /* validation requires signing */

1128 1129 1130 1131 1132 1133
	if (tcon->ses->user_name == NULL) {
		cifs_dbg(FYI, "Can't validate negotiate: null user mount\n");
		return 0; /* validation requires signing */
	}

	if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_NULL)
1134
		cifs_tcon_dbg(VFS, "Unexpected null user (anonymous) auth flag sent by server\n");
1135

1136 1137 1138 1139 1140
	pneg_inbuf = kmalloc(sizeof(*pneg_inbuf), GFP_NOFS);
	if (!pneg_inbuf)
		return -ENOMEM;

	pneg_inbuf->Capabilities =
1141
			cpu_to_le32(server->vals->req_capabilities);
1142 1143 1144
	if (tcon->ses->chan_max > 1)
		pneg_inbuf->Capabilities |= cpu_to_le32(SMB2_GLOBAL_CAP_MULTI_CHANNEL);

1145
	memcpy(pneg_inbuf->Guid, server->client_guid,
1146
					SMB2_CLIENT_GUID_SIZE);
1147 1148

	if (tcon->ses->sign)
1149
		pneg_inbuf->SecurityMode =
1150 1151
			cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
	else if (global_secflags & CIFSSEC_MAY_SIGN)
1152
		pneg_inbuf->SecurityMode =
1153 1154
			cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
	else
1155
		pneg_inbuf->SecurityMode = 0;
1156

1157

1158
	if (strcmp(server->vals->version_string,
1159
		SMB3ANY_VERSION_STRING) == 0) {
1160 1161
		pneg_inbuf->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
		pneg_inbuf->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
1162 1163 1164
		pneg_inbuf->Dialects[2] = cpu_to_le16(SMB311_PROT_ID);
		pneg_inbuf->DialectCount = cpu_to_le16(3);
		/* SMB 2.1 not included so subtract one dialect from len */
1165
		inbuflen = sizeof(*pneg_inbuf) -
1166
				(sizeof(pneg_inbuf->Dialects[0]));
1167
	} else if (strcmp(server->vals->version_string,
1168
		SMBDEFAULT_VERSION_STRING) == 0) {
1169 1170 1171
		pneg_inbuf->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
		pneg_inbuf->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
		pneg_inbuf->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
1172 1173
		pneg_inbuf->Dialects[3] = cpu_to_le16(SMB311_PROT_ID);
		pneg_inbuf->DialectCount = cpu_to_le16(4);
1174
		/* structure is big enough for 4 dialects */
1175
		inbuflen = sizeof(*pneg_inbuf);
1176 1177
	} else {
		/* otherwise specific dialect was requested */
1178
		pneg_inbuf->Dialects[0] =
1179
			cpu_to_le16(server->vals->protocol_id);
1180
		pneg_inbuf->DialectCount = cpu_to_le16(1);
1181
		/* structure is big enough for 4 dialects, sending only 1 */
1182
		inbuflen = sizeof(*pneg_inbuf) -
1183
				sizeof(pneg_inbuf->Dialects[0]) * 3;
1184
	}
1185 1186

	rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
1187
		FSCTL_VALIDATE_NEGOTIATE_INFO,
1188 1189
		(char *)pneg_inbuf, inbuflen, CIFSMaxBufSize,
		(char **)&pneg_rsp, &rsplen);
1190 1191 1192 1193 1194
	if (rc == -EOPNOTSUPP) {
		/*
		 * Old Windows versions or Netapp SMB server can return
		 * not supported error. Client should accept it.
		 */
1195
		cifs_tcon_dbg(VFS, "Server does not support validate negotiate\n");
1196 1197
		rc = 0;
		goto out_free_inbuf;
1198
	} else if (rc != 0) {
1199 1200
		cifs_tcon_dbg(VFS, "validate protocol negotiate failed: %d\n",
			      rc);
1201 1202
		rc = -EIO;
		goto out_free_inbuf;
1203 1204
	}

1205 1206
	rc = -EIO;
	if (rsplen != sizeof(*pneg_rsp)) {
1207 1208
		cifs_tcon_dbg(VFS, "Invalid protocol negotiate response size: %d\n",
			      rsplen);
1209 1210

		/* relax check since Mac returns max bufsize allowed on ioctl */
1211 1212
		if (rsplen > CIFSMaxBufSize || rsplen < sizeof(*pneg_rsp))
			goto out_free_rsp;
1213 1214 1215
	}

	/* check validate negotiate info response matches what we got earlier */
1216
	if (pneg_rsp->Dialect != cpu_to_le16(server->dialect))
1217 1218
		goto vneg_out;

1219
	if (pneg_rsp->SecurityMode != cpu_to_le16(server->sec_mode))
1220 1221 1222 1223 1224
		goto vneg_out;

	/* do not validate server guid because not saved at negprot time yet */

	if ((le32_to_cpu(pneg_rsp->Capabilities) | SMB2_NT_FIND |
1225
	      SMB2_LARGE_FILES) != server->capabilities)
1226 1227 1228
		goto vneg_out;

	/* validate negotiate successful */
1229
	rc = 0;
1230
	cifs_dbg(FYI, "validate negotiate info successful\n");
1231
	goto out_free_rsp;
1232 1233

vneg_out:
1234
	cifs_tcon_dbg(VFS, "protocol revalidation - security settings mismatch\n");
1235
out_free_rsp:
1236
	kfree(pneg_rsp);
1237 1238 1239
out_free_inbuf:
	kfree(pneg_inbuf);
	return rc;
1240 1241
}

1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
enum securityEnum
smb2_select_sectype(struct TCP_Server_Info *server, enum securityEnum requested)
{
	switch (requested) {
	case Kerberos:
	case RawNTLMSSP:
		return requested;
	case NTLMv2:
		return RawNTLMSSP;
	case Unspecified:
		if (server->sec_ntlmssp &&
			(global_secflags & CIFSSEC_MAY_NTLMSSP))
			return RawNTLMSSP;
		if ((server->sec_kerberos || server->sec_mskerberos) &&
			(global_secflags & CIFSSEC_MAY_KRB5))
			return Kerberos;
1258
		fallthrough;
1259 1260 1261 1262 1263
	default:
		return Unspecified;
	}
}

1264 1265 1266
struct SMB2_sess_data {
	unsigned int xid;
	struct cifs_ses *ses;
1267
	struct TCP_Server_Info *server;
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
	struct nls_table *nls_cp;
	void (*func)(struct SMB2_sess_data *);
	int result;
	u64 previous_session;

	/* we will send the SMB in three pieces:
	 * a fixed length beginning part, an optional
	 * SPNEGO blob (which can be zero length), and a
	 * last part which will include the strings
	 * and rest of bcc area. This allows us to avoid
	 * a large buffer 17K allocation
	 */
	int buf0_type;
	struct kvec iov[2];
};

static int
SMB2_sess_alloc_buffer(struct SMB2_sess_data *sess_data)
{
	int rc;
	struct cifs_ses *ses = sess_data->ses;
1289
	struct TCP_Server_Info *server = sess_data->server;
1290
	struct smb2_sess_setup_req *req;
1291
	unsigned int total_len;
1292
	bool is_binding = false;
1293

1294 1295 1296
	rc = smb2_plain_req_init(SMB2_SESSION_SETUP, NULL, server,
				 (void **) &req,
				 &total_len);
1297 1298 1299
	if (rc)
		return rc;

1300 1301 1302
	spin_lock(&ses->ses_lock);
	is_binding = (ses->ses_status == SES_GOOD);
	spin_unlock(&ses->ses_lock);
1303 1304 1305

	if (is_binding) {
		req->hdr.SessionId = cpu_to_le64(ses->Suid);
1306
		req->hdr.Flags |= SMB2_FLAGS_SIGNED;
1307 1308
		req->PreviousSessionId = 0;
		req->Flags = SMB2_SESSION_REQ_FLAG_BINDING;
1309
		cifs_dbg(FYI, "Binding to sess id: %llx\n", ses->Suid);
1310 1311
	} else {
		/* First session, not a reauthenticate */
1312
		req->hdr.SessionId = 0;
1313 1314 1315 1316
		/*
		 * if reconnect, we need to send previous sess id
		 * otherwise it is 0
		 */
1317
		req->PreviousSessionId = cpu_to_le64(sess_data->previous_session);
1318
		req->Flags = 0; /* MBZ */
1319 1320
		cifs_dbg(FYI, "Fresh session. Previous: %llx\n",
			 sess_data->previous_session);
1321
	}
1322 1323

	/* enough to enable echos and oplocks and one max size write */
1324 1325 1326 1327 1328 1329
	if (server->credits >= server->max_credits)
		req->hdr.CreditRequest = cpu_to_le16(0);
	else
		req->hdr.CreditRequest = cpu_to_le16(
			min_t(int, server->max_credits -
			      server->credits, 130));
1330 1331 1332 1333 1334 1335 1336 1337 1338

	/* only one of SMB2 signing flags may be set in SMB2 request */
	if (server->sign)
		req->SecurityMode = SMB2_NEGOTIATE_SIGNING_REQUIRED;
	else if (global_secflags & CIFSSEC_MAY_SIGN) /* one flag unlike MUST_ */
		req->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED;
	else
		req->SecurityMode = 0;

1339 1340 1341
#ifdef CONFIG_CIFS_DFS_UPCALL
	req->Capabilities = cpu_to_le32(SMB2_GLOBAL_CAP_DFS);
#else
1342
	req->Capabilities = 0;
1343 1344
#endif /* DFS_UPCALL */

1345 1346 1347
	req->Channel = 0; /* MBZ */

	sess_data->iov[0].iov_base = (char *)req;
1348 1349
	/* 1 for pad */
	sess_data->iov[0].iov_len = total_len - 1;
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
	/*
	 * This variable will be used to clear the buffer
	 * allocated above in case of any error in the calling function.
	 */
	sess_data->buf0_type = CIFS_SMALL_BUFFER;

	return 0;
}

static void
SMB2_sess_free_buffer(struct SMB2_sess_data *sess_data)
{
1362
	struct kvec *iov = sess_data->iov;
1363

1364 1365 1366
	/* iov[1] is already freed by caller */
	if (sess_data->buf0_type != CIFS_NO_BUFFER && iov[0].iov_base)
		memzero_explicit(iov[0].iov_base, iov[0].iov_len);
1367

1368
	free_rsp_buf(sess_data->buf0_type, iov[0].iov_base);
1369 1370 1371 1372 1373 1374 1375
	sess_data->buf0_type = CIFS_NO_BUFFER;
}

static int
SMB2_sess_sendreceive(struct SMB2_sess_data *sess_data)
{
	int rc;
1376
	struct smb_rqst rqst;
1377
	struct smb2_sess_setup_req *req = sess_data->iov[0].iov_base;
1378
	struct kvec rsp_iov = { NULL, 0 };
1379 1380 1381

	/* Testing shows that buffer offset must be at location of Buffer[0] */
	req->SecurityBufferOffset =
1382
		cpu_to_le16(sizeof(struct smb2_sess_setup_req));
1383 1384
	req->SecurityBufferLength = cpu_to_le16(sess_data->iov[1].iov_len);

1385 1386 1387
	memset(&rqst, 0, sizeof(struct smb_rqst));
	rqst.rq_iov = sess_data->iov;
	rqst.rq_nvec = 2;
1388

1389 1390
	/* BB add code to build os and lm fields */
	rc = cifs_send_recv(sess_data->xid, sess_data->ses,
1391
			    sess_data->server,
1392
			    &rqst,
1393
			    &sess_data->buf0_type,
1394
			    CIFS_LOG_ERROR | CIFS_SESS_OP, &rsp_iov);
1395 1396
	cifs_small_buf_release(sess_data->iov[0].iov_base);
	memcpy(&sess_data->iov[0], &rsp_iov, sizeof(struct kvec));
1397 1398 1399 1400 1401 1402 1403 1404 1405

	return rc;
}

static int
SMB2_sess_establish_session(struct SMB2_sess_data *sess_data)
{
	int rc = 0;
	struct cifs_ses *ses = sess_data->ses;
1406
	struct TCP_Server_Info *server = sess_data->server;
1407

1408
	cifs_server_lock(server);
1409
	if (server->ops->generate_signingkey) {
1410
		rc = server->ops->generate_signingkey(ses, server);
1411 1412 1413
		if (rc) {
			cifs_dbg(FYI,
				"SMB3 session key generation failed\n");
1414
			cifs_server_unlock(server);
1415
			return rc;
1416 1417
		}
	}
1418 1419 1420
	if (!server->session_estab) {
		server->sequence_number = 0x2;
		server->session_estab = true;
1421
	}
1422
	cifs_server_unlock(server);
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433

	cifs_dbg(FYI, "SMB2/3 session established successfully\n");
	return rc;
}

#ifdef CONFIG_CIFS_UPCALL
static void
SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
{
	int rc;
	struct cifs_ses *ses = sess_data->ses;
1434
	struct TCP_Server_Info *server = sess_data->server;
1435 1436 1437
	struct cifs_spnego_msg *msg;
	struct key *spnego_key = NULL;
	struct smb2_sess_setup_rsp *rsp = NULL;
1438
	bool is_binding = false;
1439 1440 1441 1442 1443

	rc = SMB2_sess_alloc_buffer(sess_data);
	if (rc)
		goto out;

1444
	spnego_key = cifs_get_spnego_key(ses, server);
1445 1446
	if (IS_ERR(spnego_key)) {
		rc = PTR_ERR(spnego_key);
1447 1448
		if (rc == -ENOKEY)
			cifs_dbg(VFS, "Verify user has a krb5 ticket and keyutils is installed\n");
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
		spnego_key = NULL;
		goto out;
	}

	msg = spnego_key->payload.data[0];
	/*
	 * check version field to make sure that cifs.upcall is
	 * sending us a response in an expected form
	 */
	if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) {
1459 1460
		cifs_dbg(VFS, "bad cifs.upcall version. Expected %d got %d\n",
			 CIFS_SPNEGO_UPCALL_VERSION, msg->version);
1461 1462 1463 1464
		rc = -EKEYREJECTED;
		goto out_put_spnego_key;
	}

1465 1466 1467
	spin_lock(&ses->ses_lock);
	is_binding = (ses->ses_status == SES_GOOD);
	spin_unlock(&ses->ses_lock);
1468

1469
	/* keep session key if binding */
1470
	if (!is_binding) {
1471
		kfree_sensitive(ses->auth_key.response);
1472 1473 1474
		ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len,
						 GFP_KERNEL);
		if (!ses->auth_key.response) {
1475
			cifs_dbg(VFS, "Kerberos can't allocate (%u bytes) memory\n",
1476 1477 1478 1479 1480
				 msg->sesskey_len);
			rc = -ENOMEM;
			goto out_put_spnego_key;
		}
		ses->auth_key.len = msg->sesskey_len;
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
	}

	sess_data->iov[1].iov_base = msg->data + msg->sesskey_len;
	sess_data->iov[1].iov_len = msg->secblob_len;

	rc = SMB2_sess_sendreceive(sess_data);
	if (rc)
		goto out_put_spnego_key;

	rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1491
	/* keep session id and flags if binding */
1492
	if (!is_binding) {
1493
		ses->Suid = le64_to_cpu(rsp->hdr.SessionId);
1494 1495
		ses->session_flags = le16_to_cpu(rsp->SessionFlags);
	}
1496 1497 1498 1499 1500

	rc = SMB2_sess_establish_session(sess_data);
out_put_spnego_key:
	key_invalidate(spnego_key);
	key_put(spnego_key);
1501
	if (rc) {
1502
		kfree_sensitive(ses->auth_key.response);
1503 1504 1505
		ses->auth_key.response = NULL;
		ses->auth_key.len = 0;
	}
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
out:
	sess_data->result = rc;
	sess_data->func = NULL;
	SMB2_sess_free_buffer(sess_data);
}
#else
static void
SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
{
	cifs_dbg(VFS, "Kerberos negotiated but upcall support disabled!\n");
	sess_data->result = -EOPNOTSUPP;
	sess_data->func = NULL;
}
#endif

1521 1522 1523 1524 1525
static void
SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data);

static void
SMB2_sess_auth_rawntlmssp_negotiate(struct SMB2_sess_data *sess_data)
1526
{
1527 1528
	int rc;
	struct cifs_ses *ses = sess_data->ses;
1529
	struct TCP_Server_Info *server = sess_data->server;
1530
	struct smb2_sess_setup_rsp *rsp = NULL;
1531
	unsigned char *ntlmssp_blob = NULL;
1532
	bool use_spnego = false; /* else use raw ntlmssp */
1533
	u16 blob_length = 0;
1534
	bool is_binding = false;
1535

1536 1537 1538 1539 1540
	/*
	 * If memory allocation is successful, caller of this function
	 * frees it.
	 */
	ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL);
1541 1542 1543 1544
	if (!ses->ntlmssp) {
		rc = -ENOMEM;
		goto out_err;
	}
1545
	ses->ntlmssp->sesskey_per_smbsess = true;
1546

1547
	rc = SMB2_sess_alloc_buffer(sess_data);
1548
	if (rc)
1549
		goto out_err;
1550

1551
	rc = build_ntlmssp_smb3_negotiate_blob(&ntlmssp_blob,
1552
					  &blob_length, ses, server,
1553 1554
					  sess_data->nls_cp);
	if (rc)
1555
		goto out;
1556

1557 1558 1559 1560 1561 1562 1563 1564
	if (use_spnego) {
		/* BB eventually need to add this */
		cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
		rc = -EOPNOTSUPP;
		goto out;
	}
	sess_data->iov[1].iov_base = ntlmssp_blob;
	sess_data->iov[1].iov_len = blob_length;
1565

1566 1567
	rc = SMB2_sess_sendreceive(sess_data);
	rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1568

1569 1570
	/* If true, rc here is expected and not an error */
	if (sess_data->buf0_type != CIFS_NO_BUFFER &&
1571
		rsp->hdr.Status == STATUS_MORE_PROCESSING_REQUIRED)
1572
		rc = 0;
1573

1574 1575
	if (rc)
		goto out;
1576

1577
	if (offsetof(struct smb2_sess_setup_rsp, Buffer) !=
1578 1579 1580
			le16_to_cpu(rsp->SecurityBufferOffset)) {
		cifs_dbg(VFS, "Invalid security buffer offset %d\n",
			le16_to_cpu(rsp->SecurityBufferOffset));
1581
		rc = -EIO;
1582
		goto out;
1583
	}
1584 1585 1586 1587
	rc = decode_ntlmssp_challenge(rsp->Buffer,
			le16_to_cpu(rsp->SecurityBufferLength), ses);
	if (rc)
		goto out;
1588

1589
	cifs_dbg(FYI, "rawntlmssp session setup challenge phase\n");
1590

1591 1592 1593
	spin_lock(&ses->ses_lock);
	is_binding = (ses->ses_status == SES_GOOD);
	spin_unlock(&ses->ses_lock);
1594

1595
	/* keep existing ses id and flags if binding */
1596
	if (!is_binding) {
1597
		ses->Suid = le64_to_cpu(rsp->hdr.SessionId);
1598 1599
		ses->session_flags = le16_to_cpu(rsp->SessionFlags);
	}
1600 1601

out:
1602
	kfree_sensitive(ntlmssp_blob);
1603 1604 1605 1606 1607 1608 1609
	SMB2_sess_free_buffer(sess_data);
	if (!rc) {
		sess_data->result = 0;
		sess_data->func = SMB2_sess_auth_rawntlmssp_authenticate;
		return;
	}
out_err:
1610
	kfree_sensitive(ses->ntlmssp);
1611 1612 1613 1614
	ses->ntlmssp = NULL;
	sess_data->result = rc;
	sess_data->func = NULL;
}
1615

1616 1617 1618 1619 1620
static void
SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data)
{
	int rc;
	struct cifs_ses *ses = sess_data->ses;
1621
	struct TCP_Server_Info *server = sess_data->server;
1622 1623 1624 1625 1626
	struct smb2_sess_setup_req *req;
	struct smb2_sess_setup_rsp *rsp = NULL;
	unsigned char *ntlmssp_blob = NULL;
	bool use_spnego = false; /* else use raw ntlmssp */
	u16 blob_length = 0;
1627
	bool is_binding = false;
1628

1629 1630 1631
	rc = SMB2_sess_alloc_buffer(sess_data);
	if (rc)
		goto out;
1632

1633
	req = (struct smb2_sess_setup_req *) sess_data->iov[0].iov_base;
1634
	req->hdr.SessionId = cpu_to_le64(ses->Suid);
1635

1636 1637 1638
	rc = build_ntlmssp_auth_blob(&ntlmssp_blob, &blob_length,
				     ses, server,
				     sess_data->nls_cp);
1639 1640 1641
	if (rc) {
		cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n", rc);
		goto out;
1642 1643
	}

1644 1645 1646 1647 1648 1649 1650 1651
	if (use_spnego) {
		/* BB eventually need to add this */
		cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
		rc = -EOPNOTSUPP;
		goto out;
	}
	sess_data->iov[1].iov_base = ntlmssp_blob;
	sess_data->iov[1].iov_len = blob_length;
1652

1653 1654 1655 1656 1657 1658
	rc = SMB2_sess_sendreceive(sess_data);
	if (rc)
		goto out;

	rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;

1659 1660 1661
	spin_lock(&ses->ses_lock);
	is_binding = (ses->ses_status == SES_GOOD);
	spin_unlock(&ses->ses_lock);
1662

1663
	/* keep existing ses id and flags if binding */
1664
	if (!is_binding) {
1665
		ses->Suid = le64_to_cpu(rsp->hdr.SessionId);
1666 1667
		ses->session_flags = le16_to_cpu(rsp->SessionFlags);
	}
1668

1669
	rc = SMB2_sess_establish_session(sess_data);
1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
#ifdef CONFIG_CIFS_DEBUG_DUMP_KEYS
	if (ses->server->dialect < SMB30_PROT_ID) {
		cifs_dbg(VFS, "%s: dumping generated SMB2 session keys\n", __func__);
		/*
		 * The session id is opaque in terms of endianness, so we can't
		 * print it as a long long. we dump it as we got it on the wire
		 */
		cifs_dbg(VFS, "Session Id    %*ph\n", (int)sizeof(ses->Suid),
			 &ses->Suid);
		cifs_dbg(VFS, "Session Key   %*ph\n",
			 SMB2_NTLMV2_SESSKEY_SIZE, ses->auth_key.response);
		cifs_dbg(VFS, "Signing Key   %*ph\n",
			 SMB3_SIGN_KEY_SIZE, ses->auth_key.response);
	}
#endif
1685
out:
1686
	kfree_sensitive(ntlmssp_blob);
1687
	SMB2_sess_free_buffer(sess_data);
1688
	kfree_sensitive(ses->ntlmssp);
1689 1690 1691 1692
	ses->ntlmssp = NULL;
	sess_data->result = rc;
	sess_data->func = NULL;
}
1693

1694
static int
1695
SMB2_select_sec(struct SMB2_sess_data *sess_data)
1696
{
1697
	int type;
1698 1699
	struct cifs_ses *ses = sess_data->ses;
	struct TCP_Server_Info *server = sess_data->server;
1700

1701
	type = smb2_select_sectype(server, ses->sectype);
1702 1703
	cifs_dbg(FYI, "sess setup type %d\n", type);
	if (type == Unspecified) {
1704
		cifs_dbg(VFS, "Unable to select appropriate authentication method!\n");
1705 1706
		return -EINVAL;
	}
1707

1708
	switch (type) {
1709 1710 1711 1712 1713 1714 1715
	case Kerberos:
		sess_data->func = SMB2_auth_kerberos;
		break;
	case RawNTLMSSP:
		sess_data->func = SMB2_sess_auth_rawntlmssp_negotiate;
		break;
	default:
1716
		cifs_dbg(VFS, "secType %d not supported!\n", type);
1717
		return -EOPNOTSUPP;
1718 1719
	}

1720 1721 1722 1723 1724
	return 0;
}

int
SMB2_sess_setup(const unsigned int xid, struct cifs_ses *ses,
1725
		struct TCP_Server_Info *server,
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
		const struct nls_table *nls_cp)
{
	int rc = 0;
	struct SMB2_sess_data *sess_data;

	cifs_dbg(FYI, "Session Setup\n");

	if (!server) {
		WARN(1, "%s: server is NULL!\n", __func__);
		return -EIO;
1736 1737
	}

1738 1739 1740 1741 1742 1743
	sess_data = kzalloc(sizeof(struct SMB2_sess_data), GFP_KERNEL);
	if (!sess_data)
		return -ENOMEM;

	sess_data->xid = xid;
	sess_data->ses = ses;
1744
	sess_data->server = server;
1745 1746
	sess_data->buf0_type = CIFS_NO_BUFFER;
	sess_data->nls_cp = (struct nls_table *) nls_cp;
1747
	sess_data->previous_session = ses->Suid;
1748

1749 1750 1751 1752
	rc = SMB2_select_sec(sess_data);
	if (rc)
		goto out;

1753 1754 1755
	/*
	 * Initialize the session hash with the server one.
	 */
1756
	memcpy(ses->preauth_sha_hash, server->preauth_sha_hash,
1757 1758
	       SMB2_PREAUTH_HASH_SIZE);

1759 1760 1761
	while (sess_data->func)
		sess_data->func(sess_data);

1762
	if ((ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST) && (ses->sign))
1763
		cifs_server_dbg(VFS, "signing requested but authenticated as guest\n");
1764
	rc = sess_data->result;
1765
out:
1766
	kfree_sensitive(sess_data);
1767 1768 1769 1770 1771 1772
	return rc;
}

int
SMB2_logoff(const unsigned int xid, struct cifs_ses *ses)
{
1773
	struct smb_rqst rqst;
1774 1775 1776
	struct smb2_logoff_req *req; /* response is also trivial struct */
	int rc = 0;
	struct TCP_Server_Info *server;
1777
	int flags = 0;
1778 1779 1780 1781
	unsigned int total_len;
	struct kvec iov[1];
	struct kvec rsp_iov;
	int resp_buf_type;
1782

1783
	cifs_dbg(FYI, "disconnect session %p\n", ses);
1784 1785 1786 1787 1788 1789

	if (ses && (ses->server))
		server = ses->server;
	else
		return -EIO;

1790
	/* no need to send SMB logoff if uid already closed due to reconnect */
1791 1792 1793
	spin_lock(&ses->chan_lock);
	if (CIFS_ALL_CHANS_NEED_RECONNECT(ses)) {
		spin_unlock(&ses->chan_lock);
1794
		goto smb2_session_already_dead;
1795 1796
	}
	spin_unlock(&ses->chan_lock);
1797

1798 1799
	rc = smb2_plain_req_init(SMB2_LOGOFF, NULL, ses->server,
				 (void **) &req, &total_len);
1800 1801 1802 1803
	if (rc)
		return rc;

	 /* since no tcon, smb2_init can not do this, so do here */
1804
	req->hdr.SessionId = cpu_to_le64(ses->Suid);
1805 1806 1807 1808

	if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA)
		flags |= CIFS_TRANSFORM_REQ;
	else if (server->sign)
1809
		req->hdr.Flags |= SMB2_FLAGS_SIGNED;
1810

1811
	flags |= CIFS_NO_RSP_BUF;
1812 1813 1814

	iov[0].iov_base = (char *)req;
	iov[0].iov_len = total_len;
1815

1816 1817 1818 1819
	memset(&rqst, 0, sizeof(struct smb_rqst));
	rqst.rq_iov = iov;
	rqst.rq_nvec = 1;

1820 1821
	rc = cifs_send_recv(xid, ses, ses->server,
			    &rqst, &resp_buf_type, flags, &rsp_iov);
1822
	cifs_small_buf_release(req);
1823 1824 1825 1826
	/*
	 * No tcon so can't do
	 * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
	 */
1827 1828

smb2_session_already_dead:
1829 1830
	return rc;
}
1831 1832 1833

static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code)
{
1834
	cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]);
1835 1836 1837 1838
}

#define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */)

Steve French's avatar
Steve French committed
1839 1840 1841 1842 1843 1844 1845 1846
/* These are similar values to what Windows uses */
static inline void init_copy_chunk_defaults(struct cifs_tcon *tcon)
{
	tcon->max_chunks = 256;
	tcon->max_bytes_chunk = 1048576;
	tcon->max_bytes_copy = 16777216;
}

1847 1848 1849 1850
int
SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
	  struct cifs_tcon *tcon, const struct nls_table *cp)
{
1851
	struct smb_rqst rqst;
1852 1853 1854
	struct smb2_tree_connect_req *req;
	struct smb2_tree_connect_rsp *rsp = NULL;
	struct kvec iov[2];
1855
	struct kvec rsp_iov = { NULL, 0 };
1856 1857 1858 1859
	int rc = 0;
	int resp_buftype;
	int unc_path_len;
	__le16 *unc_path = NULL;
1860
	int flags = 0;
1861
	unsigned int total_len;
1862 1863 1864 1865
	struct TCP_Server_Info *server;

	/* always use master channel */
	server = ses->server;
1866

1867
	cifs_dbg(FYI, "TCON\n");
1868

1869
	if (!server || !tree)
1870 1871 1872 1873 1874 1875
		return -EIO;

	unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
	if (unc_path == NULL)
		return -ENOMEM;

1876 1877
	unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp);
	if (unc_path_len <= 0) {
1878 1879 1880
		kfree(unc_path);
		return -EINVAL;
	}
1881
	unc_path_len *= 2;
1882

1883
	/* SMB2 TREE_CONNECT request must be called with TreeId == 0 */
1884
	tcon->tid = 0;
1885
	atomic_set(&tcon->num_remote_opens, 0);
1886 1887
	rc = smb2_plain_req_init(SMB2_TREE_CONNECT, tcon, server,
				 (void **) &req, &total_len);
1888 1889 1890 1891 1892
	if (rc) {
		kfree(unc_path);
		return rc;
	}

1893
	if (smb3_encryption_required(tcon))
1894
		flags |= CIFS_TRANSFORM_REQ;
1895 1896

	iov[0].iov_base = (char *)req;
1897 1898
	/* 1 for pad */
	iov[0].iov_len = total_len - 1;
1899 1900

	/* Testing shows that buffer offset must be at location of Buffer[0] */
1901
	req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req));
1902
	req->PathLength = cpu_to_le16(unc_path_len);
1903 1904 1905
	iov[1].iov_base = unc_path;
	iov[1].iov_len = unc_path_len;

1906 1907 1908
	/*
	 * 3.11 tcon req must be signed if not encrypted. See MS-SMB2 3.2.4.1.1
	 * unless it is guest or anonymous user. See MS-SMB2 3.2.5.3.1
1909
	 * (Samba servers don't always set the flag so also check if null user)
1910
	 */
1911
	if ((server->dialect == SMB311_PROT_ID) &&
1912
	    !smb3_encryption_required(tcon) &&
1913 1914 1915
	    !(ses->session_flags &
		    (SMB2_SESSION_FLAG_IS_GUEST|SMB2_SESSION_FLAG_IS_NULL)) &&
	    ((ses->user_name != NULL) || (ses->sectype == Kerberos)))
1916
		req->hdr.Flags |= SMB2_FLAGS_SIGNED;
1917

1918 1919 1920 1921
	memset(&rqst, 0, sizeof(struct smb_rqst));
	rqst.rq_iov = iov;
	rqst.rq_nvec = 2;

1922
	/* Need 64 for max size write so ask for more in case not there yet */
1923 1924 1925 1926 1927 1928
	if (server->credits >= server->max_credits)
		req->hdr.CreditRequest = cpu_to_le16(0);
	else
		req->hdr.CreditRequest = cpu_to_le16(
			min_t(int, server->max_credits -
			      server->credits, 64));
1929

1930 1931
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
1932 1933
	cifs_small_buf_release(req);
	rsp = (struct smb2_tree_connect_rsp *)rsp_iov.iov_base;
1934
	trace_smb3_tcon(xid, tcon->tid, ses->Suid, tree, rc);
1935
	if ((rc != 0) || (rsp == NULL)) {
Steve French's avatar
Steve French committed
1936 1937
		cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
		tcon->need_reconnect = true;
1938 1939 1940
		goto tcon_error_exit;
	}

1941 1942
	switch (rsp->ShareType) {
	case SMB2_SHARE_TYPE_DISK:
1943
		cifs_dbg(FYI, "connection to disk share\n");
1944 1945
		break;
	case SMB2_SHARE_TYPE_PIPE:
1946
		tcon->pipe = true;
1947
		cifs_dbg(FYI, "connection to pipe share\n");
1948 1949
		break;
	case SMB2_SHARE_TYPE_PRINT:
1950
		tcon->print = true;
1951
		cifs_dbg(FYI, "connection to printer\n");
1952 1953
		break;
	default:
1954
		cifs_server_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
1955 1956 1957 1958 1959
		rc = -EOPNOTSUPP;
		goto tcon_error_exit;
	}

	tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
1960
	tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
1961
	tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1962
	tcon->tid = le32_to_cpu(rsp->hdr.Id.SyncId.TreeId);
1963
	strscpy(tcon->tree_name, tree, sizeof(tcon->tree_name));
1964 1965 1966

	if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
	    ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
1967
		cifs_tcon_dbg(VFS, "DFS capability contradicts DFS flag\n");
1968 1969

	if (tcon->seal &&
1970
	    !(server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
1971
		cifs_tcon_dbg(VFS, "Encryption is requested but not supported\n");
1972

Steve French's avatar
Steve French committed
1973
	init_copy_chunk_defaults(tcon);
1974 1975
	if (server->ops->validate_negotiate)
		rc = server->ops->validate_negotiate(xid, tcon);
1976 1977 1978
	if (rc == 0) /* See MS-SMB2 2.2.10 and 3.2.5.5 */
		if (tcon->share_flags & SMB2_SHAREFLAG_ISOLATED_TRANSPORT)
			server->nosharesock = true;
1979
tcon_exit:
1980

1981 1982 1983 1984 1985
	free_rsp_buf(resp_buftype, rsp);
	kfree(unc_path);
	return rc;

tcon_error_exit:
1986
	if (rsp && rsp->hdr.Status == STATUS_BAD_NETWORK_NAME)
1987
		cifs_tcon_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree);
1988 1989 1990 1991 1992 1993
	goto tcon_exit;
}

int
SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon)
{
1994
	struct smb_rqst rqst;
1995 1996 1997
	struct smb2_tree_disconnect_req *req; /* response is trivial */
	int rc = 0;
	struct cifs_ses *ses = tcon->ses;
1998
	int flags = 0;
1999 2000 2001 2002
	unsigned int total_len;
	struct kvec iov[1];
	struct kvec rsp_iov;
	int resp_buf_type;
2003

2004
	cifs_dbg(FYI, "Tree Disconnect\n");
2005

2006
	if (!ses || !(ses->server))
2007 2008
		return -EIO;

2009
	trace_smb3_tdis_enter(xid, tcon->tid, ses->Suid, tcon->tree_name);
2010 2011 2012 2013
	spin_lock(&ses->chan_lock);
	if ((tcon->need_reconnect) ||
	    (CIFS_ALL_CHANS_NEED_RECONNECT(tcon->ses))) {
		spin_unlock(&ses->chan_lock);
2014
		return 0;
2015 2016
	}
	spin_unlock(&ses->chan_lock);
2017

2018
	invalidate_all_cached_dirs(tcon);
2019

2020 2021 2022
	rc = smb2_plain_req_init(SMB2_TREE_DISCONNECT, tcon, ses->server,
				 (void **) &req,
				 &total_len);
2023 2024 2025
	if (rc)
		return rc;

2026
	if (smb3_encryption_required(tcon))
2027 2028
		flags |= CIFS_TRANSFORM_REQ;

2029
	flags |= CIFS_NO_RSP_BUF;
2030 2031 2032 2033

	iov[0].iov_base = (char *)req;
	iov[0].iov_len = total_len;

2034 2035 2036 2037
	memset(&rqst, 0, sizeof(struct smb_rqst));
	rqst.rq_iov = iov;
	rqst.rq_nvec = 1;

2038 2039
	rc = cifs_send_recv(xid, ses, ses->server,
			    &rqst, &resp_buf_type, flags, &rsp_iov);
2040
	cifs_small_buf_release(req);
2041
	if (rc) {
2042
		cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE);
2043 2044 2045
		trace_smb3_tdis_err(xid, tcon->tid, ses->Suid, rc);
	}
	trace_smb3_tdis_done(xid, tcon->tid, ses->Suid);
2046 2047 2048

	return rc;
}
2049

Pavel Shilovsky's avatar
Pavel Shilovsky committed
2050

2051 2052 2053 2054 2055 2056 2057 2058 2059 2060
static struct create_durable *
create_durable_buf(void)
{
	struct create_durable *buf;

	buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
	if (!buf)
		return NULL;

	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2061
					(struct create_durable, Data));
2062 2063 2064 2065
	buf->ccontext.DataLength = cpu_to_le32(16);
	buf->ccontext.NameOffset = cpu_to_le16(offsetof
				(struct create_durable, Name));
	buf->ccontext.NameLength = cpu_to_le16(4);
2066
	/* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DHnQ" */
2067 2068 2069 2070 2071 2072 2073
	buf->Name[0] = 'D';
	buf->Name[1] = 'H';
	buf->Name[2] = 'n';
	buf->Name[3] = 'Q';
	return buf;
}

2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090
static struct create_durable *
create_reconnect_durable_buf(struct cifs_fid *fid)
{
	struct create_durable *buf;

	buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
	if (!buf)
		return NULL;

	buf->ccontext.DataOffset = cpu_to_le16(offsetof
					(struct create_durable, Data));
	buf->ccontext.DataLength = cpu_to_le32(16);
	buf->ccontext.NameOffset = cpu_to_le16(offsetof
				(struct create_durable, Name));
	buf->ccontext.NameLength = cpu_to_le16(4);
	buf->Data.Fid.PersistentFileId = fid->persistent_fid;
	buf->Data.Fid.VolatileFileId = fid->volatile_fid;
2091
	/* SMB2_CREATE_DURABLE_HANDLE_RECONNECT is "DHnC" */
2092 2093 2094 2095 2096 2097 2098
	buf->Name[0] = 'D';
	buf->Name[1] = 'H';
	buf->Name[2] = 'n';
	buf->Name[3] = 'C';
	return buf;
}

2099 2100 2101
static void
parse_query_id_ctxt(struct create_context *cc, struct smb2_file_all_info *buf)
{
2102
	struct create_disk_id_rsp *pdisk_id = (struct create_disk_id_rsp *)cc;
2103 2104 2105 2106 2107 2108

	cifs_dbg(FYI, "parse query id context 0x%llx 0x%llx\n",
		pdisk_id->DiskFileId, pdisk_id->VolumeId);
	buf->IndexNumber = pdisk_id->DiskFileId;
}

2109
static void
2110 2111
parse_posix_ctxt(struct create_context *cc, struct smb2_file_all_info *info,
		 struct create_posix_rsp *posix)
2112
{
2113 2114 2115 2116
	int sid_len;
	u8 *beg = (u8 *)cc + le16_to_cpu(cc->DataOffset);
	u8 *end = beg + le32_to_cpu(cc->DataLength);
	u8 *sid;
2117

2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138
	memset(posix, 0, sizeof(*posix));

	posix->nlink = le32_to_cpu(*(__le32 *)(beg + 0));
	posix->reparse_tag = le32_to_cpu(*(__le32 *)(beg + 4));
	posix->mode = le32_to_cpu(*(__le32 *)(beg + 8));

	sid = beg + 12;
	sid_len = posix_info_sid_size(sid, end);
	if (sid_len < 0) {
		cifs_dbg(VFS, "bad owner sid in posix create response\n");
		return;
	}
	memcpy(&posix->owner, sid, sid_len);

	sid = sid + sid_len;
	sid_len = posix_info_sid_size(sid, end);
	if (sid_len < 0) {
		cifs_dbg(VFS, "bad group sid in posix create response\n");
		return;
	}
	memcpy(&posix->group, sid, sid_len);
2139

2140 2141
	cifs_dbg(FYI, "nlink=%d mode=%o reparse_tag=%x\n",
		 posix->nlink, posix->mode, posix->reparse_tag);
2142 2143
}

2144 2145
void
smb2_parse_contexts(struct TCP_Server_Info *server,
2146 2147 2148 2149
		    struct smb2_create_rsp *rsp,
		    unsigned int *epoch, char *lease_key, __u8 *oplock,
		    struct smb2_file_all_info *buf,
		    struct create_posix_rsp *posix)
Pavel Shilovsky's avatar
Pavel Shilovsky committed
2150 2151
{
	char *data_offset;
2152
	struct create_context *cc;
2153 2154
	unsigned int next;
	unsigned int remaining;
2155
	char *name;
2156 2157 2158 2159 2160
	static const char smb3_create_tag_posix[] = {
		0x93, 0xAD, 0x25, 0x50, 0x9C,
		0xB4, 0x11, 0xE7, 0xB4, 0x23, 0x83,
		0xDE, 0x96, 0x8B, 0xCD, 0x7C
	};
Pavel Shilovsky's avatar
Pavel Shilovsky committed
2161

2162
	*oplock = 0;
2163
	data_offset = (char *)rsp + le32_to_cpu(rsp->CreateContextsOffset);
2164
	remaining = le32_to_cpu(rsp->CreateContextsLength);
2165
	cc = (struct create_context *)data_offset;
2166 2167 2168 2169 2170

	/* Initialize inode number to 0 in case no valid data in qfid context */
	if (buf)
		buf->IndexNumber = 0;

2171
	while (remaining >= sizeof(struct create_context)) {
2172
		name = le16_to_cpu(cc->NameOffset) + (char *)cc;
2173
		if (le16_to_cpu(cc->NameLength) == 4 &&
2174 2175 2176 2177 2178 2179
		    strncmp(name, SMB2_CREATE_REQUEST_LEASE, 4) == 0)
			*oplock = server->ops->parse_lease_buf(cc, epoch,
							   lease_key);
		else if (buf && (le16_to_cpu(cc->NameLength) == 4) &&
		    strncmp(name, SMB2_CREATE_QUERY_ON_DISK_ID, 4) == 0)
			parse_query_id_ctxt(cc, buf);
2180
		else if ((le16_to_cpu(cc->NameLength) == 16)) {
2181 2182 2183
			if (posix &&
			    memcmp(name, smb3_create_tag_posix, 16) == 0)
				parse_posix_ctxt(cc, buf, posix);
2184 2185 2186 2187 2188 2189
		}
		/* else {
			cifs_dbg(FYI, "Context not matched with len %d\n",
				le16_to_cpu(cc->NameLength));
			cifs_dump_mem("Cctxt name: ", name, 4);
		} */
2190 2191 2192 2193 2194 2195 2196

		next = le32_to_cpu(cc->Next);
		if (!next)
			break;
		remaining -= next;
		cc = (struct create_context *)((char *)cc + next);
	}
Pavel Shilovsky's avatar
Pavel Shilovsky committed
2197

2198 2199 2200 2201
	if (rsp->OplockLevel != SMB2_OPLOCK_LEVEL_LEASE)
		*oplock = rsp->OplockLevel;

	return;
Pavel Shilovsky's avatar
Pavel Shilovsky committed
2202 2203
}

2204
static int
2205 2206 2207
add_lease_context(struct TCP_Server_Info *server,
		  struct smb2_create_req *req,
		  struct kvec *iov,
2208
		  unsigned int *num_iovec, u8 *lease_key, __u8 *oplock)
2209 2210 2211
{
	unsigned int num = *num_iovec;

2212
	iov[num].iov_base = server->ops->create_lease_buf(lease_key, *oplock);
2213 2214
	if (iov[num].iov_base == NULL)
		return -ENOMEM;
2215
	iov[num].iov_len = server->vals->create_lease_size;
2216 2217 2218 2219 2220
	req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
	*num_iovec = num + 1;
	return 0;
}

2221
static struct create_durable_v2 *
2222
create_durable_v2_buf(struct cifs_open_parms *oparms)
2223
{
2224
	struct cifs_fid *pfid = oparms->fid;
2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237
	struct create_durable_v2 *buf;

	buf = kzalloc(sizeof(struct create_durable_v2), GFP_KERNEL);
	if (!buf)
		return NULL;

	buf->ccontext.DataOffset = cpu_to_le16(offsetof
					(struct create_durable_v2, dcontext));
	buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_context_v2));
	buf->ccontext.NameOffset = cpu_to_le16(offsetof
				(struct create_durable_v2, Name));
	buf->ccontext.NameLength = cpu_to_le16(4);

2238 2239 2240 2241 2242
	/*
	 * NB: Handle timeout defaults to 0, which allows server to choose
	 * (most servers default to 120 seconds) and most clients default to 0.
	 * This can be overridden at mount ("handletimeout=") if the user wants
	 * a different persistent (or resilient) handle timeout for all opens
2243
	 * on a particular SMB3 mount.
2244 2245
	 */
	buf->dcontext.Timeout = cpu_to_le32(oparms->tcon->handle_timeout);
2246
	buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2247
	generate_random_uuid(buf->dcontext.CreateGuid);
2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
	memcpy(pfid->create_guid, buf->dcontext.CreateGuid, 16);

	/* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DH2Q" */
	buf->Name[0] = 'D';
	buf->Name[1] = 'H';
	buf->Name[2] = '2';
	buf->Name[3] = 'Q';
	return buf;
}

static struct create_durable_handle_reconnect_v2 *
create_reconnect_durable_v2_buf(struct cifs_fid *fid)
{
	struct create_durable_handle_reconnect_v2 *buf;

	buf = kzalloc(sizeof(struct create_durable_handle_reconnect_v2),
			GFP_KERNEL);
	if (!buf)
		return NULL;

	buf->ccontext.DataOffset =
		cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
				     dcontext));
	buf->ccontext.DataLength =
		cpu_to_le32(sizeof(struct durable_reconnect_context_v2));
	buf->ccontext.NameOffset =
		cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
			    Name));
	buf->ccontext.NameLength = cpu_to_le16(4);

	buf->dcontext.Fid.PersistentFileId = fid->persistent_fid;
	buf->dcontext.Fid.VolatileFileId = fid->volatile_fid;
	buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
	memcpy(buf->dcontext.CreateGuid, fid->create_guid, 16);

	/* SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 is "DH2C" */
	buf->Name[0] = 'D';
	buf->Name[1] = 'H';
	buf->Name[2] = '2';
	buf->Name[3] = 'C';
	return buf;
}

2291
static int
2292 2293 2294 2295 2296
add_durable_v2_context(struct kvec *iov, unsigned int *num_iovec,
		    struct cifs_open_parms *oparms)
{
	unsigned int num = *num_iovec;

2297
	iov[num].iov_base = create_durable_v2_buf(oparms);
2298 2299 2300 2301 2302 2303 2304 2305 2306
	if (iov[num].iov_base == NULL)
		return -ENOMEM;
	iov[num].iov_len = sizeof(struct create_durable_v2);
	*num_iovec = num + 1;
	return 0;
}

static int
add_durable_reconnect_v2_context(struct kvec *iov, unsigned int *num_iovec,
2307
		    struct cifs_open_parms *oparms)
2308 2309 2310
{
	unsigned int num = *num_iovec;

2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335
	/* indicate that we don't need to relock the file */
	oparms->reconnect = false;

	iov[num].iov_base = create_reconnect_durable_v2_buf(oparms->fid);
	if (iov[num].iov_base == NULL)
		return -ENOMEM;
	iov[num].iov_len = sizeof(struct create_durable_handle_reconnect_v2);
	*num_iovec = num + 1;
	return 0;
}

static int
add_durable_context(struct kvec *iov, unsigned int *num_iovec,
		    struct cifs_open_parms *oparms, bool use_persistent)
{
	unsigned int num = *num_iovec;

	if (use_persistent) {
		if (oparms->reconnect)
			return add_durable_reconnect_v2_context(iov, num_iovec,
								oparms);
		else
			return add_durable_v2_context(iov, num_iovec, oparms);
	}

2336 2337 2338 2339 2340 2341
	if (oparms->reconnect) {
		iov[num].iov_base = create_reconnect_durable_buf(oparms->fid);
		/* indicate that we don't need to relock the file */
		oparms->reconnect = false;
	} else
		iov[num].iov_base = create_durable_buf();
2342 2343 2344 2345 2346 2347 2348
	if (iov[num].iov_base == NULL)
		return -ENOMEM;
	iov[num].iov_len = sizeof(struct create_durable);
	*num_iovec = num + 1;
	return 0;
}

2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387
/* See MS-SMB2 2.2.13.2.7 */
static struct crt_twarp_ctxt *
create_twarp_buf(__u64 timewarp)
{
	struct crt_twarp_ctxt *buf;

	buf = kzalloc(sizeof(struct crt_twarp_ctxt), GFP_KERNEL);
	if (!buf)
		return NULL;

	buf->ccontext.DataOffset = cpu_to_le16(offsetof
					(struct crt_twarp_ctxt, Timestamp));
	buf->ccontext.DataLength = cpu_to_le32(8);
	buf->ccontext.NameOffset = cpu_to_le16(offsetof
				(struct crt_twarp_ctxt, Name));
	buf->ccontext.NameLength = cpu_to_le16(4);
	/* SMB2_CREATE_TIMEWARP_TOKEN is "TWrp" */
	buf->Name[0] = 'T';
	buf->Name[1] = 'W';
	buf->Name[2] = 'r';
	buf->Name[3] = 'p';
	buf->Timestamp = cpu_to_le64(timewarp);
	return buf;
}

/* See MS-SMB2 2.2.13.2.7 */
static int
add_twarp_context(struct kvec *iov, unsigned int *num_iovec, __u64 timewarp)
{
	unsigned int num = *num_iovec;

	iov[num].iov_base = create_twarp_buf(timewarp);
	if (iov[num].iov_base == NULL)
		return -ENOMEM;
	iov[num].iov_len = sizeof(struct crt_twarp_ctxt);
	*num_iovec = num + 1;
	return 0;
}

2388
/* See http://technet.microsoft.com/en-us/library/hh509017(v=ws.10).aspx */
2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407
static void setup_owner_group_sids(char *buf)
{
	struct owner_group_sids *sids = (struct owner_group_sids *)buf;

	/* Populate the user ownership fields S-1-5-88-1 */
	sids->owner.Revision = 1;
	sids->owner.NumAuth = 3;
	sids->owner.Authority[5] = 5;
	sids->owner.SubAuthorities[0] = cpu_to_le32(88);
	sids->owner.SubAuthorities[1] = cpu_to_le32(1);
	sids->owner.SubAuthorities[2] = cpu_to_le32(current_fsuid().val);

	/* Populate the group ownership fields S-1-5-88-2 */
	sids->group.Revision = 1;
	sids->group.NumAuth = 3;
	sids->group.Authority[5] = 5;
	sids->group.SubAuthorities[0] = cpu_to_le32(88);
	sids->group.SubAuthorities[1] = cpu_to_le32(2);
	sids->group.SubAuthorities[2] = cpu_to_le32(current_fsgid().val);
2408 2409

	cifs_dbg(FYI, "owner S-1-5-88-1-%d, group S-1-5-88-2-%d\n", current_fsuid().val, current_fsgid().val);
2410 2411
}

2412 2413
/* See MS-SMB2 2.2.13.2.2 and MS-DTYP 2.4.6 */
static struct crt_sd_ctxt *
2414
create_sd_buf(umode_t mode, bool set_owner, unsigned int *len)
2415 2416
{
	struct crt_sd_ctxt *buf;
2417 2418
	__u8 *ptr, *aclptr;
	unsigned int acelen, acl_size, ace_count;
2419 2420
	unsigned int owner_offset = 0;
	unsigned int group_offset = 0;
2421
	struct smb3_acl acl = {};
2422

2423
	*len = round_up(sizeof(struct crt_sd_ctxt) + (sizeof(struct cifs_ace) * 4), 8);
2424 2425 2426 2427 2428

	if (set_owner) {
		/* sizeof(struct owner_group_sids) is already multiple of 8 so no need to round */
		*len += sizeof(struct owner_group_sids);
	}
2429 2430 2431 2432 2433

	buf = kzalloc(*len, GFP_KERNEL);
	if (buf == NULL)
		return buf;

2434
	ptr = (__u8 *)&buf[1];
2435
	if (set_owner) {
2436 2437
		/* offset fields are from beginning of security descriptor not of create context */
		owner_offset = ptr - (__u8 *)&buf->sd;
2438
		buf->sd.OffsetOwner = cpu_to_le32(owner_offset);
2439
		group_offset = owner_offset + offsetof(struct owner_group_sids, group);
2440
		buf->sd.OffsetGroup = cpu_to_le32(group_offset);
2441 2442 2443

		setup_owner_group_sids(ptr);
		ptr += sizeof(struct owner_group_sids);
2444 2445 2446 2447 2448
	} else {
		buf->sd.OffsetOwner = 0;
		buf->sd.OffsetGroup = 0;
	}

2449
	buf->ccontext.DataOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, sd));
2450
	buf->ccontext.NameOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, Name));
2451 2452 2453 2454 2455 2456 2457
	buf->ccontext.NameLength = cpu_to_le16(4);
	/* SMB2_CREATE_SD_BUFFER_TOKEN is "SecD" */
	buf->Name[0] = 'S';
	buf->Name[1] = 'e';
	buf->Name[2] = 'c';
	buf->Name[3] = 'D';
	buf->sd.Revision = 1;  /* Must be one see MS-DTYP 2.4.6 */
2458

2459 2460 2461 2462 2463 2464 2465
	/*
	 * ACL is "self relative" ie ACL is stored in contiguous block of memory
	 * and "DP" ie the DACL is present
	 */
	buf->sd.Control = cpu_to_le16(ACL_CONTROL_SR | ACL_CONTROL_DP);

	/* offset owner, group and Sbz1 and SACL are all zero */
2466 2467 2468
	buf->sd.OffsetDacl = cpu_to_le32(ptr - (__u8 *)&buf->sd);
	/* Ship the ACL for now. we will copy it into buf later. */
	aclptr = ptr;
2469
	ptr += sizeof(struct smb3_acl);
2470 2471

	/* create one ACE to hold the mode embedded in reserved special SID */
2472 2473 2474 2475
	acelen = setup_special_mode_ACE((struct cifs_ace *)ptr, (__u64)mode);
	ptr += acelen;
	acl_size = acelen + sizeof(struct smb3_acl);
	ace_count = 1;
2476 2477 2478

	if (set_owner) {
		/* we do not need to reallocate buffer to add the two more ACEs. plenty of space */
2479 2480 2481 2482 2483
		acelen = setup_special_user_owner_ACE((struct cifs_ace *)ptr);
		ptr += acelen;
		acl_size += acelen;
		ace_count += 1;
	}
2484

2485
	/* and one more ACE to allow access for authenticated users */
2486 2487 2488 2489 2490 2491 2492 2493
	acelen = setup_authusers_ACE((struct cifs_ace *)ptr);
	ptr += acelen;
	acl_size += acelen;
	ace_count += 1;

	acl.AclRevision = ACL_REVISION; /* See 2.4.4.1 of MS-DTYP */
	acl.AclSize = cpu_to_le16(acl_size);
	acl.AceCount = cpu_to_le16(ace_count);
2494
	/* acl.Sbz1 and Sbz2 MBZ so are not set here, but initialized above */
2495
	memcpy(aclptr, &acl, sizeof(struct smb3_acl));
2496 2497

	buf->ccontext.DataLength = cpu_to_le32(ptr - (__u8 *)&buf->sd);
2498
	*len = round_up((unsigned int)(ptr - (__u8 *)buf), 8);
2499

2500 2501 2502 2503
	return buf;
}

static int
2504
add_sd_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode, bool set_owner)
2505 2506 2507 2508
{
	unsigned int num = *num_iovec;
	unsigned int len = 0;

2509
	iov[num].iov_base = create_sd_buf(mode, set_owner, &len);
2510 2511 2512 2513 2514 2515 2516
	if (iov[num].iov_base == NULL)
		return -ENOMEM;
	iov[num].iov_len = len;
	*num_iovec = num + 1;
	return 0;
}

2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552
static struct crt_query_id_ctxt *
create_query_id_buf(void)
{
	struct crt_query_id_ctxt *buf;

	buf = kzalloc(sizeof(struct crt_query_id_ctxt), GFP_KERNEL);
	if (!buf)
		return NULL;

	buf->ccontext.DataOffset = cpu_to_le16(0);
	buf->ccontext.DataLength = cpu_to_le32(0);
	buf->ccontext.NameOffset = cpu_to_le16(offsetof
				(struct crt_query_id_ctxt, Name));
	buf->ccontext.NameLength = cpu_to_le16(4);
	/* SMB2_CREATE_QUERY_ON_DISK_ID is "QFid" */
	buf->Name[0] = 'Q';
	buf->Name[1] = 'F';
	buf->Name[2] = 'i';
	buf->Name[3] = 'd';
	return buf;
}

/* See MS-SMB2 2.2.13.2.9 */
static int
add_query_id_context(struct kvec *iov, unsigned int *num_iovec)
{
	unsigned int num = *num_iovec;

	iov[num].iov_base = create_query_id_buf();
	if (iov[num].iov_base == NULL)
		return -ENOMEM;
	iov[num].iov_len = sizeof(struct crt_query_id_ctxt);
	*num_iovec = num + 1;
	return 0;
}

2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572
static int
alloc_path_with_tree_prefix(__le16 **out_path, int *out_size, int *out_len,
			    const char *treename, const __le16 *path)
{
	int treename_len, path_len;
	struct nls_table *cp;
	const __le16 sep[] = {cpu_to_le16('\\'), cpu_to_le16(0x0000)};

	/*
	 * skip leading "\\"
	 */
	treename_len = strlen(treename);
	if (treename_len < 2 || !(treename[0] == '\\' && treename[1] == '\\'))
		return -EINVAL;

	treename += 2;
	treename_len -= 2;

	path_len = UniStrnlen((wchar_t *)path, PATH_MAX);

2573 2574
	/* make room for one path separator only if @path isn't empty */
	*out_len = treename_len + (path[0] ? 1 : 0) + path_len;
2575 2576

	/*
2577 2578
	 * final path needs to be 8-byte aligned as specified in
	 * MS-SMB2 2.2.13 SMB2 CREATE Request.
2579
	 */
2580
	*out_size = round_up(*out_len * sizeof(__le16), 8);
2581
	*out_path = kzalloc(*out_size + sizeof(__le16) /* null */, GFP_KERNEL);
2582 2583 2584 2585 2586
	if (!*out_path)
		return -ENOMEM;

	cp = load_nls_default();
	cifs_strtoUTF16(*out_path, treename, treename_len, cp);
2587 2588 2589

	/* Do not append the separator if the path is empty */
	if (path[0] != cpu_to_le16(0x0000)) {
2590 2591
		UniStrcat((wchar_t *)*out_path, (wchar_t *)sep);
		UniStrcat((wchar_t *)*out_path, (wchar_t *)path);
2592 2593
	}

2594 2595 2596 2597 2598
	unload_nls(cp);

	return 0;
}

2599 2600 2601 2602 2603 2604 2605
int 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)
{
	struct smb_rqst rqst;
	struct smb2_create_req *req;
2606
	struct smb2_create_rsp *rsp = NULL;
2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619
	struct cifs_ses *ses = tcon->ses;
	struct kvec iov[3]; /* make sure at least one for each open context */
	struct kvec rsp_iov = {NULL, 0};
	int resp_buftype;
	int uni_path_len;
	__le16 *copy_path = NULL;
	int copy_size;
	int rc = 0;
	unsigned int n_iov = 2;
	__u32 file_attributes = 0;
	char *pc_buf = NULL;
	int flags = 0;
	unsigned int total_len;
2620
	__le16 *utf16_path = NULL;
2621
	struct TCP_Server_Info *server = cifs_pick_channel(ses);
2622 2623 2624

	cifs_dbg(FYI, "mkdir\n");

2625 2626 2627 2628 2629
	/* resource #1: path allocation */
	utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
	if (!utf16_path)
		return -ENOMEM;

2630
	if (!ses || !server) {
2631 2632 2633
		rc = -EIO;
		goto err_free_path;
	}
2634

2635
	/* resource #2: request */
2636 2637
	rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
				 (void **) &req, &total_len);
2638
	if (rc)
2639 2640
		goto err_free_path;

2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669

	if (smb3_encryption_required(tcon))
		flags |= CIFS_TRANSFORM_REQ;

	req->ImpersonationLevel = IL_IMPERSONATION;
	req->DesiredAccess = cpu_to_le32(FILE_WRITE_ATTRIBUTES);
	/* File attributes ignored on open (used in create though) */
	req->FileAttributes = cpu_to_le32(file_attributes);
	req->ShareAccess = FILE_SHARE_ALL_LE;
	req->CreateDisposition = cpu_to_le32(FILE_CREATE);
	req->CreateOptions = cpu_to_le32(CREATE_NOT_FILE);

	iov[0].iov_base = (char *)req;
	/* -1 since last byte is buf[0] which is sent below (path) */
	iov[0].iov_len = total_len - 1;

	req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));

	/* [MS-SMB2] 2.2.13 NameOffset:
	 * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
	 * the SMB2 header, the file name includes a prefix that will
	 * be processed during DFS name normalization as specified in
	 * section 3.3.5.9. Otherwise, the file name is relative to
	 * the share that is identified by the TreeId in the SMB2
	 * header.
	 */
	if (tcon->share_flags & SHI1005_FLAGS_DFS) {
		int name_len;

2670
		req->hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
2671 2672
		rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
						 &name_len,
2673
						 tcon->tree_name, utf16_path);
2674 2675 2676
		if (rc)
			goto err_free_req;

2677 2678
		req->NameLength = cpu_to_le16(name_len * 2);
		uni_path_len = copy_size;
2679 2680 2681
		/* free before overwriting resource */
		kfree(utf16_path);
		utf16_path = copy_path;
2682
	} else {
2683
		uni_path_len = (2 * UniStrnlen((wchar_t *)utf16_path, PATH_MAX)) + 2;
2684 2685 2686 2687 2688 2689
		/* MUST set path len (NameLength) to 0 opening root of share */
		req->NameLength = cpu_to_le16(uni_path_len - 2);
		if (uni_path_len % 8 != 0) {
			copy_size = roundup(uni_path_len, 8);
			copy_path = kzalloc(copy_size, GFP_KERNEL);
			if (!copy_path) {
2690 2691
				rc = -ENOMEM;
				goto err_free_req;
2692
			}
2693
			memcpy((char *)copy_path, (const char *)utf16_path,
2694 2695
			       uni_path_len);
			uni_path_len = copy_size;
2696 2697 2698
			/* free before overwriting resource */
			kfree(utf16_path);
			utf16_path = copy_path;
2699 2700 2701 2702
		}
	}

	iov[1].iov_len = uni_path_len;
2703
	iov[1].iov_base = utf16_path;
2704 2705 2706
	req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_NONE;

	if (tcon->posix_extensions) {
2707
		/* resource #3: posix buf */
2708
		rc = add_posix_context(iov, &n_iov, mode);
2709 2710
		if (rc)
			goto err_free_req;
2711 2712 2713
		req->CreateContextsOffset = cpu_to_le32(
			sizeof(struct smb2_create_req) +
			iov[1].iov_len);
2714 2715 2716 2717 2718 2719 2720 2721
		pc_buf = iov[n_iov-1].iov_base;
	}


	memset(&rqst, 0, sizeof(struct smb_rqst));
	rqst.rq_iov = iov;
	rqst.rq_nvec = n_iov;

2722
	/* no need to inc num_remote_opens because we close it just below */
2723
	trace_smb3_posix_mkdir_enter(xid, tcon->tid, ses->Suid, full_path, CREATE_NOT_FILE,
2724
				    FILE_WRITE_ATTRIBUTES);
2725
	/* resource #4: response buffer */
2726 2727
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
2728
	if (rc) {
2729 2730
		cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
		trace_smb3_posix_mkdir_err(xid, tcon->tid, ses->Suid,
2731 2732 2733 2734 2735
					   CREATE_NOT_FILE,
					   FILE_WRITE_ATTRIBUTES, rc);
		goto err_free_rsp_buf;
	}

2736 2737 2738 2739 2740
	/*
	 * Although unlikely to be possible for rsp to be null and rc not set,
	 * adding check below is slightly safer long term (and quiets Coverity
	 * warning)
	 */
2741
	rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
2742 2743 2744 2745 2746 2747
	if (rsp == NULL) {
		rc = -EIO;
		kfree(pc_buf);
		goto err_free_req;
	}

2748 2749
	trace_smb3_posix_mkdir_done(xid, rsp->PersistentFileId, tcon->tid, ses->Suid,
				    CREATE_NOT_FILE, FILE_WRITE_ATTRIBUTES);
2750

2751
	SMB2_close(xid, tcon, rsp->PersistentFileId, rsp->VolatileFileId);
2752 2753 2754

	/* Eventually save off posix specific response info and timestaps */

2755
err_free_rsp_buf:
2756
	free_rsp_buf(resp_buftype, rsp);
2757 2758 2759 2760 2761
	kfree(pc_buf);
err_free_req:
	cifs_small_buf_release(req);
err_free_path:
	kfree(utf16_path);
2762 2763 2764
	return rc;
}

2765
int
2766 2767
SMB2_open_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
	       struct smb_rqst *rqst, __u8 *oplock,
2768
	       struct cifs_open_parms *oparms, __le16 *path)
2769 2770
{
	struct smb2_create_req *req;
2771
	unsigned int n_iov = 2;
2772
	__u32 file_attributes = 0;
2773 2774
	int copy_size;
	int uni_path_len;
2775
	unsigned int total_len;
2776 2777 2778
	struct kvec *iov = rqst->rq_iov;
	__le16 *copy_path;
	int rc;
2779

2780 2781
	rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
				 (void **) &req, &total_len);
2782 2783 2784
	if (rc)
		return rc;

2785 2786 2787
	iov[0].iov_base = (char *)req;
	/* -1 since last byte is buf[0] which is sent below (path) */
	iov[0].iov_len = total_len - 1;
2788

2789
	if (oparms->create_options & CREATE_OPTION_READONLY)
2790
		file_attributes |= ATTR_READONLY;
2791 2792
	if (oparms->create_options & CREATE_OPTION_SPECIAL)
		file_attributes |= ATTR_SYSTEM;
2793

2794
	req->ImpersonationLevel = IL_IMPERSONATION;
2795
	req->DesiredAccess = cpu_to_le32(oparms->desired_access);
2796 2797 2798
	/* File attributes ignored on open (used in create though) */
	req->FileAttributes = cpu_to_le32(file_attributes);
	req->ShareAccess = FILE_SHARE_ALL_LE;
2799

2800 2801
	req->CreateDisposition = cpu_to_le32(oparms->disposition);
	req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK);
2802
	req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814

	/* [MS-SMB2] 2.2.13 NameOffset:
	 * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
	 * the SMB2 header, the file name includes a prefix that will
	 * be processed during DFS name normalization as specified in
	 * section 3.3.5.9. Otherwise, the file name is relative to
	 * the share that is identified by the TreeId in the SMB2
	 * header.
	 */
	if (tcon->share_flags & SHI1005_FLAGS_DFS) {
		int name_len;

2815
		req->hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
2816 2817
		rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
						 &name_len,
2818
						 tcon->tree_name, path);
2819
		if (rc)
2820 2821
			return rc;
		req->NameLength = cpu_to_le16(name_len * 2);
2822 2823
		uni_path_len = copy_size;
		path = copy_path;
2824 2825 2826 2827
	} else {
		uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
		/* MUST set path len (NameLength) to 0 opening root of share */
		req->NameLength = cpu_to_le16(uni_path_len - 2);
2828
		copy_size = round_up(uni_path_len, 8);
2829 2830 2831 2832 2833 2834 2835
		copy_path = kzalloc(copy_size, GFP_KERNEL);
		if (!copy_path)
			return -ENOMEM;
		memcpy((char *)copy_path, (const char *)path,
		       uni_path_len);
		uni_path_len = copy_size;
		path = copy_path;
2836 2837
	}

2838 2839 2840
	iov[1].iov_len = uni_path_len;
	iov[1].iov_base = path;

2841
	if ((!server->oplocks) || (tcon->no_lease))
Pavel Shilovsky's avatar
Pavel Shilovsky committed
2842 2843
		*oplock = SMB2_OPLOCK_LEVEL_NONE;

2844
	if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) ||
Pavel Shilovsky's avatar
Pavel Shilovsky committed
2845 2846
	    *oplock == SMB2_OPLOCK_LEVEL_NONE)
		req->RequestedOplockLevel = *oplock;
2847 2848 2849
	else if (!(server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING) &&
		  (oparms->create_options & CREATE_NOT_FILE))
		req->RequestedOplockLevel = *oplock; /* no srv lease support */
Pavel Shilovsky's avatar
Pavel Shilovsky committed
2850
	else {
2851
		rc = add_lease_context(server, req, iov, &n_iov,
2852
				       oparms->fid->lease_key, oplock);
2853
		if (rc)
2854
			return rc;
Pavel Shilovsky's avatar
Pavel Shilovsky committed
2855 2856
	}

2857
	if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) {
2858
		rc = add_durable_context(iov, &n_iov, oparms,
2859
					tcon->use_persistent);
2860
		if (rc)
2861 2862 2863
			return rc;
	}

2864 2865
	if (tcon->posix_extensions) {
		rc = add_posix_context(iov, &n_iov, oparms->mode);
2866
		if (rc)
2867 2868 2869
			return rc;
	}

2870 2871 2872 2873 2874 2875 2876
	if (tcon->snapshot_time) {
		cifs_dbg(FYI, "adding snapshot context\n");
		rc = add_twarp_context(iov, &n_iov, tcon->snapshot_time);
		if (rc)
			return rc;
	}

2877 2878 2879 2880 2881 2882 2883 2884 2885 2886
	if ((oparms->disposition != FILE_OPEN) && (oparms->cifs_sb)) {
		bool set_mode;
		bool set_owner;

		if ((oparms->cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MODE_FROM_SID) &&
		    (oparms->mode != ACL_NO_MODE))
			set_mode = true;
		else {
			set_mode = false;
			oparms->mode = ACL_NO_MODE;
2887 2888
		}

2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899
		if (oparms->cifs_sb->mnt_cifs_flags & CIFS_MOUNT_UID_FROM_ACL)
			set_owner = true;
		else
			set_owner = false;

		if (set_owner | set_mode) {
			cifs_dbg(FYI, "add sd with mode 0x%x\n", oparms->mode);
			rc = add_sd_context(iov, &n_iov, oparms->mode, set_owner);
			if (rc)
				return rc;
		}
2900 2901
	}

2902
	add_query_id_context(iov, &n_iov);
2903

2904 2905 2906 2907 2908 2909 2910 2911
	if (n_iov > 2) {
		/*
		 * We have create contexts behind iov[1] (the file
		 * name), point at them from the main create request
		 */
		req->CreateContextsOffset = cpu_to_le32(
			sizeof(struct smb2_create_req) +
			iov[1].iov_len);
2912
		req->CreateContextsLength = 0;
2913 2914 2915 2916 2917 2918 2919 2920

		for (unsigned int i = 2; i < (n_iov-1); i++) {
			struct kvec *v = &iov[i];
			size_t len = v->iov_len;
			struct create_context *cctx =
				(struct create_context *)v->iov_base;

			cctx->Next = cpu_to_le32(len);
2921
			le32_add_cpu(&req->CreateContextsLength, len);
2922
		}
2923 2924
		le32_add_cpu(&req->CreateContextsLength,
			     iov[n_iov-1].iov_len);
2925 2926
	}

2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938
	rqst->rq_nvec = n_iov;
	return 0;
}

/* rq_iov[0] is the request and is released by cifs_small_buf_release().
 * All other vectors are freed by kfree().
 */
void
SMB2_open_free(struct smb_rqst *rqst)
{
	int i;

2939 2940 2941 2942 2943 2944
	if (rqst && rqst->rq_iov) {
		cifs_small_buf_release(rqst->rq_iov[0].iov_base);
		for (i = 1; i < rqst->rq_nvec; i++)
			if (rqst->rq_iov[i].iov_base != smb2_padding)
				kfree(rqst->rq_iov[i].iov_base);
	}
2945 2946 2947 2948 2949
}

int
SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
	  __u8 *oplock, struct smb2_file_all_info *buf,
2950
	  struct create_posix_rsp *posix,
2951 2952 2953 2954 2955 2956
	  struct kvec *err_iov, int *buftype)
{
	struct smb_rqst rqst;
	struct smb2_create_rsp *rsp = NULL;
	struct cifs_tcon *tcon = oparms->tcon;
	struct cifs_ses *ses = tcon->ses;
2957
	struct TCP_Server_Info *server = cifs_pick_channel(ses);
2958
	struct kvec iov[SMB2_CREATE_IOV_SIZE];
2959
	struct kvec rsp_iov = {NULL, 0};
2960
	int resp_buftype = CIFS_NO_BUFFER;
2961 2962 2963 2964
	int rc = 0;
	int flags = 0;

	cifs_dbg(FYI, "create/open\n");
2965
	if (!ses || !server)
2966 2967 2968 2969 2970
		return -EIO;

	if (smb3_encryption_required(tcon))
		flags |= CIFS_TRANSFORM_REQ;

2971
	memset(&rqst, 0, sizeof(struct smb_rqst));
2972
	memset(&iov, 0, sizeof(iov));
2973
	rqst.rq_iov = iov;
2974
	rqst.rq_nvec = SMB2_CREATE_IOV_SIZE;
2975

2976 2977
	rc = SMB2_open_init(tcon, server,
			    &rqst, oplock, oparms, path);
2978 2979
	if (rc)
		goto creat_exit;
2980

2981
	trace_smb3_open_enter(xid, tcon->tid, tcon->ses->Suid, oparms->path,
2982 2983
		oparms->create_options, oparms->desired_access);

2984 2985
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags,
2986
			    &rsp_iov);
2987
	rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
2988 2989 2990

	if (rc != 0) {
		cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
2991 2992
		if (err_iov && rsp) {
			*err_iov = rsp_iov;
2993
			*buftype = resp_buftype;
2994 2995 2996
			resp_buftype = CIFS_NO_BUFFER;
			rsp = NULL;
		}
2997 2998
		trace_smb3_open_err(xid, tcon->tid, ses->Suid,
				    oparms->create_options, oparms->desired_access, rc);
2999
		if (rc == -EREMCHG) {
3000
			pr_warn_once("server share %s deleted\n",
3001
				     tcon->tree_name);
3002 3003
			tcon->need_reconnect = true;
		}
3004
		goto creat_exit;
3005 3006 3007
	} else if (rsp == NULL) /* unlikely to happen, but safer to check */
		goto creat_exit;
	else
3008 3009
		trace_smb3_open_done(xid, rsp->PersistentFileId, tcon->tid, ses->Suid,
				     oparms->create_options, oparms->desired_access);
3010

3011
	atomic_inc(&tcon->num_remote_opens);
3012 3013
	oparms->fid->persistent_fid = rsp->PersistentFileId;
	oparms->fid->volatile_fid = rsp->VolatileFileId;
3014
	oparms->fid->access = oparms->desired_access;
3015
#ifdef CONFIG_CIFS_DEBUG2
3016
	oparms->fid->mid = le64_to_cpu(rsp->hdr.MessageId);
3017
#endif /* CIFS_DEBUG2 */
3018 3019

	if (buf) {
3020 3021 3022 3023
		buf->CreationTime = rsp->CreationTime;
		buf->LastAccessTime = rsp->LastAccessTime;
		buf->LastWriteTime = rsp->LastWriteTime;
		buf->ChangeTime = rsp->ChangeTime;
3024 3025 3026 3027 3028 3029
		buf->AllocationSize = rsp->AllocationSize;
		buf->EndOfFile = rsp->EndofFile;
		buf->Attributes = rsp->FileAttributes;
		buf->NumberOfLinks = cpu_to_le32(1);
		buf->DeletePending = 0;
	}
3030

3031 3032

	smb2_parse_contexts(server, rsp, &oparms->fid->epoch,
3033
			    oparms->fid->lease_key, oplock, buf, posix);
3034
creat_exit:
3035
	SMB2_open_free(&rqst);
3036 3037 3038 3039
	free_rsp_buf(resp_buftype, rsp);
	return rc;
}

3040
int
3041 3042
SMB2_ioctl_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
		struct smb_rqst *rqst,
3043
		u64 persistent_fid, u64 volatile_fid, u32 opcode,
3044
		char *in_data, u32 indatalen,
3045
		__u32 max_response_size)
3046 3047
{
	struct smb2_ioctl_req *req;
3048
	struct kvec *iov = rqst->rq_iov;
3049
	unsigned int total_len;
3050
	int rc;
3051
	char *in_data_buf;
3052

3053 3054
	rc = smb2_ioctl_req_init(opcode, tcon, server,
				 (void **) &req, &total_len);
3055 3056 3057
	if (rc)
		return rc;

3058 3059 3060 3061 3062
	if (indatalen) {
		/*
		 * indatalen is usually small at a couple of bytes max, so
		 * just allocate through generic pool
		 */
3063
		in_data_buf = kmemdup(in_data, indatalen, GFP_NOFS);
3064 3065 3066 3067 3068 3069
		if (!in_data_buf) {
			cifs_small_buf_release(req);
			return -ENOMEM;
		}
	}

3070 3071 3072 3073
	req->CtlCode = cpu_to_le32(opcode);
	req->PersistentFileId = persistent_fid;
	req->VolatileFileId = volatile_fid;

3074 3075 3076 3077 3078 3079 3080 3081 3082
	iov[0].iov_base = (char *)req;
	/*
	 * If no input data, the size of ioctl struct in
	 * protocol spec still includes a 1 byte data buffer,
	 * but if input data passed to ioctl, we do not
	 * want to double count this, so we do not send
	 * the dummy one byte of data in iovec[0] if sending
	 * input data (in iovec[1]).
	 */
3083 3084 3085 3086
	if (indatalen) {
		req->InputCount = cpu_to_le32(indatalen);
		/* do not set InputOffset if no input data */
		req->InputOffset =
3087
		       cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer));
3088 3089
		rqst->rq_nvec = 2;
		iov[0].iov_len = total_len - 1;
3090
		iov[1].iov_base = in_data_buf;
3091
		iov[1].iov_len = indatalen;
3092 3093 3094 3095
	} else {
		rqst->rq_nvec = 1;
		iov[0].iov_len = total_len;
	}
3096 3097 3098 3099 3100

	req->OutputOffset = 0;
	req->OutputCount = 0; /* MBZ */

	/*
3101 3102 3103
	 * In most cases max_response_size is set to 16K (CIFSMaxBufSize)
	 * We Could increase default MaxOutputResponse, but that could require
	 * more credits. Windows typically sets this smaller, but for some
3104 3105
	 * ioctls it may be useful to allow server to send more. No point
	 * limiting what the server can send as long as fits in one credit
3106 3107 3108 3109 3110 3111 3112 3113
	 * We can not handle more than CIFS_MAX_BUF_SIZE yet but may want
	 * to increase this limit up in the future.
	 * Note that for snapshot queries that servers like Azure expect that
	 * the first query be minimal size (and just used to get the number/size
	 * of previous versions) so response size must be specified as EXACTLY
	 * sizeof(struct snapshot_array) which is 16 when rounded up to multiple
	 * of eight bytes.  Currently that is the only case where we set max
	 * response size smaller.
3114
	 */
3115
	req->MaxOutputResponse = cpu_to_le32(max_response_size);
3116
	req->hdr.CreditCharge =
3117 3118
		cpu_to_le16(DIV_ROUND_UP(max(indatalen, max_response_size),
					 SMB2_MAX_BUFFER_SIZE));
3119 3120
	/* always an FSCTL (for now) */
	req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL);
3121

3122 3123
	/* validate negotiate request must be signed - see MS-SMB2 3.2.5.5 */
	if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO)
3124
		req->hdr.Flags |= SMB2_FLAGS_SIGNED;
3125

3126 3127 3128 3129 3130 3131
	return 0;
}

void
SMB2_ioctl_free(struct smb_rqst *rqst)
{
3132
	int i;
3133

3134
	if (rqst && rqst->rq_iov) {
3135
		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3136 3137 3138
		for (i = 1; i < rqst->rq_nvec; i++)
			if (rqst->rq_iov[i].iov_base != smb2_padding)
				kfree(rqst->rq_iov[i].iov_base);
3139
	}
3140 3141
}

3142

3143 3144 3145 3146 3147
/*
 *	SMB2 IOCTL is used for both IOCTLs and FSCTLs
 */
int
SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
3148 3149 3150
	   u64 volatile_fid, u32 opcode, char *in_data, u32 indatalen,
	   u32 max_out_data_len, char **out_data,
	   u32 *plen /* returned data len */)
3151 3152 3153 3154
{
	struct smb_rqst rqst;
	struct smb2_ioctl_rsp *rsp = NULL;
	struct cifs_ses *ses;
3155
	struct TCP_Server_Info *server;
3156
	struct kvec iov[SMB2_IOCTL_IOV_SIZE];
3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170
	struct kvec rsp_iov = {NULL, 0};
	int resp_buftype = CIFS_NO_BUFFER;
	int rc = 0;
	int flags = 0;

	cifs_dbg(FYI, "SMB2 IOCTL\n");

	if (out_data != NULL)
		*out_data = NULL;

	/* zero out returned data len, in case of error */
	if (plen)
		*plen = 0;

3171
	if (!tcon)
3172 3173
		return -EIO;

3174
	ses = tcon->ses;
3175 3176
	if (!ses)
		return -EIO;
3177 3178

	server = cifs_pick_channel(ses);
3179
	if (!server)
3180 3181 3182 3183 3184
		return -EIO;

	if (smb3_encryption_required(tcon))
		flags |= CIFS_TRANSFORM_REQ;

3185
	memset(&rqst, 0, sizeof(struct smb_rqst));
3186
	memset(&iov, 0, sizeof(iov));
3187
	rqst.rq_iov = iov;
3188
	rqst.rq_nvec = SMB2_IOCTL_IOV_SIZE;
3189

3190 3191
	rc = SMB2_ioctl_init(tcon, server,
			     &rqst, persistent_fid, volatile_fid, opcode,
3192
			     in_data, indatalen, max_out_data_len);
3193 3194
	if (rc)
		goto ioctl_exit;
3195

3196 3197
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags,
3198
			    &rsp_iov);
3199
	rsp = (struct smb2_ioctl_rsp *)rsp_iov.iov_base;
3200

3201 3202 3203 3204
	if (rc != 0)
		trace_smb3_fsctl_err(xid, persistent_fid, tcon->tid,
				ses->Suid, 0, opcode, rc);

Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
3205
	if ((rc != 0) && (rc != -EINVAL) && (rc != -E2BIG)) {
3206
		cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3207
		goto ioctl_exit;
3208 3209 3210
	} else if (rc == -EINVAL) {
		if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) &&
		    (opcode != FSCTL_SRV_COPYCHUNK)) {
3211
			cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3212 3213
			goto ioctl_exit;
		}
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
3214 3215 3216 3217 3218
	} else if (rc == -E2BIG) {
		if (opcode != FSCTL_QUERY_ALLOCATED_RANGES) {
			cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
			goto ioctl_exit;
		}
3219 3220 3221 3222 3223 3224
	}

	/* check if caller wants to look at return data or just return rc */
	if ((plen == NULL) || (out_data == NULL))
		goto ioctl_exit;

3225 3226 3227 3228 3229 3230 3231 3232 3233 3234
	/*
	 * Although unlikely to be possible for rsp to be null and rc not set,
	 * adding check below is slightly safer long term (and quiets Coverity
	 * warning)
	 */
	if (rsp == NULL) {
		rc = -EIO;
		goto ioctl_exit;
	}

3235 3236 3237 3238 3239
	*plen = le32_to_cpu(rsp->OutputCount);

	/* We check for obvious errors in the output buffer length and offset */
	if (*plen == 0)
		goto ioctl_exit; /* server returned no data */
3240
	else if (*plen > rsp_iov.iov_len || *plen > 0xFF00) {
3241
		cifs_tcon_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen);
3242 3243 3244 3245 3246
		*plen = 0;
		rc = -EIO;
		goto ioctl_exit;
	}

3247
	if (rsp_iov.iov_len - *plen < le32_to_cpu(rsp->OutputOffset)) {
3248
		cifs_tcon_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen,
3249 3250 3251 3252 3253 3254
			le32_to_cpu(rsp->OutputOffset));
		*plen = 0;
		rc = -EIO;
		goto ioctl_exit;
	}

3255 3256
	*out_data = kmemdup((char *)rsp + le32_to_cpu(rsp->OutputOffset),
			    *plen, GFP_KERNEL);
3257 3258 3259 3260 3261 3262
	if (*out_data == NULL) {
		rc = -ENOMEM;
		goto ioctl_exit;
	}

ioctl_exit:
3263
	SMB2_ioctl_free(&rqst);
3264 3265 3266 3267
	free_rsp_buf(resp_buftype, rsp);
	return rc;
}

3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280
/*
 *   Individual callers to ioctl worker function follow
 */

int
SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
		     u64 persistent_fid, u64 volatile_fid)
{
	int rc;
	struct  compress_ioctl fsctl_input;
	char *ret_data = NULL;

	fsctl_input.CompressionState =
3281
			cpu_to_le16(COMPRESSION_FORMAT_DEFAULT);
3282 3283

	rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
3284
			FSCTL_SET_COMPRESSION,
3285
			(char *)&fsctl_input /* data input */,
3286 3287
			2 /* in data len */, CIFSMaxBufSize /* max out data */,
			&ret_data /* out data */, NULL);
3288 3289 3290 3291 3292 3293

	cifs_dbg(FYI, "set compression rc %d\n", rc);

	return rc;
}

3294
int
3295 3296
SMB2_close_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
		struct smb_rqst *rqst,
3297
		u64 persistent_fid, u64 volatile_fid, bool query_attrs)
3298 3299 3300 3301 3302 3303
{
	struct smb2_close_req *req;
	struct kvec *iov = rqst->rq_iov;
	unsigned int total_len;
	int rc;

3304 3305
	rc = smb2_plain_req_init(SMB2_CLOSE, tcon, server,
				 (void **) &req, &total_len);
3306 3307 3308
	if (rc)
		return rc;

3309 3310
	req->PersistentFileId = persistent_fid;
	req->VolatileFileId = volatile_fid;
3311 3312 3313 3314
	if (query_attrs)
		req->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
	else
		req->Flags = 0;
3315 3316 3317 3318 3319 3320 3321 3322 3323
	iov[0].iov_base = (char *)req;
	iov[0].iov_len = total_len;

	return 0;
}

void
SMB2_close_free(struct smb_rqst *rqst)
{
3324 3325
	if (rqst && rqst->rq_iov)
		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3326 3327
}

3328
int
3329 3330 3331
__SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
	     u64 persistent_fid, u64 volatile_fid,
	     struct smb2_file_network_open_info *pbuf)
3332
{
3333
	struct smb_rqst rqst;
3334
	struct smb2_close_rsp *rsp = NULL;
3335
	struct cifs_ses *ses = tcon->ses;
3336
	struct TCP_Server_Info *server = cifs_pick_channel(ses);
3337
	struct kvec iov[1];
3338
	struct kvec rsp_iov;
3339
	int resp_buftype = CIFS_NO_BUFFER;
3340
	int rc = 0;
3341
	int flags = 0;
3342
	bool query_attrs = false;
3343

3344
	cifs_dbg(FYI, "Close\n");
3345

3346
	if (!ses || !server)
3347 3348
		return -EIO;

3349
	if (smb3_encryption_required(tcon))
3350 3351
		flags |= CIFS_TRANSFORM_REQ;

3352
	memset(&rqst, 0, sizeof(struct smb_rqst));
3353
	memset(&iov, 0, sizeof(iov));
3354 3355 3356
	rqst.rq_iov = iov;
	rqst.rq_nvec = 1;

3357 3358 3359 3360
	/* check if need to ask server to return timestamps in close response */
	if (pbuf)
		query_attrs = true;

3361
	trace_smb3_close_enter(xid, persistent_fid, tcon->tid, ses->Suid);
3362 3363
	rc = SMB2_close_init(tcon, server,
			     &rqst, persistent_fid, volatile_fid,
3364
			     query_attrs);
3365 3366 3367
	if (rc)
		goto close_exit;

3368 3369
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
3370
	rsp = (struct smb2_close_rsp *)rsp_iov.iov_base;
3371 3372

	if (rc != 0) {
3373
		cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
3374 3375
		trace_smb3_close_err(xid, persistent_fid, tcon->tid, ses->Suid,
				     rc);
3376
		goto close_exit;
3377
	} else {
3378 3379
		trace_smb3_close_done(xid, persistent_fid, tcon->tid,
				      ses->Suid);
3380 3381 3382 3383 3384 3385 3386
		/*
		 * Note that have to subtract 4 since struct network_open_info
		 * has a final 4 byte pad that close response does not have
		 */
		if (pbuf)
			memcpy(pbuf, (char *)&rsp->CreationTime, sizeof(*pbuf) - 4);
	}
3387

3388
	atomic_dec(&tcon->num_remote_opens);
3389
close_exit:
3390
	SMB2_close_free(&rqst);
3391
	free_rsp_buf(resp_buftype, rsp);
3392 3393

	/* retry close in a worker thread if this one is interrupted */
3394
	if (is_interrupt_error(rc)) {
3395 3396
		int tmp_rc;

3397 3398 3399 3400 3401 3402 3403
		tmp_rc = smb2_handle_cancelled_close(tcon, persistent_fid,
						     volatile_fid);
		if (tmp_rc)
			cifs_dbg(VFS, "handle cancelled close fid 0x%llx returned error %d\n",
				 persistent_fid, tmp_rc);
	}
	return rc;
3404 3405
}

3406 3407 3408 3409 3410 3411 3412
int
SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
		u64 persistent_fid, u64 volatile_fid)
{
	return __SMB2_close(xid, tcon, persistent_fid, volatile_fid, NULL);
}

3413 3414 3415
int
smb2_validate_iov(unsigned int offset, unsigned int buffer_length,
		  struct kvec *iov, unsigned int min_buf_size)
Pavel Shilovsky's avatar
Pavel Shilovsky committed
3416
{
3417
	unsigned int smb_len = iov->iov_len;
3418 3419
	char *end_of_smb = smb_len + (char *)iov->iov_base;
	char *begin_of_buf = offset + (char *)iov->iov_base;
Pavel Shilovsky's avatar
Pavel Shilovsky committed
3420 3421 3422 3423
	char *end_of_buf = begin_of_buf + buffer_length;


	if (buffer_length < min_buf_size) {
3424 3425
		cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n",
			 buffer_length, min_buf_size);
Pavel Shilovsky's avatar
Pavel Shilovsky committed
3426 3427 3428 3429 3430
		return -EINVAL;
	}

	/* check if beyond RFC1001 maximum length */
	if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
3431 3432
		cifs_dbg(VFS, "buffer length %d or smb length %d too large\n",
			 buffer_length, smb_len);
Pavel Shilovsky's avatar
Pavel Shilovsky committed
3433 3434 3435 3436
		return -EINVAL;
	}

	if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
3437
		cifs_dbg(VFS, "Invalid server response, bad offset to data\n");
Pavel Shilovsky's avatar
Pavel Shilovsky committed
3438 3439 3440 3441 3442 3443 3444 3445 3446 3447
		return -EINVAL;
	}

	return 0;
}

/*
 * If SMB buffer fields are valid, copy into temporary buffer to hold result.
 * Caller must free buffer.
 */
3448 3449 3450 3451
int
smb2_validate_and_copy_iov(unsigned int offset, unsigned int buffer_length,
			   struct kvec *iov, unsigned int minbufsize,
			   char *data)
Pavel Shilovsky's avatar
Pavel Shilovsky committed
3452
{
3453
	char *begin_of_buf = offset + (char *)iov->iov_base;
Pavel Shilovsky's avatar
Pavel Shilovsky committed
3454 3455 3456 3457 3458
	int rc;

	if (!data)
		return -EINVAL;

3459
	rc = smb2_validate_iov(offset, buffer_length, iov, minbufsize);
Pavel Shilovsky's avatar
Pavel Shilovsky committed
3460 3461 3462
	if (rc)
		return rc;

3463
	memcpy(data, begin_of_buf, minbufsize);
Pavel Shilovsky's avatar
Pavel Shilovsky committed
3464 3465 3466 3467

	return 0;
}

3468
int
3469 3470
SMB2_query_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
		     struct smb_rqst *rqst,
3471 3472
		     u64 persistent_fid, u64 volatile_fid,
		     u8 info_class, u8 info_type, u32 additional_info,
3473
		     size_t output_len, size_t input_len, void *input)
Pavel Shilovsky's avatar
Pavel Shilovsky committed
3474 3475
{
	struct smb2_query_info_req *req;
3476
	struct kvec *iov = rqst->rq_iov;
3477
	unsigned int total_len;
3478
	int rc;
Pavel Shilovsky's avatar
Pavel Shilovsky committed
3479

3480 3481
	rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
				 (void **) &req, &total_len);
Pavel Shilovsky's avatar
Pavel Shilovsky committed
3482 3483 3484
	if (rc)
		return rc;

3485
	req->InfoType = info_type;
3486
	req->FileInfoClass = info_class;
Pavel Shilovsky's avatar
Pavel Shilovsky committed
3487 3488
	req->PersistentFileId = persistent_fid;
	req->VolatileFileId = volatile_fid;
3489
	req->AdditionalInformation = cpu_to_le32(additional_info);
3490

3491
	req->OutputBufferLength = cpu_to_le32(output_len);
3492 3493 3494 3495 3496 3497
	if (input_len) {
		req->InputBufferLength = cpu_to_le32(input_len);
		/* total_len for smb query request never close to le16 max */
		req->InputBufferOffset = cpu_to_le16(total_len - 1);
		memcpy(req->Buffer, input, input_len);
	}
Pavel Shilovsky's avatar
Pavel Shilovsky committed
3498 3499

	iov[0].iov_base = (char *)req;
3500
	/* 1 for Buffer */
3501
	iov[0].iov_len = total_len - 1 + input_len;
3502 3503 3504 3505 3506 3507
	return 0;
}

void
SMB2_query_info_free(struct smb_rqst *rqst)
{
3508 3509
	if (rqst && rqst->rq_iov)
		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522
}

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)
{
	struct smb_rqst rqst;
	struct smb2_query_info_rsp *rsp = NULL;
	struct kvec iov[1];
	struct kvec rsp_iov;
	int rc = 0;
3523
	int resp_buftype = CIFS_NO_BUFFER;
3524
	struct cifs_ses *ses = tcon->ses;
3525
	struct TCP_Server_Info *server;
3526
	int flags = 0;
3527
	bool allocated = false;
3528 3529 3530

	cifs_dbg(FYI, "Query Info\n");

3531 3532
	if (!ses)
		return -EIO;
3533
	server = cifs_pick_channel(ses);
3534
	if (!server)
3535 3536 3537 3538
		return -EIO;

	if (smb3_encryption_required(tcon))
		flags |= CIFS_TRANSFORM_REQ;
Pavel Shilovsky's avatar
Pavel Shilovsky committed
3539

3540
	memset(&rqst, 0, sizeof(struct smb_rqst));
3541
	memset(&iov, 0, sizeof(iov));
3542 3543 3544
	rqst.rq_iov = iov;
	rqst.rq_nvec = 1;

3545 3546
	rc = SMB2_query_info_init(tcon, server,
				  &rqst, persistent_fid, volatile_fid,
3547
				  info_class, info_type, additional_info,
3548
				  output_len, 0, NULL);
3549 3550 3551
	if (rc)
		goto qinf_exit;

3552 3553 3554
	trace_smb3_query_info_enter(xid, persistent_fid, tcon->tid,
				    ses->Suid, info_class, (__u32)info_type);

3555 3556
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
3557
	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
3558

Pavel Shilovsky's avatar
Pavel Shilovsky committed
3559 3560
	if (rc) {
		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
3561 3562
		trace_smb3_query_info_err(xid, persistent_fid, tcon->tid,
				ses->Suid, info_class, (__u32)info_type, rc);
Pavel Shilovsky's avatar
Pavel Shilovsky committed
3563 3564 3565
		goto qinf_exit;
	}

3566 3567 3568
	trace_smb3_query_info_done(xid, persistent_fid, tcon->tid,
				ses->Suid, info_class, (__u32)info_type);

3569 3570 3571 3572 3573
	if (dlen) {
		*dlen = le32_to_cpu(rsp->OutputBufferLength);
		if (!*data) {
			*data = kmalloc(*dlen, GFP_KERNEL);
			if (!*data) {
3574
				cifs_tcon_dbg(VFS,
3575 3576 3577
					"Error %d allocating memory for acl\n",
					rc);
				*dlen = 0;
3578
				rc = -ENOMEM;
3579 3580
				goto qinf_exit;
			}
3581
			allocated = true;
3582 3583 3584
		}
	}

3585 3586
	rc = smb2_validate_and_copy_iov(le16_to_cpu(rsp->OutputBufferOffset),
					le32_to_cpu(rsp->OutputBufferLength),
3587
					&rsp_iov, dlen ? *dlen : min_len, *data);
3588 3589 3590 3591 3592
	if (rc && allocated) {
		kfree(*data);
		*data = NULL;
		*dlen = 0;
	}
Pavel Shilovsky's avatar
Pavel Shilovsky committed
3593 3594

qinf_exit:
3595
	SMB2_query_info_free(&rqst);
Pavel Shilovsky's avatar
Pavel Shilovsky committed
3596 3597 3598
	free_rsp_buf(resp_buftype, rsp);
	return rc;
}
3599

3600 3601 3602 3603 3604 3605 3606 3607 3608 3609
int SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
	u64 persistent_fid, u64 volatile_fid, struct smb2_file_all_info *data)
{
	return query_info(xid, tcon, persistent_fid, volatile_fid,
			  FILE_ALL_INFORMATION, SMB2_O_INFO_FILE, 0,
			  sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
			  sizeof(struct smb2_file_all_info), (void **)&data,
			  NULL);
}

3610 3611
#if 0
/* currently unused, as now we are doing compounding instead (see smb311_posix_query_path_info) */
3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622
int
SMB311_posix_query_info(const unsigned int xid, struct cifs_tcon *tcon,
		u64 persistent_fid, u64 volatile_fid, struct smb311_posix_qinfo *data, u32 *plen)
{
	size_t output_len = sizeof(struct smb311_posix_qinfo *) +
			(sizeof(struct cifs_sid) * 2) + (PATH_MAX * 2);
	*plen = 0;

	return query_info(xid, tcon, persistent_fid, volatile_fid,
			  SMB_FIND_FILE_POSIX_INFO, SMB2_O_INFO_FILE, 0,
			  output_len, sizeof(struct smb311_posix_qinfo), (void **)&data, plen);
3623
	/* Note caller must free "data" (passed in above). It may be allocated in query_info call */
3624
}
3625
#endif
3626

3627
int
3628
SMB2_query_acl(const unsigned int xid, struct cifs_tcon *tcon,
3629
	       u64 persistent_fid, u64 volatile_fid,
3630
	       void **data, u32 *plen, u32 extra_info)
3631
{
3632 3633
	__u32 additional_info = OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
				extra_info;
3634 3635
	*plen = 0;

3636
	return query_info(xid, tcon, persistent_fid, volatile_fid,
3637
			  0, SMB2_O_INFO_SECURITY, additional_info,
3638
			  SMB2_MAX_BUFFER_SIZE, MIN_SEC_DESC_LEN, data, plen);
3639 3640 3641 3642 3643 3644 3645
}

int
SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
		 u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
{
	return query_info(xid, tcon, persistent_fid, volatile_fid,
3646 3647
			  FILE_INTERNAL_INFORMATION, SMB2_O_INFO_FILE, 0,
			  sizeof(struct smb2_file_internal_info),
3648
			  sizeof(struct smb2_file_internal_info),
3649
			  (void **)&uniqueid, NULL);
3650 3651
}

3652 3653 3654 3655 3656
/*
 * CHANGE_NOTIFY Request is sent to get notifications on changes to a directory
 * See MS-SMB2 2.2.35 and 2.2.36
 */

3657
static int
3658
SMB2_notify_init(const unsigned int xid, struct smb_rqst *rqst,
3659 3660 3661
		 struct cifs_tcon *tcon, struct TCP_Server_Info *server,
		 u64 persistent_fid, u64 volatile_fid,
		 u32 completion_filter, bool watch_tree)
3662 3663 3664 3665 3666 3667
{
	struct smb2_change_notify_req *req;
	struct kvec *iov = rqst->rq_iov;
	unsigned int total_len;
	int rc;

3668 3669
	rc = smb2_plain_req_init(SMB2_CHANGE_NOTIFY, tcon, server,
				 (void **) &req, &total_len);
3670 3671 3672
	if (rc)
		return rc;

3673 3674
	req->PersistentFileId = persistent_fid;
	req->VolatileFileId = volatile_fid;
3675
	/* See note 354 of MS-SMB2, 64K max */
3676 3677
	req->OutputBufferLength =
		cpu_to_le32(SMB2_MAX_BUFFER_SIZE - MAX_SMB2_HDR_SIZE);
3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692
	req->CompletionFilter = cpu_to_le32(completion_filter);
	if (watch_tree)
		req->Flags = cpu_to_le16(SMB2_WATCH_TREE);
	else
		req->Flags = 0;

	iov[0].iov_base = (char *)req;
	iov[0].iov_len = total_len;

	return 0;
}

int
SMB2_change_notify(const unsigned int xid, struct cifs_tcon *tcon,
		u64 persistent_fid, u64 volatile_fid, bool watch_tree,
3693 3694
		u32 completion_filter, u32 max_out_data_len, char **out_data,
		u32 *plen /* returned data len */)
3695 3696
{
	struct cifs_ses *ses = tcon->ses;
3697
	struct TCP_Server_Info *server = cifs_pick_channel(ses);
3698
	struct smb_rqst rqst;
3699
	struct smb2_change_notify_rsp *smb_rsp;
3700 3701 3702 3703 3704 3705 3706
	struct kvec iov[1];
	struct kvec rsp_iov = {NULL, 0};
	int resp_buftype = CIFS_NO_BUFFER;
	int flags = 0;
	int rc = 0;

	cifs_dbg(FYI, "change notify\n");
3707
	if (!ses || !server)
3708 3709 3710 3711 3712 3713 3714
		return -EIO;

	if (smb3_encryption_required(tcon))
		flags |= CIFS_TRANSFORM_REQ;

	memset(&rqst, 0, sizeof(struct smb_rqst));
	memset(&iov, 0, sizeof(iov));
3715 3716 3717
	if (plen)
		*plen = 0;

3718 3719 3720
	rqst.rq_iov = iov;
	rqst.rq_nvec = 1;

3721 3722
	rc = SMB2_notify_init(xid, &rqst, tcon, server,
			      persistent_fid, volatile_fid,
3723 3724 3725 3726 3727 3728
			      completion_filter, watch_tree);
	if (rc)
		goto cnotify_exit;

	trace_smb3_notify_enter(xid, persistent_fid, tcon->tid, ses->Suid,
				(u8)watch_tree, completion_filter);
3729 3730
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
3731 3732 3733 3734 3735

	if (rc != 0) {
		cifs_stats_fail_inc(tcon, SMB2_CHANGE_NOTIFY_HE);
		trace_smb3_notify_err(xid, persistent_fid, tcon->tid, ses->Suid,
				(u8)watch_tree, completion_filter, rc);
3736
	} else {
3737
		trace_smb3_notify_done(xid, persistent_fid, tcon->tid,
3738 3739 3740
			ses->Suid, (u8)watch_tree, completion_filter);
		/* validate that notify information is plausible */
		if ((rsp_iov.iov_base == NULL) ||
3741
		    (rsp_iov.iov_len < sizeof(struct smb2_change_notify_rsp) + 1))
3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754
			goto cnotify_exit;

		smb_rsp = (struct smb2_change_notify_rsp *)rsp_iov.iov_base;

		smb2_validate_iov(le16_to_cpu(smb_rsp->OutputBufferOffset),
				le32_to_cpu(smb_rsp->OutputBufferLength), &rsp_iov,
				sizeof(struct file_notify_information));

		*out_data = kmemdup((char *)smb_rsp + le16_to_cpu(smb_rsp->OutputBufferOffset),
				le32_to_cpu(smb_rsp->OutputBufferLength), GFP_KERNEL);
		if (*out_data == NULL) {
			rc = -ENOMEM;
			goto cnotify_exit;
3755
		} else if (plen)
3756 3757
			*plen = le32_to_cpu(smb_rsp->OutputBufferLength);
	}
3758 3759 3760 3761 3762 3763 3764 3765 3766 3767

 cnotify_exit:
	if (rqst.rq_iov)
		cifs_small_buf_release(rqst.rq_iov[0].iov_base); /* request */
	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
	return rc;
}



3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778
/*
 * This is a no-op for now. We're not really interested in the reply, but
 * rather in the fact that the server sent one and that server->lstrp
 * gets updated.
 *
 * FIXME: maybe we should consider checking that the reply matches request?
 */
static void
smb2_echo_callback(struct mid_q_entry *mid)
{
	struct TCP_Server_Info *server = mid->callback_data;
3779
	struct smb2_echo_rsp *rsp = (struct smb2_echo_rsp *)mid->resp_buf;
3780
	struct cifs_credits credits = { .value = 0, .instance = 0 };
3781

3782
	if (mid->mid_state == MID_RESPONSE_RECEIVED
3783
	    || mid->mid_state == MID_RESPONSE_MALFORMED) {
3784
		credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
3785 3786
		credits.instance = server->reconnect_instance;
	}
3787

3788
	release_mid(mid);
3789
	add_credits(server, &credits, CIFS_ECHO_OP);
3790 3791
}

3792 3793 3794 3795
void smb2_reconnect_server(struct work_struct *work)
{
	struct TCP_Server_Info *server = container_of(work,
					struct TCP_Server_Info, reconnect.work);
3796 3797
	struct TCP_Server_Info *pserver;
	struct cifs_ses *ses, *ses2;
3798
	struct cifs_tcon *tcon, *tcon2;
3799 3800
	struct list_head tmp_list, tmp_ses_list;
	bool tcon_exist = false, ses_exist = false;
3801
	bool tcon_selected = false;
3802
	int rc;
3803
	bool resched = false;
3804

3805
	/* If server is a channel, select the primary channel */
3806
	pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
3807 3808

	/* Prevent simultaneous reconnects that can corrupt tcon->rlist list */
3809
	mutex_lock(&pserver->reconnect_mutex);
3810 3811

	INIT_LIST_HEAD(&tmp_list);
3812 3813
	INIT_LIST_HEAD(&tmp_ses_list);
	cifs_dbg(FYI, "Reconnecting tcons and channels\n");
3814 3815

	spin_lock(&cifs_tcp_ses_lock);
3816
	list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
3817 3818 3819 3820 3821 3822
		spin_lock(&ses->ses_lock);
		if (ses->ses_status == SES_EXITING) {
			spin_unlock(&ses->ses_lock);
			continue;
		}
		spin_unlock(&ses->ses_lock);
3823

3824
		tcon_selected = false;
3825

3826
		list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
3827
			if (tcon->need_reconnect || tcon->need_reopen_files) {
3828 3829
				tcon->tc_count++;
				list_add_tail(&tcon->rlist, &tmp_list);
3830
				tcon_selected = tcon_exist = true;
3831 3832
			}
		}
3833 3834 3835 3836
		/*
		 * IPC has the same lifetime as its session and uses its
		 * refcount.
		 */
3837 3838
		if (ses->tcon_ipc && ses->tcon_ipc->need_reconnect) {
			list_add_tail(&ses->tcon_ipc->rlist, &tmp_list);
3839
			tcon_selected = tcon_exist = true;
3840
			cifs_smb_ses_inc_refcount(ses);
3841 3842 3843 3844 3845 3846
		}
		/*
		 * handle the case where channel needs to reconnect
		 * binding session, but tcon is healthy (some other channel
		 * is active)
		 */
3847
		spin_lock(&ses->chan_lock);
3848 3849
		if (!tcon_selected && cifs_chan_needs_reconnect(ses, server)) {
			list_add_tail(&ses->rlist, &tmp_ses_list);
3850
			ses_exist = true;
3851
			cifs_smb_ses_inc_refcount(ses);
3852
		}
3853
		spin_unlock(&ses->chan_lock);
3854 3855 3856 3857 3858
	}
	/*
	 * Get the reference to server struct to be sure that the last call of
	 * cifs_put_tcon() in the loop below won't release the server pointer.
	 */
3859
	if (tcon_exist || ses_exist)
3860 3861 3862 3863 3864
		server->srv_count++;

	spin_unlock(&cifs_tcp_ses_lock);

	list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) {
3865
		rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server);
3866
		if (!rc)
3867
			cifs_reopen_persistent_handles(tcon);
3868 3869
		else
			resched = true;
3870
		list_del_init(&tcon->rlist);
3871 3872 3873 3874
		if (tcon->ipc)
			cifs_put_smb_ses(tcon->ses);
		else
			cifs_put_tcon(tcon);
3875 3876
	}

3877 3878 3879 3880
	if (!ses_exist)
		goto done;

	/* allocate a dummy tcon struct used for reconnect */
3881
	tcon = tcon_info_alloc(false);
3882 3883
	if (!tcon) {
		resched = true;
3884 3885 3886 3887
		list_for_each_entry_safe(ses, ses2, &tmp_ses_list, rlist) {
			list_del_init(&ses->rlist);
			cifs_put_smb_ses(ses);
		}
3888 3889 3890
		goto done;
	}

3891
	tcon->status = TID_GOOD;
3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903
	tcon->retry = false;
	tcon->need_reconnect = false;

	/* now reconnect sessions for necessary channels */
	list_for_each_entry_safe(ses, ses2, &tmp_ses_list, rlist) {
		tcon->ses = ses;
		rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server);
		if (rc)
			resched = true;
		list_del_init(&ses->rlist);
		cifs_put_smb_ses(ses);
	}
3904
	tconInfoFree(tcon);
3905 3906 3907

done:
	cifs_dbg(FYI, "Reconnecting tcons and channels finished\n");
3908 3909
	if (resched)
		queue_delayed_work(cifsiod_wq, &server->reconnect, 2 * HZ);
3910
	mutex_unlock(&pserver->reconnect_mutex);
3911 3912

	/* now we can safely release srv struct */
3913
	if (tcon_exist || ses_exist)
3914 3915 3916
		cifs_put_tcp_session(server, 1);
}

3917 3918 3919 3920 3921
int
SMB2_echo(struct TCP_Server_Info *server)
{
	struct smb2_echo_req *req;
	int rc = 0;
3922
	struct kvec iov[1];
3923
	struct smb_rqst rqst = { .rq_iov = iov,
3924
				 .rq_nvec = 1 };
3925
	unsigned int total_len;
3926

3927
	cifs_dbg(FYI, "In echo request for conn_id %lld\n", server->conn_id);
3928

3929
	spin_lock(&server->srv_lock);
3930 3931
	if (server->ops->need_neg &&
	    server->ops->need_neg(server)) {
3932
		spin_unlock(&server->srv_lock);
3933
		/* No need to send echo on newly established connections */
3934
		mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
3935
		return rc;
3936
	}
3937
	spin_unlock(&server->srv_lock);
3938

3939 3940
	rc = smb2_plain_req_init(SMB2_ECHO, NULL, server,
				 (void **)&req, &total_len);
3941 3942 3943
	if (rc)
		return rc;

3944
	req->hdr.CreditRequest = cpu_to_le16(1);
3945

3946 3947
	iov[0].iov_len = total_len;
	iov[0].iov_base = (char *)req;
3948

3949
	rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, NULL,
3950
			     server, CIFS_ECHO_OP, NULL);
3951
	if (rc)
3952
		cifs_dbg(FYI, "Echo request failed: %d\n", rc);
3953 3954 3955 3956

	cifs_small_buf_release(req);
	return rc;
}
3957

3958 3959 3960 3961 3962 3963 3964
void
SMB2_flush_free(struct smb_rqst *rqst)
{
	if (rqst && rqst->rq_iov)
		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
}

3965
int
3966
SMB2_flush_init(const unsigned int xid, struct smb_rqst *rqst,
3967 3968
		struct cifs_tcon *tcon, struct TCP_Server_Info *server,
		u64 persistent_fid, u64 volatile_fid)
3969 3970
{
	struct smb2_flush_req *req;
3971
	struct kvec *iov = rqst->rq_iov;
3972
	unsigned int total_len;
3973
	int rc;
3974

3975 3976
	rc = smb2_plain_req_init(SMB2_FLUSH, tcon, server,
				 (void **) &req, &total_len);
3977 3978 3979
	if (rc)
		return rc;

3980 3981
	req->PersistentFileId = persistent_fid;
	req->VolatileFileId = volatile_fid;
3982 3983

	iov[0].iov_base = (char *)req;
3984
	iov[0].iov_len = total_len;
3985

3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996
	return 0;
}

int
SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
	   u64 volatile_fid)
{
	struct cifs_ses *ses = tcon->ses;
	struct smb_rqst rqst;
	struct kvec iov[1];
	struct kvec rsp_iov = {NULL, 0};
3997
	struct TCP_Server_Info *server = cifs_pick_channel(ses);
3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008
	int resp_buftype = CIFS_NO_BUFFER;
	int flags = 0;
	int rc = 0;

	cifs_dbg(FYI, "flush\n");
	if (!ses || !(ses->server))
		return -EIO;

	if (smb3_encryption_required(tcon))
		flags |= CIFS_TRANSFORM_REQ;

4009
	memset(&rqst, 0, sizeof(struct smb_rqst));
4010
	memset(&iov, 0, sizeof(iov));
4011 4012 4013
	rqst.rq_iov = iov;
	rqst.rq_nvec = 1;

4014 4015
	rc = SMB2_flush_init(xid, &rqst, tcon, server,
			     persistent_fid, volatile_fid);
4016 4017 4018
	if (rc)
		goto flush_exit;

4019
	trace_smb3_flush_enter(xid, persistent_fid, tcon->tid, ses->Suid);
4020 4021
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
4022

4023
	if (rc != 0) {
4024
		cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
4025 4026
		trace_smb3_flush_err(xid, persistent_fid, tcon->tid, ses->Suid,
				     rc);
4027 4028 4029
	} else
		trace_smb3_flush_done(xid, persistent_fid, tcon->tid,
				      ses->Suid);
4030

4031 4032
 flush_exit:
	SMB2_flush_free(&rqst);
4033
	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4034 4035
	return rc;
}
4036

4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054
#ifdef CONFIG_CIFS_SMB_DIRECT
static inline bool smb3_use_rdma_offload(struct cifs_io_parms *io_parms)
{
	struct TCP_Server_Info *server = io_parms->server;
	struct cifs_tcon *tcon = io_parms->tcon;

	/* we can only offload if we're connected */
	if (!server || !tcon)
		return false;

	/* we can only offload on an rdma connection */
	if (!server->rdma || !server->smbd_conn)
		return false;

	/* we don't support signed offload yet */
	if (server->sign)
		return false;

4055 4056 4057 4058
	/* we don't support encrypted offload yet */
	if (smb3_encryption_required(tcon))
		return false;

4059 4060 4061 4062 4063 4064 4065 4066
	/* offload also has its overhead, so only do it if desired */
	if (io_parms->length < server->smbd_conn->rdma_readwrite_threshold)
		return false;

	return true;
}
#endif /* CONFIG_CIFS_SMB_DIRECT */

4067 4068 4069 4070 4071
/*
 * To form a chain of read requests, any read requests after the first should
 * have the end_of_chain boolean set to true.
 */
static int
4072
smb2_new_read_req(void **buf, unsigned int *total_len,
4073 4074
	struct cifs_io_parms *io_parms, struct cifs_readdata *rdata,
	unsigned int remaining_bytes, int request_type)
4075 4076
{
	int rc = -EACCES;
4077
	struct smb2_read_req *req = NULL;
4078
	struct smb2_hdr *shdr;
4079
	struct TCP_Server_Info *server = io_parms->server;
4080

4081 4082
	rc = smb2_plain_req_init(SMB2_READ, io_parms->tcon, server,
				 (void **) &req, total_len);
4083 4084
	if (rc)
		return rc;
4085 4086

	if (server == NULL)
4087 4088
		return -ECONNABORTED;

4089 4090
	shdr = &req->hdr;
	shdr->Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
4091

4092 4093
	req->PersistentFileId = io_parms->persistent_fid;
	req->VolatileFileId = io_parms->volatile_fid;
4094 4095 4096 4097 4098 4099
	req->ReadChannelInfoOffset = 0; /* reserved */
	req->ReadChannelInfoLength = 0; /* reserved */
	req->Channel = 0; /* reserved */
	req->MinimumCount = 0;
	req->Length = cpu_to_le32(io_parms->length);
	req->Offset = cpu_to_le64(io_parms->offset);
4100 4101 4102 4103 4104

	trace_smb3_read_enter(0 /* xid */,
			io_parms->persistent_fid,
			io_parms->tcon->tid, io_parms->tcon->ses->Suid,
			io_parms->offset, io_parms->length);
4105 4106 4107 4108 4109
#ifdef CONFIG_CIFS_SMB_DIRECT
	/*
	 * If we want to do a RDMA write, fill in and append
	 * smbd_buffer_descriptor_v1 to the end of read request
	 */
4110
	if (smb3_use_rdma_offload(io_parms)) {
4111
		struct smbd_buffer_descriptor_v1 *v1;
4112
		bool need_invalidate = server->dialect == SMB30_PROT_ID;
4113

4114 4115
		rdata->mr = smbd_register_mr(server->smbd_conn, &rdata->iter,
					     true, need_invalidate);
4116
		if (!rdata->mr)
4117
			return -EAGAIN;
4118 4119 4120 4121 4122

		req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
		if (need_invalidate)
			req->Channel = SMB2_CHANNEL_RDMA_V1;
		req->ReadChannelInfoOffset =
4123
			cpu_to_le16(offsetof(struct smb2_read_req, Buffer));
4124
		req->ReadChannelInfoLength =
4125
			cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
4126
		v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
4127 4128 4129
		v1->offset = cpu_to_le64(rdata->mr->mr->iova);
		v1->token = cpu_to_le32(rdata->mr->mr->rkey);
		v1->length = cpu_to_le32(rdata->mr->mr->length);
4130 4131 4132 4133

		*total_len += sizeof(*v1) - 1;
	}
#endif
4134 4135
	if (request_type & CHAINED_REQUEST) {
		if (!(request_type & END_OF_CHAIN)) {
4136
			/* next 8-byte aligned request */
4137
			*total_len = ALIGN(*total_len, 8);
4138
			shdr->NextCommand = cpu_to_le32(*total_len);
4139
		} else /* END_OF_CHAIN */
4140
			shdr->NextCommand = 0;
4141
		if (request_type & RELATED_REQUEST) {
4142
			shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
4143 4144 4145 4146
			/*
			 * Related requests use info from previous read request
			 * in chain.
			 */
4147 4148
			shdr->SessionId = cpu_to_le64(0xFFFFFFFFFFFFFFFF);
			shdr->Id.SyncId.TreeId = cpu_to_le32(0xFFFFFFFF);
4149 4150
			req->PersistentFileId = (u64)-1;
			req->VolatileFileId = (u64)-1;
4151 4152 4153 4154 4155 4156 4157
		}
	}
	if (remaining_bytes > io_parms->length)
		req->RemainingBytes = cpu_to_le32(remaining_bytes);
	else
		req->RemainingBytes = 0;

4158
	*buf = req;
4159 4160 4161 4162 4163 4164 4165 4166
	return rc;
}

static void
smb2_readv_callback(struct mid_q_entry *mid)
{
	struct cifs_readdata *rdata = mid->callback_data;
	struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
4167
	struct TCP_Server_Info *server = rdata->server;
4168 4169
	struct smb2_hdr *shdr =
				(struct smb2_hdr *)rdata->iov[0].iov_base;
4170
	struct cifs_credits credits = { .value = 0, .instance = 0 };
4171 4172 4173 4174 4175
	struct smb_rqst rqst = { .rq_iov = &rdata->iov[1], .rq_nvec = 1 };

	if (rdata->got_bytes) {
		rqst.rq_iter	  = rdata->iter;
		rqst.rq_iter_size = iov_iter_count(&rdata->iter);
Yang Li's avatar
Yang Li committed
4176
	}
4177

4178 4179 4180 4181
	WARN_ONCE(rdata->server != mid->server,
		  "rdata server %p != mid server %p",
		  rdata->server, mid->server);

4182 4183 4184
	cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%u\n",
		 __func__, mid->mid, mid->mid_state, rdata->result,
		 rdata->bytes);
4185 4186 4187

	switch (mid->mid_state) {
	case MID_RESPONSE_RECEIVED:
4188 4189
		credits.value = le16_to_cpu(shdr->CreditRequest);
		credits.instance = server->reconnect_instance;
4190
		/* result already set, check signature */
4191
		if (server->sign && !mid->decrypted) {
Pavel Shilovsky's avatar
Pavel Shilovsky committed
4192 4193
			int rc;

4194 4195
			iov_iter_revert(&rqst.rq_iter, rdata->got_bytes);
			iov_iter_truncate(&rqst.rq_iter, rdata->got_bytes);
4196
			rc = smb2_verify_signature(&rqst, server);
Pavel Shilovsky's avatar
Pavel Shilovsky committed
4197
			if (rc)
4198
				cifs_tcon_dbg(VFS, "SMB signature verification returned error = %d\n",
4199
					 rc);
Pavel Shilovsky's avatar
Pavel Shilovsky committed
4200
		}
4201
		/* FIXME: should this be counted toward the initiating task? */
4202 4203
		task_io_account_read(rdata->got_bytes);
		cifs_stats_bytes_read(tcon, rdata->got_bytes);
4204 4205 4206 4207
		break;
	case MID_REQUEST_SUBMITTED:
	case MID_RETRY_NEEDED:
		rdata->result = -EAGAIN;
4208 4209 4210 4211 4212 4213
		if (server->sign && rdata->got_bytes)
			/* reset bytes number since we can not check a sign */
			rdata->got_bytes = 0;
		/* FIXME: should this be counted toward the initiating task? */
		task_io_account_read(rdata->got_bytes);
		cifs_stats_bytes_read(tcon, rdata->got_bytes);
4214
		break;
4215
	case MID_RESPONSE_MALFORMED:
4216 4217
		credits.value = le16_to_cpu(shdr->CreditRequest);
		credits.instance = server->reconnect_instance;
4218
		fallthrough;
4219
	default:
4220
		rdata->result = -EIO;
4221
	}
4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232
#ifdef CONFIG_CIFS_SMB_DIRECT
	/*
	 * If this rdata has a memmory registered, the MR can be freed
	 * MR needs to be freed as soon as I/O finishes to prevent deadlock
	 * because they have limited number and are used for future I/Os
	 */
	if (rdata->mr) {
		smbd_deregister_mr(rdata->mr);
		rdata->mr = NULL;
	}
#endif
4233
	if (rdata->result && rdata->result != -ENODATA) {
4234
		cifs_stats_fail_inc(tcon, SMB2_READ_HE);
4235 4236 4237 4238 4239 4240 4241 4242 4243
		trace_smb3_read_err(0 /* xid */,
				    rdata->cfile->fid.persistent_fid,
				    tcon->tid, tcon->ses->Suid, rdata->offset,
				    rdata->bytes, rdata->result);
	} else
		trace_smb3_read_done(0 /* xid */,
				     rdata->cfile->fid.persistent_fid,
				     tcon->tid, tcon->ses->Suid,
				     rdata->offset, rdata->got_bytes);
4244 4245

	queue_work(cifsiod_wq, &rdata->work);
4246
	release_mid(mid);
4247
	add_credits(server, &credits, 0);
4248 4249
}

4250
/* smb2_async_readv - send an async read, and set up mid to handle result */
4251 4252 4253
int
smb2_async_readv(struct cifs_readdata *rdata)
{
4254
	int rc, flags = 0;
4255
	char *buf;
4256
	struct smb2_hdr *shdr;
4257
	struct cifs_io_parms io_parms;
4258
	struct smb_rqst rqst = { .rq_iov = rdata->iov,
4259
				 .rq_nvec = 1 };
4260
	struct TCP_Server_Info *server;
4261
	struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
4262
	unsigned int total_len;
4263
	int credit_request;
4264

4265 4266
	cifs_dbg(FYI, "%s: offset=%llu bytes=%u\n",
		 __func__, rdata->offset, rdata->bytes);
4267

4268 4269 4270
	if (!rdata->server)
		rdata->server = cifs_pick_channel(tcon->ses);

4271
	io_parms.tcon = tlink_tcon(rdata->cfile->tlink);
4272
	io_parms.server = server = rdata->server;
4273 4274 4275 4276 4277
	io_parms.offset = rdata->offset;
	io_parms.length = rdata->bytes;
	io_parms.persistent_fid = rdata->cfile->fid.persistent_fid;
	io_parms.volatile_fid = rdata->cfile->fid.volatile_fid;
	io_parms.pid = rdata->pid;
4278

4279 4280
	rc = smb2_new_read_req(
		(void **) &buf, &total_len, &io_parms, rdata, 0, 0);
4281
	if (rc)
4282 4283
		return rc;

4284
	if (smb3_encryption_required(io_parms.tcon))
4285 4286
		flags |= CIFS_TRANSFORM_REQ;

4287 4288
	rdata->iov[0].iov_base = buf;
	rdata->iov[0].iov_len = total_len;
4289

4290
	shdr = (struct smb2_hdr *)buf;
4291

4292
	if (rdata->credits.value > 0) {
4293
		shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(rdata->bytes,
4294
						SMB2_MAX_BUFFER_SIZE));
4295 4296 4297 4298 4299 4300 4301
		credit_request = le16_to_cpu(shdr->CreditCharge) + 8;
		if (server->credits >= server->max_credits)
			shdr->CreditRequest = cpu_to_le16(0);
		else
			shdr->CreditRequest = cpu_to_le16(
				min_t(int, server->max_credits -
						server->credits, credit_request));
4302 4303 4304

		rc = adjust_credits(server, &rdata->credits, rdata->bytes);
		if (rc)
4305
			goto async_readv_out;
4306

4307
		flags |= CIFS_HAS_CREDITS;
4308 4309
	}

4310
	kref_get(&rdata->refcount);
4311
	rc = cifs_call_async(server, &rqst,
4312
			     cifs_readv_receive, smb2_readv_callback,
4313 4314
			     smb3_handle_read_data, rdata, flags,
			     &rdata->credits);
4315
	if (rc) {
4316
		kref_put(&rdata->refcount, cifs_readdata_release);
4317
		cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE);
4318 4319 4320 4321 4322
		trace_smb3_read_err(0 /* xid */, io_parms.persistent_fid,
				    io_parms.tcon->tid,
				    io_parms.tcon->ses->Suid,
				    io_parms.offset, io_parms.length, rc);
	}
4323

4324
async_readv_out:
4325 4326 4327
	cifs_small_buf_release(buf);
	return rc;
}
4328

4329 4330 4331 4332
int
SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
	  unsigned int *nbytes, char **buf, int *buf_type)
{
4333
	struct smb_rqst rqst;
4334
	int resp_buftype, rc;
4335
	struct smb2_read_req *req = NULL;
4336
	struct smb2_read_rsp *rsp = NULL;
4337
	struct kvec iov[1];
4338
	struct kvec rsp_iov;
4339
	unsigned int total_len;
4340 4341
	int flags = CIFS_LOG_ERROR;
	struct cifs_ses *ses = io_parms->tcon->ses;
4342

4343 4344 4345
	if (!io_parms->server)
		io_parms->server = cifs_pick_channel(io_parms->tcon->ses);

4346
	*nbytes = 0;
4347
	rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);
4348 4349 4350
	if (rc)
		return rc;

4351
	if (smb3_encryption_required(io_parms->tcon))
4352 4353
		flags |= CIFS_TRANSFORM_REQ;

4354 4355
	iov[0].iov_base = (char *)req;
	iov[0].iov_len = total_len;
4356

4357 4358 4359 4360
	memset(&rqst, 0, sizeof(struct smb_rqst));
	rqst.rq_iov = iov;
	rqst.rq_nvec = 1;

4361 4362
	rc = cifs_send_recv(xid, ses, io_parms->server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
4363
	rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
4364

4365 4366 4367 4368
	if (rc) {
		if (rc != -ENODATA) {
			cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
			cifs_dbg(VFS, "Send error in read = %d\n", rc);
4369
			trace_smb3_read_err(xid,
4370
					    req->PersistentFileId,
4371 4372 4373
					    io_parms->tcon->tid, ses->Suid,
					    io_parms->offset, io_parms->length,
					    rc);
4374
		} else
4375 4376
			trace_smb3_read_done(xid, req->PersistentFileId, io_parms->tcon->tid,
					     ses->Suid, io_parms->offset, 0);
4377
		free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4378
		cifs_small_buf_release(req);
4379
		return rc == -ENODATA ? 0 : rc;
4380
	} else
4381
		trace_smb3_read_done(xid,
4382
				    req->PersistentFileId,
4383 4384
				    io_parms->tcon->tid, ses->Suid,
				    io_parms->offset, io_parms->length);
4385

4386 4387
	cifs_small_buf_release(req);

4388 4389 4390 4391 4392 4393 4394
	*nbytes = le32_to_cpu(rsp->DataLength);
	if ((*nbytes > CIFS_MAX_MSGSIZE) ||
	    (*nbytes > io_parms->length)) {
		cifs_dbg(FYI, "bad length %d for count %d\n",
			 *nbytes, io_parms->length);
		rc = -EIO;
		*nbytes = 0;
4395 4396 4397
	}

	if (*buf) {
4398
		memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);
4399
		free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4400
	} else if (resp_buftype != CIFS_NO_BUFFER) {
4401
		*buf = rsp_iov.iov_base;
4402 4403 4404 4405 4406 4407 4408 4409
		if (resp_buftype == CIFS_SMALL_BUFFER)
			*buf_type = CIFS_SMALL_BUFFER;
		else if (resp_buftype == CIFS_LARGE_BUFFER)
			*buf_type = CIFS_LARGE_BUFFER;
	}
	return rc;
}

4410 4411 4412 4413 4414 4415 4416 4417 4418
/*
 * Check the mid_state and signature on received buffer (if any), and queue the
 * workqueue completion task.
 */
static void
smb2_writev_callback(struct mid_q_entry *mid)
{
	struct cifs_writedata *wdata = mid->callback_data;
	struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
4419
	struct TCP_Server_Info *server = wdata->server;
4420 4421
	unsigned int written;
	struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
4422
	struct cifs_credits credits = { .value = 0, .instance = 0 };
4423

4424 4425 4426 4427
	WARN_ONCE(wdata->server != mid->server,
		  "wdata server %p != mid server %p",
		  wdata->server, mid->server);

4428 4429
	switch (mid->mid_state) {
	case MID_RESPONSE_RECEIVED:
4430
		credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4431 4432
		credits.instance = server->reconnect_instance;
		wdata->result = smb2_check_receive(mid, server, 0);
4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454
		if (wdata->result != 0)
			break;

		written = le32_to_cpu(rsp->DataLength);
		/*
		 * Mask off high 16 bits when bytes written as returned
		 * by the server is greater than bytes requested by the
		 * client. OS/2 servers are known to set incorrect
		 * CountHigh values.
		 */
		if (written > wdata->bytes)
			written &= 0xFFFF;

		if (written < wdata->bytes)
			wdata->result = -ENOSPC;
		else
			wdata->bytes = written;
		break;
	case MID_REQUEST_SUBMITTED:
	case MID_RETRY_NEEDED:
		wdata->result = -EAGAIN;
		break;
4455
	case MID_RESPONSE_MALFORMED:
4456
		credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4457
		credits.instance = server->reconnect_instance;
4458
		fallthrough;
4459 4460 4461 4462
	default:
		wdata->result = -EIO;
		break;
	}
4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475
#ifdef CONFIG_CIFS_SMB_DIRECT
	/*
	 * If this wdata has a memory registered, the MR can be freed
	 * The number of MRs available is limited, it's important to recover
	 * used MR as soon as I/O is finished. Hold MR longer in the later
	 * I/O process can possibly result in I/O deadlock due to lack of MR
	 * to send request on I/O retry
	 */
	if (wdata->mr) {
		smbd_deregister_mr(wdata->mr);
		wdata->mr = NULL;
	}
#endif
4476
	if (wdata->result) {
4477
		cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
4478 4479 4480 4481
		trace_smb3_write_err(0 /* no xid */,
				     wdata->cfile->fid.persistent_fid,
				     tcon->tid, tcon->ses->Suid, wdata->offset,
				     wdata->bytes, wdata->result);
4482
		if (wdata->result == -ENOSPC)
4483
			pr_warn_once("Out of space writing to %s\n",
4484
				     tcon->tree_name);
4485 4486 4487 4488 4489
	} else
		trace_smb3_write_done(0 /* no xid */,
				      wdata->cfile->fid.persistent_fid,
				      tcon->tid, tcon->ses->Suid,
				      wdata->offset, wdata->bytes);
4490 4491

	queue_work(cifsiod_wq, &wdata->work);
4492
	release_mid(mid);
4493
	add_credits(server, &credits, 0);
4494 4495 4496 4497
}

/* smb2_async_writev - send an async write, and set up mid to handle result */
int
4498 4499
smb2_async_writev(struct cifs_writedata *wdata,
		  void (*release)(struct kref *kref))
4500
{
4501
	int rc = -EACCES, flags = 0;
4502
	struct smb2_write_req *req = NULL;
4503
	struct smb2_hdr *shdr;
4504
	struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
4505
	struct TCP_Server_Info *server = wdata->server;
4506
	struct kvec iov[1];
4507
	struct smb_rqst rqst = { };
4508
	unsigned int total_len;
4509 4510
	struct cifs_io_parms _io_parms;
	struct cifs_io_parms *io_parms = NULL;
4511
	int credit_request;
4512

4513 4514 4515
	if (!wdata->server)
		server = wdata->server = cifs_pick_channel(tcon->ses);

4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530
	/*
	 * in future we may get cifs_io_parms passed in from the caller,
	 * but for now we construct it here...
	 */
	_io_parms = (struct cifs_io_parms) {
		.tcon = tcon,
		.server = server,
		.offset = wdata->offset,
		.length = wdata->bytes,
		.persistent_fid = wdata->cfile->fid.persistent_fid,
		.volatile_fid = wdata->cfile->fid.volatile_fid,
		.pid = wdata->pid,
	};
	io_parms = &_io_parms;

4531 4532
	rc = smb2_plain_req_init(SMB2_WRITE, tcon, server,
				 (void **) &req, &total_len);
4533 4534
	if (rc)
		return rc;
4535

4536
	if (smb3_encryption_required(tcon))
4537 4538
		flags |= CIFS_TRANSFORM_REQ;

4539
	shdr = (struct smb2_hdr *)req;
4540
	shdr->Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
4541

4542 4543
	req->PersistentFileId = io_parms->persistent_fid;
	req->VolatileFileId = io_parms->volatile_fid;
4544 4545
	req->WriteChannelInfoOffset = 0;
	req->WriteChannelInfoLength = 0;
4546
	req->Channel = SMB2_CHANNEL_NONE;
4547
	req->Offset = cpu_to_le64(io_parms->offset);
4548
	req->DataOffset = cpu_to_le16(
4549
				offsetof(struct smb2_write_req, Buffer));
4550
	req->RemainingBytes = 0;
4551

4552 4553 4554 4555 4556 4557 4558
	trace_smb3_write_enter(0 /* xid */,
			       io_parms->persistent_fid,
			       io_parms->tcon->tid,
			       io_parms->tcon->ses->Suid,
			       io_parms->offset,
			       io_parms->length);

4559 4560 4561 4562 4563
#ifdef CONFIG_CIFS_SMB_DIRECT
	/*
	 * If we want to do a server RDMA read, fill in and append
	 * smbd_buffer_descriptor_v1 to the end of write request
	 */
4564
	if (smb3_use_rdma_offload(io_parms)) {
4565
		struct smbd_buffer_descriptor_v1 *v1;
4566
		size_t data_size = iov_iter_count(&wdata->iter);
4567 4568
		bool need_invalidate = server->dialect == SMB30_PROT_ID;

4569 4570
		wdata->mr = smbd_register_mr(server->smbd_conn, &wdata->iter,
					     false, need_invalidate);
4571
		if (!wdata->mr) {
4572
			rc = -EAGAIN;
4573 4574 4575 4576
			goto async_writev_out;
		}
		req->Length = 0;
		req->DataOffset = 0;
4577
		req->RemainingBytes = cpu_to_le32(data_size);
4578 4579 4580 4581
		req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
		if (need_invalidate)
			req->Channel = SMB2_CHANNEL_RDMA_V1;
		req->WriteChannelInfoOffset =
4582
			cpu_to_le16(offsetof(struct smb2_write_req, Buffer));
4583
		req->WriteChannelInfoLength =
4584
			cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
4585
		v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
4586 4587 4588
		v1->offset = cpu_to_le64(wdata->mr->mr->iova);
		v1->token = cpu_to_le32(wdata->mr->mr->rkey);
		v1->length = cpu_to_le32(wdata->mr->mr->length);
4589 4590
	}
#endif
4591 4592
	iov[0].iov_len = total_len - 1;
	iov[0].iov_base = (char *)req;
4593

4594
	rqst.rq_iov = iov;
4595
	rqst.rq_nvec = 1;
4596 4597
	rqst.rq_iter = wdata->iter;
	rqst.rq_iter_size = iov_iter_count(&rqst.rq_iter);
4598
#ifdef CONFIG_CIFS_SMB_DIRECT
4599
	if (wdata->mr)
4600
		iov[0].iov_len += sizeof(struct smbd_buffer_descriptor_v1);
4601
#endif
4602 4603
	cifs_dbg(FYI, "async write at %llu %u bytes iter=%zx\n",
		 io_parms->offset, io_parms->length, iov_iter_count(&rqst.rq_iter));
4604

4605 4606 4607
#ifdef CONFIG_CIFS_SMB_DIRECT
	/* For RDMA read, I/O size is in RemainingBytes not in Length */
	if (!wdata->mr)
4608
		req->Length = cpu_to_le32(io_parms->length);
4609
#else
4610
	req->Length = cpu_to_le32(io_parms->length);
4611
#endif
4612

4613
	if (wdata->credits.value > 0) {
4614
		shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->bytes,
4615
						    SMB2_MAX_BUFFER_SIZE));
4616 4617 4618 4619 4620 4621 4622
		credit_request = le16_to_cpu(shdr->CreditCharge) + 8;
		if (server->credits >= server->max_credits)
			shdr->CreditRequest = cpu_to_le16(0);
		else
			shdr->CreditRequest = cpu_to_le16(
				min_t(int, server->max_credits -
						server->credits, credit_request));
4623

4624
		rc = adjust_credits(server, &wdata->credits, io_parms->length);
4625
		if (rc)
4626
			goto async_writev_out;
4627

4628
		flags |= CIFS_HAS_CREDITS;
4629 4630
	}

4631
	kref_get(&wdata->refcount);
4632
	rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, NULL,
4633
			     wdata, flags, &wdata->credits);
4634

4635
	if (rc) {
4636
		trace_smb3_write_err(0 /* no xid */,
4637 4638 4639 4640 4641 4642
				     io_parms->persistent_fid,
				     io_parms->tcon->tid,
				     io_parms->tcon->ses->Suid,
				     io_parms->offset,
				     io_parms->length,
				     rc);
4643
		kref_put(&wdata->refcount, release);
4644
		cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
4645
	}
4646 4647 4648 4649 4650

async_writev_out:
	cifs_small_buf_release(req);
	return rc;
}
4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661

/*
 * SMB2_write function gets iov pointer to kvec array with n_vec as a length.
 * The length field from io_parms must be at least 1 and indicates a number of
 * elements with data to write that begins with position 1 in iov array. All
 * data length is specified by count.
 */
int
SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
	   unsigned int *nbytes, struct kvec *iov, int n_vec)
{
4662
	struct smb_rqst rqst;
4663 4664 4665 4666
	int rc = 0;
	struct smb2_write_req *req = NULL;
	struct smb2_write_rsp *rsp = NULL;
	int resp_buftype;
4667
	struct kvec rsp_iov;
4668
	int flags = 0;
4669
	unsigned int total_len;
4670
	struct TCP_Server_Info *server;
4671

4672 4673 4674 4675 4676
	*nbytes = 0;

	if (n_vec < 1)
		return rc;

4677 4678 4679 4680 4681 4682 4683 4684
	if (!io_parms->server)
		io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
	server = io_parms->server;
	if (server == NULL)
		return -ECONNABORTED;

	rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, server,
				 (void **) &req, &total_len);
4685 4686 4687
	if (rc)
		return rc;

4688
	if (smb3_encryption_required(io_parms->tcon))
4689 4690
		flags |= CIFS_TRANSFORM_REQ;

4691
	req->hdr.Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
4692

4693 4694
	req->PersistentFileId = io_parms->persistent_fid;
	req->VolatileFileId = io_parms->volatile_fid;
4695 4696 4697 4698 4699 4700
	req->WriteChannelInfoOffset = 0;
	req->WriteChannelInfoLength = 0;
	req->Channel = 0;
	req->Length = cpu_to_le32(io_parms->length);
	req->Offset = cpu_to_le64(io_parms->offset);
	req->DataOffset = cpu_to_le16(
4701
				offsetof(struct smb2_write_req, Buffer));
4702 4703
	req->RemainingBytes = 0;

4704 4705 4706 4707
	trace_smb3_write_enter(xid, io_parms->persistent_fid,
		io_parms->tcon->tid, io_parms->tcon->ses->Suid,
		io_parms->offset, io_parms->length);

4708
	iov[0].iov_base = (char *)req;
4709 4710
	/* 1 for Buffer */
	iov[0].iov_len = total_len - 1;
4711

4712 4713 4714 4715
	memset(&rqst, 0, sizeof(struct smb_rqst));
	rqst.rq_iov = iov;
	rqst.rq_nvec = n_vec + 1;

4716 4717
	rc = cifs_send_recv(xid, io_parms->tcon->ses, server,
			    &rqst,
4718
			    &resp_buftype, flags, &rsp_iov);
4719
	rsp = (struct smb2_write_rsp *)rsp_iov.iov_base;
4720 4721

	if (rc) {
4722
		trace_smb3_write_err(xid,
4723
				     req->PersistentFileId,
4724 4725 4726
				     io_parms->tcon->tid,
				     io_parms->tcon->ses->Suid,
				     io_parms->offset, io_parms->length, rc);
4727
		cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
4728
		cifs_dbg(VFS, "Send error in write = %d\n", rc);
4729
	} else {
4730
		*nbytes = le32_to_cpu(rsp->DataLength);
4731
		trace_smb3_write_done(xid,
4732
				      req->PersistentFileId,
4733 4734 4735
				      io_parms->tcon->tid,
				      io_parms->tcon->ses->Suid,
				      io_parms->offset, *nbytes);
4736
	}
4737

4738
	cifs_small_buf_release(req);
4739
	free_rsp_buf(resp_buftype, rsp);
4740 4741
	return rc;
}
4742

4743
int posix_info_sid_size(const void *beg, const void *end)
4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766
{
	size_t subauth;
	int total;

	if (beg + 1 > end)
		return -1;

	subauth = *(u8 *)(beg+1);
	if (subauth < 1 || subauth > 15)
		return -1;

	total = 1 + 1 + 6 + 4*subauth;
	if (beg + total > end)
		return -1;

	return total;
}

int posix_info_parse(const void *beg, const void *end,
		     struct smb2_posix_info_parsed *out)

{
	int total_len = 0;
4767
	int owner_len, group_len;
4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789
	int name_len;
	const void *owner_sid;
	const void *group_sid;
	const void *name;

	/* if no end bound given, assume payload to be correct */
	if (!end) {
		const struct smb2_posix_info *p = beg;

		end = beg + le32_to_cpu(p->NextEntryOffset);
		/* last element will have a 0 offset, pick a sensible bound */
		if (end == beg)
			end += 0xFFFF;
	}

	/* check base buf */
	if (beg + sizeof(struct smb2_posix_info) > end)
		return -1;
	total_len = sizeof(struct smb2_posix_info);

	/* check owner sid */
	owner_sid = beg + total_len;
4790 4791
	owner_len = posix_info_sid_size(owner_sid, end);
	if (owner_len < 0)
4792
		return -1;
4793
	total_len += owner_len;
4794 4795 4796

	/* check group sid */
	group_sid = beg + total_len;
4797 4798
	group_len = posix_info_sid_size(group_sid, end);
	if (group_len < 0)
4799
		return -1;
4800
	total_len += group_len;
4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820

	/* check name len */
	if (beg + total_len + 4 > end)
		return -1;
	name_len = le32_to_cpu(*(__le32 *)(beg + total_len));
	if (name_len < 1 || name_len > 0xFFFF)
		return -1;
	total_len += 4;

	/* check name */
	name = beg + total_len;
	if (name + name_len > end)
		return -1;
	total_len += name_len;

	if (out) {
		out->base = beg;
		out->size = total_len;
		out->name_len = name_len;
		out->name = name;
4821 4822
		memcpy(&out->owner, owner_sid, owner_len);
		memcpy(&out->group, group_sid, group_len);
4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835
	}
	return total_len;
}

static int posix_info_extra_size(const void *beg, const void *end)
{
	int len = posix_info_parse(beg, end, NULL);

	if (len < 0)
		return -1;
	return len - sizeof(struct smb2_posix_info);
}

4836
static unsigned int
4837 4838
num_entries(int infotype, char *bufstart, char *end_of_buf, char **lastentry,
	    size_t size)
4839 4840 4841 4842
{
	int len;
	unsigned int entrycount = 0;
	unsigned int next_offset = 0;
4843 4844
	char *entryptr;
	FILE_DIRECTORY_INFO *dir_info;
4845 4846 4847 4848

	if (bufstart == NULL)
		return 0;

4849
	entryptr = bufstart;
4850 4851

	while (1) {
4852 4853 4854
		if (entryptr + next_offset < entryptr ||
		    entryptr + next_offset > end_of_buf ||
		    entryptr + next_offset + size > end_of_buf) {
4855
			cifs_dbg(VFS, "malformed search entry would overflow\n");
4856 4857 4858
			break;
		}

4859 4860 4861
		entryptr = entryptr + next_offset;
		dir_info = (FILE_DIRECTORY_INFO *)entryptr;

4862 4863 4864 4865 4866 4867 4868
		if (infotype == SMB_FIND_FILE_POSIX_INFO)
			len = posix_info_extra_size(entryptr, end_of_buf);
		else
			len = le32_to_cpu(dir_info->FileNameLength);

		if (len < 0 ||
		    entryptr + len < entryptr ||
4869 4870
		    entryptr + len > end_of_buf ||
		    entryptr + len + size > end_of_buf) {
4871 4872
			cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
				 end_of_buf);
4873 4874 4875
			break;
		}

4876
		*lastentry = entryptr;
4877 4878
		entrycount++;

4879
		next_offset = le32_to_cpu(dir_info->NextEntryOffset);
4880 4881 4882 4883 4884 4885 4886 4887 4888 4889
		if (!next_offset)
			break;
	}

	return entrycount;
}

/*
 * Readdir/FindFirst
 */
4890
int SMB2_query_directory_init(const unsigned int xid,
4891 4892 4893
			      struct cifs_tcon *tcon,
			      struct TCP_Server_Info *server,
			      struct smb_rqst *rqst,
4894 4895
			      u64 persistent_fid, u64 volatile_fid,
			      int index, int info_level)
4896 4897 4898 4899
{
	struct smb2_query_directory_req *req;
	unsigned char *bufptr;
	__le16 asteriks = cpu_to_le16('*');
4900 4901 4902
	unsigned int output_size = CIFSMaxBufSize -
		MAX_SMB2_CREATE_RESPONSE_SIZE -
		MAX_SMB2_CLOSE_RESPONSE_SIZE;
4903
	unsigned int total_len;
4904 4905
	struct kvec *iov = rqst->rq_iov;
	int len, rc;
4906

4907 4908
	rc = smb2_plain_req_init(SMB2_QUERY_DIRECTORY, tcon, server,
				 (void **) &req, &total_len);
4909 4910 4911
	if (rc)
		return rc;

4912
	switch (info_level) {
4913 4914 4915 4916 4917 4918
	case SMB_FIND_FILE_DIRECTORY_INFO:
		req->FileInformationClass = FILE_DIRECTORY_INFORMATION;
		break;
	case SMB_FIND_FILE_ID_FULL_DIR_INFO:
		req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION;
		break;
4919 4920 4921
	case SMB_FIND_FILE_POSIX_INFO:
		req->FileInformationClass = SMB_FIND_FILE_POSIX_INFO;
		break;
4922
	default:
4923
		cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
4924 4925
			info_level);
		return -EINVAL;
4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936
	}

	req->FileIndex = cpu_to_le32(index);
	req->PersistentFileId = persistent_fid;
	req->VolatileFileId = volatile_fid;

	len = 0x2;
	bufptr = req->Buffer;
	memcpy(bufptr, &asteriks, len);

	req->FileNameOffset =
4937
		cpu_to_le16(sizeof(struct smb2_query_directory_req));
4938 4939 4940 4941 4942 4943 4944 4945 4946 4947
	req->FileNameLength = cpu_to_le16(len);
	/*
	 * BB could be 30 bytes or so longer if we used SMB2 specific
	 * buffer lengths, but this is safe and close enough.
	 */
	output_size = min_t(unsigned int, output_size, server->maxBuf);
	output_size = min_t(unsigned int, output_size, 2 << 15);
	req->OutputBufferLength = cpu_to_le32(output_size);

	iov[0].iov_base = (char *)req;
4948 4949
	/* 1 for Buffer */
	iov[0].iov_len = total_len - 1;
4950 4951 4952 4953

	iov[1].iov_base = (char *)(req->Buffer);
	iov[1].iov_len = len;

4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966
	trace_smb3_query_dir_enter(xid, persistent_fid, tcon->tid,
			tcon->ses->Suid, index, output_size);

	return 0;
}

void SMB2_query_directory_free(struct smb_rqst *rqst)
{
	if (rqst && rqst->rq_iov) {
		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
	}
}

4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981
int
smb2_parse_query_directory(struct cifs_tcon *tcon,
			   struct kvec *rsp_iov,
			   int resp_buftype,
			   struct cifs_search_info *srch_inf)
{
	struct smb2_query_directory_rsp *rsp;
	size_t info_buf_size;
	char *end_of_smb;
	int rc;

	rsp = (struct smb2_query_directory_rsp *)rsp_iov->iov_base;

	switch (srch_inf->info_level) {
	case SMB_FIND_FILE_DIRECTORY_INFO:
4982
		info_buf_size = sizeof(FILE_DIRECTORY_INFO);
4983 4984
		break;
	case SMB_FIND_FILE_ID_FULL_DIR_INFO:
4985
		info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO);
4986
		break;
4987 4988 4989 4990
	case SMB_FIND_FILE_POSIX_INFO:
		/* note that posix payload are variable size */
		info_buf_size = sizeof(struct smb2_posix_info);
		break;
4991 4992 4993 4994 4995 4996 4997 4998 4999
	default:
		cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
			 srch_inf->info_level);
		return -EINVAL;
	}

	rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
			       le32_to_cpu(rsp->OutputBufferLength), rsp_iov,
			       info_buf_size);
5000 5001
	if (rc) {
		cifs_tcon_dbg(VFS, "bad info payload");
5002
		return rc;
5003
	}
5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016

	srch_inf->unicode = true;

	if (srch_inf->ntwrk_buf_start) {
		if (srch_inf->smallBuf)
			cifs_small_buf_release(srch_inf->ntwrk_buf_start);
		else
			cifs_buf_release(srch_inf->ntwrk_buf_start);
	}
	srch_inf->ntwrk_buf_start = (char *)rsp;
	srch_inf->srch_entries_start = srch_inf->last_entry =
		(char *)rsp + le16_to_cpu(rsp->OutputBufferOffset);
	end_of_smb = rsp_iov->iov_len + (char *)rsp;
5017 5018 5019 5020 5021 5022 5023 5024

	srch_inf->entries_in_buffer = num_entries(
		srch_inf->info_level,
		srch_inf->srch_entries_start,
		end_of_smb,
		&srch_inf->last_entry,
		info_buf_size);

5025 5026 5027 5028 5029 5030 5031 5032 5033
	srch_inf->index_of_last_entry += srch_inf->entries_in_buffer;
	cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n",
		 srch_inf->entries_in_buffer, srch_inf->index_of_last_entry,
		 srch_inf->srch_entries_start, srch_inf->last_entry);
	if (resp_buftype == CIFS_LARGE_BUFFER)
		srch_inf->smallBuf = false;
	else if (resp_buftype == CIFS_SMALL_BUFFER)
		srch_inf->smallBuf = true;
	else
5034
		cifs_tcon_dbg(VFS, "Invalid search buffer type\n");
5035 5036 5037 5038

	return 0;
}

5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050
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)
{
	struct smb_rqst rqst;
	struct kvec iov[SMB2_QUERY_DIRECTORY_IOV_SIZE];
	struct smb2_query_directory_rsp *rsp = NULL;
	int resp_buftype = CIFS_NO_BUFFER;
	struct kvec rsp_iov;
	int rc = 0;
	struct cifs_ses *ses = tcon->ses;
5051
	struct TCP_Server_Info *server = cifs_pick_channel(ses);
5052 5053
	int flags = 0;

5054
	if (!ses || !(ses->server))
5055 5056 5057 5058 5059
		return -EIO;

	if (smb3_encryption_required(tcon))
		flags |= CIFS_TRANSFORM_REQ;

5060
	memset(&rqst, 0, sizeof(struct smb_rqst));
5061
	memset(&iov, 0, sizeof(iov));
5062
	rqst.rq_iov = iov;
5063
	rqst.rq_nvec = SMB2_QUERY_DIRECTORY_IOV_SIZE;
5064

5065 5066
	rc = SMB2_query_directory_init(xid, tcon, server,
				       &rqst, persistent_fid,
5067 5068 5069 5070
				       volatile_fid, index,
				       srch_inf->info_level);
	if (rc)
		goto qdir_exit;
5071

5072 5073
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
5074
	rsp = (struct smb2_query_directory_rsp *)rsp_iov.iov_base;
5075

5076
	if (rc) {
5077
		if (rc == -ENODATA &&
5078
		    rsp->hdr.Status == STATUS_NO_MORE_FILES) {
5079 5080
			trace_smb3_query_dir_done(xid, persistent_fid,
				tcon->tid, tcon->ses->Suid, index, 0);
5081 5082
			srch_inf->endOfSearch = true;
			rc = 0;
5083 5084 5085
		} else {
			trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
				tcon->ses->Suid, index, 0, rc);
5086
			cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE);
5087
		}
5088 5089 5090
		goto qdir_exit;
	}

5091 5092
	rc = smb2_parse_query_directory(tcon, &rsp_iov,	resp_buftype,
					srch_inf);
5093 5094 5095
	if (rc) {
		trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
			tcon->ses->Suid, index, 0, rc);
5096
		goto qdir_exit;
5097
	}
5098 5099
	resp_buftype = CIFS_NO_BUFFER;

5100 5101
	trace_smb3_query_dir_done(xid, persistent_fid, tcon->tid,
			tcon->ses->Suid, index, srch_inf->entries_in_buffer);
5102 5103

qdir_exit:
5104
	SMB2_query_directory_free(&rqst);
5105 5106 5107 5108
	free_rsp_buf(resp_buftype, rsp);
	return rc;
}

5109
int
5110 5111 5112 5113 5114
SMB2_set_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
		   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)
5115 5116
{
	struct smb2_set_info_req *req;
5117 5118 5119
	struct kvec *iov = rqst->rq_iov;
	unsigned int i, total_len;
	int rc;
5120

5121 5122
	rc = smb2_plain_req_init(SMB2_SET_INFO, tcon, server,
				 (void **) &req, &total_len);
5123
	if (rc)
5124
		return rc;
5125

5126
	req->hdr.Id.SyncId.ProcessId = cpu_to_le32(pid);
5127
	req->InfoType = info_type;
5128 5129 5130
	req->FileInfoClass = info_class;
	req->PersistentFileId = persistent_fid;
	req->VolatileFileId = volatile_fid;
5131
	req->AdditionalInformation = cpu_to_le32(additional_info);
5132

5133
	req->BufferOffset = cpu_to_le16(sizeof(struct smb2_set_info_req));
5134 5135 5136
	req->BufferLength = cpu_to_le32(*size);

	memcpy(req->Buffer, *data, *size);
5137
	total_len += *size;
5138 5139

	iov[0].iov_base = (char *)req;
5140 5141
	/* 1 for Buffer */
	iov[0].iov_len = total_len - 1;
5142

5143
	for (i = 1; i < rqst->rq_nvec; i++) {
5144 5145 5146 5147 5148
		le32_add_cpu(&req->BufferLength, size[i]);
		iov[i].iov_base = (char *)data[i];
		iov[i].iov_len = size[i];
	}

5149 5150 5151 5152 5153 5154
	return 0;
}

void
SMB2_set_info_free(struct smb_rqst *rqst)
{
5155 5156
	if (rqst && rqst->rq_iov)
		cifs_buf_release(rqst->rq_iov[0].iov_base); /* request */
5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171
}

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)
{
	struct smb_rqst rqst;
	struct smb2_set_info_rsp *rsp = NULL;
	struct kvec *iov;
	struct kvec rsp_iov;
	int rc = 0;
	int resp_buftype;
	struct cifs_ses *ses = tcon->ses;
5172
	struct TCP_Server_Info *server = cifs_pick_channel(ses);
5173 5174
	int flags = 0;

5175
	if (!ses || !server)
5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187
		return -EIO;

	if (!num)
		return -EINVAL;

	if (smb3_encryption_required(tcon))
		flags |= CIFS_TRANSFORM_REQ;

	iov = kmalloc_array(num, sizeof(struct kvec), GFP_KERNEL);
	if (!iov)
		return -ENOMEM;

5188 5189 5190 5191
	memset(&rqst, 0, sizeof(struct smb_rqst));
	rqst.rq_iov = iov;
	rqst.rq_nvec = num;

5192 5193
	rc = SMB2_set_info_init(tcon, server,
				&rqst, persistent_fid, volatile_fid, pid,
5194 5195 5196 5197 5198 5199 5200 5201
				info_class, info_type, additional_info,
				data, size);
	if (rc) {
		kfree(iov);
		return rc;
	}


5202 5203
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags,
5204
			    &rsp_iov);
5205
	SMB2_set_info_free(&rqst);
5206
	rsp = (struct smb2_set_info_rsp *)rsp_iov.iov_base;
5207

5208
	if (rc != 0) {
5209
		cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE);
5210 5211 5212
		trace_smb3_set_info_err(xid, persistent_fid, tcon->tid,
				ses->Suid, info_class, (__u32)info_type, rc);
	}
5213

5214 5215 5216 5217 5218
	free_rsp_buf(resp_buftype, rsp);
	kfree(iov);
	return rc;
}

5219 5220
int
SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
5221
	     u64 volatile_fid, u32 pid, __le64 *eof)
5222 5223 5224 5225 5226 5227 5228 5229 5230 5231
{
	struct smb2_file_eof_info info;
	void *data;
	unsigned int size;

	info.EndOfFile = *eof;

	data = &info;
	size = sizeof(struct smb2_file_eof_info);

5232 5233
	trace_smb3_set_eof(xid, persistent_fid, tcon->tid, tcon->ses->Suid, le64_to_cpu(*eof));

5234
	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5235 5236
			pid, FILE_END_OF_FILE_INFORMATION, SMB2_O_INFO_FILE,
			0, 1, &data, &size);
5237
}
5238

5239 5240 5241 5242 5243 5244 5245 5246
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)
{
	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
			current->tgid, 0, SMB2_O_INFO_SECURITY, aclflag,
			1, (void **)&pnntsd, &pacllen);
5247
}
5248

5249 5250 5251 5252 5253 5254 5255 5256 5257 5258
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)
{
	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
		current->tgid, FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE,
		0, 1, (void **)&buf, &len);
}

5259 5260 5261 5262 5263
int
SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon,
		  const u64 persistent_fid, const u64 volatile_fid,
		  __u8 oplock_level)
{
5264
	struct smb_rqst rqst;
5265
	int rc;
5266
	struct smb2_oplock_break *req = NULL;
5267
	struct cifs_ses *ses = tcon->ses;
5268
	struct TCP_Server_Info *server = cifs_pick_channel(ses);
5269
	int flags = CIFS_OBREAK_OP;
5270 5271 5272 5273
	unsigned int total_len;
	struct kvec iov[1];
	struct kvec rsp_iov;
	int resp_buf_type;
5274

5275
	cifs_dbg(FYI, "SMB2_oplock_break\n");
5276 5277
	rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
				 (void **) &req, &total_len);
5278 5279 5280
	if (rc)
		return rc;

5281
	if (smb3_encryption_required(tcon))
5282 5283
		flags |= CIFS_TRANSFORM_REQ;

5284 5285 5286
	req->VolatileFid = volatile_fid;
	req->PersistentFid = persistent_fid;
	req->OplockLevel = oplock_level;
5287
	req->hdr.CreditRequest = cpu_to_le16(1);
5288

5289
	flags |= CIFS_NO_RSP_BUF;
5290 5291 5292 5293

	iov[0].iov_base = (char *)req;
	iov[0].iov_len = total_len;

5294 5295 5296 5297
	memset(&rqst, 0, sizeof(struct smb_rqst));
	rqst.rq_iov = iov;
	rqst.rq_nvec = 1;

5298 5299
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buf_type, flags, &rsp_iov);
5300
	cifs_small_buf_release(req);
5301 5302 5303

	if (rc) {
		cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
5304
		cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc);
5305 5306 5307 5308
	}

	return rc;
}
5309

5310 5311 5312
void
smb2_copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf,
			     struct kstatfs *kst)
5313 5314 5315 5316
{
	kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) *
			  le32_to_cpu(pfs_inf->SectorsPerAllocationUnit);
	kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits);
5317 5318
	kst->f_bfree  = kst->f_bavail =
			le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits);
5319 5320 5321
	return;
}

5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340
static void
copy_posix_fs_info_to_kstatfs(FILE_SYSTEM_POSIX_INFO *response_data,
			struct kstatfs *kst)
{
	kst->f_bsize = le32_to_cpu(response_data->BlockSize);
	kst->f_blocks = le64_to_cpu(response_data->TotalBlocks);
	kst->f_bfree =  le64_to_cpu(response_data->BlocksAvail);
	if (response_data->UserBlocksAvail == cpu_to_le64(-1))
		kst->f_bavail = kst->f_bfree;
	else
		kst->f_bavail = le64_to_cpu(response_data->UserBlocksAvail);
	if (response_data->TotalFileNodes != cpu_to_le64(-1))
		kst->f_files = le64_to_cpu(response_data->TotalFileNodes);
	if (response_data->FreeFileNodes != cpu_to_le64(-1))
		kst->f_ffree = le64_to_cpu(response_data->FreeFileNodes);

	return;
}

5341
static int
5342 5343 5344 5345
build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon,
		   struct TCP_Server_Info *server,
		   int level, int outbuf_len, u64 persistent_fid,
		   u64 volatile_fid)
5346 5347 5348
{
	int rc;
	struct smb2_query_info_req *req;
5349
	unsigned int total_len;
5350

5351
	cifs_dbg(FYI, "Query FSInfo level %d\n", level);
5352

5353
	if ((tcon->ses == NULL) || server == NULL)
5354 5355
		return -EIO;

5356 5357
	rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
				 (void **) &req, &total_len);
5358 5359 5360 5361 5362 5363 5364
	if (rc)
		return rc;

	req->InfoType = SMB2_O_INFO_FILESYSTEM;
	req->FileInfoClass = level;
	req->PersistentFileId = persistent_fid;
	req->VolatileFileId = volatile_fid;
5365
	/* 1 for pad */
5366
	req->InputBufferOffset =
5367
			cpu_to_le16(sizeof(struct smb2_query_info_req));
5368
	req->OutputBufferLength = cpu_to_le32(
5369
		outbuf_len + sizeof(struct smb2_query_info_rsp));
5370 5371

	iov->iov_base = (char *)req;
5372
	iov->iov_len = total_len;
5373 5374 5375
	return 0;
}

5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386
int
SMB311_posix_qfs_info(const unsigned int xid, struct cifs_tcon *tcon,
	      u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
{
	struct smb_rqst rqst;
	struct smb2_query_info_rsp *rsp = NULL;
	struct kvec iov;
	struct kvec rsp_iov;
	int rc = 0;
	int resp_buftype;
	struct cifs_ses *ses = tcon->ses;
5387
	struct TCP_Server_Info *server = cifs_pick_channel(ses);
5388 5389 5390
	FILE_SYSTEM_POSIX_INFO *info = NULL;
	int flags = 0;

5391 5392
	rc = build_qfs_info_req(&iov, tcon, server,
				FS_POSIX_INFORMATION,
5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404
				sizeof(FILE_SYSTEM_POSIX_INFO),
				persistent_fid, volatile_fid);
	if (rc)
		return rc;

	if (smb3_encryption_required(tcon))
		flags |= CIFS_TRANSFORM_REQ;

	memset(&rqst, 0, sizeof(struct smb_rqst));
	rqst.rq_iov = &iov;
	rqst.rq_nvec = 1;

5405 5406
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
5407 5408 5409 5410 5411 5412 5413 5414 5415
	cifs_small_buf_release(iov.iov_base);
	if (rc) {
		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
		goto posix_qfsinf_exit;
	}
	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;

	info = (FILE_SYSTEM_POSIX_INFO *)(
		le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
5416 5417 5418
	rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
			       le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
			       sizeof(FILE_SYSTEM_POSIX_INFO));
5419 5420 5421 5422 5423 5424 5425 5426
	if (!rc)
		copy_posix_fs_info_to_kstatfs(info, fsdata);

posix_qfsinf_exit:
	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
	return rc;
}

5427 5428 5429 5430
int
SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon,
	      u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
{
5431
	struct smb_rqst rqst;
5432 5433
	struct smb2_query_info_rsp *rsp = NULL;
	struct kvec iov;
5434
	struct kvec rsp_iov;
5435 5436 5437
	int rc = 0;
	int resp_buftype;
	struct cifs_ses *ses = tcon->ses;
5438
	struct TCP_Server_Info *server = cifs_pick_channel(ses);
5439
	struct smb2_fs_full_size_info *info = NULL;
5440
	int flags = 0;
5441

5442 5443
	rc = build_qfs_info_req(&iov, tcon, server,
				FS_FULL_SIZE_INFORMATION,
5444 5445 5446 5447 5448
				sizeof(struct smb2_fs_full_size_info),
				persistent_fid, volatile_fid);
	if (rc)
		return rc;

5449
	if (smb3_encryption_required(tcon))
5450 5451
		flags |= CIFS_TRANSFORM_REQ;

5452 5453 5454 5455
	memset(&rqst, 0, sizeof(struct smb_rqst));
	rqst.rq_iov = &iov;
	rqst.rq_nvec = 1;

5456 5457
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
5458
	cifs_small_buf_release(iov.iov_base);
5459 5460
	if (rc) {
		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5461
		goto qfsinf_exit;
5462
	}
5463
	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5464

5465
	info = (struct smb2_fs_full_size_info *)(
5466
		le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
5467 5468 5469
	rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
			       le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
			       sizeof(struct smb2_fs_full_size_info));
5470
	if (!rc)
5471
		smb2_copy_fs_info_to_kstatfs(info, fsdata);
5472

5473
qfsinf_exit:
5474
	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5475 5476 5477 5478 5479
	return rc;
}

int
SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon,
5480
	      u64 persistent_fid, u64 volatile_fid, int level)
5481
{
5482
	struct smb_rqst rqst;
5483 5484
	struct smb2_query_info_rsp *rsp = NULL;
	struct kvec iov;
5485
	struct kvec rsp_iov;
5486
	int rc = 0;
5487
	int resp_buftype, max_len, min_len;
5488
	struct cifs_ses *ses = tcon->ses;
5489
	struct TCP_Server_Info *server = cifs_pick_channel(ses);
5490
	unsigned int rsp_len, offset;
5491
	int flags = 0;
5492

5493 5494 5495 5496 5497 5498
	if (level == FS_DEVICE_INFORMATION) {
		max_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
		min_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
	} else if (level == FS_ATTRIBUTE_INFORMATION) {
		max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO);
		min_len = MIN_FS_ATTR_INFO_SIZE;
Steven French's avatar
Steven French committed
5499 5500 5501
	} else if (level == FS_SECTOR_SIZE_INFORMATION) {
		max_len = sizeof(struct smb3_fs_ss_info);
		min_len = sizeof(struct smb3_fs_ss_info);
5502 5503 5504
	} else if (level == FS_VOLUME_INFORMATION) {
		max_len = sizeof(struct smb3_fs_vol_info) + MAX_VOL_LABEL_LEN;
		min_len = sizeof(struct smb3_fs_vol_info);
5505
	} else {
Steven French's avatar
Steven French committed
5506
		cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level);
5507 5508 5509
		return -EINVAL;
	}

5510 5511
	rc = build_qfs_info_req(&iov, tcon, server,
				level, max_len,
5512 5513 5514 5515
				persistent_fid, volatile_fid);
	if (rc)
		return rc;

5516
	if (smb3_encryption_required(tcon))
5517 5518
		flags |= CIFS_TRANSFORM_REQ;

5519 5520 5521 5522
	memset(&rqst, 0, sizeof(struct smb_rqst));
	rqst.rq_iov = &iov;
	rqst.rq_nvec = 1;

5523 5524
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
5525
	cifs_small_buf_release(iov.iov_base);
5526 5527 5528 5529
	if (rc) {
		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
		goto qfsattr_exit;
	}
5530
	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5531 5532 5533

	rsp_len = le32_to_cpu(rsp->OutputBufferLength);
	offset = le16_to_cpu(rsp->OutputBufferOffset);
5534
	rc = smb2_validate_iov(offset, rsp_len, &rsp_iov, min_len);
5535 5536 5537 5538
	if (rc)
		goto qfsattr_exit;

	if (level == FS_ATTRIBUTE_INFORMATION)
5539
		memcpy(&tcon->fsAttrInfo, offset
5540
			+ (char *)rsp, min_t(unsigned int,
5541 5542
			rsp_len, max_len));
	else if (level == FS_DEVICE_INFORMATION)
5543
		memcpy(&tcon->fsDevInfo, offset
5544
			+ (char *)rsp, sizeof(FILE_SYSTEM_DEVICE_INFO));
Steven French's avatar
Steven French committed
5545 5546
	else if (level == FS_SECTOR_SIZE_INFORMATION) {
		struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *)
5547
			(offset + (char *)rsp);
Steven French's avatar
Steven French committed
5548 5549 5550
		tcon->ss_flags = le32_to_cpu(ss_info->Flags);
		tcon->perf_sector_size =
			le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf);
5551 5552 5553 5554 5555
	} else if (level == FS_VOLUME_INFORMATION) {
		struct smb3_fs_vol_info *vol_info = (struct smb3_fs_vol_info *)
			(offset + (char *)rsp);
		tcon->vol_serial_number = vol_info->VolumeSerialNumber;
		tcon->vol_create_time = vol_info->VolumeCreationTime;
Steven French's avatar
Steven French committed
5556
	}
5557 5558

qfsattr_exit:
5559
	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5560 5561
	return rc;
}
5562 5563 5564 5565 5566 5567

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)
{
5568
	struct smb_rqst rqst;
5569 5570 5571
	int rc = 0;
	struct smb2_lock_req *req = NULL;
	struct kvec iov[2];
5572
	struct kvec rsp_iov;
5573 5574
	int resp_buf_type;
	unsigned int count;
5575
	int flags = CIFS_NO_RSP_BUF;
5576
	unsigned int total_len;
5577
	struct TCP_Server_Info *server = cifs_pick_channel(tcon->ses);
5578

5579
	cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock);
5580

5581 5582
	rc = smb2_plain_req_init(SMB2_LOCK, tcon, server,
				 (void **) &req, &total_len);
5583 5584 5585
	if (rc)
		return rc;

5586
	if (smb3_encryption_required(tcon))
5587 5588
		flags |= CIFS_TRANSFORM_REQ;

5589
	req->hdr.Id.SyncId.ProcessId = cpu_to_le32(pid);
5590 5591 5592 5593 5594 5595 5596 5597
	req->LockCount = cpu_to_le16(num_lock);

	req->PersistentFileId = persist_fid;
	req->VolatileFileId = volatile_fid;

	count = num_lock * sizeof(struct smb2_lock_element);

	iov[0].iov_base = (char *)req;
5598
	iov[0].iov_len = total_len - sizeof(struct smb2_lock_element);
5599 5600 5601 5602
	iov[1].iov_base = (char *)buf;
	iov[1].iov_len = count;

	cifs_stats_inc(&tcon->stats.cifs_stats.num_locks);
5603 5604 5605 5606 5607

	memset(&rqst, 0, sizeof(struct smb_rqst));
	rqst.rq_iov = iov;
	rqst.rq_nvec = 2;

5608 5609
	rc = cifs_send_recv(xid, tcon->ses, server,
			    &rqst, &resp_buf_type, flags,
5610
			    &rsp_iov);
5611
	cifs_small_buf_release(req);
5612
	if (rc) {
5613
		cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc);
5614
		cifs_stats_fail_inc(tcon, SMB2_LOCK_HE);
5615 5616
		trace_smb3_lock_err(xid, persist_fid, tcon->tid,
				    tcon->ses->Suid, rc);
5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637
	}

	return rc;
}

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)
{
	struct smb2_lock_element lock;

	lock.Offset = cpu_to_le64(offset);
	lock.Length = cpu_to_le64(length);
	lock.Flags = cpu_to_le32(lock_flags);
	if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK)
		lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY);

	return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock);
}
5638 5639 5640 5641 5642

int
SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon,
		 __u8 *lease_key, const __le32 lease_state)
{
5643
	struct smb_rqst rqst;
5644 5645
	int rc;
	struct smb2_lease_ack *req = NULL;
5646
	struct cifs_ses *ses = tcon->ses;
5647
	int flags = CIFS_OBREAK_OP;
5648 5649 5650 5651
	unsigned int total_len;
	struct kvec iov[1];
	struct kvec rsp_iov;
	int resp_buf_type;
5652 5653
	__u64 *please_key_high;
	__u64 *please_key_low;
5654
	struct TCP_Server_Info *server = cifs_pick_channel(tcon->ses);
5655

5656
	cifs_dbg(FYI, "SMB2_lease_break\n");
5657 5658
	rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
				 (void **) &req, &total_len);
5659 5660 5661
	if (rc)
		return rc;

5662
	if (smb3_encryption_required(tcon))
5663 5664
		flags |= CIFS_TRANSFORM_REQ;

5665
	req->hdr.CreditRequest = cpu_to_le16(1);
5666
	req->StructureSize = cpu_to_le16(36);
5667
	total_len += 12;
5668 5669 5670 5671

	memcpy(req->LeaseKey, lease_key, 16);
	req->LeaseState = lease_state;

5672
	flags |= CIFS_NO_RSP_BUF;
5673 5674 5675 5676

	iov[0].iov_base = (char *)req;
	iov[0].iov_len = total_len;

5677 5678 5679 5680
	memset(&rqst, 0, sizeof(struct smb_rqst));
	rqst.rq_iov = iov;
	rqst.rq_nvec = 1;

5681 5682
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buf_type, flags, &rsp_iov);
5683
	cifs_small_buf_release(req);
5684

5685 5686
	please_key_low = (__u64 *)lease_key;
	please_key_high = (__u64 *)(lease_key+8);
5687 5688
	if (rc) {
		cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
5689 5690
		trace_smb3_lease_err(le32_to_cpu(lease_state), tcon->tid,
			ses->Suid, *please_key_low, *please_key_high, rc);
5691
		cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc);
5692 5693 5694
	} else
		trace_smb3_lease_done(le32_to_cpu(lease_state), tcon->tid,
			ses->Suid, *please_key_low, *please_key_high);
5695 5696 5697

	return rc;
}