Skip to contentSkip to conversation

ksmbd: release connection lock while draining old session

PATCH New Namjae Jeon 1 participant 22 messages Oct 17

Subsystems (2)
lore
Share & tools
lore

Namjae Jeon

author maintainer
#0 lore raw

PATCH 1/22 ksmbd: release connection lock while draining old session

Previous-session teardown waits for requests on the old channels. Holding srv_mutex during that wait can block their responses and prevent the drain from completing.

Record the previous session ID during authentication, finish using the request's authentication state, and release srv_mutex while the old session drains. Keep the response binding decision in the work item because signing and preauthentication hashing run after the drain.

---
 fs/smb/server/ksmbd_work.h        |  2 ++
 fs/smb/server/mgmt/user_session.c | 15 +++++++++
 fs/smb/server/smb2pdu.c           | 56 ++++++++++++++++++-------------
 3 files changed, 49 insertions(+), 24 deletions(-)
fs/smb/server/ksmbd_work.h +2 -0
index 3a14e4d69aa1..40f70a5d08b5 100644
@@ -94,6 +94,8 @@ struct ksmbd_work {
 	bool                            need_invalidate_rkey:1;
 	bool				request_open_chseq_tracked:1;
 	bool				session_setup_reauth:1;
+	/* Retain the binding decision for response signing and preauth hashing. */
+	bool				session_setup_binding:1;
 
 	unsigned int                    remote_key;
 	/* cancel works */
fs/smb/server/mgmt/user_session.c +15 -0
index 1321cd6c84e7..d814a99ff519 100644
@@ -759,6 +759,7 @@ void destroy_previous_session(struct ksmbd_conn *conn,
 {
 	struct ksmbd_session *prev_sess;
 	struct ksmbd_user *prev_user;
+	bool pinned = false;
 	int err;
 
 	down_write(&sessions_table_lock);
@@ -781,9 +782,21 @@ void destroy_previous_session(struct ksmbd_conn *conn,
 	}
 	prev_sess->tearing_down = true;
 	up_write(&prev_sess->chann_lock);
+	ksmbd_user_session_get(prev_sess);
+	pinned = true;
+	up_write(&conn->session_lock);
+	up_write(&sessions_table_lock);
 
 	ksmbd_all_conn_set_status(prev_sess, KSMBD_SESS_NEED_RECONNECT);
+	/*
+	 * The caller has finished using the connection's authentication state.
+	 * Drop srv_mutex so drained requests can write their responses.
+	 */
+	ksmbd_conn_unlock(conn);
 	err = ksmbd_conn_wait_idle_sess(conn, prev_sess);
+	ksmbd_conn_lock(conn);
+	down_write(&sessions_table_lock);
+	down_write(&conn->session_lock);
 	if (err) {
 		down_write(&prev_sess->chann_lock);
 		prev_sess->tearing_down = false;
@@ -800,6 +813,8 @@ void destroy_previous_session(struct ksmbd_conn *conn,
 out:
 	up_write(&conn->session_lock);
 	up_write(&sessions_table_lock);
+	if (pinned)
+		ksmbd_user_session_put(prev_sess);
 }
 
 static bool ksmbd_preauth_session_id_match(struct preauth_session *sess,
fs/smb/server/smb2pdu.c +32 -24

140 lines not on this page · raw message

Signature · 1 line
2.25.1
author maintainer
#1 lore raw

PATCH 2/22 ksmbd: serialize oplock break ACK state updates

ACK handling updates lease or oplock levels and wakes break waiters. Without state_lock across validation and publication, timeout or break completion can observe a partially updated state.

Serialize ACK validation and state changes under state_lock. Publish NONE after lease levels are updated, then wake waiters after unlocking.

---
 fs/smb/server/smb2pdu.c | 64 +++++++++++++++++++----------------------
 1 file changed, 29 insertions(+), 35 deletions(-)
fs/smb/server/smb2pdu.c +29 -35
index aca51f54a38d..b45453a29fbb 100644
@@ -11919,6 +11919,8 @@ static void smb20_oplock_break_ack(struct ksmbd_work *work)
 		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);
@@ -11930,6 +11932,7 @@ static void smb20_oplock_break_ack(struct ksmbd_work *work)
 			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)
@@ -11986,6 +11989,9 @@ static void smb20_oplock_break_ack(struct ksmbd_work *work)
 		rsp_oplevel = req_oplevel;
 
 	opinfo->level = rsp_oplevel;
+	opinfo->op_state = OPLOCK_STATE_NONE;
+	spin_unlock(&opinfo->state_lock);
+	wake_up_interruptible_all(&opinfo->oplock_q);
 
 	rsp->StructureSize = cpu_to_le16(24);
 	rsp->OplockLevel = rsp_oplevel;
@@ -11997,18 +12003,15 @@ static void smb20_oplock_break_ack(struct ksmbd_work *work)
 	if (ret)
 		ksmbd_debug(SMB, "failed to pin oplock break response: %d\n",
 			    ret);
-	goto out;
+	goto out_no_state_change;
 
 err_out:
-	rsp->hdr.Status = status;
-	smb2_set_err_rsp(work);
-
-out:
-	spin_lock(&opinfo->state_lock);
 	if (opinfo->op_state != OPLOCK_CLOSING)
 		opinfo->op_state = OPLOCK_STATE_NONE;
 	spin_unlock(&opinfo->state_lock);
 	wake_up_interruptible_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);
@@ -12042,7 +12045,7 @@ static void smb21_lease_break_ack(struct ksmbd_work *work)
 	struct smb2_lease_ack *req;
 	struct smb2_lease_ack *rsp;
 	struct oplock_info *opinfo;
-	int ret = 0;
+	int ret;
 	__le32 lease_state;
 	struct lease *lease;
 
@@ -12053,26 +12056,27 @@ static void smb21_lease_break_ack(struct ksmbd_work *work)
 	opinfo = lookup_lease_in_table(conn, req->LeaseKey);
 	if (!opinfo) {
 		ksmbd_debug(OPLOCK, "file not opened\n");
-		smb2_set_err_rsp(work);
 		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
+		smb2_set_err_rsp(work);
 		return;
 	}
 	lease = opinfo->o_lease;
 
-	if (opinfo->op_state == OPLOCK_STATE_NONE) {
-		pr_err("unexpected lease break state 0x%x\n",
-		       opinfo->op_state);
-		if (smb3_hdr_replay(&req->hdr))
+	/* Publish NONE only after the lease state and all open levels are updated. */
+	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_out;
+		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_out;
+		goto err_unlock;
 	}
 
 	if (check_lease_state(lease, req->LeaseState)) {
@@ -12080,40 +12084,29 @@ static void smb21_lease_break_ack(struct ksmbd_work *work)
 		ksmbd_debug(OPLOCK,
 			    "req lease state: 0x%x, expected state: 0x%x\n",
 			    req->LeaseState, lease->new_state);
-		goto err_out;
+		goto err_unlock;
 	}
 
 	lease_state = req->LeaseState;
 	lease->state = lease_state;
 	lease->new_state = SMB2_LEASE_NONE_LE;
 	lease_update_oplock_levels(lease);
-
-	rsp->StructureSize = cpu_to_le16(36);
-	rsp->Reserved = 0;
-	rsp->Flags = 0;
-	memcpy(rsp->LeaseKey, req->LeaseKey, 16);
-	rsp->LeaseState = lease_state;
-	rsp->LeaseDuration = 0;
-	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack));
-	if (ret)
-		goto err_out;
-
-	spin_lock(&opinfo->state_lock);
-	if (opinfo->op_state != OPLOCK_CLOSING)
-		opinfo->op_state = OPLOCK_STATE_NONE;
+	opinfo->op_state = OPLOCK_STATE_NONE;
+	atomic_dec_if_positive(&opinfo->breaking_cnt);
 	spin_unlock(&opinfo->state_lock);
 	wake_up_interruptible_all(&opinfo->oplock_q);
-	atomic_dec_if_positive(&opinfo->breaking_cnt);
 	wake_up_interruptible_all(&opinfo->oplock_brk);
-	opinfo_put(opinfo);
-	return;
+	goto response;
 
 replay_rsp:
+	lease_state = lease->state;
+	spin_unlock(&opinfo->state_lock);
+response:
 	rsp->StructureSize = cpu_to_le16(36);
 	rsp->Reserved = 0;
 	rsp->Flags = 0;
-	memcpy(rsp->LeaseKey, req->LeaseKey, 16);
-	rsp->LeaseState = lease->state;
+	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)
@@ -12121,10 +12114,11 @@ static void smb21_lease_break_ack(struct ksmbd_work *work)
 	opinfo_put(opinfo);
 	return;
 
+err_unlock:
+	spin_unlock(&opinfo->state_lock);
 err_out:
 	smb2_set_err_rsp(work);
 	opinfo_put(opinfo);
-	return;
 }
 
 /**
Signature · 1 line
2.25.1
author maintainer
#2 lore raw

PATCH 3/22 ksmbd: track delivery of queued TCP writes

In reply to Namjae Jeon

A nonblocking break send must distinguish a PDU accepted by TCP from one still queued in ksmbd. Retrying an accepted PDU can send duplicates, while abandoning a partial send can corrupt the stream.

Queue owned PDU bytes when TCP cannot accept the full message. Track the stream position through socket delivery and TCP ACK, and expose it to break retries. Bound retained data and stop queued writes during teardown.

---
 fs/smb/server/connection.c    |  52 +++++-
 fs/smb/server/connection.h    |  24 ++-
 fs/smb/server/transport_tcp.c | 299 +++++++++++++++++++++++++++++++++-
 3 files changed, 356 insertions(+), 19 deletions(-)
fs/smb/server/connection.c +44 -8
index d1cc725eeb06..19d32681bb92 100644
@@ -457,17 +457,13 @@ void ksmbd_all_conn_set_status(struct ksmbd_session *sess, u32 status)
 
 void ksmbd_conn_abort(struct ksmbd_conn *conn)
 {
-	bool shutdown = false;
-
 	spin_lock(&conn->request_lock);
-	if (!ksmbd_conn_exiting(conn) && !ksmbd_conn_releasing(conn)) {
+	if (!ksmbd_conn_exiting(conn) && !ksmbd_conn_releasing(conn))
 		ksmbd_conn_set_exiting(conn);
-		shutdown = true;
-	}
 	spin_unlock(&conn->request_lock);
 	wake_up_all(&conn->req_running_q);
 
-	if (shutdown && conn->transport->ops->shutdown)
+	if (conn->transport->ops->shutdown)
 		conn->transport->ops->shutdown(conn->transport);
 }
 
@@ -534,12 +530,19 @@ static int __ksmbd_conn_write(struct ksmbd_work *work,
 	tx->need_invalidate_rkey = work->need_invalidate_rkey;
 	tx->remote_key = work->remote_key;
 
-	ksmbd_conn_lock(conn);
+	if (tx->tracking) {
+		/* A busy writer must not consume the break's retry budget. */
+		if (!mutex_trylock(&conn->srv_mutex))
+			return -EAGAIN;
+	} else {
+		ksmbd_conn_lock(conn);
+	}
 	sent = conn->transport->ops->writev(conn->transport, tx);
 	ksmbd_conn_unlock(conn);
 
 	if (sent < 0) {
-		pr_err("Failed to send message: %d\n", sent);
+		if (!tx->tracking || sent != -EAGAIN)
+			pr_err("Failed to send message: %d\n", sent);
 		return sent;
 	}
 
@@ -553,6 +556,20 @@ int ksmbd_conn_write(struct ksmbd_work *work)
 	return __ksmbd_conn_write(work, &tx);
 }
 
+int ksmbd_conn_write_tracked(struct ksmbd_work *work,
+			     struct ksmbd_tx_tracking *tracking)
+{
+	struct ksmbd_transport_write tx = {};
+
+	tracking->valid = false;
+	/* Transports without delivery tracking keep their synchronous send path. */
+	if (work->conn->transport->ops->is_acked) {
+		tx.msg_flags = MSG_DONTWAIT;
+		tx.tracking = tracking;
+	}
+	return __ksmbd_conn_write(work, &tx);
+}
+
 int ksmbd_conn_write_eor(struct ksmbd_work *work)
 {
 	struct ksmbd_transport_write tx = {
@@ -805,7 +822,12 @@ int ksmbd_conn_handler_loop(void *p)
 		}
 	}
 
+	/* Exclude new break senders before draining their work references. */
+	spin_lock(&conn->request_lock);
 	ksmbd_conn_set_releasing(conn);
+	spin_unlock(&conn->request_lock);
+	/* TCP writers waiting for queue space must release their work references. */
+	wake_up_all(&conn->req_running_q);
 	ksmbd_conn_cancel_async_requests(conn);
 	/* Wait till all reference dropped to the Server object*/
 	ksmbd_debug(CONN, "Wait for all pending requests(%d)\n", atomic_read(&conn->r_count));
@@ -832,6 +854,20 @@ void ksmbd_conn_r_count_inc(struct ksmbd_conn *conn)
 	atomic_inc(&conn->r_count);
 }
 
