Skip to contentSkip to conversation

Fix easy bits of the negative dentry problem

PATCH In review NeilBrown 2 participants 7 messages Nov 25

Subsystems (6)
lore
Share & tools
lore

NeilBrown

author
#0 lore raw

v7 cover Fix easy bits of the negative dentry problem

Seventh time's the charm??

- Fixed silly error in d_duplicate(), and reviewed all the code more carefully this time.
- added comment and data_race() annotation to autofs changes, and also renamed the new function to dentry_busy().
- added text to commit message for 2/5 to explain that there is a remaining race that we didn't attempt to fix.

Thanks,
NeilBrown

Original intro - revised:

I was reading about the negative dentry problem in
https://lwn.net/Articles/1079407/ and thought I would have a go at the easy bits. Given how involved some of that was I'm glad I didn't try the tricky bits!

So I didn't try to reduce the number of negative dentries or handle them differently to positive dentries. I just tried to address specific symptoms.

This series addresses two reported symptoms.
1/ refcounts on parents can potentially overflow if there are billions
of (negative) children. This was the easiest easy bit. The first patch is all that is needed.

2/ Walking the ->d_children list can take arbitrarily long and can
trigger soft lockups. I haven't addresses the "arbitrarily long" part, but the "soft lockups" is relatively easy.
With this in place I would feel more confident addressing the "arbitrarily long" part if that seemed worth while.

The core idea is to use a common helper for all walking of ->d_children, and teach it to drop the lock and schedule when needed, inserting a cursor to keep its place. This simple idea requires that nothing should be holding any other lock while walking ->d_children

[PATCH v7 1/5] VFS: don't count references through ->d_parent [PATCH v7 2/5] fsnotify: update children flags only when parent [PATCH v7 3/5] fsnotify: don't hold i_lock while walking d_children [PATCH v7 4/5] Add d_for_each_positive_child family of iterators [PATCH v7 5/5] Use d_for_each_positive_child() in fsnotify.

author
#1 lore raw

PATCH v7 1/5 VFS: don't count references through ->d_parent

From: NeilBrown <[email protected]>

The number of negative child dentries that a given dentry can have is effectively unbounded, so counting the references through ->d_parent can overflow ->d_lockref.count.

We only use this count so that we can know when there are no remaining references including from children. However most children appear on the ->d_children list and the few remaining children (inactive DCACHE_DENTRY_CURSORs) only exist in a context were a separate reference is held on the parent.

So if we count whether d_children is nonempty (i.e. dget() when it becomes non-empty, dput() when it comes empty) and require children not on ->d_children to have a reference on the parent some other way (which they already do), then ->d_lockref.count will not overflow and we can still know exactly when all references, including through ->d_parent, are gone.

__d_move() allows that dentries might not be on any d_children list as is the case for IS_ROOT() dentries. Rather than track when this is the case we dget() either parent if they have an empty d_children before children are moved around, then dput() if they turn out to be empty afterwards. This will increment dentry if it IS_ROOT(), and then decrement it afterwards, and will decrement the refcount on old_parent if its ->d_children becomes empty.

To help with this, dput_dlock() is added which warns rather than decrementing to zero (which should never happen).

