smb2pdu.c 169 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
#include <linux/xattr.h>
26 27
#include <linux/netfs.h>
#include <trace/events/netfs.h>
28 29 30 31 32 33 34 35
#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"
36
#include "smb2glob.h"
37
#include "cifspdu.h"
38
#include "cifs_spnego.h"
39
#include "smbdirect.h"
40
#include "trace.h"
41 42 43
#ifdef CONFIG_CIFS_DFS_UPCALL
#include "dfs_cache.h"
#endif
44
#include "cached_dir.h"
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 73 74

/*
 *  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 */
};

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

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

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

99
	if (server) {
100 101 102 103 104 105 106 107 108 109 110 111 112 113
		/* 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);
		}
114
		spin_lock(&server->req_lock);
115
		/* Request up to 10 credits but don't go over the limit. */
116
		if (server->credits >= server->max_credits)
117
			shdr->CreditRequest = cpu_to_le16(0);
118
		else
119
			shdr->CreditRequest = cpu_to_le16(
120
				min_t(int, server->max_credits -
121
						server->credits, 10));
122 123
		spin_unlock(&server->req_lock);
	} else {
124
		shdr->CreditRequest = cpu_to_le16(2);
125
	}
126
	shdr->Id.SyncId.ProcessId = cpu_to_le32((__u16)current->tgid);
127 128 129 130

	if (!tcon)
		goto out;

131 132
	/* 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 */
133
	if (server && (server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
134
		shdr->CreditCharge = cpu_to_le16(1);
135 136
	/* else CreditCharge MBZ */

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

	/*
	 * 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)
153
		shdr->Flags |= SMB2_FLAGS_DFS_OPERATIONS; */
154

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

161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
/* helper function for code reuse */
static int
cifs_chan_skip_or_disable(struct cifs_ses *ses,
			  struct TCP_Server_Info *server,
			  bool from_reconnect)
{
	struct TCP_Server_Info *pserver;
	unsigned int chan_index;

	if (SERVER_IS_CHAN(server)) {
		cifs_dbg(VFS,
			"server %s does not support multichannel anymore. Skip secondary channel\n",
			 ses->server->hostname);

		spin_lock(&ses->chan_lock);
		chan_index = cifs_ses_get_chan_index(ses, server);
		if (chan_index == CIFS_INVAL_CHAN_INDEX) {
			spin_unlock(&ses->chan_lock);
			goto skip_terminate;
		}

		ses->chans[chan_index].server = NULL;
183
		server->terminate = true;
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
		spin_unlock(&ses->chan_lock);

		/*
		 * the above reference of server by channel
		 * needs to be dropped without holding chan_lock
		 * as cifs_put_tcp_session takes a higher lock
		 * i.e. cifs_tcp_ses_lock
		 */
		cifs_put_tcp_session(server, from_reconnect);

		cifs_signal_cifsd_for_reconnect(server, false);

		/* mark primary server as needing reconnect */
		pserver = server->primary_server;
		cifs_signal_cifsd_for_reconnect(pserver, false);
skip_terminate:
		return -EHOSTDOWN;
	}

	cifs_server_dbg(VFS,
		"server does not support multichannel anymore. Disable all other channels\n");
	cifs_disable_secondary_channels(ses);


	return 0;
}

211
static int
212
smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon,
213
	       struct TCP_Server_Info *server, bool from_reconnect)
214
{
215
	int rc = 0;
216
	struct nls_table *nls_codepage = NULL;
217
	struct cifs_ses *ses;
218
	int xid;
219 220 221 222 223 224 225

	/*
	 * 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)
226
		return 0;
227

228 229 230 231 232
	/*
	 * 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)
233
		return 0;
234

235
	spin_lock(&tcon->tc_lock);
236
	if (tcon->status == TID_EXITING) {
237
		/*
238
		 * only tree disconnect allowed when disconnecting ...
239
		 */
240
		if (smb2_command != SMB2_TREE_DISCONNECT) {
241
			spin_unlock(&tcon->tc_lock);
242 243
			cifs_dbg(FYI, "can not send cmd %d while umounting\n",
				 smb2_command);
244 245 246
			return -ENODEV;
		}
	}
247
	spin_unlock(&tcon->tc_lock);
248 249 250 251 252 253 254 255 256 257 258

	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)
259 260
		return -EIO;

261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
	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;
		}
	}
279 280 281 282 283 284

	/* if server is marked for termination, cifsd will cleanup */
	if (server->terminate) {
		spin_unlock(&server->srv_lock);
		return -EHOSTDOWN;
	}
285 286
	spin_unlock(&server->srv_lock);

287
again:
288
	rc = cifs_wait_for_server_reconnect(server, tcon->retry);
289 290
	if (rc)
		return rc;
291

292 293 294
	spin_lock(&ses->chan_lock);
	if (!cifs_chan_needs_reconnect(ses, server) && !tcon->need_reconnect) {
		spin_unlock(&ses->chan_lock);
295
		return 0;
296
	}
297
	spin_unlock(&ses->chan_lock);
298 299 300
	cifs_dbg(FYI, "sess reconnect mask: 0x%lx, tcon reconnect: %d",
		 tcon->ses->chans_need_reconnect,
		 tcon->need_reconnect);
301

302
	mutex_lock(&ses->session_mutex);
303 304 305 306 307 308 309 310 311 312 313 314 315
	/*
	 * if this is called by delayed work, and the channel has been disabled
	 * in parallel, the delayed work can continue to execute in parallel
	 * there's a chance that this channel may not exist anymore
	 */
	spin_lock(&server->srv_lock);
	if (server->tcpStatus == CifsExiting) {
		spin_unlock(&server->srv_lock);
		mutex_unlock(&ses->session_mutex);
		rc = -EHOSTDOWN;
		goto out;
	}

316 317 318 319 320 321
	/*
	 * 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.
	 */
	if (server->tcpStatus == CifsNeedReconnect) {
322
		spin_unlock(&server->srv_lock);
323 324 325 326 327
		mutex_unlock(&ses->session_mutex);

		if (tcon->retry)
			goto again;

328 329 330
		rc = -EHOSTDOWN;
		goto out;
	}
331
	spin_unlock(&server->srv_lock);
332

333
	nls_codepage = ses->local_nls;
334

335 336 337 338
	/*
	 * need to prevent multiple threads trying to simultaneously
	 * reconnect the same SMB session
	 */
339
	spin_lock(&ses->ses_lock);
340
	spin_lock(&ses->chan_lock);
341 342
	if (!cifs_chan_needs_reconnect(ses, server) &&
	    ses->ses_status == SES_GOOD) {
343
		spin_unlock(&ses->chan_lock);
344
		spin_unlock(&ses->ses_lock);
345
		/* this means that we only need to tree connect */
346 347 348
		if (tcon->need_reconnect)
			goto skip_sess_setup;

349
		mutex_unlock(&ses->session_mutex);
350 351 352
		goto out;
	}
	spin_unlock(&ses->chan_lock);
353
	spin_unlock(&ses->ses_lock);
354

355
	rc = cifs_negotiate_protocol(0, ses, server);
356
	if (!rc) {
357 358 359 360 361 362
		/*
		 * if server stopped supporting multichannel
		 * and the first channel reconnected, disable all the others.
		 */
		if (ses->chan_count > 1 &&
		    !(server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL)) {
363 364 365
			rc = cifs_chan_skip_or_disable(ses, server,
						       from_reconnect);
			if (rc) {
366 367 368 369 370
				mutex_unlock(&ses->session_mutex);
				goto out;
			}
		}

371
		rc = cifs_setup_session(0, ses, server, nls_codepage);
372 373 374 375 376 377 378 379 380 381 382
		if ((rc == -EACCES) || (rc == -EKEYEXPIRED) || (rc == -EKEYREVOKED)) {
			/*
			 * Try alternate password for next reconnect (key rotation
			 * could be enabled on the server e.g.) if an alternate
			 * password is available and the current password is expired,
			 * but do not swap on non pwd related errors like host down
			 */
			if (ses->password2)
				swap(ses->password2, ses->password);
		}

383
		if ((rc == -EACCES) && !tcon->retry) {
384
			mutex_unlock(&ses->session_mutex);
385
			rc = -EHOSTDOWN;
386
			goto failed;
387 388 389
		} else if (rc) {
			mutex_unlock(&ses->session_mutex);
			goto out;
390
		}
391
	} else {
392
		mutex_unlock(&ses->session_mutex);
393 394 395
		goto out;
	}

396
skip_sess_setup:
397 398 399 400
	if (!tcon->need_reconnect) {
		mutex_unlock(&ses->session_mutex);
		goto out;
	}
401
	cifs_mark_open_files_invalid(tcon);
402 403
	if (tcon->use_persistent)
		tcon->need_reopen_files = true;
404

405
	rc = cifs_tree_connect(0, tcon, nls_codepage);
406

407
	cifs_dbg(FYI, "reconnect tcon rc = %d\n", rc);
408 409
	if (rc) {
		/* If sess reconnected but tcon didn't, something strange ... */
410
		mutex_unlock(&ses->session_mutex);
411
		cifs_dbg(VFS, "reconnect tcon failed rc = %d\n", rc);
412
		goto out;
413
	}
414

415 416 417 418 419 420 421 422 423
	spin_lock(&ses->ses_lock);
	if (ses->flags & CIFS_SES_FLAG_SCALE_CHANNELS) {
		spin_unlock(&ses->ses_lock);
		mutex_unlock(&ses->session_mutex);
		goto skip_add_channels;
	}
	ses->flags |= CIFS_SES_FLAG_SCALE_CHANNELS;
	spin_unlock(&ses->ses_lock);

424
	if (!rc &&
425 426
	    (server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL) &&
	    server->ops->query_server_interfaces) {
427 428 429 430 431 432
		mutex_unlock(&ses->session_mutex);

		/*
		 * query server network interfaces, in case they change
		 */
		xid = get_xid();
433
		rc = server->ops->query_server_interfaces(xid, tcon, false);
434 435
		free_xid(xid);

436
		if (rc == -EOPNOTSUPP && ses->chan_count > 1) {
437 438 439 440 441 442 443 444 445 446 447
			/*
			 * some servers like Azure SMB server do not advertise
			 * that multichannel has been disabled with server
			 * capabilities, rather return STATUS_NOT_IMPLEMENTED.
			 * treat this as server not supporting multichannel
			 */

			rc = cifs_chan_skip_or_disable(ses, server,
						       from_reconnect);
			goto skip_add_channels;
		} else if (rc)
448 449 450 451
			cifs_dbg(FYI, "%s: failed to query server interfaces: %d\n",
				 __func__, rc);

		if (ses->chan_max > ses->chan_count &&
452
		    ses->iface_count &&
453
		    !SERVER_IS_CHAN(server)) {
454
			if (ses->chan_count == 1) {
455
				cifs_server_dbg(VFS, "supports multichannel now\n");
456 457 458
				queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
						 (SMB_INTERFACE_POLL_INTERVAL * HZ));
			}
459 460 461 462 463 464

			cifs_try_adding_channels(ses);
		}
	} else {
		mutex_unlock(&ses->session_mutex);
	}
465

466
skip_add_channels:
467 468 469
	spin_lock(&ses->ses_lock);
	ses->flags &= ~CIFS_SES_FLAG_SCALE_CHANNELS;
	spin_unlock(&ses->ses_lock);
470

471
	if (smb2_command != SMB2_INTERNAL_CMD)
472
		mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
473

474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
	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:
493
		rc = -EAGAIN;
494
	}
495
failed:
496 497 498
	return rc;
}

499
static void
500 501 502
fill_small_buf(__le16 smb2_command, struct cifs_tcon *tcon,
	       struct TCP_Server_Info *server,
	       void *buf,
503 504
	       unsigned int *total_len)
{
505
	struct smb2_pdu *spdu = buf;
506 507 508 509 510 511 512 513 514
	/* 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);

515
	smb2_hdr_assemble(&spdu->hdr, smb2_command, tcon, server);
516 517
	spdu->StructureSize2 = cpu_to_le16(parmsize);

518
	*total_len = parmsize + sizeof(struct smb2_hdr);
519 520
}

521 522 523
/*
 * 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
524
 * function must have filled in request_buf pointer.
525
 */
526
static int __smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
527 528
				 struct TCP_Server_Info *server,
				 void **request_buf, unsigned int *total_len)
529 530
{
	/* BB eventually switch this to SMB2 specific small buf size */
531 532 533
	switch (smb2_command) {
	case SMB2_SET_INFO:
	case SMB2_QUERY_INFO:
534
		*request_buf = cifs_buf_get();
535 536
		break;
	default:
537
		*request_buf = cifs_small_buf_get();
538 539
		break;
	}
540 541 542 543 544
	if (*request_buf == NULL) {
		/* BB should we add a retry in here if not a writepage? */
		return -ENOMEM;
	}

545
	fill_small_buf(smb2_command, tcon, server,
546
		       (struct smb2_hdr *)(*request_buf),
547
		       total_len);
548 549 550 551 552 553 554

	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);
	}

555 556 557 558
	return 0;
}

static int smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
559
			       struct TCP_Server_Info *server,
560 561 562 563
			       void **request_buf, unsigned int *total_len)
{
	int rc;

564
	rc = smb2_reconnect(smb2_command, tcon, server, false);
565 566 567
	if (rc)
		return rc;

568
	return __smb2_plain_req_init(smb2_command, tcon, server, request_buf,
569 570 571 572
				     total_len);
}

static int smb2_ioctl_req_init(u32 opcode, struct cifs_tcon *tcon,
573
			       struct TCP_Server_Info *server,
574 575 576 577
			       void **request_buf, unsigned int *total_len)
{
	/* Skip reconnect only for FSCTL_VALIDATE_NEGOTIATE_INFO IOCTLs */
	if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO) {
578 579
		return __smb2_plain_req_init(SMB2_IOCTL, tcon, server,
					     request_buf, total_len);
580
	}
581 582
	return smb2_plain_req_init(SMB2_IOCTL, tcon, server,
				   request_buf, total_len);
583 584
}

585
/* For explanation of negotiate contexts see MS-SMB2 section 2.2.3.1 */
586 587 588 589 590 591 592

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);
593 594
	pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
	get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
595 596 597
	pneg_ctxt->HashAlgorithms = SMB2_PREAUTH_INTEGRITY_SHA512;
}

598 599 600 601 602 603 604 605 606 607 608 609 610
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;
}

611 612 613 614 615 616 617 618 619 620
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
	 */
621 622 623
	pneg_ctxt->DataLength = cpu_to_le16(ALIGN(sizeof(struct smb2_signing_capabilities) -
					    sizeof(struct smb2_neg_context) +
					    (num_algs * sizeof(u16)), 8));
624 625 626
	pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(num_algs);
	pneg_ctxt->SigningAlgorithms[0] = cpu_to_le16(SIGNING_ALG_AES_CMAC);

627 628
	ctxt_len += sizeof(__le16) * num_algs;
	ctxt_len = ALIGN(ctxt_len, 8);
629 630 631 632
	return ctxt_len;
	/* TBD add SIGNING_ALG_AES_GMAC and/or SIGNING_ALG_HMAC_SHA256 */
}

633 634 635 636
static void
build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt)
{
	pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
637 638 639 640
	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;
641 642 643 644 645 646
	} 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;
647 648 649 650 651 652
	} 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;
	}
653 654
}

655 656 657 658 659 660 661 662
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 */
663
	pneg_ctxt->DataLength = cpu_to_le16(2 * cifs_strtoUTF16(pneg_ctxt->NetName, hostname, 100, cp));
664
	/* context size is DataLength + minimal smb2_neg_context */
665
	return ALIGN(le16_to_cpu(pneg_ctxt->DataLength) + sizeof(struct smb2_neg_context), 8);
666 667
}

668 669 670 671 672
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);
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
	/* 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;
690 691
}

692
static void
693
assemble_neg_contexts(struct smb2_negotiate_req *req,
694
		      struct TCP_Server_Info *server, unsigned int *total_len)
695
{
696
	unsigned int ctxt_len, neg_context_count;
697 698 699
	struct TCP_Server_Info *pserver;
	char *pneg_ctxt;
	char *hostname;
700

701 702
	if (*total_len > 200) {
		/* In case length corrupted don't want to overrun smb buffer */
703
		cifs_server_dbg(VFS, "Bad frame length assembling neg contexts\n");
704 705 706 707 708 709 710
		return;
	}

	/*
	 * round up total_len of fixed part of SMB3 negotiate request to 8
	 * byte boundary before adding negotiate contexts
	 */
711
	*total_len = ALIGN(*total_len, 8);
712 713 714 715

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

716
	build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt);
717
	ctxt_len = ALIGN(sizeof(struct smb2_preauth_neg_context), 8);
718 719
	*total_len += ctxt_len;
	pneg_ctxt += ctxt_len;
720

721
	build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt);
722
	ctxt_len = ALIGN(sizeof(struct smb2_encryption_neg_context), 8);
723 724 725
	*total_len += ctxt_len;
	pneg_ctxt += ctxt_len;

726 727 728 729
	/*
	 * secondary channels don't have the hostname field populated
	 * use the hostname field in the primary channel instead
	 */
730
	pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
731 732
	cifs_server_lock(pserver);
	hostname = pserver->hostname;
733
	if (hostname && (hostname[0] != 0)) {
734
		ctxt_len = build_netname_ctxt((struct smb2_netname_neg_context *)pneg_ctxt,
735
					      hostname);
736 737 738
		*total_len += ctxt_len;
		pneg_ctxt += ctxt_len;
		neg_context_count = 3;
739 740
	} else
		neg_context_count = 2;
741
	cifs_server_unlock(pserver);
742 743 744 745 746

	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++;
747

748
	if (server->compression.requested) {
749
		build_compression_ctxt((struct smb2_compression_capabilities_context *)
750
				pneg_ctxt);
751
		ctxt_len = ALIGN(sizeof(struct smb2_compression_capabilities_context), 8);
752 753
		*total_len += ctxt_len;
		pneg_ctxt += ctxt_len;
754 755
		neg_context_count++;
	}
756

757 758 759 760 761 762 763 764 765 766
	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);
767

768
}
769

770
/* If invalid preauth context warn but use what we requested, SHA-512 */
771 772 773 774
static void decode_preauth_context(struct smb2_preauth_neg_context *ctxt)
{
	unsigned int len = le16_to_cpu(ctxt->DataLength);

775 776 777 778
	/*
	 * Caller checked that DataLength remains within SMB boundary. We still
	 * need to confirm that one HashAlgorithms member is accounted for.
	 */
779
	if (len < MIN_PREAUTH_CTXT_DATA_LEN) {
780
		pr_warn_once("server sent bad preauth context\n");
781
		return;
782 783 784
	} else if (len < MIN_PREAUTH_CTXT_DATA_LEN + le16_to_cpu(ctxt->SaltLength)) {
		pr_warn_once("server sent invalid SaltLength\n");
		return;
785 786
	}
	if (le16_to_cpu(ctxt->HashAlgorithmCount) != 1)
787
		pr_warn_once("Invalid SMB3 hash algorithm count\n");
788
	if (ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
789
		pr_warn_once("unknown SMB3 hash algorithm\n");
790 791
}

792 793 794 795
static void decode_compress_ctx(struct TCP_Server_Info *server,
			 struct smb2_compression_capabilities_context *ctxt)
{
	unsigned int len = le16_to_cpu(ctxt->DataLength);
796 797 798
	__le16 alg;

	server->compression.enabled = false;
799

800 801 802 803 804
	/*
	 * Caller checked that DataLength remains within SMB boundary. We still
	 * need to confirm that one CompressionAlgorithms member is accounted
	 * for.
	 */
805
	if (len < 10) {
806
		pr_warn_once("server sent bad compression cntxt\n");
807 808
		return;
	}
809

810
	if (le16_to_cpu(ctxt->CompressionAlgorithmCount) != 1) {
811
		pr_warn_once("invalid SMB3 compress algorithm count\n");
812 813
		return;
	}
814 815 816 817 818 819

	alg = ctxt->CompressionAlgorithms[0];

	/* 'NONE' (0) compressor type is never negotiated */
	if (alg == 0 || le16_to_cpu(alg) > 3) {
		pr_warn_once("invalid compression algorithm '%u'\n", alg);
820 821
		return;
	}
822 823 824

	server->compression.alg = alg;
	server->compression.enabled = true;
825 826
}

827 828 829 830 831 832
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);
833 834 835 836 837
	/*
	 * Caller checked that DataLength remains within SMB boundary. We still
	 * need to confirm that one Cipher flexible array member is accounted
	 * for.
	 */
838
	if (len < MIN_ENCRYPT_CTXT_DATA_LEN) {
839
		pr_warn_once("server sent bad crypto ctxt len\n");
840 841 842 843
		return -EINVAL;
	}

	if (le16_to_cpu(ctxt->CipherCount) != 1) {
844
		pr_warn_once("Invalid SMB3.11 cipher count\n");
845 846 847
		return -EINVAL;
	}
	cifs_dbg(FYI, "SMB311 cipher type:%d\n", le16_to_cpu(ctxt->Ciphers[0]));
848 849 850 851 852 853
	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) {
854 855 856 857 858 859 860 861 862 863 864 865 866
		/*
		 * 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;
867 868 869 870
	} 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 */
871
		pr_warn_once("Invalid SMB3.11 cipher returned\n");
872 873 874
		return -EINVAL;
	}
	server->cipher_type = ctxt->Ciphers[0];