+/* The caller already owns a connection reference. */
+bool ksmbd_conn_r_count_inc_if_good(struct ksmbd_conn *conn)
+{
+	bool ret = false;
+
+	spin_lock(&conn->request_lock);
+	if (ksmbd_conn_good(conn)) {
+		atomic_inc(&conn->r_count);
+		ret = true;
+	}
+	spin_unlock(&conn->request_lock);
+	return ret;
+}
+
 void ksmbd_conn_r_count_dec(struct ksmbd_conn *conn)
 {
 	/*
fs/smb/server/connection.h +22 -2
index 2026a2afa5e4..85e2d2073cd2 100644
@@ -103,6 +103,8 @@ struct ksmbd_conn {
 	wait_queue_head_t		r_count_q;
 	/* Lock to protect requests list*/
 	spinlock_t			request_lock;
+	/* Set under request_lock at teardown start and kept set thereafter. */
+	bool				releasing;
 	struct list_head		requests;
 	struct list_head		async_requests;
 	int				connection_type;
@@ -162,6 +164,13 @@ struct ksmbd_conn_ops {
 	int	(*terminate_fn)(struct ksmbd_conn *conn);
 };
 
+struct ksmbd_tx_tracking {
+	/* Required TCP byte count, including transport and socket queues. */
+	u64		end;
+	unsigned long	retry_after;
+	bool		valid;
+};
+
 struct ksmbd_transport_write {
 	struct kvec	*iov;
 	int		iov_cnt;
@@ -169,6 +178,7 @@ struct ksmbd_transport_write {
 	bool		need_invalidate_rkey;
 	unsigned int	remote_key;
 	int		msg_flags;
+	struct ksmbd_tx_tracking *tracking;
 };
 
 struct ksmbd_transport_ops {
@@ -176,8 +186,12 @@ struct ksmbd_transport_ops {
 	void (*shutdown)(struct ksmbd_transport *t);
 	int (*read)(struct ksmbd_transport *t, char *buf,
 		    unsigned int size, int max_retries);
+	/* Retained bytes must be privately owned before a full result is returned. */
 	int (*writev)(struct ksmbd_transport *t,
 		      const struct ksmbd_transport_write *tx);
+	/* Optional delivery tracking for nonblocking break sends. */
+	bool (*is_acked)(struct ksmbd_transport *t,
+			 const struct ksmbd_tx_tracking *tracking);
 	int (*rdma_read)(struct ksmbd_transport *t,
 			 void *buf, unsigned int len,
 			 struct smbdirect_buffer_descriptor_v1 *desc,
@@ -217,6 +231,8 @@ int ksmbd_conn_wq_init(void);
 void ksmbd_conn_wq_destroy(void);
 bool ksmbd_conn_lookup_dialect(struct ksmbd_conn *c);
 int ksmbd_conn_write(struct ksmbd_work *work);
+int ksmbd_conn_write_tracked(struct ksmbd_work *work,
+			     struct ksmbd_tx_tracking *tracking);
 int ksmbd_conn_write_eor(struct ksmbd_work *work);
 int ksmbd_conn_rdma_read(struct ksmbd_conn *conn,
 			 void *buf, unsigned int buflen,
@@ -235,6 +251,7 @@ void ksmbd_conn_transport_destroy(void);
 void ksmbd_conn_lock(struct ksmbd_conn *conn);
 void ksmbd_conn_unlock(struct ksmbd_conn *conn);
 void ksmbd_conn_r_count_inc(struct ksmbd_conn *conn);
+bool ksmbd_conn_r_count_inc_if_good(struct ksmbd_conn *conn);
 void ksmbd_conn_r_count_dec(struct ksmbd_conn *conn);
 
 /*
@@ -250,7 +267,8 @@ static inline bool ksmbd_conn_new(struct ksmbd_conn *conn)
 
 static inline bool ksmbd_conn_good(struct ksmbd_conn *conn)
 {
-	return READ_ONCE(conn->status) == KSMBD_SESS_GOOD;
+	return !READ_ONCE(conn->releasing) &&
+		READ_ONCE(conn->status) == KSMBD_SESS_GOOD;
 }
 
 static inline unsigned int
@@ -284,7 +302,8 @@ static inline bool ksmbd_conn_exiting(struct ksmbd_conn *conn)
 
 static inline bool ksmbd_conn_releasing(struct ksmbd_conn *conn)
 {
-	return READ_ONCE(conn->status) == KSMBD_SESS_RELEASING;
+	return READ_ONCE(conn->releasing) ||
+		READ_ONCE(conn->status) == KSMBD_SESS_RELEASING;
 }
 
 static inline void ksmbd_conn_set_new(struct ksmbd_conn *conn)
@@ -319,6 +338,7 @@ static inline void ksmbd_conn_set_exiting(struct ksmbd_conn *conn)
 
 static inline void ksmbd_conn_set_releasing(struct ksmbd_conn *conn)
 {
+	WRITE_ONCE(conn->releasing, true);
 	WRITE_ONCE(conn->status, KSMBD_SESS_RELEASING);
 }
 
fs/smb/server/transport_tcp.c +290 -9

373 lines not on this page · raw message

Signature · 1 line
2.25.1
author maintainer
#3 lore raw

PATCH 4/22 ksmbd: retry break notifications on another connection

In reply to Namjae Jeon

An oplock or lease break belongs to an open that can outlive its original channel. A draining channel or stalled TCP writer can otherwise leave the break pending until timeout or invalidate a durable open.

Snapshot the owner's live channels and try eligible connections with the same notification. Track TCP delivery separately from the SMB ACK, retry when a channel stops progressing, and share one break deadline. Run ordinary break waits on a dedicated workqueue so blocked request responses do not stall breaks.

Publish NONE before sending a level II break, which requires no ACK, so an unsolicited ACK observes the completed level while TCP delivery is pending.

Keep the first rename lease notification in the request context and enqueue the interim writer only after the notification is accepted. Join that work before returning so a blocked interim response does not stop notification retries or release the request early.

---
 fs/smb/server/ksmbd_work.c        |  19 +
 fs/smb/server/ksmbd_work.h        |   2 +
 fs/smb/server/mgmt/user_session.c |  31 ++
 fs/smb/server/mgmt/user_session.h |   3 +
 fs/smb/server/oplock.c            | 855 +++++++++++++++++-------------
 fs/smb/server/oplock.h            |  14 +-
 fs/smb/server/vfs_cache.c         |   2 +
 7 files changed, 539 insertions(+), 387 deletions(-)
fs/smb/server/ksmbd_work.c +19 -0
index 52ea1a674a67..6e5122e2d6fc 100644
@@ -16,6 +16,7 @@
 
 static struct kmem_cache *work_cache;
 static struct workqueue_struct *ksmbd_wq;
+static struct workqueue_struct *ksmbd_break_wq;
 
 static int ksmbd_reserve_iov(struct ksmbd_work *work, int need_iov_cnt)
 {
@@ -110,6 +111,12 @@ int ksmbd_workqueue_init(void)
 	ksmbd_wq = alloc_workqueue("ksmbd-io", WQ_PERCPU, 0);
 	if (!ksmbd_wq)
 		return -ENOMEM;
+	ksmbd_break_wq = alloc_workqueue("ksmbd-break", WQ_UNBOUND, 0);
+	if (!ksmbd_break_wq) {
+		destroy_workqueue(ksmbd_wq);
+		ksmbd_wq = NULL;
+		return -ENOMEM;
+	}
 	return 0;
 }
 
@@ -117,6 +124,8 @@ void ksmbd_workqueue_destroy(void)
 {
 	destroy_workqueue(ksmbd_wq);
 	ksmbd_wq = NULL;
+	destroy_workqueue(ksmbd_break_wq);
+	ksmbd_break_wq = NULL;
 }
 
 bool ksmbd_queue_work(struct ksmbd_work *work)
@@ -124,6 +133,16 @@ bool ksmbd_queue_work(struct ksmbd_work *work)
 	return queue_work(ksmbd_wq, &work->work);
 }
 
+void ksmbd_queue_io_work(struct work_struct *work)
+{
+	queue_work(ksmbd_wq, work);
+}
+
+void ksmbd_queue_break_work(struct work_struct *work)
+{
+	queue_work(ksmbd_break_wq, work);
+}
+
 static inline void __ksmbd_iov_pin(struct ksmbd_work *work, void *ib,
 				   unsigned int ib_len)
 {
fs/smb/server/ksmbd_work.h +2 -0
index 40f70a5d08b5..b51dea69cb0e 100644
@@ -155,6 +155,8 @@ int ksmbd_work_pool_init(void);
 int ksmbd_workqueue_init(void);
 void ksmbd_workqueue_destroy(void);
 bool ksmbd_queue_work(struct ksmbd_work *work);
+void ksmbd_queue_io_work(struct work_struct *work);
+void ksmbd_queue_break_work(struct work_struct *work);
 int ksmbd_iov_pin_rsp_read(struct ksmbd_work *work, void *ib, int len,
 			   void *aux_buf, unsigned int aux_size);
 int ksmbd_iov_pin_rsp(struct ksmbd_work *work, void *ib, int len);
fs/smb/server/mgmt/user_session.c +31 -0
index d814a99ff519..554434c7673a 100644
@@ -674,6 +674,37 @@ struct ksmbd_session *ksmbd_session_lookup_slowpath(unsigned long long id)
 	return sess;
 }
 
+/* The caller holds a session reference and must put each returned connection. */
+unsigned int ksmbd_session_get_channels(struct ksmbd_session *sess,
+					struct ksmbd_conn **conns,
+					unsigned int max_conns)
+{
+	struct channel *chann;
+	unsigned long index;
+	unsigned int nr_conns = 0;
+
+	/*
+	 * Channel connections are borrowed. Unregister can leave the channel
+	 * list in a pinned session after removing it from the registry, so
+	 * chann_lock alone does not keep those connections alive. Only collect
+	 * registered sessions, excluding both unregister and connection cleanup
+	 * until the connection references have been taken.
+	 */
+	down_read(&sessions_table_lock);
+	if (hlist_unhashed(&sess->hlist))
+		goto out;
+	down_read(&sess->chann_lock);
+	xa_for_each(&sess->ksmbd_chann_list, index, chann) {
+		if (nr_conns == max_conns)
+			break;
+		conns[nr_conns++] = ksmbd_conn_get(chann->conn);
+	}
+	up_read(&sess->chann_lock);
+out:
+	up_read(&sessions_table_lock);
+	return nr_conns;
+}
+
 struct ksmbd_session *ksmbd_session_lookup_all_states(struct ksmbd_conn *conn,
 						      unsigned long long id)
 {
fs/smb/server/mgmt/user_session.h +3 -0
index 217258551d6d..aff31f1694db 100644
@@ -94,6 +94,9 @@ struct ksmbd_session *ksmbd_smb2_session_create(void);
 void ksmbd_session_destroy(struct ksmbd_session *sess);
 
 struct ksmbd_session *ksmbd_session_lookup_slowpath(unsigned long long id);
+unsigned int ksmbd_session_get_channels(struct ksmbd_session *sess,
+					struct ksmbd_conn **conns,
+					unsigned int max_conns);
 struct ksmbd_session *ksmbd_session_lookup(struct ksmbd_conn *conn,
 					   unsigned long long id);
 bool is_ksmbd_session_in_connection(struct ksmbd_conn *conn,
fs/smb/server/oplock.c +481 -374

1,057 lines not on this page · raw message

fs/smb/server/oplock.h +1 -13
index b08d21758e07..e114e2148c30 100644
@@ -62,6 +62,7 @@ struct lease {
 struct oplock_info {
 	struct ksmbd_conn	*conn;
 	struct ksmbd_session	*sess;
+	u64			session_id;
 	struct ksmbd_work	*work;
 	struct ksmbd_file	*o_fp;
 	int                     level;
@@ -82,19 +83,6 @@ struct oplock_info {
 	struct rcu_head		rcu;
 };
 
-struct lease_break_info {
-	__le32			curr_state;
-	__le32			new_state;
-	__le16			epoch;
-	char			lease_key[SMB2_LEASE_KEY_SIZE];
-};
-
-struct oplock_break_info {
-	int level;
-	int open_trunc;
-	int fid;
-};
-
 int smb_grant_oplock(struct ksmbd_work *work, int req_op_level,
 		     u64 pid, struct ksmbd_file *fp, __u16 tid,
 		     struct lease_ctx_info *lctx, int share_ret, bool replay);
fs/smb/server/vfs_cache.c +2 -0
index 496055ce4a4d..11c123673f9a 100644
@@ -1767,6 +1767,7 @@ static bool session_fd_check(struct ksmbd_tree_connect *tcon,
 		ksmbd_conn_put(op->conn);
 		op->conn = NULL;
 		op->sess = NULL;
+		op->session_id = 0;
 	}
 	up_write(&ci->m_lock);
 
@@ -1953,6 +1954,7 @@ int ksmbd_reopen_durable_fd(struct ksmbd_work *work, struct ksmbd_file *fp)
 			continue;
 		op->conn = ksmbd_conn_get(fp->conn);
 		op->sess = work->sess;
+		op->session_id = work->sess->id;
 	}
 	up_write(&ci->m_lock);
 
Signature · 1 line
2.25.1
author maintainer
#4 lore raw

PATCH 5/22 ksmbd: keep lease tables until their last lease is closed

In reply to Namjae Jeon

Disconnecting one channel destroys the lease table for its ClientGuid, even when another channel still uses the same opens. A lease break ACK on the surviving channel can no longer find the lease. Detached durable opens also lose their lease lookup entries before reconnect or expiry.

Tie a client table to its lease entries instead of the connection which created it. Remove the table when its last lease is removed, and release any remaining entries at server shutdown. Do not destroy client tables from connection teardown or keep a connection reference in each table.

For a detached lease, collect break candidates using the table's ClientGuid directly. The existing notification retry path takes its own references on matching live connections.

Fixes 0626e6641f6b ("cifsd: add server handler for central processing and tranport layers")
---
 fs/smb/server/oplock.c | 46 +++++++++++++++++-------------------------
 fs/smb/server/oplock.h |  3 +--
 fs/smb/server/server.c |  3 +--
 3 files changed, 20 insertions(+), 32 deletions(-)
fs/smb/server/oplock.c +18 -28
index 313bf01ad350..96b36b8329a6 100644
@@ -125,6 +125,12 @@ static void lease_add_table(struct lease *lease, struct lease_table *lb)
 	spin_unlock(&lb->lb_lock);
 }
 
+static void free_lease_table(struct lease_table *lb)
+{
+	kfree(lb);
+}
+
+/* The caller holds lease_list_lock for write. */
 static void lease_del_table(struct lease *lease)
 {
 	struct lease_table *lb = lease->l_lb;
@@ -143,6 +149,10 @@ static void lease_del_table(struct lease *lease)
 	spin_unlock(&lb->lb_lock);
 
 	lease_put(lease);
+	if (list_empty(&lb->lease_list)) {
+		list_del(&lb->l_entry);
+		free_lease_table(lb);
+	}
 }
 
 static struct lease_table *alloc_lease_table(struct oplock_info *opinfo)
@@ -155,21 +165,11 @@ static struct lease_table *alloc_lease_table(struct oplock_info *opinfo)
 
 	memcpy(lb->client_guid, opinfo->conn->ClientGUID,
 	       SMB2_CLIENT_GUID_SIZE);
-	lb->conn = ksmbd_conn_get(opinfo->conn);
 	INIT_LIST_HEAD(&lb->lease_list);
 	spin_lock_init(&lb->lb_lock);
 	return lb;
 }
 
-static void free_lease_table(struct lease_table *lb)
-{
-	if (!lb)
-		return;
-
-	ksmbd_conn_put(lb->conn);
-	kfree(lb);
-}
-
 static struct lease *alloc_lease(struct lease_ctx_info *lctx,
 				 struct ksmbd_inode *ci)
 {
@@ -927,8 +927,6 @@ static int smb2_break_collect_channels(struct oplock_info *opinfo,
 		if (lb) {
 			memcpy(guid, lb->client_guid, sizeof(guid));
 			have_guid = true;
-			if (lb->conn)
-				owner->conn = ksmbd_conn_get(lb->conn);
 		}
 		read_unlock(&lease_list_lock);
 	}
@@ -1495,25 +1493,17 @@ static void oplock_break_drain_none(struct list_head *head,
 	}
 }
 
-void destroy_lease_table(struct ksmbd_conn *conn)
+void destroy_lease_table(void)
 {
-	struct lease_table *lb, *lbtmp;
-	struct lease *lease, *ltmp;
+	struct lease_table *lb;
+	struct lease *lease;
 
 	write_lock(&lease_list_lock);
-	if (list_empty(&lease_table_list)) {
-		write_unlock(&lease_list_lock);
-		return;
-	}
-
-	list_for_each_entry_safe(lb, lbtmp, &lease_table_list, l_entry) {
-		if (conn && memcmp(lb->client_guid, conn->ClientGUID,
-				   SMB2_CLIENT_GUID_SIZE))
-			continue;
-		list_for_each_entry_safe(lease, ltmp, &lb->lease_list, l_entry)
-			lease_del_table(lease);
-		list_del(&lb->l_entry);
-		free_lease_table(lb);
+	while (!list_empty(&lease_table_list)) {
+		lb = list_first_entry(&lease_table_list, struct lease_table,
+				      l_entry);
+		lease = list_first_entry(&lb->lease_list, struct lease, l_entry);
+		lease_del_table(lease);
 	}
 	write_unlock(&lease_list_lock);
 }
fs/smb/server/oplock.h +1 -2
index e114e2148c30..5ef05166e502 100644
@@ -34,7 +34,6 @@ struct lease_ctx_info {
 
 struct lease_table {
 	char			client_guid[SMB2_CLIENT_GUID_SIZE];
-	struct ksmbd_conn	*conn;
 	struct list_head	lease_list;
 	struct list_head	l_entry;
 	spinlock_t		lb_lock;
@@ -122,7 +121,7 @@ struct oplock_info *lookup_lease_in_table(struct ksmbd_conn *conn,
 					  char *lease_key);
 int find_same_lease_key(struct ksmbd_conn *conn, struct ksmbd_inode *ci,
 			struct lease_ctx_info *lctx);
-void destroy_lease_table(struct ksmbd_conn *conn);
+void destroy_lease_table(void);
 void smb_send_parent_lease_break_noti(struct ksmbd_file *fp,
 				      struct lease_ctx_info *lctx);
 void smb_lazy_parent_lease_break_close(struct ksmbd_file *fp);
fs/smb/server/server.c +1 -2
index 1cb995a36b21..effc539548dc 100644
@@ -436,7 +436,6 @@ static int ksmbd_server_process_request(struct ksmbd_conn *conn)
 static int ksmbd_server_terminate_conn(struct ksmbd_conn *conn)
 {
 	ksmbd_conn_sessions_cleanup(conn);
-	destroy_lease_table(conn);
 	return 0;
 }
 
@@ -664,7 +663,7 @@ static int ksmbd_server_shutdown(void)
 	ksmbd_proc_cleanup();
 	ksmbd_crypto_destroy();
 	ksmbd_free_global_file_table();
-	destroy_lease_table(NULL);
+	destroy_lease_table();
 	ksmbd_work_pool_destroy();
 	ksmbd_exit_file_cache();
 	server_conf_free();
Signature · 1 line
2.25.1
author maintainer
#5 lore raw

PATCH 6/22 ksmbd: index byte-range locks independently of their connection

In reply to Namjae Jeon

SMB locks belong to an open, but the lock conflict and UNLOCK scan only visits connections in conn_list. When a channel is removed, its locks remain attached to live opens and become invisible to another channel. An exact UNLOCK returns STATUS_RANGE_NOT_LOCKED, and zero-byte lock conflicts are no longer detected. A request finishing on the old channel after it is removed can publish another invisible lock.

Index granted SMB locks by VFS inode, with the open's lock_list retaining ownership. Protect lookup, publication and removal with one spinlock. Use the inode rather than the dentry-based ksmbd_inode so hard-link opens still participate in the same conflict checks.

Keep these entries through durable detach and reconnect. Publish a batch only after the existing LOCK handler commits it, and remove every entry before final close drops the file reference. Drop the per-lock connection references and connection-local lists; channel changes no longer require moving lock entries or waiting for unrelated requests to finish.

Prefer an exclusive lock when several locks on an open match an UNLOCK. This preserves stacked zero-byte lock behavior despite the inode hash inserting newer locks before older entries.

Fixes d63528eb0d43 ("ksmbd: free ksmbd_lock when file is closed")
---
 fs/smb/server/connection.c |   2 -
 fs/smb/server/connection.h |   2 -
 fs/smb/server/smb2pdu.c    | 104 ++-----------------------
 fs/smb/server/vfs_cache.c  | 150 ++++++++++++++++++++++++++-----------
 fs/smb/server/vfs_cache.h  |   7 +-
 5 files changed, 120 insertions(+), 145 deletions(-)
fs/smb/server/connection.c +0 -2
index 19d32681bb92..0a4be9e423a3 100644
@@ -327,8 +327,6 @@ struct ksmbd_conn *ksmbd_conn_alloc(void)
 	ida_init(&conn->async_ida);
 	xa_init(&conn->sessions);
 
-	spin_lock_init(&conn->llist_lock);
-	INIT_LIST_HEAD(&conn->lock_list);
 
 	init_rwsem(&conn->session_lock);
 
fs/smb/server/connection.h +0 -2
index 85e2d2073cd2..53eb91f618b4 100644
@@ -112,8 +112,6 @@ struct ksmbd_conn {
 	char				ClientGUID[SMB2_CLIENT_GUID_SIZE];
 	struct ntlmssp_auth		ntlmssp;
 
-	spinlock_t			llist_lock;
-	struct list_head		lock_list;
 
 	struct preauth_integrity_info	*preauth_info;
 
fs/smb/server/smb2pdu.c +8 -96

136 lines not on this page · raw message

fs/smb/server/vfs_cache.c +107 -43

205 lines not on this page · raw message

fs/smb/server/vfs_cache.h +5 -2
index 706633bb0419..6df48ae04548 100644
@@ -34,11 +34,11 @@
 
 struct ksmbd_conn;
 struct ksmbd_session;
+struct ksmbd_file;
 
 struct ksmbd_lock {
 	struct file_lock *fl;
-	struct ksmbd_conn *conn;
-	struct list_head clist;
+	struct hlist_node hlist;
 	struct list_head flist;
 	struct list_head llist;
 	unsigned int flags;
@@ -48,6 +48,9 @@ struct ksmbd_lock {
 	unsigned long long end;
 };
 
+int ksmbd_file_lock_check(struct ksmbd_lock *lock);
+void ksmbd_file_lock_add(struct ksmbd_file *fp, struct list_head *locks);
+
 struct stream {
 	char *name;
 	ssize_t size;
Signature · 1 line
2.25.1
author maintainer
#6 lore raw

PATCH 7/22 ksmbd: rebind completed CREATE replays without draining the old channel

In reply to Namjae Jeon

A completed DurableHandleReqV2 CREATE can be replayed through another channel while its original channel is exiting. The existing replay path returns the open but leaves its connection and oplock references pointing at the old channel. Its open count also stays on that channel, and a later CLOSE through the surviving channel decrements the wrong counter.

After checking the owner, lease key and persistent flag, verify that an active open is still published in the requesting session's file table. Do this even when no oplock was granted, and before processing a consumed replay. Do not read a borrowed opinfo session pointer for this check.

Keep a healthy original binding. If the original channel is exiting or releasing, move the open and its own oplock references to the requesting channel. Serialize this with CLOSE using the session file-table lock, and with detach, reconnect and notification snapshots using m_lock. The earlier lock index and lease-table changes make their lifetimes independent of this connection change. No old-channel r_count wait is needed, including when an unrelated request remains active there.

Account final close against fp->conn in one place, balance durable detach and reconnect, and transfer the count with a replay binding change. A final global lookup put may run after CLOSE has removed the volatile id; unlink the open from the inode list on that final close as well.

A live completed CREATE replay may follow a break that lowered the durable open's batch oplock. Apply the batch eligibility check only to detached reconnects, while retaining the owner, lease key and persistent flag checks for active replays.

Fixes bb8bf7eb13b5 ("ksmbd: add SMB3 request replay support")
---
 fs/smb/server/smb2pdu.c   |  59 ++++----------
 fs/smb/server/vfs_cache.c | 164 ++++++++++++++++++++++----------------
 fs/smb/server/vfs_cache.h |   1 +
 3 files changed, 112 insertions(+), 112 deletions(-)
fs/smb/server/smb2pdu.c +15 -44
index 853a892e2ad5..d2f02a0957a7 100644
@@ -3747,7 +3747,7 @@ static int smb2_check_durable_replay(struct ksmbd_work *work,
 	struct oplock_info *opinfo;
 	int ret = 0;
 
-	if (!fp->is_durable && !fp->is_persistent)
+	if (!fp->conn && !fp->is_durable && !fp->is_persistent)
 		return -EACCES;
 
 	if (ksmbd_vfs_compare_durable_owner(fp, work->sess->user) == false)
@@ -3760,11 +3760,6 @@ static int smb2_check_durable_replay(struct ksmbd_work *work,
 	if (!opinfo)
 		return 0;
 
-	if (opinfo->sess && opinfo->sess->id != work->sess->id) {
-		ret = -ENOEXEC;
-		goto out;
-	}
-
 	if (opinfo->is_lease) {
 		if (!lc ||
 		    memcmp(opinfo->o_lease->lease_key, lc->lease_key,
@@ -3778,7 +3773,9 @@ static int smb2_check_durable_replay(struct ksmbd_work *work,
 			goto out;
 		}
 
-		if (fp->is_durable && opinfo->level != SMB2_OPLOCK_LEVEL_BATCH)
+		/* 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:
@@ -3982,35 +3979,18 @@ static int parse_durable_handle_context(struct ksmbd_work *work,
 						goto out;
 					}
 
-					if (!dh_info->fp->is_durable &&
-					    !dh_info->fp->is_persistent) {
-						/*
-						 * A DurableHandleReqV2 CREATE can complete
-						 * without granting durability (for example, if
-						 * it requested no oplock).  Its CreateGuid still
-						 * identifies a completed CREATE for replay.
-						 */
-						if (dh_info->fp->conn &&
-						    ksmbd_vfs_compare_durable_owner(
-							    dh_info->fp, work->sess->user)) {
-							if (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 (smb2_durable_replay_differs(
-								    dh_info->fp, req))
-								smb2_mark_durable_replay_consumed(
-									dh_info->fp);
-							dh_info->replay = true;
-							dh_info->type = dh_idx;
-							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);
-						err = -EACCES;
 						goto out;
 					}
 
@@ -4023,15 +4003,6 @@ static int parse_durable_handle_context(struct ksmbd_work *work,
 						break;
 					}
 
-					err = smb2_check_durable_replay(work,
-									dh_info->fp,
-									lc,
-									dh_info->persistent);
-					if (err) {
-						ksmbd_put_durable_fd(dh_info->fp);
-						goto out;
-					}
-
 					if (dh_info->fp->conn) {
 						if (smb2_durable_replay_differs(dh_info->fp,
 									       req))
fs/smb/server/vfs_cache.c +96 -68

304 lines not on this page · raw message

fs/smb/server/vfs_cache.h +1 -0
index 6df48ae04548..694453c75ec4 100644
@@ -260,6 +260,7 @@ void ksmbd_fd_set_delete_on_close(struct ksmbd_file *fp,
 void ksmbd_fd_set_delete_pending(struct ksmbd_file *fp);
 void ksmbd_fd_clear_delete_pending(struct ksmbd_file *fp);
 int ksmbd_reopen_durable_fd(struct ksmbd_work *work, struct ksmbd_file *fp);
+int ksmbd_rebind_replay_fd(struct ksmbd_work *work, struct ksmbd_file *fp);
 int ksmbd_validate_name_reconnect(struct ksmbd_share_config *share,
 				  struct ksmbd_file *fp, char *name);
 int ksmbd_init_file_cache(void);
Signature · 1 line
2.25.1
author maintainer
#7 lore raw

PATCH 8/22 ksmbd: track SMB2 locks above OFFSET_MAX in server lock table

In reply to Namjae Jeon

SMB2 lock ranges use unsigned 64-bit offsets, but file_lock stores signed loff_t values. Track valid ranges above OFFSET_MAX in ksmbd's inode-based lock index and arbitrate conflicts there. Keep these offsets out of file_lock, and handle blocking requests, unlocks, rollback, close cleanup and cancellation in the SMB layer.

Reserve large ranges under the index spinlock until the full request commits. Keep lookup and ownership independent of the connection so channel removal and hard-link opens use the same conflict checks.

Finish large-range unlocks in the SMB layer after unlocking any VFS portion. Wake large-range lock waiters when normal locks are removed by unlock or close.

---
 fs/smb/server/smb2pdu.c   | 235 +++++++++++++++++++++++++++++++-------
 fs/smb/server/vfs_cache.c | 119 ++++++++++++++++++-
 fs/smb/server/vfs_cache.h |   9 ++
 3 files changed, 321 insertions(+), 42 deletions(-)
fs/smb/server/smb2pdu.c +196 -39
index d2f02a0957a7..cdc214363d19 100644
@@ -10226,8 +10226,10 @@ static int smb2_set_flock_flags(struct file_lock *flock, int flags)
 	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;
@@ -10238,10 +10240,11 @@ static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
 
 	lock->cmd = cmd;
 	lock->fl = flock;
-	lock->start = flock->fl_start;
-	lock->end = flock->fl_end;
+	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);
@@ -10250,18 +10253,112 @@ static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
 	return lock;
 }
 
-static void smb2_remove_blocked_lock(void **argv)
+static void smb2_virtual_lock_cancel(void **argv)
 {
-	struct file_lock *flock = (struct file_lock *)argv[0];
+	(void)argv;
+	wake_up_all(&ksmbd_lock_wait);
+}
 
-	ksmbd_vfs_posix_lock_unblock(flock);
-	locks_wake_up(flock);
+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_free_lock(struct file_lock *flock)
+static void smb2_remove_blocked_lock(void **argv)
 {
+	struct file_lock *flock = (struct file_lock *)argv[0];
+
 	ksmbd_vfs_posix_lock_unblock(flock);
-	locks_free_lock(flock);
+	locks_wake_up(flock);
 }
 
 static void smb2_free_blocked_lock(struct file_lock *flock)
@@ -10289,13 +10386,14 @@ int smb2_lock(struct ksmbd_work *work)
 	int flags = 0;
 	int cmd = 0;
 	int err = -EIO, i, rc = 0;
-	u64 lock_start, lock_length;
+	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);
 
@@ -10358,23 +10456,29 @@ int smb2_lock(struct ksmbd_work *work)
 
 		lock_start = le64_to_cpu(lock_ele[i].Offset);
 		lock_length = le64_to_cpu(lock_ele[i].Length);
-		if (lock_start > OFFSET_MAX ||
-		    (lock_length &&
-		     lock_length - 1 > OFFSET_MAX - lock_start)) {
+		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;
 		}
 
-		flock->fl_start = lock_start;
-		flock->fl_end = lock_length ?
-			flock->fl_start + lock_length - 1 : flock->fl_start;
+		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->fl->fl_start <= flock->fl_start &&
-			    cmp_lock->fl->fl_end >= flock->fl_end) {
+			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");
@@ -10386,6 +10490,7 @@ int smb2_lock(struct ksmbd_work *work)
 		}
 
 		smb_lock = smb2_lock_init(flock, cmd, flags, !lock_length,
+					   lock_start, lock_end, virtual_lock,
 					   &lock_list);
 		if (!smb_lock) {
 			err = -EINVAL;
@@ -10422,6 +10527,22 @@ int smb2_lock(struct ksmbd_work *work)
 
 		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;
@@ -10437,7 +10558,21 @@ int smb2_lock(struct ksmbd_work *work)
 		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;
 		}
@@ -10464,6 +10599,11 @@ int smb2_lock(struct ksmbd_work *work)
 				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;
@@ -10476,11 +10616,17 @@ int smb2_lock(struct ksmbd_work *work)
 				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;
 				}
-				list_add(&smb_lock->llist, &rollback_list);
+				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);
@@ -10493,16 +10639,19 @@ int smb2_lock(struct ksmbd_work *work)
 				list_del(&work->fp_entry);
 				spin_unlock(&fp->f_lock);
 
-				list_del(&smb_lock->llist);
+				if (!smb_lock->virtual_lock)
+					list_del(&smb_lock->llist);
 
 				if (work->state == KSMBD_WORK_CANCELLED) {
 					rsp->hdr.Status = STATUS_CANCELLED;
-					kfree(smb_lock);
 					smb2_send_interim_resp(work,
 							STATUS_CANCELLED);
 					release_async_work(work);
-					locks_free_lock(flock);
 					work->send_no_response = 1;
+					if (!smb_lock->virtual_lock) {
+						kfree(smb_lock);
+						locks_free_lock(flock);
+					}
 					goto out;
 				}
 
@@ -10511,20 +10660,25 @@ int smb2_lock(struct ksmbd_work *work)
 				if (work->state == KSMBD_WORK_ACTIVE)
 					goto retry;
 
-				locks_free_lock(flock);
-
 				rsp->hdr.Status =
 					STATUS_RANGE_NOT_LOCKED;
-				kfree(smb_lock);
+				if (!smb_lock->virtual_lock) {
+					locks_free_lock(flock);
+					kfree(smb_lock);
+				}
 				/* rollback_list may still hold earlier grants */
 				goto out;
 			} else if (!rc) {
-				list_add(&smb_lock->llist, &rollback_list);
+				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 {
-				locks_free_lock(flock);
-				kfree(smb_lock);
 				err = rc;
+				if (!smb_lock->virtual_lock) {
+					locks_free_lock(flock);
+					kfree(smb_lock);
+				}
 				goto out;
 			}
 		}
@@ -10561,24 +10715,27 @@ int smb2_lock(struct ksmbd_work *work)
 	list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
 		struct file_lock *rlock = NULL;
 
-		rlock = smb_flock_init(filp);
-		if (rlock) {
-			rlock->c.flc_type = F_UNLCK;
-			rlock->fl_start = smb_lock->start;
-			rlock->fl_end = smb_lock->end;
+		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");
+				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);
-		smb2_free_lock(smb_lock->fl);
 		if (rlock)
 			locks_free_lock(rlock);
-		kfree(smb_lock);
+		smb2_free_ksmbd_lock(smb_lock);
 	}
 out2:
 	ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
fs/smb/server/vfs_cache.c +116 -3

160 lines not on this page · raw message

fs/smb/server/vfs_cache.h +9 -0
index 694453c75ec4..6831aca22cff 100644
@@ -12,6 +12,7 @@
 #include <linux/rwsem.h>
 #include <linux/spinlock.h>
 #include <linux/idr.h>
+#include <linux/wait.h>
 #include <linux/workqueue.h>
 
 #include "vfs.h"
@@ -44,12 +45,20 @@ struct ksmbd_lock {
 	unsigned int flags;
 	int cmd;
 	int zero_len;
+	bool virtual_lock;
+	bool vfs_locked;
+	bool pending;
 	unsigned long long start;
 	unsigned long long end;
 };
 
 int ksmbd_file_lock_check(struct ksmbd_lock *lock);
 void ksmbd_file_lock_add(struct ksmbd_file *fp, struct list_head *locks);
+bool ksmbd_file_lock_conflict(struct ksmbd_lock *lock);
+int ksmbd_file_lock_reserve(struct ksmbd_file *fp, struct ksmbd_lock *lock);
+void ksmbd_file_lock_remove(struct ksmbd_lock *lock);
+int ksmbd_file_lock_unlock(struct ksmbd_lock *lock);
+extern wait_queue_head_t ksmbd_lock_wait;
 
 struct stream {
 	char *name;
Signature · 1 line
2.25.1
author maintainer
#8 lore raw

PATCH 9/22 ksmbd: expire unacknowledged oplock breaks

In reply to Namjae Jeon

Arm the oplock break acknowledgment timer once the common notification path accepts a classic break for transmission. Preserve its shared retry deadline when another channel is tried. Store a deadline per open and scan the global open table when the earliest deadline expires. Drop expired breaks to NONE and restart the timer while other breaks remain.

Serialize timer expiry with client acknowledgments and close using the oplock state lock. Wake blocked requests when a break expires or sending the notification fails, and invalidate durable reconnect for the open. Use wake_up_all() for acknowledgment, timeout, close and send failure.

---
 fs/smb/server/oplock.c    | 30 ++++++++++++++--
 fs/smb/server/oplock.h    |  3 ++
 fs/smb/server/smb2pdu.c   |  6 ++--
 fs/smb/server/vfs_cache.c | 74 +++++++++++++++++++++++++++++++++++++++
 fs/smb/server/vfs_cache.h |  1 +
 5 files changed, 110 insertions(+), 4 deletions(-)
fs/smb/server/oplock.c +28 -2
index 96b36b8329a6..352a9e2293b5 100644
@@ -551,9 +551,10 @@ void close_id_del_oplock(struct ksmbd_file *fp)
 	 * takes the same lock before it acquires pending_break or sets ACK_WAIT.
 	 */
 	opinfo->op_state = OPLOCK_CLOSING;
+	opinfo->oplock_timeout_set = false;
 	clear_bit_unlock(0, &opinfo->pending_break);
 	spin_unlock(&opinfo->state_lock);
-	wake_up_interruptible_all(&opinfo->oplock_q);
+	wake_up_all(&opinfo->oplock_q);
 	if (opinfo->is_lease)
 		wake_up_interruptible_all(&opinfo->oplock_brk);
 	/* memory barrier is needed for wake_up_bit() */
@@ -744,6 +745,8 @@ static bool oplock_break_set_ack_wait(struct oplock_info *opinfo)
 	spin_lock(&opinfo->state_lock);
 	if (opinfo->op_state != OPLOCK_CLOSING) {
 		opinfo->op_state = OPLOCK_ACK_WAIT;
+		opinfo->oplock_timeout_set = false;
+		opinfo->oplock_timed_out = false;
 		ret = true;
 	}
 	spin_unlock(&opinfo->state_lock);
@@ -816,6 +819,23 @@ static bool lease_break_needed(struct oplock_info *opinfo, int req_op_level,
 	return opinfo->level > req_op_level;
 }
 
+static void smb2_break_start_timer(struct oplock_info *opinfo,
+				   unsigned long timeout)
+{
+	bool start = false;
+
+	spin_lock(&opinfo->state_lock);
+	if (!opinfo->is_lease && opinfo->op_state == OPLOCK_ACK_WAIT &&
+	    !opinfo->oplock_timeout_set) {
+		opinfo->oplock_timeout = timeout;
+		opinfo->oplock_timeout_set = true;
+		start = true;
+	}
+	spin_unlock(&opinfo->state_lock);
+	if (start)
+		ksmbd_schedule_oplock_break_timer(timeout);
+}
+
 struct smb2_break_channel {
 	struct list_head list;
 	struct ksmbd_conn *conn;
@@ -853,8 +873,10 @@ static int smb2_break_failed(struct oplock_info *opinfo, bool expect_ack)
 	}
 	opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
 	opinfo->op_state = OPLOCK_STATE_NONE;
+	opinfo->oplock_timeout_set = false;
+	opinfo->oplock_timed_out = true;
 	spin_unlock(&opinfo->state_lock);
-	wake_up_interruptible_all(&opinfo->oplock_q);
+	wake_up_all(&opinfo->oplock_q);
 	wake_up_interruptible_all(&opinfo->oplock_brk);
 	return ksmbd_invalidate_durable_fd(opinfo->fid);
 }
@@ -1169,6 +1191,8 @@ static int smb2_break_notify(struct oplock_info *opinfo, struct ksmbd_inode *ci,
 			continue;
 		}
 		channel->queued = true;
+		if (expect_ack)
+			smb2_break_start_timer(opinfo, deadline);
 		if (interim_work) {
 			ksmbd_queue_io_work(interim_work);
 			interim_work = NULL;
@@ -1209,6 +1233,8 @@ static int smb2_break_notify(struct oplock_info *opinfo, struct ksmbd_inode *ci,
 failed:
 	ret = smb2_break_failed(opinfo, expect_ack);
 out:
+	if (expect_ack && READ_ONCE(opinfo->oplock_timed_out))
+		ret = ksmbd_invalidate_durable_fd(opinfo->fid);
 	ksmbd_free_work_struct(work);
 	list_for_each_entry_safe(channel, tmp, &channels, list) {
 		list_del(&channel->list);
fs/smb/server/oplock.h +3 -0
index 5ef05166e502..03a5b93da2ec 100644
@@ -67,6 +67,9 @@ struct oplock_info {
 	int                     level;
 	int                     op_state;
 	spinlock_t		state_lock;
+	unsigned long		oplock_timeout;
+	bool			oplock_timeout_set;
+	bool			oplock_timed_out;
 	unsigned long		pending_break;
 	u64			fid;
 	atomic_t		breaking_cnt;
fs/smb/server/smb2pdu.c +4 -2
index cdc214363d19..77f3b9a5cdfc 100644
@@ -12030,8 +12030,9 @@ static void smb20_oplock_break_ack(struct ksmbd_work *work)
 
 	opinfo->level = rsp_oplevel;
 	opinfo->op_state = OPLOCK_STATE_NONE;
+	opinfo->oplock_timeout_set = false;
 	spin_unlock(&opinfo->state_lock);
-	wake_up_interruptible_all(&opinfo->oplock_q);
+	wake_up_all(&opinfo->oplock_q);
 
 	rsp->StructureSize = cpu_to_le16(24);
 	rsp->OplockLevel = rsp_oplevel;
@@ -12048,8 +12049,9 @@ static void smb20_oplock_break_ack(struct ksmbd_work *work)
 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_interruptible_all(&opinfo->oplock_q);
+	wake_up_all(&opinfo->oplock_q);
 	rsp->hdr.Status = status;
 	smb2_set_err_rsp(work);
 out_no_state_change:
fs/smb/server/vfs_cache.c +74 -0

98 lines not on this page · raw message

fs/smb/server/vfs_cache.h +1 -0
index 6831aca22cff..9de41b6e28ba 100644
@@ -242,6 +242,7 @@ void ksmbd_wake_session_blocked_works(struct ksmbd_session *sess);
 int ksmbd_close_inode_fds(struct ksmbd_work *work, struct inode *inode);
 int ksmbd_init_global_file_table(void);
 void ksmbd_free_global_file_table(void);
+void ksmbd_schedule_oplock_break_timer(unsigned long timeout);
 void ksmbd_set_fd_limit(unsigned long limit);
 int ksmbd_update_fstate(struct ksmbd_file_table *ft, struct ksmbd_file *fp,
 			unsigned int state);
Signature · 1 line
2.25.1
author maintainer
#9 lore raw

PATCH 10/22 ksmbd: expire unacknowledged lease breaks

In reply to Namjae Jeon

Arm a lease break acknowledgment timer once the common notification path accepts an ACK-required notification for transmission. Keep the deadline on the lease across channel retries and scan every lease in the global lease tables when the timer expires. Set timed-out leases and all their opens to NONE, then rearm for the next deadline.

Serialize client acknowledgments, notification state and timer expiry under the lease lock, taking each open's state lock after it. Update every open before publishing break completion so a late acknowledgment cannot restore an expired lease. Wake blocked opens on timeout, send failure and global lease-table teardown, and cancel the timer at teardown.

Keep the existing connection-independent lease-table lifetime and use the notifier's opinfo reference to retain the lease. Stop after selecting one open during lease-key lookup.

---
 fs/smb/server/oplock.c  | 184 +++++++++++++++++++++++++++++++++++-----
 fs/smb/server/oplock.h  |   3 +
 fs/smb/server/smb2pdu.c |  30 +++++--
 3 files changed, 191 insertions(+), 26 deletions(-)
fs/smb/server/oplock.c +164 -20
index 352a9e2293b5..5873bd349e08 100644
@@ -20,6 +20,11 @@
 
 static LIST_HEAD(lease_table_list);
 static DEFINE_RWLOCK(lease_list_lock);
+static DEFINE_MUTEX(lease_break_timer_lock);
+static unsigned long lease_break_timer_next;
+static bool lease_break_timer_pending;
+static void lease_break_timer(struct work_struct *work);
+static DECLARE_DELAYED_WORK(lease_break_timer_work, lease_break_timer);
 
 #define SMB2_LEASE_STATE_MASK_LE	(SMB2_LEASE_READ_CACHING_LE | \
 					 SMB2_LEASE_HANDLE_CACHING_LE | \
@@ -116,6 +121,82 @@ static void lease_put(struct lease *lease)
 		kfree(lease);
 }
 
+/* The caller holds lease->lock. */
+static void lease_break_to_none_locked(struct lease *lease)
+{
+	struct oplock_info *opinfo;
+	bool wake;
+
+	lease->state = SMB2_LEASE_NONE_LE;
+	lease->new_state = SMB2_LEASE_NONE_LE;
+	lease->breaking = false;
+	lease->break_timeout_set = false;
+	list_for_each_entry(opinfo, &lease->open_list, lease_entry) {
+		spin_lock(&opinfo->state_lock);
+		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
+		wake = opinfo->op_state == OPLOCK_ACK_WAIT;
+		if (wake) {
+			opinfo->op_state = OPLOCK_STATE_NONE;
+			opinfo->oplock_timed_out = true;
+			atomic_set(&opinfo->breaking_cnt, 0);
+		}
+		spin_unlock(&opinfo->state_lock);
+		if (wake) {
+			wake_up_all(&opinfo->oplock_q);
+			wake_up_interruptible_all(&opinfo->oplock_brk);
+		}
+	}
+}
+
+static void lease_break_timer(struct work_struct *work)
+{
+	struct lease_table *lb;
+	struct lease *lease;
+	unsigned long next = 0, now;
+	bool pending = false;
+
+	mutex_lock(&lease_break_timer_lock);
+	now = jiffies;
+	read_lock(&lease_list_lock);
+	list_for_each_entry(lb, &lease_table_list, l_entry) {
+		list_for_each_entry(lease, &lb->lease_list, l_entry) {
+			spin_lock(&lease->lock);
+			if (lease->breaking && lease->break_timeout_set) {
+				if (time_after_eq(now, lease->break_timeout)) {
+					lease_break_to_none_locked(lease);
+				} else if (!pending ||
+					   time_before(lease->break_timeout, next)) {
+					next = lease->break_timeout;
+					pending = true;
+				}
+			}
+			spin_unlock(&lease->lock);
+		}
+	}
+	read_unlock(&lease_list_lock);
+
+	lease_break_timer_pending = pending;
+	if (pending) {
+		lease_break_timer_next = next;
+		mod_delayed_work(system_wq, &lease_break_timer_work,
+				 time_after_eq(jiffies, next) ? 0 : next - jiffies);
+	}
+	mutex_unlock(&lease_break_timer_lock);
+}
+
+static void schedule_lease_break_timer(unsigned long timeout)
+{
+	mutex_lock(&lease_break_timer_lock);
+	if (!lease_break_timer_pending ||
+	    time_before(timeout, lease_break_timer_next)) {
+		lease_break_timer_pending = true;
+		lease_break_timer_next = timeout;
+		mod_delayed_work(system_wq, &lease_break_timer_work,
+				 time_after_eq(jiffies, timeout) ? 0 : timeout - jiffies);
+	}
+	mutex_unlock(&lease_break_timer_lock);
+}
+
 static void lease_add_table(struct lease *lease, struct lease_table *lb)
 {
 	lease_get(lease);
@@ -190,6 +271,8 @@ static struct lease *alloc_lease(struct lease_ctx_info *lctx,
 	lease->epoch = lctx->version == 2 ? le16_to_cpu(lctx->epoch) + 1 : 0;
 	lease->ci = ci;
 	lease->reuse_epoch = false;
+	lease->breaking = false;
+	lease->break_timeout_set = false;
 	lease->l_lb = NULL;
 	INIT_LIST_HEAD(&lease->l_entry);
 	INIT_LIST_HEAD(&lease->open_list);
@@ -822,11 +905,38 @@ static bool lease_break_needed(struct oplock_info *opinfo, int req_op_level,
 static void smb2_break_start_timer(struct oplock_info *opinfo,
 				   unsigned long timeout)
 {
-	bool start = false;
+	struct lease *lease = opinfo->o_lease;
+	struct oplock_info *open;
+	bool start = false, waiting;
+
+	if (opinfo->is_lease) {
+		read_lock(&lease_list_lock);
+		spin_lock(&lease->lock);
+		if (!lease->l_lb) {
+			lease_break_to_none_locked(lease);
+		} else if (!lease->breaking) {
+			list_for_each_entry(open, &lease->open_list, lease_entry) {
+				spin_lock(&open->state_lock);
+				waiting = open->op_state == OPLOCK_ACK_WAIT;
+				spin_unlock(&open->state_lock);
+				if (!waiting)
+					continue;
+				lease->break_timeout = timeout;
+				lease->break_timeout_set = true;
+				lease->breaking = true;
+				start = true;
+				break;
+			}
+		}
+		spin_unlock(&lease->lock);
+		read_unlock(&lease_list_lock);
+		if (start)
+			schedule_lease_break_timer(timeout);
+		return;
+	}
 
 	spin_lock(&opinfo->state_lock);
-	if (!opinfo->is_lease && opinfo->op_state == OPLOCK_ACK_WAIT &&
-	    !opinfo->oplock_timeout_set) {
+	if (opinfo->op_state == OPLOCK_ACK_WAIT && !opinfo->oplock_timeout_set) {
 		opinfo->oplock_timeout = timeout;
 		opinfo->oplock_timeout_set = true;
 		start = true;
@@ -858,25 +968,33 @@ static bool smb2_break_complete(struct oplock_info *opinfo, bool expect_ack)
 
 static int smb2_break_failed(struct oplock_info *opinfo, bool expect_ack)
 {
+	struct lease *lease = opinfo->o_lease;
+	bool timed_out;
+
+	if (opinfo->is_lease)
+		spin_lock(&lease->lock);
 	spin_lock(&opinfo->state_lock);
 	/* An ACK or close which won the race has already completed the break. */
 	if (opinfo->op_state == OPLOCK_CLOSING ||
 	    (expect_ack && opinfo->op_state == OPLOCK_STATE_NONE)) {
+		timed_out = opinfo->oplock_timed_out;
 		spin_unlock(&opinfo->state_lock);
-		return 0;
+		if (opinfo->is_lease)
+			spin_unlock(&lease->lock);
+		return timed_out ? ksmbd_invalidate_durable_fd(opinfo->fid) : 0;
 	}
 	if (opinfo->is_lease) {
-		opinfo->o_lease->state = SMB2_LEASE_NONE_LE;
-		opinfo->o_lease->new_state = SMB2_LEASE_NONE_LE;
-		lease_update_oplock_levels(opinfo->o_lease);
-		atomic_set(&opinfo->breaking_cnt, 0);
+		spin_unlock(&opinfo->state_lock);
+		lease_break_to_none_locked(lease);
+		spin_unlock(&lease->lock);
+	} else {
+		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
+		opinfo->op_state = OPLOCK_STATE_NONE;
+		opinfo->oplock_timeout_set = false;
+		opinfo->oplock_timed_out = true;
+		spin_unlock(&opinfo->state_lock);
+		wake_up_all(&opinfo->oplock_q);
 	}
-	opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
-	opinfo->op_state = OPLOCK_STATE_NONE;
-	opinfo->oplock_timeout_set = false;
-	opinfo->oplock_timed_out = true;
-	spin_unlock(&opinfo->state_lock);
-	wake_up_all(&opinfo->oplock_q);
 	wake_up_interruptible_all(&opinfo->oplock_brk);
 	return ksmbd_invalidate_durable_fd(opinfo->fid);
 }
@@ -1096,6 +1214,7 @@ static int smb2_break_notify(struct oplock_info *opinfo, struct ksmbd_inode *ci,
 	struct smb2_oplock_break *oplock_rsp;
 	struct smb2_lease_break *lease_rsp;
 	struct lease *lease = opinfo->o_lease;
+	struct oplock_info *open;
 	unsigned long deadline, retry_at;
 	int ret, size;
 	LIST_HEAD(channels);
@@ -1122,10 +1241,14 @@ static int smb2_break_notify(struct oplock_info *opinfo, struct ksmbd_inode *ci,
 	if (ret)
 		goto failed;
 
+	if (opinfo->is_lease)
+		spin_lock(&lease->lock);
 	spin_lock(&opinfo->state_lock);
 	if (opinfo->op_state == OPLOCK_CLOSING ||
 	    (expect_ack && opinfo->op_state == OPLOCK_STATE_NONE)) {
 		spin_unlock(&opinfo->state_lock);
+		if (opinfo->is_lease)
+			spin_unlock(&lease->lock);
 		ret = 0;
 		goto out;
 	}
@@ -1159,6 +1282,8 @@ static int smb2_break_notify(struct oplock_info *opinfo, struct ksmbd_inode *ci,
 		size = sizeof(*oplock_rsp);
 	}
 	spin_unlock(&opinfo->state_lock);
+	if (opinfo->is_lease)
+		spin_unlock(&lease->lock);
 	ret = ksmbd_iov_pin_rsp(work, oplock_rsp, size);
 	if (ret)
 		goto failed;
@@ -1222,12 +1347,16 @@ static int smb2_break_notify(struct oplock_info *opinfo, struct ksmbd_inode *ci,
 	if (ret)
 		goto failed;
 	if (!expect_ack && opinfo->is_lease) {
-		spin_lock(&opinfo->state_lock);
-		if (opinfo->op_state != OPLOCK_CLOSING) {
+		spin_lock(&lease->lock);
+		if (READ_ONCE(opinfo->op_state) != OPLOCK_CLOSING) {
 			lease->state = lease->new_state;
-			lease_update_oplock_levels(lease);
+			list_for_each_entry(open, &lease->open_list, lease_entry) {
+				spin_lock(&open->state_lock);
+				open->level = smb2_map_lease_to_oplock(lease->state);
+				spin_unlock(&open->state_lock);
+			}
 		}
-		spin_unlock(&opinfo->state_lock);
+		spin_unlock(&lease->lock);
 	}
 	goto out;
 failed:
@@ -1379,6 +1508,7 @@ static int oplock_break(struct oplock_info *brk_opinfo, struct ksmbd_inode *ci,
 			open_trunc = brk_opinfo->open_trunc;
 
 again:
+		spin_lock(&lease->lock);
 		atomic_inc(&brk_opinfo->breaking_cnt);
 		if (open_trunc) {
 			/*
@@ -1413,6 +1543,7 @@ static int oplock_break(struct oplock_info *brk_opinfo, struct ksmbd_inode *ci,
 					     SMB2_LEASE_HANDLE_CACHING_LE);
 		if (expect_ack) {
 			if (!oplock_break_set_ack_wait(brk_opinfo)) {
+				spin_unlock(&lease->lock);
 				atomic_dec_if_positive(&brk_opinfo->breaking_cnt);
 				clear_and_wake_up_bit(0, &brk_opinfo->pending_break);
 				return -ENOENT;
@@ -1427,6 +1558,7 @@ static int oplock_break(struct oplock_info *brk_opinfo, struct ksmbd_inode *ci,
 			inc_epoch = false;
 			lease->reuse_epoch = false;
 		}
+		spin_unlock(&lease->lock);
 		err = smb2_break_notify_with_interim(brk_opinfo, ci, expect_ack,
 						    wait_ack, inc_epoch,
 						    sent_interim ? NULL : in_work,
@@ -1524,11 +1656,20 @@ void destroy_lease_table(void)
 	struct lease_table *lb;
 	struct lease *lease;
 
+	cancel_delayed_work_sync(&lease_break_timer_work);
+	mutex_lock(&lease_break_timer_lock);
+	lease_break_timer_pending = false;
+	mutex_unlock(&lease_break_timer_lock);
+
 	write_lock(&lease_list_lock);
 	while (!list_empty(&lease_table_list)) {
 		lb = list_first_entry(&lease_table_list, struct lease_table,
 				      l_entry);
 		lease = list_first_entry(&lb->lease_list, struct lease, l_entry);
+		spin_lock(&lease->lock);
+		if (lease->breaking)
+			lease_break_to_none_locked(lease);
+		spin_unlock(&lease->lock);
 		lease_del_table(lease);
 	}
 	write_unlock(&lease_list_lock);
@@ -2551,11 +2692,13 @@ struct oplock_info *lookup_lease_in_table(struct ksmbd_conn *conn,
 	list_for_each_entry(lease, &lt->lease_list, l_entry) {
 		if (memcmp(lease->lease_key, lease_key, SMB2_LEASE_KEY_SIZE))
 			continue;
+		spin_lock(&lease->lock);
 		if (!(lease->state & (SMB2_LEASE_HANDLE_CACHING_LE |
-				      SMB2_LEASE_WRITE_CACHING_LE)))
+				      SMB2_LEASE_WRITE_CACHING_LE))) {
+			spin_unlock(&lease->lock);
 			break;
+		}
 
-		spin_lock(&lease->lock);
 		list_for_each_entry(opinfo, &lease->open_list, lease_entry) {
 			if (!opinfo->op_state ||
 			    opinfo->op_state == OPLOCK_CLOSING)
@@ -2563,6 +2706,7 @@ struct oplock_info *lookup_lease_in_table(struct ksmbd_conn *conn,
 			if (!atomic_inc_not_zero(&opinfo->refcount))
 				continue;
 			ret_op = opinfo;
+			break;
 		}
 		spin_unlock(&lease->lock);
 		if (ret_op) {
fs/smb/server/oplock.h +3 -0
index 03a5b93da2ec..d81013c514e3 100644
@@ -50,6 +50,9 @@ struct lease {
 	unsigned short		epoch;
 	bool			is_dir;
 	bool			reuse_epoch;
+	bool			breaking;
+	bool			break_timeout_set;
+	unsigned long		break_timeout;
 	struct ksmbd_inode	*ci;
 	struct lease_table	*l_lb;
 	struct list_head	l_entry;
fs/smb/server/smb2pdu.c +24 -6
index 77f3b9a5cdfc..9d6426450827 100644
@@ -12086,10 +12086,12 @@ 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;
+	struct oplock_info *opinfo, *open;
 	int ret;
 	__le32 lease_state;
 	struct lease *lease;
+	u8 level;
+	bool wake;
 
 	WORK_BUFFERS(work, req, rsp);
 
@@ -12105,6 +12107,7 @@ static void smb21_lease_break_ack(struct ksmbd_work *work)
 	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 &&
@@ -12132,17 +12135,31 @@ static void smb21_lease_break_ack(struct ksmbd_work *work)
 	lease_state = req->LeaseState;
 	lease->state = lease_state;
 	lease->new_state = SMB2_LEASE_NONE_LE;
-	lease_update_oplock_levels(lease);
-	opinfo->op_state = OPLOCK_STATE_NONE;
-	atomic_dec_if_positive(&opinfo->breaking_cnt);
+	lease->breaking = false;
+	lease->break_timeout_set = false;
+	level = smb2_map_lease_to_oplock(lease_state);
 	spin_unlock(&opinfo->state_lock);
-	wake_up_interruptible_all(&opinfo->oplock_q);
-	wake_up_interruptible_all(&opinfo->oplock_brk);
+	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;
@@ -12158,6 +12175,7 @@ static void smb21_lease_break_ack(struct ksmbd_work *work)
 
 err_unlock:
 	spin_unlock(&opinfo->state_lock);
+	spin_unlock(&lease->lock);
 err_out:
 	smb2_set_err_rsp(work);
 	opinfo_put(opinfo);
Signature · 1 line
2.25.1
author maintainer
#10 lore raw

PATCH 11/22 ksmbd: support SMB2 quota query and set information

In reply to Namjae Jeon

Handle SMB2_0_INFO_QUOTA in QUERY_INFO and SET_INFO using the user quota operations on the volume containing the open. Validate the request buffers and linked SID entries before accessing quota data.

Enumerate quotas with a per-open cursor, apply restart and single-entry requests, and return aligned FILE_QUOTA_INFORMATION records. Return zeroed records for SIDs without a quota entry and report buffer and end-of-list statuses required by SMB2.

Allow the root session user to update quota limits. Reject deletion and explicit zero-byte limits because Linux user quotas cannot represent those values without changing their meaning.

---
 fs/smb/server/smb2pdu.c   | 423 ++++++++++++++++++++++++++++++++++++++
 fs/smb/server/smb2pdu.h   |  26 +++
 fs/smb/server/vfs_cache.c |   1 +
 fs/smb/server/vfs_cache.h |   2 +
 4 files changed, 452 insertions(+)
fs/smb/server/smb2pdu.c +423 -0
index 9d6426450827..856648d93f6e 100644
@@ -19,6 +19,7 @@
 #include <linux/math.h>
 #include <linux/timekeeping.h>
 #include <linux/unaligned.h>
+#include <linux/quota.h>
 
 #include "glob.h"
 #include "../common/smbfsctl.h"
@@ -8064,6 +8065,342 @@ static int smb2_get_info_sec(struct ksmbd_work *work,
 	return rc;
 }
 
+static unsigned int smb2_current_req_len(struct ksmbd_work *work,
+					 struct smb2_hdr *hdr);
+
+static int smb2_quota_sid_len(const u8 *buf, u32 len)
+{
+	const struct smb_sid *sid = (const struct smb_sid *)buf;
+	u32 size;
+
+	if (len < CIFS_SID_BASE_SIZE || sid->revision != 1 ||
+	    sid->num_subauth > SID_MAX_SUB_AUTHORITIES)
+		return -EINVAL;
+	size = CIFS_SID_BASE_SIZE + sid->num_subauth * sizeof(__le32);
+	return size <= len ? size : -EINVAL;
+}
+
+/* Linux user quotas can name local users through the server or Unix SID. */
+static int smb2_quota_sid_to_uid(const u8 *buf, u32 len, u32 *uid)
+{
+	const struct smb_sid *sid = (const struct smb_sid *)buf;
+	struct smb_sid expected;
+	u32 id;
+
+	if (smb2_quota_sid_len(buf, len) != len || !sid->num_subauth)
+		return -EINVAL;
+	id = le32_to_cpu(sid->sub_auth[sid->num_subauth - 1]);
+	if (server_conf.domain_sid.num_subauth < SID_MAX_SUB_AUTHORITIES) {
+		id_to_sid(id, SIDOWNER, &expected);
+		if (expected.num_subauth == sid->num_subauth &&
+		    !memcmp(&expected, sid, len)) {
+			*uid = id;
+			return 0;
+		}
+	}
+	id_to_sid(id, SIDUNIX_USER, &expected);
+	if (expected.num_subauth == sid->num_subauth &&
+	    !memcmp(&expected, sid, len)) {
+		*uid = id;
+		return 0;
+	}
+	return -ENOENT;
+}
+
+static int smb2_quota_check_list(const u8 *buf, u32 len, bool set)
+{
+	u32 pos = 0, base = set ? sizeof(struct smb2_file_quota_info) :
+				  sizeof(struct smb2_get_quota_info);
+	u32 align = set ? 8 : 4;
+
+	if (!len)
+		return -EINVAL;
+	while (pos < len) {
+		u32 next;
+		u32 sid_len;
+
+		if (len - pos < base)
+			return -EINVAL;
+		next = get_unaligned_le32(buf + pos);
+		sid_len = get_unaligned_le32(buf + pos + sizeof(__le32));
+		if (sid_len > len - pos - base ||
+		    smb2_quota_sid_len(buf + pos + base, sid_len) != sid_len)
+			return -EINVAL;
+		if (!next)
+			return len - pos - base - sid_len < align ? 0 : -EINVAL;
+		if (next < ALIGN(base + sid_len, align) || next > len - pos ||
+		    !IS_ALIGNED(next, align))
+			return -EINVAL;
+		pos += next;
+	}
+	return -EINVAL;
+}
+
+static void smb2_quota_set_status(struct smb2_hdr *hdr, int rc)
+{
+	switch (rc) {
+	case -EOPNOTSUPP:
+	case -ENOSYS:
+	case -ESRCH:
+		hdr->Status = STATUS_NOT_SUPPORTED;
+		break;
+	case -EACCES:
+	case -EPERM:
+		hdr->Status = STATUS_ACCESS_DENIED;
+		break;
+	case -ENOSPC:
+		hdr->Status = STATUS_BUFFER_TOO_SMALL;
+		break;
+	case -EINVAL:
+		hdr->Status = STATUS_INVALID_PARAMETER;
+		break;
+	case -ENOMEM:
+		hdr->Status = STATUS_INSUFFICIENT_RESOURCES;
+		break;
+	case -EDQUOT:
+		hdr->Status = STATUS_QUOTA_EXCEEDED;
+		break;
+	case -EROFS:
+		hdr->Status = STATUS_MEDIA_WRITE_PROTECTED;
+		break;
+	default:
+		hdr->Status = STATUS_UNEXPECTED_IO_ERROR;
+	}
+}
+
+static int smb2_quota_append(struct smb2_query_info_rsp *rsp, u32 max_len,
+			     u32 *used, struct smb2_file_quota_info **last,
+			     const u8 *sid, u32 sid_len,
+			     const struct qc_dqblk *dq)
+{
+	struct smb2_file_quota_info *entry;
+	u32 pos = *used;
+
+	if (*last)
+		pos = ALIGN(pos, 8);
+	if (pos > max_len || sid_len > max_len - pos ||
+	    sizeof(*entry) > max_len - pos - sid_len)
+		return -ENOSPC;
+	if (*last) {
+		(*last)->NextEntryOffset = cpu_to_le32(pos -
+			((u8 *)*last - rsp->Buffer));
+		memset(rsp->Buffer + *used, 0, pos - *used);
+	}
+	entry = (struct smb2_file_quota_info *)(rsp->Buffer + pos);
+	memset(entry, 0, sizeof(*entry));
+	entry->SidLength = cpu_to_le32(sid_len);
+	if (dq) {
+		entry->QuotaUsed = cpu_to_le64(dq->d_space);
+		entry->QuotaThreshold = cpu_to_le64(dq->d_spc_softlimit ?
+						 dq->d_spc_softlimit : U64_MAX);
+		entry->QuotaLimit = cpu_to_le64(dq->d_spc_hardlimit ?
+						 dq->d_spc_hardlimit : U64_MAX);
+	}
+	memcpy(entry->Sid, sid, sid_len);
+	*used = pos + sizeof(*entry) + sid_len;
+	*last = entry;
+	return 0;
+}
+
+static int smb2_get_info_quota(struct ksmbd_work *work,
+			       struct smb2_query_info_req *req,
+			       struct smb2_query_info_rsp *rsp)
+{
+	struct ksmbd_file *fp;
+	struct smb2_query_quota_info *query;
+	struct smb2_file_quota_info *last = NULL;
+	struct super_block *sb;
+	struct qc_dqblk dq;
+	struct smb_sid sid;
+	struct kqid qid;
+	const u8 *list;
+	u32 in_len = le32_to_cpu(req->InputBufferLength);
+	u32 list_len, start_len, start_off, used = 0, pos = 0, next_id = 0;
+	u32 uid, sid_len, entry_len;
+	u32 sid_type;
+	int max_len, rc = 0;
+	bool explicit_list, scan;
+
+	if (in_len < sizeof(*query) ||
+	    le16_to_cpu(req->InputBufferOffset) < offsetof(typeof(*req), Buffer) ||
+	    le16_to_cpu(req->InputBufferOffset) >
+			smb2_current_req_len(work, &req->hdr) ||
+	    in_len > smb2_current_req_len(work, &req->hdr) -
+			le16_to_cpu(req->InputBufferOffset)) {
+		rc = -EINVAL;
+		goto out_status;
+	}
+	query = (void *)req + le16_to_cpu(req->InputBufferOffset);
+	list_len = le32_to_cpu(query->SidListLength);
+	start_len = le32_to_cpu(query->StartSidLength);
+	start_off = le32_to_cpu(query->StartSidOffset);
+	if (list_len) {
+		if (list_len > in_len - sizeof(*query) ||
+		    smb2_quota_check_list(query->SidBuffer, list_len, false)) {
+			rc = -EINVAL;
+			goto out_status;
+		}
+	} else if (start_len || start_off) {
+		if (!start_len || start_off > in_len - sizeof(*query) ||
+		    start_len > in_len - sizeof(*query) - start_off ||
+		    smb2_quota_sid_len(query->SidBuffer + start_off,
+				   start_len) != start_len) {
+			rc = -EINVAL;
+			goto out_status;
+		}
+	}
+
+	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 out_status;
+	}
+	if (!max_len) {
+		rc = -ENOSPC;
+		goto out_status;
+	}
+
+	if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS &&
+	    !has_file_id(req->VolatileFileId))
+		fp = ksmbd_lookup_fd_slow(work, work->compound_fid,
+					  work->compound_pfid);
+	else
+		fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId,
+					  req->PersistentFileId);
+	if (!fp) {
+		rc = -ENOENT;
+		rsp->hdr.Status = STATUS_FILE_CLOSED;
+		goto out_status;
+	}
+	sb = file_inode(fp->filp)->i_sb;
+	if (!sb->s_qcop || !sb->s_qcop->get_nextdqblk) {
+		rc = -EOPNOTSUPP;
+		goto out_fd;
+	}
+	explicit_list = list_len != 0;
+	scan = !explicit_list;
+	list = query->SidBuffer;
+	if (scan) {
+		sid_type = server_conf.domain_sid.num_subauth <
+			SID_MAX_SUB_AUTHORITIES ? SIDOWNER : SIDUNIX_USER;
+		id_to_sid(0, sid_type, &sid);
+		sid_len = CIFS_SID_BASE_SIZE + sid.num_subauth * sizeof(__le32);
+		if (max_len < sizeof(struct smb2_file_quota_info) + sid_len) {
+			rc = -ENOSPC;
+			goto out_fd;
+		}
+		if (start_len) {
+			rc = smb2_quota_sid_to_uid(query->SidBuffer + start_off,
+						 start_len, &uid);
+			if (rc == -ENOENT) {
+				rc = -EINVAL;
+				goto out_fd;
+			}
+			if (rc)
+				goto out_fd;
+			if (uid == U32_MAX)
+				goto no_more;
+			next_id = uid + 1;
+		} else {
+			mutex_lock(&fp->quota_lock);
+			if (query->RestartScan)
+				fp->current_quota_id = 0;
+			next_id = fp->current_quota_id;
+		}
+	}
+
+	while (true) {
+		if (explicit_list) {
+			const struct smb2_get_quota_info *item =
+				(const void *)(list + pos);
+			bool found = false;
+
+			sid_len = le32_to_cpu(item->SidLength);
+			rc = smb2_quota_sid_to_uid(item->Sid, sid_len, &uid);
+			if (rc == -EINVAL)
+				goto out_scan;
+			entry_len = sizeof(struct smb2_file_quota_info) + sid_len;
+			if (ALIGN(used, 8) + entry_len > max_len) {
+				rc = used ? 0 : -ENOSPC;
+				break;
+			}
+			if (!rc) {
+				qid = make_kqid(&init_user_ns, USRQUOTA, uid);
+				rc = sb->s_qcop->get_nextdqblk(sb, &qid, &dq);
+				if (rc == -ENOENT)
+					rc = 0;
+				else if (rc)
+					goto out_scan;
+				else
+					found = from_kqid(&init_user_ns, qid) == uid;
+			} else if (rc == -ENOENT) {
+				rc = 0;
+			}
+			rc = smb2_quota_append(rsp, max_len, &used, &last,
+						item->Sid, sid_len,
+						found ? &dq : NULL);
+			if (rc)
+				goto out_scan;
+			if (!item->NextEntryOffset || query->ReturnSingle)
+				break;
+			pos += le32_to_cpu(item->NextEntryOffset);
+		} else {
+			if (next_id == U32_MAX)
+				break;
+			if (ALIGN(used, 8) + sizeof(struct smb2_file_quota_info) +
+			    sid_len > max_len)
+				break;
+			qid = make_kqid(&init_user_ns, USRQUOTA, next_id);
+			rc = sb->s_qcop->get_nextdqblk(sb, &qid, &dq);
+			if (rc == -ENOENT) {
+				rc = 0;
+				break;
+			}
+			if (rc)
+				goto out_scan;
+			uid = from_kqid(&init_user_ns, qid);
+			if (uid < next_id) {
+				rc = -EIO;
+				goto out_scan;
+			}
+			id_to_sid(uid, sid_type, &sid);
+			rc = smb2_quota_append(rsp, max_len, &used, &last,
+						(const u8 *)&sid, sid_len, &dq);
+			if (rc)
+				goto out_scan;
+			next_id = uid == U32_MAX ? U32_MAX : uid + 1;
+			if (uid == U32_MAX || query->ReturnSingle)
+				break;
+		}
+	}
+out_scan:
+	if (scan && !start_len) {
+		if (!rc && used)
+			fp->current_quota_id = next_id;
+		mutex_unlock(&fp->quota_lock);
+	}
+	if (rc)
+		goto out_fd;
+no_more:
+	if (!used) {
+		rsp->hdr.Status = STATUS_NO_MORE_ENTRIES;
+		rsp->OutputBufferOffset = 0;
+		rsp->OutputBufferLength = 0;
+	} else {
+		rsp->OutputBufferLength = cpu_to_le32(used);
+	}
+	rc = ksmbd_iov_pin_rsp(work, rsp,
+			   offsetof(struct smb2_query_info_rsp, Buffer) + used);
+out_fd:
+	ksmbd_fd_put(work, fp);
+out_status:
+	if (rc && !rsp->hdr.Status)
+		smb2_quota_set_status(&rsp->hdr, rc);
+	return rc;
+}
+
 /**
  * smb2_query_info() - handler for smb2 query info command
  * @work:	smb work containing query info request buffer
@@ -8104,6 +8441,9 @@ int smb2_query_info(struct ksmbd_work *work)
 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
 		rc = smb2_get_info_sec(work, req, rsp);
 		break;
+	case SMB2_O_INFO_QUOTA:
+		rc = smb2_get_info_quota(work, req, rsp);
+		break;
 	default:
 		ksmbd_debug(SMB, "InfoType %d not supported yet\n",
 			    req->InfoType);
@@ -8896,6 +9236,80 @@ static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
 			buf_len, false, true);
 }
 
+static int smb2_set_info_quota(struct ksmbd_work *work, struct ksmbd_file *fp,
+			       struct smb2_set_info_req *req)
+{
+	struct super_block *sb = file_inode(fp->filp)->i_sb;
+	const u8 *buf;
+	u32 len = le32_to_cpu(req->BufferLength);
+	u32 pos = 0, uid, next;
+	int rc;
+
+	if (!sb->s_qcop || !sb->s_qcop->set_dqblk)
+		return -EOPNOTSUPP;
+	/* The SMB session must have the volume's quota administrator right. */
+	if (user_uid(work->sess->user) != 0)
+		return -EACCES;
+	if (le16_to_cpu(req->BufferOffset) < offsetof(typeof(*req), Buffer) ||
+	    le16_to_cpu(req->BufferOffset) >
+			smb2_current_req_len(work, &req->hdr) ||
+	    len > smb2_current_req_len(work, &req->hdr) -
+			le16_to_cpu(req->BufferOffset))
+		return -EINVAL;
+	buf = (const u8 *)req + le16_to_cpu(req->BufferOffset);
+	rc = smb2_quota_check_list(buf, len, true);
+	if (rc)
+		return rc;
+
+	/* Validate the whole list before applying any of its entries. */
+	while (true) {
+		const struct smb2_file_quota_info *item =
+			(const void *)(buf + pos);
+		s64 soft = (s64)le64_to_cpu(item->QuotaThreshold);
+		s64 hard = (s64)le64_to_cpu(item->QuotaLimit);
+
+		rc = smb2_quota_sid_to_uid(item->Sid,
+					le32_to_cpu(item->SidLength), &uid);
+		if (rc)
+			return rc == -ENOENT ? -EOPNOTSUPP : rc;
+		/* Linux quotas have no delete operation or explicit zero limit. */
+		if (soft < -1 || hard < -1 || !soft || !hard)
+			return -EOPNOTSUPP;
+		next = le32_to_cpu(item->NextEntryOffset);
+		if (!next)
+			break;
+		pos += next;
+	}
+
+	pos = 0;
+	while (true) {
+		const struct smb2_file_quota_info *item =
+			(const void *)(buf + pos);
+		struct qc_dqblk dq = {
+			.d_fieldmask = QC_SPC_SOFT | QC_SPC_HARD,
+		};
+		struct kqid qid;
+		s64 soft = (s64)le64_to_cpu(item->QuotaThreshold);
+		s64 hard = (s64)le64_to_cpu(item->QuotaLimit);
+
+		rc = smb2_quota_sid_to_uid(item->Sid,
+					le32_to_cpu(item->SidLength), &uid);
+		if (rc)
+			return rc == -ENOENT ? -EOPNOTSUPP : rc;
+		qid = make_kqid(&init_user_ns, USRQUOTA, uid);
+		dq.d_spc_softlimit = soft == -1 ? 0 : soft;
+		dq.d_spc_hardlimit = hard == -1 ? 0 : hard;
+		rc = sb->s_qcop->set_dqblk(sb, qid, &dq);
+		if (rc)
+			return rc;
+		next = le32_to_cpu(item->NextEntryOffset);
+		if (!next)
+			break;
+		pos += next;
+	}
+	return 0;
+}
+
 /**
  * smb2_set_info() - handler for smb2 set info command handler
  * @work:	smb work containing set info request buffer
@@ -8969,6 +9383,9 @@ int smb2_set_info(struct ksmbd_work *work)
 				       (char *)req + le16_to_cpu(req->BufferOffset),
 				       le32_to_cpu(req->BufferLength));
 		break;
+	case SMB2_O_INFO_QUOTA:
+		rc = smb2_set_info_quota(work, fp, req);
+		break;
 	default:
 		rc = -EOPNOTSUPP;
 	}
@@ -9012,6 +9429,12 @@ int smb2_set_info(struct ksmbd_work *work)
 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
 	else if (rc == -EEXIST)
 		rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
+	else if (req->InfoType == SMB2_O_INFO_QUOTA && !rsp->hdr.Status) {
+		if (rc == -ENOSPC)
+			rsp->hdr.Status = STATUS_DISK_FULL;
+		else
+			smb2_quota_set_status(&rsp->hdr, rc);
+	}
 	else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
 		rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
 	smb2_set_err_rsp(work);
fs/smb/server/smb2pdu.h +26 -0
index c90a1d4e9f11..e07700d0a405 100644
@@ -225,6 +225,32 @@ struct file_sparse {
 #define FILE_NETWORK_OPEN_INFORMATION_SIZE    56
 #define FILE_ATTRIBUTE_TAG_INFORMATION_SIZE   8
 
+struct smb2_query_quota_info {
+	u8 ReturnSingle;
+	u8 RestartScan;
+	__le16 Reserved;
+	__le32 SidListLength;
+	__le32 StartSidLength;
+	__le32 StartSidOffset;
+	u8 SidBuffer[];
+} __packed;
+
+struct smb2_get_quota_info {
+	__le32 NextEntryOffset;
+	__le32 SidLength;
+	u8 Sid[];
+} __packed;
+
+struct smb2_file_quota_info {
+	__le32 NextEntryOffset;
+	__le32 SidLength;
+	__le64 ChangeTime;
+	__le64 QuotaUsed;
+	__le64 QuotaThreshold;
+	__le64 QuotaLimit;
+	u8 Sid[];
+} __packed;
+
 /* FS Info response  size */
 #define FS_DEVICE_INFORMATION_SIZE     8
 #define FS_ATTRIBUTE_INFORMATION_SIZE  16
fs/smb/server/vfs_cache.c +1 -0
index d63fed289c79..85f583189437 100644
@@ -1491,6 +1491,7 @@ struct ksmbd_file *ksmbd_open_fd(struct ksmbd_work *work, struct file *filp)
 	INIT_LIST_HEAD(&fp->lock_list);
 	spin_lock_init(&fp->f_lock);
 	mutex_init(&fp->readdir_lock);
+	mutex_init(&fp->quota_lock);
 	atomic_set(&fp->refcount, 1);
 
 	fp->filp		= filp;
fs/smb/server/vfs_cache.h +2 -0
index 9de41b6e28ba..1054002ec4c5 100644
@@ -157,6 +157,8 @@ struct ksmbd_file {
 	/* if ls is happening on directory, below is valid*/
 	struct ksmbd_readdir_data	readdir_data;
 	struct mutex			readdir_lock;
+	struct mutex			quota_lock;
+	u32				current_quota_id;
 	int				dot_dotdot[2];
 	unsigned int			f_state;
 	bool				reserve_lease_break;
Signature · 1 line
2.25.1
author maintainer
#11 lore raw

PATCH 12/22 ksmbd: validate POSIX negotiate contexts

In reply to Namjae Jeon

The POSIX negotiate context currently enables extensions without checking its payload, and duplicate contexts are accepted.

Reject duplicate contexts and invalid payload lengths. Enable POSIX extensions only for the published tag, and use the same tag constant when building the negotiate response.

---
 fs/smb/server/smb2pdu.c | 28 ++++++++++------------------
 1 file changed, 10 insertions(+), 18 deletions(-)
fs/smb/server/smb2pdu.c +10 -18
index 856648d93f6e..17bd7413e137 100644
@@ -1431,23 +1431,7 @@ 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);
-	/* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
-	pneg_ctxt->Name[0] = 0x93;
-	pneg_ctxt->Name[1] = 0xAD;
-	pneg_ctxt->Name[2] = 0x25;
-	pneg_ctxt->Name[3] = 0x50;
-	pneg_ctxt->Name[4] = 0x9C;
-	pneg_ctxt->Name[5] = 0xB4;
-	pneg_ctxt->Name[6] = 0x11;
-	pneg_ctxt->Name[7] = 0xE7;
-	pneg_ctxt->Name[8] = 0xB4;
-	pneg_ctxt->Name[9] = 0x23;
-	pneg_ctxt->Name[10] = 0x83;
-	pneg_ctxt->Name[11] = 0xDE;
-	pneg_ctxt->Name[12] = 0x96;
-	pneg_ctxt->Name[13] = 0x8B;
-	pneg_ctxt->Name[14] = 0xCD;
-	pneg_ctxt->Name[15] = 0x7C;
+	memcpy(pneg_ctxt->Name, SMB2_CREATE_TAG_POSIX, POSIX_CTXT_DATA_LEN);
 }
 
 static unsigned int assemble_neg_contexts(struct ksmbd_conn *conn,
@@ -1753,6 +1737,7 @@ static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
 	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) {
@@ -1825,7 +1810,14 @@ static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
 		} else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
 			ksmbd_debug(SMB,
 				    "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
-			conn->posix_ext_supported = true;
+			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");
Signature · 1 line
2.25.1
author maintainer
#12 lore raw

PATCH 13/22 ksmbd: validate POSIX create contexts

In reply to Namjae Jeon

POSIX create contexts are only examined when the tree has POSIX extensions enabled, and IPC requests bypass this validation.

Examine POSIX contexts before selecting the IPC create path. Reject duplicate contexts and require an SMB3.1.1 connection, a POSIX-enabled tree and a non-IPC share for POSIX creates.

---
 fs/smb/server/oplock.c  | 14 +++++++++++---
 fs/smb/server/smb2pdu.c | 24 ++++++++++++++++++------
 2 files changed, 29 insertions(+), 9 deletions(-)
fs/smb/server/oplock.c +11 -3
index 5873bd349e08..a911ff70b29e 100644
@@ -2371,6 +2371,9 @@ struct create_context *smb2_find_context_vals(void *open_req, const char *tag, i
 	struct create_context *cc;
 	unsigned int next = 0;
 	char *name;
+	struct create_context *found = NULL;
+	bool posix_tag = tag_len == POSIX_CTXT_DATA_LEN &&
+			 !memcmp(tag, SMB2_CREATE_TAG_POSIX, POSIX_CTXT_DATA_LEN);
 	struct smb2_create_req *req = (struct smb2_create_req *)open_req;
 	unsigned int remain_len, name_off, name_len, value_off, value_len,
 		     cc_len;
@@ -2408,13 +2411,18 @@ struct create_context *smb2_find_context_vals(void *open_req, const char *tag, i
 			return ERR_PTR(-EINVAL);
 
 		name = (char *)cc + name_off;
-		if (name_len == tag_len && !memcmp(name, tag, name_len))
-			return cc;
+		if (name_len == tag_len && !memcmp(name, tag, name_len)) {
+			if (!posix_tag)
+				return cc;
+			if (found)
+				return ERR_PTR(-EINVAL);
+			found = cc;
+		}
 
 		remain_len -= next;
 	} while (next != 0);
 
-	return NULL;
+	return found;
 }
 
 /**
fs/smb/server/smb2pdu.c +18 -6
index 17bd7413e137..a1e553ddde46 100644
@@ -4264,12 +4264,7 @@ int smb2_open(struct ksmbd_work *work)
 		return -EINVAL;
 	}
 
-	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->CreateContextsOffset && tcon->posix_extensions) {
+	if (req->CreateContextsOffset) {
 		context = smb2_find_context_vals(req, SMB2_CREATE_TAG_POSIX, 16);
 		if (IS_ERR(context)) {
 			rc = PTR_ERR(context);
@@ -4277,6 +4272,19 @@ int smb2_open(struct ksmbd_work *work)
 		} 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) {
@@ -4289,6 +4297,10 @@ int smb2_open(struct ksmbd_work *work)
 			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),
Signature · 1 line
2.25.1
author maintainer
#13 lore raw

PATCH 14/22 ksmbd: enforce POSIX append-only writes

In reply to Namjae Jeon

POSIX append-only opens do not set O_APPEND, and the SMB append sentinel is rejected as a negative write offset.

Track append-only POSIX opens, set O_APPEND and require the U64_MAX offset sentinel for their writes. Accept FILE_WRITE_DATA or FILE_APPEND_DATA for WRITE requests, preserving ordinary SMB write permissions. Use the POSIX append flag and offset check to prevent POSIX append-only opens from overwriting existing data.

For synchronous writes, derive the fsync range from the completed write position so append writes flush the range actually written.

---
 fs/smb/server/smb2pdu.c   | 14 ++++++++++++--
 fs/smb/server/vfs.c       |  3 +--
 fs/smb/server/vfs_cache.h |  1 +
 3 files changed, 14 insertions(+), 4 deletions(-)
fs/smb/server/smb2pdu.c +12 -2
index a1e553ddde46..396f10fb2a91 100644
@@ -4736,6 +4736,9 @@ int smb2_open(struct ksmbd_work *work)
 					    &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)) {
@@ -4975,6 +4978,7 @@ int smb2_open(struct ksmbd_work *work)
 			FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
 
 	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, and stream are
@@ -10223,6 +10227,7 @@ int smb2_write(struct ksmbd_work *work)
 	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;
@@ -10254,7 +10259,8 @@ int smb2_write(struct ksmbd_work *work)
 		return smb2_write_pipe(work);
 	}
 
-	offset = le64_to_cpu(req->Offset);
+	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;
@@ -10357,11 +10363,15 @@ int smb2_write(struct ksmbd_work *work)
 		goto out;
 	}
 
-	if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
+	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);
fs/smb/server/vfs.c +1 -2
index 181d27f43f31..f917f6aeb84d 100644
@@ -526,7 +526,6 @@ int ksmbd_vfs_write(struct ksmbd_work *work, struct ksmbd_file *fp,
 		    ssize_t *written)
 {
 	struct file *filp;
-	loff_t	offset = *pos;
 	int err = 0;
 
 	if (work->conn->connection_type) {
@@ -573,7 +572,7 @@ int ksmbd_vfs_write(struct ksmbd_work *work, struct ksmbd_file *fp,
 	*written = err;
 	err = 0;
 	if (sync) {
-		err = vfs_fsync_range(filp, offset, offset + *written, 0);
+		err = vfs_fsync_range(filp, *pos - *written, *pos, 0);
 		if (err < 0)
 			pr_err("fsync failed for filename = %pD, err = %d\n",
 			       fp->filp, err);
fs/smb/server/vfs_cache.h +1 -0
index 1054002ec4c5..064a053b92b1 100644
@@ -173,6 +173,7 @@ struct ksmbd_file {
 	bool				durable_replay_consumed;
 
 	bool                            is_posix_ctxt;
+	bool				posix_append;
 	struct durable_owner		owner;
 	__le16				channel_sequence;
 	unsigned int			outstanding_requests;
Signature · 1 line
2.25.1
author maintainer
#14 lore raw

PATCH 15/22 ksmbd: apply byte-range lock checks per open

In reply to Namjae Jeon

Using the tree's POSIX extension flag to skip byte-range lock checks also skips them for ordinary opens on a POSIX-enabled tree.

Base the read and write lock checks on each file's POSIX create context instead.

---
 fs/smb/server/vfs.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/smb/server/vfs.c +2 -2
index f917f6aeb84d..de08e63a7794 100644
@@ -362,7 +362,7 @@ int ksmbd_vfs_read(struct ksmbd_work *work, struct ksmbd_file *fp, size_t count,
 	if (ksmbd_stream_fd(fp))
 		return ksmbd_vfs_stream_read(fp, rbuf, pos, count);
 
-	if (!work->tcon->posix_extensions) {
+	if (!fp->is_posix_ctxt) {
 		int ret;
 
 		ret = check_lock_range(filp, *pos, *pos + count - 1, READ);
@@ -547,7 +547,7 @@ int ksmbd_vfs_write(struct ksmbd_work *work, struct ksmbd_file *fp,
 		goto out;
 	}
 
-	if (!work->tcon->posix_extensions) {
+	if (!fp->is_posix_ctxt) {
 		err = check_lock_range(filp, *pos, *pos + count - 1, WRITE);
 		if (err) {
 			pr_err("unable to write due to lock\n");
Signature · 1 line
2.25.1
author maintainer
#15 lore raw

PATCH 16/22 ksmbd: use requested mode in POSIX creates

In reply to Namjae Jeon

The share mode helpers treat a requested POSIX mode of zero as an unspecified mode, replacing it with the share's default permissions.

Use the requested mode, including zero, before applying the share masks and forced modes. Pass an explicit default-mode sentinel for non-POSIX creates to keep their existing mode selection.

---
 fs/smb/server/mgmt/share_config.h | 4 ++--
 fs/smb/server/smb2pdu.c           | 2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)
fs/smb/server/mgmt/share_config.h +2 -2
index 91691b525907..390c966726f4 100644
@@ -45,7 +45,7 @@ static inline umode_t
 share_config_create_mode(struct ksmbd_share_config *share,
 			 umode_t posix_mode)
 {
-	umode_t mode = (posix_mode ?: (umode_t)-1) & share->create_mask;
+	umode_t mode = posix_mode & share->create_mask;
 
 	return mode | share->force_create_mode;
 }
@@ -54,7 +54,7 @@ static inline umode_t
 share_config_directory_mode(struct ksmbd_share_config *share,
 			    umode_t posix_mode)
 {
-	umode_t mode = (posix_mode ?: (umode_t)-1) & share->directory_mask;
+	umode_t mode = posix_mode & share->directory_mask;
 
 	return mode | share->force_directory_mode;
 }
fs/smb/server/smb2pdu.c +1 -1
index 396f10fb2a91..953a2eeaa15a 100644
@@ -4752,7 +4752,7 @@ int smb2_open(struct ksmbd_work *work)
 	/*create file if not present */
 	if (!file_present) {
 		rc = smb2_creat(work, &path, name, open_flags,
-				posix_mode,
+				posix_ctxt ? posix_mode : (umode_t)-1,
 				req->CreateOptions & FILE_DIRECTORY_FILE_LE);
 		if (rc) {
 			if (rc == -ENOENT) {
Signature · 1 line
2.25.1
author maintainer
#16 lore raw

PATCH 17/22 ksmbd: apply POSIX mode ACEs in security updates

In reply to Namjae Jeon

Explicit modes carried by NFS mode ACEs can be overwritten by the DACL permission fallback, and security updates discard special mode bits.

Track modes supplied by ACCESS_ALLOWED NFS mode ACEs and bypass the permission fallback for them. Apply both permission and special bits when setting an explicit POSIX mode.

For SET_INFO, require a POSIX open for explicit mode changes and apply the mode only when DACL security information is requested.

---
 fs/smb/server/smb2pdu.c |  7 +++++--
 fs/smb/server/smbacl.c  | 26 +++++++++++++++++++++++---
 fs/smb/server/smbacl.h  |  4 +++-
 3 files changed, 31 insertions(+), 6 deletions(-)
fs/smb/server/smb2pdu.c +5 -2
index 953a2eeaa15a..92489bb86791 100644
@@ -3667,7 +3667,8 @@ static int smb2_create_sd_buffer(struct ksmbd_work *work,
 	    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);
+			    le32_to_cpu(sd_buf->ccontext.DataLength), true, false,
+			    true, true);
 }
 
 static int ksmbd_acls_fattr(struct smb_fattr *fattr,
@@ -9241,7 +9242,9 @@ static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
 		return -EACCES;
 
 	return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
-			buf_len, false, true);
+			buf_len, false, true,
+			fp->conn->dialect == SMB311_PROT_ID && fp->is_posix_ctxt,
+			addition_info & DACL_SECINFO);
 }
 
 static int smb2_set_info_quota(struct ksmbd_work *work, struct ksmbd_file *fp,
fs/smb/server/smbacl.c +23 -3
index e75247915c87..a01e0a8b76cb 100644
@@ -477,10 +477,12 @@ static int parse_dacl(struct mnt_idmap *idmap,
 		ppace[i]->access_req =
 			smb_map_generic_desired_access(ppace[i]->access_req);
 
-		if (ppace[i]->sid.num_subauth >= 3 &&
+		if (ppace[i]->type == ACCESS_ALLOWED &&
+		    ppace[i]->sid.num_subauth >= 3 &&
 		    !(compare_sids(&ppace[i]->sid, &sid_unix_NFS_mode))) {
 			fattr->cf_mode =
 				le32_to_cpu(ppace[i]->sid.sub_auth[2]);
+			fattr->cf_posix_mode = true;
 			break;
 		} else if (!compare_sids(&ppace[i]->sid, pownersid)) {
 			acl_mode = access_flags_to_mode(fattr,
@@ -546,6 +548,10 @@ static int parse_dacl(struct mnt_idmap *idmap,
 				((acl_mode & 0700) >> 6) | 0004;
 		}
 	}
+	if (fattr->cf_posix_mode) {
+		ret = 0;
+		goto out;
+	}
 
 	if (owner_found) {
 		/* The owner must be set to at least read-only. */
@@ -1673,7 +1679,8 @@ EXPORT_SYMBOL_IF_KUNIT(smb_check_perm_dacl);
 
 int set_info_sec(struct ksmbd_conn *conn, struct ksmbd_tree_connect *tcon,
 		 const struct path *path, struct smb_ntsd *pntsd, int ntsd_len,
-		 bool type_check, bool get_write)
+		 bool type_check, bool get_write, bool posix_open,
+		 bool dacl_requested)
 {
 	int rc;
 	struct smb_fattr fattr = {{0}};
@@ -1688,6 +1695,14 @@ int set_info_sec(struct ksmbd_conn *conn, struct ksmbd_tree_connect *tcon,
 	rc = parse_sec_desc(idmap, pntsd, ntsd_len, &fattr);
 	if (rc)
 		goto out;
+	if (fattr.cf_posix_mode && !dacl_requested) {
+		fattr.cf_posix_mode = false;
+		fattr.cf_mode = inode->i_mode;
+	}
+	if (fattr.cf_posix_mode && !posix_open) {
+		rc = -EOPNOTSUPP;
+		goto out;
+	}
 
 	newattrs.ia_valid = ATTR_CTIME;
 	if (!uid_eq(fattr.cf_uid, INVALID_UID)) {
@@ -1699,7 +1714,12 @@ int set_info_sec(struct ksmbd_conn *conn, struct ksmbd_tree_connect *tcon,
 		newattrs.ia_gid = fattr.cf_gid;
 	}
 	newattrs.ia_valid |= ATTR_MODE;
-	newattrs.ia_mode = (inode->i_mode & ~0777) | (fattr.cf_mode & 0777);
+	if (fattr.cf_posix_mode)
+		newattrs.ia_mode = (inode->i_mode & ~07777) |
+				   (fattr.cf_mode & 07777);
+	else
+		newattrs.ia_mode = (inode->i_mode & ~0777) |
+				   (fattr.cf_mode & 0777);
 
 	ksmbd_vfs_remove_acl_xattrs(idmap, path);
 	/* Update posix acls */
fs/smb/server/smbacl.h +3 -1
index 01810c16cc04..c9705548efb2 100644
@@ -43,6 +43,7 @@ struct smb_fattr {
 	kuid_t	cf_uid;
 	kgid_t	cf_gid;
 	umode_t	cf_mode;
+	bool	cf_posix_mode;
 	__le32 daccess;
 	struct posix_acl *cf_acls;
 	struct posix_acl *cf_dacls;
@@ -99,7 +100,8 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path,
 			bool strict);
 int set_info_sec(struct ksmbd_conn *conn, struct ksmbd_tree_connect *tcon,
 		 const struct path *path, struct smb_ntsd *pntsd, int ntsd_len,
-		 bool type_check, bool get_write);
+		 bool type_check, bool get_write, bool posix_open,
+		 bool dacl_requested);
 void id_to_sid(unsigned int cid, uint sidtype, struct smb_sid *ssid);
 void ksmbd_init_domain(u32 *sub_auth);
 size_t smb_acl_sec_desc_scratch_len(struct smb_fattr *fattr,
Signature · 1 line
2.25.1
author maintainer
#17 lore raw

PATCH 18/22 ksmbd: correct POSIX file metadata in responses

In reply to Namjae Jeon

POSIX responses omit special permission bits, and the create response reports a file identifier as its reparse tag without encoding the file type. Directory and file queries also report rdev as the filesystem device identifier.

Report the POSIX mode and file type in create responses, include special permission bits in all three response paths, and use the special-file reparse tag consistently. Set the corresponding DOS attribute in directory and file queries, report the filesystem device identifier and initialize reserved fields.

---
 fs/smb/server/oplock.c  | 23 +++++++++++++++++++++--
 fs/smb/server/smb2pdu.c | 19 ++++++++++++++-----
 fs/smb/server/smb2pdu.h |  2 ++
 3 files changed, 37 insertions(+), 7 deletions(-)
fs/smb/server/oplock.c +21 -2
index a911ff70b29e..10c81550b8a7 100644
@@ -2569,8 +2569,27 @@ void create_posix_rsp_buf(char *cc, struct ksmbd_file *fp)
 	buf->Name[15] = 0x7C;
 
 	buf->nlink = cpu_to_le32(inode->i_nlink);
-	buf->reparse_tag = cpu_to_le32(fp->volatile_id);
-	buf->mode = cpu_to_le32(inode->i_mode & 0777);
+	buf->reparse_tag = smb2_get_reparse_tag_special_file(inode->i_mode);
+	buf->mode = cpu_to_le32(inode->i_mode & 07777);
+	switch (inode->i_mode & S_IFMT) {
+	case S_IFDIR:
+		buf->mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT);
+		break;
+	case S_IFLNK:
+		buf->mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT);
+		break;
+	case S_IFCHR:
+		buf->mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT);
+		break;
+	case S_IFBLK:
+		buf->mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT);
+		break;
+	case S_IFIFO:
+		buf->mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT);
+		break;
+	case S_IFSOCK:
+		buf->mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
+	}
 	/*
 	 * SidBuffer(44) contain two sids(Domain sid(28), UNIX group sid(16)).
 	 * Domain sid(28) = revision(1) + num_subauth(1) + authority(6) +
fs/smb/server/smb2pdu.c +14 -5
index 92489bb86791..a4908b6e566e 100644
@@ -1294,7 +1294,7 @@ void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
 	ksmbd_free_work_struct(in_work);
 }
 
-static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
+__le32 smb2_get_reparse_tag_special_file(umode_t mode)
 {
 	if (S_ISDIR(mode) || S_ISREG(mode))
 		return 0;
@@ -6020,6 +6020,7 @@ static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
 
 		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);
@@ -6029,9 +6030,11 @@ static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
 		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->rdev);
+		posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->dev);
 		posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
-		posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777);
+		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);
@@ -6056,6 +6059,8 @@ static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
 		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;
 		/*
@@ -7500,7 +7505,7 @@ static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
 		file_info->AllocationSize = cpu_to_le64((u64)seof);
 	}
 	file_info->HardLinks = cpu_to_le32(stat.nlink);
-	file_info->Mode = cpu_to_le32(stat.mode & 0777);
+	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);
@@ -7521,7 +7526,11 @@ static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
 	}
 
-	file_info->DeviceId = cpu_to_le32(stat.rdev);
+	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)).
fs/smb/server/smb2pdu.h +2 -0
index e07700d0a405..e706aa52352c 100644
@@ -168,6 +168,8 @@ struct create_posix_rsp {
 	u8 SidBuffer[44];
 } __packed;
 
+__le32 smb2_get_reparse_tag_special_file(umode_t mode);
+
 #define SMB2_0_IOCTL_IS_FSCTL 0x00000001
 
 struct sockaddr_storage_rsp {
Signature · 1 line
2.25.1
author maintainer
#18 lore raw

PATCH 19/22 ksmbd: include filenames in POSIX query info

In reply to Namjae Jeon

The POSIX file query response ends after the owner and group SIDs, omitting the filename length and filename.

Append the path relative to the share in UTF-16, without a leading separator, and include its byte length in the response. Check both the fixed fields and the converted filename against the available output buffer before writing the response.

---
 fs/smb/server/smb2pdu.c | 56 ++++++++++++++++++++++++++++++++++++-----
 1 file changed, 50 insertions(+), 6 deletions(-)
fs/smb/server/smb2pdu.c +50 -6
index a4908b6e566e..6fd8ec6be222 100644
@@ -7463,8 +7463,10 @@ static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
 	return 0;
 }
 
-static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
-				struct ksmbd_file *fp, void *rsp_org)
+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);
@@ -7472,9 +7474,13 @@ static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
 	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 out_buf_len = sizeof(struct smb311_posix_qinfo) + 32;
-	int ret;
+	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",
@@ -7485,6 +7491,38 @@ static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
 	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_array(name_bytes + 1, sizeof(*utf16_name),
+				    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);
@@ -7541,8 +7579,14 @@ static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
 		  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(out_buf_len);
+	rsp->OutputBufferLength = cpu_to_le32(fixed_len +
+					       conv_len * sizeof(__le16));
 
 	return 0;
 }
@@ -7652,7 +7696,7 @@ static int smb2_get_info_file(struct ksmbd_work *work,
 			pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
 			rc = -EOPNOTSUPP;
 		} else {
-			rc = find_file_posix_info(rsp, fp, work->response_buf);
+			rc = find_file_posix_info(work, req, rsp, fp);
 		}
 		break;
 	default:
Signature · 1 line
2.25.1
author maintainer
#19 lore raw

PATCH 20/22 ksmbd: require POSIX opens for file and directory queries

In reply to Namjae Jeon

POSIX file information queries only check the tree's extension flag, while directory queries do not verify that the directory was opened with a POSIX create context.

Require SMB3.1.1, negotiated POSIX tree extensions and a POSIX open for both file and directory POSIX information requests. Return STATUS_INVALID_INFO_CLASS when these conditions are not met.

---
 fs/smb/server/smb2pdu.c | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
fs/smb/server/smb2pdu.c +9 -2
index 6fd8ec6be222..b3683e85cb31 100644
@@ -6470,6 +6470,12 @@ int smb2_query_dir(struct ksmbd_work *work)
 		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),
@@ -7692,8 +7698,9 @@ static int smb2_get_info_file(struct ksmbd_work *work,
 		rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
 		break;
 	case SMB_FIND_FILE_POSIX_INFO:
-		if (!work->tcon->posix_extensions) {
-			pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
+		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);
Signature · 1 line
2.25.1
author maintainer
#20 lore raw

PATCH 21/22 ksmbd: query POSIX filesystem info through the open file

In reply to Namjae Jeon

POSIX filesystem queries use the share root for statfs and do not validate the requested file handle. This can report the wrong filesystem for files below a mount point within the share.

Require SMB3.1.1 POSIX extensions and a valid POSIX open. Resolve the requested handle, including compound file IDs, and use its referenced path for the filesystem query.

---
 fs/smb/server/smb2pdu.c | 73 ++++++++++++++++++++++++++---------------
 1 file changed, 47 insertions(+), 26 deletions(-)
fs/smb/server/smb2pdu.c +47 -26
index b3683e85cb31..6dfeb6078600 100644
@@ -7747,20 +7747,47 @@ static int smb2_get_info_filesystem(struct ksmbd_work *work,
 {
 	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 (!share->path)
-		return -EIO;
+	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;
+		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);
@@ -7973,25 +8000,19 @@ static int smb2_get_info_filesystem(struct ksmbd_work *work,
 	{
 		FILE_SYSTEM_POSIX_INFO *info;
 
-		if (!work->tcon->posix_extensions) {
-			pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
-			path_put(&path);
-			return -EOPNOTSUPP;
-		} else {
-			info = (FILE_SYSTEM_POSIX_INFO *)(rsp->Buffer);
-			info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
-			info->BlockSize = cpu_to_le32(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(56);
-			fixed_len = 56;
-		}
+		info = (FILE_SYSTEM_POSIX_INFO *)(rsp->Buffer);
+		info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
+		info->BlockSize = cpu_to_le32(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(56);
+		fixed_len = 56;
 		break;
 	}
 	default:
Signature · 1 line
2.25.1
author maintainer
#21 lore raw

PATCH 22/22 ksmbd: correct POSIX filesystem block size and response length

In reply to Namjae Jeon

POSIX filesystem information uses f_bsize for BlockSize even when the filesystem reports a distinct fragment size for its block counts.

Use f_frsize when available, falling back to f_bsize. Keep f_bsize as the optimal transfer size and derive the response length from the information structure instead of a hard-coded value.

---
 fs/smb/server/smb2pdu.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
fs/smb/server/smb2pdu.c +3 -3
index 6dfeb6078600..19ff569c001b 100644
@@ -8002,7 +8002,7 @@ static int smb2_get_info_filesystem(struct ksmbd_work *work,
 
 		info = (FILE_SYSTEM_POSIX_INFO *)(rsp->Buffer);
 		info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
-		info->BlockSize = 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);
@@ -8011,8 +8011,8 @@ static int smb2_get_info_filesystem(struct ksmbd_work *work,
 		info->FileSysIdentifier =
 			cpu_to_le64((u64)(u32)stfs.f_fsid.val[1] << 32 |
 				    (u32)stfs.f_fsid.val[0]);
-		rsp->OutputBufferLength = cpu_to_le32(56);
-		fixed_len = 56;
+		rsp->OutputBufferLength = cpu_to_le32(sizeof(*info));
+		fixed_len = sizeof(*info);
 		break;
 	}
 	default:
Signature · 1 line
2.25.1