Skip to contentSkip to conversation

libfs: fix readdir of offset directories

PATCH In review Christian Brauner 2 participants 5 messages Nov 1

Subsystems (4)
lore
Share & tools
lore

Christian Brauner

author maintainer
#0 lore raw

v2 cover libfs: fix readdir of offset directories

readdir on tmpfs walks d_children and only uses the offset tree to map the file position back to a dentry. d_children and offset order disagree after a rename over a name, an exchange or a wrap of the offset allocator. An unlink between two getdents64() calls then makes the walk skip entries or return the whole directory again. So walk the offset tree itself in descending offset order.

v1 did that with a full tree descent and a reference for every entry and was quite a bit slower. Now the walk keeps one ma_state for the whole call and takes no references at all. That relies on all writers holding i_rwsem exclusive while readdir holds it shared, and the maple tree only allows that if i_rwsem is the lock of the tree. The first patch makes it so, and lockdep now checks the writers. The last patch stops an lseek() past the end from returning the whole directory again.

1M entries on tmpfs, getdents64() with a 32k buffer: 146ms before, about 230ms with v1, 114ms now. Four processes listing the directory at the same time: 470ms per listing before, 113ms now.

Tested with Nickolai's reproducer, generic/736 and a seek-after-closedir test, on tmpfs and on tmpfs exported over NFSv3 and NFSv4.2, on KASAN and lockdep kernels. I also wrote a TLA+ model of the walk (cf. [1]).

[1]: https://github.com/brauner/linux-formal/tree/main/kernel/libfs/offset-readdir

---
Changes in v2:
- Make i_rwsem the lock of the offset tree.
- Keep one ma_state across the walk and take no references (Chuck).
- Don't return the whole directory again after an lseek() past
DIR_OFFSET_EOD.
- Link to v1: https://patch.msgid.link/[email protected]

---
Christian Brauner (3):
libfs: make i_rwsem the lock of the offset tree
libfs: walk offset directories in offset order
libfs: end offset readdir at positions past DIR_OFFSET_EOD

 fs/libfs.c         | 133 +++++++++++++++++++++--------------------------------
 include/linux/fs.h |   2 +-
 mm/shmem.c         |   2 +-
 3 files changed, 54 insertions(+), 83 deletions(-)

---
base-commit: b44341e39d856e4cc6ad8ed94ebffd440f39846c
change-id: 20261030-work-libfs-offset_readdir-807d3b774260

author maintainer
#1 lore raw

PATCH v2 1/3 libfs: make i_rwsem the lock of the offset tree

The offset tree of a directory is only changed with the directory's i_rwsem held exclusive and offset_readdir() walks it with i_rwsem held shared. But the maple tree doesn't know that. It is set up with its internal spinlock, which every mtree_*() helper takes, and readdir takes rcu_read_lock() around each lookup.

The next patch makes readdir keep one ma_state across dir_emit(), which can sleep. That is safe because no writer can run while readdir holds i_rwsem. But the maple tree only allows keeping a ma_state across a sleep if it is protected by the tree's lock. A reader that relies on rcu_read_lock() has to mas_pause() before it drops it, and that means a walk from the root for every entry again.

So tell the tree what protects it. Initialize it with MT_FLAGS_LOCK_EXTERN and the directory's i_rwsem as its lock and switch the writers from the mtree_*() helpers to the mas_*() api. They all run with i_rwsem held exclusive already. With lockdep enabled the maple tree now also checks that every writer holds i_rwsem exclusive.

Nothing can reach the offset tree anymore when the directory inode is destroyed. So clear the external lock with mt_on_stack() and destroy the tree with __mt_destroy() instead of taking i_rwsem in ->destroy_inode().

---
 fs/libfs.c         | 46 +++++++++++++++++++++++++++++-----------------
 include/linux/fs.h |  2 +-
 mm/shmem.c         |  2 +-
 3 files changed, 31 insertions(+), 19 deletions(-)
fs/libfs.c +29 -17
index 96a6e9b1535f..653ee8461a8f 100644
@@ -263,17 +263,18 @@ static long dentry2offset(struct dentry *dentry)
 	return (long)dentry->d_fsdata;
 }
 
-static struct lock_class_key simple_offset_lock_class;
-
 /**
  * simple_offset_init - initialize an offset_ctx
  * @octx: directory offset map to be initialized
+ * @dir: the directory @octx belongs to
  *
+ * The directory's i_rwsem is the lock of the offset map. Writers hold it
+ * exclusive, offset_readdir() holds it shared.
  */