875
	server->capabilities |= SMB2_GLOBAL_CAP_ENCRYPTION;
876 877 878
	return 0;
}

879 880 881 882 883
static void decode_signing_ctx(struct TCP_Server_Info *server,
			       struct smb2_signing_capabilities *pctxt)
{
	unsigned int len = le16_to_cpu(pctxt->DataLength);

884 885 886 887 888
	/*
	 * Caller checked that DataLength remains within SMB boundary. We still
	 * need to confirm that one SigningAlgorithms flexible array member is
	 * accounted for.
	 */
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
	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);
}


909
static int smb311_decode_neg_context(struct smb2_negotiate_rsp *rsp,
910 911
				     struct TCP_Server_Info *server,
				     unsigned int len_of_smb)
912 913 914 915 916 917 918 919 920
{
	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) {
921
		cifs_server_dbg(VFS, "Invalid response: negotiate context offset\n");
922 923 924 925 926 927 928 929 930 931 932
		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;

933
		pctx = (struct smb2_neg_context *)(offset + (char *)rsp);
934 935 936 937 938 939 940 941 942
		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);
943 944 945 946 947 948 949 950 951
		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);
952 953 954
		else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES)
			decode_compress_ctx(server,
				(struct smb2_compression_capabilities_context *)pctx);
955 956
		else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE)
			server->posix_ext_supported = true;
957 958 959
		else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES)
			decode_signing_ctx(server,
				(struct smb2_signing_capabilities *)pctx);
960
		else
961
			cifs_server_dbg(VFS, "unknown negcontext of type %d ignored\n",
962 963 964
				le16_to_cpu(pctx->ContextType));
		if (rc)
			break;
965 966

		offset += clen;
967 968 969 970 971
		len_of_ctxts -= clen;
	}
	return rc;
}

972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
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);
1007
	cifs_dbg(FYI, "mode on posix create 0%o\n", mode);
1008 1009 1010 1011 1012 1013 1014 1015 1016
	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);
1017
	if (mode == ACL_NO_MODE)
1018
		cifs_dbg(FYI, "%s: no mode\n", __func__);
1019 1020 1021 1022 1023 1024 1025
	if (iov[num].iov_base == NULL)
		return -ENOMEM;
	iov[num].iov_len = sizeof(struct create_posix);
	*num_iovec = num + 1;
	return 0;
}

1026

1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
/*
 *
 *	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
1043 1044 1045
SMB2_negotiate(const unsigned int xid,
	       struct cifs_ses *ses,
	       struct TCP_Server_Info *server)
1046
{
1047
	struct smb_rqst rqst;
1048 1049 1050
	struct smb2_negotiate_req *req;
	struct smb2_negotiate_rsp *rsp;
	struct kvec iov[1];
1051
	struct kvec rsp_iov;
1052
	int rc;
1053 1054 1055 1056
	int resp_buftype;
	int blob_offset, blob_length;
	char *security_blob;
	int flags = CIFS_NEG_OP;
1057
	unsigned int total_len;
1058

1059
	cifs_dbg(FYI, "Negotiate protocol\n");
1060

1061 1062 1063
	if (!server) {
		WARN(1, "%s: server is NULL!\n", __func__);
		return -EIO;
1064 1065
	}

1066 1067
	rc = smb2_plain_req_init(SMB2_NEGOTIATE, NULL, server,
				 (void **) &req, &total_len);
1068 1069 1070
	if (rc)
		return rc;

1071
	req->hdr.SessionId = 0;
1072

1073 1074
	memset(server->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
	memset(ses->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
1075

1076
	if (strcmp(server->vals->version_string,
1077 1078 1079
		   SMB3ANY_VERSION_STRING) == 0) {
		req->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
		req->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
1080 1081 1082
		req->Dialects[2] = cpu_to_le16(SMB311_PROT_ID);
		req->DialectCount = cpu_to_le16(3);
		total_len += 6;
1083
	} else if (strcmp(server->vals->version_string,
1084 1085 1086 1087
		   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);
1088 1089 1090
		req->Dialects[3] = cpu_to_le16(SMB311_PROT_ID);
		req->DialectCount = cpu_to_le16(4);
		total_len += 8;
1091 1092
	} else {
		/* otherwise send specific dialect */
1093
		req->Dialects[0] = cpu_to_le16(server->vals->protocol_id);
1094
		req->DialectCount = cpu_to_le16(1);
1095
		total_len += 2;
1096
	}
1097 1098

	/* only one of SMB2 signing flags may be set in SMB2 request */
1099
	if (ses->sign)
1100
		req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
1101
	else if (global_secflags & CIFSSEC_MAY_SIGN)
1102
		req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
1103 1104
	else
		req->SecurityMode = 0;
1105

1106
	req->Capabilities = cpu_to_le32(server->vals->req_capabilities);
1107 1108
	if (ses->chan_max > 1)
		req->Capabilities |= cpu_to_le32(SMB2_GLOBAL_CAP_MULTI_CHANNEL);
1109

1110
	/* ClientGUID must be zero for SMB2.02 dialect */
1111
	if (server->vals->protocol_id == SMB20_PROT_ID)
1112
		memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE);
1113
	else {
1114 1115
		memcpy(req->ClientGUID, server->client_guid,
			SMB2_CLIENT_GUID_SIZE);
1116
		if ((server->vals->protocol_id == SMB311_PROT_ID) ||
1117 1118
		    (strcmp(server->vals->version_string,
		     SMB3ANY_VERSION_STRING) == 0) ||
1119
		    (strcmp(server->vals->version_string,
1120
		     SMBDEFAULT_VERSION_STRING) == 0))
1121
			assemble_neg_contexts(req, server, &total_len);
1122
	}
1123
	iov[0].iov_base = (char *)req;
1124
	iov[0].iov_len = total_len;
1125

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

1130 1131
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
1132 1133
	cifs_small_buf_release(req);
	rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base;
1134 1135 1136 1137
	/*
	 * No tcon so can't do
	 * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
	 */
1138
	if (rc == -EOPNOTSUPP) {
1139
		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");
1140 1141
		goto neg_exit;
	} else if (rc != 0)
1142 1143
		goto neg_exit;

1144
	rc = -EIO;
1145
	if (strcmp(server->vals->version_string,
1146 1147
		   SMB3ANY_VERSION_STRING) == 0) {
		if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
1148
			cifs_server_dbg(VFS,
1149
				"SMB2 dialect returned but not requested\n");
1150
			goto neg_exit;
1151
		} else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
1152
			cifs_server_dbg(VFS,
1153
				"SMB2.1 dialect returned but not requested\n");
1154
			goto neg_exit;
1155 1156 1157 1158
		} 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;
1159
		}
1160
	} else if (strcmp(server->vals->version_string,
1161 1162
		   SMBDEFAULT_VERSION_STRING) == 0) {
		if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
1163
			cifs_server_dbg(VFS,
1164
				"SMB2 dialect returned but not requested\n");
1165
			goto neg_exit;
1166 1167
		} else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
			/* ops set to 3.0 by default for default so update */
1168 1169
			server->ops = &smb21_operations;
			server->vals = &smb21_values;
1170
		} else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
1171 1172
			server->ops = &smb311_operations;
			server->vals = &smb311_values;
1173
		}
Steve French's avatar
Steve French committed
1174
	} else if (le16_to_cpu(rsp->DialectRevision) !=
1175
				server->vals->protocol_id) {
1176
		/* if requested single dialect ensure returned dialect matched */
1177 1178
		cifs_server_dbg(VFS, "Invalid 0x%x dialect returned: not requested\n",
				le16_to_cpu(rsp->DialectRevision));
1179
		goto neg_exit;
1180 1181
	}

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

1184
	if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID))
1185
		cifs_dbg(FYI, "negotiated smb2.0 dialect\n");
1186
	else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID))
1187
		cifs_dbg(FYI, "negotiated smb2.1 dialect\n");
1188
	else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID))
1189
		cifs_dbg(FYI, "negotiated smb3.0 dialect\n");
Steve French's avatar
Steve French committed
1190 1191
	else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID))
		cifs_dbg(FYI, "negotiated smb3.02 dialect\n");
1192 1193
	else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))
		cifs_dbg(FYI, "negotiated smb3.1.1 dialect\n");
1194
	else {
1195 1196
		cifs_server_dbg(VFS, "Invalid dialect returned by server 0x%x\n",
				le16_to_cpu(rsp->DialectRevision));
1197 1198
		goto neg_exit;
	}
1199 1200

	rc = 0;
1201 1202
	server->dialect = le16_to_cpu(rsp->DialectRevision);

1203 1204 1205 1206 1207 1208 1209
	/*
	 * 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);
1210

1211 1212
	/* SMB2 only has an extended negflavor */
	server->negflavor = CIFS_NEGFLAVOR_EXTENDED;
1213 1214 1215
	/* 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);
1216 1217 1218
	server->max_read = le32_to_cpu(rsp->MaxReadSize);
	server->max_write = le32_to_cpu(rsp->MaxWriteSize);
	server->sec_mode = le16_to_cpu(rsp->SecurityMode);
1219 1220 1221
	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);
1222
	server->capabilities = le32_to_cpu(rsp->Capabilities);
1223 1224
	/* Internal types */
	server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES;
1225

1226 1227 1228 1229 1230 1231 1232
	/*
	 * 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;

1233
	security_blob = smb2_get_data_area_len(&blob_offset, &blob_length,
1234
					       (struct smb2_hdr *)rsp);
1235 1236 1237 1238 1239 1240 1241
	/*
	 * 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.
	 */
1242
	if (blob_length == 0) {
1243
		cifs_dbg(FYI, "missing security blob on negprot\n");
1244 1245
		server->sec_ntlmssp = true;
	}
1246

1247
	rc = cifs_enable_signing(server, ses->sign);
1248 1249
	if (rc)
		goto neg_exit;
1250
	if (blob_length) {
1251
		rc = decode_negTokenInit(security_blob, blob_length, server);
1252 1253 1254 1255
		if (rc == 1)
			rc = 0;
		else if (rc == 0)
			rc = -EIO;
1256
	}
1257 1258 1259

	if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
		if (rsp->NegotiateContextCount)
1260 1261
			rc = smb311_decode_neg_context(rsp, server,
						       rsp_iov.iov_len);
1262
		else
1263
			cifs_server_dbg(VFS, "Missing expected negotiate contexts\n");
1264
	}
1265 1266 1267 1268
neg_exit:
	free_rsp_buf(resp_buftype, rsp);
	return rc;
}
1269

1270 1271
int smb3_validate_negotiate(const unsigned int xid, struct cifs_tcon *tcon)
{
1272 1273
	int rc;
	struct validate_negotiate_info_req *pneg_inbuf;
1274
	struct validate_negotiate_info_rsp *pneg_rsp = NULL;
1275
	u32 rsplen;
1276
	u32 inbuflen; /* max of 4 dialects */
1277
	struct TCP_Server_Info *server = tcon->ses->server;
1278 1279 1280

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

1281
	/* In SMB3.11 preauth integrity supersedes validate negotiate */
1282
	if (server->dialect == SMB311_PROT_ID)
1283 1284
		return 0;

1285 1286
	/*
	 * validation ioctl must be signed, so no point sending this if we
1287 1288
	 * can not sign it (ie are not known user).  Even if signing is not
	 * required (enabled but not negotiated), in those cases we selectively
1289
	 * sign just this, the first and only signed request on a connection.
1290
	 * Having validation of negotiate info  helps reduce attack vectors.
1291
	 */
1292
	if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST)
1293 1294
		return 0; /* validation requires signing */

1295 1296 1297 1298 1299 1300
	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)
1301
		cifs_tcon_dbg(VFS, "Unexpected null user (anonymous) auth flag sent by server\n");
1302

1303 1304 1305 1306 1307
	pneg_inbuf = kmalloc(sizeof(*pneg_inbuf), GFP_NOFS);
	if (!pneg_inbuf)
		return -ENOMEM;

	pneg_inbuf->Capabilities =
1308
			cpu_to_le32(server->vals->req_capabilities);
1309 1310 1311
	if (tcon->ses->chan_max > 1)
		pneg_inbuf->Capabilities |= cpu_to_le32(SMB2_GLOBAL_CAP_MULTI_CHANNEL);

1312
	memcpy(pneg_inbuf->Guid, server->client_guid,
1313
					SMB2_CLIENT_GUID_SIZE);
1314 1315

	if (tcon->ses->sign)
1316
		pneg_inbuf->SecurityMode =
1317 1318
			cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
	else if (global_secflags & CIFSSEC_MAY_SIGN)
1319
		pneg_inbuf->SecurityMode =
1320 1321
			cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
	else
1322
		pneg_inbuf->SecurityMode = 0;
1323

1324

1325
	if (strcmp(server->vals->version_string,
1326
		SMB3ANY_VERSION_STRING) == 0) {
1327 1328
		pneg_inbuf->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
		pneg_inbuf->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
1329 1330 1331
		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 */
1332
		inbuflen = sizeof(*pneg_inbuf) -
1333
				(sizeof(pneg_inbuf->Dialects[0]));
1334
	} else if (strcmp(server->vals->version_string,
1335
		SMBDEFAULT_VERSION_STRING) == 0) {
1336 1337 1338
		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);
1339 1340
		pneg_inbuf->Dialects[3] = cpu_to_le16(SMB311_PROT_ID);
		pneg_inbuf->DialectCount = cpu_to_le16(4);
1341
		/* structure is big enough for 4 dialects */
1342
		inbuflen = sizeof(*pneg_inbuf);
1343 1344
	} else {
		/* otherwise specific dialect was requested */
1345
		pneg_inbuf->Dialects[0] =
1346
			cpu_to_le16(server->vals->protocol_id);
1347
		pneg_inbuf->DialectCount = cpu_to_le16(1);
1348
		/* structure is big enough for 4 dialects, sending only 1 */
1349
		inbuflen = sizeof(*pneg_inbuf) -
1350
				sizeof(pneg_inbuf->Dialects[0]) * 3;
1351
	}
1352 1353

	rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
1354
		FSCTL_VALIDATE_NEGOTIATE_INFO,
1355 1356
		(char *)pneg_inbuf, inbuflen, CIFSMaxBufSize,
		(char **)&pneg_rsp, &rsplen);
1357 1358 1359 1360 1361
	if (rc == -EOPNOTSUPP) {
		/*
		 * Old Windows versions or Netapp SMB server can return
		 * not supported error. Client should accept it.
		 */
1362
		cifs_tcon_dbg(VFS, "Server does not support validate negotiate\n");
1363 1364
		rc = 0;
		goto out_free_inbuf;
1365
	} else if (rc != 0) {
1366 1367
		cifs_tcon_dbg(VFS, "validate protocol negotiate failed: %d\n",
			      rc);
1368 1369
		rc = -EIO;
		goto out_free_inbuf;
1370 1371
	}

1372 1373
	rc = -EIO;
	if (rsplen != sizeof(*pneg_rsp)) {
1374 1375
		cifs_tcon_dbg(VFS, "Invalid protocol negotiate response size: %d\n",
			      rsplen);
1376 1377

		/* relax check since Mac returns max bufsize allowed on ioctl */
1378 1379
		if (rsplen > CIFSMaxBufSize || rsplen < sizeof(*pneg_rsp))
			goto out_free_rsp;
1380 1381 1382
	}

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

1386
	if (pneg_rsp->SecurityMode != cpu_to_le16(server->sec_mode))
1387 1388 1389 1390 1391
		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 |
1392
	      SMB2_LARGE_FILES) != server->capabilities)
1393 1394 1395
		goto vneg_out;

	/* validate negotiate successful */
1396
	rc = 0;
1397
	cifs_dbg(FYI, "validate negotiate info successful\n");
1398
	goto out_free_rsp;
1399 1400

vneg_out:
1401
	cifs_tcon_dbg(VFS, "protocol revalidation - security settings mismatch\n");
1402
out_free_rsp:
1403
	kfree(pneg_rsp);
1404 1405 1406
out_free_inbuf:
	kfree(pneg_inbuf);
	return rc;
1407 1408
}

1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
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;
1425
		fallthrough;
1426 1427 1428 1429 1430
	default:
		return Unspecified;
	}
}

1431 1432 1433
struct SMB2_sess_data {
	unsigned int xid;
	struct cifs_ses *ses;
1434
	struct TCP_Server_Info *server;
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
	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;
1456
	struct TCP_Server_Info *server = sess_data->server;
1457
	struct smb2_sess_setup_req *req;
1458
	unsigned int total_len;
1459
	bool is_binding = false;
1460

1461 1462 1463
	rc = smb2_plain_req_init(SMB2_SESSION_SETUP, NULL, server,
				 (void **) &req,
				 &total_len);
1464 1465 1466
	if (rc)
		return rc;

1467 1468 1469
	spin_lock(&ses->ses_lock);
	is_binding = (ses->ses_status == SES_GOOD);
	spin_unlock(&ses->ses_lock);
1470 1471 1472

	if (is_binding) {
		req->hdr.SessionId = cpu_to_le64(ses->Suid);
1473
		req->hdr.Flags |= SMB2_FLAGS_SIGNED;
1474 1475
		req->PreviousSessionId = 0;
		req->Flags = SMB2_SESSION_REQ_FLAG_BINDING;
1476
		cifs_dbg(FYI, "Binding to sess id: %llx\n", ses->Suid);
1477 1478
	} else {
		/* First session, not a reauthenticate */
1479
		req->hdr.SessionId = 0;
1480 1481 1482 1483
		/*
		 * if reconnect, we need to send previous sess id
		 * otherwise it is 0
		 */
1484
		req->PreviousSessionId = cpu_to_le64(sess_data->previous_session);
1485
		req->Flags = 0; /* MBZ */
1486 1487
		cifs_dbg(FYI, "Fresh session. Previous: %llx\n",
			 sess_data->previous_session);
1488
	}
1489 1490

	/* enough to enable echos and oplocks and one max size write */
1491 1492 1493 1494 1495 1496
	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));
1497 1498 1499 1500 1501 1502 1503 1504 1505

	/* 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;

1506 1507 1508
#ifdef CONFIG_CIFS_DFS_UPCALL
	req->Capabilities = cpu_to_le32(SMB2_GLOBAL_CAP_DFS);
#else
1509
	req->Capabilities = 0;
1510 1511
#endif /* DFS_UPCALL */

1512 1513 1514
	req->Channel = 0; /* MBZ */

	sess_data->iov[0].iov_base = (char *)req;
1515 1516
	/* 1 for pad */
	sess_data->iov[0].iov_len = total_len - 1;
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
	/*
	 * 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)
{
1529
	struct kvec *iov = sess_data->iov;
1530

1531 1532 1533
	/* 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);
1534

1535
	free_rsp_buf(sess_data->buf0_type, iov[0].iov_base);
1536 1537 1538 1539 1540 1541 1542
	sess_data->buf0_type = CIFS_NO_BUFFER;
}

static int
SMB2_sess_sendreceive(struct SMB2_sess_data *sess_data)
{
	int rc;
1543
	struct smb_rqst rqst;
1544
	struct smb2_sess_setup_req *req = sess_data->iov[0].iov_base;
1545
	struct kvec rsp_iov = { NULL, 0 };
1546 1547 1548

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

1552 1553 1554
	memset(&rqst, 0, sizeof(struct smb_rqst));
	rqst.rq_iov = sess_data->iov;
	rqst.rq_nvec = 2;
1555

1556 1557
	/* BB add code to build os and lm fields */
	rc = cifs_send_recv(sess_data->xid, sess_data->ses,
1558
			    sess_data->server,
1559
			    &rqst,
1560
			    &sess_data->buf0_type,
1561
			    CIFS_LOG_ERROR | CIFS_SESS_OP, &rsp_iov);
1562
	cifs_small_buf_release(sess_data->iov[0].iov_base);
1563 1564 1565 1566 1567
	if (rc == 0)
		sess_data->ses->expired_pwd = false;
	else if ((rc == -EACCES) || (rc == -EKEYEXPIRED) || (rc == -EKEYREVOKED))
		sess_data->ses->expired_pwd = true;

1568
	memcpy(&sess_data->iov[0], &rsp_iov, sizeof(struct kvec));
1569 1570 1571 1572 1573 1574 1575 1576 1577

	return rc;
}

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

1580
	cifs_server_lock(server);
1581
	if (server->ops->generate_signingkey) {
1582
		rc = server->ops->generate_signingkey(ses, server);
1583 1584 1585
		if (rc) {
			cifs_dbg(FYI,
				"SMB3 session key generation failed\n");
1586
			cifs_server_unlock(server);
1587
			return rc;
1588 1589
		}
	}
1590 1591 1592
	if (!server->session_estab) {
		server->sequence_number = 0x2;
		server->session_estab = true;
1593
	}
1594
	cifs_server_unlock(server);
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605

	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;
1606
	struct TCP_Server_Info *server = sess_data->server;
1607 1608 1609
	struct cifs_spnego_msg *msg;
	struct key *spnego_key = NULL;
	struct smb2_sess_setup_rsp *rsp = NULL;
1610
	bool is_binding = false;
1611 1612 1613 1614 1615

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

1616
	spnego_key = cifs_get_spnego_key(ses, server);
