// SPDX-License-Identifier: GPL-2.0-or-later
/*
 *   Copyright (C) 2016 Namjae Jeon <linkinjeon@kernel.org>
 *   Copyright (C) 2018 Samsung Electronics Co., Ltd.
 */

#include <crypto/utils.h>
#include <linux/inetdevice.h>
#include <net/addrconf.h>
#include <linux/syscalls.h>
#include <linux/namei.h>
#include <linux/fs_struct.h>
#include <linux/statfs.h>
#include <linux/ethtool.h>
#include <linux/falloc.h>
#include <linux/mount.h>
#include <linux/filelock.h>
#include <linux/fileattr.h>
#include <linux/math.h>
#include <linux/timekeeping.h>
#include <linux/unaligned.h>

#include "glob.h"
#include "../common/smbfsctl.h"
#include "oplock.h"
#include "smbacl.h"

#include "auth.h"
#include "asn1.h"
#include "connection.h"
#include "transport_ipc.h"
#include "transport_rdma.h"
#include "vfs.h"
#include "vfs_cache.h"
#include "misc.h"

#include "server.h"
#include "smb_common.h"
#include "../common/smb2status.h"
#include "ksmbd_work.h"
#include "mgmt/user_config.h"
#include "mgmt/share_config.h"
#include "mgmt/tree_connect.h"
#include "mgmt/user_session.h"
#include "mgmt/ksmbd_ida.h"
#include "ndr.h"
#include "stats.h"
#include "transport_tcp.h"
#include "compress.h"

static void __wbuf(struct ksmbd_work *work, void **req, void **rsp)
{
	if (work->next_smb2_rcv_hdr_off) {
		*req = ksmbd_req_buf_next(work);
		*rsp = ksmbd_resp_buf_next(work);
	} else {
		*req = smb_get_msg(work->request_buf);
		*rsp = smb_get_msg(work->response_buf);
	}
}

#define WORK_BUFFERS(w, rq, rs)	__wbuf((w), (void **)&(rq), (void **)&(rs))

#define SMB2_CREATE_FILE_ATTRIBUTE_MASK \
	(FILE_ATTRIBUTE_MASK & ~(FILE_ATTRIBUTE_INTEGRITY_STREAM | \
				 FILE_ATTRIBUTE_NO_SCRUB_DATA))

/* Windows reports automatic write-time updates at roughly 15 ms resolution. */
#define KSMBD_WRITE_TIME_RESOLUTION	(15ULL * 10000)

/* MAXFILESIZE in [MS-FSA] 2.1.5.3 Server Requests a Write. */
#define SMB2_MAX_FILE_SIZE		0xfffffff0000ULL

struct channel *lookup_chann_list(struct ksmbd_session *sess, struct ksmbd_conn *conn)
{
	struct channel *chann;

	down_read(&sess->chann_lock);
	chann = xa_load(&sess->ksmbd_chann_list, (long)conn);
	up_read(&sess->chann_lock);

	return chann;
}

static int register_session_channel(struct ksmbd_session *sess,
				    struct ksmbd_conn *conn,
				    const char *sess_key)
{
	struct channel *chann, *old;
	unsigned long index;
	unsigned int count = 0;
	int rc = 0;

	down_write(&sess->chann_lock);
	if (sess->tearing_down) {
		rc = -ESHUTDOWN;
		goto out;
	}

	if (xa_load(&sess->ksmbd_chann_list, (long)conn))
		goto out;

	xa_for_each(&sess->ksmbd_chann_list, index, chann)
		count++;
	if (count >= KSMBD_MAX_CHANNELS) {
		rc = -ENOSPC;
		goto out;
	}

	chann = kmalloc_obj(struct channel, KSMBD_DEFAULT_GFP);
	if (!chann) {
		rc = -ENOMEM;
		goto out;
	}

	if (sess->setup_conn != conn) {
		rc = ksmbd_session_reserve_slot(conn);
		if (rc) {
			kfree_sensitive(chann);
			goto out;
		}
	}

	chann->conn = ksmbd_conn_get(conn);
	memcpy(chann->sess_key, sess_key, sizeof(chann->sess_key));
	old = xa_store(&sess->ksmbd_chann_list, (long)conn, chann,
		       KSMBD_DEFAULT_GFP);
	if (xa_is_err(old)) {
		if (sess->setup_conn != conn)
			ksmbd_session_release_slot(conn);
		ksmbd_conn_put(chann->conn);
		kfree_sensitive(chann);
		rc = xa_err(old);
	} else if (sess->setup_conn == conn) {
		/* Transfer the initial reservation and reference to this channel. */
		sess->setup_conn = NULL;
		ksmbd_conn_put(conn);
	}
out:
	up_write(&sess->chann_lock);
	return rc;
}

/**
 * smb2_get_ksmbd_tcon() - get tree connection information using a tree id.
 * @work:	smb work
 *
 * Return:	0 if there is a tree connection matched or these are
 *		skipable commands, otherwise error
 */
int smb2_get_ksmbd_tcon(struct ksmbd_work *work)
{
	struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
	unsigned int cmd = le16_to_cpu(req_hdr->Command);
	unsigned int tree_id;

	if (cmd == SMB2_TREE_CONNECT_HE ||
	    cmd ==  SMB2_CANCEL_HE ||
	    cmd ==  SMB2_LOGOFF_HE) {
		ksmbd_debug(SMB, "skip to check tree connect request\n");
		return 0;
	}

	if (xa_empty(&work->sess->tree_conns)) {
		ksmbd_debug(SMB, "NO tree connected\n");
		return -ENOENT;
	}

	tree_id = le32_to_cpu(req_hdr->Id.SyncId.TreeId);

	/*
	 * If request is not the first in Compound request,
	 * Just validate tree id in header with work->tcon->id.
	 */
	if (work->next_smb2_rcv_hdr_off) {
		if (!work->tcon) {
			pr_err("The first operation in the compound does not have tcon\n");
			return -EINVAL;
		}
		if (work->tcon->t_state != TREE_CONNECTED)
			return -ENOENT;
		if (tree_id != UINT_MAX && work->tcon->id != tree_id) {
			pr_err("tree id(%u) is different with id(%u) in first operation\n",
					tree_id, work->tcon->id);
			return -EINVAL;
		}
		return 1;
	}

	work->tcon = ksmbd_tree_conn_lookup(work->sess, tree_id);
	if (!work->tcon) {
		pr_err("Invalid tid %d\n", tree_id);
		return -ENOENT;
	}

	return 1;
}

/**
 * smb2_set_err_rsp() - set error response code on smb response
 * @work:	smb work containing response buffer
 */
void smb2_set_err_rsp(struct ksmbd_work *work)
{
	struct smb2_err_rsp *err_rsp;

	if (work->next_smb2_rcv_hdr_off)
		err_rsp = ksmbd_resp_buf_next(work);
	else
		err_rsp = smb_get_msg(work->response_buf);

	if (err_rsp->hdr.Status != STATUS_STOPPED_ON_SYMLINK) {
		int err;

		err_rsp->StructureSize = SMB2_ERROR_STRUCTURE_SIZE2_LE;
		err_rsp->ErrorContextCount = 0;
		err_rsp->Reserved = 0;
		err_rsp->ByteCount = 0;
		err_rsp->ErrorData[0] = 0;
		err = ksmbd_iov_pin_rsp(work, (void *)err_rsp,
					__SMB2_HEADER_STRUCTURE_SIZE +
						SMB2_ERROR_STRUCTURE_SIZE2);
		if (err)
			work->send_no_response = 1;
	}
}

/**
 * is_smb2_neg_cmd() - is it smb2 negotiation command
 * @work:	smb work containing smb header
 *
 * Return:      true if smb2 negotiation command, otherwise false
 */
bool is_smb2_neg_cmd(struct ksmbd_work *work)
{
	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);

	/* is it SMB2 header ? */
	if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
		return false;

	/* make sure it is request not response message */
	if (hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR)
		return false;

	if (hdr->Command != SMB2_NEGOTIATE)
		return false;

	return true;
}

/**
 * is_smb2_rsp() - is it smb2 response
 * @work:	smb work containing smb response buffer
 *
 * Return:      true if smb2 response, otherwise false
 */
bool is_smb2_rsp(struct ksmbd_work *work)
{
	struct smb2_hdr *hdr = smb_get_msg(work->response_buf);

	/* is it SMB2 header ? */
	if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
		return false;

	/* make sure it is response not request message */
	if (!(hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR))
		return false;

	return true;
}

/**
 * get_smb2_cmd_val() - get smb command code from smb header
 * @work:	smb work containing smb request buffer
 *
 * Return:      smb2 request command value
 */
u16 get_smb2_cmd_val(struct ksmbd_work *work)
{
	struct smb2_hdr *rcv_hdr;

	if (work->next_smb2_rcv_hdr_off)
		rcv_hdr = ksmbd_req_buf_next(work);
	else
		rcv_hdr = smb_get_msg(work->request_buf);
	return le16_to_cpu(rcv_hdr->Command);
}

/**
 * set_smb2_rsp_status() - set error response code on smb2 header
 * @work:	smb work containing response buffer
 * @err:	error response code
 */
void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err)
{
	struct smb2_hdr *rsp_hdr;

	if (work->next_smb2_rcv_hdr_off) {
		rsp_hdr = ksmbd_resp_buf_next(work);
		rsp_hdr->Status = err;
		smb2_set_err_rsp(work);
		return;
	}

	rsp_hdr = smb_get_msg(work->response_buf);
	rsp_hdr->Status = err;

	work->iov_idx = 0;
	work->iov_cnt = 0;
	work->next_smb2_rcv_hdr_off = 0;
	smb2_set_err_rsp(work);
}

/**
 * init_smb2_neg_rsp() - initialize smb2 response for negotiate command
 * @work:	smb work containing smb request buffer
 *
 * smb2 negotiate response is sent in reply of smb1 negotiate command for
 * dialect auto-negotiation.
 */
int init_smb2_neg_rsp(struct ksmbd_work *work)
{
	struct smb2_hdr *rsp_hdr;
	struct smb2_negotiate_rsp *rsp;
	struct ksmbd_conn *conn = work->conn;
	int err;

	rsp_hdr = smb_get_msg(work->response_buf);
	memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
	rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
	rsp_hdr->CreditRequest = cpu_to_le16(2);
	rsp_hdr->Command = SMB2_NEGOTIATE;
	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
	rsp_hdr->NextCommand = 0;
	rsp_hdr->MessageId = 0;
	rsp_hdr->Id.SyncId.ProcessId = 0;
	rsp_hdr->Id.SyncId.TreeId = 0;
	rsp_hdr->SessionId = 0;
	memset(rsp_hdr->Signature, 0, 16);

	rsp = smb_get_msg(work->response_buf);

	WARN_ON(ksmbd_conn_good(conn));

	rsp->StructureSize = cpu_to_le16(65);
	ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
	rsp->DialectRevision = cpu_to_le16(conn->dialect);
	/* Not setting conn guid rsp->ServerGUID, as it
	 * not used by client for identifying connection
	 */
	rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
	/* Default Max Message Size till SMB2.0, 64K*/
	rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
	rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
	rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);

	rsp->SystemTime = cpu_to_le64(ksmbd_systime());
	rsp->ServerStartTime = 0;

	rsp->SecurityBufferOffset = cpu_to_le16(128);
	rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
	ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
		le16_to_cpu(rsp->SecurityBufferOffset));
	rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
	if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
		rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
	err = ksmbd_iov_pin_rsp(work, rsp,
				sizeof(struct smb2_negotiate_rsp) + AUTH_GSS_LENGTH);
	if (err)
		return err;
	conn->use_spnego = true;

	ksmbd_conn_set_need_negotiate(conn);
	return 0;
}

/**
 * smb2_set_rsp_credits() - set number of credits in response buffer
 * @work:	smb work containing smb response buffer
 */
int smb2_set_rsp_credits(struct ksmbd_work *work)
{
	struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
	struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
	struct ksmbd_conn *conn = work->conn;
	unsigned short credits_requested, aux_max;
	unsigned short credit_charge, credits_granted = 0;
	u64 window_room, i;

	if (work->send_no_response)
		return 0;

	hdr->CreditCharge = req_hdr->CreditCharge;

	if (conn->total_credits > conn->vals->max_credits) {
		hdr->CreditRequest = 0;
		pr_err("Total credits overflow: %d\n", conn->total_credits);
		return -EINVAL;
	}

	credit_charge = max_t(unsigned short,
			      le16_to_cpu(req_hdr->CreditCharge), 1);
	if (credit_charge > conn->total_credits) {
		ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n",
			    credit_charge, conn->total_credits);
		return -EINVAL;
	}

	conn->total_credits -= credit_charge;
	conn->outstanding_credits -= credit_charge;
	work->credit_charge = 0;
	credits_requested = max_t(unsigned short,
				  le16_to_cpu(req_hdr->CreditRequest), 1);

	/* according to smb2.credits smbtorture, Windows server
	 * 2016 or later grant up to 8192 credits at once.
	 *
	 * TODO: Need to adjuct CreditRequest value according to
	 * current cpu load
	 */
	if (hdr->Command == SMB2_NEGOTIATE)
		aux_max = 1;
	else
		aux_max = conn->vals->max_credits - conn->total_credits;

	/*
	 * The command sequence window must not grow beyond
	 * KSMBD_CMD_SEQ_WINDOW sequence numbers ahead of the oldest one still
	 * outstanding. Cap the grant by the room left in the window so that
	 * credits are withheld until the client consumes the low end (and so
	 * that seq_bitmap stays usable as a ring).
	 */
	window_room = conn->seq_low + KSMBD_CMD_SEQ_WINDOW - conn->seq_high;
	aux_max = min_t(unsigned short, aux_max, window_room);
	credits_granted = min_t(unsigned short, credits_requested, aux_max);

	conn->total_credits += credits_granted;
	work->credits_granted += credits_granted;

	/* Extend the sequence window to cover the newly granted credits. */
	for (i = conn->seq_high; i < conn->seq_high + credits_granted; i++)
		__set_bit(i & (KSMBD_CMD_SEQ_WINDOW - 1), conn->seq_bitmap);
	conn->seq_high += credits_granted;

	if (!req_hdr->NextCommand) {
		/* Update CreditRequest in last request */
		hdr->CreditRequest = cpu_to_le16(work->credits_granted);
	}
	ksmbd_debug(SMB,
		    "credits: requested[%d] granted[%d] total_granted[%d]\n",
		    credits_requested, credits_granted,
		    conn->total_credits);
	return 0;
}

static bool smb2_get_file_ids(struct smb2_hdr *hdr, u64 *volatile_id,
			      u64 *persistent_id)
{
	unsigned int offset;

	switch (hdr->Command) {
	case SMB2_CLOSE:
		offset = offsetof(struct smb2_close_req, PersistentFileId);
		break;
	case SMB2_FLUSH:
		offset = offsetof(struct smb2_flush_req, PersistentFileId);
		break;
	case SMB2_READ:
		offset = offsetof(struct smb2_read_req, PersistentFileId);
		break;
	case SMB2_WRITE:
		offset = offsetof(struct smb2_write_req, PersistentFileId);
		break;
	case SMB2_LOCK:
		offset = offsetof(struct smb2_lock_req, PersistentFileId);
		break;
	case SMB2_IOCTL: {
		struct smb2_ioctl_req *req = (struct smb2_ioctl_req *)hdr;

		switch (le32_to_cpu(req->CtlCode)) {
		case FSCTL_DFS_GET_REFERRALS:
		case FSCTL_DFS_GET_REFERRALS_EX:
		case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
		case FSCTL_VALIDATE_NEGOTIATE_INFO:
		case FSCTL_PIPE_WAIT:
			return false;
		}
		offset = offsetof(struct smb2_ioctl_req, PersistentFileId);
		break;
	}
	case SMB2_QUERY_DIRECTORY:
		offset = offsetof(struct smb2_query_directory_req, PersistentFileId);
		break;
	case SMB2_CHANGE_NOTIFY:
		offset = offsetof(struct smb2_change_notify_req, PersistentFileId);
		break;
	case SMB2_QUERY_INFO:
		offset = offsetof(struct smb2_query_info_req, PersistentFileId);
		break;
	case SMB2_SET_INFO:
		offset = offsetof(struct smb2_set_info_req, PersistentFileId);
		break;
	case SMB2_OPLOCK_BREAK:
		if (((struct smb2_oplock_break *)hdr)->StructureSize !=
		    cpu_to_le16(OP_BREAK_STRUCT_SIZE_20))
			return false;
		offset = offsetof(struct smb2_oplock_break, PersistentFid);
		break;
	default:
		return false;
	}

	/* FileId contains consecutive persistent and volatile opaque values. */
	memcpy(persistent_id, (char *)hdr + offset, sizeof(*persistent_id));
	memcpy(volatile_id, (char *)hdr + offset + sizeof(*persistent_id),
	       sizeof(*volatile_id));
	return true;
}

/* Called after message validation and signature verification. */
bool smb2_check_compound_fid(struct ksmbd_work *work)
{
	struct smb2_hdr *req = ksmbd_req_buf_next(work);
	struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
	u64 volatile_id, persistent_id;

	if (!work->next_smb2_rcv_hdr_off ||
	    !(req->Flags & SMB2_FLAGS_RELATED_OPERATIONS))
		return false;

	if (!work->compound_fid_missing &&
	    !work->compound_fid_present &&
	    smb2_get_file_ids(req, &volatile_id, &persistent_id))
		work->compound_fid_missing = true;

	if (!work->compound_fid_missing)
		return false;

	/* MS-SMB2 3.3.5.2.7.2 requires all subsequent operations to fail too. */
	rsp->Status = STATUS_INVALID_HANDLE;
	smb2_set_err_rsp(work);
	return true;
}

/**
 * init_chained_smb2_rsp() - initialize smb2 chained response
 * @work:	smb work containing smb response buffer
 */
static void init_chained_smb2_rsp(struct ksmbd_work *work)
{
	struct smb2_hdr *req = ksmbd_req_buf_next(work);
	struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
	struct smb2_hdr *rsp_hdr;
	struct smb2_hdr *rcv_hdr;
	int next_hdr_offset = 0;
	int len, new_len;
	u64 volatile_id = KSMBD_NO_FID, persistent_id = KSMBD_NO_FID;
	bool req_has_fid;

	req_has_fid = smb2_get_file_ids(req, &volatile_id, &persistent_id);
	/* A failed CREATE is handled through compound_status instead. */
	work->compound_fid_present = req_has_fid || req->Command == SMB2_CREATE;
	if (!work->compound_fid_present) {
		work->compound_fid = KSMBD_NO_FID;
		work->compound_pfid = KSMBD_NO_FID;
	}

	/* Related requests keep the inherited SessionId. */
	if (!work->next_smb2_rcv_hdr_off ||
	    !(req->Flags & SMB2_FLAGS_RELATED_OPERATIONS))
		work->compound_sid = le64_to_cpu(rsp->SessionId);

	/* Len of this response = updated RFC len - offset of previous cmd
	 * in the compound rsp
	 */

	/* Storing the current local FID which may be needed by subsequent
	 * command in the compound request
	 */
	if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
		work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId;
		work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId;
		work->compound_status = STATUS_SUCCESS;
	} else if (rsp->Status == STATUS_SUCCESS) {
		if (req_has_fid && req->Command != SMB2_CLOSE) {
			/* Preserve the inherited FID when the request uses all ones. */
			if (has_file_id(volatile_id)) {
				work->compound_fid = volatile_id;
				work->compound_pfid = persistent_id;
			}
		} else {
			work->compound_fid = KSMBD_NO_FID;
			work->compound_pfid = KSMBD_NO_FID;
		}
		work->compound_status = STATUS_SUCCESS;
	} else if (req->Command == SMB2_CREATE) {
		work->compound_fid = KSMBD_NO_FID;
		work->compound_pfid = KSMBD_NO_FID;
		work->compound_status = rsp->Status;
	} else if (rsp->Status != STATUS_SUCCESS) {
		/*
		 * Only carry the failed status forward when the failing command
		 * was itself part of the related chain. An unrelated command
		 * that fails (e.g. a standalone request with a bad session id)
		 * must not seed the status for a following related command,
		 * which has to be evaluated on its own (and may legitimately
		 * fail with a different status such as INVALID_PARAMETER). The
		 * compound session id is still tracked so a following related
		 * command can validate it.
		 */
		if (req->Flags & SMB2_FLAGS_RELATED_OPERATIONS)
			work->compound_status = rsp->Status;
	}

	len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
	next_hdr_offset = le32_to_cpu(req->NextCommand);

	new_len = ALIGN(len, 8);
	work->iov[work->iov_idx].iov_len += (new_len - len);
	inc_rfc1001_len(work->response_buf, new_len - len);
	rsp->NextCommand = cpu_to_le32(new_len);

	work->next_smb2_rcv_hdr_off += next_hdr_offset;
	work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
	work->next_smb2_rsp_hdr_off += new_len;
	ksmbd_debug(SMB,
		    "Compound req new_len = %d rcv off = %d rsp off = %d\n",
		    new_len, work->next_smb2_rcv_hdr_off,
		    work->next_smb2_rsp_hdr_off);

	rsp_hdr = ksmbd_resp_buf_next(work);
	rcv_hdr = ksmbd_req_buf_next(work);

	if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
		ksmbd_debug(SMB, "related flag should be set\n");
		work->compound_fid = KSMBD_NO_FID;
		work->compound_pfid = KSMBD_NO_FID;
		work->compound_status = STATUS_SUCCESS;
		work->compound_fid_present = false;
		work->compound_fid_missing = false;
	}
	memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
	rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
	rsp_hdr->Command = rcv_hdr->Command;

	/*
	 * Message is response. We don't grant oplock yet.
	 */
	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
				SMB2_FLAGS_RELATED_OPERATIONS);
	if (rcv_hdr->Flags & SMB2_FLAGS_REPLAY_OPERATION)
		rsp_hdr->Flags |= SMB2_FLAGS_REPLAY_OPERATION;
	rsp_hdr->NextCommand = 0;
	rsp_hdr->MessageId = rcv_hdr->MessageId;
	rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
	rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
	rsp_hdr->SessionId = rcv_hdr->SessionId;
	memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
}

static bool smb2_compound_has_failed(struct ksmbd_work *work,
				     struct smb2_hdr *rsp)
{
	if (!work->next_smb2_rcv_hdr_off ||
	    has_file_id(work->compound_fid) ||
	    work->compound_status == STATUS_SUCCESS)
		return false;

	rsp->Status = work->compound_status;
	smb2_set_err_rsp(work);
	return true;
}

/**
 * is_chained_smb2_message() - check for chained command
 * @work:	smb work containing smb request buffer
 *
 * Return:      true if chained request, otherwise false
 */
bool is_chained_smb2_message(struct ksmbd_work *work)
{
	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
	unsigned int len, next_cmd;

	if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
		return false;

	hdr = ksmbd_req_buf_next(work);
	next_cmd = le32_to_cpu(hdr->NextCommand);
	if (next_cmd > 0) {
		size_t next_rsp_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
		struct smb2_hdr *next_hdr;

		if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
			__SMB2_HEADER_STRUCTURE_SIZE >
		    get_rfc1002_len(work->request_buf)) {
			pr_err("next command(%u) offset exceeds smb msg size\n",
			       next_cmd);
			return false;
		}

		/*
		 * The next response starts at the 8-byte aligned end of this one.
		 * smb2_open() appends create contexts without checking the space
		 * left, so reserve the largest CREATE response for a chained
		 * CREATE, as smb2_allocate_rsp_buf() does for a single one.
		 */
		next_hdr = (struct smb2_hdr *)((char *)hdr + next_cmd);
		if (le16_to_cpu(next_hdr->Command) == SMB2_CREATE_HE)
			next_rsp_sz = max_t(size_t, next_rsp_sz,
					    work->conn->vals->create_rsp_size);

		if ((u64)ALIGN(get_rfc1002_len(work->response_buf), 8) +
		    next_rsp_sz > work->response_sz) {
			pr_err("next response offset exceeds response buffer size\n");
			return false;
		}

		ksmbd_debug(SMB, "got SMB2 chained command\n");
		init_chained_smb2_rsp(work);
		return true;
	} else if (work->next_smb2_rcv_hdr_off) {
		/*
		 * This is last request in chained command,
		 * align response to 8 byte
		 */
		len = ALIGN(get_rfc1002_len(work->response_buf), 8);
		len = len - get_rfc1002_len(work->response_buf);
		if (len) {
			ksmbd_debug(SMB, "padding len %u\n", len);
			work->iov[work->iov_idx].iov_len += len;
			inc_rfc1001_len(work->response_buf, len);
		}
		work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
	}
	return false;
}

/**
 * init_smb2_rsp_hdr() - initialize smb2 response
 * @work:	smb work containing smb request buffer
 *
 * Return:      0
 */
int init_smb2_rsp_hdr(struct ksmbd_work *work)
{
	struct smb2_hdr *rsp_hdr = smb_get_msg(work->response_buf);
	struct smb2_hdr *rcv_hdr = smb_get_msg(work->request_buf);

	memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
	rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
	rsp_hdr->Command = rcv_hdr->Command;

	/*
	 * Message is response. We don't grant oplock yet.
	 */
	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
	if (rcv_hdr->Flags & SMB2_FLAGS_REPLAY_OPERATION)
		rsp_hdr->Flags |= SMB2_FLAGS_REPLAY_OPERATION;
	rsp_hdr->NextCommand = 0;
	rsp_hdr->MessageId = rcv_hdr->MessageId;
	rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
	rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
	rsp_hdr->SessionId = rcv_hdr->SessionId;
	memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);

	return 0;
}

static __le16 smb3_hdr_channel_sequence(struct smb2_hdr *hdr)
{
	return ((struct smb3_hdr_req *)hdr)->ChannelSequence;
}

static bool smb3_hdr_replay(struct smb2_hdr *hdr)
{
	return hdr->Flags & SMB2_FLAGS_REPLAY_OPERATION;
}

static int smb3_verify_channel_sequence(struct ksmbd_work *work,
					struct ksmbd_file *fp,
					struct smb2_hdr *hdr,
					bool allow_stale)
{
	__le16 chseq_le;
	u16 chseq, old_chseq;
	int ret = 0;

	if (work->conn->dialect < SMB30_PROT_ID)
		return 0;

	chseq_le = smb3_hdr_channel_sequence(hdr);
	chseq = le16_to_cpu(chseq_le);

	spin_lock(&fp->f_lock);
	old_chseq = le16_to_cpu(fp->channel_sequence);
	if (smb3_hdr_replay(hdr)) {
		if (chseq == old_chseq && fp->outstanding_pre_requests == 0) {
			fp->outstanding_requests++;
		} else if ((u16)(chseq - old_chseq) <= 0x7fff &&
			   fp->outstanding_pre_requests == 0) {
			fp->outstanding_pre_requests += fp->outstanding_requests;
			fp->outstanding_requests = 1;
			fp->channel_sequence = chseq_le;
		} else if (allow_stale) {
			fp->outstanding_pre_requests++;
		} else {
			ret = -EAGAIN;
		}
	} else {
		if (chseq == old_chseq) {
			fp->outstanding_requests++;
		} else if ((u16)(chseq - old_chseq) <= 0x7fff) {
			fp->outstanding_pre_requests += fp->outstanding_requests;
			fp->outstanding_requests = 1;
			fp->channel_sequence = chseq_le;
		} else if (allow_stale) {
			fp->outstanding_pre_requests++;
		} else {
			ret = -EAGAIN;
		}
	}
	spin_unlock(&fp->f_lock);

	return ret;
}

static void smb3_complete_channel_sequence(struct ksmbd_work *work,
					   struct ksmbd_file *fp,
					   __le16 chseq_le)
{
	u16 chseq;

	if (work->conn->dialect < SMB30_PROT_ID)
		return;

	chseq = le16_to_cpu(chseq_le);

	spin_lock(&fp->f_lock);
	if (chseq == le16_to_cpu(fp->channel_sequence)) {
		if (fp->outstanding_requests)
			fp->outstanding_requests--;
	} else {
		if (fp->outstanding_pre_requests)
			fp->outstanding_pre_requests--;
	}
	spin_unlock(&fp->f_lock);
}

static int smb2_set_request_open(struct ksmbd_work *work, struct ksmbd_file *fp,
				 struct smb2_hdr *hdr, bool verify_chseq,
				 bool allow_stale_chseq)
{
	struct ksmbd_file *open;
	int ret;

	smb2_complete_request_open(work);

	open = ksmbd_file_get(fp);
	if (!open)
		return -ESTALE;

	if (verify_chseq) {
		ret = smb3_verify_channel_sequence(work, fp, hdr,
						   allow_stale_chseq);
		if (ret) {
			ksmbd_fd_put(work, open);
			return ret;
		}
		work->request_open_chseq_tracked = true;
	}

	work->request_open = open;
	work->request_open_chseq = smb3_hdr_channel_sequence(hdr);
	return 0;
}

void smb2_complete_request_open(struct ksmbd_work *work)
{
	struct ksmbd_file *open = work->request_open;

	if (!open)
		return;

	if (work->request_open_chseq_tracked)
		smb3_complete_channel_sequence(work, open,
					       work->request_open_chseq);

	work->request_open = NULL;
	work->request_open_chseq_tracked = false;
	ksmbd_fd_put(work, open);
}

static bool smb2_lock_sequence_applicable(struct ksmbd_work *work,
					  struct ksmbd_file *fp)
{
	return fp->is_resilient || fp->is_durable || fp->is_persistent ||
	       (work->conn->dialect >= SMB30_PROT_ID &&
		(work->conn->vals->req_capabilities &
		 SMB2_GLOBAL_CAP_MULTI_CHANNEL));
}

static bool smb2_verify_lock_sequence(struct ksmbd_work *work,
				       struct ksmbd_file *fp,
				       struct smb2_lock_req *req)
{
	u32 val, index;
	u8 sequence;
	bool replay = false;

	if (work->conn->dialect == SMB20_PROT_ID ||
	    !smb2_lock_sequence_applicable(work, fp))
		return false;

	val = le32_to_cpu(req->LockSequenceNumber);
	sequence = val & 0xf;
	index = val >> 4;
	if (!index || index > KSMBD_LOCK_SEQ_ARRAY_SIZE)
		return false;

	spin_lock(&fp->f_lock);
	if (fp->lock_seq[index - 1].valid) {
		if (fp->lock_seq[index - 1].sequence == sequence)
			replay = true;
		else
			fp->lock_seq[index - 1].valid = false;
	}
	spin_unlock(&fp->f_lock);

	return replay;
}

static void smb2_update_lock_sequence(struct ksmbd_work *work,
				      struct ksmbd_file *fp,
				      struct smb2_lock_req *req)
{
	u32 val, index;
	u8 sequence;

	if (work->conn->dialect == SMB20_PROT_ID ||
	    !smb2_lock_sequence_applicable(work, fp))
		return;

	val = le32_to_cpu(req->LockSequenceNumber);
	sequence = val & 0xf;
	index = val >> 4;
	if (!index || index > KSMBD_LOCK_SEQ_ARRAY_SIZE)
		return;

	spin_lock(&fp->f_lock);
	fp->lock_seq[index - 1].valid = true;
	fp->lock_seq[index - 1].sequence = sequence;
	spin_unlock(&fp->f_lock);
}

/**
 * smb2_allocate_rsp_buf() - allocate smb2 response buffer
 * @work:	smb work containing smb request buffer
 *
 * Return:      0 on success, otherwise error
 */
int smb2_allocate_rsp_buf(struct ksmbd_work *work)
{
	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
	struct smb_version_values *vals = work->conn->vals;
	size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
	size_t large_sz = small_sz + vals->max_trans_size;
	size_t sz = small_sz, pad_sz = 0;
	int cmd = le16_to_cpu(hdr->Command);

	if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
		sz = large_sz;

	if (cmd == SMB2_CREATE_HE)
		sz = max_t(size_t, sz, vals->create_rsp_size);

	if (cmd == SMB2_QUERY_INFO_HE) {
		struct smb2_query_info_req *req;

		if (get_rfc1002_len(work->request_buf) <
		    offsetof(struct smb2_query_info_req, OutputBufferLength))
			return -EINVAL;

		req = smb_get_msg(work->request_buf);
		if ((req->InfoType == SMB2_O_INFO_FILE &&
		     (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
		      req->FileInfoClass == FILE_ALL_INFORMATION ||
		      req->FileInfoClass == FILE_NORMALIZED_NAME_INFORMATION ||
		      req->FileInfoClass == FILE_STREAM_INFORMATION)) ||
		    req->InfoType == SMB2_O_INFO_SECURITY)
			sz = large_sz;
	}

	/* allocate large response buf for chained commands */
	if (le32_to_cpu(hdr->NextCommand) > 0) {
		sz = large_sz;
		/*
		 * is_chained_smb2_message() pads the last response of a
		 * compound to 8 bytes, which can take it past response_sz.
		 * Leave room for the padding. kvzalloc() zeroes it.
		 */
		pad_sz = ALIGN(sz - sizeof(__be32), 8) - (sz - sizeof(__be32));
	}

	work->response_buf = kvzalloc(sz + pad_sz, KSMBD_DEFAULT_GFP);
	if (!work->response_buf)
		return -ENOMEM;

	work->response_sz = sz;
	return 0;
}

static bool smb2_session_expired_cmd_allowed(struct ksmbd_work *work,
					      unsigned int cmd)
{
	struct smb2_lock_req *req;
	unsigned int len, lock_count, i;

	if (cmd == SMB2_CANCEL_HE || cmd == SMB2_CLOSE_HE ||
	    cmd == SMB2_LOGOFF_HE)
		return true;
	if (cmd != SMB2_LOCK_HE)
		return false;

	req = ksmbd_req_buf_next(work);
	if (req->hdr.NextCommand)
		len = le32_to_cpu(req->hdr.NextCommand);
	else {
		len = get_rfc1002_len(work->request_buf);
		if (len < work->next_smb2_rcv_hdr_off)
			return false;
		len -= work->next_smb2_rcv_hdr_off;
	}

	lock_count = le16_to_cpu(req->LockCount);
	if (!lock_count || len < offsetof(struct smb2_lock_req, locks) ||
	    lock_count > (len - offsetof(struct smb2_lock_req, locks)) /
			 sizeof(struct smb2_lock_element))
		return false;

	for (i = 0; i < lock_count; i++) {
		if (le32_to_cpu(req->locks[i].Flags) != SMB2_LOCKFLAG_UNLOCK)
			return false;
	}
	return true;
}

static bool smb2_session_kerberos_expired(struct ksmbd_session *sess)
{
	if (!sess->kerberos_expiry ||
	    ktime_get_real_seconds() < sess->kerberos_expiry)
		return false;

	if (cmpxchg(&sess->state, SMB2_SESSION_VALID,
		    SMB2_SESSION_EXPIRED) == SMB2_SESSION_VALID)
		ksmbd_counter_inc(KSMBD_COUNTER_SESSION_TIMEOUTS);
	return true;
}

/**
 * smb2_check_user_session() - check for valid session for a user
 * @work:	smb work containing smb request buffer
 *
 * Return:      0 on success, otherwise error
 */
int smb2_check_user_session(struct ksmbd_work *work)
{
	struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
	struct ksmbd_conn *conn = work->conn;
	unsigned int cmd = le16_to_cpu(req_hdr->Command);
	unsigned long long sess_id;

	/*
	 * SMB2_NEGOTIATE and SMB2_SESSION_SETUP do not require a session id.
	 * SMB2_ECHO may omit it, but an echo carrying a session id still needs
	 * the session attached to work so that its signature can be checked and
	 * the response can be signed, including after Kerberos expiry.
	 */
	if (cmd == SMB2_NEGOTIATE_HE || cmd == SMB2_SESSION_SETUP_HE)
		return 0;

	sess_id = le64_to_cpu(req_hdr->SessionId);
	if (cmd == SMB2_ECHO_HE) {
		/*
		 * ECHO remains valid without a live session, including after
		 * LOGOFF. Attach an existing session only to authenticate a signed
		 * ECHO and sign its response; a stale SessionId is not an error.
		 */
		if (!work->next_smb2_rcv_hdr_off && sess_id)
			work->sess = ksmbd_session_lookup_all_states(conn, sess_id);
		if (work->sess) {
			if (!smb2_session_kerberos_expired(work->sess) &&
			    work->sess->state != SMB2_SESSION_VALID) {
				ksmbd_user_session_put(work->sess);
				work->sess = NULL;
			}
		}
		return 0;
	}

	if (!ksmbd_conn_good(conn))
		return -EIO;

	/*
	 * If request is not the first in Compound request,
	 * Just validate session id in header with work->sess->id.
	 */
	if (work->next_smb2_rcv_hdr_off) {
		if (!work->sess) {
			pr_err("The first operation in the compound does not have sess\n");
			return -EINVAL;
		}
		if (sess_id != ULLONG_MAX && work->sess->id != sess_id) {
			pr_err("session id(%llu) is different with the first operation(%lld)\n",
					sess_id, work->sess->id);
			return -EINVAL;
		}
		smb2_session_kerberos_expired(work->sess);
		if (work->sess->state != SMB2_SESSION_VALID) {
			pr_err("compound request on a non-valid session (state %d)\n",
					work->sess->state);
			if (smb2_session_kerberos_expired(work->sess) &&
			    smb2_session_expired_cmd_allowed(work, cmd))
				return 1;
			return smb2_session_kerberos_expired(work->sess) ?
				-EKEYEXPIRED : -EINVAL;
		}
		return 1;
	}

	/* Check for validity of user session */
	work->sess = ksmbd_session_lookup_all_states(conn, sess_id);
	if (work->sess) {
		if (smb2_session_kerberos_expired(work->sess)) {
			return smb2_session_expired_cmd_allowed(work, cmd) ?
				1 : -EKEYEXPIRED;
		}
		if (work->sess->state != SMB2_SESSION_VALID) {
			/*
			 * Keep the reference for an encrypted request so the caller can
			 * return STATUS_USER_SESSION_DELETED encrypted with the old key.
			 */
			if (work->encrypted &&
			    work->sess->state == SMB2_SESSION_EXPIRED &&
			    work->sess->enc)
				return -ENOENT;
			ksmbd_user_session_put(work->sess);
			work->sess = NULL;
			return -ENOENT;
		}
		return 1;
	}
	ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
	return -ENOENT;
}

/**
 * smb2_get_name() - get filename string from on the wire smb format
 * @src:	source buffer
 * @maxlen:	maxlen of source string
 * @local_nls:	nls_table pointer
 *
 * Return:      matching converted filename on success, otherwise error ptr
 */
static char *
smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
{
	char *name;

	name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
	if (IS_ERR(name)) {
		pr_err("failed to get name %ld\n", PTR_ERR(name));
		return name;
	}

	if (*name == '\0') {
		kfree(name);
		return ERR_PTR(-EINVAL);
	}

	if (*name == '\\') {
		pr_err("not allow directory name included leading slash\n");
		kfree(name);
		return ERR_PTR(-EINVAL);
	}

	ksmbd_conv_path_to_unix(name);
	ksmbd_strip_last_slash(name);
	return name;
}

/* Link a fully initialized async work item unless the connection is closing. */
static bool ksmbd_conn_link_async_request(struct ksmbd_conn *conn,
					  struct ksmbd_work *work)
{
	bool linked = false;

	spin_lock(&conn->request_lock);
	if (!ksmbd_conn_exiting(conn) && !ksmbd_conn_releasing(conn)) {
		if (list_empty(&work->async_request_entry))
			list_add_tail(&work->async_request_entry,
				      &conn->async_requests);
		linked = true;
	}
	spin_unlock(&conn->request_lock);

	return linked;
}

int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
{
	struct ksmbd_conn *conn = work->conn;
	int id;

	id = ksmbd_acquire_async_msg_id(&conn->async_ida);
	if (id < 0) {
		pr_err("Failed to alloc async message id\n");
		return id;
	}
	work->asynchronous = true;
	work->async_id = id;
	work->cancel_fn = fn;
	work->cancel_argv = arg;

	if (!ksmbd_conn_link_async_request(conn, work)) {
		work->asynchronous = false;
		work->async_id = 0;
		work->cancel_fn = NULL;
		work->cancel_argv = NULL;
		ksmbd_release_id(&conn->async_ida, id);
		return -ESHUTDOWN;
	}

	ksmbd_debug(SMB,
		    "Send interim Response to inform async request id : %d\n",
		    work->async_id);

	return 0;
}

void release_async_work(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;

	spin_lock(&conn->request_lock);
	list_del_init(&work->async_request_entry);
	spin_unlock(&conn->request_lock);

	work->asynchronous = 0;
	work->cancel_fn = NULL;
	kfree(work->cancel_argv);
	work->cancel_argv = NULL;
	if (work->async_id) {
		ksmbd_release_id(&conn->async_ida, work->async_id);
		work->async_id = 0;
	}
}

static int smb2_send_interim_work(struct ksmbd_work *in_work,
				  struct ksmbd_work *work, bool eor)
{
	int err = 0;

	in_work->encrypted = work->encrypted;
	if (work->encrypted && work->sess && work->sess->enc &&
	    work->conn->ops->encrypt_resp) {
		in_work->sess = work->sess;
		err = work->conn->ops->encrypt_resp(in_work);
		in_work->sess = NULL;
	}
	if (err)
		return err;

	return eor ? ksmbd_conn_write_eor(in_work) :
		ksmbd_conn_write(in_work);
}

static int smb2_send_interim_prefix_work(struct ksmbd_work *work)
{
	struct ksmbd_work *in_work;
	unsigned int len, copied = 0;
	char *dst;
	int err = -ENOMEM;
	int i;

	len = get_rfc1002_len(work->iov[0].iov_base);
	in_work = ksmbd_alloc_work_struct();
	if (!in_work)
		return err;

	in_work->response_buf = kvzalloc(len + 4, KSMBD_DEFAULT_GFP);
	if (!in_work->response_buf)
		goto out;
	in_work->response_sz = len + 4;
	in_work->conn = work->conn;
	dst = in_work->response_buf + 4;
	for (i = 1; i <= work->iov_idx; i++) {
		if (work->iov[i].iov_len > len - copied) {
			err = -EINVAL;
			goto out;
		}
		memcpy(dst + copied, work->iov[i].iov_base,
		       work->iov[i].iov_len);
		copied += work->iov[i].iov_len;
	}
	if (copied != len) {
		err = -EINVAL;
		goto out;
	}

	err = ksmbd_iov_pin_rsp(in_work, dst, len);
	if (!err)
		err = smb2_send_interim_work(in_work, work, true);
out:
	ksmbd_free_work_struct(in_work);
	return err;
}

static void smb2_send_interim_compound_prefix(struct ksmbd_work *work)
{
	struct smb2_hdr *req_hdr;
	struct smb2_hdr *rsp_hdr;
	int err;

	if (!work->next_smb2_rcv_hdr_off ||
	    !work->next_smb2_rsp_hdr_off ||
	    work->curr_smb2_rsp_hdr_off == work->next_smb2_rsp_hdr_off ||
	    !work->iov_idx)
		return;

	req_hdr = ksmbd_req_buf_next(work);
	/* Detach only the final async command from the completed prefix. */
	if (req_hdr->NextCommand)
		return;

	/*
	 * The responses before the async command are sent as a standalone
	 * compound response. The last response in this prefix must terminate
	 * the chain.
	 */
	rsp_hdr = ksmbd_resp_buf_curr(work);
	rsp_hdr->NextCommand = 0;
	if ((rsp_hdr->Flags & SMB2_FLAGS_SIGNED) && work->sess &&
	    work->conn->ops->set_sign_rsp)
		work->conn->ops->set_sign_rsp(work);

	err = smb2_send_interim_prefix_work(work);
	if (err)
		ksmbd_debug(SMB, "failed to send compound interim prefix: %d\n",
			    err);

	work->iov_idx = 0;
	work->iov_cnt = 0;
	work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
	*(__be32 *)work->response_buf = 0;

	rsp_hdr = ksmbd_resp_buf_next(work);
	rsp_hdr->Flags &= ~SMB2_FLAGS_RELATED_OPERATIONS;
}

void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
{
	struct smb2_hdr *rsp_hdr;
	struct ksmbd_work *in_work = ksmbd_alloc_work_struct();
	u16 command;

	if (!in_work)
		return;

	if (allocate_interim_rsp_buf(in_work)) {
		pr_err("smb_allocate_rsp_buf failed!\n");
		ksmbd_free_work_struct(in_work);
		return;
	}

	if (status == STATUS_PENDING)
		smb2_send_interim_compound_prefix(work);

	in_work->conn = work->conn;
	memcpy(smb_get_msg(in_work->response_buf), ksmbd_resp_buf_next(work),
	       __SMB2_HEADER_STRUCTURE_SIZE);

	rsp_hdr = smb_get_msg(in_work->response_buf);
	rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
	rsp_hdr->Id.AsyncId = cpu_to_le64(work->async_id);
	smb2_set_err_rsp(in_work);
	rsp_hdr->Status = status;

	/*
	 * Async interim responses are unsigned, but final responses must
	 * follow the normal signing rules. The synthetic work has no
	 * request buffer, so use the original work for request signing
	 * checks and the response header for SMB3 command selection.
	 */
	command = work->conn->ops->get_cmd_val(work);
	if (status != STATUS_PENDING && !work->encrypted && work->sess &&
	    work->conn->ops->set_sign_rsp &&
	    (work->sess->sign ||
	     (work->conn->ops->is_sign_req &&
	      work->conn->ops->is_sign_req(work, command)))) {
		in_work->sess = work->sess;
		work->conn->ops->set_sign_rsp(in_work);
		in_work->sess = NULL;
	}

	if (smb2_send_interim_work(in_work, work, true))
		ksmbd_debug(SMB, "failed to send interim response\n");
	ksmbd_free_work_struct(in_work);
}

__le32 smb2_get_reparse_tag_special_file(umode_t mode)
{
	if (S_ISDIR(mode) || S_ISREG(mode))
		return 0;

	if (S_ISLNK(mode))
		return IO_REPARSE_TAG_LX_SYMLINK_LE;
	else if (S_ISFIFO(mode))
		return IO_REPARSE_TAG_LX_FIFO_LE;
	else if (S_ISSOCK(mode))
		return IO_REPARSE_TAG_AF_UNIX_LE;
	else if (S_ISCHR(mode))
		return IO_REPARSE_TAG_LX_CHR_LE;
	else if (S_ISBLK(mode))
		return IO_REPARSE_TAG_LX_BLK_LE;

	return 0;
}

/**
 * smb2_get_dos_mode() - get file mode in dos format from unix mode
 * @stat:	kstat containing file mode
 * @attribute:	attribute flags
 *
 * Return:      converted dos mode
 */
static int smb2_get_dos_mode(struct kstat *stat, int attribute)
{
	int attr = 0;

	if (S_ISDIR(stat->mode)) {
		attr = FILE_ATTRIBUTE_DIRECTORY |
			(attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
	} else {
		attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
		attr &= ~(FILE_ATTRIBUTE_DIRECTORY);

		if (smb2_get_reparse_tag_special_file(stat->mode))
			attr |= FILE_ATTRIBUTE_REPARSE_POINT;
	}

	return attr;
}

static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
			       __le16 hash_id)
{
	pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
	pneg_ctxt->DataLength = cpu_to_le16(38);
	pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
	pneg_ctxt->Reserved = cpu_to_le32(0);
	pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
	get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
	pneg_ctxt->HashAlgorithms = hash_id;
}

static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
			       __le16 cipher_type)
{
	pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
	pneg_ctxt->DataLength = cpu_to_le16(4);
	pneg_ctxt->Reserved = cpu_to_le32(0);
	pneg_ctxt->CipherCount = cpu_to_le16(1);
	pneg_ctxt->Ciphers[0] = cipher_type;
}

static void build_compress_ctxt(struct smb2_compression_capabilities_context *pneg_ctxt,
				__le16 compress_algorithm, bool compress_chained,
				bool compress_pattern)
{
	/*
	 * Return only algorithms implemented by ksmbd. Pattern_V1 is advertised
	 * as a second ID when the client also enabled chained transforms.
	 */
	pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
	pneg_ctxt->DataLength = cpu_to_le16(compress_pattern ? 12 : 10);
	pneg_ctxt->Reserved = cpu_to_le32(0);
	pneg_ctxt->CompressionAlgorithmCount =
		cpu_to_le16(compress_pattern ? 2 : 1);
	pneg_ctxt->Padding = cpu_to_le16(0);
	pneg_ctxt->Flags = compress_chained ?
		SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED :
		SMB2_COMPRESSION_CAPABILITIES_FLAG_NONE;
	pneg_ctxt->CompressionAlgorithms[0] = compress_algorithm;
	pneg_ctxt->CompressionAlgorithms[1] = compress_pattern ?
		SMB3_COMPRESS_PATTERN : 0;
	pneg_ctxt->CompressionAlgorithms[2] = 0;
	pneg_ctxt->CompressionAlgorithms[3] = 0;
}

/**
 * build_rdma_ctx() - build an RDMA transform negotiate response context
 * @ctxt: response context header to populate
 * @transform_ids: bitmap of transforms common to the client and server
 *
 * Return: encoded negotiate context length
 */
static int build_rdma_ctx(struct smb2_neg_context *ctxt,
			  unsigned long transform_ids)
{
	struct smb2_rdma_transform_capabilities_context *pneg_ctxt;
	int count = 0;

	pneg_ctxt = (void *)ctxt;
	pneg_ctxt->ContextType = SMB2_RDMA_TRANSFORM_CAPABILITIES;
	pneg_ctxt->Reserved = 0;
	pneg_ctxt->Reserved1 = 0;
	pneg_ctxt->Reserved2 = 0;
	if (transform_ids & BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION))
		pneg_ctxt->RDMATransformIds[count++] =
			cpu_to_le16(SMB2_RDMA_TRANSFORM_ENCRYPTION);
	if (!count)
		pneg_ctxt->RDMATransformIds[count++] =
			cpu_to_le16(SMB2_RDMA_TRANSFORM_NONE);

	pneg_ctxt->TransformCount = cpu_to_le16(count);
	pneg_ctxt->DataLength = cpu_to_le16(8 + count * sizeof(__le16));
	return sizeof(struct smb2_neg_context) +
		le16_to_cpu(pneg_ctxt->DataLength);
}

static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
				__le16 sign_algo)
{
	pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
	pneg_ctxt->DataLength =
		cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
			- sizeof(struct smb2_neg_context));
	pneg_ctxt->Reserved = cpu_to_le32(0);
	pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
	pneg_ctxt->SigningAlgorithms[0] = sign_algo;
}

static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
{
	pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
	pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
	memcpy(pneg_ctxt->Name, SMB2_CREATE_TAG_POSIX, POSIX_CTXT_DATA_LEN);
}

static unsigned int assemble_neg_contexts(struct ksmbd_conn *conn,
				  struct smb2_negotiate_rsp *rsp)
{
	char * const pneg_ctxt = (char *)rsp +
			le32_to_cpu(rsp->NegotiateContextOffset);
	int neg_ctxt_cnt = 1;
	int ctxt_size;

	ksmbd_debug(SMB,
		    "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
	build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
			   conn->preauth_info->Preauth_HashId);
	ctxt_size = sizeof(struct smb2_preauth_neg_context);

	if (conn->cipher_type) {
		/* Round to 8 byte boundary */
		ctxt_size = round_up(ctxt_size, 8);
		ksmbd_debug(SMB,
			    "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
		build_encrypt_ctxt((struct smb2_encryption_neg_context *)
				   (pneg_ctxt + ctxt_size),
				   conn->cipher_type);
		neg_ctxt_cnt++;
		ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
	}

	if (conn->compress_algorithm != SMB3_COMPRESS_NONE) {
		ctxt_size = round_up(ctxt_size, 8);
		ksmbd_debug(SMB,
			    "assemble SMB2_COMPRESSION_CAPABILITIES context\n");
		build_compress_ctxt((struct smb2_compression_capabilities_context *)
				    (pneg_ctxt + ctxt_size),
				    conn->compress_algorithm,
				    conn->compress_chained,
				    conn->compress_pattern);
		neg_ctxt_cnt++;
		ctxt_size += sizeof(struct smb2_neg_context) +
			(conn->compress_pattern ? 12 : 10);
	}

	if (conn->rdma_transform_negotiated) {
		struct smb2_neg_context *rdma_ctxt;

		ctxt_size = round_up(ctxt_size, 8);
		ksmbd_debug(SMB,
			    "assemble SMB2_RDMA_TRANSFORM_CAPABILITIES context\n");
		rdma_ctxt = (void *)(pneg_ctxt + ctxt_size);
		ctxt_size += build_rdma_ctx(rdma_ctxt,
					     conn->rdma_transform_ids);
		neg_ctxt_cnt++;
	}

	if (conn->posix_ext_supported) {
		ctxt_size = round_up(ctxt_size, 8);
		ksmbd_debug(SMB,
			    "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
		build_posix_ctxt((struct smb2_posix_neg_context *)
				 (pneg_ctxt + ctxt_size));
		neg_ctxt_cnt++;
		ctxt_size += sizeof(struct smb2_posix_neg_context);
	}

	if (conn->signing_negotiated) {
		ctxt_size = round_up(ctxt_size, 8);
		ksmbd_debug(SMB,
			    "assemble SMB2_SIGNING_CAPABILITIES context\n");
		build_sign_cap_ctxt((struct smb2_signing_capabilities *)
				    (pneg_ctxt + ctxt_size),
				    conn->signing_algorithm);
		neg_ctxt_cnt++;
		ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
	}

	rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
	return ctxt_size + AUTH_GSS_PADDING;
}

static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
				  struct smb2_preauth_neg_context *pneg_ctxt,
				  int ctxt_len)
{
	/*
	 * sizeof(smb2_preauth_neg_context) assumes SMB311_SALT_SIZE Salt,
	 * which may not be present. Only check for used HashAlgorithms[1].
	 */
	if (ctxt_len <
	    sizeof(struct smb2_neg_context) + MIN_PREAUTH_CTXT_DATA_LEN)
		return STATUS_INVALID_PARAMETER;

	if (pneg_ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
		return STATUS_SMB_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;

	conn->preauth_info->Preauth_HashId = SMB2_PREAUTH_INTEGRITY_SHA512;
	return STATUS_SUCCESS;
}

static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
				struct smb2_encryption_neg_context *pneg_ctxt,
				int ctxt_len)
{
	int cph_cnt;
	int i, cphs_size;

	if (sizeof(struct smb2_encryption_neg_context) > ctxt_len) {
		pr_err("Invalid SMB2_ENCRYPTION_CAPABILITIES context size\n");
		return;
	}

	conn->cipher_type = 0;

	cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
	cphs_size = cph_cnt * sizeof(__le16);

	if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
	    ctxt_len) {
		pr_err("Invalid cipher count(%d)\n", cph_cnt);
		return;
	}

	if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION_OFF)
		return;

	for (i = 0; i < cph_cnt; i++) {
		if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
		    pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
		    pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
		    pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
			ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
				    pneg_ctxt->Ciphers[i]);
			conn->cipher_type = pneg_ctxt->Ciphers[i];
			break;
		}
	}
}

/**
 * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
 * @conn:	smb connection
 *
 * Return:	true if connection should be encrypted, else false
 */
bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
{
	if (!conn->ops->generate_encryptionkey)
		return false;

	/*
	 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
	 * SMB 3.1.1 uses the cipher_type field.
	 */
	return (conn->vals->req_capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
	    conn->cipher_type;
}

static __le32 decode_compress_ctxt(struct ksmbd_conn *conn,
				   struct smb2_compression_capabilities_context *pneg_ctxt,
				   int ctxt_len)
{
	int alg_cnt, algs_size, i;
	__le16 *algs;

	if (sizeof(struct smb2_neg_context) + 10 > ctxt_len) {
		pr_err("Invalid SMB2_COMPRESSION_CAPABILITIES context length\n");
		return STATUS_INVALID_PARAMETER;
	}

	conn->compress_algorithm = SMB3_COMPRESS_NONE;
	conn->compress_chained = false;
	conn->compress_pattern = false;

	alg_cnt = le16_to_cpu(pneg_ctxt->CompressionAlgorithmCount);
	if (!alg_cnt)
		return STATUS_INVALID_PARAMETER;

	if (pneg_ctxt->Flags != SMB2_COMPRESSION_CAPABILITIES_FLAG_NONE &&
	    pneg_ctxt->Flags != SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED)
		return STATUS_INVALID_PARAMETER;

	algs_size = alg_cnt * sizeof(__le16);
	if (sizeof(struct smb2_neg_context) + 8 + algs_size > ctxt_len) {
		pr_err("Invalid compression algorithm count(%d)\n", alg_cnt);
		return STATUS_INVALID_PARAMETER;
	}

	/*
	 * CompressionAlgorithms[] is declared as a fixed 4-element array, but
	 * the actual element count is variable (clients such as Windows may
	 * advertise more). The on-wire length was validated above, so walk the
	 * algorithms through a pointer to avoid a fixed-array bounds check.
	 */
	algs = pneg_ctxt->CompressionAlgorithms;
	for (i = 0; i < alg_cnt; i++) {
		__le16 alg = algs[i];

		/*
		 * LZ77 is the required general-purpose codec. Pattern_V1 is an
		 * optional chained payload type and cannot stand alone.
		 */
		if (alg == SMB3_COMPRESS_LZ77) {
			conn->compress_algorithm = alg;
			conn->compress_chained =
				pneg_ctxt->Flags ==
				SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED;
			ksmbd_debug(SMB, "Compression Algorithm ID = 0x%x\n",
				    le16_to_cpu(alg));
		} else if (alg == SMB3_COMPRESS_PATTERN) {
			conn->compress_pattern = true;
		}
	}

	if (conn->compress_algorithm == SMB3_COMPRESS_NONE ||
	    !conn->compress_chained)
		conn->compress_pattern = false;

	return STATUS_SUCCESS;
}

static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
				 struct smb2_signing_capabilities *pneg_ctxt,
				 int ctxt_len)
{
	int sign_algo_cnt;
	int i, sign_alos_size;

	if (sizeof(struct smb2_signing_capabilities) > ctxt_len) {
		pr_err("Invalid SMB2_SIGNING_CAPABILITIES context length\n");
		return;
	}

	conn->signing_negotiated = false;
	sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
	sign_alos_size = sign_algo_cnt * sizeof(__le16);

	if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
	    ctxt_len) {
		pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
		return;
	}

	for (i = 0; i < sign_algo_cnt; i++) {
		if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
		    pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
			ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
				    pneg_ctxt->SigningAlgorithms[i]);
			conn->signing_negotiated = true;
			conn->signing_algorithm =
				pneg_ctxt->SigningAlgorithms[i];
			break;
		}
	}
}

/**
 * decode_rdma_ctx() - decode an RDMA transform negotiate request context
 * @conn: connection being negotiated
 * @ctxt: request context header to decode
 * @ctxt_len: total context length, including the negotiate context header
 *
 * Record transforms supported by both peers only for SMB Direct connections.
 *
 * Return: NT status describing the decode result
 */
static __le32 decode_rdma_ctx(struct ksmbd_conn *conn,
			      struct smb2_neg_context *ctxt, int ctxt_len)
{
	struct smb2_rdma_transform_capabilities_context *pneg_ctxt;
	unsigned int count, i;

	pneg_ctxt = (void *)ctxt;
	/* RDMA transforms are a node capability, not just a transport capability. */
	if (!ksmbd_rdma_enabled())
		return STATUS_SUCCESS;

	if (ctxt_len < sizeof(*pneg_ctxt))
		return STATUS_INVALID_PARAMETER;

	count = le16_to_cpu(pneg_ctxt->TransformCount);
	if (!count || count >
	    (ctxt_len - sizeof(*pneg_ctxt)) / sizeof(__le16))
		return STATUS_INVALID_PARAMETER;

	conn->rdma_transform_negotiated = true;
	conn->rdma_transform_ids = 0;
	for (i = 0; i < count; i++) {
		u16 id = le16_to_cpu(pneg_ctxt->RDMATransformIds[i]);

		if (id == SMB2_RDMA_TRANSFORM_ENCRYPTION)
			conn->rdma_transform_ids |= BIT(id);
	}
	return STATUS_SUCCESS;
}

static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
				      struct smb2_negotiate_req *req,
				      unsigned int len_of_smb)
{
	/* +4 is to account for the RFC1001 len field */
	struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
	int i = 0, len_of_ctxts;
	unsigned int offset = le32_to_cpu(req->NegotiateContextOffset);
	unsigned int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
	__le32 status = STATUS_INVALID_PARAMETER;
	int compress_ctxt_cnt = 0, rdma_transform_ctxt_cnt = 0;
	bool posix_ctxt_seen = false;

	ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
	if (len_of_smb <= offset) {
		ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
		return status;
	}

	len_of_ctxts = len_of_smb - offset;

	while (i++ < neg_ctxt_cnt) {
		int clen, ctxt_len;

		if (len_of_ctxts < (int)sizeof(struct smb2_neg_context))
			break;

		pctx = (struct smb2_neg_context *)((char *)pctx + offset);
		clen = le16_to_cpu(pctx->DataLength);
		ctxt_len = clen + sizeof(struct smb2_neg_context);

		if (ctxt_len > len_of_ctxts)
			break;

		if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
			ksmbd_debug(SMB,
				    "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
			if (conn->preauth_info->Preauth_HashId)
				break;

			status = decode_preauth_ctxt(conn,
						     (struct smb2_preauth_neg_context *)pctx,
						     ctxt_len);
			if (status != STATUS_SUCCESS)
				break;
		} else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
			ksmbd_debug(SMB,
				    "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
			if (conn->cipher_type)
				break;

			decode_encrypt_ctxt(conn,
					    (struct smb2_encryption_neg_context *)pctx,
					    ctxt_len);
		} else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
			ksmbd_debug(SMB,
				    "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
			if (compress_ctxt_cnt++) {
				status = STATUS_INVALID_PARAMETER;
				break;
			}

			status = decode_compress_ctxt(conn,
				(struct smb2_compression_capabilities_context *)
				pctx, ctxt_len);
			if (status != STATUS_SUCCESS)
				break;
		} else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
			ksmbd_debug(SMB,
				    "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
		} else if (pctx->ContextType == SMB2_RDMA_TRANSFORM_CAPABILITIES) {
			ksmbd_debug(SMB,
				    "deassemble SMB2_RDMA_TRANSFORM_CAPABILITIES context\n");
			if (ksmbd_rdma_enabled() &&
			    rdma_transform_ctxt_cnt++) {
				status = STATUS_INVALID_PARAMETER;
				break;
			}
			status = decode_rdma_ctx(conn, pctx, ctxt_len);
			if (status != STATUS_SUCCESS)
				break;
		} else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
			ksmbd_debug(SMB,
				    "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
			if (posix_ctxt_seen || clen != POSIX_CTXT_DATA_LEN) {
				status = STATUS_INVALID_PARAMETER;
				break;
			}
			posix_ctxt_seen = true;
			if (!memcmp((char *)pctx + sizeof(*pctx),
				    SMB2_CREATE_TAG_POSIX, POSIX_CTXT_DATA_LEN))
				conn->posix_ext_supported = true;
		} else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
			ksmbd_debug(SMB,
				    "deassemble SMB2_SIGNING_CAPABILITIES context\n");

			decode_sign_cap_ctxt(conn,
					     (struct smb2_signing_capabilities *)pctx,
					     ctxt_len);
		}

		/* offsets must be 8 byte aligned */
		offset = (ctxt_len + 7) & ~0x7;
		len_of_ctxts -= offset;
	}
	return status;
}

/**
 * smb2_handle_negotiate() - handler for smb2 negotiate command
 * @work:	smb work containing smb request buffer
 *
 * The caller holds conn->srv_mutex.
 *
 * Return:      0
 */
int smb2_handle_negotiate(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
	struct smb2_negotiate_req *req = smb_get_msg(work->request_buf);
	struct smb2_negotiate_rsp *rsp = smb_get_msg(work->response_buf);
	int rc = 0;
	unsigned int smb2_buf_len, smb2_neg_size, neg_ctxt_len = 0;
	__le32 status;

	ksmbd_debug(SMB, "Received negotiate request\n");
	conn->need_neg = false;
	smb2_buf_len = get_rfc1002_len(work->request_buf);
	smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
	if (smb2_neg_size > smb2_buf_len) {
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		rc = -EINVAL;
		goto err_out;
	}

	if (req->DialectCount == 0) {
		pr_err("malformed packet\n");
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		rc = -EINVAL;
		goto err_out;
	}

	if (conn->dialect == SMB311_PROT_ID) {
		unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);

		if (smb2_buf_len < nego_ctxt_off) {
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
			rc = -EINVAL;
			goto err_out;
		}

		if (smb2_neg_size > nego_ctxt_off) {
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
			rc = -EINVAL;
			goto err_out;
		}

		if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
		    nego_ctxt_off) {
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
			rc = -EINVAL;
			goto err_out;
		}
	} else {
		if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
		    smb2_buf_len) {
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
			rc = -EINVAL;
			goto err_out;
		}
	}

	conn->cli_cap = le32_to_cpu(req->Capabilities);
	switch (conn->dialect) {
	case SMB311_PROT_ID:
		conn->preauth_info =
			kzalloc_obj(struct preauth_integrity_info,
				    KSMBD_DEFAULT_GFP);
		if (!conn->preauth_info) {
			rc = -ENOMEM;
			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
			goto err_out;
		}

		status = deassemble_neg_contexts(conn, req,
						 get_rfc1002_len(work->request_buf));
		if (status != STATUS_SUCCESS) {
			pr_err("deassemble_neg_contexts error(0x%x)\n",
			       status);
			rsp->hdr.Status = status;
			rc = -EINVAL;
			kfree(conn->preauth_info);
			conn->preauth_info = NULL;
			goto err_out;
		}
		if (!conn->cipher_type)
			conn->rdma_transform_ids &=
				~BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION);
		ksmbd_debug(RDMA,
			    "RDMA transform negotiation: transport=%s context=%s encryption=%s cipher=0x%04x\n",
			    conn->transport->ops->rdma_read ? "rdma" : "tcp",
			    conn->rdma_transform_negotiated ? "present" : "absent",
			    conn->rdma_transform_ids &
			    BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION) ? "enabled" : "disabled",
			    le16_to_cpu(conn->cipher_type));

		rc = init_smb3_11_server(conn);
		if (rc < 0) {
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
			kfree(conn->preauth_info);
			conn->preauth_info = NULL;
			goto err_out;
		}

		ksmbd_gen_preauth_integrity_hash(conn,
						 work->request_buf,
						 conn->preauth_info->Preauth_HashValue);
		rsp->NegotiateContextOffset =
				cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
		neg_ctxt_len = assemble_neg_contexts(conn, rsp);
		break;
	case SMB302_PROT_ID:
		init_smb3_02_server(conn);
		break;
	case SMB30_PROT_ID:
		init_smb3_0_server(conn);
		break;
	case SMB21_PROT_ID:
		init_smb2_1_server(conn);
		break;
	case SMB2X_PROT_ID:
	case BAD_PROT_ID:
	default:
		ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
			    conn->dialect);
		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
		rc = -EINVAL;
		goto err_out;
	}
	rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);

	/* For stats */
	conn->connection_type = conn->dialect;

	rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
	rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
	rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);

	memcpy(conn->ClientGUID, req->ClientGUID,
			SMB2_CLIENT_GUID_SIZE);
	conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);

	rsp->StructureSize = cpu_to_le16(65);
	rsp->DialectRevision = cpu_to_le16(conn->dialect);
	/* Not setting conn guid rsp->ServerGUID, as it
	 * not used by client for identifying server
	 */
	memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);

	rsp->SystemTime = cpu_to_le64(ksmbd_systime());
	rsp->ServerStartTime = 0;
	ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
		    le32_to_cpu(rsp->NegotiateContextOffset),
		    le16_to_cpu(rsp->NegotiateContextCount));

	rsp->SecurityBufferOffset = cpu_to_le16(128);
	rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
	ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
				  le16_to_cpu(rsp->SecurityBufferOffset));

	rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
	conn->use_spnego = true;

	if (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
		conn->sign = true;
	if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
		server_conf.enforced_signing = true;
		rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
		conn->sign = true;
	}

	conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
	ksmbd_conn_set_need_setup(conn);

err_out:
	if (rc && rsp->hdr.Status == STATUS_SUCCESS)
		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;

	if (!rc)
		rc = ksmbd_iov_pin_rsp(work, rsp,
				       sizeof(struct smb2_negotiate_rsp) +
					AUTH_GSS_LENGTH + neg_ctxt_len);
	if (rc < 0)
		smb2_set_err_rsp(work);
	return rc;
}

static int alloc_preauth_hash(struct ksmbd_session *sess,
			      struct ksmbd_conn *conn)
{
	if (sess->Preauth_HashValue)
		return 0;

	if (!conn->preauth_info)
		return -ENOMEM;

	sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
					  PREAUTH_HASHVALUE_SIZE, KSMBD_DEFAULT_GFP);
	if (!sess->Preauth_HashValue)
		return -ENOMEM;

	return 0;
}

static int generate_preauth_hash(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
	struct ksmbd_session *sess = work->sess;
	u8 *preauth_hash;

	if (conn->dialect != SMB311_PROT_ID)
		return 0;

	if (conn->binding) {
		struct preauth_session *preauth_sess;

		preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
		if (!preauth_sess) {
			preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
			if (!preauth_sess)
				return -ENOMEM;
		}

		preauth_hash = preauth_sess->Preauth_HashValue;
	} else {
		if (!sess->Preauth_HashValue)
			if (alloc_preauth_hash(sess, conn))
				return -ENOMEM;
		preauth_hash = sess->Preauth_HashValue;
	}

	ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
	return 0;
}

static int decode_negotiation_token(struct ksmbd_conn *conn,
				    struct negotiate_message *negblob,
				    size_t sz)
{
	if (!conn->use_spnego)
		return -EINVAL;

	if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
		if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
			conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
			conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
			conn->use_spnego = false;
		}
	}
	return 0;
}

static int ntlm_negotiate(struct ksmbd_work *work,
			  struct negotiate_message *negblob,
			  size_t negblob_len, struct smb2_sess_setup_rsp *rsp)
{
	struct challenge_message *chgblob;
	unsigned char *spnego_blob = NULL;
	u16 spnego_blob_len;
	char *neg_blob;
	int sz, rc;

	ksmbd_debug(SMB, "negotiate phase\n");
	rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
	if (rc)
		return rc;

	sz = le16_to_cpu(rsp->SecurityBufferOffset);
	chgblob = (struct challenge_message *)rsp->Buffer;
	memset(chgblob, 0, sizeof(struct challenge_message));

	if (!work->conn->use_spnego) {
		sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
		if (sz < 0)
			return -ENOMEM;

		rsp->SecurityBufferLength = cpu_to_le16(sz);
		return 0;
	}

	sz = sizeof(struct challenge_message);
	sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;

	neg_blob = kzalloc(sz, KSMBD_DEFAULT_GFP);
	if (!neg_blob)
		return -ENOMEM;

	chgblob = (struct challenge_message *)neg_blob;
	sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
	if (sz < 0) {
		rc = -ENOMEM;
		goto out;
	}

	rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
					   neg_blob, sz);
	if (rc) {
		rc = -ENOMEM;
		goto out;
	}

	memcpy(rsp->Buffer, spnego_blob, spnego_blob_len);
	rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);

out:
	kfree(spnego_blob);
	kfree(neg_blob);
	return rc;
}

static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
						  struct smb2_sess_setup_req *req)
{
	int sz;

	if (conn->use_spnego && conn->mechToken)
		return (struct authenticate_message *)conn->mechToken;

	sz = le16_to_cpu(req->SecurityBufferOffset);
	return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
					       + sz);
}

static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
				       struct smb2_sess_setup_req *req)
{
	struct authenticate_message *authblob;
	struct ksmbd_user *user;
	char *name;
	unsigned int name_off, name_len, secbuf_len;

	if (conn->use_spnego && conn->mechToken)
		secbuf_len = conn->mechTokenLen;
	else
		secbuf_len = le16_to_cpu(req->SecurityBufferLength);
	if (secbuf_len < sizeof(struct authenticate_message)) {
		ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
		return NULL;
	}
	authblob = user_authblob(conn, req);
	name_off = le32_to_cpu(authblob->UserName.BufferOffset);
	name_len = le16_to_cpu(authblob->UserName.Length);

	if (secbuf_len < (u64)name_off + name_len)
		return NULL;

	name = smb_strndup_from_utf16((const char *)authblob + name_off,
				      name_len,
				      true,
				      conn->local_nls);
	if (IS_ERR(name)) {
		pr_err("cannot allocate memory\n");
		return NULL;
	}

	ksmbd_debug(SMB, "session setup request for user %s\n", name);
	user = ksmbd_login_user(name);
	kfree(name);
	return user;
}

static int ntlm_authenticate(struct ksmbd_work *work,
			     struct smb2_sess_setup_req *req,
			     struct smb2_sess_setup_rsp *rsp,
			     u64 *previous_session_id)
{
	struct ksmbd_conn *conn = work->conn;
	struct ksmbd_session *sess = work->sess;
	struct ksmbd_user *user;
	char channel_key[CIFS_KEY_SIZE] = {};
	char *auth_key = conn->binding ? channel_key : sess->sess_key;
	bool binding = conn->binding;
	int sz, rc;

	ksmbd_debug(SMB, "authenticate phase\n");
	if (conn->use_spnego) {
		unsigned char *spnego_blob;
		u16 spnego_blob_len;

		rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
						    &spnego_blob_len,
						    0);
		if (rc)
			return -ENOMEM;

		memcpy(rsp->Buffer, spnego_blob, spnego_blob_len);
		rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
		kfree(spnego_blob);
	}

	user = session_user(conn, req);
	if (!user) {
		ksmbd_debug(SMB, "Unknown user name or an error\n");
		return -EPERM;
	}

	if (sess->state == SMB2_SESSION_VALID) {
		/*
		 * Reuse session if anonymous try to connect
		 * on reauthetication.
		 */
		if (conn->binding == false && ksmbd_anonymous_user(user)) {
			ksmbd_free_user(user);
			return 0;
		}

		if (!ksmbd_compare_user(sess->user, user)) {
			ksmbd_free_user(user);
			return -EKEYREJECTED;
		}
		ksmbd_free_user(user);
	} else if (sess->user) {
		/*
		 * Reauthentication of an expired session: as for a valid
		 * session, and as krb5_authenticate() does, it must be by the
		 * same user. Replacing sess->user would also leak the old one.
		 */
		if (!ksmbd_compare_user(sess->user, user)) {
			ksmbd_free_user(user);
			return -EKEYREJECTED;
		}
		ksmbd_free_user(user);
	} else {
		sess->user = user;
	}

	if (conn->binding == false && user_guest(sess->user)) {
		rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
	} else {
		struct authenticate_message *authblob;

		authblob = user_authblob(conn, req);
		if (conn->use_spnego && conn->mechToken)
			sz = conn->mechTokenLen;
		else
			sz = le16_to_cpu(req->SecurityBufferLength);
		rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess,
						    auth_key);
		if (rc) {
			set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
			ksmbd_debug(SMB, "authentication failed\n");
			rc = -EPERM;
			goto out;
		}
	}

	*previous_session_id = le64_to_cpu(req->PreviousSessionId);

	/*
	 * If session state is SMB2_SESSION_VALID, We can assume
	 * that it is reauthentication. And the user/password
	 * has been verified, so return it here.
	 */
	if (sess->state == SMB2_SESSION_VALID) {
		if (conn->binding)
			goto binding_session;
		return 0;
	}

	if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
	     (conn->sign || server_conf.enforced_signing)) ||
	    (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
		sess->sign = true;

	if (smb3_encryption_negotiated(conn) &&
			!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
		conn->ops->generate_encryptionkey(conn, sess);
		sess->enc = true;
		if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
			rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
		/*
		 * signing is disable if encryption is enable
		 * on this session
		 */
		sess->sign = false;
	}

binding_session:
	if (conn->dialect >= SMB30_PROT_ID) {
		rc = register_session_channel(sess, conn, auth_key);
		if (rc)
			goto out;
	}

	if (conn->ops->generate_signingkey) {
		rc = conn->ops->generate_signingkey(sess, conn);
		if (rc) {
			ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
			rc = -EINVAL;
			goto out;
		}
	}

	if (!ksmbd_conn_lookup_dialect(conn)) {
		pr_err("fail to verify the dialect\n");
		rc = -ENOENT;
		goto out;
	}
	rc = 0;
out:
	if (binding)
		memzero_explicit(channel_key, sizeof(channel_key));
	return rc;
}

#ifdef CONFIG_SMB_SERVER_KERBEROS5
static int krb5_authenticate(struct ksmbd_work *work,
			     struct smb2_sess_setup_req *req,
			     struct smb2_sess_setup_rsp *rsp,
			     u64 *previous_session_id)
{
	struct ksmbd_conn *conn = work->conn;
	struct ksmbd_session *sess = work->sess;
	char *in_blob, *out_blob;
	char channel_key[CIFS_KEY_SIZE] = {};
	char reauth_key[CIFS_KEY_SIZE] = {};
	char *auth_key = conn->binding ? channel_key :
		(work->session_setup_reauth ? reauth_key : sess->sess_key);
	bool binding = conn->binding;
	int in_len, out_len;
	int retval;

	in_blob = (char *)&req->hdr.ProtocolId +
		le16_to_cpu(req->SecurityBufferOffset);
	in_len = le16_to_cpu(req->SecurityBufferLength);
	out_blob = (char *)&rsp->hdr.ProtocolId +
		le16_to_cpu(rsp->SecurityBufferOffset);
	out_len = work->response_sz - work->next_smb2_rsp_hdr_off -
		(le16_to_cpu(rsp->SecurityBufferOffset) + 4);

	retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
					 out_blob, &out_len, auth_key);
	if (retval) {
		ksmbd_debug(SMB, "krb5 authentication failed\n");
		if (retval != -EKEYREJECTED)
			retval = -EPERM;
		goto out;
	}

	*previous_session_id = le64_to_cpu(req->PreviousSessionId);

	rsp->SecurityBufferLength = cpu_to_le16(out_len);

	/*
	 * If session state is SMB2_SESSION_VALID, We can assume
	 * that it is reauthentication. And the user/password
	 * has been verified, so return it here.
	 */
	if (sess->state == SMB2_SESSION_VALID && !work->session_setup_reauth) {
		if (conn->binding)
			goto binding_session;
		return 0;
	}

	/*
	 * Reauthentication verifies the new Kerberos credentials but keeps
	 * the established SMB session keys.
	 */
	if (work->session_setup_reauth) {
		retval = 0;
		goto out;
	}

	if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
	    (conn->sign || server_conf.enforced_signing)) ||
	    (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
		sess->sign = true;

	if (smb3_encryption_negotiated(conn) &&
	    !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
		conn->ops->generate_encryptionkey(conn, sess);
		sess->enc = true;
		if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
			rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
		sess->sign = false;
	}

binding_session:
	if (conn->dialect >= SMB30_PROT_ID) {
		retval = register_session_channel(sess, conn, auth_key);
		if (retval)
			goto out;
	}

	if (conn->ops->generate_signingkey) {
		retval = conn->ops->generate_signingkey(sess, conn);
		if (retval) {
			ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
			retval = -EINVAL;
			goto out;
		}
	}

	if (!ksmbd_conn_lookup_dialect(conn)) {
		pr_err("fail to verify the dialect\n");
		retval = -ENOENT;
		goto out;
	}
	retval = 0;
out:
	memzero_explicit(reauth_key, sizeof(reauth_key));
	if (binding)
		memzero_explicit(channel_key, sizeof(channel_key));
	return retval;
}
#else
static int krb5_authenticate(struct ksmbd_work *work,
			     struct smb2_sess_setup_req *req,
			     struct smb2_sess_setup_rsp *rsp,
			     u64 *previous_session_id)
{
	return -EOPNOTSUPP;
}
#endif

int smb2_sess_setup(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
	struct smb2_sess_setup_req *req;
	struct smb2_sess_setup_rsp *rsp;
	struct ksmbd_session *sess = NULL;
	struct ksmbd_session *prev_sess = work->sess;
	bool installed = false;
	struct negotiate_message *negblob;
	unsigned int negblob_len, negblob_off;
	u64 previous_session_id = 0;
	bool authenticated = false;
	int rc = 0;

	ksmbd_debug(SMB, "Received smb2 session setup request\n");

	if (!ksmbd_conn_need_setup(conn) && !ksmbd_conn_good(conn)) {
		work->send_no_response = 1;
		return rc;
	}

	WORK_BUFFERS(work, req, rsp);

	rsp->StructureSize = cpu_to_le16(9);
	rsp->SessionFlags = 0;
	rsp->SecurityBufferOffset = cpu_to_le16(72);
	rsp->SecurityBufferLength = 0;

	ksmbd_conn_lock(conn);
	if (!req->hdr.SessionId) {
		/* Bound abandoned SessionId-zero authentication exchanges. */
		if (ksmbd_too_many_session_setups(conn)) {
			rc = -ENOSPC;
			goto out_err;
		}
		sess = ksmbd_smb2_session_create(conn);
		if (!sess) {
			rc = -ENOMEM;
			goto out_err;
		}
		rsp->hdr.SessionId = cpu_to_le64(sess->id);
		rc = ksmbd_session_register(conn, sess);
		if (rc)
			goto out_err;

		conn->binding = false;
	} else if (conn->dialect >= SMB30_PROT_ID &&
		   (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
		   req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
		u64 sess_id = le64_to_cpu(req->hdr.SessionId);

		sess = ksmbd_session_lookup_slowpath(sess_id);
		if (!sess) {
			rc = -ENOENT;
			goto out_err;
		}

		if (conn->dialect != sess->dialect) {
			rc = -EINVAL;
			goto out_err;
		}

		if (conn->dialect == SMB311_PROT_ID) {
			struct channel *chann;
			unsigned long index;

			down_read(&sess->chann_lock);
			xa_for_each(&sess->ksmbd_chann_list, index, chann) {
				if (conn->cipher_type != chann->conn->cipher_type)
					rc = -EINVAL;
				break;
			}
			up_read(&sess->chann_lock);
			if (rc)
				goto out_err;
		}

		if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
			rc = -EINVAL;
			goto out_err;
		}

		if (memcmp(conn->ClientGUID, sess->ClientGUID,
			    SMB2_CLIENT_GUID_SIZE)) {
			rc = -ENOENT;
			goto out_err;
		}

		if (sess->state == SMB2_SESSION_IN_PROGRESS) {
			rc = -EACCES;
			goto out_err;
		}

		if (sess->state == SMB2_SESSION_EXPIRED) {
			rc = -EFAULT;
			goto out_err;
		}

		if (ksmbd_conn_need_reconnect(conn)) {
			rc = -EFAULT;
			ksmbd_user_session_put(sess);
			sess = NULL;
			goto out_err;
		}

		if (is_ksmbd_session_in_connection(conn, sess_id)) {
			rc = -EACCES;
			goto out_err;
		}

		if (user_guest(sess->user)) {
			rc = -EOPNOTSUPP;
			goto out_err;
		}

		conn->binding = true;
	} else if ((conn->dialect < SMB30_PROT_ID ||
		    server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
		   (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
		sess = ksmbd_session_lookup_slowpath(le64_to_cpu(req->hdr.SessionId));
		if (sess) {
			int sign_ret;

			work->sess = sess;
			installed = true;
			if (sess->dialect >= SMB30_PROT_ID)
				sign_ret = smb3_check_sign_req(work);
			else
				sign_ret = smb2_check_sign_req(work);
			if (sess->state != SMB2_SESSION_VALID ||
			    !(req->hdr.Flags & SMB2_FLAGS_SIGNED) ||
			    !sign_ret) {
				ksmbd_user_session_put(sess);
				work->sess = NULL;
				sess = NULL;
			}
		}
		rc = -EACCES;
		goto out_err;
	} else {
		sess = ksmbd_session_lookup(conn,
					    le64_to_cpu(req->hdr.SessionId));
		if (!sess) {
			sess = ksmbd_session_lookup_slowpath(le64_to_cpu(req->hdr.SessionId));
			if (sess && !lookup_chann_list(sess, conn)) {
				ksmbd_user_session_put(sess);
				sess = NULL;
			}
		}
		if (!sess) {
			rc = -ENOENT;
			goto out_err;
		}

		if (sess->state == SMB2_SESSION_EXPIRED) {
			if (sess->kerberos_expiry &&
			    ktime_get_real_seconds() >= sess->kerberos_expiry) {
				work->session_setup_reauth = true;
			} else {
				rc = -EFAULT;
				goto out_err;
			}
		}

		if (ksmbd_conn_need_reconnect(conn)) {
			rc = -EFAULT;
			ksmbd_user_session_put(sess);
			sess = NULL;
			goto out_err;
		}

		if (work->session_setup_reauth)
			WRITE_ONCE(sess->state, SMB2_SESSION_IN_PROGRESS);

		conn->binding = false;
	}
	work->sess = sess;
	installed = true;

	negblob_off = le16_to_cpu(req->SecurityBufferOffset);
	negblob_len = le16_to_cpu(req->SecurityBufferLength);
	if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer)) {
		rc = -EINVAL;
		goto out_err;
	}

	negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
			negblob_off);

	if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
		if (conn->mechToken) {
			negblob = (struct negotiate_message *)conn->mechToken;
			negblob_len = conn->mechTokenLen;
		}
	}

	if (negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
		rc = -EINVAL;
		goto out_err;
	}

	if (server_conf.auth_mechs & conn->auth_mechs) {
		rc = generate_preauth_hash(work);
		if (rc)
			goto out_err;

		if (conn->preferred_auth_mech &
				(KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
			rc = krb5_authenticate(work, req, rsp, &previous_session_id);
			if (rc)
				goto out_err;

			authenticated = true;
		} else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
			if (negblob->MessageType == NtLmNegotiate) {
				rc = ntlm_negotiate(work, negblob, negblob_len, rsp);
				if (rc)
					goto out_err;
				rsp->hdr.Status =
					STATUS_MORE_PROCESSING_REQUIRED;
			} else if (negblob->MessageType == NtLmAuthenticate) {
				rc = ntlm_authenticate(work, req, rsp,
						       &previous_session_id);
				if (rc)
					goto out_err;

				authenticated = true;
				if (conn->binding) {
					struct preauth_session *preauth_sess;

					preauth_sess =
						ksmbd_preauth_session_lookup(conn, sess->id);
					if (preauth_sess) {
						list_del(&preauth_sess->preauth_entry);
						kfree_sensitive(preauth_sess);
					}
				}
			} else {
				pr_info_ratelimited("Unknown NTLMSSP message type : 0x%x\n",
						le32_to_cpu(negblob->MessageType));
				rc = -EINVAL;
			}
		} else {
			/* TODO: need one more negotiation */
			pr_err("Not support the preferred authentication\n");
			rc = -EINVAL;
		}
	} else {
		pr_err("Not support authentication\n");
		rc = -EINVAL;
	}

out_err:
	if (rc == -EINVAL)
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
	else if (rc == -ENOENT)
		rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
	else if (rc == -EACCES)
		rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
	else if (rc == -EFAULT)
		rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
	else if (rc == -ENOMEM || rc == -ENOSPC)
		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
	else if (rc == -EOPNOTSUPP)
		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
	else if (rc == -EKEYREJECTED)
		rsp->hdr.Status = STATUS_ACCESS_DENIED;
	else if (rc)
		rsp->hdr.Status = STATUS_LOGON_FAILURE;
	if ((rsp->hdr.Status == STATUS_USER_SESSION_DELETED ||
	     (rsp->hdr.Status == STATUS_INVALID_PARAMETER &&
	      (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING))) &&
	    (req->hdr.Flags & SMB2_FLAGS_SIGNED))
		rsp->hdr.Flags |= SMB2_FLAGS_SIGNED;

	if (conn->mechToken) {
		kfree(conn->mechToken);
		conn->mechToken = NULL;
	}

	if (rc < 0) {
		bool setup_in_progress = sess &&
			READ_ONCE(sess->state) == SMB2_SESSION_IN_PROGRESS &&
			!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING);

		/* Authentication errors must not leave the new session published. */
		if (setup_in_progress)
			ksmbd_session_unregister(conn, sess);

		if (sess && conn->dialect == SMB311_PROT_ID &&
		    (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
			struct preauth_session *preauth_sess;

			preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
			if (preauth_sess) {
				list_del(&preauth_sess->preauth_entry);
				kfree_sensitive(preauth_sess);
			}
		}

		/*
		 * SecurityBufferOffset should be set to zero
		 * in session setup error response.
		 */
		rsp->SecurityBufferOffset = 0;

		if (sess) {
			bool try_delay = false;

			/*
			 * To avoid dictionary attacks (repeated session setups rapidly sent) to
			 * connect to server, ksmbd make a delay of a 5 seconds on session setup
			 * failure to make it harder to send enough random connection requests
			 * to break into a server.
			 */
			if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
				try_delay = true;

			/*
			 * For binding requests, session belongs to another
			 * connection. Do not expire it.
			 */
			if (!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) &&
			    !setup_in_progress) {
				sess->last_active = jiffies;
				sess->kerberos_expiry = 0;
				sess->state = SMB2_SESSION_EXPIRED;
			}
			/*
			 * Keep the binding session reference until the response is
			 * signed and sent.  Error responses for a signed binding
			 * request are signed with the existing session signing key.
			 */
			if (!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) ||
			    work->sess != sess) {
				ksmbd_user_session_put(sess);
				work->sess = NULL;
			}
			if (try_delay) {
				ksmbd_conn_set_need_reconnect(conn);
				ssleep(5);
				ksmbd_conn_set_need_setup(conn);
			}
		}
		smb2_set_err_rsp(work);
		conn->binding = false;
	} else {
		unsigned int iov_len;

		if (rsp->SecurityBufferLength)
			iov_len = offsetof(struct smb2_sess_setup_rsp, Buffer) +
				le16_to_cpu(rsp->SecurityBufferLength);
		else
			iov_len = sizeof(struct smb2_sess_setup_rsp);
		rc = ksmbd_iov_pin_rsp(work, rsp, iov_len);
		if (rc)
			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
	}

	work->session_setup_binding = conn->binding;
	if (authenticated) {
		/*
		 * Draining the previous session drops srv_mutex. Finish using the
		 * connection's authentication state and free mechToken first, and
		 * retain this request's binding decision for response processing.
		 */
		if (previous_session_id && previous_session_id != sess->id)
			destroy_previous_session(conn, sess->user, previous_session_id);
		if (!ksmbd_conn_need_reconnect(conn)) {
			ksmbd_conn_set_good(conn);
			sess->state = SMB2_SESSION_VALID;
		}
	}

	ksmbd_conn_unlock(conn);

	/*
	 * Later in a compound, work->sess holds the reference that an
	 * earlier command took. Drop it once this request has installed
	 * its own session there or cleared it.
	 */
	if (prev_sess && (installed || !work->sess))
		ksmbd_user_session_put(prev_sess);
	return rc;
}

/**
 * smb2_tree_connect() - handler for smb2 tree connect command
 * @work:	smb work containing smb request buffer
 *
 * Return:      0 on success, otherwise error
 */
int smb2_tree_connect(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
	struct smb2_tree_connect_req *req;
	struct smb2_tree_connect_rsp *rsp;
	struct ksmbd_session *sess = work->sess;
	char *treename = NULL, *name = NULL;
	struct ksmbd_tree_conn_status status;
	struct ksmbd_tree_connect *tree_conn = NULL;
	struct ksmbd_share_config *share = NULL;
	int rc = -EINVAL;

	ksmbd_debug(SMB, "Received smb2 tree connect request\n");

	WORK_BUFFERS(work, req, rsp);

	treename = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->PathOffset),
					  le16_to_cpu(req->PathLength), true,
					  conn->local_nls);
	if (IS_ERR(treename)) {
		pr_err("treename is NULL\n");
		status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
		goto out_err1;
	}

	name = ksmbd_extract_sharename(conn->um, treename);
	if (IS_ERR(name)) {
		status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
		goto out_err1;
	}

	ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
		    name, treename);

	status = ksmbd_tree_conn_connect(work, name);
	if (status.ret == KSMBD_TREE_CONN_STATUS_OK) {
		tree_conn = status.tree_conn;
		rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
		share = status.tree_conn->share_conf;

		/* A share that requires encryption needs a negotiated SMB3 cipher. */
		if (test_share_config_flag(share, KSMBD_SHARE_FLAG_ENCRYPT_DATA) &&
		    !smb3_encryption_negotiated(conn)) {
			ksmbd_tree_conn_disconnect(sess, status.tree_conn);
			status.tree_conn = NULL;
			share = NULL;
			status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
			goto out_err1;
		}
	} else
		goto out_err1;

	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
		ksmbd_debug(SMB, "IPC share path request\n");
		rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
		rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
			FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
			FILE_DELETE_LE | FILE_READ_CONTROL_LE |
			FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
			FILE_SYNCHRONIZE_LE;
	} else {
		rsp->ShareType = SMB2_SHARE_TYPE_DISK;
		rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
			FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
		if (test_tree_conn_flag(status.tree_conn,
					KSMBD_TREE_CONN_FLAG_WRITABLE)) {
			rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
				FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
				FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
				FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
				FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
				FILE_SYNCHRONIZE_LE;
		}
	}

	status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
	if (conn->posix_ext_supported)
		status.tree_conn->posix_extensions = true;

	down_write(&sess->tree_conns_lock);
	if (status.tree_conn->t_state == TREE_DISCONNECTED) {
		status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
		share = NULL;
	} else {
		status.tree_conn->t_state = TREE_CONNECTED;
	}
	up_write(&sess->tree_conns_lock);
	if (status.ret != KSMBD_TREE_CONN_STATUS_OK)
		goto out_err1;
	rsp->StructureSize = cpu_to_le16(16);
out_err1:
	/*
	 * A configured CA share is not continuously available until persistent
	 * open recovery, ownership fencing, and failover are implemented.
	 */
	rsp->Capabilities = 0;
	rsp->Reserved = 0;
	/* default manual caching */
	rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
	/* Tell the client that READ requests may request compressed responses. */
	if (conn->dialect == SMB311_PROT_ID &&
	    conn->compress_algorithm != SMB3_COMPRESS_NONE)
		rsp->ShareFlags |= cpu_to_le32(SMB2_SHAREFLAG_COMPRESS_DATA);
	if (share && test_share_config_flag(share,
					    KSMBD_SHARE_FLAG_HIDE_UNREADABLE))
		rsp->ShareFlags |=
			cpu_to_le32(SMB2_SHAREFLAG_ACCESS_BASED_DIRECTORY_ENUM);
	if (share && test_share_config_flag(share,
					    KSMBD_SHARE_FLAG_ENCRYPT_DATA))
		rsp->ShareFlags |=
			cpu_to_le32(SMB2_SHAREFLAG_ENCRYPT_DATA);

	rc = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_tree_connect_rsp));
	if (rc) {
		if (status.ret == KSMBD_TREE_CONN_STATUS_OK) {
			ksmbd_tree_conn_disconnect(sess, status.tree_conn);
			status.tree_conn = NULL;
		}
		status.ret = KSMBD_TREE_CONN_STATUS_NOMEM;
	}

	if (!IS_ERR(treename))
		kfree(treename);
	if (!IS_ERR(name))
		kfree(name);

	switch (status.ret) {
	case KSMBD_TREE_CONN_STATUS_OK:
		rsp->hdr.Status = STATUS_SUCCESS;
		rc = 0;
		break;
	case -ESTALE:
	case -ENOENT:
	case KSMBD_TREE_CONN_STATUS_NO_SHARE:
		rsp->hdr.Status = STATUS_BAD_NETWORK_NAME;
		break;
	case -ENOMEM:
	case KSMBD_TREE_CONN_STATUS_NOMEM:
		rsp->hdr.Status = STATUS_NO_MEMORY;
		break;
	case KSMBD_TREE_CONN_STATUS_ERROR:
	case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
	case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
		rsp->hdr.Status = STATUS_ACCESS_DENIED;
		break;
	case -EINVAL:
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		break;
	default:
		rsp->hdr.Status = STATUS_ACCESS_DENIED;
	}

	if (status.ret != KSMBD_TREE_CONN_STATUS_OK)
		smb2_set_err_rsp(work);

	if (tree_conn)
		ksmbd_tree_connect_put(tree_conn);

	return rc;
}

/**
 * smb2_create_open_flags() - convert smb open flags to unix open flags
 * @file_present:	is file already present
 * @access:		file access flags
 * @disposition:	file disposition flags
 * @may_flags:		set with MAY_ flags
 * @coptions:		file creation options
 * @mode:		file mode
 *
 * Return:      file open flags
 */
static int smb2_create_open_flags(bool file_present, __le32 access,
				  __le32 disposition,
				  int *may_flags,
				  __le32 coptions,
				  umode_t mode)
{
	int oflags = O_NONBLOCK | O_LARGEFILE;

	if (coptions & FILE_DIRECTORY_FILE_LE || S_ISDIR(mode)) {
		access &= ~FILE_WRITE_DESIRE_ACCESS_LE;
		ksmbd_debug(SMB, "Discard write access to a directory\n");
	}

	if (access & FILE_READ_DESIRED_ACCESS_LE &&
	    access & FILE_WRITE_DESIRE_ACCESS_LE) {
		oflags |= O_RDWR;
		*may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
	} else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
		oflags |= O_WRONLY;
		*may_flags = MAY_OPEN | MAY_WRITE;
	} else {
		oflags |= O_RDONLY;
		*may_flags = MAY_OPEN | MAY_READ;
	}

	if (access == FILE_READ_ATTRIBUTES_LE || S_ISBLK(mode) || S_ISCHR(mode))
		oflags |= O_PATH;

	if (file_present) {
		switch (disposition & FILE_CREATE_MASK_LE) {
		case FILE_OPEN_LE:
		case FILE_CREATE_LE:
			break;
		case FILE_SUPERSEDE_LE:
		case FILE_OVERWRITE_LE:
		case FILE_OVERWRITE_IF_LE:
			oflags |= O_TRUNC;
			break;
		default:
			break;
		}
	} else {
		switch (disposition & FILE_CREATE_MASK_LE) {
		case FILE_SUPERSEDE_LE:
		case FILE_CREATE_LE:
		case FILE_OPEN_IF_LE:
		case FILE_OVERWRITE_IF_LE:
			oflags |= O_CREAT;
			break;
		case FILE_OPEN_LE:
		case FILE_OVERWRITE_LE:
			oflags &= ~O_CREAT;
			break;
		default:
			break;
		}
	}

	return oflags;
}

/**
 * smb2_tree_disconnect() - handler for smb tree connect request
 * @work:	smb work containing request buffer
 *
 * Return:      0 on success, otherwise error
 */
int smb2_tree_disconnect(struct ksmbd_work *work)
{
	struct smb2_tree_disconnect_rsp *rsp;
	struct smb2_tree_disconnect_req *req;
	struct ksmbd_session *sess = work->sess;
	struct ksmbd_tree_connect *tcon = work->tcon;
	int err;

	ksmbd_debug(SMB, "Received smb2 tree disconnect request\n");

	WORK_BUFFERS(work, req, rsp);

	if (!tcon) {
		ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);

		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
		err = -ENOENT;
		goto err_out;
	}

	err = ksmbd_tree_conn_disconnect(sess, tcon);

	ksmbd_close_tree_conn_fds(work);

	if (err) {
		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
		goto err_out;
	}

	rsp->StructureSize = cpu_to_le16(4);
	err = ksmbd_iov_pin_rsp(work, rsp,
				sizeof(struct smb2_tree_disconnect_rsp));
	if (err) {
		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
		goto err_out;
	}

	return 0;

err_out:
	smb2_set_err_rsp(work);
	return err;

}

/**
 * smb2_session_logoff() - handler for session log off request
 * @work:	smb work containing request buffer
 *
 * Return:      0 on success, otherwise error
 */
int smb2_session_logoff(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
	struct ksmbd_session *sess = work->sess;
	struct smb2_logoff_req *req;
	struct smb2_logoff_rsp *rsp;
	int err;

	WORK_BUFFERS(work, req, rsp);

	ksmbd_debug(SMB, "Received smb2 session logoff request\n");

	ksmbd_conn_lock(conn);
	if (!ksmbd_conn_good(conn)) {
		ksmbd_conn_unlock(conn);
		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
		smb2_set_err_rsp(work);
		return -ENOENT;
	}

	down_write(&sess->chann_lock);
	if (sess->tearing_down) {
		up_write(&sess->chann_lock);
		ksmbd_conn_unlock(conn);
		rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
		smb2_set_err_rsp(work);
		return -ENOENT;
	}
	WRITE_ONCE(sess->tearing_down, true);
	up_write(&sess->chann_lock);

	ksmbd_all_conn_set_status(sess, KSMBD_SESS_NEED_RECONNECT);
	ksmbd_conn_unlock(conn);

	err = ksmbd_conn_wait_idle_sess(conn, sess);
	if (err) {
		down_write(&sess->chann_lock);
		WRITE_ONCE(sess->tearing_down, false);
		up_write(&sess->chann_lock);
		ksmbd_all_conn_set_status(sess, KSMBD_SESS_GOOD);
		rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
		smb2_set_err_rsp(work);
		return err;
	}

	ksmbd_close_session_fds(work);
	ksmbd_session_rpc_clear_list(sess);

	if (ksmbd_tree_conn_session_logoff(sess)) {
		ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
		smb2_set_err_rsp(work);
		err = -ENOENT;
	} else {
		err = 0;
	}

	down_write(&conn->session_lock);
	sess->kerberos_expiry = 0;
	sess->state = SMB2_SESSION_EXPIRED;
	up_write(&conn->session_lock);

	ksmbd_all_conn_set_status(sess, KSMBD_SESS_NEED_SETUP);
	/* Drop the table reference while work->sess pins the response keys. */
	ksmbd_session_unregister(conn, sess);

	if (err)
		return err;

	rsp->StructureSize = cpu_to_le16(4);
	err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_logoff_rsp));
	if (err) {
		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
		smb2_set_err_rsp(work);
		return err;
	}
	return 0;
}

/**
 * create_smb2_pipe() - create IPC pipe
 * @work:	smb work containing request buffer
 *
 * Return:      0 on success, otherwise error
 */
static noinline int create_smb2_pipe(struct ksmbd_work *work)
{
	struct smb2_create_rsp *rsp;
	struct smb2_create_req *req;
	int id = -1;
	int err;
	char *name;

	WORK_BUFFERS(work, req, rsp);

	name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
				      1, work->conn->local_nls);
	if (IS_ERR(name)) {
		rsp->hdr.Status = STATUS_NO_MEMORY;
		err = PTR_ERR(name);
		goto out;
	}

	id = ksmbd_session_rpc_open(work->sess, name);
	if (id < 0) {
		/*
		 * mdssvc (Spotlight) is a routine, expected probe from macOS
		 * that we deliberately don't support -- it's disabled at the
		 * __rpc_method() level (mgmt/user_session.c), but this
		 * generic failure log would otherwise still fire on every
		 * single probe regardless.
		 */
		if (!(id == -ENOENT && (!strcmp(name, "\\mdssvc") ||
					!strcmp(name, "mdssvc"))))
			pr_err("Unable to open RPC pipe: %d\n", id);
		err = id;
		goto out;
	}

	rsp->hdr.Status = STATUS_SUCCESS;
	rsp->StructureSize = cpu_to_le16(89);
	rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
	rsp->Flags = 0;
	rsp->CreateAction = cpu_to_le32(FILE_OPENED);

	rsp->CreationTime = cpu_to_le64(0);
	rsp->LastAccessTime = cpu_to_le64(0);
	rsp->ChangeTime = cpu_to_le64(0);
	rsp->AllocationSize = cpu_to_le64(0);
	rsp->EndofFile = cpu_to_le64(0);
	rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
	rsp->Reserved2 = 0;
	rsp->VolatileFileId = id;
	rsp->PersistentFileId = 0;
	rsp->CreateContextsOffset = 0;
	rsp->CreateContextsLength = 0;

	err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_create_rsp, Buffer));
	if (err)
		goto out;

	kfree(name);
	return 0;

out:
	switch (err) {
	case -EINVAL:
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		break;
	case -ENOENT:
		rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
		break;
	case -ENOSPC:
	case -ENOMEM:
		rsp->hdr.Status = STATUS_NO_MEMORY;
		break;
	}

	if (id >= 0)
		ksmbd_session_rpc_close(work->sess, id);

	if (!IS_ERR(name))
		kfree(name);

	smb2_set_err_rsp(work);
	return err;
}

static bool smb2_is_private_ea(const char *name, size_t name_len)
{
	if (name_len == SD_PREFIX_LEN &&
	    !strncasecmp(name, SD_PREFIX, SD_PREFIX_LEN))
		return true;
	if (name_len == DOS_ATTRIBUTE_PREFIX_LEN &&
	    !strncasecmp(name, DOS_ATTRIBUTE_PREFIX,
			   DOS_ATTRIBUTE_PREFIX_LEN))
		return true;
	if (name_len >= STREAM_PREFIX_LEN &&
	    !strncasecmp(name, STREAM_PREFIX, STREAM_PREFIX_LEN))
		return true;

	return false;
}

/**
 * smb2_set_ea() - handler for setting extended attributes using set
 *		info command
 * @eabuf:	set info command buffer
 * @buf_len:	set info command buffer length
 * @path:	dentry path for get ea
 * @get_write:	get write access to a mount
 *
 * Return:	0 on success, otherwise error
 */
static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
		       const struct path *path, bool get_write)
{
	const struct mnt_idmap *idmap = mnt_idmap(path->mnt);
	char *attr_name = NULL, *value;
	int rc = 0;
	unsigned int next = 0;

	if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength + 1 +
			le16_to_cpu(eabuf->EaValueLength))
		return -EINVAL;

	attr_name = kmalloc(XATTR_NAME_MAX + 1, KSMBD_DEFAULT_GFP);
	if (!attr_name)
		return -ENOMEM;

	do {
		if (!eabuf->EaNameLength)
			goto next;

		if (eabuf->name[eabuf->EaNameLength]) {
			rc = -EBADMSG;
			break;
		}

		ksmbd_debug(SMB,
			    "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
			    eabuf->name, eabuf->EaNameLength,
			    le16_to_cpu(eabuf->EaValueLength),
			    le32_to_cpu(eabuf->NextEntryOffset));

		if (eabuf->EaNameLength >
		    (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
			rc = -EINVAL;
			break;
		}
		if (smb2_is_private_ea(eabuf->name, eabuf->EaNameLength)) {
			rc = -EACCES;
			break;
		}

		memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
		memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
		       eabuf->EaNameLength);
		attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
		value = (char *)&eabuf->name + eabuf->EaNameLength + 1;

		if (!eabuf->EaValueLength) {
			rc = ksmbd_vfs_casexattr_len(idmap,
						     path->dentry,
						     attr_name,
						     XATTR_USER_PREFIX_LEN +
						     eabuf->EaNameLength, NULL);

			/* delete the EA only when it exits */
			if (rc > 0) {
				rc = ksmbd_vfs_remove_xattr(idmap,
							    path,
							    attr_name,
							    get_write);

				if (rc < 0) {
					ksmbd_debug(SMB,
						    "remove xattr failed(%d)\n",
						    rc);
					break;
				}
			}

			/* if the EA doesn't exist, just do nothing. */
			rc = 0;
		} else {
			rc = ksmbd_vfs_setxattr(idmap, path, attr_name, value,
						le16_to_cpu(eabuf->EaValueLength),
						0, get_write);
			if (rc < 0) {
				ksmbd_debug(SMB,
					    "ksmbd_vfs_setxattr is failed(%d)\n",
					    rc);
				break;
			}
		}

next:
		next = le32_to_cpu(eabuf->NextEntryOffset);
		if (next == 0 || buf_len < next)
			break;
		buf_len -= next;
		eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
		if (buf_len < sizeof(struct smb2_ea_info)) {
			rc = -EINVAL;
			break;
		}

		if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength + 1 +
				le16_to_cpu(eabuf->EaValueLength)) {
			rc = -EINVAL;
			break;
		}
	} while (next != 0);

	kfree(attr_name);
	return rc;
}

static noinline int smb2_set_stream_name_xattr(const struct path *path,
					       struct ksmbd_file *fp,
					       char *stream_name, int s_type,
					       bool *created)
{
	const struct mnt_idmap *idmap = mnt_idmap(path->mnt);
	size_t xattr_stream_size;
	char *xattr_stream_name;
	int rc;

	rc = ksmbd_vfs_xattr_stream_name(stream_name,
					 &xattr_stream_name,
					 &xattr_stream_size,
					 s_type);
	if (rc)
		return rc;

	fp->stream.name = xattr_stream_name;
	fp->stream.size = xattr_stream_size;

	/* Keep the existing xattr's case for subsequent writes and removal. */
	rc = ksmbd_vfs_casexattr_len(idmap,
				     path->dentry,
				     xattr_stream_name,
				     xattr_stream_size, xattr_stream_name);
	if (rc >= 0)
		return 0;
	if (rc != -ENOENT && rc != -ENODATA)
		return rc;

	if (fp->cdoption == FILE_OPEN_LE) {
		if (!strcmp(stream_name, "AFP_AfpInfo") &&
		    test_share_config_flag(fp->tcon->share_conf,
					   KSMBD_SHARE_FLAG_TIME_MACHINE) &&
		    test_tree_conn_flag(fp->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
			/*
			 * Synthesize an empty AFP_AfpInfo xattr on first access.
			 * type=0/creator=0 tells macOS to use the file extension
			 * for icon and type detection.
			 *
			 * Scoped to TIME_MACHINE shares, matching the rest of
			 * the AAPL series -- conn->is_aapl alone isn't a safe
			 * gate here, since the pre-existing narrow UniqueId=0
			 * path can also set it on ordinary, non-Time-Machine
			 * shares whenever a Mac client happens to negotiate
			 * AAPL there too.
			 */
			static const u8 afpinfo_empty[60] = {
				'A', 'F', 'P', 0x00,	/* signature */
				0x00, 0x00, 0x01, 0x00,	/* version */
				[15] = 0x80,		/* backup time */
			};
			rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name,
						(void *)afpinfo_empty,
						sizeof(afpinfo_empty), 0, false);
			return rc < 0 ? rc : 0;
		}
		ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
		return -EBADF;
	}

	if (!test_tree_conn_flag(fp->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE))
		return -EACCES;

	rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name, NULL, 0, 0, false);
	if (rc < 0)
		pr_err("Failed to store XATTR stream name :%d\n", rc);
	else
		*created = true;
	return 0;
}

/*
 * fp->stream.size is the byte length of the mangled xattr *name*
 * (used as attr_name_len when looking the xattr up), not the size of
 * the xattr's value. Reporting it as EndOfFile/AllocationSize for a
 * stream handle is wrong -- query the xattr's actual value length
 * instead.
 */
static loff_t ksmbd_stream_eof(struct ksmbd_file *fp)
{
	ssize_t slen = ksmbd_vfs_casexattr_len(file_mnt_idmap(fp->filp),
					       fp->filp->f_path.dentry,
					       fp->stream.name,
					       fp->stream.size, NULL);
	return slen < 0 ? 0 : (loff_t)slen;
}

static int smb2_remove_smb_xattrs(const struct path *path)
{
	const struct mnt_idmap *idmap = mnt_idmap(path->mnt);
	char *name, *xattr_list = NULL;
	ssize_t xattr_list_len;
	int err = 0;

	xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
	if (xattr_list_len < 0) {
		goto out;
	} else if (!xattr_list_len) {
		ksmbd_debug(SMB, "empty xattr in the file\n");
		goto out;
	}

	for (name = xattr_list; name - xattr_list < xattr_list_len;
			name += strlen(name) + 1) {
		ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));

		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
		    !strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
			     STREAM_PREFIX_LEN)) {
			err = ksmbd_vfs_remove_xattr(idmap, path,
						     name, true);
			if (err)
				ksmbd_debug(SMB, "remove xattr failed : %s\n",
					    name);
		}
	}
out:
	kvfree(xattr_list);
	return err;
}

static int smb2_create_truncate(const struct path *path)
{
	int rc = vfs_truncate(path, 0);

	if (rc) {
		pr_err("vfs_truncate failed, rc %d\n", rc);
		return rc;
	}

	rc = smb2_remove_smb_xattrs(path);
	if (rc == -EOPNOTSUPP)
		rc = 0;
	if (rc)
		ksmbd_debug(SMB,
			    "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
			    rc);
	return rc;
}

static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, const struct path *path,
			    struct ksmbd_file *fp)
{
	struct xattr_dos_attrib da = {0};
	int rc;

	if (!test_share_config_flag(tcon->share_conf,
				    KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
		return;

	da.version = 4;
	da.attr = le32_to_cpu(fp->f_ci->m_fattr);
	da.itime = da.create_time = fp->create_time;
	da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
		XATTR_DOSINFO_ITIME;

	rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_idmap(path->mnt), path, &da, true);
	if (rc)
		ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
}

static bool smb2_parent_compressed(struct ksmbd_tree_connect *tcon,
				   const struct path *path)
{
	struct dentry *parent = dget_parent(path->dentry);
	struct file_kattr fa = { .flags_valid = true };
	struct xattr_dos_attrib da;
	bool compressed = false;
	int rc;

	rc = vfs_fileattr_get(parent, &fa);
	if (!rc && fa.flags & FS_COMPR_FL) {
		compressed = true;
		goto out;
	}

	rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt), parent, &da);
	if (rc > 0 && da.attr & FILE_ATTRIBUTE_COMPRESSED)
		compressed = true;

out:
	dput(parent);
	return compressed;
}

static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
			       const struct path *path, struct ksmbd_file *fp)
{
	struct xattr_dos_attrib da = {};
	bool store_dos_attrs = test_share_config_flag(tcon->share_conf,
						      KSMBD_SHARE_FLAG_STORE_DOS_ATTRS);
	int rc;

	fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);

	/* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
	rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt),
					    path->dentry, &da);
	if (rc > 0) {
		if (store_dos_attrs) {
			fp->f_ci->m_fattr = cpu_to_le32(da.attr);
			fp->create_time = da.create_time;
			fp->itime = da.itime;
		} else {
			fp->f_ci->m_fattr &=
				~(FILE_ATTRIBUTE_COMPRESSED_LE |
				  FILE_ATTRIBUTE_SPARSE_FILE_LE);
			fp->f_ci->m_fattr |=
				cpu_to_le32(da.attr &
					    (FILE_ATTRIBUTE_COMPRESSED |
					     FILE_ATTRIBUTE_SPARSE_FILE));
		}
	}
}

static int smb2_creat(struct ksmbd_work *work,
		      struct path *path, char *name, int open_flags,
		      umode_t posix_mode, bool is_dir)
{
	struct ksmbd_tree_connect *tcon = work->tcon;
	struct ksmbd_share_config *share = tcon->share_conf;
	umode_t mode;
	int rc;

	if (!(open_flags & O_CREAT))
		return -EBADF;

	ksmbd_debug(SMB, "file does not exist, so creating\n");
	if (is_dir == true) {
		ksmbd_debug(SMB, "creating directory\n");

		mode = share_config_directory_mode(share, posix_mode);
		rc = ksmbd_vfs_mkdir(work, name, mode);
		if (rc)
			return rc;
	} else {
		ksmbd_debug(SMB, "creating regular file\n");

		mode = share_config_create_mode(share, posix_mode);
		rc = ksmbd_vfs_create(work, name, mode);
		if (rc)
			return rc;
	}

	rc = ksmbd_vfs_kern_path(work, name, 0, path, 0);
	if (rc) {
		pr_err("cannot get linux path (%s), err = %d\n",
		       name, rc);
		return rc;
	}
	return 0;
}

static int smb2_create_sd_buffer(struct ksmbd_work *work,
				 struct smb2_create_req *req,
				 const struct path *path)
{
	struct create_context *context;
	struct create_sd_buf_req *sd_buf;

	if (!req->CreateContextsOffset)
		return -ENOENT;

	/* Parse SD BUFFER create contexts */
	context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER, 4);
	if (!context)
		return -ENOENT;
	else if (IS_ERR(context))
		return PTR_ERR(context);

	ksmbd_debug(SMB,
		    "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
	sd_buf = (struct create_sd_buf_req *)context;
	if (le16_to_cpu(context->DataOffset) +
	    le32_to_cpu(context->DataLength) <
	    sizeof(struct create_sd_buf_req))
		return -EINVAL;
	return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
			    le32_to_cpu(sd_buf->ccontext.DataLength), true, false,
			    true, true);
}

static int ksmbd_acls_fattr(struct smb_fattr *fattr,
			    const struct mnt_idmap *idmap,
			    struct inode *inode)
{
	struct posix_acl *acl;
	vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
	vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);

	fattr->cf_uid = vfsuid_into_kuid(vfsuid);
	fattr->cf_gid = vfsgid_into_kgid(vfsgid);
	fattr->cf_mode = inode->i_mode;
	fattr->cf_acls = NULL;
	fattr->cf_dacls = NULL;

	if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
		acl = get_inode_acl(inode, ACL_TYPE_ACCESS);
		if (IS_ERR(acl)) {
			if (acl != ERR_PTR(-EOPNOTSUPP))
				return PTR_ERR(acl);
			acl = NULL;
		}
		fattr->cf_acls = acl;

		if (S_ISDIR(inode->i_mode)) {
			acl = get_inode_acl(inode, ACL_TYPE_DEFAULT);
			if (IS_ERR(acl)) {
				if (acl != ERR_PTR(-EOPNOTSUPP)) {
					posix_acl_release(fattr->cf_acls);
					return PTR_ERR(acl);
				}
				acl = NULL;
			}
			fattr->cf_dacls = acl;
		}
	}

	return 0;
}

enum {
	DURABLE_RECONN_V2 = 1,
	DURABLE_RECONN,
	DURABLE_REQ_V2,
	DURABLE_REQ,
};

struct durable_info {
	struct ksmbd_file *fp;
	unsigned short int type;
	bool persistent;
	bool reconnected;
	bool replay;
	bool replay_consumed;
	bool app_instance_id;
	bool app_instance_version_valid;
	unsigned int timeout;
	char *CreateGuid;
	char AppInstanceId[SMB2_CREATE_GUID_SIZE];
	u64 app_instance_version_high;
	u64 app_instance_version_low;
};

static int smb2_check_durable_replay(struct ksmbd_work *work,
				     struct ksmbd_file *fp,
				     struct lease_ctx_info *lc,
				     bool persistent)
{
	struct oplock_info *opinfo;
	int ret = 0;

	if (!fp->conn && !fp->is_durable && !fp->is_persistent)
		return -EACCES;

	if (ksmbd_vfs_compare_durable_owner(fp, work->sess->user) == false)
		return -EACCES;

	if (fp->is_persistent && !persistent)
		return -EINVAL;

	opinfo = opinfo_get(fp);
	if (!opinfo)
		return 0;

	if (opinfo->is_lease) {
		if (!lc ||
		    memcmp(opinfo->o_lease->lease_key, lc->lease_key,
			   SMB2_LEASE_KEY_SIZE)) {
			ret = -EACCES;
			goto out;
		}
	} else {
		if (lc) {
			ret = -EACCES;
			goto out;
		}

		/* A live CREATE replay may follow a completed oplock break. */
		if (!fp->conn && fp->is_durable &&
		    opinfo->level != SMB2_OPLOCK_LEVEL_BATCH)
			ret = -EACCES;
	}
out:
	opinfo_put(opinfo);
	return ret;
}

static bool smb2_durable_replay_consumed(struct ksmbd_file *fp)
{
	bool consumed;

	spin_lock(&fp->f_lock);
	consumed = fp->durable_replay_consumed;
	spin_unlock(&fp->f_lock);

	return consumed;
}

static void smb2_mark_durable_replay_consumed(struct ksmbd_file *fp)
{
	spin_lock(&fp->f_lock);
	fp->durable_replay_consumed = true;
	spin_unlock(&fp->f_lock);
}

static bool smb2_durable_replay_differs(struct ksmbd_file *fp,
					struct smb2_create_req *req)
{
	return fp->cdoption != req->CreateDisposition ||
		fp->create_file_attributes != req->FileAttributes;
}

static int parse_durable_handle_context(struct ksmbd_work *work,
					struct smb2_create_req *req,
					struct lease_ctx_info *lc,
					struct durable_info *dh_info)
{
	struct ksmbd_conn *conn = work->conn;
	struct create_context *context;
	int dh_idx, err = 0;
	u64 persistent_id = 0;
	int req_op_level;
	static const char * const durable_arr[] = {"DH2C", "DHnC", "DH2Q", "DHnQ"};

	req_op_level = req->RequestedOplockLevel;
	for (dh_idx = DURABLE_RECONN_V2; dh_idx <= ARRAY_SIZE(durable_arr);
	     dh_idx++) {
		context = smb2_find_context_vals(req, durable_arr[dh_idx - 1], 4);
		if (IS_ERR(context)) {
			err = PTR_ERR(context);
			goto out;
		}
		if (!context)
			continue;

		switch (dh_idx) {
		case DURABLE_RECONN_V2:
		{
			struct create_durable_handle_reconnect_v2 *recon_v2;
			u32 flags;

			if (dh_info->type == DURABLE_RECONN ||
			    dh_info->type == DURABLE_REQ_V2) {
				err = -EINVAL;
				goto out;
			}

			if (le32_to_cpu(context->DataLength) <
			    sizeof(recon_v2->dcontext)) {
				err = -EINVAL;
				goto out;
			}

			recon_v2 = (struct create_durable_handle_reconnect_v2 *)context;
			flags = le32_to_cpu(recon_v2->dcontext.Flags);
			if (flags & ~SMB2_DHANDLE_FLAG_PERSISTENT) {
				err = -EINVAL;
				goto out;
			}
			dh_info->persistent = flags & SMB2_DHANDLE_FLAG_PERSISTENT;
			persistent_id = recon_v2->dcontext.Fid.PersistentFileId;
			dh_info->fp = ksmbd_lookup_durable_fd(persistent_id);
			if (!dh_info->fp) {
				ksmbd_debug(SMB, "Failed to get durable handle state\n");
				err = -EBADF;
				goto out;
			}

			/* A zero VolatileFileId means that the client did not specify it. */
			if (recon_v2->dcontext.Fid.VolatileFileId &&
			    dh_info->fp->durable_volatile_id !=
			    recon_v2->dcontext.Fid.VolatileFileId) {
				err = -EBADF;
				ksmbd_put_durable_fd(dh_info->fp);
				goto out;
			}

			if (memcmp(dh_info->fp->create_guid, recon_v2->dcontext.CreateGuid,
				   SMB2_CREATE_GUID_SIZE)) {
				err = -EBADF;
				ksmbd_put_durable_fd(dh_info->fp);
				goto out;
			}

			/* A persistent reconnect must match the original open type. */
			if (dh_info->fp->is_persistent != dh_info->persistent) {
				err = dh_info->persistent ? -EINVAL : -EBADF;
				ksmbd_put_durable_fd(dh_info->fp);
				goto out;
			}

			dh_info->type = dh_idx;
			dh_info->reconnected = true;
			ksmbd_debug(SMB,
				"reconnect v2 Persistent-id from reconnect = %llu\n",
					persistent_id);
			break;
		}
		case DURABLE_RECONN:
		{
			create_durable_reconn_t *recon;

			if (dh_info->type == DURABLE_RECONN_V2 ||
			    dh_info->type == DURABLE_REQ_V2) {
				err = -EINVAL;
				goto out;
			}

			if (le32_to_cpu(context->DataLength) <
			    sizeof(recon->Data)) {
				err = -EINVAL;
				goto out;
			}

			recon = (create_durable_reconn_t *)context;
			persistent_id = recon->Data.Fid.PersistentFileId;
			dh_info->fp = ksmbd_lookup_durable_fd(persistent_id);
			if (!dh_info->fp) {
				ksmbd_debug(SMB, "Failed to get durable handle state\n");
				err = -EBADF;
				goto out;
			}

			/* A zero VolatileFileId means that the client did not specify it. */
			if (recon->Data.Fid.VolatileFileId &&
			    dh_info->fp->durable_volatile_id !=
			    recon->Data.Fid.VolatileFileId) {
				err = -EBADF;
				ksmbd_put_durable_fd(dh_info->fp);
				goto out;
			}

			dh_info->type = dh_idx;
			dh_info->reconnected = true;
			ksmbd_debug(SMB, "reconnect Persistent-id from reconnect = %llu\n",
				    persistent_id);
			break;
		}
		case DURABLE_REQ_V2:
		{
			struct create_durable_req_v2 *durable_v2_blob;

			if (dh_info->type == DURABLE_RECONN ||
			    dh_info->type == DURABLE_RECONN_V2) {
				err = -EINVAL;
				goto out;
			}

			if (le32_to_cpu(context->DataLength) <
			    sizeof(durable_v2_blob->dcontext)) {
				err = -EINVAL;
				goto out;
			}

			durable_v2_blob =
				(struct create_durable_req_v2 *)context;
			if (le32_to_cpu(durable_v2_blob->dcontext.Flags) &
			    ~SMB2_DHANDLE_FLAG_PERSISTENT) {
				err = -EINVAL;
				goto out;
			}
			ksmbd_debug(SMB, "Request for durable v2 open\n");
			dh_info->CreateGuid = durable_v2_blob->dcontext.CreateGuid;
			dh_info->persistent =
				le32_to_cpu(durable_v2_blob->dcontext.Flags) &
				SMB2_DHANDLE_FLAG_PERSISTENT;
			dh_info->fp = ksmbd_lookup_fd_cguid(durable_v2_blob->dcontext.CreateGuid);
			if (dh_info->fp) {
				if (!memcmp(conn->ClientGUID, dh_info->fp->client_guid,
					    SMB2_CLIENT_GUID_SIZE)) {
					if (!(req->hdr.Flags & SMB2_FLAGS_REPLAY_OPERATION)) {
						err = -ENOEXEC;
						ksmbd_put_durable_fd(dh_info->fp);
						goto out;
					}

					if (dh_info->fp->f_state == FP_NEW) {
						/* Original CREATE is still pending. */
						ksmbd_put_durable_fd(dh_info->fp);
						err = -EAGAIN;
						goto out;
					}

					err = smb2_check_durable_replay(work,
									dh_info->fp,
									lc,
									dh_info->persistent);
					if (err) {
						ksmbd_put_durable_fd(dh_info->fp);
						goto out;
					}

					err = ksmbd_rebind_replay_fd(work, dh_info->fp);
					if (err) {
						ksmbd_put_durable_fd(dh_info->fp);
						goto out;
					}

					if (dh_info->fp->conn &&
					    smb2_durable_replay_consumed(dh_info->fp)) {
						ksmbd_put_durable_fd(dh_info->fp);
						dh_info->fp = NULL;
						dh_info->type = dh_idx;
						dh_info->replay_consumed = true;
						break;
					}

					if (dh_info->fp->conn) {
						if (smb2_durable_replay_differs(dh_info->fp,
									       req))
							smb2_mark_durable_replay_consumed(
									dh_info->fp);
						dh_info->replay = true;
					} else {
						dh_info->reconnected = true;
					}
					dh_info->type = dh_idx;
					goto out;
				}
				ksmbd_put_durable_fd(dh_info->fp);
				dh_info->fp = NULL;
			}

			if ((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
			    req_op_level == SMB2_OPLOCK_LEVEL_BATCH) {
				dh_info->timeout =
					le32_to_cpu(durable_v2_blob->dcontext.Timeout);
				dh_info->type = dh_idx;
			}
			break;
		}
		case DURABLE_REQ:
			if (dh_info->type == DURABLE_RECONN)
				goto out;
			if (dh_info->type == DURABLE_RECONN_V2 ||
			    dh_info->type == DURABLE_REQ_V2) {
				err = -EINVAL;
				goto out;
			}

			if ((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
			    req_op_level == SMB2_OPLOCK_LEVEL_BATCH) {
				ksmbd_debug(SMB, "Request for durable open\n");
				dh_info->type = dh_idx;
			}
		}
	}

out:
	return err;
}

static int parse_app_instance_id(struct smb2_create_req *req,
				 struct durable_info *dh_info)
{
	struct create_context *context;
	char *data;

	context = smb2_find_context_vals(req, SMB2_CREATE_APP_INSTANCE_ID,
					 SMB2_CREATE_GUID_SIZE);
	if (IS_ERR(context))
		return PTR_ERR(context);
	if (!context)
		return 0;

	if (le32_to_cpu(context->DataLength) < 20)
		return -EINVAL;

	data = (char *)context + le16_to_cpu(context->DataOffset);
	if (data[0] != 20 || data[1])
		return -EINVAL;

	memcpy(dh_info->AppInstanceId, data + 4, SMB2_CREATE_GUID_SIZE);
	dh_info->app_instance_id = true;
	return 0;
}

static int parse_app_instance_version(struct smb2_create_req *req,
				      struct durable_info *dh_info)
{
	struct create_context *context;
	char *data;

	context = smb2_find_context_vals(req, SMB2_CREATE_APP_INSTANCE_VERSION,
					 SMB2_CREATE_GUID_SIZE);
	if (IS_ERR(context))
		return PTR_ERR(context);
	if (!context)
		return 0;

	if (le32_to_cpu(context->DataLength) < 24)
		return -EINVAL;

	data = (char *)context + le16_to_cpu(context->DataOffset);
	if (get_unaligned_le16(data) != 24 ||
	    get_unaligned_le16(data + 2) != 0)
		return -EINVAL;

	dh_info->app_instance_version_high = get_unaligned_le64(data + 8);
	dh_info->app_instance_version_low = get_unaligned_le64(data + 16);
	dh_info->app_instance_version_valid = true;
	return 0;
}

static int smb2_app_instance_stream_matches(struct ksmbd_file *fp,
					    char *stream_name, int s_type,
					    bool *matches)
{
	char *xattr_stream_name;
	size_t xattr_stream_size;
	int rc;

	if (!stream_name) {
		*matches = !ksmbd_stream_fd(fp);
		return 0;
	}

	rc = ksmbd_vfs_xattr_stream_name(stream_name, &xattr_stream_name,
					 &xattr_stream_size, s_type);
	if (rc)
		return rc;

	*matches = fp->stream.name && fp->stream.size >= 0 &&
		   (size_t)fp->stream.size == xattr_stream_size &&
		   !strncasecmp(fp->stream.name, xattr_stream_name,
				xattr_stream_size);
	kfree(xattr_stream_name);
	return 0;
}

static int smb2_handle_app_instance_id(struct ksmbd_work *work,
				       struct smb2_create_rsp *rsp,
				       struct durable_info *dh_info,
				       const struct path *path,
				       char *stream_name, int s_type,
				       bool *closed)
{
	struct ksmbd_conn *conn = work->conn;
	struct ksmbd_file *old_fp;
	const struct path *old_path;
	char *app_instance_id;
	__le32 maximal_access = FILE_MAXIMAL_ACCESS_LE;
	bool reject = false, stream_matches;
	int cursor = 0, rc;

	*closed = false;
	if (!dh_info->app_instance_id)
		return 0;
	app_instance_id = dh_info->AppInstanceId;

	while (true) {
		old_fp = ksmbd_lookup_fd_app_instance_id_next(app_instance_id,
							      &cursor);
		if (!old_fp)
			return 0;

		if (!ksmbd_app_instance_id_matches(work, old_fp) ||
		    !path_equal(&old_fp->filp->f_path, path)) {
			ksmbd_put_durable_fd(old_fp);
			continue;
		}

		rc = smb2_app_instance_stream_matches(old_fp, stream_name,
						      s_type, &stream_matches);
		if (rc) {
			ksmbd_put_durable_fd(old_fp);
			return rc;
		}
		if (!stream_matches) {
			ksmbd_put_durable_fd(old_fp);
			continue;
		}
		break;
	}

	if (dh_info->app_instance_version_valid) {
		if (old_fp->app_instance_version_valid &&
		    (dh_info->app_instance_version_high <
			 old_fp->app_instance_version_high ||
		     (dh_info->app_instance_version_high ==
			      old_fp->app_instance_version_high &&
			      dh_info->app_instance_version_low <=
			      old_fp->app_instance_version_low)))
			reject = true;
	} else if (old_fp->app_instance_version_valid) {
		reject = true;
	}

	if (reject) {
		ksmbd_put_durable_fd(old_fp);
		rsp->hdr.Status = STATUS_FILE_FORCED_CLOSED;
		return -EIO;
	}

	/* Authorize the referenced open even if its name changes meanwhile. */
	old_path = &old_fp->filp->f_path;
	rc = smb_check_perm_dacl(conn, old_path, &maximal_access, 0,
				 work->sess->user->uid,
				 ksmbd_user_authenticated(work->sess->user), false);
	if (rc) {
		/* Access denial prevents takeover, not the CREATE itself. */
		ksmbd_put_durable_fd(old_fp);
		return rc == -EACCES ? 0 : rc;
	}
	if (maximal_access == FILE_MAXIMAL_ACCESS_LE)
		ksmbd_vfs_query_maximal_access(mnt_idmap(old_path->mnt),
					       old_path->dentry, &maximal_access);
	/* Also require read access with the effective VFS credentials. */
	if ((le32_to_cpu(maximal_access) & GENERIC_READ_FLAGS) !=
	    GENERIC_READ_FLAGS ||
	    inode_permission(mnt_idmap(old_path->mnt),
			     d_inode(old_path->dentry), MAY_OPEN | MAY_READ)) {
		ksmbd_put_durable_fd(old_fp);
		return 0;
	}

	return ksmbd_close_fd_app_instance_id(work, old_fp, closed);
}

/**
 * smb2_open() - handler for smb file open request
 * @work:	smb work containing request buffer
 *
 * Return:      0 on success, otherwise error
 */
int smb2_open(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
	struct ksmbd_session *sess = work->sess;
	struct ksmbd_tree_connect *tcon = work->tcon;
	struct smb2_create_req *req;
	struct smb2_create_rsp *rsp;
	struct path path;
	struct ksmbd_share_config *share = tcon->share_conf;
	struct ksmbd_file *fp = NULL;
	struct file *filp = NULL;
	const struct mnt_idmap *idmap = NULL;
	struct kstat stat;
	struct create_context *context;
	struct lease_ctx_info *lc = NULL;
	struct create_ea_buf_req *ea_buf = NULL;
	struct oplock_info *opinfo;
	struct durable_info dh_info = {0};
	__le32 *next_ptr = NULL;
	int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
	int rc = 0;
	int contxt_cnt = 0, query_disk_id = 0;
	bool maximal_access_ctxt = false, posix_ctxt = false;
	bool aapl_ctxt = false;
	bool durable_rsp = true;
	__u64 aapl_req_bitmap = 0, aapl_client_caps = 0;
	int s_type = 0;
	int next_off = 0;
	char *name = NULL;
	char *stream_name = NULL;
	bool file_present = false, created = false, already_permitted = false;
	bool app_instance_id_checked = false, app_instance_closed;
	bool stream_created = false;
	int share_ret, need_truncate = 0;
	u64 time, alloc_size = 0;
	umode_t posix_mode = 0;
	__le32 daccess, maximal_access = 0;
	u32 dos_attr;
	int iov_len = 0;

	ksmbd_debug(SMB, "Received smb2 create request\n");

	WORK_BUFFERS(work, req, rsp);

	if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
	    (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
		ksmbd_debug(SMB, "invalid flag in chained command\n");
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		smb2_set_err_rsp(work);
		return -EINVAL;
	}

	if (req->CreateContextsOffset) {
		context = smb2_find_context_vals(req, SMB2_CREATE_TAG_POSIX, 16);
		if (IS_ERR(context)) {
			rc = PTR_ERR(context);
			goto err_out2;
		} else if (context) {
			struct create_posix *posix = (struct create_posix *)context;

			if (conn->dialect != SMB311_PROT_ID) {
				rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
				rc = -ENOTTY;
				goto err_out2;
			}
			if (!tcon->posix_extensions) {
				rc = -EOPNOTSUPP;
				goto err_out2;
			}
			if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
				rc = -EOPNOTSUPP;
				goto err_out2;
			}
			if (le16_to_cpu(context->DataOffset) +
				le32_to_cpu(context->DataLength) <
			    sizeof(struct create_posix) - 4) {
				rc = -EINVAL;
				goto err_out2;
			}
			ksmbd_debug(SMB, "get posix context\n");

			posix_mode = le32_to_cpu(posix->Mode);
			posix_ctxt = true;
		}
	}
	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
		ksmbd_debug(SMB, "IPC pipe create request\n");
		return create_smb2_pipe(work);
	}

	if (req->NameLength) {
		name = smb2_get_name((char *)req + le16_to_cpu(req->NameOffset),
				     le16_to_cpu(req->NameLength),
				     work->conn->local_nls);
		if (IS_ERR(name)) {
			rc = PTR_ERR(name);
			name = NULL;
			goto err_out2;
		}

		ksmbd_debug(SMB, "converted name = %s\n", name);

		if (posix_ctxt == false) {
			if (strchr(name, ':')) {
				if (!test_share_config_flag(work->tcon->share_conf,
							KSMBD_SHARE_FLAG_STREAMS)) {
					rc = -EBADF;
					goto err_out2;
				}
				rc = parse_stream_name(name, &stream_name, &s_type);
				if (rc < 0)
					goto err_out2;
			}

			rc = ksmbd_validate_filename(name);
			if (rc < 0)
				goto err_out2;
		}

		if (ksmbd_share_veto_filename(share, name)) {
			rc = -ENOENT;
			ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
				    name);
			goto err_out2;
		}
	} else {
		name = kstrdup("", KSMBD_DEFAULT_GFP);
		if (!name) {
			rc = -ENOMEM;
			goto err_out2;
		}
	}

	req_op_level = req->RequestedOplockLevel;

	if (req->CreateContextsOffset) {
		rc = parse_app_instance_id(req, &dh_info);
		if (rc)
			goto err_out2;
		rc = parse_app_instance_version(req, &dh_info);
		if (rc)
			goto err_out2;
	}

	if (server_conf.flags & KSMBD_GLOBAL_FLAG_DURABLE_HANDLE &&
	    req->CreateContextsOffset) {
		lc = parse_lease_state(req);
		if (IS_ERR(lc)) {
			rc = PTR_ERR(lc);
			lc = NULL;
			goto err_out2;
		}
		if (lc && lc->version == 2 && conn->dialect < SMB30_PROT_ID) {
			kfree(lc);
			lc = NULL;
			if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
				req_op_level = SMB2_OPLOCK_LEVEL_NONE;
		}
		rc = parse_durable_handle_context(work, req, lc, &dh_info);
		if (rc) {
			ksmbd_debug(SMB, "error parsing durable handle context\n");
			goto err_out2;
		}

		if (dh_info.replay == true) {
			fp = dh_info.fp;
			if (ksmbd_override_fsids(work)) {
				rc = -ENOMEM;
				goto err_out2;
			}

			file_info = FILE_OPENED;
			rc = ksmbd_vfs_getattr(&fp->filp->f_path, &stat);
			if (rc)
				goto err_out1;

			goto reconnected_fp;
		}

		if (dh_info.reconnected == true) {
			rc = smb2_check_durable_oplock(conn, share, dh_info.fp,
					lc, sess->user, name);
			if (rc)
				goto err_out2;

			rc = ksmbd_reopen_durable_fd(work, dh_info.fp);
			if (rc) {
				if (rc == -ENOTCONN)
					rsp->hdr.Status =
						STATUS_NETWORK_NAME_DELETED;
				goto err_out2;
			}

			fp = dh_info.fp;

			if (ksmbd_override_fsids(work)) {
				rc = -ENOMEM;
				goto err_out2;
			}

			file_info = FILE_OPENED;

			rc = ksmbd_vfs_getattr(&fp->filp->f_path, &stat);
			if (rc)
				goto err_out1;

			goto reconnected_fp;
		}

	} else if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
		lc = parse_lease_state(req);
		if (IS_ERR(lc)) {
			rc = PTR_ERR(lc);
			lc = NULL;
			goto err_out2;
		}
		if (lc && lc->version == 2 && conn->dialect < SMB30_PROT_ID) {
			kfree(lc);
			lc = NULL;
			req_op_level = SMB2_OPLOCK_LEVEL_NONE;
		}
	}

	if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
		pr_err("Invalid impersonationlevel : 0x%x\n",
		       le32_to_cpu(req->ImpersonationLevel));
		rc = -EIO;
		rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
		goto err_out2;
	}

	if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
		pr_err("Invalid create options : 0x%x\n",
		       le32_to_cpu(req->CreateOptions));
		rc = -EINVAL;
		goto err_out2;
	} else {
		if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
		    req->CreateOptions & FILE_RANDOM_ACCESS_LE)
			req->CreateOptions &= ~FILE_SEQUENTIAL_ONLY_LE;

		if (req->CreateOptions &
		    (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
		     FILE_RESERVE_OPFILTER_LE)) {
			rc = -EOPNOTSUPP;
			goto err_out2;
		}

		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
			if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
				rc = -EINVAL;
				goto err_out2;
			}
		}

		/* MS-FSA 2.1.5.1: delete-on-close requires DELETE access */
		if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE &&
		    !(smb_map_generic_desired_access(req->DesiredAccess) &
		      FILE_DELETE_LE)) {
			rc = -EINVAL;
			goto err_out2;
		}
	}

	if (le32_to_cpu(req->CreateDisposition) >
	    le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
		pr_err("Invalid create disposition : 0x%x\n",
		       le32_to_cpu(req->CreateDisposition));
		rc = -EINVAL;
		goto err_out2;
	}

	if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
		pr_err("Invalid desired access : 0x%x\n",
		       le32_to_cpu(req->DesiredAccess));
		rc = -EACCES;
		goto err_out2;
	}

	if (req->DesiredAccess == FILE_SYNCHRONIZE_LE &&
	    req->CreateDisposition == FILE_OPEN_IF_LE &&
	    !req->FileAttributes) {
		rc = -EACCES;
		goto err_out2;
	}

	if (req->FileAttributes &&
	    (req->FileAttributes & ~cpu_to_le32(SMB2_CREATE_FILE_ATTRIBUTE_MASK))) {
		pr_err("Invalid file attribute : 0x%x\n",
		       le32_to_cpu(req->FileAttributes));
		rc = -EINVAL;
		goto err_out2;
	}

	if (req->CreateContextsOffset) {
		/* Parse non-durable handle create contexts */
		context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER, 4);
		if (IS_ERR(context)) {
			rc = PTR_ERR(context);
			goto err_out2;
		} else if (context) {
			ea_buf = (struct create_ea_buf_req *)context;
			if (le16_to_cpu(context->DataOffset) +
			    le32_to_cpu(context->DataLength) <
			    sizeof(struct create_ea_buf_req)) {
				rc = -EINVAL;
				goto err_out2;
			}
			if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
				rsp->hdr.Status = STATUS_ACCESS_DENIED;
				rc = -EACCES;
				goto err_out2;
			}
		}

		context = smb2_find_context_vals(req,
						 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST, 4);
		if (IS_ERR(context)) {
			rc = PTR_ERR(context);
			goto err_out2;
		} else if (context) {
			ksmbd_debug(SMB,
				    "get query maximal access context\n");
			maximal_access_ctxt = 1;
		}

		context = smb2_find_context_vals(req,
						 SMB2_CREATE_TIMEWARP_REQUEST, 4);
		if (IS_ERR(context)) {
			rc = PTR_ERR(context);
			goto err_out2;
		} else if (context) {
			ksmbd_debug(SMB, "get timewarp context\n");
			rc = -EBADF;
			goto err_out2;
		}
	}

	if (ksmbd_override_fsids(work)) {
		rc = -ENOMEM;
		goto err_out2;
	}

resolve_path:
	file_present = false;
	maximal_access = 0;
	rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS,
				 &path, 1);

	/* Validate takeover before disconnected delete-on-close cleanup. */
	if (!rc && dh_info.app_instance_id && !dh_info.reconnected &&
	    !dh_info.replay && !app_instance_id_checked) {
		app_instance_id_checked = true;
		rc = smb2_handle_app_instance_id(work, rsp, &dh_info, &path,
						 stream_name, s_type,
						 &app_instance_closed);
		if (rc) {
			path_put(&path);
			goto err_out1;
		}
		if (app_instance_closed) {
			path_put(&path);
			goto resolve_path;
		}
	}

	/*
	 * A durable handle opened with delete-on-close is preserved across a
	 * disconnect so it can be reclaimed by a durable reconnect.  When a new
	 * delete-on-close open for the same name arrives instead, the
	 * disconnected handle must give way: close it so its delete-on-close
	 * removes the file, then re-resolve so this open can create a fresh one.
	 */
	if (!rc && (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) &&
	    (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
	     req->CreateDisposition == FILE_OPEN_IF_LE) &&
	    ksmbd_close_disconnected_durable_delete_on_close(path.dentry)) {
		path_put(&path);
		rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS,
					 &path, 1);
	}

	if (!rc) {
		file_present = true;

		if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
			struct xattr_dos_attrib da;

			/*
			 * If file exists with under flags, return access
			 * denied error.
			 */
			if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
			    req->CreateDisposition == FILE_OPEN_IF_LE) {
				rc = -EACCES;
				goto err_out;
			}

			if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
				ksmbd_debug(SMB,
					    "User does not have write permission\n");
					rc = -EACCES;
					goto err_out;
				}

			if (test_share_config_flag(tcon->share_conf,
						   KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
			    ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path.mnt),
							 path.dentry, &da) > 0 &&
			    da.attr & FILE_ATTRIBUTE_READONLY) {
				rsp->hdr.Status = STATUS_CANNOT_DELETE;
				rc = -EACCES;
				goto err_out;
			}
		} else if (d_is_symlink(path.dentry)) {
			rc = -EACCES;
			goto err_out;
		}

		idmap = mnt_idmap(path.mnt);
	} else {
		if (rc != -ENOENT)
			goto err_out;
		ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
			    name, rc);
		rc = 0;
	}

	if (!file_present && req->CreateOptions & FILE_DELETE_ON_CLOSE_LE &&
	    req->FileAttributes & FILE_ATTRIBUTE_READONLY_LE) {
		rsp->hdr.Status = STATUS_CANNOT_DELETE;
		rc = -EACCES;
		goto err_out;
	}

	/*
	 * An explicit ::$DATA suffix names the unnamed data stream and is
	 * canonicalized to a NULL stream name (base file), but the request
	 * still has to be validated against the data-stream type, e.g. opening
	 * <dir>::$DATA with FILE_DIRECTORY_FILE must fail with
	 * STATUS_NOT_A_DIRECTORY.
	 */
	if (stream_name || s_type == DATA_STREAM) {
		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
			if (s_type == DATA_STREAM) {
				rc = -EIO;
				rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
			}
		} else {
			if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
			    !stream_name && s_type == DATA_STREAM) {
				rc = -EIO;
				rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
			}
		}

		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
		    req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
			rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
			rc = -EIO;
		}

		if (rc < 0)
			goto err_out;
	}

	if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
	    S_ISDIR(d_inode(path.dentry)->i_mode) &&
	    !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
		ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
			    name, req->CreateOptions);
		rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
		rc = -EIO;
		goto err_out;
	}

	if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
	    !(req->CreateDisposition == FILE_CREATE_LE) &&
	    !S_ISDIR(d_inode(path.dentry)->i_mode)) {
		rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
		rc = -EIO;
		goto err_out;
	}

	if (!stream_name && file_present &&
	    req->CreateDisposition == FILE_CREATE_LE) {
		rc = -EEXIST;
		goto err_out;
	}

	daccess = smb_map_generic_desired_access(req->DesiredAccess);

	if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
		rc = smb_check_perm_dacl(conn, &path, &daccess,
					 req->DesiredAccess,
					 sess->user->uid,
					 ksmbd_user_authenticated(sess->user), false);
		if (rc)
			goto err_out;

		if (maximal_access_ctxt) {
			maximal_access = FILE_MAXIMAL_ACCESS_LE;
			rc = smb_check_perm_dacl(conn, &path, &maximal_access,
						 0, sess->user->uid,
						 ksmbd_user_authenticated(sess->user),
						 false);
			if (rc)
				goto err_out;

			/*
			 * smb_check_perm_dacl() returns success without
			 * touching *pdaccess when the object has no stored
			 * NT ACL, leaving maximal_access as the
			 * FILE_MAXIMAL_ACCESS_LE request sentinel instead of
			 * a real access mask.
			 */
			if (maximal_access == FILE_MAXIMAL_ACCESS_LE)
				ksmbd_vfs_query_maximal_access(idmap, path.dentry,
							       &maximal_access);
		}
	}

	if (daccess & FILE_MAXIMAL_ACCESS_LE) {
		if (!file_present) {
			daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
		} else {
			ksmbd_vfs_query_maximal_access(idmap,
							    path.dentry,
							    &daccess);
			already_permitted = true;
		}
		maximal_access = daccess;
	}

	/* MAXIMUM_ALLOWED may not have granted the requested DELETE */
	if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE &&
	    !(daccess & FILE_DELETE_LE)) {
		rc = -EACCES;
		goto err_out;
	}

	open_flags = smb2_create_open_flags(file_present, daccess,
					    req->CreateDisposition,
					    &may_flags,
					    req->CreateOptions,
					    file_present ? d_inode(path.dentry)->i_mode : 0);
	if (posix_ctxt && (req->DesiredAccess & FILE_APPEND_DATA_LE) &&
	    !(req->DesiredAccess & FILE_WRITE_DATA_LE))
		open_flags |= O_APPEND;

	if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
		if (open_flags & (O_CREAT | O_TRUNC)) {
			ksmbd_debug(SMB,
				    "User does not have write permission\n");
			rc = -EACCES;
			goto err_out;
		}
	}

	/*create file if not present */
	if (!file_present) {
		rc = smb2_creat(work, &path, name, open_flags,
				posix_ctxt ? posix_mode : (umode_t)-1,
				req->CreateOptions & FILE_DIRECTORY_FILE_LE);
		if (rc) {
			if (rc == -ENOENT) {
				rc = -EIO;
				rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
			}
			goto err_out;
		}

		created = true;
		idmap = mnt_idmap(path.mnt);
		if (ea_buf) {
			if (le32_to_cpu(ea_buf->ccontext.DataLength) <
			    sizeof(struct smb2_ea_info)) {
				rc = -EINVAL;
				goto err_out;
			}

			rc = smb2_set_ea(&ea_buf->ea,
					 le32_to_cpu(ea_buf->ccontext.DataLength),
					 &path, false);
			if (rc == -EOPNOTSUPP)
				rc = 0;
			else if (rc)
				goto err_out;
		}
	} else if (!already_permitted) {
		/* FILE_READ_ATTRIBUTE is allowed without inode_permission,
		 * because execute(search) permission on a parent directory,
		 * is already granted.
		 */
		if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
			rc = inode_permission(idmap,
					      d_inode(path.dentry),
					      may_flags);
			if (rc)
				goto err_out;

			if ((daccess & FILE_DELETE_LE) ||
			    (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
				struct dentry *parent = dget_parent(path.dentry);
				struct inode *parent_inode = d_inode(parent);

				if (parent_inode)
					rc = inode_permission(idmap, parent_inode,
							      MAY_EXEC | MAY_WRITE);
				else
					rc = -ENOENT;
				dput(parent);
				if (rc)
					goto err_out;
			}
		}
	}

	{
		struct dentry *parent = dget_parent(path.dentry);

		if (!d_inode(parent)) {
			dput(parent);
			rc = -ENOENT;
			goto err_out;
		}
		rc = ksmbd_query_inode_status(parent);
		dput(parent);
	}
	if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
		rc = -EBUSY;
		goto err_out;
	}

	rc = 0;
	filp = dentry_open(&path, open_flags, current_cred());
	if (IS_ERR(filp)) {
		rc = PTR_ERR(filp);
		pr_err("dentry open for dir failed, rc %d\n", rc);
		goto err_out;
	}

	if (file_present) {
		if (!(open_flags & O_TRUNC))
			file_info = FILE_OPENED;
		else
			file_info = FILE_OVERWRITTEN;

		if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
		    FILE_SUPERSEDE_LE)
			file_info = FILE_SUPERSEDED;
	} else if (open_flags & O_CREAT) {
		file_info = FILE_CREATED;
	}

	ksmbd_vfs_set_fadvise(filp, req->CreateOptions);

	/* Obtain Volatile-ID */
	fp = ksmbd_open_fd(work, filp);
	if (IS_ERR(fp)) {
		fput(filp);
		rc = PTR_ERR(fp);
		if (rc == -ENOTCONN)
			rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
		fp = NULL;
		goto err_out;
	}

	/* Get Persistent-ID */
	ksmbd_open_durable_fd(fp);
	if (!has_file_id(fp->persistent_id)) {
		rc = -ENOMEM;
		goto err_out;
	}

	/*
	 * Publish the client and create GUID before an oplock/lease break can
	 * make this CREATE pending.  A replay of that in-flight CREATE must find
	 * this FP_NEW handle and fail with STATUS_FILE_NOT_AVAILABLE instead of
	 * waiting on the same break again.
	 */
	memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
	if (dh_info.app_instance_id) {
		memcpy(fp->app_instance_id, dh_info.AppInstanceId,
		       SMB2_CREATE_GUID_SIZE);
		fp->has_app_instance_id = true;
	}
	if (dh_info.app_instance_version_valid) {
		fp->app_instance_version_high =
			dh_info.app_instance_version_high;
		fp->app_instance_version_low = dh_info.app_instance_version_low;
		fp->app_instance_version_valid = true;
	}
	if (dh_info.CreateGuid) {
		memcpy(fp->create_guid, dh_info.CreateGuid, SMB2_CREATE_GUID_SIZE);
		fp->durable_replay_consumed = dh_info.replay_consumed;
		rc = ksmbd_vfs_set_durable_owner(fp, sess->user);
		if (rc)
			goto err_out;
	}

	fp->cdoption = req->CreateDisposition;
	fp->create_file_attributes = req->FileAttributes;
	fp->daccess = daccess;
	fp->saccess = req->ShareAccess;
	fp->coption = req->CreateOptions;

	/* Set default windows and posix acls if creating new file */
	if (created) {
		int posix_acl_rc;
		struct inode *inode = d_inode(path.dentry);
		struct inode *parent_inode;
		struct dentry *parent;

		parent = dget_parent(path.dentry);
		parent_inode = d_inode(parent);
		if (parent_inode)
			posix_acl_rc = ksmbd_vfs_inherit_posix_acl(idmap, &path,
								   parent_inode);
		else
			posix_acl_rc = -ENOENT;
		dput(parent);
		if (posix_acl_rc)
			ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);

		rc = smb2_create_sd_buffer(work, req, &path);
		if (rc && rc != -ENOENT)
			goto err_out;

		if (rc == -ENOENT) {
			if (test_share_config_flag(work->tcon->share_conf,
						   KSMBD_SHARE_FLAG_ACL_XATTR)) {
				rc = smb_inherit_dacl(conn, &path, sess->user->uid,
						      sess->user->gid);
			}
			if (rc) {
				if (posix_acl_rc)
					ksmbd_vfs_set_init_posix_acl(idmap,
								     &path);

				if (test_share_config_flag(work->tcon->share_conf,
							   KSMBD_SHARE_FLAG_ACL_XATTR)) {
					struct smb_fattr fattr;
					struct smb_ntsd *pntsd;
					int pntsd_size;
					size_t scratch_len;

					rc = ksmbd_acls_fattr(&fattr, idmap, inode);
					if (rc)
						goto err_out;

					scratch_len = smb_acl_sec_desc_scratch_len(&fattr,
							NULL, 0,
							OWNER_SECINFO | GROUP_SECINFO |
							DACL_SECINFO);
					if (!scratch_len || scratch_len == SIZE_MAX) {
						rc = -EFBIG;
						posix_acl_release(fattr.cf_acls);
						posix_acl_release(fattr.cf_dacls);
						goto err_out;
					}

					pntsd = kvzalloc(scratch_len, KSMBD_DEFAULT_GFP);
					if (!pntsd) {
						rc = -ENOMEM;
						posix_acl_release(fattr.cf_acls);
						posix_acl_release(fattr.cf_dacls);
						goto err_out;
					}

					rc = build_sec_desc(idmap,
							    pntsd, NULL, 0,
							    OWNER_SECINFO |
							    GROUP_SECINFO |
							    DACL_SECINFO,
							    &pntsd_size, &fattr);
					posix_acl_release(fattr.cf_acls);
					posix_acl_release(fattr.cf_dacls);
					if (rc) {
						kvfree(pntsd);
						goto err_out;
					}

					rc = ksmbd_vfs_set_sd_xattr(conn,
								    idmap,
								    &path,
								    pntsd,
								    pntsd_size,
								    false);
					kvfree(pntsd);
					if (rc)
						pr_err("failed to store ntacl in xattr : %d\n",
						       rc);
				}
			}
		}
		rc = 0;
	}

	if (stream_name) {
		rc = smb2_set_stream_name_xattr(&path,
						fp,
						stream_name,
						s_type,
						&stream_created);
		if (rc)
			goto err_out;
		file_info = FILE_CREATED;
	}

	fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
			FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
	need_truncate = !S_ISDIR(file_inode(filp)->i_mode) &&
			open_flags & O_TRUNC && !fp->attrib_only && !stream_name;
	/*
	 * Count the FILE_WRITE_DATA that MS-FSA 2.1.5.1.2 grants an overwrite,
	 * supersede included, or a new named stream on an existing file.
	 * An attribute-only open of the file is not truncated, and the
	 * synthesized AFP_AfpInfo stream is not created by the client.
	 */
	fp->implied_write = need_truncate ||
			    (stream_name &&
			     (open_flags & O_TRUNC ||
			      (file_present && stream_created)));

	fp->is_posix_ctxt = posix_ctxt;
	fp->posix_append = posix_ctxt && !!(open_flags & O_APPEND);

	/* fp should be searchable through ksmbd_inode.m_fp_list
	 * after daccess, saccess, attrib_only, implied_write, and
	 * stream are initialized.
	 */
	down_write(&fp->f_ci->m_lock);
	list_add(&fp->node, &fp->f_ci->m_fp_list);
	up_write(&fp->f_ci->m_lock);

	/* Check delete pending among previous fp before oplock break */
	if (ksmbd_inode_pending_delete(fp)) {
		rc = -EBUSY;
		goto err_out;
	}

	if (!stream_name && daccess & FILE_DELETE_LE &&
	    ksmbd_has_stream_without_delete_share(fp)) {
		rc = -EPERM;
		goto err_out;
	}

	if (file_present || created)
		path_put(&path);

	if (need_truncate)
		smb_break_all_oplock(work, fp);

	share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
	if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
	    (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
	     !(conn->vals->req_capabilities & SMB2_GLOBAL_CAP_LEASING))) {
		if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
			rc = share_ret;
			goto err_out1;
		}
	} else {
		if (created && !lc)
			smb_send_parent_lease_break_noti(fp, NULL);

		if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE && lc) {
			if (S_ISDIR(file_inode(filp)->i_mode)) {
				lc->req_state &= ~SMB2_LEASE_WRITE_CACHING_LE;
				lc->is_dir = true;
			}

			/*
			 * Compare parent lease using parent key. If there is no
			 * a lease that has same parent key, Send lease break
			 * notification.
			 */
			smb_send_parent_lease_break_noti(fp, lc);

			req_op_level = smb2_map_lease_to_oplock(lc->req_state);
			ksmbd_debug(SMB,
				    "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
				    name, req_op_level, lc->req_state);
			rc = find_same_lease_key(conn, fp->f_ci, lc);
			if (rc)
				goto err_out1;
		} else if (open_flags == O_RDONLY &&
			   (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
			    req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
			req_op_level = SMB2_OPLOCK_LEVEL_II;

		rc = smb_grant_oplock(work, req_op_level,
				      fp->persistent_id, fp,
				      le32_to_cpu(req->hdr.Id.SyncId.TreeId),
				      lc, share_ret,
				      smb3_hdr_replay(&req->hdr));
		if (rc < 0)
			goto err_out1;
	}

	if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
		smb_break_all_levII_oplock_for_delete(work, fp);
		ksmbd_fd_set_delete_on_close(fp, file_info);
	}

	if (need_truncate) {
		rc = smb2_create_truncate(&fp->filp->f_path);
		if (rc)
			goto err_out1;
	}

	if (req->CreateContextsOffset) {
		struct create_alloc_size_req *az_req;

		az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
					SMB2_CREATE_ALLOCATION_SIZE, 4);
		if (IS_ERR(az_req)) {
			rc = PTR_ERR(az_req);
			goto err_out1;
		} else if (az_req) {
			int err;

			if (le16_to_cpu(az_req->ccontext.DataOffset) +
			    le32_to_cpu(az_req->ccontext.DataLength) <
			    sizeof(struct create_alloc_size_req)) {
				rc = -EINVAL;
				goto err_out1;
			}
			alloc_size = le64_to_cpu(az_req->AllocationSize);
			fp->allocation_size_set = true;
			ksmbd_debug(SMB,
				    "request smb2 create allocate size : %llu\n",
				    alloc_size);
			/*
			 * fp->filp is the base file's data fork for a stream
			 * handle (streams are xattr-backed on the same
			 * underlying file) -- fallocate has no meaning for a
			 * stream and would otherwise pre-allocate storage on
			 * the base file's data instead.
			 */
			if (!ksmbd_stream_fd(fp)) {
				smb_break_all_levII_oplock(work, fp, 1);
				err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
						    alloc_size);
				if (err < 0)
					ksmbd_debug(SMB,
						    "vfs_fallocate is failed : %d\n",
						    err);
			}
		}

		context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID, 4);
		if (IS_ERR(context)) {
			rc = PTR_ERR(context);
			goto err_out1;
		} else if (context) {
			ksmbd_debug(SMB, "get query on disk id context\n");
			query_disk_id = 1;
		}

		if (test_share_config_flag(share, KSMBD_SHARE_FLAG_TIME_MACHINE)) {
			context = smb2_find_context_vals(req, SMB2_CREATE_AAPL, 4);
			if (IS_ERR(context)) {
				rc = PTR_ERR(context);
				goto err_out1;
			} else if (context) {
				struct aapl_server_query_req *aapl_req;

				if (le32_to_cpu(context->DataLength) <
				    sizeof(struct aapl_server_query_req)) {
					rc = -EINVAL;
					goto err_out1;
				}

				aapl_req = (struct aapl_server_query_req *)
					((char *)context +
					 le16_to_cpu(context->DataOffset));
				if (le32_to_cpu(aapl_req->cmd) ==
				    SMB2_CRTCTX_AAPL_SERVER_QUERY) {
					conn->is_aapl = true;
					aapl_ctxt = true;
					aapl_req_bitmap = le64_to_cpu(aapl_req->req_bitmap);
					aapl_client_caps = le64_to_cpu(aapl_req->client_caps);
				}
			}
		} else if (conn->is_aapl == false) {
			context = smb2_find_context_vals(req, SMB2_CREATE_AAPL, 4);
			if (IS_ERR(context)) {
				rc = PTR_ERR(context);
				goto err_out1;
			} else if (context)
				conn->is_aapl = true;
		}
	}

	rc = ksmbd_vfs_getattr(&path, &stat);
	if (rc)
		goto err_out1;

	if (stat.result_mask & STATX_BTIME)
		fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
	else
		fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
	fp->change_time = ksmbd_UnixTimeToNT(stat.ctime);
	fp->allocation_size = S_ISDIR(stat.mode) ? 0 :
		(alloc_size ?: stat.blocks << 9);
	if (created || fp->f_ci->m_fattr == 0)
		fp->f_ci->m_fattr =
			cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));

	if (!created)
		smb2_update_xattrs(tcon, &path, fp);
	if (need_truncate && req->FileAttributes) {
		dos_attr = le32_to_cpu(req->FileAttributes);
		fp->f_ci->m_fattr =
			cpu_to_le32(smb2_get_dos_mode(&stat, dos_attr));
		smb2_new_xattrs(tcon, &path, fp);
	}

	ksmbd_vfs_update_compressed_fattr(path.dentry, &fp->f_ci->m_fattr);

	if (created) {
		if (fp->coption & FILE_NO_COMPRESSION_LE) {
			rc = ksmbd_vfs_set_compression_create(work, fp,
							      COMPRESSION_FORMAT_NONE);
			if (rc)
				fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_COMPRESSED_LE;
			rc = 0;
		} else if (smb2_parent_compressed(tcon, &path)) {
			rc = ksmbd_vfs_set_compression_create(work, fp,
							      COMPRESSION_FORMAT_LZNT1);
			if (rc)
				fp->f_ci->m_fattr |= FILE_ATTRIBUTE_COMPRESSED_LE;
			rc = 0;
		}
	}

	if (created)
		smb2_new_xattrs(tcon, &path, fp);

	fp->create_action = cpu_to_le32(file_info);

	if (dh_info.type == DURABLE_REQ_V2 || dh_info.type == DURABLE_REQ) {
		if (dh_info.type == DURABLE_REQ_V2 && dh_info.persistent &&
		    test_share_config_flag(work->tcon->share_conf,
					   KSMBD_SHARE_FLAG_CONTINUOUS_AVAILABILITY) &&
		    (conn->vals->req_capabilities &
			     SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)) {
			/* MS-SMB2 3.3.5.9.10: a persistent open is durable too. */
			fp->is_durable = true;
			fp->is_persistent = true;
		} else {
			fp->is_durable = true;
		}
		if (dh_info.type == DURABLE_REQ_V2) {
			if (dh_info.app_instance_id)
				memcpy(fp->app_instance_id,
				       dh_info.AppInstanceId,
				       SMB2_CREATE_GUID_SIZE);
			if (dh_info.timeout)
				fp->durable_timeout =
					min_t(unsigned int, dh_info.timeout,
					      DURABLE_HANDLE_MAX_TIMEOUT);
			else
				fp->durable_timeout = 60000;
		}
	}

	/*
	 * conn->is_aapl detection above (this function's create-context
	 * parsing) is skipped on the reconnect path below, since a
	 * reconnect always arrives on a fresh connection -- if the client
	 * cares, it sends its own AAPL context on this same CREATE, which
	 * this function's normal (non-reconnect) parsing already handles.
	 */
	reconnected_fp:
	if (dh_info.replay)
		file_info = le32_to_cpu(fp->create_action);
	rsp->StructureSize = cpu_to_le16(89);
	opinfo = opinfo_get(fp);
	rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
	/*
	 * A durable CREATE replay does not modify the existing open. When
	 * replayed without an oplock, however, its response reflects that
	 * request and cannot include a new durable-handle response context.
	 */
	if (dh_info.replay && !lc &&
	    req_op_level == SMB2_OPLOCK_LEVEL_NONE) {
		rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
		durable_rsp = false;
	}
	rsp->Flags = 0;
	rsp->CreateAction = cpu_to_le32(file_info);
	rsp->CreationTime = cpu_to_le64(fp->create_time);
	time = ksmbd_UnixTimeToNT(stat.atime);
	rsp->LastAccessTime = cpu_to_le64(time);
	time = ksmbd_UnixTimeToNT(stat.mtime);
	fp->open_mtime = time;
	rsp->LastWriteTime = cpu_to_le64(time);
	rsp->ChangeTime = cpu_to_le64(fp->change_time);
	/*
	 * The cached allocation size hides filesystem rounding for the
	 * requested allocation, but it can go stale when the file grows past
	 * it via writes (e.g. across a durable reconnect). Refresh it once the
	 * file exceeds the cached value, rounding the end of file up to the
	 * volume allocation unit (the filesystem block size, matching the
	 * SectorsPerAllocationUnit/BytesPerSector ksmbd advertises) rather than
	 * using the raw on-disk block count, which can include filesystem
	 * preallocation and metadata rounding.
	 */
	if (ksmbd_stream_fd(fp)) {
		loff_t seof = ksmbd_stream_eof(fp);

		rsp->AllocationSize = cpu_to_le64((u64)seof);
		rsp->EndofFile = cpu_to_le64((u64)seof);
	} else {
		if (!S_ISDIR(stat.mode) && stat.size > fp->allocation_size)
			fp->allocation_size = round_up(stat.size, stat.blksize);
		rsp->AllocationSize = cpu_to_le64(fp->allocation_size);
		rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
	}
	rsp->FileAttributes = fp->f_ci->m_fattr;

	rsp->Reserved2 = 0;

	rsp->PersistentFileId = fp->persistent_id;
	rsp->VolatileFileId = fp->volatile_id;

	rsp->CreateContextsOffset = 0;
	rsp->CreateContextsLength = 0;
	iov_len = offsetof(struct smb2_create_rsp, Buffer);

	/* If lease is request send lease context response */
	if (opinfo && opinfo->is_lease) {
		struct create_context *lease_ccontext;

		ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
			    name, opinfo->o_lease->state);
		rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;

		lease_ccontext = (struct create_context *)rsp->Buffer;
		contxt_cnt++;
		create_lease_buf(rsp->Buffer, opinfo->o_lease);
		le32_add_cpu(&rsp->CreateContextsLength,
			     conn->vals->create_lease_size);
		iov_len += conn->vals->create_lease_size;
		next_ptr = &lease_ccontext->Next;
		next_off = conn->vals->create_lease_size;
	}
	opinfo_put(opinfo);

	if (maximal_access_ctxt) {
		struct create_context *mxac_ccontext;

		if (maximal_access == 0)
			ksmbd_vfs_query_maximal_access(idmap,
						       path.dentry,
						       &maximal_access);
		mxac_ccontext = (struct create_context *)(rsp->Buffer +
				le32_to_cpu(rsp->CreateContextsLength));
		contxt_cnt++;
		create_mxac_rsp_buf(rsp->Buffer +
				le32_to_cpu(rsp->CreateContextsLength),
				le32_to_cpu(maximal_access));
		le32_add_cpu(&rsp->CreateContextsLength,
			     conn->vals->create_mxac_size);
		iov_len += conn->vals->create_mxac_size;
		if (next_ptr)
			*next_ptr = cpu_to_le32(next_off);
		next_ptr = &mxac_ccontext->Next;
		next_off = conn->vals->create_mxac_size;
	}

	if (query_disk_id) {
		struct create_context *disk_id_ccontext;

		disk_id_ccontext = (struct create_context *)(rsp->Buffer +
				le32_to_cpu(rsp->CreateContextsLength));
		contxt_cnt++;
		create_disk_id_rsp_buf(rsp->Buffer +
				le32_to_cpu(rsp->CreateContextsLength),
				stat.ino, tcon->id);
		le32_add_cpu(&rsp->CreateContextsLength,
			     conn->vals->create_disk_id_size);
		iov_len += conn->vals->create_disk_id_size;
		if (next_ptr)
			*next_ptr = cpu_to_le32(next_off);
		next_ptr = &disk_id_ccontext->Next;
		next_off = conn->vals->create_disk_id_size;
	}

	if (durable_rsp &&
	    (dh_info.type == DURABLE_REQ || dh_info.type == DURABLE_REQ_V2)) {
		struct create_context *durable_ccontext;

		durable_ccontext = (struct create_context *)(rsp->Buffer +
				le32_to_cpu(rsp->CreateContextsLength));
		contxt_cnt++;
		if (dh_info.type == DURABLE_REQ) {
			create_durable_rsp_buf(rsp->Buffer +
					le32_to_cpu(rsp->CreateContextsLength));
			le32_add_cpu(&rsp->CreateContextsLength,
					conn->vals->create_durable_size);
			iov_len += conn->vals->create_durable_size;
		} else {
			create_durable_v2_rsp_buf(rsp->Buffer +
					le32_to_cpu(rsp->CreateContextsLength),
					fp);
			le32_add_cpu(&rsp->CreateContextsLength,
					conn->vals->create_durable_v2_size);
			iov_len += conn->vals->create_durable_v2_size;
		}

		if (next_ptr)
			*next_ptr = cpu_to_le32(next_off);
		next_ptr = &durable_ccontext->Next;
		next_off = dh_info.type == DURABLE_REQ ?
			conn->vals->create_durable_size :
			conn->vals->create_durable_v2_size;
	}

	if (posix_ctxt) {
		struct create_context *posix_ccontext;

		posix_ccontext = (struct create_context *)(rsp->Buffer +
				le32_to_cpu(rsp->CreateContextsLength));
		contxt_cnt++;
		create_posix_rsp_buf(rsp->Buffer +
				le32_to_cpu(rsp->CreateContextsLength),
				fp);
		le32_add_cpu(&rsp->CreateContextsLength,
			     conn->vals->create_posix_size);
		iov_len += conn->vals->create_posix_size;
		if (next_ptr)
			*next_ptr = cpu_to_le32(next_off);
		next_ptr = &posix_ccontext->Next;
		next_off = conn->vals->create_posix_size;
	}

	/*
	 * AAPL create context response: see smb2pdu.h for the capability
	 * rationale. Scoped to TIME_MACHINE shares only.
	 */
	if (aapl_ctxt) {
		if (aapl_client_caps & SMB2_CRTCTX_AAPL_SUPPORTS_READ_DIR_ATTR)
			conn->aapl_readdir_attr = true;
		/*
		 * V2 extends the same inline-FinderInfo mechanism (see
		 * smb2pdu.h), so a V2-requesting client also gets
		 * aapl_readdir_attr treatment -- the reply just advertises
		 * the V2 bit instead of the V1 one (create_aapl_rsp_buf).
		 */
		if (aapl_client_caps & SMB2_CRTCTX_AAPL_SUPPORTS_READ_DIR_ATTR_V2) {
			conn->aapl_readdir_attr = true;
			conn->aapl_readdir_attr_v2 = true;
		}

		contxt_cnt++;
		create_aapl_rsp_buf(rsp->Buffer +
				le32_to_cpu(rsp->CreateContextsLength),
				SMB2_CRTCTX_AAPL_FULL_SYNC,
				aapl_req_bitmap,
				conn->aapl_readdir_attr_v2);
		le32_add_cpu(&rsp->CreateContextsLength,
			     conn->vals->create_aapl_size);
		iov_len += conn->vals->create_aapl_size;
		if (next_ptr)
			*next_ptr = cpu_to_le32(next_off);
		/* AAPL is last; next_ptr need not be updated */
	}

	if (contxt_cnt > 0) {
		rsp->CreateContextsOffset =
			cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
	}

err_out:
	if (rc && (file_present || created))
		path_put(&path);

err_out1:
	ksmbd_revert_fsids(work);

err_out2:
	if (!rc) {
		if (!dh_info.replay) {
			smb2_complete_request_open(work);
			rc = ksmbd_update_fstate(&work->sess->file_table, fp,
						 FP_INITED);
			if (rc == -ENOENT)
				rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
			if (!rc) {
				work->request_open = fp;
				work->request_open_chseq =
					smb3_hdr_channel_sequence(&req->hdr);
			}
		} else {
			rc = smb2_set_request_open(work, fp, &req->hdr, false, false);
		}
		if (!rc)
			rc = ksmbd_iov_pin_rsp(work, (void *)rsp, iov_len);
	}
	if (rc) {
		if (rc == -EINVAL)
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		else if (rc == -EBADMSG)
			rsp->hdr.Status = STATUS_EA_LIST_INCONSISTENT;
		else if (rc == -EOPNOTSUPP)
			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
		else if ((rc == -EACCES || rc == -ESTALE || rc == -EXDEV) &&
			 !rsp->hdr.Status) {
			if (req->DesiredAccess & FILE_ACCESS_SYSTEM_SECURITY_LE)
				rsp->hdr.Status = STATUS_PRIVILEGE_NOT_HELD;
			else
				rsp->hdr.Status = STATUS_ACCESS_DENIED;
		} else if (rc == -ENOENT && !rsp->hdr.Status)
			rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
		else if (rc == -EPERM)
			rsp->hdr.Status = STATUS_SHARING_VIOLATION;
		else if (rc == -EBUSY)
			rsp->hdr.Status = STATUS_DELETE_PENDING;
		else if (rc == -EBADF)
			rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
		else if (rc == -ENOEXEC)
			rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
		else if (rc == -ENXIO)
			rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
		else if (rc == -EEXIST)
			rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
		else if (rc == -EMFILE)
			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
		else if (rc == -EINPROGRESS)
			rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE;
		else if (rc == -EAGAIN)
			rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE;
		if (!rsp->hdr.Status)
			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;

		if (fp && !dh_info.replay) {
			if (work->request_open == fp) {
				ksmbd_close_fd(work, fp->volatile_id);
				smb2_complete_request_open(work);
			} else {
				if (dh_info.reconnected && fp == dh_info.fp)
					ksmbd_unpublish_reopened_fd(work, fp);
				ksmbd_fd_put(work, fp);
			}
		}
		smb2_set_err_rsp(work);
		ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
	}

	if (dh_info.replay)
		ksmbd_put_durable_fd(dh_info.fp);

	if (dh_info.reconnected) {
		/*
		 * If reconnect succeeded, fp was republished in the
		 * session file table, and the error path above has
		 * already removed its volatile id.  Drop the durable
		 * lookup reference through the same session-aware path.
		 */
		if (rc && fp == dh_info.fp)
			ksmbd_fd_put(work, dh_info.fp);
		else
			ksmbd_put_durable_fd(dh_info.fp);
	}

	kfree(name);
	kfree(lc);

	return rc;
}

static int readdir_info_level_struct_sz(int info_level)
{
	switch (info_level) {
	case FILE_FULL_DIRECTORY_INFORMATION:
		return sizeof(FILE_FULL_DIRECTORY_INFO);
	case FILE_BOTH_DIRECTORY_INFORMATION:
		return sizeof(FILE_BOTH_DIRECTORY_INFO);
	case FILE_DIRECTORY_INFORMATION:
		return sizeof(FILE_DIRECTORY_INFO);
	case FILE_NAMES_INFORMATION:
		return sizeof(struct file_names_info);
	case FILEID_FULL_DIRECTORY_INFORMATION:
		return sizeof(FILE_ID_FULL_DIR_INFO);
	case FILEID_BOTH_DIRECTORY_INFORMATION:
		return sizeof(struct file_id_both_directory_info);
	case FILE_ID_EXTD_DIRECTORY_INFORMATION:
		return sizeof(struct file_id_extd_directory_info);
	case FileId64ExtdDirectoryInformation:
		return sizeof(struct file_id_64_extd_directory_info);
	case FileId64ExtdBothDirectoryInformation:
		return sizeof(struct file_id_64_extd_both_directory_info);
	case FileIdAllExtdDirectoryInformation:
		return sizeof(struct file_id_all_extd_directory_info);
	case FileIdAllExtdBothDirectoryInformation:
		return sizeof(struct file_id_all_extd_both_directory_info);
	case SMB_FIND_FILE_POSIX_INFO:
		return sizeof(struct smb2_posix_info);
	default:
		return -EOPNOTSUPP;
	}
}

static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
{
	switch (info_level) {
	case FILE_FULL_DIRECTORY_INFORMATION:
	{
		FILE_FULL_DIRECTORY_INFO *ffdinfo;

		ffdinfo = (FILE_FULL_DIRECTORY_INFO *)d_info->rptr;
		d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
		d_info->name = ffdinfo->FileName;
		d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
		return 0;
	}
	case FILE_BOTH_DIRECTORY_INFORMATION:
	{
		FILE_BOTH_DIRECTORY_INFO *fbdinfo;

		fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)d_info->rptr;
		d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
		d_info->name = fbdinfo->FileName;
		d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
		return 0;
	}
	case FILE_DIRECTORY_INFORMATION:
	{
		FILE_DIRECTORY_INFO *fdinfo;

		fdinfo = (FILE_DIRECTORY_INFO *)d_info->rptr;
		d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
		d_info->name = fdinfo->FileName;
		d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
		return 0;
	}
	case FILE_NAMES_INFORMATION:
	{
		struct file_names_info *fninfo;

		fninfo = (struct file_names_info *)d_info->rptr;
		d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
		d_info->name = fninfo->FileName;
		d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
		return 0;
	}
	case FILEID_FULL_DIRECTORY_INFORMATION:
	{
		FILE_ID_FULL_DIR_INFO *dinfo;

		dinfo = (FILE_ID_FULL_DIR_INFO *)d_info->rptr;
		d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
		d_info->name = dinfo->FileName;
		d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
		return 0;
	}
	case FILEID_BOTH_DIRECTORY_INFORMATION:
	{
		struct file_id_both_directory_info *fibdinfo;

		fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
		d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
		d_info->name = fibdinfo->FileName;
		d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
		return 0;
	}
	case FILE_ID_EXTD_DIRECTORY_INFORMATION:
	{
		struct file_id_extd_directory_info *info;

		info = (struct file_id_extd_directory_info *)d_info->rptr;
		d_info->rptr += le32_to_cpu(info->NextEntryOffset);
		d_info->name = info->FileName;
		d_info->name_len = le32_to_cpu(info->FileNameLength);
		return 0;
	}
	case FileId64ExtdDirectoryInformation:
	{
		struct file_id_64_extd_directory_info *info;

		info = (struct file_id_64_extd_directory_info *)d_info->rptr;
		d_info->rptr += le32_to_cpu(info->NextEntryOffset);
		d_info->name = info->FileName;
		d_info->name_len = le32_to_cpu(info->FileNameLength);
		return 0;
	}
	case FileId64ExtdBothDirectoryInformation:
	{
		struct file_id_64_extd_both_directory_info *info;

		info = (struct file_id_64_extd_both_directory_info *)d_info->rptr;
		d_info->rptr += le32_to_cpu(info->NextEntryOffset);
		d_info->name = info->FileName;
		d_info->name_len = le32_to_cpu(info->FileNameLength);
		return 0;
	}
	case FileIdAllExtdDirectoryInformation:
	{
		struct file_id_all_extd_directory_info *info;

		info = (struct file_id_all_extd_directory_info *)d_info->rptr;
		d_info->rptr += le32_to_cpu(info->NextEntryOffset);
		d_info->name = info->FileName;
		d_info->name_len = le32_to_cpu(info->FileNameLength);
		return 0;
	}
	case FileIdAllExtdBothDirectoryInformation:
	{
		struct file_id_all_extd_both_directory_info *info;

		info = (struct file_id_all_extd_both_directory_info *)d_info->rptr;
		d_info->rptr += le32_to_cpu(info->NextEntryOffset);
		d_info->name = info->FileName;
		d_info->name_len = le32_to_cpu(info->FileNameLength);
		return 0;
	}
	case SMB_FIND_FILE_POSIX_INFO:
	{
		struct smb2_posix_info *posix_info;

		posix_info = (struct smb2_posix_info *)d_info->rptr;
		d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
		d_info->name = posix_info->name;
		d_info->name_len = le32_to_cpu(posix_info->name_len);
		return 0;
	}
	default:
		return -EINVAL;
	}
}

/**
 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
 * buffer
 * @conn:	connection instance
 * @info_level:	smb information level
 * @d_info:	structure included variables for query dir
 * @ksmbd_kstat:	ksmbd wrapper of dirent stat information
 *
 * if directory has many entries, find first can't read it fully.
 * find next might be called multiple times to read remaining dir entries
 *
 * Return:	0 on success, otherwise error
 */
static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
				       struct ksmbd_dir_info *d_info,
				       struct ksmbd_kstat *ksmbd_kstat)
{
	int next_entry_offset = 0;
	char *conv_name;
	int conv_len;
	void *kstat;
	int struct_sz, rc = 0;

	conv_name = ksmbd_convert_dir_info_name(d_info,
						conn->local_nls,
						&conv_len);
	if (!conv_name)
		return -ENOMEM;

	/* Somehow the name has only terminating NULL bytes */
	if (conv_len < 0) {
		rc = -EINVAL;
		goto free_conv_name;
	}

	struct_sz = readdir_info_level_struct_sz(info_level);
	if (struct_sz == -EOPNOTSUPP) {
		rc = -EINVAL;
		goto free_conv_name;
	}

	struct_sz += conv_len;
	next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
	d_info->last_entry_off_align = next_entry_offset - struct_sz;

	if (next_entry_offset > d_info->out_buf_len) {
		d_info->out_buf_len = 0;
		rc = -ENOSPC;
		goto free_conv_name;
	}

	kstat = d_info->wptr;
	if (info_level != FILE_NAMES_INFORMATION)
		kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);

	switch (info_level) {
	case FILE_FULL_DIRECTORY_INFORMATION:
	{
		FILE_FULL_DIRECTORY_INFO *ffdinfo;

		ffdinfo = (FILE_FULL_DIRECTORY_INFO *)kstat;
		ffdinfo->FileNameLength = cpu_to_le32(conv_len);
		ffdinfo->EaSize =
			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
		if (ffdinfo->EaSize)
			ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
		if (d_info->hide_dot_file && d_info->name[0] == '.')
			ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
		memcpy(ffdinfo->FileName, conv_name, conv_len);
		ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILE_BOTH_DIRECTORY_INFORMATION:
	{
		FILE_BOTH_DIRECTORY_INFO *fbdinfo;

		fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)kstat;
		fbdinfo->FileNameLength = cpu_to_le32(conv_len);
		fbdinfo->EaSize =
			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
		if (fbdinfo->EaSize)
			fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
		fbdinfo->ShortNameLength = 0;
		fbdinfo->Reserved = 0;
		if (d_info->hide_dot_file && d_info->name[0] == '.')
			fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
		memcpy(fbdinfo->FileName, conv_name, conv_len);
		fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILE_DIRECTORY_INFORMATION:
	{
		FILE_DIRECTORY_INFO *fdinfo;

		fdinfo = (FILE_DIRECTORY_INFO *)kstat;
		fdinfo->FileNameLength = cpu_to_le32(conv_len);
		if (d_info->hide_dot_file && d_info->name[0] == '.')
			fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
		memcpy(fdinfo->FileName, conv_name, conv_len);
		fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILE_NAMES_INFORMATION:
	{
		struct file_names_info *fninfo;

		fninfo = (struct file_names_info *)kstat;
		fninfo->FileNameLength = cpu_to_le32(conv_len);
		memcpy(fninfo->FileName, conv_name, conv_len);
		fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILEID_FULL_DIRECTORY_INFORMATION:
	{
		FILE_ID_FULL_DIR_INFO *dinfo;

		dinfo = (FILE_ID_FULL_DIR_INFO *)kstat;
		dinfo->FileNameLength = cpu_to_le32(conv_len);
		dinfo->EaSize =
			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
		if (dinfo->EaSize)
			dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
		dinfo->Reserved = 0;
		if (conn->is_aapl)
			dinfo->UniqueId = 0;
		else
			dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
		if (d_info->hide_dot_file && d_info->name[0] == '.')
			dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
		memcpy(dinfo->FileName, conv_name, conv_len);
		dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILEID_BOTH_DIRECTORY_INFORMATION:
	{
		struct file_id_both_directory_info *fibdinfo;

		fibdinfo = (struct file_id_both_directory_info *)kstat;
		fibdinfo->FileNameLength = cpu_to_le32(conv_len);
		if (conn->is_aapl)
			fibdinfo->UniqueId = 0;
		else
			fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
		fibdinfo->ShortNameLength = 0;
		fibdinfo->Reserved = 0;
		if (conn->aapl_readdir_attr) {
			/*
			 * READDIR_ATTR wire format, confirmed against reference server's
			 * reference implementation marshalling (reference implementation behavior):
			 *   EaSize           = max_access (expanded specific
			 *                      rights, simplified to "grant all")
			 *   ShortNameLength  = 24 (fixed; not 0, despite the spec)
			 *   ShortName[0..7]  = resource fork size (uint64 LE, 0 = no rfork)
			 *   ShortName[8..23] = compressed FinderInfo (type+creator+flags+
			 *                      ext_flags+date_added, 16 bytes LE; all
			 *                      zeros means type=0/creator=0, i.e. use
			 *                      the file extension for icon lookup)
			 *   Reserved2        = Unix mode bits (uint16 LE)
			 * Reparse-point tag is indicated via ExtFileAttributes, not EaSize.
			 *
			 * V2 (conn->aapl_readdir_attr_v2): ShortNameLength+Reserved
			 * are read as a single flags field instead of being ignored
			 * -- see smb2pdu.h for the wire-format confirmation and
			 * AAPL_READDIR_ATTR_V2_NO_XATTR's meaning.
			 */
			__le32 reparse_tag =
				smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);

			if (reparse_tag)
				fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
			/*
			 * FILE_GENERIC_ALL_LE (0x10000000) is the raw
			 * "generic all" meta-bit -- valid only in a
			 * client's requested access mask, for the server
			 * to expand. It has none of the specific FILE_*
			 * rights bits set (FILE_LIST_DIRECTORY, FILE_TRAVERSE,
			 * etc.), so reporting it here as max_access would make
			 * macOS's bit-by-bit access checks fail on every
			 * entry -> permanent "no entry" badges in Finder.
			 * Report the actual expanded rights instead, same
			 * as smb_map_generic_desired_access() does when
			 * translating a client's GENERIC_ALL request.
			 */
			fibdinfo->EaSize = cpu_to_le32(GENERIC_ALL_FLAGS);
			/*
			 * The spec says ShortNameLength should be 0 when
			 * there's no short name; 24 here instead matches
			 * reference implementation marshalling (reference
			 * behavior) for server-to-server wire parity.
			 * V2 repurposes it as a flags field that is
			 * interpreted; V1 doesn't. Either value is safe
			 * here, so keep 24 for parity.
			 */
			if (conn->aapl_readdir_attr_v2) {
				/*
				 * V2 repurposes this field as flags (see comment
				 * above) -- 24 is a V1-only convention that real
				 * macOS clients ignore outright, so don't reuse it
				 * here as a base value for a field V2 clients
				 * actually interpret.
				 */
				fibdinfo->ShortNameLength = 0;
				if (!ksmbd_kstat->has_ads_stream)
					fibdinfo->ShortNameLength = AAPL_READDIR_ATTR_V2_NO_XATTR;
			} else {
				fibdinfo->ShortNameLength = 24;
			}
			memset(fibdinfo->ShortName, 0, sizeof(fibdinfo->ShortName));
			fibdinfo->Reserved2 = cpu_to_le16(ksmbd_kstat->kstat->mode & 0xffff);
		} else {
			fibdinfo->EaSize =
				smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
			if (fibdinfo->EaSize)
				fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
			fibdinfo->Reserved2 = cpu_to_le16(0);
		}
		if (d_info->hide_dot_file && d_info->name[0] == '.')
			fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
		memcpy(fibdinfo->FileName, conv_name, conv_len);
		fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILE_ID_EXTD_DIRECTORY_INFORMATION:
	{
		struct file_id_extd_directory_info *info;

		info = (struct file_id_extd_directory_info *)kstat;
		info->FileNameLength = cpu_to_le32(conv_len);
		info->EaSize = 0;
		info->ReparsePointTag =
			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
		if (info->ReparsePointTag)
			info->ExtFileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT_LE;
		/* The VFS does not provide a 128-bit file ID. */
		memset(info->FileId, 0, sizeof(info->FileId));
		if (d_info->hide_dot_file && d_info->name[0] == '.')
			info->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
		memcpy(info->FileName, conv_name, conv_len);
		memset(info->FileName + conv_len, 0, d_info->last_entry_off_align);
		info->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FileId64ExtdDirectoryInformation:
	{
		struct file_id_64_extd_directory_info *info;

		info = (struct file_id_64_extd_directory_info *)kstat;
		info->FileNameLength = cpu_to_le32(conv_len);
		info->EaSize = 0;
		info->ReparsePointTag =
			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
		if (info->ReparsePointTag)
			info->ExtFileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT_LE;
		if (conn->is_aapl)
			info->FileId = 0;
		else
			info->FileId = cpu_to_le64(ksmbd_kstat->kstat->ino);
		if (d_info->hide_dot_file && d_info->name[0] == '.')
			info->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
		memcpy(info->FileName, conv_name, conv_len);
		memset(info->FileName + conv_len, 0, d_info->last_entry_off_align);
		info->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FileId64ExtdBothDirectoryInformation:
	{
		struct file_id_64_extd_both_directory_info *info;

		info = (struct file_id_64_extd_both_directory_info *)kstat;
		info->FileNameLength = cpu_to_le32(conv_len);
		info->EaSize = 0;
		info->ReparsePointTag =
			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
		if (info->ReparsePointTag)
			info->ExtFileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT_LE;
		if (conn->is_aapl)
			info->FileId = 0;
		else
			info->FileId = cpu_to_le64(ksmbd_kstat->kstat->ino);
		info->ShortNameLength = 0;
		info->Reserved1 = 0;
		memset(info->ShortName, 0, sizeof(info->ShortName));
		if (d_info->hide_dot_file && d_info->name[0] == '.')
			info->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
		memcpy(info->FileName, conv_name, conv_len);
		memset(info->FileName + conv_len, 0, d_info->last_entry_off_align);
		info->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FileIdAllExtdDirectoryInformation:
	{
		struct file_id_all_extd_directory_info *info;

		info = (struct file_id_all_extd_directory_info *)kstat;
		info->FileNameLength = cpu_to_le32(conv_len);
		info->EaSize = 0;
		info->ReparsePointTag =
			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
		if (info->ReparsePointTag)
			info->ExtFileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT_LE;
		if (conn->is_aapl)
			info->FileId = 0;
		else
			info->FileId = cpu_to_le64(ksmbd_kstat->kstat->ino);
		/* The VFS does not provide a 128-bit file ID. */
		memset(info->FileId128, 0, sizeof(info->FileId128));
		if (d_info->hide_dot_file && d_info->name[0] == '.')
			info->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
		memcpy(info->FileName, conv_name, conv_len);
		memset(info->FileName + conv_len, 0, d_info->last_entry_off_align);
		info->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FileIdAllExtdBothDirectoryInformation:
	{
		struct file_id_all_extd_both_directory_info *info;

		info = (struct file_id_all_extd_both_directory_info *)kstat;
		info->FileNameLength = cpu_to_le32(conv_len);
		info->EaSize = 0;
		info->ReparsePointTag =
			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
		if (info->ReparsePointTag)
			info->ExtFileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT_LE;
		if (conn->is_aapl)
			info->FileId = 0;
		else
			info->FileId = cpu_to_le64(ksmbd_kstat->kstat->ino);
		/* The VFS does not provide a 128-bit file ID. */
		memset(info->FileId128, 0, sizeof(info->FileId128));
		info->ShortNameLength = 0;
		info->Reserved1 = 0;
		memset(info->ShortName, 0, sizeof(info->ShortName));
		if (d_info->hide_dot_file && d_info->name[0] == '.')
			info->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
		memcpy(info->FileName, conv_name, conv_len);
		memset(info->FileName + conv_len, 0, d_info->last_entry_off_align);
		info->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case SMB_FIND_FILE_POSIX_INFO:
	{
		struct smb2_posix_info *posix_info;
		u64 time;

		posix_info = (struct smb2_posix_info *)kstat;
		posix_info->Ignored = 0;
		posix_info->Zero = 0;
		posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
		posix_info->ChangeTime = cpu_to_le64(time);
		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
		posix_info->LastAccessTime = cpu_to_le64(time);
		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
		posix_info->LastWriteTime = cpu_to_le64(time);
		posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
		posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
		posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->dev);
		posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
		posix_info->ReparseTag =
			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
		posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 07777);
		switch (ksmbd_kstat->kstat->mode & S_IFMT) {
		case S_IFDIR:
			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT);
			break;
		case S_IFLNK:
			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT);
			break;
		case S_IFCHR:
			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT);
			break;
		case S_IFBLK:
			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT);
			break;
		case S_IFIFO:
			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT);
			break;
		case S_IFSOCK:
			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
		}

		posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
		posix_info->DosAttributes =
			S_ISDIR(ksmbd_kstat->kstat->mode) ?
				FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
		if (posix_info->ReparseTag)
			posix_info->DosAttributes |= FILE_ATTRIBUTE_REPARSE_POINT_LE;
		if (d_info->hide_dot_file && d_info->name[0] == '.')
			posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
		/*
		 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
		 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
		 *		  sub_auth(4 * 1(num_subauth)) + RID(4).
		 */
		id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
			  SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
		id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
			  SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
		memcpy(posix_info->name, conv_name, conv_len);
		posix_info->name_len = cpu_to_le32(conv_len);
		posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}

	} /* switch (info_level) */

	d_info->last_entry_offset = d_info->data_count;
	d_info->data_count += next_entry_offset;
	d_info->out_buf_len -= next_entry_offset;
	d_info->wptr += next_entry_offset;

	ksmbd_debug(SMB,
		    "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
		    info_level, d_info->out_buf_len,
		    next_entry_offset, d_info->data_count);

free_conv_name:
	kfree(conv_name);
	return rc;
}

struct smb2_query_dir_private {
	struct ksmbd_work	*work;
	char			*search_pattern;
	struct ksmbd_file	*dir_fp;

	struct ksmbd_dir_info	*d_info;
	int			info_level;
};

static int process_query_dir_entries(struct smb2_query_dir_private *priv)
{
	const struct mnt_idmap	*idmap = file_mnt_idmap(priv->dir_fp->filp);
	struct kstat		kstat;
	struct ksmbd_kstat	ksmbd_kstat;
	int			rc;
	int			i;

	for (i = 0; i < priv->d_info->num_entry; i++) {
		struct dentry *dent;
		struct path path;

		if (dentry_name(priv->d_info, priv->info_level))
			return -EINVAL;

		dent = lookup_one_unlocked(idmap,
					   &QSTR_LEN(priv->d_info->name,
						     priv->d_info->name_len),
					   priv->dir_fp->filp->f_path.dentry);

		if (IS_ERR(dent)) {
			ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
				    priv->d_info->name,
				    PTR_ERR(dent));
			continue;
		}
		if (unlikely(d_is_negative(dent))) {
			dput(dent);
			ksmbd_debug(SMB, "Negative dentry `%s'\n",
				    priv->d_info->name);
			continue;
		}

		if (test_share_config_flag(priv->work->tcon->share_conf,
					   KSMBD_SHARE_FLAG_HIDE_UNREADABLE)) {
			__le32 daccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
				FILE_READ_ATTRIBUTES_LE;

			path.mnt = priv->dir_fp->filp->f_path.mnt;
			path.dentry = dent;
			rc = smb_check_perm_dacl(priv->work->conn, &path,
						 &daccess, daccess,
						 priv->work->sess->user->uid,
						 ksmbd_user_authenticated(priv->work->sess->user),
						 true);
			if (rc) {
				dput(dent);
				continue;
			}
		}

		ksmbd_kstat.kstat = &kstat;
		if (priv->info_level != FILE_NAMES_INFORMATION) {
			rc = ksmbd_vfs_fill_dentry_attrs(priv->work,
							 idmap,
							 dent,
							 &ksmbd_kstat);
			if (rc) {
				dput(dent);
				continue;
			}
		}

		rc = smb2_populate_readdir_entry(priv->work->conn,
						 priv->info_level,
						 priv->d_info,
						 &ksmbd_kstat);
		dput(dent);
		if (rc)
			return rc;
	}
	return 0;
}

static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
				   int info_level)
{
	int struct_sz;
	int conv_len;
	int next_entry_offset;

	struct_sz = readdir_info_level_struct_sz(info_level);
	if (struct_sz == -EOPNOTSUPP)
		return -EOPNOTSUPP;

	conv_len = (d_info->name_len + 1) * 2;
	next_entry_offset = ALIGN(struct_sz + conv_len,
				  KSMBD_DIR_INFO_ALIGNMENT);

	if (next_entry_offset > d_info->out_buf_len) {
		d_info->out_buf_len = 0;
		return -ENOSPC;
	}

	switch (info_level) {
	case FILE_FULL_DIRECTORY_INFORMATION:
	{
		FILE_FULL_DIRECTORY_INFO *ffdinfo;

		ffdinfo = (FILE_FULL_DIRECTORY_INFO *)d_info->wptr;
		memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
		ffdinfo->FileName[d_info->name_len] = 0x00;
		ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
		ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILE_BOTH_DIRECTORY_INFORMATION:
	{
		FILE_BOTH_DIRECTORY_INFO *fbdinfo;

		fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)d_info->wptr;
		memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
		fbdinfo->FileName[d_info->name_len] = 0x00;
		fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
		fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILE_DIRECTORY_INFORMATION:
	{
		FILE_DIRECTORY_INFO *fdinfo;

		fdinfo = (FILE_DIRECTORY_INFO *)d_info->wptr;
		memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
		fdinfo->FileName[d_info->name_len] = 0x00;
		fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
		fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILE_NAMES_INFORMATION:
	{
		struct file_names_info *fninfo;

		fninfo = (struct file_names_info *)d_info->wptr;
		memcpy(fninfo->FileName, d_info->name, d_info->name_len);
		fninfo->FileName[d_info->name_len] = 0x00;
		fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
		fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILEID_FULL_DIRECTORY_INFORMATION:
	{
		FILE_ID_FULL_DIR_INFO *dinfo;

		dinfo = (FILE_ID_FULL_DIR_INFO *)d_info->wptr;
		memcpy(dinfo->FileName, d_info->name, d_info->name_len);
		dinfo->FileName[d_info->name_len] = 0x00;
		dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
		dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILEID_BOTH_DIRECTORY_INFORMATION:
	{
		struct file_id_both_directory_info *fibdinfo;

		fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
		memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
		fibdinfo->FileName[d_info->name_len] = 0x00;
		fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
		fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILE_ID_EXTD_DIRECTORY_INFORMATION:
	{
		struct file_id_extd_directory_info *info;

		info = (struct file_id_extd_directory_info *)d_info->wptr;
		memcpy(info->FileName, d_info->name, d_info->name_len);
		info->FileName[d_info->name_len] = 0x00;
		info->FileNameLength = cpu_to_le32(d_info->name_len);
		info->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FileId64ExtdDirectoryInformation:
	{
		struct file_id_64_extd_directory_info *info;

		info = (struct file_id_64_extd_directory_info *)d_info->wptr;
		memcpy(info->FileName, d_info->name, d_info->name_len);
		info->FileName[d_info->name_len] = 0x00;
		info->FileNameLength = cpu_to_le32(d_info->name_len);
		info->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FileId64ExtdBothDirectoryInformation:
	{
		struct file_id_64_extd_both_directory_info *info;

		info = (struct file_id_64_extd_both_directory_info *)d_info->wptr;
		memcpy(info->FileName, d_info->name, d_info->name_len);
		info->FileName[d_info->name_len] = 0x00;
		info->FileNameLength = cpu_to_le32(d_info->name_len);
		info->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FileIdAllExtdDirectoryInformation:
	{
		struct file_id_all_extd_directory_info *info;

		info = (struct file_id_all_extd_directory_info *)d_info->wptr;
		memcpy(info->FileName, d_info->name, d_info->name_len);
		info->FileName[d_info->name_len] = 0x00;
		info->FileNameLength = cpu_to_le32(d_info->name_len);
		info->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FileIdAllExtdBothDirectoryInformation:
	{
		struct file_id_all_extd_both_directory_info *info;

		info = (struct file_id_all_extd_both_directory_info *)d_info->wptr;
		memcpy(info->FileName, d_info->name, d_info->name_len);
		info->FileName[d_info->name_len] = 0x00;
		info->FileNameLength = cpu_to_le32(d_info->name_len);
		info->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case SMB_FIND_FILE_POSIX_INFO:
	{
		struct smb2_posix_info *posix_info;

		posix_info = (struct smb2_posix_info *)d_info->wptr;
		memcpy(posix_info->name, d_info->name, d_info->name_len);
		posix_info->name[d_info->name_len] = 0x00;
		posix_info->name_len = cpu_to_le32(d_info->name_len);
		posix_info->NextEntryOffset =
			cpu_to_le32(next_entry_offset);
		break;
	}
	} /* switch (info_level) */

	d_info->num_entry++;
	d_info->out_buf_len -= next_entry_offset;
	d_info->wptr += next_entry_offset;
	return 0;
}

static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
		       loff_t offset, u64 ino, unsigned int d_type)
{
	struct ksmbd_readdir_data	*buf;
	struct smb2_query_dir_private	*priv;
	struct ksmbd_dir_info		*d_info;
	int				rc;

	buf	= container_of(ctx, struct ksmbd_readdir_data, ctx);
	priv	= buf->private;
	d_info	= priv->d_info;

	/* dot and dotdot entries are already reserved */
	if (!strcmp(".", name) || !strcmp("..", name))
		return true;
	d_info->num_scan++;
	if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
		return true;
	if (!match_pattern(name, namlen, priv->search_pattern))
		return true;

	d_info->name		= name;
	d_info->name_len	= namlen;
	rc = reserve_populate_dentry(d_info, priv->info_level);
	if (rc)
		return false;
	if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
		d_info->out_buf_len = 0;
	return true;
}

static int verify_info_level(int info_level)
{
	switch (info_level) {
	case FILE_FULL_DIRECTORY_INFORMATION:
	case FILE_BOTH_DIRECTORY_INFORMATION:
	case FILE_DIRECTORY_INFORMATION:
	case FILE_NAMES_INFORMATION:
	case FILEID_FULL_DIRECTORY_INFORMATION:
	case FILEID_BOTH_DIRECTORY_INFORMATION:
	case SMB_FIND_FILE_POSIX_INFO:
	case FILE_ID_EXTD_DIRECTORY_INFORMATION:
	case FileId64ExtdDirectoryInformation:
	case FileId64ExtdBothDirectoryInformation:
	case FileIdAllExtdDirectoryInformation:
	case FileIdAllExtdBothDirectoryInformation:
		break;
	default:
		return -EOPNOTSUPP;
	}

	return 0;
}

static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
{
	int free_len;

	free_len = (int)(work->response_sz -
		(get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
	return free_len;
}

static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
				     unsigned short hdr2_len,
				     unsigned int out_buf_len)
{
	int free_len;

	if (out_buf_len > work->conn->vals->max_trans_size)
		return -EINVAL;

	free_len = smb2_resp_buf_len(work, hdr2_len);
	if (free_len < 0)
		return -EINVAL;

	return min_t(int, out_buf_len, free_len);
}

int smb2_query_dir(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
	struct smb2_query_directory_req *req;
	struct smb2_query_directory_rsp *rsp;
	struct ksmbd_share_config *share = work->tcon->share_conf;
	struct ksmbd_file *dir_fp = NULL;
	struct ksmbd_dir_info d_info;
	int rc = 0;
	char *srch_ptr = NULL;
	unsigned char srch_flag;
	int buffer_sz;
	struct smb2_query_dir_private query_dir_private = {NULL, };
	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;

	ksmbd_debug(SMB, "Received smb2 query directory request\n");

	WORK_BUFFERS(work, req, rsp);

	if (smb2_compound_has_failed(work, &rsp->hdr))
		return -EACCES;

	if (work->next_smb2_rcv_hdr_off &&
	    !has_file_id(req->VolatileFileId)) {
		ksmbd_debug(SMB, "Compound request set FID = %llu\n",
			    work->compound_fid);
		id = work->compound_fid;
		pid = work->compound_pfid;
	}

	if (!has_file_id(id)) {
		id = req->VolatileFileId;
		pid = req->PersistentFileId;
	}

	if (ksmbd_override_fsids(work)) {
		rsp->hdr.Status = STATUS_NO_MEMORY;
		smb2_set_err_rsp(work);
		return -ENOMEM;
	}

	rc = verify_info_level(req->FileInformationClass);
	if (rc) {
		rc = -EFAULT;
		goto err_out2;
	}

	dir_fp = ksmbd_lookup_fd_slow(work, id, pid);
	if (!dir_fp) {
		rc = -EBADF;
		goto err_out2;
	}
	if (req->FileInformationClass == SMB_FIND_FILE_POSIX_INFO &&
	    (conn->dialect != SMB311_PROT_ID ||
	     !work->tcon->posix_extensions || !dir_fp->is_posix_ctxt)) {
		rc = -EFAULT;
		goto err_out2;
	}

	if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
	    inode_permission(file_mnt_idmap(dir_fp->filp),
			     file_inode(dir_fp->filp),
			     MAY_READ | MAY_EXEC)) {
		pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
		rc = -EACCES;
		goto err_out2;
	}

	if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
		pr_err("can't do query dir for a file\n");
		rc = -EINVAL;
		goto err_out2;
	}

	srch_flag = req->Flags;
	srch_ptr = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->FileNameOffset),
					  le16_to_cpu(req->FileNameLength), 1,
					  conn->local_nls);
	if (IS_ERR(srch_ptr)) {
		ksmbd_debug(SMB, "Search Pattern not found\n");
		rc = -EINVAL;
		goto err_out2;
	} else {
		ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
	}

	mutex_lock(&dir_fp->readdir_lock);

	if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
		ksmbd_debug(SMB, "Restart directory scan\n");
		generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
	}

	memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
	d_info.wptr = (char *)rsp->Buffer;
	d_info.rptr = (char *)rsp->Buffer;
	d_info.out_buf_len =
		smb2_calc_max_out_buf_len(work,
				offsetof(struct smb2_query_directory_rsp, Buffer),
				le32_to_cpu(req->OutputBufferLength));
	if (d_info.out_buf_len < 0) {
		rc = -EINVAL;
		goto err_out;
	}
	d_info.flags = srch_flag;

	/*
	 * reserve dot and dotdot entries in head of buffer
	 * in first response
	 */
	rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
					       dir_fp, &d_info, srch_ptr,
					       smb2_populate_readdir_entry);
	if (rc == -ENOSPC)
		rc = 0;
	else if (rc)
		goto err_out;

	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
		d_info.hide_dot_file = true;

	buffer_sz				= d_info.out_buf_len;
	d_info.rptr				= d_info.wptr;
	query_dir_private.work			= work;
	query_dir_private.search_pattern	= srch_ptr;
	query_dir_private.dir_fp		= dir_fp;
	query_dir_private.d_info		= &d_info;
	query_dir_private.info_level		= req->FileInformationClass;
	dir_fp->readdir_data.private		= &query_dir_private;
	set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
again:
	d_info.num_scan = 0;
	rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
	/*
	 * num_entry can be 0 if the directory iteration stops before reaching
	 * the end of the directory and no file is matched with the search
	 * pattern.
	 */
	if (rc >= 0 && !d_info.num_entry && d_info.num_scan &&
	    d_info.out_buf_len > 0)
		goto again;
	/*
	 * req->OutputBufferLength is too small to contain even one entry.
	 * In this case, it immediately returns OutputBufferLength 0 to client.
	 */
	if (!d_info.out_buf_len && !d_info.num_entry)
		goto no_buf_len;
	if (rc > 0 || rc == -ENOSPC)
		rc = 0;
	else if (rc)
		goto err_out;

	d_info.wptr = d_info.rptr;
	d_info.out_buf_len = buffer_sz;
	rc = process_query_dir_entries(&query_dir_private);
	if (rc)
		goto err_out;

	if (!d_info.data_count && d_info.out_buf_len >= 0) {
		if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
			rsp->hdr.Status = STATUS_NO_SUCH_FILE;
		} else {
			dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
			rsp->hdr.Status = STATUS_NO_MORE_FILES;
		}
		rsp->StructureSize = cpu_to_le16(9);
		rsp->OutputBufferOffset = cpu_to_le16(0);
		rsp->OutputBufferLength = cpu_to_le32(0);
		rsp->Buffer[0] = 0;
		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
				       offsetof(struct smb2_query_directory_rsp, Buffer)
				       + 1);
		if (rc)
			goto err_out;
	} else {
no_buf_len:
		((FILE_DIRECTORY_INFO *)
		((char *)rsp->Buffer + d_info.last_entry_offset))
		->NextEntryOffset = 0;
		if (d_info.data_count >= d_info.last_entry_off_align)
			d_info.data_count -= d_info.last_entry_off_align;

		rsp->StructureSize = cpu_to_le16(9);
		rsp->OutputBufferOffset = cpu_to_le16(72);
		rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
				       offsetof(struct smb2_query_directory_rsp, Buffer) +
				       d_info.data_count);
		if (rc)
			goto err_out;
	}

	mutex_unlock(&dir_fp->readdir_lock);
	kfree(srch_ptr);
	ksmbd_fd_put(work, dir_fp);
	ksmbd_revert_fsids(work);
	return 0;

err_out:
	pr_err("error while processing smb2 query dir rc = %d\n", rc);
	mutex_unlock(&dir_fp->readdir_lock);
	kfree(srch_ptr);

err_out2:
	if (rc == -EINVAL)
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
	else if (rc == -EACCES)
		rsp->hdr.Status = STATUS_ACCESS_DENIED;
	else if (rc == -ENOENT)
		rsp->hdr.Status = STATUS_NO_SUCH_FILE;
	else if (rc == -EBADF)
		rsp->hdr.Status = STATUS_FILE_CLOSED;
	else if (rc == -ENOMEM)
		rsp->hdr.Status = STATUS_NO_MEMORY;
	else if (rc == -EFAULT)
		rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
	else if (rc == -EIO)
		rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
	if (!rsp->hdr.Status)
		rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;

	smb2_set_err_rsp(work);
	ksmbd_fd_put(work, dir_fp);
	ksmbd_revert_fsids(work);
	return rc;
}

/**
 * buffer_check_err() - helper function to check buffer errors
 * @reqOutputBufferLength:	max buffer length expected in command response
 * @fixed_len:			minimum fixed response length
 * @rsp:		query info response buffer contains output buffer length
 *
 * Return:	0 on success, otherwise error
 */
static int buffer_check_err(int reqOutputBufferLength,
			    unsigned int fixed_len,
			    struct smb2_query_info_rsp *rsp)
{
	unsigned int output_len = le32_to_cpu(rsp->OutputBufferLength);

	if (reqOutputBufferLength < fixed_len) {
		pr_err("Invalid Buffer Size Requested\n");
		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
		return -EINVAL;
	}

	if (reqOutputBufferLength < output_len) {
		rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
		rsp->OutputBufferLength = cpu_to_le32(reqOutputBufferLength);
	}
	return 0;
}

static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp)
{
	struct smb2_file_standard_info *sinfo;

	sinfo = (struct smb2_file_standard_info *)rsp->Buffer;

	sinfo->AllocationSize = cpu_to_le64(4096);
	sinfo->EndOfFile = cpu_to_le64(0);
	sinfo->NumberOfLinks = cpu_to_le32(1);
	sinfo->DeletePending = 1;
	sinfo->Directory = 0;
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_standard_info));
}

static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num)
{
	struct smb2_file_internal_info *file_info;

	file_info = (struct smb2_file_internal_info *)rsp->Buffer;

	/* any unique number */
	file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_internal_info));
}

static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
				   struct smb2_query_info_req *req,
				   struct smb2_query_info_rsp *rsp)
{
	u64 id;
	int rc;

	/*
	 * Windows can sometime send query file info request on
	 * pipe without opening it, checking error condition here
	 */
	id = req->VolatileFileId;

	lockdep_assert_not_held(&sess->rpc_lock);

	down_read(&sess->rpc_lock);
	if (!ksmbd_session_rpc_method(sess, id)) {
		up_read(&sess->rpc_lock);
		return -ENOENT;
	}
	up_read(&sess->rpc_lock);

	ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
		    req->FileInfoClass, req->VolatileFileId);

	switch (req->FileInfoClass) {
	case FILE_STANDARD_INFORMATION:
		get_standard_info_pipe(rsp);
		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
				      le32_to_cpu(rsp->OutputBufferLength),
				      rsp);
		break;
	case FILE_INTERNAL_INFORMATION:
		get_internal_info_pipe(rsp, id);
		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
				      le32_to_cpu(rsp->OutputBufferLength),
				      rsp);
		break;
	default:
		ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
			    req->FileInfoClass);
		rc = -EOPNOTSUPP;
	}
	return rc;
}

/**
 * smb2_get_ea() - handler for smb2 get extended attribute command
 * @work:	smb work containing query info command buffer
 * @fp:		ksmbd_file pointer
 * @req:	get extended attribute request
 * @rsp:	response buffer pointer
 * @rsp_org:	base response buffer pointer in case of chained response
 *
 * Return:	0 on success, otherwise error
 */
static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
		       struct smb2_query_info_req *req,
		       struct smb2_query_info_rsp *rsp, void *rsp_org)
{
	struct smb2_ea_info *eainfo, *prev_eainfo;
	char *name, *ptr, *xattr_list = NULL, *buf;
	int rc, name_len, value_len, xattr_list_len, idx;
	ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
	struct smb2_ea_info_req *ea_req = NULL;
	const struct path *path;
	const struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);

	if (!(fp->daccess & FILE_READ_EA_LE)) {
		pr_err("Not permitted to read ext attr : 0x%x\n",
		       fp->daccess);
		return -EACCES;
	}

	path = &fp->filp->f_path;
	/* single EA entry is requested with given user.* name */
	if (req->InputBufferLength) {
		if (le32_to_cpu(req->InputBufferLength) <=
		    sizeof(struct smb2_ea_info_req))
			return -EINVAL;

		ea_req = (struct smb2_ea_info_req *)((char *)req +
						     le16_to_cpu(req->InputBufferOffset));

		if (le32_to_cpu(req->InputBufferLength) <
		    offsetof(struct smb2_ea_info_req, name) +
		    ea_req->EaNameLength)
			return -EINVAL;
	} else {
		/* need to send all EAs, if no specific EA is requested*/
		if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
			ksmbd_debug(SMB,
				    "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
				    le32_to_cpu(req->Flags));
	}

	buf_free_len =
		smb2_calc_max_out_buf_len(work,
				offsetof(struct smb2_query_info_rsp, Buffer),
				le32_to_cpu(req->OutputBufferLength));
	if (buf_free_len < 0)
		return -EINVAL;

	rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
	if (rc < 0) {
		rsp->hdr.Status = STATUS_INVALID_HANDLE;
		goto out;
	} else if (!rc) { /* there is no EA in the file */
		ksmbd_debug(SMB, "no ea data in the file\n");
		goto done;
	}
	xattr_list_len = rc;

	ptr = (char *)rsp->Buffer;
	eainfo = (struct smb2_ea_info *)ptr;
	prev_eainfo = eainfo;
	idx = 0;

	while (idx < xattr_list_len) {
		name = xattr_list + idx;
		name_len = strlen(name);

		ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
		idx += name_len + 1;

		/*
		 * CIFS does not support EA other than user.* namespace,
		 * still keep the framework generic, to list other attrs
		 * in future.
		 */
		if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
			continue;

		if (req->InputBufferLength &&
		    strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
			    ea_req->EaNameLength))
			continue;

		if (smb2_is_private_ea(&name[XATTR_USER_PREFIX_LEN],
				       name_len - XATTR_USER_PREFIX_LEN))
			continue;

		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
			name_len -= XATTR_USER_PREFIX_LEN;

		ptr = eainfo->name + name_len + 1;
		buf_free_len -= (offsetof(struct smb2_ea_info, name) +
				name_len + 1);
		/* bailout if xattr can't fit in buf_free_len */
		value_len = ksmbd_vfs_getxattr(idmap, path->dentry,
					       name, &buf);
		if (value_len <= 0) {
			rc = -ENOENT;
			rsp->hdr.Status = STATUS_INVALID_HANDLE;
			goto out;
		}

		buf_free_len -= value_len;
		if (buf_free_len < 0) {
			kfree(buf);
			break;
		}

		memcpy(ptr, buf, value_len);
		kfree(buf);

		ptr += value_len;
		eainfo->Flags = 0;
		eainfo->EaNameLength = name_len;

		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
			memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
			       name_len);
		else
			memcpy(eainfo->name, name, name_len);

		eainfo->name[name_len] = '\0';
		eainfo->EaValueLength = cpu_to_le16(value_len);
		next_offset = offsetof(struct smb2_ea_info, name) +
			name_len + 1 + value_len;

		/* align next xattr entry at 4 byte bundary */
		alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
		if (alignment_bytes) {
			if (buf_free_len < alignment_bytes)
				break;
			memset(ptr, '\0', alignment_bytes);
			ptr += alignment_bytes;
			next_offset += alignment_bytes;
			buf_free_len -= alignment_bytes;
		}
		eainfo->NextEntryOffset = cpu_to_le32(next_offset);
		prev_eainfo = eainfo;
		eainfo = (struct smb2_ea_info *)ptr;
		rsp_data_cnt += next_offset;

		if (req->InputBufferLength) {
			ksmbd_debug(SMB, "single entry requested\n");
			break;
		}
	}

	/* no more ea entries */
	prev_eainfo->NextEntryOffset = 0;
done:
	rc = 0;
	if (rsp_data_cnt == 0)
		rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
	rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
out:
	kvfree(xattr_list);
	return rc;
}

static void get_file_access_info(struct smb2_query_info_rsp *rsp,
				 struct ksmbd_file *fp, void *rsp_org)
{
	struct smb2_file_access_info *file_info;

	file_info = (struct smb2_file_access_info *)rsp->Buffer;
	file_info->AccessFlags = fp->daccess;
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_access_info));
}

static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
			       struct ksmbd_file *fp, void *rsp_org)
{
	struct file_basic_info *basic_info;
	struct kstat stat;
	u64 time;
	int ret;

	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
		pr_err("no right to read the attributes : 0x%x\n",
		       fp->daccess);
		return -EACCES;
	}

	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
			  AT_STATX_SYNC_AS_STAT);
	if (ret)
		return ret;

	basic_info = (struct file_basic_info *)rsp->Buffer;
	basic_info->CreationTime = cpu_to_le64(fp->create_time);
	time = ksmbd_UnixTimeToNT(stat.atime);
	basic_info->LastAccessTime = cpu_to_le64(time);
	time = ksmbd_UnixTimeToNT(stat.mtime);
	basic_info->LastWriteTime = cpu_to_le64(time);
	basic_info->ChangeTime = cpu_to_le64(fp->change_time);
	basic_info->Attributes = fp->f_ci->m_fattr;
	basic_info->Pad = 0;
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct file_basic_info));
	return 0;
}

static int get_file_allocation_stat(struct ksmbd_file *fp, struct kstat *stat)
{
	int ret;

	/*
	 * Buffered writes can leave delayed allocation in a state where two
	 * consecutive queries report different block counts even when the
	 * second write only overwrites the first one. Complete writeback before
	 * reporting the filesystem allocation for an ordinary open.
	 */
	if (!fp->allocation_size_set) {
		ret = file_write_and_wait(fp->filp);
		if (ret)
			return ret;
	}

	ret = vfs_getattr(&fp->filp->f_path, stat, STATX_BASIC_STATS,
			  AT_STATX_SYNC_AS_STAT);
	if (!ret && !fp->allocation_size_set)
		fp->allocation_size = S_ISDIR(stat->mode) ? 0 : stat->blocks << 9;

	return ret;
}

static int get_file_standard_info(struct smb2_query_info_rsp *rsp,
				  struct ksmbd_file *fp, void *rsp_org)
{
	struct smb2_file_standard_info *sinfo;
	unsigned int delete_pending;
	struct kstat stat;
	int ret;

	ret = get_file_allocation_stat(fp, &stat);
	if (ret)
		return ret;

	sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
	delete_pending = ksmbd_inode_pending_delete(fp);

	if (ksmbd_stream_fd(fp) == false) {
		sinfo->AllocationSize = cpu_to_le64(fp->allocation_size);
		sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
	} else {
		loff_t seof = ksmbd_stream_eof(fp);

		sinfo->AllocationSize = cpu_to_le64((u64)seof);
		sinfo->EndOfFile = cpu_to_le64((u64)seof);
	}
	sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
	sinfo->DeletePending = delete_pending;
	sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_standard_info));

	return 0;
}

static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
				    void *rsp_org)
{
	struct smb2_file_alignment_info *file_info;

	file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
	file_info->AlignmentRequirement = 0;
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_alignment_info));
}

static int get_file_all_info(struct ksmbd_work *work,
			     struct smb2_query_info_rsp *rsp,
			     struct ksmbd_file *fp,
			     void *rsp_org)
{
	struct ksmbd_conn *conn = work->conn;
	struct smb2_file_all_info *file_info;
	unsigned int delete_pending;
	struct kstat stat;
	int conv_len;
	char *filename;
	u64 time;
	int ret, buf_free_len, filename_len;

	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
		ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
			    fp->daccess);
		return -EACCES;
	}

	filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
	if (IS_ERR(filename))
		return PTR_ERR(filename);

	filename_len = strlen(filename);
	buf_free_len = smb2_resp_buf_len(work,
			offsetof(struct smb2_query_info_rsp, Buffer) +
			offsetof(struct smb2_file_all_info, FileName));
	if (buf_free_len < (filename_len + 1) * 2) {
		kfree(filename);
		return -EINVAL;
	}

	ret = get_file_allocation_stat(fp, &stat);
	if (ret) {
		kfree(filename);
		return ret;
	}

	ksmbd_debug(SMB, "filename = %s\n", filename);
	delete_pending = ksmbd_inode_pending_delete(fp);
	file_info = (struct smb2_file_all_info *)rsp->Buffer;

	file_info->CreationTime = cpu_to_le64(fp->create_time);
	time = ksmbd_UnixTimeToNT(stat.atime);
	file_info->LastAccessTime = cpu_to_le64(time);
	time = ksmbd_UnixTimeToNT(stat.mtime);
	file_info->LastWriteTime = cpu_to_le64(time);
	file_info->ChangeTime = cpu_to_le64(fp->change_time);
	file_info->Attributes = fp->f_ci->m_fattr;
	file_info->Pad1 = 0;
	if (ksmbd_stream_fd(fp) == false) {
		file_info->AllocationSize = cpu_to_le64(fp->allocation_size);
		file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
	} else {
		loff_t seof = ksmbd_stream_eof(fp);

		file_info->AllocationSize = cpu_to_le64((u64)seof);
		file_info->EndOfFile = cpu_to_le64((u64)seof);
	}
	file_info->NumberOfLinks =
			cpu_to_le32(get_nlink(&stat) - delete_pending);
	file_info->DeletePending = delete_pending;
	file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
	file_info->Pad2 = 0;
	file_info->IndexNumber = cpu_to_le64(stat.ino);
	file_info->EASize = 0;
	file_info->AccessFlags = fp->daccess;
	if (ksmbd_stream_fd(fp) == false)
		file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
	else
		file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos);
	file_info->Mode = fp->coption;
	file_info->AlignmentRequirement = 0;
	conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
				     min(filename_len, PATH_MAX),
				     conn->local_nls, 0);
	conv_len *= 2;
	file_info->FileNameLength = cpu_to_le32(conv_len);
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
	kfree(filename);
	return 0;
}

static void get_file_alternate_info(struct ksmbd_work *work,
				    struct smb2_query_info_rsp *rsp,
				    struct ksmbd_file *fp,
				    void *rsp_org)
{
	struct ksmbd_conn *conn = work->conn;
	struct smb2_file_name_info *file_info;
	struct dentry *dentry = fp->filp->f_path.dentry;
	int conv_len;

	spin_lock(&dentry->d_lock);
	file_info = (struct smb2_file_name_info *)rsp->Buffer;
	conv_len = ksmbd_extract_shortname(conn,
					   dentry->d_name.name,
					   file_info->FileName);
	spin_unlock(&dentry->d_lock);
	file_info->FileNameLength = cpu_to_le32(conv_len);
	rsp->OutputBufferLength =
		cpu_to_le32(struct_size(file_info, FileName, conv_len));
}

static char *smb2_get_normalized_stream_name(struct ksmbd_file *fp)
{
	char *name, *stream_name = NULL, *xattr_list = NULL;
	ssize_t xattr_list_len;

	if (!ksmbd_stream_fd(fp))
		return NULL;

	xattr_list_len = ksmbd_vfs_listxattr(fp->filp->f_path.dentry,
					     &xattr_list);
	if (xattr_list_len <= 0)
		goto out;

	for (name = xattr_list; name - xattr_list < xattr_list_len;
	     name += strlen(name) + 1) {
		char *type;

		if (strlen(name) + 1 != fp->stream.size ||
		    strncasecmp(name, fp->stream.name, fp->stream.size - 1))
			continue;

		name += XATTR_NAME_STREAM_LEN;
		type = strrchr(name, ':');
		if (type)
			stream_name = kstrndup(name, type - name,
						  KSMBD_DEFAULT_GFP);
		break;
	}
out:
	kvfree(xattr_list);
	return stream_name;
}

static int get_file_normalized_name_info(struct ksmbd_work *work,
					 struct smb2_query_info_rsp *rsp,
					 struct ksmbd_file *fp)
{
	struct smb2_file_name_info *file_info;
	char *filename, *normalized, *stream_name;
	int buf_free_len, conv_len, filename_len;

	if (work->conn->dialect < SMB311_PROT_ID) {
		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
		return -EOPNOTSUPP;
	}

	filename = convert_to_nt_pathname(work->tcon->share_conf,
					  &fp->filp->f_path);
	if (IS_ERR(filename))
		return PTR_ERR(filename);
	if (filename[0] == '\\')
		memmove(filename, filename + 1, strlen(filename));

	stream_name = smb2_get_normalized_stream_name(fp);
	normalized = kasprintf(KSMBD_DEFAULT_GFP, "%s%s%s", filename,
			      stream_name ? ":" : "",
			      stream_name ? stream_name : "");
	kfree(stream_name);
	kfree(filename);
	if (!normalized)
		return -ENOMEM;

	filename_len = strlen(normalized);
	buf_free_len = smb2_resp_buf_len(work, sizeof(*rsp) +
					 sizeof(*file_info));
	if (buf_free_len < 0 ||
	    (size_t)buf_free_len < (filename_len + 1) * sizeof(__le16)) {
		kfree(normalized);
		return -EINVAL;
	}

	file_info = (struct smb2_file_name_info *)rsp->Buffer;
	conv_len = smbConvertToUTF16((__le16 *)file_info->FileName,
				     normalized, filename_len,
				     work->conn->local_nls, 0);
	kfree(normalized);
	conv_len *= 2;
	file_info->FileNameLength = cpu_to_le32(conv_len);
	rsp->OutputBufferLength = cpu_to_le32(sizeof(*file_info) + conv_len);
	return 0;
}

struct smb2_stream_info_buffer {
	struct smb2_query_info_rsp *rsp;
	struct smb2_file_stream_info *last;
	const struct nls_table *local_nls;
	unsigned int length;
	unsigned int capacity;
};

static int smb2_add_stream_info(struct smb2_stream_info_buffer *buf,
				const char *name, loff_t size, u64 allocation_size)
{
	struct smb2_file_stream_info *file_info;
	__le16 *utf16_name;
	size_t name_len = strlen(name);
	unsigned int offset = ALIGN(buf->length, 8), name_bytes;
	int conv_len, ret = 0;

	if (offset > buf->capacity ||
	    buf->capacity - offset < sizeof(*file_info))
		return -ENOSPC;

	utf16_name = kmalloc_objs(*utf16_name, name_len + 1, KSMBD_DEFAULT_GFP);
	if (!utf16_name)
		return -ENOMEM;

	conv_len = smbConvertToUTF16(utf16_name, name, name_len,
				     buf->local_nls, 0);
	if (conv_len < 0) {
		ret = conv_len;
		goto out;
	}

	name_bytes = conv_len * sizeof(*utf16_name);
	if (name_bytes > buf->capacity - offset - sizeof(*file_info)) {
		ret = -ENOSPC;
		goto out;
	}

	file_info = (struct smb2_file_stream_info *)&buf->rsp->Buffer[offset];
	if (buf->last) {
		memset(&buf->rsp->Buffer[buf->length], 0, offset - buf->length);
		buf->last->NextEntryOffset =
			cpu_to_le32((char *)file_info - (char *)buf->last);
	}
	file_info->NextEntryOffset = 0;
	file_info->StreamNameLength = cpu_to_le32(name_bytes);
	file_info->StreamSize = cpu_to_le64(size);
	file_info->StreamAllocationSize = cpu_to_le64(allocation_size);
	memcpy(file_info->StreamName, utf16_name, name_bytes);

	buf->last = file_info;
	buf->length = offset + sizeof(*file_info) + name_bytes;
out:
	kfree(utf16_name);
	return ret;
}

static int get_file_stream_info(struct ksmbd_work *work,
				struct smb2_query_info_req *req,
				struct smb2_query_info_rsp *rsp,
				struct ksmbd_file *fp)
{
	struct smb2_stream_info_buffer buf = {
		.rsp = rsp,
		.local_nls = work->conn->local_nls,
	};
	char *stream_name, *xattr_list = NULL, *stream_buf;
	struct kstat stat;
	const struct path *path = &fp->filp->f_path;
	ssize_t xattr_list_len;
	ssize_t slen;
	loff_t ssize;
	unsigned int req_output_len = le32_to_cpu(req->OutputBufferLength);
	int streamlen, idx = 0;
	int buf_free_len;
	int ret;

	if (req_output_len < FILE_STREAM_INFORMATION_SIZE) {
		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
		return -EINVAL;
	}

	buf_free_len = smb2_calc_max_out_buf_len(work,
						 offsetof(struct smb2_query_info_rsp, Buffer),
						 req_output_len);
	if (buf_free_len < 0)
		return buf_free_len;
	buf.capacity = buf_free_len;

	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
			  AT_STATX_SYNC_AS_STAT);
	if (ret)
		return ret;

	xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
	if (xattr_list_len < 0) {
		goto default_stream;
	} else if (!xattr_list_len) {
		ksmbd_debug(SMB, "empty xattr in the file\n");
		goto default_stream;
	}

	while (idx < xattr_list_len) {
		stream_name = xattr_list + idx;
		streamlen = strlen(stream_name);
		idx += streamlen + 1;

		ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);

		if (strncmp(stream_name, XATTR_NAME_STREAM,
			    XATTR_NAME_STREAM_LEN))
			continue;

		stream_buf = kasprintf(KSMBD_DEFAULT_GFP, ":%s",
				       &stream_name[XATTR_NAME_STREAM_LEN]);
		if (!stream_buf) {
			ret = -ENOMEM;
			goto out;
		}
		slen = ksmbd_vfs_xattr_len(file_mnt_idmap(fp->filp),
					   path->dentry, stream_name);
		ssize = slen < 0 ? 0 : (loff_t)slen;
		ret = smb2_add_stream_info(&buf, stream_buf, ssize, ssize);
		kfree(stream_buf);
		if (ret == -ENOSPC)
			goto overflow;
		if (ret)
			goto out;
	}

default_stream:
	if (!S_ISDIR(stat.mode)) {
		ret = smb2_add_stream_info(&buf, "::$DATA", stat.size,
					   stat.blocks << 9);
		if (ret == -ENOSPC)
			goto overflow;
		if (ret)
			goto out;
	}

	ret = 0;
	goto out;

overflow:
	rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
	/* An empty overflow needs an SMB2 error response. */
	ret = buf.length ? 0 : -EOVERFLOW;
out:
	if (!ret)
		rsp->OutputBufferLength = cpu_to_le32(buf.length);
	kvfree(xattr_list);
	return ret;
}

static int get_file_internal_info(struct smb2_query_info_rsp *rsp,
				  struct ksmbd_file *fp, void *rsp_org)
{
	struct smb2_file_internal_info *file_info;
	struct kstat stat;
	int ret;

	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
			  AT_STATX_SYNC_AS_STAT);
	if (ret)
		return ret;

	file_info = (struct smb2_file_internal_info *)rsp->Buffer;
	file_info->IndexNumber = cpu_to_le64(stat.ino);
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_internal_info));

	return 0;
}

static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
				      struct ksmbd_file *fp, void *rsp_org)
{
	struct smb2_file_network_open_info *file_info;
	struct kstat stat;
	u64 time;
	int ret;

	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
		pr_err("no right to read the attributes : 0x%x\n",
		       fp->daccess);
		return -EACCES;
	}

	ret = get_file_allocation_stat(fp, &stat);
	if (ret)
		return ret;

	file_info = (struct smb2_file_network_open_info *)rsp->Buffer;

	file_info->CreationTime = cpu_to_le64(fp->create_time);
	time = ksmbd_UnixTimeToNT(stat.atime);
	file_info->LastAccessTime = cpu_to_le64(time);
	time = ksmbd_UnixTimeToNT(stat.mtime);
	file_info->LastWriteTime = cpu_to_le64(time);
	file_info->ChangeTime = cpu_to_le64(fp->change_time);
	file_info->Attributes = fp->f_ci->m_fattr;
	if (ksmbd_stream_fd(fp) == false) {
		file_info->AllocationSize = cpu_to_le64(fp->allocation_size);
		file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
	} else {
		loff_t seof = ksmbd_stream_eof(fp);

		file_info->AllocationSize = cpu_to_le64((u64)seof);
		file_info->EndOfFile = cpu_to_le64((u64)seof);
	}
	file_info->Reserved = cpu_to_le32(0);
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_network_open_info));
	return 0;
}

static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
{
	struct smb2_file_ea_info *file_info;

	file_info = (struct smb2_file_ea_info *)rsp->Buffer;
	file_info->EASize = 0;
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_ea_info));
}

static void get_file_position_info(struct smb2_query_info_rsp *rsp,
				   struct ksmbd_file *fp, void *rsp_org)
{
	struct smb2_file_pos_info *file_info;

	file_info = (struct smb2_file_pos_info *)rsp->Buffer;
	if (ksmbd_stream_fd(fp) == false)
		file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
	else
		file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos);

	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_pos_info));
}

static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
			       struct ksmbd_file *fp, void *rsp_org)
{
	struct smb2_file_mode_info *file_info;

	file_info = (struct smb2_file_mode_info *)rsp->Buffer;
	file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_mode_info));
}

static int get_file_compression_info(struct smb2_query_info_rsp *rsp,
				     struct ksmbd_file *fp, void *rsp_org)
{
	struct smb2_file_comp_info *file_info;
	struct kstat stat;
	u16 fmt;
	int ret;

	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
			  AT_STATX_SYNC_AS_STAT);
	if (ret)
		return ret;

	ret = ksmbd_vfs_get_compression(fp, &fmt);
	if (ret)
		return ret;

	file_info = (struct smb2_file_comp_info *)rsp->Buffer;
	file_info->CompressedFileSize = cpu_to_le64(min_t(u64, stat.blocks << 9, stat.size));
	file_info->CompressionFormat = cpu_to_le16(fmt);
	file_info->CompressionUnitShift = 0;
	file_info->ChunkShift = 0;
	file_info->ClusterShift = 0;
	memset(&file_info->Reserved[0], 0, 3);

	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_comp_info));

	return 0;
}

static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
				       struct ksmbd_file *fp, void *rsp_org)
{
	struct smb2_file_attr_tag_info *file_info;

	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
		pr_err("no right to read the attributes : 0x%x\n",
		       fp->daccess);
		return -EACCES;
	}

	file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
	file_info->FileAttributes = fp->f_ci->m_fattr;
	file_info->ReparseTag = 0;
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
	return 0;
}

static int find_file_posix_info(struct ksmbd_work *work,
				struct smb2_query_info_req *req,
				struct smb2_query_info_rsp *rsp,
				struct ksmbd_file *fp)
{
	struct smb311_posix_qinfo *file_info;
	struct inode *inode = file_inode(fp->filp);
	const struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
	vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
	vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
	struct kstat stat;
	char *filename;
	__le16 *utf16_name;
	__le32 *filename_len;
	size_t name_bytes;
	u64 time;
	int fixed_len = sizeof(struct smb311_posix_qinfo) + 32 + sizeof(__le32);
	int max_len, conv_len, ret;

	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
		pr_err("no right to read the attributes : 0x%x\n",
		       fp->daccess);
		return -EACCES;
	}

	ret = get_file_allocation_stat(fp, &stat);
	if (ret)
		return ret;
	max_len = smb2_calc_max_out_buf_len(work,
			offsetof(struct smb2_query_info_rsp, Buffer),
			le32_to_cpu(req->OutputBufferLength));
	if (max_len < fixed_len) {
		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
		return -EINVAL;
	}
	filename = convert_to_nt_pathname(work->tcon->share_conf,
					   &fp->filp->f_path);
	if (IS_ERR(filename))
		return PTR_ERR(filename);
	if (filename[0] == '\\')
		memmove(filename, filename + 1, strlen(filename));
	name_bytes = strlen(filename);
	utf16_name = kmalloc_objs(*utf16_name, name_bytes + 1,
				  KSMBD_DEFAULT_GFP);
	if (!utf16_name) {
		kfree(filename);
		return -ENOMEM;
	}
	conv_len = smbConvertToUTF16(utf16_name, filename, name_bytes,
				      work->conn->local_nls, 0);
	kfree(filename);
	if (conv_len < 0) {
		kfree(utf16_name);
		return conv_len;
	}
	if (conv_len > (max_len - fixed_len) / sizeof(*utf16_name)) {
		kfree(utf16_name);
		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
		return -EINVAL;
	}

	file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
	file_info->CreationTime = cpu_to_le64(fp->create_time);
	time = ksmbd_UnixTimeToNT(stat.atime);
	file_info->LastAccessTime = cpu_to_le64(time);
	time = ksmbd_UnixTimeToNT(stat.mtime);
	file_info->LastWriteTime = cpu_to_le64(time);
	file_info->ChangeTime = cpu_to_le64(fp->change_time);
	file_info->DosAttributes = fp->f_ci->m_fattr;
	file_info->Inode = cpu_to_le64(stat.ino);
	if (ksmbd_stream_fd(fp) == false) {
		file_info->EndOfFile = cpu_to_le64(stat.size);
		file_info->AllocationSize = cpu_to_le64(fp->allocation_size);
	} else {
		loff_t seof = ksmbd_stream_eof(fp);

		file_info->EndOfFile = cpu_to_le64((u64)seof);
		file_info->AllocationSize = cpu_to_le64((u64)seof);
	}
	file_info->HardLinks = cpu_to_le32(stat.nlink);
	file_info->Mode = cpu_to_le32(stat.mode & 07777);
	switch (stat.mode & S_IFMT) {
	case S_IFDIR:
		file_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT);
		break;
	case S_IFLNK:
		file_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT);
		break;
	case S_IFCHR:
		file_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT);
		break;
	case S_IFBLK:
		file_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT);
		break;
	case S_IFIFO:
		file_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT);
		break;
	case S_IFSOCK:
		file_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
	}

	file_info->DeviceId = cpu_to_le32(stat.dev);
	file_info->Zero = 0;
	file_info->ReparseTag = smb2_get_reparse_tag_special_file(stat.mode);
	if (file_info->ReparseTag)
		file_info->DosAttributes |= FILE_ATTRIBUTE_REPARSE_POINT_LE;

	/*
	 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
	 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
	 *		  sub_auth(4 * 1(num_subauth)) + RID(4).
	 */
	id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
		  SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
	id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
		  SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
	filename_len = (__le32 *)&file_info->Sids[32];
	memcpy(&file_info->Sids[36], utf16_name,
	       conv_len * sizeof(*utf16_name));
	kfree(utf16_name);
	*filename_len = cpu_to_le32(conv_len * sizeof(__le16));

	rsp->OutputBufferLength = cpu_to_le32(fixed_len +
					       conv_len * sizeof(__le16));

	return 0;
}

static int smb2_get_info_file(struct ksmbd_work *work,
			      struct smb2_query_info_req *req,
			      struct smb2_query_info_rsp *rsp)
{
	struct ksmbd_file *fp;
	int fileinfoclass = 0;
	int rc = 0;
	unsigned int fixed_len, req_output_len;
	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;

	if (test_share_config_flag(work->tcon->share_conf,
				   KSMBD_SHARE_FLAG_PIPE)) {
		/* smb2 info file called for pipe */
		rc = smb2_get_info_file_pipe(work->sess, req, rsp);
		goto iov_pin_out;
	}

	if (work->next_smb2_rcv_hdr_off) {
		if (!has_file_id(req->VolatileFileId)) {
			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
				    work->compound_fid);
			id = work->compound_fid;
			pid = work->compound_pfid;
		}
	}

	if (!has_file_id(id)) {
		id = req->VolatileFileId;
		pid = req->PersistentFileId;
	}

	fp = ksmbd_lookup_fd_slow(work, id, pid);
	if (!fp)
		return -ENOENT;

	fileinfoclass = req->FileInfoClass;

	switch (fileinfoclass) {
	case FILE_ACCESS_INFORMATION:
		get_file_access_info(rsp, fp, work->response_buf);
		break;

	case FILE_BASIC_INFORMATION:
		rc = get_file_basic_info(rsp, fp, work->response_buf);
		break;

	case FILE_STANDARD_INFORMATION:
		rc = get_file_standard_info(rsp, fp, work->response_buf);
		break;

	case FILE_ALIGNMENT_INFORMATION:
		get_file_alignment_info(rsp, work->response_buf);
		break;

	case FILE_ALL_INFORMATION:
		rc = get_file_all_info(work, rsp, fp, work->response_buf);
		break;

	case FILE_ALTERNATE_NAME_INFORMATION:
		get_file_alternate_info(work, rsp, fp, work->response_buf);
		break;
	case FILE_NORMALIZED_NAME_INFORMATION:
		rc = get_file_normalized_name_info(work, rsp, fp);
		break;

	case FILE_STREAM_INFORMATION:
		rc = get_file_stream_info(work, req, rsp, fp);
		break;

	case FILE_INTERNAL_INFORMATION:
		rc = get_file_internal_info(rsp, fp, work->response_buf);
		break;

	case FILE_NETWORK_OPEN_INFORMATION:
		rc = get_file_network_open_info(rsp, fp, work->response_buf);
		break;

	case FILE_EA_INFORMATION:
		get_file_ea_info(rsp, work->response_buf);
		break;

	case FILE_FULL_EA_INFORMATION:
		rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
		break;

	case FILE_POSITION_INFORMATION:
		get_file_position_info(rsp, fp, work->response_buf);
		break;

	case FILE_MODE_INFORMATION:
		get_file_mode_info(rsp, fp, work->response_buf);
		break;

	case FILE_COMPRESSION_INFORMATION:
		rc = get_file_compression_info(rsp, fp, work->response_buf);
		break;

	case FILE_ATTRIBUTE_TAG_INFORMATION:
		rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
		break;
	case SMB_FIND_FILE_POSIX_INFO:
		if (work->conn->dialect != SMB311_PROT_ID ||
		    !work->tcon->posix_extensions || !fp->is_posix_ctxt) {
			rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
			rc = -EOPNOTSUPP;
		} else {
			rc = find_file_posix_info(work, req, rsp, fp);
		}
		break;
	default:
		ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
			    fileinfoclass);
		rc = -EOPNOTSUPP;
	}
	if (!rc) {
		req_output_len = le32_to_cpu(req->OutputBufferLength);
		fixed_len = le32_to_cpu(rsp->OutputBufferLength);
		switch (fileinfoclass) {
		case FILE_ALL_INFORMATION:
			fixed_len = FILE_ALL_INFORMATION_SIZE;
			break;
		case FILE_ALTERNATE_NAME_INFORMATION:
			fixed_len = FILE_NAME_INFORMATION_SIZE;
			break;
		case FILE_NORMALIZED_NAME_INFORMATION:
			fixed_len = FILE_NAME_INFORMATION_SIZE;
			req_output_len = round_down(req_output_len, 2);
			break;
		case FILE_STREAM_INFORMATION:
			fixed_len = FILE_STREAM_INFORMATION_SIZE;
			break;
		}
		rc = buffer_check_err(req_output_len, fixed_len, rsp);
	}
	ksmbd_fd_put(work, fp);

iov_pin_out:
	if (!rc)
		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
				offsetof(struct smb2_query_info_rsp, Buffer) +
				le32_to_cpu(rsp->OutputBufferLength));
	return rc;
}

static int smb2_get_info_filesystem(struct ksmbd_work *work,
				    struct smb2_query_info_req *req,
				    struct smb2_query_info_rsp *rsp)
{
	struct ksmbd_conn *conn = work->conn;
	struct ksmbd_share_config *share = work->tcon->share_conf;
	struct ksmbd_file *fp;
	int fsinfoclass = 0;
	struct kstatfs stfs;
	struct path path;
	int rc = 0, len;
	unsigned int fixed_len = 0;
	u64 id, pid;

	if (req->FileInfoClass == FS_POSIX_INFORMATION) {
		if (conn->dialect != SMB311_PROT_ID ||
		    !work->tcon->posix_extensions) {
			rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
			return -EOPNOTSUPP;
		}
		id = req->VolatileFileId;
		pid = req->PersistentFileId;
		if (work->next_smb2_rcv_hdr_off && !has_file_id(id)) {
			id = work->compound_fid;
			pid = work->compound_pfid;
		}
		fp = ksmbd_lookup_fd_slow(work, id, pid);
		if (!fp)
			return -ENOENT;
		if (!fp->is_posix_ctxt) {
			ksmbd_fd_put(work, fp);
			rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
			return -EOPNOTSUPP;
		}
		path = fp->filp->f_path;
		path_get(&path);
		ksmbd_fd_put(work, fp);
	} else {
		if (!share->path)
			return -EIO;

		scoped_with_init_fs()
			rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
		if (rc) {
			pr_err("cannot create vfs path\n");
			return -EIO;
		}
	}

	rc = vfs_statfs(&path, &stfs);
	if (rc) {
		pr_err("cannot do stat of path %s\n", share->path);
		path_put(&path);
		return -EIO;
	}

	fsinfoclass = req->FileInfoClass;

	switch (fsinfoclass) {
	case FS_DEVICE_INFORMATION:
	{
		FILE_SYSTEM_DEVICE_INFO *info;

		info = (FILE_SYSTEM_DEVICE_INFO *)rsp->Buffer;

		info->DeviceType = cpu_to_le32(FILE_DEVICE_DISK);
		info->DeviceCharacteristics =
			cpu_to_le32(FILE_DEVICE_IS_MOUNTED);
		if (!test_tree_conn_flag(work->tcon,
					 KSMBD_TREE_CONN_FLAG_WRITABLE))
			info->DeviceCharacteristics |=
				cpu_to_le32(FILE_READ_ONLY_DEVICE);
		rsp->OutputBufferLength = cpu_to_le32(8);
		fixed_len = 8;
		break;
	}
	case FS_ATTRIBUTE_INFORMATION:
	{
		FILE_SYSTEM_ATTRIBUTE_INFO *info;
		struct file_kattr fa = {};
		size_t sz;
		u32 attrs;
		int err;

		info = (FILE_SYSTEM_ATTRIBUTE_INFO *)rsp->Buffer;
		attrs = FILE_SUPPORTS_OBJECT_IDS |
			FILE_PERSISTENT_ACLS |
			FILE_UNICODE_ON_DISK |
			FILE_FILE_COMPRESSION |
			FILE_SUPPORTS_SPARSE_FILES |
			FILE_SUPPORTS_BLOCK_REFCOUNTING;

		err = vfs_fileattr_get(path.dentry, &fa);
		/*
		 * -EINVAL, -EOPNOTSUPP: ntfs-3g and other FUSE
		 * filesystems that lack FS_IOC_FSGETXATTR support.
		 */
		if (err && err != -ENOIOCTLCMD && err != -ENOTTY &&
		    err != -EINVAL && err != -EOPNOTSUPP) {
			path_put(&path);
			return err;
		}
		if (!(fa.fsx_xflags & FS_XFLAG_CASEFOLD))
			attrs |= FILE_CASE_SENSITIVE_SEARCH;
		if (!(fa.fsx_xflags & FS_XFLAG_CASENONPRESERVING))
			attrs |= FILE_CASE_PRESERVED_NAMES;

		info->Attributes = cpu_to_le32(attrs);
		info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);

		if (test_share_config_flag(work->tcon->share_conf,
		    KSMBD_SHARE_FLAG_STREAMS))
			info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);

		info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
		/*
		 * some application(potableapp) can not run on ksmbd share
		 * because only NTFS handle security setting on windows.
		 * So Although local fs(EXT4 or F2fs, etc) is not NTFS,
		 * ksmbd should show share as NTFS. Later, If needed, we can add
		 * fs type(s) parameter to change fs type user wanted.
		 */
		len = smbConvertToUTF16((__le16 *)info->FileSystemName,
					"NTFS", PATH_MAX, conn->local_nls, 0);
		len = len * 2;
		info->FileSystemNameLen = cpu_to_le32(len);
		sz = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO) + len;
		rsp->OutputBufferLength = cpu_to_le32(sz);
		fixed_len = 16;
		break;
	}
	case FS_VOLUME_INFORMATION:
	{
		struct filesystem_vol_info *info;
		size_t sz;
		unsigned int serial_crc = 0;

		info = (struct filesystem_vol_info *)(rsp->Buffer);
		info->VolumeCreationTime = 0;
		serial_crc = crc32_le(serial_crc, share->name,
				      strlen(share->name));
		serial_crc = crc32_le(serial_crc, share->path,
				      strlen(share->path));
		serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
				      strlen(ksmbd_netbios_name()));
		/* Taking dummy value of serial number*/
		info->VolumeSerialNumber = cpu_to_le32(serial_crc);
		len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
					share->name, PATH_MAX,
					conn->local_nls, 0);
		len = len * 2;
		info->VolumeLabelLength = cpu_to_le32(len);
		info->Reserved = 0;
		info->SupportsObjects = 0;
		sz = sizeof(struct filesystem_vol_info) + len;
		rsp->OutputBufferLength = cpu_to_le32(sz);
		fixed_len = 24;
		break;
	}
	case FS_SIZE_INFORMATION:
	{
		FILE_SYSTEM_SIZE_INFO *info;

		info = (FILE_SYSTEM_SIZE_INFO *)(rsp->Buffer);
		info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
		info->AvailableAllocationUnits = cpu_to_le64(stfs.f_bfree);
		info->SectorsPerAllocationUnit = cpu_to_le32(1);
		info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
		rsp->OutputBufferLength = cpu_to_le32(24);
		fixed_len = 24;
		break;
	}
	case FS_FULL_SIZE_INFORMATION:
	{
		struct smb2_fs_full_size_info *info;

		info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
		info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
		info->CallerAvailableAllocationUnits =
					cpu_to_le64(stfs.f_bavail);
		info->ActualAvailableAllocationUnits =
					cpu_to_le64(stfs.f_bfree);
		info->SectorsPerAllocationUnit = cpu_to_le32(1);
		info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
		rsp->OutputBufferLength = cpu_to_le32(32);
		fixed_len = 32;
		break;
	}
	case FS_OBJECT_ID_INFORMATION:
	{
		struct object_id_info *info;

		info = (struct object_id_info *)(rsp->Buffer);
		memset(info, 0, sizeof(*info));

		if (path.mnt->mnt_sb->s_uuid_len == 16)
			memcpy(info->objid, path.mnt->mnt_sb->s_uuid.b,
					path.mnt->mnt_sb->s_uuid_len);
		else
			memcpy(info->objid, &stfs.f_fsid, sizeof(stfs.f_fsid));

		info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
		info->extended_info.version = cpu_to_le32(1);
		info->extended_info.release = cpu_to_le32(1);
		info->extended_info.rel_date = 0;
		memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
		rsp->OutputBufferLength = cpu_to_le32(64);
		fixed_len = 64;
		break;
	}
	case FS_SECTOR_SIZE_INFORMATION:
	{
		struct smb3_fs_ss_info *info;
		unsigned int sector_size =
			min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);

		info = (struct smb3_fs_ss_info *)(rsp->Buffer);

		info->LogicalBytesPerSector = cpu_to_le32(sector_size);
		info->PhysicalBytesPerSectorForAtomicity =
				cpu_to_le32(sector_size);
		info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
		info->FSEffPhysicalBytesPerSectorForAtomicity =
				cpu_to_le32(sector_size);
		info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
				    SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE |
				    SSINFO_FLAGS_TRIM_ENABLED);
		info->ByteOffsetForSectorAlignment = 0;
		info->ByteOffsetForPartitionAlignment = 0;
		rsp->OutputBufferLength = cpu_to_le32(28);
		fixed_len = 28;
		break;
	}
	case FS_CONTROL_INFORMATION:
	{
		/*
		 * TODO : The current implementation is based on
		 * test result with win7(NTFS) server. It's need to
		 * modify this to get valid Quota values
		 * from Linux kernel
		 */
		struct smb2_fs_control_info *info;

		info = (struct smb2_fs_control_info *)(rsp->Buffer);
		info->FreeSpaceStartFiltering = 0;
		info->FreeSpaceThreshold = 0;
		info->FreeSpaceStopFiltering = 0;
		info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
		info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
		info->FileSystemControlFlags = 0;
		info->Padding = 0;
		rsp->OutputBufferLength = cpu_to_le32(48);
		fixed_len = 48;
		break;
	}
	case FS_POSIX_INFORMATION:
	{
		FILE_SYSTEM_POSIX_INFO *info;

		info = (FILE_SYSTEM_POSIX_INFO *)(rsp->Buffer);
		info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
		info->BlockSize = cpu_to_le32(stfs.f_frsize ?: stfs.f_bsize);
		info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
		info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
		info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
		info->TotalFileNodes = cpu_to_le64(stfs.f_files);
		info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
		info->FileSysIdentifier =
			cpu_to_le64((u64)(u32)stfs.f_fsid.val[1] << 32 |
				    (u32)stfs.f_fsid.val[0]);
		rsp->OutputBufferLength = cpu_to_le32(sizeof(*info));
		fixed_len = sizeof(*info);
		break;
	}
	default:
		path_put(&path);
		return -EOPNOTSUPP;
	}
	rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
			      fixed_len,
			      rsp);
	path_put(&path);

	if (!rc)
		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
				offsetof(struct smb2_query_info_rsp, Buffer) +
				le32_to_cpu(rsp->OutputBufferLength));
	return rc;
}

static int smb2_get_info_sec(struct ksmbd_work *work,
			     struct smb2_query_info_req *req,
			     struct smb2_query_info_rsp *rsp)
{
	struct ksmbd_file *fp;
	const struct mnt_idmap *idmap;
	struct smb_ntsd *pntsd = NULL, *ppntsd = NULL;
	struct smb_fattr fattr = {{0}};
	struct inode *inode;
	__u32 secdesclen = 0;
	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
	int addition_info = le32_to_cpu(req->AdditionalInformation);
	int rc = 0, ppntsd_size = 0, max_len;
	size_t scratch_len = 0;

	if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
			      PROTECTED_DACL_SECINFO |
			      UNPROTECTED_DACL_SECINFO)) {
		ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
		       addition_info);

		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
		return -EINVAL;
	}

	if (work->next_smb2_rcv_hdr_off) {
		if (!has_file_id(req->VolatileFileId)) {
			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
				    work->compound_fid);
			id = work->compound_fid;
			pid = work->compound_pfid;
		}
	}

	if (!has_file_id(id)) {
		id = req->VolatileFileId;
		pid = req->PersistentFileId;
	}

	fp = ksmbd_lookup_fd_slow(work, id, pid);
	if (!fp)
		return -ENOENT;

	if (addition_info & (OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO) &&
	    !(fp->daccess & FILE_READ_CONTROL_LE)) {
		ksmbd_fd_put(work, fp);
		return -EACCES;
	}

	if (le32_to_cpu(req->OutputBufferLength) < sizeof(struct smb_ntsd)) {
		rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
		ksmbd_fd_put(work, fp);
		return -ENOSPC;
	}

	idmap = file_mnt_idmap(fp->filp);
	inode = file_inode(fp->filp);
	rc = ksmbd_acls_fattr(&fattr, idmap, inode);
	if (rc) {
		ksmbd_fd_put(work, fp);
		return rc;
	}

	if (test_share_config_flag(work->tcon->share_conf,
				   KSMBD_SHARE_FLAG_ACL_XATTR))
		ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, idmap,
						     fp->filp->f_path.dentry,
						     &ppntsd);

	/* Check if sd buffer size exceeds response buffer size */
	max_len = smb2_calc_max_out_buf_len(work,
			offsetof(struct smb2_query_info_rsp, Buffer),
			le32_to_cpu(req->OutputBufferLength));
	if (max_len < 0) {
		rc = -EINVAL;
		goto release_acl;
	}

	scratch_len = smb_acl_sec_desc_scratch_len(&fattr, ppntsd,
			ppntsd_size, addition_info);
	if (!scratch_len || scratch_len == SIZE_MAX) {
		rc = -EFBIG;
		goto release_acl;
	}

	pntsd = kvzalloc(scratch_len, KSMBD_DEFAULT_GFP);
	if (!pntsd) {
		rc = -ENOMEM;
		goto release_acl;
	}

	rc = build_sec_desc(idmap, pntsd, ppntsd, ppntsd_size,
			addition_info, &secdesclen, &fattr);

release_acl:
	posix_acl_release(fattr.cf_acls);
	posix_acl_release(fattr.cf_dacls);
	kfree(ppntsd);
	ksmbd_fd_put(work, fp);

	if (!rc && ALIGN(secdesclen, 8) > scratch_len)
		rc = -EFBIG;
	if (rc)
		goto err_out;

	rsp->OutputBufferLength = cpu_to_le32(secdesclen);
	rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
			      le32_to_cpu(rsp->OutputBufferLength),
			      rsp);
	if (rc)
		goto err_out;

	rc = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
			offsetof(struct smb2_query_info_rsp, Buffer),
			pntsd, secdesclen);
err_out:
	if (rc) {
		rsp->OutputBufferLength = 0;
		kvfree(pntsd);
	}

	return rc;
}

/**
 * smb2_query_info() - handler for smb2 query info command
 * @work:	smb work containing query info request buffer
 *
 * Return:	0 on success, otherwise error
 */
int smb2_query_info(struct ksmbd_work *work)
{
	struct smb2_query_info_req *req;
	struct smb2_query_info_rsp *rsp;
	int rc = 0;

	ksmbd_debug(SMB, "Received request smb2 query info request\n");

	WORK_BUFFERS(work, req, rsp);

	if (smb2_compound_has_failed(work, &rsp->hdr))
		return -EACCES;

	if (ksmbd_override_fsids(work)) {
		rc = -ENOMEM;
		goto err_out;
	}

	rsp->StructureSize = cpu_to_le16(9);
	rsp->OutputBufferOffset = cpu_to_le16(72);

	switch (req->InfoType) {
	case SMB2_O_INFO_FILE:
		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
		rc = smb2_get_info_file(work, req, rsp);
		break;
	case SMB2_O_INFO_FILESYSTEM:
		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
		rc = smb2_get_info_filesystem(work, req, rsp);
		break;
	case SMB2_O_INFO_SECURITY:
		ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
		rc = smb2_get_info_sec(work, req, rsp);
		break;
	default:
		ksmbd_debug(SMB, "InfoType %d not supported yet\n",
			    req->InfoType);
		rc = -EOPNOTSUPP;
	}
	ksmbd_revert_fsids(work);

err_out:
	if (rc < 0) {
		if (rc == -EACCES)
			rsp->hdr.Status = STATUS_ACCESS_DENIED;
		else if (rc == -ENOENT)
			rsp->hdr.Status = STATUS_FILE_CLOSED;
		else if (rc == -EIO)
			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
		else if (rc == -ENOMEM)
			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
		else if (rc == -EINVAL && rsp->hdr.Status == 0)
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		else if (rsp->hdr.Status == 0)
			rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
		smb2_set_err_rsp(work);

		ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
			    rc);
		return rc;
	}
	return 0;
}

/**
 * smb2_close_pipe() - handler for closing IPC pipe
 * @work:	smb work containing close request buffer
 *
 * Return:	0
 */
static noinline int smb2_close_pipe(struct ksmbd_work *work)
{
	u64 id;
	struct smb2_close_req *req;
	struct smb2_close_rsp *rsp;

	WORK_BUFFERS(work, req, rsp);

	id = req->VolatileFileId;
	ksmbd_session_rpc_close(work->sess, id);

	rsp->StructureSize = cpu_to_le16(60);
	rsp->Flags = 0;
	rsp->Reserved = 0;
	rsp->CreationTime = 0;
	rsp->LastAccessTime = 0;
	rsp->LastWriteTime = 0;
	rsp->ChangeTime = 0;
	rsp->AllocationSize = 0;
	rsp->EndOfFile = 0;
	rsp->Attributes = 0;

	return ksmbd_iov_pin_rsp(work, (void *)rsp,
				 sizeof(struct smb2_close_rsp));
}

/**
 * smb2_close() - handler for smb2 close file command
 * @work:	smb work containing close request buffer
 *
 * Return:	0 on success, otherwise error
 */
int smb2_close(struct ksmbd_work *work)
{
	u64 volatile_id = KSMBD_NO_FID;
	u64 sess_id;
	struct smb2_close_req *req;
	struct smb2_close_rsp *rsp;
	struct ksmbd_file *fp;
	u64 time;
	int err = 0;

	ksmbd_debug(SMB, "Received smb2 close request\n");

	WORK_BUFFERS(work, req, rsp);

	if (smb2_compound_has_failed(work, &rsp->hdr))
		return -EACCES;

	if (test_share_config_flag(work->tcon->share_conf,
				   KSMBD_SHARE_FLAG_PIPE)) {
		ksmbd_debug(SMB, "IPC pipe close request\n");
		return smb2_close_pipe(work);
	}

	sess_id = le64_to_cpu(req->hdr.SessionId);
	if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
		sess_id = work->compound_sid;

	work->compound_sid = 0;
	if (work->sess && work->sess->id == sess_id) {
		work->compound_sid = sess_id;
	} else {
		rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
		if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		err = -EBADF;
		goto out;
	}

	if (work->next_smb2_rcv_hdr_off &&
	    !has_file_id(req->VolatileFileId)) {
		if (!has_file_id(work->compound_fid)) {
			/* file already closed, return FILE_CLOSED */
			ksmbd_debug(SMB, "file already closed\n");
			rsp->hdr.Status = STATUS_FILE_CLOSED;
			err = -EBADF;
			goto out;
		} else {
			ksmbd_debug(SMB,
				    "Compound request set FID = %llu:%llu\n",
				    work->compound_fid,
				    work->compound_pfid);
			volatile_id = work->compound_fid;

			/* file closed, stored id is not valid anymore */
			work->compound_fid = KSMBD_NO_FID;
			work->compound_pfid = KSMBD_NO_FID;
		}
	} else {
		volatile_id = req->VolatileFileId;
	}
	ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);

	rsp->StructureSize = cpu_to_le16(60);
	rsp->Reserved = 0;

	if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
		struct kstat stat;
		int ret;

		fp = ksmbd_lookup_fd_fast(work, volatile_id);
		if (!fp) {
			err = -ENOENT;
			goto out;
		}

		ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
				  AT_STATX_SYNC_AS_STAT);
		if (ret) {
			ksmbd_fd_put(work, fp);
			goto out;
		}

		rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
		rsp->AllocationSize = cpu_to_le64(fp->allocation_size);
		rsp->EndOfFile = cpu_to_le64(stat.size);
		rsp->Attributes = fp->f_ci->m_fattr;
		rsp->CreationTime = cpu_to_le64(fp->create_time);
		time = ksmbd_UnixTimeToNT(stat.atime);
		rsp->LastAccessTime = cpu_to_le64(time);
		time = ksmbd_UnixTimeToNT(stat.mtime);
		if (time > fp->open_mtime &&
		    time - fp->open_mtime < KSMBD_WRITE_TIME_RESOLUTION)
			time = fp->open_mtime;
		rsp->LastWriteTime = cpu_to_le64(time);
		rsp->ChangeTime = cpu_to_le64(fp->change_time);
		ksmbd_fd_put(work, fp);
	} else {
		rsp->Flags = 0;
		rsp->AllocationSize = 0;
		rsp->EndOfFile = 0;
		rsp->Attributes = 0;
		rsp->CreationTime = 0;
		rsp->LastAccessTime = 0;
		rsp->LastWriteTime = 0;
		rsp->ChangeTime = 0;
	}

	err = ksmbd_close_fd(work, volatile_id);
out:
	if (!err)
		err = ksmbd_iov_pin_rsp(work, (void *)rsp,
					sizeof(struct smb2_close_rsp));

	if (err) {
		if (rsp->hdr.Status == 0)
			rsp->hdr.Status = STATUS_FILE_CLOSED;
		smb2_set_err_rsp(work);
	}

	return err;
}

/**
 * smb2_echo() - handler for smb2 echo(ping) command
 * @work:	smb work containing echo request buffer
 *
 * Return:	0 on success, otherwise error
 */
int smb2_echo(struct ksmbd_work *work)
{
	struct smb2_echo_rsp *rsp = smb_get_msg(work->response_buf);

	ksmbd_debug(SMB, "Received smb2 echo request\n");

	if (work->next_smb2_rcv_hdr_off)
		rsp = ksmbd_resp_buf_next(work);

	rsp->StructureSize = cpu_to_le16(4);
	rsp->Reserved = 0;
	return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_echo_rsp));
}

static int smb2_rename(struct ksmbd_work *work,
		       struct ksmbd_file *fp,
		       struct smb2_file_rename_info *file_info,
		       struct nls_table *local_nls)
{
	struct ksmbd_share_config *share = fp->tcon->share_conf;
	char *new_name = NULL;
	int rc, flags = 0;

	ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
	new_name = smb2_get_name(file_info->FileName,
				 le32_to_cpu(file_info->FileNameLength),
				 local_nls);
	if (IS_ERR(new_name))
		return PTR_ERR(new_name);

	if (fp->is_posix_ctxt == false && strchr(new_name, ':')) {
		int s_type = 0;
		char *xattr_stream_name, *stream_name = NULL;
		char *stream_buf = NULL;
		size_t xattr_stream_size;
		ssize_t stream_buf_len = 0;
		int len;

		rc = parse_stream_name(new_name, &stream_name, &s_type);
		if (rc < 0)
			goto out;

		len = strlen(new_name);
		if (len > 0 && new_name[len - 1] != '/') {
			pr_err("not allow base filename in rename\n");
			rc = -ESHARE;
			goto out;
		}

		/* An empty stream name is the base file's default stream. */
		if (!stream_name || !stream_name[0])
			goto out;

		rc = ksmbd_vfs_xattr_stream_name(stream_name,
						 &xattr_stream_name,
						 &xattr_stream_size,
						 s_type);
		if (rc)
			goto out;

		/* A handle opened without a stream has no source to copy. */
		if (ksmbd_stream_fd(fp)) {
			if (!strcasecmp(xattr_stream_name, fp->stream.name)) {
				kfree(xattr_stream_name);
				goto out;
			}

			stream_buf_len = ksmbd_vfs_getcasexattr(file_mnt_idmap(fp->filp),
								fp->filp->f_path.dentry,
								fp->stream.name,
								fp->stream.size,
								&stream_buf);
			if (stream_buf_len < 0) {
				rc = stream_buf_len;
				kfree(xattr_stream_name);
				goto out;
			}
		}

		rc = ksmbd_vfs_setxattr(file_mnt_idmap(fp->filp),
					&fp->filp->f_path,
					xattr_stream_name,
					stream_buf, stream_buf_len, 0, true);
		kfree(stream_buf);
		if (rc < 0)
			pr_err("failed to store stream name in xattr: %d\n",
			       rc);

		kfree(xattr_stream_name);
		goto out;
	}

	ksmbd_debug(SMB, "new name %s\n", new_name);
	if (ksmbd_share_veto_filename(share, new_name)) {
		rc = -ENOENT;
		ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
		goto out;
	}

	if (!file_info->ReplaceIfExists)
		flags = RENAME_NOREPLACE;

	rc = ksmbd_vfs_check_rename_share(work, &fp->filp->f_path);
	if (rc)
		goto out;

	smb_break_all_levII_oplock_rename(work, fp);
	rc = ksmbd_vfs_rename(work, fp, new_name, flags);
out:
	kfree(new_name);
	return rc;
}

static int smb2_create_link(struct ksmbd_work *work,
			    struct ksmbd_share_config *share,
			    struct smb2_file_link_info *file_info,
			    unsigned int buf_len, struct file *filp,
			    struct nls_table *local_nls)
{
	char *link_name = NULL, *target_name = NULL, *pathname = NULL;
	struct path path;
	int rc;

	if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
			le32_to_cpu(file_info->FileNameLength))
		return -EINVAL;

	ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
	pathname = kmalloc(PATH_MAX, KSMBD_DEFAULT_GFP);
	if (!pathname)
		return -ENOMEM;

	link_name = smb2_get_name(file_info->FileName,
				  le32_to_cpu(file_info->FileNameLength),
				  local_nls);
	if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
		rc = -EINVAL;
		goto out;
	}

	ksmbd_debug(SMB, "link name is %s\n", link_name);
	target_name = file_path(filp, pathname, PATH_MAX);
	if (IS_ERR(target_name)) {
		rc = -EINVAL;
		goto out;
	}

	ksmbd_debug(SMB, "target name is %s\n", target_name);
	rc = ksmbd_vfs_kern_path_start_removing(work, link_name, LOOKUP_NO_SYMLINKS,
						&path, 0);
	if (rc) {
		if (rc != -ENOENT)
			goto out;
	} else {
		if (file_info->ReplaceIfExists) {
			rc = ksmbd_vfs_remove_file(work, &path);
			if (rc) {
				rc = -EINVAL;
				ksmbd_debug(SMB, "cannot delete %s\n",
					    link_name);
			}
		} else {
			rc = -EEXIST;
			ksmbd_debug(SMB, "link already exists\n");
		}
		ksmbd_vfs_kern_path_end_removing(&path);
		if (rc)
			goto out;
	}
	rc = ksmbd_vfs_link(work, target_name, link_name);
	if (rc)
		rc = -EINVAL;
out:

	if (!IS_ERR(link_name))
		kfree(link_name);
	kfree(pathname);
	return rc;
}

static int set_file_basic_info(struct ksmbd_file *fp,
			       struct file_basic_info *file_info,
			       struct ksmbd_share_config *share)
{
	struct iattr attrs;
	struct file *filp;
	struct inode *inode;
	const struct mnt_idmap *idmap;
	__le32 attrs_mask = FILE_ATTRIBUTE_DIRECTORY_LE |
		FILE_ATTRIBUTE_COMPRESSED_LE;
	int rc = 0;

	if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
		return -EACCES;

	attrs.ia_valid = 0;
	filp = fp->filp;
	inode = file_inode(filp);
	idmap = file_mnt_idmap(filp);

	/* MS-FSA FileBasicInformation: a directory can't be marked TEMPORARY */
	if (S_ISDIR(inode->i_mode) &&
	    (file_info->Attributes & FILE_ATTRIBUTE_TEMPORARY_LE))
		return -EINVAL;

	if (file_info->CreationTime)
		fp->create_time = le64_to_cpu(file_info->CreationTime);

	if (file_info->LastAccessTime) {
		attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
		attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
	}

	if (file_info->ChangeTime) {
		fp->change_time = le64_to_cpu(file_info->ChangeTime);
		inode_set_ctime_to_ts(inode,
				ksmbd_NTtimeToUnix(file_info->ChangeTime));
	}

	if (file_info->LastWriteTime) {
		attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
		attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET | ATTR_CTIME);
	}

	if (file_info->Attributes) {
		if (!S_ISDIR(inode->i_mode) &&
		    file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
			pr_err("can't change a file to a directory\n");
			return -EINVAL;
		}

		if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
			fp->f_ci->m_fattr =
				(file_info->Attributes & ~FILE_ATTRIBUTE_COMPRESSED_LE) |
				(fp->f_ci->m_fattr & attrs_mask);
	}

	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
	    (file_info->CreationTime || file_info->Attributes)) {
		struct xattr_dos_attrib da = {0};

		da.version = 4;
		da.itime = fp->itime;
		da.create_time = fp->create_time;
		da.attr = le32_to_cpu(fp->f_ci->m_fattr);
		da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
			XATTR_DOSINFO_ITIME;

		rc = ksmbd_vfs_set_dos_attrib_xattr(idmap, &filp->f_path, &da,
				true);
		if (rc)
			ksmbd_debug(SMB,
				    "failed to restore file attribute in EA\n");
		rc = 0;
	}

	if (attrs.ia_valid) {
		struct dentry *dentry = filp->f_path.dentry;
		struct inode *inode = d_inode(dentry);

		if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
			return -EACCES;

		inode_lock(inode);
		rc = notify_change(idmap, dentry, &attrs, NULL);
		inode_unlock(inode);
	}
	return rc;
}

static int set_file_allocation_info(struct ksmbd_work *work,
				    struct ksmbd_file *fp,
				    struct smb2_file_alloc_info *file_alloc_info)
{
	/*
	 * TODO : It's working fine only when store dos attributes
	 * is not yes. need to implement a logic which works
	 * properly with any smb.conf option
	 */

	u64 alloc_size, target, alloc_blks;
	u32 alloc_unit;
	struct inode *inode;
	struct kstat stat;
	struct kstatfs stfs;
	int rc;

	if (!(fp->daccess & FILE_WRITE_DATA_LE))
		return -EACCES;

	if (ksmbd_stream_fd(fp) == true)
		return 0;

	rc = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
			 AT_STATX_SYNC_AS_STAT);
	if (rc)
		return rc;
	rc = vfs_statfs(&fp->filp->f_path, &stfs);
	if (rc)
		return rc;

	/*
	 * Use the allocation unit advertised in FS_SIZE_INFORMATION.
	 * Reject requests that overflow when rounded to a whole unit.
	 */
	alloc_size = le64_to_cpu(file_alloc_info->AllocationSize);
	if (stfs.f_bsize <= 0 || (u64)stfs.f_bsize > U32_MAX)
		return -EINVAL;
	alloc_unit = stfs.f_bsize;
	if (alloc_size > MAX_LFS_FILESIZE - (alloc_unit - 1))
		return -EINVAL;

	target = DIV_ROUND_UP_ULL(alloc_size, alloc_unit) * alloc_unit;
	alloc_blks = DIV_ROUND_UP_ULL(target, 512);
	inode = file_inode(fp->filp);
	if (target > inode->i_sb->s_maxbytes)
		return -EINVAL;

	if (alloc_blks > stat.blocks) {
		smb_break_all_levII_oplock(work, fp, 1);
		rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0, target);
		if (rc && rc != -EOPNOTSUPP) {
			pr_err("vfs_fallocate is failed : %d\n", rc);
			return rc;
		}
	} else if (alloc_blks < stat.blocks &&
		   target <= i_size_read(inode)) {
		/*
		 * Truncate at or below EOF to discard excess allocation.
		 * Truncating above EOF would extend the file on disk.
		 */
		rc = ksmbd_vfs_truncate(work, fp, target);
		if (rc) {
			pr_err("truncate failed!, err %d\n", rc);
			return rc;
		}
	}

	fp->allocation_size = target;
	fp->allocation_size_set = true;
	return 0;
}

static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
				struct smb2_file_eof_info *file_eof_info)
{
	loff_t newsize;
	struct inode *inode;
	int rc;

	if (!(fp->daccess & FILE_WRITE_DATA_LE))
		return -EACCES;

	newsize = le64_to_cpu(file_eof_info->EndOfFile);
	inode = file_inode(fp->filp);
	if (ksmbd_stream_fd(fp))
		return ksmbd_vfs_stream_truncate(fp, newsize);

	/*
	 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
	 * on FAT32 shared device, truncate execution time is too long
	 * and network error could cause from windows client. because
	 * truncate of some filesystem like FAT32 fill zero data in
	 * truncated range.
	 */
	if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
		ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
		rc = ksmbd_vfs_truncate(work, fp, newsize);
		if (rc) {
			ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
			if (rc != -EAGAIN)
				rc = -EBADF;
			return rc;
		}
	}
	return 0;
}

static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
			   struct smb2_file_rename_info *rename_info,
			   unsigned int buf_len)
{
	if (!(fp->daccess & FILE_DELETE_LE)) {
		pr_err("no right to delete : 0x%x\n", fp->daccess);
		return -EACCES;
	}

	if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
			le32_to_cpu(rename_info->FileNameLength))
		return -EINVAL;

	if (!le32_to_cpu(rename_info->FileNameLength))
		return -EINVAL;

	return smb2_rename(work, fp, rename_info, work->conn->local_nls);
}

static int set_file_disposition_info(struct ksmbd_work *work,
				     struct ksmbd_file *fp,
				     struct smb2_file_disposition_info *file_info)
{
	struct inode *inode;
	int err;

	if (!(fp->daccess & FILE_DELETE_LE)) {
		pr_err("no right to delete : 0x%x\n", fp->daccess);
		return -EACCES;
	}

	if (fp->f_ci->m_fattr & FILE_ATTRIBUTE_READONLY_LE)
		return -EACCES;

	inode = file_inode(fp->filp);
	if (file_info->DeletePending) {
		if (ksmbd_has_stream_without_delete_share(fp))
			return -ESHARE;

		if (S_ISDIR(inode->i_mode) && !ksmbd_stream_fd(fp)) {
			mutex_lock(&fp->readdir_lock);
			err = ksmbd_vfs_empty_dir(fp);
			mutex_unlock(&fp->readdir_lock);
			if (err == -ENOTEMPTY)
				return -EBUSY;
		}
		smb_break_all_levII_oplock_for_delete(work, fp);
		ksmbd_fd_set_delete_pending(fp);
	} else {
		ksmbd_fd_clear_delete_pending(fp);
	}
	return 0;
}

static int set_file_position_info(struct ksmbd_file *fp,
				  struct smb2_file_pos_info *file_info)
{
	loff_t current_byte_offset;
	unsigned long sector_size;
	struct inode *inode;

	inode = file_inode(fp->filp);
	current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
	sector_size = inode->i_sb->s_blocksize;

	if (current_byte_offset < 0 ||
	    (fp->coption & FILE_NO_INTERMEDIATE_BUFFERING_LE &&
	     current_byte_offset & (sector_size - 1))) {
		pr_err("CurrentByteOffset is not valid : %llu\n",
		       current_byte_offset);
		return -EINVAL;
	}

	if (ksmbd_stream_fd(fp) == false)
		fp->filp->f_pos = current_byte_offset;
	else {
		if (current_byte_offset > XATTR_SIZE_MAX)
			current_byte_offset = XATTR_SIZE_MAX;
		fp->stream.pos = current_byte_offset;
	}
	return 0;
}

static int set_file_mode_info(struct ksmbd_file *fp,
			      struct smb2_file_mode_info *file_info)
{
	__le32 mode;

	mode = file_info->Mode;

	if ((mode & ~FILE_MODE_INFO_MASK)) {
		pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
		return -EINVAL;
	}

	/*
	 * TODO : need to implement consideration for
	 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
	 */
	ksmbd_vfs_set_fadvise(fp->filp, mode);
	fp->coption = mode;
	return 0;
}

/**
 * smb2_set_info_file() - handler for smb2 set info command
 * @work:	smb work containing set info command buffer
 * @fp:		ksmbd_file pointer
 * @req:	request buffer pointer
 * @share:	ksmbd_share_config pointer
 *
 * Return:	0 on success, otherwise error
 */
static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
			      struct smb2_set_info_req *req,
			      struct ksmbd_share_config *share)
{
	unsigned int buf_len = le32_to_cpu(req->BufferLength);
	char *buffer = (char *)req + le16_to_cpu(req->BufferOffset);

	switch (req->FileInfoClass) {
	case FILE_BASIC_INFORMATION:
	{
		if (buf_len < sizeof(struct file_basic_info))
			return -EMSGSIZE;

		return set_file_basic_info(fp, (struct file_basic_info *)buffer, share);
	}
	case FILE_ALLOCATION_INFORMATION:
	{
		if (buf_len < sizeof(struct smb2_file_alloc_info))
			return -EMSGSIZE;

		return set_file_allocation_info(work, fp,
						(struct smb2_file_alloc_info *)buffer);
	}
	case FILE_END_OF_FILE_INFORMATION:
	{
		if (buf_len < sizeof(struct smb2_file_eof_info))
			return -EMSGSIZE;

		return set_end_of_file_info(work, fp,
					    (struct smb2_file_eof_info *)buffer);
	}
	case FILE_RENAME_INFORMATION:
	{
		if (buf_len < sizeof(struct smb2_file_rename_info))
			return -EMSGSIZE;

		return set_rename_info(work, fp,
				       (struct smb2_file_rename_info *)buffer,
				       buf_len);
	}
	case FILE_LINK_INFORMATION:
	{
		struct smb2_file_link_info *file_info;

		if (buf_len < sizeof(struct smb2_file_link_info))
			return -EMSGSIZE;

		file_info = (struct smb2_file_link_info *)buffer;
		if (file_info->ReplaceIfExists && !(fp->daccess & FILE_DELETE_LE)) {
			pr_err("no right to delete : 0x%x\n", fp->daccess);
			return -EACCES;
		}

		return smb2_create_link(work, work->tcon->share_conf, file_info,
					buf_len, fp->filp,
					work->conn->local_nls);
	}
	case FILE_DISPOSITION_INFORMATION:
	{
		if (buf_len < sizeof(struct smb2_file_disposition_info))
			return -EMSGSIZE;

		return set_file_disposition_info(work, fp,
						 (struct smb2_file_disposition_info *)buffer);
	}
	case FILE_FULL_EA_INFORMATION:
	{
		if (!(fp->daccess & FILE_WRITE_EA_LE)) {
			pr_err("Not permitted to write ext  attr: 0x%x\n",
			       fp->daccess);
			return -EACCES;
		}

		if (buf_len < sizeof(struct smb2_ea_info))
			return -EMSGSIZE;

		return smb2_set_ea((struct smb2_ea_info *)buffer,
				   buf_len, &fp->filp->f_path, true);
	}
	case FILE_POSITION_INFORMATION:
	{
		if (buf_len < sizeof(struct smb2_file_pos_info))
			return -EMSGSIZE;

		return set_file_position_info(fp, (struct smb2_file_pos_info *)buffer);
	}
	case FILE_MODE_INFORMATION:
	{
		if (buf_len < sizeof(struct smb2_file_mode_info))
			return -EMSGSIZE;

		return set_file_mode_info(fp, (struct smb2_file_mode_info *)buffer);
	}
	}

	pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
	return -EOPNOTSUPP;
}

static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
			     char *buffer, int buf_len)
{
	struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;

	fp->saccess |= FILE_SHARE_DELETE_LE;

	if (!(fp->daccess & (FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE)))
		return -EACCES;

	return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
			buf_len, false, true,
			fp->conn->dialect == SMB311_PROT_ID && fp->is_posix_ctxt,
			addition_info & DACL_SECINFO);
}

/**
 * smb2_set_info() - handler for smb2 set info command handler
 * @work:	smb work containing set info request buffer
 *
 * Return:	0 on success, otherwise error
 */
int smb2_set_info(struct ksmbd_work *work)
{
	const struct cred *saved_cred;
	struct smb2_set_info_req *req;
	struct smb2_set_info_rsp *rsp;
	struct ksmbd_file *fp = NULL;
	int rc = 0;
	bool chseq_err = false;
	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;

	ksmbd_debug(SMB, "Received smb2 set info request\n");

	if (work->next_smb2_rcv_hdr_off) {
		req = ksmbd_req_buf_next(work);
		rsp = ksmbd_resp_buf_next(work);
		if (smb2_compound_has_failed(work, &rsp->hdr))
			return -EACCES;
		if (!has_file_id(req->VolatileFileId)) {
			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
				    work->compound_fid);
			id = work->compound_fid;
			pid = work->compound_pfid;
		}
	} else {
		req = smb_get_msg(work->request_buf);
		rsp = smb_get_msg(work->response_buf);
	}

	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
		ksmbd_debug(SMB, "User does not have write permission\n");
		pr_err("User does not have write permission\n");
		rc = -EACCES;
		goto err_out;
	}

	if (!has_file_id(id)) {
		id = req->VolatileFileId;
		pid = req->PersistentFileId;
	}

	fp = ksmbd_lookup_fd_slow(work, id, pid);
	if (!fp) {
		ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
		rc = -ENOENT;
		goto err_out;
	}

	rc = smb2_set_request_open(work, fp, &req->hdr, true, false);
	if (rc) {
		rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE;
		chseq_err = true;
		goto err_out;
	}

	saved_cred = override_creds(fp->filp->f_cred);
	switch (req->InfoType) {
	case SMB2_O_INFO_FILE:
		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
		rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
		break;
	case SMB2_O_INFO_SECURITY:
		ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
		rc = smb2_set_info_sec(fp,
				       le32_to_cpu(req->AdditionalInformation),
				       (char *)req + le16_to_cpu(req->BufferOffset),
				       le32_to_cpu(req->BufferLength));
		break;
	default:
		rc = -EOPNOTSUPP;
	}
	revert_creds(saved_cred);

	if (rc < 0)
		goto err_out;

	rsp->StructureSize = cpu_to_le16(2);
	rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
			       sizeof(struct smb2_set_info_rsp));
	if (rc)
		goto err_out;
	ksmbd_fd_put(work, fp);
	return 0;

err_out:
	if (rc == -EACCES || rc == -EPERM || rc == -EXDEV) {
		if (fp && req->InfoType == SMB2_O_INFO_FILE &&
		    req->FileInfoClass == FILE_DISPOSITION_INFORMATION &&
		    fp->f_ci->m_fattr & FILE_ATTRIBUTE_READONLY_LE)
			rsp->hdr.Status = STATUS_CANNOT_DELETE;
		else
			rsp->hdr.Status = STATUS_ACCESS_DENIED;
	}
	else if (rc == -EINVAL)
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
	else if (rc == -EBADMSG)
		rsp->hdr.Status = STATUS_EA_LIST_INCONSISTENT;
	else if (rc == -EMSGSIZE)
		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
	else if (rc == -ENOSPC || rc == -EFBIG)
		rsp->hdr.Status = STATUS_DISK_FULL;
	else if (rc == -ESHARE)
		rsp->hdr.Status = STATUS_SHARING_VIOLATION;
	else if (rc == -ENOENT)
		rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
	else if (rc == -EBUSY || rc == -ENOTEMPTY)
		rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
	else if (rc == -EAGAIN && !chseq_err)
		rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
	else if (rc == -EBADF || rc == -ESTALE)
		rsp->hdr.Status = STATUS_INVALID_HANDLE;
	else if (rc == -EEXIST)
		rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
	else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
		rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
	smb2_set_err_rsp(work);
	ksmbd_fd_put(work, fp);
	ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
	return rc;
}

static __le32 smb2_pipe_error_status(int err, __le32 fallback)
{
	switch (err) {
	case -ECANCELED:
		return STATUS_CANCELLED;
	case -ESHUTDOWN:
		return STATUS_CONNECTION_DISCONNECTED;
	case -EBADF:
	case -ENOENT:
		return STATUS_FILE_CLOSED;
	default:
		return fallback;
	}
}

static void smb2_pipe_response_done(struct ksmbd_session_rpc *rpc,
				    unsigned int nbytes)
{
	rpc->pending_offset += nbytes;
	if (rpc->pending_offset == rpc->pending->payload_sz) {
		kvfree(rpc->pending);
		rpc->pending = NULL;
		rpc->pending_offset = 0;
	}
}

/**
 * smb2_read_pipe() - handler for smb2 read from IPC pipe
 * @work:	smb work containing read IPC pipe command buffer
 *
 * Return:	0 on success, otherwise error
 */
static noinline int smb2_read_pipe(struct ksmbd_work *work)
{
	unsigned int nbytes = 0, length;
	u64 id;
	struct ksmbd_rpc_command *rpc_resp;
	struct ksmbd_session_rpc *rpc;
	struct smb2_read_req *req;
	struct smb2_read_rsp *rsp;
	void *aux_payload_buf;
	int err;

	WORK_BUFFERS(work, req, rsp);

	id = req->VolatileFileId;

	lockdep_assert_not_held(&work->sess->rpc_lock);
	down_read(&work->sess->rpc_lock);
	if (!ksmbd_session_rpc_method(work->sess, id)) {
		up_read(&work->sess->rpc_lock);
		rsp->hdr.Status = STATUS_FILE_CLOSED;
		smb2_set_err_rsp(work);
		return -ENOENT;
	}
	up_read(&work->sess->rpc_lock);

	rpc = ksmbd_session_rpc_get(work, id);
	if (IS_ERR(rpc)) {
		err = PTR_ERR(rpc);
		goto out;
	}

	length = le32_to_cpu(req->Length);
	if (!length)
		goto empty;

	if (!rpc->pending) {
		rpc_resp = ksmbd_rpc_read(work->sess, rpc);
		if (!rpc_resp) {
			err = -EIO;
			goto out_put;
		}
		if (rpc_resp->flags != KSMBD_RPC_OK) {
			kvfree(rpc_resp);
			err = -EINVAL;
			goto out_put;
		}
		rpc->pending = rpc_resp;
	}

	rpc_resp = rpc->pending;
	nbytes = min(length, rpc_resp->payload_sz - rpc->pending_offset);
	if (!nbytes) {
		smb2_pipe_response_done(rpc, 0);
		goto empty;
	}

	aux_payload_buf = kvmalloc(ALIGN(nbytes, 8), KSMBD_DEFAULT_GFP);
	if (!aux_payload_buf) {
		err = -ENOMEM;
		goto out_put;
	}
	memcpy(aux_payload_buf, rpc_resp->payload + rpc->pending_offset, nbytes);
	if (nbytes & 7)
		memset(aux_payload_buf + nbytes, 0, ALIGN(nbytes, 8) - nbytes);

	err = ksmbd_iov_pin_rsp_read(work, rsp,
				     offsetof(struct smb2_read_rsp, Buffer),
				     aux_payload_buf, nbytes);
	if (err) {
		kvfree(aux_payload_buf);
		goto out_put;
	}
	smb2_pipe_response_done(rpc, nbytes);
	if (rpc->pending)
		rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
	goto done;

empty:
	err = ksmbd_iov_pin_rsp(work, rsp,
				offsetof(struct smb2_read_rsp, Buffer));
	if (err)
		goto out_put;
done:
	rsp->StructureSize = cpu_to_le16(17);
	rsp->DataOffset = 80;
	rsp->Reserved = 0;
	rsp->DataLength = cpu_to_le32(nbytes);
	rsp->DataRemaining = 0;
	rsp->Flags = 0;
	ksmbd_session_rpc_put(rpc);
	return 0;

out_put:
	ksmbd_session_rpc_put(rpc);
out:
	rsp->hdr.Status = smb2_pipe_error_status(err,
						STATUS_UNEXPECTED_IO_ERROR);
	smb2_set_err_rsp(work);
	return err;
}

/**
 * smb2_set_rdma_key() - validate descriptors and save invalidation state
 * @work: request work item
 * @desc: first RDMA buffer descriptor
 * @Channel: nested RDMA channel type
 * @channel_info_len: descriptor array length
 *
 * Return: 0 on success, otherwise -EINVAL
 */
static int smb2_set_rdma_key(struct ksmbd_work *work,
			     struct smbdirect_buffer_descriptor_v1 *desc,
			     __le32 Channel, __le16 channel_info_len)
{
	unsigned int i, ch_count;

	if (Channel != SMB2_CHANNEL_RDMA_V1 &&
	    Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE)
		return -EINVAL;
	if (work->conn->dialect == SMB30_PROT_ID &&
	    Channel != SMB2_CHANNEL_RDMA_V1)
		return -EINVAL;
	if (le16_to_cpu(channel_info_len) % sizeof(*desc))
		return -EINVAL;

	ch_count = le16_to_cpu(channel_info_len) / sizeof(*desc);
	if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
		for (i = 0; i < ch_count; i++) {
			pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
				i,
				le32_to_cpu(desc[i].token),
				le32_to_cpu(desc[i].length));
		}
	}
	if (!ch_count)
		return -EINVAL;

	work->need_invalidate_rkey =
		(Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
	if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
		work->remote_key = le32_to_cpu(desc->token);
	return 0;
}

/**
 * smb2_prep_rdma_read() - transform an RDMA READ payload
 * @work: request work item
 * @req: READ request controlling encryption or signing
 * @rsp: READ response receiving transform metadata
 * @data: data that will be transferred through RDMA
 * @datalen: data length
 *
 * Encrypt the payload in place and encode the detached crypto metadata in
 * the response buffer.
 *
 * Return: metadata length, zero when no transform applies, or negative errno
 */
static int smb2_prep_rdma_read(struct ksmbd_work *work,
			       struct smb2_read_req *req,
			       struct smb2_read_rsp *rsp,
			       void *data, unsigned int datalen)
{
	struct ksmbd_conn *conn = work->conn;
	struct smb2_rdma_transform *transform;
	struct smb2_rdma_crypto_transform *crypto;
	u8 *nonce;
	unsigned int nonce_len = 0, transform_len;
	u16 transform_type;
	int err;

	if (!work->encrypted ||
	    !(conn->rdma_transform_ids & BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION)))
		return 0;

	transform_type = SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION;
	nonce_len = (conn->cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
		     conn->cipher_type == SMB2_ENCRYPTION_AES256_GCM) ?
		SMB3_AES_GCM_NONCE : SMB3_AES_CCM_NONCE;

	transform = (struct smb2_rdma_transform *)rsp->Buffer;
	crypto = (struct smb2_rdma_crypto_transform *)(transform + 1);
	memset(transform, 0, sizeof(*transform) + sizeof(*crypto) +
	       SMB2_SIGNATURE_SIZE + nonce_len);
	transform->Channel = SMB2_CHANNEL_NONE;
	transform->TransformCount = cpu_to_le16(1);

	crypto->TransformType = cpu_to_le16(transform_type);
	crypto->SignatureLength = cpu_to_le16(SMB2_SIGNATURE_SIZE);
	crypto->NonceLength = cpu_to_le16(nonce_len);
	nonce = crypto->Signature + SMB2_SIGNATURE_SIZE;

	get_random_bytes(nonce, nonce_len);
	err = ksmbd_crypt_rdma(conn,
			       work->sess->smb3encryptionkey,
			       data, datalen, nonce, nonce_len,
			       crypto->Signature,
			       SMB2_SIGNATURE_SIZE, true);
	if (err) {
		pr_err("RDMA READ encryption failed: session=%llu payload=%u rc=%d\n",
		       work->sess->id, datalen, err);
		return err;
	}

	transform_len = sizeof(*transform) + sizeof(*crypto) +
		SMB2_SIGNATURE_SIZE + nonce_len;
	rsp->Flags = SMB2_READFLAG_RESPONSE_RDMA_TRANSFORM;
	rsp->DataLength = cpu_to_le32(transform_len);
	ksmbd_debug(RDMA,
		    "RDMA READ encryption prepared: session=%llu cipher=0x%04x payload=%u transform=%u nonce=%u tag=%u\n",
		    work->sess->id, le16_to_cpu(conn->cipher_type), datalen,
		    transform_len, nonce_len, SMB2_SIGNATURE_SIZE);
	return transform_len;
}

struct smb2_rdma_write_transform {
	struct smbdirect_buffer_descriptor_v1 *desc;
	struct smb2_rdma_crypto_transform *crypto;
	u8 *nonce;
	unsigned int desc_len;
	unsigned int nonce_len;
	unsigned int signature_len;
	u16 type;
	__le32 channel;
};

/**
 * smb2_current_req_len() - return the current compound request element size
 * @work: request work item
 * @hdr: current SMB2 header
 *
 * Return: current request element length measured from the SMB2 header
 */
static unsigned int smb2_current_req_len(struct ksmbd_work *work,
					 struct smb2_hdr *hdr)
{
	if (hdr->NextCommand)
		return le32_to_cpu(hdr->NextCommand);
	return get_rfc1002_len(work->request_buf) -
		work->next_smb2_rcv_hdr_off;
}

/**
 * check_rdma_desc() - validate an RDMA descriptor array
 * @desc: descriptor array
 * @desc_len: descriptor array length
 * @required_len: minimum aggregate buffer length
 *
 * Return: 0 when the descriptors cover the transfer, otherwise -EINVAL
 */
static int check_rdma_desc(struct smbdirect_buffer_descriptor_v1 *desc,
			   unsigned int desc_len,
			   unsigned int required_len)
{
	unsigned int i, count;
	u64 described_len = 0;

	if (!desc_len || desc_len % sizeof(*desc))
		return -EINVAL;
	count = desc_len / sizeof(*desc);
	if (!le32_to_cpu(desc[0].length))
		return -EINVAL;
	for (i = 0; i < count; i++)
		described_len += le32_to_cpu(desc[i].length);
	return described_len < required_len ? -EINVAL : 0;
}

/**
 * smb2_parse_rdma_write_transform() - validate RDMA WRITE transform metadata
 * @work: request work item
 * @req: WRITE request containing the transform
 * @info: parsed transform information
 *
 * Validate transform counts, crypto fields, descriptor alignment and bounds,
 * negotiated algorithms, and the nested RDMA channel.
 *
 * Return: 0 on success, otherwise a negative errno
 */
static int smb2_parse_rdma_write_transform(struct ksmbd_work *work,
					   struct smb2_write_req *req,
					   struct smb2_rdma_write_transform *info)
{
	struct smb2_rdma_transform *transform;
	struct smb2_rdma_crypto_transform *crypto;
	unsigned int req_len = smb2_current_req_len(work, &req->hdr);
	unsigned int offset = le16_to_cpu(req->WriteChannelInfoOffset);
	unsigned int length = le16_to_cpu(req->WriteChannelInfoLength);
	unsigned int desc_offset, desc_len, crypto_len, expected_desc_offset;
	int err;

	if (!work->conn->rdma_transform_ids ||
	    offset < offsetof(struct smb2_write_req, Buffer) ||
	    length < sizeof(*transform) || offset > req_len ||
	    length > req_len - offset)
		return -EINVAL;

	transform = (struct smb2_rdma_transform *)((char *)req + offset);
	if (le16_to_cpu(transform->TransformCount) != 1 ||
	    (transform->Channel != SMB2_CHANNEL_RDMA_V1 &&
	     transform->Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE))
		return -EINVAL;

	desc_offset = le16_to_cpu(transform->RdmaDescriptorOffset);
	desc_len = le16_to_cpu(transform->RdmaDescriptorLength);
	if (!desc_len || desc_len % sizeof(*info->desc) ||
	    desc_offset < sizeof(*transform) || desc_offset > length ||
	    desc_len > length - desc_offset)
		return -EINVAL;

	crypto = (struct smb2_rdma_crypto_transform *)(transform + 1);
	if (length - sizeof(*transform) < sizeof(*crypto))
		return -EINVAL;
	info->type = le16_to_cpu(crypto->TransformType);
	info->signature_len = le16_to_cpu(crypto->SignatureLength);
	info->nonce_len = le16_to_cpu(crypto->NonceLength);
	if (!info->signature_len)
		return info->type == SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION ?
			-EBADMSG : -EINVAL;
	if (info->signature_len > SMB2_SIGNATURE_SIZE)
		return info->type == SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION ?
			-EBADMSG : -EINVAL;
	if (info->signature_len > length - sizeof(*transform) - sizeof(*crypto) ||
	    info->nonce_len > length - sizeof(*transform) - sizeof(*crypto) -
				 info->signature_len)
		return -EINVAL;

	crypto_len = sizeof(*crypto) + info->signature_len + info->nonce_len;
	expected_desc_offset = ALIGN(sizeof(*transform) + crypto_len, 8);
	if (desc_offset != expected_desc_offset)
		return -EINVAL;

	if (info->type == SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION) {
		unsigned int expected_nonce_len;

		if (!(work->conn->rdma_transform_ids &
		      BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION)) || !work->encrypted)
			return -EINVAL;
		expected_nonce_len =
			(work->conn->cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
			 work->conn->cipher_type == SMB2_ENCRYPTION_AES256_GCM) ?
			SMB3_AES_GCM_NONCE : SMB3_AES_CCM_NONCE;
		if (info->nonce_len != expected_nonce_len)
			return -EBADMSG;
	} else {
		return -EINVAL;
	}

	info->desc = (struct smbdirect_buffer_descriptor_v1 *)
		((char *)transform + desc_offset);
	info->desc_len = desc_len;
	info->crypto = crypto;
	info->nonce = crypto->Signature + info->signature_len;
	info->channel = transform->Channel;
	err = check_rdma_desc(info->desc, info->desc_len,
			      le32_to_cpu(req->RemainingBytes));
	if (err)
		return err;

	ksmbd_debug(RDMA,
		    "RDMA WRITE encryption metadata: session=%llu cipher=0x%04x payload=%u channel=0x%x descriptors=%zu nonce=%u tag=%u\n",
		    work->sess->id, le16_to_cpu(work->conn->cipher_type),
		    le32_to_cpu(req->RemainingBytes), le32_to_cpu(info->channel),
		    info->desc_len / sizeof(*info->desc), info->nonce_len,
		    info->signature_len);
	return 0;
}

/**
 * smb2_read_rdma() - transfer READ data to client RDMA buffers
 * @work: request work item
 * @req: READ request containing client descriptors
 * @data_buf: data to transfer
 * @length: data length
 *
 * Return: transferred length on success, otherwise a negative errno
 */
static ssize_t smb2_read_rdma(struct ksmbd_work *work,
			      struct smb2_read_req *req, void *data_buf,
			      size_t length)
{
	int err;

	err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
				    (struct smbdirect_buffer_descriptor_v1 *)
				    ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
				    le16_to_cpu(req->ReadChannelInfoLength));
	if (err)
		return err;

	return length;
}

/**
 * smb2_read() - handler for smb2 read from file
 * @work:	smb work containing read command buffer
 *
 * Return:	0 on success, otherwise error
 */
int smb2_read(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
	struct smb2_read_req *req;
	struct smb2_read_rsp *rsp;
	struct ksmbd_file *fp = NULL;
	loff_t offset;
	size_t length, mincount;
	ssize_t nbytes = 0, remain_bytes = 0;
	int err = 0;
	int rdma_transform_len = 0;
	bool is_rdma_channel = false, async_interim = false;
	unsigned int max_read_size = conn->vals->max_read_size;
	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
	void *aux_payload_buf;

	ksmbd_debug(SMB, "Received smb2 read request\n");

	if (test_share_config_flag(work->tcon->share_conf,
				   KSMBD_SHARE_FLAG_PIPE)) {
		ksmbd_debug(SMB, "IPC pipe read request\n");
		return smb2_read_pipe(work);
	}

	if (work->next_smb2_rcv_hdr_off) {
		req = ksmbd_req_buf_next(work);
		rsp = ksmbd_resp_buf_next(work);
		if (smb2_compound_has_failed(work, &rsp->hdr))
			return -EACCES;
		if (!has_file_id(req->VolatileFileId)) {
			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
					work->compound_fid);
			id = work->compound_fid;
			pid = work->compound_pfid;
		}
	} else {
		req = smb_get_msg(work->request_buf);
		rsp = smb_get_msg(work->response_buf);
	}

	if (!has_file_id(id)) {
		id = req->VolatileFileId;
		pid = req->PersistentFileId;
	}

	if (req->Channel != SMB2_CHANNEL_NONE &&
	    req->Channel != SMB2_CHANNEL_RDMA_V1 &&
	    req->Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
		err = -EINVAL;
		goto out;
	}
	if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
	    req->Channel == SMB2_CHANNEL_RDMA_V1) {
		is_rdma_channel = true;
		max_read_size = get_smbd_max_read_write_size(work->conn->transport);
		if (max_read_size == 0) {
			err = -EINVAL;
			goto out;
		}
	}

	if (is_rdma_channel == true) {
		unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
		unsigned int ch_len = le16_to_cpu(req->ReadChannelInfoLength);
		unsigned int req_len = smb2_current_req_len(work, &req->hdr);
		struct smbdirect_buffer_descriptor_v1 *desc;

		if (!le32_to_cpu(req->Length) ||
		    ch_offset < offsetof(struct smb2_read_req, Buffer) ||
		    ch_offset > req_len || ch_len > req_len - ch_offset) {
			err = -EINVAL;
			goto out;
		}
		desc = (struct smbdirect_buffer_descriptor_v1 *)
			((char *)req + ch_offset);
		err = check_rdma_desc(desc, ch_len, le32_to_cpu(req->Length));
		if (err)
			goto out;
		err = smb2_set_rdma_key(work, desc,
					req->Channel,
					req->ReadChannelInfoLength);
		if (err)
			goto out;
	}

	fp = ksmbd_lookup_fd_slow(work, id, pid);
	if (!fp) {
		err = -ENOENT;
		goto out;
	}

	err = smb2_set_request_open(work, fp, &req->hdr, true, true);
	if (err)
		goto out;

	if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
		pr_err("Not permitted to read : 0x%x\n", fp->daccess);
		err = -EACCES;
		goto out;
	}

	if (work->next_smb2_rcv_hdr_off && !req->hdr.NextCommand) {
		err = setup_async_work(work, NULL, NULL);
		if (err)
			goto out;
		smb2_send_interim_resp(work, STATUS_PENDING);
		async_interim = true;
	}

	offset = le64_to_cpu(req->Offset);
	if (offset < 0) {
		err = -EINVAL;
		goto out;
	}
	length = le32_to_cpu(req->Length);
	mincount = le32_to_cpu(req->MinimumCount);

	if (length > max_read_size) {
		ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
			    max_read_size);
		err = -EINVAL;
		goto out;
	}

	ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
		    fp->filp, offset, length);

	aux_payload_buf = kvmalloc(ALIGN(length, 8), KSMBD_DEFAULT_GFP);
	if (!aux_payload_buf) {
		err = -ENOMEM;
		goto out;
	}

	nbytes = ksmbd_vfs_read(work, fp, length, &offset, aux_payload_buf);
	if (nbytes < 0) {
		kvfree(aux_payload_buf);
		err = nbytes;
		goto out;
	}

	/*
	 * ksmbd_vfs_read() fills only nbytes; the [nbytes, ALIGN(nbytes, 8))
	 * tail of the un-zeroed buffer is transmitted as compound-response
	 * alignment padding, leaking uninitialized kernel memory to the
	 * client.  Zero just that tail.
	 */
	if (nbytes & 7)
		memset(aux_payload_buf + nbytes, 0, ALIGN(nbytes, 8) - nbytes);

	if ((nbytes == 0 && length != 0) || nbytes < mincount) {
		kvfree(aux_payload_buf);
		rsp->hdr.Status = STATUS_END_OF_FILE;
		smb2_set_err_rsp(work);
		if (async_interim)
			release_async_work(work);
		ksmbd_fd_put(work, fp);
		return -ENODATA;
	}

	ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
		    nbytes, offset, mincount);

	if (is_rdma_channel == true) {
		rdma_transform_len = smb2_prep_rdma_read(work, req,
							 rsp,
							 aux_payload_buf,
							 nbytes);
		if (rdma_transform_len < 0) {
			kvfree(aux_payload_buf);
			err = rdma_transform_len;
			goto out;
		}
		/* write data to the client using rdma channel */
		remain_bytes = smb2_read_rdma(work, req,
					      aux_payload_buf,
					      nbytes);
		if (remain_bytes < 0)
			pr_err("RDMA READ transfer failed: session=%llu payload=%zu transform=%d rc=%zd\n",
			       work->sess ? work->sess->id : 0, nbytes,
			       rdma_transform_len, remain_bytes);
		else
			ksmbd_debug(RDMA,
				    "RDMA READ transfer completed: session=%llu payload=%zu transform=%d\n",
				    work->sess ? work->sess->id : 0, nbytes,
				    rdma_transform_len);
		kvfree(aux_payload_buf);
		aux_payload_buf = NULL;
		nbytes = 0;
		if (remain_bytes < 0) {
			err = (int)remain_bytes;
			goto out;
		}
	}

	rsp->StructureSize = cpu_to_le16(17);
	rsp->DataOffset = 80;
	rsp->Reserved = 0;
	rsp->DataLength = cpu_to_le32(rdma_transform_len ?: nbytes);
	rsp->DataRemaining = cpu_to_le32(remain_bytes);
	rsp->Flags = rdma_transform_len ?
		SMB2_READFLAG_RESPONSE_RDMA_TRANSFORM : 0;
	err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
				     offsetof(struct smb2_read_rsp, Buffer) +
				     rdma_transform_len,
				     aux_payload_buf, nbytes);
	if (err) {
		kvfree(aux_payload_buf);
		goto out;
	}
	if (async_interim)
		release_async_work(work);
	/*
	 * RDMA responses are transferred through channel buffers and encrypted
	 * responses use the encryption transform, so only normal SMB transport
	 * responses are candidates for compression.
	 */
	if (!is_rdma_channel && nbytes &&
	    (req->Flags & SMB2_READFLAG_REQUEST_COMPRESSED) &&
	    conn->compress_algorithm != SMB3_COMPRESS_NONE)
		work->compress_response = true;
	ksmbd_fd_put(work, fp);
	return 0;

out:
	if (async_interim)
		release_async_work(work);
	if (err) {
		if (err == -EISDIR)
			rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
		else if (err == -EAGAIN)
			rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
		else if (err == -ENOENT)
			rsp->hdr.Status = STATUS_FILE_CLOSED;
		else if (err == -EACCES)
			rsp->hdr.Status = STATUS_ACCESS_DENIED;
		else if (err == -ESHARE)
			rsp->hdr.Status = STATUS_SHARING_VIOLATION;
		else if (err == -EINVAL)
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		else
			rsp->hdr.Status = STATUS_INVALID_HANDLE;

		smb2_set_err_rsp(work);
	}
	ksmbd_fd_put(work, fp);
	return err;
}

/**
 * smb2_write_pipe() - handler for smb2 write on IPC pipe
 * @work:	smb work containing write IPC pipe command buffer
 *
 * Return:	0 on success, otherwise error
 */
static noinline int smb2_write_pipe(struct ksmbd_work *work)
{
	struct smb2_write_req *req;
	struct smb2_write_rsp *rsp;
	struct ksmbd_rpc_command *rpc_resp;
	struct ksmbd_session_rpc *rpc;
	u64 id = 0;
	int err = 0, ret = 0;
	char *data_buf;
	size_t length;
	unsigned int data_offset, req_len;

	WORK_BUFFERS(work, req, rsp);

	length = le32_to_cpu(req->Length);
	id = req->VolatileFileId;
	data_offset = le16_to_cpu(req->DataOffset);
	req_len = smb2_current_req_len(work, &req->hdr);

	if (data_offset < offsetof(struct smb2_write_req, Buffer) ||
	    data_offset > req_len || length > req_len - data_offset) {
		pr_err("invalid write data offset %u, length %zu, req_len %u\n",
		       data_offset, length, req_len);
		err = -EINVAL;
		goto out;
	}

	lockdep_assert_not_held(&work->sess->rpc_lock);
	down_read(&work->sess->rpc_lock);
	if (!ksmbd_session_rpc_method(work->sess, id)) {
		up_read(&work->sess->rpc_lock);
		rsp->hdr.Status = STATUS_FILE_CLOSED;
		smb2_set_err_rsp(work);
		return -ENOENT;
	}
	up_read(&work->sess->rpc_lock);

	data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
			   data_offset);

	rpc = ksmbd_session_rpc_get(work, id);
	if (IS_ERR(rpc)) {
		err = PTR_ERR(rpc);
		rsp->hdr.Status = smb2_pipe_error_status(err,
							 STATUS_INVALID_HANDLE);
		smb2_set_err_rsp(work);
		return err;
	}
	rpc_resp = ksmbd_rpc_write(work->sess, rpc, data_buf, length);
	ksmbd_session_rpc_put(rpc);
	if (!rpc_resp) {
		rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
		smb2_set_err_rsp(work);
		return -EIO;
	}
	if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
		kvfree(rpc_resp);
		smb2_set_err_rsp(work);
		return -EOPNOTSUPP;
	}
	if (rpc_resp->flags != KSMBD_RPC_OK) {
		rsp->hdr.Status = STATUS_INVALID_HANDLE;
		smb2_set_err_rsp(work);
		kvfree(rpc_resp);
		return ret;
	}
	kvfree(rpc_resp);

	rsp->StructureSize = cpu_to_le16(17);
	rsp->DataOffset = 0;
	rsp->Reserved = 0;
	rsp->DataLength = cpu_to_le32(length);
	rsp->DataRemaining = 0;
	rsp->Reserved2 = 0;
	err = ksmbd_iov_pin_rsp(work, (void *)rsp,
				offsetof(struct smb2_write_rsp, Buffer));
out:
	if (err) {
		rsp->hdr.Status = STATUS_INVALID_HANDLE;
		smb2_set_err_rsp(work);
	}

	return err;
}

/**
 * smb2_write_rdma() - receive and store an RDMA WRITE payload
 * @work: request work item
 * @desc: client RDMA buffer descriptors
 * @desc_len: descriptor array length
 * @transform: parsed transform, or NULL for an untransformed transfer
 * @fp: target open file
 * @offset: target file offset
 * @length: transfer length
 * @sync: request synchronous storage completion
 *
 * Receive the payload, authenticate or decrypt it when required, and write it
 * to the target file.
 *
 * Return: written byte count on success, otherwise a negative errno
 */
static ssize_t smb2_write_rdma(struct ksmbd_work *work,
			       struct smbdirect_buffer_descriptor_v1 *desc,
			       unsigned int desc_len,
			       struct smb2_rdma_write_transform *transform,
			       struct ksmbd_file *fp, loff_t offset,
			       size_t length, bool sync)
{
	char *data_buf;
	int ret;
	ssize_t nbytes;

	data_buf = kvzalloc(length, KSMBD_DEFAULT_GFP);
	if (!data_buf)
		return -ENOMEM;

	ret = ksmbd_conn_rdma_read(work->conn, data_buf, length, desc,
				   desc_len);
	if (ret < 0) {
		if (transform)
			pr_err("RDMA WRITE encrypted transfer failed: session=%llu payload=%zu rdma_read_rc=%d\n",
			       work->sess->id, length, ret);
		kvfree(data_buf);
		return ret;
	}
	if (transform &&
	    transform->type == SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION) {
		ret = ksmbd_crypt_rdma(work->conn,
				       work->sess->smb3decryptionkey,
				       data_buf, length, transform->nonce,
				       transform->nonce_len,
				       transform->crypto->Signature,
				       transform->signature_len, false);
		if (ret) {
			pr_err("RDMA WRITE decryption failed: session=%llu payload=%zu rc=%d\n",
			       work->sess->id, length, ret);
			kvfree(data_buf);
			return ret == -ENOMEM ? ret : -EBADMSG;
		}
	}

	ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
	kvfree(data_buf);
	if (ret < 0) {
		if (transform)
			pr_err("RDMA WRITE encrypted file write failed: session=%llu payload=%zu rc=%d\n",
			       work->sess->id, length, ret);
		return ret;
	}
	ksmbd_debug(RDMA,
		    "RDMA WRITE transfer completed: session=%llu payload=%zu transformed=%u written=%zd\n",
		    work->sess ? work->sess->id : 0, length, !!transform, nbytes);

	return nbytes;
}

/**
 * smb2_write() - handler for smb2 write from file
 * @work:	smb work containing write command buffer
 *
 * Return:	0 on success, otherwise error
 */
int smb2_write(struct ksmbd_work *work)
{
	struct smb2_write_req *req;
	struct smb2_write_rsp *rsp;
	struct smb2_rdma_write_transform rdma_transform = {};
	struct smb2_rdma_write_transform *rdma_info = NULL;
	struct smbdirect_buffer_descriptor_v1 *rdma_desc = NULL;
	unsigned int rdma_desc_len = 0;
	struct ksmbd_file *fp = NULL;
	loff_t offset;
	size_t length;
	ssize_t nbytes;
	char *data_buf;
	bool writethrough = false, is_rdma_channel = false;
	bool append_write;
	bool async_interim = false;
	bool chseq_err = false;
	int err = 0;
	unsigned int max_write_size = work->conn->vals->max_write_size;
	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;

	ksmbd_debug(SMB, "Received smb2 write request\n");

	WORK_BUFFERS(work, req, rsp);

	if (smb2_compound_has_failed(work, &rsp->hdr))
		return -EACCES;

	if (work->next_smb2_rcv_hdr_off &&
	    !has_file_id(req->VolatileFileId)) {
		ksmbd_debug(SMB, "Compound request set FID = %llu\n",
			    work->compound_fid);
		id = work->compound_fid;
		pid = work->compound_pfid;
	}

	if (!has_file_id(id)) {
		id = req->VolatileFileId;
		pid = req->PersistentFileId;
	}

	if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
		ksmbd_debug(SMB, "IPC pipe write request\n");
		return smb2_write_pipe(work);
	}

	append_write = le64_to_cpu(req->Offset) == U64_MAX;
	offset = append_write ? 0 : le64_to_cpu(req->Offset);
	if (offset < 0) {
		err = -EINVAL;
		goto out;
	}
	length = le32_to_cpu(req->Length);

	if (req->Channel != SMB2_CHANNEL_NONE &&
	    req->Channel != SMB2_CHANNEL_RDMA_V1 &&
	    req->Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE &&
	    req->Channel != SMB2_CHANNEL_RDMA_TRANSFORM) {
		err = -EINVAL;
		goto out;
	}
	if (req->Channel == SMB2_CHANNEL_RDMA_TRANSFORM &&
	    work->conn->dialect != SMB311_PROT_ID) {
		err = -EINVAL;
		goto out;
	}
	if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
	    req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
	    req->Channel == SMB2_CHANNEL_RDMA_TRANSFORM) {
		is_rdma_channel = true;
		max_write_size = get_smbd_max_read_write_size(work->conn->transport);
		if (max_write_size == 0) {
			err = -EINVAL;
			goto out;
		}
		length = le32_to_cpu(req->RemainingBytes);
	}

	if (length) {
		u64 end = (u64)offset + length;

		if (end > SMB2_MAX_FILE_SIZE) {
			err = -EINVAL;
			goto out;
		}
		if (end == SMB2_MAX_FILE_SIZE) {
			err = -EFBIG;
			goto out;
		}
	}

	if (is_rdma_channel == true) {
		unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
		unsigned int ch_len = le16_to_cpu(req->WriteChannelInfoLength);
		unsigned int req_len = smb2_current_req_len(work, &req->hdr);

		if (!length || req->Length != 0 || req->DataOffset != 0 ||
		    ch_offset < offsetof(struct smb2_write_req, Buffer) ||
		    ch_offset > req_len || ch_len > req_len - ch_offset) {
			err = -EINVAL;
			goto out;
		}
		if (req->Channel == SMB2_CHANNEL_RDMA_TRANSFORM) {
			err = smb2_parse_rdma_write_transform(work, req,
							      &rdma_transform);
			if (err) {
				pr_err("RDMA WRITE encryption metadata rejected: session=%llu rc=%d\n",
				       work->sess ? work->sess->id : 0, err);
				goto out;
			}
			rdma_desc = rdma_transform.desc;
			rdma_desc_len = rdma_transform.desc_len;
			rdma_info = &rdma_transform;
			err = smb2_set_rdma_key(work, rdma_desc,
						rdma_transform.channel,
						cpu_to_le16(rdma_desc_len));
		} else {
			rdma_desc = (struct smbdirect_buffer_descriptor_v1 *)
				((char *)req + ch_offset);
			rdma_desc_len = ch_len;
			err = check_rdma_desc(rdma_desc, rdma_desc_len, length);
			if (err)
				goto out;
			err = smb2_set_rdma_key(work, rdma_desc,
						req->Channel,
						req->WriteChannelInfoLength);
		}
		if (err)
			goto out;
	}

	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
		ksmbd_debug(SMB, "User does not have write permission\n");
		err = -EACCES;
		goto out;
	}

	fp = ksmbd_lookup_fd_slow(work, id, pid);
	if (!fp) {
		err = -ENOENT;
		goto out;
	}

	err = smb2_set_request_open(work, fp, &req->hdr, true, false);
	if (err) {
		rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE;
		chseq_err = true;
		goto out;
	}

	if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_APPEND_DATA_LE))) {
		pr_err("Not permitted to write : 0x%x\n", fp->daccess);
		err = -EACCES;
		goto out;
	}
	if (append_write != fp->posix_append) {
		err = -EINVAL;
		goto out;
	}

	if (work->next_smb2_rcv_hdr_off && !req->hdr.NextCommand) {
		err = setup_async_work(work, NULL, NULL);
		if (err)
			goto out;
		smb2_send_interim_resp(work, STATUS_PENDING);
		async_interim = true;
	}

	if (length > max_write_size) {
		ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
			    max_write_size);
		err = -EINVAL;
		goto out;
	}

	ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
	if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
		writethrough = true;

	if (is_rdma_channel == false) {
		unsigned int data_offset = le16_to_cpu(req->DataOffset);
		unsigned int req_len = smb2_current_req_len(work, &req->hdr);

		if (data_offset < offsetof(struct smb2_write_req, Buffer) ||
		    data_offset > req_len ||
		    length > req_len - data_offset) {
			ksmbd_debug(SMB,
				    "invalid write data offset %u, length %zu, req_len %u\n",
				    data_offset, length, req_len);
			err = -EINVAL;
			goto out;
		}

		data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
				    data_offset);

		ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
			    fp->filp, offset, length);
		err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
				      writethrough, &nbytes);
		if (err < 0)
			goto out;
	} else {
		/* read data from the client using rdma channel, and
		 * write the data.
		 */
		nbytes = smb2_write_rdma(work, rdma_desc, rdma_desc_len,
					 rdma_info, fp, offset, length,
					 writethrough);
		if (nbytes < 0) {
			err = (int)nbytes;
			goto out;
		}
	}

	rsp->StructureSize = cpu_to_le16(17);
	rsp->DataOffset = 0;
	rsp->Reserved = 0;
	rsp->DataLength = cpu_to_le32(nbytes);
	rsp->DataRemaining = 0;
	rsp->Reserved2 = 0;
	err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_write_rsp, Buffer));
	if (err)
		goto out;
	if (async_interim)
		release_async_work(work);
	ksmbd_fd_put(work, fp);
	return 0;

out:
	if (async_interim)
		release_async_work(work);

	if (err == -EAGAIN && !chseq_err)
		rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
	else if (err == -ENOSPC || err == -EFBIG)
		rsp->hdr.Status = STATUS_DISK_FULL;
	else if (err == -ENOENT)
		rsp->hdr.Status = STATUS_FILE_CLOSED;
	else if (err == -EACCES)
		rsp->hdr.Status = STATUS_ACCESS_DENIED;
	else if (err == -ESHARE)
		rsp->hdr.Status = STATUS_SHARING_VIOLATION;
	else if (err == -EINVAL)
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
	else if (err == -EBADMSG)
		rsp->hdr.Status = STATUS_AUTH_TAG_MISMATCH;
	else if (err == -EKEYREJECTED)
		rsp->hdr.Status = STATUS_INVALID_SIGNATURE;
	else if (rsp->hdr.Status == 0)
		rsp->hdr.Status = STATUS_INVALID_HANDLE;

	smb2_set_err_rsp(work);
	ksmbd_fd_put(work, fp);
	return err;
}

/**
 * smb2_flush() - handler for smb2 flush file - fsync
 * @work:	smb work containing flush command buffer
 *
 * Return:	0 on success, otherwise error
 */
int smb2_flush(struct ksmbd_work *work)
{
	struct smb2_flush_req *req;
	struct smb2_flush_rsp *rsp;
	u64 id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
	int err;

	WORK_BUFFERS(work, req, rsp);

	ksmbd_debug(SMB, "Received smb2 flush request(fid : %llu)\n", req->VolatileFileId);

	if (smb2_compound_has_failed(work, &rsp->hdr))
		return -EACCES;

	if (work->next_smb2_rcv_hdr_off &&
	    !has_file_id(req->VolatileFileId)) {
		ksmbd_debug(SMB, "Compound request set FID = %llu\n",
			    work->compound_fid);
		id = work->compound_fid;
		pid = work->compound_pfid;
	}

	if (!has_file_id(id)) {
		id = req->VolatileFileId;
		pid = req->PersistentFileId;
	}

	err = ksmbd_vfs_fsync(work, id, pid);
	if (err)
		goto out;

	rsp->StructureSize = cpu_to_le16(4);
	rsp->Reserved = 0;
	return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_flush_rsp));

out:
	rsp->hdr.Status = STATUS_INVALID_HANDLE;
	smb2_set_err_rsp(work);
	return err;
}

/**
 * smb2_cancel() - handler for smb2 cancel command
 * @work:	smb work containing cancel command buffer
 *
 * Return:	0 on success, otherwise error
 */
int smb2_cancel(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
	struct smb2_hdr *chdr;
	struct ksmbd_work *iter;
	struct list_head *command_list;

	if (work->next_smb2_rcv_hdr_off)
		hdr = ksmbd_resp_buf_next(work);

	ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
		    le64_to_cpu(hdr->MessageId),
		    le32_to_cpu(hdr->Flags));

	if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
		command_list = &conn->async_requests;

		spin_lock(&conn->request_lock);
		list_for_each_entry(iter, command_list,
				    async_request_entry) {
			chdr = smb_get_msg(iter->request_buf);

			if (iter->async_id !=
			    le64_to_cpu(hdr->Id.AsyncId))
				continue;

			/*
			 * Only an ACTIVE deferred work may have its cancel_fn
			 * fired.  A CANCELLED or CLOSED work already took the
			 * smb2_lock() non-ACTIVE early-exit that frees the
			 * file_lock and skips release_async_work(), so it is
			 * still on conn->async_requests with a live cancel_fn
			 * pointing at the freed file_lock.
			 */
			if (cmpxchg(&iter->state, KSMBD_WORK_ACTIVE,
				    KSMBD_WORK_CANCELLED) != KSMBD_WORK_ACTIVE)
				break;

			ksmbd_debug(SMB,
				    "smb2 with AsyncId %llu cancelled command = 0x%x\n",
				    le64_to_cpu(hdr->Id.AsyncId),
				    le16_to_cpu(chdr->Command));
			if (iter->cancel_fn)
				iter->cancel_fn(iter->cancel_argv);
			break;
		}
		spin_unlock(&conn->request_lock);
	} else {
		command_list = &conn->requests;

		spin_lock(&conn->request_lock);
		list_for_each_entry(iter, command_list, request_entry) {
			chdr = smb_get_msg(iter->request_buf);

			if (chdr->MessageId != hdr->MessageId ||
			    iter == work)
				continue;

			if (cmpxchg(&iter->state, KSMBD_WORK_ACTIVE,
				    KSMBD_WORK_CANCELLED) != KSMBD_WORK_ACTIVE)
				break;

			ksmbd_debug(SMB,
				    "smb2 with mid %llu cancelled command = 0x%x\n",
				    le64_to_cpu(hdr->MessageId),
				    le16_to_cpu(chdr->Command));
			if (iter->cancel_fn)
				iter->cancel_fn(iter->cancel_argv);
			break;
		}
		spin_unlock(&conn->request_lock);
	}

	/* For SMB2_CANCEL command itself send no response*/
	work->send_no_response = 1;
	return 0;
}

struct file_lock *smb_flock_init(struct file *f)
{
	struct file_lock *fl;

	fl = locks_alloc_lock();
	if (!fl)
		goto out;

	locks_init_lock(fl);

	fl->c.flc_owner = f;
	fl->c.flc_pid = current->tgid;
	fl->c.flc_file = f;
	fl->c.flc_flags = FL_POSIX;
	fl->fl_ops = NULL;
	fl->fl_lmops = NULL;

out:
	return fl;
}

static int smb2_set_flock_flags(struct file_lock *flock, int flags)
{
	int cmd = -EINVAL;

	/* Checking for wrong flag combination during lock request*/
	switch (flags) {
	case SMB2_LOCKFLAG_SHARED:
		ksmbd_debug(SMB, "received shared request\n");
		cmd = F_SETLKW;
		flock->c.flc_type = F_RDLCK;
		flock->c.flc_flags |= FL_SLEEP;
		break;
	case SMB2_LOCKFLAG_EXCLUSIVE:
		ksmbd_debug(SMB, "received exclusive request\n");
		cmd = F_SETLKW;
		flock->c.flc_type = F_WRLCK;
		flock->c.flc_flags |= FL_SLEEP;
		break;
	case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
		ksmbd_debug(SMB,
			    "received shared & fail immediately request\n");
		cmd = F_SETLK;
		flock->c.flc_type = F_RDLCK;
		break;
	case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
		ksmbd_debug(SMB,
			    "received exclusive & fail immediately request\n");
		cmd = F_SETLK;
		flock->c.flc_type = F_WRLCK;
		break;
	case SMB2_LOCKFLAG_UNLOCK:
		ksmbd_debug(SMB, "received unlock request\n");
		flock->c.flc_type = F_UNLCK;
		cmd = F_SETLK;
		break;
	}

	return cmd;
}

/* Track SMB locks that cannot be represented by a signed loff_t. */
static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
					 unsigned int cmd, int flags, bool zero_len,
					 u64 start, u64 end, bool virtual_lock,
					 struct list_head *lock_list)
{
	struct ksmbd_lock *lock;

	lock = kzalloc_obj(struct ksmbd_lock, KSMBD_DEFAULT_GFP);
	if (!lock)
		return NULL;

	lock->cmd = cmd;
	lock->fl = flock;
	lock->start = start;
	lock->end = end;
	lock->flags = flags;
	lock->zero_len = zero_len;
	lock->virtual_lock = virtual_lock;
	INIT_HLIST_NODE(&lock->hlist);
	INIT_LIST_HEAD(&lock->flist);
	INIT_LIST_HEAD(&lock->llist);
	list_add_tail(&lock->llist, lock_list);

	return lock;
}

static void smb2_virtual_lock_cancel(void **argv)
{
	(void)argv;
	wake_up_all(&ksmbd_lock_wait);
}

static int smb2_virtual_lock_wait(struct ksmbd_work *work,
				  struct ksmbd_file *fp,
				  struct ksmbd_lock *smb_lock,
				  struct smb2_lock_rsp *rsp)
{
	void **argv = NULL;
	bool async = false;
	int ret;

	for (;;) {
		ret = ksmbd_file_lock_reserve(fp, smb_lock);
		if (ret != -EAGAIN ||
		    (smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
			break;

		if (!async) {
			argv = kmalloc_obj(*argv, KSMBD_DEFAULT_GFP);
			if (!argv)
				return -ENOMEM;
			argv[0] = NULL;
			ret = setup_async_work(work, smb2_virtual_lock_cancel, argv);
			if (ret) {
				kfree(argv);
				return ret;
			}
			async = true;

			read_lock(&work->sess->file_table.lock);
			if (fp->f_state != FP_INITED) {
				read_unlock(&work->sess->file_table.lock);
				release_async_work(work);
				return -ENOENT;
			}
			spin_lock(&fp->f_lock);
			list_add(&work->fp_entry, &fp->blocked_works);
			spin_unlock(&fp->f_lock);
			read_unlock(&work->sess->file_table.lock);
			smb2_send_interim_resp(work, STATUS_PENDING);
		}

		wait_event(ksmbd_lock_wait,
			   READ_ONCE(work->state) != KSMBD_WORK_ACTIVE ||
			   !ksmbd_file_lock_conflict(smb_lock));

		if (READ_ONCE(work->state) != KSMBD_WORK_ACTIVE) {
			spin_lock(&fp->f_lock);
			list_del_init(&work->fp_entry);
			spin_unlock(&fp->f_lock);
			if (work->state == KSMBD_WORK_CANCELLED) {
				rsp->hdr.Status = STATUS_CANCELLED;
				smb2_send_interim_resp(work, STATUS_CANCELLED);
				work->send_no_response = 1;
				ret = -ECANCELED;
			} else {
				rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
				ret = -EIO;
			}
			release_async_work(work);
			return ret;
		}
	}

	if (async) {
		bool cancelled;

		spin_lock(&fp->f_lock);
		list_del_init(&work->fp_entry);
		cancelled = READ_ONCE(work->state) != KSMBD_WORK_ACTIVE;
		spin_unlock(&fp->f_lock);
		release_async_work(work);
		if (cancelled) {
			ksmbd_file_lock_remove(smb_lock);
			if (work->state == KSMBD_WORK_CANCELLED) {
				rsp->hdr.Status = STATUS_CANCELLED;
				smb2_send_interim_resp(work, STATUS_CANCELLED);
				work->send_no_response = 1;
				return -ECANCELED;
			}
			rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
			return -EIO;
		}
	}

	return ret;
}

static void smb2_free_ksmbd_lock(struct ksmbd_lock *smb_lock)
{
	if (smb_lock->vfs_locked)
		ksmbd_vfs_posix_lock_unblock(smb_lock->fl);
	locks_free_lock(smb_lock->fl);
	kfree(smb_lock);
}

static void smb2_remove_blocked_lock(void **argv)
{
	struct file_lock *flock = (struct file_lock *)argv[0];

	ksmbd_vfs_posix_lock_unblock(flock);
	locks_wake_up(flock);
}

static void smb2_free_blocked_lock(struct file_lock *flock)
{
	ksmbd_vfs_posix_lock_unblock(flock);
	locks_wake_up(flock);
	locks_free_lock(flock);
}

/**
 * smb2_lock() - handler for smb2 file lock command
 * @work:	smb work containing lock command buffer
 *
 * Return:	0 on success, otherwise error
 */
int smb2_lock(struct ksmbd_work *work)
{
	struct smb2_lock_req *req;
	struct smb2_lock_rsp *rsp;
	struct smb2_lock_element *lock_ele;
	struct ksmbd_file *fp = NULL;
	struct file_lock *flock = NULL;
	struct file *filp = NULL;
	int lock_count;
	int flags = 0;
	int cmd = 0;
	int err = -EIO, i, rc = 0;
	u64 lock_start, lock_length, lock_end;
	struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp;
	LIST_HEAD(lock_list);
	LIST_HEAD(rollback_list);
	int prior_lock = 0;
	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
	bool lock_replayed;
	bool virtual_lock;

	WORK_BUFFERS(work, req, rsp);

	ksmbd_debug(SMB, "Received smb2 lock request\n");

	if (smb2_compound_has_failed(work, &rsp->hdr))
		return -EACCES;

	if (work->next_smb2_rcv_hdr_off &&
	    !has_file_id(req->VolatileFileId)) {
		ksmbd_debug(SMB, "Compound request set FID = %llu\n",
			    work->compound_fid);
		id = work->compound_fid;
		pid = work->compound_pfid;
	}

	if (!has_file_id(id)) {
		id = req->VolatileFileId;
		pid = req->PersistentFileId;
	}

	fp = ksmbd_lookup_fd_slow(work, id, pid);
	if (!fp) {
		ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
		err = -ENOENT;
		goto out2;
	}

	err = smb2_set_request_open(work, fp, &req->hdr, false, false);
	if (err)
		goto out2;

	lock_replayed = smb2_verify_lock_sequence(work, fp, req);
	if (lock_replayed)
		goto lock_success;

	filp = fp->filp;
	lock_count = le16_to_cpu(req->LockCount);
	lock_ele = req->locks;

	ksmbd_debug(SMB, "lock count is %d\n", lock_count);
	/*
	 * Cap lock_count at 64. The MS-SMB2 spec defines Open.LockSequenceArray
	 * as exactly 64 entries so 64 is the intended ceiling. No real workload
	 * comes close to this in a single request.
	 */
	if (!lock_count || lock_count > 64) {
		err = -EINVAL;
		goto out2;
	}

	for (i = 0; i < lock_count; i++) {
		flags = le32_to_cpu(lock_ele[i].Flags);

		flock = smb_flock_init(filp);
		if (!flock)
			goto out;

		cmd = smb2_set_flock_flags(flock, flags);

		lock_start = le64_to_cpu(lock_ele[i].Offset);
		lock_length = le64_to_cpu(lock_ele[i].Length);
		if (lock_length && lock_length - 1 > U64_MAX - lock_start) {
			pr_err("Invalid lock range requested\n");
			rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
			locks_free_lock(flock);
			goto out;
		}

		lock_end = lock_length ? lock_start + lock_length - 1 : lock_start;
		virtual_lock = lock_end > OFFSET_MAX;

		/* Lock the representable portion in VFS as well. */
		if (lock_start > OFFSET_MAX) {
			flock->fl_start = 0;
			flock->fl_end = 0;
		} else {
			flock->fl_start = lock_start;
			flock->fl_end = min_t(u64, lock_end, OFFSET_MAX);
		}

		/* Check conflict locks in one request */
		list_for_each_entry(cmp_lock, &lock_list, llist) {
			if (cmp_lock->start <= lock_start &&
			    cmp_lock->end >= lock_end) {
				if (cmp_lock->fl->c.flc_type != F_UNLCK &&
				    flock->c.flc_type != F_UNLCK) {
					pr_err("conflict two locks in one request\n");
					err = -EINVAL;
					locks_free_lock(flock);
					goto out;
				}
			}
		}

		smb_lock = smb2_lock_init(flock, cmd, flags, !lock_length,
					   lock_start, lock_end, virtual_lock,
					   &lock_list);
		if (!smb_lock) {
			err = -EINVAL;
			locks_free_lock(flock);
			goto out;
		}
	}

	list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
		if (lock_count > 1 &&
		    !(le32_to_cpu(lock_ele[0].Flags) & SMB2_LOCKFLAG_UNLOCK) &&
		    !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY)) {
			err = -EINVAL;
			goto out;
		}

		if (smb_lock->cmd < 0) {
			err = -EINVAL;
			goto out;
		}

		if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
			err = -EINVAL;
			goto out;
		}

		if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
		     smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
		    (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
		     !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
			err = -EINVAL;
			goto out;
		}

		prior_lock = smb_lock->flags;

		/* The SMB lock table stores ranges that file_lock cannot express. */
		if (smb_lock->virtual_lock &&
		    !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))
			goto no_check_cl;
		if (smb_lock->virtual_lock &&
		    (smb_lock->flags & SMB2_LOCKFLAG_UNLOCK)) {
			err = ksmbd_file_lock_unlock(smb_lock);
			if (err) {
				rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
				goto out;
			}
			list_del(&smb_lock->llist);
			smb2_free_ksmbd_lock(smb_lock);
			continue;
		}

		if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
		    !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
			goto no_check_cl;

		err = ksmbd_file_lock_check(smb_lock);
		if (err) {
			if (err == -ENOENT)
				rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
			goto out;
		}

no_check_cl:
		flock = smb_lock->fl;
		list_del(&smb_lock->llist);

		if (smb_lock->virtual_lock &&
		    !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK)) {
			rc = smb2_virtual_lock_wait(work, fp, smb_lock, rsp);
			if (rc) {
				err = rc;
				smb2_free_ksmbd_lock(smb_lock);
				goto out;
			}
			list_add(&smb_lock->llist, &rollback_list);
			if (smb_lock->start > OFFSET_MAX)
				continue;
		}

		if (smb_lock->zero_len) {
			rc = 0;
			err = 0;
			goto skip;
		}
retry:
		rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
skip:
		if (smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) {
			locks_free_lock(flock);
			kfree(smb_lock);
			if (!rc) {
				ksmbd_debug(SMB, "File unlocked\n");
			} else if (rc == -ENOENT) {
				rsp->hdr.Status = STATUS_NOT_LOCKED;
				err = rc;
				goto out;
			}
		} else {
			if (rc == FILE_LOCK_DEFERRED) {
				void **argv;

				ksmbd_debug(SMB,
					    "would have to wait for getting lock\n");

				argv = kmalloc(sizeof(void *), KSMBD_DEFAULT_GFP);
				if (!argv) {
					err = -ENOMEM;
					if (smb_lock->virtual_lock) {
						ksmbd_vfs_posix_lock_unblock(flock);
						locks_wake_up(flock);
						goto out;
					}
					smb2_free_blocked_lock(flock);
					kfree(smb_lock);
					goto out;
				}
				argv[0] = flock;

				rc = setup_async_work(work,
						      smb2_remove_blocked_lock,
						      argv);
				if (rc) {
					kfree(argv);
					err = -ENOMEM;
					if (smb_lock->virtual_lock) {
						ksmbd_vfs_posix_lock_unblock(flock);
						locks_wake_up(flock);
						goto out;
					}
					smb2_free_blocked_lock(flock);
					kfree(smb_lock);
					goto out;
				}
				if (!smb_lock->virtual_lock)
					list_add(&smb_lock->llist, &rollback_list);
				spin_lock(&fp->f_lock);
				list_add(&work->fp_entry, &fp->blocked_works);
				spin_unlock(&fp->f_lock);

				smb2_send_interim_resp(work, STATUS_PENDING);

				ksmbd_vfs_posix_lock_wait(flock);

				spin_lock(&fp->f_lock);
				list_del(&work->fp_entry);
				spin_unlock(&fp->f_lock);

				if (!smb_lock->virtual_lock)
					list_del(&smb_lock->llist);

				if (work->state == KSMBD_WORK_CANCELLED) {
					rsp->hdr.Status = STATUS_CANCELLED;
					smb2_send_interim_resp(work,
							STATUS_CANCELLED);
					release_async_work(work);
					work->send_no_response = 1;
					if (!smb_lock->virtual_lock) {
						kfree(smb_lock);
						locks_free_lock(flock);
					}
					goto out;
				}

				release_async_work(work);

				if (work->state == KSMBD_WORK_ACTIVE)
					goto retry;

				rsp->hdr.Status =
					STATUS_RANGE_NOT_LOCKED;
				if (!smb_lock->virtual_lock) {
					locks_free_lock(flock);
					kfree(smb_lock);
				}
				/* rollback_list may still hold earlier grants */
				goto out;
			} else if (!rc) {
				smb_lock->vfs_locked = !smb_lock->zero_len;
				if (!smb_lock->virtual_lock)
					list_add(&smb_lock->llist, &rollback_list);
				ksmbd_debug(SMB, "successful in taking lock\n");
			} else {
				err = rc;
				if (!smb_lock->virtual_lock) {
					locks_free_lock(flock);
					kfree(smb_lock);
				}
				goto out;
			}
		}
	}

	if (atomic_read(&fp->f_ci->op_count) > 1)
		smb_break_all_oplock(work, fp);

lock_success:
	rsp->StructureSize = cpu_to_le16(4);
	ksmbd_debug(SMB, "successful in taking lock\n");
	rsp->hdr.Status = STATUS_SUCCESS;
	rsp->Reserved = 0;
	err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lock_rsp));
	if (err)
		goto out;

	/* publish only once the whole batch has committed */
	ksmbd_file_lock_add(fp, &rollback_list);

	if (!lock_replayed)
		smb2_update_lock_sequence(work, fp, req);

	ksmbd_fd_put(work, fp);
	return 0;

out:
	list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
		locks_free_lock(smb_lock->fl);
		list_del(&smb_lock->llist);
		kfree(smb_lock);
	}

	list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
		struct file_lock *rlock = NULL;

		if (smb_lock->vfs_locked) {
			rlock = smb_flock_init(filp);
			if (rlock) {
				rlock->c.flc_type = F_UNLCK;
				rlock->fl_start = smb_lock->fl->fl_start;
				rlock->fl_end = smb_lock->fl->fl_end;

				rc = vfs_lock_file(filp, F_SETLK, rlock, NULL);
				if (rc)
					pr_err("rollback unlock fail : %d\n", rc);
			} else {
				pr_err("rollback unlock alloc failed\n");
			}
		}
		if (smb_lock->virtual_lock)
			ksmbd_file_lock_remove(smb_lock);

		list_del(&smb_lock->llist);
		if (rlock)
			locks_free_lock(rlock);
		smb2_free_ksmbd_lock(smb_lock);
	}
out2:
	ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);

	if (!rsp->hdr.Status) {
		if (err == -EINVAL)
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		else if (err == -ENOMEM)
			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
		else if (err == -ENOENT)
			rsp->hdr.Status = STATUS_FILE_CLOSED;
		else
			rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
	}

	smb2_set_err_rsp(work);
	ksmbd_fd_put(work, fp);
	return err;
}

static int fsctl_copychunk(struct ksmbd_work *work,
			   struct copychunk_ioctl_req *ci_req,
			   unsigned int cnt_code,
			   unsigned int input_count,
			   unsigned long long volatile_id,
			   unsigned long long persistent_id,
			   struct smb2_ioctl_rsp *rsp)
{
	struct copychunk_ioctl_rsp *ci_rsp;
	struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
	struct srv_copychunk *chunks;
	unsigned int i, chunk_count, chunk_count_written = 0;
	unsigned int chunk_size_written = 0;
	loff_t total_size_written = 0;
	int ret = 0;

	ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];

	rsp->VolatileFileId = volatile_id;
	rsp->PersistentFileId = persistent_id;
	ci_rsp->ChunksWritten =
		cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
	ci_rsp->ChunkBytesWritten =
		cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
	ci_rsp->TotalBytesWritten =
		cpu_to_le32(ksmbd_server_side_copy_max_total_size());

	chunk_count = le32_to_cpu(ci_req->ChunkCount);
	/*
	 * ChunkCount=0 is the standard SMB2 "query my copy limits" request
	 * (no data copied) -- but macOS Finder's Cmd+D duplicate sends
	 * FSCTL_SRV_COPYCHUNK with ChunkCount=0 meaning "copy the whole
	 * file", relying on the AAPL-negotiated server to do a full copy
	 * instead. Keep the standard no-op behavior for everyone else.
	 *
	 * Gate on the TIME_MACHINE share flag, not just conn->is_aapl:
	 * that flag alone has ambiguous provenance -- the pre-existing
	 * narrow UniqueId=0 path can also set it on ordinary,
	 * non-Time-Machine shares, and this series' stated design keeps
	 * every AAPL-driven behavior opt-in per share.
	 */
	if (chunk_count == 0 &&
	    !(work->conn->is_aapl &&
	      test_share_config_flag(work->tcon->share_conf,
				     KSMBD_SHARE_FLAG_TIME_MACHINE)))
		goto out;
	total_size_written = 0;
	i = 0;

	if (chunk_count) {
		/* verify the SRV_COPYCHUNK_COPY packet */
		if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
		    input_count < struct_size(ci_req, Chunks, chunk_count)) {
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
			return -EINVAL;
		}

		chunks = &ci_req->Chunks[0];
		for (i = 0; i < chunk_count; i++) {
			if (le32_to_cpu(chunks[i].Length) == 0 ||
			    le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
				break;
			total_size_written += le32_to_cpu(chunks[i].Length);
		}
	} else {
		chunks = &ci_req->Chunks[0];
	}

	if (i < chunk_count ||
	    total_size_written > ksmbd_server_side_copy_max_total_size()) {
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		return -EINVAL;
	}

	src_fp = ksmbd_lookup_foreign_fd(work,
					 le64_to_cpu(ci_req->SourceKeyU64[0]));
	dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
	ret = -EINVAL;
	if (!src_fp ||
	    src_fp->persistent_id != le64_to_cpu(ci_req->SourceKeyU64[1])) {
		rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
		goto out;
	}

	if (!dst_fp) {
		rsp->hdr.Status = STATUS_FILE_CLOSED;
		goto out;
	}

	/*
	 * FILE_READ_DATA should only be included in
	 * the FSCTL_SRV_COPYCHUNK case
	 */
	if (cnt_code == FSCTL_SRV_COPYCHUNK &&
	    !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
		rsp->hdr.Status = STATUS_ACCESS_DENIED;
		goto out;
	}

	ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
					 chunks, chunk_count,
					 &chunk_count_written,
					 &chunk_size_written,
					 &total_size_written);
	if (ret < 0) {
		if (ret == -EACCES)
			rsp->hdr.Status = STATUS_ACCESS_DENIED;
		else if (ret == -EAGAIN)
			rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
		else if (ret == -EBADF)
			rsp->hdr.Status = STATUS_INVALID_HANDLE;
		else if (ret == -EFBIG || ret == -ENOSPC)
			rsp->hdr.Status = STATUS_DISK_FULL;
		else if (ret == -EINVAL)
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		else if (ret == -EISDIR)
			rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
		else if (ret == -E2BIG)
			rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
		else
			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
	}

	ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
	ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
	ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
out:
	ksmbd_fd_put(work, src_fp);
	ksmbd_fd_put(work, dst_fp);
	return ret;
}

static __be32 idev_ipv4_address(struct in_device *idev)
{
	__be32 addr = 0;

	struct in_ifaddr *ifa;

	rcu_read_lock();
	in_dev_for_each_ifa_rcu(ifa, idev) {
		if (ifa->ifa_flags & IFA_F_SECONDARY)
			continue;

		addr = ifa->ifa_address;
		break;
	}
	rcu_read_unlock();
	return addr;
}

static struct network_interface_info_ioctl_rsp *
ksmbd_iface_entry_init(struct smb2_ioctl_rsp *rsp, int nbytes,
		       struct net_device *netdev, unsigned long long speed)
{
	struct network_interface_info_ioctl_rsp *nii_rsp;

	nii_rsp = (struct network_interface_info_ioctl_rsp *)&rsp->Buffer[nbytes];
	nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
	nii_rsp->Capability = 0;
	if (netdev->real_num_tx_queues > 1)
		nii_rsp->Capability |= RSS_CAPABLE;
	if (ksmbd_rdma_capable_netdev(netdev))
		nii_rsp->Capability |= RDMA_CAPABLE;
	nii_rsp->Next = cpu_to_le32(152);
	nii_rsp->Reserved = 0;
	nii_rsp->LinkSpeed = cpu_to_le64(speed);
	memset(nii_rsp->SockAddr_Storage, 0, 128);

	return nii_rsp;
}

static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
					struct smb2_ioctl_rsp *rsp,
					unsigned int out_buf_len)
{
	struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
	int nbytes = 0;
	struct net_device *netdev;
	struct sockaddr_storage_rsp *sockaddr_storage;
	unsigned int flags;
	unsigned long long speed;
	struct ethtool_link_ksettings cmd;

	rtnl_lock();
	for_each_netdev(&init_net, netdev) {
		struct inet6_ifaddr *ifa;
		struct inet6_dev *idev6;
		struct in_device *idev;
		struct in6_addr ip6 = { };
		bool have_ip6 = false;
		__be32 ip4 = 0;

		if (netdev->type == ARPHRD_LOOPBACK)
			continue;

		if (!ksmbd_find_netdev_name_iface_list(netdev->name))
			continue;

		flags = netif_get_flags(netdev);
		if (!(flags & IFF_RUNNING))
			continue;

		if (!__ethtool_get_link_ksettings(netdev, &cmd) &&
		    cmd.base.speed && cmd.base.speed != SPEED_UNKNOWN) {
			speed = cmd.base.speed;
		} else {
			ksmbd_debug(SMB, "%s %s\n", netdev->name,
				    "speed is unknown, defaulting to 1Gb/sec");
			speed = SPEED_1000;
		}
		speed *= 1000000;

		/*
		 * Query IPv4 and IPv6 independently; emit an entry only when a
		 * usable address exists, so an interface missing one family is
		 * still reported for the other and 0.0.0.0 / :: placeholders are
		 * never advertised.
		 */
		idev = __in_dev_get_rtnl(netdev);
		if (idev)
			ip4 = idev_ipv4_address(idev);

		idev6 = __in6_dev_get(netdev);
		if (idev6) {
			rcu_read_lock();
			list_for_each_entry_rcu(ifa, &idev6->addr_list, if_list) {
				if (ifa->flags & (IFA_F_TENTATIVE | IFA_F_DEPRECATED))
					continue;
				memcpy(&ip6, ifa->addr.s6_addr, sizeof(ip6));
				have_ip6 = true;
				break;
			}
			rcu_read_unlock();
		}

		if (ip4) {
			if (out_buf_len <
			    nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
				rtnl_unlock();
				return -ENOSPC;
			}

			nii_rsp = ksmbd_iface_entry_init(rsp, nbytes, netdev, speed);
			sockaddr_storage = (struct sockaddr_storage_rsp *)nii_rsp->SockAddr_Storage;
			sockaddr_storage->Family = INTERNETWORK;
			sockaddr_storage->addr4.Port = 0;
			sockaddr_storage->addr4.IPv4Address = ip4;
			nbytes += sizeof(struct network_interface_info_ioctl_rsp);
		}

		if (have_ip6) {
			if (out_buf_len <
			    nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
				rtnl_unlock();
				return -ENOSPC;
			}

			nii_rsp = ksmbd_iface_entry_init(rsp, nbytes, netdev, speed);
			sockaddr_storage = (struct sockaddr_storage_rsp *)nii_rsp->SockAddr_Storage;
			sockaddr_storage->Family = INTERNETWORKV6;
			sockaddr_storage->addr6.Port = 0;
			sockaddr_storage->addr6.FlowInfo = 0;
			memcpy(sockaddr_storage->addr6.IPv6Address, ip6.s6_addr, 16);
			sockaddr_storage->addr6.ScopeId = 0;
			nbytes += sizeof(struct network_interface_info_ioctl_rsp);
		}
	}
	rtnl_unlock();

	/* Clear Next of the last committed entry to terminate the list. */
	if (nbytes > 0) {
		nii_rsp = (struct network_interface_info_ioctl_rsp *)
			  &rsp->Buffer[nbytes - sizeof(*nii_rsp)];
		nii_rsp->Next = 0;
	}

	rsp->PersistentFileId = SMB2_NO_FID;
	rsp->VolatileFileId = SMB2_NO_FID;
	return nbytes;
}

static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
					 struct validate_negotiate_info_req *neg_req,
					 struct validate_negotiate_info_rsp *neg_rsp,
					 unsigned int in_buf_len)
{
	int ret = 0;
	int dialect;

	if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
			le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
		return -EINVAL;

	dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
					     neg_req->DialectCount);
	if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
		ret = -EINVAL;
		goto err_out;
	}

	if (memcmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
		ret = -EINVAL;
		goto err_out;
	}

	if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
		ret = -EINVAL;
		goto err_out;
	}

	if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
		ret = -EINVAL;
		goto err_out;
	}

	neg_rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
	memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
	neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
	neg_rsp->Dialect = cpu_to_le16(conn->dialect);
err_out:
	return ret;
}

static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
					struct file_allocated_range_buffer *qar_req,
					struct file_allocated_range_buffer *qar_rsp,
					unsigned int in_count, unsigned int *out_count)
{
	struct ksmbd_file *fp;
	loff_t start, length;
	int ret = 0;

	*out_count = 0;

	start = le64_to_cpu(qar_req->file_offset);
	length = le64_to_cpu(qar_req->length);

	if (start < 0 || length < 0)
		return -EINVAL;

	fp = ksmbd_lookup_fd_fast(work, id);
	if (!fp)
		return -ENOENT;

	if (!(fp->daccess & FILE_READ_DATA_LE)) {
		ret = -EACCES;
		goto out;
	}

	if (!in_count) {
		struct file_allocated_range_buffer range;

		ret = ksmbd_vfs_query_allocated_ranges(fp, start, length,
						       &range, 1, out_count);
		if ((!ret || ret == -E2BIG) && *out_count)
			ret = -ENOSPC;
		*out_count = 0;
	} else {
		ret = ksmbd_vfs_query_allocated_ranges(fp, start, length,
						       qar_rsp, in_count,
						       out_count);
	}
	if (ret && ret != -E2BIG)
		*out_count = 0;

out:
	ksmbd_fd_put(work, fp);
	return ret;
}

static int smb2_ioctl_rsp(struct ksmbd_work *work, struct smb2_ioctl_rsp *rsp,
			  unsigned int cnt_code, unsigned int nbytes)
{
	rsp->CtlCode = cpu_to_le32(cnt_code);
	rsp->InputCount = cpu_to_le32(0);
	rsp->InputOffset = cpu_to_le32(112);
	rsp->OutputOffset = cpu_to_le32(112);
	rsp->OutputCount = cpu_to_le32(nbytes);
	rsp->StructureSize = cpu_to_le16(49);
	rsp->Reserved = cpu_to_le16(0);
	rsp->Flags = cpu_to_le32(0);
	rsp->Reserved2 = cpu_to_le32(0);
	return ksmbd_iov_pin_rsp(work, rsp,
				 sizeof(struct smb2_ioctl_rsp) + nbytes);
}

static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
				 unsigned int out_buf_len,
				 struct smb2_ioctl_req *req,
				 struct smb2_ioctl_rsp *rsp)
{
	struct ksmbd_rpc_command *rpc_resp;
	struct ksmbd_session_rpc *rpc;
	char *data_buf = (char *)req + le32_to_cpu(req->InputOffset);
	unsigned int nbytes = 0;
	int ret;

	rpc = ksmbd_session_rpc_get(work, id);
	if (IS_ERR(rpc)) {
		ret = PTR_ERR(rpc);
		rsp->hdr.Status = smb2_pipe_error_status(ret,
						 STATUS_INVALID_PARAMETER);
		smb2_set_err_rsp(work);
		return 0;
	}

	if (rpc->pending) {
		ksmbd_session_rpc_put(rpc);
		rsp->hdr.Status = STATUS_PIPE_BUSY;
		smb2_set_err_rsp(work);
		return 0;
	}

	rpc_resp = ksmbd_rpc_ioctl(work->sess, rpc, data_buf,
				   le32_to_cpu(req->InputCount));
	if (!rpc_resp) {
		ksmbd_session_rpc_put(rpc);
		rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
		smb2_set_err_rsp(work);
		return 0;
	}

	if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
		rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
	} else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
		goto free_resp;
	} else if (rpc_resp->flags != KSMBD_RPC_OK) {
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		goto free_resp;
	}

	if (!rpc_resp->payload_sz) {
		rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
		goto free_resp;
	}
	rpc->pending = rpc_resp;
	nbytes = rpc_resp->payload_sz - rpc->pending_offset;
	if (nbytes > out_buf_len) {
		rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
		nbytes = out_buf_len;
	}
	memcpy(rsp->Buffer, rpc_resp->payload + rpc->pending_offset, nbytes);
	ret = smb2_ioctl_rsp(work, rsp, FSCTL_PIPE_TRANSCEIVE, nbytes);
	if (!ret)
		smb2_pipe_response_done(rpc, nbytes);
	ksmbd_session_rpc_put(rpc);
	return ret;

free_resp:
	kvfree(rpc_resp);
	rsp->hdr.Status = smb2_pipe_error_status(-EINVAL, rsp->hdr.Status);
	ksmbd_session_rpc_put(rpc);
	smb2_set_err_rsp(work);
	return 0;
}

static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
				   struct file_sparse *sparse)
{
	struct ksmbd_file *fp;
	const struct mnt_idmap *idmap;
	int ret = 0;
	__le32 old_fattr;

	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
		ksmbd_debug(SMB, "User does not have write permission\n");
		return -EACCES;
	}

	fp = ksmbd_lookup_fd_fast(work, id);
	if (!fp)
		return -ENOENT;

	if (S_ISDIR(file_inode(fp->filp)->i_mode)) {
		ret = -EINVAL;
		goto out;
	}

	if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_APPEND_DATA_LE |
			     FILE_WRITE_ATTRIBUTES_LE))) {
		ret = -EACCES;
		goto out;
	}

	idmap = file_mnt_idmap(fp->filp);

	old_fattr = fp->f_ci->m_fattr;
	if (!sparse->SetSparse &&
	    (old_fattr & FILE_ATTRIBUTE_SPARSE_FILE_LE)) {
		ret = ksmbd_vfs_zero_holes(fp);
		if (ret)
			goto out;
	}

	if (sparse->SetSparse)
		fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
	else
		fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;

	if (fp->f_ci->m_fattr != old_fattr) {
		const struct cred *saved_cred;
		struct xattr_dos_attrib da = {0};

		ret = ksmbd_vfs_get_dos_attrib_xattr(idmap,
						     fp->filp->f_path.dentry, &da);
		if (ret <= 0) {
			da.version = 4;
			da.itime = fp->itime;
			da.create_time = fp->create_time;
			da.flags = XATTR_DOSINFO_CREATE_TIME |
				XATTR_DOSINFO_ITIME;
		}

		da.attr = le32_to_cpu(fp->f_ci->m_fattr);
		da.flags |= XATTR_DOSINFO_ATTRIB;
		saved_cred = override_creds(fp->filp->f_cred);
		ret = ksmbd_vfs_set_dos_attrib_xattr(idmap,
						     &fp->filp->f_path,
						     &da, true);
		revert_creds(saved_cred);
		if (ret)
			fp->f_ci->m_fattr = old_fattr;
	}

out:
	ksmbd_fd_put(work, fp);
	return ret;
}

static int fsctl_request_resume_key(struct ksmbd_work *work,
				    struct smb2_ioctl_req *req,
				    struct resume_key_ioctl_rsp *key_rsp)
{
	struct ksmbd_file *fp;

	fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
	if (!fp)
		return -ENOENT;

	memset(key_rsp, 0, sizeof(*key_rsp));
	key_rsp->ResumeKeyU64[0] = req->VolatileFileId;
	key_rsp->ResumeKeyU64[1] = req->PersistentFileId;
	ksmbd_fd_put(work, fp);

	return 0;
}

/**
 * smb2_ioctl() - handler for smb2 ioctl command
 * @work:	smb work containing ioctl command buffer
 *
 * Return:	0 on success, otherwise error
 */
int smb2_ioctl(struct ksmbd_work *work)
{
	struct smb2_ioctl_req *req;
	struct smb2_ioctl_rsp *rsp;
	unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
	u64 id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
	struct ksmbd_conn *conn = work->conn;
	int ret = 0;
	char *buffer;
	bool no_fileid_ioctl = false;
	bool chseq_err = false;

	ksmbd_debug(SMB, "Received smb2 ioctl request\n");

	if (work->next_smb2_rcv_hdr_off) {
		req = ksmbd_req_buf_next(work);
		rsp = ksmbd_resp_buf_next(work);
		if (smb2_compound_has_failed(work, &rsp->hdr))
			return -EACCES;
		if (!has_file_id(req->VolatileFileId)) {
			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
				    work->compound_fid);
			id = work->compound_fid;
			pid = work->compound_pfid;
		}
	} else {
		req = smb_get_msg(work->request_buf);
		rsp = smb_get_msg(work->response_buf);
	}

	if (!has_file_id(id)) {
		id = req->VolatileFileId;
		pid = req->PersistentFileId;
	}

	if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
		ret = -EOPNOTSUPP;
		goto out;
	}

	buffer = (char *)req + le32_to_cpu(req->InputOffset);

	cnt_code = le32_to_cpu(req->CtlCode);
	switch (cnt_code) {
	case FSCTL_DFS_GET_REFERRALS:
	case FSCTL_DFS_GET_REFERRALS_EX:
	case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
	case FSCTL_VALIDATE_NEGOTIATE_INFO:
	case FSCTL_PIPE_WAIT:
		no_fileid_ioctl = true;
		break;
	case FSCTL_PIPE_TRANSCEIVE:
		if (!test_share_config_flag(work->tcon->share_conf,
					    KSMBD_SHARE_FLAG_PIPE)) {
			ret = -EOPNOTSUPP;
			goto out;
		}

		/* RPC pipe handles are not in the regular file table. */
		if (has_file_id(id) && !pid) {
			down_read(&work->sess->rpc_lock);
			no_fileid_ioctl =
				ksmbd_session_rpc_method(work->sess, id) != 0;
			up_read(&work->sess->rpc_lock);
		}
		if (!no_fileid_ioctl) {
			ret = -EBADF;
			rsp->hdr.Status = STATUS_FILE_CLOSED;
			goto out2;
		}
		break;
	default:
		break;
	}

	if (!no_fileid_ioctl && has_file_id(id)) {
		struct ksmbd_file *fp;

		fp = ksmbd_lookup_fd_slow(work, id, pid);
		if (!fp) {
			if (cnt_code == FSCTL_DUPLICATE_EXTENTS_TO_FILE) {
				rsp->hdr.Status = STATUS_FILE_CLOSED;
				goto out2;
			}
			ret = -ENOENT;
			goto out;
		}

		ret = smb2_set_request_open(work, fp, &req->hdr, true, false);
		ksmbd_fd_put(work, fp);
		if (ret) {
			rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE;
			chseq_err = true;
			goto out;
		}
	}

	ret = smb2_calc_max_out_buf_len(work,
			offsetof(struct smb2_ioctl_rsp, Buffer),
			le32_to_cpu(req->MaxOutputResponse));
	if (ret < 0) {
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		goto out;
	}
	out_buf_len = (unsigned int)ret;
	in_buf_len = le32_to_cpu(req->InputCount);

	switch (cnt_code) {
	case FSCTL_SRV_ENUM_SNAPS: {
		struct srv_snapshot_array *snap_rsp;
		struct ksmbd_file *fp;

		if (out_buf_len < sizeof(*snap_rsp)) {
			ret = -EINVAL;
			goto out;
		}

		fp = ksmbd_lookup_fd_fast(work, id);
		if (!fp) {
			ret = -ENOENT;
			goto out;
		}
		ksmbd_fd_put(work, fp);

		snap_rsp = (struct srv_snapshot_array *)rsp->Buffer;
		snap_rsp->NumberOfSnapShots = 0;
		snap_rsp->NumberOfSnapShotsReturned = 0;
		snap_rsp->SnapShotArraySize = cpu_to_le32(2);
		snap_rsp->Reserved = 0;
		nbytes = sizeof(*snap_rsp);
		break;
	}
	case FSCTL_DFS_GET_REFERRALS:
	case FSCTL_DFS_GET_REFERRALS_EX:
		/* Not support DFS yet */
		ret = -EOPNOTSUPP;
		rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
		goto out2;
	case FSCTL_GET_COMPRESSION: {
		struct compress_ioctl *cmpr_rsp;
		struct ksmbd_file *fp;
		u16 fmt;

		if (out_buf_len < sizeof(struct compress_ioctl)) {
			ret = -EINVAL;
			goto out;
		}

		fp = ksmbd_lookup_fd_fast(work, id);
		if (!fp) {
			ret = -ENOENT;
			goto out;
		}

		ret = ksmbd_vfs_get_compression(fp, &fmt);
		ksmbd_fd_put(work, fp);
		if (ret < 0)
			goto out;

		cmpr_rsp = (struct compress_ioctl *)&rsp->Buffer[0];
		cmpr_rsp->CompressionState = cpu_to_le16(fmt);
		nbytes = sizeof(struct compress_ioctl);
		rsp->PersistentFileId = req->PersistentFileId;
		rsp->VolatileFileId = req->VolatileFileId;
		break;
	}
	case FSCTL_SET_COMPRESSION: {
		struct compress_ioctl *cmpr_req;
		struct ksmbd_file *fp;

		if (in_buf_len < sizeof(struct compress_ioctl)) {
			ret = -EINVAL;
			goto out;
		}

		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
			ksmbd_debug(SMB, "User does not have write permission\n");
			ret = -EACCES;
			goto out;
		}

		cmpr_req = (struct compress_ioctl *)buffer;
		fp = ksmbd_lookup_fd_fast(work, id);
		if (!fp) {
			ret = -ENOENT;
			goto out;
		}

		ret = ksmbd_vfs_set_compression(work, fp, le16_to_cpu(cmpr_req->CompressionState));
		ksmbd_fd_put(work, fp);
		if (ret)
			goto out;
		break;
	}
	case FSCTL_CREATE_OR_GET_OBJECT_ID:
	{
		struct file_object_buf_type1_ioctl_rsp *obj_buf;
		struct ksmbd_file *fp;

		fp = ksmbd_lookup_fd_fast(work, id);
		if (!fp) {
			ret = -EBADF;
			rsp->hdr.Status = STATUS_FILE_CLOSED;
			goto out2;
		}

		if (out_buf_len < sizeof(struct file_object_buf_type1_ioctl_rsp)) {
			ksmbd_fd_put(work, fp);
			ret = -EINVAL;
			goto out;
		}
		ksmbd_fd_put(work, fp);

		nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
		obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
			&rsp->Buffer[0];

		/*
		 * TODO: This is dummy implementation to pass smbtorture
		 * Need to check correct response later
		 */
		memset(obj_buf->ObjectId, 0x0, 16);
		memset(obj_buf->BirthVolumeId, 0x0, 16);
		memset(obj_buf->BirthObjectId, 0x0, 16);
		memset(obj_buf->DomainId, 0x0, 16);

		break;
	}
	case FSCTL_PIPE_TRANSCEIVE:
		rsp->PersistentFileId = pid;
		rsp->VolatileFileId = id;
		out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
		ret = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
		if (ret)
			goto out;
		return 0;
	case FSCTL_VALIDATE_NEGOTIATE_INFO:
		if (conn->dialect < SMB30_PROT_ID) {
			ret = -EOPNOTSUPP;
			goto out;
		}

		if (in_buf_len < offsetof(struct validate_negotiate_info_req,
					  Dialects)) {
			ret = -EINVAL;
			goto out;
		}

		if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
			ret = -EINVAL;
			goto out;
		}

		ret = fsctl_validate_negotiate_info(conn,
			(struct validate_negotiate_info_req *)buffer,
			(struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
			in_buf_len);
		if (ret < 0)
			goto out;

		nbytes = sizeof(struct validate_negotiate_info_rsp);
		rsp->PersistentFileId = SMB2_NO_FID;
		rsp->VolatileFileId = SMB2_NO_FID;
		break;
	case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
		if (req->PersistentFileId != SMB2_NO_FID ||
		    req->VolatileFileId != SMB2_NO_FID) {
			ret = -EINVAL;
			goto out;
		}

		ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
		if (ret < 0)
			goto out;
		nbytes = ret;
		break;
	case FSCTL_SRV_REQUEST_RESUME_KEY:
		if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
			ret = -EINVAL;
			goto out;
		}

		ret = fsctl_request_resume_key(work, req,
					       (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
		if (ret < 0)
			goto out;
		rsp->PersistentFileId = req->PersistentFileId;
		rsp->VolatileFileId = req->VolatileFileId;
		nbytes = sizeof(struct resume_key_ioctl_rsp);
		break;
	case FSCTL_SRV_COPYCHUNK:
	case FSCTL_SRV_COPYCHUNK_WRITE:
		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
			ksmbd_debug(SMB,
				    "User does not have write permission\n");
			ret = -EACCES;
			goto out;
		}

		if (in_buf_len < offsetof(struct copychunk_ioctl_req, Chunks)) {
			ret = -EINVAL;
			goto out;
		}

		if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
			ret = -EINVAL;
			goto out;
		}

		nbytes = sizeof(struct copychunk_ioctl_rsp);
		rsp->VolatileFileId = req->VolatileFileId;
		rsp->PersistentFileId = req->PersistentFileId;
		fsctl_copychunk(work,
				(struct copychunk_ioctl_req *)buffer,
				le32_to_cpu(req->CtlCode),
				le32_to_cpu(req->InputCount),
				req->VolatileFileId,
				req->PersistentFileId,
				rsp);
		break;
	case FSCTL_SET_SPARSE:
	{
		struct file_sparse sparse = {0};

		if (in_buf_len && in_buf_len < sizeof(struct file_sparse)) {
			ret = -EINVAL;
			goto out;
		}

		*(u8 *)&sparse = 1;
		ret = fsctl_set_sparse(work, id, in_buf_len ?
				       (struct file_sparse *)buffer : &sparse);
		if (ret < 0)
			goto out;
		break;
	}
	case FSCTL_SET_ZERO_DATA:
	{
		struct file_zero_data_information *zero_data;
		struct ksmbd_file *fp;
		loff_t off, len, bfz;

		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
			ksmbd_debug(SMB,
				    "User does not have write permission\n");
			ret = -EACCES;
			goto out;
		}

		if (in_buf_len < sizeof(struct file_zero_data_information)) {
			ret = -EINVAL;
			goto out;
		}

		zero_data =
			(struct file_zero_data_information *)buffer;

		off = le64_to_cpu(zero_data->FileOffset);
		bfz = le64_to_cpu(zero_data->BeyondFinalZero);
		if (off < 0 || bfz < 0 || off > bfz) {
			ret = -EINVAL;
			goto out;
		}

		len = bfz - off;
		if (len) {
			fp = ksmbd_lookup_fd_fast(work, id);
			if (!fp) {
				ret = -ENOENT;
				goto out;
			}

			if (!(fp->daccess & FILE_WRITE_DATA_LE)) {
				ksmbd_fd_put(work, fp);
				ret = -EACCES;
				goto out;
			}

			ret = ksmbd_vfs_zero_data(work, fp, off, len);
			ksmbd_fd_put(work, fp);
			if (ret == -EAGAIN) {
				rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
				ret = 0;
				goto out;
			} else if (ret < 0) {
				goto out;
			}
		}
		break;
	}
	case FSCTL_FILE_LEVEL_TRIM:
	{
		struct file_level_trim *trim_req;
		struct file_level_trim_output *trim_rsp;
		struct ksmbd_file *fp;
		u32 i, num_ranges;

		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
			ksmbd_debug(SMB,
				    "User does not have write permission\n");
			ret = -EACCES;
			goto out;
		}

		if (in_buf_len < offsetof(struct file_level_trim, Ranges)) {
			ret = -EINVAL;
			goto out;
		}

		if (out_buf_len < sizeof(struct file_level_trim_output)) {
			ret = -EINVAL;
			goto out;
		}

		trim_req = (struct file_level_trim *)buffer;
		num_ranges = le32_to_cpu(trim_req->NumRanges);
		if (num_ranges >
		    (in_buf_len - offsetof(struct file_level_trim, Ranges)) /
		    sizeof(struct file_level_trim_range)) {
			ret = -EINVAL;
			goto out;
		}

		fp = ksmbd_lookup_fd_fast(work, id);
		if (!fp) {
			ret = -ENOENT;
			goto out;
		}

		if (!(fp->daccess & FILE_WRITE_DATA_LE)) {
			ksmbd_fd_put(work, fp);
			ret = -EACCES;
			goto out;
		}

		trim_rsp = (struct file_level_trim_output *)&rsp->Buffer[0];
		trim_rsp->NumRangesProcessed = 0;
		for (i = 0; i < num_ranges; i++) {
			loff_t off = le64_to_cpu(trim_req->Ranges[i].Offset);
			loff_t len = le64_to_cpu(trim_req->Ranges[i].Length);

			if (off < 0 || len < 0) {
				ret = -EINVAL;
				break;
			}

			if (!len) {
				trim_rsp->NumRangesProcessed =
					cpu_to_le32(i + 1);
				continue;
			}

			ret = ksmbd_vfs_trim_data(work, fp, off, len);
			if (ret)
				break;
			trim_rsp->NumRangesProcessed = cpu_to_le32(i + 1);
		}
		ksmbd_fd_put(work, fp);
		if (ret == -EAGAIN) {
			rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
			ret = 0;
			goto out;
		} else if (ret < 0) {
			goto out;
		}

		nbytes = sizeof(struct file_level_trim_output);
		break;
	}
	case FSCTL_QUERY_ALLOCATED_RANGES:
		if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
			ret = -EINVAL;
			goto out;
		}

		ret = fsctl_query_allocated_ranges(work, id,
			(struct file_allocated_range_buffer *)buffer,
			(struct file_allocated_range_buffer *)&rsp->Buffer[0],
			out_buf_len /
			sizeof(struct file_allocated_range_buffer), &nbytes);
		if (ret == -E2BIG) {
			rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
		} else if (ret < 0) {
			nbytes = 0;
			goto out;
		}

		nbytes *= sizeof(struct file_allocated_range_buffer);
		break;
	case FSCTL_GET_REPARSE_POINT:
	{
		struct reparse_data_buffer *reparse_ptr;
		struct ksmbd_file *fp;

		if (out_buf_len < sizeof(struct reparse_data_buffer)) {
			ret = -EINVAL;
			goto out;
		}

		reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
		fp = ksmbd_lookup_fd_fast(work, id);
		if (!fp) {
			pr_err("not found fp!!\n");
			ret = -ENOENT;
			goto out;
		}

		reparse_ptr->ReparseTag =
			smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
		reparse_ptr->ReparseDataLength = 0;
		ksmbd_fd_put(work, fp);
		nbytes = sizeof(struct reparse_data_buffer);
		break;
	}
	case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
	{
		struct ksmbd_file *fp_in, *fp_out = NULL;
		struct duplicate_extents_to_file *dup_ext;
		loff_t src_off, dst_off, length, cloned;

		if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
			ret = -EINVAL;
			goto out;
		}

		dup_ext = (struct duplicate_extents_to_file *)buffer;

		fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
					     dup_ext->PersistentFileHandle);
		if (!fp_in) {
			pr_err("not found file handle in duplicate extent to file\n");
			ret = -EBADF;
			rsp->hdr.Status = STATUS_INVALID_HANDLE;
			goto out2;
		}

		fp_out = ksmbd_lookup_fd_fast(work, id);
		if (!fp_out) {
			pr_err("not found fp\n");
			ret = -EBADF;
			rsp->hdr.Status = STATUS_FILE_CLOSED;
			ksmbd_fd_put(work, fp_in);
			goto out2;
		}

		if (!test_tree_conn_flag(work->tcon,
					 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
			ret = -EACCES;
			goto dup_ext_out;
		}

		if (!(fp_out->daccess & FILE_WRITE_DATA_LE)) {
			ret = -EACCES;
			goto dup_ext_out;
		}
		if (!(fp_in->daccess & FILE_READ_DATA_LE)) {
			ret = -EACCES;
			goto dup_ext_out;
		}

		src_off = le64_to_cpu(dup_ext->SourceFileOffset);
		dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
		length = le64_to_cpu(dup_ext->ByteCount);
		if (src_off < 0 || dst_off < 0 || length < 0 ||
		    src_off + length < src_off || dst_off + length < dst_off) {
			ret = -EINVAL;
			goto dup_ext_out;
		}
		if (src_off + length > i_size_read(file_inode(fp_in->filp))) {
			ret = -EOPNOTSUPP;
			goto dup_ext_out;
		}
		if (dst_off + length > i_size_read(file_inode(fp_out->filp)))
			goto dup_ext_out;
		if ((fp_in->f_ci->m_fattr & FILE_ATTRIBUTE_SPARSE_FILE_LE) &&
		    !(fp_out->f_ci->m_fattr & FILE_ATTRIBUTE_SPARSE_FILE_LE)) {
			ret = -EOPNOTSUPP;
			goto dup_ext_out;
		}
		if (file_inode(fp_in->filp) == file_inode(fp_out->filp) &&
		    dst_off + length > src_off &&
		    dst_off < src_off + length) {
			ret = -EOPNOTSUPP;
			goto dup_ext_out;
		}

		cloned = vfs_clone_file_range(fp_in->filp, src_off,
					      fp_out->filp, dst_off, length, 0);
		if (cloned != length) {
			cloned = vfs_copy_file_range(fp_in->filp, src_off,
						     fp_out->filp, dst_off,
						     length, 0);
			if (cloned != length) {
				if (cloned < 0)
					ret = cloned;
				else
					ret = -EINVAL;
			}
		}

dup_ext_out:
		ksmbd_fd_put(work, fp_in);
		ksmbd_fd_put(work, fp_out);
		if (ret < 0)
			goto out;
		break;
	}
	default:
		ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
			    cnt_code);
		ret = -EOPNOTSUPP;
		goto out;
	}

	ret = smb2_ioctl_rsp(work, rsp, cnt_code, nbytes);
	if (!ret)
		return ret;

out:
	if (ret == -EACCES)
		rsp->hdr.Status = STATUS_ACCESS_DENIED;
	else if (ret == -ENOENT)
		rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
	else if (ret == -EOPNOTSUPP)
		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
	else if (ret == -ENOSPC)
		rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
	else if (!chseq_err && (ret < 0 || rsp->hdr.Status == 0))
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;

out2:
	smb2_set_err_rsp(work);
	return ret;
}

/**
 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
 * @work:	smb work containing oplock break command buffer
 *
 * Return:	0
 */
static void smb20_oplock_break_ack(struct ksmbd_work *work)
{
	struct smb2_oplock_break *req;
	struct smb2_oplock_break *rsp;
	struct ksmbd_file *fp;
	struct oplock_info *opinfo = NULL;
	__le32 status = STATUS_SUCCESS;
	int ret;
	u64 volatile_id, persistent_id;
	u8 req_oplevel = 0, rsp_oplevel = 0;

	WORK_BUFFERS(work, req, rsp);

	volatile_id = req->VolatileFid;
	persistent_id = req->PersistentFid;
	req_oplevel = req->OplockLevel;
	ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
		    volatile_id, persistent_id, req_oplevel);

	fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
	if (!fp) {
		rsp->hdr.Status = STATUS_FILE_CLOSED;
		smb2_set_err_rsp(work);
		return;
	}

	ret = smb2_set_request_open(work, fp, &req->hdr, false, false);
	if (ret) {
		rsp->hdr.Status = STATUS_FILE_CLOSED;
		smb2_set_err_rsp(work);
		ksmbd_fd_put(work, fp);
		return;
	}

	opinfo = opinfo_get(fp);
	if (!opinfo) {
		pr_err("unexpected null oplock_info\n");
		rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
		smb2_set_err_rsp(work);
		ksmbd_fd_put(work, fp);
		return;
	}

	/* Serialize the level update with break completion and timeout. */
	spin_lock(&opinfo->state_lock);
	if (opinfo->op_state != OPLOCK_ACK_WAIT) {
		ksmbd_debug(SMB, "unexpected oplock state 0x%x\n",
			    opinfo->op_state);
		if (smb3_hdr_replay(&req->hdr) &&
		    opinfo->op_state == OPLOCK_STATE_NONE) {
			rsp->StructureSize = cpu_to_le16(24);
			rsp->OplockLevel = opinfo->level;
			rsp->Reserved = 0;
			rsp->Reserved2 = 0;
			rsp->VolatileFid = volatile_id;
			rsp->PersistentFid = persistent_id;
			spin_unlock(&opinfo->state_lock);
			ret = ksmbd_iov_pin_rsp(work, rsp,
						 sizeof(struct smb2_oplock_break));
			if (ret)
				ksmbd_debug(SMB,
					    "failed to pin replayed oplock break response: %d\n",
					    ret);
			goto out_no_state_change;
		}
		if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE)
			status = STATUS_INVALID_OPLOCK_PROTOCOL;
		else
			status = STATUS_INVALID_DEVICE_STATE;
		goto err_out;
	}

	if (req_oplevel == SMB2_OPLOCK_LEVEL_LEASE) {
		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
		status = STATUS_INVALID_PARAMETER;
		goto err_out;
	}

	if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
		status = STATUS_INVALID_OPLOCK_PROTOCOL;
		goto err_out;
	}

	if (opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE &&
	    req_oplevel != SMB2_OPLOCK_LEVEL_II &&
	    req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
		status = STATUS_INVALID_OPLOCK_PROTOCOL;
		goto err_out;
	}

	if (opinfo->level == SMB2_OPLOCK_LEVEL_BATCH &&
	    req_oplevel != SMB2_OPLOCK_LEVEL_II &&
	    req_oplevel != SMB2_OPLOCK_LEVEL_NONE &&
	    req_oplevel != SMB2_OPLOCK_LEVEL_EXCLUSIVE) {
		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
		status = STATUS_INVALID_OPLOCK_PROTOCOL;
		goto err_out;
	}

	if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
	    req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
		status = STATUS_INVALID_OPLOCK_PROTOCOL;
		goto err_out;
	}

	if (req_oplevel == SMB2_OPLOCK_LEVEL_EXCLUSIVE)
		rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
	else
		rsp_oplevel = req_oplevel;

	opinfo->level = rsp_oplevel;
	opinfo->op_state = OPLOCK_STATE_NONE;
	opinfo->oplock_timeout_set = false;
	spin_unlock(&opinfo->state_lock);
	wake_up_all(&opinfo->oplock_q);

	rsp->StructureSize = cpu_to_le16(24);
	rsp->OplockLevel = rsp_oplevel;
	rsp->Reserved = 0;
	rsp->Reserved2 = 0;
	rsp->VolatileFid = volatile_id;
	rsp->PersistentFid = persistent_id;
	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_oplock_break));
	if (ret)
		ksmbd_debug(SMB, "failed to pin oplock break response: %d\n",
			    ret);
	goto out_no_state_change;

err_out:
	if (opinfo->op_state != OPLOCK_CLOSING)
		opinfo->op_state = OPLOCK_STATE_NONE;
	opinfo->oplock_timeout_set = false;
	spin_unlock(&opinfo->state_lock);
	wake_up_all(&opinfo->oplock_q);
	rsp->hdr.Status = status;
	smb2_set_err_rsp(work);
out_no_state_change:
	opinfo_put(opinfo);
	ksmbd_fd_put(work, fp);
}

static bool smb2_lease_state_valid(__le32 state)
{
	return !(state & ~(SMB2_LEASE_READ_CACHING_LE |
			   SMB2_LEASE_HANDLE_CACHING_LE |
			   SMB2_LEASE_WRITE_CACHING_LE));
}

static int check_lease_state(struct lease *lease, __le32 req_state)
{
	if (smb2_lease_state_valid(req_state) &&
	    !(req_state & ~lease->new_state))
		return 0;

	return 1;
}

/**
 * smb21_lease_break_ack() - handler for smb2.1 lease break command
 * @work:	smb work containing lease break command buffer
 *
 * Return:	0
 */
static void smb21_lease_break_ack(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
	struct smb2_lease_ack *req;
	struct smb2_lease_ack *rsp;
	struct oplock_info *opinfo, *open;
	int ret;
	__le32 lease_state;
	struct lease *lease;
	u8 level;
	bool wake;

	WORK_BUFFERS(work, req, rsp);

	ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
		    le32_to_cpu(req->LeaseState));
	opinfo = lookup_lease_in_table(conn, req->LeaseKey);
	if (!opinfo) {
		ksmbd_debug(OPLOCK, "file not opened\n");
		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
		smb2_set_err_rsp(work);
		return;
	}
	lease = opinfo->o_lease;

	/* Publish NONE only after the lease state and all open levels are updated. */
	spin_lock(&lease->lock);
	spin_lock(&opinfo->state_lock);
	if (opinfo->op_state != OPLOCK_ACK_WAIT) {
		if (opinfo->op_state == OPLOCK_STATE_NONE &&
		    smb3_hdr_replay(&req->hdr))
			goto replay_rsp;
		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
		goto err_unlock;
	}

	if (!atomic_read(&opinfo->breaking_cnt)) {
		if (smb3_hdr_replay(&req->hdr))
			goto replay_rsp;
		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
		goto err_unlock;
	}

	if (check_lease_state(lease, req->LeaseState)) {
		rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
		ksmbd_debug(OPLOCK,
			    "req lease state: 0x%x, expected state: 0x%x\n",
			    req->LeaseState, lease->new_state);
		goto err_unlock;
	}

	lease_state = req->LeaseState;
	lease->state = lease_state;
	lease->new_state = SMB2_LEASE_NONE_LE;
	lease->breaking = false;
	lease->break_timeout_set = false;
	level = smb2_map_lease_to_oplock(lease_state);
	spin_unlock(&opinfo->state_lock);
	list_for_each_entry(open, &lease->open_list, lease_entry) {
		spin_lock(&open->state_lock);
		open->level = level;
		wake = open->op_state == OPLOCK_ACK_WAIT;
		if (wake) {
			open->op_state = OPLOCK_STATE_NONE;
			atomic_set(&open->breaking_cnt, 0);
		}
		spin_unlock(&open->state_lock);
		if (wake) {
			wake_up_all(&open->oplock_q);
			wake_up_interruptible_all(&open->oplock_brk);
		}
	}
	spin_unlock(&lease->lock);
	goto response;

replay_rsp:
	lease_state = lease->state;
	spin_unlock(&opinfo->state_lock);
	spin_unlock(&lease->lock);
response:
	rsp->StructureSize = cpu_to_le16(36);
	rsp->Reserved = 0;
	rsp->Flags = 0;
	memcpy(rsp->LeaseKey, req->LeaseKey, SMB2_LEASE_KEY_SIZE);
	rsp->LeaseState = lease_state;
	rsp->LeaseDuration = 0;
	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack));
	if (ret)
		goto err_out;
	opinfo_put(opinfo);
	return;

err_unlock:
	spin_unlock(&opinfo->state_lock);
	spin_unlock(&lease->lock);
err_out:
	smb2_set_err_rsp(work);
	opinfo_put(opinfo);
}

/**
 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
 * @work:	smb work containing oplock/lease break command buffer
 *
 * Return:	0 on success, otherwise error
 */
int smb2_oplock_break(struct ksmbd_work *work)
{
	struct smb2_oplock_break *req;
	struct smb2_oplock_break *rsp;

	ksmbd_debug(SMB, "Received smb2 oplock break acknowledgment request\n");

	WORK_BUFFERS(work, req, rsp);

	switch (le16_to_cpu(req->StructureSize)) {
	case OP_BREAK_STRUCT_SIZE_20:
		smb20_oplock_break_ack(work);
		break;
	case OP_BREAK_STRUCT_SIZE_21:
		smb21_lease_break_ack(work);
		break;
	default:
		ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
			    le16_to_cpu(req->StructureSize));
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		smb2_set_err_rsp(work);
		return -EINVAL;
	}

	return 0;
}

struct ksmbd_notify_req {
	wait_queue_head_t wait;
};

/*
 * Cancel handler for a pending CHANGE_NOTIFY. Called either by
 * smb2_cancel() (conn->request_lock held, work->state already set to
 * KSMBD_WORK_CANCELLED by the caller) or by
 * set_close_state_blocked_works() (vfs_cache.c, fp->f_lock held,
 * work->state already set to KSMBD_WORK_CLOSED by the caller) -- both
 * callers hold a spinlock across this call, so it must not sleep.
 * wake_up() only wakes the waiter in smb2_notify(); it does not touch
 * fp->blocked_works itself, matching smb2_remove_blocked_lock()'s same
 * non-mutating style for the equivalent byte-range-lock wait.
 */
static void smb2_notify_cancel(void **argv)
{
	struct ksmbd_notify_req *notify_req = argv[0];

	wake_up(&notify_req->wait);
}

/**
 * smb2_notify() - handler for smb2 notify request
 * @work:   smb work containing notify command buffer
 *
 * Return:      0 on success, otherwise error
 */
int smb2_notify(struct ksmbd_work *work)
{
	struct smb2_change_notify_req *req;
	struct smb2_change_notify_rsp *rsp;
	struct ksmbd_notify_req notify_req;
	struct ksmbd_file *fp = NULL;
	void **argv = NULL;
	bool async_work = false;
	int err = 0;

	ksmbd_debug(SMB, "Received smb2 notify\n");

	WORK_BUFFERS(work, req, rsp);

	if (smb2_compound_has_failed(work, &rsp->hdr))
		return -EACCES;

	if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
		rsp->hdr.Status = STATUS_INTERNAL_ERROR;
		err = -EIO;
		goto out;
	}

	fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
	if (!fp) {
		rsp->hdr.Status = STATUS_FILE_CLOSED;
		err = -ENOENT;
		goto out;
	}

	argv = kmalloc_obj(*argv, KSMBD_DEFAULT_GFP);
	if (!argv) {
		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
		err = -ENOMEM;
		goto out;
	}
	init_waitqueue_head(&notify_req.wait);
	argv[0] = &notify_req;

	err = setup_async_work(work, smb2_notify_cancel, argv);
	if (err) {
		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
		goto out;
	}
	async_work = true;

	/*
	 * Handle close holds the file-table write lock while it marks the
	 * handle closed and walks blocked_works.  Hold the matching read lock
	 * across the state check and registration so close cannot finish its
	 * walk between the lookup above and this list insertion.
	 */
	read_lock(&work->sess->file_table.lock);
	if (fp->f_state != FP_INITED) {
		read_unlock(&work->sess->file_table.lock);
		rsp->hdr.Status = STATUS_NOTIFY_CLEANUP;
		err = -ENOENT;
		goto out;
	}
	spin_lock(&fp->f_lock);
	list_add_tail(&work->fp_entry, &fp->blocked_works);
	spin_unlock(&fp->f_lock);
	read_unlock(&work->sess->file_table.lock);

	smb2_send_interim_resp(work, STATUS_PENDING);

	err = wait_event_interruptible(notify_req.wait,
				       READ_ONCE(work->state) != KSMBD_WORK_ACTIVE);
	if (err && READ_ONCE(work->state) == KSMBD_WORK_ACTIVE) {
		/*
		 * Woken by a signal, not a real cancel/close. There is no
		 * notification backend yet to report anything else against,
		 * so treat this the same as a client-side cancel.
		 */
		WRITE_ONCE(work->state, KSMBD_WORK_CANCELLED);
	}

	spin_lock(&fp->f_lock);
	list_del_init(&work->fp_entry);
	spin_unlock(&fp->f_lock);

	rsp->hdr.Status = work->state == KSMBD_WORK_CLOSED ?
			  STATUS_NOTIFY_CLEANUP : STATUS_CANCELLED;
	smb2_send_interim_resp(work, rsp->hdr.Status);
	work->send_no_response = 1;

out:
	if (rsp->hdr.Status != STATUS_SUCCESS && !work->send_no_response)
		smb2_set_err_rsp(work);
	if (async_work)
		release_async_work(work);
	else
		kfree(argv);
	if (fp)
		ksmbd_fd_put(work, fp);
	return err;
}

/**
 * smb2_is_sign_req() - handler for checking packet signing status
 * @work:	smb work containing notify command buffer
 * @command:	SMB2 command id
 *
 * Return:	true if packed is signed, false otherwise
 */
bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
{
	struct smb2_hdr *rcv_hdr2 = smb_get_msg(work->request_buf);

	if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
	    command != SMB2_NEGOTIATE_HE)
		return true;

	return false;
}

/**
 * smb2_check_sign_req() - handler for req packet sign processing
 * @work:   smb work containing notify command buffer
 *
 * Return:	1 on success, 0 otherwise
 */
int smb2_check_sign_req(struct ksmbd_work *work)
{
	struct smb2_hdr *hdr;
	char signature_req[SMB2_SIGNATURE_SIZE];
	char signature[SMB2_HMACSHA256_SIZE];
	struct kvec iov[1];
	size_t len;

	hdr = smb_get_msg(work->request_buf);
	if (work->next_smb2_rcv_hdr_off)
		hdr = ksmbd_req_buf_next(work);

	if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
		len = get_rfc1002_len(work->request_buf);
	else if (hdr->NextCommand)
		len = le32_to_cpu(hdr->NextCommand);
	else
		len = get_rfc1002_len(work->request_buf) -
			work->next_smb2_rcv_hdr_off;

	memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);

	iov[0].iov_base = (char *)&hdr->ProtocolId;
	iov[0].iov_len = len;

	ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
			    signature);

	if (crypto_memneq(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
		pr_err("bad smb2 signature\n");
		return 0;
	}

	return 1;
}

/**
 * smb2_get_sign_rsp_iov() - get the iovecs used to sign a response
 * @work: work that has the response iovecs
 * @hdr: SMB2 header of the response
 * @n_vec: set to the number of iovecs to sign
 *
 * Response data may be in another buffer. In this case, the response uses
 * more than one iovec. Find the iovec that starts with @hdr. Sign this
 * iovec and all iovecs after it.
 *
 * Return: The first iovec to sign.
 */
static struct kvec *smb2_get_sign_rsp_iov(struct ksmbd_work *work,
					   struct smb2_hdr *hdr, int *n_vec)
{
	int i;

	/*
	 * iov[0] has the RFC1002 message length. It is not part of the SMB2
	 * message, so do not sign it.
	 */
	for (i = 1; i <= work->iov_idx; i++) {
		if (work->iov[i].iov_base == hdr) {
			*n_vec = work->iov_idx - i + 1;
			return &work->iov[i];
		}
	}

	WARN_ON_ONCE(1);
	*n_vec = 1;
	return &work->iov[work->iov_idx];
}

/**
 * smb2_set_sign_rsp() - handler for rsp packet sign processing
 * @work:   smb work containing notify command buffer
 *
 */
void smb2_set_sign_rsp(struct ksmbd_work *work)
{
	struct smb2_hdr *hdr;
	char signature[SMB2_HMACSHA256_SIZE];
	struct kvec *iov;
	int n_vec;

	hdr = ksmbd_resp_buf_curr(work);
	hdr->Flags |= SMB2_FLAGS_SIGNED;
	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);

	iov = smb2_get_sign_rsp_iov(work, hdr, &n_vec);

	ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
			    signature);
	memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
}

/**
 * smb3_check_sign_req() - handler for req packet sign processing
 * @work:   smb work containing notify command buffer
 *
 * Return:	1 on success, 0 otherwise
 */
int smb3_check_sign_req(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
	char *signing_key;
	struct smb2_hdr *hdr;
	struct channel *chann;
	char signature_req[SMB2_SIGNATURE_SIZE];
	char signature[SMB2_CMACAES_SIZE];
	struct kvec iov[1];
	size_t len;

	hdr = smb_get_msg(work->request_buf);
	if (work->next_smb2_rcv_hdr_off)
		hdr = ksmbd_req_buf_next(work);

	if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
		len = get_rfc1002_len(work->request_buf);
	else if (hdr->NextCommand)
		len = le32_to_cpu(hdr->NextCommand);
	else
		len = get_rfc1002_len(work->request_buf) -
			work->next_smb2_rcv_hdr_off;

	if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
		signing_key = work->sess->smb3signingkey;
	} else {
		chann = lookup_chann_list(work->sess, conn);
		if (!chann) {
			if (le16_to_cpu(hdr->Command) != SMB2_SESSION_SETUP_HE ||
			    !(hdr->Flags & SMB2_FLAGS_SIGNED))
				return 0;
			signing_key = work->sess->smb3signingkey;
		} else {
			signing_key = chann->smb3signingkey;
		}
	}

	if (!signing_key) {
		pr_err("SMB3 signing key is not generated\n");
		return 0;
	}

	memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
	iov[0].iov_base = (char *)&hdr->ProtocolId;
	iov[0].iov_len = len;

	ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature);

	if (crypto_memneq(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
		pr_err("bad smb2 signature\n");
		return 0;
	}

	return 1;
}

/**
 * smb3_set_sign_rsp() - handler for rsp packet sign processing
 * @work:   smb work containing notify command buffer
 *
 */
void smb3_set_sign_rsp(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
	struct smb2_hdr *hdr;
	struct channel *chann;
	char signature[SMB2_CMACAES_SIZE];
	struct kvec *iov;
	u16 command;
	int n_vec;
	char *signing_key;

	hdr = ksmbd_resp_buf_curr(work);
	command = le16_to_cpu(hdr->Command);

	if (command == SMB2_SESSION_SETUP_HE &&
	    (!work->session_setup_binding || hdr->Status != STATUS_SUCCESS)) {
		signing_key = work->sess->smb3signingkey;
	} else {
		chann = lookup_chann_list(work->sess, work->conn);
		if (!chann) {
			return;
		}
		signing_key = chann->smb3signingkey;
	}

	if (!signing_key)
		return;

	hdr->Flags |= SMB2_FLAGS_SIGNED;
	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);

	iov = smb2_get_sign_rsp_iov(work, hdr, &n_vec);

	ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec, signature);
	memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
}

/**
 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
 * @work:   smb work containing response buffer
 *
 */
void smb3_preauth_hash_rsp(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
	struct ksmbd_session *sess = work->sess;
	struct smb2_hdr *req, *rsp;

	if (conn->dialect != SMB311_PROT_ID)
		return;

	WORK_BUFFERS(work, req, rsp);

	if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE) {
		ksmbd_conn_lock(conn);
		if (conn->preauth_info)
			ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
							 conn->preauth_info->Preauth_HashValue);
		ksmbd_conn_unlock(conn);
	}

	if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
		ksmbd_conn_lock(conn);

		if (work->session_setup_binding) {
			struct preauth_session *preauth_sess;

			preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
			if (preauth_sess)
				ksmbd_gen_preauth_integrity_hash(conn,
					work->response_buf,
					preauth_sess->Preauth_HashValue);
		} else if (sess->Preauth_HashValue) {
			ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
					 sess->Preauth_HashValue);
		}
		ksmbd_conn_unlock(conn);
	}
}

static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
{
	struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
	struct smb2_hdr *hdr = smb_get_msg(old_buf);
	unsigned int orig_len = get_rfc1002_len(old_buf);

	/* tr_buf must be cleared by the caller */
	tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
	tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
	tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
	if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
	    cipher_type == SMB2_ENCRYPTION_AES256_GCM)
		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
	else
		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
	memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
	inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
	inc_rfc1001_len(tr_buf, orig_len);
}

int smb3_encrypt_resp(struct ksmbd_work *work)
{
	struct kvec *iov = work->iov;
	int rc = -ENOMEM;
	void *tr_buf;

	tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, KSMBD_DEFAULT_GFP);
	if (!tr_buf)
		return rc;

	/* fill transform header */
	fill_transform_hdr(tr_buf, work->response_buf, work->conn->cipher_type);

	iov[0].iov_base = tr_buf;
	iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
	work->tr_buf = tr_buf;

	return ksmbd_crypt_message(work, iov, work->iov_idx + 1, 1);
}

bool smb3_is_transform_hdr(void *buf)
{
	struct smb2_transform_hdr *trhdr = smb_get_msg(buf);

	return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
}

/*
 * The decryption key is selected by the transform SessionId, but
 * the request is authorized under the session named in the
 * decrypted SMB2 header. Per MS-SMB2 the two must match, so check
 * the decrypted message and its compound chain before dispatch.
 */
int ksmbd_check_transform_session(struct ksmbd_work *work, u64 tr_sess_id)
{
	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
	size_t msg_len = get_rfc1002_len(work->request_buf);
	size_t off = 0;
	bool first = true;

	if (msg_len < sizeof(*hdr)) {
		pr_err_ratelimited("Decrypted message is smaller than SMB2 header\n");
		return -ECONNABORTED;
	}

	for (;;) {
		u64 sid = le64_to_cpu(hdr->SessionId);
		u32 next;

		if (first) {
			if (hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS) {
				pr_err_ratelimited("RELATED_OPERATIONS set on first operation\n");
				return -ECONNABORTED;
			}
			if (sid != tr_sess_id) {
				pr_err_ratelimited("SessionId mismatch between transform and inner header\n");
				return -ECONNABORTED;
			}
			first = false;
		} else if (!(hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS) &&
			   sid != tr_sess_id) {
			pr_err_ratelimited("SessionId mismatch in compound chain\n");
			return -ECONNABORTED;
		}

		next = le32_to_cpu(hdr->NextCommand);
		if (!next)
			return 0;
		if (next % 8) {
			pr_err_ratelimited("NextCommand %u is not 8-byte aligned\n", next);
			return -ECONNABORTED;
		}
		if (next > msg_len - off - sizeof(*hdr)) {
			pr_err_ratelimited("NextCommand %u is out of the message\n", next);
			return -ECONNABORTED;
		}
		off += next;
		hdr = (struct smb2_hdr *)((u8 *)smb_get_msg(work->request_buf) + off);
	}
}

int smb3_decrypt_req(struct ksmbd_work *work)
{
	char *buf = work->request_buf;
	unsigned int pdu_length = get_rfc1002_len(buf);
	struct kvec iov[2];
	unsigned int buf_data_size;
	struct smb2_transform_hdr *tr_hdr = smb_get_msg(buf);
	unsigned int original_msg_size;
	int rc = 0;

	if (pdu_length < sizeof(struct smb2_transform_hdr)) {
		pr_err("Transform message is too small (%u)\n",
		       pdu_length);
		return -ECONNABORTED;
	}

	if (tr_hdr->Flags != cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED)) {
		pr_err_ratelimited("Invalid transform flags 0x%04x\n",
				   le16_to_cpu(tr_hdr->Flags));
		return -ECONNABORTED;
	}

	buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
	original_msg_size = le32_to_cpu(tr_hdr->OriginalMessageSize);
	if (buf_data_size < sizeof(struct smb2_compression_hdr) ||
	    original_msg_size < sizeof(struct smb2_compression_hdr)) {
		pr_err("Transform message is too small (%u)\n",
		       pdu_length);
		return -ECONNABORTED;
	}

	if (buf_data_size < original_msg_size) {
		pr_err("Transform message is broken\n");
		return -ECONNABORTED;
	}

	iov[0].iov_base = buf;
	iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
	iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
	iov[1].iov_len = buf_data_size;
	rc = ksmbd_crypt_message(work, iov, 2, 0);
	if (rc)
		return rc;

	/* Drop the AEAD authentication tag from the inner RFC1002 frame. */
	memmove(buf + 4, iov[1].iov_base, original_msg_size);
	*(__be32 *)buf = cpu_to_be32(original_msg_size);

	return rc;
}

bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
	struct ksmbd_session *sess = work->sess;
	struct smb2_hdr *rsp = smb_get_msg(work->response_buf);

	if (conn->dialect < SMB30_PROT_ID)
		return false;

	if (work->next_smb2_rcv_hdr_off)
		rsp = ksmbd_resp_buf_next(work);

	if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
	    sess->user && !user_guest(sess->user) &&
	    rsp->Status == STATUS_SUCCESS)
		return true;
	return false;
}