-void simple_offset_init(struct offset_ctx *octx)
+void simple_offset_init(struct offset_ctx *octx, struct inode *dir)
 {
-	mt_init_flags(&octx->mt, MT_FLAGS_ALLOC_RANGE);
-	lockdep_set_class(&octx->mt.ma_lock, &simple_offset_lock_class);
+	mt_init_flags(&octx->mt, MT_FLAGS_ALLOC_RANGE | MT_FLAGS_LOCK_EXTERN);
+	mt_set_external_lock(&octx->mt, &dir->i_rwsem);
 	octx->next_offset = DIR_OFFSET_MIN;
 }
 
@@ -290,12 +291,13 @@ int simple_offset_add(struct offset_ctx *octx, struct dentry *dentry)
 	unsigned long offset;
 	int ret;
 
+	MA_STATE(mas, &octx->mt, 0, 0);
+
 	if (dentry2offset(dentry) != 0)
 		return -EBUSY;
 
-	ret = mtree_alloc_cyclic(&octx->mt, &offset, dentry, DIR_OFFSET_MIN,
-				 DIR_OFFSET_MAX, &octx->next_offset,
-				 GFP_KERNEL);
+	ret = mas_alloc_cyclic(&mas, &offset, dentry, DIR_OFFSET_MIN,
+			       DIR_OFFSET_MAX, &octx->next_offset, GFP_KERNEL);
 	if (unlikely(ret < 0))
 		return ret == -EBUSY ? -ENOSPC : ret;
 