1617 1618
	if (IS_ERR(spnego_key)) {
		rc = PTR_ERR(spnego_key);
1619 1620
		if (rc == -ENOKEY)
			cifs_dbg(VFS, "Verify user has a krb5 ticket and keyutils is installed\n");
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
		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) {
1631 1632
		cifs_dbg(VFS, "bad cifs.upcall version. Expected %d got %d\n",
			 CIFS_SPNEGO_UPCALL_VERSION, msg->version);
1633 1634 1635 1636
		rc = -EKEYREJECTED;
		goto out_put_spnego_key;
	}

1637 1638 1639
	spin_lock(&ses->ses_lock);
	is_binding = (ses->ses_status == SES_GOOD);
	spin_unlock(&ses->ses_lock);
1640

1641
	/* keep session key if binding */
1642
	if (!is_binding) {
1643
		kfree_sensitive(ses->auth_key.response);
1644 1645 1646
		ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len,
						 GFP_KERNEL);
		if (!ses->auth_key.response) {
1647
			cifs_dbg(VFS, "Kerberos can't allocate (%u bytes) memory\n",
1648 1649 1650 1651 1652
				 msg->sesskey_len);
			rc = -ENOMEM;
			goto out_put_spnego_key;
		}
		ses->auth_key.len = msg->sesskey_len;
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
	}

	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;
1663
	/* keep session 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 1670 1671 1672

	rc = SMB2_sess_establish_session(sess_data);
out_put_spnego_key:
	key_invalidate(spnego_key);
	key_put(spnego_key);
1673
	if (rc) {
1674
		kfree_sensitive(ses->auth_key.response);
1675 1676 1677
		ses->auth_key.response = NULL;
		ses->auth_key.len = 0;
	}
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
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

1693 1694 1695 1696 1697
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)
1698
{
1699 1700
	int rc;
	struct cifs_ses *ses = sess_data->ses;
1701
	struct TCP_Server_Info *server = sess_data->server;
1702
	struct smb2_sess_setup_rsp *rsp = NULL;
1703
	unsigned char *ntlmssp_blob = NULL;
1704
	bool use_spnego = false; /* else use raw ntlmssp */
1705
	u16 blob_length = 0;
1706
	bool is_binding = false;
1707

1708 1709 1710 1711 1712
	/*
	 * If memory allocation is successful, caller of this function
	 * frees it.
	 */
	ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL);
1713 1714 1715 1716
	if (!ses->ntlmssp) {
		rc = -ENOMEM;
		goto out_err;
	}
1717
	ses->ntlmssp->sesskey_per_smbsess = true;
1718

1719
	rc = SMB2_sess_alloc_buffer(sess_data);
1720
	if (rc)
1721
		goto out_err;
1722

1723
	rc = build_ntlmssp_smb3_negotiate_blob(&ntlmssp_blob,
1724
					  &blob_length, ses, server,
1725 1726
					  sess_data->nls_cp);
	if (rc)
1727
		goto out;
1728

1729 1730 1731 1732 1733 1734 1735 1736
	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;
1737

1738 1739
	rc = SMB2_sess_sendreceive(sess_data);
	rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1740

1741 1742
	/* If true, rc here is expected and not an error */
	if (sess_data->buf0_type != CIFS_NO_BUFFER &&
1743
		rsp->hdr.Status == STATUS_MORE_PROCESSING_REQUIRED)
1744
		rc = 0;
1745

1746 1747
	if (rc)
		goto out;
1748

1749
	if (offsetof(struct smb2_sess_setup_rsp, Buffer) !=
1750 1751 1752
			le16_to_cpu(rsp->SecurityBufferOffset)) {
		cifs_dbg(VFS, "Invalid security buffer offset %d\n",
			le16_to_cpu(rsp->SecurityBufferOffset));
1753
		rc = -EIO;
1754
		goto out;
1755
	}
1756 1757 1758 1759
	rc = decode_ntlmssp_challenge(rsp->Buffer,
			le16_to_cpu(rsp->SecurityBufferLength), ses);
	if (rc)
		goto out;
1760

1761
	cifs_dbg(FYI, "rawntlmssp session setup challenge phase\n");
1762

1763 1764 1765
	spin_lock(&ses->ses_lock);
	is_binding = (ses->ses_status == SES_GOOD);
	spin_unlock(&ses->ses_lock);
1766

1767
	/* keep existing ses id and flags if binding */
1768
	if (!is_binding) {
1769
		ses->Suid = le64_to_cpu(rsp->hdr.SessionId);
1770 1771
		ses->session_flags = le16_to_cpu(rsp->SessionFlags);
	}
1772 1773

out:
1774
	kfree_sensitive(ntlmssp_blob);
1775 1776 1777 1778 1779 1780 1781
	SMB2_sess_free_buffer(sess_data);
	if (!rc) {
		sess_data->result = 0;
		sess_data->func = SMB2_sess_auth_rawntlmssp_authenticate;
		return;
	}
out_err:
1782
	kfree_sensitive(ses->ntlmssp);
1783 1784 1785 1786
	ses->ntlmssp = NULL;
	sess_data->result = rc;
	sess_data->func = NULL;
}
1787

1788 1789 1790 1791 1792
static void
SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data)
{
	int rc;
	struct cifs_ses *ses = sess_data->ses;
1793
	struct TCP_Server_Info *server = sess_data->server;
1794 1795 1796 1797 1798
	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;
1799
	bool is_binding = false;
1800

1801 1802 1803
	rc = SMB2_sess_alloc_buffer(sess_data);
	if (rc)
		goto out;
1804

1805
	req = (struct smb2_sess_setup_req *) sess_data->iov[0].iov_base;
1806
	req->hdr.SessionId = cpu_to_le64(ses->Suid);
1807

1808 1809 1810
	rc = build_ntlmssp_auth_blob(&ntlmssp_blob, &blob_length,
				     ses, server,
				     sess_data->nls_cp);
1811 1812 1813
	if (rc) {
		cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n", rc);
		goto out;
1814 1815
	}

1816 1817 1818 1819 1820 1821 1822 1823
	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;
1824

1825 1826 1827 1828 1829 1830
	rc = SMB2_sess_sendreceive(sess_data);
	if (rc)
		goto out;

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

1831 1832 1833
	spin_lock(&ses->ses_lock);
	is_binding = (ses->ses_status == SES_GOOD);
	spin_unlock(&ses->ses_lock);
1834

1835
	/* keep existing ses id and flags if binding */
1836
	if (!is_binding) {
1837
		ses->Suid = le64_to_cpu(rsp->hdr.SessionId);
1838 1839
		ses->session_flags = le16_to_cpu(rsp->SessionFlags);
	}
1840

1841
	rc = SMB2_sess_establish_session(sess_data);
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
#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
1857
out:
1858
	kfree_sensitive(ntlmssp_blob);
1859
	SMB2_sess_free_buffer(sess_data);
1860
	kfree_sensitive(ses->ntlmssp);
1861 1862 1863 1864
	ses->ntlmssp = NULL;
	sess_data->result = rc;
	sess_data->func = NULL;
}
1865

1866
static int
1867
SMB2_select_sec(struct SMB2_sess_data *sess_data)
1868
{
1869
	int type;
1870 1871
	struct cifs_ses *ses = sess_data->ses;
	struct TCP_Server_Info *server = sess_data->server;
1872

1873
	type = smb2_select_sectype(server, ses->sectype);
1874 1875
	cifs_dbg(FYI, "sess setup type %d\n", type);
	if (type == Unspecified) {
1876
		cifs_dbg(VFS, "Unable to select appropriate authentication method!\n");
1877 1878
		return -EINVAL;
	}
1879

1880
	switch (type) {
1881 1882 1883 1884 1885 1886 1887
	case Kerberos:
		sess_data->func = SMB2_auth_kerberos;
		break;
	case RawNTLMSSP:
		sess_data->func = SMB2_sess_auth_rawntlmssp_negotiate;
		break;
	default:
1888
		cifs_dbg(VFS, "secType %d not supported!\n", type);
1889
		return -EOPNOTSUPP;
1890 1891
	}

1892 1893 1894 1895 1896
	return 0;
}

int
SMB2_sess_setup(const unsigned int xid, struct cifs_ses *ses,
1897
		struct TCP_Server_Info *server,
1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
		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;
1908 1909
	}

1910 1911 1912 1913 1914 1915
	sess_data = kzalloc(sizeof(struct SMB2_sess_data), GFP_KERNEL);
	if (!sess_data)
		return -ENOMEM;

	sess_data->xid = xid;
	sess_data->ses = ses;
1916
	sess_data->server = server;
1917 1918
	sess_data->buf0_type = CIFS_NO_BUFFER;
	sess_data->nls_cp = (struct nls_table *) nls_cp;
1919
	sess_data->previous_session = ses->Suid;
1920

1921 1922 1923 1924
	rc = SMB2_select_sec(sess_data);
	if (rc)
		goto out;

1925 1926 1927
	/*
	 * Initialize the session hash with the server one.
	 */
1928
	memcpy(ses->preauth_sha_hash, server->preauth_sha_hash,
1929 1930
	       SMB2_PREAUTH_HASH_SIZE);

1931 1932 1933
	while (sess_data->func)
		sess_data->func(sess_data);

1934
	if ((ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST) && (ses->sign))
1935
		cifs_server_dbg(VFS, "signing requested but authenticated as guest\n");
1936
	rc = sess_data->result;
1937
out:
1938
	kfree_sensitive(sess_data);
1939 1940 1941 1942 1943 1944
	return rc;
}

int
SMB2_logoff(const unsigned int xid, struct cifs_ses *ses)
{
1945
	struct smb_rqst rqst;
1946 1947 1948
	struct smb2_logoff_req *req; /* response is also trivial struct */
	int rc = 0;
	struct TCP_Server_Info *server;
1949
	int flags = 0;
1950 1951 1952 1953
	unsigned int total_len;
	struct kvec iov[1];
	struct kvec rsp_iov;
	int resp_buf_type;
1954

1955
	cifs_dbg(FYI, "disconnect session %p\n", ses);
1956 1957 1958 1959 1960 1961

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

1962
	/* no need to send SMB logoff if uid already closed due to reconnect */
1963 1964 1965
	spin_lock(&ses->chan_lock);
	if (CIFS_ALL_CHANS_NEED_RECONNECT(ses)) {
		spin_unlock(&ses->chan_lock);
1966
		goto smb2_session_already_dead;
1967 1968
	}
	spin_unlock(&ses->chan_lock);
1969

1970 1971
	rc = smb2_plain_req_init(SMB2_LOGOFF, NULL, ses->server,
				 (void **) &req, &total_len);
1972 1973 1974 1975
	if (rc)
		return rc;

	 /* since no tcon, smb2_init can not do this, so do here */
1976
	req->hdr.SessionId = cpu_to_le64(ses->Suid);
1977 1978 1979 1980

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

1983
	flags |= CIFS_NO_RSP_BUF;
1984 1985 1986

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

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

1992 1993
	rc = cifs_send_recv(xid, ses, ses->server,
			    &rqst, &resp_buf_type, flags, &rsp_iov);
1994
	cifs_small_buf_release(req);
1995 1996 1997 1998
	/*
	 * No tcon so can't do
	 * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
	 */
1999 2000

smb2_session_already_dead:
2001 2002
	return rc;
}
2003 2004 2005

static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code)
{
2006
	cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]);
2007 2008 2009 2010
}

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

Steve French's avatar
Steve French committed
2011 2012 2013 2014 2015 2016 2017 2018
/* 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;
}

2019 2020 2021 2022
int
SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
	  struct cifs_tcon *tcon, const struct nls_table *cp)
{
2023
	struct smb_rqst rqst;
2024 2025 2026
	struct smb2_tree_connect_req *req;
	struct smb2_tree_connect_rsp *rsp = NULL;
	struct kvec iov[2];
2027
	struct kvec rsp_iov = { NULL, 0 };
2028 2029 2030 2031
	int rc = 0;
	int resp_buftype;
	int unc_path_len;
	__le16 *unc_path = NULL;
2032
	int flags = 0;
2033
	unsigned int total_len;
2034
	struct TCP_Server_Info *server = cifs_pick_channel(ses);
2035

2036
	cifs_dbg(FYI, "TCON\n");
2037

2038
	if (!server || !tree)
2039 2040 2041 2042 2043 2044
		return -EIO;

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

2045 2046
	unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp);
	if (unc_path_len <= 0) {
2047 2048 2049
		kfree(unc_path);
		return -EINVAL;
	}
2050
	unc_path_len *= 2;
2051

2052
	/* SMB2 TREE_CONNECT request must be called with TreeId == 0 */
2053
	tcon->tid = 0;
2054
	atomic_set(&tcon->num_remote_opens, 0);
2055 2056
	rc = smb2_plain_req_init(SMB2_TREE_CONNECT, tcon, server,
				 (void **) &req, &total_len);
2057 2058 2059 2060 2061
	if (rc) {
		kfree(unc_path);
		return rc;
	}

2062
	if (smb3_encryption_required(tcon))
2063
		flags |= CIFS_TRANSFORM_REQ;
2064 2065

	iov[0].iov_base = (char *)req;
2066 2067
	/* 1 for pad */
	iov[0].iov_len = total_len - 1;
2068 2069

	/* Testing shows that buffer offset must be at location of Buffer[0] */
2070
	req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req));
2071
	req->PathLength = cpu_to_le16(unc_path_len);
2072 2073 2074
	iov[1].iov_base = unc_path;
	iov[1].iov_len = unc_path_len;

2075 2076 2077
	/*
	 * 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
2078
	 * (Samba servers don't always set the flag so also check if null user)
2079
	 */
2080
	if ((server->dialect == SMB311_PROT_ID) &&
2081
	    !smb3_encryption_required(tcon) &&
2082 2083 2084
	    !(ses->session_flags &
		    (SMB2_SESSION_FLAG_IS_GUEST|SMB2_SESSION_FLAG_IS_NULL)) &&
	    ((ses->user_name != NULL) || (ses->sectype == Kerberos)))
2085
		req->hdr.Flags |= SMB2_FLAGS_SIGNED;
2086

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

2091
	/* Need 64 for max size write so ask for more in case not there yet */
2092 2093 2094 2095 2096 2097
	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));
2098

2099 2100
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
2101 2102
	cifs_small_buf_release(req);
	rsp = (struct smb2_tree_connect_rsp *)rsp_iov.iov_base;
2103
	trace_smb3_tcon(xid, tcon->tid, ses->Suid, tree, rc);
2104
	if ((rc != 0) || (rsp == NULL)) {
2105 2106
		cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
		tcon->need_reconnect = true;
2107 2108 2109
		goto tcon_error_exit;
	}

2110 2111
	switch (rsp->ShareType) {
	case SMB2_SHARE_TYPE_DISK:
2112
		cifs_dbg(FYI, "connection to disk share\n");
2113 2114
		break;
	case SMB2_SHARE_TYPE_PIPE:
2115
		tcon->pipe = true;
2116
		cifs_dbg(FYI, "connection to pipe share\n");
2117 2118
		break;
	case SMB2_SHARE_TYPE_PRINT:
2119
		tcon->print = true;
2120
		cifs_dbg(FYI, "connection to printer\n");
2121 2122
		break;
	default:
2123
		cifs_server_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
2124 2125 2126 2127 2128
		rc = -EOPNOTSUPP;
		goto tcon_error_exit;
	}

	tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
2129
	tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
2130
	tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
2131
	tcon->tid = le32_to_cpu(rsp->hdr.Id.SyncId.TreeId);
2132
	strscpy(tcon->tree_name, tree, sizeof(tcon->tree_name));
2133 2134 2135

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

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

Steve French's avatar
Steve French committed
2142
	init_copy_chunk_defaults(tcon);
2143 2144
	if (server->ops->validate_negotiate)
		rc = server->ops->validate_negotiate(xid, tcon);
2145 2146 2147
	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;
2148
tcon_exit:
2149

2150 2151 2152 2153 2154
	free_rsp_buf(resp_buftype, rsp);
	kfree(unc_path);
	return rc;

tcon_error_exit:
2155
	if (rsp && rsp->hdr.Status == STATUS_BAD_NETWORK_NAME)
2156
		cifs_tcon_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree);
2157 2158 2159 2160 2161 2162
	goto tcon_exit;
}

int
SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon)
{
2163
	struct smb_rqst rqst;
2164 2165 2166
	struct smb2_tree_disconnect_req *req; /* response is trivial */
	int rc = 0;
	struct cifs_ses *ses = tcon->ses;
2167
	struct TCP_Server_Info *server = cifs_pick_channel(ses);
2168
	int flags = 0;
2169 2170 2171 2172
	unsigned int total_len;
	struct kvec iov[1];
	struct kvec rsp_iov;
	int resp_buf_type;
2173

2174
	cifs_dbg(FYI, "Tree Disconnect\n");
2175

2176
	if (!ses || !(ses->server))
2177 2178
		return -EIO;

2179
	trace_smb3_tdis_enter(xid, tcon->tid, ses->Suid, tcon->tree_name);
2180 2181 2182 2183
	spin_lock(&ses->chan_lock);
	if ((tcon->need_reconnect) ||
	    (CIFS_ALL_CHANS_NEED_RECONNECT(tcon->ses))) {
		spin_unlock(&ses->chan_lock);
2184
		return 0;
2185 2186
	}
	spin_unlock(&ses->chan_lock);
2187

2188
	invalidate_all_cached_dirs(tcon);
2189

2190
	rc = smb2_plain_req_init(SMB2_TREE_DISCONNECT, tcon, server,
2191 2192
				 (void **) &req,
				 &total_len);
2193 2194 2195
	if (rc)
		return rc;

2196
	if (smb3_encryption_required(tcon))
2197 2198
		flags |= CIFS_TRANSFORM_REQ;

2199
	flags |= CIFS_NO_RSP_BUF;
2200 2201 2202 2203

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

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

2208
	rc = cifs_send_recv(xid, ses, server,
2209
			    &rqst, &resp_buf_type, flags, &rsp_iov);
2210
	cifs_small_buf_release(req);
2211
	if (rc) {
2212
		cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE);
2213 2214 2215
		trace_smb3_tdis_err(xid, tcon->tid, ses->Suid, rc);
	}
	trace_smb3_tdis_done(xid, tcon->tid, ses->Suid);
2216 2217 2218

	return rc;
}
2219

2220

2221 2222 2223 2224 2225 2226 2227 2228 2229 2230
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
2231
					(struct create_durable, Data));
2232 2233 2234 2235
	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);
2236
	/* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DHnQ" */
2237 2238 2239 2240 2241 2242 2243
	buf->Name[0] = 'D';
	buf->Name[1] = 'H';
	buf->Name[2] = 'n';
	buf->Name[3] = 'Q';
	return buf;
}

2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260
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;
2261
	/* SMB2_CREATE_DURABLE_HANDLE_RECONNECT is "DHnC" */
2262 2263 2264 2265 2266 2267 2268
	buf->Name[0] = 'D';
	buf->Name[1] = 'H';
	buf->Name[2] = 'n';
	buf->Name[3] = 'C';
	return buf;
}

2269 2270 2271
static void
parse_query_id_ctxt(struct create_context *cc, struct smb2_file_all_info *buf)
{
2272
	struct create_disk_id_rsp *pdisk_id = (struct create_disk_id_rsp *)cc;
2273 2274 2275 2276 2277 2278

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

2279
static void
2280 2281
parse_posix_ctxt(struct create_context *cc, struct smb2_file_all_info *info,
		 struct create_posix_rsp *posix)
2282
{
2283 2284 2285 2286
	int sid_len;
	u8 *beg = (u8 *)cc + le16_to_cpu(cc->DataOffset);
	u8 *end = beg + le32_to_cpu(cc->DataLength);
	u8 *sid;
2287

2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308
	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);
2309

2310 2311
	cifs_dbg(FYI, "nlink=%d mode=%o reparse_tag=%x\n",
		 posix->nlink, posix->mode, posix->reparse_tag);
2312 2313
}

2314 2315 2316 2317 2318 2319
int smb2_parse_contexts(struct TCP_Server_Info *server,
			struct kvec *rsp_iov,
			unsigned int *epoch,
			char *lease_key, __u8 *oplock,
			struct smb2_file_all_info *buf,
			struct create_posix_rsp *posix)
