File Index
Files and directories
Sign in
FILE

smb2ops.c

File preview with syntax highlighting.

linux-6.19.14/fs/smb/client/smb2ops.c C
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 *  SMB2 version specific operations
   4 *
   5 *  Copyright (c) 2012, Jeff Layton <jlayton@redhat.com>
   6 */
   7
   8#include <linux/pagemap.h>
   9#include <linux/vfs.h>
  10#include <linux/falloc.h>
  11#include <linux/scatterlist.h>
  12#include <linux/uuid.h>
  13#include <linux/sort.h>
  14#include <crypto/aead.h>
  15#include <linux/fiemap.h>
  16#include <linux/folio_queue.h>
  17#include <uapi/linux/magic.h>
  18#include "cifsfs.h"
  19#include "cifsglob.h"
  20#include "cifsproto.h"
  21#include "smb2proto.h"
  22#include "smb2pdu.h"
  23#include "cifs_debug.h"
  24#include "cifs_unicode.h"
  25#include "../common/smb2status.h"
  26#include "smb2glob.h"
  27#include "cifs_ioctl.h"
  28#include "smbdirect.h"
  29#include "fscache.h"
  30#include "fs_context.h"
  31#include "cached_dir.h"
  32#include "reparse.h"
  33
  34/* Change credits for different ops and return the total number of credits */
  35static int
  36change_conf(struct TCP_Server_Info *server)
  37{
  38	server->credits += server->echo_credits + server->oplock_credits;
  39	if (server->credits > server->max_credits)
  40		server->credits = server->max_credits;
  41	server->oplock_credits = server->echo_credits = 0;
  42	switch (server->credits) {
  43	case 0:
  44		return 0;
  45	case 1:
  46		server->echoes = false;
  47		server->oplocks = false;
  48		break;
  49	case 2:
  50		server->echoes = true;
  51		server->oplocks = false;
  52		server->echo_credits = 1;
  53		break;
  54	default:
  55		server->echoes = true;
  56		if (enable_oplocks) {
  57			server->oplocks = true;
  58			server->oplock_credits = 1;
  59		} else
  60			server->oplocks = false;
  61
  62		server->echo_credits = 1;
  63	}
  64	server->credits -= server->echo_credits + server->oplock_credits;
  65	return server->credits + server->echo_credits + server->oplock_credits;
  66}
  67
  68static void
  69smb2_add_credits(struct TCP_Server_Info *server,
  70		 struct cifs_credits *credits, const int optype)
  71{
  72	int *val, rc = -1;
  73	int scredits, in_flight;
  74	unsigned int add = credits->value;
  75	unsigned int instance = credits->instance;
  76	bool reconnect_detected = false;
  77	bool reconnect_with_invalid_credits = false;
  78
  79	spin_lock(&server->req_lock);
  80	val = server->ops->get_credits_field(server, optype);
  81
  82	/* eg found case where write overlapping reconnect messed up credits */
  83	if (((optype & CIFS_OP_MASK) == CIFS_NEG_OP) && (*val != 0))
  84		reconnect_with_invalid_credits = true;
  85
  86	if ((instance == 0) || (instance == server->reconnect_instance))
  87		*val += add;
  88	else
  89		reconnect_detected = true;
  90
  91	if (*val > 65000) {
  92		*val = 65000; /* Don't get near 64K credits, avoid srv bugs */
  93		pr_warn_once("server overflowed SMB3 credits\n");
  94		trace_smb3_overflow_credits(server->current_mid,
  95					    server->conn_id, server->hostname, *val,
  96					    add, server->in_flight);
  97	}
  98	if (credits->in_flight_check > 1) {
  99		pr_warn_once("rreq R=%08x[%x] Credits not in flight\n",
 100			     credits->rreq_debug_id, credits->rreq_debug_index);
 101	} else {
 102		credits->in_flight_check = 2;
 103	}
 104	if (WARN_ON_ONCE(server->in_flight == 0)) {
 105		pr_warn_once("rreq R=%08x[%x] Zero in_flight\n",
 106			     credits->rreq_debug_id, credits->rreq_debug_index);
 107		trace_smb3_rw_credits(credits->rreq_debug_id,
 108				      credits->rreq_debug_index,
 109				      credits->value,
 110				      server->credits, server->in_flight, 0,
 111				      cifs_trace_rw_credits_zero_in_flight);
 112	}
 113	server->in_flight--;
 114	if (server->in_flight == 0 &&
 115	   ((optype & CIFS_OP_MASK) != CIFS_NEG_OP) &&
 116	   ((optype & CIFS_OP_MASK) != CIFS_SESS_OP))
 117		rc = change_conf(server);
 118	/*
 119	 * Sometimes server returns 0 credits on oplock break ack - we need to
 120	 * rebalance credits in this case.
 121	 */
 122	else if (server->in_flight > 0 && server->oplock_credits == 0 &&
 123		 server->oplocks) {
 124		if (server->credits > 1) {
 125			server->credits--;
 126			server->oplock_credits++;
 127		}
 128	} else if ((server->in_flight > 0) && (server->oplock_credits > 3) &&
 129		   ((optype & CIFS_OP_MASK) == CIFS_OBREAK_OP))
 130		/* if now have too many oplock credits, rebalance so don't starve normal ops */
 131		change_conf(server);
 132
 133	scredits = *val;
 134	in_flight = server->in_flight;
 135	spin_unlock(&server->req_lock);
 136	wake_up(&server->request_q);
 137
 138	if (reconnect_detected) {
 139		trace_smb3_reconnect_detected(server->current_mid,
 140			server->conn_id, server->hostname, scredits, add, in_flight);
 141
 142		cifs_dbg(FYI, "trying to put %d credits from the old server instance %d\n",
 143			 add, instance);
 144	}
 145
 146	if (reconnect_with_invalid_credits) {
 147		trace_smb3_reconnect_with_invalid_credits(server->current_mid,
 148			server->conn_id, server->hostname, scredits, add, in_flight);
 149		cifs_dbg(FYI, "Negotiate operation when server credits is non-zero. Optype: %d, server credits: %d, credits added: %d\n",
 150			 optype, scredits, add);
 151	}
 152
 153	spin_lock(&server->srv_lock);
 154	if (server->tcpStatus == CifsNeedReconnect
 155	    || server->tcpStatus == CifsExiting) {
 156		spin_unlock(&server->srv_lock);
 157		return;
 158	}
 159	spin_unlock(&server->srv_lock);
 160
 161	switch (rc) {
 162	case -1:
 163		/* change_conf hasn't been executed */
 164		break;
 165	case 0:
 166		cifs_server_dbg(VFS, "Possible client or server bug - zero credits\n");
 167		break;
 168	case 1:
 169		cifs_server_dbg(VFS, "disabling echoes and oplocks\n");
 170		break;
 171	case 2:
 172		cifs_dbg(FYI, "disabling oplocks\n");
 173		break;
 174	default:
 175		/* change_conf rebalanced credits for different types */
 176		break;
 177	}
 178
 179	trace_smb3_add_credits(server->current_mid,
 180			server->conn_id, server->hostname, scredits, add, in_flight);
 181	cifs_dbg(FYI, "%s: added %u credits total=%d\n", __func__, add, scredits);
 182}
 183
 184static void
 185smb2_set_credits(struct TCP_Server_Info *server, const int val)
 186{
 187	int scredits, in_flight;
 188
 189	spin_lock(&server->req_lock);
 190	server->credits = val;
 191	if (val == 1) {
 192		server->reconnect_instance++;
 193		/*
 194		 * ChannelSequence updated for all channels in primary channel so that consistent
 195		 * across SMB3 requests sent on any channel. See MS-SMB2 3.2.4.1 and 3.2.7.1
 196		 */
 197		if (SERVER_IS_CHAN(server))
 198			server->primary_server->channel_sequence_num++;
 199		else
 200			server->channel_sequence_num++;
 201	}
 202	scredits = server->credits;
 203	in_flight = server->in_flight;
 204	spin_unlock(&server->req_lock);
 205
 206	trace_smb3_set_credits(server->current_mid,
 207			server->conn_id, server->hostname, scredits, val, in_flight);
 208	cifs_dbg(FYI, "%s: set %u credits\n", __func__, val);
 209
 210	/* don't log while holding the lock */
 211	if (val == 1)
 212		cifs_dbg(FYI, "set credits to 1 due to smb2 reconnect\n");
 213}
 214
 215static int *
 216smb2_get_credits_field(struct TCP_Server_Info *server, const int optype)
 217{
 218	switch (optype) {
 219	case CIFS_ECHO_OP:
 220		return &server->echo_credits;
 221	case CIFS_OBREAK_OP:
 222		return &server->oplock_credits;
 223	default:
 224		return &server->credits;
 225	}
 226}
 227
 228static unsigned int
 229smb2_get_credits(struct mid_q_entry *mid)
 230{
 231	return mid->credits_received;
 232}
 233
 234static int
 235smb2_wait_mtu_credits(struct TCP_Server_Info *server, size_t size,
 236		      size_t *num, struct cifs_credits *credits)
 237{
 238	int rc = 0;
 239	unsigned int scredits, in_flight;
 240
 241	spin_lock(&server->req_lock);
 242	while (1) {
 243		spin_unlock(&server->req_lock);
 244
 245		spin_lock(&server->srv_lock);
 246		if (server->tcpStatus == CifsExiting) {
 247			spin_unlock(&server->srv_lock);
 248			return -ENOENT;
 249		}
 250		spin_unlock(&server->srv_lock);
 251
 252		spin_lock(&server->req_lock);
 253		if (server->credits <= 0) {
 254			spin_unlock(&server->req_lock);
 255			cifs_num_waiters_inc(server);
 256			rc = wait_event_killable(server->request_q,
 257				has_credits(server, &server->credits, 1));
 258			cifs_num_waiters_dec(server);
 259			if (rc)
 260				return rc;
 261			spin_lock(&server->req_lock);
 262		} else {
 263			scredits = server->credits;
 264			/* can deadlock with reopen */
 265			if (scredits <= 8) {
 266				*num = SMB2_MAX_BUFFER_SIZE;
 267				credits->value = 0;
 268				credits->instance = 0;
 269				break;
 270			}
 271
 272			/* leave some credits for reopen and other ops */
 273			scredits -= 8;
 274			*num = min_t(unsigned int, size,
 275				     scredits * SMB2_MAX_BUFFER_SIZE);
 276
 277			credits->value =
 278				DIV_ROUND_UP(*num, SMB2_MAX_BUFFER_SIZE);
 279			credits->instance = server->reconnect_instance;
 280			server->credits -= credits->value;
 281			server->in_flight++;
 282			if (server->in_flight > server->max_in_flight)
 283				server->max_in_flight = server->in_flight;
 284			break;
 285		}
 286	}
 287	scredits = server->credits;
 288	in_flight = server->in_flight;
 289	spin_unlock(&server->req_lock);
 290
 291	trace_smb3_wait_credits(server->current_mid,
 292			server->conn_id, server->hostname, scredits, -(credits->value), in_flight);
 293	cifs_dbg(FYI, "%s: removed %u credits total=%d\n",
 294			__func__, credits->value, scredits);
 295
 296	return rc;
 297}
 298
 299static int
 300smb2_adjust_credits(struct TCP_Server_Info *server,
 301		    struct cifs_io_subrequest *subreq,
 302		    unsigned int /*enum smb3_rw_credits_trace*/ trace)
 303{
 304	struct cifs_credits *credits = &subreq->credits;
 305	int new_val = DIV_ROUND_UP(subreq->subreq.len - subreq->subreq.transferred,
 306				   SMB2_MAX_BUFFER_SIZE);
 307	int scredits, in_flight;
 308
 309	if (!credits->value || credits->value == new_val)
 310		return 0;
 311
 312	if (credits->value < new_val) {
 313		trace_smb3_rw_credits(subreq->rreq->debug_id,
 314				      subreq->subreq.debug_index,
 315				      credits->value,
 316				      server->credits, server->in_flight,
 317				      new_val - credits->value,
 318				      cifs_trace_rw_credits_no_adjust_up);
 319		trace_smb3_too_many_credits(server->current_mid,
 320				server->conn_id, server->hostname, 0, credits->value - new_val, 0);
 321		cifs_server_dbg(VFS, "R=%x[%x] request has less credits (%d) than required (%d)",
 322				subreq->rreq->debug_id, subreq->subreq.debug_index,
 323				credits->value, new_val);
 324
 325		return -EOPNOTSUPP;
 326	}
 327
 328	spin_lock(&server->req_lock);
 329
 330	if (server->reconnect_instance != credits->instance) {
 331		scredits = server->credits;
 332		in_flight = server->in_flight;
 333		spin_unlock(&server->req_lock);
 334
 335		trace_smb3_rw_credits(subreq->rreq->debug_id,
 336				      subreq->subreq.debug_index,
 337				      credits->value,
 338				      server->credits, server->in_flight,
 339				      new_val - credits->value,
 340				      cifs_trace_rw_credits_old_session);
 341		trace_smb3_reconnect_detected(server->current_mid,
 342			server->conn_id, server->hostname, scredits,
 343			credits->value - new_val, in_flight);
 344		cifs_server_dbg(VFS, "R=%x[%x] trying to return %d credits to old session\n",
 345				subreq->rreq->debug_id, subreq->subreq.debug_index,
 346				credits->value - new_val);
 347		return -EAGAIN;
 348	}
 349
 350	trace_smb3_rw_credits(subreq->rreq->debug_id,
 351			      subreq->subreq.debug_index,
 352			      credits->value,
 353			      server->credits, server->in_flight,
 354			      new_val - credits->value, trace);
 355	server->credits += credits->value - new_val;
 356	scredits = server->credits;
 357	in_flight = server->in_flight;
 358	spin_unlock(&server->req_lock);
 359	wake_up(&server->request_q);
 360
 361	trace_smb3_adj_credits(server->current_mid,
 362			server->conn_id, server->hostname, scredits,
 363			credits->value - new_val, in_flight);
 364	cifs_dbg(FYI, "%s: adjust added %u credits total=%d\n",
 365			__func__, credits->value - new_val, scredits);
 366
 367	credits->value = new_val;
 368
 369	return 0;
 370}
 371
 372static __u64
 373smb2_get_next_mid(struct TCP_Server_Info *server)
 374{
 375	__u64 mid;
 376	/* for SMB2 we need the current value */
 377	spin_lock(&server->mid_counter_lock);
 378	mid = server->current_mid++;
 379	spin_unlock(&server->mid_counter_lock);
 380	return mid;
 381}
 382
 383static void
 384smb2_revert_current_mid(struct TCP_Server_Info *server, const unsigned int val)
 385{
 386	spin_lock(&server->mid_counter_lock);
 387	if (server->current_mid >= val)
 388		server->current_mid -= val;
 389	spin_unlock(&server->mid_counter_lock);
 390}
 391
 392static struct mid_q_entry *
 393__smb2_find_mid(struct TCP_Server_Info *server, char *buf, bool dequeue)
 394{
 395	struct mid_q_entry *mid;
 396	struct smb2_hdr *shdr = (struct smb2_hdr *)buf;
 397	__u64 wire_mid = le64_to_cpu(shdr->MessageId);
 398
 399	if (shdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM) {
 400		cifs_server_dbg(VFS, "Encrypted frame parsing not supported yet\n");
 401		return NULL;
 402	}
 403
 404	spin_lock(&server->mid_queue_lock);
 405	list_for_each_entry(mid, &server->pending_mid_q, qhead) {
 406		if ((mid->mid == wire_mid) &&
 407		    (mid->mid_state == MID_REQUEST_SUBMITTED) &&
 408		    (mid->command == shdr->Command)) {
 409			smb_get_mid(mid);
 410			if (dequeue) {
 411				list_del_init(&mid->qhead);
 412				mid->deleted_from_q = true;
 413			}
 414			spin_unlock(&server->mid_queue_lock);
 415			return mid;
 416		}
 417	}
 418	spin_unlock(&server->mid_queue_lock);
 419	return NULL;
 420}
 421
 422static struct mid_q_entry *
 423smb2_find_mid(struct TCP_Server_Info *server, char *buf)
 424{
 425	return __smb2_find_mid(server, buf, false);
 426}
 427
 428static struct mid_q_entry *
 429smb2_find_dequeue_mid(struct TCP_Server_Info *server, char *buf)
 430{
 431	return __smb2_find_mid(server, buf, true);
 432}
 433
 434static void
 435smb2_dump_detail(void *buf, size_t buf_len, struct TCP_Server_Info *server)
 436{
 437#ifdef CONFIG_CIFS_DEBUG2
 438	struct smb2_hdr *shdr = (struct smb2_hdr *)buf;
 439
 440	cifs_server_dbg(VFS, "Cmd: %d Err: 0x%x Flags: 0x%x Mid: %llu Pid: %d\n",
 441		 shdr->Command, shdr->Status, shdr->Flags, shdr->MessageId,
 442		 shdr->Id.SyncId.ProcessId);
 443	if (!server->ops->check_message(buf, buf_len, server->total_read, server)) {
 444		cifs_server_dbg(VFS, "smb buf %p len %u\n", buf,
 445				server->ops->calc_smb_size(buf));
 446	}
 447#endif
 448}
 449
 450static bool
 451smb2_need_neg(struct TCP_Server_Info *server)
 452{
 453	return server->max_read == 0;
 454}
 455
 456static int
 457smb2_negotiate(const unsigned int xid,
 458	       struct cifs_ses *ses,
 459	       struct TCP_Server_Info *server)
 460{
 461	int rc;
 462
 463	spin_lock(&server->mid_counter_lock);
 464	server->current_mid = 0;
 465	spin_unlock(&server->mid_counter_lock);
 466	rc = SMB2_negotiate(xid, ses, server);
 467	return rc;
 468}
 469
 470static inline unsigned int
 471prevent_zero_iosize(unsigned int size, const char *type)
 472{
 473	if (size == 0) {
 474		cifs_dbg(VFS, "SMB: Zero %ssize calculated, using minimum value %u\n",
 475			 type, CIFS_MIN_DEFAULT_IOSIZE);
 476		return CIFS_MIN_DEFAULT_IOSIZE;
 477	}
 478	return size;
 479}
 480
 481static unsigned int
 482smb2_negotiate_wsize(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
 483{
 484	struct TCP_Server_Info *server = tcon->ses->server;
 485	unsigned int wsize;
 486
 487	/* start with specified wsize, or default */
 488	wsize = ctx->got_wsize ? ctx->vol_wsize : CIFS_DEFAULT_IOSIZE;
 489	wsize = min_t(unsigned int, wsize, server->max_write);
 490	if (!(server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
 491		wsize = min_t(unsigned int, wsize, SMB2_MAX_BUFFER_SIZE);
 492
 493	return prevent_zero_iosize(wsize, "w");
 494}
 495
 496static unsigned int
 497smb3_negotiate_wsize(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
 498{
 499	struct TCP_Server_Info *server = tcon->ses->server;
 500	unsigned int wsize;
 501
 502	/* start with specified wsize, or default */
 503	wsize = ctx->got_wsize ? ctx->vol_wsize : SMB3_DEFAULT_IOSIZE;
 504	wsize = min_t(unsigned int, wsize, server->max_write);
 505#ifdef CONFIG_CIFS_SMB_DIRECT
 506	if (server->rdma) {
 507		const struct smbdirect_socket_parameters *sp =
 508			smbd_get_parameters(server->smbd_conn);
 509
 510		if (server->sign)
 511			/*
 512			 * Account for SMB2 data transfer packet header and
 513			 * possible encryption header
 514			 */
 515			wsize = min_t(unsigned int,
 516				wsize,
 517				sp->max_fragmented_send_size -
 518					SMB2_READWRITE_PDU_HEADER_SIZE -
 519					sizeof(struct smb2_transform_hdr));
 520		else
 521			wsize = min_t(unsigned int,
 522				wsize, sp->max_read_write_size);
 523	}
 524#endif
 525	if (!(server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
 526		wsize = min_t(unsigned int, wsize, SMB2_MAX_BUFFER_SIZE);
 527
 528	return prevent_zero_iosize(wsize, "w");
 529}
 530
 531static unsigned int
 532smb2_negotiate_rsize(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
 533{
 534	struct TCP_Server_Info *server = tcon->ses->server;
 535	unsigned int rsize;
 536
 537	/* start with specified rsize, or default */
 538	rsize = ctx->got_rsize ? ctx->vol_rsize : CIFS_DEFAULT_IOSIZE;
 539	rsize = min_t(unsigned int, rsize, server->max_read);
 540
 541	if (!(server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
 542		rsize = min_t(unsigned int, rsize, SMB2_MAX_BUFFER_SIZE);
 543
 544	return prevent_zero_iosize(rsize, "r");
 545}
 546
 547static unsigned int
 548smb3_negotiate_rsize(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
 549{
 550	struct TCP_Server_Info *server = tcon->ses->server;
 551	unsigned int rsize;
 552
 553	/* start with specified rsize, or default */
 554	rsize = ctx->got_rsize ? ctx->vol_rsize : SMB3_DEFAULT_IOSIZE;
 555	rsize = min_t(unsigned int, rsize, server->max_read);
 556#ifdef CONFIG_CIFS_SMB_DIRECT
 557	if (server->rdma) {
 558		const struct smbdirect_socket_parameters *sp =
 559			smbd_get_parameters(server->smbd_conn);
 560
 561		if (server->sign)
 562			/*
 563			 * Account for SMB2 data transfer packet header and
 564			 * possible encryption header
 565			 */
 566			rsize = min_t(unsigned int,
 567				rsize,
 568				sp->max_fragmented_recv_size -
 569					SMB2_READWRITE_PDU_HEADER_SIZE -
 570					sizeof(struct smb2_transform_hdr));
 571		else
 572			rsize = min_t(unsigned int,
 573				rsize, sp->max_read_write_size);
 574	}
 575#endif
 576
 577	if (!(server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
 578		rsize = min_t(unsigned int, rsize, SMB2_MAX_BUFFER_SIZE);
 579
 580	return prevent_zero_iosize(rsize, "r");
 581}
 582
 583/*
 584 * compare two interfaces a and b
 585 * return 0 if everything matches.
 586 * return 1 if a is rdma capable, or rss capable, or has higher link speed
 587 * return -1 otherwise.
 588 */
 589static int
 590iface_cmp(struct cifs_server_iface *a, struct cifs_server_iface *b)
 591{
 592	int cmp_ret = 0;
 593
 594	WARN_ON(!a || !b);
 595	if (a->rdma_capable == b->rdma_capable) {
 596		if (a->rss_capable == b->rss_capable) {
 597			if (a->speed == b->speed) {
 598				cmp_ret = cifs_ipaddr_cmp((struct sockaddr *) &a->sockaddr,
 599							  (struct sockaddr *) &b->sockaddr);
 600				if (!cmp_ret)
 601					return 0;
 602				else if (cmp_ret > 0)
 603					return 1;
 604				else
 605					return -1;
 606			} else if (a->speed > b->speed)
 607				return 1;
 608			else
 609				return -1;
 610		} else if (a->rss_capable > b->rss_capable)
 611			return 1;
 612		else
 613			return -1;
 614	} else if (a->rdma_capable > b->rdma_capable)
 615		return 1;
 616	else
 617		return -1;
 618}
 619
 620static int
 621parse_server_interfaces(struct network_interface_info_ioctl_rsp *buf,
 622			size_t buf_len, struct cifs_ses *ses, bool in_mount)
 623{
 624	struct network_interface_info_ioctl_rsp *p;
 625	struct sockaddr_in *addr4;
 626	struct sockaddr_in6 *addr6;
 627	struct smb_sockaddr_in *p4;
 628	struct smb_sockaddr_in6 *p6;
 629	struct cifs_server_iface *info = NULL, *iface = NULL, *niface = NULL;
 630	struct cifs_server_iface tmp_iface;
 631	__be16 port;
 632	ssize_t bytes_left;
 633	size_t next = 0;
 634	int nb_iface = 0;
 635	int rc = 0, ret = 0;
 636
 637	bytes_left = buf_len;
 638	p = buf;
 639
 640	spin_lock(&ses->iface_lock);
 641
 642	/*
 643	 * Go through iface_list and mark them as inactive
 644	 */
 645	list_for_each_entry_safe(iface, niface, &ses->iface_list,
 646				 iface_head)
 647		iface->is_active = 0;
 648
 649	spin_unlock(&ses->iface_lock);
 650
 651	/*
 652	 * Samba server e.g. can return an empty interface list in some cases,
 653	 * which would only be a problem if we were requesting multichannel
 654	 */
 655	if (bytes_left == 0) {
 656		/* avoid spamming logs every 10 minutes, so log only in mount */
 657		if ((ses->chan_max > 1) && in_mount)
 658			cifs_dbg(VFS,
 659				 "multichannel not available\n"
 660				 "Empty network interface list returned by server %s\n",
 661				 ses->server->hostname);
 662		rc = -EOPNOTSUPP;
 663		goto out;
 664	}
 665
 666	spin_lock(&ses->server->srv_lock);
 667	if (ses->server->dstaddr.ss_family == AF_INET)
 668		port = ((struct sockaddr_in *)&ses->server->dstaddr)->sin_port;
 669	else if (ses->server->dstaddr.ss_family == AF_INET6)
 670		port = ((struct sockaddr_in6 *)&ses->server->dstaddr)->sin6_port;
 671	else
 672		port = cpu_to_be16(CIFS_PORT);
 673	spin_unlock(&ses->server->srv_lock);
 674
 675	while (bytes_left >= (ssize_t)sizeof(*p)) {
 676		memset(&tmp_iface, 0, sizeof(tmp_iface));
 677		/* default to 1Gbps when link speed is unset */
 678		tmp_iface.speed = le64_to_cpu(p->LinkSpeed) ?: 1000000000;
 679		tmp_iface.rdma_capable = le32_to_cpu(p->Capability & RDMA_CAPABLE) ? 1 : 0;
 680		tmp_iface.rss_capable = le32_to_cpu(p->Capability & RSS_CAPABLE) ? 1 : 0;
 681
 682		switch (p->Family) {
 683		/*
 684		 * The kernel and wire socket structures have the same
 685		 * layout and use network byte order but make the
 686		 * conversion explicit in case either one changes.
 687		 */
 688		case INTERNETWORK:
 689			addr4 = (struct sockaddr_in *)&tmp_iface.sockaddr;
 690			p4 = (struct smb_sockaddr_in *)p->Buffer;
 691			addr4->sin_family = AF_INET;
 692			memcpy(&addr4->sin_addr, &p4->IPv4Address, 4);
 693
 694			/* [MS-SMB2] 2.2.32.5.1.1 Clients MUST ignore these */
 695			addr4->sin_port = port;
 696
 697			cifs_dbg(FYI, "%s: ipv4 %pI4\n", __func__,
 698				 &addr4->sin_addr);
 699			break;
 700		case INTERNETWORKV6:
 701			addr6 =	(struct sockaddr_in6 *)&tmp_iface.sockaddr;
 702			p6 = (struct smb_sockaddr_in6 *)p->Buffer;
 703			addr6->sin6_family = AF_INET6;
 704			memcpy(&addr6->sin6_addr, &p6->IPv6Address, 16);
 705
 706			/* [MS-SMB2] 2.2.32.5.1.2 Clients MUST ignore these */
 707			addr6->sin6_flowinfo = 0;
 708			addr6->sin6_scope_id = 0;
 709			addr6->sin6_port = port;
 710
 711			cifs_dbg(FYI, "%s: ipv6 %pI6\n", __func__,
 712				 &addr6->sin6_addr);
 713			break;
 714		default:
 715			cifs_dbg(VFS,
 716				 "%s: skipping unsupported socket family\n",
 717				 __func__);
 718			goto next_iface;
 719		}
 720
 721		/*
 722		 * The iface_list is assumed to be sorted by speed.
 723		 * Check if the new interface exists in that list.
 724		 * NEVER change iface. it could be in use.
 725		 * Add a new one instead
 726		 */
 727		spin_lock(&ses->iface_lock);
 728		list_for_each_entry_safe(iface, niface, &ses->iface_list,
 729					 iface_head) {
 730			ret = iface_cmp(iface, &tmp_iface);
 731			if (!ret) {
 732				iface->is_active = 1;
 733				spin_unlock(&ses->iface_lock);
 734				goto next_iface;
 735			} else if (ret < 0) {
 736				/* all remaining ifaces are slower */
 737				kref_get(&iface->refcount);
 738				break;
 739			}
 740		}
 741		spin_unlock(&ses->iface_lock);
 742
 743		/* no match. insert the entry in the list */
 744		info = kmalloc(sizeof(struct cifs_server_iface),
 745			       GFP_KERNEL);
 746		if (!info) {
 747			rc = -ENOMEM;
 748			goto out;
 749		}
 750		memcpy(info, &tmp_iface, sizeof(tmp_iface));
 751
 752		/* add this new entry to the list */
 753		kref_init(&info->refcount);
 754		info->is_active = 1;
 755
 756		cifs_dbg(FYI, "%s: adding iface %zu\n", __func__, ses->iface_count);
 757		cifs_dbg(FYI, "%s: speed %zu bps\n", __func__, info->speed);
 758		cifs_dbg(FYI, "%s: capabilities 0x%08x\n", __func__,
 759			 le32_to_cpu(p->Capability));
 760
 761		spin_lock(&ses->iface_lock);
 762		if (!list_entry_is_head(iface, &ses->iface_list, iface_head)) {
 763			list_add_tail(&info->iface_head, &iface->iface_head);
 764			kref_put(&iface->refcount, release_iface);
 765		} else
 766			list_add_tail(&info->iface_head, &ses->iface_list);
 767
 768		ses->iface_count++;
 769		spin_unlock(&ses->iface_lock);
 770next_iface:
 771		nb_iface++;
 772		next = le32_to_cpu(p->Next);
 773		if (!next) {
 774			bytes_left -= sizeof(*p);
 775			break;
 776		}
 777		/* Validate that Next doesn't point beyond the buffer */
 778		if (next > bytes_left) {
 779			cifs_dbg(VFS, "%s: invalid Next pointer %zu > %zd\n",
 780				 __func__, next, bytes_left);
 781			rc = -EINVAL;
 782			goto out;
 783		}
 784		p = (struct network_interface_info_ioctl_rsp *)((u8 *)p+next);
 785		bytes_left -= next;
 786	}
 787
 788	if (!nb_iface) {
 789		cifs_dbg(VFS, "%s: malformed interface info\n", __func__);
 790		rc = -EINVAL;
 791		goto out;
 792	}
 793
 794	/* Azure rounds the buffer size up 8, to a 16 byte boundary */
 795	if ((bytes_left > 8) ||
 796	    (bytes_left >= offsetof(struct network_interface_info_ioctl_rsp, Next)
 797	     + sizeof(p->Next) && p->Next))
 798		cifs_dbg(VFS, "%s: incomplete interface info\n", __func__);
 799
 800out:
 801	/*
 802	 * Go through the list again and put the inactive entries
 803	 */
 804	spin_lock(&ses->iface_lock);
 805	list_for_each_entry_safe(iface, niface, &ses->iface_list,
 806				 iface_head) {
 807		if (!iface->is_active) {
 808			list_del(&iface->iface_head);
 809			kref_put(&iface->refcount, release_iface);
 810			ses->iface_count--;
 811		}
 812	}
 813	spin_unlock(&ses->iface_lock);
 814
 815	return rc;
 816}
 817
 818int
 819SMB3_request_interfaces(const unsigned int xid, struct cifs_tcon *tcon, bool in_mount)
 820{
 821	int rc;
 822	unsigned int ret_data_len = 0;
 823	struct network_interface_info_ioctl_rsp *out_buf = NULL;
 824	struct cifs_ses *ses = tcon->ses;
 825	struct TCP_Server_Info *pserver;
 826
 827	/* do not query too frequently */
 828	spin_lock(&ses->iface_lock);
 829	if (ses->iface_last_update &&
 830	    time_before(jiffies, ses->iface_last_update +
 831			(SMB_INTERFACE_POLL_INTERVAL * HZ))) {
 832		spin_unlock(&ses->iface_lock);
 833		return 0;
 834	}
 835
 836	ses->iface_last_update = jiffies;
 837
 838	spin_unlock(&ses->iface_lock);
 839
 840	rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
 841			FSCTL_QUERY_NETWORK_INTERFACE_INFO,
 842			NULL /* no data input */, 0 /* no data input */,
 843			CIFSMaxBufSize, (char **)&out_buf, &ret_data_len);
 844	if (rc == -EOPNOTSUPP) {
 845		cifs_dbg(FYI,
 846			 "server does not support query network interfaces\n");
 847		ret_data_len = 0;
 848	} else if (rc != 0) {
 849		cifs_tcon_dbg(VFS, "error %d on ioctl to get interface list\n", rc);
 850		goto out;
 851	}
 852
 853	rc = parse_server_interfaces(out_buf, ret_data_len, ses, in_mount);
 854	if (rc)
 855		goto out;
 856
 857	/* check if iface is still active */
 858	spin_lock(&ses->chan_lock);
 859	pserver = ses->chans[0].server;
 860	if (pserver && !cifs_chan_is_iface_active(ses, pserver)) {
 861		spin_unlock(&ses->chan_lock);
 862		cifs_chan_update_iface(ses, pserver);
 863		spin_lock(&ses->chan_lock);
 864	}
 865	spin_unlock(&ses->chan_lock);
 866
 867out:
 868	kfree(out_buf);
 869	return rc;
 870}
 871
 872static void
 873smb3_qfs_tcon(const unsigned int xid, struct cifs_tcon *tcon,
 874	      struct cifs_sb_info *cifs_sb)
 875{
 876	int rc;
 877	__le16 srch_path = 0; /* Null - open root of share */
 878	u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
 879	struct cifs_open_parms oparms;
 880	struct cifs_fid fid;
 881	struct cached_fid *cfid = NULL;
 882
 883	oparms = (struct cifs_open_parms) {
 884		.tcon = tcon,
 885		.path = "",
 886		.desired_access = FILE_READ_ATTRIBUTES,
 887		.disposition = FILE_OPEN,
 888		.create_options = cifs_create_options(cifs_sb, 0),
 889		.fid = &fid,
 890	};
 891
 892	rc = open_cached_dir(xid, tcon, "", cifs_sb, false, &cfid);
 893	if (rc == 0)
 894		memcpy(&fid, &cfid->fid, sizeof(struct cifs_fid));
 895	else
 896		rc = SMB2_open(xid, &oparms, &srch_path, &oplock, NULL, NULL,
 897			       NULL, NULL);
 898	if (rc)
 899		return;
 900
 901	SMB3_request_interfaces(xid, tcon, true /* called during  mount */);
 902
 903	SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
 904			FS_ATTRIBUTE_INFORMATION);
 905	SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
 906			FS_DEVICE_INFORMATION);
 907	SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
 908			FS_VOLUME_INFORMATION);
 909	SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
 910			FS_SECTOR_SIZE_INFORMATION); /* SMB3 specific */
 911	if (cfid == NULL)
 912		SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
 913	else
 914		close_cached_dir(cfid);
 915}
 916
 917static void
 918smb2_qfs_tcon(const unsigned int xid, struct cifs_tcon *tcon,
 919	      struct cifs_sb_info *cifs_sb)
 920{
 921	int rc;
 922	__le16 srch_path = 0; /* Null - open root of share */
 923	u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
 924	struct cifs_open_parms oparms;
 925	struct cifs_fid fid;
 926
 927	oparms = (struct cifs_open_parms) {
 928		.tcon = tcon,
 929		.path = "",
 930		.desired_access = FILE_READ_ATTRIBUTES,
 931		.disposition = FILE_OPEN,
 932		.create_options = cifs_create_options(cifs_sb, 0),
 933		.fid = &fid,
 934	};
 935
 936	rc = SMB2_open(xid, &oparms, &srch_path, &oplock, NULL, NULL,
 937		       NULL, NULL);
 938	if (rc)
 939		return;
 940
 941	SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
 942			FS_ATTRIBUTE_INFORMATION);
 943	SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
 944			FS_DEVICE_INFORMATION);
 945	SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
 946}
 947
 948static int
 949smb2_is_path_accessible(const unsigned int xid, struct cifs_tcon *tcon,
 950			struct cifs_sb_info *cifs_sb, const char *full_path)
 951{
 952	__le16 *utf16_path;
 953	__u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
 954	int err_buftype = CIFS_NO_BUFFER;
 955	struct cifs_open_parms oparms;
 956	struct kvec err_iov = {};
 957	struct cifs_fid fid;
 958	struct cached_fid *cfid;
 959	bool islink;
 960	int rc, rc2;
 961
 962	rc = open_cached_dir(xid, tcon, full_path, cifs_sb, true, &cfid);
 963	if (!rc) {
 964		close_cached_dir(cfid);
 965		return 0;
 966	}
 967
 968	utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
 969	if (!utf16_path)
 970		return -ENOMEM;
 971
 972	oparms = (struct cifs_open_parms) {
 973		.tcon = tcon,
 974		.path = full_path,
 975		.desired_access = FILE_READ_ATTRIBUTES,
 976		.disposition = FILE_OPEN,
 977		.create_options = cifs_create_options(cifs_sb, 0),
 978		.fid = &fid,
 979	};
 980
 981	rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, NULL,
 982		       &err_iov, &err_buftype);
 983	if (rc) {
 984		struct smb2_hdr *hdr = err_iov.iov_base;
 985
 986		if (unlikely(!hdr || err_buftype == CIFS_NO_BUFFER))
 987			goto out;
 988
 989		if (rc != -EREMOTE && hdr->Status == STATUS_OBJECT_NAME_INVALID) {
 990			rc2 = cifs_inval_name_dfs_link_error(xid, tcon, cifs_sb,
 991							     full_path, &islink);
 992			if (rc2) {
 993				rc = rc2;
 994				goto out;
 995			}
 996			if (islink)
 997				rc = -EREMOTE;
 998		}
 999		if (rc == -EREMOTE && IS_ENABLED(CONFIG_CIFS_DFS_UPCALL) &&
1000		    (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_DFS))
1001			rc = -EOPNOTSUPP;
1002		goto out;
1003	}
1004
1005	rc = SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
1006
1007out:
1008	free_rsp_buf(err_buftype, err_iov.iov_base);
1009	kfree(utf16_path);
1010	return rc;
1011}
1012
1013static int smb2_get_srv_inum(const unsigned int xid, struct cifs_tcon *tcon,
1014			     struct cifs_sb_info *cifs_sb, const char *full_path,
1015			     u64 *uniqueid, struct cifs_open_info_data *data)
1016{
1017	*uniqueid = le64_to_cpu(data->fi.IndexNumber);
1018	return 0;
1019}
1020
1021static int smb2_query_file_info(const unsigned int xid, struct cifs_tcon *tcon,
1022				struct cifsFileInfo *cfile, struct cifs_open_info_data *data)
1023{
1024	struct cifs_fid *fid = &cfile->fid;
1025
1026	if (cfile->symlink_target) {
1027		data->symlink_target = kstrdup(cfile->symlink_target, GFP_KERNEL);
1028		if (!data->symlink_target)
1029			return -ENOMEM;
1030	}
1031	data->contains_posix_file_info = false;
1032	return SMB2_query_info(xid, tcon, fid->persistent_fid, fid->volatile_fid, &data->fi);
1033}
1034
1035#ifdef CONFIG_CIFS_XATTR
1036static ssize_t
1037move_smb2_ea_to_cifs(char *dst, size_t dst_size,
1038		     struct smb2_file_full_ea_info *src, size_t src_size,
1039		     const unsigned char *ea_name)
1040{
1041	int rc = 0;
1042	unsigned int ea_name_len = ea_name ? strlen(ea_name) : 0;
1043	char *name, *value;
1044	size_t buf_size = dst_size;
1045	size_t name_len, value_len, user_name_len;
1046
1047	while (src_size > 0) {
1048		name_len = (size_t)src->ea_name_length;
1049		value_len = (size_t)le16_to_cpu(src->ea_value_length);
1050
1051		if (name_len == 0)
1052			break;
1053
1054		if (src_size < 8 + name_len + 1 + value_len) {
1055			cifs_dbg(FYI, "EA entry goes beyond length of list\n");
1056			rc = smb_EIO2(smb_eio_trace_ea_overrun,
1057				      src_size, 8 + name_len + 1 + value_len);
1058			goto out;
1059		}
1060
1061		name = &src->ea_data[0];
1062		value = &src->ea_data[src->ea_name_length + 1];
1063
1064		if (ea_name) {
1065			if (ea_name_len == name_len &&
1066			    memcmp(ea_name, name, name_len) == 0) {
1067				rc = value_len;
1068				if (dst_size == 0)
1069					goto out;
1070				if (dst_size < value_len) {
1071					rc = -ERANGE;
1072					goto out;
1073				}
1074				memcpy(dst, value, value_len);
1075				goto out;
1076			}
1077		} else {
1078			/* 'user.' plus a terminating null */
1079			user_name_len = 5 + 1 + name_len;
1080
1081			if (buf_size == 0) {
1082				/* skip copy - calc size only */
1083				rc += user_name_len;
1084			} else if (dst_size >= user_name_len) {
1085				dst_size -= user_name_len;
1086				memcpy(dst, "user.", 5);
1087				dst += 5;
1088				memcpy(dst, src->ea_data, name_len);
1089				dst += name_len;
1090				*dst = 0;
1091				++dst;
1092				rc += user_name_len;
1093			} else {
1094				/* stop before overrun buffer */
1095				rc = -ERANGE;
1096				break;
1097			}
1098		}
1099
1100		if (!src->next_entry_offset)
1101			break;
1102
1103		if (src_size < le32_to_cpu(src->next_entry_offset)) {
1104			/* stop before overrun buffer */
1105			rc = -ERANGE;
1106			break;
1107		}
1108		src_size -= le32_to_cpu(src->next_entry_offset);
1109		src = (void *)((char *)src +
1110			       le32_to_cpu(src->next_entry_offset));
1111	}
1112
1113	/* didn't find the named attribute */
1114	if (ea_name)
1115		rc = -ENODATA;
1116
1117out:
1118	return (ssize_t)rc;
1119}
1120
1121static ssize_t
1122smb2_query_eas(const unsigned int xid, struct cifs_tcon *tcon,
1123	       const unsigned char *path, const unsigned char *ea_name,
1124	       char *ea_data, size_t buf_size,
1125	       struct cifs_sb_info *cifs_sb)
1126{
1127	int rc;
1128	struct kvec rsp_iov = {NULL, 0};
1129	int buftype = CIFS_NO_BUFFER;
1130	struct smb2_query_info_rsp *rsp;
1131	struct smb2_file_full_ea_info *info = NULL;
1132
1133	rc = smb2_query_info_compound(xid, tcon, path,
1134				      FILE_READ_EA,
1135				      FILE_FULL_EA_INFORMATION,
1136				      SMB2_O_INFO_FILE,
1137				      CIFSMaxBufSize -
1138				      MAX_SMB2_CREATE_RESPONSE_SIZE -
1139				      MAX_SMB2_CLOSE_RESPONSE_SIZE,
1140				      &rsp_iov, &buftype, cifs_sb);
1141	if (rc) {
1142		/*
1143		 * If ea_name is NULL (listxattr) and there are no EAs,
1144		 * return 0 as it's not an error. Otherwise, the specified
1145		 * ea_name was not found.
1146		 */
1147		if (!ea_name && rc == -ENODATA)
1148			rc = 0;
1149		goto qeas_exit;
1150	}
1151
1152	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
1153	rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
1154			       le32_to_cpu(rsp->OutputBufferLength),
1155			       &rsp_iov,
1156			       sizeof(struct smb2_file_full_ea_info));
1157	if (rc)
1158		goto qeas_exit;
1159
1160	info = (struct smb2_file_full_ea_info *)(
1161			le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
1162	rc = move_smb2_ea_to_cifs(ea_data, buf_size, info,
1163			le32_to_cpu(rsp->OutputBufferLength), ea_name);
1164
1165 qeas_exit:
1166	free_rsp_buf(buftype, rsp_iov.iov_base);
1167	return rc;
1168}
1169
1170static int
1171smb2_set_ea(const unsigned int xid, struct cifs_tcon *tcon,
1172	    const char *path, const char *ea_name, const void *ea_value,
1173	    const __u16 ea_value_len, const struct nls_table *nls_codepage,
1174	    struct cifs_sb_info *cifs_sb)
1175{
1176	struct smb2_compound_vars *vars;
1177	struct cifs_ses *ses = tcon->ses;
1178	struct TCP_Server_Info *server;
1179	struct smb_rqst *rqst;
1180	struct kvec *rsp_iov;
1181	__le16 *utf16_path = NULL;
1182	int ea_name_len = strlen(ea_name);
1183	int flags = CIFS_CP_CREATE_CLOSE_OP;
1184	int len;
1185	int resp_buftype[3];
1186	struct cifs_open_parms oparms;
1187	__u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
1188	struct cifs_fid fid;
1189	unsigned int size[1];
1190	void *data[1];
1191	struct smb2_file_full_ea_info *ea;
1192	struct smb2_query_info_rsp *rsp;
1193	int rc, used_len = 0;
1194	int retries = 0, cur_sleep = 1;
1195
1196replay_again:
1197	/* reinitialize for possible replay */
1198	used_len = 0;
1199	flags = CIFS_CP_CREATE_CLOSE_OP;
1200	oplock = SMB2_OPLOCK_LEVEL_NONE;
1201	server = cifs_pick_channel(ses);
1202
1203	if (smb3_encryption_required(tcon))
1204		flags |= CIFS_TRANSFORM_REQ;
1205
1206	if (ea_name_len > 255)
1207		return -EINVAL;
1208
1209	utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
1210	if (!utf16_path)
1211		return -ENOMEM;
1212
1213	ea = NULL;
1214	resp_buftype[0] = resp_buftype[1] = resp_buftype[2] = CIFS_NO_BUFFER;
1215	vars = kzalloc(sizeof(*vars), GFP_KERNEL);
1216	if (!vars) {
1217		rc = -ENOMEM;
1218		goto out_free_path;
1219	}
1220	rqst = vars->rqst;
1221	rsp_iov = vars->rsp_iov;
1222
1223	if (ses->server->ops->query_all_EAs) {
1224		if (!ea_value) {
1225			rc = ses->server->ops->query_all_EAs(xid, tcon, path,
1226							     ea_name, NULL, 0,
1227							     cifs_sb);
1228			if (rc == -ENODATA)
1229				goto sea_exit;
1230		} else {
1231			/* If we are adding a attribute we should first check
1232			 * if there will be enough space available to store
1233			 * the new EA. If not we should not add it since we
1234			 * would not be able to even read the EAs back.
1235			 */
1236			rc = smb2_query_info_compound(xid, tcon, path,
1237				      FILE_READ_EA,
1238				      FILE_FULL_EA_INFORMATION,
1239				      SMB2_O_INFO_FILE,
1240				      CIFSMaxBufSize -
1241				      MAX_SMB2_CREATE_RESPONSE_SIZE -
1242				      MAX_SMB2_CLOSE_RESPONSE_SIZE,
1243				      &rsp_iov[1], &resp_buftype[1], cifs_sb);
1244			if (rc == 0) {
1245				rsp = (struct smb2_query_info_rsp *)rsp_iov[1].iov_base;
1246				used_len = le32_to_cpu(rsp->OutputBufferLength);
1247			}
1248			free_rsp_buf(resp_buftype[1], rsp_iov[1].iov_base);
1249			resp_buftype[1] = CIFS_NO_BUFFER;
1250			memset(&rsp_iov[1], 0, sizeof(rsp_iov[1]));
1251			rc = 0;
1252
1253			/* Use a fudge factor of 256 bytes in case we collide
1254			 * with a different set_EAs command.
1255			 */
1256			if (CIFSMaxBufSize - MAX_SMB2_CREATE_RESPONSE_SIZE -
1257			   MAX_SMB2_CLOSE_RESPONSE_SIZE - 256 <
1258			   used_len + ea_name_len + ea_value_len + 1) {
1259				rc = -ENOSPC;
1260				goto sea_exit;
1261			}
1262		}
1263	}
1264
1265	/* Open */
1266	rqst[0].rq_iov = vars->open_iov;
1267	rqst[0].rq_nvec = SMB2_CREATE_IOV_SIZE;
1268
1269	oparms = (struct cifs_open_parms) {
1270		.tcon = tcon,
1271		.path = path,
1272		.desired_access = FILE_WRITE_EA,
1273		.disposition = FILE_OPEN,
1274		.create_options = cifs_create_options(cifs_sb, 0),
1275		.fid = &fid,
1276		.replay = !!(retries),
1277	};
1278
1279	rc = SMB2_open_init(tcon, server,
1280			    &rqst[0], &oplock, &oparms, utf16_path);
1281	if (rc)
1282		goto sea_exit;
1283	smb2_set_next_command(tcon, &rqst[0]);
1284
1285
1286	/* Set Info */
1287	rqst[1].rq_iov = vars->si_iov;
1288	rqst[1].rq_nvec = 1;
1289
1290	len = sizeof(*ea) + ea_name_len + ea_value_len + 1;
1291	ea = kzalloc(len, GFP_KERNEL);
1292	if (ea == NULL) {
1293		rc = -ENOMEM;
1294		goto sea_exit;
1295	}
1296
1297	ea->ea_name_length = ea_name_len;
1298	ea->ea_value_length = cpu_to_le16(ea_value_len);
1299	memcpy(ea->ea_data, ea_name, ea_name_len + 1);
1300	memcpy(ea->ea_data + ea_name_len + 1, ea_value, ea_value_len);
1301
1302	size[0] = len;
1303	data[0] = ea;
1304
1305	rc = SMB2_set_info_init(tcon, server,
1306				&rqst[1], COMPOUND_FID,
1307				COMPOUND_FID, current->tgid,
1308				FILE_FULL_EA_INFORMATION,
1309				SMB2_O_INFO_FILE, 0, data, size);
1310	if (rc)
1311		goto sea_exit;
1312	smb2_set_next_command(tcon, &rqst[1]);
1313	smb2_set_related(&rqst[1]);
1314
1315	/* Close */
1316	rqst[2].rq_iov = &vars->close_iov;
1317	rqst[2].rq_nvec = 1;
1318	rc = SMB2_close_init(tcon, server,
1319			     &rqst[2], COMPOUND_FID, COMPOUND_FID, false);
1320	if (rc)
1321		goto sea_exit;
1322	smb2_set_related(&rqst[2]);
1323
1324	if (retries) {
1325		smb2_set_replay(server, &rqst[0]);
1326		smb2_set_replay(server, &rqst[1]);
1327		smb2_set_replay(server, &rqst[2]);
1328	}
1329
1330	rc = compound_send_recv(xid, ses, server,
1331				flags, 3, rqst,
1332				resp_buftype, rsp_iov);
1333	/* no need to bump num_remote_opens because handle immediately closed */
1334
1335 sea_exit:
1336	kfree(ea);
1337	SMB2_open_free(&rqst[0]);
1338	SMB2_set_info_free(&rqst[1]);
1339	SMB2_close_free(&rqst[2]);
1340	free_rsp_buf(resp_buftype[0], rsp_iov[0].iov_base);
1341	free_rsp_buf(resp_buftype[1], rsp_iov[1].iov_base);
1342	free_rsp_buf(resp_buftype[2], rsp_iov[2].iov_base);
1343	kfree(vars);
1344out_free_path:
1345	kfree(utf16_path);
1346
1347	if (is_replayable_error(rc) &&
1348	    smb2_should_replay(tcon, &retries, &cur_sleep))
1349		goto replay_again;
1350
1351	return rc;
1352}
1353#endif
1354
1355static bool
1356smb2_can_echo(struct TCP_Server_Info *server)
1357{
1358	return server->echoes;
1359}
1360
1361static void
1362smb2_clear_stats(struct cifs_tcon *tcon)
1363{
1364	int i;
1365
1366	for (i = 0; i < NUMBER_OF_SMB2_COMMANDS; i++) {
1367		atomic_set(&tcon->stats.smb2_stats.smb2_com_sent[i], 0);
1368		atomic_set(&tcon->stats.smb2_stats.smb2_com_failed[i], 0);
1369	}
1370}
1371
1372static void
1373smb2_dump_share_caps(struct seq_file *m, struct cifs_tcon *tcon)
1374{
1375	seq_puts(m, "\n\tShare Capabilities:");
1376	if (tcon->capabilities & SMB2_SHARE_CAP_DFS)
1377		seq_puts(m, " DFS,");
1378	if (tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
1379		seq_puts(m, " CONTINUOUS AVAILABILITY,");
1380	if (tcon->capabilities & SMB2_SHARE_CAP_SCALEOUT)
1381		seq_puts(m, " SCALEOUT,");
1382	if (tcon->capabilities & SMB2_SHARE_CAP_CLUSTER)
1383		seq_puts(m, " CLUSTER,");
1384	if (tcon->capabilities & SMB2_SHARE_CAP_ASYMMETRIC)
1385		seq_puts(m, " ASYMMETRIC,");
1386	if (tcon->capabilities == 0)
1387		seq_puts(m, " None");
1388	if (tcon->ss_flags & SSINFO_FLAGS_ALIGNED_DEVICE)
1389		seq_puts(m, " Aligned,");
1390	if (tcon->ss_flags & SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE)
1391		seq_puts(m, " Partition Aligned,");
1392	if (tcon->ss_flags & SSINFO_FLAGS_NO_SEEK_PENALTY)
1393		seq_puts(m, " SSD,");
1394	if (tcon->ss_flags & SSINFO_FLAGS_TRIM_ENABLED)
1395		seq_puts(m, " TRIM-support,");
1396
1397	seq_printf(m, "\tShare Flags: 0x%x", tcon->share_flags);
1398	seq_printf(m, "\n\ttid: 0x%x", tcon->tid);
1399	if (tcon->perf_sector_size)
1400		seq_printf(m, "\tOptimal sector size: 0x%x",
1401			   tcon->perf_sector_size);
1402	seq_printf(m, "\tMaximal Access: 0x%x", tcon->maximal_access);
1403}
1404
1405static void
1406smb2_print_stats(struct seq_file *m, struct cifs_tcon *tcon)
1407{
1408	atomic_t *sent = tcon->stats.smb2_stats.smb2_com_sent;
1409	atomic_t *failed = tcon->stats.smb2_stats.smb2_com_failed;
1410
1411	/*
1412	 *  Can't display SMB2_NEGOTIATE, SESSION_SETUP, LOGOFF, CANCEL and ECHO
1413	 *  totals (requests sent) since those SMBs are per-session not per tcon
1414	 */
1415	seq_printf(m, "\nBytes read: %llu  Bytes written: %llu",
1416		   (long long)(tcon->bytes_read),
1417		   (long long)(tcon->bytes_written));
1418	seq_printf(m, "\nOpen files: %d total (local), %d open on server",
1419		   atomic_read(&tcon->num_local_opens),
1420		   atomic_read(&tcon->num_remote_opens));
1421	seq_printf(m, "\nTreeConnects: %d total %d failed",
1422		   atomic_read(&sent[SMB2_TREE_CONNECT_HE]),
1423		   atomic_read(&failed[SMB2_TREE_CONNECT_HE]));
1424	seq_printf(m, "\nTreeDisconnects: %d total %d failed",
1425		   atomic_read(&sent[SMB2_TREE_DISCONNECT_HE]),
1426		   atomic_read(&failed[SMB2_TREE_DISCONNECT_HE]));
1427	seq_printf(m, "\nCreates: %d total %d failed",
1428		   atomic_read(&sent[SMB2_CREATE_HE]),
1429		   atomic_read(&failed[SMB2_CREATE_HE]));
1430	seq_printf(m, "\nCloses: %d total %d failed",
1431		   atomic_read(&sent[SMB2_CLOSE_HE]),
1432		   atomic_read(&failed[SMB2_CLOSE_HE]));
1433	seq_printf(m, "\nFlushes: %d total %d failed",
1434		   atomic_read(&sent[SMB2_FLUSH_HE]),
1435		   atomic_read(&failed[SMB2_FLUSH_HE]));
1436	seq_printf(m, "\nReads: %d total %d failed",
1437		   atomic_read(&sent[SMB2_READ_HE]),
1438		   atomic_read(&failed[SMB2_READ_HE]));
1439	seq_printf(m, "\nWrites: %d total %d failed",
1440		   atomic_read(&sent[SMB2_WRITE_HE]),
1441		   atomic_read(&failed[SMB2_WRITE_HE]));
1442	seq_printf(m, "\nLocks: %d total %d failed",
1443		   atomic_read(&sent[SMB2_LOCK_HE]),
1444		   atomic_read(&failed[SMB2_LOCK_HE]));
1445	seq_printf(m, "\nIOCTLs: %d total %d failed",
1446		   atomic_read(&sent[SMB2_IOCTL_HE]),
1447		   atomic_read(&failed[SMB2_IOCTL_HE]));
1448	seq_printf(m, "\nQueryDirectories: %d total %d failed",
1449		   atomic_read(&sent[SMB2_QUERY_DIRECTORY_HE]),
1450		   atomic_read(&failed[SMB2_QUERY_DIRECTORY_HE]));
1451	seq_printf(m, "\nChangeNotifies: %d total %d failed",
1452		   atomic_read(&sent[SMB2_CHANGE_NOTIFY_HE]),
1453		   atomic_read(&failed[SMB2_CHANGE_NOTIFY_HE]));
1454	seq_printf(m, "\nQueryInfos: %d total %d failed",
1455		   atomic_read(&sent[SMB2_QUERY_INFO_HE]),
1456		   atomic_read(&failed[SMB2_QUERY_INFO_HE]));
1457	seq_printf(m, "\nSetInfos: %d total %d failed",
1458		   atomic_read(&sent[SMB2_SET_INFO_HE]),
1459		   atomic_read(&failed[SMB2_SET_INFO_HE]));
1460	seq_printf(m, "\nOplockBreaks: %d sent %d failed",
1461		   atomic_read(&sent[SMB2_OPLOCK_BREAK_HE]),
1462		   atomic_read(&failed[SMB2_OPLOCK_BREAK_HE]));
1463}
1464
1465static void
1466smb2_set_fid(struct cifsFileInfo *cfile, struct cifs_fid *fid, __u32 oplock)
1467{
1468	struct cifsInodeInfo *cinode = CIFS_I(d_inode(cfile->dentry));
1469	struct TCP_Server_Info *server = tlink_tcon(cfile->tlink)->ses->server;
1470
1471	cfile->fid.persistent_fid = fid->persistent_fid;
1472	cfile->fid.volatile_fid = fid->volatile_fid;
1473	cfile->fid.access = fid->access;
1474#ifdef CONFIG_CIFS_DEBUG2
1475	cfile->fid.mid = fid->mid;
1476#endif /* CIFS_DEBUG2 */
1477	server->ops->set_oplock_level(cinode, oplock, fid->epoch,
1478				      &fid->purge_cache);
1479	cinode->can_cache_brlcks = CIFS_CACHE_WRITE(cinode);
1480	memcpy(cfile->fid.create_guid, fid->create_guid, 16);
1481}
1482
1483static int
1484smb2_close_file(const unsigned int xid, struct cifs_tcon *tcon,
1485		struct cifs_fid *fid)
1486{
1487	return SMB2_close(xid, tcon, fid->persistent_fid, fid->volatile_fid);
1488}
1489
1490static int
1491smb2_close_getattr(const unsigned int xid, struct cifs_tcon *tcon,
1492		   struct cifsFileInfo *cfile)
1493{
1494	struct smb2_file_network_open_info file_inf;
1495	struct inode *inode;
1496	u64 asize;
1497	int rc;
1498
1499	rc = __SMB2_close(xid, tcon, cfile->fid.persistent_fid,
1500		   cfile->fid.volatile_fid, &file_inf);
1501	if (rc)
1502		return rc;
1503
1504	inode = d_inode(cfile->dentry);
1505
1506	spin_lock(&inode->i_lock);
1507	CIFS_I(inode)->time = jiffies;
1508
1509	/* Creation time should not need to be updated on close */
1510	if (file_inf.LastWriteTime)
1511		inode_set_mtime_to_ts(inode,
1512				      cifs_NTtimeToUnix(file_inf.LastWriteTime));
1513	if (file_inf.ChangeTime)
1514		inode_set_ctime_to_ts(inode,
1515				      cifs_NTtimeToUnix(file_inf.ChangeTime));
1516	if (file_inf.LastAccessTime)
1517		inode_set_atime_to_ts(inode,
1518				      cifs_NTtimeToUnix(file_inf.LastAccessTime));
1519
1520	asize = le64_to_cpu(file_inf.AllocationSize);
1521	if (asize > 4096)
1522		inode->i_blocks = CIFS_INO_BLOCKS(asize);
1523
1524	/* End of file and Attributes should not have to be updated on close */
1525	spin_unlock(&inode->i_lock);
1526	return rc;
1527}
1528
1529static int
1530SMB2_request_res_key(const unsigned int xid, struct cifs_tcon *tcon,
1531		     u64 persistent_fid, u64 volatile_fid,
1532		     struct copychunk_ioctl_req *pcchunk)
1533{
1534	int rc;
1535	unsigned int ret_data_len;
1536	struct resume_key_ioctl_rsp *res_key;
1537
1538	rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
1539			FSCTL_SRV_REQUEST_RESUME_KEY, NULL, 0 /* no input */,
1540			CIFSMaxBufSize, (char **)&res_key, &ret_data_len);
1541
1542	if (rc == -EOPNOTSUPP) {
1543		pr_warn_once("Server share %s does not support copy range\n", tcon->tree_name);
1544		goto req_res_key_exit;
1545	} else if (rc) {
1546		cifs_tcon_dbg(VFS, "refcpy ioctl error %d getting resume key\n", rc);
1547		goto req_res_key_exit;
1548	}
1549	if (ret_data_len < sizeof(struct resume_key_ioctl_rsp)) {
1550		cifs_tcon_dbg(VFS, "Invalid refcopy resume key length\n");
1551		rc = -EINVAL;
1552		goto req_res_key_exit;
1553	}
1554	memcpy(pcchunk->SourceKey, res_key->ResumeKey, COPY_CHUNK_RES_KEY_SIZE);
1555
1556req_res_key_exit:
1557	kfree(res_key);
1558	return rc;
1559}
1560
1561static int
1562smb2_ioctl_query_info(const unsigned int xid,
1563		      struct cifs_tcon *tcon,
1564		      struct cifs_sb_info *cifs_sb,
1565		      __le16 *path, int is_dir,
1566		      unsigned long p)
1567{
1568	struct smb2_compound_vars *vars;
1569	struct smb_rqst *rqst;
1570	struct kvec *rsp_iov;
1571	struct cifs_ses *ses = tcon->ses;
1572	struct TCP_Server_Info *server;
1573	char __user *arg = (char __user *)p;
1574	struct smb_query_info qi;
1575	struct smb_query_info __user *pqi;
1576	int rc = 0;
1577	int flags = CIFS_CP_CREATE_CLOSE_OP;
1578	struct smb2_query_info_rsp *qi_rsp = NULL;
1579	struct smb2_ioctl_rsp *io_rsp = NULL;
1580	void *buffer = NULL;
1581	int resp_buftype[3];
1582	struct cifs_open_parms oparms;
1583	u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
1584	struct cifs_fid fid;
1585	unsigned int size[2];
1586	void *data[2];
1587	int create_options = is_dir ? CREATE_NOT_FILE : CREATE_NOT_DIR;
1588	void (*free_req1_func)(struct smb_rqst *r);
1589	int retries = 0, cur_sleep = 1;
1590
1591replay_again:
1592	/* reinitialize for possible replay */
1593	buffer = NULL;
1594	flags = CIFS_CP_CREATE_CLOSE_OP;
1595	oplock = SMB2_OPLOCK_LEVEL_NONE;
1596	server = cifs_pick_channel(ses);
1597
1598	vars = kzalloc(sizeof(*vars), GFP_ATOMIC);
1599	if (vars == NULL)
1600		return -ENOMEM;
1601	rqst = &vars->rqst[0];
1602	rsp_iov = &vars->rsp_iov[0];
1603
1604	resp_buftype[0] = resp_buftype[1] = resp_buftype[2] = CIFS_NO_BUFFER;
1605
1606	if (copy_from_user(&qi, arg, sizeof(struct smb_query_info))) {
1607		rc = -EFAULT;
1608		goto free_vars;
1609	}
1610	if (qi.output_buffer_length > 1024) {
1611		rc = -EINVAL;
1612		goto free_vars;
1613	}
1614
1615	if (!ses || !server) {
1616		rc = smb_EIO(smb_eio_trace_null_pointers);
1617		goto free_vars;
1618	}
1619
1620	if (smb3_encryption_required(tcon))
1621		flags |= CIFS_TRANSFORM_REQ;
1622
1623	if (qi.output_buffer_length) {
1624		buffer = memdup_user(arg + sizeof(struct smb_query_info), qi.output_buffer_length);
1625		if (IS_ERR(buffer)) {
1626			rc = PTR_ERR(buffer);
1627			goto free_vars;
1628		}
1629	}
1630
1631	/* Open */
1632	rqst[0].rq_iov = &vars->open_iov[0];
1633	rqst[0].rq_nvec = SMB2_CREATE_IOV_SIZE;
1634
1635	oparms = (struct cifs_open_parms) {
1636		.tcon = tcon,
1637		.disposition = FILE_OPEN,
1638		.create_options = cifs_create_options(cifs_sb, create_options),
1639		.fid = &fid,
1640		.replay = !!(retries),
1641	};
1642
1643	if (qi.flags & PASSTHRU_FSCTL) {
1644		switch (qi.info_type & FSCTL_DEVICE_ACCESS_MASK) {
1645		case FSCTL_DEVICE_ACCESS_FILE_READ_WRITE_ACCESS:
1646			oparms.desired_access = FILE_READ_DATA | FILE_WRITE_DATA | FILE_READ_ATTRIBUTES | SYNCHRONIZE;
1647			break;
1648		case FSCTL_DEVICE_ACCESS_FILE_ANY_ACCESS:
1649			oparms.desired_access = GENERIC_ALL;
1650			break;
1651		case FSCTL_DEVICE_ACCESS_FILE_READ_ACCESS:
1652			oparms.desired_access = GENERIC_READ;
1653			break;
1654		case FSCTL_DEVICE_ACCESS_FILE_WRITE_ACCESS:
1655			oparms.desired_access = GENERIC_WRITE;
1656			break;
1657		}
1658	} else if (qi.flags & PASSTHRU_SET_INFO) {
1659		oparms.desired_access = GENERIC_WRITE;
1660	} else {
1661		oparms.desired_access = FILE_READ_ATTRIBUTES | READ_CONTROL;
1662	}
1663
1664	rc = SMB2_open_init(tcon, server,
1665			    &rqst[0], &oplock, &oparms, path);
1666	if (rc)
1667		goto free_output_buffer;
1668	smb2_set_next_command(tcon, &rqst[0]);
1669
1670	/* Query */
1671	if (qi.flags & PASSTHRU_FSCTL) {
1672		/* Can eventually relax perm check since server enforces too */
1673		if (!capable(CAP_SYS_ADMIN)) {
1674			rc = -EPERM;
1675			goto free_open_req;
1676		}
1677		rqst[1].rq_iov = &vars->io_iov[0];
1678		rqst[1].rq_nvec = SMB2_IOCTL_IOV_SIZE;
1679
1680		rc = SMB2_ioctl_init(tcon, server, &rqst[1], COMPOUND_FID, COMPOUND_FID,
1681				     qi.info_type, buffer, qi.output_buffer_length,
1682				     CIFSMaxBufSize - MAX_SMB2_CREATE_RESPONSE_SIZE -
1683				     MAX_SMB2_CLOSE_RESPONSE_SIZE);
1684		free_req1_func = SMB2_ioctl_free;
1685	} else if (qi.flags == PASSTHRU_SET_INFO) {
1686		/* Can eventually relax perm check since server enforces too */
1687		if (!capable(CAP_SYS_ADMIN)) {
1688			rc = -EPERM;
1689			goto free_open_req;
1690		}
1691		if (qi.output_buffer_length < 8) {
1692			rc = -EINVAL;
1693			goto free_open_req;
1694		}
1695		rqst[1].rq_iov = vars->si_iov;
1696		rqst[1].rq_nvec = 1;
1697
1698		/* MS-FSCC 2.4.13 FileEndOfFileInformation */
1699		size[0] = 8;
1700		data[0] = buffer;
1701
1702		rc = SMB2_set_info_init(tcon, server, &rqst[1], COMPOUND_FID, COMPOUND_FID,
1703					current->tgid, FILE_END_OF_FILE_INFORMATION,
1704					SMB2_O_INFO_FILE, 0, data, size);
1705		free_req1_func = SMB2_set_info_free;
1706	} else if (qi.flags == PASSTHRU_QUERY_INFO) {
1707		rqst[1].rq_iov = &vars->qi_iov;
1708		rqst[1].rq_nvec = 1;
1709
1710		rc = SMB2_query_info_init(tcon, server,
1711				  &rqst[1], COMPOUND_FID,
1712				  COMPOUND_FID, qi.file_info_class,
1713				  qi.info_type, qi.additional_information,
1714				  qi.input_buffer_length,
1715				  qi.output_buffer_length, buffer);
1716		free_req1_func = SMB2_query_info_free;
1717	} else { /* unknown flags */
1718		cifs_tcon_dbg(VFS, "Invalid passthru query flags: 0x%x\n",
1719			      qi.flags);
1720		rc = -EINVAL;
1721	}
1722
1723	if (rc)
1724		goto free_open_req;
1725	smb2_set_next_command(tcon, &rqst[1]);
1726	smb2_set_related(&rqst[1]);
1727
1728	/* Close */
1729	rqst[2].rq_iov = &vars->close_iov;
1730	rqst[2].rq_nvec = 1;
1731
1732	rc = SMB2_close_init(tcon, server,
1733			     &rqst[2], COMPOUND_FID, COMPOUND_FID, false);
1734	if (rc)
1735		goto free_req_1;
1736	smb2_set_related(&rqst[2]);
1737
1738	if (retries) {
1739		smb2_set_replay(server, &rqst[0]);
1740		smb2_set_replay(server, &rqst[1]);
1741		smb2_set_replay(server, &rqst[2]);
1742	}
1743
1744	rc = compound_send_recv(xid, ses, server,
1745				flags, 3, rqst,
1746				resp_buftype, rsp_iov);
1747	if (rc)
1748		goto out;
1749
1750	/* No need to bump num_remote_opens since handle immediately closed */
1751	if (qi.flags & PASSTHRU_FSCTL) {
1752		pqi = (struct smb_query_info __user *)arg;
1753		io_rsp = (struct smb2_ioctl_rsp *)rsp_iov[1].iov_base;
1754		if (le32_to_cpu(io_rsp->OutputCount) < qi.input_buffer_length)
1755			qi.input_buffer_length = le32_to_cpu(io_rsp->OutputCount);
1756		if (qi.input_buffer_length > 0 &&
1757		    le32_to_cpu(io_rsp->OutputOffset) + qi.input_buffer_length
1758		    > rsp_iov[1].iov_len) {
1759			rc = -EFAULT;
1760			goto out;
1761		}
1762
1763		if (copy_to_user(&pqi->input_buffer_length,
1764				 &qi.input_buffer_length,
1765				 sizeof(qi.input_buffer_length))) {
1766			rc = -EFAULT;
1767			goto out;
1768		}
1769
1770		if (copy_to_user((void __user *)pqi + sizeof(struct smb_query_info),
1771				 (const void *)io_rsp + le32_to_cpu(io_rsp->OutputOffset),
1772				 qi.input_buffer_length))
1773			rc = -EFAULT;
1774	} else {
1775		pqi = (struct smb_query_info __user *)arg;
1776		qi_rsp = (struct smb2_query_info_rsp *)rsp_iov[1].iov_base;
1777		if (le32_to_cpu(qi_rsp->OutputBufferLength) < qi.input_buffer_length)
1778			qi.input_buffer_length = le32_to_cpu(qi_rsp->OutputBufferLength);
1779		if (copy_to_user(&pqi->input_buffer_length,
1780				 &qi.input_buffer_length,
1781				 sizeof(qi.input_buffer_length))) {
1782			rc = -EFAULT;
1783			goto out;
1784		}
1785
1786		if (copy_to_user(pqi + 1, qi_rsp->Buffer,
1787				 qi.input_buffer_length))
1788			rc = -EFAULT;
1789	}
1790
1791out:
1792	free_rsp_buf(resp_buftype[0], rsp_iov[0].iov_base);
1793	free_rsp_buf(resp_buftype[1], rsp_iov[1].iov_base);
1794	free_rsp_buf(resp_buftype[2], rsp_iov[2].iov_base);
1795	SMB2_close_free(&rqst[2]);
1796free_req_1:
1797	free_req1_func(&rqst[1]);
1798free_open_req:
1799	SMB2_open_free(&rqst[0]);
1800free_output_buffer:
1801	kfree(buffer);
1802free_vars:
1803	kfree(vars);
1804
1805	if (is_replayable_error(rc) &&
1806	    smb2_should_replay(tcon, &retries, &cur_sleep))
1807		goto replay_again;
1808
1809	return rc;
1810}
1811
1812/**
1813 * calc_chunk_count - calculates the number chunks to be filled in the Chunks[]
1814 * array of struct copychunk_ioctl
1815 *
1816 * @tcon: destination file tcon
1817 * @bytes_left: how many bytes are left to copy
1818 *
1819 * Return: maximum number of chunks with which Chunks[] can be filled.
1820 */
1821static inline u32
1822calc_chunk_count(struct cifs_tcon *tcon, u64 bytes_left)
1823{
1824	u32 max_chunks = READ_ONCE(tcon->max_chunks);
1825	u32 max_bytes_copy = READ_ONCE(tcon->max_bytes_copy);
1826	u32 max_bytes_chunk = READ_ONCE(tcon->max_bytes_chunk);
1827	u64 need;
1828	u32 allowed;
1829
1830	if (!max_bytes_chunk || !max_bytes_copy || !max_chunks)
1831		return 0;
1832
1833	/* chunks needed for the remaining bytes */
1834	need = DIV_ROUND_UP_ULL(bytes_left, max_bytes_chunk);
1835	/* chunks allowed per cc request */
1836	allowed = DIV_ROUND_UP(max_bytes_copy, max_bytes_chunk);
1837
1838	return (u32)umin(need, umin(max_chunks, allowed));
1839}
1840
1841/**
1842 * smb2_copychunk_range - server-side copy of data range
1843 *
1844 * @xid: transaction id
1845 * @src_file: source file
1846 * @dst_file: destination file
1847 * @src_off: source file byte offset
1848 * @len: number of bytes to copy
1849 * @dst_off: destination file byte offset
1850 *
1851 * Obtains a resume key for @src_file and issues FSCTL_SRV_COPYCHUNK_WRITE
1852 * IOCTLs, splitting the request into chunks limited by tcon->max_*.
1853 *
1854 * Return: @len on success; negative errno on failure.
1855 */
1856static ssize_t
1857smb2_copychunk_range(const unsigned int xid,
1858		     struct cifsFileInfo *src_file,
1859		     struct cifsFileInfo *dst_file,
1860		     u64 src_off,
1861		     u64 len,
1862		     u64 dst_off)
1863{
1864	int rc = 0;
1865	unsigned int ret_data_len = 0;
1866	struct copychunk_ioctl_req *cc_req = NULL;
1867	struct copychunk_ioctl_rsp *cc_rsp = NULL;
1868	struct cifs_tcon *tcon;
1869	struct srv_copychunk *chunk;
1870	u32 chunks, chunk_count, chunk_bytes;
1871	u32 copy_bytes, copy_bytes_left;
1872	u32 chunks_written, bytes_written;
1873	u64 total_bytes_left = len;
1874	u64 src_off_prev, dst_off_prev;
1875	u32 retries = 0;
1876
1877	tcon = tlink_tcon(dst_file->tlink);
1878
1879	trace_smb3_copychunk_enter(xid, src_file->fid.volatile_fid,
1880				   dst_file->fid.volatile_fid, tcon->tid,
1881				   tcon->ses->Suid, src_off, dst_off, len);
1882
1883retry:
1884	chunk_count = calc_chunk_count(tcon, total_bytes_left);
1885	if (!chunk_count) {
1886		rc = -EOPNOTSUPP;
1887		goto out;
1888	}
1889
1890	cc_req = kzalloc(struct_size(cc_req, Chunks, chunk_count), GFP_KERNEL);
1891	if (!cc_req) {
1892		rc = -ENOMEM;
1893		goto out;
1894	}
1895
1896	/* Request a key from the server to identify the source of the copy */
1897	rc = SMB2_request_res_key(xid,
1898				  tlink_tcon(src_file->tlink),
1899				  src_file->fid.persistent_fid,
1900				  src_file->fid.volatile_fid,
1901				  cc_req);
1902
1903	/* Note: request_res_key sets res_key null only if rc != 0 */
1904	if (rc)
1905		goto out;
1906
1907	while (total_bytes_left > 0) {
1908
1909		/* Store previous offsets to allow rewind */
1910		src_off_prev = src_off;
1911		dst_off_prev = dst_off;
1912
1913		/*
1914		 * __counted_by_le(ChunkCount): set to allocated chunks before
1915		 * populating Chunks[]
1916		 */
1917		cc_req->ChunkCount = cpu_to_le32(chunk_count);
1918
1919		chunks = 0;
1920		copy_bytes = 0;
1921		copy_bytes_left = umin(total_bytes_left, tcon->max_bytes_copy);
1922		while (copy_bytes_left > 0 && chunks < chunk_count) {
1923			chunk = &cc_req->Chunks[chunks++];
1924
1925			chunk->SourceOffset = cpu_to_le64(src_off);
1926			chunk->TargetOffset = cpu_to_le64(dst_off);
1927
1928			chunk_bytes = umin(copy_bytes_left, tcon->max_bytes_chunk);
1929
1930			chunk->Length = cpu_to_le32(chunk_bytes);
1931			/* Buffer is zeroed, no need to set chunk->Reserved = 0 */
1932
1933			src_off += chunk_bytes;
1934			dst_off += chunk_bytes;
1935
1936			copy_bytes_left -= chunk_bytes;
1937			copy_bytes += chunk_bytes;
1938		}
1939
1940		cc_req->ChunkCount = cpu_to_le32(chunks);
1941		/* Buffer is zeroed, no need to set cc_req->Reserved = 0 */
1942
1943		/* Request server copy to target from src identified by key */
1944		kfree(cc_rsp);
1945		cc_rsp = NULL;
1946		rc = SMB2_ioctl(xid, tcon, dst_file->fid.persistent_fid,
1947			dst_file->fid.volatile_fid, FSCTL_SRV_COPYCHUNK_WRITE,
1948			(char *)cc_req, struct_size(cc_req, Chunks, chunks),
1949			CIFSMaxBufSize, (char **)&cc_rsp, &ret_data_len);
1950
1951		if (rc && rc != -EINVAL)
1952			goto out;
1953
1954		if (unlikely(ret_data_len != sizeof(*cc_rsp))) {
1955			cifs_tcon_dbg(VFS, "Copychunk invalid response: size %u/%zu\n",
1956				      ret_data_len, sizeof(*cc_rsp));
1957			rc = smb_EIO1(smb_eio_trace_copychunk_inv_rsp, ret_data_len);
1958			goto out;
1959		}
1960
1961		bytes_written = le32_to_cpu(cc_rsp->TotalBytesWritten);
1962		chunks_written = le32_to_cpu(cc_rsp->ChunksWritten);
1963		chunk_bytes = le32_to_cpu(cc_rsp->ChunkBytesWritten);
1964
1965		if (rc == 0) {
1966			/* Check if server claimed to write more than we asked */
1967			if (unlikely(!bytes_written || bytes_written > copy_bytes)) {
1968				cifs_tcon_dbg(VFS, "Copychunk invalid response: bytes written %u/%u\n",
1969					      bytes_written, copy_bytes);
1970				rc = smb_EIO2(smb_eio_trace_copychunk_overcopy_b,
1971					      bytes_written, copy_bytes);
1972				goto out;
1973			}
1974			if (unlikely(!chunks_written || chunks_written > chunks)) {
1975				cifs_tcon_dbg(VFS, "Copychunk invalid response: chunks written %u/%u\n",
1976					      chunks_written, chunks);
1977				rc = smb_EIO2(smb_eio_trace_copychunk_overcopy_c,
1978					      chunks_written, chunks);
1979				goto out;
1980			}
1981
1982			/* Partial write: rewind */
1983			if (bytes_written < copy_bytes) {
1984				u32 delta = copy_bytes - bytes_written;
1985
1986				src_off -= delta;
1987				dst_off -= delta;
1988			}
1989
1990			total_bytes_left -= bytes_written;
1991			continue;
1992		}
1993
1994		/*
1995		 * Check if server is not asking us to reduce size.
1996		 *
1997		 * Note: As per MS-SMB2 2.2.32.1, the values returned
1998		 * in cc_rsp are not strictly lower than what existed
1999		 * before.
2000		 */
2001		if (bytes_written < tcon->max_bytes_copy) {
2002			cifs_tcon_dbg(FYI, "Copychunk MaxBytesCopy updated: %u -> %u\n",
2003				      tcon->max_bytes_copy, bytes_written);
2004			tcon->max_bytes_copy = bytes_written;
2005		}
2006
2007		if (chunks_written < tcon->max_chunks) {
2008			cifs_tcon_dbg(FYI, "Copychunk MaxChunks updated: %u -> %u\n",
2009				      tcon->max_chunks, chunks_written);
2010			tcon->max_chunks = chunks_written;
2011		}
2012
2013		if (chunk_bytes < tcon->max_bytes_chunk) {
2014			cifs_tcon_dbg(FYI, "Copychunk MaxBytesChunk updated: %u -> %u\n",
2015				      tcon->max_bytes_chunk, chunk_bytes);
2016			tcon->max_bytes_chunk = chunk_bytes;
2017		}
2018
2019		/* reset to last offsets */
2020		if (retries++ < 2) {
2021			src_off = src_off_prev;
2022			dst_off = dst_off_prev;
2023			kfree(cc_req);
2024			cc_req = NULL;
2025			goto retry;
2026		}
2027
2028		break;
2029	}
2030
2031out:
2032	kfree(cc_req);
2033	kfree(cc_rsp);
2034	if (rc) {
2035		trace_smb3_copychunk_err(xid, src_file->fid.volatile_fid,
2036					 dst_file->fid.volatile_fid, tcon->tid,
2037					 tcon->ses->Suid, src_off, dst_off, len, rc);
2038		return rc;
2039	} else {
2040		trace_smb3_copychunk_done(xid, src_file->fid.volatile_fid,
2041					  dst_file->fid.volatile_fid, tcon->tid,
2042					  tcon->ses->Suid, src_off, dst_off, len);
2043		return len;
2044	}
2045}
2046
2047static int
2048smb2_flush_file(const unsigned int xid, struct cifs_tcon *tcon,
2049		struct cifs_fid *fid)
2050{
2051	return SMB2_flush(xid, tcon, fid->persistent_fid, fid->volatile_fid);
2052}
2053
2054static unsigned int
2055smb2_read_data_offset(char *buf)
2056{
2057	struct smb2_read_rsp *rsp = (struct smb2_read_rsp *)buf;
2058
2059	return rsp->DataOffset;
2060}
2061
2062static unsigned int
2063smb2_read_data_length(char *buf, bool in_remaining)
2064{
2065	struct smb2_read_rsp *rsp = (struct smb2_read_rsp *)buf;
2066
2067	if (in_remaining)
2068		return le32_to_cpu(rsp->DataRemaining);
2069
2070	return le32_to_cpu(rsp->DataLength);
2071}
2072
2073
2074static int
2075smb2_sync_read(const unsigned int xid, struct cifs_fid *pfid,
2076	       struct cifs_io_parms *parms, unsigned int *bytes_read,
2077	       char **buf, int *buf_type)
2078{
2079	parms->persistent_fid = pfid->persistent_fid;
2080	parms->volatile_fid = pfid->volatile_fid;
2081	return SMB2_read(xid, parms, bytes_read, buf, buf_type);
2082}
2083
2084static int
2085smb2_sync_write(const unsigned int xid, struct cifs_fid *pfid,
2086		struct cifs_io_parms *parms, unsigned int *written,
2087		struct kvec *iov, unsigned long nr_segs)
2088{
2089
2090	parms->persistent_fid = pfid->persistent_fid;
2091	parms->volatile_fid = pfid->volatile_fid;
2092	return SMB2_write(xid, parms, written, iov, nr_segs);
2093}
2094
2095/* Set or clear the SPARSE_FILE attribute based on value passed in setsparse */
2096static bool smb2_set_sparse(const unsigned int xid, struct cifs_tcon *tcon,
2097		struct cifsFileInfo *cfile, struct inode *inode, __u8 setsparse)
2098{
2099	struct cifsInodeInfo *cifsi;
2100	int rc;
2101
2102	cifsi = CIFS_I(inode);
2103
2104	/* if file already sparse don't bother setting sparse again */
2105	if ((cifsi->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE) && setsparse)
2106		return true; /* already sparse */
2107
2108	if (!(cifsi->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE) && !setsparse)
2109		return true; /* already not sparse */
2110
2111	/*
2112	 * Can't check for sparse support on share the usual way via the
2113	 * FS attribute info (FILE_SUPPORTS_SPARSE_FILES) on the share
2114	 * since Samba server doesn't set the flag on the share, yet
2115	 * supports the set sparse FSCTL and returns sparse correctly
2116	 * in the file attributes. If we fail setting sparse though we
2117	 * mark that server does not support sparse files for this share
2118	 * to avoid repeatedly sending the unsupported fsctl to server
2119	 * if the file is repeatedly extended.
2120	 */
2121	if (tcon->broken_sparse_sup)
2122		return false;
2123
2124	rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
2125			cfile->fid.volatile_fid, FSCTL_SET_SPARSE,
2126			&setsparse, 1, CIFSMaxBufSize, NULL, NULL);
2127	if (rc) {
2128		tcon->broken_sparse_sup = true;
2129		cifs_dbg(FYI, "set sparse rc = %d\n", rc);
2130		return false;
2131	}
2132
2133	if (setsparse)
2134		cifsi->cifsAttrs |= FILE_ATTRIBUTE_SPARSE_FILE;
2135	else
2136		cifsi->cifsAttrs &= (~FILE_ATTRIBUTE_SPARSE_FILE);
2137
2138	return true;
2139}
2140
2141static int
2142smb2_set_file_size(const unsigned int xid, struct cifs_tcon *tcon,
2143		   struct cifsFileInfo *cfile, __u64 size, bool set_alloc)
2144{
2145	struct inode *inode;
2146
2147	/*
2148	 * If extending file more than one page make sparse. Many Linux fs
2149	 * make files sparse by default when extending via ftruncate
2150	 */
2151	inode = d_inode(cfile->dentry);
2152
2153	if (!set_alloc && (size > inode->i_size + 8192)) {
2154		__u8 set_sparse = 1;
2155
2156		/* whether set sparse succeeds or not, extend the file */
2157		smb2_set_sparse(xid, tcon, cfile, inode, set_sparse);
2158	}
2159
2160	return SMB2_set_eof(xid, tcon, cfile->fid.persistent_fid,
2161			    cfile->fid.volatile_fid, cfile->pid, size);
2162}
2163
2164static int
2165smb2_duplicate_extents(const unsigned int xid,
2166			struct cifsFileInfo *srcfile,
2167			struct cifsFileInfo *trgtfile, u64 src_off,
2168			u64 len, u64 dest_off)
2169{
2170	int rc;
2171	unsigned int ret_data_len;
2172	struct inode *inode;
2173	struct duplicate_extents_to_file dup_ext_buf;
2174	struct cifs_tcon *tcon = tlink_tcon(trgtfile->tlink);
2175
2176	/* server fileays advertise duplicate extent support with this flag */
2177	if ((le32_to_cpu(tcon->fsAttrInfo.Attributes) &
2178	     FILE_SUPPORTS_BLOCK_REFCOUNTING) == 0)
2179		return -EOPNOTSUPP;
2180
2181	dup_ext_buf.VolatileFileHandle = srcfile->fid.volatile_fid;
2182	dup_ext_buf.PersistentFileHandle = srcfile->fid.persistent_fid;
2183	dup_ext_buf.SourceFileOffset = cpu_to_le64(src_off);
2184	dup_ext_buf.TargetFileOffset = cpu_to_le64(dest_off);
2185	dup_ext_buf.ByteCount = cpu_to_le64(len);
2186	cifs_dbg(FYI, "Duplicate extents: src off %lld dst off %lld len %lld\n",
2187		src_off, dest_off, len);
2188	trace_smb3_clone_enter(xid, srcfile->fid.volatile_fid,
2189			       trgtfile->fid.volatile_fid, tcon->tid,
2190			       tcon->ses->Suid, src_off, dest_off, len);
2191	inode = d_inode(trgtfile->dentry);
2192	if (inode->i_size < dest_off + len) {
2193		rc = smb2_set_file_size(xid, tcon, trgtfile, dest_off + len, false);
2194		if (rc)
2195			goto duplicate_extents_out;
2196		netfs_resize_file(netfs_inode(inode), dest_off + len, true);
2197		cifs_setsize(inode, dest_off + len);
2198	}
2199	rc = SMB2_ioctl(xid, tcon, trgtfile->fid.persistent_fid,
2200			trgtfile->fid.volatile_fid,
2201			FSCTL_DUPLICATE_EXTENTS_TO_FILE,
2202			(char *)&dup_ext_buf,
2203			sizeof(struct duplicate_extents_to_file),
2204			CIFSMaxBufSize, NULL,
2205			&ret_data_len);
2206
2207	if (ret_data_len > 0)
2208		cifs_dbg(FYI, "Non-zero response length in duplicate extents\n");
2209
2210duplicate_extents_out:
2211	if (rc)
2212		trace_smb3_clone_err(xid, srcfile->fid.volatile_fid,
2213				     trgtfile->fid.volatile_fid,
2214				     tcon->tid, tcon->ses->Suid, src_off,
2215				     dest_off, len, rc);
2216	else
2217		trace_smb3_clone_done(xid, srcfile->fid.volatile_fid,
2218				      trgtfile->fid.volatile_fid, tcon->tid,
2219				      tcon->ses->Suid, src_off, dest_off, len);
2220	return rc;
2221}
2222
2223static int
2224smb2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
2225		   struct cifsFileInfo *cfile)
2226{
2227	return SMB2_set_compression(xid, tcon, cfile->fid.persistent_fid,
2228			    cfile->fid.volatile_fid);
2229}
2230
2231static int
2232smb3_set_integrity(const unsigned int xid, struct cifs_tcon *tcon,
2233		   struct cifsFileInfo *cfile)
2234{
2235	struct fsctl_set_integrity_information_req integr_info;
2236	unsigned int ret_data_len;
2237
2238	integr_info.ChecksumAlgorithm = cpu_to_le16(CHECKSUM_TYPE_UNCHANGED);
2239	integr_info.Flags = 0;
2240	integr_info.Reserved = 0;
2241
2242	return SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
2243			cfile->fid.volatile_fid,
2244			FSCTL_SET_INTEGRITY_INFORMATION,
2245			(char *)&integr_info,
2246			sizeof(struct fsctl_set_integrity_information_req),
2247			CIFSMaxBufSize, NULL,
2248			&ret_data_len);
2249
2250}
2251
2252/* GMT Token is @GMT-YYYY.MM.DD-HH.MM.SS Unicode which is 48 bytes + null */
2253#define GMT_TOKEN_SIZE 50
2254
2255#define MIN_SNAPSHOT_ARRAY_SIZE 16 /* See MS-SMB2 section 3.3.5.15.1 */
2256
2257/*
2258 * Input buffer contains (empty) struct smb_snapshot array with size filled in
2259 * For output see struct SRV_SNAPSHOT_ARRAY in MS-SMB2 section 2.2.32.2
2260 */
2261static int
2262smb3_enum_snapshots(const unsigned int xid, struct cifs_tcon *tcon,
2263		   struct cifsFileInfo *cfile, void __user *ioc_buf)
2264{
2265	char *retbuf = NULL;
2266	unsigned int ret_data_len = 0;
2267	int rc;
2268	u32 max_response_size;
2269	struct smb_snapshot_array snapshot_in;
2270
2271	/*
2272	 * On the first query to enumerate the list of snapshots available
2273	 * for this volume the buffer begins with 0 (number of snapshots
2274	 * which can be returned is zero since at that point we do not know
2275	 * how big the buffer needs to be). On the second query,
2276	 * it (ret_data_len) is set to number of snapshots so we can
2277	 * know to set the maximum response size larger (see below).
2278	 */
2279	if (get_user(ret_data_len, (unsigned int __user *)ioc_buf))
2280		return -EFAULT;
2281
2282	/*
2283	 * Note that for snapshot queries that servers like Azure expect that
2284	 * the first query be minimal size (and just used to get the number/size
2285	 * of previous versions) so response size must be specified as EXACTLY
2286	 * sizeof(struct snapshot_array) which is 16 when rounded up to multiple
2287	 * of eight bytes.
2288	 */
2289	if (ret_data_len == 0)
2290		max_response_size = MIN_SNAPSHOT_ARRAY_SIZE;
2291	else
2292		max_response_size = CIFSMaxBufSize;
2293
2294	rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
2295			cfile->fid.volatile_fid,
2296			FSCTL_SRV_ENUMERATE_SNAPSHOTS,
2297			NULL, 0 /* no input data */, max_response_size,
2298			(char **)&retbuf,
2299			&ret_data_len);
2300	cifs_dbg(FYI, "enum snapshots ioctl returned %d and ret buflen is %d\n",
2301			rc, ret_data_len);
2302	if (rc)
2303		return rc;
2304
2305	if (ret_data_len && (ioc_buf != NULL) && (retbuf != NULL)) {
2306		/* Fixup buffer */
2307		if (copy_from_user(&snapshot_in, ioc_buf,
2308		    sizeof(struct smb_snapshot_array))) {
2309			rc = -EFAULT;
2310			kfree(retbuf);
2311			return rc;
2312		}
2313
2314		/*
2315		 * Check for min size, ie not large enough to fit even one GMT
2316		 * token (snapshot).  On the first ioctl some users may pass in
2317		 * smaller size (or zero) to simply get the size of the array
2318		 * so the user space caller can allocate sufficient memory
2319		 * and retry the ioctl again with larger array size sufficient
2320		 * to hold all of the snapshot GMT tokens on the second try.
2321		 */
2322		if (snapshot_in.snapshot_array_size < GMT_TOKEN_SIZE)
2323			ret_data_len = sizeof(struct smb_snapshot_array);
2324
2325		/*
2326		 * We return struct SRV_SNAPSHOT_ARRAY, followed by
2327		 * the snapshot array (of 50 byte GMT tokens) each
2328		 * representing an available previous version of the data
2329		 */
2330		if (ret_data_len > (snapshot_in.snapshot_array_size +
2331					sizeof(struct smb_snapshot_array)))
2332			ret_data_len = snapshot_in.snapshot_array_size +
2333					sizeof(struct smb_snapshot_array);
2334
2335		if (copy_to_user(ioc_buf, retbuf, ret_data_len))
2336			rc = -EFAULT;
2337	}
2338
2339	kfree(retbuf);
2340	return rc;
2341}
2342
2343
2344
2345static int
2346smb3_notify(const unsigned int xid, struct file *pfile,
2347	    void __user *ioc_buf, bool return_changes)
2348{
2349	struct smb3_notify_info notify;
2350	struct smb3_notify_info __user *pnotify_buf;
2351	struct dentry *dentry = pfile->f_path.dentry;
2352	struct inode *inode = file_inode(pfile);
2353	struct cifs_sb_info *cifs_sb = CIFS_SB(inode->i_sb);
2354	struct cifs_open_parms oparms;
2355	struct cifs_fid fid;
2356	struct cifs_tcon *tcon;
2357	const unsigned char *path;
2358	char *returned_ioctl_info = NULL;
2359	void *page = alloc_dentry_path();
2360	__le16 *utf16_path = NULL;
2361	u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
2362	int rc = 0;
2363	__u32 ret_len = 0;
2364
2365	path = build_path_from_dentry(dentry, page);
2366	if (IS_ERR(path)) {
2367		rc = PTR_ERR(path);
2368		goto notify_exit;
2369	}
2370
2371	utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
2372	if (utf16_path == NULL) {
2373		rc = -ENOMEM;
2374		goto notify_exit;
2375	}
2376
2377	if (return_changes) {
2378		if (copy_from_user(&notify, ioc_buf, sizeof(struct smb3_notify_info))) {
2379			rc = -EFAULT;
2380			goto notify_exit;
2381		}
2382	} else {
2383		if (copy_from_user(&notify, ioc_buf, sizeof(struct smb3_notify))) {
2384			rc = -EFAULT;
2385			goto notify_exit;
2386		}
2387		notify.data_len = 0;
2388	}
2389
2390	tcon = cifs_sb_master_tcon(cifs_sb);
2391	oparms = (struct cifs_open_parms) {
2392		.tcon = tcon,
2393		.path = path,
2394		.desired_access = FILE_READ_ATTRIBUTES | FILE_READ_DATA,
2395		.disposition = FILE_OPEN,
2396		.create_options = cifs_create_options(cifs_sb, 0),
2397		.fid = &fid,
2398	};
2399
2400	rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, NULL, NULL,
2401		       NULL);
2402	if (rc)
2403		goto notify_exit;
2404
2405	rc = SMB2_change_notify(xid, tcon, fid.persistent_fid, fid.volatile_fid,
2406				notify.watch_tree, notify.completion_filter,
2407				notify.data_len, &returned_ioctl_info, &ret_len);
2408
2409	SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
2410
2411	cifs_dbg(FYI, "change notify for path %s rc %d\n", path, rc);
2412	if (return_changes && (ret_len > 0) && (notify.data_len > 0)) {
2413		if (ret_len > notify.data_len)
2414			ret_len = notify.data_len;
2415		pnotify_buf = (struct smb3_notify_info __user *)ioc_buf;
2416		if (copy_to_user(pnotify_buf->notify_data, returned_ioctl_info, ret_len))
2417			rc = -EFAULT;
2418		else if (copy_to_user(&pnotify_buf->data_len, &ret_len, sizeof(ret_len)))
2419			rc = -EFAULT;
2420	}
2421	kfree(returned_ioctl_info);
2422notify_exit:
2423	free_dentry_path(page);
2424	kfree(utf16_path);
2425	return rc;
2426}
2427
2428static int
2429smb2_query_dir_first(const unsigned int xid, struct cifs_tcon *tcon,
2430		     const char *path, struct cifs_sb_info *cifs_sb,
2431		     struct cifs_fid *fid, __u16 search_flags,
2432		     struct cifs_search_info *srch_inf)
2433{
2434	__le16 *utf16_path;
2435	struct smb_rqst rqst[2];
2436	struct kvec rsp_iov[2];
2437	int resp_buftype[2];
2438	struct kvec open_iov[SMB2_CREATE_IOV_SIZE];
2439	struct kvec qd_iov[SMB2_QUERY_DIRECTORY_IOV_SIZE];
2440	int rc, flags = 0;
2441	u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
2442	struct cifs_open_parms oparms;
2443	struct smb2_query_directory_rsp *qd_rsp = NULL;
2444	struct smb2_create_rsp *op_rsp = NULL;
2445	struct TCP_Server_Info *server;
2446	int retries = 0, cur_sleep = 1;
2447
2448replay_again:
2449	/* reinitialize for possible replay */
2450	flags = 0;
2451	oplock = SMB2_OPLOCK_LEVEL_NONE;
2452	server = cifs_pick_channel(tcon->ses);
2453
2454	utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
2455	if (!utf16_path)
2456		return -ENOMEM;
2457
2458	if (smb3_encryption_required(tcon))
2459		flags |= CIFS_TRANSFORM_REQ;
2460
2461	memset(rqst, 0, sizeof(rqst));
2462	resp_buftype[0] = resp_buftype[1] = CIFS_NO_BUFFER;
2463	memset(rsp_iov, 0, sizeof(rsp_iov));
2464
2465	/* Open */
2466	memset(&open_iov, 0, sizeof(open_iov));
2467	rqst[0].rq_iov = open_iov;
2468	rqst[0].rq_nvec = SMB2_CREATE_IOV_SIZE;
2469
2470	oparms = (struct cifs_open_parms) {
2471		.tcon = tcon,
2472		.path = path,
2473		.desired_access = FILE_READ_ATTRIBUTES | FILE_READ_DATA,
2474		.disposition = FILE_OPEN,
2475		.create_options = cifs_create_options(cifs_sb, 0),
2476		.fid = fid,
2477		.replay = !!(retries),
2478	};
2479
2480	rc = SMB2_open_init(tcon, server,
2481			    &rqst[0], &oplock, &oparms, utf16_path);
2482	if (rc)
2483		goto qdf_free;
2484	smb2_set_next_command(tcon, &rqst[0]);
2485
2486	/* Query directory */
2487	srch_inf->entries_in_buffer = 0;
2488	srch_inf->index_of_last_entry = 2;
2489
2490	memset(&qd_iov, 0, sizeof(qd_iov));
2491	rqst[1].rq_iov = qd_iov;
2492	rqst[1].rq_nvec = SMB2_QUERY_DIRECTORY_IOV_SIZE;
2493
2494	rc = SMB2_query_directory_init(xid, tcon, server,
2495				       &rqst[1],
2496				       COMPOUND_FID, COMPOUND_FID,
2497				       0, srch_inf->info_level);
2498	if (rc)
2499		goto qdf_free;
2500
2501	smb2_set_related(&rqst[1]);
2502
2503	if (retries) {
2504		smb2_set_replay(server, &rqst[0]);
2505		smb2_set_replay(server, &rqst[1]);
2506	}
2507
2508	rc = compound_send_recv(xid, tcon->ses, server,
2509				flags, 2, rqst,
2510				resp_buftype, rsp_iov);
2511
2512	/* If the open failed there is nothing to do */
2513	op_rsp = (struct smb2_create_rsp *)rsp_iov[0].iov_base;
2514	if (op_rsp == NULL || op_rsp->hdr.Status != STATUS_SUCCESS) {
2515		cifs_dbg(FYI, "query_dir_first: open failed rc=%d\n", rc);
2516		goto qdf_free;
2517	}
2518	fid->persistent_fid = op_rsp->PersistentFileId;
2519	fid->volatile_fid = op_rsp->VolatileFileId;
2520
2521	/* Anything else than ENODATA means a genuine error */
2522	if (rc && rc != -ENODATA) {
2523		SMB2_close(xid, tcon, fid->persistent_fid, fid->volatile_fid);
2524		cifs_dbg(FYI, "query_dir_first: query directory failed rc=%d\n", rc);
2525		trace_smb3_query_dir_err(xid, fid->persistent_fid,
2526					 tcon->tid, tcon->ses->Suid, 0, 0, rc);
2527		goto qdf_free;
2528	}
2529
2530	atomic_inc(&tcon->num_remote_opens);
2531
2532	qd_rsp = (struct smb2_query_directory_rsp *)rsp_iov[1].iov_base;
2533	if (qd_rsp->hdr.Status == STATUS_NO_MORE_FILES) {
2534		trace_smb3_query_dir_done(xid, fid->persistent_fid,
2535					  tcon->tid, tcon->ses->Suid, 0, 0);
2536		srch_inf->endOfSearch = true;
2537		rc = 0;
2538		goto qdf_free;
2539	}
2540
2541	rc = smb2_parse_query_directory(tcon, &rsp_iov[1], resp_buftype[1],
2542					srch_inf);
2543	if (rc) {
2544		trace_smb3_query_dir_err(xid, fid->persistent_fid, tcon->tid,
2545			tcon->ses->Suid, 0, 0, rc);
2546		goto qdf_free;
2547	}
2548	resp_buftype[1] = CIFS_NO_BUFFER;
2549
2550	trace_smb3_query_dir_done(xid, fid->persistent_fid, tcon->tid,
2551			tcon->ses->Suid, 0, srch_inf->entries_in_buffer);
2552
2553 qdf_free:
2554	kfree(utf16_path);
2555	SMB2_open_free(&rqst[0]);
2556	SMB2_query_directory_free(&rqst[1]);
2557	free_rsp_buf(resp_buftype[0], rsp_iov[0].iov_base);
2558	free_rsp_buf(resp_buftype[1], rsp_iov[1].iov_base);
2559
2560	if (is_replayable_error(rc) &&
2561	    smb2_should_replay(tcon, &retries, &cur_sleep))
2562		goto replay_again;
2563
2564	return rc;
2565}
2566
2567static int
2568smb2_query_dir_next(const unsigned int xid, struct cifs_tcon *tcon,
2569		    struct cifs_fid *fid, __u16 search_flags,
2570		    struct cifs_search_info *srch_inf)
2571{
2572	return SMB2_query_directory(xid, tcon, fid->persistent_fid,
2573				    fid->volatile_fid, 0, srch_inf);
2574}
2575
2576static int
2577smb2_close_dir(const unsigned int xid, struct cifs_tcon *tcon,
2578	       struct cifs_fid *fid)
2579{
2580	return SMB2_close(xid, tcon, fid->persistent_fid, fid->volatile_fid);
2581}
2582
2583/*
2584 * If we negotiate SMB2 protocol and get STATUS_PENDING - update
2585 * the number of credits and return true. Otherwise - return false.
2586 */
2587static bool
2588smb2_is_status_pending(char *buf, struct TCP_Server_Info *server)
2589{
2590	struct smb2_hdr *shdr = (struct smb2_hdr *)buf;
2591	int scredits, in_flight;
2592
2593	if (shdr->Status != STATUS_PENDING)
2594		return false;
2595
2596	if (shdr->CreditRequest) {
2597		spin_lock(&server->req_lock);
2598		server->credits += le16_to_cpu(shdr->CreditRequest);
2599		scredits = server->credits;
2600		in_flight = server->in_flight;
2601		spin_unlock(&server->req_lock);
2602		wake_up(&server->request_q);
2603
2604		trace_smb3_pend_credits(server->current_mid,
2605				server->conn_id, server->hostname, scredits,
2606				le16_to_cpu(shdr->CreditRequest), in_flight);
2607		cifs_dbg(FYI, "%s: status pending add %u credits total=%d\n",
2608				__func__, le16_to_cpu(shdr->CreditRequest), scredits);
2609	}
2610
2611	return true;
2612}
2613
2614static bool
2615smb2_is_session_expired(char *buf)
2616{
2617	struct smb2_hdr *shdr = (struct smb2_hdr *)buf;
2618
2619	if (shdr->Status != STATUS_NETWORK_SESSION_EXPIRED &&
2620	    shdr->Status != STATUS_USER_SESSION_DELETED)
2621		return false;
2622
2623	trace_smb3_ses_expired(le32_to_cpu(shdr->Id.SyncId.TreeId),
2624			       le64_to_cpu(shdr->SessionId),
2625			       le16_to_cpu(shdr->Command),
2626			       le64_to_cpu(shdr->MessageId));
2627	cifs_dbg(FYI, "Session expired or deleted\n");
2628
2629	return true;
2630}
2631
2632static bool
2633smb2_is_status_io_timeout(char *buf)
2634{
2635	struct smb2_hdr *shdr = (struct smb2_hdr *)buf;
2636
2637	if (shdr->Status == STATUS_IO_TIMEOUT)
2638		return true;
2639	else
2640		return false;
2641}
2642
2643static bool
2644smb2_is_network_name_deleted(char *buf, struct TCP_Server_Info *server)
2645{
2646	struct smb2_hdr *shdr = (struct smb2_hdr *)buf;
2647	struct TCP_Server_Info *pserver;
2648	struct cifs_ses *ses;
2649	struct cifs_tcon *tcon;
2650
2651	if (shdr->Status != STATUS_NETWORK_NAME_DELETED)
2652		return false;
2653
2654	/* If server is a channel, select the primary channel */
2655	pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
2656
2657	spin_lock(&cifs_tcp_ses_lock);
2658	list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
2659		if (cifs_ses_exiting(ses))
2660			continue;
2661		list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
2662			if (tcon->tid == le32_to_cpu(shdr->Id.SyncId.TreeId)) {
2663				spin_lock(&tcon->tc_lock);
2664				tcon->need_reconnect = true;
2665				spin_unlock(&tcon->tc_lock);
2666				spin_unlock(&cifs_tcp_ses_lock);
2667				pr_warn_once("Server share %s deleted.\n",
2668					     tcon->tree_name);
2669				return true;
2670			}
2671		}
2672	}
2673	spin_unlock(&cifs_tcp_ses_lock);
2674
2675	return false;
2676}
2677
2678static int
2679smb2_oplock_response(struct cifs_tcon *tcon, __u64 persistent_fid,
2680		__u64 volatile_fid, __u16 net_fid, struct cifsInodeInfo *cinode)
2681{
2682	if (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_LEASING)
2683		return SMB2_lease_break(0, tcon, cinode->lease_key,
2684					smb2_get_lease_state(cinode));
2685
2686	return SMB2_oplock_break(0, tcon, persistent_fid, volatile_fid,
2687				 CIFS_CACHE_READ(cinode) ? 1 : 0);
2688}
2689
2690void
2691smb2_set_replay(struct TCP_Server_Info *server, struct smb_rqst *rqst)
2692{
2693	struct smb2_hdr *shdr;
2694
2695	if (server->dialect < SMB30_PROT_ID)
2696		return;
2697
2698	shdr = (struct smb2_hdr *)(rqst->rq_iov[0].iov_base);
2699	if (shdr == NULL) {
2700		cifs_dbg(FYI, "shdr NULL in smb2_set_related\n");
2701		return;
2702	}
2703	shdr->Flags |= SMB2_FLAGS_REPLAY_OPERATION;
2704}
2705
2706void
2707smb2_set_related(struct smb_rqst *rqst)
2708{
2709	struct smb2_hdr *shdr;
2710
2711	shdr = (struct smb2_hdr *)(rqst->rq_iov[0].iov_base);
2712	if (shdr == NULL) {
2713		cifs_dbg(FYI, "shdr NULL in smb2_set_related\n");
2714		return;
2715	}
2716	shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
2717}
2718
2719char smb2_padding[7] = {0, 0, 0, 0, 0, 0, 0};
2720
2721void
2722smb2_set_next_command(struct cifs_tcon *tcon, struct smb_rqst *rqst)
2723{
2724	struct smb2_hdr *shdr;
2725	struct cifs_ses *ses = tcon->ses;
2726	struct TCP_Server_Info *server = ses->server;
2727	unsigned long len = smb_rqst_len(server, rqst);
2728	int num_padding;
2729
2730	shdr = (struct smb2_hdr *)(rqst->rq_iov[0].iov_base);
2731	if (shdr == NULL) {
2732		cifs_dbg(FYI, "shdr NULL in smb2_set_next_command\n");
2733		return;
2734	}
2735
2736	/* SMB headers in a compound are 8 byte aligned. */
2737	if (IS_ALIGNED(len, 8))
2738		goto out;
2739
2740	num_padding = 8 - (len & 7);
2741	if (smb3_encryption_required(tcon)) {
2742		int i;
2743
2744		/*
2745		 * Flatten request into a single buffer with required padding as
2746		 * the encryption layer can't handle the padding iovs.
2747		 */
2748		for (i = 1; i < rqst->rq_nvec; i++) {
2749			memcpy(rqst->rq_iov[0].iov_base +
2750			       rqst->rq_iov[0].iov_len,
2751			       rqst->rq_iov[i].iov_base,
2752			       rqst->rq_iov[i].iov_len);
2753			rqst->rq_iov[0].iov_len += rqst->rq_iov[i].iov_len;
2754		}
2755		memset(rqst->rq_iov[0].iov_base + rqst->rq_iov[0].iov_len,
2756		       0, num_padding);
2757		rqst->rq_iov[0].iov_len += num_padding;
2758		rqst->rq_nvec = 1;
2759	} else {
2760		rqst->rq_iov[rqst->rq_nvec].iov_base = smb2_padding;
2761		rqst->rq_iov[rqst->rq_nvec].iov_len = num_padding;
2762		rqst->rq_nvec++;
2763	}
2764	len += num_padding;
2765out:
2766	shdr->NextCommand = cpu_to_le32(len);
2767}
2768
2769/*
2770 * helper function for exponential backoff and check if replayable
2771 */
2772bool smb2_should_replay(struct cifs_tcon *tcon,
2773				int *pretries,
2774				int *pcur_sleep)
2775{
2776	if (!pretries || !pcur_sleep)
2777		return false;
2778
2779	if (tcon->retry || (*pretries)++ < tcon->ses->server->retrans) {
2780		msleep(*pcur_sleep);
2781		(*pcur_sleep) = ((*pcur_sleep) << 1);
2782		if ((*pcur_sleep) > CIFS_MAX_SLEEP)
2783			(*pcur_sleep) = CIFS_MAX_SLEEP;
2784		return true;
2785	}
2786
2787	return false;
2788}
2789
2790/*
2791 * Passes the query info response back to the caller on success.
2792 * Caller need to free this with free_rsp_buf().
2793 */
2794int
2795smb2_query_info_compound(const unsigned int xid, struct cifs_tcon *tcon,
2796			 const char *path, u32 desired_access,
2797			 u32 class, u32 type, u32 output_len,
2798			 struct kvec *rsp, int *buftype,
2799			 struct cifs_sb_info *cifs_sb)
2800{
2801	struct smb2_compound_vars *vars;
2802	struct cifs_ses *ses = tcon->ses;
2803	struct TCP_Server_Info *server;
2804	int flags = CIFS_CP_CREATE_CLOSE_OP;
2805	struct smb_rqst *rqst;
2806	int resp_buftype[3];
2807	struct kvec *rsp_iov;
2808	u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
2809	struct cifs_open_parms oparms;
2810	struct cifs_fid fid;
2811	int rc;
2812	__le16 *utf16_path;
2813	struct cached_fid *cfid;
2814	int retries = 0, cur_sleep = 1;
2815
2816replay_again:
2817	/* reinitialize for possible replay */
2818	cfid = NULL;
2819	flags = CIFS_CP_CREATE_CLOSE_OP;
2820	oplock = SMB2_OPLOCK_LEVEL_NONE;
2821	server = cifs_pick_channel(ses);
2822
2823	if (!path)
2824		path = "";
2825	utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
2826	if (!utf16_path)
2827		return -ENOMEM;
2828
2829	if (smb3_encryption_required(tcon))
2830		flags |= CIFS_TRANSFORM_REQ;
2831
2832	resp_buftype[0] = resp_buftype[1] = resp_buftype[2] = CIFS_NO_BUFFER;
2833	vars = kzalloc(sizeof(*vars), GFP_KERNEL);
2834	if (!vars) {
2835		rc = -ENOMEM;
2836		goto out_free_path;
2837	}
2838	rqst = vars->rqst;
2839	rsp_iov = vars->rsp_iov;
2840
2841	/*
2842	 * We can only call this for things we know are directories.
2843	 */
2844	if (!strcmp(path, ""))
2845		open_cached_dir(xid, tcon, path, cifs_sb, false,
2846				&cfid); /* cfid null if open dir failed */
2847
2848	rqst[0].rq_iov = vars->open_iov;
2849	rqst[0].rq_nvec = SMB2_CREATE_IOV_SIZE;
2850
2851	oparms = (struct cifs_open_parms) {
2852		.tcon = tcon,
2853		.path = path,
2854		.desired_access = desired_access,
2855		.disposition = FILE_OPEN,
2856		.create_options = cifs_create_options(cifs_sb, 0),
2857		.fid = &fid,
2858		.replay = !!(retries),
2859	};
2860
2861	rc = SMB2_open_init(tcon, server,
2862			    &rqst[0], &oplock, &oparms, utf16_path);
2863	if (rc)
2864		goto qic_exit;
2865	smb2_set_next_command(tcon, &rqst[0]);
2866
2867	rqst[1].rq_iov = &vars->qi_iov;
2868	rqst[1].rq_nvec = 1;
2869
2870	if (cfid) {
2871		rc = SMB2_query_info_init(tcon, server,
2872					  &rqst[1],
2873					  cfid->fid.persistent_fid,
2874					  cfid->fid.volatile_fid,
2875					  class, type, 0,
2876					  output_len, 0,
2877					  NULL);
2878	} else {
2879		rc = SMB2_query_info_init(tcon, server,
2880					  &rqst[1],
2881					  COMPOUND_FID,
2882					  COMPOUND_FID,
2883					  class, type, 0,
2884					  output_len, 0,
2885					  NULL);
2886	}
2887	if (rc)
2888		goto qic_exit;
2889	if (!cfid) {
2890		smb2_set_next_command(tcon, &rqst[1]);
2891		smb2_set_related(&rqst[1]);
2892	}
2893
2894	rqst[2].rq_iov = &vars->close_iov;
2895	rqst[2].rq_nvec = 1;
2896
2897	rc = SMB2_close_init(tcon, server,
2898			     &rqst[2], COMPOUND_FID, COMPOUND_FID, false);
2899	if (rc)
2900		goto qic_exit;
2901	smb2_set_related(&rqst[2]);
2902
2903	if (retries) {
2904		if (!cfid) {
2905			smb2_set_replay(server, &rqst[0]);
2906			smb2_set_replay(server, &rqst[2]);
2907		}
2908		smb2_set_replay(server, &rqst[1]);
2909	}
2910
2911	if (cfid) {
2912		rc = compound_send_recv(xid, ses, server,
2913					flags, 1, &rqst[1],
2914					&resp_buftype[1], &rsp_iov[1]);
2915	} else {
2916		rc = compound_send_recv(xid, ses, server,
2917					flags, 3, rqst,
2918					resp_buftype, rsp_iov);
2919	}
2920	if (rc) {
2921		free_rsp_buf(resp_buftype[1], rsp_iov[1].iov_base);
2922		if (rc == -EREMCHG) {
2923			tcon->need_reconnect = true;
2924			pr_warn_once("server share %s deleted\n",
2925				     tcon->tree_name);
2926		}
2927		goto qic_exit;
2928	}
2929	*rsp = rsp_iov[1];
2930	*buftype = resp_buftype[1];
2931
2932 qic_exit:
2933	SMB2_open_free(&rqst[0]);
2934	SMB2_query_info_free(&rqst[1]);
2935	SMB2_close_free(&rqst[2]);
2936	free_rsp_buf(resp_buftype[0], rsp_iov[0].iov_base);
2937	free_rsp_buf(resp_buftype[2], rsp_iov[2].iov_base);
2938	if (cfid)
2939		close_cached_dir(cfid);
2940	kfree(vars);
2941out_free_path:
2942	kfree(utf16_path);
2943
2944	if (is_replayable_error(rc) &&
2945	    smb2_should_replay(tcon, &retries, &cur_sleep))
2946		goto replay_again;
2947
2948	return rc;
2949}
2950
2951static int
2952smb2_queryfs(const unsigned int xid, struct cifs_tcon *tcon,
2953	     const char *path, struct cifs_sb_info *cifs_sb, struct kstatfs *buf)
2954{
2955	struct smb2_query_info_rsp *rsp;
2956	struct smb2_fs_full_size_info *info = NULL;
2957	struct kvec rsp_iov = {NULL, 0};
2958	int buftype = CIFS_NO_BUFFER;
2959	int rc;
2960
2961
2962	rc = smb2_query_info_compound(xid, tcon, path,
2963				      FILE_READ_ATTRIBUTES,
2964				      FS_FULL_SIZE_INFORMATION,
2965				      SMB2_O_INFO_FILESYSTEM,
2966				      sizeof(struct smb2_fs_full_size_info),
2967				      &rsp_iov, &buftype, cifs_sb);
2968	if (rc)
2969		goto qfs_exit;
2970
2971	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
2972	buf->f_type = SMB2_SUPER_MAGIC;
2973	info = (struct smb2_fs_full_size_info *)(
2974		le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
2975	rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
2976			       le32_to_cpu(rsp->OutputBufferLength),
2977			       &rsp_iov,
2978			       sizeof(struct smb2_fs_full_size_info));
2979	if (!rc)
2980		smb2_copy_fs_info_to_kstatfs(info, buf);
2981
2982qfs_exit:
2983	trace_smb3_qfs_done(xid, tcon->tid, tcon->ses->Suid, tcon->tree_name, rc);
2984	free_rsp_buf(buftype, rsp_iov.iov_base);
2985	return rc;
2986}
2987
2988static int
2989smb311_queryfs(const unsigned int xid, struct cifs_tcon *tcon,
2990	       const char *path, struct cifs_sb_info *cifs_sb, struct kstatfs *buf)
2991{
2992	int rc;
2993	__le16 *utf16_path = NULL;
2994	u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
2995	struct cifs_open_parms oparms;
2996	struct cifs_fid fid;
2997
2998	if (!tcon->posix_extensions)
2999		return smb2_queryfs(xid, tcon, path, cifs_sb, buf);
3000
3001	oparms = (struct cifs_open_parms) {
3002		.tcon = tcon,
3003		.path = path,
3004		.desired_access = FILE_READ_ATTRIBUTES,
3005		.disposition = FILE_OPEN,
3006		.create_options = cifs_create_options(cifs_sb, 0),
3007		.fid = &fid,
3008	};
3009
3010	utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
3011	if (utf16_path == NULL)
3012		return -ENOMEM;
3013
3014	rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, NULL,
3015		       NULL, NULL);
3016	kfree(utf16_path);
3017	if (rc)
3018		return rc;
3019
3020	rc = SMB311_posix_qfs_info(xid, tcon, fid.persistent_fid,
3021				   fid.volatile_fid, buf);
3022	buf->f_type = SMB2_SUPER_MAGIC;
3023	SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
3024	return rc;
3025}
3026
3027static bool
3028smb2_compare_fids(struct cifsFileInfo *ob1, struct cifsFileInfo *ob2)
3029{
3030	return ob1->fid.persistent_fid == ob2->fid.persistent_fid &&
3031	       ob1->fid.volatile_fid == ob2->fid.volatile_fid;
3032}
3033
3034static int
3035smb2_mand_lock(const unsigned int xid, struct cifsFileInfo *cfile, __u64 offset,
3036	       __u64 length, __u32 type, int lock, int unlock, bool wait)
3037{
3038	if (unlock && !lock)
3039		type = SMB2_LOCKFLAG_UNLOCK;
3040	return SMB2_lock(xid, tlink_tcon(cfile->tlink),
3041			 cfile->fid.persistent_fid, cfile->fid.volatile_fid,
3042			 current->tgid, length, offset, type, wait);
3043}
3044
3045static void
3046smb2_get_lease_key(struct inode *inode, struct cifs_fid *fid)
3047{
3048	memcpy(fid->lease_key, CIFS_I(inode)->lease_key, SMB2_LEASE_KEY_SIZE);
3049}
3050
3051static void
3052smb2_set_lease_key(struct inode *inode, struct cifs_fid *fid)
3053{
3054	memcpy(CIFS_I(inode)->lease_key, fid->lease_key, SMB2_LEASE_KEY_SIZE);
3055}
3056
3057static void
3058smb2_new_lease_key(struct cifs_fid *fid)
3059{
3060	generate_random_uuid(fid->lease_key);
3061}
3062
3063static int
3064smb2_get_dfs_refer(const unsigned int xid, struct cifs_ses *ses,
3065		   const char *search_name,
3066		   struct dfs_info3_param **target_nodes,
3067		   unsigned int *num_of_nodes,
3068		   const struct nls_table *nls_codepage, int remap)
3069{
3070	int rc;
3071	__le16 *utf16_path = NULL;
3072	int utf16_path_len = 0;
3073	struct cifs_tcon *tcon;
3074	struct fsctl_get_dfs_referral_req *dfs_req = NULL;
3075	struct get_dfs_referral_rsp *dfs_rsp = NULL;
3076	u32 dfs_req_size = 0, dfs_rsp_size = 0;
3077	int retry_once = 0;
3078
3079	cifs_dbg(FYI, "%s: path: %s\n", __func__, search_name);
3080
3081	/*
3082	 * Try to use the IPC tcon, otherwise just use any
3083	 */
3084	tcon = ses->tcon_ipc;
3085	if (tcon == NULL) {
3086		spin_lock(&cifs_tcp_ses_lock);
3087		tcon = list_first_entry_or_null(&ses->tcon_list,
3088						struct cifs_tcon,
3089						tcon_list);
3090		if (tcon) {
3091			spin_lock(&tcon->tc_lock);
3092			tcon->tc_count++;
3093			spin_unlock(&tcon->tc_lock);
3094			trace_smb3_tcon_ref(tcon->debug_id, tcon->tc_count,
3095					    netfs_trace_tcon_ref_get_dfs_refer);
3096		}
3097		spin_unlock(&cifs_tcp_ses_lock);
3098	}
3099
3100	if (tcon == NULL) {
3101		cifs_dbg(VFS, "session %p has no tcon available for a dfs referral request\n",
3102			 ses);
3103		rc = -ENOTCONN;
3104		goto out;
3105	}
3106
3107	utf16_path = cifs_strndup_to_utf16(search_name, PATH_MAX,
3108					   &utf16_path_len,
3109					   nls_codepage, remap);
3110	if (!utf16_path) {
3111		rc = -ENOMEM;
3112		goto out;
3113	}
3114
3115	dfs_req_size = sizeof(*dfs_req) + utf16_path_len;
3116	dfs_req = kzalloc(dfs_req_size, GFP_KERNEL);
3117	if (!dfs_req) {
3118		rc = -ENOMEM;
3119		goto out;
3120	}
3121
3122	/* Highest DFS referral version understood */
3123	dfs_req->MaxReferralLevel = DFS_VERSION;
3124
3125	/* Path to resolve in an UTF-16 null-terminated string */
3126	memcpy(dfs_req->RequestFileName, utf16_path, utf16_path_len);
3127
3128	for (;;) {
3129		rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
3130				FSCTL_DFS_GET_REFERRALS,
3131				(char *)dfs_req, dfs_req_size, CIFSMaxBufSize,
3132				(char **)&dfs_rsp, &dfs_rsp_size);
3133		if (fatal_signal_pending(current)) {
3134			rc = -EINTR;
3135			break;
3136		}
3137		if (!is_retryable_error(rc) || retry_once++)
3138			break;
3139		usleep_range(512, 2048);
3140	}
3141
3142	if (!rc && !dfs_rsp)
3143		rc = smb_EIO(smb_eio_trace_dfsref_no_rsp);
3144	if (rc) {
3145		if (!is_retryable_error(rc) && rc != -ENOENT && rc != -EOPNOTSUPP)
3146			cifs_tcon_dbg(FYI, "%s: ioctl error: rc=%d\n", __func__, rc);
3147		goto out;
3148	}
3149
3150	rc = parse_dfs_referrals(dfs_rsp, dfs_rsp_size,
3151				 num_of_nodes, target_nodes,
3152				 nls_codepage, remap, search_name,
3153				 true /* is_unicode */);
3154	if (rc && rc != -ENOENT) {
3155		cifs_tcon_dbg(VFS, "%s: failed to parse DFS referral %s: %d\n",
3156			      __func__, search_name, rc);
3157	}
3158
3159 out:
3160	if (tcon && !tcon->ipc) {
3161		/* ipc tcons are not refcounted */
3162		cifs_put_tcon(tcon, netfs_trace_tcon_ref_put_dfs_refer);
3163		trace_smb3_tcon_ref(tcon->debug_id, tcon->tc_count,
3164				    netfs_trace_tcon_ref_dec_dfs_refer);
3165	}
3166	kfree(utf16_path);
3167	kfree(dfs_req);
3168	kfree(dfs_rsp);
3169	return rc;
3170}
3171
3172static struct smb_ntsd *
3173get_smb2_acl_by_fid(struct cifs_sb_info *cifs_sb,
3174		    const struct cifs_fid *cifsfid, u32 *pacllen, u32 info)
3175{
3176	struct smb_ntsd *pntsd = NULL;
3177	unsigned int xid;
3178	int rc = -EOPNOTSUPP;
3179	struct tcon_link *tlink = cifs_sb_tlink(cifs_sb);
3180
3181	if (IS_ERR(tlink))
3182		return ERR_CAST(tlink);
3183
3184	xid = get_xid();
3185	cifs_dbg(FYI, "trying to get acl\n");
3186
3187	rc = SMB2_query_acl(xid, tlink_tcon(tlink), cifsfid->persistent_fid,
3188			    cifsfid->volatile_fid, (void **)&pntsd, pacllen,
3189			    info);
3190	free_xid(xid);
3191
3192	cifs_put_tlink(tlink);
3193
3194	cifs_dbg(FYI, "%s: rc = %d ACL len %d\n", __func__, rc, *pacllen);
3195	if (rc)
3196		return ERR_PTR(rc);
3197	return pntsd;
3198
3199}
3200
3201static struct smb_ntsd *
3202get_smb2_acl_by_path(struct cifs_sb_info *cifs_sb,
3203		     const char *path, u32 *pacllen, u32 info)
3204{
3205	struct smb_ntsd *pntsd = NULL;
3206	u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
3207	unsigned int xid;
3208	int rc;
3209	struct cifs_tcon *tcon;
3210	struct tcon_link *tlink = cifs_sb_tlink(cifs_sb);
3211	struct cifs_fid fid;
3212	struct cifs_open_parms oparms;
3213	__le16 *utf16_path;
3214
3215	cifs_dbg(FYI, "get smb3 acl for path %s\n", path);
3216	if (IS_ERR(tlink))
3217		return ERR_CAST(tlink);
3218
3219	tcon = tlink_tcon(tlink);
3220	xid = get_xid();
3221
3222	utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
3223	if (!utf16_path) {
3224		rc = -ENOMEM;
3225		goto put_tlink;
3226	}
3227
3228	oparms = (struct cifs_open_parms) {
3229		.tcon = tcon,
3230		.path = path,
3231		.desired_access = READ_CONTROL,
3232		.disposition = FILE_OPEN,
3233		/*
3234		 * When querying an ACL, even if the file is a symlink
3235		 * we want to open the source not the target, and so
3236		 * the protocol requires that the client specify this
3237		 * flag when opening a reparse point
3238		 */
3239		.create_options = cifs_create_options(cifs_sb, 0) |
3240				  OPEN_REPARSE_POINT,
3241		.fid = &fid,
3242	};
3243
3244	if (info & SACL_SECINFO)
3245		oparms.desired_access |= SYSTEM_SECURITY;
3246
3247	rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, NULL, NULL,
3248		       NULL);
3249	kfree(utf16_path);
3250	if (!rc) {
3251		rc = SMB2_query_acl(xid, tlink_tcon(tlink), fid.persistent_fid,
3252				    fid.volatile_fid, (void **)&pntsd, pacllen,
3253				    info);
3254		SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
3255	}
3256
3257put_tlink:
3258	cifs_put_tlink(tlink);
3259	free_xid(xid);
3260
3261	cifs_dbg(FYI, "%s: rc = %d ACL len %d\n", __func__, rc, *pacllen);
3262	if (rc)
3263		return ERR_PTR(rc);
3264	return pntsd;
3265}
3266
3267static int
3268set_smb2_acl(struct smb_ntsd *pnntsd, __u32 acllen,
3269		struct inode *inode, const char *path, int aclflag)
3270{
3271	u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
3272	unsigned int xid;
3273	int rc, access_flags = 0;
3274	struct cifs_tcon *tcon;
3275	struct cifs_sb_info *cifs_sb = CIFS_SB(inode->i_sb);
3276	struct tcon_link *tlink = cifs_sb_tlink(cifs_sb);
3277	struct cifs_fid fid;
3278	struct cifs_open_parms oparms;
3279	__le16 *utf16_path;
3280
3281	cifs_dbg(FYI, "set smb3 acl for path %s\n", path);
3282	if (IS_ERR(tlink))
3283		return PTR_ERR(tlink);
3284
3285	tcon = tlink_tcon(tlink);
3286	xid = get_xid();
3287
3288	if (aclflag & CIFS_ACL_OWNER || aclflag & CIFS_ACL_GROUP)
3289		access_flags |= WRITE_OWNER;
3290	if (aclflag & CIFS_ACL_SACL)
3291		access_flags |= SYSTEM_SECURITY;
3292	if (aclflag & CIFS_ACL_DACL)
3293		access_flags |= WRITE_DAC;
3294
3295	utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
3296	if (!utf16_path) {
3297		rc = -ENOMEM;
3298		goto put_tlink;
3299	}
3300
3301	oparms = (struct cifs_open_parms) {
3302		.tcon = tcon,
3303		.desired_access = access_flags,
3304		.create_options = cifs_create_options(cifs_sb, 0),
3305		.disposition = FILE_OPEN,
3306		.path = path,
3307		.fid = &fid,
3308	};
3309
3310	rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, NULL,
3311		       NULL, NULL);
3312	kfree(utf16_path);
3313	if (!rc) {
3314		rc = SMB2_set_acl(xid, tlink_tcon(tlink), fid.persistent_fid,
3315			    fid.volatile_fid, pnntsd, acllen, aclflag);
3316		SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
3317	}
3318
3319put_tlink:
3320	cifs_put_tlink(tlink);
3321	free_xid(xid);
3322	return rc;
3323}
3324
3325/* Retrieve an ACL from the server */
3326static struct smb_ntsd *
3327get_smb2_acl(struct cifs_sb_info *cifs_sb,
3328	     struct inode *inode, const char *path,
3329	     u32 *pacllen, u32 info)
3330{
3331	struct smb_ntsd *pntsd = NULL;
3332	struct cifsFileInfo *open_file = NULL;
3333
3334	if (inode && !(info & SACL_SECINFO))
3335		open_file = find_readable_file(CIFS_I(inode), true);
3336	if (!open_file || (info & SACL_SECINFO))
3337		return get_smb2_acl_by_path(cifs_sb, path, pacllen, info);
3338
3339	pntsd = get_smb2_acl_by_fid(cifs_sb, &open_file->fid, pacllen, info);
3340	cifsFileInfo_put(open_file);
3341	return pntsd;
3342}
3343
3344static long smb3_zero_data(struct file *file, struct cifs_tcon *tcon,
3345			     loff_t offset, loff_t len, unsigned int xid)
3346{
3347	struct cifsFileInfo *cfile = file->private_data;
3348	struct file_zero_data_information fsctl_buf;
3349
3350	cifs_dbg(FYI, "Offset %lld len %lld\n", offset, len);
3351
3352	fsctl_buf.FileOffset = cpu_to_le64(offset);
3353	fsctl_buf.BeyondFinalZero = cpu_to_le64(offset + len);
3354
3355	return SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
3356			  cfile->fid.volatile_fid, FSCTL_SET_ZERO_DATA,
3357			  (char *)&fsctl_buf,
3358			  sizeof(struct file_zero_data_information),
3359			  0, NULL, NULL);
3360}
3361
3362static long smb3_zero_range(struct file *file, struct cifs_tcon *tcon,
3363			    unsigned long long offset, unsigned long long len,
3364			    bool keep_size)
3365{
3366	struct cifs_ses *ses = tcon->ses;
3367	struct inode *inode = file_inode(file);
3368	struct cifsInodeInfo *cifsi = CIFS_I(inode);
3369	struct cifsFileInfo *cfile = file->private_data;
3370	struct netfs_inode *ictx = netfs_inode(inode);
3371	unsigned long long i_size, new_size, remote_size;
3372	long rc;
3373	unsigned int xid;
3374
3375	xid = get_xid();
3376
3377	trace_smb3_zero_enter(xid, cfile->fid.persistent_fid, tcon->tid,
3378			      ses->Suid, offset, len);
3379
3380	filemap_invalidate_lock(inode->i_mapping);
3381
3382	i_size = i_size_read(inode);
3383	remote_size = ictx->remote_i_size;
3384	if (offset + len >= remote_size && offset < i_size) {
3385		unsigned long long top = umin(offset + len, i_size);
3386
3387		rc = filemap_write_and_wait_range(inode->i_mapping, offset, top - 1);
3388		if (rc < 0)
3389			goto zero_range_exit;
3390	}
3391
3392	/*
3393	 * We zero the range through ioctl, so we need remove the page caches
3394	 * first, otherwise the data may be inconsistent with the server.
3395	 */
3396	truncate_pagecache_range(inode, offset, offset + len - 1);
3397	netfs_wait_for_outstanding_io(inode);
3398
3399	/* if file not oplocked can't be sure whether asking to extend size */
3400	rc = -EOPNOTSUPP;
3401	if (keep_size == false && !CIFS_CACHE_READ(cifsi))
3402		goto zero_range_exit;
3403
3404	rc = smb3_zero_data(file, tcon, offset, len, xid);
3405	if (rc < 0)
3406		goto zero_range_exit;
3407
3408	/*
3409	 * do we also need to change the size of the file?
3410	 */
3411	new_size = offset + len;
3412	if (keep_size == false && (unsigned long long)i_size_read(inode) < new_size) {
3413		rc = SMB2_set_eof(xid, tcon, cfile->fid.persistent_fid,
3414				  cfile->fid.volatile_fid, cfile->pid, new_size);
3415		if (rc >= 0) {
3416			truncate_setsize(inode, new_size);
3417			netfs_resize_file(&cifsi->netfs, new_size, true);
3418			if (offset < cifsi->netfs.zero_point)
3419				cifsi->netfs.zero_point = offset;
3420			fscache_resize_cookie(cifs_inode_cookie(inode), new_size);
3421		}
3422	}
3423
3424 zero_range_exit:
3425	filemap_invalidate_unlock(inode->i_mapping);
3426	free_xid(xid);
3427	if (rc)
3428		trace_smb3_zero_err(xid, cfile->fid.persistent_fid, tcon->tid,
3429			      ses->Suid, offset, len, rc);
3430	else
3431		trace_smb3_zero_done(xid, cfile->fid.persistent_fid, tcon->tid,
3432			      ses->Suid, offset, len);
3433	return rc;
3434}
3435
3436static long smb3_punch_hole(struct file *file, struct cifs_tcon *tcon,
3437			    loff_t offset, loff_t len)
3438{
3439	struct inode *inode = file_inode(file);
3440	struct cifsFileInfo *cfile = file->private_data;
3441	struct file_zero_data_information fsctl_buf;
3442	unsigned long long end = offset + len, i_size, remote_i_size;
3443	long rc;
3444	unsigned int xid;
3445	__u8 set_sparse = 1;
3446
3447	xid = get_xid();
3448
3449	/* Need to make file sparse, if not already, before freeing range. */
3450	/* Consider adding equivalent for compressed since it could also work */
3451	if (!smb2_set_sparse(xid, tcon, cfile, inode, set_sparse)) {
3452		rc = -EOPNOTSUPP;
3453		goto out;
3454	}
3455
3456	filemap_invalidate_lock(inode->i_mapping);
3457	/*
3458	 * We implement the punch hole through ioctl, so we need remove the page
3459	 * caches first, otherwise the data may be inconsistent with the server.
3460	 */
3461	truncate_pagecache_range(inode, offset, offset + len - 1);
3462	netfs_wait_for_outstanding_io(inode);
3463
3464	cifs_dbg(FYI, "Offset %lld len %lld\n", offset, len);
3465
3466	fsctl_buf.FileOffset = cpu_to_le64(offset);
3467	fsctl_buf.BeyondFinalZero = cpu_to_le64(offset + len);
3468
3469	rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
3470			cfile->fid.volatile_fid, FSCTL_SET_ZERO_DATA,
3471			(char *)&fsctl_buf,
3472			sizeof(struct file_zero_data_information),
3473			CIFSMaxBufSize, NULL, NULL);
3474
3475	if (rc)
3476		goto unlock;
3477
3478	/* If there's dirty data in the buffer that would extend the EOF if it
3479	 * were written, then we need to move the EOF marker over to the lower
3480	 * of the high end of the hole and the proposed EOF.  The problem is
3481	 * that we locally hole-punch the tail of the dirty data, the proposed
3482	 * EOF update will end up in the wrong place.
3483	 */
3484	i_size = i_size_read(inode);
3485	remote_i_size = netfs_inode(inode)->remote_i_size;
3486	if (end > remote_i_size && i_size > remote_i_size) {
3487		unsigned long long extend_to = umin(end, i_size);
3488		rc = SMB2_set_eof(xid, tcon, cfile->fid.persistent_fid,
3489				  cfile->fid.volatile_fid, cfile->pid, extend_to);
3490		if (rc >= 0)
3491			netfs_inode(inode)->remote_i_size = extend_to;
3492	}
3493
3494unlock:
3495	filemap_invalidate_unlock(inode->i_mapping);
3496out:
3497	free_xid(xid);
3498	return rc;
3499}
3500
3501static int smb3_simple_fallocate_write_range(unsigned int xid,
3502					     struct cifs_tcon *tcon,
3503					     struct cifsFileInfo *cfile,
3504					     loff_t off, loff_t len,
3505					     char *buf)
3506{
3507	struct cifs_io_parms io_parms = {0};
3508	int nbytes;
3509	int rc = 0;
3510	struct kvec iov[2];
3511
3512	io_parms.netfid = cfile->fid.netfid;
3513	io_parms.pid = current->tgid;
3514	io_parms.tcon = tcon;
3515	io_parms.persistent_fid = cfile->fid.persistent_fid;
3516	io_parms.volatile_fid = cfile->fid.volatile_fid;
3517
3518	while (len) {
3519		io_parms.offset = off;
3520		io_parms.length = len;
3521		if (io_parms.length > SMB2_MAX_BUFFER_SIZE)
3522			io_parms.length = SMB2_MAX_BUFFER_SIZE;
3523		/* iov[0] is reserved for smb header */
3524		iov[1].iov_base = buf;
3525		iov[1].iov_len = io_parms.length;
3526		rc = SMB2_write(xid, &io_parms, &nbytes, iov, 1);
3527		if (rc)
3528			break;
3529		if (nbytes > len)
3530			return -EINVAL;
3531		buf += nbytes;
3532		off += nbytes;
3533		len -= nbytes;
3534	}
3535	return rc;
3536}
3537
3538static int smb3_simple_fallocate_range(unsigned int xid,
3539				       struct cifs_tcon *tcon,
3540				       struct cifsFileInfo *cfile,
3541				       loff_t off, loff_t len)
3542{
3543	struct file_allocated_range_buffer in_data, *out_data = NULL, *tmp_data;
3544	u32 out_data_len;
3545	char *buf = NULL;
3546	loff_t l;
3547	int rc;
3548
3549	in_data.file_offset = cpu_to_le64(off);
3550	in_data.length = cpu_to_le64(len);
3551	rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
3552			cfile->fid.volatile_fid,
3553			FSCTL_QUERY_ALLOCATED_RANGES,
3554			(char *)&in_data, sizeof(in_data),
3555			1024 * sizeof(struct file_allocated_range_buffer),
3556			(char **)&out_data, &out_data_len);
3557	if (rc)
3558		goto out;
3559
3560	buf = kzalloc(1024 * 1024, GFP_KERNEL);
3561	if (buf == NULL) {
3562		rc = -ENOMEM;
3563		goto out;
3564	}
3565
3566	tmp_data = out_data;
3567	while (len) {
3568		/*
3569		 * The rest of the region is unmapped so write it all.
3570		 */
3571		if (out_data_len == 0) {
3572			rc = smb3_simple_fallocate_write_range(xid, tcon,
3573					       cfile, off, len, buf);
3574			goto out;
3575		}
3576
3577		if (out_data_len < sizeof(struct file_allocated_range_buffer)) {
3578			rc = -EINVAL;
3579			goto out;
3580		}
3581
3582		if (off < le64_to_cpu(tmp_data->file_offset)) {
3583			/*
3584			 * We are at a hole. Write until the end of the region
3585			 * or until the next allocated data,
3586			 * whichever comes next.
3587			 */
3588			l = le64_to_cpu(tmp_data->file_offset) - off;
3589			if (len < l)
3590				l = len;
3591			rc = smb3_simple_fallocate_write_range(xid, tcon,
3592					       cfile, off, l, buf);
3593			if (rc)
3594				goto out;
3595			off = off + l;
3596			len = len - l;
3597			if (len == 0)
3598				goto out;
3599		}
3600		/*
3601		 * We are at a section of allocated data, just skip forward
3602		 * until the end of the data or the end of the region
3603		 * we are supposed to fallocate, whichever comes first.
3604		 */
3605		l = le64_to_cpu(tmp_data->length);
3606		if (len < l)
3607			l = len;
3608		off += l;
3609		len -= l;
3610
3611		tmp_data = &tmp_data[1];
3612		out_data_len -= sizeof(struct file_allocated_range_buffer);
3613	}
3614
3615 out:
3616	kfree(out_data);
3617	kfree(buf);
3618	return rc;
3619}
3620
3621
3622static long smb3_simple_falloc(struct file *file, struct cifs_tcon *tcon,
3623			    loff_t off, loff_t len, bool keep_size)
3624{
3625	struct inode *inode;
3626	struct cifsInodeInfo *cifsi;
3627	struct cifsFileInfo *cfile = file->private_data;
3628	long rc = -EOPNOTSUPP;
3629	unsigned int xid;
3630	loff_t new_eof;
3631
3632	xid = get_xid();
3633
3634	inode = d_inode(cfile->dentry);
3635	cifsi = CIFS_I(inode);
3636
3637	trace_smb3_falloc_enter(xid, cfile->fid.persistent_fid, tcon->tid,
3638				tcon->ses->Suid, off, len);
3639	/* if file not oplocked can't be sure whether asking to extend size */
3640	if (!CIFS_CACHE_READ(cifsi))
3641		if (keep_size == false) {
3642			trace_smb3_falloc_err(xid, cfile->fid.persistent_fid,
3643				tcon->tid, tcon->ses->Suid, off, len, rc);
3644			free_xid(xid);
3645			return rc;
3646		}
3647
3648	/*
3649	 * Extending the file
3650	 */
3651	if ((keep_size == false) && i_size_read(inode) < off + len) {
3652		rc = inode_newsize_ok(inode, off + len);
3653		if (rc)
3654			goto out;
3655
3656		if (cifsi->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE)
3657			smb2_set_sparse(xid, tcon, cfile, inode, false);
3658
3659		new_eof = off + len;
3660		rc = SMB2_set_eof(xid, tcon, cfile->fid.persistent_fid,
3661				  cfile->fid.volatile_fid, cfile->pid, new_eof);
3662		if (rc == 0) {
3663			netfs_resize_file(&cifsi->netfs, new_eof, true);
3664			cifs_setsize(inode, new_eof);
3665		}
3666		goto out;
3667	}
3668
3669	/*
3670	 * Files are non-sparse by default so falloc may be a no-op
3671	 * Must check if file sparse. If not sparse, and since we are not
3672	 * extending then no need to do anything since file already allocated
3673	 */
3674	if ((cifsi->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE) == 0) {
3675		rc = 0;
3676		goto out;
3677	}
3678
3679	if (keep_size == true) {
3680		/*
3681		 * We can not preallocate pages beyond the end of the file
3682		 * in SMB2
3683		 */
3684		if (off >= i_size_read(inode)) {
3685			rc = 0;
3686			goto out;
3687		}
3688		/*
3689		 * For fallocates that are partially beyond the end of file,
3690		 * clamp len so we only fallocate up to the end of file.
3691		 */
3692		if (off + len > i_size_read(inode)) {
3693			len = i_size_read(inode) - off;
3694		}
3695	}
3696
3697	if ((keep_size == true) || (i_size_read(inode) >= off + len)) {
3698		/*
3699		 * At this point, we are trying to fallocate an internal
3700		 * regions of a sparse file. Since smb2 does not have a
3701		 * fallocate command we have two options on how to emulate this.
3702		 * We can either turn the entire file to become non-sparse
3703		 * which we only do if the fallocate is for virtually
3704		 * the whole file,  or we can overwrite the region with zeroes
3705		 * using SMB2_write, which could be prohibitevly expensive
3706		 * if len is large.
3707		 */
3708		/*
3709		 * We are only trying to fallocate a small region so
3710		 * just write it with zero.
3711		 */
3712		if (len <= 1024 * 1024) {
3713			rc = smb3_simple_fallocate_range(xid, tcon, cfile,
3714							 off, len);
3715			goto out;
3716		}
3717
3718		/*
3719		 * Check if falloc starts within first few pages of file
3720		 * and ends within a few pages of the end of file to
3721		 * ensure that most of file is being forced to be
3722		 * fallocated now. If so then setting whole file sparse
3723		 * ie potentially making a few extra pages at the beginning
3724		 * or end of the file non-sparse via set_sparse is harmless.
3725		 */
3726		if ((off > 8192) || (off + len + 8192 < i_size_read(inode))) {
3727			rc = -EOPNOTSUPP;
3728			goto out;
3729		}
3730	}
3731
3732	smb2_set_sparse(xid, tcon, cfile, inode, false);
3733	rc = 0;
3734
3735out:
3736	if (rc)
3737		trace_smb3_falloc_err(xid, cfile->fid.persistent_fid, tcon->tid,
3738				tcon->ses->Suid, off, len, rc);
3739	else
3740		trace_smb3_falloc_done(xid, cfile->fid.persistent_fid, tcon->tid,
3741				tcon->ses->Suid, off, len);
3742
3743	free_xid(xid);
3744	return rc;
3745}
3746
3747static long smb3_collapse_range(struct file *file, struct cifs_tcon *tcon,
3748			    loff_t off, loff_t len)
3749{
3750	int rc;
3751	unsigned int xid;
3752	struct inode *inode = file_inode(file);
3753	struct cifsInodeInfo *cifsi = CIFS_I(inode);
3754	struct cifsFileInfo *cfile = file->private_data;
3755	struct netfs_inode *ictx = &cifsi->netfs;
3756	loff_t old_eof, new_eof;
3757
3758	xid = get_xid();
3759
3760	old_eof = i_size_read(inode);
3761	if ((off >= old_eof) ||
3762	    off + len >= old_eof) {
3763		rc = -EINVAL;
3764		goto out;
3765	}
3766
3767	filemap_invalidate_lock(inode->i_mapping);
3768	rc = filemap_write_and_wait_range(inode->i_mapping, off, old_eof - 1);
3769	if (rc < 0)
3770		goto out_2;
3771
3772	truncate_pagecache_range(inode, off, old_eof);
3773	ictx->zero_point = old_eof;
3774	netfs_wait_for_outstanding_io(inode);
3775
3776	rc = smb2_copychunk_range(xid, cfile, cfile, off + len,
3777				  old_eof - off - len, off);
3778	if (rc < 0)
3779		goto out_2;
3780
3781	new_eof = old_eof - len;
3782	rc = SMB2_set_eof(xid, tcon, cfile->fid.persistent_fid,
3783			  cfile->fid.volatile_fid, cfile->pid, new_eof);
3784	if (rc < 0)
3785		goto out_2;
3786
3787	rc = 0;
3788
3789	truncate_setsize(inode, new_eof);
3790	netfs_resize_file(&cifsi->netfs, new_eof, true);
3791	ictx->zero_point = new_eof;
3792	fscache_resize_cookie(cifs_inode_cookie(inode), new_eof);
3793out_2:
3794	filemap_invalidate_unlock(inode->i_mapping);
3795out:
3796	free_xid(xid);
3797	return rc;
3798}
3799
3800static long smb3_insert_range(struct file *file, struct cifs_tcon *tcon,
3801			      loff_t off, loff_t len)
3802{
3803	int rc;
3804	unsigned int xid;
3805	struct cifsFileInfo *cfile = file->private_data;
3806	struct inode *inode = file_inode(file);
3807	struct cifsInodeInfo *cifsi = CIFS_I(inode);
3808	__u64 count, old_eof, new_eof;
3809
3810	xid = get_xid();
3811
3812	old_eof = i_size_read(inode);
3813	if (off >= old_eof) {
3814		rc = -EINVAL;
3815		goto out;
3816	}
3817
3818	count = old_eof - off;
3819	new_eof = old_eof + len;
3820
3821	filemap_invalidate_lock(inode->i_mapping);
3822	rc = filemap_write_and_wait_range(inode->i_mapping, off, new_eof - 1);
3823	if (rc < 0)
3824		goto out_2;
3825	truncate_pagecache_range(inode, off, old_eof);
3826	netfs_wait_for_outstanding_io(inode);
3827
3828	rc = SMB2_set_eof(xid, tcon, cfile->fid.persistent_fid,
3829			  cfile->fid.volatile_fid, cfile->pid, new_eof);
3830	if (rc < 0)
3831		goto out_2;
3832
3833	truncate_setsize(inode, new_eof);
3834	netfs_resize_file(&cifsi->netfs, i_size_read(inode), true);
3835	fscache_resize_cookie(cifs_inode_cookie(inode), i_size_read(inode));
3836
3837	rc = smb2_copychunk_range(xid, cfile, cfile, off, count, off + len);
3838	if (rc < 0)
3839		goto out_2;
3840	cifsi->netfs.zero_point = new_eof;
3841
3842	rc = smb3_zero_data(file, tcon, off, len, xid);
3843	if (rc < 0)
3844		goto out_2;
3845
3846	rc = 0;
3847out_2:
3848	filemap_invalidate_unlock(inode->i_mapping);
3849out:
3850	free_xid(xid);
3851	return rc;
3852}
3853
3854static loff_t smb3_llseek(struct file *file, struct cifs_tcon *tcon, loff_t offset, int whence)
3855{
3856	struct cifsFileInfo *wrcfile, *cfile = file->private_data;
3857	struct cifsInodeInfo *cifsi;
3858	struct inode *inode;
3859	int rc = 0;
3860	struct file_allocated_range_buffer in_data, *out_data = NULL;
3861	u32 out_data_len;
3862	unsigned int xid;
3863
3864	if (whence != SEEK_HOLE && whence != SEEK_DATA)
3865		return generic_file_llseek(file, offset, whence);
3866
3867	inode = d_inode(cfile->dentry);
3868	cifsi = CIFS_I(inode);
3869
3870	if (offset < 0 || offset >= i_size_read(inode))
3871		return -ENXIO;
3872
3873	xid = get_xid();
3874	/*
3875	 * We need to be sure that all dirty pages are written as they
3876	 * might fill holes on the server.
3877	 * Note that we also MUST flush any written pages since at least
3878	 * some servers (Windows2016) will not reflect recent writes in
3879	 * QUERY_ALLOCATED_RANGES until SMB2_flush is called.
3880	 */
3881	wrcfile = find_writable_file(cifsi, FIND_WR_ANY);
3882	if (wrcfile) {
3883		filemap_write_and_wait(inode->i_mapping);
3884		smb2_flush_file(xid, tcon, &wrcfile->fid);
3885		cifsFileInfo_put(wrcfile);
3886	}
3887
3888	if (!(cifsi->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE)) {
3889		if (whence == SEEK_HOLE)
3890			offset = i_size_read(inode);
3891		goto lseek_exit;
3892	}
3893
3894	in_data.file_offset = cpu_to_le64(offset);
3895	in_data.length = cpu_to_le64(i_size_read(inode));
3896
3897	rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
3898			cfile->fid.volatile_fid,
3899			FSCTL_QUERY_ALLOCATED_RANGES,
3900			(char *)&in_data, sizeof(in_data),
3901			sizeof(struct file_allocated_range_buffer),
3902			(char **)&out_data, &out_data_len);
3903	if (rc == -E2BIG)
3904		rc = 0;
3905	if (rc)
3906		goto lseek_exit;
3907
3908	if (whence == SEEK_HOLE && out_data_len == 0)
3909		goto lseek_exit;
3910
3911	if (whence == SEEK_DATA && out_data_len == 0) {
3912		rc = -ENXIO;
3913		goto lseek_exit;
3914	}
3915
3916	if (out_data_len < sizeof(struct file_allocated_range_buffer)) {
3917		rc = -EINVAL;
3918		goto lseek_exit;
3919	}
3920	if (whence == SEEK_DATA) {
3921		offset = le64_to_cpu(out_data->file_offset);
3922		goto lseek_exit;
3923	}
3924	if (offset < le64_to_cpu(out_data->file_offset))
3925		goto lseek_exit;
3926
3927	offset = le64_to_cpu(out_data->file_offset) + le64_to_cpu(out_data->length);
3928
3929 lseek_exit:
3930	free_xid(xid);
3931	kfree(out_data);
3932	if (!rc)
3933		return vfs_setpos(file, offset, inode->i_sb->s_maxbytes);
3934	else
3935		return rc;
3936}
3937
3938static int smb3_fiemap(struct cifs_tcon *tcon,
3939		       struct cifsFileInfo *cfile,
3940		       struct fiemap_extent_info *fei, u64 start, u64 len)
3941{
3942	unsigned int xid;
3943	struct file_allocated_range_buffer in_data, *out_data;
3944	u32 out_data_len;
3945	int i, num, rc, flags, last_blob;
3946	u64 next;
3947
3948	rc = fiemap_prep(d_inode(cfile->dentry), fei, start, &len, 0);
3949	if (rc)
3950		return rc;
3951
3952	xid = get_xid();
3953 again:
3954	in_data.file_offset = cpu_to_le64(start);
3955	in_data.length = cpu_to_le64(len);
3956
3957	rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
3958			cfile->fid.volatile_fid,
3959			FSCTL_QUERY_ALLOCATED_RANGES,
3960			(char *)&in_data, sizeof(in_data),
3961			1024 * sizeof(struct file_allocated_range_buffer),
3962			(char **)&out_data, &out_data_len);
3963	if (rc == -E2BIG) {
3964		last_blob = 0;
3965		rc = 0;
3966	} else
3967		last_blob = 1;
3968	if (rc)
3969		goto out;
3970
3971	if (out_data_len && out_data_len < sizeof(struct file_allocated_range_buffer)) {
3972		rc = -EINVAL;
3973		goto out;
3974	}
3975	if (out_data_len % sizeof(struct file_allocated_range_buffer)) {
3976		rc = -EINVAL;
3977		goto out;
3978	}
3979
3980	num = out_data_len / sizeof(struct file_allocated_range_buffer);
3981	for (i = 0; i < num; i++) {
3982		flags = 0;
3983		if (i == num - 1 && last_blob)
3984			flags |= FIEMAP_EXTENT_LAST;
3985
3986		rc = fiemap_fill_next_extent(fei,
3987				le64_to_cpu(out_data[i].file_offset),
3988				le64_to_cpu(out_data[i].file_offset),
3989				le64_to_cpu(out_data[i].length),
3990				flags);
3991		if (rc < 0)
3992			goto out;
3993		if (rc == 1) {
3994			rc = 0;
3995			goto out;
3996		}
3997	}
3998
3999	if (!last_blob) {
4000		next = le64_to_cpu(out_data[num - 1].file_offset) +
4001		  le64_to_cpu(out_data[num - 1].length);
4002		len = len - (next - start);
4003		start = next;
4004		goto again;
4005	}
4006
4007 out:
4008	free_xid(xid);
4009	kfree(out_data);
4010	return rc;
4011}
4012
4013static long smb3_fallocate(struct file *file, struct cifs_tcon *tcon, int mode,
4014			   loff_t off, loff_t len)
4015{
4016	/* KEEP_SIZE already checked for by do_fallocate */
4017	if (mode & FALLOC_FL_PUNCH_HOLE)
4018		return smb3_punch_hole(file, tcon, off, len);
4019	else if (mode & FALLOC_FL_ZERO_RANGE) {
4020		if (mode & FALLOC_FL_KEEP_SIZE)
4021			return smb3_zero_range(file, tcon, off, len, true);
4022		return smb3_zero_range(file, tcon, off, len, false);
4023	} else if (mode == FALLOC_FL_KEEP_SIZE)
4024		return smb3_simple_falloc(file, tcon, off, len, true);
4025	else if (mode == FALLOC_FL_COLLAPSE_RANGE)
4026		return smb3_collapse_range(file, tcon, off, len);
4027	else if (mode == FALLOC_FL_INSERT_RANGE)
4028		return smb3_insert_range(file, tcon, off, len);
4029	else if (mode == 0)
4030		return smb3_simple_falloc(file, tcon, off, len, false);
4031
4032	return -EOPNOTSUPP;
4033}
4034
4035static void
4036smb2_downgrade_oplock(struct TCP_Server_Info *server,
4037		      struct cifsInodeInfo *cinode, __u32 oplock,
4038		      __u16 epoch, bool *purge_cache)
4039{
4040	server->ops->set_oplock_level(cinode, oplock, 0, NULL);
4041}
4042
4043static void
4044smb21_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
4045		       __u16 epoch, bool *purge_cache);
4046
4047static void
4048smb3_downgrade_oplock(struct TCP_Server_Info *server,
4049		       struct cifsInodeInfo *cinode, __u32 oplock,
4050		       __u16 epoch, bool *purge_cache)
4051{
4052	unsigned int old_state = cinode->oplock;
4053	__u16 old_epoch = cinode->epoch;
4054	unsigned int new_state;
4055
4056	if (epoch > old_epoch) {
4057		smb21_set_oplock_level(cinode, oplock, 0, NULL);
4058		cinode->epoch = epoch;
4059	}
4060
4061	new_state = cinode->oplock;
4062	*purge_cache = false;
4063
4064	if ((old_state & CIFS_CACHE_READ_FLG) != 0 &&
4065	    (new_state & CIFS_CACHE_READ_FLG) == 0)
4066		*purge_cache = true;
4067	else if (old_state == new_state && (epoch - old_epoch > 1))
4068		*purge_cache = true;
4069}
4070
4071static void
4072smb2_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
4073		      __u16 epoch, bool *purge_cache)
4074{
4075	oplock &= 0xFF;
4076	cinode->lease_granted = false;
4077	if (oplock == SMB2_OPLOCK_LEVEL_NOCHANGE)
4078		return;
4079	if (oplock == SMB2_OPLOCK_LEVEL_BATCH) {
4080		cinode->oplock = CIFS_CACHE_RHW_FLG;
4081		cifs_dbg(FYI, "Batch Oplock granted on inode %p\n",
4082			 &cinode->netfs.inode);
4083	} else if (oplock == SMB2_OPLOCK_LEVEL_EXCLUSIVE) {
4084		cinode->oplock = CIFS_CACHE_RW_FLG;
4085		cifs_dbg(FYI, "Exclusive Oplock granted on inode %p\n",
4086			 &cinode->netfs.inode);
4087	} else if (oplock == SMB2_OPLOCK_LEVEL_II) {
4088		cinode->oplock = CIFS_CACHE_READ_FLG;
4089		cifs_dbg(FYI, "Level II Oplock granted on inode %p\n",
4090			 &cinode->netfs.inode);
4091	} else
4092		cinode->oplock = 0;
4093}
4094
4095static void
4096smb21_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
4097		       __u16 epoch, bool *purge_cache)
4098{
4099	char message[5] = {0};
4100	unsigned int new_oplock = 0;
4101
4102	oplock &= 0xFF;
4103	cinode->lease_granted = true;
4104	if (oplock == SMB2_OPLOCK_LEVEL_NOCHANGE)
4105		return;
4106
4107	/* Check if the server granted an oplock rather than a lease */
4108	if (oplock & SMB2_OPLOCK_LEVEL_EXCLUSIVE)
4109		return smb2_set_oplock_level(cinode, oplock, epoch,
4110					     purge_cache);
4111
4112	if (oplock & SMB2_LEASE_READ_CACHING_HE) {
4113		new_oplock |= CIFS_CACHE_READ_FLG;
4114		strcat(message, "R");
4115	}
4116	if (oplock & SMB2_LEASE_HANDLE_CACHING_HE) {
4117		new_oplock |= CIFS_CACHE_HANDLE_FLG;
4118		strcat(message, "H");
4119	}
4120	if (oplock & SMB2_LEASE_WRITE_CACHING_HE) {
4121		new_oplock |= CIFS_CACHE_WRITE_FLG;
4122		strcat(message, "W");
4123	}
4124	if (!new_oplock)
4125		strscpy(message, "None");
4126
4127	cinode->oplock = new_oplock;
4128	cifs_dbg(FYI, "%s Lease granted on inode %p\n", message,
4129		 &cinode->netfs.inode);
4130}
4131
4132static void
4133smb3_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
4134		      __u16 epoch, bool *purge_cache)
4135{
4136	unsigned int old_oplock = cinode->oplock;
4137
4138	smb21_set_oplock_level(cinode, oplock, epoch, purge_cache);
4139
4140	if (purge_cache) {
4141		*purge_cache = false;
4142		if (old_oplock == CIFS_CACHE_READ_FLG) {
4143			if (cinode->oplock == CIFS_CACHE_READ_FLG &&
4144			    (epoch - cinode->epoch > 0))
4145				*purge_cache = true;
4146			else if (cinode->oplock == CIFS_CACHE_RH_FLG &&
4147				 (epoch - cinode->epoch > 1))
4148				*purge_cache = true;
4149			else if (cinode->oplock == CIFS_CACHE_RHW_FLG &&
4150				 (epoch - cinode->epoch > 1))
4151				*purge_cache = true;
4152			else if (cinode->oplock == 0 &&
4153				 (epoch - cinode->epoch > 0))
4154				*purge_cache = true;
4155		} else if (old_oplock == CIFS_CACHE_RH_FLG) {
4156			if (cinode->oplock == CIFS_CACHE_RH_FLG &&
4157			    (epoch - cinode->epoch > 0))
4158				*purge_cache = true;
4159			else if (cinode->oplock == CIFS_CACHE_RHW_FLG &&
4160				 (epoch - cinode->epoch > 1))
4161				*purge_cache = true;
4162		}
4163		cinode->epoch = epoch;
4164	}
4165}
4166
4167#ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
4168static bool
4169smb2_is_read_op(__u32 oplock)
4170{
4171	return oplock == SMB2_OPLOCK_LEVEL_II;
4172}
4173#endif /* CIFS_ALLOW_INSECURE_LEGACY */
4174
4175static bool
4176smb21_is_read_op(__u32 oplock)
4177{
4178	return (oplock & SMB2_LEASE_READ_CACHING_HE) &&
4179	       !(oplock & SMB2_LEASE_WRITE_CACHING_HE);
4180}
4181
4182static __le32
4183map_oplock_to_lease(u8 oplock)
4184{
4185	if (oplock == SMB2_OPLOCK_LEVEL_EXCLUSIVE)
4186		return SMB2_LEASE_WRITE_CACHING_LE | SMB2_LEASE_READ_CACHING_LE;
4187	else if (oplock == SMB2_OPLOCK_LEVEL_II)
4188		return SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE;
4189	else if (oplock == SMB2_OPLOCK_LEVEL_BATCH)
4190		return SMB2_LEASE_HANDLE_CACHING_LE | SMB2_LEASE_READ_CACHING_LE |
4191		       SMB2_LEASE_WRITE_CACHING_LE;
4192	return 0;
4193}
4194
4195static char *
4196smb2_create_lease_buf(u8 *lease_key, u8 oplock, u8 *parent_lease_key, __le32 flags)
4197{
4198	struct create_lease *buf;
4199
4200	buf = kzalloc(sizeof(struct create_lease), GFP_KERNEL);
4201	if (!buf)
4202		return NULL;
4203
4204	memcpy(&buf->lcontext.LeaseKey, lease_key, SMB2_LEASE_KEY_SIZE);
4205	buf->lcontext.LeaseState = map_oplock_to_lease(oplock);
4206
4207	buf->ccontext.DataOffset = cpu_to_le16(offsetof
4208					(struct create_lease, lcontext));
4209	buf->ccontext.DataLength = cpu_to_le32(sizeof(struct lease_context));
4210	buf->ccontext.NameOffset = cpu_to_le16(offsetof
4211				(struct create_lease, Name));
4212	buf->ccontext.NameLength = cpu_to_le16(4);
4213	/* SMB2_CREATE_REQUEST_LEASE is "RqLs" */
4214	buf->Name[0] = 'R';
4215	buf->Name[1] = 'q';
4216	buf->Name[2] = 'L';
4217	buf->Name[3] = 's';
4218	return (char *)buf;
4219}
4220
4221static char *
4222smb3_create_lease_buf(u8 *lease_key, u8 oplock, u8 *parent_lease_key, __le32 flags)
4223{
4224	struct create_lease_v2 *buf;
4225
4226	buf = kzalloc(sizeof(struct create_lease_v2), GFP_KERNEL);
4227	if (!buf)
4228		return NULL;
4229
4230	memcpy(&buf->lcontext.LeaseKey, lease_key, SMB2_LEASE_KEY_SIZE);
4231	buf->lcontext.LeaseState = map_oplock_to_lease(oplock);
4232	buf->lcontext.LeaseFlags = flags;
4233	if (flags & SMB2_LEASE_FLAG_PARENT_LEASE_KEY_SET_LE)
4234		memcpy(&buf->lcontext.ParentLeaseKey, parent_lease_key, SMB2_LEASE_KEY_SIZE);
4235
4236	buf->ccontext.DataOffset = cpu_to_le16(offsetof
4237					(struct create_lease_v2, lcontext));
4238	buf->ccontext.DataLength = cpu_to_le32(sizeof(struct lease_context_v2));
4239	buf->ccontext.NameOffset = cpu_to_le16(offsetof
4240				(struct create_lease_v2, Name));
4241	buf->ccontext.NameLength = cpu_to_le16(4);
4242	/* SMB2_CREATE_REQUEST_LEASE is "RqLs" */
4243	buf->Name[0] = 'R';
4244	buf->Name[1] = 'q';
4245	buf->Name[2] = 'L';
4246	buf->Name[3] = 's';
4247	return (char *)buf;
4248}
4249
4250static __u8
4251smb2_parse_lease_buf(void *buf, __u16 *epoch, char *lease_key)
4252{
4253	struct create_lease *lc = (struct create_lease *)buf;
4254
4255	*epoch = 0; /* not used */
4256	if (lc->lcontext.LeaseFlags & SMB2_LEASE_FLAG_BREAK_IN_PROGRESS_LE)
4257		return SMB2_OPLOCK_LEVEL_NOCHANGE;
4258	return le32_to_cpu(lc->lcontext.LeaseState);
4259}
4260
4261static __u8
4262smb3_parse_lease_buf(void *buf, __u16 *epoch, char *lease_key)
4263{
4264	struct create_lease_v2 *lc = (struct create_lease_v2 *)buf;
4265
4266	*epoch = le16_to_cpu(lc->lcontext.Epoch);
4267	if (lc->lcontext.LeaseFlags & SMB2_LEASE_FLAG_BREAK_IN_PROGRESS_LE)
4268		return SMB2_OPLOCK_LEVEL_NOCHANGE;
4269	if (lease_key)
4270		memcpy(lease_key, &lc->lcontext.LeaseKey, SMB2_LEASE_KEY_SIZE);
4271	return le32_to_cpu(lc->lcontext.LeaseState);
4272}
4273
4274static unsigned int
4275smb2_wp_retry_size(struct inode *inode)
4276{
4277	return min_t(unsigned int, CIFS_SB(inode->i_sb)->ctx->wsize,
4278		     SMB2_MAX_BUFFER_SIZE);
4279}
4280
4281static bool
4282smb2_dir_needs_close(struct cifsFileInfo *cfile)
4283{
4284	return !cfile->invalidHandle;
4285}
4286
4287static void
4288fill_transform_hdr(struct smb2_transform_hdr *tr_hdr, unsigned int orig_len,
4289		   struct smb_rqst *old_rq, __le16 cipher_type)
4290{
4291	struct smb2_hdr *shdr =
4292			(struct smb2_hdr *)old_rq->rq_iov[0].iov_base;
4293
4294	memset(tr_hdr, 0, sizeof(struct smb2_transform_hdr));
4295	tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
4296	tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
4297	tr_hdr->Flags = cpu_to_le16(0x01);
4298	if ((cipher_type == SMB2_ENCRYPTION_AES128_GCM) ||
4299	    (cipher_type == SMB2_ENCRYPTION_AES256_GCM))
4300		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
4301	else
4302		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
4303	memcpy(&tr_hdr->SessionId, &shdr->SessionId, 8);
4304}
4305
4306static void *smb2_aead_req_alloc(struct crypto_aead *tfm, const struct smb_rqst *rqst,
4307				 int num_rqst, const u8 *sig, u8 **iv,
4308				 struct aead_request **req, struct sg_table *sgt,
4309				 unsigned int *num_sgs)
4310{
4311	unsigned int req_size = sizeof(**req) + crypto_aead_reqsize(tfm);
4312	unsigned int iv_size = crypto_aead_ivsize(tfm);
4313	unsigned int len;
4314	u8 *p;
4315
4316	*num_sgs = cifs_get_num_sgs(rqst, num_rqst, sig);
4317	if (IS_ERR_VALUE((long)(int)*num_sgs))
4318		return ERR_PTR(*num_sgs);
4319
4320	len = iv_size;
4321	len += crypto_aead_alignmask(tfm) & ~(crypto_tfm_ctx_alignment() - 1);
4322	len = ALIGN(len, crypto_tfm_ctx_alignment());
4323	len += req_size;
4324	len = ALIGN(len, __alignof__(struct scatterlist));
4325	len += array_size(*num_sgs, sizeof(struct scatterlist));
4326
4327	p = kzalloc(len, GFP_NOFS);
4328	if (!p)
4329		return ERR_PTR(-ENOMEM);
4330
4331	*iv = (u8 *)PTR_ALIGN(p, crypto_aead_alignmask(tfm) + 1);
4332	*req = (struct aead_request *)PTR_ALIGN(*iv + iv_size,
4333						crypto_tfm_ctx_alignment());
4334	sgt->sgl = (struct scatterlist *)PTR_ALIGN((u8 *)*req + req_size,
4335						   __alignof__(struct scatterlist));
4336	return p;
4337}
4338
4339static void *smb2_get_aead_req(struct crypto_aead *tfm, struct smb_rqst *rqst,
4340			       int num_rqst, const u8 *sig, u8 **iv,
4341			       struct aead_request **req, struct scatterlist **sgl)
4342{
4343	struct sg_table sgtable = {};
4344	unsigned int skip, num_sgs, i, j;
4345	ssize_t rc;
4346	void *p;
4347
4348	p = smb2_aead_req_alloc(tfm, rqst, num_rqst, sig, iv, req, &sgtable, &num_sgs);
4349	if (IS_ERR(p))
4350		return ERR_CAST(p);
4351
4352	sg_init_marker(sgtable.sgl, num_sgs);
4353
4354	/*
4355	 * The first rqst has a transform header where the
4356	 * first 20 bytes are not part of the encrypted blob.
4357	 */
4358	skip = 20;
4359
4360	for (i = 0; i < num_rqst; i++) {
4361		struct iov_iter *iter = &rqst[i].rq_iter;
4362		size_t count = iov_iter_count(iter);
4363
4364		for (j = 0; j < rqst[i].rq_nvec; j++) {
4365			cifs_sg_set_buf(&sgtable,
4366					rqst[i].rq_iov[j].iov_base + skip,
4367					rqst[i].rq_iov[j].iov_len - skip);
4368
4369			/* See the above comment on the 'skip' assignment */
4370			skip = 0;
4371		}
4372		sgtable.orig_nents = sgtable.nents;
4373
4374		rc = extract_iter_to_sg(iter, count, &sgtable,
4375					num_sgs - sgtable.nents, 0);
4376		iov_iter_revert(iter, rc);
4377		sgtable.orig_nents = sgtable.nents;
4378	}
4379
4380	cifs_sg_set_buf(&sgtable, sig, SMB2_SIGNATURE_SIZE);
4381	sg_mark_end(&sgtable.sgl[sgtable.nents - 1]);
4382	*sgl = sgtable.sgl;
4383	return p;
4384}
4385
4386static int
4387smb2_get_enc_key(struct TCP_Server_Info *server, __u64 ses_id, int enc, u8 *key)
4388{
4389	struct TCP_Server_Info *pserver;
4390	struct cifs_ses *ses;
4391	u8 *ses_enc_key;
4392
4393	/* If server is a channel, select the primary channel */
4394	pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
4395
4396	spin_lock(&cifs_tcp_ses_lock);
4397	list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
4398		if (ses->Suid == ses_id) {
4399			spin_lock(&ses->ses_lock);
4400			ses_enc_key = enc ? ses->smb3encryptionkey :
4401				ses->smb3decryptionkey;
4402			memcpy(key, ses_enc_key, SMB3_ENC_DEC_KEY_SIZE);
4403			spin_unlock(&ses->ses_lock);
4404			spin_unlock(&cifs_tcp_ses_lock);
4405			return 0;
4406		}
4407	}
4408	spin_unlock(&cifs_tcp_ses_lock);
4409
4410	trace_smb3_ses_not_found(ses_id);
4411
4412	return -EAGAIN;
4413}
4414/*
4415 * Encrypt or decrypt @rqst message. @rqst[0] has the following format:
4416 * iov[0]   - transform header (associate data),
4417 * iov[1-N] - SMB2 header and pages - data to encrypt.
4418 * On success return encrypted data in iov[1-N] and pages, leave iov[0]
4419 * untouched.
4420 */
4421static int
4422crypt_message(struct TCP_Server_Info *server, int num_rqst,
4423	      struct smb_rqst *rqst, int enc, struct crypto_aead *tfm)
4424{
4425	struct smb2_transform_hdr *tr_hdr =
4426		(struct smb2_transform_hdr *)rqst[0].rq_iov[0].iov_base;
4427	unsigned int assoc_data_len = sizeof(struct smb2_transform_hdr) - 20;
4428	int rc = 0;
4429	struct scatterlist *sg;
4430	u8 sign[SMB2_SIGNATURE_SIZE] = {};
4431	u8 key[SMB3_ENC_DEC_KEY_SIZE];
4432	struct aead_request *req;
4433	u8 *iv;
4434	DECLARE_CRYPTO_WAIT(wait);
4435	unsigned int crypt_len = le32_to_cpu(tr_hdr->OriginalMessageSize);
4436	void *creq;
4437
4438	rc = smb2_get_enc_key(server, le64_to_cpu(tr_hdr->SessionId), enc, key);
4439	if (rc) {
4440		cifs_server_dbg(FYI, "%s: Could not get %scryption key. sid: 0x%llx\n", __func__,
4441			 enc ? "en" : "de", le64_to_cpu(tr_hdr->SessionId));
4442		return rc;
4443	}
4444
4445	if ((server->cipher_type == SMB2_ENCRYPTION_AES256_CCM) ||
4446		(server->cipher_type == SMB2_ENCRYPTION_AES256_GCM))
4447		rc = crypto_aead_setkey(tfm, key, SMB3_GCM256_CRYPTKEY_SIZE);
4448	else
4449		rc = crypto_aead_setkey(tfm, key, SMB3_GCM128_CRYPTKEY_SIZE);
4450
4451	if (rc) {
4452		cifs_server_dbg(VFS, "%s: Failed to set aead key %d\n", __func__, rc);
4453		return rc;
4454	}
4455
4456	rc = crypto_aead_setauthsize(tfm, SMB2_SIGNATURE_SIZE);
4457	if (rc) {
4458		cifs_server_dbg(VFS, "%s: Failed to set authsize %d\n", __func__, rc);
4459		return rc;
4460	}
4461
4462	creq = smb2_get_aead_req(tfm, rqst, num_rqst, sign, &iv, &req, &sg);
4463	if (IS_ERR(creq))
4464		return PTR_ERR(creq);
4465
4466	if (!enc) {
4467		memcpy(sign, &tr_hdr->Signature, SMB2_SIGNATURE_SIZE);
4468		crypt_len += SMB2_SIGNATURE_SIZE;
4469	}
4470
4471	if ((server->cipher_type == SMB2_ENCRYPTION_AES128_GCM) ||
4472	    (server->cipher_type == SMB2_ENCRYPTION_AES256_GCM))
4473		memcpy(iv, (char *)tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
4474	else {
4475		iv[0] = 3;
4476		memcpy(iv + 1, (char *)tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
4477	}
4478
4479	aead_request_set_tfm(req, tfm);
4480	aead_request_set_crypt(req, sg, sg, crypt_len, iv);
4481	aead_request_set_ad(req, assoc_data_len);
4482
4483	aead_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
4484				  crypto_req_done, &wait);
4485
4486	rc = crypto_wait_req(enc ? crypto_aead_encrypt(req)
4487				: crypto_aead_decrypt(req), &wait);
4488
4489	if (!rc && enc)
4490		memcpy(&tr_hdr->Signature, sign, SMB2_SIGNATURE_SIZE);
4491
4492	kfree_sensitive(creq);
4493	return rc;
4494}
4495
4496/*
4497 * Copy data from an iterator to the folios in a folio queue buffer.
4498 */
4499static bool cifs_copy_iter_to_folioq(struct iov_iter *iter, size_t size,
4500				     struct folio_queue *buffer)
4501{
4502	for (; buffer; buffer = buffer->next) {
4503		for (int s = 0; s < folioq_count(buffer); s++) {
4504			struct folio *folio = folioq_folio(buffer, s);
4505			size_t part = folioq_folio_size(buffer, s);
4506
4507			part = umin(part, size);
4508
4509			if (copy_folio_from_iter(folio, 0, part, iter) != part)
4510				return false;
4511			size -= part;
4512		}
4513	}
4514	return true;
4515}
4516
4517void
4518smb3_free_compound_rqst(int num_rqst, struct smb_rqst *rqst)
4519{
4520	for (int i = 0; i < num_rqst; i++)
4521		netfs_free_folioq_buffer(rqst[i].rq_buffer);
4522}
4523
4524/*
4525 * This function will initialize new_rq and encrypt the content.
4526 * The first entry, new_rq[0], only contains a single iov which contains
4527 * a smb2_transform_hdr and is pre-allocated by the caller.
4528 * This function then populates new_rq[1+] with the content from olq_rq[0+].
4529 *
4530 * The end result is an array of smb_rqst structures where the first structure
4531 * only contains a single iov for the transform header which we then can pass
4532 * to crypt_message().
4533 *
4534 * new_rq[0].rq_iov[0] :  smb2_transform_hdr pre-allocated by the caller
4535 * new_rq[1+].rq_iov[*] == old_rq[0+].rq_iov[*] : SMB2/3 requests
4536 */
4537static int
4538smb3_init_transform_rq(struct TCP_Server_Info *server, int num_rqst,
4539		       struct smb_rqst *new_rq, struct smb_rqst *old_rq)
4540{
4541	struct smb2_transform_hdr *tr_hdr = new_rq[0].rq_iov[0].iov_base;
4542	unsigned int orig_len = 0;
4543	int rc = -ENOMEM;
4544
4545	for (int i = 1; i < num_rqst; i++) {
4546		struct smb_rqst *old = &old_rq[i - 1];
4547		struct smb_rqst *new = &new_rq[i];
4548		struct folio_queue *buffer = NULL;
4549		size_t size = iov_iter_count(&old->rq_iter);
4550
4551		orig_len += smb_rqst_len(server, old);
4552		new->rq_iov = old->rq_iov;
4553		new->rq_nvec = old->rq_nvec;
4554
4555		if (size > 0) {
4556			size_t cur_size = 0;
4557			rc = netfs_alloc_folioq_buffer(NULL, &buffer, &cur_size,
4558						       size, GFP_NOFS);
4559			if (rc < 0)
4560				goto err_free;
4561
4562			new->rq_buffer = buffer;
4563			iov_iter_folio_queue(&new->rq_iter, ITER_SOURCE,
4564					     buffer, 0, 0, size);
4565
4566			if (!cifs_copy_iter_to_folioq(&old->rq_iter, size, buffer)) {
4567				rc = smb_EIO1(smb_eio_trace_tx_copy_iter_to_buf, size);
4568				goto err_free;
4569			}
4570		}
4571	}
4572
4573	/* fill the 1st iov with a transform header */
4574	fill_transform_hdr(tr_hdr, orig_len, old_rq, server->cipher_type);
4575
4576	rc = crypt_message(server, num_rqst, new_rq, 1, server->secmech.enc);
4577	cifs_dbg(FYI, "Encrypt message returned %d\n", rc);
4578	if (rc)
4579		goto err_free;
4580
4581	return rc;
4582
4583err_free:
4584	smb3_free_compound_rqst(num_rqst - 1, &new_rq[1]);
4585	return rc;
4586}
4587
4588static int
4589smb3_is_transform_hdr(void *buf)
4590{
4591	struct smb2_transform_hdr *trhdr = buf;
4592
4593	return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
4594}
4595
4596static int
4597decrypt_raw_data(struct TCP_Server_Info *server, char *buf,
4598		 unsigned int buf_data_size, struct iov_iter *iter,
4599		 bool is_offloaded)
4600{
4601	struct crypto_aead *tfm;
4602	struct smb_rqst rqst = {NULL};
4603	struct kvec iov[2];
4604	size_t iter_size = 0;
4605	int rc;
4606
4607	iov[0].iov_base = buf;
4608	iov[0].iov_len = sizeof(struct smb2_transform_hdr);
4609	iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr);
4610	iov[1].iov_len = buf_data_size;
4611
4612	rqst.rq_iov = iov;
4613	rqst.rq_nvec = 2;
4614	if (iter) {
4615		rqst.rq_iter = *iter;
4616		iter_size = iov_iter_count(iter);
4617	}
4618
4619	if (is_offloaded) {
4620		if ((server->cipher_type == SMB2_ENCRYPTION_AES128_GCM) ||
4621		    (server->cipher_type == SMB2_ENCRYPTION_AES256_GCM))
4622			tfm = crypto_alloc_aead("gcm(aes)", 0, 0);
4623		else
4624			tfm = crypto_alloc_aead("ccm(aes)", 0, 0);
4625		if (IS_ERR(tfm)) {
4626			rc = PTR_ERR(tfm);
4627			cifs_server_dbg(VFS, "%s: Failed alloc decrypt TFM, rc=%d\n", __func__, rc);
4628
4629			return rc;
4630		}
4631	} else {
4632		rc = smb3_crypto_aead_allocate(server);
4633		if (unlikely(rc))
4634			return rc;
4635		tfm = server->secmech.dec;
4636	}
4637
4638	rc = crypt_message(server, 1, &rqst, 0, tfm);
4639	cifs_dbg(FYI, "Decrypt message returned %d\n", rc);
4640
4641	if (is_offloaded)
4642		crypto_free_aead(tfm);
4643
4644	if (rc)
4645		return rc;
4646
4647	memmove(buf, iov[1].iov_base, buf_data_size);
4648
4649	if (!is_offloaded)
4650		server->total_read = buf_data_size + iter_size;
4651
4652	return rc;
4653}
4654
4655static int
4656cifs_copy_folioq_to_iter(struct folio_queue *folioq, size_t data_size,
4657			 size_t skip, struct iov_iter *iter)
4658{
4659	for (; folioq; folioq = folioq->next) {
4660		for (int s = 0; s < folioq_count(folioq); s++) {
4661			struct folio *folio = folioq_folio(folioq, s);
4662			size_t fsize = folio_size(folio);
4663			size_t n, len = umin(fsize - skip, data_size);
4664
4665			n = copy_folio_to_iter(folio, skip, len, iter);
4666			if (n != len) {
4667				cifs_dbg(VFS, "%s: something went wrong\n", __func__);
4668				return smb_EIO2(smb_eio_trace_rx_copy_to_iter,
4669						n, len);
4670			}
4671			data_size -= n;
4672			skip = 0;
4673		}
4674	}
4675
4676	return 0;
4677}
4678
4679static int
4680handle_read_data(struct TCP_Server_Info *server, struct mid_q_entry *mid,
4681		 char *buf, unsigned int buf_len, struct folio_queue *buffer,
4682		 unsigned int buffer_len, bool is_offloaded)
4683{
4684	unsigned int data_offset;
4685	unsigned int data_len;
4686	unsigned int cur_off;
4687	unsigned int cur_page_idx;
4688	unsigned int pad_len;
4689	struct cifs_io_subrequest *rdata = mid->callback_data;
4690	struct smb2_hdr *shdr = (struct smb2_hdr *)buf;
4691	size_t copied;
4692	bool use_rdma_mr = false;
4693
4694	if (shdr->Command != SMB2_READ) {
4695		cifs_server_dbg(VFS, "only big read responses are supported\n");
4696		return -EOPNOTSUPP;
4697	}
4698
4699	if (server->ops->is_session_expired &&
4700	    server->ops->is_session_expired(buf)) {
4701		if (!is_offloaded)
4702			cifs_reconnect(server, true);
4703		return -1;
4704	}
4705
4706	if (server->ops->is_status_pending &&
4707			server->ops->is_status_pending(buf, server))
4708		return -1;
4709
4710	/* set up first two iov to get credits */
4711	rdata->iov[0].iov_base = buf;
4712	rdata->iov[0].iov_len = 0;
4713	rdata->iov[1].iov_base = buf;
4714	rdata->iov[1].iov_len =
4715		min_t(unsigned int, buf_len, server->vals->read_rsp_size);
4716	cifs_dbg(FYI, "0: iov_base=%p iov_len=%zu\n",
4717		 rdata->iov[0].iov_base, rdata->iov[0].iov_len);
4718	cifs_dbg(FYI, "1: iov_base=%p iov_len=%zu\n",
4719		 rdata->iov[1].iov_base, rdata->iov[1].iov_len);
4720
4721	rdata->result = server->ops->map_error(buf, true);
4722	if (rdata->result != 0) {
4723		cifs_dbg(FYI, "%s: server returned error %d\n",
4724			 __func__, rdata->result);
4725		/* normal error on read response */
4726		if (is_offloaded)
4727			mid->mid_state = MID_RESPONSE_RECEIVED;
4728		else
4729			dequeue_mid(server, mid, false);
4730		return 0;
4731	}
4732
4733	data_offset = server->ops->read_data_offset(buf);
4734#ifdef CONFIG_CIFS_SMB_DIRECT
4735	use_rdma_mr = rdata->mr;
4736#endif
4737	data_len = server->ops->read_data_length(buf, use_rdma_mr);
4738
4739	if (data_offset < server->vals->read_rsp_size) {
4740		/*
4741		 * win2k8 sometimes sends an offset of 0 when the read
4742		 * is beyond the EOF. Treat it as if the data starts just after
4743		 * the header.
4744		 */
4745		cifs_dbg(FYI, "%s: data offset (%u) inside read response header\n",
4746			 __func__, data_offset);
4747		data_offset = server->vals->read_rsp_size;
4748	} else if (data_offset > MAX_CIFS_SMALL_BUFFER_SIZE) {
4749		/* data_offset is beyond the end of smallbuf */
4750		cifs_dbg(FYI, "%s: data offset (%u) beyond end of smallbuf\n",
4751			 __func__, data_offset);
4752		rdata->result = smb_EIO1(smb_eio_trace_rx_overlong, data_offset);
4753		if (is_offloaded)
4754			mid->mid_state = MID_RESPONSE_MALFORMED;
4755		else
4756			dequeue_mid(server, mid, rdata->result);
4757		return 0;
4758	}
4759
4760	pad_len = data_offset - server->vals->read_rsp_size;
4761
4762	if (buf_len <= data_offset) {
4763		/* read response payload is in pages */
4764		cur_page_idx = pad_len / PAGE_SIZE;
4765		cur_off = pad_len % PAGE_SIZE;
4766
4767		if (cur_page_idx != 0) {
4768			/* data offset is beyond the 1st page of response */
4769			cifs_dbg(FYI, "%s: data offset (%u) beyond 1st page of response\n",
4770				 __func__, data_offset);
4771			rdata->result = smb_EIO1(smb_eio_trace_rx_overpage, data_offset);
4772			if (is_offloaded)
4773				mid->mid_state = MID_RESPONSE_MALFORMED;
4774			else
4775				dequeue_mid(server, mid, rdata->result);
4776			return 0;
4777		}
4778
4779		if (data_len > buffer_len - pad_len) {
4780			/* data_len is corrupt -- discard frame */
4781			rdata->result = smb_EIO1(smb_eio_trace_rx_bad_datalen, data_len);
4782			if (is_offloaded)
4783				mid->mid_state = MID_RESPONSE_MALFORMED;
4784			else
4785				dequeue_mid(server, mid, rdata->result);
4786			return 0;
4787		}
4788
4789		/* Copy the data to the output I/O iterator. */
4790		rdata->result = cifs_copy_folioq_to_iter(buffer, buffer_len,
4791							 cur_off, &rdata->subreq.io_iter);
4792		if (rdata->result != 0) {
4793			if (is_offloaded)
4794				mid->mid_state = MID_RESPONSE_MALFORMED;
4795			else
4796				dequeue_mid(server, mid, rdata->result);
4797			return 0;
4798		}
4799		rdata->got_bytes = buffer_len;
4800
4801	} else if (buf_len >= data_offset + data_len) {
4802		/* read response payload is in buf */
4803		WARN_ONCE(buffer, "read data can be either in buf or in buffer");
4804		copied = copy_to_iter(buf + data_offset, data_len, &rdata->subreq.io_iter);
4805		if (copied == 0)
4806			return smb_EIO2(smb_eio_trace_rx_copy_to_iter, copied, data_len);
4807		rdata->got_bytes = copied;
4808	} else {
4809		/* read response payload cannot be in both buf and pages */
4810		WARN_ONCE(1, "buf can not contain only a part of read data");
4811		rdata->result = smb_EIO(smb_eio_trace_rx_both_buf);
4812		if (is_offloaded)
4813			mid->mid_state = MID_RESPONSE_MALFORMED;
4814		else
4815			dequeue_mid(server, mid, rdata->result);
4816		return 0;
4817	}
4818
4819	if (is_offloaded)
4820		mid->mid_state = MID_RESPONSE_RECEIVED;
4821	else
4822		dequeue_mid(server, mid, false);
4823	return 0;
4824}
4825
4826struct smb2_decrypt_work {
4827	struct work_struct decrypt;
4828	struct TCP_Server_Info *server;
4829	struct folio_queue *buffer;
4830	char *buf;
4831	unsigned int len;
4832};
4833
4834
4835static void smb2_decrypt_offload(struct work_struct *work)
4836{
4837	struct smb2_decrypt_work *dw = container_of(work,
4838				struct smb2_decrypt_work, decrypt);
4839	int rc;
4840	struct mid_q_entry *mid;
4841	struct iov_iter iter;
4842
4843	iov_iter_folio_queue(&iter, ITER_DEST, dw->buffer, 0, 0, dw->len);
4844	rc = decrypt_raw_data(dw->server, dw->buf, dw->server->vals->read_rsp_size,
4845			      &iter, true);
4846	if (rc) {
4847		cifs_dbg(VFS, "error decrypting rc=%d\n", rc);
4848		goto free_pages;
4849	}
4850
4851	dw->server->lstrp = jiffies;
4852	mid = smb2_find_dequeue_mid(dw->server, dw->buf);
4853	if (mid == NULL)
4854		cifs_dbg(FYI, "mid not found\n");
4855	else {
4856		mid->decrypted = true;
4857		rc = handle_read_data(dw->server, mid, dw->buf,
4858				      dw->server->vals->read_rsp_size,
4859				      dw->buffer, dw->len,
4860				      true);
4861		if (rc >= 0) {
4862#ifdef CONFIG_CIFS_STATS2
4863			mid->when_received = jiffies;
4864#endif
4865			if (dw->server->ops->is_network_name_deleted)
4866				dw->server->ops->is_network_name_deleted(dw->buf,
4867									 dw->server);
4868
4869			mid_execute_callback(dw->server, mid);
4870		} else {
4871			spin_lock(&dw->server->srv_lock);
4872			if (dw->server->tcpStatus == CifsNeedReconnect) {
4873				spin_lock(&dw->server->mid_queue_lock);
4874				mid->mid_state = MID_RETRY_NEEDED;
4875				spin_unlock(&dw->server->mid_queue_lock);
4876				spin_unlock(&dw->server->srv_lock);
4877				mid_execute_callback(dw->server, mid);
4878			} else {
4879				spin_lock(&dw->server->mid_queue_lock);
4880				mid->mid_state = MID_REQUEST_SUBMITTED;
4881				mid->deleted_from_q = false;
4882				list_add_tail(&mid->qhead,
4883					&dw->server->pending_mid_q);
4884				spin_unlock(&dw->server->mid_queue_lock);
4885				spin_unlock(&dw->server->srv_lock);
4886			}
4887		}
4888		release_mid(dw->server, mid);
4889	}
4890
4891free_pages:
4892	netfs_free_folioq_buffer(dw->buffer);
4893	cifs_small_buf_release(dw->buf);
4894	kfree(dw);
4895}
4896
4897
4898static int
4899receive_encrypted_read(struct TCP_Server_Info *server, struct mid_q_entry **mid,
4900		       int *num_mids)
4901{
4902	char *buf = server->smallbuf;
4903	struct smb2_transform_hdr *tr_hdr = (struct smb2_transform_hdr *)buf;
4904	struct iov_iter iter;
4905	unsigned int len;
4906	unsigned int buflen = server->pdu_size;
4907	int rc;
4908	struct smb2_decrypt_work *dw;
4909
4910	dw = kzalloc(sizeof(struct smb2_decrypt_work), GFP_KERNEL);
4911	if (!dw)
4912		return -ENOMEM;
4913	INIT_WORK(&dw->decrypt, smb2_decrypt_offload);
4914	dw->server = server;
4915
4916	*num_mids = 1;
4917	len = min_t(unsigned int, buflen, server->vals->read_rsp_size +
4918		sizeof(struct smb2_transform_hdr)) - HEADER_SIZE(server) + 1;
4919
4920	rc = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1, len);
4921	if (rc < 0)
4922		goto free_dw;
4923	server->total_read += rc;
4924
4925	len = le32_to_cpu(tr_hdr->OriginalMessageSize) -
4926		server->vals->read_rsp_size;
4927	dw->len = len;
4928	len = round_up(dw->len, PAGE_SIZE);
4929
4930	size_t cur_size = 0;
4931	rc = netfs_alloc_folioq_buffer(NULL, &dw->buffer, &cur_size, len, GFP_NOFS);
4932	if (rc < 0)
4933		goto discard_data;
4934
4935	iov_iter_folio_queue(&iter, ITER_DEST, dw->buffer, 0, 0, len);
4936
4937	/* Read the data into the buffer and clear excess bufferage. */
4938	rc = cifs_read_iter_from_socket(server, &iter, dw->len);
4939	if (rc < 0)
4940		goto discard_data;
4941
4942	server->total_read += rc;
4943	if (rc < len) {
4944		struct iov_iter tmp = iter;
4945
4946		iov_iter_advance(&tmp, rc);
4947		iov_iter_zero(len - rc, &tmp);
4948	}
4949	iov_iter_truncate(&iter, dw->len);
4950
4951	rc = cifs_discard_remaining_data(server);
4952	if (rc)
4953		goto free_pages;
4954
4955	/*
4956	 * For large reads, offload to different thread for better performance,
4957	 * use more cores decrypting which can be expensive
4958	 */
4959
4960	if ((server->min_offload) && (server->in_flight > 1) &&
4961	    (server->pdu_size >= server->min_offload)) {
4962		dw->buf = server->smallbuf;
4963		server->smallbuf = (char *)cifs_small_buf_get();
4964
4965		queue_work(decrypt_wq, &dw->decrypt);
4966		*num_mids = 0; /* worker thread takes care of finding mid */
4967		return -1;
4968	}
4969
4970	rc = decrypt_raw_data(server, buf, server->vals->read_rsp_size,
4971			      &iter, false);
4972	if (rc)
4973		goto free_pages;
4974
4975	*mid = smb2_find_mid(server, buf);
4976	if (*mid == NULL) {
4977		cifs_dbg(FYI, "mid not found\n");
4978	} else {
4979		cifs_dbg(FYI, "mid found\n");
4980		(*mid)->decrypted = true;
4981		rc = handle_read_data(server, *mid, buf,
4982				      server->vals->read_rsp_size,
4983				      dw->buffer, dw->len, false);
4984		if (rc >= 0) {
4985			if (server->ops->is_network_name_deleted) {
4986				server->ops->is_network_name_deleted(buf,
4987								server);
4988			}
4989		}
4990	}
4991
4992free_pages:
4993	netfs_free_folioq_buffer(dw->buffer);
4994free_dw:
4995	kfree(dw);
4996	return rc;
4997discard_data:
4998	cifs_discard_remaining_data(server);
4999	goto free_pages;
5000}
5001
5002static int
5003receive_encrypted_standard(struct TCP_Server_Info *server,
5004			   struct mid_q_entry **mids, char **bufs,
5005			   int *num_mids)
5006{
5007	int ret, length;
5008	char *buf = server->smallbuf;
5009	struct smb2_hdr *shdr;
5010	unsigned int pdu_length = server->pdu_size;
5011	unsigned int buf_size;
5012	unsigned int next_cmd;
5013	struct mid_q_entry *mid_entry;
5014	int next_is_large;
5015	char *next_buffer = NULL;
5016
5017	*num_mids = 0;
5018
5019	/* switch to large buffer if too big for a small one */
5020	if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE) {
5021		server->large_buf = true;
5022		memcpy(server->bigbuf, buf, server->total_read);
5023		buf = server->bigbuf;
5024	}
5025
5026	/* now read the rest */
5027	length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
5028				pdu_length - HEADER_SIZE(server) + 1);
5029	if (length < 0)
5030		return length;
5031	server->total_read += length;
5032
5033	buf_size = pdu_length - sizeof(struct smb2_transform_hdr);
5034	length = decrypt_raw_data(server, buf, buf_size, NULL, false);
5035	if (length)
5036		return length;
5037
5038	next_is_large = server->large_buf;
5039one_more:
5040	shdr = (struct smb2_hdr *)buf;
5041	next_cmd = le32_to_cpu(shdr->NextCommand);
5042	if (next_cmd) {
5043		if (WARN_ON_ONCE(next_cmd > pdu_length))
5044			return -1;
5045		if (next_is_large)
5046			next_buffer = (char *)cifs_buf_get();
5047		else
5048			next_buffer = (char *)cifs_small_buf_get();
5049		if (!next_buffer) {
5050			cifs_server_dbg(VFS, "No memory for (large) SMB response\n");
5051			return -1;
5052		}
5053		memcpy(next_buffer, buf + next_cmd, pdu_length - next_cmd);
5054	}
5055
5056	mid_entry = smb2_find_mid(server, buf);
5057	if (mid_entry == NULL)
5058		cifs_dbg(FYI, "mid not found\n");
5059	else {
5060		cifs_dbg(FYI, "mid found\n");
5061		mid_entry->decrypted = true;
5062		mid_entry->resp_buf_size = server->pdu_size;
5063	}
5064
5065	if (*num_mids >= MAX_COMPOUND) {
5066		cifs_server_dbg(VFS, "too many PDUs in compound\n");
5067		return -1;
5068	}
5069	bufs[*num_mids] = buf;
5070	mids[(*num_mids)++] = mid_entry;
5071
5072	if (mid_entry && mid_entry->handle)
5073		ret = mid_entry->handle(server, mid_entry);
5074	else
5075		ret = cifs_handle_standard(server, mid_entry);
5076
5077	if (ret == 0 && next_cmd) {
5078		pdu_length -= next_cmd;
5079		server->large_buf = next_is_large;
5080		if (next_is_large)
5081			server->bigbuf = buf = next_buffer;
5082		else
5083			server->smallbuf = buf = next_buffer;
5084		goto one_more;
5085	} else if (ret != 0) {
5086		/*
5087		 * ret != 0 here means that we didn't get to handle_mid() thus
5088		 * server->smallbuf and server->bigbuf are still valid. We need
5089		 * to free next_buffer because it is not going to be used
5090		 * anywhere.
5091		 */
5092		if (next_is_large)
5093			free_rsp_buf(CIFS_LARGE_BUFFER, next_buffer);
5094		else
5095			free_rsp_buf(CIFS_SMALL_BUFFER, next_buffer);
5096	}
5097
5098	return ret;
5099}
5100
5101static int
5102smb3_receive_transform(struct TCP_Server_Info *server,
5103		       struct mid_q_entry **mids, char **bufs, int *num_mids)
5104{
5105	char *buf = server->smallbuf;
5106	unsigned int pdu_length = server->pdu_size;
5107	struct smb2_transform_hdr *tr_hdr = (struct smb2_transform_hdr *)buf;
5108	unsigned int orig_len = le32_to_cpu(tr_hdr->OriginalMessageSize);
5109
5110	if (pdu_length < sizeof(struct smb2_transform_hdr) +
5111						sizeof(struct smb2_hdr)) {
5112		cifs_server_dbg(VFS, "Transform message is too small (%u)\n",
5113			 pdu_length);
5114		cifs_reconnect(server, true);
5115		return -ECONNABORTED;
5116	}
5117
5118	if (pdu_length < orig_len + sizeof(struct smb2_transform_hdr)) {
5119		cifs_server_dbg(VFS, "Transform message is broken\n");
5120		cifs_reconnect(server, true);
5121		return -ECONNABORTED;
5122	}
5123
5124	/* TODO: add support for compounds containing READ. */
5125	if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server)) {
5126		return receive_encrypted_read(server, &mids[0], num_mids);
5127	}
5128
5129	return receive_encrypted_standard(server, mids, bufs, num_mids);
5130}
5131
5132int
5133smb3_handle_read_data(struct TCP_Server_Info *server, struct mid_q_entry *mid)
5134{
5135	char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
5136
5137	return handle_read_data(server, mid, buf, server->pdu_size,
5138				NULL, 0, false);
5139}
5140
5141static int smb2_next_header(struct TCP_Server_Info *server, char *buf,
5142			    unsigned int *noff)
5143{
5144	struct smb2_hdr *hdr = (struct smb2_hdr *)buf;
5145	struct smb2_transform_hdr *t_hdr = (struct smb2_transform_hdr *)buf;
5146
5147	if (hdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM) {
5148		*noff = le32_to_cpu(t_hdr->OriginalMessageSize);
5149		if (unlikely(check_add_overflow(*noff, sizeof(*t_hdr), noff)))
5150			return -EINVAL;
5151	} else {
5152		*noff = le32_to_cpu(hdr->NextCommand);
5153	}
5154	if (unlikely(*noff && *noff < MID_HEADER_SIZE(server)))
5155		return -EINVAL;
5156	return 0;
5157}
5158
5159int __cifs_sfu_make_node(unsigned int xid, struct inode *inode,
5160				struct dentry *dentry, struct cifs_tcon *tcon,
5161				const char *full_path, umode_t mode, dev_t dev,
5162				const char *symname)
5163{
5164	struct TCP_Server_Info *server = tcon->ses->server;
5165	struct cifs_open_parms oparms;
5166	struct cifs_open_info_data idata;
5167	struct cifs_io_parms io_parms = {};
5168	struct cifs_sb_info *cifs_sb = CIFS_SB(inode->i_sb);
5169	struct cifs_fid fid;
5170	unsigned int bytes_written;
5171	u8 type[8];
5172	int type_len = 0;
5173	struct {
5174		__le64 major;
5175		__le64 minor;
5176	} __packed pdev = {};
5177	__le16 *symname_utf16 = NULL;
5178	u8 *data = NULL;
5179	int data_len = 0;
5180	struct kvec iov[3];
5181	__u32 oplock = server->oplocks ? REQ_OPLOCK : 0;
5182	int rc;
5183
5184	switch (mode & S_IFMT) {
5185	case S_IFCHR:
5186		type_len = 8;
5187		memcpy(type, "IntxCHR\0", type_len);
5188		pdev.major = cpu_to_le64(MAJOR(dev));
5189		pdev.minor = cpu_to_le64(MINOR(dev));
5190		data = (u8 *)&pdev;
5191		data_len = sizeof(pdev);
5192		break;
5193	case S_IFBLK:
5194		type_len = 8;
5195		memcpy(type, "IntxBLK\0", type_len);
5196		pdev.major = cpu_to_le64(MAJOR(dev));
5197		pdev.minor = cpu_to_le64(MINOR(dev));
5198		data = (u8 *)&pdev;
5199		data_len = sizeof(pdev);
5200		break;
5201	case S_IFLNK:
5202		type_len = 8;
5203		memcpy(type, "IntxLNK\1", type_len);
5204		symname_utf16 = cifs_strndup_to_utf16(symname, strlen(symname),
5205						      &data_len, cifs_sb->local_nls,
5206						      NO_MAP_UNI_RSVD);
5207		if (!symname_utf16) {
5208			rc = -ENOMEM;
5209			goto out;
5210		}
5211		data_len -= 2; /* symlink is without trailing wide-nul */
5212		data = (u8 *)symname_utf16;
5213		break;
5214	case S_IFSOCK:
5215		type_len = 8;
5216		strscpy(type, "LnxSOCK");
5217		data = (u8 *)&pdev;
5218		data_len = sizeof(pdev);
5219		break;
5220	case S_IFIFO:
5221		type_len = 8;
5222		strscpy(type, "LnxFIFO");
5223		data = (u8 *)&pdev;
5224		data_len = sizeof(pdev);
5225		break;
5226	default:
5227		rc = -EPERM;
5228		goto out;
5229	}
5230
5231	oparms = CIFS_OPARMS(cifs_sb, tcon, full_path, GENERIC_WRITE,
5232			     FILE_CREATE, CREATE_NOT_DIR |
5233			     CREATE_OPTION_SPECIAL, ACL_NO_MODE);
5234	oparms.fid = &fid;
5235	idata.contains_posix_file_info = false;
5236	rc = server->ops->open(xid, &oparms, &oplock, &idata);
5237	if (rc)
5238		goto out;
5239
5240	/*
5241	 * Check if the server honored ATTR_SYSTEM flag by CREATE_OPTION_SPECIAL
5242	 * option. If not then server does not support ATTR_SYSTEM and newly
5243	 * created file is not SFU compatible, which means that the call failed.
5244	 */
5245	if (!(le32_to_cpu(idata.fi.Attributes) & ATTR_SYSTEM)) {
5246		rc = -EOPNOTSUPP;
5247		goto out_close;
5248	}
5249
5250	if (type_len + data_len > 0) {
5251		io_parms.pid = current->tgid;
5252		io_parms.tcon = tcon;
5253		io_parms.length = type_len + data_len;
5254		iov[1].iov_base = type;
5255		iov[1].iov_len = type_len;
5256		iov[2].iov_base = data;
5257		iov[2].iov_len = data_len;
5258
5259		rc = server->ops->sync_write(xid, &fid, &io_parms,
5260					     &bytes_written,
5261					     iov, ARRAY_SIZE(iov)-1);
5262	}
5263
5264out_close:
5265	server->ops->close(xid, tcon, &fid);
5266
5267	/*
5268	 * If CREATE was successful but either setting ATTR_SYSTEM failed or
5269	 * writing type/data information failed then remove the intermediate
5270	 * object created by CREATE. Otherwise intermediate empty object stay
5271	 * on the server.
5272	 */
5273	if (rc)
5274		server->ops->unlink(xid, tcon, full_path, cifs_sb, NULL);
5275
5276out:
5277	kfree(symname_utf16);
5278	return rc;
5279}
5280
5281int cifs_sfu_make_node(unsigned int xid, struct inode *inode,
5282		       struct dentry *dentry, struct cifs_tcon *tcon,
5283		       const char *full_path, umode_t mode, dev_t dev)
5284{
5285	struct inode *new = NULL;
5286	int rc;
5287
5288	rc = __cifs_sfu_make_node(xid, inode, dentry, tcon,
5289				  full_path, mode, dev, NULL);
5290	if (rc)
5291		return rc;
5292
5293	if (tcon->posix_extensions) {
5294		rc = smb311_posix_get_inode_info(&new, full_path, NULL,
5295						 inode->i_sb, xid);
5296	} else if (tcon->unix_ext) {
5297		rc = cifs_get_inode_info_unix(&new, full_path,
5298					      inode->i_sb, xid);
5299	} else {
5300		rc = cifs_get_inode_info(&new, full_path, NULL,
5301					 inode->i_sb, xid, NULL);
5302	}
5303	if (!rc)
5304		d_instantiate(dentry, new);
5305	return rc;
5306}
5307
5308static int smb2_make_node(unsigned int xid, struct inode *inode,
5309			  struct dentry *dentry, struct cifs_tcon *tcon,
5310			  const char *full_path, umode_t mode, dev_t dev)
5311{
5312	struct cifs_sb_info *cifs_sb = CIFS_SB(inode->i_sb);
5313	int rc = -EOPNOTSUPP;
5314
5315	/*
5316	 * Check if mounted with mount parm 'sfu' mount parm.
5317	 * SFU emulation should work with all servers, but only
5318	 * supports block and char device, socket & fifo,
5319	 * and was used by default in earlier versions of Windows
5320	 */
5321	if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_UNX_EMUL) {
5322		rc = cifs_sfu_make_node(xid, inode, dentry, tcon,
5323					full_path, mode, dev);
5324	} else if (CIFS_REPARSE_SUPPORT(tcon)) {
5325		rc = mknod_reparse(xid, inode, dentry, tcon,
5326				   full_path, mode, dev);
5327	}
5328	return rc;
5329}
5330
5331#ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
5332struct smb_version_operations smb20_operations = {
5333	.compare_fids = smb2_compare_fids,
5334	.setup_request = smb2_setup_request,
5335	.setup_async_request = smb2_setup_async_request,
5336	.check_receive = smb2_check_receive,
5337	.add_credits = smb2_add_credits,
5338	.set_credits = smb2_set_credits,
5339	.get_credits_field = smb2_get_credits_field,
5340	.get_credits = smb2_get_credits,
5341	.wait_mtu_credits = cifs_wait_mtu_credits,
5342	.get_next_mid = smb2_get_next_mid,
5343	.revert_current_mid = smb2_revert_current_mid,
5344	.read_data_offset = smb2_read_data_offset,
5345	.read_data_length = smb2_read_data_length,
5346	.map_error = map_smb2_to_linux_error,
5347	.find_mid = smb2_find_mid,
5348	.check_message = smb2_check_message,
5349	.dump_detail = smb2_dump_detail,
5350	.clear_stats = smb2_clear_stats,
5351	.print_stats = smb2_print_stats,
5352	.is_oplock_break = smb2_is_valid_oplock_break,
5353	.handle_cancelled_mid = smb2_handle_cancelled_mid,
5354	.downgrade_oplock = smb2_downgrade_oplock,
5355	.need_neg = smb2_need_neg,
5356	.negotiate = smb2_negotiate,
5357	.negotiate_wsize = smb2_negotiate_wsize,
5358	.negotiate_rsize = smb2_negotiate_rsize,
5359	.sess_setup = SMB2_sess_setup,
5360	.logoff = SMB2_logoff,
5361	.tree_connect = SMB2_tcon,
5362	.tree_disconnect = SMB2_tdis,
5363	.qfs_tcon = smb2_qfs_tcon,
5364	.is_path_accessible = smb2_is_path_accessible,
5365	.can_echo = smb2_can_echo,
5366	.echo = SMB2_echo,
5367	.query_path_info = smb2_query_path_info,
5368	.query_reparse_point = smb2_query_reparse_point,
5369	.get_srv_inum = smb2_get_srv_inum,
5370	.query_file_info = smb2_query_file_info,
5371	.set_path_size = smb2_set_path_size,
5372	.set_file_size = smb2_set_file_size,
5373	.set_file_info = smb2_set_file_info,
5374	.set_compression = smb2_set_compression,
5375	.mkdir = smb2_mkdir,
5376	.mkdir_setinfo = smb2_mkdir_setinfo,
5377	.rmdir = smb2_rmdir,
5378	.unlink = smb2_unlink,
5379	.rename = smb2_rename_path,
5380	.create_hardlink = smb2_create_hardlink,
5381	.get_reparse_point_buffer = smb2_get_reparse_point_buffer,
5382	.query_mf_symlink = smb3_query_mf_symlink,
5383	.create_mf_symlink = smb3_create_mf_symlink,
5384	.create_reparse_inode = smb2_create_reparse_inode,
5385	.open = smb2_open_file,
5386	.set_fid = smb2_set_fid,
5387	.close = smb2_close_file,
5388	.flush = smb2_flush_file,
5389	.async_readv = smb2_async_readv,
5390	.async_writev = smb2_async_writev,
5391	.sync_read = smb2_sync_read,
5392	.sync_write = smb2_sync_write,
5393	.query_dir_first = smb2_query_dir_first,
5394	.query_dir_next = smb2_query_dir_next,
5395	.close_dir = smb2_close_dir,
5396	.calc_smb_size = smb2_calc_size,
5397	.is_status_pending = smb2_is_status_pending,
5398	.is_session_expired = smb2_is_session_expired,
5399	.oplock_response = smb2_oplock_response,
5400	.queryfs = smb2_queryfs,
5401	.mand_lock = smb2_mand_lock,
5402	.mand_unlock_range = smb2_unlock_range,
5403	.push_mand_locks = smb2_push_mandatory_locks,
5404	.get_lease_key = smb2_get_lease_key,
5405	.set_lease_key = smb2_set_lease_key,
5406	.new_lease_key = smb2_new_lease_key,
5407	.is_read_op = smb2_is_read_op,
5408	.set_oplock_level = smb2_set_oplock_level,
5409	.create_lease_buf = smb2_create_lease_buf,
5410	.parse_lease_buf = smb2_parse_lease_buf,
5411	.copychunk_range = smb2_copychunk_range,
5412	.wp_retry_size = smb2_wp_retry_size,
5413	.dir_needs_close = smb2_dir_needs_close,
5414	.get_dfs_refer = smb2_get_dfs_refer,
5415	.select_sectype = smb2_select_sectype,
5416#ifdef CONFIG_CIFS_XATTR
5417	.query_all_EAs = smb2_query_eas,
5418	.set_EA = smb2_set_ea,
5419#endif /* CIFS_XATTR */
5420	.get_acl = get_smb2_acl,
5421	.get_acl_by_fid = get_smb2_acl_by_fid,
5422	.set_acl = set_smb2_acl,
5423	.next_header = smb2_next_header,
5424	.ioctl_query_info = smb2_ioctl_query_info,
5425	.make_node = smb2_make_node,
5426	.fiemap = smb3_fiemap,
5427	.llseek = smb3_llseek,
5428	.is_status_io_timeout = smb2_is_status_io_timeout,
5429	.is_network_name_deleted = smb2_is_network_name_deleted,
5430	.rename_pending_delete = smb2_rename_pending_delete,
5431};
5432#endif /* CIFS_ALLOW_INSECURE_LEGACY */
5433
5434struct smb_version_operations smb21_operations = {
5435	.compare_fids = smb2_compare_fids,
5436	.setup_request = smb2_setup_request,
5437	.setup_async_request = smb2_setup_async_request,
5438	.check_receive = smb2_check_receive,
5439	.add_credits = smb2_add_credits,
5440	.set_credits = smb2_set_credits,
5441	.get_credits_field = smb2_get_credits_field,
5442	.get_credits = smb2_get_credits,
5443	.wait_mtu_credits = smb2_wait_mtu_credits,
5444	.adjust_credits = smb2_adjust_credits,
5445	.get_next_mid = smb2_get_next_mid,
5446	.revert_current_mid = smb2_revert_current_mid,
5447	.read_data_offset = smb2_read_data_offset,
5448	.read_data_length = smb2_read_data_length,
5449	.map_error = map_smb2_to_linux_error,
5450	.find_mid = smb2_find_mid,
5451	.check_message = smb2_check_message,
5452	.dump_detail = smb2_dump_detail,
5453	.clear_stats = smb2_clear_stats,
5454	.print_stats = smb2_print_stats,
5455	.is_oplock_break = smb2_is_valid_oplock_break,
5456	.handle_cancelled_mid = smb2_handle_cancelled_mid,
5457	.downgrade_oplock = smb2_downgrade_oplock,
5458	.need_neg = smb2_need_neg,
5459	.negotiate = smb2_negotiate,
5460	.negotiate_wsize = smb2_negotiate_wsize,
5461	.negotiate_rsize = smb2_negotiate_rsize,
5462	.sess_setup = SMB2_sess_setup,
5463	.logoff = SMB2_logoff,
5464	.tree_connect = SMB2_tcon,
5465	.tree_disconnect = SMB2_tdis,
5466	.qfs_tcon = smb2_qfs_tcon,
5467	.is_path_accessible = smb2_is_path_accessible,
5468	.can_echo = smb2_can_echo,
5469	.echo = SMB2_echo,
5470	.query_path_info = smb2_query_path_info,
5471	.query_reparse_point = smb2_query_reparse_point,
5472	.get_srv_inum = smb2_get_srv_inum,
5473	.query_file_info = smb2_query_file_info,
5474	.set_path_size = smb2_set_path_size,
5475	.set_file_size = smb2_set_file_size,
5476	.set_file_info = smb2_set_file_info,
5477	.set_compression = smb2_set_compression,
5478	.mkdir = smb2_mkdir,
5479	.mkdir_setinfo = smb2_mkdir_setinfo,
5480	.rmdir = smb2_rmdir,
5481	.unlink = smb2_unlink,
5482	.rename = smb2_rename_path,
5483	.create_hardlink = smb2_create_hardlink,
5484	.get_reparse_point_buffer = smb2_get_reparse_point_buffer,
5485	.query_mf_symlink = smb3_query_mf_symlink,
5486	.create_mf_symlink = smb3_create_mf_symlink,
5487	.create_reparse_inode = smb2_create_reparse_inode,
5488	.open = smb2_open_file,
5489	.set_fid = smb2_set_fid,
5490	.close = smb2_close_file,
5491	.flush = smb2_flush_file,
5492	.async_readv = smb2_async_readv,
5493	.async_writev = smb2_async_writev,
5494	.sync_read = smb2_sync_read,
5495	.sync_write = smb2_sync_write,
5496	.query_dir_first = smb2_query_dir_first,
5497	.query_dir_next = smb2_query_dir_next,
5498	.close_dir = smb2_close_dir,
5499	.calc_smb_size = smb2_calc_size,
5500	.is_status_pending = smb2_is_status_pending,
5501	.is_session_expired = smb2_is_session_expired,
5502	.oplock_response = smb2_oplock_response,
5503	.queryfs = smb2_queryfs,
5504	.mand_lock = smb2_mand_lock,
5505	.mand_unlock_range = smb2_unlock_range,
5506	.push_mand_locks = smb2_push_mandatory_locks,
5507	.get_lease_key = smb2_get_lease_key,
5508	.set_lease_key = smb2_set_lease_key,
5509	.new_lease_key = smb2_new_lease_key,
5510	.is_read_op = smb21_is_read_op,
5511	.set_oplock_level = smb21_set_oplock_level,
5512	.create_lease_buf = smb2_create_lease_buf,
5513	.parse_lease_buf = smb2_parse_lease_buf,
5514	.copychunk_range = smb2_copychunk_range,
5515	.wp_retry_size = smb2_wp_retry_size,
5516	.dir_needs_close = smb2_dir_needs_close,
5517	.enum_snapshots = smb3_enum_snapshots,
5518	.notify = smb3_notify,
5519	.get_dfs_refer = smb2_get_dfs_refer,
5520	.select_sectype = smb2_select_sectype,
5521#ifdef CONFIG_CIFS_XATTR
5522	.query_all_EAs = smb2_query_eas,
5523	.set_EA = smb2_set_ea,
5524#endif /* CIFS_XATTR */
5525	.get_acl = get_smb2_acl,
5526	.get_acl_by_fid = get_smb2_acl_by_fid,
5527	.set_acl = set_smb2_acl,
5528	.next_header = smb2_next_header,
5529	.ioctl_query_info = smb2_ioctl_query_info,
5530	.make_node = smb2_make_node,
5531	.fiemap = smb3_fiemap,
5532	.llseek = smb3_llseek,
5533	.is_status_io_timeout = smb2_is_status_io_timeout,
5534	.is_network_name_deleted = smb2_is_network_name_deleted,
5535	.rename_pending_delete = smb2_rename_pending_delete,
5536};
5537
5538struct smb_version_operations smb30_operations = {
5539	.compare_fids = smb2_compare_fids,
5540	.setup_request = smb2_setup_request,
5541	.setup_async_request = smb2_setup_async_request,
5542	.check_receive = smb2_check_receive,
5543	.add_credits = smb2_add_credits,
5544	.set_credits = smb2_set_credits,
5545	.get_credits_field = smb2_get_credits_field,
5546	.get_credits = smb2_get_credits,
5547	.wait_mtu_credits = smb2_wait_mtu_credits,
5548	.adjust_credits = smb2_adjust_credits,
5549	.get_next_mid = smb2_get_next_mid,
5550	.revert_current_mid = smb2_revert_current_mid,
5551	.read_data_offset = smb2_read_data_offset,
5552	.read_data_length = smb2_read_data_length,
5553	.map_error = map_smb2_to_linux_error,
5554	.find_mid = smb2_find_mid,
5555	.check_message = smb2_check_message,
5556	.dump_detail = smb2_dump_detail,
5557	.clear_stats = smb2_clear_stats,
5558	.print_stats = smb2_print_stats,
5559	.dump_share_caps = smb2_dump_share_caps,
5560	.is_oplock_break = smb2_is_valid_oplock_break,
5561	.handle_cancelled_mid = smb2_handle_cancelled_mid,
5562	.downgrade_oplock = smb3_downgrade_oplock,
5563	.need_neg = smb2_need_neg,
5564	.negotiate = smb2_negotiate,
5565	.negotiate_wsize = smb3_negotiate_wsize,
5566	.negotiate_rsize = smb3_negotiate_rsize,
5567	.sess_setup = SMB2_sess_setup,
5568	.logoff = SMB2_logoff,
5569	.tree_connect = SMB2_tcon,
5570	.tree_disconnect = SMB2_tdis,
5571	.qfs_tcon = smb3_qfs_tcon,
5572	.query_server_interfaces = SMB3_request_interfaces,
5573	.is_path_accessible = smb2_is_path_accessible,
5574	.can_echo = smb2_can_echo,
5575	.echo = SMB2_echo,
5576	.query_path_info = smb2_query_path_info,
5577	/* WSL tags introduced long after smb2.1, enable for SMB3, 3.11 only */
5578	.query_reparse_point = smb2_query_reparse_point,
5579	.get_srv_inum = smb2_get_srv_inum,
5580	.query_file_info = smb2_query_file_info,
5581	.set_path_size = smb2_set_path_size,
5582	.set_file_size = smb2_set_file_size,
5583	.set_file_info = smb2_set_file_info,
5584	.set_compression = smb2_set_compression,
5585	.mkdir = smb2_mkdir,
5586	.mkdir_setinfo = smb2_mkdir_setinfo,
5587	.rmdir = smb2_rmdir,
5588	.unlink = smb2_unlink,
5589	.rename = smb2_rename_path,
5590	.create_hardlink = smb2_create_hardlink,
5591	.get_reparse_point_buffer = smb2_get_reparse_point_buffer,
5592	.query_mf_symlink = smb3_query_mf_symlink,
5593	.create_mf_symlink = smb3_create_mf_symlink,
5594	.create_reparse_inode = smb2_create_reparse_inode,
5595	.open = smb2_open_file,
5596	.set_fid = smb2_set_fid,
5597	.close = smb2_close_file,
5598	.close_getattr = smb2_close_getattr,
5599	.flush = smb2_flush_file,
5600	.async_readv = smb2_async_readv,
5601	.async_writev = smb2_async_writev,
5602	.sync_read = smb2_sync_read,
5603	.sync_write = smb2_sync_write,
5604	.query_dir_first = smb2_query_dir_first,
5605	.query_dir_next = smb2_query_dir_next,
5606	.close_dir = smb2_close_dir,
5607	.calc_smb_size = smb2_calc_size,
5608	.is_status_pending = smb2_is_status_pending,
5609	.is_session_expired = smb2_is_session_expired,
5610	.oplock_response = smb2_oplock_response,
5611	.queryfs = smb2_queryfs,
5612	.mand_lock = smb2_mand_lock,
5613	.mand_unlock_range = smb2_unlock_range,
5614	.push_mand_locks = smb2_push_mandatory_locks,
5615	.get_lease_key = smb2_get_lease_key,
5616	.set_lease_key = smb2_set_lease_key,
5617	.new_lease_key = smb2_new_lease_key,
5618	.generate_signingkey = generate_smb30signingkey,
5619	.set_integrity  = smb3_set_integrity,
5620	.is_read_op = smb21_is_read_op,
5621	.set_oplock_level = smb3_set_oplock_level,
5622	.create_lease_buf = smb3_create_lease_buf,
5623	.parse_lease_buf = smb3_parse_lease_buf,
5624	.copychunk_range = smb2_copychunk_range,
5625	.duplicate_extents = smb2_duplicate_extents,
5626	.validate_negotiate = smb3_validate_negotiate,
5627	.wp_retry_size = smb2_wp_retry_size,
5628	.dir_needs_close = smb2_dir_needs_close,
5629	.fallocate = smb3_fallocate,
5630	.enum_snapshots = smb3_enum_snapshots,
5631	.notify = smb3_notify,
5632	.init_transform_rq = smb3_init_transform_rq,
5633	.is_transform_hdr = smb3_is_transform_hdr,
5634	.receive_transform = smb3_receive_transform,
5635	.get_dfs_refer = smb2_get_dfs_refer,
5636	.select_sectype = smb2_select_sectype,
5637#ifdef CONFIG_CIFS_XATTR
5638	.query_all_EAs = smb2_query_eas,
5639	.set_EA = smb2_set_ea,
5640#endif /* CIFS_XATTR */
5641	.get_acl = get_smb2_acl,
5642	.get_acl_by_fid = get_smb2_acl_by_fid,
5643	.set_acl = set_smb2_acl,
5644	.next_header = smb2_next_header,
5645	.ioctl_query_info = smb2_ioctl_query_info,
5646	.make_node = smb2_make_node,
5647	.fiemap = smb3_fiemap,
5648	.llseek = smb3_llseek,
5649	.is_status_io_timeout = smb2_is_status_io_timeout,
5650	.is_network_name_deleted = smb2_is_network_name_deleted,
5651	.rename_pending_delete = smb2_rename_pending_delete,
5652};
5653
5654struct smb_version_operations smb311_operations = {
5655	.compare_fids = smb2_compare_fids,
5656	.setup_request = smb2_setup_request,
5657	.setup_async_request = smb2_setup_async_request,
5658	.check_receive = smb2_check_receive,
5659	.add_credits = smb2_add_credits,
5660	.set_credits = smb2_set_credits,
5661	.get_credits_field = smb2_get_credits_field,
5662	.get_credits = smb2_get_credits,
5663	.wait_mtu_credits = smb2_wait_mtu_credits,
5664	.adjust_credits = smb2_adjust_credits,
5665	.get_next_mid = smb2_get_next_mid,
5666	.revert_current_mid = smb2_revert_current_mid,
5667	.read_data_offset = smb2_read_data_offset,
5668	.read_data_length = smb2_read_data_length,
5669	.map_error = map_smb2_to_linux_error,
5670	.find_mid = smb2_find_mid,
5671	.check_message = smb2_check_message,
5672	.dump_detail = smb2_dump_detail,
5673	.clear_stats = smb2_clear_stats,
5674	.print_stats = smb2_print_stats,
5675	.dump_share_caps = smb2_dump_share_caps,
5676	.is_oplock_break = smb2_is_valid_oplock_break,
5677	.handle_cancelled_mid = smb2_handle_cancelled_mid,
5678	.downgrade_oplock = smb3_downgrade_oplock,
5679	.need_neg = smb2_need_neg,
5680	.negotiate = smb2_negotiate,
5681	.negotiate_wsize = smb3_negotiate_wsize,
5682	.negotiate_rsize = smb3_negotiate_rsize,
5683	.sess_setup = SMB2_sess_setup,
5684	.logoff = SMB2_logoff,
5685	.tree_connect = SMB2_tcon,
5686	.tree_disconnect = SMB2_tdis,
5687	.qfs_tcon = smb3_qfs_tcon,
5688	.query_server_interfaces = SMB3_request_interfaces,
5689	.is_path_accessible = smb2_is_path_accessible,
5690	.can_echo = smb2_can_echo,
5691	.echo = SMB2_echo,
5692	.query_path_info = smb2_query_path_info,
5693	.query_reparse_point = smb2_query_reparse_point,
5694	.get_srv_inum = smb2_get_srv_inum,
5695	.query_file_info = smb2_query_file_info,
5696	.set_path_size = smb2_set_path_size,
5697	.set_file_size = smb2_set_file_size,
5698	.set_file_info = smb2_set_file_info,
5699	.set_compression = smb2_set_compression,
5700	.mkdir = smb2_mkdir,
5701	.mkdir_setinfo = smb2_mkdir_setinfo,
5702	.posix_mkdir = smb311_posix_mkdir,
5703	.rmdir = smb2_rmdir,
5704	.unlink = smb2_unlink,
5705	.rename = smb2_rename_path,
5706	.create_hardlink = smb2_create_hardlink,
5707	.get_reparse_point_buffer = smb2_get_reparse_point_buffer,
5708	.query_mf_symlink = smb3_query_mf_symlink,
5709	.create_mf_symlink = smb3_create_mf_symlink,
5710	.create_reparse_inode = smb2_create_reparse_inode,
5711	.open = smb2_open_file,
5712	.set_fid = smb2_set_fid,
5713	.close = smb2_close_file,
5714	.close_getattr = smb2_close_getattr,
5715	.flush = smb2_flush_file,
5716	.async_readv = smb2_async_readv,
5717	.async_writev = smb2_async_writev,
5718	.sync_read = smb2_sync_read,
5719	.sync_write = smb2_sync_write,
5720	.query_dir_first = smb2_query_dir_first,
5721	.query_dir_next = smb2_query_dir_next,
5722	.close_dir = smb2_close_dir,
5723	.calc_smb_size = smb2_calc_size,
5724	.is_status_pending = smb2_is_status_pending,
5725	.is_session_expired = smb2_is_session_expired,
5726	.oplock_response = smb2_oplock_response,
5727	.queryfs = smb311_queryfs,
5728	.mand_lock = smb2_mand_lock,
5729	.mand_unlock_range = smb2_unlock_range,
5730	.push_mand_locks = smb2_push_mandatory_locks,
5731	.get_lease_key = smb2_get_lease_key,
5732	.set_lease_key = smb2_set_lease_key,
5733	.new_lease_key = smb2_new_lease_key,
5734	.generate_signingkey = generate_smb311signingkey,
5735	.set_integrity  = smb3_set_integrity,
5736	.is_read_op = smb21_is_read_op,
5737	.set_oplock_level = smb3_set_oplock_level,
5738	.create_lease_buf = smb3_create_lease_buf,
5739	.parse_lease_buf = smb3_parse_lease_buf,
5740	.copychunk_range = smb2_copychunk_range,
5741	.duplicate_extents = smb2_duplicate_extents,
5742/*	.validate_negotiate = smb3_validate_negotiate, */ /* not used in 3.11 */
5743	.wp_retry_size = smb2_wp_retry_size,
5744	.dir_needs_close = smb2_dir_needs_close,
5745	.fallocate = smb3_fallocate,
5746	.enum_snapshots = smb3_enum_snapshots,
5747	.notify = smb3_notify,
5748	.init_transform_rq = smb3_init_transform_rq,
5749	.is_transform_hdr = smb3_is_transform_hdr,
5750	.receive_transform = smb3_receive_transform,
5751	.get_dfs_refer = smb2_get_dfs_refer,
5752	.select_sectype = smb2_select_sectype,
5753#ifdef CONFIG_CIFS_XATTR
5754	.query_all_EAs = smb2_query_eas,
5755	.set_EA = smb2_set_ea,
5756#endif /* CIFS_XATTR */
5757	.get_acl = get_smb2_acl,
5758	.get_acl_by_fid = get_smb2_acl_by_fid,
5759	.set_acl = set_smb2_acl,
5760	.next_header = smb2_next_header,
5761	.ioctl_query_info = smb2_ioctl_query_info,
5762	.make_node = smb2_make_node,
5763	.fiemap = smb3_fiemap,
5764	.llseek = smb3_llseek,
5765	.is_status_io_timeout = smb2_is_status_io_timeout,
5766	.is_network_name_deleted = smb2_is_network_name_deleted,
5767	.rename_pending_delete = smb2_rename_pending_delete,
5768};
5769
5770#ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
5771struct smb_version_values smb20_values = {
5772	.version_string = SMB20_VERSION_STRING,
5773	.protocol_id = SMB20_PROT_ID,
5774	.req_capabilities = 0, /* MBZ */
5775	.large_lock_type = 0,
5776	.exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE,
5777	.shared_lock_type = SMB2_LOCKFLAG_SHARED,
5778	.unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
5779	.header_size = sizeof(struct smb2_hdr),
5780	.max_header_size = MAX_SMB2_HDR_SIZE,
5781	.read_rsp_size = sizeof(struct smb2_read_rsp),
5782	.lock_cmd = SMB2_LOCK,
5783	.cap_unix = 0,
5784	.cap_nt_find = SMB2_NT_FIND,
5785	.cap_large_files = SMB2_LARGE_FILES,
5786	.signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
5787	.signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
5788	.create_lease_size = sizeof(struct create_lease),
5789};
5790#endif /* ALLOW_INSECURE_LEGACY */
5791
5792struct smb_version_values smb21_values = {
5793	.version_string = SMB21_VERSION_STRING,
5794	.protocol_id = SMB21_PROT_ID,
5795	.req_capabilities = 0, /* MBZ on negotiate req until SMB3 dialect */
5796	.large_lock_type = 0,
5797	.exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE,
5798	.shared_lock_type = SMB2_LOCKFLAG_SHARED,
5799	.unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
5800	.header_size = sizeof(struct smb2_hdr),
5801	.max_header_size = MAX_SMB2_HDR_SIZE,
5802	.read_rsp_size = sizeof(struct smb2_read_rsp),
5803	.lock_cmd = SMB2_LOCK,
5804	.cap_unix = 0,
5805	.cap_nt_find = SMB2_NT_FIND,
5806	.cap_large_files = SMB2_LARGE_FILES,
5807	.signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
5808	.signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
5809	.create_lease_size = sizeof(struct create_lease),
5810};
5811
5812struct smb_version_values smb3any_values = {
5813	.version_string = SMB3ANY_VERSION_STRING,
5814	.protocol_id = SMB302_PROT_ID, /* doesn't matter, send protocol array */
5815	.req_capabilities = SMB2_GLOBAL_CAP_DFS | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_PERSISTENT_HANDLES | SMB2_GLOBAL_CAP_ENCRYPTION | SMB2_GLOBAL_CAP_DIRECTORY_LEASING,
5816	.large_lock_type = 0,
5817	.exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE,
5818	.shared_lock_type = SMB2_LOCKFLAG_SHARED,
5819	.unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
5820	.header_size = sizeof(struct smb2_hdr),
5821	.max_header_size = MAX_SMB2_HDR_SIZE,
5822	.read_rsp_size = sizeof(struct smb2_read_rsp),
5823	.lock_cmd = SMB2_LOCK,
5824	.cap_unix = 0,
5825	.cap_nt_find = SMB2_NT_FIND,
5826	.cap_large_files = SMB2_LARGE_FILES,
5827	.signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
5828	.signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
5829	.create_lease_size = sizeof(struct create_lease_v2),
5830};
5831
5832struct smb_version_values smbdefault_values = {
5833	.version_string = SMBDEFAULT_VERSION_STRING,
5834	.protocol_id = SMB302_PROT_ID, /* doesn't matter, send protocol array */
5835	.req_capabilities = SMB2_GLOBAL_CAP_DFS | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_PERSISTENT_HANDLES | SMB2_GLOBAL_CAP_ENCRYPTION | SMB2_GLOBAL_CAP_DIRECTORY_LEASING,
5836	.large_lock_type = 0,
5837	.exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE,
5838	.shared_lock_type = SMB2_LOCKFLAG_SHARED,
5839	.unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
5840	.header_size = sizeof(struct smb2_hdr),
5841	.max_header_size = MAX_SMB2_HDR_SIZE,
5842	.read_rsp_size = sizeof(struct smb2_read_rsp),
5843	.lock_cmd = SMB2_LOCK,
5844	.cap_unix = 0,
5845	.cap_nt_find = SMB2_NT_FIND,
5846	.cap_large_files = SMB2_LARGE_FILES,
5847	.signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
5848	.signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
5849	.create_lease_size = sizeof(struct create_lease_v2),
5850};
5851
5852struct smb_version_values smb30_values = {
5853	.version_string = SMB30_VERSION_STRING,
5854	.protocol_id = SMB30_PROT_ID,
5855	.req_capabilities = SMB2_GLOBAL_CAP_DFS | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_PERSISTENT_HANDLES | SMB2_GLOBAL_CAP_ENCRYPTION | SMB2_GLOBAL_CAP_DIRECTORY_LEASING,
5856	.large_lock_type = 0,
5857	.exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE,
5858	.shared_lock_type = SMB2_LOCKFLAG_SHARED,
5859	.unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
5860	.header_size = sizeof(struct smb2_hdr),
5861	.max_header_size = MAX_SMB2_HDR_SIZE,
5862	.read_rsp_size = sizeof(struct smb2_read_rsp),
5863	.lock_cmd = SMB2_LOCK,
5864	.cap_unix = 0,
5865	.cap_nt_find = SMB2_NT_FIND,
5866	.cap_large_files = SMB2_LARGE_FILES,
5867	.signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
5868	.signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
5869	.create_lease_size = sizeof(struct create_lease_v2),
5870};
5871
5872struct smb_version_values smb302_values = {
5873	.version_string = SMB302_VERSION_STRING,
5874	.protocol_id = SMB302_PROT_ID,
5875	.req_capabilities = SMB2_GLOBAL_CAP_DFS | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_PERSISTENT_HANDLES | SMB2_GLOBAL_CAP_ENCRYPTION | SMB2_GLOBAL_CAP_DIRECTORY_LEASING,
5876	.large_lock_type = 0,
5877	.exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE,
5878	.shared_lock_type = SMB2_LOCKFLAG_SHARED,
5879	.unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
5880	.header_size = sizeof(struct smb2_hdr),
5881	.max_header_size = MAX_SMB2_HDR_SIZE,
5882	.read_rsp_size = sizeof(struct smb2_read_rsp),
5883	.lock_cmd = SMB2_LOCK,
5884	.cap_unix = 0,
5885	.cap_nt_find = SMB2_NT_FIND,
5886	.cap_large_files = SMB2_LARGE_FILES,
5887	.signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
5888	.signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
5889	.create_lease_size = sizeof(struct create_lease_v2),
5890};
5891
5892struct smb_version_values smb311_values = {
5893	.version_string = SMB311_VERSION_STRING,
5894	.protocol_id = SMB311_PROT_ID,
5895	.req_capabilities = SMB2_GLOBAL_CAP_DFS | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_PERSISTENT_HANDLES | SMB2_GLOBAL_CAP_ENCRYPTION | SMB2_GLOBAL_CAP_DIRECTORY_LEASING,
5896	.large_lock_type = 0,
5897	.exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE,
5898	.shared_lock_type = SMB2_LOCKFLAG_SHARED,
5899	.unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
5900	.header_size = sizeof(struct smb2_hdr),
5901	.max_header_size = MAX_SMB2_HDR_SIZE,
5902	.read_rsp_size = sizeof(struct smb2_read_rsp),
5903	.lock_cmd = SMB2_LOCK,
5904	.cap_unix = 0,
5905	.cap_nt_find = SMB2_NT_FIND,
5906	.cap_large_files = SMB2_LARGE_FILES,
5907	.signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
5908	.signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
5909	.create_lease_size = sizeof(struct create_lease_v2),
5910};
~/ Read-only file preview.