Skip to contentSkip to conversation

smb/server: change notify support

PATCH In review ChenXiaoSong 2 participants 17 messages Oct 25 – Oct 28

Subsystems (2)
lore
Share & tools
lore

ChenXiaoSong

author reviewer
#0 lore raw

v2 cover smb/server: change notify support

From: ChenXiaoSong <[email protected]>

v1->v2:
- Patch #04 #07: fix LAST_WRITE and LAST_ACCESS notify event mappings.
- Patch #04 #08 #09 #11 #12: limit notify event memory per open.
- Add patch #13: support change notify for named streams.

v1: https://lore.kernel.org/linux-cifs/[email protected]/

TODO: The KUnit test cases are still being modified.

To test this feature, the following patches need to be applied to cifs-utils and kernel smb client:
- cifs-utils: https://chenxiaosong.com/lkml/cifs-utils-parse-notify
- kernel smb client: https://chenxiaosong.com/lkml/cifs-improve-notify

The complete kernel client and server patches are also available at the following link:
https://chenxiaosong.com/repo/linux/ksmbd-change-notify

ChenXiaoSong (13):
smb/server: move change notify handling into notify.c smb/server: add more validation for change notify requests smb/server: add debug type for change notify smb/server: support non-recursive directory change watches smb/server: support recursive directory change watches smb/server: keep notify watches on file handles smb/server: save simple notify events
smb/server: save old names for rename notify events smb/server: match rename notify events
smb/server: encode notify events
smb/server: send notify events to the client smb/server: break directory leases before sending notify events smb/server: support change notify for named streams

 fs/smb/server/Kconfig     |    1 +
 fs/smb/server/Makefile    |    3 +-
 fs/smb/server/glob.h      |    3 +-
 fs/smb/server/notify.c    | 1415 +++++++++++++++++++++++++++++++++++++
 fs/smb/server/notify.h    |   80 +++
 fs/smb/server/oplock.c    |   40 ++
 fs/smb/server/oplock.h    |    1 +
 fs/smb/server/server.c    |    2 +-
 fs/smb/server/smb2pdu.c   |  112 +--
 fs/smb/server/vfs.c       |   67 +-
 fs/smb/server/vfs_cache.c |    3 +
 fs/smb/server/vfs_cache.h |    4 +
 12 files changed, 1614 insertions(+), 117 deletions(-)
 create mode 100644 fs/smb/server/notify.c
 create mode 100644 fs/smb/server/notify.h
Signature · 1 line
2.55.0
author reviewer
#1 lore raw

PATCH v2 1/13 smb/server: move change notify handling into notify.c

From: ChenXiaoSong <[email protected]>

Move the SMB2 CHANGE_NOTIFY implementation out of smb2pdu.c into a dedicated notify.c file.

Factor out two helper functions ksmbd_notify_validate_req() and ksmbd_notify_wait().

No functional change.

---
 fs/smb/server/Makefile  |   3 +-
 fs/smb/server/notify.c  | 179 ++++++++++++++++++++++++++++++++++++++++
 fs/smb/server/notify.h  |  30 +++++++
 fs/smb/server/smb2pdu.c | 110 +-----------------------
 4 files changed, 215 insertions(+), 107 deletions(-)
 create mode 100644 fs/smb/server/notify.c
 create mode 100644 fs/smb/server/notify.h
fs/smb/server/Makefile +2 -1
index 9bc87695a53c..5daae1727b32 100644
@@ -10,7 +10,8 @@ ksmbd-y :=	unicode.o auth.o vfs.o vfs_cache.o server.o ndr.o \
 		mgmt/tree_connect.o mgmt/user_session.o smb_common.o \
 		transport_tcp.o transport_ipc.o smbacl.o smb2pdu.o \
 		smb2ops.o smb2misc.o ksmbd_spnego_negtokeninit.asn1.o \
-		ksmbd_spnego_negtokentarg.asn1.o asn1.o compress.o
+		ksmbd_spnego_negtokentarg.asn1.o asn1.o compress.o \
+		notify.o
 
 $(obj)/asn1.o: $(obj)/ksmbd_spnego_negtokeninit.asn1.h $(obj)/ksmbd_spnego_negtokentarg.asn1.h
 
fs/smb/server/notify.c new file +179 -0

179 lines not on this page · raw message

fs/smb/server/notify.h new file +30 -0
new file mode 100644
index 000000000000..eb2fc646208f
@@ -0,0 +1,30 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/*
+ *
+ *   SMB2 CHANGE_NOTIFY
+ *
+ *   Copyright (C) 2026 KylinSoft Co., Ltd. All rights reserved.
+ *
+ *   Author(s): ChenXiaoSong <[email protected]>
+ *              Gael Blivet <[email protected]>
+ *
+ */
+
+#ifndef __SMB_SERVER_NOTIFY_H__
+#define __SMB_SERVER_NOTIFY_H__
+
+#include <linux/wait.h>
+
+struct ksmbd_work;
+struct smb2_change_notify_req;
+struct smb2_change_notify_rsp;
+
+struct ksmbd_notify_req {
+	wait_queue_head_t wait;
+};
+
+int ksmbd_handle_notify(struct ksmbd_work *work,
+			struct smb2_change_notify_req *req,
+			struct smb2_change_notify_rsp *rsp);
+
+#endif /* __SMB_SERVER_NOTIFY_H__ */
fs/smb/server/smb2pdu.c +4 -106

136 lines not on this page · raw message

Signature · 1 line
2.55.0
author reviewer
#2 lore raw

PATCH v2 2/13 smb/server: add more validation for change notify requests

In reply to ChenXiaoSong

From: ChenXiaoSong <[email protected]>

Add validation for the file type, directory list access and output buffer length before setting up a change notify watch.

---
 fs/smb/server/notify.c | 31 +++++++++++++++++++++++++++++++
 1 file changed, 31 insertions(+)
fs/smb/server/notify.c +31 -0
index 7bf55ee633c3..a5a71c2efe5d 100644
@@ -44,6 +44,7 @@ ksmbd_notify_validate_req(struct ksmbd_work *work,
 			  struct smb2_change_notify_rsp *rsp)
 {
 	struct ksmbd_file *fp;
+	int err;
 
 	if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
 		pr_err("Notify request is not the last compound command\n");
@@ -61,7 +62,37 @@ ksmbd_notify_validate_req(struct ksmbd_work *work,
 		return ERR_PTR(-ENOENT);
 	}
 
+	if (le32_to_cpu(req->OutputBufferLength) >
+	    work->conn->vals->max_trans_size) {
+		pr_err("Notify output buffer length %u exceeds maximum %u\n",
+		       le32_to_cpu(req->OutputBufferLength),
+		       work->conn->vals->max_trans_size);
+		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
+		err = -EINVAL;
+		goto err_put_fp;
+	}
+
+	if (!S_ISDIR(file_inode(fp->filp)->i_mode)) {
+		pr_err("Notify file id is not a directory, fid %llu:%llu\n",
+		       fp->persistent_id, fp->volatile_id);
+		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
+		err = -EINVAL;
+		goto err_put_fp;
+	}
+
+	if (!(fp->daccess & FILE_LIST_DIRECTORY_LE)) {
+		pr_err("No permission to monitor directory, fid %llu:%llu\n",
+		       fp->persistent_id, fp->volatile_id);
+		rsp->hdr.Status = STATUS_ACCESS_DENIED;
+		err = -EACCES;
+		goto err_put_fp;
+	}
+
 	return fp;
+
+err_put_fp:
+	ksmbd_fd_put(work, fp);
+	return ERR_PTR(err);
 }
 
 static int ksmbd_notify_wait(struct ksmbd_work *work,
Signature · 1 line
2.55.0
author reviewer
#3 lore raw

PATCH v2 3/13 smb/server: add debug type for change notify

In reply to ChenXiaoSong

From: ChenXiaoSong <[email protected]>

Add KSMBD_DEBUG_NOTIFY and expose it as "notify" to print logs for the change notify feature.

Example:

ksmbd.control --debug=notify
[ksmbd.control/802]: INFO: smb auth vfs oplock ipc conn rdma [notify]

---
 fs/smb/server/glob.h    |  3 ++-
 fs/smb/server/notify.c  | 12 ++++++++++++
 fs/smb/server/server.c  |  2 +-
 fs/smb/server/smb2pdu.c |  2 +-
 4 files changed, 16 insertions(+), 3 deletions(-)
fs/smb/server/glob.h +2 -1
index 4ea187af2348..5131bad88d96 100644
@@ -21,10 +21,11 @@ extern int ksmbd_debug_types;
 #define KSMBD_DEBUG_IPC         BIT(4)
 #define KSMBD_DEBUG_CONN        BIT(5)
 #define KSMBD_DEBUG_RDMA        BIT(6)
+#define KSMBD_DEBUG_NOTIFY      BIT(7)
 #define KSMBD_DEBUG_ALL         (KSMBD_DEBUG_SMB | KSMBD_DEBUG_AUTH |	\
 				KSMBD_DEBUG_VFS | KSMBD_DEBUG_OPLOCK |	\
 				KSMBD_DEBUG_IPC | KSMBD_DEBUG_CONN |	\
-				KSMBD_DEBUG_RDMA)
+				KSMBD_DEBUG_RDMA | KSMBD_DEBUG_NOTIFY)
 
 #ifdef pr_fmt
 #undef pr_fmt
fs/smb/server/notify.c +12 -0
index a5a71c2efe5d..744dacc070c6 100644
@@ -35,6 +35,7 @@ static void smb2_notify_cancel(void **argv)
 {
 	struct ksmbd_notify_req *notify_req = argv[0];
 
+	ksmbd_debug(NOTIFY, "Wake pending notify request\n");
 	wake_up(&notify_req->wait);
 }
 
@@ -62,6 +63,11 @@ ksmbd_notify_validate_req(struct ksmbd_work *work,
 		return ERR_PTR(-ENOENT);
 	}
 