2320
{
2321
	struct smb2_create_rsp *rsp = rsp_iov->iov_base;
2322
	struct create_context *cc;
2323 2324 2325
	size_t rem, off, len;
	size_t doff, dlen;
	size_t noff, nlen;
2326
	char *name;
2327 2328 2329 2330 2331
	static const char smb3_create_tag_posix[] = {
		0x93, 0xAD, 0x25, 0x50, 0x9C,
		0xB4, 0x11, 0xE7, 0xB4, 0x23, 0x83,
		0xDE, 0x96, 0x8B, 0xCD, 0x7C
	};
2332

2333
	*oplock = 0;
2334 2335 2336 2337 2338 2339

	off = le32_to_cpu(rsp->CreateContextsOffset);
	rem = le32_to_cpu(rsp->CreateContextsLength);
	if (check_add_overflow(off, rem, &len) || len > rsp_iov->iov_len)
		return -EINVAL;
	cc = (struct create_context *)((u8 *)rsp + off);
2340 2341 2342 2343 2344

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

2345 2346 2347 2348 2349 2350 2351 2352
	while (rem >= sizeof(*cc)) {
		doff = le16_to_cpu(cc->DataOffset);
		dlen = le32_to_cpu(cc->DataLength);
		if (check_add_overflow(doff, dlen, &len) || len > rem)
			return -EINVAL;

		noff = le16_to_cpu(cc->NameOffset);
		nlen = le16_to_cpu(cc->NameLength);
2353
		if (noff + nlen > doff)
2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368
			return -EINVAL;

		name = (char *)cc + noff;
		switch (nlen) {
		case 4:
			if (!strncmp(name, SMB2_CREATE_REQUEST_LEASE, 4)) {
				*oplock = server->ops->parse_lease_buf(cc, epoch,
								       lease_key);
			} else if (buf &&
				   !strncmp(name, SMB2_CREATE_QUERY_ON_DISK_ID, 4)) {
				parse_query_id_ctxt(cc, buf);
			}
			break;
		case 16:
			if (posix && !memcmp(name, smb3_create_tag_posix, 16))
2369
				parse_posix_ctxt(cc, buf, posix);
2370 2371 2372 2373 2374 2375 2376
			break;
		default:
			cifs_dbg(FYI, "%s: unhandled context (nlen=%zu dlen=%zu)\n",
				 __func__, nlen, dlen);
			if (IS_ENABLED(CONFIG_CIFS_DEBUG2))
				cifs_dump_mem("context data: ", cc, dlen);
			break;
2377
		}
2378 2379 2380

		off = le32_to_cpu(cc->Next);
		if (!off)
2381
			break;
2382 2383 2384
		if (check_sub_overflow(rem, off, &rem))
			return -EINVAL;
		cc = (struct create_context *)((u8 *)cc + off);
2385
	}
2386

2387 2388 2389
	if (rsp->OplockLevel != SMB2_OPLOCK_LEVEL_LEASE)
		*oplock = rsp->OplockLevel;

2390
	return 0;
2391 2392
}

2393
static int
2394 2395 2396
add_lease_context(struct TCP_Server_Info *server,
		  struct smb2_create_req *req,
		  struct kvec *iov,
2397
		  unsigned int *num_iovec, u8 *lease_key, __u8 *oplock)
2398 2399 2400
{
	unsigned int num = *num_iovec;

2401
	iov[num].iov_base = server->ops->create_lease_buf(lease_key, *oplock);
2402 2403
	if (iov[num].iov_base == NULL)
		return -ENOMEM;
2404
	iov[num].iov_len = server->vals->create_lease_size;
2405 2406 2407 2408 2409
	req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
	*num_iovec = num + 1;
	return 0;
}

2410
static struct create_durable_v2 *
2411
create_durable_v2_buf(struct cifs_open_parms *oparms)
2412
{
2413
	struct cifs_fid *pfid = oparms->fid;
2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426
	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);

2427 2428 2429 2430 2431
	/*
	 * 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
2432
	 * on a particular SMB3 mount.
2433 2434
	 */
	buf->dcontext.Timeout = cpu_to_le32(oparms->tcon->handle_timeout);
2435
	buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2436 2437 2438 2439 2440 2441 2442

	/* for replay, we should not overwrite the existing create guid */
	if (!oparms->replay) {
		generate_random_uuid(buf->dcontext.CreateGuid);
		memcpy(pfid->create_guid, buf->dcontext.CreateGuid, 16);
	} else
		memcpy(buf->dcontext.CreateGuid, pfid->create_guid, 16);
2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484

	/* 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;
}

2485
static int
2486 2487 2488 2489 2490
add_durable_v2_context(struct kvec *iov, unsigned int *num_iovec,
		    struct cifs_open_parms *oparms)
{
	unsigned int num = *num_iovec;

2491
	iov[num].iov_base = create_durable_v2_buf(oparms);
2492 2493 2494 2495 2496 2497 2498 2499 2500
	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,
2501
		    struct cifs_open_parms *oparms)
2502 2503 2504
{
	unsigned int num = *num_iovec;

2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529
	/* 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);
	}

2530 2531 2532 2533 2534 2535
	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();
2536 2537 2538 2539 2540 2541 2542
	if (iov[num].iov_base == NULL)
		return -ENOMEM;
	iov[num].iov_len = sizeof(struct create_durable);
	*num_iovec = num + 1;
	return 0;
}

2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581
/* 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;
}

2582
/* See http://technet.microsoft.com/en-us/library/hh509017(v=ws.10).aspx */
2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601
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);
2602 2603

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

2606 2607
/* See MS-SMB2 2.2.13.2.2 and MS-DTYP 2.4.6 */
static struct crt_sd_ctxt *
2608
create_sd_buf(umode_t mode, bool set_owner, unsigned int *len)
2609 2610
{
	struct crt_sd_ctxt *buf;
2611 2612
	__u8 *ptr, *aclptr;
	unsigned int acelen, acl_size, ace_count;
2613 2614
	unsigned int owner_offset = 0;
	unsigned int group_offset = 0;
2615
	struct smb3_acl acl = {};
2616

2617
	*len = round_up(sizeof(struct crt_sd_ctxt) + (sizeof(struct cifs_ace) * 4), 8);
2618 2619 2620 2621 2622

	if (set_owner) {
		/* sizeof(struct owner_group_sids) is already multiple of 8 so no need to round */
		*len += sizeof(struct owner_group_sids);
	}
2623 2624 2625 2626 2627

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

2628
	ptr = (__u8 *)&buf[1];
2629
	if (set_owner) {
2630 2631
		/* offset fields are from beginning of security descriptor not of create context */
		owner_offset = ptr - (__u8 *)&buf->sd;
2632
		buf->sd.OffsetOwner = cpu_to_le32(owner_offset);
2633
		group_offset = owner_offset + offsetof(struct owner_group_sids, group);
2634
		buf->sd.OffsetGroup = cpu_to_le32(group_offset);
2635 2636 2637

		setup_owner_group_sids(ptr);
		ptr += sizeof(struct owner_group_sids);
2638 2639 2640 2641 2642
	} else {
		buf->sd.OffsetOwner = 0;
		buf->sd.OffsetGroup = 0;
	}

2643
	buf->ccontext.DataOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, sd));
2644
	buf->ccontext.NameOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, Name));
2645 2646 2647 2648 2649 2650 2651
	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 */
2652

2653 2654 2655 2656 2657 2658 2659
	/*
	 * 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 */
2660 2661 2662
	buf->sd.OffsetDacl = cpu_to_le32(ptr - (__u8 *)&buf->sd);
	/* Ship the ACL for now. we will copy it into buf later. */
	aclptr = ptr;
2663
	ptr += sizeof(struct smb3_acl);
2664 2665

	/* create one ACE to hold the mode embedded in reserved special SID */
2666 2667 2668 2669
	acelen = setup_special_mode_ACE((struct cifs_ace *)ptr, (__u64)mode);
	ptr += acelen;
	acl_size = acelen + sizeof(struct smb3_acl);
	ace_count = 1;
2670 2671 2672

	if (set_owner) {
		/* we do not need to reallocate buffer to add the two more ACEs. plenty of space */
2673 2674 2675 2676 2677
		acelen = setup_special_user_owner_ACE((struct cifs_ace *)ptr);
		ptr += acelen;
		acl_size += acelen;
		ace_count += 1;
	}
2678

2679
	/* and one more ACE to allow access for authenticated users */
2680 2681 2682 2683 2684 2685 2686 2687
	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);
2688
	/* acl.Sbz1 and Sbz2 MBZ so are not set here, but initialized above */
2689
	memcpy(aclptr, &acl, sizeof(struct smb3_acl));
2690 2691

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

2694 2695 2696 2697
	return buf;
}

static int
2698
add_sd_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode, bool set_owner)
2699 2700 2701 2702
{
	unsigned int num = *num_iovec;
	unsigned int len = 0;

2703
	iov[num].iov_base = create_sd_buf(mode, set_owner, &len);
2704 2705 2706 2707 2708 2709 2710
	if (iov[num].iov_base == NULL)
		return -ENOMEM;
	iov[num].iov_len = len;
	*num_iovec = num + 1;
	return 0;
}

2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746
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;
}

2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757
static void add_ea_context(struct cifs_open_parms *oparms,
			   struct kvec *rq_iov, unsigned int *num_iovs)
{
	struct kvec *iov = oparms->ea_cctx;

	if (iov && iov->iov_base && iov->iov_len) {
		rq_iov[(*num_iovs)++] = *iov;
		memset(iov, 0, sizeof(*iov));
	}
}

2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777
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);

2778 2779
	/* make room for one path separator only if @path isn't empty */
	*out_len = treename_len + (path[0] ? 1 : 0) + path_len;
2780 2781

	/*
2782 2783
	 * final path needs to be 8-byte aligned as specified in
	 * MS-SMB2 2.2.13 SMB2 CREATE Request.
2784
	 */
2785
	*out_size = round_up(*out_len * sizeof(__le16), 8);
2786
	*out_path = kzalloc(*out_size + sizeof(__le16) /* null */, GFP_KERNEL);
2787 2788 2789 2790 2791
	if (!*out_path)
		return -ENOMEM;

	cp = load_nls_default();
	cifs_strtoUTF16(*out_path, treename, treename_len, cp);
2792 2793 2794

	/* Do not append the separator if the path is empty */
	if (path[0] != cpu_to_le16(0x0000)) {
2795 2796
		UniStrcat((wchar_t *)*out_path, (wchar_t *)sep);
		UniStrcat((wchar_t *)*out_path, (wchar_t *)path);
2797 2798
	}

2799 2800 2801 2802 2803
	unload_nls(cp);

	return 0;
}

2804 2805 2806 2807 2808 2809 2810
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;
2811
	struct smb2_create_rsp *rsp = NULL;
2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824
	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;
2825
	__le16 *utf16_path = NULL;
2826 2827 2828 2829 2830 2831 2832 2833
	struct TCP_Server_Info *server;
	int retries = 0, cur_sleep = 1;

replay_again:
	/* reinitialize for possible replay */
	flags = 0;
	n_iov = 2;
	server = cifs_pick_channel(ses);
2834 2835 2836

	cifs_dbg(FYI, "mkdir\n");

2837 2838 2839 2840 2841
	/* resource #1: path allocation */
	utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
	if (!utf16_path)
		return -ENOMEM;

2842
	if (!ses || !server) {
2843 2844 2845
		rc = -EIO;
		goto err_free_path;
	}
2846

2847
	/* resource #2: request */
2848 2849
	rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
				 (void **) &req, &total_len);
2850
	if (rc)
2851 2852
		goto err_free_path;

2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881

	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;

2882
		req->hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
2883 2884
		rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
						 &name_len,
2885
						 tcon->tree_name, utf16_path);
2886 2887 2888
		if (rc)
			goto err_free_req;

2889 2890
		req->NameLength = cpu_to_le16(name_len * 2);
		uni_path_len = copy_size;
2891 2892 2893
		/* free before overwriting resource */
		kfree(utf16_path);
		utf16_path = copy_path;
2894
	} else {
2895
		uni_path_len = (2 * UniStrnlen((wchar_t *)utf16_path, PATH_MAX)) + 2;
2896 2897 2898 2899 2900 2901
		/* 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) {
2902 2903
				rc = -ENOMEM;
				goto err_free_req;
2904
			}
2905
			memcpy((char *)copy_path, (const char *)utf16_path,
2906 2907
			       uni_path_len);
			uni_path_len = copy_size;
2908 2909 2910
			/* free before overwriting resource */
			kfree(utf16_path);
			utf16_path = copy_path;
2911 2912 2913 2914
		}
	}

	iov[1].iov_len = uni_path_len;
2915
	iov[1].iov_base = utf16_path;
2916 2917 2918
	req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_NONE;

	if (tcon->posix_extensions) {
2919
		/* resource #3: posix buf */
2920
		rc = add_posix_context(iov, &n_iov, mode);
2921 2922
		if (rc)
			goto err_free_req;
2923 2924 2925
		req->CreateContextsOffset = cpu_to_le32(
			sizeof(struct smb2_create_req) +
			iov[1].iov_len);
2926 2927 2928 2929 2930 2931 2932 2933
		pc_buf = iov[n_iov-1].iov_base;
	}


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

2934
	/* no need to inc num_remote_opens because we close it just below */
2935
	trace_smb3_posix_mkdir_enter(xid, tcon->tid, ses->Suid, full_path, CREATE_NOT_FILE,
2936
				    FILE_WRITE_ATTRIBUTES);
2937 2938 2939 2940

	if (retries)
		smb2_set_replay(server, &rqst);

2941
	/* resource #4: response buffer */
2942 2943
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
2944
	if (rc) {
2945 2946
		cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
		trace_smb3_posix_mkdir_err(xid, tcon->tid, ses->Suid,
2947 2948 2949 2950 2951
					   CREATE_NOT_FILE,
					   FILE_WRITE_ATTRIBUTES, rc);
		goto err_free_rsp_buf;
	}

2952 2953 2954 2955 2956
	/*
	 * 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)
	 */
2957
	rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
2958 2959 2960 2961 2962 2963
	if (rsp == NULL) {
		rc = -EIO;
		kfree(pc_buf);
		goto err_free_req;
	}

2964 2965
	trace_smb3_posix_mkdir_done(xid, rsp->PersistentFileId, tcon->tid, ses->Suid,
				    CREATE_NOT_FILE, FILE_WRITE_ATTRIBUTES);
2966

2967
	SMB2_close(xid, tcon, rsp->PersistentFileId, rsp->VolatileFileId);
2968 2969 2970

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

2971
err_free_rsp_buf:
2972
	free_rsp_buf(resp_buftype, rsp);
2973 2974 2975 2976 2977
	kfree(pc_buf);
err_free_req:
	cifs_small_buf_release(req);
err_free_path:
	kfree(utf16_path);
2978 2979 2980 2981 2982

	if (is_replayable_error(rc) &&
	    smb2_should_replay(tcon, &retries, &cur_sleep))
		goto replay_again;

2983 2984 2985
	return rc;
}

2986
int
2987 2988
SMB2_open_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
	       struct smb_rqst *rqst, __u8 *oplock,
2989
	       struct cifs_open_parms *oparms, __le16 *path)
2990 2991
{
	struct smb2_create_req *req;
2992
	unsigned int n_iov = 2;
2993
	__u32 file_attributes = 0;
2994 2995
	int copy_size;
	int uni_path_len;
2996
	unsigned int total_len;
2997 2998 2999
	struct kvec *iov = rqst->rq_iov;
	__le16 *copy_path;
	int rc;
3000

3001 3002
	rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
				 (void **) &req, &total_len);
3003 3004 3005
	if (rc)
		return rc;

3006 3007 3008
	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;
3009

3010
	if (oparms->create_options & CREATE_OPTION_READONLY)
3011
		file_attributes |= ATTR_READONLY;
3012 3013
	if (oparms->create_options & CREATE_OPTION_SPECIAL)
		file_attributes |= ATTR_SYSTEM;
3014

3015
	req->ImpersonationLevel = IL_IMPERSONATION;
3016
	req->DesiredAccess = cpu_to_le32(oparms->desired_access);
3017 3018 3019
	/* File attributes ignored on open (used in create though) */
	req->FileAttributes = cpu_to_le32(file_attributes);
	req->ShareAccess = FILE_SHARE_ALL_LE;
3020

3021 3022
	req->CreateDisposition = cpu_to_le32(oparms->disposition);
	req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK);
3023
	req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035

	/* [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;

3036
		req->hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
3037 3038
		rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
						 &name_len,
3039
						 tcon->tree_name, path);
3040
		if (rc)
3041 3042
			return rc;
		req->NameLength = cpu_to_le16(name_len * 2);
3043 3044
		uni_path_len = copy_size;
		path = copy_path;
3045 3046 3047 3048
	} 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);
3049
		copy_size = round_up(uni_path_len, 8);
3050 3051 3052 3053 3054 3055 3056
		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;
3057 3058
	}

3059 3060 3061
	iov[1].iov_len = uni_path_len;
	iov[1].iov_base = path;

3062
	if ((!server->oplocks) || (tcon->no_lease))
3063 3064
		*oplock = SMB2_OPLOCK_LEVEL_NONE;

3065
	if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) ||
3066 3067
	    *oplock == SMB2_OPLOCK_LEVEL_NONE)
		req->RequestedOplockLevel = *oplock;
3068 3069 3070
	else if (!(server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING) &&
		  (oparms->create_options & CREATE_NOT_FILE))
		req->RequestedOplockLevel = *oplock; /* no srv lease support */
3071
	else {
3072
		rc = add_lease_context(server, req, iov, &n_iov,
3073
				       oparms->fid->lease_key, oplock);
3074
		if (rc)
3075
			return rc;
3076 3077
	}

3078
	if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) {
3079
		rc = add_durable_context(iov, &n_iov, oparms,
3080
					tcon->use_persistent);
3081
		if (rc)
3082 3083 3084
			return rc;
	}

3085 3086
	if (tcon->posix_extensions) {
		rc = add_posix_context(iov, &n_iov, oparms->mode);
3087
		if (rc)
3088 3089 3090
			return rc;
	}

3091 3092 3093 3094 3095 3096 3097
	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;
	}

3098 3099 3100 3101 3102 3103 3104 3105 3106 3107
	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;
3108 3109
		}

3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120
		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;
		}
3121 3122
	}

3123
	add_query_id_context(iov, &n_iov);
3124
	add_ea_context(oparms, iov, &n_iov);
3125

3126 3127 3128 3129 3130 3131 3132 3133
	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);
3134
		req->CreateContextsLength = 0;
3135 3136 3137 3138 3139 3140 3141 3142

		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);
3143
			le32_add_cpu(&req->CreateContextsLength, len);
3144
		}
3145 3146
		le32_add_cpu(&req->CreateContextsLength,
			     iov[n_iov-1].iov_len);
3147 3148
	}

3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160
	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;

3161 3162 3163 3164 3165 3166
	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);
	}
3167 3168 3169 3170 3171
}

int
SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
	  __u8 *oplock, struct smb2_file_all_info *buf,
3172
	  struct create_posix_rsp *posix,
3173 3174 3175 3176 3177 3178
	  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;
3179
	struct TCP_Server_Info *server;
3180
	struct kvec iov[SMB2_CREATE_IOV_SIZE];
3181
	struct kvec rsp_iov = {NULL, 0};
3182
	int resp_buftype = CIFS_NO_BUFFER;
3183 3184
	int rc = 0;
	int flags = 0;
3185 3186 3187 3188 3189 3190
	int retries = 0, cur_sleep = 1;

replay_again:
	/* reinitialize for possible replay */
	flags = 0;
	server = cifs_pick_channel(ses);
3191
	oparms->replay = !!(retries);
3192 3193

	cifs_dbg(FYI, "create/open\n");
3194
	if (!ses || !server)
3195 3196 3197 3198 3199
		return -EIO;

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

3200
	memset(&rqst, 0, sizeof(struct smb_rqst));
3201
	memset(&iov, 0, sizeof(iov));
3202
	rqst.rq_iov = iov;
3203
	rqst.rq_nvec = SMB2_CREATE_IOV_SIZE;
3204

3205 3206
	rc = SMB2_open_init(tcon, server,
			    &rqst, oplock, oparms, path);
3207 3208
	if (rc)
		goto creat_exit;
3209

3210
	trace_smb3_open_enter(xid, tcon->tid, tcon->ses->Suid, oparms->path,
3211 3212
		oparms->create_options, oparms->desired_access);

3213 3214 3215
	if (retries)
		smb2_set_replay(server, &rqst);

3216 3217
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags,
3218
			    &rsp_iov);
3219
	rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
3220 3221 3222

	if (rc != 0) {
		cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
3223 3224
		if (err_iov && rsp) {
			*err_iov = rsp_iov;
3225
			*buftype = resp_buftype;
3226 3227 3228
			resp_buftype = CIFS_NO_BUFFER;
			rsp = NULL;
		}
3229 3230
		trace_smb3_open_err(xid, tcon->tid, ses->Suid,
				    oparms->create_options, oparms->desired_access, rc);
3231
		if (rc == -EREMCHG) {
3232
			pr_warn_once("server share %s deleted\n",
3233
				     tcon->tree_name);
3234 3235
			tcon->need_reconnect = true;
		}
3236
		goto creat_exit;
3237 3238 3239
	} else if (rsp == NULL) /* unlikely to happen, but safer to check */
		goto creat_exit;
	else
3240 3241
		trace_smb3_open_done(xid, rsp->PersistentFileId, tcon->tid, ses->Suid,
				     oparms->create_options, oparms->desired_access);
3242

3243
	atomic_inc(&tcon->num_remote_opens);
3244 3245
	oparms->fid->persistent_fid = rsp->PersistentFileId;
	oparms->fid->volatile_fid = rsp->VolatileFileId;
3246
	oparms->fid->access = oparms->desired_access;
3247
#ifdef CONFIG_CIFS_DEBUG2
3248
	oparms->fid->mid = le64_to_cpu(rsp->hdr.MessageId);
3249
#endif /* CIFS_DEBUG2 */
3250 3251

	if (buf) {
3252 3253 3254 3255
		buf->CreationTime = rsp->CreationTime;
		buf->LastAccessTime = rsp->LastAccessTime;
		buf->LastWriteTime = rsp->LastWriteTime;
		buf->ChangeTime = rsp->ChangeTime;
3256 3257 3258 3259 3260 3261
		buf->AllocationSize = rsp->AllocationSize;
		buf->EndOfFile = rsp->EndofFile;
		buf->Attributes = rsp->FileAttributes;
		buf->NumberOfLinks = cpu_to_le32(1);
		buf->DeletePending = 0;
	}