@@ -308,7 +310,9 @@ static int simple_offset_replace(struct offset_ctx *octx, struct dentry *dentry,
 {
 	int ret;
 
-	ret = mtree_store(&octx->mt, offset, dentry, GFP_KERNEL);
+	MA_STATE(mas, &octx->mt, offset, offset);
+
+	ret = mas_store_gfp(&mas, dentry, GFP_KERNEL);
 	if (ret)
 		return ret;
 	offset_set(dentry, offset);
@@ -323,13 +327,14 @@ static int simple_offset_replace(struct offset_ctx *octx, struct dentry *dentry,
  */
 void simple_offset_remove(struct offset_ctx *octx, struct dentry *dentry)
 {
-	long offset;
+	long offset = dentry2offset(dentry);
+
+	MA_STATE(mas, &octx->mt, offset, offset);
 
-	offset = dentry2offset(dentry);
 	if (offset == 0)
 		return;
 
-	mtree_erase(&octx->mt, offset);
+	mas_erase(&mas);
 	offset_set(dentry, 0);
 }
 
@@ -387,16 +392,20 @@ int simple_offset_rename_exchange(struct inode *old_dir,
 	long new_index = dentry2offset(new_dentry);
 	int ret;
 
+	MA_STATE(old_mas, &old_ctx->mt, old_index, old_index);
+	MA_STATE(new_mas, &new_ctx->mt, new_index, new_index);
+
 	if (WARN_ON(!old_index || !new_index))
 		return -EINVAL;
 
-	ret = mtree_store(&new_ctx->mt, new_index, old_dentry, GFP_KERNEL);
+	ret = mas_store_gfp(&new_mas, old_dentry, GFP_KERNEL);
 	if (WARN_ON(ret))
 		return ret;
 
-	ret = mtree_store(&old_ctx->mt, old_index, new_dentry, GFP_KERNEL);
+	ret = mas_store_gfp(&old_mas, new_dentry, GFP_KERNEL);
 	if (WARN_ON(ret)) {
-		mtree_store(&new_ctx->mt, new_index, new_dentry, GFP_KERNEL);
+		mas_set(&new_mas, new_index);
+		mas_store_gfp(&new_mas, new_dentry, GFP_KERNEL);
 		return ret;
 	}
 
@@ -411,11 +420,14 @@ int simple_offset_rename_exchange(struct inode *old_dir,
  * @octx: directory offset ctx that is about to be destroyed
  *
  * During fs teardown (eg. umount), a directory's offset map might still
- * contain entries. xa_destroy() cleans out anything that remains.
+ * contain entries. __mt_destroy() cleans out anything that remains.
+ * Nothing can reach the map of a directory that is being destroyed, so
+ * this runs without the directory's i_rwsem.
  */
 void simple_offset_destroy(struct offset_ctx *octx)
 {
-	mtree_destroy(&octx->mt);
+	mt_on_stack(octx->mt);
+	__mt_destroy(&octx->mt);
 }
 
 /**
include/linux/fs.h +1 -1
index b5485f2c1f2b..a2046718e839 100644
@@ -3330,7 +3330,7 @@ struct offset_ctx {
 	unsigned long		next_offset;
 };
 
-void simple_offset_init(struct offset_ctx *octx);
+void simple_offset_init(struct offset_ctx *octx, struct inode *dir);
 int simple_offset_add(struct offset_ctx *octx, struct dentry *dentry);
 void simple_offset_remove(struct offset_ctx *octx, struct dentry *dentry);
 void simple_offset_rename(struct inode *old_dir, struct dentry *old_dentry,
mm/shmem.c +1 -1
index 0d891ade18b5..24e2b9510c7c 100644
@@ -3089,7 +3089,7 @@ static struct inode *__shmem_get_inode(const struct mnt_idmap *idmap,
 		inode->i_size = 2 * BOGO_DIRENT_SIZE;
 		inode->i_op = &shmem_dir_inode_operations;
 		inode->i_fop = &simple_offset_dir_operations;
-		simple_offset_init(shmem_get_offset_ctx(inode));
+		simple_offset_init(shmem_get_offset_ctx(inode), inode);
 		break;
 	case S_IFLNK:
 		/*
Signature · 1 line
2.53.0
author maintainer
#2 lore raw

PATCH v2 2/3 libfs: walk offset directories in offset order

In reply to Christian Brauner

offset_iterate_dir() walks d_children from the head and only uses the maple tree to map ctx->pos back to a dentry when a getdents64() call resumes. offset_dir_lookup() finds the entry at ctx->pos, or the one with the next lower offset if it is gone, and the list walk continues from there.

That only works if list order and offset order agree and quite often they don't. A rename over an existing name gives the moved dentry the offset of the name it replaced but __d_move() puts it at the head of d_children. RENAME_EXCHANGE does the same to both dentries. And once the cyclic offset allocator wraps new entries get low offsets at the head of the list.

So if the entry at ctx->pos is unlinked between two getdents64() calls we resume at the entry with the next lower offset and that one can sit anywhere in the list:

(1) If it sits further down the list everything in between is skipped. Create y, t, a, b and rename b over t. The list is now t(4) a(5) y(3). Stop the listing at t and unlink t. The next call resumes at y and a is never returned although nobody touched it.

(2) If there is no lower entry we restart at the head and return the whole directory again. Nickolai reported this for the simple case of unlinking the oldest entry while a listing is about to reach it. Ending the walk there instead turns this into (1): create a, b, c, rename c over a, stop the listing at the renamed entry, unlink it, and b is lost.

Instead of the list let's walk the maple tree itself in descending offset order. Then ctx->pos really means that everything above it has been emitted and resuming at the highest offset at or below it is right no matter where the dentry sits in d_children. Entries created or renamed to a new name after the listing started get an offset above ctx->pos and aren't returned, same as with the list walk which never went back to the head. So a readdir loop that renames or creates an entry for each one it reads still terminates.

The maple tree can't change under us as all modifications happen with the directory's i_rwsem held exclusive and offset_readdir() holds it shared. That also covers the dentries in the tree. They are all persistent and only unlink, rmdir and rename remove or rename them. And since the previous patch i_rwsem is the lock of the tree. So keep a single ma_state across the walk and emit directly from the dentry without taking rcu_read_lock(), a reference or d_lock.

This also makes the walk cheaper than the list walk was. With a million entries on tmpfs a getdents64() listing goes from 146ms to 114ms. With four processes listing the directory at the same time it goes from 470ms to 113ms per listing as they don't bounce the parent's d_lock and the dentries' lockrefs between them anymore.

                                                base     v2       this
      1M entries, getdents64 32k buffer (ms)    146      127      114
      1M entries, getdents64 1k buffer (ms)     184      156      141
      1M entries, getdents64 128b buffer (ms)   429      364      335
      1M entries, ls -f (s)                     0.259    0.239    0.228
      1M entries, LC_ALL=C ls (s)               0.482    0.467    0.455
      1M entries, 4 parallel listers (ms)       470      125      113
      18 entries, rewind and list (ns)          4107     3594     3323
      250k of 1M left, getdents64 32k (ms)      58.8     57.8     53.8
      250k of 1M left, getdents64 128b (ms)     128      114      108
Fixes b9b588f22a0c ("libfs: Use d_children list to iterate simple_offset directories")
Fixes f70681e9e606 ("libfs: Fix duplicate directory entry in offset_dir_lookup")
---
 fs/libfs.c | 85 ++++++++++++++++----------------------------------------------
 1 file changed, 22 insertions(+), 63 deletions(-)
fs/libfs.c +22 -63
index 653ee8461a8f..654f487b05c0 100644
@@ -283,6 +283,12 @@ void simple_offset_init(struct offset_ctx *octx, struct inode *dir)
  * @octx: directory offset ctx to be updated
  * @dentry: new dentry being added
  *
+ * The offset map holds no reference to @dentry. Once positive, @dentry
+ * must be pinned with d_make_persistent() for as long as it is in the
+ * map, and entries may only be added, removed or renamed with the
+ * directory's i_rwsem held exclusive: offset_readdir() emits straight
+ * from the map under the shared lock.
+ *
  * Returns zero on success. @octx and the dentry's offset are updated.
  * Otherwise, a negative errno value is returned.
  */
@@ -458,51 +464,6 @@ static loff_t offset_dir_llseek(struct file *file, loff_t offset, int whence)
 	return vfs_setpos(file, offset, LONG_MAX);
 }
 
-static struct dentry *find_positive_dentry(struct dentry *parent,
-					   struct dentry *dentry,
-					   bool next)
-{
-	struct dentry *found = NULL;
-
-	spin_lock(&parent->d_lock);
-	if (next)
-		dentry = d_next_sibling(dentry);
-	else if (!dentry)
-		dentry = d_first_child(parent);
-	hlist_for_each_entry_from(dentry, d_sib) {
-		if (!simple_positive(dentry))
-			continue;
-		spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
-		if (simple_positive(dentry))
-			found = dget_dlock(dentry);
-		spin_unlock(&dentry->d_lock);
-		if (likely(found))
-			break;
-	}
-	spin_unlock(&parent->d_lock);
-	return found;
-}
-
-static noinline_for_stack struct dentry *
-offset_dir_lookup(struct dentry *parent, loff_t offset)
-{
-	struct inode *inode = d_inode(parent);
-	struct offset_ctx *octx = inode->i_op->get_offset_ctx(inode);
-	struct dentry *child, *found = NULL;
-
-	MA_STATE(mas, &octx->mt, offset, offset);
-
-	if (offset == DIR_OFFSET_FIRST)
-		found = find_positive_dentry(parent, NULL, false);
-	else {
-		rcu_read_lock();
-		child = mas_find_rev(&mas, DIR_OFFSET_MIN);
-		found = find_positive_dentry(parent, child, false);
-		rcu_read_unlock();
-	}
-	return found;
-}
-
 static bool offset_dir_emit(struct dir_context *ctx, struct dentry *dentry)
 {
 	struct inode *inode = d_inode(dentry);
@@ -511,32 +472,30 @@ static bool offset_dir_emit(struct dir_context *ctx, struct dentry *dentry)
 			inode->i_ino, fs_umode_to_dtype(inode->i_mode));
 }
 
+/*
+ * Emit entries in descending offset order. The directory's i_rwsem is the
+ * lock of the offset tree and the persistent dentries in it only change
+ * with it held exclusive. We hold it shared, so @mas stays valid across
+ * dir_emit() and the dentries need no references.
+ */
 static void offset_iterate_dir(struct file *file, struct dir_context *ctx)
 {
-	struct dentry *dir = file->f_path.dentry;
+	struct inode *inode = file_inode(file);
+	struct offset_ctx *octx = inode->i_op->get_offset_ctx(inode);
+	loff_t start = ctx->pos == DIR_OFFSET_FIRST ? DIR_OFFSET_MAX : ctx->pos;
 	struct dentry *dentry;
 
-	dentry = offset_dir_lookup(dir, ctx->pos);
-	if (!dentry)
-		goto out_eod;
-	while (true) {
-		struct dentry *next;
+	MA_STATE(mas, &octx->mt, start, start);
 
+	for (;;) {
+		dentry = mas_find_rev(&mas, DIR_OFFSET_MIN);
+		if (!dentry)
+			break;
+		VFS_WARN_ON_ONCE(!(dentry->d_flags & DCACHE_PERSISTENT));
 		ctx->pos = dentry2offset(dentry);
 		if (!offset_dir_emit(ctx, dentry))
-			break;
-
-		next = find_positive_dentry(dir, dentry, true);
-		dput(dentry);
-
-		if (!next)
-			goto out_eod;
-		dentry = next;
+			return;
 	}
-	dput(dentry);
-	return;
-
-out_eod:
 	ctx->pos = DIR_OFFSET_EOD;
 }
 
Signature · 1 line
2.53.0
author maintainer
#3 lore raw

PATCH v2 3/3 libfs: end offset readdir at positions past DIR_OFFSET_EOD

In reply to Christian Brauner

offset_dir_llseek() takes any position up to LONG_MAX but offset_readdir() only skips the walk for DIR_OFFSET_EOD itself. For a position past it mas_find_rev() starts the walk at the highest offset in the directory. So an lseek() past the end makes the next getdents64() return the whole directory again.

Before commit b9b588f22a0c ("libfs: Use d_children list to iterate simple_offset directories") the walk went up from the position and found nothing past the end, and dcache_readdir() returns nothing there either. So only walk for positions below DIR_OFFSET_EOD.

Fixes b9b588f22a0c ("libfs: Use d_children list to iterate simple_offset directories")
---
 fs/libfs.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/libfs.c +1 -1
index 654f487b05c0..46e0205154e7 100644
@@ -530,7 +530,7 @@ static int offset_readdir(struct file *file, struct dir_context *ctx)
 
 	if (!dir_emit_dots(file, ctx))
 		return 0;
-	if (ctx->pos != DIR_OFFSET_EOD)
+	if (ctx->pos < DIR_OFFSET_EOD)
 		offset_iterate_dir(file, ctx);
 	return 0;
 }
Signature · 1 line
2.53.0
Reviewed-by on the v2 series
#4 lore raw
In reply to Christian Brauner
Quoted 42 lines · Christian Brauner

readdir on tmpfs walks d_children and only uses the offset tree to map the file position back to a dentry. d_children and offset order disagree after a rename over a name, an exchange or a wrap of the offset allocator. An unlink between two getdents64() calls then makes the walk skip entries or return the whole directory again. So walk the offset tree itself in descending offset order.

v1 did that with a full tree descent and a reference for every entry and was quite a bit slower. Now the walk keeps one ma_state for the whole call and takes no references at all. That relies on all writers holding i_rwsem exclusive while readdir holds it shared, and the maple tree only allows that if i_rwsem is the lock of the tree. The first patch makes it so, and lockdep now checks the writers. The last patch stops an lseek() past the end from returning the whole directory again.

1M entries on tmpfs, getdents64() with a 32k buffer: 146ms before, about 230ms with v1, 114ms now. Four processes listing the directory at the same time: 470ms per listing before, 113ms now.

Tested with Nickolai's reproducer, generic/736 and a seek-after-closedir test, on tmpfs and on tmpfs exported over NFSv3 and NFSv4.2, on KASAN and lockdep kernels. I also wrote a TLA+ model of the walk (cf. [1]).

[1]:
https://github.com/brauner/linux-formal/tree/main/kernel/libfs/offset-readdir

---
Changes in v2:
- Make i_rwsem the lock of the offset tree.
- Keep one ma_state across the walk and take no references (Chuck).
- Don't return the whole directory again after an lseek() past DIR_OFFSET_EOD.
- Link to v1:
https://patch.msgid.link/[email protected]

---
Christian Brauner (3):
libfs: make i_rwsem the lock of the offset tree
libfs: walk offset directories in offset order
libfs: end offset readdir at positions past DIR_OFFSET_EOD

Quoted 7 lines
 fs/libfs.c         | 133 +++++++++++++++++++++--------------------------------
 include/linux/fs.h |   2 +-
 mm/shmem.c         |   2 +-
 3 files changed, 54 insertions(+), 83 deletions(-)

---
base-commit: b44341e39d856e4cc6ad8ed94ebffd440f39846c
change-id: 20261030-work-libfs-offset_readdir-807d3b774260

Signature · 1 line
Chuck Lever (Come to NFS bake-a-thon! https://nfsv4bat.org)