+	ksmbd_debug(NOTIFY,
+		    "fid %llu:%llu, handle notify request, filter 0x%x, flags 0x%x\n",
+		    fp->persistent_id, fp->volatile_id,
+		    le32_to_cpu(req->CompletionFilter), le16_to_cpu(req->Flags));
+
 	if (le32_to_cpu(req->OutputBufferLength) >
 	    work->conn->vals->max_trans_size) {
 		pr_err("Notify output buffer length %u exceeds maximum %u\n",
@@ -117,6 +123,8 @@ static int ksmbd_notify_wait(struct ksmbd_work *work,
 	spin_unlock(&fp->f_lock);
 	read_unlock(&work->sess->file_table.lock);
 
+	ksmbd_debug(NOTIFY, "Notify request pending, async id %d\n",
+		    work->async_id);
 	smb2_send_interim_resp(work, STATUS_PENDING);
 
 	err = wait_event_interruptible(notify_req->wait,
@@ -191,8 +199,12 @@ int ksmbd_handle_notify(struct ksmbd_work *work,
 
 	if (work->state == KSMBD_WORK_CLOSED) {
 		rsp->hdr.Status = STATUS_NOTIFY_CLEANUP;
+		ksmbd_debug(NOTIFY, "Notify handle closed, async id %d\n",
+			    work->async_id);
 	} else {
 		rsp->hdr.Status = STATUS_CANCELLED;
+		ksmbd_debug(NOTIFY, "Notify request cancelled, async id %d\n",
+			    work->async_id);
 	}
 	smb2_send_interim_resp(work, rsp->hdr.Status);
 	work->send_no_response = 1;
fs/smb/server/server.c +1 -1
index 064f99427ca6..387e3a13ec7e 100644
@@ -589,7 +589,7 @@ static ssize_t kill_server_store(const struct class *class,
 
 static const char * const debug_type_strings[] = {"smb", "auth", "vfs",
 						  "oplock", "ipc", "conn",
-						  "rdma"};
+						  "rdma", "notify"};
 
 static ssize_t debug_show(const struct class *class, const struct class_attribute *attr,
 			  char *buf)
fs/smb/server/smb2pdu.c +1 -1
index 5ad78e3eee2d..8ee53c0ba93a 100644
@@ -12478,7 +12478,7 @@ int smb2_notify(struct ksmbd_work *work)
 	struct smb2_change_notify_req *req;
 	struct smb2_change_notify_rsp *rsp;
 
-	ksmbd_debug(SMB, "Received smb2 notify\n");
+	ksmbd_debug(NOTIFY, "Received smb2 notify\n");
 
 	WORK_BUFFERS(work, req, rsp);
 
Signature · 1 line
2.55.0
author reviewer
#4 lore raw

PATCH v2 4/13 smb/server: support non-recursive directory change watches

In reply to ChenXiaoSong

From: ChenXiaoSong <[email protected]>

Use fsnotify to watch a directory for changes. Add one watch for each SMB2 CHANGE_NOTIFY request with SMB2_WATCH_TREE unset.

Example:

1. client: smbinfo notify /mnt
2. server: ksmbd.control --debug=notify
3. server: touch /export/file
4. server debug log:

     ksmbd: fid 4:4, notify event: mask=0x00000100 inode=2 name=file cookie=0
     ksmbd: fid 4:4, notify event: mask=0x08000004 inode=2 name=file cookie=0
---
 fs/smb/server/Kconfig  |   1 +
 fs/smb/server/notify.c | 219 ++++++++++++++++++++++++++++++++++++++++-
 fs/smb/server/notify.h |  15 ++-
 3 files changed, 232 insertions(+), 3 deletions(-)
fs/smb/server/Kconfig +1 -0
index f8b03605db59..7b8ec245b12f 100644
@@ -20,6 +20,7 @@ config SMB_SERVER
 	select ASN1
 	select OID_REGISTRY
 	select CRC32
+	select FSNOTIFY
 	default n
 	help
 	  Choose Y here if you want to allow SMB3 compliant clients
fs/smb/server/notify.c +217 -2

276 lines not on this page · raw message

fs/smb/server/notify.h +14 -1
index eb2fc646208f..185ce93b01cc 100644
@@ -13,16 +13,29 @@
 #ifndef __SMB_SERVER_NOTIFY_H__
 #define __SMB_SERVER_NOTIFY_H__
 
-#include <linux/wait.h>
+#include <linux/fsnotify_backend.h>
 
 struct ksmbd_work;
 struct smb2_change_notify_req;
 struct smb2_change_notify_rsp;
 
+struct ksmbd_notify {
+	struct fsnotify_group *group;
+	struct fsnotify_mark *mark;
+	struct ksmbd_file *fp;
+	/* Protects filter, rename state and the queued events. */
+	spinlock_t lock;
+	u32 filter;
+	u32 mask;
+};
+
 struct ksmbd_notify_req {
 	wait_queue_head_t wait;
 };
 
+#define KSMBD_NOTIFY_NAME_EVENT_MASK	(FS_CREATE | FS_DELETE | \
+					 FS_MOVED_FROM | FS_MOVED_TO)
+
 int ksmbd_handle_notify(struct ksmbd_work *work,
 			struct smb2_change_notify_req *req,
 			struct smb2_change_notify_rsp *rsp);
Signature · 1 line
2.55.0
maintainer
#5 lore raw

Re: [PATCH v2 04/13] smb/server: support non-recursive directory change watches

Quoted 10 lines
fs/smb/server/notify.c +6 -0
@@ -20,6 +21,40 @@
 #include "vfs_cache.h"
 #include "mgmt/user_session.h"
 
+static const struct {
+       u32 notify_mask;
+       u32 fsnotify_mask;
+} ksmbd_notify_mapping[] = {
+       { FILE_NOTIFY_CHANGE_FILE_NAME,
+         KSMBD_NOTIFY_NAME_EVENT_MASK },

fs/smb/server/notify.c line 39

Quoted 10 lines
fs/smb/server/notify.c +10 -0
+       { FILE_NOTIFY_CHANGE_DIR_NAME,
+         KSMBD_NOTIFY_NAME_EVENT_MASK },
+       { FILE_NOTIFY_CHANGE_ATTRIBUTES,
+         FS_ATTRIB | FS_MOVED_FROM | FS_MOVED_TO | FS_MODIFY },
+       { FILE_NOTIFY_CHANGE_SIZE, FS_MODIFY },
+       { FILE_NOTIFY_CHANGE_LAST_WRITE, FS_ATTRIB | FS_MODIFY },
+       { FILE_NOTIFY_CHANGE_LAST_ACCESS, FS_ATTRIB | FS_ACCESS },
+       { FILE_NOTIFY_CHANGE_EA, FS_ATTRIB },
+       { FILE_NOTIFY_CHANGE_SECURITY, FS_ATTRIB },
+};

FILE_NOTIFY_CHANGE_CREATION is missing here ?

author reviewer
#6 lore raw

PATCH v2 5/13 smb/server: support recursive directory change watches

In reply to ChenXiaoSong

From: ChenXiaoSong <[email protected]>

Support SMB2 CHANGE_NOTIFY requests with SMB2_WATCH_TREE set.

Example:

1. client: smbinfo notify /mnt
2. server: ksmbd.control --debug=notify
3. server: mkdir /export/dir; touch /export/dir/file
4. server debug log:

     ksmbd: fid 1:1, notify event: mask=0x00000100 inode=11 name=dir\file cookie=0
     ksmbd: fid 1:1, notify event: mask=0x00000004 inode=11 name=dir\file cookie=0
---
 fs/smb/server/notify.c | 153 +++++++++++++++++++++++++++++++++++++++--
 fs/smb/server/notify.h |   2 +
 2 files changed, 149 insertions(+), 6 deletions(-)
fs/smb/server/notify.c +147 -6
index 57a8e29bfb09..a9175b864e19 100644
@@ -11,6 +11,7 @@
  */
 
 #include <linux/fsnotify_backend.h>
+#include <linux/dcache.h>
 #include "glob.h"
 #include "../common/smb2status.h"
 #include "connection.h"
@@ -95,6 +96,100 @@ static int ksmbd_notify_handle_inode_event(struct ksmbd_notify *notify,
 	return 0;
 }
 
+static char *ksmbd_notify_tree_name(struct ksmbd_notify *notify,
+				    const void *data, int data_type,
+				    struct inode *dir,
+				    const struct qstr *file_name,
+				    struct qstr *tree_name)
+{
+	struct dentry *root = file_dentry(notify->fp->filp);
+	struct inode *inode = fsnotify_data_inode(data, data_type);
+	struct dentry *dentry;
+	char *buf = NULL, *root_buf = NULL, *name = NULL;
+	char *path, *root_path, *relative;
+	size_t file_name_len = file_name ? file_name->len : 0;
+	size_t prefix_len, root_len, len, i;
+
+	/* Name events refer to @file_name below @dir. */
+	if (file_name && dir) {
+		dentry = d_find_alias(dir);
+	} else {
+		dentry = fsnotify_data_dentry(data, data_type);
+		if (dentry)
+			dget(dentry);
+		else
+			dentry = inode ? d_find_alias(inode) : NULL;
+	}
+	if (!dentry)
+		return ERR_PTR(-ENOENT);
+
+	/* A superblock mark also reports events outside the watched tree. */
+	if (!is_subdir(dentry, root)) {
+		name = ERR_PTR(-EXDEV);
+		goto out_dput;
+	}
+
+	buf = kmalloc(PATH_MAX, KSMBD_DEFAULT_GFP);
+	root_buf = kmalloc(PATH_MAX, KSMBD_DEFAULT_GFP);
+	if (!buf || !root_buf) {
+		name = ERR_PTR(-ENOMEM);
+		goto out_free_bufs;
+	}
+
+	path = dentry_path_raw(dentry, buf, PATH_MAX);
+	root_path = dentry_path_raw(root, root_buf, PATH_MAX);
+	if (IS_ERR(path) || IS_ERR(root_path)) {
+		name = ERR_PTR(IS_ERR(path) ? PTR_ERR(path) : PTR_ERR(root_path));
+		goto out_free_bufs;
+	}
+
+	root_len = strlen(root_path);
+	if (root_len == 1 && root_path[0] == '/') {
+		relative = path + 1;
+	} else if (!strncmp(path, root_path, root_len) &&
+		   (path[root_len] == '/' || path[root_len] == '\0')) {
+		relative = path + root_len;
+		if (*relative == '/')
+			relative++;
+	} else {
+		/* The watched directory was renamed between the two snapshots. */
+		name = ERR_PTR(-EAGAIN);
+		goto out_free_bufs;
+	}
+
+	prefix_len = strlen(relative);
+	if (prefix_len > SIZE_MAX - file_name_len - 2) {
+		name = ERR_PTR(-EOVERFLOW);
+		goto out_free_bufs;
+	}
+	len = prefix_len + file_name_len + (prefix_len && file_name ? 1 : 0);
+	name = kmalloc(len + 1, KSMBD_DEFAULT_GFP);
+	if (!name) {
+		name = ERR_PTR(-ENOMEM);
+		goto out_free_bufs;
+	}
+
+	memcpy(name, relative, prefix_len);
+	if (prefix_len && file_name)
+		name[prefix_len++] = '\\';
+	if (file_name_len)
+		memcpy(name + prefix_len, file_name->name, file_name_len);
+	name[len] = '\0';
+	for (i = 0; i < len; i++) {
+		if (name[i] == '/')
+			name[i] = '\\';
+	}
+	tree_name->name = name;
+	tree_name->len = len;
+
+out_free_bufs:
+	kfree(root_buf);
+	kfree(buf);
+out_dput:
+	dput(dentry);
+	return name;
+}
+
 static int ksmbd_notify_handle_event(struct fsnotify_group *group, u32 mask,
 				     const void *data, int data_type,
 				     struct inode *dir,
@@ -102,10 +197,32 @@ static int ksmbd_notify_handle_event(struct fsnotify_group *group, u32 mask,
 				     struct fsnotify_iter_info *iter_info)
 {
 	struct ksmbd_notify *notify = group->private;
-	struct inode *inode = fsnotify_data_inode(data, data_type);
+	struct qstr tree_name = {};
+	struct inode *inode;
+	char *name = NULL;
+	int err;
+
+	if (!READ_ONCE(notify->watch_tree)) {
+		/* Non-tree watches accept events from the root inode mark only. */
+		if (!fsnotify_iter_inode_mark(iter_info) &&
+		    !fsnotify_iter_parent_mark(iter_info))
+			return 0;
+	} else {
+		name = ksmbd_notify_tree_name(notify, data, data_type, dir,
+					      file_name, &tree_name);
+		if (IS_ERR(name)) {
+			if (PTR_ERR(name) == -ENOMEM)
+				pr_err("Failed to allocate tree notify event name\n");
+			return 0;
+		}
+		file_name = &tree_name;
+	}
 
-	return ksmbd_notify_handle_inode_event(notify, mask, inode, dir,
+	inode = fsnotify_data_inode(data, data_type);
+	err = ksmbd_notify_handle_inode_event(notify, mask, inode, dir,
 					      file_name, cookie);
+	kfree(name);
+	return err;
 }
 
 static void ksmbd_notify_free_mark(struct fsnotify_mark *mark)
@@ -149,6 +266,10 @@ ksmbd_notify_add_mark(struct ksmbd_notify *notify, u32 mask, void *obj,
 
 static void ksmbd_notify_destroy_marks(struct ksmbd_notify *notify)
 {
+	if (notify->tree_mark) {
+		fsnotify_destroy_mark(notify->tree_mark, notify->group);
+		fsnotify_put_mark(notify->tree_mark);
+	}
 	if (notify->mark) {
 		fsnotify_destroy_mark(notify->mark, notify->group);
 		fsnotify_put_mark(notify->mark);
@@ -158,10 +279,11 @@ static void ksmbd_notify_destroy_marks(struct ksmbd_notify *notify)
 }
 
 static int ksmbd_notify_add(struct ksmbd_file *fp, u32 mask, u32 filter,
+			    bool watch_tree,
 			    struct ksmbd_notify **notify_out)
 {
 	struct ksmbd_notify *notify;
-	struct fsnotify_mark *mark;
+	struct fsnotify_mark *mark, *tree_mark;
 	int err = 0;
 
 	notify = kzalloc_obj(*notify, KSMBD_DEFAULT_GFP);
@@ -175,6 +297,7 @@ static int ksmbd_notify_add(struct ksmbd_file *fp, u32 mask, u32 filter,
 	spin_lock_init(&notify->lock);
 	notify->filter = filter;
 	notify->mask = mask;
+	notify->watch_tree = watch_tree;
 
 	notify->group = fsnotify_alloc_group(&ksmbd_notify_fsnotify_ops, 0);
 	if (IS_ERR(notify->group)) {
@@ -193,11 +316,27 @@ static int ksmbd_notify_add(struct ksmbd_file *fp, u32 mask, u32 filter,
 	}
 	notify->mark = mark;
 
+	if (watch_tree) {
+		/*
+		 * FS_EVENT_ON_CHILD covers only one level. A filesystem mark
+		 * supplies recursive events; the callback limits them to the
+		 * directory rooted at fp.
+		 */
+		tree_mark = ksmbd_notify_add_mark(notify, mask,
+						  file_inode(fp->filp)->i_sb,
+						  FSNOTIFY_OBJ_TYPE_SB);
+		if (IS_ERR(tree_mark)) {
+			err = PTR_ERR(tree_mark);
+			goto err_destroy_marks;
+		}
+		notify->tree_mark = tree_mark;
+	}
+
 	*notify_out = notify;
 	ksmbd_debug(NOTIFY,
-		    "Added fsnotify mark, inode %llu, mask 0x%x, filter 0x%x\n",
+		    "Added fsnotify mark, inode %llu, mask 0x%x, filter 0x%x, watch tree %d\n",
 		    (unsigned long long)file_inode(fp->filp)->i_ino, mark->mask,
-		    filter);
+		    filter, watch_tree);
 	goto out;
 
 err_destroy_marks:
@@ -292,7 +431,9 @@ ksmbd_notify_setup_watch(struct ksmbd_file *fp,
 		ksmbd_debug(NOTIFY,
 			    "No mapped completion filter bits; request will remain pending\n");
 
-	err = ksmbd_notify_add(fp, mask, filter, &notify);
+	err = ksmbd_notify_add(fp, mask, filter,
+			       le16_to_cpu(req->Flags) & SMB2_WATCH_TREE,
+			       &notify);
 	if (err) {
 		pr_err("Failed to add notify watch, fid %llu:%llu: %d\n",
 		       fp->persistent_id, fp->volatile_id, err);
fs/smb/server/notify.h +2 -0
index 185ce93b01cc..e899a0ed5721 100644
@@ -22,11 +22,13 @@ struct smb2_change_notify_rsp;
 struct ksmbd_notify {
 	struct fsnotify_group *group;
 	struct fsnotify_mark *mark;
+	struct fsnotify_mark *tree_mark;
 	struct ksmbd_file *fp;
 	/* Protects filter, rename state and the queued events. */
 	spinlock_t lock;
 	u32 filter;
 	u32 mask;
+	bool watch_tree;
 };
 
 struct ksmbd_notify_req {
Signature · 1 line
2.55.0
author reviewer
#7 lore raw

PATCH v2 6/13 smb/server: keep notify watches on file handles

In reply to ChenXiaoSong

From: ChenXiaoSong <[email protected]>

Keep one notify watch on each file handle. Reuse it for later requests, and remove it when the handle is closed.

---
 fs/smb/server/notify.c    | 44 +++++++++++++++++++++++++++++++++++----
 fs/smb/server/notify.h    |  2 ++
 fs/smb/server/vfs_cache.c |  3 +++
 fs/smb/server/vfs_cache.h |  4 ++++
 4 files changed, 49 insertions(+), 4 deletions(-)
fs/smb/server/notify.c +40 -4
index a9175b864e19..1d5301a7f9ea 100644
@@ -286,6 +286,18 @@ static int ksmbd_notify_add(struct ksmbd_file *fp, u32 mask, u32 filter,
 	struct fsnotify_mark *mark, *tree_mark;
 	int err = 0;
 
+	mutex_lock(&fp->notify_lock);
+	if (fp->notify) {
+		/* Further requests on this open use the first request's options. */
+		ksmbd_debug(NOTIFY,
+			    "Reusing fsnotify mark, inode %llu, mask 0x%x, filter 0x%x, watch tree %d\n",
+			    (unsigned long long)file_inode(fp->filp)->i_ino,
+			    fp->notify->mark->mask, fp->notify->filter,
+			    fp->notify->watch_tree);
+		*notify_out = fp->notify;
+		goto out;
+	}
+
 	notify = kzalloc_obj(*notify, KSMBD_DEFAULT_GFP);
 	if (!notify) {
 		pr_err("Failed to allocate notify watch\n");
@@ -332,6 +344,7 @@ static int ksmbd_notify_add(struct ksmbd_file *fp, u32 mask, u32 filter,
 		notify->tree_mark = tree_mark;
 	}
 
+	fp->notify = notify;
 	*notify_out = notify;
 	ksmbd_debug(NOTIFY,
 		    "Added fsnotify mark, inode %llu, mask 0x%x, filter 0x%x, watch tree %d\n",
@@ -344,9 +357,36 @@ static int ksmbd_notify_add(struct ksmbd_file *fp, u32 mask, u32 filter,
 	kfree(notify);
 
 out:
+	mutex_unlock(&fp->notify_lock);
 	return err;
 }
 
+/**
+ * ksmbd_notify_remove() - remove the notify watch for a closing handle
+ * @fp: file handle whose watch is being removed
+ *
+ * A cancelled CHANGE_NOTIFY request leaves this watch installed. The watch is
+ * owned by @fp and removed only when the file handle is finally closed.
+ */
+void ksmbd_notify_remove(struct ksmbd_file *fp)
+{
+	struct ksmbd_notify *notify;
+
+	mutex_lock(&fp->notify_lock);
+	notify = fp->notify;
+	fp->notify = NULL;
+	mutex_unlock(&fp->notify_lock);
+	if (!notify)
+		return;
+
+	ksmbd_debug(NOTIFY,
+		    "Removing fsnotify mark, inode %llu, mask 0x%x, watch tree %d\n",
+		    (unsigned long long)file_inode(fp->filp)->i_ino,
+		    notify->mark->mask, notify->watch_tree);
+	ksmbd_notify_destroy_marks(notify);
+	kfree(notify);
+}
+
 static struct ksmbd_file *
 ksmbd_notify_validate_req(struct ksmbd_work *work,
 			  struct smb2_change_notify_req *req,
@@ -568,10 +608,6 @@ int ksmbd_handle_notify(struct ksmbd_work *work,
 		release_async_work(work);
 	else
 		kfree(argv);
-	if (notify) {
-		ksmbd_notify_destroy_marks(notify);
-		kfree(notify);
-	}
 	if (fp)
 		ksmbd_fd_put(work, fp);
 	return err;
fs/smb/server/notify.h +2 -0
index e899a0ed5721..ace9afc022b7 100644
@@ -16,6 +16,7 @@
 #include <linux/fsnotify_backend.h>
 
 struct ksmbd_work;
+struct ksmbd_file;
 struct smb2_change_notify_req;
 struct smb2_change_notify_rsp;
 
@@ -41,5 +42,6 @@ struct ksmbd_notify_req {
 int ksmbd_handle_notify(struct ksmbd_work *work,
 			struct smb2_change_notify_req *req,
 			struct smb2_change_notify_rsp *rsp);
+void ksmbd_notify_remove(struct ksmbd_file *fp);
 
 #endif /* __SMB_SERVER_NOTIFY_H__ */
fs/smb/server/vfs_cache.c +3 -0
index 7a0f13277ec0..e4922c1731b2 100644
@@ -20,6 +20,7 @@
 #include "vfs.h"
 #include "connection.h"
 #include "misc.h"
+#include "notify.h"
 #include "mgmt/tree_connect.h"
 #include "mgmt/user_session.h"
 #include "mgmt/user_config.h"
@@ -914,6 +915,7 @@ static void __ksmbd_close_fd(struct ksmbd_file_table *ft, struct ksmbd_file *fp)
 
 	/* Remove lookup entries before dropping the file's inode reference. */
 	ksmbd_file_lock_clear(fp);
+	ksmbd_notify_remove(fp);
 	__ksmbd_inode_close(fp);
 	if (!IS_ERR_OR_NULL(filp))
 		fput(filp);
@@ -1491,6 +1493,7 @@ struct ksmbd_file *ksmbd_open_fd(struct ksmbd_work *work, struct file *filp)
 	INIT_LIST_HEAD(&fp->node);
 	INIT_LIST_HEAD(&fp->lock_list);
 	spin_lock_init(&fp->f_lock);
+	mutex_init(&fp->notify_lock);
 	mutex_init(&fp->readdir_lock);
 	atomic_set(&fp->refcount, 1);
 
fs/smb/server/vfs_cache.h +4 -0
index c00d92fdf94a..25721c257791 100644
@@ -34,6 +34,7 @@
 #define SMB2_NO_FID		(0xFFFFFFFFFFFFFFFFULL)
 
 struct ksmbd_conn;
+struct ksmbd_notify;
 struct ksmbd_session;
 struct ksmbd_file;
 
@@ -108,6 +109,9 @@ struct ksmbd_file {
 	u64				durable_volatile_id;
 
 	spinlock_t			f_lock;
+	/* Protects notify watch creation and removal. */
+	struct mutex			notify_lock;
+	struct ksmbd_notify		*notify;
 
 	struct ksmbd_inode		*f_ci;
 	struct ksmbd_inode		*f_parent_ci;
Signature · 1 line
2.55.0
author reviewer
#8 lore raw

PATCH v2 7/13 smb/server: save simple notify events

In reply to ChenXiaoSong

From: ChenXiaoSong <[email protected]>

Save create, delete, and change events.

Example:

1. client: smbinfo notify /mnt
2. server: ksmbd.control --debug=notify
3. server: touch /export/file
server debug log:
ksmbd: Queueing notify event, action 1, name file
ksmbd: Queueing notify event, action 3, name file
4. server: rm /export/file
server debug log:
ksmbd: Queueing notify event, action 2, name file

---
 fs/smb/server/notify.c | 182 ++++++++++++++++++++++++++++++++++++++++-
 fs/smb/server/notify.h |  16 ++++
 2 files changed, 197 insertions(+), 1 deletion(-)
fs/smb/server/notify.c +181 -1
index 1d5301a7f9ea..a3ed26e1b631 100644
@@ -12,6 +12,8 @@
 
 #include <linux/fsnotify_backend.h>
 #include <linux/dcache.h>
+#include <linux/sizes.h>
+#include <linux/slab.h>
 #include "glob.h"
 #include "../common/smb2status.h"
 #include "connection.h"
@@ -22,6 +24,9 @@
 #include "vfs_cache.h"
 #include "mgmt/user_session.h"
 
+#define KSMBD_NOTIFY_EVENT_MASK		(FS_ACCESS | FS_ATTRIB | FS_MODIFY | \
+					 KSMBD_NOTIFY_NAME_EVENT_MASK)
+
 static const struct {
 	u32 notify_mask;
 	u32 fsnotify_mask;
@@ -56,6 +61,69 @@ static u32 ksmbd_notify_map(u32 filter)
 	return mask;
 }
 
+static void ksmbd_notify_free_event(struct ksmbd_notify *notify,
+				    struct ksmbd_notify_event *event)
+{
+	size_t alloc_size;
+
+	if (!event)
+		return;
+	alloc_size = event->alloc_size;
+	kfree(event);
+	spin_lock(&notify->lock);
+	notify->event_bytes -= alloc_size;
+	spin_unlock(&notify->lock);
+}
+
+static void ksmbd_notify_free_events(struct ksmbd_notify *notify,
+				     struct list_head *events)
+{
+	struct ksmbd_notify_event *event, *tmp;
+
+	list_for_each_entry_safe(event, tmp, events, list) {
+		list_del(&event->list);
+		ksmbd_notify_free_event(notify, event);
+	}
+}
+
+/* The caller holds notify->lock. Keep charges until the events are freed. */
+static void ksmbd_notify_discard_events(struct ksmbd_notify *notify,
+					struct list_head *discard)
+{
+	list_splice_tail_init(&notify->events, discard);
+	notify->num_events = 0;
+}
+
+static void ksmbd_notify_set_overflow(struct ksmbd_notify *notify)
+{
+	LIST_HEAD(discard);
+
+	spin_lock(&notify->lock);
+	notify->overflow = true;
+	ksmbd_notify_discard_events(notify, &discard);
+	spin_unlock(&notify->lock);
+
+	ksmbd_notify_free_events(notify, &discard);
+}
+
+static bool ksmbd_notify_filter_match(struct ksmbd_notify *notify, u32 mask)
+{
+	u32 filter, notify_mask;
+
+	spin_lock(&notify->lock);
+	filter = notify->filter;
+	notify_mask = notify->mask;
+	spin_unlock(&notify->lock);
+
+	if (mask & KSMBD_NOTIFY_NAME_EVENT_MASK) {
+		if (mask & FS_ISDIR)
+			return filter & FILE_NOTIFY_CHANGE_DIR_NAME;
+		return filter & FILE_NOTIFY_CHANGE_FILE_NAME;
+	}
+
+	return mask & notify_mask;
+}
+
 /*
  * Cancel handler for a pending CHANGE_NOTIFY. Called either by
  * smb2_cancel() (conn->request_lock held, work->state already set to
@@ -75,14 +143,86 @@ static void smb2_notify_cancel(void **argv)
 	wake_up(&notify_req->wait);
 }
 
+static struct ksmbd_notify_event *
+ksmbd_notify_alloc_event(struct ksmbd_notify *notify, u32 action,
+			 const struct qstr *file_name, gfp_t gfp)
+{
+	struct ksmbd_notify_event *event;
+	size_t name_len = file_name ? file_name->len : 0;
+	size_t alloc_size;
+
+	if (name_len > KSMBD_NOTIFY_MAX_BYTES - sizeof(*event) - 1)
+		goto overflow;
+	alloc_size = kmalloc_size_roundup(sizeof(*event) + name_len + 1);
+
+	/* Reserve before allocating so concurrent callbacks share one budget. */
+	spin_lock(&notify->lock);
+	if (notify->overflow) {
+		spin_unlock(&notify->lock);
+		return NULL;
+	}
+	if (alloc_size > KSMBD_NOTIFY_MAX_BYTES - notify->event_bytes) {
+		spin_unlock(&notify->lock);
+		goto overflow;
+	}
+	notify->event_bytes += alloc_size;
+	spin_unlock(&notify->lock);
+
+	event = kmalloc(alloc_size, gfp);
+	if (!event) {
+		pr_err("Failed to allocate notify event, action %u, name %.*s\n",
+		       action, file_name ? file_name->len : 0,
+		       file_name ? (const char *)file_name->name : "");
+		spin_lock(&notify->lock);
+		notify->event_bytes -= alloc_size;
+		spin_unlock(&notify->lock);
+		goto overflow;
+	}
+
+	INIT_LIST_HEAD(&event->list);
+	event->action = action;
+	event->when = ktime_get_ns();
+	event->name_len = name_len;
+	event->alloc_size = alloc_size;
+	if (name_len)
+		memcpy(event->name, file_name->name, name_len);
+	event->name[name_len] = '\0';
+
+	return event;
+
+overflow:
+	ksmbd_notify_set_overflow(notify);
+	return NULL;
+}
+
+static void
+ksmbd_notify_queue_event(struct ksmbd_notify *notify,
+			 struct ksmbd_notify_event *event)
+{
+	ksmbd_debug(NOTIFY, "Queueing notify event, action %u, name %s\n",
+		    event->action, event->name);
+
+	spin_lock(&notify->lock);
+	if (notify->overflow) {
+		spin_unlock(&notify->lock);
+		ksmbd_notify_free_event(notify, event);
+		return;
+	}
+	list_add_tail(&event->list, &notify->events);
+	notify->num_events++;
+	spin_unlock(&notify->lock);
+}
+
 static int ksmbd_notify_handle_inode_event(struct ksmbd_notify *notify,
 					   u32 mask, struct inode *inode,
 					   struct inode *dir,
 					   const struct qstr *file_name,
 					   u32 cookie)
 {
+	struct ksmbd_notify_event *event;
 	struct inode *event_inode = dir ?: inode;
 	struct ksmbd_file *fp;
+	u32 action;
 
 	fp = notify->fp;
 
@@ -93,6 +233,30 @@ static int ksmbd_notify_handle_inode_event(struct ksmbd_notify *notify,
 		    file_name ? file_name->len : 0,
 		    file_name ? (const char *)file_name->name : "", cookie);
 
+	if (!(mask & KSMBD_NOTIFY_EVENT_MASK)) {
+		ksmbd_debug(NOTIFY, "Ignored notify event mask 0x%x\n", mask);
+		return 0;
+	}
+
+	/* Only matching changes may consume the budget or signal overflow. */
+	if (!ksmbd_notify_filter_match(notify, mask))
+		return 0;
+
+	if (mask & FS_CREATE) {
+		action = FILE_ACTION_ADDED;
+	} else if (mask & FS_DELETE) {
+		action = FILE_ACTION_REMOVED;
+	} else {
+		action = FILE_ACTION_MODIFIED;
+	}
+
+	event = ksmbd_notify_alloc_event(notify, action, file_name,
+					 KSMBD_DEFAULT_GFP);
+	if (!event)
+		return 0;
+
+	ksmbd_notify_queue_event(notify, event);
+
 	return 0;
 }
 
@@ -202,6 +366,21 @@ static int ksmbd_notify_handle_event(struct fsnotify_group *group, u32 mask,
 	char *name = NULL;
 	int err;
 
+	/*
+	 * fsnotify_access() reports reads and directory enumeration as path
+	 * events, even when atime is unchanged. Keep the dentry-based FS_ACCESS
+	 * events from fsnotify_change() for explicit atime updates.
+	 */
+	if (data_type == FSNOTIFY_EVENT_PATH)
+		mask &= ~FS_ACCESS;
+	if (!(mask & KSMBD_NOTIFY_EVENT_MASK))
+		return 0;
+
+	inode = fsnotify_data_inode(data, data_type);
+	/* CHANGE_NOTIFY reports changes below the watched directory. */
+	if (inode == file_inode(notify->fp->filp))
+		return 0;
+
 	if (!READ_ONCE(notify->watch_tree)) {
 		/* Non-tree watches accept events from the root inode mark only. */
 		if (!fsnotify_iter_inode_mark(iter_info) &&
@@ -218,7 +397,6 @@ static int ksmbd_notify_handle_event(struct fsnotify_group *group, u32 mask,
 		file_name = &tree_name;
 	}
 
-	inode = fsnotify_data_inode(data, data_type);
 	err = ksmbd_notify_handle_inode_event(notify, mask, inode, dir,
 					      file_name, cookie);
 	kfree(name);
@@ -307,6 +485,7 @@ static int ksmbd_notify_add(struct ksmbd_file *fp, u32 mask, u32 filter,
 
 	notify->fp = fp;
 	spin_lock_init(&notify->lock);
+	INIT_LIST_HEAD(&notify->events);
 	notify->filter = filter;
 	notify->mask = mask;
 	notify->watch_tree = watch_tree;
@@ -384,6 +563,7 @@ void ksmbd_notify_remove(struct ksmbd_file *fp)
 		    (unsigned long long)file_inode(fp->filp)->i_ino,
 		    notify->mark->mask, notify->watch_tree);
 	ksmbd_notify_destroy_marks(notify);
+	ksmbd_notify_free_events(notify, &notify->events);
 	kfree(notify);
 }
 
fs/smb/server/notify.h +16 -0
index ace9afc022b7..a80775bd1163 100644
@@ -14,12 +14,22 @@
 #define __SMB_SERVER_NOTIFY_H__
 
 #include <linux/fsnotify_backend.h>
+#include <linux/sizes.h>
 
 struct ksmbd_work;
 struct ksmbd_file;
 struct smb2_change_notify_req;
 struct smb2_change_notify_rsp;
 
+struct ksmbd_notify_event {
+	struct list_head list;
+	u32 action;
+	u64 when;
+	size_t name_len;
+	size_t alloc_size;
+	char name[];
+};
+
 struct ksmbd_notify {
 	struct fsnotify_group *group;
 	struct fsnotify_mark *mark;
@@ -27,6 +37,11 @@ struct ksmbd_notify {
 	struct ksmbd_file *fp;
 	/* Protects filter, rename state and the queued events. */
 	spinlock_t lock;
+	struct list_head events;
+	unsigned int num_events;
+	/* Includes reservations, rename state and events owned by requests. */
+	size_t event_bytes;
+	bool overflow;
 	u32 filter;
 	u32 mask;
 	bool watch_tree;
@@ -36,6 +51,7 @@ struct ksmbd_notify_req {
 	wait_queue_head_t wait;
 };
 
+#define KSMBD_NOTIFY_MAX_BYTES		SZ_64K
 #define KSMBD_NOTIFY_NAME_EVENT_MASK	(FS_CREATE | FS_DELETE | \
 					 FS_MOVED_FROM | FS_MOVED_TO)
 
Signature · 1 line
2.55.0
author reviewer
#9 lore raw

PATCH v2 8/13 smb/server: save old names for rename notify events

In reply to ChenXiaoSong

From: ChenXiaoSong <[email protected]>

Save the old name from FS_MOVED_FROM events for matching with a subsequent FS_MOVED_TO event. Queue unmatched events as removals after a short delay.

Example:

1. client: smbinfo notify /mnt
2. server: ksmbd.control --debug=notify
3. server: mkdir /export/dir/; touch /export/file
4. server: mv /export/file /export/dir/

     server debug log:
       [40622.865858] ksmbd: Saved moved from, mask 0x40, name file, cookie 1134
       [40622.975906] ksmbd: Queue moved from as removed, name file
---
 fs/smb/server/notify.c | 83 ++++++++++++++++++++++++++++++++++++++++++
 fs/smb/server/notify.h |  5 +++
 2 files changed, 88 insertions(+)
fs/smb/server/notify.c +83 -0
index a3ed26e1b631..77cb58ba950f 100644
@@ -24,6 +24,7 @@
 #include "vfs_cache.h"
 #include "mgmt/user_session.h"
 
+#define KSMBD_NOTIFY_MOVED_FROM_MSECS	100
 #define KSMBD_NOTIFY_EVENT_MASK		(FS_ACCESS | FS_ATTRIB | FS_MODIFY | \
 					 KSMBD_NOTIFY_NAME_EVENT_MASK)
 
@@ -92,6 +93,12 @@ static void ksmbd_notify_discard_events(struct ksmbd_notify *notify,
 {
 	list_splice_tail_init(&notify->events, discard);
 	notify->num_events = 0;
+	if (notify->moved_from_event) {
+		list_add_tail(&notify->moved_from_event->list, discard);
+		notify->moved_from_event = NULL;
+	}
+	notify->moved_from_mask = 0;
+	notify->moved_from_cookie = 0;
 }
 
 static void ksmbd_notify_set_overflow(struct ksmbd_notify *notify)
@@ -213,6 +220,70 @@ ksmbd_notify_queue_event(struct ksmbd_notify *notify,
 	spin_unlock(&notify->lock);
 }
 
+static void
+ksmbd_notify_trigger_removed(struct ksmbd_notify *notify,
+			     struct ksmbd_notify_event *event)
+{
+	ksmbd_debug(NOTIFY,
+		    "Queue moved from as removed, name %s\n",
+		    event->name);
+	event->action = FILE_ACTION_REMOVED;
+	event->when = ktime_get_ns();
+	ksmbd_notify_queue_event(notify, event);
+}
+
+static void ksmbd_notify_moved_from_timeout(struct work_struct *work)
+{
+	struct ksmbd_notify_event *event;
+	struct ksmbd_notify *notify;
+
+	notify = container_of(to_delayed_work(work), struct ksmbd_notify,
+			      moved_from_work);
+
+	spin_lock(&notify->lock);
+	event = notify->moved_from_event;
+	notify->moved_from_event = NULL;
+	spin_unlock(&notify->lock);
+
+	if (!event)
+		return;
+	ksmbd_notify_trigger_removed(notify, event);
+}
+
+static void ksmbd_notify_save_moved_from(struct ksmbd_notify *notify,
+					 u32 mask, u32 cookie,
+					 const struct qstr *file_name)
+{
+	struct ksmbd_notify_event *event, *old_event;
+
+	event = ksmbd_notify_alloc_event(notify, FILE_ACTION_RENAMED_OLD_NAME,
+					 file_name, KSMBD_DEFAULT_GFP);
+	if (!event)
+		return;
+
+	spin_lock(&notify->lock);
+	if (notify->overflow) {
+		spin_unlock(&notify->lock);
+		ksmbd_notify_free_event(notify, event);
+		return;
+	}
+	old_event = notify->moved_from_event;
+	notify->moved_from_event = event;
+	notify->moved_from_mask = mask;
+	notify->moved_from_cookie = cookie;
+	spin_unlock(&notify->lock);
+
+	ksmbd_debug(NOTIFY,
+		    "Saved moved from, mask 0x%x, name %.*s, cookie %u\n",
+		    mask, file_name ? file_name->len : 0,
+		    file_name ? (const char *)file_name->name : "", cookie);
+	if (old_event)
+		ksmbd_notify_trigger_removed(notify, old_event);
+
+	mod_delayed_work(system_dfl_wq, &notify->moved_from_work,
+			 msecs_to_jiffies(KSMBD_NOTIFY_MOVED_FROM_MSECS));
+}
+
 static int ksmbd_notify_handle_inode_event(struct ksmbd_notify *notify,
 					   u32 mask, struct inode *inode,
 					   struct inode *dir,
@@ -242,6 +313,14 @@ static int ksmbd_notify_handle_inode_event(struct ksmbd_notify *notify,
 	if (!ksmbd_notify_filter_match(notify, mask))
 		return 0;
 
+	if (mask & FS_MOVED_FROM) {
+		ksmbd_notify_save_moved_from(notify, mask, cookie, file_name);
+		return 0;
+	}
+
+	if (mask & FS_MOVED_TO)
+		return 0;
+
 	if (mask & FS_CREATE) {
 		action = FILE_ACTION_ADDED;
 	} else if (mask & FS_DELETE) {
@@ -489,6 +568,8 @@ static int ksmbd_notify_add(struct ksmbd_file *fp, u32 mask, u32 filter,
 	notify->filter = filter;
 	notify->mask = mask;
 	notify->watch_tree = watch_tree;
+	INIT_DELAYED_WORK(&notify->moved_from_work,
+			  ksmbd_notify_moved_from_timeout);
 
 	notify->group = fsnotify_alloc_group(&ksmbd_notify_fsnotify_ops, 0);
 	if (IS_ERR(notify->group)) {
@@ -563,6 +644,8 @@ void ksmbd_notify_remove(struct ksmbd_file *fp)
 		    (unsigned long long)file_inode(fp->filp)->i_ino,
 		    notify->mark->mask, notify->watch_tree);
 	ksmbd_notify_destroy_marks(notify);
+	cancel_delayed_work_sync(&notify->moved_from_work);
+	ksmbd_notify_free_event(notify, notify->moved_from_event);
 	ksmbd_notify_free_events(notify, &notify->events);
 	kfree(notify);
 }
fs/smb/server/notify.h +5 -0
index a80775bd1163..d6da2e45cfcc 100644
@@ -15,6 +15,7 @@
 
 #include <linux/fsnotify_backend.h>
 #include <linux/sizes.h>
+#include <linux/workqueue.h>
 
 struct ksmbd_work;
 struct ksmbd_file;
@@ -45,6 +46,10 @@ struct ksmbd_notify {
 	u32 filter;
 	u32 mask;
 	bool watch_tree;
+	struct ksmbd_notify_event *moved_from_event;
+	u32 moved_from_mask;
+	u32 moved_from_cookie;
+	struct delayed_work moved_from_work;
 };
 
 struct ksmbd_notify_req {
Signature · 1 line
2.55.0
author reviewer
#10 lore raw

PATCH v2 9/13 smb/server: match rename notify events

In reply to ChenXiaoSong

From: ChenXiaoSong <[email protected]>

Match old and new rename names by cookie. Save both names as events.

Example:

1. client: smbinfo notify /mnt
2. server: ksmbd.control --debug=notify
3. server: touch /export/file1
4. server: mv /export/file1 /export/file2

     server debug log:
       ksmbd: fid 5:5, notify event: mask=0x00000040 inode=2 name=file1 cookie=974
       ksmbd: Saved moved from, mask 0x40, name file1, cookie 974
       ksmbd: fid 5:5, notify event: mask=0x00000080 inode=2 name=file2 cookie=974
       ksmbd: Matched rename file1 to file2, cookie 974
---
 fs/smb/server/notify.c | 98 +++++++++++++++++++++++++++++++++++++-----
 1 file changed, 88 insertions(+), 10 deletions(-)
fs/smb/server/notify.c +88 -10
index 77cb58ba950f..e4996730c679 100644
@@ -203,23 +203,40 @@ ksmbd_notify_alloc_event(struct ksmbd_notify *notify, u32 action,
 }
 
 static void
-ksmbd_notify_queue_event(struct ksmbd_notify *notify,
-			 struct ksmbd_notify_event *event)
+ksmbd_notify_queue_events(struct ksmbd_notify *notify,
+			  struct ksmbd_notify_event *event,
+			  struct ksmbd_notify_event *next)
 {
-	ksmbd_debug(NOTIFY, "Queueing notify event, action %u, name %s\n",
-		    event->action, event->name);
+	if (!event && !next)
+		return;
 
 	spin_lock(&notify->lock);
 	if (notify->overflow) {
 		spin_unlock(&notify->lock);
 		ksmbd_notify_free_event(notify, event);
+		ksmbd_notify_free_event(notify, next);
 		return;
 	}
-	list_add_tail(&event->list, &notify->events);
-	notify->num_events++;
+	if (event) {
+		list_add_tail(&event->list, &notify->events);
+		notify->num_events++;
+	}
+	if (next) {
+		list_add_tail(&next->list, &notify->events);
+		notify->num_events++;
+	}
 	spin_unlock(&notify->lock);
 }
 
+static void
+ksmbd_notify_queue_event(struct ksmbd_notify *notify,
+			 struct ksmbd_notify_event *event)
+{
+	ksmbd_debug(NOTIFY, "Queueing notify event, action %u, name %s\n",
+		    event->action, event->name);
+	ksmbd_notify_queue_events(notify, event, NULL);
+}
+
 static void
 ksmbd_notify_trigger_removed(struct ksmbd_notify *notify,
 			     struct ksmbd_notify_event *event)
@@ -284,6 +301,65 @@ static void ksmbd_notify_save_moved_from(struct ksmbd_notify *notify,
 			 msecs_to_jiffies(KSMBD_NOTIFY_MOVED_FROM_MSECS));
 }
 
+static bool
+ksmbd_notify_handle_rename(struct ksmbd_notify *notify, u32 mask,
+				 u32 cookie, const struct qstr *file_name)
+{
+	struct ksmbd_notify_event *from, *to;
+	u32 from_mask;
+
+	to = ksmbd_notify_alloc_event(notify, FILE_ACTION_RENAMED_NEW_NAME, file_name,
+				      KSMBD_DEFAULT_GFP);
+	if (!to)
+		return true;
+
+	spin_lock(&notify->lock);
+	if (!notify->moved_from_event ||
+	    notify->moved_from_cookie != cookie) {
+		spin_unlock(&notify->lock);
+		ksmbd_notify_free_event(notify, to);
+		ksmbd_debug(NOTIFY,
+			    "No rename source for destination %.*s, cookie %u\n",
+			    file_name ? file_name->len : 0,
+			    file_name ? (const char *)file_name->name : "",
+			    cookie);
+		return false;
+	}
+	from = notify->moved_from_event;
+	from_mask = notify->moved_from_mask;
+	notify->moved_from_event = NULL;
+	notify->moved_from_mask = 0;
+	notify->moved_from_cookie = 0;
+	cancel_delayed_work(&notify->moved_from_work);
+	spin_unlock(&notify->lock);
+
+	from->action = FILE_ACTION_RENAMED_OLD_NAME;
+	ksmbd_debug(NOTIFY, "Matched rename %.*s to %.*s, cookie %u\n",
+		    (int)from->name_len, from->name,
+		    file_name ? file_name->len : 0,
+		    file_name ? (const char *)file_name->name : "", cookie);
+
+	if (!ksmbd_notify_filter_match(notify, from_mask)) {
+		ksmbd_debug(NOTIFY, "Filtered rename source %.*s\n",
+			    (int)from->name_len, from->name);
+		ksmbd_notify_free_event(notify, from);
+		from = NULL;
+	}
+
+	if (!ksmbd_notify_filter_match(notify, mask)) {
+		ksmbd_debug(NOTIFY, "Filtered rename destination %.*s\n",
+			    file_name ? file_name->len : 0,
+			    file_name ? (const char *)file_name->name : "");
+		ksmbd_notify_free_event(notify, to);
+		to = NULL;
+	}
+
+	/* A waiter must not take only the first half of a rename pair. */
+	ksmbd_notify_queue_events(notify, from, to);
+
+	return true;
+}
+
 static int ksmbd_notify_handle_inode_event(struct ksmbd_notify *notify,
 					   u32 mask, struct inode *inode,
 					   struct inode *dir,
@@ -318,10 +394,12 @@ static int ksmbd_notify_handle_inode_event(struct ksmbd_notify *notify,
 		return 0;
 	}
 
-	if (mask & FS_MOVED_TO)
-		return 0;
-
-	if (mask & FS_CREATE) {
+	if (mask & FS_MOVED_TO) {
+		if (ksmbd_notify_handle_rename(notify, mask, cookie,
+					       file_name))
+			return 0;
+		action = FILE_ACTION_ADDED;
+	} else if (mask & FS_CREATE) {
 		action = FILE_ACTION_ADDED;
 	} else if (mask & FS_DELETE) {
 		action = FILE_ACTION_REMOVED;
Signature · 1 line
2.55.0
author reviewer
#11 lore raw

PATCH v2 10/13 smb/server: encode notify events

In reply to ChenXiaoSong

From: ChenXiaoSong <[email protected]>

Sort and merge events, then encode their names as UTF-16 records.

---
 fs/smb/server/notify.c | 106 +++++++++++++++++++++++++++++++++++++++++
 1 file changed, 106 insertions(+)
fs/smb/server/notify.c +106 -0
index e4996730c679..e93ce85cc3a4 100644
@@ -12,6 +12,7 @@
 
 #include <linux/fsnotify_backend.h>
 #include <linux/dcache.h>
+#include <linux/list_sort.h>
 #include <linux/sizes.h>
 #include <linux/slab.h>
 #include "glob.h"
@@ -728,6 +729,111 @@ void ksmbd_notify_remove(struct ksmbd_file *fp)
 	kfree(notify);
 }
 
+static int ksmbd_notify_event_cmp(void *priv, const struct list_head *a,
+				  const struct list_head *b)
+{
+	struct ksmbd_notify_event *event_a;
+	struct ksmbd_notify_event *event_b;
+
+	event_a = list_entry(a, struct ksmbd_notify_event, list);
+	event_b = list_entry(b, struct ksmbd_notify_event, list);
+
+	if (event_a->when < event_b->when)
+		return -1;
+	if (event_a->when > event_b->when)
+		return 1;
+	return 0;
+}
+
+static void *ksmbd_notify_encode_events(struct ksmbd_work *work,
+					struct list_head *events,
+					u32 max_len, size_t *data_len)
+{
+	struct ksmbd_notify_event *event;
+	u8 *data = NULL;
+	size_t len = 0;
+
+	list_sort(NULL, events, ksmbd_notify_event_cmp);
+
+	list_for_each_entry(event, events, list) {
+		struct file_notify_information *info;
+		struct ksmbd_notify_event *next;
+		size_t alloc_len, buf_len, name_buf_len, record_len;
+		bool last = list_is_last(&event->list, events);
+		__le16 *name;
+		u8 *new_data;
+		int name_len;
+
+		/* Coalesce adjacent, case-sensitive duplicate records. */
+		if (!last) {
+			next = list_next_entry(event, list);
+			if (event->action == next->action &&
+			    event->name_len == next->name_len &&
+			    !memcmp(event->name, next->name, event->name_len))
+				continue;
+		}
+
+		name_buf_len = (event->name_len + 1) * sizeof(__le16);
+		name = kmalloc(name_buf_len, KSMBD_DEFAULT_GFP);
+		if (!name) {
+			pr_err("Failed to allocate notify event name buffer\n");
+			goto fail;
+		}
+
+		name_len = smbConvertToUTF16(name, event->name,
+					     event->name_len,
+					     work->conn->local_nls, 0);
+		name_len *= sizeof(__le16);
+		record_len = sizeof(*info) + name_len;
+		alloc_len = ALIGN(record_len, 4);
+		if (alloc_len > SIZE_MAX - 7 ||
+		    len > SIZE_MAX - alloc_len - 7) {
+			pr_err("Notify event data length overflow\n");
+			kfree(name);
+			goto fail;
+		}
+
+		/*
+		 * Compound response finalization can extend the last iov to an
+		 * 8-byte boundary.  Keep that padding inside this allocation and
+		 * zeroed, while reporting only the protocol payload in data_len.
+		 */
+		buf_len = ALIGN(len + alloc_len, 8);
+		new_data = kvrealloc(data, buf_len, KSMBD_DEFAULT_GFP);
+		if (!new_data) {
+			pr_err("Failed to allocate notify event data, length %zu\n",
+			       buf_len);
+			kfree(name);
+			goto fail;
+		}
+		data = new_data;
+		memset(data + len, 0, buf_len - len);
+
+		info = (struct file_notify_information *)(data + len);
+		info->NextEntryOffset = last ? 0 : cpu_to_le32(alloc_len);
+		info->Action = cpu_to_le32(event->action);
+		info->FileNameLength = cpu_to_le32(name_len);
+		memcpy(info->FileName, name, name_len);
+		kfree(name);
+
+		len += alloc_len;
+		if (len > max_len) {
+			ksmbd_debug(NOTIFY,
+				    "Notify event data length %zu exceeds output buffer %u\n",
+				    len, max_len);
+			goto fail;
+		}
+	}
+
+	*data_len = len;
+	return data;
+
+fail:
+	kvfree(data);
+	*data_len = 0;
+	return NULL;
+}
+
 static struct ksmbd_file *
 ksmbd_notify_validate_req(struct ksmbd_work *work,
 			  struct smb2_change_notify_req *req,
Signature · 1 line
2.55.0
author reviewer
#12 lore raw

PATCH v2 11/13 smb/server: send notify events to the client

In reply to ChenXiaoSong

From: ChenXiaoSong <[email protected]>

Wake one pending request and send its saved events in the reply.

Example:

smbinfo notify /mnt

# server: touch /export/file1
Notifications received, returned data_len is 48
Action: 0x00000001, FileName: file1
Action: 0x00000003, FileName: file1

# server: mv /export/file1 /export/file2
Notifications received, returned data_len is 48
Action: 0x00000004, FileName: file1
Action: 0x00000005, FileName: file2

---
 fs/smb/server/notify.c | 208 ++++++++++++++++++++++++++++++++++++++++-
 fs/smb/server/notify.h |   5 +
 2 files changed, 210 insertions(+), 3 deletions(-)
fs/smb/server/notify.c +205 -3
index e93ce85cc3a4..7c8f36c0b951 100644
@@ -25,6 +25,8 @@
 #include "vfs_cache.h"
 #include "mgmt/user_session.h"
 
+#define KSMBD_NOTIFY_BROADCAST_MSECS	1000
+#define KSMBD_NOTIFY_BROADCAST_MAX_EVENTS	100
 #define KSMBD_NOTIFY_MOVED_FROM_MSECS	100
 #define KSMBD_NOTIFY_EVENT_MASK		(FS_ACCESS | FS_ATTRIB | FS_MODIFY | \
 					 KSMBD_NOTIFY_NAME_EVENT_MASK)
@@ -112,6 +114,7 @@ static void ksmbd_notify_set_overflow(struct ksmbd_notify *notify)
 	spin_unlock(&notify->lock);
 
 	ksmbd_notify_free_events(notify, &discard);
+	mod_delayed_work(system_dfl_long_wq, &notify->broadcast_work, 0);
 }
 
 static bool ksmbd_notify_filter_match(struct ksmbd_notify *notify, u32 mask)
@@ -208,6 +211,10 @@ ksmbd_notify_queue_events(struct ksmbd_notify *notify,
 			  struct ksmbd_notify_event *event,
 			  struct ksmbd_notify_event *next)
 {
+	unsigned long broadcast_delay = 0;
+	bool schedule_broadcast = false;
+	bool first;
+
 	if (!event && !next)
 		return;
 
@@ -218,6 +225,7 @@ ksmbd_notify_queue_events(struct ksmbd_notify *notify,
 		ksmbd_notify_free_event(notify, next);
 		return;
 	}
+	first = !notify->num_events;
 	if (event) {
 		list_add_tail(&event->list, &notify->events);
 		notify->num_events++;
@@ -226,7 +234,19 @@ ksmbd_notify_queue_events(struct ksmbd_notify *notify,
 		list_add_tail(&next->list, &notify->events);
 		notify->num_events++;
 	}
+	/* Start one timer per batch; reaching the limit flushes it early. */
+	if (first) {
+		broadcast_delay =
+			msecs_to_jiffies(KSMBD_NOTIFY_BROADCAST_MSECS);
+		schedule_broadcast = true;
+	} else if (notify->num_events >= KSMBD_NOTIFY_BROADCAST_MAX_EVENTS) {
+		schedule_broadcast = true;
+	}
 	spin_unlock(&notify->lock);
+
+	if (schedule_broadcast)
+		mod_delayed_work(system_dfl_long_wq, &notify->broadcast_work,
+				 broadcast_delay);
 }
 
 static void
@@ -361,6 +381,66 @@ ksmbd_notify_handle_rename(struct ksmbd_notify *notify, u32 mask,
 	return true;
 }
 
+/* The caller holds notify->lock; ownership changes do not release memory. */
+static void ksmbd_notify_transfer_events(struct ksmbd_notify *notify,
+					 struct ksmbd_notify_req *notify_req)
+{
+	list_splice_tail_init(&notify->events, &notify_req->events);
+	notify_req->num_events = notify->num_events;
+	notify_req->overflow = notify->overflow;
+	notify->num_events = 0;
+	notify->overflow = false;
+}
+
+/*
+ * Give queued events to the oldest pending notify request. The caller holds
+ * notify->lock so this lookup and transfer are atomic with synchronous takes.
+ */
+static bool ksmbd_notify_wake_waiter(struct ksmbd_notify *notify)
+{
+	struct ksmbd_notify_req *notify_req;
+	struct ksmbd_work *work;
+	bool found = false;
+
+	spin_lock(&notify->fp->f_lock);
+	list_for_each_entry(work, &notify->fp->blocked_works, fp_entry) {
+		if (READ_ONCE(work->state) != KSMBD_WORK_ACTIVE ||
+		    work->cancel_fn != smb2_notify_cancel ||
+		    !work->cancel_argv)
+			continue;
+
+		notify_req = work->cancel_argv[0];
+		if (READ_ONCE(notify_req->notified))
+			continue;
+
+		ksmbd_notify_transfer_events(notify, notify_req);
+		WRITE_ONCE(notify_req->notified, true);
+		wake_up(&notify_req->wait);
+		found = true;
+		break;
+	}
+	spin_unlock(&notify->fp->f_lock);
+
+	return found;
+}
+
+static void ksmbd_notify_broadcast(struct ksmbd_notify *notify)
+{
+	spin_lock(&notify->lock);
+	if (notify->overflow || !list_empty(&notify->events))
+		ksmbd_notify_wake_waiter(notify);
+	spin_unlock(&notify->lock);
+}
+
+static void ksmbd_notify_broadcast_work(struct work_struct *work)
+{
+	struct ksmbd_notify *notify;
+
+	notify = container_of(to_delayed_work(work), struct ksmbd_notify,
+			      broadcast_work);
+	ksmbd_notify_broadcast(notify);
+}
+
 static int ksmbd_notify_handle_inode_event(struct ksmbd_notify *notify,
 					   u32 mask, struct inode *inode,
 					   struct inode *dir,
@@ -649,6 +729,8 @@ static int ksmbd_notify_add(struct ksmbd_file *fp, u32 mask, u32 filter,
 	notify->watch_tree = watch_tree;
 	INIT_DELAYED_WORK(&notify->moved_from_work,
 			  ksmbd_notify_moved_from_timeout);
+	INIT_DELAYED_WORK(&notify->broadcast_work,
+			  ksmbd_notify_broadcast_work);
 
 	notify->group = fsnotify_alloc_group(&ksmbd_notify_fsnotify_ops, 0);
 	if (IS_ERR(notify->group)) {
@@ -724,11 +806,61 @@ void ksmbd_notify_remove(struct ksmbd_file *fp)
 		    notify->mark->mask, notify->watch_tree);
 	ksmbd_notify_destroy_marks(notify);
 	cancel_delayed_work_sync(&notify->moved_from_work);
+	cancel_delayed_work_sync(&notify->broadcast_work);
 	ksmbd_notify_free_event(notify, notify->moved_from_event);
 	ksmbd_notify_free_events(notify, &notify->events);
 	kfree(notify);
 }
 
+static bool
+ksmbd_notify_take_events(struct ksmbd_notify *notify,
+			 struct ksmbd_notify_req *notify_req)
+{
+	bool pending;
+
+	spin_lock(&notify->lock);
+	pending = notify->overflow || notify->num_events;
+	if (pending && ksmbd_notify_wake_waiter(notify))
+		pending = false;
+	else if (pending)
+		ksmbd_notify_transfer_events(notify, notify_req);
+	spin_unlock(&notify->lock);
+
+	if (pending)
+		ksmbd_debug(NOTIFY,
+			    "Take %u queued notify events, overflow %d, for synchronous reply\n",
+			    notify_req->num_events, notify_req->overflow);
+	return pending;
+}
+
+static void
+ksmbd_notify_requeue_events(struct ksmbd_notify *notify,
+			    struct ksmbd_notify_req *notify_req)
+{
+	LIST_HEAD(discard);
+
+	if (!notify_req->num_events && !notify_req->overflow)
+		return;
+
+	spin_lock(&notify->lock);
+	if (notify_req->overflow || notify->overflow) {
+		/* Cancellation must not consume an undelivered overflow. */
+		notify->overflow = true;
+		ksmbd_notify_discard_events(notify, &discard);
+		list_splice_tail_init(&notify_req->events, &discard);
+	} else {
+		/* These events are already charged to this open's budget. */
+		list_splice_init(&notify_req->events, &notify->events);
+		notify->num_events += notify_req->num_events;
+	}
+	notify_req->num_events = 0;
+	notify_req->overflow = false;
+	spin_unlock(&notify->lock);
+
+	ksmbd_notify_free_events(notify, &discard);
+	ksmbd_notify_broadcast(notify);
+}
+
 static int ksmbd_notify_event_cmp(void *priv, const struct list_head *a,
 				  const struct list_head *b)
 {
@@ -834,6 +966,52 @@ static void *ksmbd_notify_encode_events(struct ksmbd_work *work,
 	return NULL;
 }
 
+static int ksmbd_notify_reply(struct ksmbd_work *work,
+			      struct smb2_change_notify_req *req,
+			      struct smb2_change_notify_rsp *rsp,
+			      struct ksmbd_notify *notify,
+			      struct ksmbd_notify_req *notify_req)
+{
+	u32 max_len = le32_to_cpu(req->OutputBufferLength);
+	size_t data_len = 0;
+	void *data = NULL;
+	int err;
+
+	if (!notify_req->overflow)
+		data = ksmbd_notify_encode_events(work, &notify_req->events,
+						  max_len, &data_len);
+	ksmbd_notify_free_events(notify, &notify_req->events);
+	notify_req->num_events = 0;
+
+	/* Maps a successful zero-length notify reply to ENUM_DIR. */
+	if (!data_len) {
+		ksmbd_debug(NOTIFY,
+			    "Return notify enum directory, output buffer length %u\n",
+			    max_len);
+		rsp->hdr.Status = STATUS_NOTIFY_ENUM_DIR;
+		return 0;
+	}
+
+	rsp->StructureSize = cpu_to_le16(9);
+	rsp->OutputBufferOffset = cpu_to_le16(72);
+	rsp->OutputBufferLength = cpu_to_le32(data_len);
+	err = ksmbd_iov_pin_rsp_read(work, rsp,
+				     offsetof(struct smb2_change_notify_rsp, Buffer),
+				     data, data_len);
+	if (err) {
+		pr_err("Failed to pin notify response data, length %zu: %d\n",
+		       data_len, err);
+		kvfree(data);
+		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
+	} else {
+		ksmbd_debug(NOTIFY,
+			    "Prepared notify response, data length %zu\n",
+			    data_len);
+	}
+
+	return err;
+}
+
 static struct ksmbd_file *
 ksmbd_notify_validate_req(struct ksmbd_work *work,
 			  struct smb2_change_notify_req *req,
@@ -954,11 +1132,15 @@ static int ksmbd_notify_wait(struct ksmbd_work *work,
 	spin_unlock(&fp->f_lock);
 	read_unlock(&work->sess->file_table.lock);
 
+	/* Close the race between the synchronous check and queuing the waiter. */
+	ksmbd_notify_broadcast(notify);
+
 	ksmbd_debug(NOTIFY, "Notify request pending, async id %d\n",
 		    work->async_id);
 	smb2_send_interim_resp(work, STATUS_PENDING);
 
 	err = wait_event_interruptible(notify_req->wait,
+				       READ_ONCE(notify_req->notified) ||
 				       READ_ONCE(work->state) !=
 					       KSMBD_WORK_ACTIVE);
 	if (err && READ_ONCE(work->state) == KSMBD_WORK_ACTIVE) {
@@ -1012,6 +1194,13 @@ int ksmbd_handle_notify(struct ksmbd_work *work,
 		goto out;
 	}
 
+	/* Changes which arrived without a waiter are returned synchronously. */
+	INIT_LIST_HEAD(&notify_req.events);
+	if (ksmbd_notify_take_events(notify, &notify_req)) {
+		err = ksmbd_notify_reply(work, req, rsp, notify, &notify_req);
+		goto out;
+	}
+
 	argv = kmalloc_obj(*argv, KSMBD_DEFAULT_GFP);
 	if (!argv) {
 		pr_err("Failed to allocate notify cancel arguments\n");
@@ -1037,16 +1226,29 @@ int ksmbd_handle_notify(struct ksmbd_work *work,
 	}
 
 	if (work->state == KSMBD_WORK_CLOSED) {
+		ksmbd_notify_requeue_events(notify, &notify_req);
 		rsp->hdr.Status = STATUS_NOTIFY_CLEANUP;
 		ksmbd_debug(NOTIFY, "Notify handle closed, async id %d\n",
 			    work->async_id);
-	} else {
+		smb2_send_interim_resp(work, rsp->hdr.Status);
+		work->send_no_response = 1;
+	} else if (work->state == KSMBD_WORK_CANCELLED) {
+		ksmbd_notify_requeue_events(notify, &notify_req);
 		rsp->hdr.Status = STATUS_CANCELLED;
 		ksmbd_debug(NOTIFY, "Notify request cancelled, async id %d\n",
 			    work->async_id);
+		smb2_send_interim_resp(work, rsp->hdr.Status);
+		work->send_no_response = 1;
+	} else {
+		/* Complete the request using the AsyncId sent in STATUS_PENDING. */
+		rsp->hdr.Flags |= SMB2_FLAGS_ASYNC_COMMAND;
+		rsp->hdr.Id.AsyncId = cpu_to_le64(work->async_id);
+		err = ksmbd_notify_reply(work, req, rsp, notify, &notify_req);
+		if (!err)
+			ksmbd_debug(NOTIFY,
+				    "Completed notify request, async id %d\n",
+				    work->async_id);
 	}
-	smb2_send_interim_resp(work, rsp->hdr.Status);
-	work->send_no_response = 1;
 
 out:
 	if (rsp->hdr.Status != STATUS_SUCCESS && !work->send_no_response)
fs/smb/server/notify.h +5 -0
index d6da2e45cfcc..b7d8df4bef1d 100644
@@ -50,10 +50,15 @@ struct ksmbd_notify {
 	u32 moved_from_mask;
 	u32 moved_from_cookie;
 	struct delayed_work moved_from_work;
+	struct delayed_work broadcast_work;
 };
 
 struct ksmbd_notify_req {
 	wait_queue_head_t wait;
+	struct list_head events;
+	unsigned int num_events;
+	bool overflow;
+	bool notified;
 };
 
 #define KSMBD_NOTIFY_MAX_BYTES		SZ_64K
Signature · 1 line
2.55.0
author reviewer
#13 lore raw

PATCH v2 12/13 smb/server: break directory leases before sending notify events

In reply to ChenXiaoSong

From: ChenXiaoSong <[email protected]>

Reproducer:

1. ksmbd: ksmbd.conf:
[global]
smb2 leases = yes
2. ksmbd: systemctl start ksmbd
3. Windows 11 File Explorer:
Mount the share and enter the top-level directory of the mount point.
4. ksmbd: touch /export/file
5. Windows 11 File Explorer:
file does not appear in the top-level directory of the mount point.

Windows can keep directory data in a cache while it has a directory lease. A file change made on the server does not use the SMB request path, so the lease is not broken.

The server sends a notify event, but Windows may still use the old data. Some new files are then not shown in File Explorer.

---
 fs/smb/server/notify.c | 34 +++++++++++++++++++++++++++++++---
 fs/smb/server/oplock.c | 40 ++++++++++++++++++++++++++++++++++++++++
 fs/smb/server/oplock.h |  1 +
 3 files changed, 72 insertions(+), 3 deletions(-)
fs/smb/server/notify.c +31 -3
index 7c8f36c0b951..8db3fd59990a 100644
@@ -20,6 +20,7 @@
 #include "connection.h"
 #include "ksmbd_work.h"
 #include "notify.h"
+#include "oplock.h"
 #include "smb_common.h"
 #include "smb2pdu.h"
 #include "vfs_cache.h"
@@ -432,13 +433,34 @@ static void ksmbd_notify_broadcast(struct ksmbd_notify *notify)
 	spin_unlock(&notify->lock);
 }
 
+static bool ksmbd_notify_events_pending(struct ksmbd_notify *notify)
+{
+	bool pending;
+
+	spin_lock(&notify->lock);
+	pending = notify->overflow || !list_empty(&notify->events);
+	spin_unlock(&notify->lock);
+
+	return pending;
+}
+
+/* Invalidate directory caches before making the change visible to a client. */
+static void ksmbd_notify_dispatch(struct ksmbd_notify *notify)
+{
+	if (!ksmbd_notify_events_pending(notify))
+		return;
+
+	smb_break_dir_lease(notify->fp);
+	ksmbd_notify_broadcast(notify);
+}
+
 static void ksmbd_notify_broadcast_work(struct work_struct *work)
 {
 	struct ksmbd_notify *notify;
 
 	notify = container_of(to_delayed_work(work), struct ksmbd_notify,
 			      broadcast_work);
-	ksmbd_notify_broadcast(notify);
+	ksmbd_notify_dispatch(notify);
 }
 
 static int ksmbd_notify_handle_inode_event(struct ksmbd_notify *notify,
@@ -818,6 +840,12 @@ ksmbd_notify_take_events(struct ksmbd_notify *notify,
 {
 	bool pending;
 
+	if (!ksmbd_notify_events_pending(notify))
+		return false;
+
+	/* This path bypasses broadcast_work, so break directory leases here. */
+	smb_break_dir_lease(notify->fp);
+
 	spin_lock(&notify->lock);
 	pending = notify->overflow || notify->num_events;
 	if (pending && ksmbd_notify_wake_waiter(notify))
@@ -858,7 +886,7 @@ ksmbd_notify_requeue_events(struct ksmbd_notify *notify,
 	spin_unlock(&notify->lock);
 
 	ksmbd_notify_free_events(notify, &discard);
-	ksmbd_notify_broadcast(notify);
+	ksmbd_notify_dispatch(notify);
 }
 
 static int ksmbd_notify_event_cmp(void *priv, const struct list_head *a,
@@ -1133,7 +1161,7 @@ static int ksmbd_notify_wait(struct ksmbd_work *work,
 	read_unlock(&work->sess->file_table.lock);
 
 	/* Close the race between the synchronous check and queuing the waiter. */
-	ksmbd_notify_broadcast(notify);
+	ksmbd_notify_dispatch(notify);
 
 	ksmbd_debug(NOTIFY, "Notify request pending, async id %d\n",
 		    work->async_id);
fs/smb/server/oplock.c +40 -0
index d479508c06c5..9ded27df159f 100644
@@ -1794,6 +1794,46 @@ void smb_send_parent_lease_break_noti(struct ksmbd_file *fp,
 	ksmbd_inode_put(p_ci);
 }
 
+/**
+ * smb_break_dir_lease() - break leases when a directory changes
+ * @fp: open directory that changed
+ *
+ * Some directory changes do not go through the SMB request path. fsnotify
+ * reports these changes. Break the directory leases before sending the
+ * changes to the SMB client.
+ *
+ * This function can sleep while it waits for a reply from the client. Do not
+ * call it from the fsnotify callback.
+ */
+void smb_break_dir_lease(struct ksmbd_file *fp)
+{
+	struct ksmbd_inode *ci = fp->f_ci;
+	struct oplock_info *opinfo;
+	LIST_HEAD(brk_list);
+
+	down_read(&ci->m_lock);
+	list_for_each_entry(opinfo, &ci->m_op_list, op_entry) {
+		if (!opinfo->conn || !opinfo->is_lease ||
+		    !opinfo->o_lease->is_dir ||
+		    opinfo->o_lease->state == SMB2_LEASE_NONE_LE)
+			continue;
+
+		if (!atomic_inc_not_zero(&opinfo->refcount))
+			continue;
+
+		if (ksmbd_conn_releasing(opinfo->conn)) {
+			opinfo_put(opinfo);
+			continue;
+		}
+
+		if (oplock_break_add(&brk_list, opinfo))
+			opinfo_put(opinfo);
+	}
+	up_read(&ci->m_lock);
+
+	oplock_break_drain_none(&brk_list, ci);
+}
+
 void smb_lazy_parent_lease_break_close(struct ksmbd_file *fp)
 {
 	struct oplock_info *opinfo;
fs/smb/server/oplock.h +1 -0
index d81013c514e3..00da63b6ae7e 100644
@@ -130,6 +130,7 @@ int find_same_lease_key(struct ksmbd_conn *conn, struct ksmbd_inode *ci,
 void destroy_lease_table(void);
 void smb_send_parent_lease_break_noti(struct ksmbd_file *fp,
 				      struct lease_ctx_info *lctx);
+void smb_break_dir_lease(struct ksmbd_file *fp);
 void smb_lazy_parent_lease_break_close(struct ksmbd_file *fp);
 int smb2_check_durable_oplock(struct ksmbd_conn *conn,
 			      struct ksmbd_share_config *share,
Signature · 1 line
2.55.0
author reviewer
#14 lore raw

PATCH v2 13/13 smb/server: support change notify for named streams

In reply to ChenXiaoSong

From: ChenXiaoSong <[email protected]>

Example:

  mount -t cifs  -o nomapposix //${server_ip}/export /mnt
  smbinfo notify /mnt
  printf 'file data\n' > /mnt/file

printf 'named stream\n' > /mnt/file:stream Notifications received, returned data_len is 112
Action: 0x00000003, FileName: file
Action: 0x00000006, FileName: file:stream
Action: 0x00000003, FileName: file
Action: 0x00000008, FileName: file:stream

smbinfo filestreaminfo /mnt/file
Name: stream
Size: 13 bytes
Allocation size: 13 bytes
...

printf 'modify named stream\n' > /mnt/file:stream Notifications received, returned data_len is 56
Action: 0x00000003, FileName: file
Action: 0x00000008, FileName: file:stream

rm -- /mnt/file:stream
Notifications received, returned data_len is 56
Action: 0x00000003, FileName: file
Action: 0x00000007, FileName: file:stream

---
 fs/smb/server/notify.c | 126 ++++++++++++++++++++++++++++++++++++++++-
 fs/smb/server/notify.h |   7 +++
 fs/smb/server/vfs.c    |  67 +++++++++++++++++++---
 3 files changed, 192 insertions(+), 8 deletions(-)
fs/smb/server/notify.c +125 -1
index 8db3fd59990a..5d331c0866be 100644
@@ -24,6 +24,7 @@
 #include "smb_common.h"
 #include "smb2pdu.h"
 #include "vfs_cache.h"
+#include "xattr.h"
 #include "mgmt/user_session.h"
 
 #define KSMBD_NOTIFY_BROADCAST_MSECS	1000
@@ -32,6 +33,16 @@
 #define KSMBD_NOTIFY_EVENT_MASK		(FS_ACCESS | FS_ATTRIB | FS_MODIFY | \
 					 KSMBD_NOTIFY_NAME_EVENT_MASK)
 
+/* Protect the watch list and notify->fp during event delivery. */
+static DECLARE_RWSEM(ksmbd_notify_stream_lock);
+static LIST_HEAD(ksmbd_notify_stream_watches);
+
+/* Only a hint; list traversal still needs ksmbd_notify_stream_lock. */
+bool ksmbd_notify_has_stream_watches(void)
+{
+	return !list_empty(&ksmbd_notify_stream_watches);
+}
+
 static const struct {
 	u32 notify_mask;
 	u32 fsnotify_mask;
@@ -614,6 +625,109 @@ static char *ksmbd_notify_tree_name(struct ksmbd_notify *notify,
 	return name;
 }
 
+static void ksmbd_notify_stream_event(struct ksmbd_notify *notify,
+				      const struct path *path,
+				      const char *stream, size_t stream_len,
+				      u32 action, u32 filter)
+{
+	struct dentry *root = file_dentry(notify->fp->filp);
+	struct ksmbd_notify_event *event;
+	struct qstr file_name = {}, stream_name;
+	char *name, *full_name;
+
+	if (!(notify->filter & filter) || root->d_sb != path->dentry->d_sb ||
+	    d_inode(root) == d_inode(path->dentry))
+		return;
+
+	if (!notify->watch_tree) {
+		struct dentry *parent = dget_parent(path->dentry);
+		bool match = parent == root;
+
+		dput(parent);
+		if (!match)
+			return;
+	}
+
+	name = ksmbd_notify_tree_name(notify, path, FSNOTIFY_EVENT_PATH,
+				      NULL, NULL, &file_name);
+	if (IS_ERR(name)) {
+		if (PTR_ERR(name) != -EXDEV)
+			ksmbd_notify_set_overflow(notify);
+		return;
+	}
+	/* Unknown old size: cannot tell add from modify. */
+	if (!action) {
+		ksmbd_notify_set_overflow(notify);
+		goto out;
+	}
+
+	/* MS-FSA: relative file name + ':' + stream name. */
+	full_name = kasprintf(KSMBD_DEFAULT_GFP, "%s:%.*s", name,
+			      (int)stream_len, stream);
+	if (!full_name) {
+		ksmbd_notify_set_overflow(notify);
+		goto out;
+	}
+	stream_name.name = full_name;
+	stream_name.len = file_name.len + 1 + stream_len;
+	event = ksmbd_notify_alloc_event(notify, action, &stream_name,
+					 KSMBD_DEFAULT_GFP);
+	kfree(full_name);
+	if (event)
+		ksmbd_notify_queue_event(notify, event);
+out:
+	kfree(name);
+}
+
+/**
+ * ksmbd_notify_stream() - report a stream change
+ * @path: base file or directory
+ * @xattr_name: stream xattr name, including the type
+ * @old_size: old length, or -ENODATA for a new stream
+ * @new_size: new length, or -ENODATA for a deleted stream
+ *
+ * FS_ATTRIB has no xattr name or old size. Call this after a successful
+ * stream xattr change.
+ */
+void ksmbd_notify_stream(const struct path *path, const char *xattr_name,
+			 ssize_t old_size, ssize_t new_size)
+{
+	struct ksmbd_notify *notify;
+	const char *stream, *type;
+	u32 action, filter;
+
+	if (strncmp(xattr_name, XATTR_NAME_STREAM, XATTR_NAME_STREAM_LEN))
+		return;
+	stream = xattr_name + XATTR_NAME_STREAM_LEN;
+	type = strrchr(stream, ':');
+	if (!type || type == stream ||
+	    (strcasecmp(type, ":$DATA") &&
+	     strcasecmp(type, ":$INDEX_ALLOCATION")))
+		return;
+
+	if (new_size == -ENODATA) {
+		action = FILE_ACTION_REMOVED_STREAM;
+		filter = FILE_NOTIFY_CHANGE_STREAM_NAME;
+	} else if (old_size == -ENODATA) {
+		action = FILE_ACTION_ADDED_STREAM;
+		filter = FILE_NOTIFY_CHANGE_STREAM_NAME;
+	} else if (old_size < 0) {
+		action = 0;
+		filter = KSMBD_NOTIFY_STREAM_MASK;
+	} else {
+		action = FILE_ACTION_MODIFIED_STREAM;
+		filter = FILE_NOTIFY_CHANGE_STREAM_WRITE;
+		if (old_size != new_size)
+			filter |= FILE_NOTIFY_CHANGE_STREAM_SIZE;
+	}
+
+	down_read(&ksmbd_notify_stream_lock);
+	list_for_each_entry(notify, &ksmbd_notify_stream_watches, stream_list)
+		ksmbd_notify_stream_event(notify, path, stream, type - stream,
+					  action, filter);
+	up_read(&ksmbd_notify_stream_lock);
+}
+
 static int ksmbd_notify_handle_event(struct fsnotify_group *group, u32 mask,
 				     const void *data, int data_type,
 				     struct inode *dir,
@@ -744,6 +858,7 @@ static int ksmbd_notify_add(struct ksmbd_file *fp, u32 mask, u32 filter,
 	}
 
 	notify->fp = fp;
+	INIT_LIST_HEAD(&notify->stream_list);
 	spin_lock_init(&notify->lock);
 	INIT_LIST_HEAD(&notify->events);
 	notify->filter = filter;
@@ -787,6 +902,11 @@ static int ksmbd_notify_add(struct ksmbd_file *fp, u32 mask, u32 filter,
 		notify->tree_mark = tree_mark;
 	}
 
+	if (filter & KSMBD_NOTIFY_STREAM_MASK) {
+		down_write(&ksmbd_notify_stream_lock);
+		list_add_tail(&notify->stream_list, &ksmbd_notify_stream_watches);
+		up_write(&ksmbd_notify_stream_lock);
+	}
 	fp->notify = notify;
 	*notify_out = notify;
 	ksmbd_debug(NOTIFY,
@@ -822,6 +942,10 @@ void ksmbd_notify_remove(struct ksmbd_file *fp)
 	if (!notify)
 		return;
 
+	down_write(&ksmbd_notify_stream_lock);
+	list_del_init(&notify->stream_list);
+	up_write(&ksmbd_notify_stream_lock);
+
 	ksmbd_debug(NOTIFY,
 		    "Removing fsnotify mark, inode %llu, mask 0x%x, watch tree %d\n",
 		    (unsigned long long)file_inode(fp->filp)->i_ino,
@@ -1120,7 +1244,7 @@ ksmbd_notify_setup_watch(struct ksmbd_file *fp,
 
 	filter = le32_to_cpu(req->CompletionFilter);
 	mask = ksmbd_notify_map(filter);
-	if (!mask)
+	if (!mask && !(filter & KSMBD_NOTIFY_STREAM_MASK))
 		ksmbd_debug(NOTIFY,
 			    "No mapped completion filter bits; request will remain pending\n");
 
fs/smb/server/notify.h +7 -0
index b7d8df4bef1d..c8840e46c60f 100644
@@ -32,6 +32,7 @@ struct ksmbd_notify_event {
 };
 
 struct ksmbd_notify {
+	struct list_head stream_list;
 	struct fsnotify_group *group;
 	struct fsnotify_mark *mark;
 	struct fsnotify_mark *tree_mark;
@@ -64,10 +65,16 @@ struct ksmbd_notify_req {
 #define KSMBD_NOTIFY_MAX_BYTES		SZ_64K
 #define KSMBD_NOTIFY_NAME_EVENT_MASK	(FS_CREATE | FS_DELETE | \
 					 FS_MOVED_FROM | FS_MOVED_TO)
+#define KSMBD_NOTIFY_STREAM_MASK		(FILE_NOTIFY_CHANGE_STREAM_NAME | \
+					 FILE_NOTIFY_CHANGE_STREAM_SIZE | \
+					 FILE_NOTIFY_CHANGE_STREAM_WRITE)
 
 int ksmbd_handle_notify(struct ksmbd_work *work,
 			struct smb2_change_notify_req *req,
 			struct smb2_change_notify_rsp *rsp);
 void ksmbd_notify_remove(struct ksmbd_file *fp);
+bool ksmbd_notify_has_stream_watches(void);
+void ksmbd_notify_stream(const struct path *path, const char *xattr_name,
+			 ssize_t old_size, ssize_t new_size);
 
 #endif /* __SMB_SERVER_NOTIFY_H__ */
fs/smb/server/vfs.c +60 -7

98 lines not on this page · raw message

Signature · 1 line
2.55.0
maintainer
#15 lore raw
In reply to ChenXiaoSong
Quoted 19 lines · ChenXiaoSong

From: ChenXiaoSong <[email protected]>

v1->v2:
- Patch #04 #07: fix LAST_WRITE and LAST_ACCESS notify event mappings.
- Patch #04 #08 #09 #11 #12: limit notify event memory per open.
- Add patch #13: support change notify for named streams.

v1: https://lore.kernel.org/linux-cifs/[email protected]/

TODO: The KUnit test cases are still being modified.

To test this feature, the following patches need to be applied to cifs-utils and kernel smb client:
- cifs-utils: https://chenxiaosong.com/lkml/cifs-utils-parse-notify
- kernel smb client: https://chenxiaosong.com/lkml/cifs-improve-notify

The complete kernel client and server patches are also available at the following link:
https://chenxiaosong.com/repo/linux/ksmbd-change-notify

Quoted 14 lines

ChenXiaoSong (13):
smb/server: move change notify handling into notify.c smb/server: add more validation for change notify requests smb/server: add debug type for change notify smb/server: support non-recursive directory change watches smb/server: support recursive directory change watches smb/server: keep notify watches on file handles smb/server: save simple notify events
smb/server: save old names for rename notify events smb/server: match rename notify events
smb/server: encode notify events
smb/server: send notify events to the client smb/server: break directory leases before sending notify events smb/server: support change notify for named streams

Can you check the review comments from sashiko ?

https://sashiko.dev/#/patchset/20261025083450.212604-1-chenxiaosong%40chenxiaosong.com

Thanks.