3262

3263

3264 3265
	rc = smb2_parse_contexts(server, &rsp_iov, &oparms->fid->epoch,
				 oparms->fid->lease_key, oplock, buf, posix);
3266
creat_exit:
3267
	SMB2_open_free(&rqst);
3268
	free_rsp_buf(resp_buftype, rsp);
3269 3270 3271 3272 3273

	if (is_replayable_error(rc) &&
	    smb2_should_replay(tcon, &retries, &cur_sleep))
		goto replay_again;

3274 3275 3276
	return rc;
}

3277
int
3278 3279
SMB2_ioctl_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
		struct smb_rqst *rqst,
3280
		u64 persistent_fid, u64 volatile_fid, u32 opcode,
3281
		char *in_data, u32 indatalen,
3282
		__u32 max_response_size)
3283 3284
{
	struct smb2_ioctl_req *req;
3285
	struct kvec *iov = rqst->rq_iov;
3286
	unsigned int total_len;
3287
	int rc;
3288
	char *in_data_buf;
3289

3290 3291
	rc = smb2_ioctl_req_init(opcode, tcon, server,
				 (void **) &req, &total_len);
3292 3293 3294
	if (rc)
		return rc;

3295 3296 3297 3298 3299
	if (indatalen) {
		/*
		 * indatalen is usually small at a couple of bytes max, so
		 * just allocate through generic pool
		 */
3300
		in_data_buf = kmemdup(in_data, indatalen, GFP_NOFS);
3301 3302 3303 3304 3305 3306
		if (!in_data_buf) {
			cifs_small_buf_release(req);
			return -ENOMEM;
		}
	}

3307 3308 3309 3310
	req->CtlCode = cpu_to_le32(opcode);
	req->PersistentFileId = persistent_fid;
	req->VolatileFileId = volatile_fid;

3311 3312 3313 3314 3315 3316 3317 3318 3319
	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]).
	 */
3320 3321 3322 3323
	if (indatalen) {
		req->InputCount = cpu_to_le32(indatalen);
		/* do not set InputOffset if no input data */
		req->InputOffset =
3324
		       cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer));
3325 3326
		rqst->rq_nvec = 2;
		iov[0].iov_len = total_len - 1;
3327
		iov[1].iov_base = in_data_buf;
3328
		iov[1].iov_len = indatalen;
3329 3330 3331 3332
	} else {
		rqst->rq_nvec = 1;
		iov[0].iov_len = total_len;
	}
3333 3334 3335 3336 3337

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

	/*
3338 3339 3340
	 * 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
3341 3342
	 * 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
3343 3344 3345 3346 3347 3348 3349 3350
	 * 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.
3351
	 */
3352
	req->MaxOutputResponse = cpu_to_le32(max_response_size);
3353
	req->hdr.CreditCharge =
3354 3355
		cpu_to_le16(DIV_ROUND_UP(max(indatalen, max_response_size),
					 SMB2_MAX_BUFFER_SIZE));
3356 3357
	/* always an FSCTL (for now) */
	req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL);
3358

3359 3360
	/* validate negotiate request must be signed - see MS-SMB2 3.2.5.5 */
	if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO)
3361
		req->hdr.Flags |= SMB2_FLAGS_SIGNED;
3362

3363 3364 3365 3366 3367 3368
	return 0;
}

void
SMB2_ioctl_free(struct smb_rqst *rqst)
{
3369
	int i;
3370

3371
	if (rqst && rqst->rq_iov) {
3372
		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3373 3374 3375
		for (i = 1; i < rqst->rq_nvec; i++)
			if (rqst->rq_iov[i].iov_base != smb2_padding)
				kfree(rqst->rq_iov[i].iov_base);
3376
	}
3377 3378
}

3379

3380 3381 3382 3383 3384
/*
 *	SMB2 IOCTL is used for both IOCTLs and FSCTLs
 */
int
SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
3385 3386 3387
	   u64 volatile_fid, u32 opcode, char *in_data, u32 indatalen,
	   u32 max_out_data_len, char **out_data,
	   u32 *plen /* returned data len */)
3388 3389 3390 3391
{
	struct smb_rqst rqst;
	struct smb2_ioctl_rsp *rsp = NULL;
	struct cifs_ses *ses;
3392
	struct TCP_Server_Info *server;
3393
	struct kvec iov[SMB2_IOCTL_IOV_SIZE];
3394 3395 3396 3397
	struct kvec rsp_iov = {NULL, 0};
	int resp_buftype = CIFS_NO_BUFFER;
	int rc = 0;
	int flags = 0;
3398
	int retries = 0, cur_sleep = 1;
3399

3400
	if (!tcon)
3401 3402
		return -EIO;

3403
	ses = tcon->ses;
3404 3405
	if (!ses)
		return -EIO;
3406

3407 3408 3409
replay_again:
	/* reinitialize for possible replay */
	flags = 0;
3410
	server = cifs_pick_channel(ses);
3411

3412
	if (!server)
3413 3414
		return -EIO;

3415 3416 3417 3418 3419 3420 3421 3422 3423
	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;

3424 3425 3426
	if (smb3_encryption_required(tcon))
		flags |= CIFS_TRANSFORM_REQ;

3427
	memset(&rqst, 0, sizeof(struct smb_rqst));
3428
	memset(&iov, 0, sizeof(iov));
3429
	rqst.rq_iov = iov;
3430
	rqst.rq_nvec = SMB2_IOCTL_IOV_SIZE;
3431

3432 3433
	rc = SMB2_ioctl_init(tcon, server,
			     &rqst, persistent_fid, volatile_fid, opcode,
3434
			     in_data, indatalen, max_out_data_len);
3435 3436
	if (rc)
		goto ioctl_exit;
3437

3438 3439 3440
	if (retries)
		smb2_set_replay(server, &rqst);

3441 3442
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags,
3443
			    &rsp_iov);
3444
	rsp = (struct smb2_ioctl_rsp *)rsp_iov.iov_base;
3445

3446 3447 3448 3449
	if (rc != 0)
		trace_smb3_fsctl_err(xid, persistent_fid, tcon->tid,
				ses->Suid, 0, opcode, rc);

Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
3450
	if ((rc != 0) && (rc != -EINVAL) && (rc != -E2BIG)) {
3451
		cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3452
		goto ioctl_exit;
3453 3454 3455
	} else if (rc == -EINVAL) {
		if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) &&
		    (opcode != FSCTL_SRV_COPYCHUNK)) {
3456
			cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3457 3458
			goto ioctl_exit;
		}
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
3459 3460 3461 3462 3463
	} else if (rc == -E2BIG) {
		if (opcode != FSCTL_QUERY_ALLOCATED_RANGES) {
			cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
			goto ioctl_exit;
		}
3464 3465 3466 3467 3468 3469
	}

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

3470 3471 3472 3473 3474 3475 3476 3477 3478 3479
	/*
	 * 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;
	}

3480 3481 3482 3483 3484
	*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 */
3485
	else if (*plen > rsp_iov.iov_len || *plen > 0xFF00) {
3486
		cifs_tcon_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen);
3487 3488 3489 3490 3491
		*plen = 0;
		rc = -EIO;
		goto ioctl_exit;
	}

3492
	if (rsp_iov.iov_len - *plen < le32_to_cpu(rsp->OutputOffset)) {
3493
		cifs_tcon_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen,
3494 3495 3496 3497 3498 3499
			le32_to_cpu(rsp->OutputOffset));
		*plen = 0;
		rc = -EIO;
		goto ioctl_exit;
	}

3500 3501
	*out_data = kmemdup((char *)rsp + le32_to_cpu(rsp->OutputOffset),
			    *plen, GFP_KERNEL);
3502 3503 3504 3505 3506 3507
	if (*out_data == NULL) {
		rc = -ENOMEM;
		goto ioctl_exit;
	}

ioctl_exit:
3508
	SMB2_ioctl_free(&rqst);
3509
	free_rsp_buf(resp_buftype, rsp);
3510 3511 3512 3513 3514

	if (is_replayable_error(rc) &&
	    smb2_should_replay(tcon, &retries, &cur_sleep))
		goto replay_again;

3515 3516 3517
	return rc;
}

3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530
/*
 *   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 =
3531
			cpu_to_le16(COMPRESSION_FORMAT_DEFAULT);
3532 3533

	rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
3534
			FSCTL_SET_COMPRESSION,
3535
			(char *)&fsctl_input /* data input */,
3536 3537
			2 /* in data len */, CIFSMaxBufSize /* max out data */,
			&ret_data /* out data */, NULL);
3538 3539 3540 3541 3542 3543

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

	return rc;
}

3544
int
3545 3546
SMB2_close_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
		struct smb_rqst *rqst,
3547
		u64 persistent_fid, u64 volatile_fid, bool query_attrs)
3548 3549 3550 3551 3552 3553
{
	struct smb2_close_req *req;
	struct kvec *iov = rqst->rq_iov;
	unsigned int total_len;
	int rc;

3554 3555
	rc = smb2_plain_req_init(SMB2_CLOSE, tcon, server,
				 (void **) &req, &total_len);
3556 3557 3558
	if (rc)
		return rc;

3559 3560
	req->PersistentFileId = persistent_fid;
	req->VolatileFileId = volatile_fid;
3561 3562 3563 3564
	if (query_attrs)
		req->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
	else
		req->Flags = 0;
3565 3566 3567 3568 3569 3570 3571 3572 3573
	iov[0].iov_base = (char *)req;
	iov[0].iov_len = total_len;

	return 0;
}

void
SMB2_close_free(struct smb_rqst *rqst)
{
3574 3575
	if (rqst && rqst->rq_iov)
		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3576 3577
}

3578
int
3579 3580 3581
__SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
	     u64 persistent_fid, u64 volatile_fid,
	     struct smb2_file_network_open_info *pbuf)
3582
{
3583
	struct smb_rqst rqst;
3584
	struct smb2_close_rsp *rsp = NULL;
3585
	struct cifs_ses *ses = tcon->ses;
3586
	struct TCP_Server_Info *server;
3587
	struct kvec iov[1];
3588
	struct kvec rsp_iov;
3589
	int resp_buftype = CIFS_NO_BUFFER;
3590
	int rc = 0;
3591
	int flags = 0;
3592
	bool query_attrs = false;
3593 3594 3595 3596 3597 3598 3599
	int retries = 0, cur_sleep = 1;

replay_again:
	/* reinitialize for possible replay */
	flags = 0;
	query_attrs = false;
	server = cifs_pick_channel(ses);
3600

3601
	cifs_dbg(FYI, "Close\n");
3602

3603
	if (!ses || !server)
3604 3605
		return -EIO;

3606
	if (smb3_encryption_required(tcon))
3607 3608
		flags |= CIFS_TRANSFORM_REQ;

3609
	memset(&rqst, 0, sizeof(struct smb_rqst));
3610
	memset(&iov, 0, sizeof(iov));
3611 3612 3613
	rqst.rq_iov = iov;
	rqst.rq_nvec = 1;

3614 3615 3616 3617
	/* check if need to ask server to return timestamps in close response */
	if (pbuf)
		query_attrs = true;

3618
	trace_smb3_close_enter(xid, persistent_fid, tcon->tid, ses->Suid);
3619 3620
	rc = SMB2_close_init(tcon, server,
			     &rqst, persistent_fid, volatile_fid,
3621
			     query_attrs);
3622 3623 3624
	if (rc)
		goto close_exit;

3625 3626 3627
	if (retries)
		smb2_set_replay(server, &rqst);

3628 3629
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
3630
	rsp = (struct smb2_close_rsp *)rsp_iov.iov_base;
3631 3632

	if (rc != 0) {
3633
		cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
3634 3635
		trace_smb3_close_err(xid, persistent_fid, tcon->tid, ses->Suid,
				     rc);
3636
		goto close_exit;
3637
	} else {
3638 3639
		trace_smb3_close_done(xid, persistent_fid, tcon->tid,
				      ses->Suid);
3640
		if (pbuf)
3641 3642 3643
			memcpy(&pbuf->network_open_info,
			       &rsp->network_open_info,
			       sizeof(pbuf->network_open_info));
3644
		atomic_dec(&tcon->num_remote_opens);
3645
	}
3646 3647

close_exit:
3648
	SMB2_close_free(&rqst);
3649
	free_rsp_buf(resp_buftype, rsp);
3650 3651

	/* retry close in a worker thread if this one is interrupted */
3652
	if (is_interrupt_error(rc)) {
3653 3654
		int tmp_rc;

3655 3656 3657 3658 3659 3660
		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);
	}
3661 3662 3663 3664 3665

	if (is_replayable_error(rc) &&
	    smb2_should_replay(tcon, &retries, &cur_sleep))
		goto replay_again;

3666
	return rc;
3667 3668
}

3669 3670 3671 3672 3673 3674 3675
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);
}

3676 3677 3678
int
smb2_validate_iov(unsigned int offset, unsigned int buffer_length,
		  struct kvec *iov, unsigned int min_buf_size)
3679
{
3680
	unsigned int smb_len = iov->iov_len;
3681 3682
	char *end_of_smb = smb_len + (char *)iov->iov_base;
	char *begin_of_buf = offset + (char *)iov->iov_base;
3683 3684 3685 3686
	char *end_of_buf = begin_of_buf + buffer_length;


	if (buffer_length < min_buf_size) {
3687 3688
		cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n",
			 buffer_length, min_buf_size);
3689 3690 3691 3692 3693
		return -EINVAL;
	}

	/* check if beyond RFC1001 maximum length */
	if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
3694 3695
		cifs_dbg(VFS, "buffer length %d or smb length %d too large\n",
			 buffer_length, smb_len);
3696 3697 3698 3699
		return -EINVAL;
	}

	if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
3700
		cifs_dbg(VFS, "Invalid server response, bad offset to data\n");
3701 3702 3703 3704 3705 3706 3707 3708 3709 3710
		return -EINVAL;
	}

	return 0;
}

/*
 * If SMB buffer fields are valid, copy into temporary buffer to hold result.
 * Caller must free buffer.
 */
3711 3712 3713 3714
int
smb2_validate_and_copy_iov(unsigned int offset, unsigned int buffer_length,
			   struct kvec *iov, unsigned int minbufsize,
			   char *data)
3715
{
3716
	char *begin_of_buf = offset + (char *)iov->iov_base;
3717 3718 3719 3720 3721
	int rc;

	if (!data)
		return -EINVAL;

3722
	rc = smb2_validate_iov(offset, buffer_length, iov, minbufsize);
3723 3724 3725
	if (rc)
		return rc;

3726
	memcpy(data, begin_of_buf, minbufsize);
3727 3728 3729 3730

	return 0;
}

3731
int
3732 3733
SMB2_query_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
		     struct smb_rqst *rqst,
3734 3735
		     u64 persistent_fid, u64 volatile_fid,
		     u8 info_class, u8 info_type, u32 additional_info,
3736
		     size_t output_len, size_t input_len, void *input)
3737 3738
{
	struct smb2_query_info_req *req;
3739
	struct kvec *iov = rqst->rq_iov;
3740
	unsigned int total_len;
3741
	size_t len;
3742
	int rc;
3743

3744 3745 3746 3747
	if (unlikely(check_add_overflow(input_len, sizeof(*req), &len) ||
		     len > CIFSMaxBufSize))
		return -EINVAL;

3748 3749
	rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
				 (void **) &req, &total_len);
3750 3751 3752
	if (rc)
		return rc;

3753
	req->InfoType = info_type;
3754
	req->FileInfoClass = info_class;
3755 3756
	req->PersistentFileId = persistent_fid;
	req->VolatileFileId = volatile_fid;
3757
	req->AdditionalInformation = cpu_to_le32(additional_info);
3758

3759
	req->OutputBufferLength = cpu_to_le32(output_len);
3760 3761 3762 3763 3764 3765
	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);
	}
3766 3767

	iov[0].iov_base = (char *)req;
3768
	/* 1 for Buffer */
3769
	iov[0].iov_len = len;
3770 3771 3772 3773 3774 3775
	return 0;
}

void
SMB2_query_info_free(struct smb_rqst *rqst)
{
3776
	if (rqst && rqst->rq_iov)
3777
		cifs_buf_release(rqst->rq_iov[0].iov_base); /* request */
3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790
}

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;
3791
	int resp_buftype = CIFS_NO_BUFFER;
3792
	struct cifs_ses *ses = tcon->ses;
3793
	struct TCP_Server_Info *server;
3794
	int flags = 0;
3795
	bool allocated = false;
3796
	int retries = 0, cur_sleep = 1;
3797 3798 3799

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

3800 3801
	if (!ses)
		return -EIO;
3802 3803 3804 3805 3806

replay_again:
	/* reinitialize for possible replay */
	flags = 0;
	allocated = false;
3807
	server = cifs_pick_channel(ses);
3808

3809
	if (!server)
3810 3811 3812 3813
		return -EIO;

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

3815
	memset(&rqst, 0, sizeof(struct smb_rqst));
3816
	memset(&iov, 0, sizeof(iov));
3817 3818 3819
	rqst.rq_iov = iov;
	rqst.rq_nvec = 1;

3820 3821
	rc = SMB2_query_info_init(tcon, server,
				  &rqst, persistent_fid, volatile_fid,
3822
				  info_class, info_type, additional_info,
3823
				  output_len, 0, NULL);
3824 3825 3826
	if (rc)
		goto qinf_exit;

3827 3828 3829
	trace_smb3_query_info_enter(xid, persistent_fid, tcon->tid,
				    ses->Suid, info_class, (__u32)info_type);

3830 3831 3832
	if (retries)
		smb2_set_replay(server, &rqst);

3833 3834
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
3835
	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
3836

3837 3838
	if (rc) {
		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
3839 3840
		trace_smb3_query_info_err(xid, persistent_fid, tcon->tid,
				ses->Suid, info_class, (__u32)info_type, rc);
3841 3842 3843
		goto qinf_exit;
	}

3844 3845 3846
	trace_smb3_query_info_done(xid, persistent_fid, tcon->tid,
				ses->Suid, info_class, (__u32)info_type);

3847 3848 3849 3850 3851
	if (dlen) {
		*dlen = le32_to_cpu(rsp->OutputBufferLength);
		if (!*data) {
			*data = kmalloc(*dlen, GFP_KERNEL);
			if (!*data) {
3852
				cifs_tcon_dbg(VFS,
3853 3854 3855
					"Error %d allocating memory for acl\n",
					rc);
				*dlen = 0;
3856
				rc = -ENOMEM;
3857 3858
				goto qinf_exit;
			}
3859
			allocated = true;
3860 3861 3862
		}
	}

3863 3864
	rc = smb2_validate_and_copy_iov(le16_to_cpu(rsp->OutputBufferOffset),
					le32_to_cpu(rsp->OutputBufferLength),
3865
					&rsp_iov, dlen ? *dlen : min_len, *data);
3866 3867 3868 3869 3870
	if (rc && allocated) {
		kfree(*data);
		*data = NULL;
		*dlen = 0;
	}
3871 3872

qinf_exit:
3873
	SMB2_query_info_free(&rqst);
3874
	free_rsp_buf(resp_buftype, rsp);
3875 3876 3877 3878 3879

	if (is_replayable_error(rc) &&
	    smb2_should_replay(tcon, &retries, &cur_sleep))
		goto replay_again;

3880 3881
	return rc;
}
3882

3883 3884 3885 3886 3887 3888 3889 3890 3891 3892
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);
}

3893 3894
#if 0
/* currently unused, as now we are doing compounding instead (see smb311_posix_query_path_info) */
3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905
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);
3906
	/* Note caller must free "data" (passed in above). It may be allocated in query_info call */
3907
}
3908
#endif
3909

3910
int
3911
SMB2_query_acl(const unsigned int xid, struct cifs_tcon *tcon,
3912
	       u64 persistent_fid, u64 volatile_fid,
3913
	       void **data, u32 *plen, u32 extra_info)
3914
{
3915 3916
	__u32 additional_info = OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
				extra_info;
3917 3918
	*plen = 0;

3919
	return query_info(xid, tcon, persistent_fid, volatile_fid,
3920
			  0, SMB2_O_INFO_SECURITY, additional_info,
3921
			  SMB2_MAX_BUFFER_SIZE, MIN_SEC_DESC_LEN, data, plen);
3922 3923 3924 3925 3926 3927 3928
}

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,
3929 3930
			  FILE_INTERNAL_INFORMATION, SMB2_O_INFO_FILE, 0,
			  sizeof(struct smb2_file_internal_info),
3931
			  sizeof(struct smb2_file_internal_info),
3932
			  (void **)&uniqueid, NULL);
3933 3934
}

3935 3936 3937 3938 3939
/*
 * CHANGE_NOTIFY Request is sent to get notifications on changes to a directory
 * See MS-SMB2 2.2.35 and 2.2.36
 */

3940
static int
3941
SMB2_notify_init(const unsigned int xid, struct smb_rqst *rqst,
3942 3943 3944
		 struct cifs_tcon *tcon, struct TCP_Server_Info *server,
		 u64 persistent_fid, u64 volatile_fid,
		 u32 completion_filter, bool watch_tree)