When a DCACHE_CURSOR dentry is added to d_children, it is only ever added "before" or "behind" an existing child, so it will never be the first child added, and so never needs to adjust the refcount on the parent. If it remains on the list until dput() it could be the last child to be removed, in which case normal handling applies in dentry_unlist() (where it has been moved from dentry_kill(). When a cursor is deliberately removed from the d_children list the refcount must be decremented if that leaves the list empty.

hlist_move_behind() and hlist_move_before() are added to simplify moving a cursor within the d_children list. This results in some duplicate code as they share a common prefix with d_detach_cursor() (hlist_del) which is currently factored out. We can expect the compiler to optimise this away and don't need to clutter the C code with it.

autofs compares d_count() with the number of known children of a dentry to detect if there are any concurrent references to a dentry. These comparisons must be changed to reflect that we now only count "one" for any children rather than "one" for each child. This can be done without using ino->count but simply by looking at ->d_children. So a new static-inline "dentry_busy()" is added which performs the check and is told how many unusual references to expect.
As no locks are held, this test is racy. And comment is provided explaining why the race is of no consequence.

---
 fs/autofs/expire.c     | 43 +++++++++++++++++++++++++----------------
 fs/dcache.c            | 44 ++++++++++++++++++++++++++++++++++--------
 fs/internal.h          | 10 ++++++++++
 fs/libfs.c             | 14 +++++++-------
 include/linux/dcache.h | 17 +++++++++++++++-
 include/linux/list.h   | 30 ++++++++++++++++++++++++++++
 6 files changed, 125 insertions(+), 33 deletions(-)
fs/autofs/expire.c +26 -17
index 5c2d459e1e48..4eabf61719fc 100644
@@ -7,6 +7,28 @@
 
 #include "autofs_i.h"
 
+static inline bool dentry_busy(struct dentry *d, int expected)
+{
+	/*
+	 * The dentry is not locked so both ->d_children and d_count()
+	 * could change asychronously, possibly resulting in a false
+	 * negative.  This is of no consequence as a negative results in
+	 * should_expire() finding a dentry, and autofs_expire_indirect()
+	 * requires that should_expire() find the same dentry twice in
+	 * a row.  Even if both attempts race the same way, the worst case
+	 * is that a mount is expired early and has to be remounted.
+	 */
+
+	/* a ref is always held on 'd' */
+	expected += 1;
+	/* DCACHE_PERSISTENT is always set */
+	expected += 1;
+	if (!hlist_empty(&d->d_children))
+		/* expect children to be counted */
+		expected += 1;
+	return data_race(d_count(d) > expected);
+}
+
 /* Check if a dentry can be expired */
 static inline int autofs_can_expire(struct dentry *dentry,
 				    unsigned long timeout, unsigned int how)
@@ -207,16 +229,8 @@ static int autofs_tree_busy(struct vfsmount *mnt,
 				return 1;
 			}
 		} else {
-			struct autofs_info *ino = autofs_dentry_ino(p);
-			unsigned int ino_count = READ_ONCE(ino->count);
-
-			/* allow for dget above and top is already dgot */
-			if (p == top)
-				ino_count += 2;
-			else
-				ino_count++;
-
-			if (d_count(p) > ino_count) {
+			/* an extra reference is held on "top" */
+			if (dentry_busy(p, (p==top))) {
 				top_ino->last_used = jiffies;
 				dput(p);
 				return 1;
@@ -321,7 +335,6 @@ static struct dentry *should_expire(struct dentry *dentry,
 				    unsigned int how)
 {
 	struct autofs_info *ino = autofs_dentry_ino(dentry);
-	unsigned int ino_count;
 
 	/* No point expiring a pending mount */
 	if (ino->flags & AUTOFS_INF_PENDING)
@@ -375,9 +388,7 @@ static struct dentry *should_expire(struct dentry *dentry,
 	if (!(how & AUTOFS_EXP_LEAVES)) {
 		/* Not a forced expire? */
 		if (!(how & AUTOFS_EXP_FORCED)) {
-			/* ref-walk currently on this dentry? */
-			ino_count = READ_ONCE(ino->count) + 1;
-			if (d_count(dentry) > ino_count)
+			if (dentry_busy(dentry, 0))
 				return NULL;
 		}
 
@@ -392,9 +403,7 @@ static struct dentry *should_expire(struct dentry *dentry,
 
 		/* Not a forced expire? */
 		if (!(how & AUTOFS_EXP_FORCED)) {
-			/* ref-walk currently on this dentry? */
-			ino_count = READ_ONCE(ino->count) + 1;
-			if (d_count(dentry) > ino_count)
+			if (dentry_busy(dentry, 0))
 				return NULL;
 		}
 
fs/dcache.c +36 -8

95 lines not on this page · raw message

fs/internal.h +10 -0
index 3f2fbac40f8e..22e018429759 100644
@@ -235,6 +235,16 @@ extern struct dentry *__d_lookup(const struct dentry *, const struct qstr *);
 extern struct dentry *__d_lookup_rcu(const struct dentry *parent,
 				const struct qstr *name, unsigned *seq);
 
+static inline void d_detach_cursor(struct dentry *cursor)
+{
+	if (hlist_unhashed(&cursor->d_sib))
+		return;
+	hlist_del_init(&cursor->d_sib);
+	if (hlist_empty(&cursor->d_parent->d_children))
+		/* That was the last child, must drop implied reference */
+		dput_dlock(cursor->d_parent);
+}
+
 /*
  * pipe.c
  */
fs/libfs.c +7 -7
index 46e0205154e7..9f7f6bf5666a 100644
@@ -128,9 +128,7 @@ static struct dentry *scan_positives(struct dentry *cursor,
 			count = 1;
 		}
 		if (need_resched()) {
-			if (!hlist_unhashed(&cursor->d_sib))
-				__hlist_del(&cursor->d_sib);
-			hlist_add_behind(&cursor->d_sib, &d->d_sib);
+			hlist_move_behind(&cursor->d_sib, &d->d_sib);
 			p = &cursor->d_sib.next;
 			spin_unlock(&dentry->d_lock);
 			cond_resched();
@@ -166,9 +164,10 @@ loff_t dcache_dir_lseek(struct file *file, loff_t offset, int whence)
 			to = scan_positives(cursor, &dentry->d_children.first,
 					    offset - 2, NULL);
 		spin_lock(&dentry->d_lock);
-		hlist_del_init(&cursor->d_sib);
 		if (to)
-			hlist_add_behind(&cursor->d_sib, &to->d_sib);
+			hlist_move_behind(&cursor->d_sib, &to->d_sib);
+		else
+			d_detach_cursor(cursor);
 		spin_unlock(&dentry->d_lock);
 		dput(to);
 
@@ -210,9 +209,10 @@ int dcache_readdir(struct file *file, struct dir_context *ctx)
 		p = &next->d_sib.next;
 	}
 	spin_lock(&dentry->d_lock);
-	hlist_del_init(&cursor->d_sib);
 	if (next)
-		hlist_add_before(&cursor->d_sib, &next->d_sib);
+		hlist_move_before(&cursor->d_sib, &next->d_sib);
+	else
+		d_detach_cursor(cursor);
 	spin_unlock(&dentry->d_lock);
 	dput(next);
 
include/linux/dcache.h +16 -1
index aaa4ba7a1299..83e8569a82e5 100644
@@ -330,7 +330,7 @@ extern char *dentry_path(const struct dentry *, char *, int);
 /* Allocation counts.. */
 
 /**
- * dget_dlock -	get a reference to a dentry
+ * dget_dlock -	get a reference to a dentry while locked
  * @dentry: dentry to get a reference to
  *
  * Given a live dentry, increment the reference count and return the dentry.
@@ -345,6 +345,21 @@ static inline struct dentry *dget_dlock(struct dentry *dentry)
 	return dentry;
 }
 
+/**
+ * dput_dlock - put a reference to a dentry while locked
+ * @dentry: dentry to get a reference to
+ *
+ * Given a live dentry, decrement the reference count and return the dentry.
+ * Caller must hold @dentry->d_lock.  The dentry must still have
+ * a reference after the decrement.  This can be used when two
+ * references are held and one must be dropped.
+ */
+static inline struct dentry *dput_dlock(struct dentry *dentry)
+{
+	if (!WARN_ON(dentry->d_lockref.count <= 1))
+		dentry->d_lockref.count--;
+	return dentry;
+}
 
 /**
  * dget - get a reference to a dentry
include/linux/list.h +30 -0
index e3753695e76c..ab8ad0d18d09 100644
@@ -1123,6 +1123,36 @@ static inline void hlist_add_behind(struct hlist_node *n,
 		WRITE_ONCE(n->next->pprev, &n->next);
 }
 
+/**
+ * hlist_move_behind - move an hlist node to a new location in list
+ * @n: hlist node to be moved
+ * @prev: hlist node after which @n should be added.
+ *
+ * @n may be on the list or unhashed but must not be @prev.
+ * It is removed if necessary and re-added after @prev.
+ */
+static inline void hlist_move_behind(struct hlist_node *n,
+				     struct hlist_node *prev)
+{
+	hlist_del_init(n);
+	hlist_add_behind(n, prev);
+}
+
+/**
+ * hlist_move_before - move an hlist node to a new location in list
+ * @n: hlist node to be moved
+ * @next: hlist node before which @n should be added.
+ *
+ * @n may be on the list or unhashed but must not be @next.
+ * It is removed if necessary and re-added before @next.
+ */
+static inline void hlist_move_before(struct hlist_node *n,
+				     struct hlist_node *next)
+{
+	hlist_del_init(n);
+	hlist_add_before(n, next);
+}
+
 /**
  * hlist_add_fake - create a fake hlist consisting of a single headless node
  * @n: Node to make a fake list out of

base-commit: 4843f6873f7c4835e62f2c73ba0fd538e57a2f22

Signature · 1 line
2.50.0.107.gf914562f5916.dirty
maintainer Reviewed-by on v7 1/5
#2 lore raw

Re: [PATCH v7 1/5] VFS: don't count references through ->d_parent

Quoted 55 lines · NeilBrown

From: NeilBrown <[email protected]>

The number of negative child dentries that a given dentry can have is effectively unbounded, so counting the references through ->d_parent can overflow ->d_lockref.count.

We only use this count so that we can know when there are no remaining references including from children. However most children appear on the ->d_children list and the few remaining children (inactive DCACHE_DENTRY_CURSORs) only exist in a context were a separate reference is held on the parent.

So if we count whether d_children is nonempty (i.e. dget() when it becomes non-empty, dput() when it comes empty) and require children not on ->d_children to have a reference on the parent some other way (which they already do), then ->d_lockref.count will not overflow and we can still know exactly when all references, including through ->d_parent, are gone.

__d_move() allows that dentries might not be on any d_children list as is the case for IS_ROOT() dentries. Rather than track when this is the case we dget() either parent if they have an empty d_children before children are moved around, then dput() if they turn out to be empty afterwards. This will increment dentry if it IS_ROOT(), and then decrement it afterwards, and will decrement the refcount on old_parent if its ->d_children becomes empty.

To help with this, dput_dlock() is added which warns rather than decrementing to zero (which should never happen).

When a DCACHE_CURSOR dentry is added to d_children, it is only ever added "before" or "behind" an existing child, so it will never be the first child added, and so never needs to adjust the refcount on the parent. If it remains on the list until dput() it could be the last child to be removed, in which case normal handling applies in dentry_unlist() (where it has been moved from dentry_kill(). When a cursor is deliberately removed from the d_children list the refcount must be decremented if that leaves the list empty.

hlist_move_behind() and hlist_move_before() are added to simplify moving a cursor within the d_children list. This results in some duplicate code as they share a common prefix with d_detach_cursor() (hlist_del) which is currently factored out. We can expect the compiler to optimise this away and don't need to clutter the C code with it.

autofs compares d_count() with the number of known children of a dentry to detect if there are any concurrent references to a dentry. These comparisons must be changed to reflect that we now only count "one" for any children rather than "one" for each child. This can be done without using ino->count but simply by looking at ->d_children. So a new static-inline "dentry_busy()" is added which performs the check and is told how many unusual references to expect.
As no locks are held, this test is racy. And comment is provided explaining why the race is of no consequence.

Quoted 1 line

Looks good to me although I'm not very confident autofs (but I don't see an obvious issue there). Feel free to add:

Just one nit below.

fs/dcache.c static void __d_move(struct dentry *dentry, struct dentry *target, · line 3316

Quoted 10 lines
fs/dcache.c +6 -0
@@ -3300,12 +3308,21 @@ static void __d_move(struct dentry *dentry, struct dentry *target,
 
 	/* ... and switch them in the tree */
 	dentry->d_parent = target->d_parent;
+
+	/*
+	 * Ensure ref count on parents reflect d_children being non-empty,
+	 * which they almost certainly are.  If either end up being empty,
+	 * this is handled below after the moves.
+	 */

I'd add here: "Note that old_parent->d_children can indeed be empty if e.g. @dentry was IS_ROOT." Because otherwise one has to think too hard why the condition is here :)

fs/dcache.c static void __d_move(struct dentry *dentry, struct dentry *target, · line 3321

Quoted 5 lines
fs/dcache.c +5 -0
+	if (hlist_empty(&old_parent->d_children))
+		dget_dlock(old_parent);
+	if (dentry->d_parent != old_parent &&
+	    hlist_empty(&dentry->d_parent->d_children))
+		dget_dlock(dentry->d_parent);

Honza

Quoted 1 line
(quoted diff) +1 -0
+
Signature · 2 lines
Jan Kara <[email protected]>
SUSE Labs, CR
author
#3 lore raw

PATCH v7 2/5 fsnotify: update children flags only when parent starts watching children

In reply to NeilBrown

From: Amir Goldstein <[email protected]>

We only need to set the PARENT_WATCHED flag on children when the parent inode starts watching children. When the parent stops watching, false positive PARENT_WATCHED flags are cleared lazily in __fsnotify_parent().

The recalc that observes the parent starting to watch children is not necessarily the recalc of the mark that added the watch. It may be the recalc of a concurrent remover in another group, or a recalc in a context that cannot walk the children, such as dnotify event handling.

Record the need to update children flags in a connector flag when the recalc observes the transition and let callers that are allowed to walk the children consume the flag via fsnotify_conn_set_children_dentry_flags() after mask recalc. This way, the caller that added the watch is guaranteed to either update the children flags or find that another caller has committed to doing so.

Also avoid the update children walk with mark spinlock held. This was only done by dnotify and can be easily avoided.

Note there is still a race that this patch does not attempt to address. If some other caller has committed to updating PARENT_WATCHED, it may not complete that task until after this thread returns to user-space, so some notifications might be missed. Before this patch, PARENT_WATCHED might not get set at all in the case of a race. With this patch it will be set, but possibly not before a syscall completes.

Fixes 172e422ffea20 ("fsnotify: clear PARENT_WATCHED flags lazily")
---
 fs/notify/dnotify/dnotify.c        |  6 +++
 fs/notify/fanotify/fanotify_user.c |  4 +-
 fs/notify/inotify/inotify_user.c   |  2 +-
 fs/notify/mark.c                   | 86 +++++++++++++++++++++---------
 include/linux/fsnotify_backend.h   |  6 +++
 5 files changed, 77 insertions(+), 27 deletions(-)
fs/notify/dnotify/dnotify.c +6 -0
index 9fb73bafd41d..0afd2b039333 100644
@@ -181,6 +181,11 @@ void dnotify_flush(struct file *filp, fl_owner_t id)
 	}
 
 	spin_unlock(&fsn_mark->lock);
+	/*
+	 * We only remove mask bits here, but our recalc may be the first to
+	 * observe another group starting to watch children.
+	 */
+	fsnotify_conn_set_children_dentry_flags(fsn_mark->connector);
 
 	/* nothing else could have found us thanks to the dnotify_groups
 	   mark_mutex */
@@ -380,6 +385,7 @@ int fcntl_dirnotify(int fd, struct file *filp, unsigned int arg)
 	dnotify_recalc_inode_mask(fsn_mark);
 out:
 	spin_unlock(&fsn_mark->lock);
+	fsnotify_conn_set_children_dentry_flags(fsn_mark->connector);
 
 	if (destroy)
 		fsnotify_detach_mark(fsn_mark);
fs/notify/fanotify/fanotify_user.c +2 -2
index 63c9759fc3b0..c064b0070c51 100644
@@ -1264,7 +1264,7 @@ static int fanotify_remove_mark(struct fsnotify_group *group,
 	removed = fanotify_mark_remove_from_mask(fsn_mark, mask, flags,
 						 umask, &destroy_mark);
 	if (removed & fsnotify_conn_mask(fsn_mark->connector))
-		fsnotify_recalc_mask(fsn_mark->connector);
+		fsnotify_recalc_mask_and_update_children(fsn_mark->connector);
 	if (destroy_mark)
 		fsnotify_detach_mark(fsn_mark);
 	fsnotify_group_unlock(group);
@@ -1538,7 +1538,7 @@ static int fanotify_add_mark(struct fsnotify_group *group,
 
 	recalc = fanotify_mark_add_to_mask(fsn_mark, mask, fan_flags);
 	if (recalc)
-		fsnotify_recalc_mask(fsn_mark->connector);
+		fsnotify_recalc_mask_and_update_children(fsn_mark->connector);
 
 out:
 	fsnotify_group_unlock(group);
fs/notify/inotify/inotify_user.c +1 -1
index 5f19c24ec187..6018c2d717ac 100644
@@ -562,7 +562,7 @@ static int inotify_update_existing_watch(struct fsnotify_group *group,
 	fsn_mark->flags |= inotify_arg_to_flags(arg);
 	spin_unlock(&fsn_mark->lock);
 
-	fsnotify_recalc_mask(fsn_mark->connector);
+	fsnotify_recalc_mask_and_update_children(fsn_mark->connector);
 
 	/* return the wd */
 	ret = i_mark->wd;
fs/notify/mark.c +62 -24

151 lines not on this page · raw message

include/linux/fsnotify_backend.h +6 -0
index faf21564380d..052d8674ad89 100644
@@ -567,6 +567,7 @@ struct fsnotify_mark_connector {
 #define FSNOTIFY_CONN_FLAG_IS_WATCHED	0x01
 #define FSNOTIFY_CONN_FLAG_HAS_IREF	0x02
 #define FSNOTIFY_CONN_FLAG_DESTROYING	0x04
+#define FSNOTIFY_CONN_FLAG_UPDATE_CHILDREN	0x08
 	unsigned short flags;	/* flags [lock] */
 	union {
 		/* Object pointer [lock] */
@@ -888,6 +889,11 @@ static inline __u32 fsnotify_calc_mask(struct fsnotify_mark *mark)
 extern __u32 fsnotify_conn_mask(struct fsnotify_mark_connector *conn);
 /* Calculate mask of events for a list of marks */
 extern void fsnotify_recalc_mask(struct fsnotify_mark_connector *conn);
+/* Recalculate mask and update children dentry flags if needed */
+extern void fsnotify_recalc_mask_and_update_children(
+					struct fsnotify_mark_connector *conn);
+extern void fsnotify_conn_set_children_dentry_flags(
+					struct fsnotify_mark_connector *conn);
 extern void fsnotify_init_mark(struct fsnotify_mark *mark,
 			       struct fsnotify_group *group);
 /* Find mark belonging to given group in the list of marks */
Signature · 1 line
2.50.0.107.gf914562f5916.dirty
author
#4 lore raw

PATCH v7 3/5 fsnotify: don't hold i_lock while walking d_children in fsnotify_set_children_dentry_flags()

In reply to NeilBrown

From: NeilBrown <[email protected]>

Rather than hold i_lock across a d_children walk, dget() a reference to the dentry and drop the i_lock before the walk. This is easily done with d_find_alias().

This requires that we dput() which can sleep. Now that no locks are held across calls to fsnotify_set_children_dentry_flags(), this is safe.

---
 fs/notify/fsnotify.c | 40 ++++++++++++++++++++--------------------
 1 file changed, 20 insertions(+), 20 deletions(-)
fs/notify/fsnotify.c +20 -20
index 8657bb94dfa8..58566e6b9679 100644
@@ -71,32 +71,32 @@ void fsnotify_sb_free(struct super_block *sb)
  */
 void fsnotify_set_children_dentry_flags(struct inode *inode)
 {
-	struct dentry *alias;
+	struct dentry *alias, *child;
 
 	if (!S_ISDIR(inode->i_mode))
 		return;
 
-	spin_lock(&inode->i_lock);
-	/* run all of the dentries associated with this inode.  Since this is a
-	 * directory, there damn well better only be one item on this list */
-	for_each_alias(alias, inode) {
-		struct dentry *child;
-
-		/* run all of the children of the original inode and fix their
-		 * d_flags to indicate parental interest (their parent is the
-		 * original inode) */
-		spin_lock(&alias->d_lock);
-		hlist_for_each_entry(child, &alias->d_children, d_sib) {
-			if (!child->d_inode)
-				continue;
+	/* Find the dentry for inode - there can only be one */
+	alias = d_find_alias(inode);
+	if (!alias)
+		return;
 
-			spin_lock_nested(&child->d_lock, DENTRY_D_LOCK_NESTED);
-			child->d_flags |= DCACHE_FSNOTIFY_PARENT_WATCHED;
-			spin_unlock(&child->d_lock);
-		}
-		spin_unlock(&alias->d_lock);
+	/*
+	 * run through all of the children of the original inode and fix
+	 * their d_flags to indicate parental interest (their parent is
+	 * the original inode)
+	 */
+	spin_lock(&alias->d_lock);
+	hlist_for_each_entry(child, &alias->d_children, d_sib) {
+		if (!child->d_inode)
+			continue;
+
+		spin_lock_nested(&child->d_lock, DENTRY_D_LOCK_NESTED);
+		child->d_flags |= DCACHE_FSNOTIFY_PARENT_WATCHED;
+		spin_unlock(&child->d_lock);
 	}
-	spin_unlock(&inode->i_lock);
+	spin_unlock(&alias->d_lock);
+	dput(alias);
 }
 
 /*
Signature · 1 line
2.50.0.107.gf914562f5916.dirty
author
#5 lore raw

PATCH v7 4/5 Add d_for_each_positive_child family of iterators

In reply to NeilBrown

From: NeilBrown <[email protected]>

Provide iterators for the d_children/d_sib lists. These iterators only report dentries that are positive (though they could be negative by the time they are used). As DCACHE_DENTRY_CURSOR dentries are never positive they are never reported.

d_for_each_positive_child() takes the parent lock and sets the iterator to each positive child in turn.

d_for_each_positive_child_continue() can continue after an existing dentry, or (when initialised to NULL) behave like d_for_each_positive_child(). This requires that something prevent the start dentry from being moved before d_for_each_positive_child_continue() can take the parent lock - typically ->i_rwsem.

The use of scoped_guard() in these macros makes it safe to "break" or "goto" out of the loop - the lock will be dropped in that case.

As there are reports that large numbers of negative dentries can lead to soft lockups when walking the d_children/d_sib list, particularly in fsnotify_set_children_dentry_flags(), we call cond_resched() as needed during the walk.

To achieve this we use an on-stack dentry (about 330 bytes) to place a cursor while calling cond_resched(). On-stack dentries are not standard practice but should be safe since

Commit 3df5153c5f12 ("make cursors NORCU")

made cursors NORCU, confirming that they can safely be released without waiting. Also importantly nothing ever takes a reference on a cursor that it doesn't own.

To facilitate this, a new __d_init() is split out of __d_alloc() and used in d_init_cursor() which can be called on an on-stack dentry as is done in the new d_next_sibling_sched().

Link https://lwn.net/Articles/1079407/

---
 fs/dcache.c            | 116 ++++++++++++++++++++++++++++++++++-------
 include/linux/dcache.h |  68 ++++++++++++++++++++++++
 2 files changed, 164 insertions(+), 20 deletions(-)
fs/dcache.c +96 -20
index 8ddfddc31546..a8b453f2ae4e 100644
@@ -1950,6 +1950,27 @@ void d_invalidate(struct dentry *dentry)
 }
 EXPORT_SYMBOL(d_invalidate);
 
+static void __d_init(struct dentry *dentry, struct super_block *sb)
+{
+	dentry->d_flags = 0;
+	lockref_init(&dentry->d_lockref);
+	seqcount_spinlock_init(&dentry->d_seq, &dentry->d_lock);
+	dentry->d_inode = NULL;
+	dentry->d_parent = dentry;
+	dentry->d_sb = sb;
+	dentry->d_op = sb->__s_d_op;
+	dentry->d_flags = sb->s_d_flags;
+	dentry->d_fsdata = NULL;
+	INIT_HLIST_BL_NODE(&dentry->d_hash);
+	INIT_LIST_HEAD(&dentry->d_lru);
+	INIT_HLIST_HEAD(&dentry->d_children);
+	dentry->waiters = NULL;
+	INIT_HLIST_NODE(&dentry->d_sib);
+
+	lockdep_init_map(&dentry->dep_map, "DCACHE_PAR_LOOKUP",
+			 &sb->s_type->d_lookup_key, 0);
+}
+
 /**
  * __d_alloc - allocate a dcache entry
  * @sb: filesystem it will belong to
@@ -1959,7 +1980,6 @@ EXPORT_SYMBOL(d_invalidate);
  * available. On a success the dentry is returned. The name passed in is
  * copied and the copy passed in may be reused after this call.
  */
- 
 static struct dentry *__d_alloc(struct super_block *sb, const struct qstr *name)
 {
 	struct dentry *dentry;
@@ -1991,14 +2011,14 @@ static struct dentry *__d_alloc(struct super_block *sb, const struct qstr *name)
 		p = kmalloc_flex(*p, name, name->len + 1,
 				 GFP_KERNEL_ACCOUNT | __GFP_RECLAIMABLE);
 		if (!p) {
-			kmem_cache_free(dentry_cache, dentry); 
+			kmem_cache_free(dentry_cache, dentry);
 			return NULL;
 		}
 		atomic_set(&p->count, 1);
 		dname = p->name;
 	} else  {
 		dname = dentry->d_shortname.string;
-	}	
+	}
 
 	dentry->__d_name.len = name->len;
 	dentry->__d_name.hash = name->hash;
@@ -2008,23 +2028,7 @@ static struct dentry *__d_alloc(struct super_block *sb, const struct qstr *name)
 	/* Make sure we always see the terminating NUL character */
 	smp_store_release(&dentry->__d_name.name, dname); /* ^^^ */
 
-	dentry->d_flags = 0;
-	lockref_init(&dentry->d_lockref);
-	seqcount_spinlock_init(&dentry->d_seq, &dentry->d_lock);
-	dentry->d_inode = NULL;
-	dentry->d_parent = dentry;
-	dentry->d_sb = sb;
-	dentry->d_op = sb->__s_d_op;
-	dentry->d_flags = sb->s_d_flags;
-	dentry->d_fsdata = NULL;
-	INIT_HLIST_BL_NODE(&dentry->d_hash);
-	INIT_LIST_HEAD(&dentry->d_lru);
-	INIT_HLIST_HEAD(&dentry->d_children);
-	dentry->waiters = NULL;
-	INIT_HLIST_NODE(&dentry->d_sib);
-
-	lockdep_init_map(&dentry->dep_map, "DCACHE_PAR_LOOKUP",
-			 &sb->s_type->d_lookup_key, 0);
+	__d_init(dentry, sb);
 
 	if (dentry->d_op && dentry->d_op->d_init) {
 		err = dentry->d_op->d_init(dentry);
@@ -2041,6 +2045,78 @@ static struct dentry *__d_alloc(struct super_block *sb, const struct qstr *name)
 	return dentry;
 }
 
+/**
+ * d_init_cursor - initialise an on-stack dentry cursor
+ * @dentry: the dentry to be initialised
+ * @parent: dentry of parent where cursor will be used.
+ *
+ * A DCACHE_DENTRY_CURSOR is initalised for use in marking
+ * a place in the d_children/d_sib list.  While sb-related
+ * fields are filled in, they should never be used.
+ * The filesystems d_init is not called and a final d_put()
+ * should not be called, else d_release would be called.
+ */
+static void d_init_cursor(struct dentry *dentry, struct dentry *parent)
+{
+	const struct qstr *name = &slash_name;
+	char *dname;
+
+	/*
+	 * We guarantee that the inline name is always NUL-terminated.
+	 * This way the memcpy() done by the name switching in rename
+	 * will still always have a NUL at the end, even if we might
+	 * be overwriting an internal NUL character
+	 */
+	dentry->d_shortname.string[DNAME_INLINE_LEN-1] = 0;
+	name = &slash_name;
+	dname = dentry->d_shortname.string;
+
+	dentry->__d_name.len = name->len;
+	dentry->__d_name.hash = name->hash;
+	memcpy(dname, name->name, name->len);
+	dname[name->len] = 0;
+
+	/* Make sure we always see the terminating NUL character */
+	smp_store_release(&dentry->__d_name.name, dname); /* ^^^ */
+
+	__d_init(dentry, parent->d_sb);
+	dentry->d_parent = parent;
+	dentry->d_flags |= DCACHE_DENTRY_CURSOR | DCACHE_NORCU;
+}
+
+/**
+ * d_next_sibling_sched - return next sibling, but schedule() first
+ * @child:  current child
+ *
+ * This behaves like d_next_sibling(), but drops the parent d_lock
+ * and calls cond_resched() to avoid any soft-lockup.  A cursor
+ * is inserted as place holder.
+ *
+ * Caller must hold the parents d_lock, and must hold a counted
+ * reference on the parent.
+ *
+ * @child should not be a cursor, else two threads could potentially
+ * live-lock, each only stepping over each others cursors.
+ *
+ * Returns: the next sibling, or %NULL if there is none.
+ */
+struct dentry *d_next_sibling_sched(struct dentry *child)
+__must_hold(&child->d_parent->d_lock)
+{
+	struct dentry cursor;
+
+	d_init_cursor(&cursor, child->d_parent);
+	hlist_add_behind(&cursor.d_sib, &child->d_sib);
+	spin_unlock(&cursor.d_parent->d_lock);
+	cond_resched();
+	spin_lock(&cursor.d_parent->d_lock);
+	child = d_next_sibling(&cursor);
+	d_detach_cursor(&cursor);
+	WARN_ON(d_count(&cursor) != 1);
+	return child;
+}
+EXPORT_SYMBOL(d_next_sibling_sched);
+
 /**
  * d_alloc - allocate a dcache entry
  * @parent: parent of entry to allocate
include/linux/dcache.h +68 -0

74 lines not on this page · raw message

Signature · 1 line
2.50.0.107.gf914562f5916.dirty
author
#6 lore raw

PATCH v7 5/5 Use d_for_each_positive_child() in fsnotify.

In reply to NeilBrown

From: NeilBrown <[email protected]>

fsnotify has been reported as source of soft-lockups when iterating a long ->d_children list. Change it to use d_for_each_positive_child() which will call cond_resched() as needed to avoid soft-lockups.

Link https://lwn.net/Articles/1079407/

---
 fs/notify/fsnotify.c | 6 +-----
 1 file changed, 1 insertion(+), 5 deletions(-)
fs/notify/fsnotify.c +1 -5
index 58566e6b9679..33c5d10f78ba 100644
@@ -86,16 +86,12 @@ void fsnotify_set_children_dentry_flags(struct inode *inode)
 	 * their d_flags to indicate parental interest (their parent is
 	 * the original inode)
 	 */
-	spin_lock(&alias->d_lock);
-	hlist_for_each_entry(child, &alias->d_children, d_sib) {
-		if (!child->d_inode)
-			continue;
 
+	d_for_each_positive_child(child, alias) {
 		spin_lock_nested(&child->d_lock, DENTRY_D_LOCK_NESTED);
 		child->d_flags |= DCACHE_FSNOTIFY_PARENT_WATCHED;
 		spin_unlock(&child->d_lock);
 	}
-	spin_unlock(&alias->d_lock);
 	dput(alias);
 }
 
Signature · 1 line
2.50.0.107.gf914562f5916.dirty