| Seq | Timestamp | Type | Name | Duration |
|---|---|---|---|---|
| 0/0 | 2026/09/26 03:18 | flow | patch-triage |
3mArgs:null Results: {
"EnableConfigs": [
"FSNOTIFY"
],
"FocusSymbols": [
"vacate_mount",
"cleanup_mnt",
"mntput_no_expire_slowpath",
"__detach_mounts",
"umount_tree",
"namespace_unlock",
"__do_sys_fspick",
"fsnotify_init_connector",
"fsnotify_detach_connector_from_object",
"fsnotify_add_mark_list"
],
"KMSANReasoning": "The patch series resolves reference count cycles between detached mounts and attached submounts (e.g., loop devices or filesystems holding references on parent mounts) by introducing 'vacant mounts' that substitute a private knullfs instance for the submount's root/superblock when unreferenced while attached, and updates fsnotify mark connectors to explicitly track superblocks.\n\nRisk analysis:\n1. Uninitialized Memory / Info Leaks: None. No new kernel-to-user copy interfaces, ioctls, or user-visible data structures are added or altered. The fields added to internal structures (`mnt_old_root` in `struct mount` and `sb` in `struct fsnotify_mark_connector`) are explicitly initialized upon allocation or setup (`alloc_vfsmnt` uses `kmem_cache_zalloc`, `vacate_mount` sets `mnt_old_root`, and `fsnotify_init_connector` sets `conn-\u003esb`). There are no uninitialized variables or conditional branches dependent on uninitialized data.\n2. Memory Safety and Concurrency: The primary risks associated with this patch involve reference counting errors (e.g., mount refcount underflows/leaks, use-after-free, double puts), superblock and dentry lifecycle management, and synchronization/locking around mount teardown. These bugs are detected by KASAN (use-after-free, double free), refcount sanity checks, and LOCKDEP.\n\nBecause there are no uninitialized memory access or info-leak risks, running a dedicated KMSAN session is not justified; standard KASAN and LOCKDEP coverage is sufficient.",
"NeedsKMSAN": false,
"Reasoning": "The patch series introduces 'vacant mounts' backed by a private nullfs instance (knullfs) to break reference cycles where an unmounted mount loses its last reference while remaining attached to an unmounted parent. It modifies core VFS mount lifetime and reference counting logic (fs/namespace.c), updates fsnotify mark connectors to track their originating superblock across mount sb replacement (fs/notify/mark.c), and adds an SB_NOUSER check to fspick (fs/fsopen.c). It also introduces new runtime assertions (e.g. VFS_WARN_ON_ONCE(is_vacant(mnt))). These changes are in core reachable kernel subsystems and can be exercised via standard filesystem and mount syscalls (mount, umount2, fspick, open_tree, move_mount, fanotify/inotify). Due to the complex reference counting, refactoring of mount teardown, and dynamic superblock swapping, this code warrants focused fuzzing.",
"WorthFuzzing": true
} |
| 1/1 | 2026/09/26 03:18 | action | read-patch-diff |
0mArgs:null Results: {
"PatchDiff": "commit 6828955f7f8d6b3588066fb61312f9f956fbddf0\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate: Sat Sep 26 03:18:27 2026 +0000\n\n syz-cluster: applied patch under review\n\ndiff --git a/fs/fsopen.c b/fs/fsopen.c\nindex ae19e51365986..9d5a7a22b5292 100644\n--- a/fs/fsopen.c\n+++ b/fs/fsopen.c\n@@ -190,6 +190,9 @@ SYSCALL_DEFINE3(fspick, int, dfd, const char __user *, path, unsigned int, flags\n \tret = -EINVAL;\n \tif (target.mnt-\u003emnt_root != target.dentry)\n \t\tgoto err_path;\n+\t/* kernel-internal superblocks are nobody's to reconfigure */\n+\tif (target.dentry-\u003ed_sb-\u003es_flags \u0026 SB_NOUSER)\n+\t\tgoto err_path;\n \n \tfc = fs_context_for_reconfigure(target.dentry, 0, 0);\n \tif (IS_ERR(fc)) {\ndiff --git a/fs/mount.h b/fs/mount.h\nindex 94fcc306d21e7..50d0999ff09ff 100644\n--- a/fs/mount.h\n+++ b/fs/mount.h\n@@ -6,6 +6,7 @@\n #include \u003clinux/fs_pin.h\u003e\n \n extern struct file_system_type nullfs_fs_type;\n+extern struct vfsmount *knullfs;\n extern struct list_head notify_list;\n \n struct mnt_namespace {\n@@ -50,8 +51,13 @@ struct mount {\n \tstruct vfsmount mnt;\n \tunion {\n \t\tstruct rb_node mnt_node; /* node in the ns-\u003emounts rbtree */\n-\t\tstruct rcu_head mnt_rcu;\n-\t\tstruct llist_node mnt_llist;\n+\t\tstruct {\t\t /* once it has left its namespace */\n+\t\t\tunion {\n+\t\t\t\tstruct rcu_head mnt_rcu;\n+\t\t\t\tstruct llist_node mnt_llist;\n+\t\t\t};\n+\t\t\tstruct dentry *mnt_old_root; /* what a vacant mount stands in for */\n+\t\t};\n \t};\n #ifdef CONFIG_SMP\n \tstruct mnt_pcp __percpu *mnt_pcp;\n@@ -84,7 +90,7 @@ struct mount {\n \tstruct mountpoint *mnt_mp;\t/* where is it mounted */\n \tunion {\n \t\tstruct hlist_node mnt_mp_list;\t/* list mounts with the same mountpoint */\n-\t\tstruct hlist_node mnt_umount;\n+\t\tstruct hlist_node mnt_umount;\t/* in the parent's mnt_stuck_children */\n \t};\n #ifdef CONFIG_FSNOTIFY\n \tstruct fsnotify_mark_connector __rcu *mnt_fsnotify_marks;\ndiff --git a/fs/namespace.c b/fs/namespace.c\nindex 580877e46b1ac..175e8165693b6 100644\n--- a/fs/namespace.c\n+++ b/fs/namespace.c\n@@ -80,8 +80,9 @@ static u64 mnt_id_ctr = MNT_UNIQUE_ID_OFFSET;\n static struct hlist_head *mount_hashtable __ro_after_init;\n static struct hlist_head *mountpoint_hashtable __ro_after_init;\n static struct kmem_cache *mnt_cache __ro_after_init;\n+struct vfsmount *knullfs __ro_after_init;\t/* private nullfs instance */\n static DECLARE_RWSEM(namespace_sem);\n-static HLIST_HEAD(unmounted);\t/* protected by namespace_sem */\n+static LIST_HEAD(unmounted);\t/* protected by namespace_sem */\n static LIST_HEAD(ex_mountpoints); /* protected by namespace_sem */\n static struct mnt_namespace *emptied_ns; /* protected by namespace_sem */\n \n@@ -227,6 +228,17 @@ static void mnt_free_id(struct mount *mnt)\n \txa_erase(\u0026mnt_id_xa, mnt-\u003emnt_id);\n }\n \n+/* mnt_id_ctr is protected by the lock of mnt_id_xa, see mnt_alloc_id(). */\n+static u64 mnt_alloc_unique_id(void)\n+{\n+\tu64 id;\n+\n+\txa_lock(\u0026mnt_id_xa);\n+\tid = ++mnt_id_ctr;\n+\txa_unlock(\u0026mnt_id_xa);\n+\treturn id;\n+}\n+\n /*\n * Allocate a new peer group ID\n */\n@@ -1150,18 +1162,28 @@ static void commit_tree(struct mount *mnt)\n \ttouch_mnt_namespace(n);\n }\n \n-static void setup_mnt(struct mount *m, struct dentry *root)\n+/*\n+ * Point @m at @root: a reference on the superblock and its root, and a\n+ * place on the superblock's list of instances.\n+ * locks: mount_lock, as mount_locked_reader or mount_writer\n+ */\n+static void __setup_mnt(struct mount *m, struct dentry *root)\n {\n \tstruct super_block *s = root-\u003ed_sb;\n \n \tatomic_inc(\u0026s-\u003es_active);\n \tm-\u003emnt.mnt_sb = s;\n \tm-\u003emnt.mnt_root = dget(root);\n-\tm-\u003emnt_mountpoint = m-\u003emnt.mnt_root;\n+\tmnt_add_instance(m, s);\n+}\n+\n+static void setup_mnt(struct mount *m, struct dentry *root)\n+{\n+\tm-\u003emnt_mountpoint = root;\n \tm-\u003emnt_parent = m;\n \n \tguard(mount_locked_reader)();\n-\tmnt_add_instance(m, s);\n+\t__setup_mnt(m, root);\n }\n \n /**\n@@ -1294,8 +1316,20 @@ static struct mount *clone_mnt(struct mount *old, struct dentry *root,\n \treturn ERR_PTR(err);\n }\n \n+/*\n+ * The only mounts of knullfs' superblock that are ever attached are\n+ * vacant mounts.\n+ */\n+static inline bool is_vacant(const struct mount *mnt)\n+{\n+\treturn mnt-\u003emnt.mnt_sb == knullfs-\u003emnt_sb;\n+}\n+\n static void cleanup_mnt(struct mount *mnt)\n {\n+\tbool release = !(mnt-\u003emnt.mnt_flags \u0026 MNT_DOOMED);\n+\tstruct dentry *root = release ? mnt-\u003emnt_old_root : mnt-\u003emnt.mnt_root;\n+\tstruct super_block *sb = root-\u003ed_sb;\n \tstruct hlist_node *p;\n \tstruct mount *m;\n \t/*\n@@ -1303,9 +1337,10 @@ static void cleanup_mnt(struct mount *mnt)\n \t * up a mnt_want/drop_write() pair. If this happens, the\n \t * filesystem was probably unable to make r/w-\u003er/o transitions.\n \t * The locking used to deal with mnt_count decrement provides barriers,\n-\t * so mnt_get_writers() below is safe.\n+\t * so mnt_get_writers() below is safe. A vacant mount is still reachable\n+\t * and a failing mnt_want_write() on it bumps the count for a moment.\n \t */\n-\tWARN_ON(mnt_get_writers(mnt));\n+\tWARN_ON(!release \u0026\u0026 mnt_get_writers(mnt));\n \tif (unlikely(mnt-\u003emnt_pins.first))\n \t\tmnt_pin_kill(mnt);\n \thlist_for_each_entry_safe(m, p, \u0026mnt-\u003emnt_stuck_children, mnt_umount) {\n@@ -1313,12 +1348,35 @@ static void cleanup_mnt(struct mount *mnt)\n \t\tmntput(\u0026m-\u003emnt);\n \t}\n \tfsnotify_vfsmount_delete(\u0026mnt-\u003emnt);\n-\tdput(mnt-\u003emnt.mnt_root);\n-\tdeactivate_super(mnt-\u003emnt.mnt_sb);\n+\tdput(root);\n+\tdeactivate_super(sb);\n+\t/* A new vacant mount is just put here. */\n+\tif (unlikely(release)) {\n+\t\t/* the reference vacate_mount() gave the release */\n+\t\tmntput(\u0026mnt-\u003emnt);\n+\t\treturn;\n+\t}\n \tmnt_free_id(mnt);\n \tcall_rcu(\u0026mnt-\u003emnt_rcu, delayed_free_vfsmnt);\n }\n \n+/*\n+ * @mnt lost its last reference while still attached. Don't reveal what's\n+ * beneath so mount knullfs over it.\n+ */\n+static void vacate_mount(struct mount *mnt)\n+{\n+\t/* a vacant mount is put only after it has been unhashed */\n+\tVFS_WARN_ON_ONCE(is_vacant(mnt));\n+\tmnt-\u003emnt_old_root = mnt-\u003emnt.mnt_root;\n+\t__setup_mnt(mnt, knullfs-\u003emnt_root);\n+\tmnt-\u003emnt.mnt_flags |= MNT_READONLY;\n+\t/* It's a new mount so give it its own mount id. */\n+\tmnt-\u003emnt_id_unique = mnt_alloc_unique_id();\n+\t/* One reference for the parent and one for cleanup_mnt(). */\n+\tmnt_add_count(mnt, 2);\n+}\n+\n static void __cleanup_mnt(struct rcu_head *head)\n {\n \tcleanup_mnt(container_of(head, struct mount, mnt_rcu));\n@@ -1338,6 +1396,7 @@ static DECLARE_DELAYED_WORK(delayed_mntput_work, delayed_mntput);\n static void noinline mntput_no_expire_slowpath(struct mount *mnt)\n {\n \tLIST_HEAD(list);\n+\tbool vacate = false;\n \tint count;\n \n \tVFS_BUG_ON(mnt-\u003emnt_ns);\n@@ -1360,7 +1419,11 @@ static void noinline mntput_no_expire_slowpath(struct mount *mnt)\n \t\tunlock_mount_hash();\n \t\treturn;\n \t}\n-\tmnt-\u003emnt.mnt_flags |= MNT_DOOMED;\n+\t/* Still attached, so it held its own reference: keep the slot filled. */\n+\tif (unlikely(mnt_has_parent(mnt)))\n+\t\tvacate = true;\n+\telse\n+\t\tmnt-\u003emnt.mnt_flags |= MNT_DOOMED;\n \trcu_read_unlock();\n \n \tmnt_del_instance(mnt);\n@@ -1371,9 +1434,13 @@ static void noinline mntput_no_expire_slowpath(struct mount *mnt)\n \t\tstruct mount *p, *tmp;\n \t\tlist_for_each_entry_safe(p, tmp, \u0026mnt-\u003emnt_mounts, mnt_child) {\n \t\t\t__umount_mnt(p, \u0026list);\n-\t\t\thlist_add_head(\u0026p-\u003emnt_umount, \u0026mnt-\u003emnt_stuck_children);\n+\t\t\t/* only a vacant mount is owned by its parent */\n+\t\t\tif (is_vacant(p))\n+\t\t\t\thlist_add_head(\u0026p-\u003emnt_umount, \u0026mnt-\u003emnt_stuck_children);\n \t\t}\n \t}\n+\tif (unlikely(vacate))\n+\t\tvacate_mount(mnt);\n \tunlock_mount_hash();\n \tshrink_dentry_list(\u0026list);\n \n@@ -1688,13 +1755,12 @@ static bool need_notify_mnt_list(void)\n static void free_mnt_ns(struct mnt_namespace *);\n static void namespace_unlock(void)\n {\n-\tstruct hlist_head head;\n-\tstruct hlist_node *p;\n-\tstruct mount *m;\n+\tstruct mount *m, *n;\n \tstruct mnt_namespace *ns = emptied_ns;\n+\tLIST_HEAD(head);\n \tLIST_HEAD(list);\n \n-\thlist_move_list(\u0026unmounted, \u0026head);\n+\tlist_splice_init(\u0026unmounted, \u0026head);\n \tlist_splice_init(\u0026ex_mountpoints, \u0026list);\n \temptied_ns = NULL;\n \n@@ -1718,13 +1784,14 @@ static void namespace_unlock(void)\n \n \tshrink_dentry_list(\u0026list);\n \n-\tif (likely(hlist_empty(\u0026head)))\n+\tif (likely(list_empty(\u0026head)))\n \t\treturn;\n \n \tsynchronize_rcu_expedited();\n \n-\thlist_for_each_entry_safe(m, p, \u0026head, mnt_umount) {\n-\t\thlist_del(\u0026m-\u003emnt_umount);\n+\t/* In tree order, so a subtree nobody holds goes without vacant mounts. */\n+\tlist_for_each_entry_safe(m, n, \u0026head, mnt_list) {\n+\t\tlist_del_init(\u0026m-\u003emnt_list);\n \t\tmntput(\u0026m-\u003emnt);\n \t}\n }\n@@ -1740,6 +1807,19 @@ enum umount_tree_flags {\n \tUMOUNT_CONNECTED = 4,\n };\n \n+/*\n+ * An unmounted mount that stays attached to its unmounted parent:\n+ *\n+ * - is hashed and on the parent's list of children, so a walk on the\n+ * parent finds it and never ends up in what it covered\n+ * - is unreachable from any namespace root\n+ * - holds its own reference, dropped by namespace_unlock(); the parent's\n+ * final mntput() unhashes it without putting it, so a child whose\n+ * superblock pins an ancestor can still shut down\n+ * - is vacated if it loses its last reference while attached\n+ * it releases the filesystem it carried and a knullfs mount is placed on\n+ * the parent which is owned by it\n+ */\n static bool disconnect_mount(struct mount *mnt, enum umount_tree_flags how)\n {\n \t/* Leaving mounts connected is only valid for lazy umounts */\n@@ -1750,10 +1830,7 @@ static bool disconnect_mount(struct mount *mnt, enum umount_tree_flags how)\n \tif (!mnt_has_parent(mnt))\n \t\treturn true;\n \n-\t/* Because the reference counting rules change when mounts are\n-\t * unmounted and connected, umounted mounts may not be\n-\t * connected to mounted mounts.\n-\t */\n+\t/* An unmounted mount may only stay attached to an unmounted parent */\n \tif (!(mnt-\u003emnt_parent-\u003emnt.mnt_flags \u0026 MNT_UMOUNT))\n \t\treturn true;\n \n@@ -1769,10 +1846,6 @@ static bool disconnect_mount(struct mount *mnt, enum umount_tree_flags how)\n \treturn true;\n }\n \n-/*\n- * mount_lock must be held\n- * namespace_sem must be held for write\n- */\n static void umount_tree(struct mount *mnt, enum umount_tree_flags how)\n {\n \tLIST_HEAD(tmp_list);\n@@ -1824,8 +1897,8 @@ static void umount_tree(struct mount *mnt, enum umount_tree_flags how)\n \t\t\t\tumount_mnt(p);\n \t\t\t}\n \t\t}\n-\t\tif (disconnect)\n-\t\t\thlist_add_head(\u0026p-\u003emnt_umount, \u0026unmounted);\n+\t\t/* attached or not, it holds its own reference */\n+\t\tlist_add_tail(\u0026p-\u003emnt_list, \u0026unmounted);\n \n \t\t/*\n \t\t * At this point p-\u003emnt_ns is NULL, notification will be queued\n@@ -1994,9 +2067,12 @@ void __detach_mounts(struct dentry *dentry)\n \t\tmnt = hlist_entry(mp.node.next, struct mount, mnt_mp_list);\n \t\tif (mnt-\u003emnt.mnt_flags \u0026 MNT_UMOUNT) {\n \t\t\tumount_mnt(mnt);\n-\t\t\thlist_add_head(\u0026mnt-\u003emnt_umount, \u0026unmounted);\n+\t\t\t/* only a vacant mount is owned by its parent */\n+\t\t\tif (is_vacant(mnt))\n+\t\t\t\tlist_add_tail(\u0026mnt-\u003emnt_list, \u0026unmounted);\n+\t\t} else {\n+\t\t\tumount_tree(mnt, UMOUNT_CONNECTED);\n \t\t}\n-\t\telse umount_tree(mnt, UMOUNT_CONNECTED);\n \t}\n \tunpin_mountpoint(\u0026mp);\n }\n@@ -6210,10 +6286,12 @@ static void __init init_mount_tree(void)\n \t *\n \t * (1) nullfs with mount id 1\n \t * (2) mutable rootfs with mount id 2\n-\t * (3) private nullfs for kthreads (SB_KERNMOUNT)\n+\t * (3) private nullfs for kthreads (SB_KERNMOUNT), kept in knullfs\n \t *\n \t * with (2) mounted on top of (1). The init_task's root and pwd\n \t * are pointed at (3) so all kthreads start isolated in nullfs.\n+\t * A mount that dies while still attached to its parent is pointed\n+\t * at (3) as well, see vacate_mount().\n \t */\n \tnullfs_mnt = vfs_kern_mount(\u0026nullfs_fs_type, 0, \"nullfs\", NULL);\n \tif (IS_ERR(nullfs_mnt))\n@@ -6245,11 +6323,11 @@ static void __init init_mount_tree(void)\n \t\tinit_mnt_ns.nr_mounts++;\n \t}\n \n-\tnullfs_mnt = kern_mount(\u0026nullfs_fs_type);\n-\tif (IS_ERR(nullfs_mnt))\n+\tknullfs = kern_mount(\u0026nullfs_fs_type);\n+\tif (IS_ERR(knullfs))\n \t\tpanic(\"VFS: Failed to create private nullfs instance\");\n-\troot.mnt\t= nullfs_mnt;\n-\troot.dentry\t= nullfs_mnt-\u003emnt_root;\n+\troot.mnt\t= knullfs;\n+\troot.dentry\t= knullfs-\u003emnt_root;\n \n \tinit_task.nsproxy-\u003emnt_ns = \u0026init_mnt_ns;\n \tget_mnt_ns(\u0026init_mnt_ns);\ndiff --git a/fs/notify/fsnotify.h b/fs/notify/fsnotify.h\nindex 58c7bb25e5718..0be351275dad7 100644\n--- a/fs/notify/fsnotify.h\n+++ b/fs/notify/fsnotify.h\n@@ -54,10 +54,11 @@ static inline struct super_block *fsnotify_object_sb(void *obj,\n \t}\n }\n \n+/* The sb the connector is accounted on; NULL once it has been detached */\n static inline struct super_block *fsnotify_connector_sb(\n \t\t\t\tstruct fsnotify_mark_connector *conn)\n {\n-\treturn fsnotify_object_sb(conn-\u003eobj, conn-\u003etype);\n+\treturn conn-\u003esb;\n }\n \n static inline fsnotify_connp_t *fsnotify_sb_marks(struct super_block *sb)\ndiff --git a/fs/notify/mark.c b/fs/notify/mark.c\nindex b2640d836a712..1b6095fcf039f 100644\n--- a/fs/notify/mark.c\n+++ b/fs/notify/mark.c\n@@ -425,6 +425,7 @@ static void *fsnotify_detach_connector_from_object(\n \tconn-\u003etype = FSNOTIFY_OBJ_TYPE_DETACHED;\n \tif (sb)\n \t\tfsnotify_update_sb_watchers(sb, conn);\n+\tconn-\u003esb = NULL;\n \n \treturn inode;\n }\n@@ -791,6 +792,8 @@ static void fsnotify_init_connector(struct fsnotify_mark_connector *conn,\n \tconn-\u003eprio = 0;\n \tconn-\u003etype = obj_type;\n \tconn-\u003eobj = obj;\n+\t/* the object may move to another sb, the accounting doesn't */\n+\tconn-\u003esb = fsnotify_object_sb(obj, obj_type);\n }\n \n static struct fsnotify_mark_connector *\n@@ -953,8 +956,8 @@ static int fsnotify_add_mark_list(struct fsnotify_mark *mark, void *obj,\n \t/* mark should be the last entry. last is the current last entry */\n \thlist_add_behind_rcu(\u0026mark-\u003eobj_list, \u0026last-\u003eobj_list);\n added:\n-\tif (sb)\n-\t\tfsnotify_update_sb_watchers(sb, conn);\n+\tif (conn-\u003esb)\n+\t\tfsnotify_update_sb_watchers(conn-\u003esb, conn);\n \t/*\n \t * Since connector is attached to object using cmpxchg() we are\n \t * guaranteed that connector initialization is fully visible by anyone\ndiff --git a/include/linux/fsnotify_backend.h b/include/linux/fsnotify_backend.h\nindex 618eed4d6d724..3a9ab9e0104b4 100644\n--- a/include/linux/fsnotify_backend.h\n+++ b/include/linux/fsnotify_backend.h\n@@ -573,6 +573,8 @@ struct fsnotify_mark_connector {\n \t\t/* Used listing heads to free after srcu period expires */\n \t\tstruct fsnotify_mark_connector *destroy_next;\n \t};\n+\t/* sb whose watched_objects account for this connector [lock] */\n+\tstruct super_block *sb;\n \tstruct hlist_head list;\t/* List of marks */\n };\n \ndiff --git a/tools/testing/selftests/Makefile b/tools/testing/selftests/Makefile\nindex 273853937c254..fb3a85d6396de 100644\n--- a/tools/testing/selftests/Makefile\n+++ b/tools/testing/selftests/Makefile\n@@ -43,6 +43,7 @@ TARGETS += filesystems/open_tree_ns\n TARGETS += filesystems/overlayfs\n TARGETS += filesystems/statmount\n TARGETS += filesystems/mount-notify\n+TARGETS += filesystems/mount_cycle\n TARGETS += filesystems/nsfs\n TARGETS += filesystems/fuse\n TARGETS += filesystems/move_mount\ndiff --git a/tools/testing/selftests/filesystems/mount_cycle/.gitignore b/tools/testing/selftests/filesystems/mount_cycle/.gitignore\nnew file mode 100644\nindex 0000000000000..28c623ef4d9dc\n--- /dev/null\n+++ b/tools/testing/selftests/filesystems/mount_cycle/.gitignore\n@@ -0,0 +1,2 @@\n+# SPDX-License-Identifier: GPL-2.0-only\n+loop_cycle_test\ndiff --git a/tools/testing/selftests/filesystems/mount_cycle/Makefile b/tools/testing/selftests/filesystems/mount_cycle/Makefile\nnew file mode 100644\nindex 0000000000000..3becec29d69fb\n--- /dev/null\n+++ b/tools/testing/selftests/filesystems/mount_cycle/Makefile\n@@ -0,0 +1,6 @@\n+# SPDX-License-Identifier: GPL-2.0\n+TEST_GEN_PROGS := loop_cycle_test\n+\n+CFLAGS += -Wall -O2 -g $(KHDR_INCLUDES)\n+\n+include ../../lib.mk\ndiff --git a/tools/testing/selftests/filesystems/mount_cycle/loop_cycle_test.c b/tools/testing/selftests/filesystems/mount_cycle/loop_cycle_test.c\nnew file mode 100644\nindex 0000000000000..09cc824c769e0\n--- /dev/null\n+++ b/tools/testing/selftests/filesystems/mount_cycle/loop_cycle_test.c\n@@ -0,0 +1,1225 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * A mount that another namespace's rmdir detached, or that went down with\n+ * the detached tree it was in when the tree's last fd was closed, keeps\n+ * its submounts connected, and a connected submount is put by its\n+ * parent's final mntput(). A submount whose filesystem keeps a file open\n+ * on the parent then holds the parent's count above zero for good:\n+ * nothing in userspace refers to either mount any more and nothing can\n+ * release them. A loop device is the simplest such filesystem, its\n+ * backing file sits on the parent.\n+ */\n+#define _GNU_SOURCE\n+#include \u003cdirent.h\u003e\n+#include \u003cerrno.h\u003e\n+#include \u003cfcntl.h\u003e\n+#include \u003csched.h\u003e\n+#include \u003cstdio.h\u003e\n+#include \u003cstdlib.h\u003e\n+#include \u003cstring.h\u003e\n+#include \u003csys/ioctl.h\u003e\n+#include \u003csys/mount.h\u003e\n+#include \u003csys/stat.h\u003e\n+#include \u003cstdbool.h\u003e\n+#include \u003csys/wait.h\u003e\n+#include \u003cunistd.h\u003e\n+#include \u003clinux/fuse.h\u003e\n+#include \u003clinux/keyctl.h\u003e\n+#include \u003clinux/major.h\u003e\n+#include \u003clinux/raid/md_u.h\u003e\n+#include \u003clinux/raid/md_p.h\u003e\n+#include \u003clinux/loop.h\u003e\n+#include \u003clinux/magic.h\u003e\n+#include \u003csys/syscall.h\u003e\n+#include \u003csys/sysmacros.h\u003e\n+#include \u003csys/uio.h\u003e\n+\n+#include \"../wrappers.h\"\n+#include \"../../kselftest_harness.h\"\n+\n+#define IMAGE_SIZE\t(1440 * 1024)\n+#define SECTOR\t\t512\n+\n+/* A blank FAT12 floppy image: boot sector, two FATs, an empty root directory. */\n+static int write_fat12(int fd)\n+{\n+\tstruct stat st;\n+\tunsigned char sector[SECTOR] = {\n+\t\t0xeb, 0x3c, 0x90, 'M', 'S', 'W', 'I', 'N', '4', '.', '1',\n+\t\t[11] = 0x00, 0x02,\t/* bytes per sector: 512 */\n+\t\t[13] = 1,\t\t/* sectors per cluster */\n+\t\t[14] = 1, 0,\t\t/* reserved sectors */\n+\t\t[16] = 2,\t\t/* FATs */\n+\t\t[17] = 0xe0, 0x00,\t/* root directory entries: 224 */\n+\t\t[19] = 0x40, 0x0b,\t/* total sectors: 2880 */\n+\t\t[21] = 0xf0,\t\t/* media descriptor */\n+\t\t[22] = 9, 0,\t\t/* sectors per FAT */\n+\t\t[24] = 18, 0,\t\t/* sectors per track */\n+\t\t[26] = 2, 0,\t\t/* heads */\n+\t\t[38] = 0x29,\t\t/* extended boot signature */\n+\t\t[39] = 0x12, 0x34, 0x56, 0x78,\n+\t\t[43] = 'N', 'O', ' ', 'N', 'A', 'M', 'E', ' ', ' ', ' ', ' ',\n+\t\t[54] = 'F', 'A', 'T', '1', '2', ' ', ' ', ' ',\n+\t\t[510] = 0x55, 0xaa,\n+\t};\n+\tunsigned char fat[SECTOR] = { 0xf0, 0xff, 0xff };\n+\n+\tif (pwrite(fd, sector, SECTOR, 0) != SECTOR)\n+\t\treturn -1;\n+\t/* the first FAT and the second one, one sector each is enough */\n+\tif (pwrite(fd, fat, SECTOR, 1 * SECTOR) != SECTOR ||\n+\t pwrite(fd, fat, SECTOR, 10 * SECTOR) != SECTOR)\n+\t\treturn -1;\n+\tif (fstat(fd, \u0026st) || S_ISBLK(st.st_mode))\n+\t\treturn 0;\n+\treturn ftruncate(fd, IMAGE_SIZE);\n+}\n+\n+/*\n+ * A blank FAT12 image with 4 KiB sectors and @sectors of them, for a device\n+ * with 4 KiB logical blocks (zram) or for a bigger image than a floppy.\n+ */\n+static int write_fat12_4k(int fd, unsigned int sectors)\n+{\n+\tunsigned int fat_sectors = (sectors * 3 / 2 + 4095) / 4096;\n+\tunsigned char sector[4096] = {\n+\t\t0xeb, 0x3c, 0x90, 'M', 'S', 'W', 'I', 'N', '4', '.', '1',\n+\t\t[11] = 0x00, 0x10,\t/* bytes per sector: 4096 */\n+\t\t[13] = 1,\t\t/* sectors per cluster */\n+\t\t[14] = 1, 0,\t\t/* reserved sectors */\n+\t\t[16] = 2,\t\t/* FATs */\n+\t\t[17] = 128, 0,\t\t/* root directory entries: one sector */\n+\t\t[19] = sectors \u0026 0xff, sectors \u003e\u003e 8,\n+\t\t[21] = 0xf8,\t\t/* media descriptor */\n+\t\t[22] = fat_sectors, 0,\n+\t\t[24] = 63, 0,\t\t/* sectors per track */\n+\t\t[26] = 255, 0,\t\t/* heads */\n+\t\t[38] = 0x29,\t\t/* extended boot signature */\n+\t\t[39] = 0x12, 0x34, 0x56, 0x78,\n+\t\t[43] = 'N', 'O', ' ', 'N', 'A', 'M', 'E', ' ', ' ', ' ', ' ',\n+\t\t[54] = 'F', 'A', 'T', '1', '2', ' ', ' ', ' ',\n+\t\t[510] = 0x55, 0xaa,\n+\t};\n+\tunsigned char fat[4096] = { 0xf8, 0xff, 0xff };\n+\tstruct stat st;\n+\n+\tif (pwrite(fd, sector, sizeof(sector), 0) != sizeof(sector))\n+\t\treturn -1;\n+\tif (pwrite(fd, fat, sizeof(fat), 1 * 4096) != sizeof(fat) ||\n+\t pwrite(fd, fat, sizeof(fat), (1 + fat_sectors) * 4096) != sizeof(fat))\n+\t\treturn -1;\n+\tif (fstat(fd, \u0026st) || S_ISBLK(st.st_mode))\n+\t\treturn 0;\n+\treturn ftruncate(fd, (off_t)sectors * 4096);\n+}\n+\n+#define MINIX_BLOCK\t1024\n+#define MINIX_BLOCKS\t4096\t\t\t/* a 4 MiB image */\n+#define MINIX_INODES\t512\n+#define MINIX_ITABLE\t(MINIX_INODES * 32 / MINIX_BLOCK)\n+#define MINIX_FIRSTDATA\t(2 + 1 + 1 + MINIX_ITABLE)\t/* boot, super, imap, zmap, inodes */\n+\n+/*\n+ * A blank minix v1 image, for the holders that need a FIFO or a device\n+ * node on the dying mount, which vfat can't hold. Superblock in block 1,\n+ * one block each for the inode and zone bitmaps, the inode table, and\n+ * the root directory in the first data zone.\n+ */\n+static int write_minix(int fd)\n+{\n+\tstruct {\n+\t\t__u16 s_ninodes, s_nzones, s_imap_blocks, s_zmap_blocks;\n+\t\t__u16 s_firstdatazone, s_log_zone_size;\n+\t\t__u32 s_max_size;\n+\t\t__u16 s_magic, s_state;\n+\t} sb = {\n+\t\t.s_ninodes = MINIX_INODES,\n+\t\t.s_nzones = MINIX_BLOCKS,\n+\t\t.s_imap_blocks = 1,\n+\t\t.s_zmap_blocks = 1,\n+\t\t.s_firstdatazone = MINIX_FIRSTDATA,\n+\t\t.s_max_size = (7 + 512 + 512 * 512) * MINIX_BLOCK,\n+\t\t.s_magic = MINIX_SUPER_MAGIC,\n+\t\t.s_state = 1,\t\t/* MINIX_VALID_FS */\n+\t};\n+\tstruct {\n+\t\t__u16 i_mode, i_uid;\n+\t\t__u32 i_size, i_time;\n+\t\t__u8 i_gid, i_nlinks;\n+\t\t__u16 i_zone[9];\n+\t} root = {\n+\t\t.i_mode = S_IFDIR | 0755,\n+\t\t.i_size = 2 * 16,\n+\t\t.i_nlinks = 2,\n+\t\t.i_zone = { MINIX_FIRSTDATA },\n+\t};\n+\tunsigned char imap[MINIX_BLOCK], zmap[MINIX_BLOCK], dir[MINIX_BLOCK] = {};\n+\tint i;\n+\n+\t/* bit 0 is reserved in both maps, the root inode and its zone are in use */\n+\tmemset(imap, 0xff, sizeof(imap));\n+\tfor (i = 2; i \u003c= MINIX_INODES; i++)\n+\t\timap[i / 8] \u0026= ~(1 \u003c\u003c (i % 8));\n+\tmemset(zmap, 0xff, sizeof(zmap));\n+\tfor (i = 2; i \u003c= MINIX_BLOCKS - MINIX_FIRSTDATA; i++)\n+\t\tzmap[i / 8] \u0026= ~(1 \u003c\u003c (i % 8));\n+\tdir[0] = 1;\n+\tdir[2] = '.';\n+\tdir[16] = 1;\n+\tdir[18] = '.';\n+\tdir[19] = '.';\n+\n+\tif (pwrite(fd, \u0026sb, sizeof(sb), 1 * MINIX_BLOCK) != sizeof(sb) ||\n+\t pwrite(fd, imap, sizeof(imap), 2 * MINIX_BLOCK) != sizeof(imap) ||\n+\t pwrite(fd, zmap, sizeof(zmap), 3 * MINIX_BLOCK) != sizeof(zmap) ||\n+\t pwrite(fd, \u0026root, sizeof(root), 4 * MINIX_BLOCK) != sizeof(root) ||\n+\t pwrite(fd, dir, sizeof(dir), MINIX_FIRSTDATA * MINIX_BLOCK) != sizeof(dir))\n+\t\treturn -1;\n+\treturn ftruncate(fd, (off_t)MINIX_BLOCKS * MINIX_BLOCK);\n+}\n+\n+static int read_sysfs(const char *path, char *buf, size_t size)\n+{\n+\tssize_t n;\n+\tint fd;\n+\n+\tfd = open(path, O_RDONLY);\n+\tif (fd \u003c 0)\n+\t\treturn -1;\n+\tn = read(fd, buf, size - 1);\n+\tclose(fd);\n+\tif (n \u003c 0)\n+\t\treturn -1;\n+\tbuf[n] = '\\0';\n+\treturn 0;\n+}\n+\n+/* Does any mount namespace in the system show a mount of @dev? */\n+static bool mounted_anywhere(const char *dev)\n+{\n+\tchar path[PATH_MAX], line[4096];\n+\tstruct dirent *de;\n+\tbool found = false;\n+\tDIR *proc;\n+\tFILE *f;\n+\n+\tproc = opendir(\"/proc\");\n+\tif (!proc)\n+\t\treturn false;\n+\twhile (!found \u0026\u0026 (de = readdir(proc))) {\n+\t\tif (de-\u003ed_name[0] \u003c '0' || de-\u003ed_name[0] \u003e '9')\n+\t\t\tcontinue;\n+\t\tsnprintf(path, sizeof(path), \"/proc/%s/mountinfo\", de-\u003ed_name);\n+\t\tf = fopen(path, \"re\");\n+\t\tif (!f)\n+\t\t\tcontinue;\n+\t\twhile (fgets(line, sizeof(line), f)) {\n+\t\t\tif (strstr(line, dev)) {\n+\t\t\t\tfound = true;\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t}\n+\t\tfclose(f);\n+\t}\n+\tclosedir(proc);\n+\treturn found;\n+}\n+\n+/* Wait up to @ms milliseconds for the loop device to give up its backing file. */\n+static bool loop_released(const char *sysfs, int ms)\n+{\n+\tchar buf[PATH_MAX];\n+\n+\tfor (; ms \u003e 0; ms -= 100) {\n+\t\tif (read_sysfs(sysfs, buf, sizeof(buf)) \u003c 0)\n+\t\t\treturn true;\n+\t\tusleep(100000);\n+\t}\n+\treturn read_sysfs(sysfs, buf, sizeof(buf)) \u003c 0;\n+}\n+\n+FIXTURE(loop_cycle) {\n+\tchar dev[32];\t\t/* the loop device the child set up */\n+\tchar sysfs[64];\t\t/* its backing_file attribute */\n+};\n+\n+FIXTURE_SETUP(loop_cycle)\n+{\n+\tif (geteuid() != 0)\n+\t\tSKIP(return, \"test requires CAP_SYS_ADMIN\");\n+\tif (access(\"/dev/loop-control\", R_OK | W_OK))\n+\t\tSKIP(return, \"test requires loop devices\");\n+\n+\tASSERT_EQ(unshare(CLONE_NEWNS), 0);\n+\tASSERT_EQ(mount(\"\", \"/\", NULL, MS_REC | MS_PRIVATE, NULL), 0);\n+\n+\trmdir(\"/mnt_dir\");\n+\tASSERT_EQ(mkdir(\"/mnt_dir\", 0755), 0);\n+\tASSERT_EQ(mount(\"tmpfs\", \"/mnt_dir\", \"tmpfs\", 0, NULL), 0);\n+\tself-\u003edev[0] = '\\0';\n+}\n+\n+FIXTURE_TEARDOWN(loop_cycle)\n+{\n+\tumount2(\"/mnt_dir\", MNT_DETACH);\n+\trmdir(\"/mnt_dir\");\n+}\n+\n+/* Child exit codes. */\n+enum {\n+\tCHILD_OK,\n+\tCHILD_NS,\t\t/* could not set up the namespace or the tmpfs */\n+\tCHILD_IMAGE,\t\t/* could not write the image */\n+\tCHILD_LOOP,\t\t/* could not set up the loop device */\n+\tCHILD_MOUNT,\t\t/* could not mount it (vfat and msdos both refused) */\n+\tCHILD_PIPE,\t\t/* the parent went away */\n+\tCHILD_HOLDER,\t\t/* could not set the holder up below the mount */\n+\tCHILD_SKIP,\t\t/* the kernel lacks what the holder needs */\n+};\n+\n+/* Bind a free loop device to the open image @ifd; the device number. */\n+static int loop_bind(int ifd)\n+{\n+\tint cfd, lfd, n;\n+\tchar dev[32];\n+\n+\tcfd = open(\"/dev/loop-control\", O_RDWR);\n+\tif (cfd \u003c 0)\n+\t\treturn -1;\n+\tn = ioctl(cfd, LOOP_CTL_GET_FREE);\n+\tclose(cfd);\n+\tif (n \u003c 0)\n+\t\treturn -1;\n+\tsnprintf(dev, sizeof(dev), \"/dev/loop%d\", n);\n+\tlfd = open(dev, O_RDWR);\n+\tif (lfd \u003c 0)\n+\t\treturn -1;\n+\tif (ioctl(lfd, LOOP_SET_FD, ifd))\n+\t\tn = -1;\n+\tclose(lfd);\n+\treturn n;\n+}\n+\n+/* Write an image to @img, bind a loop device to it and mount that at @mp; the device number. */\n+static int loop_mount(const char *img, const char *mp)\n+{\n+\tchar dev[32];\n+\tint ifd, n;\n+\n+\tifd = open(img, O_RDWR | O_CREAT | O_EXCL, 0600);\n+\tif (ifd \u003c 0 || write_fat12(ifd))\n+\t\treturn -CHILD_IMAGE;\n+\tn = loop_bind(ifd);\n+\tclose(ifd);\t/* the loop device holds the file from now on */\n+\tif (n \u003c 0)\n+\t\treturn -CHILD_LOOP;\n+\tsnprintf(dev, sizeof(dev), \"/dev/loop%d\", n);\n+\tif (mkdir(mp, 0755))\n+\t\treturn -CHILD_MOUNT;\n+\tif (mount(dev, mp, \"vfat\", 0, NULL) \u0026\u0026 mount(dev, mp, \"msdos\", 0, NULL))\n+\t\treturn -CHILD_MOUNT;\n+\treturn n;\n+}\n+\n+/*\n+ * Two tmpfs mounts, each carrying the image of the loop mount below the\n+ * other: the loop mount below /mnt_dir/vol has its image on /mnt_dir/vol2\n+ * and the other way round.\n+ */\n+static int crossed_child(int to_parent, int from_parent)\n+{\n+\tint n[2];\n+\tchar c;\n+\n+\tif (unshare(CLONE_NEWNS) || mount(\"\", \"/\", NULL, MS_REC | MS_PRIVATE, NULL))\n+\t\treturn CHILD_NS;\n+\tif (mkdir(\"/mnt_dir/vol\", 0755) || mount(\"tmpfs\", \"/mnt_dir/vol\", \"tmpfs\", 0, NULL) ||\n+\t mkdir(\"/mnt_dir/vol2\", 0755) || mount(\"tmpfs\", \"/mnt_dir/vol2\", \"tmpfs\", 0, NULL))\n+\t\treturn CHILD_NS;\n+\tn[0] = loop_mount(\"/mnt_dir/vol2/img\", \"/mnt_dir/vol/mnt\");\n+\tif (n[0] \u003c 0)\n+\t\treturn -n[0];\n+\tn[1] = loop_mount(\"/mnt_dir/vol/img\", \"/mnt_dir/vol2/mnt\");\n+\tif (n[1] \u003c 0)\n+\t\treturn -n[1];\n+\tif (write(to_parent, n, sizeof(n)) != sizeof(n))\n+\t\treturn CHILD_PIPE;\n+\tif (read(from_parent, \u0026c, 1) != 1)\n+\t\treturn CHILD_PIPE;\n+\treturn CHILD_OK;\n+}\n+\n+/*\n+ * In its own mount namespace the child mounts a tmpfs on /mnt_dir/vol,\n+ * puts a filesystem image on it, binds a loop device to the image and\n+ * mounts that loop device below. The loop device's backing file is a\n+ * reference on the mount the image is on, held by the loop device, held\n+ * by the mounted filesystem, held by the mount below.\n+ */\n+static int loop_child(int to_parent, int from_parent)\n+{\n+\tchar c;\n+\tint n;\n+\n+\tif (unshare(CLONE_NEWNS) || mount(\"\", \"/\", NULL, MS_REC | MS_PRIVATE, NULL))\n+\t\treturn CHILD_NS;\n+\tif (mkdir(\"/mnt_dir/vol\", 0755) || mount(\"tmpfs\", \"/mnt_dir/vol\", \"tmpfs\", 0, NULL))\n+\t\treturn CHILD_NS;\n+\tn = loop_mount(\"/mnt_dir/vol/img\", \"/mnt_dir/vol/mnt\");\n+\tif (n \u003c 0)\n+\t\treturn -n;\n+\n+\tif (write(to_parent, \u0026n, sizeof(n)) != sizeof(n))\n+\t\treturn CHILD_PIPE;\n+\t/* keep the namespace alive while the parent removes the directory */\n+\tif (read(from_parent, \u0026c, 1) != 1)\n+\t\treturn CHILD_PIPE;\n+\treturn CHILD_OK;\n+}\n+\n+/*\n+ * An exclusive open of the device fails while a filesystem holds it, and\n+ * the only filesystem that ever did is the one mounted below the dead\n+ * mount. Give a release in flight a moment. Then the device must clear\n+ * right away rather than only be marked for autoclear.\n+ */\n+static void assert_loop_released(struct __test_metadata *_metadata,\n+\t\t\t\t FIXTURE_DATA(loop_cycle) *self)\n+{\n+\tint lfd;\n+\n+\tfor (int i = 0; i \u003c 20; i++) {\n+\t\tlfd = open(self-\u003edev, O_RDONLY | O_EXCL);\n+\t\tif (lfd \u003e= 0)\n+\t\t\tbreak;\n+\t\tusleep(100000);\n+\t}\n+\tEXPECT_GE(lfd, 0)\n+\t\tTH_LOG(\"%s is still held by the loop mount below the dead mount: nothing refers to either mount and nothing can release them\",\n+\t\t self-\u003edev);\n+\tif (lfd \u003e= 0)\n+\t\tclose(lfd);\n+\n+\tlfd = open(self-\u003edev, O_RDWR);\n+\tASSERT_GE(lfd, 0);\n+\tASSERT_EQ(ioctl(lfd, LOOP_CLR_FD), 0);\n+\tclose(lfd);\n+\tASSERT_TRUE(loop_released(self-\u003esysfs, 5000))\n+\t\tTH_LOG(\"%s kept its backing file after LOOP_CLR_FD: the filesystem on it is still mounted somewhere nobody can reach\",\n+\t\t self-\u003edev);\n+}\n+\n+/*\n+ * rmdir of /mnt_dir/vol from here, where it is not a mountpoint, detaches\n+ * the child's tmpfs with the loop mount connected below it. Once the child\n+ * is gone nothing refers to either mount. The loop device must then be\n+ * free to give up its backing file, which only happens when the mounted\n+ * filesystem below the detached tmpfs has been released.\n+ */\n+TEST_F(loop_cycle, detached_loop_mount_released)\n+{\n+\tint to_parent[2], to_child[2];\n+\tchar buf[PATH_MAX];\n+\tint status, n = -1;\n+\tpid_t pid;\n+\n+\tASSERT_EQ(pipe(to_parent), 0);\n+\tASSERT_EQ(pipe(to_child), 0);\n+\n+\tpid = fork();\n+\tASSERT_GE(pid, 0);\n+\tif (pid == 0) {\n+\t\tclose(to_parent[0]);\n+\t\tclose(to_child[1]);\n+\t\t_exit(loop_child(to_parent[1], to_child[0]));\n+\t}\n+\tclose(to_parent[1]);\n+\tclose(to_child[0]);\n+\n+\tif (read(to_parent[0], \u0026n, sizeof(n)) != sizeof(n)) {\n+\t\twaitpid(pid, \u0026status, 0);\n+\t\tif (WIFEXITED(status) \u0026\u0026 WEXITSTATUS(status) == CHILD_MOUNT)\n+\t\t\tSKIP(return, \"test requires a FAT filesystem\");\n+\t\tASSERT_EQ(status, 0);\n+\t}\n+\tsnprintf(self-\u003edev, sizeof(self-\u003edev), \"/dev/loop%d\", n);\n+\tsnprintf(self-\u003esysfs, sizeof(self-\u003esysfs), \"/sys/block/loop%d/loop/backing_file\", n);\n+\tASSERT_EQ(read_sysfs(self-\u003esysfs, buf, sizeof(buf)), 0);\n+\tASSERT_NE(strstr(buf, \"/mnt_dir/vol/img\"), NULL);\n+\n+\t/* not a mountpoint in this namespace, so the directory can go */\n+\tASSERT_EQ(rmdir(\"/mnt_dir/vol\"), 0);\n+\n+\t/* the child leaves: its namespace and every reference it held are gone */\n+\tASSERT_EQ(write(to_child[1], \"\", 1), 1);\n+\tASSERT_EQ(waitpid(pid, \u0026status, 0), pid);\n+\tASSERT_EQ(status, 0);\n+\tclose(to_parent[0]);\n+\tclose(to_child[1]);\n+\n+\t/* nothing can reach the two mounts any more */\n+\tASSERT_EQ(access(\"/mnt_dir/vol\", F_OK), -1);\n+\tASSERT_FALSE(mounted_anywhere(self-\u003edev));\n+\n+\tassert_loop_released(_metadata, self);\n+}\n+\n+/*\n+ * The same two mounts in a detached tree: a clone of /mnt_dir/vol from\n+ * open_tree(), the image opened through the clone so that the loop device\n+ * holds the clone, and the loop mount moved below the clone. The last\n+ * close of the tree's fd dissolves the tree with the loop mount left\n+ * connected below the dead clone, and nothing refers to either afterwards.\n+ */\n+TEST_F(loop_cycle, dissolved_tree_loop_mount_released)\n+{\n+\tint tfd, ifd, fsfd, mfd, n;\n+\tchar buf[PATH_MAX];\n+\n+\tfsfd = sys_fsopen(\"vfat\", 0);\n+\tif (fsfd \u003c 0)\n+\t\tfsfd = sys_fsopen(\"msdos\", 0);\n+\tif (fsfd \u003c 0)\n+\t\tSKIP(return, \"test requires a FAT filesystem\");\n+\n+\tASSERT_EQ(mkdir(\"/mnt_dir/vol\", 0755), 0);\n+\tASSERT_EQ(mount(\"tmpfs\", \"/mnt_dir/vol\", \"tmpfs\", 0, NULL), 0);\n+\ttfd = sys_open_tree(AT_FDCWD, \"/mnt_dir/vol\", OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);\n+\tASSERT_GE(tfd, 0);\n+\n+\t/* the image, opened through the clone: the loop device holds the clone */\n+\tifd = openat(tfd, \"img\", O_RDWR | O_CREAT | O_EXCL, 0600);\n+\tASSERT_GE(ifd, 0);\n+\tASSERT_EQ(write_fat12(ifd), 0);\n+\tn = loop_bind(ifd);\n+\tclose(ifd);\n+\tASSERT_GE(n, 0);\n+\tsnprintf(self-\u003edev, sizeof(self-\u003edev), \"/dev/loop%d\", n);\n+\tsnprintf(self-\u003esysfs, sizeof(self-\u003esysfs), \"/sys/block/loop%d/loop/backing_file\", n);\n+\n+\t/* the loop mount, moved below the clone */\n+\tASSERT_EQ(mkdirat(tfd, \"mnt\", 0755), 0);\n+\tASSERT_EQ(sys_fsconfig(fsfd, FSCONFIG_SET_STRING, \"source\", self-\u003edev, 0), 0);\n+\tASSERT_EQ(sys_fsconfig(fsfd, FSCONFIG_CMD_CREATE, NULL, NULL, 0), 0);\n+\tmfd = sys_fsmount(fsfd, 0, 0);\n+\tASSERT_GE(mfd, 0);\n+\tclose(fsfd);\n+\tASSERT_EQ(sys_move_mount(mfd, \"\", tfd, \"mnt\", MOVE_MOUNT_F_EMPTY_PATH), 0);\n+\tclose(mfd);\n+\n+\tASSERT_EQ(read_sysfs(self-\u003esysfs, buf, sizeof(buf)), 0);\n+\tASSERT_NE(strstr(buf, \"img\"), NULL);\n+\n+\t/* the last fd of the tree: both mounts die, the loop mount connected */\n+\tclose(tfd);\n+\n+\t/* nothing can reach the two mounts any more */\n+\tASSERT_FALSE(mounted_anywhere(self-\u003edev));\n+\n+\tassert_loop_released(_metadata, self);\n+}\n+\n+/*\n+ * The cycle in two steps: rmdir of /mnt_dir/vol leaves the loop mount\n+ * below it connected while its image's mount, /mnt_dir/vol2, is alive;\n+ * then rmdir of /mnt_dir/vol2 takes that one with the loop mount whose\n+ * image is on the dead /mnt_dir/vol. Each dead mount now owns a loop\n+ * mount whose filesystem pins the other.\n+ */\n+TEST_F(loop_cycle, crossed_images_released)\n+{\n+\tint to_parent[2], to_child[2];\n+\tchar sysfs[2][64], dev[2][32];\n+\tint status, n[2] = { -1, -1 };\n+\tpid_t pid;\n+\n+\tASSERT_EQ(pipe(to_parent), 0);\n+\tASSERT_EQ(pipe(to_child), 0);\n+\n+\tpid = fork();\n+\tASSERT_GE(pid, 0);\n+\tif (pid == 0) {\n+\t\tclose(to_parent[0]);\n+\t\tclose(to_child[1]);\n+\t\t_exit(crossed_child(to_parent[1], to_child[0]));\n+\t}\n+\tclose(to_parent[1]);\n+\tclose(to_child[0]);\n+\n+\tif (read(to_parent[0], n, sizeof(n)) != sizeof(n)) {\n+\t\twaitpid(pid, \u0026status, 0);\n+\t\tif (WIFEXITED(status) \u0026\u0026 WEXITSTATUS(status) == CHILD_MOUNT)\n+\t\t\tSKIP(return, \"test requires a FAT filesystem\");\n+\t\tASSERT_EQ(status, 0);\n+\t}\n+\tfor (int i = 0; i \u003c 2; i++) {\n+\t\tsnprintf(dev[i], sizeof(dev[i]), \"/dev/loop%d\", n[i]);\n+\t\tsnprintf(sysfs[i], sizeof(sysfs[i]), \"/sys/block/loop%d/loop/backing_file\", n[i]);\n+\t}\n+\n+\t/* step one: the mount with the first loop mount below it goes */\n+\tASSERT_EQ(rmdir(\"/mnt_dir/vol\"), 0);\n+\n+\t/* step two: the other one, with the loop mount whose image is on the first */\n+\tASSERT_EQ(rmdir(\"/mnt_dir/vol2\"), 0);\n+\n+\t/* the child leaves: its namespace and every reference it held are gone */\n+\tASSERT_EQ(write(to_child[1], \"\", 1), 1);\n+\tASSERT_EQ(waitpid(pid, \u0026status, 0), pid);\n+\tASSERT_EQ(status, 0);\n+\tclose(to_parent[0]);\n+\tclose(to_child[1]);\n+\n+\t/* nothing can reach the four mounts any more */\n+\tfor (int i = 0; i \u003c 2; i++) {\n+\t\tASSERT_FALSE(mounted_anywhere(dev[i]));\n+\t\tstrcpy(self-\u003edev, dev[i]);\n+\t\tstrcpy(self-\u003esysfs, sysfs[i]);\n+\t\tassert_loop_released(_metadata, self);\n+\t}\n+}\n+\n+/*\n+ * The holders. Each keeps a file or a path on a mount P for as long as\n+ * its own filesystem or device lives, and each has that filesystem or\n+ * device mounted at C below P. Once another namespace's rmdir has\n+ * detached P with C connected below it and the child is gone, P is owned\n+ * by nobody, C by P, and P is kept by whatever the holder still holds.\n+ *\n+ * P is a loop mount so that its death can be observed: the loop device\n+ * gives its backing file up when P's superblock goes. The image sits on\n+ * a tmpfs next to P, not above it, so the loop device's own reference is\n+ * not part of the picture.\n+ */\n+enum holder {\n+\tHOLDER_AUTOFS,\t\t/* a FIFO on P as the daemon's pipe */\n+\tHOLDER_ZRAM,\t\t/* a device node on P as the writeback device */\n+\tHOLDER_ECRYPTFS,\t/* a directory on P as the lower directory */\n+\tHOLDER_BINFMT_MISC,\t/* an executable on P as an 'F' interpreter */\n+\tHOLDER_FUSE,\t\t/* a file on P as a passthrough backing file */\n+\tHOLDER_ZLOOP,\t\t/* a directory on P for the zone files */\n+\tHOLDER_GADGET,\t\t/* a file on P as a mass storage LUN, over dummy_hcd */\n+\tHOLDER_MD,\t\t/* a file on P as an array's bitmap file */\n+};\n+\n+#define HOLDER_IMG\t\"/mnt_dir/img/p.img\"\n+#define HOLDER_MNT\t\"/mnt_dir/p\"\n+#define HOLDER_BELOW\t\"/mnt_dir/p/c\"\n+\n+static int write_file(const char *path, const char *s)\n+{\n+\tint fd = open(path, O_WRONLY);\n+\tssize_t n;\n+\n+\tif (fd \u003c 0)\n+\t\treturn -1;\n+\tn = write(fd, s, strlen(s));\n+\tclose(fd);\n+\treturn n == (ssize_t)strlen(s) ? 0 : -1;\n+}\n+\n+/* Bind a free loop device to @img; the device number. */\n+static int loop_attach(const char *img)\n+{\n+\tint ifd, n;\n+\n+\tifd = open(img, O_RDWR);\n+\tif (ifd \u003c 0)\n+\t\treturn -1;\n+\tn = loop_bind(ifd);\n+\tclose(ifd);\n+\treturn n;\n+}\n+\n+static int holder_autofs(void)\n+{\n+\tchar opts[64];\n+\tint pfd;\n+\n+\tif (mkfifo(HOLDER_MNT \"/pipe\", 0600))\n+\t\treturn CHILD_HOLDER;\n+\tpfd = open(HOLDER_MNT \"/pipe\", O_RDWR);\n+\tif (pfd \u003c 0)\n+\t\treturn CHILD_HOLDER;\n+\tsnprintf(opts, sizeof(opts), \"fd=%d,minproto=5,maxproto=5\", pfd);\n+\tif (mount(\"autofs\", HOLDER_BELOW, \"autofs\", 0, opts))\n+\t\treturn errno == ENODEV ? CHILD_SKIP : CHILD_HOLDER;\n+\tclose(pfd);\t/* the mount keeps its own */\n+\treturn CHILD_OK;\n+}\n+\n+/*\n+ * zram's writeback device has to be a block device node, and that node has\n+ * to be on P. Point it at a second loop device.\n+ */\n+static int holder_zram(void)\n+{\n+\tchar buf[64];\n+\tint fd, n;\n+\n+\tif (access(\"/sys/block/zram0/backing_dev\", W_OK))\n+\t\treturn CHILD_SKIP;\n+\t/* somebody else's device, leave it alone */\n+\tif (read_sysfs(\"/sys/block/zram0/initstate\", buf, sizeof(buf)) || buf[0] != '0')\n+\t\treturn CHILD_SKIP;\n+\tfd = open(\"/mnt_dir/img/wb.img\", O_RDWR | O_CREAT | O_EXCL, 0600);\n+\tif (fd \u003c 0 || ftruncate(fd, IMAGE_SIZE))\n+\t\treturn CHILD_HOLDER;\n+\tclose(fd);\n+\tn = loop_attach(\"/mnt_dir/img/wb.img\");\n+\tif (n \u003c 0)\n+\t\treturn CHILD_HOLDER;\n+\tif (mknod(HOLDER_MNT \"/wbdev\", S_IFBLK | 0600, makedev(7, n)))\n+\t\treturn CHILD_HOLDER;\n+\tif (write_file(\"/sys/block/zram0/backing_dev\", HOLDER_MNT \"/wbdev\"))\n+\t\treturn CHILD_HOLDER;\n+\tsnprintf(buf, sizeof(buf), \"%d\", 4 * 1024 * 1024);\n+\tif (write_file(\"/sys/block/zram0/disksize\", buf))\n+\t\treturn CHILD_HOLDER;\n+\tfd = open(\"/dev/zram0\", O_RDWR);\n+\tif (fd \u003c 0 || write_fat12_4k(fd, 1024))\t/* zram has 4 KiB blocks */\n+\t\treturn CHILD_HOLDER;\n+\tclose(fd);\n+\tif (mount(\"/dev/zram0\", HOLDER_BELOW, \"vfat\", 0, NULL) \u0026\u0026\n+\t mount(\"/dev/zram0\", HOLDER_BELOW, \"msdos\", 0, NULL))\n+\t\treturn CHILD_HOLDER;\n+\treturn CHILD_OK;\n+}\n+\n+/* The kernel's auth token layout, which userspace has to match byte for byte. */\n+struct ecryptfs_auth_tok {\n+\t__u16 version;\n+\t__u16 token_type;\n+\t__u32 flags;\n+\tstruct {\n+\t\t__u32 flags, encrypted_key_size, decrypted_key_size;\n+\t\t__u8 encrypted_key[512], decrypted_key[64];\n+\t} session_key;\n+\t__u8 reserved[32];\n+\tstruct {\n+\t\t__u32 password_bytes;\n+\t\t__s32 hash_algo;\n+\t\t__u32 hash_iterations, session_key_encryption_key_bytes, flags;\n+\t\t__u8 session_key_encryption_key[64];\n+\t\t__u8 signature[17];\n+\t\t__u8 salt[8];\n+\t} password;\n+} __attribute__((packed));\n+\n+#define ECRYPTFS_SIG\t\"0123456789abcdef\"\n+\n+static int holder_ecryptfs(void)\n+{\n+\tstruct ecryptfs_auth_tok tok = {\n+\t\t.version = 0x0004,\n+\t\t.token_type = 0,\t\t/* ECRYPTFS_PASSWORD */\n+\t\t.password.session_key_encryption_key_bytes = 16,\n+\t\t.password.flags = 0x02,\t\t/* ECRYPTFS_SESSION_KEY_ENCRYPTION_KEY_SET */\n+\t\t.password.signature = ECRYPTFS_SIG,\n+\t};\n+\n+\tif (syscall(__NR_add_key, \"user\", ECRYPTFS_SIG, \u0026tok, sizeof(tok),\n+\t\t KEY_SPEC_SESSION_KEYRING) \u003c 0)\n+\t\treturn CHILD_HOLDER;\n+\tif (mkdir(HOLDER_MNT \"/lower\", 0755))\n+\t\treturn CHILD_HOLDER;\n+\tif (mount(HOLDER_MNT \"/lower\", HOLDER_BELOW, \"ecryptfs\", 0,\n+\t\t \"ecryptfs_sig=\" ECRYPTFS_SIG \",ecryptfs_cipher=aes,ecryptfs_key_bytes=16\"))\n+\t\treturn errno == ENODEV ? CHILD_SKIP : CHILD_HOLDER;\n+\treturn CHILD_OK;\n+}\n+\n+/*\n+ * binfmt_misc instances are per user namespace, so the mount below P is\n+ * made from a new one, which gets a copy of P.\n+ */\n+static int holder_binfmt_misc(void)\n+{\n+\tchar buf[4096];\n+\tint in, out;\n+\tssize_t n;\n+\n+\tin = open(\"/proc/self/exe\", O_RDONLY);\n+\tout = open(HOLDER_MNT \"/interp\", O_WRONLY | O_CREAT | O_EXCL, 0755);\n+\tif (in \u003c 0 || out \u003c 0)\n+\t\treturn CHILD_HOLDER;\n+\twhile ((n = read(in, buf, sizeof(buf))) \u003e 0)\n+\t\tif (write(out, buf, n) != n)\n+\t\t\treturn CHILD_HOLDER;\n+\tclose(in);\n+\tclose(out);\n+\n+\tif (unshare(CLONE_NEWUSER | CLONE_NEWNS))\n+\t\treturn errno == EINVAL ? CHILD_SKIP : CHILD_HOLDER;\n+\tif (write_file(\"/proc/self/setgroups\", \"deny\") ||\n+\t write_file(\"/proc/self/uid_map\", \"0 0 1\") ||\n+\t write_file(\"/proc/self/gid_map\", \"0 0 1\"))\n+\t\treturn CHILD_HOLDER;\n+\tif (mount(\"binfmt_misc\", HOLDER_BELOW, \"binfmt_misc\", 0, NULL))\n+\t\treturn errno == ENODEV ? CHILD_SKIP : CHILD_HOLDER;\n+\tif (write_file(HOLDER_BELOW \"/register\", \":cycle:E::cyc::\" HOLDER_MNT \"/interp:F\"))\n+\t\treturn CHILD_HOLDER;\n+\treturn CHILD_OK;\n+}\n+\n+/*\n+ * A fuse server that only ever answers FUSE_INIT, with passthrough on, and\n+ * then registers a file on P as a backing file. The registration alone\n+ * makes the fuse superblock hold the file.\n+ */\n+static int holder_fuse(void)\n+{\n+\tstruct fuse_backing_map map = {};\n+\tstruct fuse_in_header *ih;\n+\tstruct fuse_init_out init = {\n+\t\t.major = FUSE_KERNEL_VERSION,\n+\t\t.minor = FUSE_KERNEL_MINOR_VERSION,\n+\t\t.flags = FUSE_INIT_EXT,\n+\t\t.flags2 = FUSE_PASSTHROUGH \u003e\u003e 32,\n+\t\t.max_write = 4096,\n+\t\t.max_stack_depth = 1,\n+\t};\n+\tstruct fuse_out_header oh = { .len = sizeof(oh) + sizeof(init) };\n+\tstruct iovec iov[2] = { { \u0026oh, sizeof(oh) }, { \u0026init, sizeof(init) } };\n+\tchar opts[64], buf[8192];\n+\tint ffd, bfd;\n+\tssize_t n;\n+\n+\tbfd = open(HOLDER_MNT \"/backing\", O_RDWR | O_CREAT | O_EXCL, 0600);\n+\tif (bfd \u003c 0)\n+\t\treturn CHILD_HOLDER;\n+\tffd = open(\"/dev/fuse\", O_RDWR);\n+\tif (ffd \u003c 0)\n+\t\treturn CHILD_SKIP;\n+\tsnprintf(opts, sizeof(opts), \"fd=%d,rootmode=40000,user_id=0,group_id=0\", ffd);\n+\tif (mount(\"fuse\", HOLDER_BELOW, \"fuse\", 0, opts))\n+\t\treturn errno == ENODEV ? CHILD_SKIP : CHILD_HOLDER;\n+\n+\tn = read(ffd, buf, sizeof(buf));\n+\tih = (void *)buf;\n+\tif (n \u003c (ssize_t)sizeof(*ih) || ih-\u003eopcode != FUSE_INIT)\n+\t\treturn CHILD_HOLDER;\n+\toh.unique = ih-\u003eunique;\n+\tif (writev(ffd, iov, 2) != (ssize_t)oh.len)\n+\t\treturn CHILD_HOLDER;\n+\n+\tmap.fd = bfd;\n+\tif (ioctl(ffd, FUSE_DEV_IOC_BACKING_OPEN, \u0026map) \u003c 0)\n+\t\treturn errno == EPERM ? CHILD_SKIP : CHILD_HOLDER;\n+\tclose(bfd);\t/* the connection keeps its own */\n+\treturn CHILD_OK;\t/* ffd stays open until the child exits */\n+}\n+\n+/* Wait for a device node the kernel is about to create. */\n+static int open_when_there(const char *dev, int flags, int ms)\n+{\n+\tint fd;\n+\n+\tfor (; ms \u003e 0; ms -= 100) {\n+\t\tfd = open(dev, flags);\n+\t\tif (fd \u003e= 0)\n+\t\t\treturn fd;\n+\t\tusleep(100000);\n+\t}\n+\treturn -1;\n+}\n+\n+/*\n+ * zloop keeps every zone file open. One conventional zone is enough for a\n+ * FAT image, the sequential one stays empty.\n+ */\n+static int holder_zloop(void)\n+{\n+\tint fd;\n+\n+\tif (access(\"/dev/zloop-control\", W_OK))\n+\t\treturn CHILD_SKIP;\n+\tif (mkdir(HOLDER_MNT \"/zl\", 0755) || mkdir(HOLDER_MNT \"/zl/0\", 0755))\n+\t\treturn CHILD_HOLDER;\n+\tif (write_file(\"/dev/zloop-control\",\n+\t\t \"add id=0,capacity_mb=8,zone_size_mb=4,conv_zones=1,base_dir=\" HOLDER_MNT \"/zl\"))\n+\t\treturn CHILD_HOLDER;\n+\tfd = open_when_there(\"/dev/zloop0\", O_RDWR, 5000);\n+\tif (fd \u003c 0 || write_fat12_4k(fd, 1024))\t/* 4 KiB blocks, like P */\n+\t\treturn CHILD_HOLDER;\n+\tclose(fd);\n+\tif (mount(\"/dev/zloop0\", HOLDER_BELOW, \"vfat\", 0, NULL) \u0026\u0026\n+\t mount(\"/dev/zloop0\", HOLDER_BELOW, \"msdos\", 0, NULL))\n+\t\treturn CHILD_HOLDER;\n+\treturn CHILD_OK;\n+}\n+\n+#define GADGET\t\"/sys/kernel/config/usb_gadget/g1\"\n+\n+/* The disk usb-storage created for the gadget, by the LUN's inquiry string. */\n+static int find_gadget_disk(char *dev, size_t len, int ms)\n+{\n+\tchar path[PATH_MAX], model[64];\n+\tstruct dirent *de;\n+\tDIR *d;\n+\n+\tfor (; ms \u003e 0; ms -= 100, usleep(100000)) {\n+\t\td = opendir(\"/sys/block\");\n+\t\tif (!d)\n+\t\t\treturn -1;\n+\t\twhile ((de = readdir(d))) {\n+\t\t\tif (strncmp(de-\u003ed_name, \"sd\", 2))\n+\t\t\t\tcontinue;\n+\t\t\tsnprintf(path, sizeof(path), \"/sys/block/%s/device/model\", de-\u003ed_name);\n+\t\t\tif (read_sysfs(path, model, sizeof(model)) ||\n+\t\t\t strncmp(model, \"File-Stor Gadget\", 16))\n+\t\t\t\tcontinue;\n+\t\t\tsnprintf(dev, len, \"/dev/%s\", de-\u003ed_name);\n+\t\t\tclosedir(d);\n+\t\t\treturn 0;\n+\t\t}\n+\t\tclosedir(d);\n+\t}\n+\treturn -1;\n+}\n+\n+/*\n+ * A mass storage gadget bound to the dummy UDC, so that this kernel is\n+ * also the USB host that sees the LUN as a SCSI disk. sd locks the\n+ * medium on open, which is what keeps the LUN's file from being ejected.\n+ */\n+#define GADGET_STEP(x) do {\t\t\t\t\t\t\\\n+\tif (x) {\t\t\t\t\t\t\t\\\n+\t\tfprintf(stderr, \"gadget: %s failed: %s\\n\", #x, strerror(errno)); \\\n+\t\treturn CHILD_HOLDER;\t\t\t\t\t\\\n+\t}\t\t\t\t\t\t\t\t\\\n+} while (0)\n+\n+static int holder_gadget(void)\n+{\n+\tchar dev[PATH_MAX];\n+\tint fd;\n+\n+\tif (access(\"/sys/kernel/config\", F_OK) ||\n+\t (mount(\"configfs\", \"/sys/kernel/config\", \"configfs\", 0, NULL) \u0026\u0026 errno != EBUSY))\n+\t\treturn CHILD_SKIP;\n+\tif (access(\"/sys/kernel/config/usb_gadget\", F_OK) ||\n+\t access(\"/sys/class/udc/dummy_udc.0\", F_OK))\n+\t\treturn CHILD_SKIP;\n+\n+\tfd = open(HOLDER_MNT \"/lun.img\", O_RDWR | O_CREAT | O_EXCL, 0600);\n+\tif (fd \u003c 0 || write_fat12(fd))\n+\t\treturn CHILD_HOLDER;\n+\tclose(fd);\n+\n+\tGADGET_STEP(mkdir(GADGET, 0755));\n+\tGADGET_STEP(write_file(GADGET \"/idVendor\", \"0x1d6b\"));\n+\tGADGET_STEP(write_file(GADGET \"/idProduct\", \"0x0104\"));\n+\tGADGET_STEP(mkdir(GADGET \"/strings/0x409\", 0755));\n+\tGADGET_STEP(write_file(GADGET \"/strings/0x409/serialnumber\", \"1\"));\n+\tGADGET_STEP(write_file(GADGET \"/strings/0x409/manufacturer\", \"kselftest\"));\n+\tGADGET_STEP(write_file(GADGET \"/strings/0x409/product\", \"cycle\"));\n+\tGADGET_STEP(mkdir(GADGET \"/configs/c.1\", 0755));\n+\tGADGET_STEP(mkdir(GADGET \"/configs/c.1/strings/0x409\", 0755));\n+\tGADGET_STEP(write_file(GADGET \"/configs/c.1/strings/0x409/configuration\", \"c\"));\n+\tGADGET_STEP(mkdir(GADGET \"/functions/mass_storage.0\", 0755));\n+\tGADGET_STEP(write_file(GADGET \"/functions/mass_storage.0/lun.0/removable\", \"1\"));\n+\tGADGET_STEP(write_file(GADGET \"/functions/mass_storage.0/lun.0/file\", HOLDER_MNT \"/lun.img\"));\n+\tGADGET_STEP(symlink(GADGET \"/functions/mass_storage.0\", GADGET \"/configs/c.1/mass_storage.0\"));\n+\tGADGET_STEP(write_file(GADGET \"/UDC\", \"dummy_udc.0\"));\n+\n+\t/* usb-storage waits a second before it scans the device */\n+\tGADGET_STEP(find_gadget_disk(dev, sizeof(dev), 15000));\n+\tfd = open_when_there(dev, O_RDONLY, 5000);\n+\tGADGET_STEP(fd \u003c 0);\n+\tclose(fd);\n+\tif (mount(dev, HOLDER_BELOW, \"vfat\", 0, NULL) \u0026\u0026\n+\t mount(dev, HOLDER_BELOW, \"msdos\", 0, NULL))\n+\t\treturn CHILD_HOLDER;\n+\treturn CHILD_OK;\n+}\n+\n+#define BITMAP_MAGIC\t0x6d746962\n+\n+/*\n+ * A RAID1 of one loop device, not persistent, with its bitmap in a file\n+ * on P. The bitmap file needs a superblock the kernel accepts; sync_size,\n+ * uuid and events are not looked at for a non-persistent array.\n+ */\n+static int holder_md(void)\n+{\n+\tstruct {\n+\t\t__u32 magic, version;\n+\t\t__u8 uuid[16];\n+\t\t__u64 events, events_cleared, sync_size;\n+\t\t__u32 state, chunksize, daemon_sleep, write_behind;\n+\t} bsb = {\n+\t\t.magic = BITMAP_MAGIC,\n+\t\t.version = 4,\n+\t\t.chunksize = 64 * 1024,\n+\t\t.daemon_sleep = 5,\n+\t};\n+\tmdu_array_info_t info = {\n+\t\t.level = 1,\n+\t\t.raid_disks = 1,\n+\t\t.size = 8 * 1024,\t\t/* KiB */\n+\t\t.not_persistent = 1,\n+\t};\n+\tmdu_disk_info_t disk = {\n+\t\t.major = 7,\n+\t\t.state = (1 \u003c\u003c MD_DISK_ACTIVE) | (1 \u003c\u003c MD_DISK_SYNC),\n+\t};\n+\tint fd, mdfd, bfd, n;\n+\tchar buf[4096];\n+\n+\tfd = open(\"/mnt_dir/img/md.img\", O_RDWR | O_CREAT | O_EXCL, 0600);\n+\tif (fd \u003c 0 || ftruncate(fd, 8 * 1024 * 1024))\n+\t\treturn CHILD_HOLDER;\n+\tclose(fd);\n+\tn = loop_attach(\"/mnt_dir/img/md.img\");\n+\tif (n \u003c 0)\n+\t\treturn CHILD_HOLDER;\n+\tdisk.minor = n;\n+\n+\tbfd = open(HOLDER_MNT \"/bitmap\", O_RDWR | O_CREAT | O_EXCL, 0600);\n+\tif (bfd \u003c 0 || write(bfd, \u0026bsb, sizeof(bsb)) != sizeof(bsb) || ftruncate(bfd, 4096))\n+\t\treturn CHILD_HOLDER;\n+\n+\tif (read_sysfs(\"/proc/mdstat\", buf, sizeof(buf)) || !strstr(buf, \"[raid1]\")) {\n+\t\tfprintf(stderr, \"md: no raid1 personality: %s\\n\", buf);\n+\t\treturn CHILD_SKIP;\n+\t}\n+\tif (access(\"/dev/md0\", F_OK) \u0026\u0026 mknod(\"/dev/md0\", S_IFBLK | 0600, makedev(9, 0)))\n+\t\treturn CHILD_HOLDER;\n+\tmdfd = open(\"/dev/md0\", O_RDWR);\n+\tif (mdfd \u003c 0)\n+\t\treturn CHILD_SKIP;\n+\t/* the bitmap ops are only installed once a bitmap type is chosen */\n+\twrite_file(\"/sys/block/md0/md/bitmap_type\", \"bitmap\");\n+\t/* EBUSY: somebody else's array, leave it alone */\n+\tif (ioctl(mdfd, SET_ARRAY_INFO, \u0026info))\n+\t\treturn errno == EBUSY ? CHILD_SKIP : CHILD_HOLDER;\n+\tif (ioctl(mdfd, ADD_NEW_DISK, \u0026disk))\n+\t\treturn CHILD_HOLDER;\n+\t/* attach the bitmap file before the array runs, the way mdadm does */\n+\tif (ioctl(mdfd, SET_BITMAP_FILE, bfd)) {\n+\t\tfprintf(stderr, \"md: SET_BITMAP_FILE: %s\\n\", strerror(errno));\n+\t\treturn errno == EINVAL ? CHILD_SKIP : CHILD_HOLDER;\n+\t}\n+\tclose(bfd);\t/* the array keeps its own */\n+\tif (ioctl(mdfd, RUN_ARRAY, NULL)) {\n+\t\tfprintf(stderr, \"md: RUN_ARRAY: %s\\n\", strerror(errno));\n+\t\treturn CHILD_HOLDER;\n+\t}\n+\tif (write_fat12(mdfd))\n+\t\treturn CHILD_HOLDER;\n+\tclose(mdfd);\n+\tif (mount(\"/dev/md0\", HOLDER_BELOW, \"vfat\", 0, NULL) \u0026\u0026\n+\t mount(\"/dev/md0\", HOLDER_BELOW, \"msdos\", 0, NULL))\n+\t\treturn CHILD_HOLDER;\n+\treturn CHILD_OK;\n+}\n+\n+/*\n+ * In its own mount namespace the child puts the image on a tmpfs next to\n+ * P, mounts P from a loop device, and sets the holder up with its own\n+ * filesystem or device mounted at C below P.\n+ */\n+static int holder_child(int to_parent, int from_parent, enum holder holder)\n+{\n+\tbool fifo = holder == HOLDER_AUTOFS || holder == HOLDER_ZRAM;\n+\t/* room for a 4 MiB zone file or a floppy image on P */\n+\tbool big = holder == HOLDER_ZLOOP || holder == HOLDER_GADGET;\n+\tconst char *type = fifo ? \"minix\" : \"vfat\";\n+\tchar dev[32], c;\n+\tint ifd, n, ret;\n+\n+\tif (unshare(CLONE_NEWNS) || mount(\"\", \"/\", NULL, MS_REC | MS_PRIVATE, NULL))\n+\t\treturn CHILD_NS;\n+\tif (mkdir(\"/mnt_dir/img\", 0755) || mount(\"tmpfs\", \"/mnt_dir/img\", \"tmpfs\", 0, NULL))\n+\t\treturn CHILD_NS;\n+\n+\tifd = open(HOLDER_IMG, O_RDWR | O_CREAT | O_EXCL, 0600);\n+\tif (ifd \u003c 0 || (fifo ? write_minix(ifd) :\n+\t\t\tbig ? write_fat12_4k(ifd, 3072) : write_fat12(ifd)))\n+\t\treturn CHILD_IMAGE;\n+\tclose(ifd);\n+\tn = loop_attach(HOLDER_IMG);\n+\tif (n \u003c 0)\n+\t\treturn CHILD_LOOP;\n+\tsnprintf(dev, sizeof(dev), \"/dev/loop%d\", n);\n+\tif (mkdir(HOLDER_MNT, 0755))\n+\t\treturn CHILD_MOUNT;\n+\tif (mount(dev, HOLDER_MNT, type, 0, NULL) \u0026\u0026\n+\t (fifo || mount(dev, HOLDER_MNT, \"msdos\", 0, NULL)))\n+\t\treturn fifo \u0026\u0026 errno == ENODEV ? CHILD_SKIP : CHILD_MOUNT;\n+\tif (mkdir(HOLDER_BELOW, 0755))\n+\t\treturn CHILD_MOUNT;\n+\n+\tswitch (holder) {\n+\tcase HOLDER_AUTOFS:\n+\t\tret = holder_autofs();\n+\t\tbreak;\n+\tcase HOLDER_ZRAM:\n+\t\tret = holder_zram();\n+\t\tbreak;\n+\tcase HOLDER_ECRYPTFS:\n+\t\tret = holder_ecryptfs();\n+\t\tbreak;\n+\tcase HOLDER_BINFMT_MISC:\n+\t\tret = holder_binfmt_misc();\n+\t\tbreak;\n+\tcase HOLDER_FUSE:\n+\t\tret = holder_fuse();\n+\t\tbreak;\n+\tcase HOLDER_ZLOOP:\n+\t\tret = holder_zloop();\n+\t\tbreak;\n+\tcase HOLDER_GADGET:\n+\t\tret = holder_gadget();\n+\t\tbreak;\n+\tcase HOLDER_MD:\n+\t\tret = holder_md();\n+\t\tbreak;\n+\tdefault:\n+\t\tret = CHILD_HOLDER;\n+\t}\n+\tif (ret != CHILD_OK)\n+\t\treturn ret;\n+\n+\tif (write(to_parent, \u0026n, sizeof(n)) != sizeof(n))\n+\t\treturn CHILD_PIPE;\n+\tif (read(from_parent, \u0026c, 1) != 1)\n+\t\treturn CHILD_PIPE;\n+\treturn CHILD_OK;\n+}\n+\n+/*\n+ * A device keeps its file for as long as it is configured, so once nothing\n+ * below the dead mount is left the device has to be told to let go. With\n+ * the cycle unbroken C's filesystem still holds the device and every one\n+ * of these refuses.\n+ */\n+static int holder_let_go_once(enum holder holder)\n+{\n+\tint fd, ret;\n+\n+\tswitch (holder) {\n+\tcase HOLDER_ZRAM:\n+\t\treturn write_file(\"/sys/block/zram0/reset\", \"1\");\n+\tcase HOLDER_ZLOOP:\n+\t\treturn write_file(\"/dev/zloop-control\", \"remove id=0\");\n+\tcase HOLDER_GADGET:\n+\t\tif (mount(\"configfs\", \"/sys/kernel/config\", \"configfs\", 0, NULL) \u0026\u0026 errno != EBUSY)\n+\t\t\treturn -1;\n+\t\t/* a zero-length write is a no-op for configfs; a newline ejects */\n+\t\treturn write_file(GADGET \"/functions/mass_storage.0/lun.0/file\", \"\\n\");\n+\tcase HOLDER_MD:\n+\t\tfd = open(\"/dev/md0\", O_RDONLY);\n+\t\tif (fd \u003c 0)\n+\t\t\treturn -1;\n+\t\tret = ioctl(fd, STOP_ARRAY);\n+\t\tclose(fd);\n+\t\treturn ret;\n+\tdefault:\n+\t\treturn 0;\n+\t}\n+}\n+\n+/*\n+ * The release of C's filesystem may still be in flight when the child is\n+ * gone, and a device that is still held refuses to let go, so try for a\n+ * while. With the cycle unbroken it refuses for good.\n+ */\n+static void holder_let_go(enum holder holder)\n+{\n+\tfor (int i = 0; i \u003c 50; i++) {\n+\t\tif (!holder_let_go_once(holder))\n+\t\t\treturn;\n+\t\tusleep(100000);\n+\t}\n+}\n+\n+/*\n+ * rmdir of /mnt_dir/p from here, where it is a plain directory, detaches\n+ * P in the child's namespace with C connected below it. Once the child is\n+ * gone the holder's file on P is the only thing left that refers to P,\n+ * and it is dropped only when C's filesystem dies, which waits for P.\n+ * The loop device backing P tells whether that resolved.\n+ */\n+static void holder_cycle(struct __test_metadata *_metadata,\n+\t\t\t FIXTURE_DATA(loop_cycle) *self, enum holder holder)\n+{\n+\tint to_parent[2], from_parent[2], status, n;\n+\tpid_t pid;\n+\n+\tASSERT_EQ(pipe(to_parent), 0);\n+\tASSERT_EQ(pipe(from_parent), 0);\n+\tpid = fork();\n+\tASSERT_GE(pid, 0);\n+\tif (pid == 0) {\n+\t\tclose(to_parent[0]);\n+\t\tclose(from_parent[1]);\n+\t\t_exit(holder_child(to_parent[1], from_parent[0], holder));\n+\t}\n+\tclose(to_parent[1]);\n+\tclose(from_parent[0]);\n+\n+\tif (read(to_parent[0], \u0026n, sizeof(n)) != sizeof(n)) {\n+\t\twaitpid(pid, \u0026status, 0);\n+\t\tif (WIFEXITED(status) \u0026\u0026 WEXITSTATUS(status) == CHILD_SKIP)\n+\t\t\tSKIP(return, \"the kernel lacks what this holder needs\");\n+\t\tASSERT_TRUE(false)\n+\t\t\tTH_LOG(\"child failed to set the holder up: exit status %d\",\n+\t\t\t WIFEXITED(status) ? WEXITSTATUS(status) : -1);\n+\t}\n+\tsnprintf(self-\u003edev, sizeof(self-\u003edev), \"/dev/loop%d\", n);\n+\tsnprintf(self-\u003esysfs, sizeof(self-\u003esysfs), \"/sys/block/loop%d/loop/backing_file\", n);\n+\n+\tASSERT_EQ(rmdir(HOLDER_MNT), 0);\n+\tASSERT_EQ(write(from_parent[1], \"x\", 1), 1);\n+\tASSERT_EQ(waitpid(pid, \u0026status, 0), pid);\n+\tASSERT_EQ(WEXITSTATUS(status), CHILD_OK);\n+\n+\tholder_let_go(holder);\n+\tassert_loop_released(_metadata, self);\n+\tif (holder == HOLDER_GADGET)\n+\t\twrite_file(GADGET \"/UDC\", \"\\n\");\n+}\n+\n+TEST_F(loop_cycle, autofs_pipe_on_dead_mount_released)\n+{\n+\tholder_cycle(_metadata, self, HOLDER_AUTOFS);\n+}\n+\n+TEST_F(loop_cycle, zram_writeback_node_on_dead_mount_released)\n+{\n+\tholder_cycle(_metadata, self, HOLDER_ZRAM);\n+}\n+\n+TEST_F(loop_cycle, ecryptfs_lower_on_dead_mount_released)\n+{\n+\tholder_cycle(_metadata, self, HOLDER_ECRYPTFS);\n+}\n+\n+TEST_F(loop_cycle, binfmt_misc_interpreter_on_dead_mount_released)\n+{\n+\tholder_cycle(_metadata, self, HOLDER_BINFMT_MISC);\n+}\n+\n+TEST_F(loop_cycle, fuse_backing_file_on_dead_mount_released)\n+{\n+\tholder_cycle(_metadata, self, HOLDER_FUSE);\n+}\n+\n+TEST_F(loop_cycle, zloop_zone_files_on_dead_mount_released)\n+{\n+\tholder_cycle(_metadata, self, HOLDER_ZLOOP);\n+}\n+\n+TEST_F(loop_cycle, mass_storage_lun_on_dead_mount_released)\n+{\n+\tholder_cycle(_metadata, self, HOLDER_GADGET);\n+}\n+\n+TEST_F(loop_cycle, md_bitmap_file_on_dead_mount_released)\n+{\n+\tholder_cycle(_metadata, self, HOLDER_MD);\n+}\n+\n+TEST_HARNESS_MAIN\n"
} |
| 2/1 | 2026/09/26 03:18 | agent | patch-evaluator |
1mModel:core Args: null Results: {
"EnableConfigs": [
"FSNOTIFY"
],
"FocusSymbols": [
"vacate_mount",
"cleanup_mnt",
"mntput_no_expire_slowpath",
"__detach_mounts",
"umount_tree",
"namespace_unlock",
"__do_sys_fspick",
"fsnotify_init_connector",
"fsnotify_detach_connector_from_object",
"fsnotify_add_mark_list"
],
"Reasoning": "The patch series introduces 'vacant mounts' backed by a private nullfs instance (knullfs) to break reference cycles where an unmounted mount loses its last reference while remaining attached to an unmounted parent. It modifies core VFS mount lifetime and reference counting logic (fs/namespace.c), updates fsnotify mark connectors to track their originating superblock across mount sb replacement (fs/notify/mark.c), and adds an SB_NOUSER check to fspick (fs/fsopen.c). It also introduces new runtime assertions (e.g. VFS_WARN_ON_ONCE(is_vacant(mnt))). These changes are in core reachable kernel subsystems and can be exercised via standard filesystem and mount syscalls (mount, umount2, fspick, open_tree, move_mount, fanotify/inotify). Due to the complex reference counting, refactoring of mount teardown, and dynamic superblock swapping, this code warrants focused fuzzing.",
"WorthFuzzing": true
}Instruction: You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.
IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.
================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.
- REACHABILITY IS THE PRIMARY GATE:
Fuzzing can only discover bugs in code that can actually execute in standard virtualized
environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
regardless of whether it adds assertions or complex logic.
- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
Patch authors routinely label changes as "cleanups", "refactorings", or state
"No functional change intended". Do NOT take these claims at face value.
Code refactorings that rearrange logic, introduce helper functions, or alter state management
in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
If reachable executable code is modified or refactored, it MUST be fuzzed.
- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
Even if the author believes the invariant always holds, fuzzing is essential to verify whether
an unusual sequence of operations can violate it.
================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:
- Non-kernel and non-executable changes:
* Modifications to Documentation/, comments, or spelling fixes.
* User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
that do not affect the compiled kernel image (vmlinux) or kernel modules.
* Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
that do not alter control flow or data structures.
* Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
* Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
* Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
physical PCI hot-unplug or manual sysfs driver unbinding.
* Code paths exclusive to architectures other than the target architecture.
================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
* Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
* Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
* Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
* Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).
================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:
- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
Do NOT list generic, ubiquitous functions called by almost every program in the corpus
(including, but not limited to: general memory allocators and deallocators, page fault
and trap handlers, or core synchronization primitives; this is not an exhaustive list).
Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
which severely dilutes fuzzing effort away from the actual changes.
- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
List functions that specifically implement the logic being added or altered, or direct API entrypoints
for the subsystem feature under review.
- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).
================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Target architecture: amd64
For your convenience, here is the diff of the changes:
commit 6828955f7f8d6b3588066fb61312f9f956fbddf0
Author: syz-cluster <triage@syzkaller.com>
Date: Sat Sep 26 03:18:27 2026 +0000
syz-cluster: applied patch under review
diff --git a/fs/fsopen.c b/fs/fsopen.c
index ae19e51365986..9d5a7a22b5292 100644
--- a/fs/fsopen.c
+++ b/fs/fsopen.c
@@ -190,6 +190,9 @@ SYSCALL_DEFINE3(fspick, int, dfd, const char __user *, path, unsigned int, flags
ret = -EINVAL;
if (target.mnt->mnt_root != target.dentry)
goto err_path;
+ /* kernel-internal superblocks are nobody's to reconfigure */
+ if (target.dentry->d_sb->s_flags & SB_NOUSER)
+ goto err_path;
fc = fs_context_for_reconfigure(target.dentry, 0, 0);
if (IS_ERR(fc)) {
diff --git a/fs/mount.h b/fs/mount.h
index 94fcc306d21e7..50d0999ff09ff 100644
--- a/fs/mount.h
+++ b/fs/mount.h
@@ -6,6 +6,7 @@
#include <linux/fs_pin.h>
extern struct file_system_type nullfs_fs_type;
+extern struct vfsmount *knullfs;
extern struct list_head notify_list;
struct mnt_namespace {
@@ -50,8 +51,13 @@ struct mount {
struct vfsmount mnt;
union {
struct rb_node mnt_node; /* node in the ns->mounts rbtree */
- struct rcu_head mnt_rcu;
- struct llist_node mnt_llist;
+ struct { /* once it has left its namespace */
+ union {
+ struct rcu_head mnt_rcu;
+ struct llist_node mnt_llist;
+ };
+ struct dentry *mnt_old_root; /* what a vacant mount stands in for */
+ };
};
#ifdef CONFIG_SMP
struct mnt_pcp __percpu *mnt_pcp;
@@ -84,7 +90,7 @@ struct mount {
struct mountpoint *mnt_mp; /* where is it mounted */
union {
struct hlist_node mnt_mp_list; /* list mounts with the same mountpoint */
- struct hlist_node mnt_umount;
+ struct hlist_node mnt_umount; /* in the parent's mnt_stuck_children */
};
#ifdef CONFIG_FSNOTIFY
struct fsnotify_mark_connector __rcu *mnt_fsnotify_marks;
diff --git a/fs/namespace.c b/fs/namespace.c
index 580877e46b1ac..175e8165693b6 100644
--- a/fs/namespace.c
+++ b/fs/namespace.c
@@ -80,8 +80,9 @@ static u64 mnt_id_ctr = MNT_UNIQUE_ID_OFFSET;
static struct hlist_head *mount_hashtable __ro_after_init;
static struct hlist_head *mountpoint_hashtable __ro_after_init;
static struct kmem_cache *mnt_cache __ro_after_init;
+struct vfsmount *knullfs __ro_after_init; /* private nullfs instance */
static DECLARE_RWSEM(namespace_sem);
-static HLIST_HEAD(unmounted); /* protected by namespace_sem */
+static LIST_HEAD(unmounted); /* protected by namespace_sem */
static LIST_HEAD(ex_mountpoints); /* protected by namespace_sem */
static struct mnt_namespace *emptied_ns; /* protected by namespace_sem */
@@ -227,6 +228,17 @@ static void mnt_free_id(struct mount *mnt)
xa_erase(&mnt_id_xa, mnt->mnt_id);
}
+/* mnt_id_ctr is protected by the lock of mnt_id_xa, see mnt_alloc_id(). */
+static u64 mnt_alloc_unique_id(void)
+{
+ u64 id;
+
+ xa_lock(&mnt_id_xa);
+ id = ++mnt_id_ctr;
+ xa_unlock(&mnt_id_xa);
+ return id;
+}
+
/*
* Allocate a new peer group ID
*/
@@ -1150,18 +1162,28 @@ static void commit_tree(struct mount *mnt)
touch_mnt_namespace(n);
}
-static void setup_mnt(struct mount *m, struct dentry *root)
+/*
+ * Point @m at @root: a reference on the superblock and its root, and a
+ * place on the superblock's list of instances.
+ * locks: mount_lock, as mount_locked_reader or mount_writer
+ */
+static void __setup_mnt(struct mount *m, struct dentry *root)
{
struct super_block *s = root->d_sb;
atomic_inc(&s->s_active);
m->mnt.mnt_sb = s;
m->mnt.mnt_root = dget(root);
- m->mnt_mountpoint = m->mnt.mnt_root;
+ mnt_add_instance(m, s);
+}
+
+static void setup_mnt(struct mount *m, struct dentry *root)
+{
+ m->mnt_mountpoint = root;
m->mnt_parent = m;
guard(mount_locked_reader)();
- mnt_add_instance(m, s);
+ __setup_mnt(m, root);
}
/**
@@ -1294,8 +1316,20 @@ static struct mount *clone_mnt(struct mount *old, struct dentry *root,
return ERR_PTR(err);
}
+/*
+ * The only mounts of knullfs' superblock that are ever attached are
+ * vacant mounts.
+ */
+static inline bool is_vacant(const struct mount *mnt)
+{
+ return mnt->mnt.mnt_sb == knullfs->mnt_sb;
+}
+
static void cleanup_mnt(struct mount *mnt)
{
+ bool release = !(mnt->mnt.mnt_flags & MNT_DOOMED);
+ struct dentry *root = release ? mnt->mnt_old_root : mnt->mnt.mnt_root;
+ struct super_block *sb = root->d_sb;
struct hlist_node *p;
struct mount *m;
/*
@@ -1303,9 +1337,10 @@ static void cleanup_mnt(struct mount *mnt)
* up a mnt_want/drop_write() pair. If this happens, the
* filesystem was probably unable to make r/w->r/o transitions.
* The locking used to deal with mnt_count decrement provides barriers,
- * so mnt_get_writers() below is safe.
+ * so mnt_get_writers() below is safe. A vacant mount is still reachable
+ * and a failing mnt_want_write() on it bumps the count for a moment.
*/
- WARN_ON(mnt_get_writers(mnt));
+ WARN_ON(!release && mnt_get_writers(mnt));
if (unlikely(mnt->mnt_pins.first))
mnt_pin_kill(mnt);
hlist_for_each_entry_safe(m, p, &mnt->mnt_stuck_children, mnt_umount) {
@@ -1313,12 +1348,35 @@ static void cleanup_mnt(struct mount *mnt)
mntput(&m->mnt);
}
fsnotify_vfsmount_delete(&mnt->mnt);
- dput(mnt->mnt.mnt_root);
- deactivate_super(mnt->mnt.mnt_sb);
+ dput(root);
+ deactivate_super(sb);
+ /* A new vacant mount is just put here. */
+ if (unlikely(release)) {
+ /* the reference vacate_mount() gave the release */
+ mntput(&mnt->mnt);
+ return;
+ }
mnt_free_id(mnt);
call_rcu(&mnt->mnt_rcu, delayed_free_vfsmnt);
}
+/*
+ * @mnt lost its last reference while still attached. Don't reveal what's
+ * beneath so mount knullfs over it.
+ */
+static void vacate_mount(struct mount *mnt)
+{
+ /* a vacant mount is put only after it has been unhashed */
+ VFS_WARN_ON_ONCE(is_vacant(mnt));
+ mnt->mnt_old_root = mnt->mnt.mnt_root;
+ __setup_mnt(mnt, knullfs->mnt_root);
+ mnt->mnt.mnt_flags |= MNT_READONLY;
+ /* It's a new mount so give it its own mount id. */
+ mnt->mnt_id_unique = mnt_alloc_unique_id();
+ /* One reference for the parent and one for cleanup_mnt(). */
+ mnt_add_count(mnt, 2);
+}
+
static void __cleanup_mnt(struct rcu_head *head)
{
cleanup_mnt(container_of(head, struct mount, mnt_rcu));
@@ -1338,6 +1396,7 @@ static DECLARE_DELAYED_WORK(delayed_mntput_work, delayed_mntput);
static void noinline mntput_no_expire_slowpath(struct mount *mnt)
{
LIST_HEAD(list);
+ bool vacate = false;
int count;
VFS_BUG_ON(mnt->mnt_ns);
@@ -1360,7 +1419,11 @@ static void noinline mntput_no_expire_slowpath(struct mount *mnt)
unlock_mount_hash();
return;
}
- mnt->mnt.mnt_flags |= MNT_DOOMED;
+ /* Still attached, so it held its own reference: keep the slot filled. */
+ if (unlikely(mnt_has_parent(mnt)))
+ vacate = true;
+ else
+ mnt->mnt.mnt_flags |= MNT_DOOMED;
rcu_read_unlock();
mnt_del_instance(mnt);
@@ -1371,9 +1434,13 @@ static void noinline mntput_no_expire_slowpath(struct mount *mnt)
struct mount *p, *tmp;
list_for_each_entry_safe(p, tmp, &mnt->mnt_mounts, mnt_child) {
__umount_mnt(p, &list);
- hlist_add_head(&p->mnt_umount, &mnt->mnt_stuck_children);
+ /* only a vacant mount is owned by its parent */
+ if (is_vacant(p))
+ hlist_add_head(&p->mnt_umount, &mnt->mnt_stuck_children);
}
}
+ if (unlikely(vacate))
+ vacate_mount(mnt);
unlock_mount_hash();
shrink_dentry_list(&list);
@@ -1688,13 +1755,12 @@ static bool need_notify_mnt_list(void)
static void free_mnt_ns(struct mnt_namespace *);
static void namespace_unlock(void)
{
- struct hlist_head head;
- struct hlist_node *p;
- struct mount *m;
+ struct mount *m, *n;
struct mnt_namespace *ns = emptied_ns;
+ LIST_HEAD(head);
LIST_HEAD(list);
- hlist_move_list(&unmounted, &head);
+ list_splice_init(&unmounted, &head);
list_splice_init(&ex_mountpoints, &list);
emptied_ns = NULL;
@@ -1718,13 +1784,14 @@ static void namespace_unlock(void)
shrink_dentry_list(&list);
- if (likely(hlist_empty(&head)))
+ if (likely(list_empty(&head)))
return;
synchronize_rcu_expedited();
- hlist_for_each_entry_safe(m, p, &head, mnt_umount) {
- hlist_del(&m->mnt_umount);
+ /* In tree order, so a subtree nobody holds goes without vacant mounts. */
+ list_for_each_entry_safe(m, n, &head, mnt_list) {
+ list_del_init(&m->mnt_list);
mntput(&m->mnt);
}
}
@@ -1740,6 +1807,19 @@ enum umount_tree_flags {
UMOUNT_CONNECTED = 4,
};
+/*
+ * An unmounted mount that stays attached to its unmounted parent:
+ *
+ * - is hashed and on the parent's list of children, so a walk on the
+ * parent finds it and never ends up in what it covered
+ * - is unreachable from any namespace root
+ * - holds its own reference, dropped by namespace_unlock(); the parent's
+ * final mntput() unhashes it without putting it, so a child whose
+ * superblock pins an ancestor can still shut down
+ * - is vacated if it loses its last reference while attached
+ * it releases the filesystem it carried and a knullfs mount is placed on
+ * the parent which is owned by it
+ */
static bool disconnect_mount(struct mount *mnt, enum umount_tree_flags how)
{
/* Leaving mounts connected is only valid for lazy umounts */
@@ -1750,10 +1830,7 @@ static bool disconnect_mount(struct mount *mnt, enum umount_tree_flags how)
if (!mnt_has_parent(mnt))
return true;
- /* Because the reference counting rules change when mounts are
- * unmounted and connected, umounted mounts may not be
- * connected to mounted mounts.
- */
+ /* An unmounted mount may only stay attached to an unmounted parent */
if (!(mnt->mnt_parent->mnt.mnt_flags & MNT_UMOUNT))
return true;
@@ -1769,10 +1846,6 @@ static bool disconnect_mount(struct mount *mnt, enum umount_tree_flags how)
return true;
}
-/*
- * mount_lock must be held
- * namespace_sem must be held for write
- */
static void umount_tree(struct mount *mnt, enum umount_tree_flags how)
{
LIST_HEAD(tmp_list);
@@ -1824,8 +1897,8 @@ static void umount_tree(struct mount *mnt, enum umount_tree_flags how)
umount_mnt(p);
}
}
- if (disconnect)
- hlist_add_head(&p->mnt_umount, &unmounted);
+ /* attached or not, it holds its own reference */
+ list_add_tail(&p->mnt_list, &unmounted);
/*
* At this point p->mnt_ns is NULL, notification will be queued
@@ -1994,9 +2067,12 @@ void __detach_mounts(struct dentry *dentry)
mnt = hlist_entry(mp.node.next, struct mount, mnt_mp_list);
if (mnt->mnt.mnt_flags & MNT_UMOUNT) {
umount_mnt(mnt);
- hlist_add_head(&mnt->mnt_umount, &unmounted);
+ /* only a vacant mount is owned by its parent */
+ if (is_vacant(mnt))
+ list_add_tail(&mnt->mnt_list, &unmounted);
+ } else {
+ umount_tree(mnt, UMOUNT_CONNECTED);
}
- else umount_tree(mnt, UMOUNT_CONNECTED);
}
unpin_mountpoint(&mp);
}
@@ -6210,10 +6286,12 @@ static void __init init_mount_tree(void)
*
* (1) nullfs with mount id 1
* (2) mutable rootfs with mount id 2
- * (3) private nullfs for kthreads (SB_KERNMOUNT)
+ * (3) private nullfs for kthreads (SB_KERNMOUNT), kept in knullfs
*
* with (2) mounted on top of (1). The init_task's root and pwd
* are pointed at (3) so all kthreads start isolated in nullfs.
+ * A mount that dies while still attached to its parent is pointed
+ * at (3) as well, see vacate_mount().
*/
nullfs_mnt = vfs_kern_mount(&nullfs_fs_type, 0, "nullfs", NULL);
if (IS_ERR(nullfs_mnt))
@@ -6245,11 +6323,11 @@ static void __init init_mount_tree(void)
init_mnt_ns.nr_mounts++;
}
- nullfs_mnt = kern_mount(&nullfs_fs_type);
- if (IS_ERR(nullfs_mnt))
+ knullfs = kern_mount(&nullfs_fs_type);
+ if (IS_ERR(knullfs))
panic("VFS: Failed to create private nullfs instance");
- root.mnt = nullfs_mnt;
- root.dentry = nullfs_mnt->mnt_root;
+ root.mnt = knullfs;
+ root.dentry = knullfs->mnt_root;
init_task.nsproxy->mnt_ns = &init_mnt_ns;
get_mnt_ns(&init_mnt_ns);
diff --git a/fs/notify/fsnotify.h b/fs/notify/fsnotify.h
index 58c7bb25e5718..0be351275dad7 100644
--- a/fs/notify/fsnotify.h
+++ b/fs/notify/fsnotify.h
@@ -54,10 +54,11 @@ static inline struct super_block *fsnotify_object_sb(void *obj,
}
}
+/* The sb the connector is accounted on; NULL once it has been detached */
static inline struct super_block *fsnotify_connector_sb(
struct fsnotify_mark_connector *conn)
{
- return fsnotify_object_sb(conn->obj, conn->type);
+ return conn->sb;
}
static inline fsnotify_connp_t *fsnotify_sb_marks(struct super_block *sb)
diff --git a/fs/notify/mark.c b/fs/notify/mark.c
index b2640d836a712..1b6095fcf039f 100644
--- a/fs/notify/mark.c
+++ b/fs/notify/mark.c
@@ -425,6 +425,7 @@ static void *fsnotify_detach_connector_from_object(
conn->type = FSNOTIFY_OBJ_TYPE_DETACHED;
if (sb)
fsnotify_update_sb_watchers(sb, conn);
+ conn->sb = NULL;
return inode;
}
@@ -791,6 +792,8 @@ static void fsnotify_init_connector(struct fsnotify_mark_connector *conn,
conn->prio = 0;
conn->type = obj_type;
conn->obj = obj;
+ /* the object may move to another sb, the accounting doesn't */
+ conn->sb = fsnotify_object_sb(obj, obj_type);
}
static struct fsnotify_mark_connector *
@@ -953,8 +956,8 @@ static int fsnotify_add_mark_list(struct fsnotify_mark *mark, void *obj,
/* mark should be the last entry. last is the current last entry */
hlist_add_behind_rcu(&mark->obj_list, &last->obj_list);
added:
- if (sb)
- fsnotify_update_sb_watchers(sb, conn);
+ if (conn->sb)
+ fsnotify_update_sb_watchers(conn->sb, conn);
/*
* Since connector is attached to object using cmpxchg() we are
* guaranteed that connector initialization is fully visible by anyone
diff --git a/include/linux/fsnotify_backend.h b/include/linux/fsnotify_backend.h
index 618eed4d6d724..3a9ab9e0104b4 100644
--- a/include/linux/fsnotify_backend.h
+++ b/include/linux/fsnotify_backend.h
@@ -573,6 +573,8 @@ struct fsnotify_mark_connector {
/* Used listing heads to free after srcu period expires */
struct fsnotify_mark_connector *destroy_next;
};
+ /* sb whose watched_objects account for this connector [lock] */
+ struct super_block *sb;
struct hlist_head list; /* List of marks */
};
diff --git a/tools/testing/selftests/Makefile b/tools/testing/selftests/Makefile
index 273853937c254..fb3a85d6396de 100644
--- a/tools/testing/selftests/Makefile
+++ b/tools/testing/selftests/Makefile
@@ -43,6 +43,7 @@ TARGETS += filesystems/open_tree_ns
TARGETS += filesystems/overlayfs
TARGETS += filesystems/statmount
TARGETS += filesystems/mount-notify
+TARGETS += filesystems/mount_cycle
TARGETS += filesystems/nsfs
TARGETS += filesystems/fuse
TARGETS += filesystems/move_mount
diff --git a/tools/testing/selftests/filesystems/mount_cycle/.gitignore b/tools/testing/selftests/filesystems/mount_cycle/.gitignore
new file mode 100644
index 0000000000000..28c623ef4d9dc
--- /dev/null
+++ b/tools/testing/selftests/filesystems/mount_cycle/.gitignore
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: GPL-2.0-only
+loop_cycle_test
diff --git a/tools/testing/selftests/filesystems/mount_cycle/Makefile b/tools/testing/selftests/filesystems/mount_cycle/Makefile
new file mode 100644
index 0000000000000..3becec29d69fb
--- /dev/null
+++ b/tools/testing/selftests/filesystems/mount_cycle/Makefile
@@ -0,0 +1,6 @@
+# SPDX-License-Identifier: GPL-2.0
+TEST_GEN_PROGS := loop_cycle_test
+
+CFLAGS += -Wall -O2 -g $(KHDR_INCLUDES)
+
+include ../../lib.mk
diff --git a/tools/testing/selftests/filesystems/mount_cycle/loop_cycle_test.c b/tools/testing/selftests/filesystems/mount_cycle/loop_cycle_test.c
new file mode 100644
index 0000000000000..09cc824c769e0
--- /dev/null
+++ b/tools/testing/selftests/filesystems/mount_cycle/loop_cycle_test.c
@@ -0,0 +1,1225 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A mount that another namespace's rmdir detached, or that went down with
+ * the detached tree it was in when the tree's last fd was closed, keeps
+ * its submounts connected, and a connected submount is put by its
+ * parent's final mntput(). A submount whose filesystem keeps a file open
+ * on the parent then holds the parent's count above zero for good:
+ * nothing in userspace refers to either mount any more and nothing can
+ * release them. A loop device is the simplest such filesystem, its
+ * backing file sits on the parent.
+ */
+#define _GNU_SOURCE
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <sched.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <stdbool.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include <linux/fuse.h>
+#include <linux/keyctl.h>
+#include <linux/major.h>
+#include <linux/raid/md_u.h>
+#include <linux/raid/md_p.h>
+#include <linux/loop.h>
+#include <linux/magic.h>
+#include <sys/syscall.h>
+#include <sys/sysmacros.h>
+#include <sys/uio.h>
+
+#include "../wrappers.h"
+#include "../../kselftest_harness.h"
+
+#define IMAGE_SIZE (1440 * 1024)
+#define SECTOR 512
+
+/* A blank FAT12 floppy image: boot sector, two FATs, an empty root directory. */
+static int write_fat12(int fd)
+{
+ struct stat st;
+ unsigned char sector[SECTOR] = {
+ 0xeb, 0x3c, 0x90, 'M', 'S', 'W', 'I', 'N', '4', '.', '1',
+ [11] = 0x00, 0x02, /* bytes per sector: 512 */
+ [13] = 1, /* sectors per cluster */
+ [14] = 1, 0, /* reserved sectors */
+ [16] = 2, /* FATs */
+ [17] = 0xe0, 0x00, /* root directory entries: 224 */
+ [19] = 0x40, 0x0b, /* total sectors: 2880 */
+ [21] = 0xf0, /* media descriptor */
+ [22] = 9, 0, /* sectors per FAT */
+ [24] = 18, 0, /* sectors per track */
+ [26] = 2, 0, /* heads */
+ [38] = 0x29, /* extended boot signature */
+ [39] = 0x12, 0x34, 0x56, 0x78,
+ [43] = 'N', 'O', ' ', 'N', 'A', 'M', 'E', ' ', ' ', ' ', ' ',
+ [54] = 'F', 'A', 'T', '1', '2', ' ', ' ', ' ',
+ [510] = 0x55, 0xaa,
+ };
+ unsigned char fat[SECTOR] = { 0xf0, 0xff, 0xff };
+
+ if (pwrite(fd, sector, SECTOR, 0) != SECTOR)
+ return -1;
+ /* the first FAT and the second one, one sector each is enough */
+ if (pwrite(fd, fat, SECTOR, 1 * SECTOR) != SECTOR ||
+ pwrite(fd, fat, SECTOR, 10 * SECTOR) != SECTOR)
+ return -1;
+ if (fstat(fd, &st) || S_ISBLK(st.st_mode))
+ return 0;
+ return ftruncate(fd, IMAGE_SIZE);
+}
+
+/*
+ * A blank FAT12 image with 4 KiB sectors and @sectors of them, for a device
+ * with 4 KiB logical blocks (zram) or for a bigger image than a floppy.
+ */
+static int write_fat12_4k(int fd, unsigned int sectors)
+{
+ unsigned int fat_sectors = (sectors * 3 / 2 + 4095) / 4096;
+ unsigned char sector[4096] = {
+ 0xeb, 0x3c, 0x90, 'M', 'S', 'W', 'I', 'N', '4', '.', '1',
+ [11] = 0x00, 0x10, /* bytes per sector: 4096 */
+ [13] = 1, /* sectors per cluster */
+ [14] = 1, 0, /* reserved sectors */
+ [16] = 2, /* FATs */
+ [17] = 128, 0, /* root directory entries: one sector */
+ [19] = sectors & 0xff, sectors >> 8,
+ [21] = 0xf8, /* media descriptor */
+ [22] = fat_sectors, 0,
+ [24] = 63, 0, /* sectors per track */
+ [26] = 255, 0, /* heads */
+ [38] = 0x29, /* extended boot signature */
+ [39] = 0x12, 0x34, 0x56, 0x78,
+ [43] = 'N', 'O', ' ', 'N', 'A', 'M', 'E', ' ', ' ', ' ', ' ',
+ [54] = 'F', 'A', 'T', '1', '2', ' ', ' ', ' ',
+ [510] = 0x55, 0xaa,
+ };
+ unsigned char fat[4096] = { 0xf8, 0xff, 0xff };
+ struct stat st;
+
+ if (pwrite(fd, sector, sizeof(sector), 0) != sizeof(sector))
+ return -1;
+ if (pwrite(fd, fat, sizeof(fat), 1 * 4096) != sizeof(fat) ||
+ pwrite(fd, fat, sizeof(fat), (1 + fat_sectors) * 4096) != sizeof(fat))
+ return -1;
+ if (fstat(fd, &st) || S_ISBLK(st.st_mode))
+ return 0;
+ return ftruncate(fd, (off_t)sectors * 4096);
+}
+
+#define MINIX_BLOCK 1024
+#define MINIX_BLOCKS 4096 /* a 4 MiB image */
+#define MINIX_INODES 512
+#define MINIX_ITABLE (MINIX_INODES * 32 / MINIX_BLOCK)
+#define MINIX_FIRSTDATA (2 + 1 + 1 + MINIX_ITABLE) /* boot, super, imap, zmap, inodes */
+
+/*
+ * A blank minix v1 image, for the holders that need a FIFO or a device
+ * node on the dying mount, which vfat can't hold. Superblock in block 1,
+ * one block each for the inode and zone bitmaps, the inode table, and
+ * the root directory in the first data zone.
+ */
+static int write_minix(int fd)
+{
+ struct {
+ __u16 s_ninodes, s_nzones, s_imap_blocks, s_zmap_blocks;
+ __u16 s_firstdatazone, s_log_zone_size;
+ __u32 s_max_size;
+ __u16 s_magic, s_state;
+ } sb = {
+ .s_ninodes = MINIX_INODES,
+ .s_nzones = MINIX_BLOCKS,
+ .s_imap_blocks = 1,
+ .s_zmap_blocks = 1,
+ .s_firstdatazone = MINIX_FIRSTDATA,
+ .s_max_size = (7 + 512 + 512 * 512) * MINIX_BLOCK,
+ .s_magic = MINIX_SUPER_MAGIC,
+ .s_state = 1, /* MINIX_VALID_FS */
+ };
+ struct {
+ __u16 i_mode, i_uid;
+ __u32 i_size, i_time;
+ __u8 i_gid, i_nlinks;
+ __u16 i_zone[9];
+ } root = {
+ .i_mode = S_IFDIR | 0755,
+ .i_size = 2 * 16,
+ .i_nlinks = 2,
+ .i_zone = { MINIX_FIRSTDATA },
+ };
+ unsigned char imap[MINIX_BLOCK], zmap[MINIX_BLOCK], dir[MINIX_BLOCK] = {};
+ int i;
+
+ /* bit 0 is reserved in both maps, the root inode and its zone are in use */
+ memset(imap, 0xff, sizeof(imap));
+ for (i = 2; i <= MINIX_INODES; i++)
+ imap[i / 8] &= ~(1 << (i % 8));
+ memset(zmap, 0xff, sizeof(zmap));
+ for (i = 2; i <= MINIX_BLOCKS - MINIX_FIRSTDATA; i++)
+ zmap[i / 8] &= ~(1 << (i % 8));
+ dir[0] = 1;
+ dir[2] = '.';
+ dir[16] = 1;
+ dir[18] = '.';
+ dir[19] = '.';
+
+ if (pwrite(fd, &sb, sizeof(sb), 1 * MINIX_BLOCK) != sizeof(sb) ||
+ pwrite(fd, imap, sizeof(imap), 2 * MINIX_BLOCK) != sizeof(imap) ||
+ pwrite(fd, zmap, sizeof(zmap), 3 * MINIX_BLOCK) != sizeof(zmap) ||
+ pwrite(fd, &root, sizeof(root), 4 * MINIX_BLOCK) != sizeof(root) ||
+ pwrite(fd, dir, sizeof(dir), MINIX_FIRSTDATA * MINIX_BLOCK) != sizeof(dir))
+ return -1;
+ return ftruncate(fd, (off_t)MINIX_BLOCKS * MINIX_BLOCK);
+}
+
+static int read_sysfs(const char *path, char *buf, size_t size)
+{
+ ssize_t n;
+ int fd;
+
+ fd = open(path, O_RDONLY);
+ if (fd < 0)
+ return -1;
+ n = read(fd, buf, size - 1);
+ close(fd);
+ if (n < 0)
+ return -1;
+ buf[n] = '\0';
+ return 0;
+}
+
+/* Does any mount namespace in the system show a mount of @dev? */
+static bool mounted_anywhere(const char *dev)
+{
+ char path[PATH_MAX], line[4096];
+ struct dirent *de;
+ bool found = false;
+ DIR *proc;
+ FILE *f;
+
+ proc = opendir("/proc");
+ if (!proc)
+ return false;
+ while (!found && (de = readdir(proc))) {
+ if (de->d_name[0] < '0' || de->d_name[0] > '9')
+ continue;
+ snprintf(path, sizeof(path), "/proc/%s/mountinfo", de->d_name);
+ f = fopen(path, "re");
+ if (!f)
+ continue;
+ while (fgets(line, sizeof(line), f)) {
+ if (strstr(line, dev)) {
+ found = true;
+ break;
+ }
+ }
+ fclose(f);
+ }
+ closedir(proc);
+ return found;
+}
+
+/* Wait up to @ms milliseconds for the loop device to give up its backing file. */
+static bool loop_released(const char *sysfs, int ms)
+{
+ char buf[PATH_MAX];
+
+ for (; ms > 0; ms -= 100) {
+ if (read_sysfs(sysfs, buf, sizeof(buf)) < 0)
+ return true;
+ usleep(100000);
+ }
+ return read_sysfs(sysfs, buf, sizeof(buf)) < 0;
+}
+
+FIXTURE(loop_cycle) {
+ char dev[32]; /* the loop device the child set up */
+ char sysfs[64]; /* its backing_file attribute */
+};
+
+FIXTURE_SETUP(loop_cycle)
+{
+ if (geteuid() != 0)
+ SKIP(return, "test requires CAP_SYS_ADMIN");
+ if (access("/dev/loop-control", R_OK | W_OK))
+ SKIP(return, "test requires loop devices");
+
+ ASSERT_EQ(unshare(CLONE_NEWNS), 0);
+ ASSERT_EQ(mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL), 0);
+
+ rmdir("/mnt_dir");
+ ASSERT_EQ(mkdir("/mnt_dir", 0755), 0);
+ ASSERT_EQ(mount("tmpfs", "/mnt_dir", "tmpfs", 0, NULL), 0);
+ self->dev[0] = '\0';
+}
+
+FIXTURE_TEARDOWN(loop_cycle)
+{
+ umount2("/mnt_dir", MNT_DETACH);
+ rmdir("/mnt_dir");
+}
+
+/* Child exit codes. */
+enum {
+ CHILD_OK,
+ CHILD_NS, /* could not set up the namespace or the tmpfs */
+ CHILD_IMAGE, /* could not write the image */
+ CHILD_LOOP, /* could not set up the loop device */
+ CHILD_MOUNT, /* could not mount it (vfat and msdos both refused) */
+ CHILD_PIPE, /* the parent went away */
+ CHILD_HOLDER, /* could not set the holder up below the mount */
+ CHILD_SKIP, /* the kernel lacks what the holder needs */
+};
+
+/* Bind a free loop device to the open image @ifd; the device number. */
+static int loop_bind(int ifd)
+{
+ int cfd, lfd, n;
+ char dev[32];
+
+ cfd = open("/dev/loop-control", O_RDWR);
+ if (cfd < 0)
+ return -1;
+ n = ioctl(cfd, LOOP_CTL_GET_FREE);
+ close(cfd);
+ if (n < 0)
+ return -1;
+ snprintf(dev, sizeof(dev), "/dev/loop%d", n);
+ lfd = open(dev, O_RDWR);
+ if (lfd < 0)
+ return -1;
+ if (ioctl(lfd, LOOP_SET_FD, ifd))
+ n = -1;
+ close(lfd);
+ return n;
+}
+
+/* Write an image to @img, bind a loop device to it and mount that at @mp; the device number. */
+static int loop_mount(const char *img, const char *mp)
+{
+ char dev[32];
+ int ifd, n;
+
+ ifd = open(img, O_RDWR | O_CREAT | O_EXCL, 0600);
+ if (ifd < 0 || write_fat12(ifd))
+ return -CHILD_IMAGE;
+ n = loop_bind(ifd);
+ close(ifd); /* the loop device holds the file from now on */
+ if (n < 0)
+ return -CHILD_LOOP;
+ snprintf(dev, sizeof(dev), "/dev/loop%d", n);
+ if (mkdir(mp, 0755))
+ return -CHILD_MOUNT;
+ if (mount(dev, mp, "vfat", 0, NULL) && mount(dev, mp, "msdos", 0, NULL))
+ return -CHILD_MOUNT;
+ return n;
+}
+
+/*
+ * Two tmpfs mounts, each carrying the image of the loop mount below the
+ * other: the loop mount below /mnt_dir/vol has its image on /mnt_dir/vol2
+ * and the other way round.
+ */
+static int crossed_child(int to_parent, int from_parent)
+{
+ int n[2];
+ char c;
+
+ if (unshare(CLONE_NEWNS) || mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL))
+ return CHILD_NS;
+ if (mkdir("/mnt_dir/vol", 0755) || mount("tmpfs", "/mnt_dir/vol", "tmpfs", 0, NULL) ||
+ mkdir("/mnt_dir/vol2", 0755) || mount("tmpfs", "/mnt_dir/vol2", "tmpfs", 0, NULL))
+ return CHILD_NS;
+ n[0] = loop_mount("/mnt_dir/vol2/img", "/mnt_dir/vol/mnt");
+ if (n[0] < 0)
+ return -n[0];
+ n[1] = loop_mount("/mnt_dir/vol/img", "/mnt_dir/vol2/mnt");
+ if (n[1] < 0)
+ return -n[1];
+ if (write(to_parent, n, sizeof(n)) != sizeof(n))
+ return CHILD_PIPE;
+ if (read(from_parent, &c, 1) != 1)
+ return CHILD_PIPE;
+ return CHILD_OK;
+}
+
+/*
+ * In its own mount namespace the child mounts a tmpfs on /mnt_dir/vol,
+ * puts a filesystem image on it, binds a loop device to the image and
+ * mounts that loop device below. The loop device's backing file is a
+ * reference on the mount the image is on, held by the loop device, held
+ * by the mounted filesystem, held by the mount below.
+ */
+static int loop_child(int to_parent, int from_parent)
+{
+ char c;
+ int n;
+
+ if (unshare(CLONE_NEWNS) || mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL))
+ return CHILD_NS;
+ if (mkdir("/mnt_dir/vol", 0755) || mount("tmpfs", "/mnt_dir/vol", "tmpfs", 0, NULL))
+ return CHILD_NS;
+ n = loop_mount("/mnt_dir/vol/img", "/mnt_dir/vol/mnt");
+ if (n < 0)
+ return -n;
+
+ if (write(to_parent, &n, sizeof(n)) != sizeof(n))
+ return CHILD_PIPE;
+ /* keep the namespace alive while the parent removes the directory */
+ if (read(from_parent, &c, 1) != 1)
+ return CHILD_PIPE;
+ return CHILD_OK;
+}
+
+/*
+ * An exclusive open of the device fails while a filesystem holds it, and
+ * the only filesystem that ever did is the one mounted below the dead
+ * mount. Give a release in flight a moment. Then the device must clear
+ * right away rather than only be marked for autoclear.
+ */
+static void assert_loop_released(struct __test_metadata *_metadata,
+ FIXTURE_DATA(loop_cycle) *self)
+{
+ int lfd;
+
+ for (int i = 0; i < 20; i++) {
+ lfd = open(self->dev, O_RDONLY | O_EXCL);
+ if (lfd >= 0)
+ break;
+ usleep(100000);
+ }
+ EXPECT_GE(lfd, 0)
+ TH_LOG("%s is still held by the loop mount below the dead mount: nothing refers to either mount and nothing can release them",
+ self->dev);
+ if (lfd >= 0)
+ close(lfd);
+
+ lfd = open(self->dev, O_RDWR);
+ ASSERT_GE(lfd, 0);
+ ASSERT_EQ(ioctl(lfd, LOOP_CLR_FD), 0);
+ close(lfd);
+ ASSERT_TRUE(loop_released(self->sysfs, 5000))
+ TH_LOG("%s kept its backing file after LOOP_CLR_FD: the filesystem on it is still mounted somewhere nobody can reach",
+ self->dev);
+}
+
+/*
+ * rmdir of /mnt_dir/vol from here, where it is not a mountpoint, detaches
+ * the child's tmpfs with the loop mount connected below it. Once the child
+ * is gone nothing refers to either mount. The loop device must then be
+ * free to give up its backing file, which only happens when the mounted
+ * filesystem below the detached tmpfs has been released.
+ */
+TEST_F(loop_cycle, detached_loop_mount_released)
+{
+ int to_parent[2], to_child[2];
+ char buf[PATH_MAX];
+ int status, n = -1;
+ pid_t pid;
+
+ ASSERT_EQ(pipe(to_parent), 0);
+ ASSERT_EQ(pipe(to_child), 0);
+
+ pid = fork();
+ ASSERT_GE(pid, 0);
+ if (pid == 0) {
+ close(to_parent[0]);
+ close(to_child[1]);
+ _exit(loop_child(to_parent[1], to_child[0]));
+ }
+ close(to_parent[1]);
+ close(to_child[0]);
+
+ if (read(to_parent[0], &n, sizeof(n)) != sizeof(n)) {
+ waitpid(pid, &status, 0);
+ if (WIFEXITED(status) && WEXITSTATUS(status) == CHILD_MOUNT)
+ SKIP(return, "test requires a FAT filesystem");
+ ASSERT_EQ(status, 0);
+ }
+ snprintf(self->dev, sizeof(self->dev), "/dev/loop%d", n);
+ snprintf(self->sysfs, sizeof(self->sysfs), "/sys/block/loop%d/loop/backing_file", n);
+ ASSERT_EQ(read_sysfs(self->sysfs, buf, sizeof(buf)), 0);
+ ASSERT_NE(strstr(buf, "/mnt_dir/vol/img"), NULL);
+
+ /* not a mountpoint in this namespace, so the directory can go */
+ ASSERT_EQ(rmdir("/mnt_dir/vol"), 0);
+
+ /* the child leaves: its namespace and every reference it held are gone */
+ ASSERT_EQ(write(to_child[1], "", 1), 1);
+ ASSERT_EQ(waitpid(pid, &status, 0), pid);
+ ASSERT_EQ(status, 0);
+ close(to_parent[0]);
+ close(to_child[1]);
+
+ /* nothing can reach the two mounts any more */
+ ASSERT_EQ(access("/mnt_dir/vol", F_OK), -1);
+ ASSERT_FALSE(mounted_anywhere(self->dev));
+
+ assert_loop_released(_metadata, self);
+}
+
+/*
+ * The same two mounts in a detached tree: a clone of /mnt_dir/vol from
+ * open_tree(), the image opened through the clone so that the loop device
+ * holds the clone, and the loop mount moved below the clone. The last
+ * close of the tree's fd dissolves the tree with the loop mount left
+ * connected below the dead clone, and nothing refers to either afterwards.
+ */
+TEST_F(loop_cycle, dissolved_tree_loop_mount_released)
+{
+ int tfd, ifd, fsfd, mfd, n;
+ char buf[PATH_MAX];
+
+ fsfd = sys_fsopen("vfat", 0);
+ if (fsfd < 0)
+ fsfd = sys_fsopen("msdos", 0);
+ if (fsfd < 0)
+ SKIP(return, "test requires a FAT filesystem");
+
+ ASSERT_EQ(mkdir("/mnt_dir/vol", 0755), 0);
+ ASSERT_EQ(mount("tmpfs", "/mnt_dir/vol", "tmpfs", 0, NULL), 0);
+ tfd = sys_open_tree(AT_FDCWD, "/mnt_dir/vol", OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);
+ ASSERT_GE(tfd, 0);
+
+ /* the image, opened through the clone: the loop device holds the clone */
+ ifd = openat(tfd, "img", O_RDWR | O_CREAT | O_EXCL, 0600);
+ ASSERT_GE(ifd, 0);
+ ASSERT_EQ(write_fat12(ifd), 0);
+ n = loop_bind(ifd);
+ close(ifd);
+ ASSERT_GE(n, 0);
+ snprintf(self->dev, sizeof(self->dev), "/dev/loop%d", n);
+ snprintf(self->sysfs, sizeof(self->sysfs), "/sys/block/loop%d/loop/backing_file", n);
+
+ /* the loop mount, moved below the clone */
+ ASSERT_EQ(mkdirat(tfd, "mnt", 0755), 0);
+ ASSERT_EQ(sys_fsconfig(fsfd, FSCONFIG_SET_STRING, "source", self->dev, 0), 0);
+ ASSERT_EQ(sys_fsconfig(fsfd, FSCONFIG_CMD_CREATE, NULL, NULL, 0), 0);
+ mfd = sys_fsmount(fsfd, 0, 0);
+ ASSERT_GE(mfd, 0);
+ close(fsfd);
+ ASSERT_EQ(sys_move_mount(mfd, "", tfd, "mnt", MOVE_MOUNT_F_EMPTY_PATH), 0);
+ close(mfd);
+
+ ASSERT_EQ(read_sysfs(self->sysfs, buf, sizeof(buf)), 0);
+ ASSERT_NE(strstr(buf, "img"), NULL);
+
+ /* the last fd of the tree: both mounts die, the loop mount connected */
+ close(tfd);
+
+ /* nothing can reach the two mounts any more */
+ ASSERT_FALSE(mounted_anywhere(self->dev));
+
+ assert_loop_released(_metadata, self);
+}
+
+/*
+ * The cycle in two steps: rmdir of /mnt_dir/vol leaves the loop mount
+ * below it connected while its image's mount, /mnt_dir/vol2, is alive;
+ * then rmdir of /mnt_dir/vol2 takes that one with the loop mount whose
+ * image is on the dead /mnt_dir/vol. Each dead mount now owns a loop
+ * mount whose filesystem pins the other.
+ */
+TEST_F(loop_cycle, crossed_images_released)
+{
+ int to_parent[2], to_child[2];
+ char sysfs[2][64], dev[2][32];
+ int status, n[2] = { -1, -1 };
+ pid_t pid;
+
+ ASSERT_EQ(pipe(to_parent), 0);
+ ASSERT_EQ(pipe(to_child), 0);
+
+ pid = fork();
+ ASSERT_GE(pid, 0);
+ if (pid == 0) {
+ close(to_parent[0]);
+ close(to_child[1]);
+ _exit(crossed_child(to_parent[1], to_child[0]));
+ }
+ close(to_parent[1]);
+ close(to_child[0]);
+
+ if (read(to_parent[0], n, sizeof(n)) != sizeof(n)) {
+ waitpid(pid, &status, 0);
+ if (WIFEXITED(status) && WEXITSTATUS(status) == CHILD_MOUNT)
+ SKIP(return, "test requires a FAT filesystem");
+ ASSERT_EQ(status, 0);
+ }
+ for (int i = 0; i < 2; i++) {
+ snprintf(dev[i], sizeof(dev[i]), "/dev/loop%d", n[i]);
+ snprintf(sysfs[i], sizeof(sysfs[i]), "/sys/block/loop%d/loop/backing_file", n[i]);
+ }
+
+ /* step one: the mount with the first loop mount below it goes */
+ ASSERT_EQ(rmdir("/mnt_dir/vol"), 0);
+
+ /* step two: the other one, with the loop mount whose image is on the first */
+ ASSERT_EQ(rmdir("/mnt_dir/vol2"), 0);
+
+ /* the child leaves: its namespace and every reference it held are gone */
+ ASSERT_EQ(write(to_child[1], "", 1), 1);
+ ASSERT_EQ(waitpid(pid, &status, 0), pid);
+ ASSERT_EQ(status, 0);
+ close(to_parent[0]);
+ close(to_child[1]);
+
+ /* nothing can reach the four mounts any more */
+ for (int i = 0; i < 2; i++) {
+ ASSERT_FALSE(mounted_anywhere(dev[i]));
+ strcpy(self->dev, dev[i]);
+ strcpy(self->sysfs, sysfs[i]);
+ assert_loop_released(_metadata, self);
+ }
+}
+
+/*
+ * The holders. Each keeps a file or a path on a mount P for as long as
+ * its own filesystem or device lives, and each has that filesystem or
+ * device mounted at C below P. Once another namespace's rmdir has
+ * detached P with C connected below it and the child is gone, P is owned
+ * by nobody, C by P, and P is kept by whatever the holder still holds.
+ *
+ * P is a loop mount so that its death can be observed: the loop device
+ * gives its backing file up when P's superblock goes. The image sits on
+ * a tmpfs next to P, not above it, so the loop device's own reference is
+ * not part of the picture.
+ */
+enum holder {
+ HOLDER_AUTOFS, /* a FIFO on P as the daemon's pipe */
+ HOLDER_ZRAM, /* a device node on P as the writeback device */
+ HOLDER_ECRYPTFS, /* a directory on P as the lower directory */
+ HOLDER_BINFMT_MISC, /* an executable on P as an 'F' interpreter */
+ HOLDER_FUSE, /* a file on P as a passthrough backing file */
+ HOLDER_ZLOOP, /* a directory on P for the zone files */
+ HOLDER_GADGET, /* a file on P as a mass storage LUN, over dummy_hcd */
+ HOLDER_MD, /* a file on P as an array's bitmap file */
+};
+
+#define HOLDER_IMG "/mnt_dir/img/p.img"
+#define HOLDER_MNT "/mnt_dir/p"
+#define HOLDER_BELOW "/mnt_dir/p/c"
+
+static int write_file(const char *path, const char *s)
+{
+ int fd = open(path, O_WRONLY);
+ ssize_t n;
+
+ if (fd < 0)
+ return -1;
+ n = write(fd, s, strlen(s));
+ close(fd);
+ return n == (ssize_t)strlen(s) ? 0 : -1;
+}
+
+/* Bind a free loop device to @img; the device number. */
+static int loop_attach(const char *img)
+{
+ int ifd, n;
+
+ ifd = open(img, O_RDWR);
+ if (ifd < 0)
+ return -1;
+ n = loop_bind(ifd);
+ close(ifd);
+ return n;
+}
+
+static int holder_autofs(void)
+{
+ char opts[64];
+ int pfd;
+
+ if (mkfifo(HOLDER_MNT "/pipe", 0600))
+ return CHILD_HOLDER;
+ pfd = open(HOLDER_MNT "/pipe", O_RDWR);
+ if (pfd < 0)
+ return CHILD_HOLDER;
+ snprintf(opts, sizeof(opts), "fd=%d,minproto=5,maxproto=5", pfd);
+ if (mount("autofs", HOLDER_BELOW, "autofs", 0, opts))
+ return errno == ENODEV ? CHILD_SKIP : CHILD_HOLDER;
+ close(pfd); /* the mount keeps its own */
+ return CHILD_OK;
+}
+
+/*
+ * zram's writeback device has to be a block device node, and that node has
+ * to be on P. Point it at a second loop device.
+ */
+static int holder_zram(void)
+{
+ char buf[64];
+ int fd, n;
+
+ if (access("/sys/block/zram0/backing_dev", W_OK))
+ return CHILD_SKIP;
+ /* somebody else's device, leave it alone */
+ if (read_sysfs("/sys/block/zram0/initstate", buf, sizeof(buf)) || buf[0] != '0')
+ return CHILD_SKIP;
+ fd = open("/mnt_dir/img/wb.img", O_RDWR | O_CREAT | O_EXCL, 0600);
+ if (fd < 0 || ftruncate(fd, IMAGE_SIZE))
+ return CHILD_HOLDER;
+ close(fd);
+ n = loop_attach("/mnt_dir/img/wb.img");
+ if (n < 0)
+ return CHILD_HOLDER;
+ if (mknod(HOLDER_MNT "/wbdev", S_IFBLK | 0600, makedev(7, n)))
+ return CHILD_HOLDER;
+ if (write_file("/sys/block/zram0/backing_dev", HOLDER_MNT "/wbdev"))
+ return CHILD_HOLDER;
+ snprintf(buf, sizeof(buf), "%d", 4 * 1024 * 1024);
+ if (write_file("/sys/block/zram0/disksize", buf))
+ return CHILD_HOLDER;
+ fd = open("/dev/zram0", O_RDWR);
+ if (fd < 0 || write_fat12_4k(fd, 1024)) /* zram has 4 KiB blocks */
+ return CHILD_HOLDER;
+ close(fd);
+ if (mount("/dev/zram0", HOLDER_BELOW, "vfat", 0, NULL) &&
+ mount("/dev/zram0", HOLDER_BELOW, "msdos", 0, NULL))
+ return CHILD_HOLDER;
+ return CHILD_OK;
+}
+
+/* The kernel's auth token layout, which userspace has to match byte for byte. */
+struct ecryptfs_auth_tok {
+ __u16 version;
+ __u16 token_type;
+ __u32 flags;
+ struct {
+ __u32 flags, encrypted_key_size, decrypted_key_size;
+ __u8 encrypted_key[512], decrypted_key[64];
+ } session_key;
+ __u8 reserved[32];
+ struct {
+ __u32 password_bytes;
+ __s32 hash_algo;
+ __u32 hash_iterations, session_key_encryption_key_bytes, flags;
+ __u8 session_key_encryption_key[64];
+ __u8 signature[17];
+ __u8 salt[8];
+ } password;
+} __attribute__((packed));
+
+#define ECRYPTFS_SIG "0123456789abcdef"
+
+static int holder_ecryptfs(void)
+{
+ struct ecryptfs_auth_tok tok = {
+ .version = 0x0004,
+ .token_type = 0, /* ECRYPTFS_PASSWORD */
+ .password.session_key_encryption_key_bytes = 16,
+ .password.flags = 0x02, /* ECRYPTFS_SESSION_KEY_ENCRYPTION_KEY_SET */
+ .password.signature = ECRYPTFS_SIG,
+ };
+
+ if (syscall(__NR_add_key, "user", ECRYPTFS_SIG, &tok, sizeof(tok),
+ KEY_SPEC_SESSION_KEYRING) < 0)
+ return CHILD_HOLDER;
+ if (mkdir(HOLDER_MNT "/lower", 0755))
+ return CHILD_HOLDER;
+ if (mount(HOLDER_MNT "/lower", HOLDER_BELOW, "ecryptfs", 0,
+ "ecryptfs_sig=" ECRYPTFS_SIG ",ecryptfs_cipher=aes,ecryptfs_key_bytes=16"))
+ return errno == ENODEV ? CHILD_SKIP : CHILD_HOLDER;
+ return CHILD_OK;
+}
+
+/*
+ * binfmt_misc instances are per user namespace, so the mount below P is
+ * made from a new one, which gets a copy of P.
+ */
+static int holder_binfmt_misc(void)
+{
+ char buf[4096];
+ int in, out;
+ ssize_t n;
+
+ in = open("/proc/self/exe", O_RDONLY);
+ out = open(HOLDER_MNT "/interp", O_WRONLY | O_CREAT | O_EXCL, 0755);
+ if (in < 0 || out < 0)
+ return CHILD_HOLDER;
+ while ((n = read(in, buf, sizeof(buf))) > 0)
+ if (write(out, buf, n) != n)
+ return CHILD_HOLDER;
+ close(in);
+ close(out);
+
+ if (unshare(CLONE_NEWUSER | CLONE_NEWNS))
+ return errno == EINVAL ? CHILD_SKIP : CHILD_HOLDER;
+ if (write_file("/proc/self/setgroups", "deny") ||
+ write_file("/proc/self/uid_map", "0 0 1") ||
+ write_file("/proc/self/gid_map", "0 0 1"))
+ return CHILD_HOLDER;
+ if (mount("binfmt_misc", HOLDER_BELOW, "binfmt_misc", 0, NULL))
+ return errno == ENODEV ? CHILD_SKIP : CHILD_HOLDER;
+ if (write_file(HOLDER_BELOW "/register", ":cycle:E::cyc::" HOLDER_MNT "/interp:F"))
+ return CHILD_HOLDER;
+ return CHILD_OK;
+}
+
+/*
+ * A fuse server that only ever answers FUSE_INIT, with passthrough on, and
+ * then registers a file on P as a backing file. The registration alone
+ * makes the fuse superblock hold the file.
+ */
+static int holder_fuse(void)
+{
+ struct fuse_backing_map map = {};
+ struct fuse_in_header *ih;
+ struct fuse_init_out init = {
+ .major = FUSE_KERNEL_VERSION,
+ .minor = FUSE_KERNEL_MINOR_VERSION,
+ .flags = FUSE_INIT_EXT,
+ .flags2 = FUSE_PASSTHROUGH >> 32,
+ .max_write = 4096,
+ .max_stack_depth = 1,
+ };
+ struct fuse_out_header oh = { .len = sizeof(oh) + sizeof(init) };
+ struct iovec iov[2] = { { &oh, sizeof(oh) }, { &init, sizeof(init) } };
+ char opts[64], buf[8192];
+ int ffd, bfd;
+ ssize_t n;
+
+ bfd = open(HOLDER_MNT "/backing", O_RDWR | O_CREAT | O_EXCL, 0600);
+ if (bfd < 0)
+ return CHILD_HOLDER;
+ ffd = open("/dev/fuse", O_RDWR);
+ if (ffd < 0)
+ return CHILD_SKIP;
+ snprintf(opts, sizeof(opts), "fd=%d,rootmode=40000,user_id=0,group_id=0", ffd);
+ if (mount("fuse", HOLDER_BELOW, "fuse", 0, opts))
+ return errno == ENODEV ? CHILD_SKIP : CHILD_HOLDER;
+
+ n = read(ffd, buf, sizeof(buf));
+ ih = (void *)buf;
+ if (n < (ssize_t)sizeof(*ih) || ih->opcode != FUSE_INIT)
+ return CHILD_HOLDER;
+ oh.unique = ih->unique;
+ if (writev(ffd, iov, 2) != (ssize_t)oh.len)
+ return CHILD_HOLDER;
+
+ map.fd = bfd;
+ if (ioctl(ffd, FUSE_DEV_IOC_BACKING_OPEN, &map) < 0)
+ return errno == EPERM ? CHILD_SKIP : CHILD_HOLDER;
+ close(bfd); /* the connection keeps its own */
+ return CHILD_OK; /* ffd stays open until the child exits */
+}
+
+/* Wait for a device node the kernel is about to create. */
+static int open_when_there(const char *dev, int flags, int ms)
+{
+ int fd;
+
+ for (; ms > 0; ms -= 100) {
+ fd = open(dev, flags);
+ if (fd >= 0)
+ return fd;
+ usleep(100000);
+ }
+ return -1;
+}
+
+/*
+ * zloop keeps every zone file open. One conventional zone is enough for a
+ * FAT image, the sequential one stays empty.
+ */
+static int holder_zloop(void)
+{
+ int fd;
+
+ if (access("/dev/zloop-control", W_OK))
+ return CHILD_SKIP;
+ if (mkdir(HOLDER_MNT "/zl", 0755) || mkdir(HOLDER_MNT "/zl/0", 0755))
+ return CHILD_HOLDER;
+ if (write_file("/dev/zloop-control",
+ "add id=0,capacity_mb=8,zone_size_mb=4,conv_zones=1,base_dir=" HOLDER_MNT "/zl"))
+ return CHILD_HOLDER;
+ fd = open_when_there("/dev/zloop0", O_RDWR, 5000);
+ if (fd < 0 || write_fat12_4k(fd, 1024)) /* 4 KiB blocks, like P */
+ return CHILD_HOLDER;
+ close(fd);
+ if (mount("/dev/zloop0", HOLDER_BELOW, "vfat", 0, NULL) &&
+ mount("/dev/zloop0", HOLDER_BELOW, "msdos", 0, NULL))
+ return CHILD_HOLDER;
+ return CHILD_OK;
+}
+
+#define GADGET "/sys/kernel/config/usb_gadget/g1"
+
+/* The disk usb-storage created for the gadget, by the LUN's inquiry string. */
+static int find_gadget_disk(char *dev, size_t len, int ms)
+{
+ char path[PATH_MAX], model[64];
+ struct dirent *de;
+ DIR *d;
+
+ for (; ms > 0; ms -= 100, usleep(100000)) {
+ d = opendir("/sys/block");
+ if (!d)
+ return -1;
+ while ((de = readdir(d))) {
+ if (strncmp(de->d_name, "sd", 2))
+ continue;
+ snprintf(path, sizeof(path), "/sys/block/%s/device/model", de->d_name);
+ if (read_sysfs(path, model, sizeof(model)) ||
+ strncmp(model, "File-Stor Gadget", 16))
+ continue;
+ snprintf(dev, len, "/dev/%s", de->d_name);
+ closedir(d);
+ return 0;
+ }
+ closedir(d);
+ }
+ return -1;
+}
+
+/*
+ * A mass storage gadget bound to the dummy UDC, so that this kernel is
+ * also the USB host that sees the LUN as a SCSI disk. sd locks the
+ * medium on open, which is what keeps the LUN's file from being ejected.
+ */
+#define GADGET_STEP(x) do { \
+ if (x) { \
+ fprintf(stderr, "gadget: %s failed: %s\n", #x, strerror(errno)); \
+ return CHILD_HOLDER; \
+ } \
+} while (0)
+
+static int holder_gadget(void)
+{
+ char dev[PATH_MAX];
+ int fd;
+
+ if (access("/sys/kernel/config", F_OK) ||
+ (mount("configfs", "/sys/kernel/config", "configfs", 0, NULL) && errno != EBUSY))
+ return CHILD_SKIP;
+ if (access("/sys/kernel/config/usb_gadget", F_OK) ||
+ access("/sys/class/udc/dummy_udc.0", F_OK))
+ return CHILD_SKIP;
+
+ fd = open(HOLDER_MNT "/lun.img", O_RDWR | O_CREAT | O_EXCL, 0600);
+ if (fd < 0 || write_fat12(fd))
+ return CHILD_HOLDER;
+ close(fd);
+
+ GADGET_STEP(mkdir(GADGET, 0755));
+ GADGET_STEP(write_file(GADGET "/idVendor", "0x1d6b"));
+ GADGET_STEP(write_file(GADGET "/idProduct", "0x0104"));
+ GADGET_STEP(mkdir(GADGET "/strings/0x409", 0755));
+ GADGET_STEP(write_file(GADGET "/strings/0x409/serialnumber", "1"));
+ GADGET_STEP(write_file(GADGET "/strings/0x409/manufacturer", "kselftest"));
+ GADGET_STEP(write_file(GADGET "/strings/0x409/product", "cycle"));
+ GADGET_STEP(mkdir(GADGET "/configs/c.1", 0755));
+ GADGET_STEP(mkdir(GADGET "/configs/c.1/strings/0x409", 0755));
+ GADGET_STEP(write_file(GADGET "/configs/c.1/strings/0x409/configuration", "c"));
+ GADGET_STEP(mkdir(GADGET "/functions/mass_storage.0", 0755));
+ GADGET_STEP(write_file(GADGET "/functions/mass_storage.0/lun.0/removable", "1"));
+ GADGET_STEP(write_file(GADGET "/functions/mass_storage.0/lun.0/file", HOLDER_MNT "/lun.img"));
+ GADGET_STEP(symlink(GADGET "/functions/mass_storage.0", GADGET "/configs/c.1/mass_storage.0"));
+ GADGET_STEP(write_file(GADGET "/UDC", "dummy_udc.0"));
+
+ /* usb-storage waits a second before it scans the device */
+ GADGET_STEP(find_gadget_disk(dev, sizeof(dev), 15000));
+ fd = open_when_there(dev, O_RDONLY, 5000);
+ GADGET_STEP(fd < 0);
+ close(fd);
+ if (mount(dev, HOLDER_BELOW, "vfat", 0, NULL) &&
+ mount(dev, HOLDER_BELOW, "msdos", 0, NULL))
+ return CHILD_HOLDER;
+ return CHILD_OK;
+}
+
+#define BITMAP_MAGIC 0x6d746962
+
+/*
+ * A RAID1 of one loop device, not persistent, with its bitmap in a file
+ * on P. The bitmap file needs a superblock the kernel accepts; sync_size,
+ * uuid and events are not looked at for a non-persistent array.
+ */
+static int holder_md(void)
+{
+ struct {
+ __u32 magic, version;
+ __u8 uuid[16];
+ __u64 events, events_cleared, sync_size;
+ __u32 state, chunksize, daemon_sleep, write_behind;
+ } bsb = {
+ .magic = BITMAP_MAGIC,
+ .version = 4,
+ .chunksize = 64 * 1024,
+ .daemon_sleep = 5,
+ };
+ mdu_array_info_t info = {
+ .level = 1,
+ .raid_disks = 1,
+ .size = 8 * 1024, /* KiB */
+ .not_persistent = 1,
+ };
+ mdu_disk_info_t disk = {
+ .major = 7,
+ .state = (1 << MD_DISK_ACTIVE) | (1 << MD_DISK_SYNC),
+ };
+ int fd, mdfd, bfd, n;
+ char buf[4096];
+
+ fd = open("/mnt_dir/img/md.img", O_RDWR | O_CREAT | O_EXCL, 0600);
+ if (fd < 0 || ftruncate(fd, 8 * 1024 * 1024))
+ return CHILD_HOLDER;
+ close(fd);
+ n = loop_attach("/mnt_dir/img/md.img");
+ if (n < 0)
+ return CHILD_HOLDER;
+ disk.minor = n;
+
+ bfd = open(HOLDER_MNT "/bitmap", O_RDWR | O_CREAT | O_EXCL, 0600);
+ if (bfd < 0 || write(bfd, &bsb, sizeof(bsb)) != sizeof(bsb) || ftruncate(bfd, 4096))
+ return CHILD_HOLDER;
+
+ if (read_sysfs("/proc/mdstat", buf, sizeof(buf)) || !strstr(buf, "[raid1]")) {
+ fprintf(stderr, "md: no raid1 personality: %s\n", buf);
+ return CHILD_SKIP;
+ }
+ if (access("/dev/md0", F_OK) && mknod("/dev/md0", S_IFBLK | 0600, makedev(9, 0)))
+ return CHILD_HOLDER;
+ mdfd = open("/dev/md0", O_RDWR);
+ if (mdfd < 0)
+ return CHILD_SKIP;
+ /* the bitmap ops are only installed once a bitmap type is chosen */
+ write_file("/sys/block/md0/md/bitmap_type", "bitmap");
+ /* EBUSY: somebody else's array, leave it alone */
+ if (ioctl(mdfd, SET_ARRAY_INFO, &info))
+ return errno == EBUSY ? CHILD_SKIP : CHILD_HOLDER;
+ if (ioctl(mdfd, ADD_NEW_DISK, &disk))
+ return CHILD_HOLDER;
+ /* attach the bitmap file before the array runs, the way mdadm does */
+ if (ioctl(mdfd, SET_BITMAP_FILE, bfd)) {
+ fprintf(stderr, "md: SET_BITMAP_FILE: %s\n", strerror(errno));
+ return errno == EINVAL ? CHILD_SKIP : CHILD_HOLDER;
+ }
+ close(bfd); /* the array keeps its own */
+ if (ioctl(mdfd, RUN_ARRAY, NULL)) {
+ fprintf(stderr, "md: RUN_ARRAY: %s\n", strerror(errno));
+ return CHILD_HOLDER;
+ }
+ if (write_fat12(mdfd))
+ return CHILD_HOLDER;
+ close(mdfd);
+ if (mount("/dev/md0", HOLDER_BELOW, "vfat", 0, NULL) &&
+ mount("/dev/md0", HOLDER_BELOW, "msdos", 0, NULL))
+ return CHILD_HOLDER;
+ return CHILD_OK;
+}
+
+/*
+ * In its own mount namespace the child puts the image on a tmpfs next to
+ * P, mounts P from a loop device, and sets the holder up with its own
+ * filesystem or device mounted at C below P.
+ */
+static int holder_child(int to_parent, int from_parent, enum holder holder)
+{
+ bool fifo = holder == HOLDER_AUTOFS || holder == HOLDER_ZRAM;
+ /* room for a 4 MiB zone file or a floppy image on P */
+ bool big = holder == HOLDER_ZLOOP || holder == HOLDER_GADGET;
+ const char *type = fifo ? "minix" : "vfat";
+ char dev[32], c;
+ int ifd, n, ret;
+
+ if (unshare(CLONE_NEWNS) || mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL))
+ return CHILD_NS;
+ if (mkdir("/mnt_dir/img", 0755) || mount("tmpfs", "/mnt_dir/img", "tmpfs", 0, NULL))
+ return CHILD_NS;
+
+ ifd = open(HOLDER_IMG, O_RDWR | O_CREAT | O_EXCL, 0600);
+ if (ifd < 0 || (fifo ? write_minix(ifd) :
+ big ? write_fat12_4k(ifd, 3072) : write_fat12(ifd)))
+ return CHILD_IMAGE;
+ close(ifd);
+ n = loop_attach(HOLDER_IMG);
+ if (n < 0)
+ return CHILD_LOOP;
+ snprintf(dev, sizeof(dev), "/dev/loop%d", n);
+ if (mkdir(HOLDER_MNT, 0755))
+ return CHILD_MOUNT;
+ if (mount(dev, HOLDER_MNT, type, 0, NULL) &&
+ (fifo || mount(dev, HOLDER_MNT, "msdos", 0, NULL)))
+ return fifo && errno == ENODEV ? CHILD_SKIP : CHILD_MOUNT;
+ if (mkdir(HOLDER_BELOW, 0755))
+ return CHILD_MOUNT;
+
+ switch (holder) {
+ case HOLDER_AUTOFS:
+ ret = holder_autofs();
+ break;
+ case HOLDER_ZRAM:
+ ret = holder_zram();
+ break;
+ case HOLDER_ECRYPTFS:
+ ret = holder_ecryptfs();
+ break;
+ case HOLDER_BINFMT_MISC:
+ ret = holder_binfmt_misc();
+ break;
+ case HOLDER_FUSE:
+ ret = holder_fuse();
+ break;
+ case HOLDER_ZLOOP:
+ ret = holder_zloop();
+ break;
+ case HOLDER_GADGET:
+ ret = holder_gadget();
+ break;
+ case HOLDER_MD:
+ ret = holder_md();
+ break;
+ default:
+ ret = CHILD_HOLDER;
+ }
+ if (ret != CHILD_OK)
+ return ret;
+
+ if (write(to_parent, &n, sizeof(n)) != sizeof(n))
+ return CHILD_PIPE;
+ if (read(from_parent, &c, 1) != 1)
+ return CHILD_PIPE;
+ return CHILD_OK;
+}
+
+/*
+ * A device keeps its file for as long as it is configured, so once nothing
+ * below the dead mount is left the device has to be told to let go. With
+ * the cycle unbroken C's filesystem still holds the device and every one
+ * of these refuses.
+ */
+static int holder_let_go_once(enum holder holder)
+{
+ int fd, ret;
+
+ switch (holder) {
+ case HOLDER_ZRAM:
+ return write_file("/sys/block/zram0/reset", "1");
+ case HOLDER_ZLOOP:
+ return write_file("/dev/zloop-control", "remove id=0");
+ case HOLDER_GADGET:
+ if (mount("configfs", "/sys/kernel/config", "configfs", 0, NULL) && errno != EBUSY)
+ return -1;
+ /* a zero-length write is a no-op for configfs; a newline ejects */
+ return write_file(GADGET "/functions/mass_storage.0/lun.0/file", "\n");
+ case HOLDER_MD:
+ fd = open("/dev/md0", O_RDONLY);
+ if (fd < 0)
+ return -1;
+ ret = ioctl(fd, STOP_ARRAY);
+ close(fd);
+ return ret;
+ default:
+ return 0;
+ }
+}
+
+/*
+ * The release of C's filesystem may still be in flight when the child is
+ * gone, and a device that is still held refuses to let go, so try for a
+ * while. With the cycle unbroken it refuses for good.
+ */
+static void holder_let_go(enum holder holder)
+{
+ for (int i = 0; i < 50; i++) {
+ if (!holder_let_go_once(holder))
+ return;
+ usleep(100000);
+ }
+}
+
+/*
+ * rmdir of /mnt_dir/p from here, where it is a plain directory, detaches
+ * P in the child's namespace with C connected below it. Once the child is
+ * gone the holder's file on P is the only thing left that refers to P,
+ * and it is dropped only when C's filesystem dies, which waits for P.
+ * The loop device backing P tells whether that resolved.
+ */
+static void holder_cycle(struct __test_metadata *_metadata,
+ FIXTURE_DATA(loop_cycle) *self, enum holder holder)
+{
+ int to_parent[2], from_parent[2], status, n;
+ pid_t pid;
+
+ ASSERT_EQ(pipe(to_parent), 0);
+ ASSERT_EQ(pipe(from_parent), 0);
+ pid = fork();
+ ASSERT_GE(pid, 0);
+ if (pid == 0) {
+ close(to_parent[0]);
+ close(from_parent[1]);
+ _exit(holder_child(to_parent[1], from_parent[0], holder));
+ }
+ close(to_parent[1]);
+ close(from_parent[0]);
+
+ if (read(to_parent[0], &n, sizeof(n)) != sizeof(n)) {
+ waitpid(pid, &status, 0);
+ if (WIFEXITED(status) && WEXITSTATUS(status) == CHILD_SKIP)
+ SKIP(return, "the kernel lacks what this holder needs");
+ ASSERT_TRUE(false)
+ TH_LOG("child failed to set the holder up: exit status %d",
+ WIFEXITED(status) ? WEXITSTATUS(status) : -1);
+ }
+ snprintf(self->dev, sizeof(self->dev), "/dev/loop%d", n);
+ snprintf(self->sysfs, sizeof(self->sysfs), "/sys/block/loop%d/loop/backing_file", n);
+
+ ASSERT_EQ(rmdir(HOLDER_MNT), 0);
+ ASSERT_EQ(write(from_parent[1], "x", 1), 1);
+ ASSERT_EQ(waitpid(pid, &status, 0), pid);
+ ASSERT_EQ(WEXITSTATUS(status), CHILD_OK);
+
+ holder_let_go(holder);
+ assert_loop_released(_metadata, self);
+ if (holder == HOLDER_GADGET)
+ write_file(GADGET "/UDC", "\n");
+}
+
+TEST_F(loop_cycle, autofs_pipe_on_dead_mount_released)
+{
+ holder_cycle(_metadata, self, HOLDER_AUTOFS);
+}
+
+TEST_F(loop_cycle, zram_writeback_node_on_dead_mount_released)
+{
+ holder_cycle(_metadata, self, HOLDER_ZRAM);
+}
+
+TEST_F(loop_cycle, ecryptfs_lower_on_dead_mount_released)
+{
+ holder_cycle(_metadata, self, HOLDER_ECRYPTFS);
+}
+
+TEST_F(loop_cycle, binfmt_misc_interpreter_on_dead_mount_released)
+{
+ holder_cycle(_metadata, self, HOLDER_BINFMT_MISC);
+}
+
+TEST_F(loop_cycle, fuse_backing_file_on_dead_mount_released)
+{
+ holder_cycle(_metadata, self, HOLDER_FUSE);
+}
+
+TEST_F(loop_cycle, zloop_zone_files_on_dead_mount_released)
+{
+ holder_cycle(_metadata, self, HOLDER_ZLOOP);
+}
+
+TEST_F(loop_cycle, mass_storage_lun_on_dead_mount_released)
+{
+ holder_cycle(_metadata, self, HOLDER_GADGET);
+}
+
+TEST_F(loop_cycle, md_bitmap_file_on_dead_mount_released)
+{
+ holder_cycle(_metadata, self, HOLDER_MD);
+}
+
+TEST_HARNESS_MAIN
|
| 3/2 | 2026/09/26 03:18 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 25056 output: 26 thoughts: 1794 Thoughts: **VFS Mount Lifecycle and fsnotify Patch Analysis** Alright, let's dive into this patch series. My initial assessment is that this is significant, touching as it does the core VFS, particularly the mount and unmount lifecycle, and also fsnotify. Firstly, the patch modifies `fs/fsopen.c`, adding a check within `SYSCALL_DEFINE3(fspick...)`, suggesting potential behavior changes during filesystem picking. I'll need to double-check how `fspick` is actually exposed to the syscall interface, in order to know what the symbol exposed is. Then, there's a lot going on within `fs/namespace.c`. The introduction of "vacant mounts" is a key aspect. It seems the patch is addressing a scenario where a mount loses its last reference, but remains attached. The added `knullfs` and related functions (`vacate_mount`, `cleanup_mnt`, `mntput_no_expire_slowpath`, `is_vacant`, `__setup_mnt`, `mnt_alloc_unique_id`, `__detach_mounts`, `umount_tree`, and `namespace_unlock`) handle the lifecycle of these vacant mounts. I'm particularly interested in how `vacate_mount` is used by `mntput_no_expire_slowpath` and in what cases. I'll need to understand the interactions between these new functions and the existing mount/unmount logic. I'll also want to understand the impact of the list changes in `namespace_unlock`, `umount_tree`, and `__detach_mounts`. The modifications in `fs/notify/` are also of note. Caching `conn->sb` in `fsnotify_mark_connector` strongly suggests that the patch is meant to prevent or fix potential race conditions related to the superblock when the mount is "switched" or cleaned up. This would prevent the `fsnotify` code from crashing or misbehaving. The functions here that have my attention are `fsnotify_init_connector`, `fsnotify_detach_connector_from_object`, `fsnotify_add_mark_list`, and the inline `fsnotify_connector_sb`. Based on the prompt's criteria, this is unequivocally WorthFuzzing=true. We're dealing with core VFS logic here, directly accessible through system calls (`mount`, `umount`, `fspick`, `open_tree`, `move_mount`, `fanotify_mark`, `inotify_add_watch`, etc.), making it a perfect target for fuzzing. Now, let's pinpoint the specific symbols to focus on for fuzzing. Given the patch's changes, I'd say the following functions are the most relevant: * In `fs/fsopen.c`: Whatever function `SYSCALL_DEFINE3(fspick)` exposes - either `__se_sys_fspick` or `__do_sys_fspick`, or just `fspick`. * In `fs/namespace.c`: `vacate_mount`, `cleanup_mnt`, `mntput_no_expire_slowpath`, `namespace_unlock`, `umount_tree`, `__detach_mounts`, `__setup_mnt`, `setup_mnt`, `mnt_alloc_unique_id`. * In `fs/notify/mark.c`: `fsnotify_init_connector`, `fsnotify_detach_connector_from_object`, `fsnotify_add_mark_list`. * In `fs/notify/fsnotify.h`: `fsnotify_connector_sb`. I'll need to check the codebase to confirm whether any of these are inlined or static, as this affects how Syzkaller will be able to target them. I'll pay close attention to the call sites of `vacate_mount` and `cleanup_mnt` to understand the broader impact. I also want to double-check the logic of the VFS warnings introduced in `vacate_mount` and `cleanup_mnt`. It's also worth noting the addition of the `loop_cycle_test` selftest; I'll want to review that as well, as it likely hints at the type of mount-related cycles or issues the patch is trying to address. |
| 4/2 | 2026/09/26 03:18 | tool | grepper |
0mArgs:{
"Expression": "vacate_mount",
"PathPrefix": "fs/"
}Results: {
"Output": "fs/namespace.c=1328=static void cleanup_mnt(struct mount *mnt)\n--\nfs/namespace.c-1354-\tif (unlikely(release)) {\nfs/namespace.c:1355:\t\t/* the reference vacate_mount() gave the release */\nfs/namespace.c-1356-\t\tmntput(\u0026mnt-\u003emnt);\n--\nfs/namespace.c-1366- */\nfs/namespace.c:1367:static void vacate_mount(struct mount *mnt)\nfs/namespace.c-1368-{\n--\nfs/namespace.c=1396=static void noinline mntput_no_expire_slowpath(struct mount *mnt)\n--\nfs/namespace.c-1442-\tif (unlikely(vacate))\nfs/namespace.c:1443:\t\tvacate_mount(mnt);\nfs/namespace.c-1444-\tunlock_mount_hash();\n--\nfs/namespace.c=6278=static void __init init_mount_tree(void)\n--\nfs/namespace.c-6293-\t * A mount that dies while still attached to its parent is pointed\nfs/namespace.c:6294:\t * at (3) as well, see vacate_mount().\nfs/namespace.c-6295-\t */\n"
} |
| 5/2 | 2026/09/26 03:18 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 28149 output: 31 thoughts: 319 Thoughts: **Analyzing Potential Hot-Paths in File System Operations** Okay, let's dive into this. I need to review this code and pinpoint any potential issues, especially regarding lifecycle management. My initial thought is to examine functions like `vacate_mount`, `cleanup_mnt`, `mntput_no_expire_slowpath`, `umount_tree`, `__detach_mounts`, `namespace_unlock`, and `fspick`. Those seem like sensible starting points for understanding how mounts are handled. But hold on a second... is `mntput_no_expire_slowpath` truly ubiquitous? That's a crucial question. We need to be careful about including functions that are called everywhere, as that would dilute the fuzzing effort. I need to make sure I am focusing the fuzzing effort effectively. Right, let's consult Section 4 of the guidelines. Ah, here it is: "AVOID UBIQUITOUS LIFECYCLE HOT-PATHS...". It explicitly says *not* to list generic, ubiquitous functions. That makes perfect sense; it's a critical point to avoid wasting resources on fuzzing. It emphasizes focusing on specific feature logic and entry points. So, back to the question: is `mntput_no_expire_slowpath` ubiquitous? I need to think this through carefully. Let's see... `mntput` is called every time a file or path is closed, or when unmounting. Hmm, `mntput_no_expire` checks if the mount's refcount is greater than one. If the refcount drops to zero (or one in some situations), then `mntput_no_expire_slowpath` gets called. Now, I have to consider the implications of every file/path close, or unmount, calling `mntput`. This seems quite common. Okay, I need to check `mntput` itself. Let's look at `fs/namespace.c` for that. I need to establish a solid understanding of how often it's used. |
| 6/2 | 2026/09/26 03:18 | tool | grepper |
0mArgs:{
"Expression": "mntput_no_expire_slowpath",
"PathPrefix": "fs/"
}Results: {
"Output": "fs/namespace.c=1394=static DECLARE_DELAYED_WORK(delayed_mntput_work, delayed_mntput);\nfs/namespace.c-1395-\nfs/namespace.c:1396:static void noinline mntput_no_expire_slowpath(struct mount *mnt)\nfs/namespace.c-1397-{\n--\nfs/namespace.c=1461=static void mntput_no_expire(struct mount *mnt)\n--\nfs/namespace.c-1477-\t}\nfs/namespace.c:1478:\tmntput_no_expire_slowpath(mnt);\nfs/namespace.c-1479-}\n"
} |
| 7/2 | 2026/09/26 03:18 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 29111 output: 31 thoughts: 465 Thoughts: **Analyzing Potential Syzkaller Coverage of Recent Mount/Unmount Changes** Okay, let's break this down. First, I noticed `mntput_no_expire_slowpath` is flagged as `noinline`, which immediately caught my attention. I know this function is responsible for the delicate task of dropping a mount when its reference count hits zero or during unmounting. I then went to check `cleanup_mnt`, also in `fs/namespace.c`. Next I thought about `vacate_mount`, which is `static` and called only within `mntput_no_expire_slowpath`. The compiler *might* inline it, and that's the key question. If the compiler does inline `vacate_mount`, a specific function for the added logic, Syzkaller coverage could be affected. Even if inlined, could Syzkaller still identify it through kallsyms or DWARF? Syzkaller relies on kallsyms for symbol coverage checks. Inlined functions disappear from kallsyms, so that would be problematic. To ensure I'm getting a comprehensive understanding, I switched gears to identify *all* the key functions modified or added related to this area. I needed to ensure my coverage analysis is complete and accurate. I compiled a list, starting with `vacate_mount`, and included `cleanup_mnt`, `mntput_no_expire_slowpath`, `umount_tree`, `__detach_mounts`, `namespace_unlock`, `setup_mnt`, and now, `fspick` or `__do_sys_fspick`, as well as file system notification changes, namely `fsnotify_init_connector`, `fsnotify_detach_connector_from_object`, and `fsnotify_add_mark_list`. I had to keep a list to organize my thoughts. Finally, I need to understand how Syzkaller identifies syscalls like `fspick`. Remembering my kernel internals, especially for x86_64 systems, it could be either `__x64_sys_fspick` or `__do_sys_fspick`. That means I should grep for `fspick` in `fs/fsopen.c`, as a starting point. This is to make sure I am accounting for all possible functions. |
| 8/2 | 2026/09/26 03:18 | tool | grepper |
0mArgs:{
"Expression": "SYSCALL_DEFINE.*fspick",
"PathPrefix": "fs/"
}Results: {
"Output": "fs/fsopen.c=120=SYSCALL_DEFINE2(fsopen, const char __user *, _fs_name, unsigned int, flags)\n--\nfs/fsopen.c-162- */\nfs/fsopen.c:163:SYSCALL_DEFINE3(fspick, int, dfd, const char __user *, path, unsigned int, flags)\nfs/fsopen.c-164-{\n"
} |
| 9/2 | 2026/09/26 03:18 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 30212 output: 34 thoughts: 218 Thoughts: **Analyzing the `fspick` System Call** Okay, let's dive into this `fspick` system call. My initial instinct is to start by examining the generated functions, specifically `__se_sys_fspick` and `__do_sys_fspick`. Based on my understanding of how system calls are typically handled in the kernel, I know these likely come from a `SYSCALL_DEFINE3(fspick, ...)` macro. Now, a quick check – can either the base `fspick` symbol, or `__do_sys_fspick` itself be directly included? My intuition tells me to investigate. Right, I'm remembering that `SYSCALL_DEFINE` generates a family of symbols, including `__do_sys_fspick`, `__se_sys_fspick`, and on x86, there's also usually a `__x64_sys_fspick`. That's a good mental note. Thinking about syzkaller's FocusSymbols, that's where kernel symbol names, usually the `__do_sys_fspick` or the helper function (like `do_fspick`) can be found. In this instance, I know it's in `fs/fsopen.c`, line 163 where I see `SYSCALL_DEFINE3(fspick, ...)`. To get a clearer picture, I'm going to read lines 160 through 210 of `fs/fsopen.c`. I need to figure out if there's a helper function that `fspick` might call. That will give me a better understanding of the call's overall structure and potentially where the core logic resides. |
| 10/2 | 2026/09/26 03:18 | tool | read-file |
0mArgs:{
"File": "fs/fsopen.c",
"FirstLine": 160,
"LineCount": 60
}Results: {
"Contents": " 160:\t/*\n 161:\t * Pick a superblock into a context for reconfiguration.\n 162:\t */\n 163:\tSYSCALL_DEFINE3(fspick, int, dfd, const char __user *, path, unsigned int, flags)\n 164:\t{\n 165:\t\tstruct fs_context *fc;\n 166:\t\tstruct path target;\n 167:\t\tunsigned int lookup_flags;\n 168:\t\tint ret;\n 169:\t\n 170:\t\tif (!may_mount())\n 171:\t\t\treturn -EPERM;\n 172:\t\n 173:\t\tif ((flags \u0026 ~(FSPICK_CLOEXEC |\n 174:\t\t\t FSPICK_SYMLINK_NOFOLLOW |\n 175:\t\t\t FSPICK_NO_AUTOMOUNT |\n 176:\t\t\t FSPICK_EMPTY_PATH)) != 0)\n 177:\t\t\treturn -EINVAL;\n 178:\t\n 179:\t\tlookup_flags = LOOKUP_FOLLOW | LOOKUP_AUTOMOUNT;\n 180:\t\tif (flags \u0026 FSPICK_SYMLINK_NOFOLLOW)\n 181:\t\t\tlookup_flags \u0026= ~LOOKUP_FOLLOW;\n 182:\t\tif (flags \u0026 FSPICK_NO_AUTOMOUNT)\n 183:\t\t\tlookup_flags \u0026= ~LOOKUP_AUTOMOUNT;\n 184:\t\tCLASS(filename_flags, filename)(path,\n 185:\t\t\t\t (flags \u0026 FSPICK_EMPTY_PATH) ? LOOKUP_EMPTY : 0);\n 186:\t\tret = filename_lookup(dfd, filename, lookup_flags, \u0026target, NULL);\n 187:\t\tif (ret \u003c 0)\n 188:\t\t\tgoto err;\n 189:\t\n 190:\t\tret = -EINVAL;\n 191:\t\tif (target.mnt-\u003emnt_root != target.dentry)\n 192:\t\t\tgoto err_path;\n 193:\t\t/* kernel-internal superblocks are nobody's to reconfigure */\n 194:\t\tif (target.dentry-\u003ed_sb-\u003es_flags \u0026 SB_NOUSER)\n 195:\t\t\tgoto err_path;\n 196:\t\n 197:\t\tfc = fs_context_for_reconfigure(target.dentry, 0, 0);\n 198:\t\tif (IS_ERR(fc)) {\n 199:\t\t\tret = PTR_ERR(fc);\n 200:\t\t\tgoto err_path;\n 201:\t\t}\n 202:\t\n 203:\t\tfc-\u003ephase = FS_CONTEXT_RECONF_PARAMS;\n 204:\t\n 205:\t\tret = fscontext_alloc_log(fc);\n 206:\t\tif (ret \u003c 0)\n 207:\t\t\tgoto err_fc;\n 208:\t\n 209:\t\tpath_put(\u0026target);\n 210:\t\treturn fscontext_create_fd(fc, flags \u0026 FSPICK_CLOEXEC ? O_CLOEXEC : 0);\n 211:\t\n 212:\terr_fc:\n 213:\t\tput_fs_context(fc);\n 214:\terr_path:\n 215:\t\tpath_put(\u0026target);\n 216:\terr:\n 217:\t\treturn ret;\n 218:\t}\n 219:\t\n"
} |
| 11/2 | 2026/09/26 03:18 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 31739 output: 28 thoughts: 707 Thoughts: **Analyzing a Vacant Mount and its Impact on Filesystem Notifications** Okay, let's break this down. First, I see `fspick` checks for `SB_NOUSER` on the superblock. It appears this flag is set for `knullfs`, which is used for vacant mounts. So, if `fspick` is called on a vacant mount, it's rejected with `-EINVAL`. This makes sense, it's a security/sanity check. Now, the core of the issue seems to be around `fsnotify`. I remember that code... Let's look at `fsnotify/mark.c`. Specifically, functions like `fsnotify_detach_connector_from_object`, `fsnotify_init_connector`, and `fsnotify_add_mark_list` are modified. And the key is in the change from `fsnotify_connector_sb` returning `fsnotify_object_sb(conn->obj, conn->type);`. Ah, right, with vacant mounts, the superblock changes! When a mount is vacated using `vacate_mount(mnt)`, the superblock switches to `knullfs->mnt_sb`. Previously, `fsnotify_object_sb` for a mount would look up the superblock using `real_mount(obj)->mnt.mnt_sb`. So before the patch, calls to `fsnotify_connector_sb`, or passing `sb` to `fsnotify_update_sb_watchers(sb, conn)`, would lead to an issue. If the mount's superblock changed to `knullfs`, fsnotify would be updating watchers on the wrong superblock – `knullfs` instead of the original filesystem's. This is a classic accounting error, potentially leading to imbalance, use-after-free, or list corruption. The patch resolves this by adding a `struct super_block *sb;` to `struct fsnotify_mark_connector` to remember which superblock the connector was initially associated with. That's a clean solution. Let me refresh myself on the `fs/notify/mark.c` code to make sure I understand how those functions fit together: `fsnotify_init_connector`, `fsnotify_detach_connector_from_object`, and `fsnotify_add_mark_list` are all part of the relevant patch. Now, let's quickly glance at `fs/namespace.c`. A lot of functions are modified: `vacate_mount`, `cleanup_mnt`, `mntput_no_expire_slowpath`, `namespace_unlock`, `umount_tree`, `__detach_mounts`, `setup_mnt`, `__setup_mnt`, `mnt_alloc_unique_id`, and `disconnect_mount`. Looks like the vacant mount logic is being touched. Let's quickly check `disconnect_mount`. Is it static? Yes, it is: `static bool disconnect_mount(struct mount *mnt, enum umount_tree_flags how)`. Okay, looking at the comments in that function... looks like no functional change, just documentation updates. To be thorough, let me double-check lines 1740-1847 to make sure I did not miss anything. |
| 12/2 | 2026/09/26 03:19 | tool | grepper |
0mArgs:{
"Expression": "disconnect_mount",
"PathPrefix": "fs/namespace.c"
}Results: {
"Output": "fs/namespace.c=1804=enum umount_tree_flags {\n--\nfs/namespace.c-1822- */\nfs/namespace.c:1823:static bool disconnect_mount(struct mount *mnt, enum umount_tree_flags how)\nfs/namespace.c-1824-{\n--\nfs/namespace.c=1849=static void umount_tree(struct mount *mnt, enum umount_tree_flags how)\n--\nfs/namespace.c-1890-\nfs/namespace.c:1891:\t\tdisconnect = disconnect_mount(p, how);\nfs/namespace.c-1892-\t\tif (mnt_has_parent(p)) {\n"
} |
| 13/2 | 2026/09/26 03:19 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 33344 output: 27 thoughts: 58 Thoughts: Okay, let's dive into this code. **Investigating Mount Detachment and Cleanup** Alright, my immediate focus is on how mounts are detached and cleaned up. My initial thought process is to trace a few key functions: `umount_tree`, `__detach_mounts`, `namespace_unlock`, `cleanup_mnt`, `vacate_mount`, and `mntput_no_expire_slowpath`. I need to understand the order of operations and interactions between these. Specifically, I need to know the call structure and data dependencies of these routines to gain a full comprehension. Now, my next step is to specifically focus on the call sites of `__detach_mounts`. Understanding who's calling it is crucial to understand the context and rationale for the detach operation, which is central to overall stability. |
| 14/2 | 2026/09/26 03:19 | tool | grepper |
0mArgs:{
"Expression": "__detach_mounts",
"PathPrefix": "fs/"
}Results: {
"Output": "fs/mount.h=150=static inline bool __path_is_mountpoint(const struct path *path)\n--\nfs/mount.h-155-\nfs/mount.h:156:extern void __detach_mounts(struct dentry *dentry);\nfs/mount.h-157-\nfs/mount.h=158=static inline void detach_mounts(struct dentry *dentry)\n--\nfs/mount.h-161-\t\treturn;\nfs/mount.h:162:\t__detach_mounts(dentry);\nfs/mount.h-163-}\n--\nfs/namespace.c=1943=static int do_umount(struct mount *mnt, int flags)\n--\nfs/namespace.c-2044-/*\nfs/namespace.c:2045: * __detach_mounts - lazily unmount all mounts on the specified dentry\nfs/namespace.c-2046- *\n--\nfs/namespace.c-2053- */\nfs/namespace.c:2054:void __detach_mounts(struct dentry *dentry)\nfs/namespace.c-2055-{\n"
} |
| 15/2 | 2026/09/26 03:19 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 33905 output: 28 thoughts: 324 Thoughts: **Dissecting the Mount Detachment Process** Okay, so `__detach_mounts` isn't static, it's a regular function with the signature `void __detach_mounts(struct dentry *dentry)`. My job now is to understand its usage. Let's see who's calling it. It looks like `detach_mounts(dentry)` gets triggered when a directory is unlinked, removed, or renamed. More specifically, `d_delete`, `d_invalidate`, or `vfs_rmdir` seem to be the culprits. Inside `__detach_mounts`, the code iterates through potential mounts. Ah, I see, it checks if a mount has the `MNT_UMOUNT` flag set. If it does, `umount_mnt` is invoked. If the mount is considered 'vacant' after the unmount, it's added to a `unmounted` list. Otherwise, `umount_tree` is called with the `UMOUNT_CONNECTED` flag. Now, I need to know what happens *after* the unmount. Let's dig into `cleanup_mnt`. Who calls *that*? Okay, `__cleanup_mnt` (which seems to be an RCU callback) calls `cleanup_mnt` directly, and `delayed_mntput` also makes a call. This means there's a delayed clean-up mechanism involved. I need to understand that relationship better. Let's check the callers of `cleanup_mnt` again, to refresh my memory and make sure I haven't missed anything. |
| 16/2 | 2026/09/26 03:19 | tool | grepper |
0mArgs:{
"Expression": "cleanup_mnt",
"PathPrefix": "fs/namespace.c"
}Results: {
"Output": "fs/namespace.c=1323=static inline bool is_vacant(const struct mount *mnt)\n--\nfs/namespace.c-1327-\nfs/namespace.c:1328:static void cleanup_mnt(struct mount *mnt)\nfs/namespace.c-1329-{\n--\nfs/namespace.c=1367=static void vacate_mount(struct mount *mnt)\n--\nfs/namespace.c-1375-\tmnt-\u003emnt_id_unique = mnt_alloc_unique_id();\nfs/namespace.c:1376:\t/* One reference for the parent and one for cleanup_mnt(). */\nfs/namespace.c-1377-\tmnt_add_count(mnt, 2);\n--\nfs/namespace.c-1379-\nfs/namespace.c:1380:static void __cleanup_mnt(struct rcu_head *head)\nfs/namespace.c-1381-{\nfs/namespace.c:1382:\tcleanup_mnt(container_of(head, struct mount, mnt_rcu));\nfs/namespace.c-1383-}\n--\nfs/namespace.c=1386=static void delayed_mntput(struct work_struct *unused)\n--\nfs/namespace.c-1391-\tllist_for_each_entry_safe(m, t, node, mnt_llist)\nfs/namespace.c:1392:\t\tcleanup_mnt(m);\nfs/namespace.c-1393-}\n--\nfs/namespace.c=1396=static void noinline mntput_no_expire_slowpath(struct mount *mnt)\n--\nfs/namespace.c-1449-\t\tif (likely(!(task-\u003eflags \u0026 PF_KTHREAD))) {\nfs/namespace.c:1450:\t\t\tinit_task_work(\u0026mnt-\u003emnt_rcu, __cleanup_mnt);\nfs/namespace.c-1451-\t\t\tif (!task_work_add(task, \u0026mnt-\u003emnt_rcu, TWA_RESUME))\n--\nfs/namespace.c-1457-\t}\nfs/namespace.c:1458:\tcleanup_mnt(mnt);\nfs/namespace.c-1459-}\n"
} |
| 17/2 | 2026/09/26 03:19 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 35164 output: 25 thoughts: 1030 Thoughts: **Analyzing Mount Cleanup and Namespace Management** Okay, so I'm diving into this mount and namespace code, trying to get a handle on how these mount points are cleaned up and how the system handles the transition of mount states. `cleanup_mnt` seems to be the central function here. I see it handles the actual release of a mount. The `release` flag is crucial. If a mount is *not* doomed, we're dealing with an active mount. The code checks for writers, decrements references with `dput`, and deactivates the super block. If the mount is marked as "released" using the `MNT_DOOMED` flag, it calls `mntput`. If the mount isn't released, it calls `mnt_free_id`, and then schedules it for RCU cleanup. Now, `mntput_no_expire_slowpath` is interesting. This path handles the "slow" part of unmounting when a mount can't be immediately freed. The `vacate` flag plays a role here. If the mount has a parent, it gets marked for vacating; otherwise, it becomes doomed. I need to remember the difference between `vacate` and `doomed`. After this conditional, it removes the mount from the instance list, iterates through any child mounts, and attempts to unmount them using `__umount_mnt`. Vacant child mounts are moved to a `mnt_stuck_children` list. Finally, if `vacate` is true, it calls `vacate_mount` and unlocks the mount hash, then shrinks the dentry list. `namespace_unlock` is also important. This function iterates through a list of mounts in tree order and calls `mntput` on each, effectively releasing the references. This is part of the overall unmounting process. The code is written in a way to make sure that subtrees that have no references are cleaned up. Then there's `umount_tree`, which seems to manage the unmounting of entire mount trees. It adds the mount to a list for processing, irrespective of whether it's currently attached. It seems the mount always holds its own reference. Now, `vacate_mount` is critical. It appears this function is called specifically when a mount needs to be "vacated" – essentially, converted into a placeholder mount. It sets the `mnt_old_root`, swaps the root to a dummy mount `knullfs->mnt_root`, and marks the mount as read-only. It also allocates a unique mount ID and adds two references to the mount for the parent and `cleanup_mnt`. I need to review where these references are added and released to fully understand the reference counting. Okay, so I understand these basic operations. The question now is how things are connected. I think these filesystem notifications are important. I need to understand what triggers the file system notification code. Looking at `fsnotify`, I see functions like `fsnotify_init_connector`, `fsnotify_detach_connector_from_object`, and `fsnotify_add_mark_list`. I need to figure out how these come into play. I need to verify the dependencies. Are there any specific configuration options that would be relevant to reach these code paths? The fact that `mnt_pcp` was conditionally compiled with `CONFIG_SMP` is something to remember, but I also see changes outside the `#ifdef` block. Now I need to understand what makes up the standard VFS, in context of the files that are being reviewed, looking at `fs/namespace.c` and `fs/fsopen.c`, and the `fs/Makefile`. It's all connected. |
| 18/2 | 2026/09/26 03:19 | tool | grepper |
0mArgs:{
"Expression": "namespace\\.o",
"PathPrefix": "fs/"
}Results: {
"Output": "fs/Makefile=10=obj-y :=\topen.o read_write.o file_table.o super.o \\\n--\nfs/Makefile-12-\t\tioctl.o readdir.o select.o dcache.o inode.o \\\nfs/Makefile:13:\t\tattr.o bad_inode.o file.o filesystems.o namespace.o \\\nfs/Makefile-14-\t\tseq_file.o xattr.o libfs.o fs-writeback.o \\\n--\nfs/Makefile=21=obj-$(CONFIG_BUFFER_HEAD)\t+= buffer.o mpage.o\nfs/Makefile:22:obj-$(CONFIG_PROC_FS)\t\t+= proc_namespace.o\nfs/Makefile-23-obj-$(CONFIG_LEGACY_DIRECT_IO)\t+= direct-io.o\n--\nfs/nfs/Makefile=9=nfs-y \t\t\t:= client.o dir.o file.o getroot.o inode.o super.o \\\nfs/nfs/Makefile-10-\t\t\t io.o direct.o pagelist.o read.o symlink.o unlink.o \\\nfs/nfs/Makefile:11:\t\t\t write.o namespace.o mount_clnt.o nfstrace.o \\\nfs/nfs/Makefile-12-\t\t\t export.o sysfs.o fs_context.o\n--\nfs/nfs/Makefile=27=nfsv4-y := nfs4proc.o nfs4xdr.o nfs4state.o nfs4renewd.o nfs4super.o nfs4file.o \\\nfs/nfs/Makefile-28-\t delegation.o nfs4idmap.o callback.o callback_xdr.o callback_proc.o \\\nfs/nfs/Makefile:29:\t nfs4namespace.o nfs4getroot.o nfs4client.o nfs4session.o \\\nfs/nfs/Makefile-30-\t dns_resolve.o nfs4trace.o pnfs.o pnfs_dev.o pnfs_nfs.o\n--\nfs/smb/client/Makefile=8=cifs-y := trace.o cifsfs.o cifs_debug.o connect.o dir.o file.o \\\n--\nfs/smb/client/Makefile-14-\t dns_resolve.o cifs_spnego_negtokeninit.asn1.o asn1.o \\\nfs/smb/client/Makefile:15:\t namespace.o reparse.o\nfs/smb/client/Makefile-16-\n"
} |
| 19/2 | 2026/09/26 03:19 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 37639 output: 26 thoughts: 39 Thoughts: Okay, let's see... **Examining the Build Process** Right, so `namespace.o` is definitively always built, part of the core build (`obj-y`). Now, `fsopen.o`... I need to figure out how *it's* handled. Time to go right to the source: the `fs/Makefile`. That's where I'll find the dependencies and how this particular object file is integrated into the build. |
| 20/2 | 2026/09/26 03:19 | tool | grepper |
0mArgs:{
"Expression": "fsopen\\.o",
"PathPrefix": "fs/"
}Results: {
"Output": "fs/Makefile=10=obj-y :=\topen.o read_write.o file_table.o super.o \\\n--\nfs/Makefile-16-\t\tstack.o fs_struct.o statfs.o fs_pin.o nsfs.o \\\nfs/Makefile:17:\t\tfs_dirent.o fs_context.o fs_parser.o fsopen.o init.o \\\nfs/Makefile-18-\t\tkernel_read_file.o mnt_idmapping.o remap_range.o pidfs.o \\\n"
} |
| 21/2 | 2026/09/26 03:19 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 37944 output: 27 thoughts: 34 Thoughts: Here's my summary, as I delve into this code: **Navigating the Build System** Okay, so `fsopen.o` is indeed included in `obj-y`. That's good to confirm. Now, my next thought is about `fs/notify/`. I need to understand how *that* module is being handled in the build process. Best way to figure that out is to jump into the `fs/notify/Makefile`. Let's see what's defined there. That's where the magic probably happens. |
| 22/2 | 2026/09/26 03:19 | tool | grepper |
0mArgs:{
"Expression": "mark\\.o",
"PathPrefix": "fs/notify/"
}Results: {
"Output": "fs/notify/Makefile-1-# SPDX-License-Identifier: GPL-2.0\nfs/notify/Makefile:2:obj-$(CONFIG_FSNOTIFY)\t\t+= fsnotify.o notification.o group.o mark.o \\\nfs/notify/Makefile-3-\t\t\t\t fdinfo.o\n"
} |
| 23/2 | 2026/09/26 03:19 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 38201 output: 26 thoughts: 31 Thoughts: Here's my analysis of the situation: **Investigating the Dependency of `mark.o` on `CONFIG_FSNOTIFY`** Okay, so `CONFIG_FSNOTIFY` is the key to controlling the build of `mark.o`. That's the starting point. My next move is clear: I need to determine the default state of `CONFIG_FSNOTIFY` and if it is conditional. Does it always exist? Or is it dependent on other configurations, kernel options, or hardware? Understanding this dependency is critical because it will determine the flexibility of the `mark.o` compilation. Knowing the dependencies on the config is vital to ensure its use in a build. |
| 24/2 | 2026/09/26 03:19 | tool | grepper |
0mArgs:{
"Expression": "config FSNOTIFY",
"PathPrefix": "fs/"
}Results: {
"Output": "fs/notify/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\nfs/notify/Kconfig:2:config FSNOTIFY\nfs/notify/Kconfig-3-\tdef_bool n\n"
} |
| 25/2 | 2026/09/26 03:19 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 38466 output: 26 thoughts: 13 Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience: **Investigating the FSNOTIFY Configuration** Okay, so I need to understand the dependencies around `FSNOTIFY`. My immediate thought is, "Let's dig into the Kconfig files." I want to see precisely what other options or features trigger the selection of `FSNOTIFY` – what prerequisites or enabling conditions lead to this module being included in the build. This is a standard first step for me when reverse engineering the configuration landscape. I'm looking for the logical path: how does this become enabled, either directly or indirectly, through other dependencies? This should quickly reveal the key areas of the kernel that interact with or rely on `FSNOTIFY`. |
| 26/2 | 2026/09/26 03:19 | tool | grepper |
0mArgs:{
"Expression": "select FSNOTIFY",
"PathPrefix": "fs/"
}Results: {
"Output": "fs/notify/dnotify/Kconfig=2=config DNOTIFY\nfs/notify/dnotify/Kconfig-3-\tbool \"Dnotify support\"\nfs/notify/dnotify/Kconfig:4:\tselect FSNOTIFY\nfs/notify/dnotify/Kconfig-5-\tdefault y\n--\nfs/notify/fanotify/Kconfig=2=config FANOTIFY\nfs/notify/fanotify/Kconfig-3-\tbool \"Filesystem wide access notification\"\nfs/notify/fanotify/Kconfig:4:\tselect FSNOTIFY\nfs/notify/fanotify/Kconfig-5-\tselect EXPORTFS\n--\nfs/notify/inotify/Kconfig=2=config INOTIFY_USER\nfs/notify/inotify/Kconfig-3-\tbool \"Inotify support for userspace\"\nfs/notify/inotify/Kconfig:4:\tselect FSNOTIFY\nfs/notify/inotify/Kconfig-5-\tdefault y\n"
} |
| 27/2 | 2026/09/26 03:19 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 38903 output: 30 thoughts: 2022 Thoughts: **Focus Symbol Selection for Kernel Fuzzing** Alright, let's get down to brass tacks. Based on the configuration context, it's a no-brainer that `FSNOTIFY` should be enabled. My focus now is on pinpointing the right kernel functions for the `FocusSymbols` list, to guide the fuzzer effectively. Remember the rules: avoid ubiquitous functions and target specific feature logic and entrypoints. First, I've identified several functions with changes: 1. `fs/fsopen.c`: The relevant symbol is `__do_sys_fspick`. Given how `SYSCALL_DEFINE3` works, that's definitely the symbol we want, not the macro itself. 2. `fs/namespace.c`: This is where things get interesting. We've got `vacate_mount` (new and specific), and modifications to: `cleanup_mnt`, `mntput_no_expire_slowpath`, `__detach_mounts`, `umount_tree`, `namespace_unlock`, and `setup_mnt`. The key here is not to include those that are used everywhere, because they dilute the fuzzer. Now, `mntput_no_expire_slowpath` is explicitly `noinline`, so that is perfect. The rest are not likely inlined because they're called from many places. 3. `fs/notify/mark.c`: We have `fsnotify_init_connector`, `fsnotify_detach_connector_from_object`, and `fsnotify_add_mark_list`, which are clearly specific to inotify/fanotify mark operations, so those seem fine. So I think the following need to be in the final `FocusSymbols` list: * `__do_sys_fspick` * `vacate_mount` * `mntput_no_expire_slowpath` * `cleanup_mnt` * `__detach_mounts` * `umount_tree` * `namespace_unlock` * `fsnotify_init_connector` * `fsnotify_detach_connector_from_object` * `fsnotify_add_mark_list` This should give the fuzzer a sharp focus on the new and changed logic, without getting bogged down in the noise of general kernel operations. |
| 28/2 | 2026/09/26 03:19 | tool | grepper |
0mArgs:{
"Expression": "fsnotify_init_connector",
"PathPrefix": "fs/notify/"
}Results: {
"Output": "fs/notify/fsnotify.c=719=static __init int fsnotify_init(void)\n--\nfs/notify/fsnotify.c-728-\nfs/notify/fsnotify.c:729:\tfsnotify_init_connector_caches();\nfs/notify/fsnotify.c-730-\n--\nfs/notify/fsnotify.h=111=extern void fsnotify_set_children_dentry_flags(struct inode *inode);\nfs/notify/fsnotify.h-112-\nfs/notify/fsnotify.h:113:void fsnotify_init_connector_caches(void);\nfs/notify/fsnotify.h-114-\n--\nfs/notify/mark.c=774=void fsnotify_unmount_inodes(struct fsnotify_sb_info *sbinfo)\n--\nfs/notify/mark.c-785-\nfs/notify/mark.c:786:static void fsnotify_init_connector(struct fsnotify_mark_connector *conn,\nfs/notify/mark.c-787-\t\t\t\t void *obj, unsigned int obj_type)\n--\nfs/notify/mark.c=800=fsnotify_alloc_inode_connector(struct inode *inode)\n--\nfs/notify/mark.c-809-\nfs/notify/mark.c:810:\tfsnotify_init_connector(\u0026iconn-\u003ecommon, inode, FSNOTIFY_OBJ_TYPE_INODE);\nfs/notify/mark.c-811-\tspin_lock(\u0026sbinfo-\u003elist_lock);\n--\nfs/notify/mark.c=833=static int fsnotify_attach_connector_to_object(fsnotify_connp_t *connp,\n--\nfs/notify/mark.c-845-\t\tif (conn)\nfs/notify/mark.c:846:\t\t\tfsnotify_init_connector(conn, obj, obj_type);\nfs/notify/mark.c-847-\t}\n--\nfs/notify/mark.c=1188=EXPORT_SYMBOL_GPL(fsnotify_wait_marks_destroyed);\nfs/notify/mark.c-1189-\nfs/notify/mark.c:1190:__init void fsnotify_init_connector_caches(void)\nfs/notify/mark.c-1191-{\n"
} |
| 29/2 | 2026/09/26 03:19 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 42062 output: 34 thoughts: 27 Thoughts: Okay, here's my interpretation of those thoughts, tailored for an expert audience, and delivered as if they were my own: **Internal Review of fsnotify Synchronization** Right, let's take a look at how we're handling the disassociation and marking within our `fsnotify` implementation. My immediate focus is on two specific functions: `fsnotify_detach_connector_from_object` and `fsnotify_add_mark_list`. I need to ensure that the logic within these functions, especially their interactions, is sound and that any potential race conditions are avoided. I want to confirm that when a connector is detached, the corresponding marks are handled correctly. Are we achieving the expected synchronization? This likely involves checking how resources are released, the order of operations, and the implications for event delivery. A key question is whether events are delivered after the connector is detached but before the mark has been fully updated. Then is this process atomic so there isn't a race? The goal is to verify that these low-level functions don't introduce any subtle bugs that could manifest as data corruption or incorrect event propagation within the file notification system. It's a critical part of ensuring robust file system event monitoring. |
| 30/2 | 2026/09/26 03:19 | tool | grepper |
0mArgs:{
"Expression": "fsnotify_detach_connector_from_object",
"PathPrefix": "fs/notify/"
}Results: {
"Output": "fs/notify/mark.c=393=static void fsnotify_untrack_connector(struct fsnotify_mark_connector *conn);\nfs/notify/mark.c-394-\nfs/notify/mark.c:395:static void *fsnotify_detach_connector_from_object(\nfs/notify/mark.c-396-\t\t\t\t\tstruct fsnotify_mark_connector *conn,\n--\nfs/notify/mark.c=454=void fsnotify_put_mark(struct fsnotify_mark *mark)\n--\nfs/notify/mark.c-476-\tif (hlist_empty(\u0026conn-\u003elist)) {\nfs/notify/mark.c:477:\t\tobjp = fsnotify_detach_connector_from_object(conn, \u0026type);\nfs/notify/mark.c-478-\t\tfree_conn = true;\n--\nfs/notify/mark.c=1108=void fsnotify_destroy_marks(fsnotify_connp_t *connp)\n--\nfs/notify/mark.c-1138-\t */\nfs/notify/mark.c:1139:\tobjp = fsnotify_detach_connector_from_object(conn, \u0026type);\nfs/notify/mark.c-1140-\tspin_unlock(\u0026conn-\u003elock);\n"
} |
| 31/2 | 2026/09/26 03:19 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 42705 output: 32 thoughts: 14 Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience, and written as if they were my own: **Analyzing `fsnotify_add_mark_list`** Right, let's dive into `fsnotify_add_mark_list`. I need to ensure the logic here is sound and doesn't introduce any unforeseen edge cases. I'm especially interested in how it interacts with the broader event system. My initial concerns are around performance with very large directory trees, and the potential for race conditions during mark addition and removal. I need to be sure the locking strategy is robust enough to prevent missed events or corruption. Let me mentally walk through the code... are there any obvious bottlenecks, potential deadlocks, or areas where contention could become an issue under heavy load? I'll also be considering how it handles nested directories and symlinks; these are always tricky in filesystem monitoring. Time to scrutinize the data structures involved; what's the memory footprint, and are we paying any avoidable overhead? Finally, I need to consider potential security implications; is there anything here that could be exploited to cause a denial-of-service or escalate privileges? Right, time to dig in and see if the implementation lives up to the expectations. |
| 32/2 | 2026/09/26 03:19 | tool | grepper |
0mArgs:{
"Expression": "fsnotify_add_mark_list",
"PathPrefix": "fs/notify/"
}Results: {
"Output": "fs/notify/mark.c=869=static struct fsnotify_mark_connector *fsnotify_grab_connector(\n--\nfs/notify/mark.c-895- */\nfs/notify/mark.c:896:static int fsnotify_add_mark_list(struct fsnotify_mark *mark, void *obj,\nfs/notify/mark.c-897-\t\t\t\t unsigned int obj_type, int add_flags)\n--\nfs/notify/mark.c=978=int fsnotify_add_mark_locked(struct fsnotify_mark *mark,\n--\nfs/notify/mark.c-999-\nfs/notify/mark.c:1000:\tret = fsnotify_add_mark_list(mark, obj, obj_type, add_flags);\nfs/notify/mark.c-1001-\tif (ret)\n"
} |
| 33/2 | 2026/09/26 03:19 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 43234 output: 28 thoughts: 123 Thoughts: Okay, let's break this down. **Analyzing Filesystem Notification Detachment and Mark Addition** Right, so `fsnotify_detach_connector_from_object` is the key function here, called from `fsnotify_put_mark` and `fsnotify_destroy_marks`. That makes sense - cleaning up after a mark is removed, and when the whole mark infrastructure is destroyed. Now, where is `fsnotify_add_mark_list` used? Ah, it's called within `fsnotify_add_mark_locked`. Ok, this is good. I'm beginning to see the lifecycle of marks and how they're managed in the filesystem notification system. Now, let's make sure everything is properly configured. Are there any specific Kconfigs we need to enable? Obviously, `FSNOTIFY` is fundamental for the whole `fs/notify/` code to work; that's expected. Okay, what about dependencies on other filesystems? For example, is `nullfs` involved here? I need to quickly check where `nullfs_fs_type` is actually defined to get the full picture. Let's see... |
| 34/2 | 2026/09/26 03:19 | tool | grepper |
0mArgs:{
"Expression": "nullfs_fs_type",
"PathPrefix": "fs/"
}Results: {
"Output": "fs/mount.h-7-\nfs/mount.h:8:extern struct file_system_type nullfs_fs_type;\nfs/mount.h-9-extern struct vfsmount *knullfs;\n--\nfs/namespace.c=3178=static struct mnt_namespace *create_new_namespace(struct path *path,\n--\nfs/namespace.c-3203-\nfs/namespace.c:3204:\tVFS_WARN_ON_ONCE(old_ns_root-\u003emnt.mnt_sb-\u003es_type != \u0026nullfs_fs_type);\nfs/namespace.c-3205-\n--\nfs/namespace.c=6278=static void __init init_mount_tree(void)\n--\nfs/namespace.c-6295-\t */\nfs/namespace.c:6296:\tnullfs_mnt = vfs_kern_mount(\u0026nullfs_fs_type, 0, \"nullfs\", NULL);\nfs/namespace.c-6297-\tif (IS_ERR(nullfs_mnt))\n--\nfs/namespace.c-6325-\nfs/namespace.c:6326:\tknullfs = kern_mount(\u0026nullfs_fs_type);\nfs/namespace.c-6327-\tif (IS_ERR(knullfs))\n--\nfs/nullfs.c=54=static int nullfs_init_fs_context(struct fs_context *fc)\n--\nfs/nullfs.c-61-\nfs/nullfs.c:62:struct file_system_type nullfs_fs_type = {\nfs/nullfs.c-63-\t.name\t\t\t= \"nullfs\",\n"
} |
| 35/2 | 2026/09/26 03:19 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 44059 output: 25 thoughts: 25 Thoughts: Okay, let's dive into this. Here's how I'd approach that particular line of inquiry, thinking like a seasoned kernel developer: **Investigating the Build Process of `nullfs.c`** Alright, so the task at hand is to determine the build behavior of `nullfs.c`. My immediate thought is, "Where's the definitive source of truth for the build rules for this particular file?" The answer, as it almost always is in these scenarios, is the `fs/Makefile`. That's where the magic happens, the instructions that dictate when and how a given file gets compiled and linked into the kernel. Therefore, my primary target is the `fs/Makefile`. I'll open that up and specifically look for any lines, any patterns, any conditions that mention `nullfs.c` or, potentially, its corresponding object file (`nullfs.o`, or something similar). My objective is clear: to see if `nullfs.c` is unconditionally included in the build, or if it is only built in response to a specific configuration option, perhaps a module selection, or under certain platform conditions. I need to understand if it's always there, or if I need to dig further to understand how it's included, or excluded. I need to be sure before I make any decisions about it. |
| 36/2 | 2026/09/26 03:19 | tool | grepper |
0mArgs:{
"Expression": "nullfs",
"PathPrefix": "fs/Makefile"
}Results: {
"Output": "fs/Makefile=10=obj-y :=\topen.o read_write.o file_table.o super.o \\\n--\nfs/Makefile-18-\t\tkernel_read_file.o mnt_idmapping.o remap_range.o pidfs.o \\\nfs/Makefile:19:\t\tfile_attr.o fserror.o nullfs.o failfs.o\nfs/Makefile-20-\n"
} |
| 37/2 | 2026/09/26 03:19 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 44501 output: 328 thoughts: 1230 Thoughts: **Fuzzing Target Identification: Mount Lifecycle and fsnotify Interactions** Okay, so I'm looking at this patch and immediately, `nullfs.o` is `obj-y`, so that's always in. But what about `CONFIG_FSNOTIFY`? Ah, right, that determines if `fsnotify.o`, `notification.o`, `group.o`, `mark.o`, and `fdinfo.o` are compiled, and to get into `fs/notify/mark.c`, `CONFIG_FSNOTIFY` *is* required. Good to know. Now, let's see if there are other configuration dependencies. Checking `fspick` and `fs/fsopen.c`... `fsopen.o` is also `obj-y`. Wait, what about those selftests involving loop mounts and detachments? Those tests are specifically designed to exercise scenarios of mount trees with submounts or loop mounts detaching. When a mount loses its last reference, `vacate_mount` replaces it with a vacant mount pointing to `knullfs->mnt_root` and `MNT_READONLY`, enabling clean up of the backing filesystem. That's key. Right, so what are the critical assertions here? `VFS_WARN_ON_ONCE(is_vacant(mnt))` in `vacate_mount` and `WARN_ON(!release && mnt_get_writers(mnt))` in `cleanup_mnt`. These are big red flags. And the complexity? Refcounting with `mnt_add_count(mnt, 2)`, changing the superblock on the fly to `knullfs->mnt_sb`, tracking `mnt_old_root`, fsnotify connector superblock tracking, and the `cleanup_mnt` unmounting and releasing. This is intricate VFS logic, all involving reference counting, lifetime management, and superblock swapping. This screams "fuzz me!" Any mismatch in `mnt_count`, unmount order, concurrent lookup/mount/umount, or fsnotify events on a vacant mount could easily trigger those `WARN_ON`s, use-after-frees, or memory leaks. Let's nail down the critical functions. Good candidates: `vacate_mount`, `cleanup_mnt`, `mntput_no_expire_slowpath`, `__detach_mounts`, `umount_tree`, `namespace_unlock`, `__do_sys_fspick`, `fsnotify_init_connector`, `fsnotify_detach_connector_from_object`, and `fsnotify_add_mark_list`. Hold on, is `__do_sys_fspick` the best entrypoint or `do_umount` or something else? Wait, `__do_sys_fspick` directly contains the `if (target.dentry->d_sb->s_flags & SB_NOUSER) goto err_path;` check! And yes, `vacate_mount`, `cleanup_mnt`, `mntput_no_expire_slowpath`, `__detach_mounts`, `umount_tree`, `namespace_unlock` are all in `fs/namespace.c`. `fsnotify_init_connector`, `fsnotify_detach_connector_from_object`, `fsnotify_add_mark_list` are in `fs/notify/mark.c`. Okay, are these functions ubiquitous? Nope, none of these are generic allocators, page fault handlers, locks, or other hot paths. `cleanup_mnt`, `mntput_no_expire_slowpath`, `vacate_mount`, `__detach_mounts`, `umount_tree`, `namespace_unlock` are *specifically* mount lifecycle and teardown functions. `fsnotify_init_connector`, `fsnotify_detach_connector_from_object`, `fsnotify_add_mark_list` are fsnotify mark specific, and `__do_sys_fspick` is the syscall entrypoint for `fspick(2)`. Checking the EnableConfigs again... `FSNOTIFY` is needed for `fs/notify/mark.c`. Everything else in `fs/namespace.c` and `fs/fsopen.c` is always enabled. Alright, let's break this down clearly: 1. This patch introduces "vacant mounts" using `knullfs` to handle mount cycles during detached mount lifecycles, rewires mount reference counting, updates fsnotify mark connectors, and prevents reconfiguration of kernel-internal superblocks. 2. All changes are in core VFS (`fs/namespace.c`, `fs/fsopen.c`, `fs/notify/mark.c`), easily reachable via unprivileged or privileged syscalls like `mount`, `umount`, `f |
| 38/2 | 2026/09/26 03:20 | tool | set-results |
0mArgs:{
"EnableConfigs": [
"FSNOTIFY"
],
"FocusSymbols": [
"vacate_mount",
"cleanup_mnt",
"mntput_no_expire_slowpath",
"__detach_mounts",
"umount_tree",
"namespace_unlock",
"__do_sys_fspick",
"fsnotify_init_connector",
"fsnotify_detach_connector_from_object",
"fsnotify_add_mark_list"
],
"Reasoning": "The patch series introduces 'vacant mounts' backed by a private nullfs instance (knullfs) to break reference cycles where an unmounted mount loses its last reference while remaining attached to an unmounted parent. It modifies core VFS mount lifetime and reference counting logic (fs/namespace.c), updates fsnotify mark connectors to track their originating superblock across mount sb replacement (fs/notify/mark.c), and adds an SB_NOUSER check to fspick (fs/fsopen.c). It also introduces new runtime assertions (e.g. VFS_WARN_ON_ONCE(is_vacant(mnt))). These changes are in core reachable kernel subsystems and can be exercised via standard filesystem and mount syscalls (mount, umount2, fspick, open_tree, move_mount, fanotify/inotify). Due to the complex reference counting, refactoring of mount teardown, and dynamic superblock swapping, this code warrants focused fuzzing.",
"WorthFuzzing": true
}Results: {
"EnableConfigs": [
"FSNOTIFY"
],
"FocusSymbols": [
"vacate_mount",
"cleanup_mnt",
"mntput_no_expire_slowpath",
"__detach_mounts",
"umount_tree",
"namespace_unlock",
"__do_sys_fspick",
"fsnotify_init_connector",
"fsnotify_detach_connector_from_object",
"fsnotify_add_mark_list"
],
"Reasoning": "The patch series introduces 'vacant mounts' backed by a private nullfs instance (knullfs) to break reference cycles where an unmounted mount loses its last reference while remaining attached to an unmounted parent. It modifies core VFS mount lifetime and reference counting logic (fs/namespace.c), updates fsnotify mark connectors to track their originating superblock across mount sb replacement (fs/notify/mark.c), and adds an SB_NOUSER check to fspick (fs/fsopen.c). It also introduces new runtime assertions (e.g. VFS_WARN_ON_ONCE(is_vacant(mnt))). These changes are in core reachable kernel subsystems and can be exercised via standard filesystem and mount syscalls (mount, umount2, fspick, open_tree, move_mount, fanotify/inotify). Due to the complex reference counting, refactoring of mount teardown, and dynamic superblock swapping, this code warrants focused fuzzing.",
"WorthFuzzing": true
} |
| 39/1 | 2026/09/26 03:20 | action | If |
1mArgs:{
"WorthFuzzing": true
}Results: null |
| 40/2 | 2026/09/26 03:20 | agent | kmsan-evaluator |
1mModel:core Args: null Results: {
"KMSANReasoning": "The patch series resolves reference count cycles between detached mounts and attached submounts (e.g., loop devices or filesystems holding references on parent mounts) by introducing 'vacant mounts' that substitute a private knullfs instance for the submount's root/superblock when unreferenced while attached, and updates fsnotify mark connectors to explicitly track superblocks.\n\nRisk analysis:\n1. Uninitialized Memory / Info Leaks: None. No new kernel-to-user copy interfaces, ioctls, or user-visible data structures are added or altered. The fields added to internal structures (`mnt_old_root` in `struct mount` and `sb` in `struct fsnotify_mark_connector`) are explicitly initialized upon allocation or setup (`alloc_vfsmnt` uses `kmem_cache_zalloc`, `vacate_mount` sets `mnt_old_root`, and `fsnotify_init_connector` sets `conn-\u003esb`). There are no uninitialized variables or conditional branches dependent on uninitialized data.\n2. Memory Safety and Concurrency: The primary risks associated with this patch involve reference counting errors (e.g., mount refcount underflows/leaks, use-after-free, double puts), superblock and dentry lifecycle management, and synchronization/locking around mount teardown. These bugs are detected by KASAN (use-after-free, double free), refcount sanity checks, and LOCKDEP.\n\nBecause there are no uninitialized memory access or info-leak risks, running a dedicated KMSAN session is not justified; standard KASAN and LOCKDEP coverage is sufficient.",
"NeedsKMSAN": false
}Instruction: You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.
CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
a comprehensive suite of debugging tools and sanitizers, including KASAN
(out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
(locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
or page allocations) and kernel-to-user memory info-leaks.
Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.
Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.
Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
attributes, ioctl output arguments, socket options, or BPF buffers) where fields
or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
uninitialized bytes of existing buffers.
Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
dereferences, locking deadlocks, or use-after-free bugs (these are already caught
by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.
Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Target architecture: amd64
For your convenience, here is the diff of the changes:
commit 6828955f7f8d6b3588066fb61312f9f956fbddf0
Author: syz-cluster <triage@syzkaller.com>
Date: Sat Sep 26 03:18:27 2026 +0000
syz-cluster: applied patch under review
diff --git a/fs/fsopen.c b/fs/fsopen.c
index ae19e51365986..9d5a7a22b5292 100644
--- a/fs/fsopen.c
+++ b/fs/fsopen.c
@@ -190,6 +190,9 @@ SYSCALL_DEFINE3(fspick, int, dfd, const char __user *, path, unsigned int, flags
ret = -EINVAL;
if (target.mnt->mnt_root != target.dentry)
goto err_path;
+ /* kernel-internal superblocks are nobody's to reconfigure */
+ if (target.dentry->d_sb->s_flags & SB_NOUSER)
+ goto err_path;
fc = fs_context_for_reconfigure(target.dentry, 0, 0);
if (IS_ERR(fc)) {
diff --git a/fs/mount.h b/fs/mount.h
index 94fcc306d21e7..50d0999ff09ff 100644
--- a/fs/mount.h
+++ b/fs/mount.h
@@ -6,6 +6,7 @@
#include <linux/fs_pin.h>
extern struct file_system_type nullfs_fs_type;
+extern struct vfsmount *knullfs;
extern struct list_head notify_list;
struct mnt_namespace {
@@ -50,8 +51,13 @@ struct mount {
struct vfsmount mnt;
union {
struct rb_node mnt_node; /* node in the ns->mounts rbtree */
- struct rcu_head mnt_rcu;
- struct llist_node mnt_llist;
+ struct { /* once it has left its namespace */
+ union {
+ struct rcu_head mnt_rcu;
+ struct llist_node mnt_llist;
+ };
+ struct dentry *mnt_old_root; /* what a vacant mount stands in for */
+ };
};
#ifdef CONFIG_SMP
struct mnt_pcp __percpu *mnt_pcp;
@@ -84,7 +90,7 @@ struct mount {
struct mountpoint *mnt_mp; /* where is it mounted */
union {
struct hlist_node mnt_mp_list; /* list mounts with the same mountpoint */
- struct hlist_node mnt_umount;
+ struct hlist_node mnt_umount; /* in the parent's mnt_stuck_children */
};
#ifdef CONFIG_FSNOTIFY
struct fsnotify_mark_connector __rcu *mnt_fsnotify_marks;
diff --git a/fs/namespace.c b/fs/namespace.c
index 580877e46b1ac..175e8165693b6 100644
--- a/fs/namespace.c
+++ b/fs/namespace.c
@@ -80,8 +80,9 @@ static u64 mnt_id_ctr = MNT_UNIQUE_ID_OFFSET;
static struct hlist_head *mount_hashtable __ro_after_init;
static struct hlist_head *mountpoint_hashtable __ro_after_init;
static struct kmem_cache *mnt_cache __ro_after_init;
+struct vfsmount *knullfs __ro_after_init; /* private nullfs instance */
static DECLARE_RWSEM(namespace_sem);
-static HLIST_HEAD(unmounted); /* protected by namespace_sem */
+static LIST_HEAD(unmounted); /* protected by namespace_sem */
static LIST_HEAD(ex_mountpoints); /* protected by namespace_sem */
static struct mnt_namespace *emptied_ns; /* protected by namespace_sem */
@@ -227,6 +228,17 @@ static void mnt_free_id(struct mount *mnt)
xa_erase(&mnt_id_xa, mnt->mnt_id);
}
+/* mnt_id_ctr is protected by the lock of mnt_id_xa, see mnt_alloc_id(). */
+static u64 mnt_alloc_unique_id(void)
+{
+ u64 id;
+
+ xa_lock(&mnt_id_xa);
+ id = ++mnt_id_ctr;
+ xa_unlock(&mnt_id_xa);
+ return id;
+}
+
/*
* Allocate a new peer group ID
*/
@@ -1150,18 +1162,28 @@ static void commit_tree(struct mount *mnt)
touch_mnt_namespace(n);
}
-static void setup_mnt(struct mount *m, struct dentry *root)
+/*
+ * Point @m at @root: a reference on the superblock and its root, and a
+ * place on the superblock's list of instances.
+ * locks: mount_lock, as mount_locked_reader or mount_writer
+ */
+static void __setup_mnt(struct mount *m, struct dentry *root)
{
struct super_block *s = root->d_sb;
atomic_inc(&s->s_active);
m->mnt.mnt_sb = s;
m->mnt.mnt_root = dget(root);
- m->mnt_mountpoint = m->mnt.mnt_root;
+ mnt_add_instance(m, s);
+}
+
+static void setup_mnt(struct mount *m, struct dentry *root)
+{
+ m->mnt_mountpoint = root;
m->mnt_parent = m;
guard(mount_locked_reader)();
- mnt_add_instance(m, s);
+ __setup_mnt(m, root);
}
/**
@@ -1294,8 +1316,20 @@ static struct mount *clone_mnt(struct mount *old, struct dentry *root,
return ERR_PTR(err);
}
+/*
+ * The only mounts of knullfs' superblock that are ever attached are
+ * vacant mounts.
+ */
+static inline bool is_vacant(const struct mount *mnt)
+{
+ return mnt->mnt.mnt_sb == knullfs->mnt_sb;
+}
+
static void cleanup_mnt(struct mount *mnt)
{
+ bool release = !(mnt->mnt.mnt_flags & MNT_DOOMED);
+ struct dentry *root = release ? mnt->mnt_old_root : mnt->mnt.mnt_root;
+ struct super_block *sb = root->d_sb;
struct hlist_node *p;
struct mount *m;
/*
@@ -1303,9 +1337,10 @@ static void cleanup_mnt(struct mount *mnt)
* up a mnt_want/drop_write() pair. If this happens, the
* filesystem was probably unable to make r/w->r/o transitions.
* The locking used to deal with mnt_count decrement provides barriers,
- * so mnt_get_writers() below is safe.
+ * so mnt_get_writers() below is safe. A vacant mount is still reachable
+ * and a failing mnt_want_write() on it bumps the count for a moment.
*/
- WARN_ON(mnt_get_writers(mnt));
+ WARN_ON(!release && mnt_get_writers(mnt));
if (unlikely(mnt->mnt_pins.first))
mnt_pin_kill(mnt);
hlist_for_each_entry_safe(m, p, &mnt->mnt_stuck_children, mnt_umount) {
@@ -1313,12 +1348,35 @@ static void cleanup_mnt(struct mount *mnt)
mntput(&m->mnt);
}
fsnotify_vfsmount_delete(&mnt->mnt);
- dput(mnt->mnt.mnt_root);
- deactivate_super(mnt->mnt.mnt_sb);
+ dput(root);
+ deactivate_super(sb);
+ /* A new vacant mount is just put here. */
+ if (unlikely(release)) {
+ /* the reference vacate_mount() gave the release */
+ mntput(&mnt->mnt);
+ return;
+ }
mnt_free_id(mnt);
call_rcu(&mnt->mnt_rcu, delayed_free_vfsmnt);
}
+/*
+ * @mnt lost its last reference while still attached. Don't reveal what's
+ * beneath so mount knullfs over it.
+ */
+static void vacate_mount(struct mount *mnt)
+{
+ /* a vacant mount is put only after it has been unhashed */
+ VFS_WARN_ON_ONCE(is_vacant(mnt));
+ mnt->mnt_old_root = mnt->mnt.mnt_root;
+ __setup_mnt(mnt, knullfs->mnt_root);
+ mnt->mnt.mnt_flags |= MNT_READONLY;
+ /* It's a new mount so give it its own mount id. */
+ mnt->mnt_id_unique = mnt_alloc_unique_id();
+ /* One reference for the parent and one for cleanup_mnt(). */
+ mnt_add_count(mnt, 2);
+}
+
static void __cleanup_mnt(struct rcu_head *head)
{
cleanup_mnt(container_of(head, struct mount, mnt_rcu));
@@ -1338,6 +1396,7 @@ static DECLARE_DELAYED_WORK(delayed_mntput_work, delayed_mntput);
static void noinline mntput_no_expire_slowpath(struct mount *mnt)
{
LIST_HEAD(list);
+ bool vacate = false;
int count;
VFS_BUG_ON(mnt->mnt_ns);
@@ -1360,7 +1419,11 @@ static void noinline mntput_no_expire_slowpath(struct mount *mnt)
unlock_mount_hash();
return;
}
- mnt->mnt.mnt_flags |= MNT_DOOMED;
+ /* Still attached, so it held its own reference: keep the slot filled. */
+ if (unlikely(mnt_has_parent(mnt)))
+ vacate = true;
+ else
+ mnt->mnt.mnt_flags |= MNT_DOOMED;
rcu_read_unlock();
mnt_del_instance(mnt);
@@ -1371,9 +1434,13 @@ static void noinline mntput_no_expire_slowpath(struct mount *mnt)
struct mount *p, *tmp;
list_for_each_entry_safe(p, tmp, &mnt->mnt_mounts, mnt_child) {
__umount_mnt(p, &list);
- hlist_add_head(&p->mnt_umount, &mnt->mnt_stuck_children);
+ /* only a vacant mount is owned by its parent */
+ if (is_vacant(p))
+ hlist_add_head(&p->mnt_umount, &mnt->mnt_stuck_children);
}
}
+ if (unlikely(vacate))
+ vacate_mount(mnt);
unlock_mount_hash();
shrink_dentry_list(&list);
@@ -1688,13 +1755,12 @@ static bool need_notify_mnt_list(void)
static void free_mnt_ns(struct mnt_namespace *);
static void namespace_unlock(void)
{
- struct hlist_head head;
- struct hlist_node *p;
- struct mount *m;
+ struct mount *m, *n;
struct mnt_namespace *ns = emptied_ns;
+ LIST_HEAD(head);
LIST_HEAD(list);
- hlist_move_list(&unmounted, &head);
+ list_splice_init(&unmounted, &head);
list_splice_init(&ex_mountpoints, &list);
emptied_ns = NULL;
@@ -1718,13 +1784,14 @@ static void namespace_unlock(void)
shrink_dentry_list(&list);
- if (likely(hlist_empty(&head)))
+ if (likely(list_empty(&head)))
return;
synchronize_rcu_expedited();
- hlist_for_each_entry_safe(m, p, &head, mnt_umount) {
- hlist_del(&m->mnt_umount);
+ /* In tree order, so a subtree nobody holds goes without vacant mounts. */
+ list_for_each_entry_safe(m, n, &head, mnt_list) {
+ list_del_init(&m->mnt_list);
mntput(&m->mnt);
}
}
@@ -1740,6 +1807,19 @@ enum umount_tree_flags {
UMOUNT_CONNECTED = 4,
};
+/*
+ * An unmounted mount that stays attached to its unmounted parent:
+ *
+ * - is hashed and on the parent's list of children, so a walk on the
+ * parent finds it and never ends up in what it covered
+ * - is unreachable from any namespace root
+ * - holds its own reference, dropped by namespace_unlock(); the parent's
+ * final mntput() unhashes it without putting it, so a child whose
+ * superblock pins an ancestor can still shut down
+ * - is vacated if it loses its last reference while attached
+ * it releases the filesystem it carried and a knullfs mount is placed on
+ * the parent which is owned by it
+ */
static bool disconnect_mount(struct mount *mnt, enum umount_tree_flags how)
{
/* Leaving mounts connected is only valid for lazy umounts */
@@ -1750,10 +1830,7 @@ static bool disconnect_mount(struct mount *mnt, enum umount_tree_flags how)
if (!mnt_has_parent(mnt))
return true;
- /* Because the reference counting rules change when mounts are
- * unmounted and connected, umounted mounts may not be
- * connected to mounted mounts.
- */
+ /* An unmounted mount may only stay attached to an unmounted parent */
if (!(mnt->mnt_parent->mnt.mnt_flags & MNT_UMOUNT))
return true;
@@ -1769,10 +1846,6 @@ static bool disconnect_mount(struct mount *mnt, enum umount_tree_flags how)
return true;
}
-/*
- * mount_lock must be held
- * namespace_sem must be held for write
- */
static void umount_tree(struct mount *mnt, enum umount_tree_flags how)
{
LIST_HEAD(tmp_list);
@@ -1824,8 +1897,8 @@ static void umount_tree(struct mount *mnt, enum umount_tree_flags how)
umount_mnt(p);
}
}
- if (disconnect)
- hlist_add_head(&p->mnt_umount, &unmounted);
+ /* attached or not, it holds its own reference */
+ list_add_tail(&p->mnt_list, &unmounted);
/*
* At this point p->mnt_ns is NULL, notification will be queued
@@ -1994,9 +2067,12 @@ void __detach_mounts(struct dentry *dentry)
mnt = hlist_entry(mp.node.next, struct mount, mnt_mp_list);
if (mnt->mnt.mnt_flags & MNT_UMOUNT) {
umount_mnt(mnt);
- hlist_add_head(&mnt->mnt_umount, &unmounted);
+ /* only a vacant mount is owned by its parent */
+ if (is_vacant(mnt))
+ list_add_tail(&mnt->mnt_list, &unmounted);
+ } else {
+ umount_tree(mnt, UMOUNT_CONNECTED);
}
- else umount_tree(mnt, UMOUNT_CONNECTED);
}
unpin_mountpoint(&mp);
}
@@ -6210,10 +6286,12 @@ static void __init init_mount_tree(void)
*
* (1) nullfs with mount id 1
* (2) mutable rootfs with mount id 2
- * (3) private nullfs for kthreads (SB_KERNMOUNT)
+ * (3) private nullfs for kthreads (SB_KERNMOUNT), kept in knullfs
*
* with (2) mounted on top of (1). The init_task's root and pwd
* are pointed at (3) so all kthreads start isolated in nullfs.
+ * A mount that dies while still attached to its parent is pointed
+ * at (3) as well, see vacate_mount().
*/
nullfs_mnt = vfs_kern_mount(&nullfs_fs_type, 0, "nullfs", NULL);
if (IS_ERR(nullfs_mnt))
@@ -6245,11 +6323,11 @@ static void __init init_mount_tree(void)
init_mnt_ns.nr_mounts++;
}
- nullfs_mnt = kern_mount(&nullfs_fs_type);
- if (IS_ERR(nullfs_mnt))
+ knullfs = kern_mount(&nullfs_fs_type);
+ if (IS_ERR(knullfs))
panic("VFS: Failed to create private nullfs instance");
- root.mnt = nullfs_mnt;
- root.dentry = nullfs_mnt->mnt_root;
+ root.mnt = knullfs;
+ root.dentry = knullfs->mnt_root;
init_task.nsproxy->mnt_ns = &init_mnt_ns;
get_mnt_ns(&init_mnt_ns);
diff --git a/fs/notify/fsnotify.h b/fs/notify/fsnotify.h
index 58c7bb25e5718..0be351275dad7 100644
--- a/fs/notify/fsnotify.h
+++ b/fs/notify/fsnotify.h
@@ -54,10 +54,11 @@ static inline struct super_block *fsnotify_object_sb(void *obj,
}
}
+/* The sb the connector is accounted on; NULL once it has been detached */
static inline struct super_block *fsnotify_connector_sb(
struct fsnotify_mark_connector *conn)
{
- return fsnotify_object_sb(conn->obj, conn->type);
+ return conn->sb;
}
static inline fsnotify_connp_t *fsnotify_sb_marks(struct super_block *sb)
diff --git a/fs/notify/mark.c b/fs/notify/mark.c
index b2640d836a712..1b6095fcf039f 100644
--- a/fs/notify/mark.c
+++ b/fs/notify/mark.c
@@ -425,6 +425,7 @@ static void *fsnotify_detach_connector_from_object(
conn->type = FSNOTIFY_OBJ_TYPE_DETACHED;
if (sb)
fsnotify_update_sb_watchers(sb, conn);
+ conn->sb = NULL;
return inode;
}
@@ -791,6 +792,8 @@ static void fsnotify_init_connector(struct fsnotify_mark_connector *conn,
conn->prio = 0;
conn->type = obj_type;
conn->obj = obj;
+ /* the object may move to another sb, the accounting doesn't */
+ conn->sb = fsnotify_object_sb(obj, obj_type);
}
static struct fsnotify_mark_connector *
@@ -953,8 +956,8 @@ static int fsnotify_add_mark_list(struct fsnotify_mark *mark, void *obj,
/* mark should be the last entry. last is the current last entry */
hlist_add_behind_rcu(&mark->obj_list, &last->obj_list);
added:
- if (sb)
- fsnotify_update_sb_watchers(sb, conn);
+ if (conn->sb)
+ fsnotify_update_sb_watchers(conn->sb, conn);
/*
* Since connector is attached to object using cmpxchg() we are
* guaranteed that connector initialization is fully visible by anyone
diff --git a/include/linux/fsnotify_backend.h b/include/linux/fsnotify_backend.h
index 618eed4d6d724..3a9ab9e0104b4 100644
--- a/include/linux/fsnotify_backend.h
+++ b/include/linux/fsnotify_backend.h
@@ -573,6 +573,8 @@ struct fsnotify_mark_connector {
/* Used listing heads to free after srcu period expires */
struct fsnotify_mark_connector *destroy_next;
};
+ /* sb whose watched_objects account for this connector [lock] */
+ struct super_block *sb;
struct hlist_head list; /* List of marks */
};
diff --git a/tools/testing/selftests/Makefile b/tools/testing/selftests/Makefile
index 273853937c254..fb3a85d6396de 100644
--- a/tools/testing/selftests/Makefile
+++ b/tools/testing/selftests/Makefile
@@ -43,6 +43,7 @@ TARGETS += filesystems/open_tree_ns
TARGETS += filesystems/overlayfs
TARGETS += filesystems/statmount
TARGETS += filesystems/mount-notify
+TARGETS += filesystems/mount_cycle
TARGETS += filesystems/nsfs
TARGETS += filesystems/fuse
TARGETS += filesystems/move_mount
diff --git a/tools/testing/selftests/filesystems/mount_cycle/.gitignore b/tools/testing/selftests/filesystems/mount_cycle/.gitignore
new file mode 100644
index 0000000000000..28c623ef4d9dc
--- /dev/null
+++ b/tools/testing/selftests/filesystems/mount_cycle/.gitignore
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: GPL-2.0-only
+loop_cycle_test
diff --git a/tools/testing/selftests/filesystems/mount_cycle/Makefile b/tools/testing/selftests/filesystems/mount_cycle/Makefile
new file mode 100644
index 0000000000000..3becec29d69fb
--- /dev/null
+++ b/tools/testing/selftests/filesystems/mount_cycle/Makefile
@@ -0,0 +1,6 @@
+# SPDX-License-Identifier: GPL-2.0
+TEST_GEN_PROGS := loop_cycle_test
+
+CFLAGS += -Wall -O2 -g $(KHDR_INCLUDES)
+
+include ../../lib.mk
diff --git a/tools/testing/selftests/filesystems/mount_cycle/loop_cycle_test.c b/tools/testing/selftests/filesystems/mount_cycle/loop_cycle_test.c
new file mode 100644
index 0000000000000..09cc824c769e0
--- /dev/null
+++ b/tools/testing/selftests/filesystems/mount_cycle/loop_cycle_test.c
@@ -0,0 +1,1225 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A mount that another namespace's rmdir detached, or that went down with
+ * the detached tree it was in when the tree's last fd was closed, keeps
+ * its submounts connected, and a connected submount is put by its
+ * parent's final mntput(). A submount whose filesystem keeps a file open
+ * on the parent then holds the parent's count above zero for good:
+ * nothing in userspace refers to either mount any more and nothing can
+ * release them. A loop device is the simplest such filesystem, its
+ * backing file sits on the parent.
+ */
+#define _GNU_SOURCE
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <sched.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <stdbool.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include <linux/fuse.h>
+#include <linux/keyctl.h>
+#include <linux/major.h>
+#include <linux/raid/md_u.h>
+#include <linux/raid/md_p.h>
+#include <linux/loop.h>
+#include <linux/magic.h>
+#include <sys/syscall.h>
+#include <sys/sysmacros.h>
+#include <sys/uio.h>
+
+#include "../wrappers.h"
+#include "../../kselftest_harness.h"
+
+#define IMAGE_SIZE (1440 * 1024)
+#define SECTOR 512
+
+/* A blank FAT12 floppy image: boot sector, two FATs, an empty root directory. */
+static int write_fat12(int fd)
+{
+ struct stat st;
+ unsigned char sector[SECTOR] = {
+ 0xeb, 0x3c, 0x90, 'M', 'S', 'W', 'I', 'N', '4', '.', '1',
+ [11] = 0x00, 0x02, /* bytes per sector: 512 */
+ [13] = 1, /* sectors per cluster */
+ [14] = 1, 0, /* reserved sectors */
+ [16] = 2, /* FATs */
+ [17] = 0xe0, 0x00, /* root directory entries: 224 */
+ [19] = 0x40, 0x0b, /* total sectors: 2880 */
+ [21] = 0xf0, /* media descriptor */
+ [22] = 9, 0, /* sectors per FAT */
+ [24] = 18, 0, /* sectors per track */
+ [26] = 2, 0, /* heads */
+ [38] = 0x29, /* extended boot signature */
+ [39] = 0x12, 0x34, 0x56, 0x78,
+ [43] = 'N', 'O', ' ', 'N', 'A', 'M', 'E', ' ', ' ', ' ', ' ',
+ [54] = 'F', 'A', 'T', '1', '2', ' ', ' ', ' ',
+ [510] = 0x55, 0xaa,
+ };
+ unsigned char fat[SECTOR] = { 0xf0, 0xff, 0xff };
+
+ if (pwrite(fd, sector, SECTOR, 0) != SECTOR)
+ return -1;
+ /* the first FAT and the second one, one sector each is enough */
+ if (pwrite(fd, fat, SECTOR, 1 * SECTOR) != SECTOR ||
+ pwrite(fd, fat, SECTOR, 10 * SECTOR) != SECTOR)
+ return -1;
+ if (fstat(fd, &st) || S_ISBLK(st.st_mode))
+ return 0;
+ return ftruncate(fd, IMAGE_SIZE);
+}
+
+/*
+ * A blank FAT12 image with 4 KiB sectors and @sectors of them, for a device
+ * with 4 KiB logical blocks (zram) or for a bigger image than a floppy.
+ */
+static int write_fat12_4k(int fd, unsigned int sectors)
+{
+ unsigned int fat_sectors = (sectors * 3 / 2 + 4095) / 4096;
+ unsigned char sector[4096] = {
+ 0xeb, 0x3c, 0x90, 'M', 'S', 'W', 'I', 'N', '4', '.', '1',
+ [11] = 0x00, 0x10, /* bytes per sector: 4096 */
+ [13] = 1, /* sectors per cluster */
+ [14] = 1, 0, /* reserved sectors */
+ [16] = 2, /* FATs */
+ [17] = 128, 0, /* root directory entries: one sector */
+ [19] = sectors & 0xff, sectors >> 8,
+ [21] = 0xf8, /* media descriptor */
+ [22] = fat_sectors, 0,
+ [24] = 63, 0, /* sectors per track */
+ [26] = 255, 0, /* heads */
+ [38] = 0x29, /* extended boot signature */
+ [39] = 0x12, 0x34, 0x56, 0x78,
+ [43] = 'N', 'O', ' ', 'N', 'A', 'M', 'E', ' ', ' ', ' ', ' ',
+ [54] = 'F', 'A', 'T', '1', '2', ' ', ' ', ' ',
+ [510] = 0x55, 0xaa,
+ };
+ unsigned char fat[4096] = { 0xf8, 0xff, 0xff };
+ struct stat st;
+
+ if (pwrite(fd, sector, sizeof(sector), 0) != sizeof(sector))
+ return -1;
+ if (pwrite(fd, fat, sizeof(fat), 1 * 4096) != sizeof(fat) ||
+ pwrite(fd, fat, sizeof(fat), (1 + fat_sectors) * 4096) != sizeof(fat))
+ return -1;
+ if (fstat(fd, &st) || S_ISBLK(st.st_mode))
+ return 0;
+ return ftruncate(fd, (off_t)sectors * 4096);
+}
+
+#define MINIX_BLOCK 1024
+#define MINIX_BLOCKS 4096 /* a 4 MiB image */
+#define MINIX_INODES 512
+#define MINIX_ITABLE (MINIX_INODES * 32 / MINIX_BLOCK)
+#define MINIX_FIRSTDATA (2 + 1 + 1 + MINIX_ITABLE) /* boot, super, imap, zmap, inodes */
+
+/*
+ * A blank minix v1 image, for the holders that need a FIFO or a device
+ * node on the dying mount, which vfat can't hold. Superblock in block 1,
+ * one block each for the inode and zone bitmaps, the inode table, and
+ * the root directory in the first data zone.
+ */
+static int write_minix(int fd)
+{
+ struct {
+ __u16 s_ninodes, s_nzones, s_imap_blocks, s_zmap_blocks;
+ __u16 s_firstdatazone, s_log_zone_size;
+ __u32 s_max_size;
+ __u16 s_magic, s_state;
+ } sb = {
+ .s_ninodes = MINIX_INODES,
+ .s_nzones = MINIX_BLOCKS,
+ .s_imap_blocks = 1,
+ .s_zmap_blocks = 1,
+ .s_firstdatazone = MINIX_FIRSTDATA,
+ .s_max_size = (7 + 512 + 512 * 512) * MINIX_BLOCK,
+ .s_magic = MINIX_SUPER_MAGIC,
+ .s_state = 1, /* MINIX_VALID_FS */
+ };
+ struct {
+ __u16 i_mode, i_uid;
+ __u32 i_size, i_time;
+ __u8 i_gid, i_nlinks;
+ __u16 i_zone[9];
+ } root = {
+ .i_mode = S_IFDIR | 0755,
+ .i_size = 2 * 16,
+ .i_nlinks = 2,
+ .i_zone = { MINIX_FIRSTDATA },
+ };
+ unsigned char imap[MINIX_BLOCK], zmap[MINIX_BLOCK], dir[MINIX_BLOCK] = {};
+ int i;
+
+ /* bit 0 is reserved in both maps, the root inode and its zone are in use */
+ memset(imap, 0xff, sizeof(imap));
+ for (i = 2; i <= MINIX_INODES; i++)
+ imap[i / 8] &= ~(1 << (i % 8));
+ memset(zmap, 0xff, sizeof(zmap));
+ for (i = 2; i <= MINIX_BLOCKS - MINIX_FIRSTDATA; i++)
+ zmap[i / 8] &= ~(1 << (i % 8));
+ dir[0] = 1;
+ dir[2] = '.';
+ dir[16] = 1;
+ dir[18] = '.';
+ dir[19] = '.';
+
+ if (pwrite(fd, &sb, sizeof(sb), 1 * MINIX_BLOCK) != sizeof(sb) ||
+ pwrite(fd, imap, sizeof(imap), 2 * MINIX_BLOCK) != sizeof(imap) ||
+ pwrite(fd, zmap, sizeof(zmap), 3 * MINIX_BLOCK) != sizeof(zmap) ||
+ pwrite(fd, &root, sizeof(root), 4 * MINIX_BLOCK) != sizeof(root) ||
+ pwrite(fd, dir, sizeof(dir), MINIX_FIRSTDATA * MINIX_BLOCK) != sizeof(dir))
+ return -1;
+ return ftruncate(fd, (off_t)MINIX_BLOCKS * MINIX_BLOCK);
+}
+
+static int read_sysfs(const char *path, char *buf, size_t size)
+{
+ ssize_t n;
+ int fd;
+
+ fd = open(path, O_RDONLY);
+ if (fd < 0)
+ return -1;
+ n = read(fd, buf, size - 1);
+ close(fd);
+ if (n < 0)
+ return -1;
+ buf[n] = '\0';
+ return 0;
+}
+
+/* Does any mount namespace in the system show a mount of @dev? */
+static bool mounted_anywhere(const char *dev)
+{
+ char path[PATH_MAX], line[4096];
+ struct dirent *de;
+ bool found = false;
+ DIR *proc;
+ FILE *f;
+
+ proc = opendir("/proc");
+ if (!proc)
+ return false;
+ while (!found && (de = readdir(proc))) {
+ if (de->d_name[0] < '0' || de->d_name[0] > '9')
+ continue;
+ snprintf(path, sizeof(path), "/proc/%s/mountinfo", de->d_name);
+ f = fopen(path, "re");
+ if (!f)
+ continue;
+ while (fgets(line, sizeof(line), f)) {
+ if (strstr(line, dev)) {
+ found = true;
+ break;
+ }
+ }
+ fclose(f);
+ }
+ closedir(proc);
+ return found;
+}
+
+/* Wait up to @ms milliseconds for the loop device to give up its backing file. */
+static bool loop_released(const char *sysfs, int ms)
+{
+ char buf[PATH_MAX];
+
+ for (; ms > 0; ms -= 100) {
+ if (read_sysfs(sysfs, buf, sizeof(buf)) < 0)
+ return true;
+ usleep(100000);
+ }
+ return read_sysfs(sysfs, buf, sizeof(buf)) < 0;
+}
+
+FIXTURE(loop_cycle) {
+ char dev[32]; /* the loop device the child set up */
+ char sysfs[64]; /* its backing_file attribute */
+};
+
+FIXTURE_SETUP(loop_cycle)
+{
+ if (geteuid() != 0)
+ SKIP(return, "test requires CAP_SYS_ADMIN");
+ if (access("/dev/loop-control", R_OK | W_OK))
+ SKIP(return, "test requires loop devices");
+
+ ASSERT_EQ(unshare(CLONE_NEWNS), 0);
+ ASSERT_EQ(mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL), 0);
+
+ rmdir("/mnt_dir");
+ ASSERT_EQ(mkdir("/mnt_dir", 0755), 0);
+ ASSERT_EQ(mount("tmpfs", "/mnt_dir", "tmpfs", 0, NULL), 0);
+ self->dev[0] = '\0';
+}
+
+FIXTURE_TEARDOWN(loop_cycle)
+{
+ umount2("/mnt_dir", MNT_DETACH);
+ rmdir("/mnt_dir");
+}
+
+/* Child exit codes. */
+enum {
+ CHILD_OK,
+ CHILD_NS, /* could not set up the namespace or the tmpfs */
+ CHILD_IMAGE, /* could not write the image */
+ CHILD_LOOP, /* could not set up the loop device */
+ CHILD_MOUNT, /* could not mount it (vfat and msdos both refused) */
+ CHILD_PIPE, /* the parent went away */
+ CHILD_HOLDER, /* could not set the holder up below the mount */
+ CHILD_SKIP, /* the kernel lacks what the holder needs */
+};
+
+/* Bind a free loop device to the open image @ifd; the device number. */
+static int loop_bind(int ifd)
+{
+ int cfd, lfd, n;
+ char dev[32];
+
+ cfd = open("/dev/loop-control", O_RDWR);
+ if (cfd < 0)
+ return -1;
+ n = ioctl(cfd, LOOP_CTL_GET_FREE);
+ close(cfd);
+ if (n < 0)
+ return -1;
+ snprintf(dev, sizeof(dev), "/dev/loop%d", n);
+ lfd = open(dev, O_RDWR);
+ if (lfd < 0)
+ return -1;
+ if (ioctl(lfd, LOOP_SET_FD, ifd))
+ n = -1;
+ close(lfd);
+ return n;
+}
+
+/* Write an image to @img, bind a loop device to it and mount that at @mp; the device number. */
+static int loop_mount(const char *img, const char *mp)
+{
+ char dev[32];
+ int ifd, n;
+
+ ifd = open(img, O_RDWR | O_CREAT | O_EXCL, 0600);
+ if (ifd < 0 || write_fat12(ifd))
+ return -CHILD_IMAGE;
+ n = loop_bind(ifd);
+ close(ifd); /* the loop device holds the file from now on */
+ if (n < 0)
+ return -CHILD_LOOP;
+ snprintf(dev, sizeof(dev), "/dev/loop%d", n);
+ if (mkdir(mp, 0755))
+ return -CHILD_MOUNT;
+ if (mount(dev, mp, "vfat", 0, NULL) && mount(dev, mp, "msdos", 0, NULL))
+ return -CHILD_MOUNT;
+ return n;
+}
+
+/*
+ * Two tmpfs mounts, each carrying the image of the loop mount below the
+ * other: the loop mount below /mnt_dir/vol has its image on /mnt_dir/vol2
+ * and the other way round.
+ */
+static int crossed_child(int to_parent, int from_parent)
+{
+ int n[2];
+ char c;
+
+ if (unshare(CLONE_NEWNS) || mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL))
+ return CHILD_NS;
+ if (mkdir("/mnt_dir/vol", 0755) || mount("tmpfs", "/mnt_dir/vol", "tmpfs", 0, NULL) ||
+ mkdir("/mnt_dir/vol2", 0755) || mount("tmpfs", "/mnt_dir/vol2", "tmpfs", 0, NULL))
+ return CHILD_NS;
+ n[0] = loop_mount("/mnt_dir/vol2/img", "/mnt_dir/vol/mnt");
+ if (n[0] < 0)
+ return -n[0];
+ n[1] = loop_mount("/mnt_dir/vol/img", "/mnt_dir/vol2/mnt");
+ if (n[1] < 0)
+ return -n[1];
+ if (write(to_parent, n, sizeof(n)) != sizeof(n))
+ return CHILD_PIPE;
+ if (read(from_parent, &c, 1) != 1)
+ return CHILD_PIPE;
+ return CHILD_OK;
+}
+
+/*
+ * In its own mount namespace the child mounts a tmpfs on /mnt_dir/vol,
+ * puts a filesystem image on it, binds a loop device to the image and
+ * mounts that loop device below. The loop device's backing file is a
+ * reference on the mount the image is on, held by the loop device, held
+ * by the mounted filesystem, held by the mount below.
+ */
+static int loop_child(int to_parent, int from_parent)
+{
+ char c;
+ int n;
+
+ if (unshare(CLONE_NEWNS) || mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL))
+ return CHILD_NS;
+ if (mkdir("/mnt_dir/vol", 0755) || mount("tmpfs", "/mnt_dir/vol", "tmpfs", 0, NULL))
+ return CHILD_NS;
+ n = loop_mount("/mnt_dir/vol/img", "/mnt_dir/vol/mnt");
+ if (n < 0)
+ return -n;
+
+ if (write(to_parent, &n, sizeof(n)) != sizeof(n))
+ return CHILD_PIPE;
+ /* keep the namespace alive while the parent removes the directory */
+ if (read(from_parent, &c, 1) != 1)
+ return CHILD_PIPE;
+ return CHILD_OK;
+}
+
+/*
+ * An exclusive open of the device fails while a filesystem holds it, and
+ * the only filesystem that ever did is the one mounted below the dead
+ * mount. Give a release in flight a moment. Then the device must clear
+ * right away rather than only be marked for autoclear.
+ */
+static void assert_loop_released(struct __test_metadata *_metadata,
+ FIXTURE_DATA(loop_cycle) *self)
+{
+ int lfd;
+
+ for (int i = 0; i < 20; i++) {
+ lfd = open(self->dev, O_RDONLY | O_EXCL);
+ if (lfd >= 0)
+ break;
+ usleep(100000);
+ }
+ EXPECT_GE(lfd, 0)
+ TH_LOG("%s is still held by the loop mount below the dead mount: nothing refers to either mount and nothing can release them",
+ self->dev);
+ if (lfd >= 0)
+ close(lfd);
+
+ lfd = open(self->dev, O_RDWR);
+ ASSERT_GE(lfd, 0);
+ ASSERT_EQ(ioctl(lfd, LOOP_CLR_FD), 0);
+ close(lfd);
+ ASSERT_TRUE(loop_released(self->sysfs, 5000))
+ TH_LOG("%s kept its backing file after LOOP_CLR_FD: the filesystem on it is still mounted somewhere nobody can reach",
+ self->dev);
+}
+
+/*
+ * rmdir of /mnt_dir/vol from here, where it is not a mountpoint, detaches
+ * the child's tmpfs with the loop mount connected below it. Once the child
+ * is gone nothing refers to either mount. The loop device must then be
+ * free to give up its backing file, which only happens when the mounted
+ * filesystem below the detached tmpfs has been released.
+ */
+TEST_F(loop_cycle, detached_loop_mount_released)
+{
+ int to_parent[2], to_child[2];
+ char buf[PATH_MAX];
+ int status, n = -1;
+ pid_t pid;
+
+ ASSERT_EQ(pipe(to_parent), 0);
+ ASSERT_EQ(pipe(to_child), 0);
+
+ pid = fork();
+ ASSERT_GE(pid, 0);
+ if (pid == 0) {
+ close(to_parent[0]);
+ close(to_child[1]);
+ _exit(loop_child(to_parent[1], to_child[0]));
+ }
+ close(to_parent[1]);
+ close(to_child[0]);
+
+ if (read(to_parent[0], &n, sizeof(n)) != sizeof(n)) {
+ waitpid(pid, &status, 0);
+ if (WIFEXITED(status) && WEXITSTATUS(status) == CHILD_MOUNT)
+ SKIP(return, "test requires a FAT filesystem");
+ ASSERT_EQ(status, 0);
+ }
+ snprintf(self->dev, sizeof(self->dev), "/dev/loop%d", n);
+ snprintf(self->sysfs, sizeof(self->sysfs), "/sys/block/loop%d/loop/backing_file", n);
+ ASSERT_EQ(read_sysfs(self->sysfs, buf, sizeof(buf)), 0);
+ ASSERT_NE(strstr(buf, "/mnt_dir/vol/img"), NULL);
+
+ /* not a mountpoint in this namespace, so the directory can go */
+ ASSERT_EQ(rmdir("/mnt_dir/vol"), 0);
+
+ /* the child leaves: its namespace and every reference it held are gone */
+ ASSERT_EQ(write(to_child[1], "", 1), 1);
+ ASSERT_EQ(waitpid(pid, &status, 0), pid);
+ ASSERT_EQ(status, 0);
+ close(to_parent[0]);
+ close(to_child[1]);
+
+ /* nothing can reach the two mounts any more */
+ ASSERT_EQ(access("/mnt_dir/vol", F_OK), -1);
+ ASSERT_FALSE(mounted_anywhere(self->dev));
+
+ assert_loop_released(_metadata, self);
+}
+
+/*
+ * The same two mounts in a detached tree: a clone of /mnt_dir/vol from
+ * open_tree(), the image opened through the clone so that the loop device
+ * holds the clone, and the loop mount moved below the clone. The last
+ * close of the tree's fd dissolves the tree with the loop mount left
+ * connected below the dead clone, and nothing refers to either afterwards.
+ */
+TEST_F(loop_cycle, dissolved_tree_loop_mount_released)
+{
+ int tfd, ifd, fsfd, mfd, n;
+ char buf[PATH_MAX];
+
+ fsfd = sys_fsopen("vfat", 0);
+ if (fsfd < 0)
+ fsfd = sys_fsopen("msdos", 0);
+ if (fsfd < 0)
+ SKIP(return, "test requires a FAT filesystem");
+
+ ASSERT_EQ(mkdir("/mnt_dir/vol", 0755), 0);
+ ASSERT_EQ(mount("tmpfs", "/mnt_dir/vol", "tmpfs", 0, NULL), 0);
+ tfd = sys_open_tree(AT_FDCWD, "/mnt_dir/vol", OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);
+ ASSERT_GE(tfd, 0);
+
+ /* the image, opened through the clone: the loop device holds the clone */
+ ifd = openat(tfd, "img", O_RDWR | O_CREAT | O_EXCL, 0600);
+ ASSERT_GE(ifd, 0);
+ ASSERT_EQ(write_fat12(ifd), 0);
+ n = loop_bind(ifd);
+ close(ifd);
+ ASSERT_GE(n, 0);
+ snprintf(self->dev, sizeof(self->dev), "/dev/loop%d", n);
+ snprintf(self->sysfs, sizeof(self->sysfs), "/sys/block/loop%d/loop/backing_file", n);
+
+ /* the loop mount, moved below the clone */
+ ASSERT_EQ(mkdirat(tfd, "mnt", 0755), 0);
+ ASSERT_EQ(sys_fsconfig(fsfd, FSCONFIG_SET_STRING, "source", self->dev, 0), 0);
+ ASSERT_EQ(sys_fsconfig(fsfd, FSCONFIG_CMD_CREATE, NULL, NULL, 0), 0);
+ mfd = sys_fsmount(fsfd, 0, 0);
+ ASSERT_GE(mfd, 0);
+ close(fsfd);
+ ASSERT_EQ(sys_move_mount(mfd, "", tfd, "mnt", MOVE_MOUNT_F_EMPTY_PATH), 0);
+ close(mfd);
+
+ ASSERT_EQ(read_sysfs(self->sysfs, buf, sizeof(buf)), 0);
+ ASSERT_NE(strstr(buf, "img"), NULL);
+
+ /* the last fd of the tree: both mounts die, the loop mount connected */
+ close(tfd);
+
+ /* nothing can reach the two mounts any more */
+ ASSERT_FALSE(mounted_anywhere(self->dev));
+
+ assert_loop_released(_metadata, self);
+}
+
+/*
+ * The cycle in two steps: rmdir of /mnt_dir/vol leaves the loop mount
+ * below it connected while its image's mount, /mnt_dir/vol2, is alive;
+ * then rmdir of /mnt_dir/vol2 takes that one with the loop mount whose
+ * image is on the dead /mnt_dir/vol. Each dead mount now owns a loop
+ * mount whose filesystem pins the other.
+ */
+TEST_F(loop_cycle, crossed_images_released)
+{
+ int to_parent[2], to_child[2];
+ char sysfs[2][64], dev[2][32];
+ int status, n[2] = { -1, -1 };
+ pid_t pid;
+
+ ASSERT_EQ(pipe(to_parent), 0);
+ ASSERT_EQ(pipe(to_child), 0);
+
+ pid = fork();
+ ASSERT_GE(pid, 0);
+ if (pid == 0) {
+ close(to_parent[0]);
+ close(to_child[1]);
+ _exit(crossed_child(to_parent[1], to_child[0]));
+ }
+ close(to_parent[1]);
+ close(to_child[0]);
+
+ if (read(to_parent[0], n, sizeof(n)) != sizeof(n)) {
+ waitpid(pid, &status, 0);
+ if (WIFEXITED(status) && WEXITSTATUS(status) == CHILD_MOUNT)
+ SKIP(return, "test requires a FAT filesystem");
+ ASSERT_EQ(status, 0);
+ }
+ for (int i = 0; i < 2; i++) {
+ snprintf(dev[i], sizeof(dev[i]), "/dev/loop%d", n[i]);
+ snprintf(sysfs[i], sizeof(sysfs[i]), "/sys/block/loop%d/loop/backing_file", n[i]);
+ }
+
+ /* step one: the mount with the first loop mount below it goes */
+ ASSERT_EQ(rmdir("/mnt_dir/vol"), 0);
+
+ /* step two: the other one, with the loop mount whose image is on the first */
+ ASSERT_EQ(rmdir("/mnt_dir/vol2"), 0);
+
+ /* the child leaves: its namespace and every reference it held are gone */
+ ASSERT_EQ(write(to_child[1], "", 1), 1);
+ ASSERT_EQ(waitpid(pid, &status, 0), pid);
+ ASSERT_EQ(status, 0);
+ close(to_parent[0]);
+ close(to_child[1]);
+
+ /* nothing can reach the four mounts any more */
+ for (int i = 0; i < 2; i++) {
+ ASSERT_FALSE(mounted_anywhere(dev[i]));
+ strcpy(self->dev, dev[i]);
+ strcpy(self->sysfs, sysfs[i]);
+ assert_loop_released(_metadata, self);
+ }
+}
+
+/*
+ * The holders. Each keeps a file or a path on a mount P for as long as
+ * its own filesystem or device lives, and each has that filesystem or
+ * device mounted at C below P. Once another namespace's rmdir has
+ * detached P with C connected below it and the child is gone, P is owned
+ * by nobody, C by P, and P is kept by whatever the holder still holds.
+ *
+ * P is a loop mount so that its death can be observed: the loop device
+ * gives its backing file up when P's superblock goes. The image sits on
+ * a tmpfs next to P, not above it, so the loop device's own reference is
+ * not part of the picture.
+ */
+enum holder {
+ HOLDER_AUTOFS, /* a FIFO on P as the daemon's pipe */
+ HOLDER_ZRAM, /* a device node on P as the writeback device */
+ HOLDER_ECRYPTFS, /* a directory on P as the lower directory */
+ HOLDER_BINFMT_MISC, /* an executable on P as an 'F' interpreter */
+ HOLDER_FUSE, /* a file on P as a passthrough backing file */
+ HOLDER_ZLOOP, /* a directory on P for the zone files */
+ HOLDER_GADGET, /* a file on P as a mass storage LUN, over dummy_hcd */
+ HOLDER_MD, /* a file on P as an array's bitmap file */
+};
+
+#define HOLDER_IMG "/mnt_dir/img/p.img"
+#define HOLDER_MNT "/mnt_dir/p"
+#define HOLDER_BELOW "/mnt_dir/p/c"
+
+static int write_file(const char *path, const char *s)
+{
+ int fd = open(path, O_WRONLY);
+ ssize_t n;
+
+ if (fd < 0)
+ return -1;
+ n = write(fd, s, strlen(s));
+ close(fd);
+ return n == (ssize_t)strlen(s) ? 0 : -1;
+}
+
+/* Bind a free loop device to @img; the device number. */
+static int loop_attach(const char *img)
+{
+ int ifd, n;
+
+ ifd = open(img, O_RDWR);
+ if (ifd < 0)
+ return -1;
+ n = loop_bind(ifd);
+ close(ifd);
+ return n;
+}
+
+static int holder_autofs(void)
+{
+ char opts[64];
+ int pfd;
+
+ if (mkfifo(HOLDER_MNT "/pipe", 0600))
+ return CHILD_HOLDER;
+ pfd = open(HOLDER_MNT "/pipe", O_RDWR);
+ if (pfd < 0)
+ return CHILD_HOLDER;
+ snprintf(opts, sizeof(opts), "fd=%d,minproto=5,maxproto=5", pfd);
+ if (mount("autofs", HOLDER_BELOW, "autofs", 0, opts))
+ return errno == ENODEV ? CHILD_SKIP : CHILD_HOLDER;
+ close(pfd); /* the mount keeps its own */
+ return CHILD_OK;
+}
+
+/*
+ * zram's writeback device has to be a block device node, and that node has
+ * to be on P. Point it at a second loop device.
+ */
+static int holder_zram(void)
+{
+ char buf[64];
+ int fd, n;
+
+ if (access("/sys/block/zram0/backing_dev", W_OK))
+ return CHILD_SKIP;
+ /* somebody else's device, leave it alone */
+ if (read_sysfs("/sys/block/zram0/initstate", buf, sizeof(buf)) || buf[0] != '0')
+ return CHILD_SKIP;
+ fd = open("/mnt_dir/img/wb.img", O_RDWR | O_CREAT | O_EXCL, 0600);
+ if (fd < 0 || ftruncate(fd, IMAGE_SIZE))
+ return CHILD_HOLDER;
+ close(fd);
+ n = loop_attach("/mnt_dir/img/wb.img");
+ if (n < 0)
+ return CHILD_HOLDER;
+ if (mknod(HOLDER_MNT "/wbdev", S_IFBLK | 0600, makedev(7, n)))
+ return CHILD_HOLDER;
+ if (write_file("/sys/block/zram0/backing_dev", HOLDER_MNT "/wbdev"))
+ return CHILD_HOLDER;
+ snprintf(buf, sizeof(buf), "%d", 4 * 1024 * 1024);
+ if (write_file("/sys/block/zram0/disksize", buf))
+ return CHILD_HOLDER;
+ fd = open("/dev/zram0", O_RDWR);
+ if (fd < 0 || write_fat12_4k(fd, 1024)) /* zram has 4 KiB blocks */
+ return CHILD_HOLDER;
+ close(fd);
+ if (mount("/dev/zram0", HOLDER_BELOW, "vfat", 0, NULL) &&
+ mount("/dev/zram0", HOLDER_BELOW, "msdos", 0, NULL))
+ return CHILD_HOLDER;
+ return CHILD_OK;
+}
+
+/* The kernel's auth token layout, which userspace has to match byte for byte. */
+struct ecryptfs_auth_tok {
+ __u16 version;
+ __u16 token_type;
+ __u32 flags;
+ struct {
+ __u32 flags, encrypted_key_size, decrypted_key_size;
+ __u8 encrypted_key[512], decrypted_key[64];
+ } session_key;
+ __u8 reserved[32];
+ struct {
+ __u32 password_bytes;
+ __s32 hash_algo;
+ __u32 hash_iterations, session_key_encryption_key_bytes, flags;
+ __u8 session_key_encryption_key[64];
+ __u8 signature[17];
+ __u8 salt[8];
+ } password;
+} __attribute__((packed));
+
+#define ECRYPTFS_SIG "0123456789abcdef"
+
+static int holder_ecryptfs(void)
+{
+ struct ecryptfs_auth_tok tok = {
+ .version = 0x0004,
+ .token_type = 0, /* ECRYPTFS_PASSWORD */
+ .password.session_key_encryption_key_bytes = 16,
+ .password.flags = 0x02, /* ECRYPTFS_SESSION_KEY_ENCRYPTION_KEY_SET */
+ .password.signature = ECRYPTFS_SIG,
+ };
+
+ if (syscall(__NR_add_key, "user", ECRYPTFS_SIG, &tok, sizeof(tok),
+ KEY_SPEC_SESSION_KEYRING) < 0)
+ return CHILD_HOLDER;
+ if (mkdir(HOLDER_MNT "/lower", 0755))
+ return CHILD_HOLDER;
+ if (mount(HOLDER_MNT "/lower", HOLDER_BELOW, "ecryptfs", 0,
+ "ecryptfs_sig=" ECRYPTFS_SIG ",ecryptfs_cipher=aes,ecryptfs_key_bytes=16"))
+ return errno == ENODEV ? CHILD_SKIP : CHILD_HOLDER;
+ return CHILD_OK;
+}
+
+/*
+ * binfmt_misc instances are per user namespace, so the mount below P is
+ * made from a new one, which gets a copy of P.
+ */
+static int holder_binfmt_misc(void)
+{
+ char buf[4096];
+ int in, out;
+ ssize_t n;
+
+ in = open("/proc/self/exe", O_RDONLY);
+ out = open(HOLDER_MNT "/interp", O_WRONLY | O_CREAT | O_EXCL, 0755);
+ if (in < 0 || out < 0)
+ return CHILD_HOLDER;
+ while ((n = read(in, buf, sizeof(buf))) > 0)
+ if (write(out, buf, n) != n)
+ return CHILD_HOLDER;
+ close(in);
+ close(out);
+
+ if (unshare(CLONE_NEWUSER | CLONE_NEWNS))
+ return errno == EINVAL ? CHILD_SKIP : CHILD_HOLDER;
+ if (write_file("/proc/self/setgroups", "deny") ||
+ write_file("/proc/self/uid_map", "0 0 1") ||
+ write_file("/proc/self/gid_map", "0 0 1"))
+ return CHILD_HOLDER;
+ if (mount("binfmt_misc", HOLDER_BELOW, "binfmt_misc", 0, NULL))
+ return errno == ENODEV ? CHILD_SKIP : CHILD_HOLDER;
+ if (write_file(HOLDER_BELOW "/register", ":cycle:E::cyc::" HOLDER_MNT "/interp:F"))
+ return CHILD_HOLDER;
+ return CHILD_OK;
+}
+
+/*
+ * A fuse server that only ever answers FUSE_INIT, with passthrough on, and
+ * then registers a file on P as a backing file. The registration alone
+ * makes the fuse superblock hold the file.
+ */
+static int holder_fuse(void)
+{
+ struct fuse_backing_map map = {};
+ struct fuse_in_header *ih;
+ struct fuse_init_out init = {
+ .major = FUSE_KERNEL_VERSION,
+ .minor = FUSE_KERNEL_MINOR_VERSION,
+ .flags = FUSE_INIT_EXT,
+ .flags2 = FUSE_PASSTHROUGH >> 32,
+ .max_write = 4096,
+ .max_stack_depth = 1,
+ };
+ struct fuse_out_header oh = { .len = sizeof(oh) + sizeof(init) };
+ struct iovec iov[2] = { { &oh, sizeof(oh) }, { &init, sizeof(init) } };
+ char opts[64], buf[8192];
+ int ffd, bfd;
+ ssize_t n;
+
+ bfd = open(HOLDER_MNT "/backing", O_RDWR | O_CREAT | O_EXCL, 0600);
+ if (bfd < 0)
+ return CHILD_HOLDER;
+ ffd = open("/dev/fuse", O_RDWR);
+ if (ffd < 0)
+ return CHILD_SKIP;
+ snprintf(opts, sizeof(opts), "fd=%d,rootmode=40000,user_id=0,group_id=0", ffd);
+ if (mount("fuse", HOLDER_BELOW, "fuse", 0, opts))
+ return errno == ENODEV ? CHILD_SKIP : CHILD_HOLDER;
+
+ n = read(ffd, buf, sizeof(buf));
+ ih = (void *)buf;
+ if (n < (ssize_t)sizeof(*ih) || ih->opcode != FUSE_INIT)
+ return CHILD_HOLDER;
+ oh.unique = ih->unique;
+ if (writev(ffd, iov, 2) != (ssize_t)oh.len)
+ return CHILD_HOLDER;
+
+ map.fd = bfd;
+ if (ioctl(ffd, FUSE_DEV_IOC_BACKING_OPEN, &map) < 0)
+ return errno == EPERM ? CHILD_SKIP : CHILD_HOLDER;
+ close(bfd); /* the connection keeps its own */
+ return CHILD_OK; /* ffd stays open until the child exits */
+}
+
+/* Wait for a device node the kernel is about to create. */
+static int open_when_there(const char *dev, int flags, int ms)
+{
+ int fd;
+
+ for (; ms > 0; ms -= 100) {
+ fd = open(dev, flags);
+ if (fd >= 0)
+ return fd;
+ usleep(100000);
+ }
+ return -1;
+}
+
+/*
+ * zloop keeps every zone file open. One conventional zone is enough for a
+ * FAT image, the sequential one stays empty.
+ */
+static int holder_zloop(void)
+{
+ int fd;
+
+ if (access("/dev/zloop-control", W_OK))
+ return CHILD_SKIP;
+ if (mkdir(HOLDER_MNT "/zl", 0755) || mkdir(HOLDER_MNT "/zl/0", 0755))
+ return CHILD_HOLDER;
+ if (write_file("/dev/zloop-control",
+ "add id=0,capacity_mb=8,zone_size_mb=4,conv_zones=1,base_dir=" HOLDER_MNT "/zl"))
+ return CHILD_HOLDER;
+ fd = open_when_there("/dev/zloop0", O_RDWR, 5000);
+ if (fd < 0 || write_fat12_4k(fd, 1024)) /* 4 KiB blocks, like P */
+ return CHILD_HOLDER;
+ close(fd);
+ if (mount("/dev/zloop0", HOLDER_BELOW, "vfat", 0, NULL) &&
+ mount("/dev/zloop0", HOLDER_BELOW, "msdos", 0, NULL))
+ return CHILD_HOLDER;
+ return CHILD_OK;
+}
+
+#define GADGET "/sys/kernel/config/usb_gadget/g1"
+
+/* The disk usb-storage created for the gadget, by the LUN's inquiry string. */
+static int find_gadget_disk(char *dev, size_t len, int ms)
+{
+ char path[PATH_MAX], model[64];
+ struct dirent *de;
+ DIR *d;
+
+ for (; ms > 0; ms -= 100, usleep(100000)) {
+ d = opendir("/sys/block");
+ if (!d)
+ return -1;
+ while ((de = readdir(d))) {
+ if (strncmp(de->d_name, "sd", 2))
+ continue;
+ snprintf(path, sizeof(path), "/sys/block/%s/device/model", de->d_name);
+ if (read_sysfs(path, model, sizeof(model)) ||
+ strncmp(model, "File-Stor Gadget", 16))
+ continue;
+ snprintf(dev, len, "/dev/%s", de->d_name);
+ closedir(d);
+ return 0;
+ }
+ closedir(d);
+ }
+ return -1;
+}
+
+/*
+ * A mass storage gadget bound to the dummy UDC, so that this kernel is
+ * also the USB host that sees the LUN as a SCSI disk. sd locks the
+ * medium on open, which is what keeps the LUN's file from being ejected.
+ */
+#define GADGET_STEP(x) do { \
+ if (x) { \
+ fprintf(stderr, "gadget: %s failed: %s\n", #x, strerror(errno)); \
+ return CHILD_HOLDER; \
+ } \
+} while (0)
+
+static int holder_gadget(void)
+{
+ char dev[PATH_MAX];
+ int fd;
+
+ if (access("/sys/kernel/config", F_OK) ||
+ (mount("configfs", "/sys/kernel/config", "configfs", 0, NULL) && errno != EBUSY))
+ return CHILD_SKIP;
+ if (access("/sys/kernel/config/usb_gadget", F_OK) ||
+ access("/sys/class/udc/dummy_udc.0", F_OK))
+ return CHILD_SKIP;
+
+ fd = open(HOLDER_MNT "/lun.img", O_RDWR | O_CREAT | O_EXCL, 0600);
+ if (fd < 0 || write_fat12(fd))
+ return CHILD_HOLDER;
+ close(fd);
+
+ GADGET_STEP(mkdir(GADGET, 0755));
+ GADGET_STEP(write_file(GADGET "/idVendor", "0x1d6b"));
+ GADGET_STEP(write_file(GADGET "/idProduct", "0x0104"));
+ GADGET_STEP(mkdir(GADGET "/strings/0x409", 0755));
+ GADGET_STEP(write_file(GADGET "/strings/0x409/serialnumber", "1"));
+ GADGET_STEP(write_file(GADGET "/strings/0x409/manufacturer", "kselftest"));
+ GADGET_STEP(write_file(GADGET "/strings/0x409/product", "cycle"));
+ GADGET_STEP(mkdir(GADGET "/configs/c.1", 0755));
+ GADGET_STEP(mkdir(GADGET "/configs/c.1/strings/0x409", 0755));
+ GADGET_STEP(write_file(GADGET "/configs/c.1/strings/0x409/configuration", "c"));
+ GADGET_STEP(mkdir(GADGET "/functions/mass_storage.0", 0755));
+ GADGET_STEP(write_file(GADGET "/functions/mass_storage.0/lun.0/removable", "1"));
+ GADGET_STEP(write_file(GADGET "/functions/mass_storage.0/lun.0/file", HOLDER_MNT "/lun.img"));
+ GADGET_STEP(symlink(GADGET "/functions/mass_storage.0", GADGET "/configs/c.1/mass_storage.0"));
+ GADGET_STEP(write_file(GADGET "/UDC", "dummy_udc.0"));
+
+ /* usb-storage waits a second before it scans the device */
+ GADGET_STEP(find_gadget_disk(dev, sizeof(dev), 15000));
+ fd = open_when_there(dev, O_RDONLY, 5000);
+ GADGET_STEP(fd < 0);
+ close(fd);
+ if (mount(dev, HOLDER_BELOW, "vfat", 0, NULL) &&
+ mount(dev, HOLDER_BELOW, "msdos", 0, NULL))
+ return CHILD_HOLDER;
+ return CHILD_OK;
+}
+
+#define BITMAP_MAGIC 0x6d746962
+
+/*
+ * A RAID1 of one loop device, not persistent, with its bitmap in a file
+ * on P. The bitmap file needs a superblock the kernel accepts; sync_size,
+ * uuid and events are not looked at for a non-persistent array.
+ */
+static int holder_md(void)
+{
+ struct {
+ __u32 magic, version;
+ __u8 uuid[16];
+ __u64 events, events_cleared, sync_size;
+ __u32 state, chunksize, daemon_sleep, write_behind;
+ } bsb = {
+ .magic = BITMAP_MAGIC,
+ .version = 4,
+ .chunksize = 64 * 1024,
+ .daemon_sleep = 5,
+ };
+ mdu_array_info_t info = {
+ .level = 1,
+ .raid_disks = 1,
+ .size = 8 * 1024, /* KiB */
+ .not_persistent = 1,
+ };
+ mdu_disk_info_t disk = {
+ .major = 7,
+ .state = (1 << MD_DISK_ACTIVE) | (1 << MD_DISK_SYNC),
+ };
+ int fd, mdfd, bfd, n;
+ char buf[4096];
+
+ fd = open("/mnt_dir/img/md.img", O_RDWR | O_CREAT | O_EXCL, 0600);
+ if (fd < 0 || ftruncate(fd, 8 * 1024 * 1024))
+ return CHILD_HOLDER;
+ close(fd);
+ n = loop_attach("/mnt_dir/img/md.img");
+ if (n < 0)
+ return CHILD_HOLDER;
+ disk.minor = n;
+
+ bfd = open(HOLDER_MNT "/bitmap", O_RDWR | O_CREAT | O_EXCL, 0600);
+ if (bfd < 0 || write(bfd, &bsb, sizeof(bsb)) != sizeof(bsb) || ftruncate(bfd, 4096))
+ return CHILD_HOLDER;
+
+ if (read_sysfs("/proc/mdstat", buf, sizeof(buf)) || !strstr(buf, "[raid1]")) {
+ fprintf(stderr, "md: no raid1 personality: %s\n", buf);
+ return CHILD_SKIP;
+ }
+ if (access("/dev/md0", F_OK) && mknod("/dev/md0", S_IFBLK | 0600, makedev(9, 0)))
+ return CHILD_HOLDER;
+ mdfd = open("/dev/md0", O_RDWR);
+ if (mdfd < 0)
+ return CHILD_SKIP;
+ /* the bitmap ops are only installed once a bitmap type is chosen */
+ write_file("/sys/block/md0/md/bitmap_type", "bitmap");
+ /* EBUSY: somebody else's array, leave it alone */
+ if (ioctl(mdfd, SET_ARRAY_INFO, &info))
+ return errno == EBUSY ? CHILD_SKIP : CHILD_HOLDER;
+ if (ioctl(mdfd, ADD_NEW_DISK, &disk))
+ return CHILD_HOLDER;
+ /* attach the bitmap file before the array runs, the way mdadm does */
+ if (ioctl(mdfd, SET_BITMAP_FILE, bfd)) {
+ fprintf(stderr, "md: SET_BITMAP_FILE: %s\n", strerror(errno));
+ return errno == EINVAL ? CHILD_SKIP : CHILD_HOLDER;
+ }
+ close(bfd); /* the array keeps its own */
+ if (ioctl(mdfd, RUN_ARRAY, NULL)) {
+ fprintf(stderr, "md: RUN_ARRAY: %s\n", strerror(errno));
+ return CHILD_HOLDER;
+ }
+ if (write_fat12(mdfd))
+ return CHILD_HOLDER;
+ close(mdfd);
+ if (mount("/dev/md0", HOLDER_BELOW, "vfat", 0, NULL) &&
+ mount("/dev/md0", HOLDER_BELOW, "msdos", 0, NULL))
+ return CHILD_HOLDER;
+ return CHILD_OK;
+}
+
+/*
+ * In its own mount namespace the child puts the image on a tmpfs next to
+ * P, mounts P from a loop device, and sets the holder up with its own
+ * filesystem or device mounted at C below P.
+ */
+static int holder_child(int to_parent, int from_parent, enum holder holder)
+{
+ bool fifo = holder == HOLDER_AUTOFS || holder == HOLDER_ZRAM;
+ /* room for a 4 MiB zone file or a floppy image on P */
+ bool big = holder == HOLDER_ZLOOP || holder == HOLDER_GADGET;
+ const char *type = fifo ? "minix" : "vfat";
+ char dev[32], c;
+ int ifd, n, ret;
+
+ if (unshare(CLONE_NEWNS) || mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL))
+ return CHILD_NS;
+ if (mkdir("/mnt_dir/img", 0755) || mount("tmpfs", "/mnt_dir/img", "tmpfs", 0, NULL))
+ return CHILD_NS;
+
+ ifd = open(HOLDER_IMG, O_RDWR | O_CREAT | O_EXCL, 0600);
+ if (ifd < 0 || (fifo ? write_minix(ifd) :
+ big ? write_fat12_4k(ifd, 3072) : write_fat12(ifd)))
+ return CHILD_IMAGE;
+ close(ifd);
+ n = loop_attach(HOLDER_IMG);
+ if (n < 0)
+ return CHILD_LOOP;
+ snprintf(dev, sizeof(dev), "/dev/loop%d", n);
+ if (mkdir(HOLDER_MNT, 0755))
+ return CHILD_MOUNT;
+ if (mount(dev, HOLDER_MNT, type, 0, NULL) &&
+ (fifo || mount(dev, HOLDER_MNT, "msdos", 0, NULL)))
+ return fifo && errno == ENODEV ? CHILD_SKIP : CHILD_MOUNT;
+ if (mkdir(HOLDER_BELOW, 0755))
+ return CHILD_MOUNT;
+
+ switch (holder) {
+ case HOLDER_AUTOFS:
+ ret = holder_autofs();
+ break;
+ case HOLDER_ZRAM:
+ ret = holder_zram();
+ break;
+ case HOLDER_ECRYPTFS:
+ ret = holder_ecryptfs();
+ break;
+ case HOLDER_BINFMT_MISC:
+ ret = holder_binfmt_misc();
+ break;
+ case HOLDER_FUSE:
+ ret = holder_fuse();
+ break;
+ case HOLDER_ZLOOP:
+ ret = holder_zloop();
+ break;
+ case HOLDER_GADGET:
+ ret = holder_gadget();
+ break;
+ case HOLDER_MD:
+ ret = holder_md();
+ break;
+ default:
+ ret = CHILD_HOLDER;
+ }
+ if (ret != CHILD_OK)
+ return ret;
+
+ if (write(to_parent, &n, sizeof(n)) != sizeof(n))
+ return CHILD_PIPE;
+ if (read(from_parent, &c, 1) != 1)
+ return CHILD_PIPE;
+ return CHILD_OK;
+}
+
+/*
+ * A device keeps its file for as long as it is configured, so once nothing
+ * below the dead mount is left the device has to be told to let go. With
+ * the cycle unbroken C's filesystem still holds the device and every one
+ * of these refuses.
+ */
+static int holder_let_go_once(enum holder holder)
+{
+ int fd, ret;
+
+ switch (holder) {
+ case HOLDER_ZRAM:
+ return write_file("/sys/block/zram0/reset", "1");
+ case HOLDER_ZLOOP:
+ return write_file("/dev/zloop-control", "remove id=0");
+ case HOLDER_GADGET:
+ if (mount("configfs", "/sys/kernel/config", "configfs", 0, NULL) && errno != EBUSY)
+ return -1;
+ /* a zero-length write is a no-op for configfs; a newline ejects */
+ return write_file(GADGET "/functions/mass_storage.0/lun.0/file", "\n");
+ case HOLDER_MD:
+ fd = open("/dev/md0", O_RDONLY);
+ if (fd < 0)
+ return -1;
+ ret = ioctl(fd, STOP_ARRAY);
+ close(fd);
+ return ret;
+ default:
+ return 0;
+ }
+}
+
+/*
+ * The release of C's filesystem may still be in flight when the child is
+ * gone, and a device that is still held refuses to let go, so try for a
+ * while. With the cycle unbroken it refuses for good.
+ */
+static void holder_let_go(enum holder holder)
+{
+ for (int i = 0; i < 50; i++) {
+ if (!holder_let_go_once(holder))
+ return;
+ usleep(100000);
+ }
+}
+
+/*
+ * rmdir of /mnt_dir/p from here, where it is a plain directory, detaches
+ * P in the child's namespace with C connected below it. Once the child is
+ * gone the holder's file on P is the only thing left that refers to P,
+ * and it is dropped only when C's filesystem dies, which waits for P.
+ * The loop device backing P tells whether that resolved.
+ */
+static void holder_cycle(struct __test_metadata *_metadata,
+ FIXTURE_DATA(loop_cycle) *self, enum holder holder)
+{
+ int to_parent[2], from_parent[2], status, n;
+ pid_t pid;
+
+ ASSERT_EQ(pipe(to_parent), 0);
+ ASSERT_EQ(pipe(from_parent), 0);
+ pid = fork();
+ ASSERT_GE(pid, 0);
+ if (pid == 0) {
+ close(to_parent[0]);
+ close(from_parent[1]);
+ _exit(holder_child(to_parent[1], from_parent[0], holder));
+ }
+ close(to_parent[1]);
+ close(from_parent[0]);
+
+ if (read(to_parent[0], &n, sizeof(n)) != sizeof(n)) {
+ waitpid(pid, &status, 0);
+ if (WIFEXITED(status) && WEXITSTATUS(status) == CHILD_SKIP)
+ SKIP(return, "the kernel lacks what this holder needs");
+ ASSERT_TRUE(false)
+ TH_LOG("child failed to set the holder up: exit status %d",
+ WIFEXITED(status) ? WEXITSTATUS(status) : -1);
+ }
+ snprintf(self->dev, sizeof(self->dev), "/dev/loop%d", n);
+ snprintf(self->sysfs, sizeof(self->sysfs), "/sys/block/loop%d/loop/backing_file", n);
+
+ ASSERT_EQ(rmdir(HOLDER_MNT), 0);
+ ASSERT_EQ(write(from_parent[1], "x", 1), 1);
+ ASSERT_EQ(waitpid(pid, &status, 0), pid);
+ ASSERT_EQ(WEXITSTATUS(status), CHILD_OK);
+
+ holder_let_go(holder);
+ assert_loop_released(_metadata, self);
+ if (holder == HOLDER_GADGET)
+ write_file(GADGET "/UDC", "\n");
+}
+
+TEST_F(loop_cycle, autofs_pipe_on_dead_mount_released)
+{
+ holder_cycle(_metadata, self, HOLDER_AUTOFS);
+}
+
+TEST_F(loop_cycle, zram_writeback_node_on_dead_mount_released)
+{
+ holder_cycle(_metadata, self, HOLDER_ZRAM);
+}
+
+TEST_F(loop_cycle, ecryptfs_lower_on_dead_mount_released)
+{
+ holder_cycle(_metadata, self, HOLDER_ECRYPTFS);
+}
+
+TEST_F(loop_cycle, binfmt_misc_interpreter_on_dead_mount_released)
+{
+ holder_cycle(_metadata, self, HOLDER_BINFMT_MISC);
+}
+
+TEST_F(loop_cycle, fuse_backing_file_on_dead_mount_released)
+{
+ holder_cycle(_metadata, self, HOLDER_FUSE);
+}
+
+TEST_F(loop_cycle, zloop_zone_files_on_dead_mount_released)
+{
+ holder_cycle(_metadata, self, HOLDER_ZLOOP);
+}
+
+TEST_F(loop_cycle, mass_storage_lun_on_dead_mount_released)
+{
+ holder_cycle(_metadata, self, HOLDER_GADGET);
+}
+
+TEST_F(loop_cycle, md_bitmap_file_on_dead_mount_released)
+{
+ holder_cycle(_metadata, self, HOLDER_MD);
+}
+
+TEST_HARNESS_MAIN
|
| 41/3 | 2026/09/26 03:20 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 24268 output: 20 thoughts: 2195 Thoughts: **KMSAN Evaluation for this Patch Series** Okay, let's break this down. The task is to determine if a dedicated KMSAN session is warranted for these filesystem changes. My initial assessment is that this warrants careful scrutiny. The patch series is touching various areas, and the core concept seems to revolve around handling "vacant" mounts – mounts that no longer have active references but are still linked somehow. This has the potential to introduce uninitialized memory reads or information leaks, so it's a good place to start. First, I see the check in `fs/fsopen.c` is simple; it should not be an issue for KMSAN. The real areas of interest are in the changes to `struct mount` and the filesystem notification structures. Looking at `struct mount`, the union change is the most concerning part. The code cleverly uses a union to optimize memory usage, switching between the `mnt_node` (for mounts in a namespace) and a new struct containing `mnt_old_root`, which holds a pointer to the original root *dentry*. My first thought is: can `mnt_old_root` possibly overlap with uninitialized parts of the `mnt_node` in the union? However, upon further inspection, I'm noting that the sizes are carefully calculated to match when the mount becomes vacant. `mnt_old_root` seems to be initialized in `vacate_mount()`, which sets `mnt_old_root` before the union switch happens. This *should* prevent uninitialized memory issues. `cleanup_mnt()` checks `MNT_DOOMED`, which is only set when the mount has a parent. I need to make sure this logic is correct, and I'll revisit it later during code review. The changes in `fsnotify` are interesting as well. The addition of the `sb` field to `struct fsnotify_mark_connector` is designed to deal with a mount that might become "vacant" or move. This is a good sign, and it means the patches understand the original mount super block is needed. However, I need to check how `sb` is initialized and used. Any place where the `sb` pointer may have been accidentally swapped or forgotten during the unmounting or relocation of mount points could be a source of uninitialized memory reads. I will need to trace where this `fsnotify_mark_connector` structure is allocated and initialized to ensure there are no unintended consequences. The patch includes self-tests. This is excellent! I need to ensure these tests are run, and if they're not fully covering the new vacant mount logic, I should think about supplementing them, perhaps with fuzzing or more targeted tests, that I will need to construct to confirm the correctness of the union logic. Based on my current analysis, while the changes *seem* safe because they are setting up the `mnt_old_root` value before it is read, there's always a risk of subtle initialization issues that KMSAN can catch, especially around the vacant mount concept and `fsnotify`. The patch *could* have introduced uninitialized memory reads or information leaks, so, given the complexity, I'm leaning toward a **tentative "Yes" for NeedsKMSAN**. I need to do a thorough code review, but right now, I'm cautiously optimistic, but I'll need to run it through a fuzzing run to be completely certain. I would lean towards KMSAN for the patch. |
| 42/3 | 2026/09/26 03:20 | tool | grepper |
0mArgs:{
"Expression": "fsnotify_init_connector"
}Results: {
"Output": "fs/notify/fsnotify.c=719=static __init int fsnotify_init(void)\n--\nfs/notify/fsnotify.c-728-\nfs/notify/fsnotify.c:729:\tfsnotify_init_connector_caches();\nfs/notify/fsnotify.c-730-\n--\nfs/notify/fsnotify.h=111=extern void fsnotify_set_children_dentry_flags(struct inode *inode);\nfs/notify/fsnotify.h-112-\nfs/notify/fsnotify.h:113:void fsnotify_init_connector_caches(void);\nfs/notify/fsnotify.h-114-\n--\nfs/notify/mark.c=774=void fsnotify_unmount_inodes(struct fsnotify_sb_info *sbinfo)\n--\nfs/notify/mark.c-785-\nfs/notify/mark.c:786:static void fsnotify_init_connector(struct fsnotify_mark_connector *conn,\nfs/notify/mark.c-787-\t\t\t\t void *obj, unsigned int obj_type)\n--\nfs/notify/mark.c=800=fsnotify_alloc_inode_connector(struct inode *inode)\n--\nfs/notify/mark.c-809-\nfs/notify/mark.c:810:\tfsnotify_init_connector(\u0026iconn-\u003ecommon, inode, FSNOTIFY_OBJ_TYPE_INODE);\nfs/notify/mark.c-811-\tspin_lock(\u0026sbinfo-\u003elist_lock);\n--\nfs/notify/mark.c=833=static int fsnotify_attach_connector_to_object(fsnotify_connp_t *connp,\n--\nfs/notify/mark.c-845-\t\tif (conn)\nfs/notify/mark.c:846:\t\t\tfsnotify_init_connector(conn, obj, obj_type);\nfs/notify/mark.c-847-\t}\n--\nfs/notify/mark.c=1188=EXPORT_SYMBOL_GPL(fsnotify_wait_marks_destroyed);\nfs/notify/mark.c-1189-\nfs/notify/mark.c:1190:__init void fsnotify_init_connector_caches(void)\nfs/notify/mark.c-1191-{\n"
} |
| 43/3 | 2026/09/26 03:20 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 27797 output: 35 thoughts: 106 Thoughts: Okay, here's my understanding, focusing on the core concepts you've outlined, as if I were processing this information directly: **Connector Object State Management Deep Dive** Alright, so the initial state of this `conn` structure is being set up right from the get-go. Specifically, `fsnotify_init_connector` is grabbing the superblock associated with the object and assigning it to `conn->sb`. That seems like a reasonable initial setup for our connector. This also makes sense given the type of object involved, which is important to remember. Now, a key point to examine is the explicit clearing of `conn->sb` in `fsnotify_detach_connector_from_object`. The fact that it's being *explicitly* set to `NULL` raises a flag. It suggests that this isn't just a side effect of object deallocation, but a controlled detachment. This brings up a natural follow up: are there other places we are allocating or initializing this `conn` object? The whole lifecycle is tied to these two operations. Let's delve into the allocation and attachment functions, `fsnotify_alloc_inode_connector` and `fsnotify_attach_connector_to_object` because these are the places where the initial state is set up. They should provide the answer, and a full picture of the connector's lifecycle. |
| 44/3 | 2026/09/26 03:20 | tool | read-file |
0mArgs:{
"File": "fs/notify/mark.c",
"FirstLine": 785,
"LineCount": 70
}Results: {
"Contents": " 785:\t\n 786:\tstatic void fsnotify_init_connector(struct fsnotify_mark_connector *conn,\n 787:\t\t\t\t\t void *obj, unsigned int obj_type)\n 788:\t{\n 789:\t\tspin_lock_init(\u0026conn-\u003elock);\n 790:\t\tINIT_HLIST_HEAD(\u0026conn-\u003elist);\n 791:\t\tconn-\u003eflags = 0;\n 792:\t\tconn-\u003eprio = 0;\n 793:\t\tconn-\u003etype = obj_type;\n 794:\t\tconn-\u003eobj = obj;\n 795:\t\t/* the object may move to another sb, the accounting doesn't */\n 796:\t\tconn-\u003esb = fsnotify_object_sb(obj, obj_type);\n 797:\t}\n 798:\t\n 799:\tstatic struct fsnotify_mark_connector *\n 800:\tfsnotify_alloc_inode_connector(struct inode *inode)\n 801:\t{\n 802:\t\tstruct fsnotify_inode_mark_connector *iconn;\n 803:\t\tstruct fsnotify_sb_info *sbinfo = fsnotify_sb_info(inode-\u003ei_sb);\n 804:\t\n 805:\t\ticonn = kmem_cache_alloc(fsnotify_inode_mark_connector_cachep,\n 806:\t\t\t\t\t GFP_KERNEL);\n 807:\t\tif (!iconn)\n 808:\t\t\treturn NULL;\n 809:\t\n 810:\t\tfsnotify_init_connector(\u0026iconn-\u003ecommon, inode, FSNOTIFY_OBJ_TYPE_INODE);\n 811:\t\tspin_lock(\u0026sbinfo-\u003elist_lock);\n 812:\t\tlist_add(\u0026iconn-\u003econns_list, \u0026sbinfo-\u003einode_conn_list);\n 813:\t\tspin_unlock(\u0026sbinfo-\u003elist_lock);\n 814:\t\n 815:\t\treturn \u0026iconn-\u003ecommon;\n 816:\t}\n 817:\t\n 818:\tstatic void fsnotify_untrack_connector(struct fsnotify_mark_connector *conn)\n 819:\t{\n 820:\t\tstruct fsnotify_inode_mark_connector *iconn;\n 821:\t\tstruct fsnotify_sb_info *sbinfo;\n 822:\t\n 823:\t\tif (conn-\u003etype != FSNOTIFY_OBJ_TYPE_INODE)\n 824:\t\t\treturn;\n 825:\t\n 826:\t\ticonn = container_of(conn, struct fsnotify_inode_mark_connector, common);\n 827:\t\tsbinfo = fsnotify_sb_info(fsnotify_conn_inode(conn)-\u003ei_sb);\n 828:\t\tspin_lock(\u0026sbinfo-\u003elist_lock);\n 829:\t\tlist_del(\u0026iconn-\u003econns_list);\n 830:\t\tspin_unlock(\u0026sbinfo-\u003elist_lock);\n 831:\t}\n 832:\t\n 833:\tstatic int fsnotify_attach_connector_to_object(fsnotify_connp_t *connp,\n 834:\t\t\t\t\t\t void *obj, unsigned int obj_type)\n 835:\t{\n 836:\t\tstruct fsnotify_mark_connector *conn;\n 837:\t\n 838:\t\tif (obj_type == FSNOTIFY_OBJ_TYPE_INODE) {\n 839:\t\t\tstruct inode *inode = obj;\n 840:\t\n 841:\t\t\tconn = fsnotify_alloc_inode_connector(inode);\n 842:\t\t} else {\n 843:\t\t\tconn = kmem_cache_alloc(fsnotify_mark_connector_cachep,\n 844:\t\t\t\t\t\tGFP_KERNEL);\n 845:\t\t\tif (conn)\n 846:\t\t\t\tfsnotify_init_connector(conn, obj, obj_type);\n 847:\t\t}\n 848:\t\tif (!conn)\n 849:\t\t\treturn -ENOMEM;\n 850:\t\n 851:\t\t/*\n 852:\t\t * cmpxchg() provides the barrier so that readers of *connp can see\n 853:\t\t * only initialized structure\n 854:\t\t */\n"
} |
| 45/3 | 2026/09/26 03:20 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 29320 output: 27 thoughts: 498 Thoughts: **Analyzing Potential Uninitialized Memory Issues** Okay, let's break this down systematically. My initial concern was about potential uninitialized memory reads, particularly around file system interactions. The first thing I considered was the `fsnotify` connector. I confirmed that the `conn->sb` (superblock) field is *always* initialized, either by `fsnotify_init_connector` upon connection or set to `NULL` upon detachment. So, that's not a source of uninitialized reads. Next, I looked at `fsopen.c`, specifically the `fspick` system call. The snippet reveals a standard sanity check – ensuring the target is the mount's root and that the superblock isn't a kernel-internal one (`SB_NOUSER`). There's no evident vulnerability there; no direct memory copy from kernel space to user space or usage of uninitialized memory. That's a good sign. Now, let's move on to mounting and namespace operations, specifically focusing on how unique mount IDs are managed. I examined `mnt_alloc_unique_id()` and found a critical detail. The `mnt_id_ctr` is incremented and assigned to a `u64 id` within a lock-protected region. This confirms that the return value is *always* initialized. It looks like it's safe. Lastly, I need to check `mnt_old_root`, so I'm looking into how and when the mount structure (`mnt`) is allocated and freed. The function `alloc_vfsmnt` should contain the information I am searching for. |
| 46/3 | 2026/09/26 03:20 | tool | grepper |
0mArgs:{
"Expression": "alloc_vfsmnt",
"PathPrefix": "fs/"
}Results: {
"Output": "fs/namespace.c=281=int mnt_get_count(struct mount *mnt)\n--\nfs/namespace.c-296-\nfs/namespace.c:297:static struct mount *alloc_vfsmnt(const char *name)\nfs/namespace.c-298-{\n--\nfs/namespace.c=1198=struct vfsmount *vfs_create_mount(struct fs_context *fc)\n--\nfs/namespace.c-1204-\nfs/namespace.c:1205:\tmnt = alloc_vfsmnt(fc-\u003esource);\nfs/namespace.c-1206-\tif (!mnt)\n--\nfs/namespace.c=1267=static struct mount *clone_mnt(struct mount *old, struct dentry *root,\n--\nfs/namespace.c-1272-\nfs/namespace.c:1273:\tmnt = alloc_vfsmnt(old-\u003emnt_devname);\nfs/namespace.c-1274-\tif (!mnt)\n"
} |
| 47/3 | 2026/09/26 03:20 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 30444 output: 33 thoughts: 11 Thoughts: Okay, let's dive into this. Here's my take on `alloc_vfsmnt`, tailored for a fellow expert: **Delving into `alloc_vfsmnt`** Alright, let's get into the nitty-gritty of `alloc_vfsmnt`. Right off the bat, I know what we're dealing with – memory allocation for a `vfsmnt` structure. This function is the cornerstone, the starting point for mounting a filesystem. It's where the kernel grabs the necessary memory space to represent a mounted filesystem instance. My initial thoughts run through potential issues. Is it using the standard `kmalloc`? Does it account for possible memory pressure? Does it handle potential failure gracefully, or does it just return NULL and kick the problem down the road? What about alignment? Are there any subtle alignment requirements that could introduce performance bottlenecks or, worse, hard-to-debug memory corruption issues down the line? I'm also curious about the specific flags it might be using with the memory allocator. `GFP_KERNEL` is the standard, but are there more specific flags depending on the mount type or the context? Does it use a specific slab allocator or cache? Depending on the architecture, these details can make a significant difference. I should also check the associated free function to see if it makes use of kfree, or if there's any odd behavior that may cause memory leaks. Furthermore, I’ll be looking for any initialization that happens within this function. Does it populate any critical fields of the `vfsmnt` structure immediately? Does it set the `mnt_count` or other important reference counters? How does it handle potential concurrent access to this newly allocated and initialized structure? Are there any locking primitives involved, or is everything assumed to be single-threaded at this point? Does it make use of RCU? I'm thinking about the bigger picture, too. How does this fit into the broader mount process? What's the typical caller sequence? I need to understand the relationship between this and the other core functions like `vfs_kern_mount` and `do_mount`. Understanding those interdependencies is key to grasping the overall flow of the filesystem mounting process and how this function fits in. Finally, I’ll be checking for any potential error conditions and handling. Does it check for resource exhaustion, and if so, how does it report this back to the calling function? Does it have error recovery or rollback mechanisms that are being implemented? Basically, I want to understand how robust and optimized this allocation process is, and how it handles corner cases. |
| 48/3 | 2026/09/26 03:20 | tool | read-file |
0mArgs:{
"File": "fs/namespace.c",
"FirstLine": 297,
"LineCount": 40
}Results: {
"Contents": " 297:\tstatic struct mount *alloc_vfsmnt(const char *name)\n 298:\t{\n 299:\t\tstruct mount *mnt = kmem_cache_zalloc(mnt_cache, GFP_KERNEL);\n 300:\t\tif (mnt) {\n 301:\t\t\tint err;\n 302:\t\n 303:\t\t\terr = mnt_alloc_id(mnt);\n 304:\t\t\tif (err)\n 305:\t\t\t\tgoto out_free_cache;\n 306:\t\n 307:\t\t\tif (name)\n 308:\t\t\t\tmnt-\u003emnt_devname = kstrdup_const(name,\n 309:\t\t\t\t\t\t\t\t GFP_KERNEL_ACCOUNT);\n 310:\t\t\telse\n 311:\t\t\t\tmnt-\u003emnt_devname = \"none\";\n 312:\t\t\tif (!mnt-\u003emnt_devname)\n 313:\t\t\t\tgoto out_free_id;\n 314:\t\n 315:\t#ifdef CONFIG_SMP\n 316:\t\t\tmnt-\u003emnt_pcp = alloc_percpu(struct mnt_pcp);\n 317:\t\t\tif (!mnt-\u003emnt_pcp)\n 318:\t\t\t\tgoto out_free_devname;\n 319:\t\n 320:\t\t\tthis_cpu_add(mnt-\u003emnt_pcp-\u003emnt_count, 1);\n 321:\t#else\n 322:\t\t\tmnt-\u003emnt_count = 1;\n 323:\t\t\tmnt-\u003emnt_writers = 0;\n 324:\t#endif\n 325:\t\n 326:\t\t\tINIT_HLIST_NODE(\u0026mnt-\u003emnt_hash);\n 327:\t\t\tINIT_LIST_HEAD(\u0026mnt-\u003emnt_child);\n 328:\t\t\tINIT_LIST_HEAD(\u0026mnt-\u003emnt_mounts);\n 329:\t\t\tINIT_LIST_HEAD(\u0026mnt-\u003emnt_list);\n 330:\t\t\tINIT_LIST_HEAD(\u0026mnt-\u003emnt_expire);\n 331:\t\t\tINIT_LIST_HEAD(\u0026mnt-\u003emnt_share);\n 332:\t\t\tINIT_HLIST_HEAD(\u0026mnt-\u003emnt_slave_list);\n 333:\t\t\tINIT_HLIST_NODE(\u0026mnt-\u003emnt_slave);\n 334:\t\t\tINIT_HLIST_NODE(\u0026mnt-\u003emnt_mp_list);\n 335:\t\t\tINIT_HLIST_HEAD(\u0026mnt-\u003emnt_stuck_children);\n 336:\t\t\tINIT_HLIST_NODE(\u0026mnt-\u003emnt_ns_visible);\n"
} |
| 49/3 | 2026/09/26 03:20 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 31674 output: 26 thoughts: 316 Thoughts: **Analyzing the 'vacate_mount' Function and Potential User-Space Visibility of Vacant Mounts** Okay, so I've got a new `mnt` structure allocated using `kmem_cache_zalloc` and now I'm looking at `vacate_mount`. It's pretty straightforward: it's supposed to handle unhashing and preparing a mount for recycling. It sets the old root, re-parents it to `knullfs`, marks it read-only, and assigns a new unique ID. It also increments the reference count. But this `is_vacant(mnt)` check keeps niggling at me. Is it possible for user-space to somehow peek at the state of a "vacant" mount? Could APIs like `statmount`, `listmount`, or the various `/proc/[pid]/mountinfo` entries potentially leak information about these vacant mounts? I need to be absolutely sure because if a vacant mount's state is visible, that's a security vulnerability. Time to go hunting. Let's start with a `grep` for `is_vacant` and any other accesses of vacant mounts in `fs/namespace.c`. That's the place where the mount namespace magic happens. |
| 50/3 | 2026/09/26 03:20 | tool | grepper |
0mArgs:{
"Expression": "is_vacant",
"PathPrefix": "fs/"
}Results: {
"Output": "fs/namespace.c=1267=static struct mount *clone_mnt(struct mount *old, struct dentry *root,\n--\nfs/namespace.c-1322- */\nfs/namespace.c:1323:static inline bool is_vacant(const struct mount *mnt)\nfs/namespace.c-1324-{\n--\nfs/namespace.c=1367=static void vacate_mount(struct mount *mnt)\n--\nfs/namespace.c-1369-\t/* a vacant mount is put only after it has been unhashed */\nfs/namespace.c:1370:\tVFS_WARN_ON_ONCE(is_vacant(mnt));\nfs/namespace.c-1371-\tmnt-\u003emnt_old_root = mnt-\u003emnt.mnt_root;\n--\nfs/namespace.c=1396=static void noinline mntput_no_expire_slowpath(struct mount *mnt)\n--\nfs/namespace.c-1437-\t\t\t/* only a vacant mount is owned by its parent */\nfs/namespace.c:1438:\t\t\tif (is_vacant(p))\nfs/namespace.c-1439-\t\t\t\thlist_add_head(\u0026p-\u003emnt_umount, \u0026mnt-\u003emnt_stuck_children);\n--\nfs/namespace.c=2054=void __detach_mounts(struct dentry *dentry)\n--\nfs/namespace.c-2070-\t\t\t/* only a vacant mount is owned by its parent */\nfs/namespace.c:2071:\t\t\tif (is_vacant(mnt))\nfs/namespace.c-2072-\t\t\t\tlist_add_tail(\u0026mnt-\u003emnt_list, \u0026unmounted);\n"
} |
| 51/3 | 2026/09/26 03:20 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 32712 output: 30 thoughts: 296 Thoughts: **Analyzing Mount Reachability** Okay, let's break this down. My focus right now is understanding how we reach a "vacant mount." I'll start by examining the surrounding code comments around `vacate_mount` and `disconnect_mount`. The text says, in effect, that an unmounted mount, still attached to its unmounted parent, has these characteristics: it's hashed and listed on the parent's children. It's unreachable from any namespace root. It holds its own reference, dropped by `namespace_unlock()`, and its final mntput unhashes it without putting it, allowing for proper shutdown even if a child's superblock pins an ancestor. It's vacated if it loses its last reference while attached; it releases the file system and a knullfs mount is placed on the parent. The key observation here is "is unreachable from any namespace root". Right, it's out of the namespacing structure. This is important. Now, recall `mntput_no_expire_slowpath(mnt)`? That function call throws a `VFS_BUG_ON(mnt->mnt_ns);` condition. That confirms the mount `mnt` has already been detached from any namespace. `mnt->mnt_ns` is `NULL`. So, the question is, can functions like `statmount` or `listmount` even *see* mounts where `mnt->mnt_ns` is `NULL`? That's the critical point I need to clarify. I'll need to dig into the implementation of `statmount` to figure this out. This is where I'll find my answer. |
| 52/3 | 2026/09/26 03:20 | tool | grepper |
0mArgs:{
"Expression": "SYSCALL_DEFINE.*statmount",
"PathPrefix": "fs/"
}Results: {
"Output": "fs/namespace.c=6012=static struct mnt_namespace *grab_requested_mnt_ns(const struct mnt_id_req *kreq)\n--\nfs/namespace.c-6043-\nfs/namespace.c:6044:SYSCALL_DEFINE4(statmount, const struct mnt_id_req __user *, req,\nfs/namespace.c-6045-\t\tstruct statmount __user *, buf, size_t, bufsize,\n"
} |
| 53/3 | 2026/09/26 03:20 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 33515 output: 34 thoughts: 14 Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience: **Analyzing the Mount Lookup Process with `statmount`** Alright, let's dive in. I need to refresh my understanding of how `statmount` handles mount lookups. I'm specifically interested in the internal mechanics. I know the high-level concept: it's designed to give me detailed information about a mounted filesystem. But I'm going to get into the nitty-gritty. I want to understand the *exact* steps involved when it's querying for a specific mount point. What's the query process? Are there any clever optimizations? Does it interact with `/proc/mounts` directly, or is there a more sophisticated underlying mechanism? What data structures are in play internally? Are there any corner cases or potential performance bottlenecks I should be aware of? I'm going to look at the source code, maybe step through with a debugger, and thoroughly dissect the lookup logic. This isn't just about using the tool, it's about *really* knowing how it works. That level of understanding allows for more effective troubleshooting and optimization, and even the ability to contribute patches. Now, where did I put that debugger? |
| 54/3 | 2026/09/26 03:20 | tool | read-file |
0mArgs:{
"File": "fs/namespace.c",
"FirstLine": 6044,
"LineCount": 40
}Results: {
"Contents": "6044:\tSYSCALL_DEFINE4(statmount, const struct mnt_id_req __user *, req,\n6045:\t\t\tstruct statmount __user *, buf, size_t, bufsize,\n6046:\t\t\tunsigned int, flags)\n6047:\t{\n6048:\t\tstruct mnt_namespace *ns __free(mnt_ns_release) = NULL;\n6049:\t\tstruct kstatmount *ks __free(kfree) = NULL;\n6050:\t\tstruct file *mnt_file __free(fput) = NULL;\n6051:\t\tstruct mnt_id_req kreq;\n6052:\t\t/* We currently support retrieval of 3 strings. */\n6053:\t\tsize_t seq_size = 3 * PATH_MAX;\n6054:\t\tint ret;\n6055:\t\n6056:\t\tif (flags \u0026 ~STATMOUNT_BY_FD)\n6057:\t\t\treturn -EINVAL;\n6058:\t\n6059:\t\tret = copy_mnt_id_req(req, \u0026kreq, flags);\n6060:\t\tif (ret)\n6061:\t\t\treturn ret;\n6062:\t\n6063:\t\tif (flags \u0026 STATMOUNT_BY_FD) {\n6064:\t\t\tmnt_file = fget_raw(kreq.mnt_fd);\n6065:\t\t\tif (!mnt_file)\n6066:\t\t\t\treturn -EBADF;\n6067:\t\t\t/* do_statmount sets ns in case of STATMOUNT_BY_FD */\n6068:\t\t} else {\n6069:\t\t\tns = grab_requested_mnt_ns(\u0026kreq);\n6070:\t\t\tif (IS_ERR(ns))\n6071:\t\t\t\treturn PTR_ERR(ns);\n6072:\t\n6073:\t\t\tif (kreq.mnt_ns_id \u0026\u0026 (ns != current-\u003ensproxy-\u003emnt_ns) \u0026\u0026\n6074:\t\t\t !ns_capable_noaudit(ns-\u003euser_ns, CAP_SYS_ADMIN))\n6075:\t\t\t\treturn -EPERM;\n6076:\t\t}\n6077:\t\n6078:\t\tks = kmalloc_obj(*ks, GFP_KERNEL_ACCOUNT);\n6079:\t\tif (!ks)\n6080:\t\t\treturn -ENOMEM;\n6081:\t\n6082:\tretry:\n6083:\t\tret = prepare_kstatmount(ks, \u0026kreq, buf, bufsize, seq_size);\n"
} |
| 55/3 | 2026/09/26 03:20 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 34481 output: 34 thoughts: 46 Thoughts: Okay, let's break this down. **Deciding on the Best Approach for Lookup** My initial thought is, do I need to look this up via `lookup_mnt_in_ns` or should I use the `mnt_id`? Right off the bat, I know I'm dealing with mount namespace lookup, so this choice is critical for efficiency. To refresh my memory of the exact mechanics, especially any potential nuances between the two, I need to consult the source. Lines 6085-6120 of `fs/namespace.c` seem like the relevant area for `lookup_mnt_in_ns`. Let's dive in. |
| 56/3 | 2026/09/26 03:20 | tool | read-file |
0mArgs:{
"File": "fs/namespace.c",
"FirstLine": 6084,
"LineCount": 40
}Results: {
"Contents": "6084:\t\tif (ret)\n6085:\t\t\treturn ret;\n6086:\t\n6087:\t\tscoped_guard(namespace_shared)\n6088:\t\t\tret = do_statmount(ks, kreq.mnt_id, kreq.mnt_ns_id, mnt_file, ns);\n6089:\t\n6090:\t\tif (!ret)\n6091:\t\t\tret = copy_statmount_to_user(ks);\n6092:\t\tkvfree(ks-\u003eseq.buf);\n6093:\t\tpath_put(\u0026ks-\u003eroot);\n6094:\t\tif (retry_statmount(ret, \u0026seq_size))\n6095:\t\t\tgoto retry;\n6096:\t\treturn ret;\n6097:\t}\n6098:\t\n6099:\tstruct klistmount {\n6100:\t\tu64 last_mnt_id;\n6101:\t\tu64 mnt_parent_id;\n6102:\t\tu64 *kmnt_ids;\n6103:\t\tu32 nr_mnt_ids;\n6104:\t\tstruct mnt_namespace *ns;\n6105:\t\tstruct path root;\n6106:\t};\n6107:\t\n6108:\t/* locks: namespace_shared */\n6109:\tstatic ssize_t do_listmount(struct klistmount *kls, bool reverse)\n6110:\t{\n6111:\t\tstruct mnt_namespace *ns = kls-\u003ens;\n6112:\t\tu64 mnt_parent_id = kls-\u003emnt_parent_id;\n6113:\t\tu64 last_mnt_id = kls-\u003elast_mnt_id;\n6114:\t\tu64 *mnt_ids = kls-\u003ekmnt_ids;\n6115:\t\tsize_t nr_mnt_ids = kls-\u003enr_mnt_ids;\n6116:\t\tstruct path orig;\n6117:\t\tstruct mount *r, *first;\n6118:\t\tssize_t ret;\n6119:\t\n6120:\t\trwsem_assert_held(\u0026namespace_sem);\n6121:\t\n6122:\t\tret = grab_requested_root(ns, \u0026kls-\u003eroot);\n6123:\t\tif (ret)\n"
} |
| 57/3 | 2026/09/26 03:20 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 35315 output: 28 thoughts: 11 Thoughts: Okay, here's my interpretation of that thought process, assuming I'm an expert in this field, presented as a first-person summary: **Analyzing `do_statmount`** Alright, let's break down this `do_statmount` function or process. I immediately start thinking about its purpose. What is it designed to *do*? The name itself suggests a "stat" related operation. "Stat" implies information about a mounted file system or volume – likely size, usage, inodes, etc. - basically, the kind of data you'd see from a `df` or `stat` command. The "mount" portion confirms this; it's almost certainly involved in mounting and perhaps gathering the statistics from the file systems. My mind quickly jumps to the various places this function might be used. Is it called during initial system boot, at an interval, upon user request, when doing an unmount, or some other trigger? Understanding the calling context is *critical* to assessing its impact and potential problems. I'm considering what data structures this function is likely working with. Does it use the kernel's internal mount table? Is it interacting with the `mntent` or `fstab` data, or something similar? Are there any obvious potential race conditions with mounting/unmounting activity, or is there a robust locking mechanism in place? The underlying implementation is on my mind. Does it use direct syscalls (like `statfs`, for example), or does it interface through a higher-level library? Are there any potential vulnerabilities, like format string bugs, buffer overflows, or integer overflows during calculations? Any complex parsing or string manipulation in the codebase? Then, the error handling. I hope the code is robust and gracefully handles failures when accessing the file system or if there is a permission issue. What does it log? Is it logging the error to a useful location for me or does it just bail without telling me what went wrong? I'm thinking about performance too. If it's called frequently, I'll need to consider how efficient it is, especially if there are any network file systems involved. Is it optimized for common scenarios, or are there any easily avoidable bottlenecks? Are there ways to cache the results where appropriate? In short, my mind is already running through all the angles: its purpose, usage context, data structures, possible vulnerabilities, error handling, and performance considerations. I am already thinking about what questions I might ask to get to the core of the function. |
| 58/3 | 2026/09/26 03:20 | tool | grepper |
0mArgs:{
"Expression": "static int do_statmount",
"PathPrefix": "fs/"
}Results: {
"Output": "fs/namespace.c=5757=static int grab_requested_root(struct mnt_namespace *ns, struct path *root)\n--\nfs/namespace.c-5807-/* locks: namespace_shared */\nfs/namespace.c:5808:static int do_statmount(struct kstatmount *s, u64 mnt_id, u64 mnt_ns_id,\nfs/namespace.c-5809- struct file *mnt_file, struct mnt_namespace *ns)\n"
} |
| 59/3 | 2026/09/26 03:20 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 36015 output: 34 thoughts: 10 Thoughts: Okay, here's my interpretation of that thought process, assuming I'm already well-versed in this area: **Deconstructing `do_statmount`** Alright, so the initial thought is clear: I'm diving into the `do_statmount` function. This isn't just a casual glance; it's a deliberate step. I'm choosing to parse this specific function because it's *critical*. Given the context, I'm probably looking at a system's core initialization or a related process that hinges on mounting filesystems and their state. I need to understand its behaviour thoroughly. This might be to debug a specific issue, optimize some code, or just gain deeper understanding of how the system boots. I know this is a critical section that I need to master. |
| 60/3 | 2026/09/26 03:20 | tool | read-file |
0mArgs:{
"File": "fs/namespace.c",
"FirstLine": 5808,
"LineCount": 40
}Results: {
"Contents": "5808:\tstatic int do_statmount(struct kstatmount *s, u64 mnt_id, u64 mnt_ns_id,\n5809:\t struct file *mnt_file, struct mnt_namespace *ns)\n5810:\t{\n5811:\t\tint err;\n5812:\t\n5813:\t\tif (mnt_file) {\n5814:\t\t\tWARN_ON_ONCE(ns != NULL);\n5815:\t\n5816:\t\t\ts-\u003emnt = mnt_file-\u003ef_path.mnt;\n5817:\t\t\tns = real_mount(s-\u003emnt)-\u003emnt_ns;\n5818:\t\t\tif (IS_ERR(ns))\n5819:\t\t\t\treturn PTR_ERR(ns);\n5820:\t\t\tif (!ns)\n5821:\t\t\t\t/*\n5822:\t\t\t\t * We can't set mount point and mnt_ns_id since we don't have a\n5823:\t\t\t\t * ns for the mount. This can happen if the mount is unmounted\n5824:\t\t\t\t * with MNT_DETACH.\n5825:\t\t\t\t */\n5826:\t\t\t\ts-\u003emask \u0026= ~(STATMOUNT_MNT_POINT | STATMOUNT_MNT_NS_ID);\n5827:\t\t} else {\n5828:\t\t\t/* Has the namespace already been emptied? */\n5829:\t\t\tif (mnt_ns_id \u0026\u0026 mnt_ns_empty(ns))\n5830:\t\t\t\treturn -ENOENT;\n5831:\t\n5832:\t\t\ts-\u003emnt = lookup_mnt_in_ns(mnt_id, ns);\n5833:\t\t\tif (!s-\u003emnt)\n5834:\t\t\t\treturn -ENOENT;\n5835:\t\t}\n5836:\t\n5837:\t\tif (ns) {\n5838:\t\t\terr = grab_requested_root(ns, \u0026s-\u003eroot);\n5839:\t\t\tif (err)\n5840:\t\t\t\treturn err;\n5841:\t\n5842:\t\t\tif (!mnt_file) {\n5843:\t\t\t\tstruct mount *m;\n5844:\t\t\t\t/*\n5845:\t\t\t\t * Don't trigger audit denials. We just want to determine what\n5846:\t\t\t\t * mounts to show users.\n5847:\t\t\t\t */\n"
} |
| 61/3 | 2026/09/26 03:20 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 36834 output: 25 thoughts: 1407 Thoughts: **Analyzing the Vacant Mount and Nullfs Vulnerability**
Okay, let's break this down step by step. I'm focusing on the potential security implications here, specifically regarding vacant mounts and the `nullfs` instance.
First, I notice that the `lookup_mnt_in_ns` function checks the mounts within a namespace using the `ns->mounts` rbtree. It's crucial to remember that vacant mounts are *not* associated with any namespace because they've been unmounted. In `mntput_no_expire_slowpath`, the code asserts that `mnt->mnt_ns` is null for a vacant mount. This makes sense. Also, if a file had been opened on the mount, the mount wouldn't be vacant because the open file holds a reference to the vfsmount, so the slow path wouldn't be called. `mntput_no_expire_slowpath` is only called when the reference count drops to zero. This confirms that when a mount is vacated, there are no file descriptors referencing it.
But here's a wrinkle: What happens if a path lookup goes through the parent mount? The text describes a scenario where "a walk on the parent finds it and never ends up in what it covered." If someone walks into this vacant mount, the system will execute `__setup_mnt(mnt, knullfs->mnt_root);`. The crucial point is that `knullfs` is a `kern_mount(&nullfs_fs_type)` created in `init_mount_tree()`. It's a special `kern_mount` which sets the `SB_KERNMOUNT | SB_NOUSER` flags. This signifies an empty filesystem.
Now, the code change in `fs/fsopen.c` is important. This check, which prevents reconfiguration of kernel-internal superblocks with the `SB_NOUSER` flag, was added. I see why: someone could call `fspick()` on a vacant mount (or the `knullfs` instance).
Can someone open a file or dentry on a vacant mount? Yes, if a walk on the parent finds the vacant mount, the path walk could get a `struct path` to `knullfs->mnt_root` on `mnt` and userspace could call `fspick()` on that path. But thankfully, `kern_mount()` sets the `SB_KERNMOUNT | SB_NOUSER` flags. This means `fspick` should be stopped before any issues arise. And I see that the kernel will prevent userspace reconfiguration of these mounts through the `if` check.
Now, let's examine the memory initialization aspect very closely. I must confirm that there are *no* kernel structures being copied to userspace and that there are no uninitialized variables.
1. `fs/fsopen.c`: The only addition is the `SB_NOUSER` flag check. Nothing is copied to userspace; this is simply a flag check.
2. `fs/mount.h`: The `struct mount` union has been modified. Notably:
```c
union {
struct rb_node mnt_node; /* node in the ns->mounts rbtree */
struct { /* once it has left its namespace */
union {
struct rcu_head mnt_rcu;
struct llist_node mnt_llist;
};
struct dentry *mnt_old_root; /* what a vacant mount stands in for */
};
};
```
Is `struct mount` ever copied to userspace? No, this struct is purely internal to the VFS. This is good news.
Could any of `struct mount`'s fields be read uninitialized? I need to look at all accesses to `mnt_old_root`. It is used in `cleanup_mnt`:
```c
bool release = !(mnt->mnt.mnt_flags & MNT_DOOMED);
struct dentry *root = release ? mnt->mnt_old_root : mnt->mnt.mnt_root;
```
Here, when `release` is true, the `mnt_old_root` is accessed. `release` is true when `!(mnt->mnt.mnt_flags & MNT_DOOMED)`. I need to figure out when `MNT_DOOMED` is set. It is handled in `mntput_no_expire_slowpath`:
```c
/* Still attached, so it held its own reference: keep the slot filled. */
if (unlikely(mnt_has_parent(mnt)))
vacate =
|
| 62/3 | 2026/09/26 03:21 | tool | grepper |
0mArgs:{
"Expression": "cleanup_mnt",
"PathPrefix": "fs/"
}Results: {
"Output": "fs/namespace.c=1323=static inline bool is_vacant(const struct mount *mnt)\n--\nfs/namespace.c-1327-\nfs/namespace.c:1328:static void cleanup_mnt(struct mount *mnt)\nfs/namespace.c-1329-{\n--\nfs/namespace.c=1367=static void vacate_mount(struct mount *mnt)\n--\nfs/namespace.c-1375-\tmnt-\u003emnt_id_unique = mnt_alloc_unique_id();\nfs/namespace.c:1376:\t/* One reference for the parent and one for cleanup_mnt(). */\nfs/namespace.c-1377-\tmnt_add_count(mnt, 2);\n--\nfs/namespace.c-1379-\nfs/namespace.c:1380:static void __cleanup_mnt(struct rcu_head *head)\nfs/namespace.c-1381-{\nfs/namespace.c:1382:\tcleanup_mnt(container_of(head, struct mount, mnt_rcu));\nfs/namespace.c-1383-}\n--\nfs/namespace.c=1386=static void delayed_mntput(struct work_struct *unused)\n--\nfs/namespace.c-1391-\tllist_for_each_entry_safe(m, t, node, mnt_llist)\nfs/namespace.c:1392:\t\tcleanup_mnt(m);\nfs/namespace.c-1393-}\n--\nfs/namespace.c=1396=static void noinline mntput_no_expire_slowpath(struct mount *mnt)\n--\nfs/namespace.c-1449-\t\tif (likely(!(task-\u003eflags \u0026 PF_KTHREAD))) {\nfs/namespace.c:1450:\t\t\tinit_task_work(\u0026mnt-\u003emnt_rcu, __cleanup_mnt);\nfs/namespace.c-1451-\t\t\tif (!task_work_add(task, \u0026mnt-\u003emnt_rcu, TWA_RESUME))\n--\nfs/namespace.c-1457-\t}\nfs/namespace.c:1458:\tcleanup_mnt(mnt);\nfs/namespace.c-1459-}\n--\nfs/open.c=910=static inline int file_get_write_access(struct file *f)\n--\nfs/open.c-922-\t\tif (unlikely(error))\nfs/open.c:923:\t\t\tgoto cleanup_mnt;\nfs/open.c-924-\t}\n--\nfs/open.c-926-\nfs/open.c:927:cleanup_mnt:\nfs/open.c-928-\tmnt_put_write_access(f-\u003ef_path.mnt);\n"
} |
| 63/3 | 2026/09/26 03:21 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 39994 output: 34 thoughts: 40 Thoughts: Here's a breakdown of my thought process: **Diving into `mntput_no_expire_slowpath`** Okay, so I'm focusing on `mntput_no_expire_slowpath`. I need to understand what's happening within it, especially regarding namespace management. Right off the bat, I know that to get a handle on it, I want to zero in on lines 1440 to 1460 in `fs/namespace.c`. That section is usually where the core logic related to the filesystem namespace operations are handled. I'm guessing that particular block of code will provide crucial insight into how mount points are handled and how their lifetime is managed, or specifically, *not* managed in this 'slow path' scenario. Time to go dig in. |
| 64/3 | 2026/09/26 03:21 | tool | read-file |
0mArgs:{
"File": "fs/namespace.c",
"FirstLine": 1440,
"LineCount": 30
}Results: {
"Contents": "1440:\t\t\t}\n1441:\t\t}\n1442:\t\tif (unlikely(vacate))\n1443:\t\t\tvacate_mount(mnt);\n1444:\t\tunlock_mount_hash();\n1445:\t\tshrink_dentry_list(\u0026list);\n1446:\t\n1447:\t\tif (likely(!(mnt-\u003emnt.mnt_flags \u0026 MNT_INTERNAL))) {\n1448:\t\t\tstruct task_struct *task = current;\n1449:\t\t\tif (likely(!(task-\u003eflags \u0026 PF_KTHREAD))) {\n1450:\t\t\t\tinit_task_work(\u0026mnt-\u003emnt_rcu, __cleanup_mnt);\n1451:\t\t\t\tif (!task_work_add(task, \u0026mnt-\u003emnt_rcu, TWA_RESUME))\n1452:\t\t\t\t\treturn;\n1453:\t\t\t}\n1454:\t\t\tif (llist_add(\u0026mnt-\u003emnt_llist, \u0026delayed_mntput_list))\n1455:\t\t\t\tschedule_delayed_work(\u0026delayed_mntput_work, 1);\n1456:\t\t\treturn;\n1457:\t\t}\n1458:\t\tcleanup_mnt(mnt);\n1459:\t}\n1460:\t\n1461:\tstatic void mntput_no_expire(struct mount *mnt)\n1462:\t{\n1463:\t\trcu_read_lock();\n1464:\t\tif (likely(READ_ONCE(mnt-\u003emnt_ns))) {\n1465:\t\t\t/*\n1466:\t\t\t * Since we don't do lock_mount_hash() here,\n1467:\t\t\t * -\u003emnt_ns can change under us. However, if it's\n1468:\t\t\t * non-NULL, then there's a reference that won't\n1469:\t\t\t * be dropped until after an RCU delay done after\n"
} |
| 65/3 | 2026/09/26 03:21 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 40724 output: 26 thoughts: 2009 Thoughts: **Analyzing Mount Cleanup and Potential Issues** Okay, let's break this down. When a mount is vacated, `vacate_mount(mnt)` gets called. The code then checks if the mount is internal. If it's not, the mount is marked for delayed cleanup using `task_work_add` and `llist_add`. Essentially, RCU mechanisms are being used to defer the `cleanup_mnt` operation, to avoid blocking. Now, I see the interesting `struct mount` definition. The anonymous union is clever. `mnt_rcu` and `mnt_llist` share space, followed by `mnt_old_root`. This means that `init_task_work(&mnt->mnt_rcu, __cleanup_mnt)` writes to the `mnt_rcu` or `mnt_llist`, depending on what we use. Critically, it *doesn't* overwrite `mnt_old_root`. `__cleanup_mnt` then calls `cleanup_mnt`, and here's the key. `release` is determined by `MNT_DOOMED`. If `release` is true, it means we have a vacant mount, and the logic jumps to `mntput(&mnt->mnt); return;` This `mntput` is the initial reference from `vacate_mount`, and the vacant mount is still active. If false, it cleans up `knullfs`, frees the mount ID, and queues the mount structure for RCU freeing using `call_rcu()`. Notice that when `release` is true, we don't call `mnt_free_id` and `call_rcu`, so the vacant mount is still alive. If its parent mount goes away, or is detached, then it will become doomed. The code seems to ensure that there are no uninitialized reads of `mnt->mnt_old_root`. When `release` is true, `mnt->mnt_old_root` *is* initialized in `vacate_mount`. When `release` is false, it uses `mnt->mnt.mnt_root` instead. I'm checking the changes related to `unmounted` mounts. The `unmounted` list has changed to a `LIST_HEAD`, and the code uses `mnt->mnt_list`. The `mnt_list` member is properly initialized in `alloc_vfsmnt` with `INIT_LIST_HEAD`. It is properly initialized. Regarding `fsnotify`: The changes here focus on `fsnotify_mark_connector` and its associated `sb`. The `conn->sb` is initialized and explicitly set to `NULL` when detached. It appears the code ensures that the `sb` is managed consistently. Finally, I'm checking for potential information leaks to userspace. I've scanned the diff for `copy_to_user`, `put_user`, and `nla_put` calls and I'm not seeing any, so nothing is leaked to the user. I'll need to double check how the mount information is exposed through `/proc/mountinfo`, specifically `show_mountinfo`. It's critical to determine if any of these `mnt` fields are exposed in an uninitialized or insecure state. This seems safe from an initial review. |
| 66/3 | 2026/09/26 03:21 | tool | grepper |
0mArgs:{
"Expression": "show_mountinfo",
"PathPrefix": "fs/"
}Results: {
"Output": "fs/proc_namespace.c=101=static int show_vfsmnt(struct seq_file *m, struct vfsmount *mnt)\n--\nfs/proc_namespace.c-134-\nfs/proc_namespace.c:135:static int show_mountinfo(struct seq_file *m, struct vfsmount *mnt)\nfs/proc_namespace.c-136-{\n--\nfs/proc_namespace.c=303=static int mountinfo_open(struct inode *inode, struct file *file)\nfs/proc_namespace.c-304-{\nfs/proc_namespace.c:305:\treturn mounts_open_common(inode, file, show_mountinfo);\nfs/proc_namespace.c-306-}\n"
} |
| 67/3 | 2026/09/26 03:21 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 43656 output: 35 thoughts: 22 Thoughts: Here's a summary of my thought process: **Diving into `show_mountinfo` in `fs/proc_namespace.c`** Okay, so I need to understand what `show_mountinfo` is doing, specifically within the context of `fs/proc_namespace.c`. I'm assuming this function is responsible for populating the `/proc/mountinfo` file or a similar mount information interface. Given my expertise, I'm expecting to see details related to the namespace's view of mounted filesystems. I'll be looking for how it iterates through the mount list, gathers information about each mount point (source, target, filesystem type, options, etc.), and then formats that data into the appropriate output structure. I'll likely want to identify how it handles potentially complex scenarios, such as nested mount namespaces, shared or slave mounts, and bind mounts, as these intricacies are key to understanding the full picture of the filesystem namespace. I’m also curious about any optimizations or caching that might be employed for performance, given that `/proc/mountinfo` is frequently accessed. |
| 68/3 | 2026/09/26 03:21 | tool | read-file |
0mArgs:{
"File": "fs/proc_namespace.c",
"FirstLine": 135,
"LineCount": 45
}Results: {
"Contents": " 135:\tstatic int show_mountinfo(struct seq_file *m, struct vfsmount *mnt)\n 136:\t{\n 137:\t\tstruct proc_mounts *p = m-\u003eprivate;\n 138:\t\tstruct mount *r = real_mount(mnt);\n 139:\t\tstruct super_block *sb = mnt-\u003emnt_sb;\n 140:\t\tstruct path mnt_path = { .dentry = mnt-\u003emnt_root, .mnt = mnt };\n 141:\t\tint err;\n 142:\t\n 143:\t\tseq_printf(m, \"%i %i %u:%u \", r-\u003emnt_id, r-\u003emnt_parent-\u003emnt_id,\n 144:\t\t\t MAJOR(sb-\u003es_dev), MINOR(sb-\u003es_dev));\n 145:\t\terr = show_path(m, mnt-\u003emnt_root);\n 146:\t\tif (err)\n 147:\t\t\tgoto out;\n 148:\t\tseq_putc(m, ' ');\n 149:\t\n 150:\t\t/* mountpoints outside of chroot jail will give SEQ_SKIP on this */\n 151:\t\terr = seq_path_root(m, \u0026mnt_path, \u0026p-\u003eroot, \" \\t\\n\\\\\");\n 152:\t\tif (err)\n 153:\t\t\tgoto out;\n 154:\t\n 155:\t\tseq_puts(m, mnt-\u003emnt_flags \u0026 MNT_READONLY ? \" ro\" : \" rw\");\n 156:\t\tshow_vfsmnt_opts(m, mnt);\n 157:\t\n 158:\t\t/* Tagged fields (\"foo:X\" or \"bar\") */\n 159:\t\tif (IS_MNT_SHARED(r))\n 160:\t\t\tseq_printf(m, \" shared:%i\", r-\u003emnt_group_id);\n 161:\t\tif (IS_MNT_SLAVE(r)) {\n 162:\t\t\tint master = r-\u003emnt_master-\u003emnt_group_id;\n 163:\t\t\tint dom = get_dominating_id(r, \u0026p-\u003eroot);\n 164:\t\t\tseq_printf(m, \" master:%i\", master);\n 165:\t\t\tif (dom \u0026\u0026 dom != master)\n 166:\t\t\t\tseq_printf(m, \" propagate_from:%i\", dom);\n 167:\t\t}\n 168:\t\tif (IS_MNT_UNBINDABLE(r))\n 169:\t\t\tseq_puts(m, \" unbindable\");\n 170:\t\n 171:\t\t/* Filesystem specific data */\n 172:\t\tseq_puts(m, \" - \");\n 173:\t\tshow_type(m, sb);\n 174:\t\tseq_putc(m, ' ');\n 175:\t\tif (sb-\u003es_op-\u003eshow_devname) {\n 176:\t\t\terr = sb-\u003es_op-\u003eshow_devname(m, mnt-\u003emnt_root);\n 177:\t\t\tif (err)\n 178:\t\t\t\tgoto out;\n 179:\t\t} else {\n"
} |
| 69/3 | 2026/09/26 03:21 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 44757 output: 363 thoughts: 1075 Thoughts: **Assessing the KMSAN Needs for This Patch Series** Okay, let's break this down. My initial thought is that `/proc/mountinfo` isn't relevant here; it only sees mounts within the current mount namespace, and vacant mounts don't exist there. So, we can move past that. Then, I see there's a good test suite (`tools/testing/selftests/filesystems/mount_cycle/loop_cycle_test.c`) that seems to cover lazy unmounts and detached mounts held by loop devices, autofs, fuse, etc. That's a good start. The test suite checks that when everything closes, these mounts and backing devices are properly released, so that is a helpful validation. Now, let's think about the target bugs and potential new issues. This patch series looks like it addresses reference count cycles in detached mounts where a child filesystem holds something (like a file or device) on the parent. This prevents both from being cleaned up, causing leaks. The solution introduces "vacant mounts" using `knullfs` to release the child's reference to the parent, allowing the parent to unmount and shut down. So, what could go wrong? Reference counting bugs (leaks, use-after-free, double mntput), locking/synchronization issues (deadlock, races), superblock/dentry pinning or use-after-free, and null pointer dereferences. KASAN and LOCKDEP should catch most of these issues. Does this introduce uninitialized memory risks? Let's check: 1. **Kernel structures exposed to userspace:** Nope. No new structures or copies to userspace. 2. **Conditional logic based on uninitialized variables:** No. `mnt_old_root`, `is_vacant()`, `conn->sb` are properly initialized. 3. **Complex data structure initialization:** No. All allocations (`alloc_vfsmnt`) use `kmem_cache_zalloc`, `fsnotify_mark_connector` initializes `conn->sb`. 4. **Buffer bounds checks/uninitialized bytes:** No. Therefore, I conclude that this patch series *does not* introduce uninitialized memory risks. KASAN and LOCKDEP are the correct tools for these potential bugs (UAF, refcounting, lock ordering). A KMSAN fuzzing session is not needed here. Now, let's define the `set-results` parameters. `NeedsKMSAN` is `false`. The `KMSANReasoning` is key: The patch resolves mount reference cycles in disconnected mounts (e.g., loop mounts backed by files on a detached parent mount) by introducing vacant mounts. These vacant mounts swap the child's root/sb to a private `knullfs` instance upon losing references while still attached and track superblocks in fsnotify connectors. The risks are related to reference counting (leaks or underflows, use-after-free), mount hierarchy detachment bugs, locking/race conditions during mount teardown, and dentry/superblock lifecycle management. These are KASAN, refcount checking, and LOCKDEP issues. KMSAN won't detect these. No new structures are exposed, no new `copy_to_user` paths, and the struct allocations correctly initialize all fields, and no conditional branching relies on uninitialized data. Standard KASAN/LOCKDEP fuzzing is sufficient. Okay, all that's left is to call `set-results`. |
| 70/3 | 2026/09/26 03:21 | tool | set-results |
0mArgs:{
"KMSANReasoning": "The patch series resolves reference count cycles between detached mounts and attached submounts (e.g., loop devices or filesystems holding references on parent mounts) by introducing 'vacant mounts' that substitute a private knullfs instance for the submount's root/superblock when unreferenced while attached, and updates fsnotify mark connectors to explicitly track superblocks.\n\nRisk analysis:\n1. Uninitialized Memory / Info Leaks: None. No new kernel-to-user copy interfaces, ioctls, or user-visible data structures are added or altered. The fields added to internal structures (`mnt_old_root` in `struct mount` and `sb` in `struct fsnotify_mark_connector`) are explicitly initialized upon allocation or setup (`alloc_vfsmnt` uses `kmem_cache_zalloc`, `vacate_mount` sets `mnt_old_root`, and `fsnotify_init_connector` sets `conn-\u003esb`). There are no uninitialized variables or conditional branches dependent on uninitialized data.\n2. Memory Safety and Concurrency: The primary risks associated with this patch involve reference counting errors (e.g., mount refcount underflows/leaks, use-after-free, double puts), superblock and dentry lifecycle management, and synchronization/locking around mount teardown. These bugs are detected by KASAN (use-after-free, double free), refcount sanity checks, and LOCKDEP.\n\nBecause there are no uninitialized memory access or info-leak risks, running a dedicated KMSAN session is not justified; standard KASAN and LOCKDEP coverage is sufficient.",
"NeedsKMSAN": false
}Results: {
"KMSANReasoning": "The patch series resolves reference count cycles between detached mounts and attached submounts (e.g., loop devices or filesystems holding references on parent mounts) by introducing 'vacant mounts' that substitute a private knullfs instance for the submount's root/superblock when unreferenced while attached, and updates fsnotify mark connectors to explicitly track superblocks.\n\nRisk analysis:\n1. Uninitialized Memory / Info Leaks: None. No new kernel-to-user copy interfaces, ioctls, or user-visible data structures are added or altered. The fields added to internal structures (`mnt_old_root` in `struct mount` and `sb` in `struct fsnotify_mark_connector`) are explicitly initialized upon allocation or setup (`alloc_vfsmnt` uses `kmem_cache_zalloc`, `vacate_mount` sets `mnt_old_root`, and `fsnotify_init_connector` sets `conn-\u003esb`). There are no uninitialized variables or conditional branches dependent on uninitialized data.\n2. Memory Safety and Concurrency: The primary risks associated with this patch involve reference counting errors (e.g., mount refcount underflows/leaks, use-after-free, double puts), superblock and dentry lifecycle management, and synchronization/locking around mount teardown. These bugs are detected by KASAN (use-after-free, double free), refcount sanity checks, and LOCKDEP.\n\nBecause there are no uninitialized memory access or info-leak risks, running a dedicated KMSAN session is not justified; standard KASAN and LOCKDEP coverage is sufficient.",
"NeedsKMSAN": false
} |
| Total Calls | Total Tokens | Avg Tokens | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|
| Total Calls | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|