3945 3946 3947 3948 3949 3950
{
	struct smb2_change_notify_req *req;
	struct kvec *iov = rqst->rq_iov;
	unsigned int total_len;
	int rc;

3951 3952
	rc = smb2_plain_req_init(SMB2_CHANGE_NOTIFY, tcon, server,
				 (void **) &req, &total_len);
3953 3954 3955
	if (rc)
		return rc;

3956 3957
	req->PersistentFileId = persistent_fid;
	req->VolatileFileId = volatile_fid;
3958
	/* See note 354 of MS-SMB2, 64K max */
3959 3960
	req->OutputBufferLength =
		cpu_to_le32(SMB2_MAX_BUFFER_SIZE - MAX_SMB2_HDR_SIZE);
3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975
	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,
3976 3977
		u32 completion_filter, u32 max_out_data_len, char **out_data,
		u32 *plen /* returned data len */)
3978 3979
{
	struct cifs_ses *ses = tcon->ses;
3980
	struct TCP_Server_Info *server;
3981
	struct smb_rqst rqst;
3982
	struct smb2_change_notify_rsp *smb_rsp;
3983 3984 3985 3986 3987
	struct kvec iov[1];
	struct kvec rsp_iov = {NULL, 0};
	int resp_buftype = CIFS_NO_BUFFER;
	int flags = 0;
	int rc = 0;
3988 3989 3990 3991 3992 3993
	int retries = 0, cur_sleep = 1;

replay_again:
	/* reinitialize for possible replay */
	flags = 0;
	server = cifs_pick_channel(ses);
3994 3995

	cifs_dbg(FYI, "change notify\n");
3996
	if (!ses || !server)
3997 3998 3999 4000 4001 4002 4003
		return -EIO;

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

	memset(&rqst, 0, sizeof(struct smb_rqst));
	memset(&iov, 0, sizeof(iov));
4004 4005 4006
	if (plen)
		*plen = 0;

4007 4008 4009
	rqst.rq_iov = iov;
	rqst.rq_nvec = 1;

4010 4011
	rc = SMB2_notify_init(xid, &rqst, tcon, server,
			      persistent_fid, volatile_fid,
4012 4013 4014 4015 4016 4017
			      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);
4018 4019 4020 4021

	if (retries)
		smb2_set_replay(server, &rqst);

4022 4023
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
4024 4025 4026 4027 4028

	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);
4029
	} else {
4030
		trace_smb3_notify_done(xid, persistent_fid, tcon->tid,
4031 4032 4033
			ses->Suid, (u8)watch_tree, completion_filter);
		/* validate that notify information is plausible */
		if ((rsp_iov.iov_base == NULL) ||
4034
		    (rsp_iov.iov_len < sizeof(struct smb2_change_notify_rsp) + 1))
4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047
			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;
4048
		} else if (plen)
4049 4050
			*plen = le32_to_cpu(smb_rsp->OutputBufferLength);
	}
4051 4052 4053 4054 4055

 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);
4056 4057 4058 4059 4060

	if (is_replayable_error(rc) &&
	    smb2_should_replay(tcon, &retries, &cur_sleep))
		goto replay_again;

4061 4062 4063 4064 4065
	return rc;
}



4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076
/*
 * 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;
4077
	struct smb2_echo_rsp *rsp = (struct smb2_echo_rsp *)mid->resp_buf;
4078
	struct cifs_credits credits = { .value = 0, .instance = 0 };
4079

4080
	if (mid->mid_state == MID_RESPONSE_RECEIVED
4081
	    || mid->mid_state == MID_RESPONSE_MALFORMED) {
4082
		credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4083 4084
		credits.instance = server->reconnect_instance;
	}
4085

4086
	release_mid(mid);
4087
	add_credits(server, &credits, CIFS_ECHO_OP);
4088 4089
}

4090 4091 4092 4093
void smb2_reconnect_server(struct work_struct *work)
{
	struct TCP_Server_Info *server = container_of(work,
					struct TCP_Server_Info, reconnect.work);
4094 4095
	struct TCP_Server_Info *pserver;
	struct cifs_ses *ses, *ses2;
4096
	struct cifs_tcon *tcon, *tcon2;
4097
	struct list_head tmp_list, tmp_ses_list;
4098
	bool ses_exist = false;
4099
	bool tcon_selected = false;
4100
	int rc;
4101
	bool resched = false;
4102

4103 4104 4105 4106 4107 4108 4109 4110 4111
	/* first check if ref count has reached 0, if not inc ref count */
	spin_lock(&cifs_tcp_ses_lock);
	if (!server->srv_count) {
		spin_unlock(&cifs_tcp_ses_lock);
		return;
	}
	server->srv_count++;
	spin_unlock(&cifs_tcp_ses_lock);

4112
	/* If server is a channel, select the primary channel */
4113
	pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
4114 4115

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

4118 4119 4120 4121 4122 4123 4124
	/* if the server is marked for termination, drop the ref count here */
	if (server->terminate) {
		cifs_put_tcp_session(server, true);
		mutex_unlock(&pserver->reconnect_mutex);
		return;
	}

4125
	INIT_LIST_HEAD(&tmp_list);
4126 4127
	INIT_LIST_HEAD(&tmp_ses_list);
	cifs_dbg(FYI, "Reconnecting tcons and channels\n");
4128 4129

	spin_lock(&cifs_tcp_ses_lock);
4130
	list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
4131 4132 4133 4134 4135 4136
		spin_lock(&ses->ses_lock);
		if (ses->ses_status == SES_EXITING) {
			spin_unlock(&ses->ses_lock);
			continue;
		}
		spin_unlock(&ses->ses_lock);
4137

4138
		tcon_selected = false;
4139

4140
		list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
4141
			if (tcon->need_reconnect || tcon->need_reopen_files) {
4142
				tcon->tc_count++;
4143 4144
				trace_smb3_tcon_ref(tcon->debug_id, tcon->tc_count,
						    netfs_trace_tcon_ref_get_reconnect_server);
4145
				list_add_tail(&tcon->rlist, &tmp_list);
4146
				tcon_selected = true;
4147 4148
			}
		}
4149 4150 4151 4152
		/*
		 * IPC has the same lifetime as its session and uses its
		 * refcount.
		 */
4153 4154
		if (ses->tcon_ipc && ses->tcon_ipc->need_reconnect) {
			list_add_tail(&ses->tcon_ipc->rlist, &tmp_list);
4155
			tcon_selected = true;
4156
			cifs_smb_ses_inc_refcount(ses);
4157 4158 4159 4160 4161 4162
		}
		/*
		 * handle the case where channel needs to reconnect
		 * binding session, but tcon is healthy (some other channel
		 * is active)
		 */
4163
		spin_lock(&ses->chan_lock);
4164 4165
		if (!tcon_selected && cifs_chan_needs_reconnect(ses, server)) {
			list_add_tail(&ses->rlist, &tmp_ses_list);
4166
			ses_exist = true;
4167
			cifs_smb_ses_inc_refcount(ses);
4168
		}
4169
		spin_unlock(&ses->chan_lock);
4170 4171 4172 4173
	}
	spin_unlock(&cifs_tcp_ses_lock);

	list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) {
4174
		rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server, true);
4175
		if (!rc)
4176
			cifs_reopen_persistent_handles(tcon);
4177 4178
		else
			resched = true;
4179
		list_del_init(&tcon->rlist);
4180 4181 4182
		if (tcon->ipc)
			cifs_put_smb_ses(tcon->ses);
		else
4183
			cifs_put_tcon(tcon, netfs_trace_tcon_ref_put_reconnect_server);
4184 4185
	}

4186 4187 4188 4189
	if (!ses_exist)
		goto done;

	/* allocate a dummy tcon struct used for reconnect */
4190
	tcon = tcon_info_alloc(false, netfs_trace_tcon_ref_new_reconnect_server);
4191 4192
	if (!tcon) {
		resched = true;
4193 4194 4195 4196
		list_for_each_entry_safe(ses, ses2, &tmp_ses_list, rlist) {
			list_del_init(&ses->rlist);
			cifs_put_smb_ses(ses);
		}
4197 4198 4199
		goto done;
	}

4200
	tcon->status = TID_GOOD;
4201 4202 4203 4204 4205 4206
	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;
4207
		rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server, true);
4208 4209 4210 4211 4212
		if (rc)
			resched = true;
		list_del_init(&ses->rlist);
		cifs_put_smb_ses(ses);
	}
4213
	tconInfoFree(tcon, netfs_trace_tcon_ref_free_reconnect_server);
4214 4215 4216

done:
	cifs_dbg(FYI, "Reconnecting tcons and channels finished\n");
4217
	if (resched)
4218
		queue_delayed_work(cifsiod_wq, &server->reconnect, 2 * HZ);
4219
	mutex_unlock(&pserver->reconnect_mutex);
4220 4221

	/* now we can safely release srv struct */
4222
	cifs_put_tcp_session(server, true);
4223 4224
}

4225 4226 4227 4228 4229
int
SMB2_echo(struct TCP_Server_Info *server)
{
	struct smb2_echo_req *req;
	int rc = 0;
4230
	struct kvec iov[1];
4231
	struct smb_rqst rqst = { .rq_iov = iov,
4232
				 .rq_nvec = 1 };
4233
	unsigned int total_len;
4234

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

4237
	spin_lock(&server->srv_lock);
4238 4239
	if (server->ops->need_neg &&
	    server->ops->need_neg(server)) {
4240
		spin_unlock(&server->srv_lock);
4241
		/* No need to send echo on newly established connections */
4242
		mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
4243
		return rc;
4244
	}
4245
	spin_unlock(&server->srv_lock);
4246

4247 4248
	rc = smb2_plain_req_init(SMB2_ECHO, NULL, server,
				 (void **)&req, &total_len);
4249 4250 4251
	if (rc)
		return rc;

4252
	req->hdr.CreditRequest = cpu_to_le16(1);
4253

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

4257
	rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, NULL,
4258
			     server, CIFS_ECHO_OP, NULL);
4259
	if (rc)
4260
		cifs_dbg(FYI, "Echo request failed: %d\n", rc);
4261 4262 4263 4264

	cifs_small_buf_release(req);
	return rc;
}
4265

4266 4267 4268 4269 4270 4271 4272
void
SMB2_flush_free(struct smb_rqst *rqst)
{
	if (rqst && rqst->rq_iov)
		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
}

4273
int
4274
SMB2_flush_init(const unsigned int xid, struct smb_rqst *rqst,
4275 4276
		struct cifs_tcon *tcon, struct TCP_Server_Info *server,
		u64 persistent_fid, u64 volatile_fid)
4277 4278
{
	struct smb2_flush_req *req;
4279
	struct kvec *iov = rqst->rq_iov;
4280
	unsigned int total_len;
4281
	int rc;
4282

4283 4284
	rc = smb2_plain_req_init(SMB2_FLUSH, tcon, server,
				 (void **) &req, &total_len);
4285 4286 4287
	if (rc)
		return rc;

4288 4289
	req->PersistentFileId = persistent_fid;
	req->VolatileFileId = volatile_fid;
4290 4291

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

4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304
	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};
4305
	struct TCP_Server_Info *server;
4306 4307 4308
	int resp_buftype = CIFS_NO_BUFFER;
	int flags = 0;
	int rc = 0;
4309 4310 4311 4312 4313 4314
	int retries = 0, cur_sleep = 1;

replay_again:
	/* reinitialize for possible replay */
	flags = 0;
	server = cifs_pick_channel(ses);
4315 4316 4317 4318 4319 4320 4321 4322

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

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

4323
	memset(&rqst, 0, sizeof(struct smb_rqst));
4324
	memset(&iov, 0, sizeof(iov));
4325 4326 4327
	rqst.rq_iov = iov;
	rqst.rq_nvec = 1;

4328 4329
	rc = SMB2_flush_init(xid, &rqst, tcon, server,
			     persistent_fid, volatile_fid);
4330 4331 4332
	if (rc)
		goto flush_exit;

4333
	trace_smb3_flush_enter(xid, persistent_fid, tcon->tid, ses->Suid);
4334 4335 4336 4337

	if (retries)
		smb2_set_replay(server, &rqst);

4338 4339
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
4340

4341
	if (rc != 0) {
4342
		cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
4343 4344
		trace_smb3_flush_err(xid, persistent_fid, tcon->tid, ses->Suid,
				     rc);
4345 4346 4347
	} else
		trace_smb3_flush_done(xid, persistent_fid, tcon->tid,
				      ses->Suid);
4348

4349 4350
 flush_exit:
	SMB2_flush_free(&rqst);
4351
	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4352 4353 4354 4355 4356

	if (is_replayable_error(rc) &&
	    smb2_should_replay(tcon, &retries, &cur_sleep))
		goto replay_again;

4357 4358
	return rc;
}
4359

4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377
#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;

4378 4379 4380 4381
	/* we don't support encrypted offload yet */
	if (smb3_encryption_required(tcon))
		return false;

4382 4383 4384 4385 4386 4387 4388 4389
	/* 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 */

4390 4391 4392 4393 4394
/*
 * 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
4395
smb2_new_read_req(void **buf, unsigned int *total_len,
4396
	struct cifs_io_parms *io_parms, struct cifs_io_subrequest *rdata,
4397
	unsigned int remaining_bytes, int request_type)
4398 4399
{
	int rc = -EACCES;
4400
	struct smb2_read_req *req = NULL;
4401
	struct smb2_hdr *shdr;
4402
	struct TCP_Server_Info *server = io_parms->server;
4403

4404 4405
	rc = smb2_plain_req_init(SMB2_READ, io_parms->tcon, server,
				 (void **) &req, total_len);
4406 4407
	if (rc)
		return rc;
4408 4409

	if (server == NULL)
4410 4411
		return -ECONNABORTED;

4412 4413
	shdr = &req->hdr;
	shdr->Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
4414

4415 4416
	req->PersistentFileId = io_parms->persistent_fid;
	req->VolatileFileId = io_parms->volatile_fid;
4417 4418 4419 4420 4421 4422
	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);
4423

4424 4425 4426 4427 4428 4429
	trace_smb3_read_enter(rdata ? rdata->rreq->debug_id : 0,
			      rdata ? rdata->subreq.debug_index : 0,
			      rdata ? rdata->xid : 0,
			      io_parms->persistent_fid,
			      io_parms->tcon->tid, io_parms->tcon->ses->Suid,
			      io_parms->offset, io_parms->length);
4430 4431 4432 4433 4434
#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
	 */
4435
	if (smb3_use_rdma_offload(io_parms)) {
4436
		struct smbd_buffer_descriptor_v1 *v1;
4437
		bool need_invalidate = server->dialect == SMB30_PROT_ID;
4438

4439
		rdata->mr = smbd_register_mr(server->smbd_conn, &rdata->subreq.io_iter,
4440
					     true, need_invalidate);
4441
		if (!rdata->mr)
4442
			return -EAGAIN;
4443 4444 4445 4446 4447

		req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
		if (need_invalidate)
			req->Channel = SMB2_CHANNEL_RDMA_V1;
		req->ReadChannelInfoOffset =
4448
			cpu_to_le16(offsetof(struct smb2_read_req, Buffer));
4449
		req->ReadChannelInfoLength =
4450
			cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
4451
		v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
4452 4453 4454
		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);
4455 4456 4457 4458

		*total_len += sizeof(*v1) - 1;
	}
#endif
4459 4460
	if (request_type & CHAINED_REQUEST) {
		if (!(request_type & END_OF_CHAIN)) {
4461
			/* next 8-byte aligned request */
4462
			*total_len = ALIGN(*total_len, 8);
4463
			shdr->NextCommand = cpu_to_le32(*total_len);
4464
		} else /* END_OF_CHAIN */
4465
			shdr->NextCommand = 0;
4466
		if (request_type & RELATED_REQUEST) {
4467
			shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
4468 4469 4470 4471
			/*
			 * Related requests use info from previous read request
			 * in chain.
			 */
4472 4473
			shdr->SessionId = cpu_to_le64(0xFFFFFFFFFFFFFFFF);
			shdr->Id.SyncId.TreeId = cpu_to_le32(0xFFFFFFFF);
4474 4475
			req->PersistentFileId = (u64)-1;
			req->VolatileFileId = (u64)-1;
4476 4477 4478 4479 4480 4481 4482
		}
	}
	if (remaining_bytes > io_parms->length)
		req->RemainingBytes = cpu_to_le32(remaining_bytes);
	else
		req->RemainingBytes = 0;

4483
	*buf = req;
4484 4485 4486 4487 4488 4489
	return rc;
}

static void
smb2_readv_callback(struct mid_q_entry *mid)
{
4490
	struct cifs_io_subrequest *rdata = mid->callback_data;
4491
	struct cifs_tcon *tcon = tlink_tcon(rdata->req->cfile->tlink);
4492
	struct TCP_Server_Info *server = rdata->server;
4493 4494
	struct smb2_hdr *shdr =
				(struct smb2_hdr *)rdata->iov[0].iov_base;
4495
	struct cifs_credits credits = { .value = 0, .instance = 0 };
4496 4497 4498
	struct smb_rqst rqst = { .rq_iov = &rdata->iov[1], .rq_nvec = 1 };

	if (rdata->got_bytes) {
4499 4500
		rqst.rq_iter	  = rdata->subreq.io_iter;
		rqst.rq_iter_size = iov_iter_count(&rdata->subreq.io_iter);
Yang Li's avatar
Yang Li committed
4501
	}
4502

4503 4504 4505 4506
	WARN_ONCE(rdata->server != mid->server,
		  "rdata server %p != mid server %p",
		  rdata->server, mid->server);

4507
	cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%zu\n",
4508
		 __func__, mid->mid, mid->mid_state, rdata->result,
4509
		 rdata->subreq.len);
4510 4511 4512

	switch (mid->mid_state) {
	case MID_RESPONSE_RECEIVED:
4513 4514
		credits.value = le16_to_cpu(shdr->CreditRequest);
		credits.instance = server->reconnect_instance;
4515
		/* result already set, check signature */
4516
		if (server->sign && !mid->decrypted) {
4517 4518
			int rc;

4519
			iov_iter_truncate(&rqst.rq_iter, rdata->got_bytes);
4520
			rc = smb2_verify_signature(&rqst, server);
4521
			if (rc)
4522
				cifs_tcon_dbg(VFS, "SMB signature verification returned error = %d\n",
4523
					 rc);
4524
		}
4525
		/* FIXME: should this be counted toward the initiating task? */
4526 4527
		task_io_account_read(rdata->got_bytes);
		cifs_stats_bytes_read(tcon, rdata->got_bytes);
4528 4529 4530 4531
		break;
	case MID_REQUEST_SUBMITTED:
	case MID_RETRY_NEEDED:
		rdata->result = -EAGAIN;
4532 4533 4534 4535 4536 4537
		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);
4538
		break;
4539
	case MID_RESPONSE_MALFORMED:
4540 4541
		credits.value = le16_to_cpu(shdr->CreditRequest);
		credits.instance = server->reconnect_instance;
4542
		fallthrough;
4543
	default:
4544
		rdata->result = -EIO;
4545
	}
4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556
#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
4557
	if (rdata->result && rdata->result != -ENODATA) {
4558
		cifs_stats_fail_inc(tcon, SMB2_READ_HE);
4559 4560 4561 4562
		trace_smb3_read_err(rdata->rreq->debug_id,
				    rdata->subreq.debug_index,
				    rdata->xid,
				    rdata->req->cfile->fid.persistent_fid,
4563 4564
				    tcon->tid, tcon->ses->Suid, rdata->subreq.start,
				    rdata->subreq.len, rdata->result);
4565
	} else
4566 4567 4568 4569
		trace_smb3_read_done(rdata->rreq->debug_id,
				     rdata->subreq.debug_index,
				     rdata->xid,
				     rdata->req->cfile->fid.persistent_fid,
4570
				     tcon->tid, tcon->ses->Suid,
4571
				     rdata->subreq.start, rdata->got_bytes);
4572

4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583
	if (rdata->result == -ENODATA) {
		/* We may have got an EOF error because fallocate
		 * failed to enlarge the file.
		 */
		if (rdata->subreq.start < rdata->subreq.rreq->i_size)
			rdata->result = 0;
	}
	rdata->credits.value = 0;
	netfs_subreq_terminated(&rdata->subreq,
				(rdata->result == 0 || rdata->result == -EAGAIN) ?
				rdata->got_bytes : rdata->result, true);
4584
	release_mid(mid);
4585
	add_credits(server, &credits, 0);
4586 4587
}

4588
/* smb2_async_readv - send an async read, and set up mid to handle result */
4589
int
4590
smb2_async_readv(struct cifs_io_subrequest *rdata)
4591
{
4592
	int rc, flags = 0;
4593
	char *buf;
4594
	struct smb2_hdr *shdr;
4595
	struct cifs_io_parms io_parms;
4596
	struct smb_rqst rqst = { .rq_iov = rdata->iov,
4597
				 .rq_nvec = 1 };
4598
	struct TCP_Server_Info *server;
4599
	struct cifs_tcon *tcon = tlink_tcon(rdata->req->cfile->tlink);
4600
	unsigned int total_len;
4601
	int credit_request;
4602

4603 4604
	cifs_dbg(FYI, "%s: offset=%llu bytes=%zu\n",
		 __func__, rdata->subreq.start, rdata->subreq.len);
4605

4606 4607 4608
	if (!rdata->server)
		rdata->server = cifs_pick_channel(tcon->ses);

4609
	io_parms.tcon = tlink_tcon(rdata->req->cfile->tlink);
4610
	io_parms.server = server = rdata->server;
4611 4612
	io_parms.offset = rdata->subreq.start;
	io_parms.length = rdata->subreq.len;
4613 4614
	io_parms.persistent_fid = rdata->req->cfile->fid.persistent_fid;
	io_parms.volatile_fid = rdata->req->cfile->fid.volatile_fid;
4615
	io_parms.pid = rdata->pid;
4616

4617 4618
	rc = smb2_new_read_req(
		(void **) &buf, &total_len, &io_parms, rdata, 0, 0);
4619
	if (rc)
4620 4621
		return rc;

4622
	if (smb3_encryption_required(io_parms.tcon))
4623 4624
		flags |= CIFS_TRANSFORM_REQ;

4625 4626
	rdata->iov[0].iov_base = buf;
	rdata->iov[0].iov_len = total_len;
4627

4628
	shdr = (struct smb2_hdr *)buf;
4629

4630
	if (rdata->credits.value > 0) {
4631
		shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(rdata->subreq.len,
4632
						SMB2_MAX_BUFFER_SIZE));
4633 4634 4635 4636 4637 4638 4639
		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));
4640

4641
		rc = adjust_credits(server, &rdata->credits, rdata->subreq.len);
4642
		if (rc)
4643
			goto async_readv_out;
4644

4645
		flags |= CIFS_HAS_CREDITS;
4646 4647
	}

4648
	rc = cifs_call_async(server, &rqst,
4649
			     cifs_readv_receive, smb2_readv_callback,
4650 4651
			     smb3_handle_read_data, rdata, flags,
			     &rdata->credits);
4652 4653
	if (rc) {
		cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE);
4654 4655 4656
		trace_smb3_read_err(rdata->rreq->debug_id,
				    rdata->subreq.debug_index,
				    rdata->xid, io_parms.persistent_fid,
4657 4658 4659 4660
				    io_parms.tcon->tid,
				    io_parms.tcon->ses->Suid,
				    io_parms.offset, io_parms.length, rc);
	}
4661

4662
async_readv_out:
4663 4664 4665
	cifs_small_buf_release(buf);
	return rc;
}
4666

4667 4668 4669 4670
int
SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
	  unsigned int *nbytes, char **buf, int *buf_type)
{
4671
	struct smb_rqst rqst;
4672
	int resp_buftype, rc;
4673
	struct smb2_read_req *req = NULL;
4674
	struct smb2_read_rsp *rsp = NULL;
4675
	struct kvec iov[1];
4676
	struct kvec rsp_iov;
4677
	unsigned int total_len;
4678 4679
	int flags = CIFS_LOG_ERROR;
	struct cifs_ses *ses = io_parms->tcon->ses;
4680

4681 4682 4683
	if (!io_parms->server)
		io_parms->server = cifs_pick_channel(io_parms->tcon->ses);

4684
	*nbytes = 0;
4685
	rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);
4686 4687 4688
	if (rc)
		return rc;

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

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

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

4699 4700
	rc = cifs_send_recv(xid, ses, io_parms->server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
4701
	rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
4702

4703 4704 4705 4706
	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);
4707
			trace_smb3_read_err(0, 0, xid,
4708
					    req->PersistentFileId,
4709 4710 4711
					    io_parms->tcon->tid, ses->Suid,
					    io_parms->offset, io_parms->length,
					    rc);
4712
		} else
4713 4714
			trace_smb3_read_done(0, 0, xid,
					     req->PersistentFileId, io_parms->tcon->tid,
4715
					     ses->Suid, io_parms->offset, 0);
4716
		free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4717
		cifs_small_buf_release(req);
4718
		return rc == -ENODATA ? 0 : rc;
4719
	} else
4720 4721 4722 4723
		trace_smb3_read_done(0, 0, xid,
				     req->PersistentFileId,
				     io_parms->tcon->tid, ses->Suid,
				     io_parms->offset, io_parms->length);
4724

4725 4726
	cifs_small_buf_release(req);

4727 4728 4729 4730 4731 4732 4733
	*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;
4734 4735 4736
	}

	if (*buf) {
4737
		memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);
4738
		free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4739
	} else if (resp_buftype != CIFS_NO_BUFFER) {
4740
		*buf = rsp_iov.iov_base;
4741 4742 4743 4744 4745 4746 4747 4748
		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;
}

4749 4750 4751 4752 4753 4754 4755
/*
 * 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)
{
4756
	struct cifs_io_subrequest *wdata = mid->callback_data;
4757
	struct cifs_tcon *tcon = tlink_tcon(wdata->req->cfile->tlink);
4758
	struct TCP_Server_Info *server = wdata->server;
4759
	struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
4760
	struct cifs_credits credits = { .value = 0, .instance = 0 };
4761 4762
	ssize_t result = 0;
	size_t written;
4763

4764 4765 4766 4767
	WARN_ONCE(wdata->server != mid->server,
		  "wdata server %p != mid server %p",
		  wdata->server, mid->server);

4768 4769
	switch (mid->mid_state) {
	case MID_RESPONSE_RECEIVED:
4770
		credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4771
		credits.instance = server->reconnect_instance;
4772 4773
		result = smb2_check_receive(mid, server, 0);
		if (result != 0)
4774 4775 4776 4777 4778 4779 4780 4781 4782
			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.
		 */
4783
		if (written > wdata->subreq.len)
4784 4785
			written &= 0xFFFF;

4786
		if (written < wdata->subreq.len)
4787 4788
			wdata->result = -ENOSPC;
		else
4789
			wdata->subreq.len = written;
4790 4791 4792
		break;
	case MID_REQUEST_SUBMITTED:
	case MID_RETRY_NEEDED:
4793
		result = -EAGAIN;
4794
		break;
4795
	case MID_RESPONSE_MALFORMED:
4796
		credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4797
		credits.instance = server->reconnect_instance;
4798
		fallthrough;
4799
	default:
4800
		result = -EIO;
4801 4802
		break;
	}
4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815
#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
4816
	if (result) {
4817
		cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
4818 4819
		trace_smb3_write_err(wdata->xid,
				     wdata->req->cfile->fid.persistent_fid,
4820 4821
				     tcon->tid, tcon->ses->Suid, wdata->subreq.start,
				     wdata->subreq.len, wdata->result);
4822
		if (wdata->result == -ENOSPC)
4823
			pr_warn_once("Out of space writing to %s\n",
4824
				     tcon->tree_name);
4825 4826
	} else
		trace_smb3_write_done(0 /* no xid */,
4827
				      wdata->req->cfile->fid.persistent_fid,
4828
				      tcon->tid, tcon->ses->Suid,
4829
				      wdata->subreq.start, wdata->subreq.len);
4830

4831 4832
	wdata->credits.value = 0;
	cifs_write_subrequest_terminated(wdata, result ?: written, true);
4833
	release_mid(mid);
4834
	add_credits(server, &credits, 0);
4835 4836 4837
}

/* smb2_async_writev - send an async write, and set up mid to handle result */
4838
void
4839
smb2_async_writev(struct cifs_io_subrequest *wdata)
4840
{
4841
	int rc = -EACCES, flags = 0;
4842
	struct smb2_write_req *req = NULL;
4843
	struct smb2_hdr *shdr;
4844
	struct cifs_tcon *tcon = tlink_tcon(wdata->req->cfile->tlink);
4845
	struct TCP_Server_Info *server = wdata->server;
4846
	struct kvec iov[1];
4847
	struct smb_rqst rqst = { };
4848
	unsigned int total_len, xid = wdata->xid;
4849 4850
	struct cifs_io_parms _io_parms;
	struct cifs_io_parms *io_parms = NULL;
4851
	int credit_request;
4852

4853
	if (!wdata->server || test_bit(NETFS_SREQ_RETRYING, &wdata->subreq.flags))
4854 4855
		server = wdata->server = cifs_pick_channel(tcon->ses);

4856 4857 4858 4859 4860 4861 4862
	/*
	 * 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,
4863 4864
		.offset = wdata->subreq.start,
		.length = wdata->subreq.len,
4865 4866
		.persistent_fid = wdata->req->cfile->fid.persistent_fid,
		.volatile_fid = wdata->req->cfile->fid.volatile_fid,
4867 4868 4869 4870
		.pid = wdata->pid,
	};
	io_parms = &_io_parms;

4871 4872
	rc = smb2_plain_req_init(SMB2_WRITE, tcon, server,
				 (void **) &req, &total_len);
4873
	if (rc)
4874
		goto out;
4875

4876
	if (smb3_encryption_required(tcon))
4877 4878
		flags |= CIFS_TRANSFORM_REQ;

4879
	shdr = (struct smb2_hdr *)req;
4880
	shdr->Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
4881

4882 4883
	req->PersistentFileId = io_parms->persistent_fid;
	req->VolatileFileId = io_parms->volatile_fid;
4884 4885
	req->WriteChannelInfoOffset = 0;
	req->WriteChannelInfoLength = 0;
4886
	req->Channel = SMB2_CHANNEL_NONE;
4887
	req->Offset = cpu_to_le64(io_parms->offset);
4888
	req->DataOffset = cpu_to_le16(
4889
				offsetof(struct smb2_write_req, Buffer));
4890
	req->RemainingBytes = 0;
4891

4892
	trace_smb3_write_enter(wdata->xid,
4893 4894 4895 4896 4897 4898
			       io_parms->persistent_fid,
			       io_parms->tcon->tid,
			       io_parms->tcon->ses->Suid,
			       io_parms->offset,
			       io_parms->length);

4899 4900 4901 4902 4903
#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
	 */
4904
	if (smb3_use_rdma_offload(io_parms)) {
4905
		struct smbd_buffer_descriptor_v1 *v1;
4906
		size_t data_size = iov_iter_count(&wdata->subreq.io_iter);
4907 4908
		bool need_invalidate = server->dialect == SMB30_PROT_ID;

4909
		wdata->mr = smbd_register_mr(server->smbd_conn, &wdata->subreq.io_iter,
4910
					     false, need_invalidate);
4911
		if (!wdata->mr) {
4912
			rc = -EAGAIN;
4913 4914 4915 4916
			goto async_writev_out;
		}
		req->Length = 0;
		req->DataOffset = 0;
4917
		req->RemainingBytes = cpu_to_le32(data_size);
4918 4919 4920 4921
		req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
		if (need_invalidate)
			req->Channel = SMB2_CHANNEL_RDMA_V1;
		req->WriteChannelInfoOffset =
4922
			cpu_to_le16(offsetof(struct smb2_write_req, Buffer));
4923
		req->WriteChannelInfoLength =
4924
			cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
4925
		v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
4926 4927 4928
		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);
4929 4930
	}
#endif
4931 4932
	iov[0].iov_len = total_len - 1;
	iov[0].iov_base = (char *)req;
4933

4934
	rqst.rq_iov = iov;
4935
	rqst.rq_nvec = 1;
4936
	rqst.rq_iter = wdata->subreq.io_iter;
4937
	rqst.rq_iter_size = iov_iter_count(&rqst.rq_iter);
4938
	if (test_bit(NETFS_SREQ_RETRYING, &wdata->subreq.flags))
4939
		smb2_set_replay(server, &rqst);
4940
#ifdef CONFIG_CIFS_SMB_DIRECT
4941
	if (wdata->mr)
4942
		iov[0].iov_len += sizeof(struct smbd_buffer_descriptor_v1);
4943
#endif
4944 4945
	cifs_dbg(FYI, "async write at %llu %u bytes iter=%zx\n",
		 io_parms->offset, io_parms->length, iov_iter_count(&rqst.rq_iter));
4946

4947 4948 4949
#ifdef CONFIG_CIFS_SMB_DIRECT
	/* For RDMA read, I/O size is in RemainingBytes not in Length */
	if (!wdata->mr)
4950
		req->Length = cpu_to_le32(io_parms->length);
4951
#else
4952
	req->Length = cpu_to_le32(io_parms->length);
4953
#endif
4954

4955
	if (wdata->credits.value > 0) {
4956
		shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->subreq.len,
4957
						    SMB2_MAX_BUFFER_SIZE));
4958 4959 4960 4961 4962 4963 4964
		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));
4965

4966
		rc = adjust_credits(server, &wdata->credits, io_parms->length);
4967
		if (rc)
4968
			goto async_writev_out;
4969

4970
		flags |= CIFS_HAS_CREDITS;
4971 4972
	}

4973
	rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, NULL,
4974
			     wdata, flags, &wdata->credits);
4975
	/* Can't touch wdata if rc == 0 */
4976
	if (rc) {
4977
		trace_smb3_write_err(xid,
4978 4979 4980 4981 4982 4983
				     io_parms->persistent_fid,
				     io_parms->tcon->tid,
				     io_parms->tcon->ses->Suid,
				     io_parms->offset,
				     io_parms->length,
				     rc);
4984
		cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
4985
	}
4986 4987 4988

async_writev_out:
	cifs_small_buf_release(req);
4989 4990 4991 4992 4993
out:
	if (rc) {
		add_credits_and_wake_if(wdata->server, &wdata->credits, 0);
		cifs_write_subrequest_terminated(wdata, rc, true);
	}
4994
}
4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005

/*
 * 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)
{
5006
	struct smb_rqst rqst;
5007 5008 5009 5010
	int rc = 0;
	struct smb2_write_req *req = NULL;
	struct smb2_write_rsp *rsp = NULL;
	int resp_buftype;
5011
	struct kvec rsp_iov;
5012
	int flags = 0;
5013
	unsigned int total_len;
5014
	struct TCP_Server_Info *server;
5015
	int retries = 0, cur_sleep = 1;
5016

5017 5018 5019
replay_again:
	/* reinitialize for possible replay */
	flags = 0;
5020
	*nbytes = 0;
5021 5022 5023 5024 5025 5026
	if (!io_parms->server)
		io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
	server = io_parms->server;
	if (server == NULL)
		return -ECONNABORTED;

5027 5028 5029
	if (n_vec < 1)
		return rc;

5030 5031
	rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, server,
				 (void **) &req, &total_len);
5032 5033 5034
	if (rc)
		return rc;

5035
	if (smb3_encryption_required(io_parms->tcon))
5036 5037
		flags |= CIFS_TRANSFORM_REQ;

5038
	req->hdr.Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
5039

5040 5041
	req->PersistentFileId = io_parms->persistent_fid;
	req->VolatileFileId = io_parms->volatile_fid;
5042 5043 5044 5045 5046 5047
	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(
5048
				offsetof(struct smb2_write_req, Buffer));
5049 5050
	req->RemainingBytes = 0;

5051 5052 5053 5054
	trace_smb3_write_enter(xid, io_parms->persistent_fid,
		io_parms->tcon->tid, io_parms->tcon->ses->Suid,
		io_parms->offset, io_parms->length);

5055
	iov[0].iov_base = (char *)req;
5056 5057
	/* 1 for Buffer */
	iov[0].iov_len = total_len - 1;
5058

5059 5060 5061 5062
	memset(&rqst, 0, sizeof(struct smb_rqst));
	rqst.rq_iov = iov;
	rqst.rq_nvec = n_vec + 1;

5063 5064 5065
	if (retries)
		smb2_set_replay(server, &rqst);

5066 5067
	rc = cifs_send_recv(xid, io_parms->tcon->ses, server,
			    &rqst,
5068
			    &resp_buftype, flags, &rsp_iov);
5069
	rsp = (struct smb2_write_rsp *)rsp_iov.iov_base;
5070 5071

	if (rc) {
5072
		trace_smb3_write_err(xid,
5073
				     req->PersistentFileId,
5074 5075 5076
				     io_parms->tcon->tid,
				     io_parms->tcon->ses->Suid,
				     io_parms->offset, io_parms->length, rc);
5077
		cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
5078
		cifs_dbg(VFS, "Send error in write = %d\n", rc);
5079
	} else {
5080
		*nbytes = le32_to_cpu(rsp->DataLength);
5081
		trace_smb3_write_done(xid,
5082
				      req->PersistentFileId,
5083 5084 5085
				      io_parms->tcon->tid,
				      io_parms->tcon->ses->Suid,
				      io_parms->offset, *nbytes);
5086
	}
5087

5088
	cifs_small_buf_release(req);
5089
	free_rsp_buf(resp_buftype, rsp);
5090 5091 5092 5093 5094

	if (is_replayable_error(rc) &&
	    smb2_should_replay(io_parms->tcon, &retries, &cur_sleep))
		goto replay_again;

5095 5096
	return rc;
}
5097

5098
int posix_info_sid_size(const void *beg, const void *end)
5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121
{
	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;
5122
	int owner_len, group_len;
5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144
	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;
5145 5146
	owner_len = posix_info_sid_size(owner_sid, end);
	if (owner_len < 0)
5147
		return -1;
5148
	total_len += owner_len;
5149 5150 5151

	/* check group sid */
	group_sid = beg + total_len;
5152 5153
	group_len = posix_info_sid_size(group_sid, end);
	if (group_len < 0)
5154
		return -1;
5155
	total_len += group_len;
5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175

	/* 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;
5176 5177
		memcpy(&out->owner, owner_sid, owner_len);
		memcpy(&out->group, group_sid, group_len);
5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190
	}
	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);
}

5191
static unsigned int
5192 5193
num_entries(int infotype, char *bufstart, char *end_of_buf, char **lastentry,
	    size_t size)
5194 5195 5196 5197
{
	int len;
	unsigned int entrycount = 0;
	unsigned int next_offset = 0;
5198 5199
	char *entryptr;
	FILE_DIRECTORY_INFO *dir_info;
5200 5201 5202 5203

	if (bufstart == NULL)
		return 0;

5204
	entryptr = bufstart;
5205 5206

	while (1) {
5207 5208 5209
		if (entryptr + next_offset < entryptr ||
		    entryptr + next_offset > end_of_buf ||
		    entryptr + next_offset + size > end_of_buf) {
5210
			cifs_dbg(VFS, "malformed search entry would overflow\n");
5211 5212 5213
			break;
		}

5214 5215 5216
		entryptr = entryptr + next_offset;
		dir_info = (FILE_DIRECTORY_INFO *)entryptr;

5217 5218 5219 5220 5221 5222 5223
		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 ||
5224 5225
		    entryptr + len > end_of_buf ||
		    entryptr + len + size > end_of_buf) {
5226 5227
			cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
				 end_of_buf);
5228 5229 5230
			break;
		}

5231
		*lastentry = entryptr;
5232 5233
		entrycount++;

5234
		next_offset = le32_to_cpu(dir_info->NextEntryOffset);
5235 5236 5237 5238 5239 5240 5241 5242 5243 5244
		if (!next_offset)
			break;
	}

	return entrycount;
}

/*
 * Readdir/FindFirst
 */
5245
int SMB2_query_directory_init(const unsigned int xid,
5246 5247 5248
			      struct cifs_tcon *tcon,
			      struct TCP_Server_Info *server,
			      struct smb_rqst *rqst,
5249 5250
			      u64 persistent_fid, u64 volatile_fid,
			      int index, int info_level)
5251 5252 5253 5254
{
	struct smb2_query_directory_req *req;
	unsigned char *bufptr;
	__le16 asteriks = cpu_to_le16('*');
5255 5256 5257
	unsigned int output_size = CIFSMaxBufSize -
		MAX_SMB2_CREATE_RESPONSE_SIZE -
		MAX_SMB2_CLOSE_RESPONSE_SIZE;
5258
	unsigned int total_len;
5259 5260
	struct kvec *iov = rqst->rq_iov;
	int len, rc;
5261

5262 5263
	rc = smb2_plain_req_init(SMB2_QUERY_DIRECTORY, tcon, server,
				 (void **) &req, &total_len);
5264 5265 5266
	if (rc)
		return rc;

5267
	switch (info_level) {
5268 5269 5270 5271 5272 5273
	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;
5274 5275 5276
	case SMB_FIND_FILE_POSIX_INFO:
		req->FileInformationClass = SMB_FIND_FILE_POSIX_INFO;
		break;
5277 5278 5279
	case SMB_FIND_FILE_FULL_DIRECTORY_INFO:
		req->FileInformationClass = FILE_FULL_DIRECTORY_INFORMATION;
		break;
5280
	default:
5281
		cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
5282 5283
			info_level);
		return -EINVAL;
5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294
	}

	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 =
5295
		cpu_to_le16(sizeof(struct smb2_query_directory_req));
5296 5297 5298 5299 5300 5301 5302 5303 5304 5305
	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;
5306 5307
	/* 1 for Buffer */
	iov[0].iov_len = total_len - 1;
5308 5309 5310 5311

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

5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324
	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 */
	}
}

5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339
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:
5340
		info_buf_size = sizeof(FILE_DIRECTORY_INFO);
5341 5342
		break;
	case SMB_FIND_FILE_ID_FULL_DIR_INFO:
5343
		info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO);
5344
		break;
5345 5346 5347 5348
	case SMB_FIND_FILE_POSIX_INFO:
		/* note that posix payload are variable size */
		info_buf_size = sizeof(struct smb2_posix_info);
		break;
5349 5350 5351
	case SMB_FIND_FILE_FULL_DIRECTORY_INFO:
		info_buf_size = sizeof(FILE_FULL_DIRECTORY_INFO);
		break;
5352 5353 5354 5355 5356 5357 5358 5359 5360
	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);
5361 5362
	if (rc) {
		cifs_tcon_dbg(VFS, "bad info payload");
5363
		return rc;
5364
	}
5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377

	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;
5378 5379 5380 5381 5382 5383 5384 5385

	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);

5386 5387 5388 5389 5390 5391 5392 5393 5394
	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
5395
		cifs_tcon_dbg(VFS, "Invalid search buffer type\n");
5396 5397 5398 5399

	return 0;
}

5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411
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;
5412
	struct TCP_Server_Info *server;
5413
	int flags = 0;
5414 5415 5416 5417 5418 5419
	int retries = 0, cur_sleep = 1;

replay_again:
	/* reinitialize for possible replay */
	flags = 0;
	server = cifs_pick_channel(ses);
5420

5421
	if (!ses || !(ses->server))
5422 5423 5424 5425 5426
		return -EIO;

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

5427
	memset(&rqst, 0, sizeof(struct smb_rqst));
5428
	memset(&iov, 0, sizeof(iov));
5429
	rqst.rq_iov = iov;
5430
	rqst.rq_nvec = SMB2_QUERY_DIRECTORY_IOV_SIZE;
5431

5432 5433
	rc = SMB2_query_directory_init(xid, tcon, server,
				       &rqst, persistent_fid,
5434 5435 5436 5437
				       volatile_fid, index,
				       srch_inf->info_level);
	if (rc)
		goto qdir_exit;
5438

5439 5440 5441
	if (retries)
		smb2_set_replay(server, &rqst);

5442 5443
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
5444
	rsp = (struct smb2_query_directory_rsp *)rsp_iov.iov_base;
5445

5446
	if (rc) {
5447
		if (rc == -ENODATA &&
5448
		    rsp->hdr.Status == STATUS_NO_MORE_FILES) {
5449 5450
			trace_smb3_query_dir_done(xid, persistent_fid,
				tcon->tid, tcon->ses->Suid, index, 0);
5451 5452
			srch_inf->endOfSearch = true;
			rc = 0;
5453 5454 5455
		} else {
			trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
				tcon->ses->Suid, index, 0, rc);
5456
			cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE);
5457
		}
5458 5459 5460
		goto qdir_exit;
	}

5461 5462
	rc = smb2_parse_query_directory(tcon, &rsp_iov,	resp_buftype,
					srch_inf);
5463 5464 5465
	if (rc) {
		trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
			tcon->ses->Suid, index, 0, rc);
5466
		goto qdir_exit;
5467
	}
5468 5469
	resp_buftype = CIFS_NO_BUFFER;

5470 5471
	trace_smb3_query_dir_done(xid, persistent_fid, tcon->tid,
			tcon->ses->Suid, index, srch_inf->entries_in_buffer);
5472 5473

qdir_exit:
5474
	SMB2_query_directory_free(&rqst);
5475
	free_rsp_buf(resp_buftype, rsp);
5476 5477 5478 5479 5480

	if (is_replayable_error(rc) &&
	    smb2_should_replay(tcon, &retries, &cur_sleep))
		goto replay_again;

5481 5482 5483
	return rc;
}

5484
int
5485 5486 5487 5488 5489
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)
5490 5491
{
	struct smb2_set_info_req *req;
5492 5493 5494
	struct kvec *iov = rqst->rq_iov;
	unsigned int i, total_len;
	int rc;
5495

5496 5497
	rc = smb2_plain_req_init(SMB2_SET_INFO, tcon, server,
				 (void **) &req, &total_len);
5498
	if (rc)
5499
		return rc;
5500

5501
	req->hdr.Id.SyncId.ProcessId = cpu_to_le32(pid);
5502
	req->InfoType = info_type;
5503 5504 5505
	req->FileInfoClass = info_class;
	req->PersistentFileId = persistent_fid;
	req->VolatileFileId = volatile_fid;
5506
	req->AdditionalInformation = cpu_to_le32(additional_info);
5507

5508
	req->BufferOffset = cpu_to_le16(sizeof(struct smb2_set_info_req));
5509 5510 5511
	req->BufferLength = cpu_to_le32(*size);

	memcpy(req->Buffer, *data, *size);
5512
	total_len += *size;
5513 5514

	iov[0].iov_base = (char *)req;
5515 5516
	/* 1 for Buffer */
	iov[0].iov_len = total_len - 1;
5517

5518
	for (i = 1; i < rqst->rq_nvec; i++) {
5519 5520 5521 5522 5523
		le32_add_cpu(&req->BufferLength, size[i]);
		iov[i].iov_base = (char *)data[i];
		iov[i].iov_len = size[i];
	}

5524 5525 5526 5527 5528 5529
	return 0;
}

void
SMB2_set_info_free(struct smb_rqst *rqst)
{
5530 5531
	if (rqst && rqst->rq_iov)
		cifs_buf_release(rqst->rq_iov[0].iov_base); /* request */
5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546
}

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;
5547
	struct TCP_Server_Info *server;
5548
	int flags = 0;
5549 5550 5551 5552 5553 5554
	int retries = 0, cur_sleep = 1;

replay_again:
	/* reinitialize for possible replay */
	flags = 0;
	server = cifs_pick_channel(ses);
5555

5556
	if (!ses || !server)
5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568
		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;

5569 5570 5571 5572
	memset(&rqst, 0, sizeof(struct smb_rqst));
	rqst.rq_iov = iov;
	rqst.rq_nvec = num;

5573 5574
	rc = SMB2_set_info_init(tcon, server,
				&rqst, persistent_fid, volatile_fid, pid,
5575 5576 5577 5578 5579 5580 5581
				info_class, info_type, additional_info,
				data, size);
	if (rc) {
		kfree(iov);
		return rc;
	}

5582 5583
	if (retries)
		smb2_set_replay(server, &rqst);
5584

5585 5586
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags,
5587
			    &rsp_iov);
5588
	SMB2_set_info_free(&rqst);
5589
	rsp = (struct smb2_set_info_rsp *)rsp_iov.iov_base;
5590

5591
	if (rc != 0) {
5592
		cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE);
5593 5594 5595
		trace_smb3_set_info_err(xid, persistent_fid, tcon->tid,
				ses->Suid, info_class, (__u32)info_type, rc);
	}
5596

5597 5598
	free_rsp_buf(resp_buftype, rsp);
	kfree(iov);
5599 5600 5601 5602 5603

	if (is_replayable_error(rc) &&
	    smb2_should_replay(tcon, &retries, &cur_sleep))
		goto replay_again;

5604 5605 5606
	return rc;
}

5607 5608
int
SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
5609
	     u64 volatile_fid, u32 pid, loff_t new_eof)
5610 5611 5612 5613 5614
{
	struct smb2_file_eof_info info;
	void *data;
	unsigned int size;

5615
	info.EndOfFile = cpu_to_le64(new_eof);
5616 5617 5618 5619

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

5620
	trace_smb3_set_eof(xid, persistent_fid, tcon->tid, tcon->ses->Suid, new_eof);
5621

5622
	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5623 5624
			pid, FILE_END_OF_FILE_INFORMATION, SMB2_O_INFO_FILE,
			0, 1, &data, &size);
5625
}
5626

5627 5628 5629 5630 5631 5632 5633 5634
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);
5635
}
5636

5637 5638 5639 5640 5641 5642 5643 5644 5645 5646
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);
}

5647 5648 5649 5650 5651
int
SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon,
		  const u64 persistent_fid, const u64 volatile_fid,
		  __u8 oplock_level)
{
5652
	struct smb_rqst rqst;
5653
	int rc;
5654
	struct smb2_oplock_break *req = NULL;
5655
	struct cifs_ses *ses = tcon->ses;
5656
	struct TCP_Server_Info *server;
5657
	int flags = CIFS_OBREAK_OP;
5658 5659 5660 5661
	unsigned int total_len;
	struct kvec iov[1];
	struct kvec rsp_iov;
	int resp_buf_type;
5662 5663 5664 5665 5666 5667
	int retries = 0, cur_sleep = 1;

replay_again:
	/* reinitialize for possible replay */
	flags = CIFS_OBREAK_OP;
	server = cifs_pick_channel(ses);
5668

5669
	cifs_dbg(FYI, "SMB2_oplock_break\n");
5670 5671
	rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
				 (void **) &req, &total_len);
5672 5673 5674
	if (rc)
		return rc;

5675
	if (smb3_encryption_required(tcon))
5676 5677
		flags |= CIFS_TRANSFORM_REQ;

5678 5679 5680
	req->VolatileFid = volatile_fid;
	req->PersistentFid = persistent_fid;
	req->OplockLevel = oplock_level;
5681
	req->hdr.CreditRequest = cpu_to_le16(1);
5682

5683
	flags |= CIFS_NO_RSP_BUF;
5684 5685 5686 5687

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

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

5692 5693 5694
	if (retries)
		smb2_set_replay(server, &rqst);

5695 5696
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buf_type, flags, &rsp_iov);
5697
	cifs_small_buf_release(req);
5698 5699
	if (rc) {
		cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
5700
		cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc);
5701 5702
	}

5703 5704 5705 5706
	if (is_replayable_error(rc) &&
	    smb2_should_replay(tcon, &retries, &cur_sleep))
		goto replay_again;

5707 5708
	return rc;
}
5709

5710 5711 5712
void
smb2_copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf,
			     struct kstatfs *kst)
5713 5714 5715 5716
{
	kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) *
			  le32_to_cpu(pfs_inf->SectorsPerAllocationUnit);
	kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits);
5717 5718
	kst->f_bfree  = kst->f_bavail =
			le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits);
5719 5720 5721
	return;
}

5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740
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;
}

5741
static int
5742 5743 5744 5745
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)
5746 5747 5748
{
	int rc;
	struct smb2_query_info_req *req;
5749
	unsigned int total_len;
5750

5751
	cifs_dbg(FYI, "Query FSInfo level %d\n", level);
5752

5753
	if ((tcon->ses == NULL) || server == NULL)
5754 5755
		return -EIO;

5756 5757
	rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
				 (void **) &req, &total_len);
5758 5759 5760 5761 5762 5763 5764
	if (rc)
		return rc;

	req->InfoType = SMB2_O_INFO_FILESYSTEM;
	req->FileInfoClass = level;
	req->PersistentFileId = persistent_fid;
	req->VolatileFileId = volatile_fid;
5765
	/* 1 for pad */
5766
	req->InputBufferOffset =
5767
			cpu_to_le16(sizeof(struct smb2_query_info_req));
5768
	req->OutputBufferLength = cpu_to_le32(
5769
		outbuf_len + sizeof(struct smb2_query_info_rsp));
5770 5771

	iov->iov_base = (char *)req;
5772
	iov->iov_len = total_len;
5773 5774 5775
	return 0;
}

5776 5777 5778 5779 5780
static inline void free_qfs_info_req(struct kvec *iov)
{
	cifs_buf_release(iov->iov_base);
}

5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791
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;
5792
	struct TCP_Server_Info *server;
5793 5794
	FILE_SYSTEM_POSIX_INFO *info = NULL;
	int flags = 0;
5795 5796 5797 5798 5799 5800
	int retries = 0, cur_sleep = 1;

replay_again:
	/* reinitialize for possible replay */
	flags = 0;
	server = cifs_pick_channel(ses);
5801

5802 5803
	rc = build_qfs_info_req(&iov, tcon, server,
				FS_POSIX_INFORMATION,
5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815
				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;

5816 5817 5818
	if (retries)
		smb2_set_replay(server, &rqst);

5819 5820
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
5821
	free_qfs_info_req(&iov);
5822 5823 5824 5825 5826 5827 5828 5829
	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);
5830 5831 5832
	rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
			       le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
			       sizeof(FILE_SYSTEM_POSIX_INFO));
5833 5834 5835 5836 5837
	if (!rc)
		copy_posix_fs_info_to_kstatfs(info, fsdata);

posix_qfsinf_exit:
	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5838 5839 5840 5841 5842

	if (is_replayable_error(rc) &&
	    smb2_should_replay(tcon, &retries, &cur_sleep))
		goto replay_again;

5843 5844 5845
	return rc;
}

5846 5847 5848 5849
int
SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon,
	      u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
{
5850
	struct smb_rqst rqst;
5851 5852
	struct smb2_query_info_rsp *rsp = NULL;
	struct kvec iov;
5853
	struct kvec rsp_iov;
5854 5855 5856
	int rc = 0;
	int resp_buftype;
	struct cifs_ses *ses = tcon->ses;
5857
	struct TCP_Server_Info *server;
5858
	struct smb2_fs_full_size_info *info = NULL;
5859
	int flags = 0;
5860 5861 5862 5863 5864 5865
	int retries = 0, cur_sleep = 1;

replay_again:
	/* reinitialize for possible replay */
	flags = 0;
	server = cifs_pick_channel(ses);
5866

5867 5868
	rc = build_qfs_info_req(&iov, tcon, server,
				FS_FULL_SIZE_INFORMATION,
5869 5870 5871 5872 5873
				sizeof(struct smb2_fs_full_size_info),
				persistent_fid, volatile_fid);
	if (rc)
		return rc;

5874
	if (smb3_encryption_required(tcon))
5875 5876
		flags |= CIFS_TRANSFORM_REQ;

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

5881 5882 5883
	if (retries)
		smb2_set_replay(server, &rqst);

5884 5885
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
5886
	free_qfs_info_req(&iov);
5887 5888
	if (rc) {
		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5889
		goto qfsinf_exit;
5890
	}
5891
	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5892

5893
	info = (struct smb2_fs_full_size_info *)(
5894
		le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
5895 5896 5897
	rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
			       le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
			       sizeof(struct smb2_fs_full_size_info));
5898
	if (!rc)
5899
		smb2_copy_fs_info_to_kstatfs(info, fsdata);
5900

5901
qfsinf_exit:
5902
	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5903 5904 5905 5906 5907

	if (is_replayable_error(rc) &&
	    smb2_should_replay(tcon, &retries, &cur_sleep))
		goto replay_again;

5908 5909 5910 5911 5912
	return rc;
}

int
SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon,
5913
	      u64 persistent_fid, u64 volatile_fid, int level)
5914
{
5915
	struct smb_rqst rqst;
5916 5917
	struct smb2_query_info_rsp *rsp = NULL;
	struct kvec iov;
5918
	struct kvec rsp_iov;
5919
	int rc = 0;
5920
	int resp_buftype, max_len, min_len;
5921
	struct cifs_ses *ses = tcon->ses;
5922
	struct TCP_Server_Info *server;
5923
	unsigned int rsp_len, offset;
5924
	int flags = 0;
5925 5926 5927 5928 5929 5930
	int retries = 0, cur_sleep = 1;

replay_again:
	/* reinitialize for possible replay */
	flags = 0;
	server = cifs_pick_channel(ses);
5931

5932 5933 5934 5935 5936 5937
	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
5938 5939 5940
	} else if (level == FS_SECTOR_SIZE_INFORMATION) {
		max_len = sizeof(struct smb3_fs_ss_info);
		min_len = sizeof(struct smb3_fs_ss_info);
5941 5942 5943
	} 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);
5944
	} else {
Steven French's avatar
Steven French committed
5945
		cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level);
5946 5947 5948
		return -EINVAL;
	}

5949 5950
	rc = build_qfs_info_req(&iov, tcon, server,
				level, max_len,
5951 5952 5953 5954
				persistent_fid, volatile_fid);
	if (rc)
		return rc;

5955
	if (smb3_encryption_required(tcon))
5956 5957
		flags |= CIFS_TRANSFORM_REQ;

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

5962 5963 5964
	if (retries)
		smb2_set_replay(server, &rqst);

5965 5966
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buftype, flags, &rsp_iov);
5967
	free_qfs_info_req(&iov);
5968 5969 5970 5971
	if (rc) {
		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
		goto qfsattr_exit;
	}
5972
	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5973 5974 5975

	rsp_len = le32_to_cpu(rsp->OutputBufferLength);
	offset = le16_to_cpu(rsp->OutputBufferOffset);
5976
	rc = smb2_validate_iov(offset, rsp_len, &rsp_iov, min_len);
5977 5978 5979 5980
	if (rc)
		goto qfsattr_exit;

	if (level == FS_ATTRIBUTE_INFORMATION)
5981
		memcpy(&tcon->fsAttrInfo, offset
5982
			+ (char *)rsp, min_t(unsigned int,
5983 5984
			rsp_len, max_len));
	else if (level == FS_DEVICE_INFORMATION)
5985
		memcpy(&tcon->fsDevInfo, offset
5986
			+ (char *)rsp, sizeof(FILE_SYSTEM_DEVICE_INFO));
Steven French's avatar
Steven French committed
5987 5988
	else if (level == FS_SECTOR_SIZE_INFORMATION) {
		struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *)
5989
			(offset + (char *)rsp);
Steven French's avatar
Steven French committed
5990 5991 5992
		tcon->ss_flags = le32_to_cpu(ss_info->Flags);
		tcon->perf_sector_size =
			le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf);
5993 5994 5995 5996 5997
	} 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
5998
	}
5999 6000

qfsattr_exit:
6001
	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
6002 6003 6004 6005 6006

	if (is_replayable_error(rc) &&
	    smb2_should_replay(tcon, &retries, &cur_sleep))
		goto replay_again;

6007 6008
	return rc;
}
6009 6010 6011 6012 6013 6014

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)
{
6015
	struct smb_rqst rqst;
6016 6017 6018
	int rc = 0;
	struct smb2_lock_req *req = NULL;
	struct kvec iov[2];
6019
	struct kvec rsp_iov;
6020 6021
	int resp_buf_type;
	unsigned int count;
6022
	int flags = CIFS_NO_RSP_BUF;
6023
	unsigned int total_len;
6024 6025 6026 6027 6028 6029 6030
	struct TCP_Server_Info *server;
	int retries = 0, cur_sleep = 1;

replay_again:
	/* reinitialize for possible replay */
	flags = CIFS_NO_RSP_BUF;
	server = cifs_pick_channel(tcon->ses);
6031

6032
	cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock);
6033

6034 6035
	rc = smb2_plain_req_init(SMB2_LOCK, tcon, server,
				 (void **) &req, &total_len);
6036 6037 6038
	if (rc)
		return rc;

6039
	if (smb3_encryption_required(tcon))
6040 6041
		flags |= CIFS_TRANSFORM_REQ;

6042
	req->hdr.Id.SyncId.ProcessId = cpu_to_le32(pid);
6043 6044 6045 6046 6047 6048 6049 6050
	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;
6051
	iov[0].iov_len = total_len - sizeof(struct smb2_lock_element);
6052 6053 6054 6055
	iov[1].iov_base = (char *)buf;
	iov[1].iov_len = count;

	cifs_stats_inc(&tcon->stats.cifs_stats.num_locks);
6056 6057 6058 6059 6060

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

6061 6062 6063
	if (retries)
		smb2_set_replay(server, &rqst);

6064 6065
	rc = cifs_send_recv(xid, tcon->ses, server,
			    &rqst, &resp_buf_type, flags,
6066
			    &rsp_iov);
6067
	cifs_small_buf_release(req);
6068
	if (rc) {
6069
		cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc);
6070
		cifs_stats_fail_inc(tcon, SMB2_LOCK_HE);
6071 6072
		trace_smb3_lock_err(xid, persist_fid, tcon->tid,
				    tcon->ses->Suid, rc);
6073 6074
	}

6075 6076 6077 6078
	if (is_replayable_error(rc) &&
	    smb2_should_replay(tcon, &retries, &cur_sleep))
		goto replay_again;

6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097
	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);
}
6098 6099 6100 6101 6102

int
SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon,
		 __u8 *lease_key, const __le32 lease_state)
{
6103
	struct smb_rqst rqst;
6104 6105
	int rc;
	struct smb2_lease_ack *req = NULL;
6106
	struct cifs_ses *ses = tcon->ses;
6107
	int flags = CIFS_OBREAK_OP;
6108 6109 6110 6111
	unsigned int total_len;
	struct kvec iov[1];
	struct kvec rsp_iov;
	int resp_buf_type;
6112 6113
	__u64 *please_key_high;
	__u64 *please_key_low;
6114
	struct TCP_Server_Info *server = cifs_pick_channel(tcon->ses);
6115

6116
	cifs_dbg(FYI, "SMB2_lease_break\n");
6117 6118
	rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
				 (void **) &req, &total_len);
6119 6120 6121
	if (rc)
		return rc;

6122
	if (smb3_encryption_required(tcon))
6123 6124
		flags |= CIFS_TRANSFORM_REQ;

6125
	req->hdr.CreditRequest = cpu_to_le16(1);
6126
	req->StructureSize = cpu_to_le16(36);
6127
	total_len += 12;
6128 6129 6130 6131

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

6132
	flags |= CIFS_NO_RSP_BUF;
6133 6134 6135 6136

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

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

6141 6142
	rc = cifs_send_recv(xid, ses, server,
			    &rqst, &resp_buf_type, flags, &rsp_iov);
6143
	cifs_small_buf_release(req);
6144

6145 6146
	please_key_low = (__u64 *)lease_key;
	please_key_high = (__u64 *)(lease_key+8);
6147 6148
	if (rc) {
		cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
6149 6150
		trace_smb3_lease_err(le32_to_cpu(lease_state), tcon->tid,
			ses->Suid, *please_key_low, *please_key_high, rc);
6151
		cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc);
6152 6153 6154
	} else
		trace_smb3_lease_done(le32_to_cpu(lease_state), tcon->tid,
			ses->Suid, *please_key_low, *please_key_high);
6155 6156 6157

	return rc;
}