Skip to contentSkip to conversation

fs: Deferred inode reclaim

PATCH New Jan Kara 2 participants 14 messages Dec 1 – Dec 2

Subsystems (5)
lore
Share & tools
lore

Jan Kara

author maintainer
#0 lore raw

v5 cover fs: Deferred inode reclaim

Hello,

here is the fifth revision of my patches implementing deferred inode reclaim to deal with MM warnings due to GFP_NOFAIL allocations from reclaim paths. This happens because to reclaim some inodes, filesystems have to do IO including complex operations using journalling and forward progress of these depends on successful memory allocations (which is impossible to guarantee from reclaim context).

There is one notable change since v4 - I've dropped the patch implementing protection of deferred inode reclaim from filesystem freezing. The reasons for that are:

1) Inode reclaim can hang on frozen fs now the same way as with deferred inode reclaim. So far nobody complained about kswapd being blocked like that and blocking deferred inode reclaim worker is going to have even lower impact on the system. So this apparently isn't a practical problem today.

2) Such blocking of inode eviction on frozen fs is rare (the only scenario I'm aware of is overlayfs dropping last reference of unlinked inode on lower fs from its ->evict method).

3) Protecting inode deferred inode reclaim from freezing (and blocking on frozen fs) would introduce much more visible stalls in reclaim on frozen fs with possible (userspace) deadlocks when somebody wants to read inode under reclaim back into memory.

The patches have survived full fstests run on ext4 when marking all loaded ext4 inodes for deferred reclaim to stress the deferred reclaim paths. I have also tested (when marking all inodes for deferred reclaim) the patches by creating a memcg with 128m memory limit and then scanning from 10 processes 1m inodes in total which heavily exercises deferred inode reclaim paths. This also verified efficiency of throttling of marking of inodes for deferred reclaim. Basically we cannot guarantee any particular limit on the number of inodes queued for deferred reclaim as that is bound only by their number in memory and memory pressure. But as the number of queued inodes grows, the tasks creating them get slowed down so eventually some equilibrium is hit. In my VM this was at ~10k inodes (only slightly above the 8k limit when throttling kicks in) but this all very much depends on the reclaim pressure, speed of deferred reclaim etc. so I don't think this is some representative number.

The first patch is a pure fix for a problem I've hit when running fstests, the second patch fixes queueing of inodes with only timestamps dirty into writeback lists. The third patch deals with lazy timestamp updates which I've decided to handle better directly inside the writeback infrastructure instead of deferring reclaim. The remaining patches implement the inode reclaim deferal. Ext4 use of deferred inode reclaim is there mostly as a demonstration. Other filesystems need to determine which inodes need deferred reclaim and mark them as such which generally requires good internal knowledge of the filesystem. I'm hoping that once the infrastructure is there, fs developers prompted by MM warnings will start using it :). I know for a fact that besides ext4 e.g. gfs2 wants to use this infrastructure.

Honza

Changes since v4:
* Fix whitespace damage
* Avoid pointless schedule on 0 delays in throttle_inode_deferred_reclaim()
* Added fix for redirty_tail_locked() and process_inode_switch_wbs() to move inode to b_dirty_time list of only timestamps are dirty
* Waking of workes now takes into account total number of queued inodes, not just the immedialy queued batch so that more workers are woken up for a storm of single-inode additions.
* Removed freeze protection of reclaim workers

Changes since v3:
* Improve logic to expedite writeback of I_DIRTY_TIME inodes to handle also the case when inode is dirty or under writeback
* Defer reclaim of I_METADATA_WRITEBACK inodes
* Handle kernel workers when throttling deferred inode reclaim
* Fix memory leak in throttling code
* Fix synchronization between superblock teardown and deferred inode reclaim
* Fix synchronization between superblock freezing and deferred inode reclaim

Changes since v2:
* Some cleanups and simplifications from Andreas Grunbacher
* Fixed couple of bugs pointed out by Sashiko
* Added support for auto-deferring eviction from iput() when inode has 0 link count and we are in reclaim path
* Added protection of deferred reclaim from filesystem freezing
* Throttling now doesn't happen directly in mark_inode_reclaim_deferred() but on exit to userspace

Changes since v1:
* Multiple workers to reclaim deferred inodes, related to that I've moved lists of deferred inodes from per-sb to global ones
* Added missed lazytime sync fix

Previous versions:

author maintainer
#1 lore raw

PATCH v5 1/8 writeback: Fix missed lazytime flush

move_expired_inodes() moves to b_io list inodes which were dirtied at current_time - dirtytime_expire_interval or before. __writeback_single_inode() however calls sync_lazytime() only if the inode was dirtied strictly before current_time - dirtytime_expire_interval. It can thus happen that inode with dirty timestamps gets queued to b_io list, then fails the check in __writeback_single_inode() and as a result is just placed back to b_dirty_time list with a refreshed timestamp and so timestamps aren't written when they should have been.

This is a very difficult race to hit in practice but changes to how dirty time expiry is handled on last iput() will make this much easier to hit.

Fixes 5fcd57505c00 ("writeback: Drop I_DIRTY_TIME_EXPIRE")
---
 fs/fs-writeback.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/fs-writeback.c +2 -2
index de77b6bc1dc4..65b1af2879e8 100644
@@ -1910,8 +1910,8 @@ __writeback_single_inode(struct inode *inode, struct writeback_control *wbc)
 	 */
 	if ((inode_state_read_once(inode) & I_DIRTY_TIME) &&
 	    (wbc->sync_mode == WB_SYNC_ALL ||
-	     time_after(jiffies, inode->dirtied_time_when +
-			dirtytime_expire_interval * HZ)))
+	     time_after_eq(jiffies, inode->dirtied_time_when +
+			   dirtytime_expire_interval * HZ)))
 		sync_lazytime(inode);
 
 	/*
Signature · 1 line
2.53.0
author maintainer
#2 lore raw

PATCH v5 2/8 fs: Fix inode writeback list placement for switched and redirtied inodes

In reply to Jan Kara

inode_switch_wbs() places dirty inodes to b_dirty list even if they have only dirty timestamps. This is somewhat inconsistent and furthermore when writeback runs, it queues such inodes, __writeback_single_inode() does nothing for them (timestamps have not expired yet so they are not synced to the inode) and so their dirtied_when is only clobbered again and now they end up in b_dirty_time list. Similarly redirty_tail_locked() may place inodes with only timestamps dirty to b_dirty list. Fix the code to place such inodes to b_dirty_time list in both cases.

---
 fs/fs-writeback.c | 50 +++++++++++++++++++++++++++++++++++------------
 1 file changed, 37 insertions(+), 13 deletions(-)
fs/fs-writeback.c +37 -13
index 65b1af2879e8..ec65ec6e48e7 100644
@@ -416,6 +416,8 @@ static void bdi_up_write_wb_switch_rwsem(struct backing_dev_info *bdi)
 	up_write(&bdi->wb_switch_rwsem);
 }
 
+static void redirty_tail_locked(struct inode *inode, struct bdi_writeback *wb);
+
 static bool inode_do_switch_wbs(struct inode *inode,
 				struct bdi_writeback *old_wb,
 				struct bdi_writeback *new_wb)
@@ -481,15 +483,12 @@ static bool inode_do_switch_wbs(struct inode *inode,
 
 		if (inode_state_read(inode) & I_DIRTY_ALL) {
 			/*
-			 * We need to keep b_dirty list sorted by
+			 * We need to keep b_dirty[_time] list sorted by
 			 * dirtied_when. However properly sorting the
 			 * inode in the list gets too expensive when switching
-			 * many inodes. So just attach inode at the end of the
-			 * dirty list and clobber the dirtied_when.
+			 * many inodes. So just use redirty_tail_locked().
 			 */
-			inode->dirtied_when = jiffies;
-			inode_io_list_move_locked(inode, new_wb,
-						  &new_wb->b_dirty);
+			redirty_tail_locked(inode, new_wb);
 		} else {
 			inode_cgwb_move_to_attached(inode, new_wb);
 		}
@@ -1542,9 +1541,28 @@ void sb_clear_inode_writeback(struct inode *inode)
 	}
 }
 
+static void move_to_dirtytime_locked(struct inode *inode,
+				     struct bdi_writeback *wb)
+{
+	/* If the inode is used, move it to the tail of b_dirty_time list */
+	if (icount_read(inode)) {
+		inode->dirtied_when = jiffies;
+		inode_io_list_move_locked(inode, wb, &wb->b_dirty_time);
+		return;
+	}
+
+	/*
+	 * Inode is not used. Expedite writeback by moving it to the head
+	 * of b_dirty_time list so that it can enter LRU and be evicted.
+	 */
+	inode_add_dirtytime_head(inode, wb);
+	wb_io_lists_depopulated(wb);
+}
+
 /*
  * Redirty an inode: set its when-it-was dirtied timestamp and move it to the
- * furthest end of its superblock's dirty-inode list.
+ * furthest end of its wb's dirty list or dirty_time list if only timestamps
+ * are dirty.
  *
  * Before stamping the inode's ->dirtied_when, we check to see whether it is
  * already the most-recently-dirtied inode on the b_dirty list.  If that is
@@ -1566,14 +1584,20 @@ static void redirty_tail_locked(struct inode *inode, struct bdi_writeback *wb)
 		wb_io_lists_depopulated(wb);
 		return;
 	}
-	if (!list_empty(&wb->b_dirty)) {
-		struct inode *tail;
 
-		tail = wb_inode(wb->b_dirty.next);
-		if (time_before(inode->dirtied_when, tail->dirtied_when))
-			inode->dirtied_when = jiffies;
+	if (inode_state_read(inode) & I_DIRTY) {
+		if (!list_empty(&wb->b_dirty)) {
+			struct inode *tail;
+
+			tail = wb_inode(wb->b_dirty.next);
+			if (time_before(inode->dirtied_when,
+					tail->dirtied_when))
+				inode->dirtied_when = jiffies;
+		}
+		inode_io_list_move_locked(inode, wb, &wb->b_dirty);
+	} else {
+		move_to_dirtytime_locked(inode, wb);
 	}
-	inode_io_list_move_locked(inode, wb, &wb->b_dirty);
 }
 
 static void redirty_tail(struct inode *inode, struct bdi_writeback *wb)
Signature · 1 line
2.53.0
#3 lore raw

Re: [PATCH v5 2/8] fs: Fix inode writeback list placement for switched and redirtied inodes

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] fs: undeclared inode_add_dirtytime_head() call in move_to_dirtytime_locked() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] fs: undeclared inode_add_dirtytime_head() call in move_to_dirtytime_locked()
--

commit 3ef967660439f9f374de899cfcacafdd5ea2e364
Author: Jan Kara <[email protected]>

fs: Fix inode writeback list placement for switched and redirtied inodes

This commit updates redirty_tail_locked() and inode_do_switch_wbs() so that inodes with only dirty timestamps are placed on b_dirty_time instead of b_dirty.

Quoted 4 lines
fs/fs-writeback.c +0 -0
index 65b1af2879e87..ec65ec6e48e7d 100644

[ ... ]

Quoted 11 lines
fs/fs-writeback.c +7 -0
@@ -1542,9 +1541,28 @@ void sb_clear_inode_writeback(struct inode *inode)
 	}
 }
 
+static void move_to_dirtytime_locked(struct inode *inode,
+				     struct bdi_writeback *wb)
+{
+	/* If the inode is used, move it to the tail of b_dirty_time list */
+	if (icount_read(inode)) {
+		inode->dirtied_when = jiffies;
+		inode_io_list_move_locked(inode, wb, &wb->b_dirty_time);

fs/fs-writeback.c void sb_clear_inode_writeback(struct inode *inode) · line 1560

Quoted 10 lines
fs/fs-writeback.c +10 -0
+		return;
+	}
+
+	/*
+	 * Inode is not used. Expedite writeback by moving it to the head
+	 * of b_dirty_time list so that it can enter LRU and be evicted.
+	 */
+	inode_add_dirtytime_head(inode, wb);
+	wb_io_lists_depopulated(wb);
+}

[Severity: High]
Does this break the build at this point in the series by calling inode_add_dirtytime_head() before it is defined? inode_add_dirtytime_head() is only introduced in the next patch in the series, commit "fs: Avoid inode dirtying on last iput", so compiling at this commit fails with an implicit function declaration error and breaks bisection.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
author maintainer
#4 lore raw

PATCH v5 3/8 fs: Avoid inode dirtying on last iput

In reply to Jan Kara

When inode has dirtied timestamps, we currently call sync_lazytime() on last iput. This is done because inode with any dirty bit set is not inserted into LRU and dirty timestamps expire only after many (12 by default) hours so these inodes would be sitting outside of LRU aging for a really long time. However this can result in doing IO and consequently GFP_NOFAIL allocations from dentry reclaim making MM complain. Sample trace for ext4 is:

prune_dcache_sb
shrink_dentry_list
__dentry_kill
iput
sync_lazytime
__mark_inode_dirty
ext4_dirty_inode
__ext4_mark_inode_dirty
ext4_reserve_inode_write
ext4_get_inode_loc
bdev_getblk
__filemap_get_folio_mpol

Avoid this dirtying on last iput by reshuffling unused inodes to the beginning of b_dirty_time list and clobbering dirtied_time_when instead so that they get written during next periodic writeback.

---
 fs/fs-writeback.c | 68 ++++++++++++++++++++++++++++++++++++++++++++---
 fs/inode.c        | 15 +++++------
 fs/internal.h     |  1 +
 3 files changed, 72 insertions(+), 12 deletions(-)
fs/fs-writeback.c +64 -4
index ec65ec6e48e7..44f68a8c146f 100644
@@ -1541,6 +1541,24 @@ void sb_clear_inode_writeback(struct inode *inode)
 	}
 }
 
+static void inode_add_dirtytime_head(struct inode *inode,
+				      struct bdi_writeback *wb)
+{
+	unsigned long new_time;
+
+	new_time = jiffies - dirtytime_expire_interval * HZ;
+	if (!list_empty(&wb->b_dirty_time)) {
+		struct inode *first = wb_inode(wb->b_dirty_time.prev);
+		unsigned long first_time = READ_ONCE(first->dirtied_time_when);
+
+		if (time_before(first_time, new_time))
+			new_time = first_time;
+	}
+	inode->dirtied_when = new_time;
+	inode->dirtied_time_when = new_time;
+	list_move_tail(&inode->i_io_list, &wb->b_dirty_time);
+}
+
 static void move_to_dirtytime_locked(struct inode *inode,
 				     struct bdi_writeback *wb)
 {
@@ -1854,8 +1872,7 @@ static void requeue_inode(struct inode *inode, struct bdi_writeback *wb,
 		 */
 		redirty_tail_locked(inode, wb);
 	} else if (inode_state_read(inode) & I_DIRTY_TIME) {
-		inode->dirtied_when = jiffies;
-		inode_io_list_move_locked(inode, wb, &wb->b_dirty_time);
+		move_to_dirtytime_locked(inode, wb);
 		inode_state_clear(inode, I_SYNC_QUEUED);
 	} else {
 		/* The inode is clean. Remove from writeback lists. */
@@ -2096,8 +2113,7 @@ static int writeback_single_inode(struct inode *inode,
 			inode_cgwb_move_to_attached(inode, wb);
 		else if (!(istate & I_SYNC_QUEUED) && !(istate & I_DIRTY)) {
 			WARN_ON_ONCE(!(istate & I_DIRTY_TIME));
-			inode->dirtied_when = jiffies;
-			inode_io_list_move_locked(inode, wb, &wb->b_dirty_time);
+			move_to_dirtytime_locked(inode, wb);
 		}
 	}
 
@@ -2986,6 +3002,50 @@ void __mark_inode_dirty(struct inode *inode, int flags)
 }
 EXPORT_SYMBOL(__mark_inode_dirty);
 
+/*
+ * If inode has dirty timestamps to write out, make sure flush worker writes
+ * them out during its next periodic writeback writeout.
+ */
+void queue_dirtytime_writeback(struct inode *inode)
+{
+	struct bdi_writeback *wb;
+	unsigned int i_state;
+
+	lockdep_assert_held(&inode->i_lock);
+
+	wb = locked_inode_to_wb_and_lock_list(inode);
+	spin_lock(&inode->i_lock);
+	i_state = inode_state_read(inode);
+	/* Written back while we dropped i_lock? */
+	if (!(i_state & I_DIRTY_TIME))
+		goto out_wb_lock;
+
+	/*
+	 * If the inode is dirty, next writeback will come soon so we don't
+	 * need to do anything. If it is under writeback, we cannot touch dirty
+	 * lists now so we handle moving the inode after writeback is complete.
+	 */
+	if (i_state & (I_SYNC_QUEUED | I_SYNC | I_DIRTY)) {
+		/*
+		 * Clobber dirtied_time_when so that timestamps get synced on
+		 * next inode writeback.
+		 */
+		inode->dirtied_time_when = jiffies -
+						dirtytime_expire_interval * HZ;
+		goto out_wb_lock;
+	}
+
+	/*
+	 * Move inode to the beginning of dirty queue so that it gets written
+	 * out during the next periodic writeback.
+	 */
+	inode_add_dirtytime_head(inode, wb);
+	/* Wake up flush worker to ensure timely flush of the inode */
+	wb_wakeup_delayed(wb);
+out_wb_lock:
+	spin_unlock(&wb->list_lock);
+}
+
 /*
  * The @s_sync_lock is used to serialise concurrent sync operations
  * to avoid lock contention problems with concurrent wait_sb_inodes() calls.
fs/inode.c +7 -8
index bf9403c32188..a9f757fba23b 100644
@@ -2051,7 +2051,6 @@ void iput(struct inode *inode)
 	if (unlikely(!inode))
 		return;
 
-retry:
 	lockdep_assert_not_held(&inode->i_lock);
 	VFS_BUG_ON_INODE(inode_state_read_once(inode) & (I_FREEING | I_CLEAR), inode);
 	/*
@@ -2064,14 +2063,14 @@ void iput(struct inode *inode)
 	if (atomic_add_unless(&inode->i_count, -1, 1))
 		return;
 
-	if (inode->i_nlink && sync_lazytime(inode))
-		goto retry;
-
 	spin_lock(&inode->i_lock);
-	if (unlikely((inode_state_read(inode) & I_DIRTY_TIME) && inode->i_nlink)) {
-		spin_unlock(&inode->i_lock);
-		goto retry;
-	}
+	/*
+	 * If inode has timestamp updates pending, queue flushing them now as
+	 * otherwise the dirtiness could be preventing the inode from entering
+	 * LRU for hours.
+	 */
+	if (inode->i_nlink && inode_state_read(inode) & I_DIRTY_TIME)
+		queue_dirtytime_writeback(inode);
 
 	if (!atomic_dec_and_test(&inode->i_count)) {
 		spin_unlock(&inode->i_lock);
fs/internal.h +1 -0
index 9580afef293e..855a80f4b879 100644
@@ -222,6 +222,7 @@ bool in_group_or_capable(const struct mnt_idmap *idmap,
  */
 long get_nr_dirty_inodes(void);
 bool sync_lazytime(struct inode *inode);
+void queue_dirtytime_writeback(struct inode *inode);
 
 /*
  * dcache.c
Signature · 1 line
2.53.0
#5 lore raw

Re: [PATCH v5 3/8] fs: Avoid inode dirtying on last iput

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider: - [Medium] writeback: missed delayed wakeup for unused inodes on b_dirty_time - [Medium] fs…

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider:
- [Medium] writeback: missed delayed wakeup for unused inodes on b_dirty_time
- [Medium] fs: queue_dirtytime_writeback() queues unhashed and evicted inodes
- [Medium] writeback: redirty_tail_locked() puts unused inodes at b_dirty_time head
- [Medium] writeback: clobbered dirtied_time_when persists across __mark_inode_dirty()
- [Medium] fs: lost lazytime timestamps in iput_final() when drop_inode() returns 1
--

commit 84464a49204ee2cc47ba9c4cc55f3f3c862e495d
Author: Jan Kara <[email protected]>

fs: Avoid inode dirtying on last iput

This commit replaces the synchronous sync_lazytime() call in iput() with queue_dirtytime_writeback(), moving unused inodes with dirty timestamps to the head of wb->b_dirty_time with an expired dirtied_time_when timestamp so that periodic writeback flushes them.

Quoted 19 lines
fs/fs-writeback.c +11 -0
index ec65ec6e48e7d..44f68a8c146f2 100644
@@ -1541,6 +1541,24 @@ void sb_clear_inode_writeback(struct inode *inode)
 	}
 }
 
+static void inode_add_dirtytime_head(struct inode *inode,
+				      struct bdi_writeback *wb)
+{
+	unsigned long new_time;
+
+	new_time = jiffies - dirtytime_expire_interval * HZ;
+	if (!list_empty(&wb->b_dirty_time)) {
+		struct inode *first = wb_inode(wb->b_dirty_time.prev);
+		unsigned long first_time = READ_ONCE(first->dirtied_time_when);
+
+		if (time_before(first_time, new_time))

fs/fs-writeback.c void sb_clear_inode_writeback(struct inode *inode) · line 1564

Quoted 10 lines
fs/fs-writeback.c +7 -0
+			new_time = first_time;
+	}
+	inode->dirtied_when = new_time;
+	inode->dirtied_time_when = new_time;
+	list_move_tail(&inode->i_io_list, &wb->b_dirty_time);
+}
+
 static void move_to_dirtytime_locked(struct inode *inode,
 				     struct bdi_writeback *wb)
 {

[Severity: Medium]
When writeback skips an unused I_DIRTY_TIME inode and calls redirty_tail() or redirty_tail_locked() (for example when super_trylock_shared() fails in __writeback_inodes_wb() or when writeback_sb_inodes() filters for a different superblock), does calling move_to_dirtytime_locked() -> inode_add_dirtytime_head() put the skipped inode back at the oldest end of wb->b_dirty_time (wb->b_dirty_time.prev) with an expired dirtied_when?

On the next iteration of wb_writeback(), queue_io() -> move_expired_inodes() will immediately see the skipped inode as expired and move it back onto wb->b_io, busy-retrying it instead of deferring it to the tail with dirtied_when = jiffies.

[Severity: Medium]
Can clobbering inode->dirtied_time_when to jiffies - dirtytime_expire_interval * HZ here (and in queue_dirtytime_writeback()) leave a permanently expired timestamp on the inode after I_DIRTY_TIME is cleared?

Neither sync_lazytime() nor __mark_inode_dirty(inode, I_DIRTY_INODE) resets dirtied_time_when, and __mark_inode_dirty(inode, I_DIRTY_TIME) only updates dirtied_time_when when !was_dirty and !(i_state & I_SYNC_QUEUED):

fs/fs-writeback.c:__mark_inode_dirty() {
	...
		if (inode_state_read(inode) & I_SYNC_QUEUED)
			goto out_unlock;
	...
		if (!was_dirty) {
			...
			inode->dirtied_when = jiffies;
			if (dirtytime)
				inode->dirtied_time_when = jiffies;
	...
}

If the cached inode is reused and has I_DIRTY_PAGES or I_SYNC_QUEUED set when its timestamps are dirtied again, dirtied_time_when retains the clobbered value from hours ago, causing __writeback_single_inode() to call sync_lazytime() immediately on the next data writeback pass.

[ ... ]

Quoted 37 lines
fs/fs-writeback.c +33 -0
@@ -2986,6 +3002,50 @@ void __mark_inode_dirty(struct inode *inode, int flags)
 }
 EXPORT_SYMBOL(__mark_inode_dirty);
 
+/*
+ * If inode has dirty timestamps to write out, make sure flush worker writes
+ * them out during its next periodic writeback writeout.
+ */
+void queue_dirtytime_writeback(struct inode *inode)
+{
+	struct bdi_writeback *wb;
+	unsigned int i_state;
+
+	lockdep_assert_held(&inode->i_lock);
+
+	wb = locked_inode_to_wb_and_lock_list(inode);
+	spin_lock(&inode->i_lock);
+	i_state = inode_state_read(inode);
+	/* Written back while we dropped i_lock? */
+	if (!(i_state & I_DIRTY_TIME))
+		goto out_wb_lock;
+
+	/*
+	 * If the inode is dirty, next writeback will come soon so we don't
+	 * need to do anything. If it is under writeback, we cannot touch dirty
+	 * lists now so we handle moving the inode after writeback is complete.
+	 */
+	if (i_state & (I_SYNC_QUEUED | I_SYNC | I_DIRTY)) {
+		/*
+		 * Clobber dirtied_time_when so that timestamps get synced on
+		 * next inode writeback.
+		 */
+		inode->dirtied_time_when = jiffies -
+						dirtytime_expire_interval * HZ;
+		goto out_wb_lock;
+	}
+

fs/fs-writeback.c void __mark_inode_dirty(struct inode *inode, int flags) · line 3047

Quoted 10 lines
fs/fs-writeback.c +10 -0
+	/*
+	 * Move inode to the beginning of dirty queue so that it gets written
+	 * out during the next periodic writeback.
+	 */
+	inode_add_dirtytime_head(inode, wb);
+	/* Wake up flush worker to ensure timely flush of the inode */
+	wb_wakeup_delayed(wb);
+out_wb_lock:
+	spin_unlock(&wb->list_lock);
+}

[Severity: Medium]
Can an unused inode placed at the head of wb->b_dirty_time miss periodic writeback scheduling and stay off the LRU for up to dirtytime_expire_interval?

If queue_dirtytime_writeback() hits the I_SYNC_QUEUED | I_SYNC | I_DIRTY branch while __writeback_single_inode() has already passed its dirtied_time_when check, writeback finishes with I_DIRTY_TIME still set and calls move_to_dirtytime_locked(). For icount_read(inode) == 0, move_to_dirtytime_locked() calls inode_add_dirtytime_head() and wb_io_lists_depopulated() (which clears WB_has_dirty_io when b_dirty, b_io and b_more_io are empty) without calling wb_wakeup_delayed(wb).

Similarly, even when queue_dirtytime_writeback() calls wb_wakeup_delayed(wb), b_dirty_time does not set WB_has_dirty_io. If wb_workfn() runs before wb->last_old_flush + msecs_to_jiffies(dirty_writeback_interval * 10), wb_check_old_data_flush() returns 0 and wb_workfn() only re-arms wb->dwork if wb_has_dirty_io(wb) is true, leaving wb->b_dirty_time unscheduled until wakeup_dirtytime_writeback() runs hours later.

[Severity: Medium]
Can queue_dirtytime_writeback() place unhashed non-blockdev inodes onto wb->b_dirty_time or clobber timestamps on inodes that are still in use or about to be evicted?

__mark_inode_dirty() sets I_DIRTY_TIME in i_state before skipping dirty-list insertion for (!S_ISBLK(inode->i_mode) && inode_unhashed(inode)). Because queue_dirtytime_writeback() does not check inode_unhashed(inode), and drops inode->i_lock in locked_inode_to_wb_and_lock_list() without rechecking icount_read(inode) == 1 or inode->i_nlink after re-acquiring i_lock, it will link unhashed inodes onto wb->b_dirty_time and clobber timestamps even if another thread grabbed a reference while i_lock was dropped. It also queues and wakes writeback for I_DONTCACHE or unhashed inodes that iput_final() immediately evicts.

Quoted 24 lines
fs/inode.c +0 -8
index f2003ae753745..4b13125f0678c 100644
@@ -2052,7 +2052,6 @@ void iput(struct inode *inode)
 	if (unlikely(!inode))
 		return;
 
-retry:
 	lockdep_assert_not_held(&inode->i_lock);
 	VFS_BUG_ON_INODE(inode_state_read_once(inode) & (I_FREEING | I_CLEAR), inode);
 	/*
@@ -2065,14 +2064,14 @@ void iput(struct inode *inode)
 	if (atomic_add_unless(&inode->i_count, -1, 1))
 		return;
 
-	if (inode->i_nlink && sync_lazytime(inode))
-		goto retry;
-
 	spin_lock(&inode->i_lock);
-	if (unlikely((inode_state_read(inode) & I_DIRTY_TIME) && inode->i_nlink)) {
-		spin_unlock(&inode->i_lock);
-		goto retry;
-	}

fs/inode.c void iput(struct inode *inode) · line 2077

Quoted 10 lines
fs/inode.c +7 -0
+	/*
+	 * If inode has timestamp updates pending, queue flushing them now as
+	 * otherwise the dirtiness could be preventing the inode from entering
+	 * LRU for hours.
+	 */
+	if (inode->i_nlink && inode_state_read(inode) & I_DIRTY_TIME)
+		queue_dirtytime_writeback(inode);
 
 	if (!atomic_dec_and_test(&inode->i_count)) {
 		spin_unlock(&inode->i_lock);

[Severity: Medium]
Can this lose pending lazytime timestamp updates when ->drop_inode() returns 1 on a linked inode?

Previously, iput() called sync_lazytime() before iput_final(), invoking ->dirty_inode(inode, I_DIRTY_SYNC | I_DIRTY_TIME). Now I_DIRTY_TIME is only queued on wb->b_dirty_time, and when op->drop_inode(inode) returns 1 in iput_final(), the drop branch skips write_inode_now(inode, 1) and evicts the inode directly:

fs/inode.c:iput_final() {
	...
	if (drop) {
		inode_state_set(inode, I_FREEING);
	} else {
		inode_state_set(inode, I_WILL_FREE);
		spin_unlock(&inode->i_lock);

		write_inode_now(inode, 1);
	...
}

For example, during unmount of a lazytime gfs2 filesystem, gfs2_kill_sb() -> gfs2_evict_inodes() sets SDF_EVICTING so gfs2_drop_inode() returns 1 for all linked inodes before kill_block_super() runs, and evict_linked_inode() skips writing the inode because gfs2_dirty_inode() was never called to copy the timestamps and set GLF_DIRTY.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
author maintainer
#6 lore raw

PATCH v5 4/8 fs: Basic infrastructure for offloading inode reclaim

In reply to Jan Kara

Reclaim of some inodes is rather complex requiring running transactions or doing other IO. Consequently filesystems end up doing GFP_NOFAIL allocations from kswapd or even direct reclaim which is problematic because forward progress of these allocations isn't guaranteed. Add infrastructure for marking inodes whose reclaim is difficult and offload reclaim of such inodes into a workqueue to not block kswapd with difficult inode reclaim. The processing of the queued inodes happens in parallel from several work items so that the reclaim has higher chances of keeping up with the inflow of inodes if reclaim of some inodes progresses slowly.

---
 fs/inode.c                       | 216 ++++++++++++++++++++++++++++++-
 fs/super.c                       |   2 +
 include/linux/fs.h               |   3 +
 include/linux/fs/super_types.h   |   3 +
 include/trace/events/writeback.h |   3 +-
 5 files changed, 223 insertions(+), 4 deletions(-)
fs/inode.c +213 -3
index a9f757fba23b..5713e18229e0 100644
@@ -74,6 +74,25 @@ static DEFINE_PER_CPU(unsigned long, nr_unused);
 
 static struct kmem_cache *inode_cachep __ro_after_init;
 
+struct deferred_reclaim_queue {
+	struct list_head list;
+	spinlock_t lock;
+};
+
+/* Inodes for deferred reclaim */
+struct inode_deferred_reclaim {
+	int workers;			/* Number of parallel workers */
+	struct workqueue_struct *wq;	/* Workqueue for workers */
+	struct work_struct *work;	/* Workers */
+	/*
+	 * Queue of deferred inodes. The number of queues is the same number
+	 * as the number of workers
+	 */
+	struct deferred_reclaim_queue *queues;
+};
+
+static struct inode_deferred_reclaim deferred_reclaim;
+
 static long get_nr_inodes(void)
 {
 	int i;
@@ -965,7 +984,7 @@ static enum lru_status inode_lru_isolate(struct list_head *item,
 	 */
 	if (icount_read(inode) ||
 	    (inode_state_read(inode) &
-	     ~(I_REFERENCED | I_METADATA_WRITEBACK)) ||
+	     ~(I_REFERENCED | I_METADATA_WRITEBACK | I_DEFER_RECLAIM)) ||
 	    !mapping_shrinkable(&inode->i_data)) {
 		list_lru_isolate(lru, &inode->i_lru);
 		spin_unlock(&inode->i_lock);
@@ -1016,6 +1035,39 @@ static enum lru_status inode_lru_isolate(struct list_head *item,
 	return LRU_REMOVED;
 }
 
+/* Number of inodes to process in one reclaim batch */
+#define INODE_RECLAIM_BATCH_SIZE 16
+
+static int get_deferred_sb_id(struct super_block *sb)
+{
+	return hash_ptr(sb, 32) % deferred_reclaim.workers;
+}
+
+static void queue_deferred_reclaim(struct super_block *sb, int count,
+				   struct list_head *list)
+{
+	int id = get_deferred_sb_id(sb);
+	struct deferred_reclaim_queue *queue =
+					&deferred_reclaim.queues[id];
+	int i, wake_count;
+
+	spin_lock(&queue->lock);
+	list_splice_tail(list, &queue->list);
+	atomic_add(count, &sb->s_deferred_reclaim_count);
+	spin_unlock(&queue->lock);
+
+	/* Make sure enough workers are woken for queued inodes of this sb */
+	wake_count = DIV_ROUND_UP(atomic_read(&sb->s_deferred_reclaim_count),
+				  INODE_RECLAIM_BATCH_SIZE);
+	if (wake_count > deferred_reclaim.workers)
+		wake_count = deferred_reclaim.workers;
+	for (i = 0; i < wake_count; i++) {
+		queue_work(deferred_reclaim.wq,
+			   &deferred_reclaim.work[id]);
+		id = (id + 1) % deferred_reclaim.workers;
+	}
+}
+
 /*
  * Walk the superblock inode LRU for freeable inodes and attempt to free them.
  * This is called from the superblock shrinker function with a number of inodes
@@ -1025,14 +1077,169 @@ static enum lru_status inode_lru_isolate(struct list_head *item,
 long prune_icache_sb(struct super_block *sb, struct shrink_control *sc)
 {
 	LIST_HEAD(freeable);
-	long freed;
+	long freed, deferred = 0;
+	struct inode *inode, *tmp;
 
 	freed = list_lru_shrink_walk(&sb->s_inode_lru, sc,
 				     inode_lru_isolate, &freeable);
-	dispose_list(&freeable);
+
+	list_for_each_entry_safe(inode, tmp, &freeable, i_lru) {
+		if (inode_state_read_once(inode) & I_DEFER_RECLAIM) {
+			deferred++;
+			continue;
+		}
+		list_del_init(&inode->i_lru);
+		evict(inode);
+		cond_resched();
+	}
+
+	if (!list_empty(&freeable))
+		queue_deferred_reclaim(sb, deferred, &freeable);
 	return freed;
 }
 
+static void __get_inode_reclaim_batch(int *start, int end,
+				      struct list_head *list, int *count)
+{
+	int i;
+
+	for (i = *start; i < end; i++) {
+		struct deferred_reclaim_queue *queue =
+						&deferred_reclaim.queues[i];
+		struct list_head *entry, tmp;
+
+		if (list_empty_careful(&queue->list))
+			continue;
+		spin_lock(&queue->lock);
+		list_for_each(entry, &queue->list) {
+			if (*count >= INODE_RECLAIM_BATCH_SIZE)
+				break;
+			(*count)++;
+		}
+		list_cut_before(&tmp, &queue->list, entry);
+		list_splice_tail(&tmp, list);
+		spin_unlock(&queue->lock);
+		if (*count >= INODE_RECLAIM_BATCH_SIZE)
+			break;
+	}
+	*start = i;
+}
+
+/* Move a batch of inodes from queued lists to our private list */
+static int get_inode_reclaim_batch(int *id, struct list_head *list)
+{
+	int count = 0;
+	int orig_id = *id;
+
+	__get_inode_reclaim_batch(id, deferred_reclaim.workers, list, &count);
+	if (count >= INODE_RECLAIM_BATCH_SIZE)
+		return count;
+	/* Wrap around */
+	if (orig_id > 0) {
+		*id = 0;
+		__get_inode_reclaim_batch(id, orig_id, list, &count);
+	}
+	return count;
+}
+
+
+static void inode_reclaim_deferred(struct work_struct *work)
+{
+	struct inode *inode;
+	LIST_HEAD(inode_batch);
+	/*
+	 * We start with the list corresponding to the work but rolling a dice
+	 * would work as well
+	 */
+	int id = work - deferred_reclaim.work;
+
+	while (1) {
+		if (!get_inode_reclaim_batch(&id, &inode_batch))
+			break;
+		while (!list_empty(&inode_batch)) {
+			struct super_block *sb;
+
+			/*
+			 * inode_batch list is private and I_FREEING flags
+			 * protect us from anybody else trying to remove the
+			 * inode from the LRU list. No locking needed.
+			 */
+			inode = list_first_entry(&inode_batch, struct inode,
+						 i_lru);
+			list_del_init(&inode->i_lru);
+			sb = inode->i_sb;
+			evict(inode);
+			/*
+			 * The elevated s_deferred_reclaim_count keeps sb alive
+			 * until we drop it. Use RCU to keep sb alive until
+			 * the wakeup is done.
+			 */
+			rcu_read_lock();
+			if (atomic_dec_and_test(&sb->s_deferred_reclaim_count))
+				wake_up_var(&sb->s_deferred_reclaim_count);
+			rcu_read_unlock();
+			cond_resched();
+		}
+	}
+}
+
+/* Maximum number of inode reclaim workers */
+#define MAX_RECLAIM_WORKERS 16
+
+static void __init deferred_reclaim_init(void)
+{
+	int workers = MAX_RECLAIM_WORKERS;
+	int i;
+
+	/* Scale down the number of workers for small systems */
+	if (workers > num_possible_cpus())
+		workers = num_possible_cpus();
+
+	deferred_reclaim.workers = workers;
+	deferred_reclaim.work = kmalloc_objs(struct work_struct, workers);
+	deferred_reclaim.queues =
+			kmalloc_objs(struct deferred_reclaim_queue, workers);
+	if (!deferred_reclaim.work || !deferred_reclaim.queues)
+		panic("Failed to allocate deferred inode reclaim queues");
+
+	deferred_reclaim.wq = alloc_workqueue("deferred-inode-reclaim",
+			WQ_FREEZABLE | WQ_MEM_RECLAIM | WQ_UNBOUND,
+			workers);
+	if (!deferred_reclaim.wq)
+		panic("Failed to allocate deferred inode reclaim workqueue");
+
+	for (i = 0; i < workers; i++) {
+		INIT_WORK(&deferred_reclaim.work[i], inode_reclaim_deferred);
+		spin_lock_init(&deferred_reclaim.queues[i].lock);
+		INIT_LIST_HEAD(&deferred_reclaim.queues[i].list);
+	}
+}
+
+/*
+ * Mark inode for deferred reclaim. When slab reclaim path will be freeing the
+ * inode, it will not call evict() directly but rather offload it to a worker
+ * in a workqueue. This is useful when inode reclaim is expected to take a
+ * long time (e.g. because it needs to do IO) so that it doesn't block kswapd
+ * or because it needs allocating memory (which cannot be guaranteed from
+ * reclaim path).
+ *
+ * Note that we currently don't provide a way to unmark inode for deferred
+ * reclaim. It could be done but the benefit is unclear. The rationale is that
+ * to make inode hard to reclaim, relatively expensive things like writing data
+ * to the file have to be done and in such case the additional CPU overhead and
+ * latency of offloading the inode reclaim is negligible in the overall load.
+ */
+void mark_inode_reclaim_deferred(struct inode *inode)
+{
+	if (inode_state_read_once(inode) & I_DEFER_RECLAIM)
+		return;
+
+	spin_lock(&inode->i_lock);
+	inode_state_set(inode, I_DEFER_RECLAIM);
+	spin_unlock(&inode->i_lock);
+}
+EXPORT_SYMBOL_GPL(mark_inode_reclaim_deferred);
+
 static void __wait_on_freeing_inode(struct inode *inode, bool hash_locked, bool rcu_locked);
 static bool igrab_from_hash(struct inode *inode);
 
@@ -2680,6 +2887,9 @@ void __init inode_init(void)
 					 SLAB_ACCOUNT),
 					 init_once);
 
+	/* Deferred inode reclaim infrastructure */
+	deferred_reclaim_init();
+
 	/* Hash may have been set up in inode_init_early */
 	if (!hashdist)
 		return;
fs/super.c +2 -0
index 4e68e7cac342..fa345d5027bf 100644
@@ -652,6 +652,8 @@ void deactivate_locked_super(struct super_block *s)
 	struct file_system_type *fs = s->s_type;
 	if (atomic_dec_and_test(&s->s_active)) {
 		shrinker_free(s->s_shrink);
+		wait_var_event(&s->s_deferred_reclaim_count,
+			       !atomic_read(&s->s_deferred_reclaim_count));
 		fs->kill_sb(s);
 
 		kill_super_notify(s);
include/linux/fs.h +3 -0
index 92a2841184f3..fc1a2cc9eb21 100644
@@ -744,6 +744,7 @@ enum inode_state_flags_enum {
 	I_SYNC_QUEUED		= (1U << 17),
 	I_PINNING_NETFS_WB	= (1U << 18),
 	I_METADATA_WRITEBACK	= (1U << 19),
+	I_DEFER_RECLAIM		= (1U << 20),
 };
 
 #define I_DIRTY_INODE (I_DIRTY_SYNC | I_DIRTY_DATASYNC)
@@ -2229,6 +2230,8 @@ static inline void set_inode_metadata_writeback(struct inode *inode)
 	spin_unlock(&inode->i_lock);
 }
 
+void mark_inode_reclaim_deferred(struct inode *inode);
+
 /*
  * returns the refcount on the inode. it can change arbitrarily.
  */
include/linux/fs/super_types.h +3 -0
index 4454e3574b2c..fc8f7f2261e2 100644
@@ -239,6 +239,9 @@ struct super_block {
 
 	struct shrinker				*s_shrink;	/* per-sb shrinker handle */
 
+	/* Number of inodes queued for deferred reclaim */
+	atomic_t				s_deferred_reclaim_count;
+
 	/* Number of inodes with nlink == 0 but still referenced */
 	atomic_long_t				s_remove_count;
 
include/trace/events/writeback.h +2 -1
index b7dfc9f7bb61..c2a5b492a71a 100644
@@ -28,7 +28,8 @@
 		{I_DONTCACHE,		"I_DONTCACHE"},		\
 		{I_SYNC_QUEUED,		"I_SYNC_QUEUED"},	\
 		{I_PINNING_NETFS_WB,	"I_PINNING_NETFS_WB"},	\
-		{I_LRU_ISOLATING,	"I_LRU_ISOLATING"}	\
+		{I_LRU_ISOLATING,	"I_LRU_ISOLATING"},	\
+		{I_DEFER_RECLAIM,	"I_DEFER_RECLAIM"}	\
 	)
 
 /* enums need to be exported to user space */
Signature · 1 line
2.53.0
#7 lore raw

Re: [PATCH v5 4/8] fs: Basic infrastructure for offloading inode reclaim

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] fs: max_active in deferred_reclaim_init() halves reclaim worker concurrency --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] fs: max_active in deferred_reclaim_init() halves reclaim worker concurrency
--

commit 78588b33f83dd121e8205d253bf4506e512f1879
Author: Jan Kara <[email protected]>

fs: Basic infrastructure for offloading inode reclaim

This commit adds infrastructure to mark inodes with I_DEFER_RECLAIM and offload their eviction from prune_icache_sb() to a dedicated unbound workqueue with parallel workers.

Quoted 4 lines
fs/inode.c +0 -0
index 4b13125f0678c..1f2f31d0f055c 100644

[ ... ]

Quoted 36 lines
fs/inode.c +32 -0
@@ -1017,6 +1036,39 @@ static enum lru_status inode_lru_isolate(struct list_head *item,
 	return LRU_REMOVED;
 }
 
+/* Number of inodes to process in one reclaim batch */
+#define INODE_RECLAIM_BATCH_SIZE 16
+
+static int get_deferred_sb_id(struct super_block *sb)
+{
+	return hash_ptr(sb, 32) % deferred_reclaim.workers;
+}
+
+static void queue_deferred_reclaim(struct super_block *sb, int count,
+				   struct list_head *list)
+{
+	int id = get_deferred_sb_id(sb);
+	struct deferred_reclaim_queue *queue =
+					&deferred_reclaim.queues[id];
+	int i, wake_count;
+
+	spin_lock(&queue->lock);
+	list_splice_tail(list, &queue->list);
+	atomic_add(count, &sb->s_deferred_reclaim_count);
+	spin_unlock(&queue->lock);
+
+	/* Make sure enough workers are woken for queued inodes of this sb */
+	wake_count = DIV_ROUND_UP(atomic_read(&sb->s_deferred_reclaim_count),
+				  INODE_RECLAIM_BATCH_SIZE);
+	if (wake_count > deferred_reclaim.workers)
+		wake_count = deferred_reclaim.workers;
+	for (i = 0; i < wake_count; i++) {
+		queue_work(deferred_reclaim.wq,
+			   &deferred_reclaim.work[id]);
+		id = (id + 1) % deferred_reclaim.workers;
+	}
+}

[ ... ]

Quoted 12 lines
fs/inode.c +12 -0
+/* Maximum number of inode reclaim workers */
+#define MAX_RECLAIM_WORKERS 16
+
+static void __init deferred_reclaim_init(void)
+{
+	int workers = MAX_RECLAIM_WORKERS;
+	int i;
+
+	/* Scale down the number of workers for small systems */
+	if (workers > num_possible_cpus())
+		workers = num_possible_cpus();
+

fs/inode.c static enum lru_status inode_lru_isolate(struct list_head *item, · line 1207

Quoted 10 lines
fs/inode.c +10 -0
+	deferred_reclaim.workers = workers;
+	deferred_reclaim.work = kmalloc_objs(struct work_struct, workers);
+	deferred_reclaim.queues =
+			kmalloc_objs(struct deferred_reclaim_queue, workers);
+	if (!deferred_reclaim.work || !deferred_reclaim.queues)
+		panic("Failed to allocate deferred inode reclaim queues");
+
+	deferred_reclaim.wq = alloc_workqueue("deferred-inode-reclaim",
+			WQ_FREEZABLE | WQ_MEM_RECLAIM | WQ_UNBOUND,
+			workers);

[Severity: Medium]
Can setting max_active to workers cap the workqueue at half of its intended concurrency during a sustained reclaim backlog?

When deferred_reclaim.work[id] starts executing in process_one_work(), WORK_STRUCT_PENDING_BIT is cleared while the work item retains its nr_active slot until inode_reclaim_deferred() returns. Because queue_deferred_reclaim() always starts queuing from the same base id for a superblock, any subsequent call while work[id] is still running in inode_reclaim_deferred() re-queues that executing work_struct. __queue_work() then acquires a second nr_active slot for the same work[id] and wakes an idle kworker, which detects the execution collision in assign_work(), moves work[id] to collision->scheduled, and goes back to sleep while keeping the second nr_active slot pinned.

Once workers / 2 work items are running and have been re-queued once, all max_active slots are consumed (or even earlier per node on NUMA systems where max_active is distributed across nodes). The remaining idle work[(id + i) % workers] items are placed on pwq->inactive_works and cannot start because running workers do not exit inode_reclaim_deferred() until all queues are completely empty. Since the number of concurrent workers is already bounded by the deferred_reclaim.work array of size workers, passing 0 (or WQ_MAX_ACTIVE) as max_active to alloc_workqueue() would avoid the nr_active exhaustion, though re-queuing active work items will still cause extra kworker wakeups.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
author maintainer
#8 lore raw

PATCH v5 5/8 fs: Defer reclaim of unlinked inodes

In reply to Jan Kara

Sometimes it can happen that reclaim of some slab object drops the last reference of an inode that is already unlinked. The frequently reported case of this is a reclaim of overlayfs inode dropping the last reference of an inode on upper filesystem. Because the inode is unlinked, evict() will delete it which generally requires writing to the filesystem and memory allocations - not good from kswapd or even direct reclaim. Defer inode reclaim of unlinked inodes to a workqueue when the last inode reference is dropped from a reclaim path.

---
 fs/inode.c | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)
fs/inode.c +17 -0
index 5713e18229e0..e6af38faa964 100644
@@ -2240,6 +2240,23 @@ static void iput_final(struct inode *inode)
 	inode_lru_list_del(inode);
 	spin_unlock(&inode->i_lock);
 
+	/*
+	 * Are we going to delete this inode while in reclaim path? Likely
+	 * reclaim of some object (e.g. overlayfs inode) ended up dropping the
+	 * last reference to an already deleted inode. Offload the eviction as
+	 * it's likely to require memory allocations and block on IO. Since
+	 * this eviction was triggered by a reclaim of unrelated object, the
+	 * inode is already outliving the operation that originally deleted it
+	 * (unlink, file close...). A slightly longer delay thus should not be
+	 * observable by userspace.
+	 */
+	if (current->flags & PF_MEMALLOC && !inode->i_nlink) {
+		LIST_HEAD(defer);
+
+		list_add(&inode->i_lru, &defer);
+		queue_deferred_reclaim(sb, 1, &defer);
+		return;
+	}
 	evict(inode);
 }
 
Signature · 1 line
2.53.0
#9 lore raw

Re: [PATCH v5 5/8] fs: Defer reclaim of unlinked inodes

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] fs: deferred eviction of unlinked inodes blocks on frozen fs in WQ_FREEZABLE wq --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] fs: deferred eviction of unlinked inodes blocks on frozen fs in WQ_FREEZABLE wq
--

commit c843e43a3dce9da35d7adae047df0c6b85fc0c3d
Author: Jan Kara <[email protected]>

fs: Defer reclaim of unlinked inodes

This commit offloads eviction of unlinked inodes to the deferred reclaim workqueue when the last reference is dropped from a memory reclaim path.

Quoted 17 lines
fs/inode.c +9 -0
index 1f2f31d0f055c..5dde1f9a9fb46 100644
@@ -2241,6 +2241,23 @@ static void iput_final(struct inode *inode)
 	inode_lru_list_del(inode);
 	spin_unlock(&inode->i_lock);
 
+	/*
+	 * Are we going to delete this inode while in reclaim path? Likely
+	 * reclaim of some object (e.g. overlayfs inode) ended up dropping the
+	 * last reference to an already deleted inode. Offload the eviction as
+	 * it's likely to require memory allocations and block on IO. Since
+	 * this eviction was triggered by a reclaim of unrelated object, the
+	 * inode is already outliving the operation that originally deleted it
+	 * (unlink, file close...). A slightly longer delay thus should not be
+	 * observable by userspace.

fs/inode.c static void iput_final(struct inode *inode) · line 2262

Quoted 10 lines
fs/inode.c +8 -0
+	 */
+	if (current->flags & PF_MEMALLOC && !inode->i_nlink) {
+		LIST_HEAD(defer);
+
+		list_add(&inode->i_lru, &defer);
+		queue_deferred_reclaim(sb, 1, &defer);
+		return;
+	}
 	evict(inode);
 }

[Severity: High]
Can queuing unlinked inodes to deferred_reclaim.wq stall a worker in sb_start_intwrite() when the filesystem is frozen?

When inode_reclaim_deferred() calls evict() -> op->evict_inode() for an unlinked inode, filesystems such as ext4, btrfs, and f2fs call sb_start_intwrite(inode->i_sb), which blocks uninterruptibly once the superblock reaches SB_FREEZE_FS. Unlike XFS's per-mount m_inodegc_wq, freeze_super() does not drain or stop deferred reclaim before advancing to SB_FREEZE_FS, and iput_final() keeps queuing unlinked inodes while the superblock is freezing or frozen.

Because deferred_reclaim.wq is allocated with WQ_FREEZABLE, an active work item blocked in sb_start_intwrite() prevents freeze_workqueues_busy() from completing and causes system suspend or hibernation to fail after the 20-second freezer timeout. In addition, get_inode_reclaim_batch() pulls up to 16 inodes across all queues onto a worker's private inode_batch list, so blocking on one frozen superblock traps inodes from other superblocks in that batch and can exhaust the global worker pool, hanging unmounts of unrelated filesystems in deactivate_locked_super() while waiting on s_deferred_reclaim_count.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
author maintainer
#10 lore raw

PATCH v5 6/8 fs: Defer reclaim of inodes requiring metadata writeback

In reply to Jan Kara

When we are reclaiming inodes which have I_METADATA_WRITEBACK set, we have to callback into the filesystem to write out any dirty metadata associated with the inode since we are going to loose track of it. This will require IO and is problematic from memory reclaim paths. Defer reclaim of inodes with I_METADATA_WRITEBACK set.

---
 fs/inode.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
fs/inode.c +2 -1
index e6af38faa964..5cc36e3df2e8 100644
@@ -1084,7 +1084,8 @@ long prune_icache_sb(struct super_block *sb, struct shrink_control *sc)
 				     inode_lru_isolate, &freeable);
 
 	list_for_each_entry_safe(inode, tmp, &freeable, i_lru) {
-		if (inode_state_read_once(inode) & I_DEFER_RECLAIM) {
+		if (inode_state_read_once(inode) &
+				(I_DEFER_RECLAIM | I_METADATA_WRITEBACK)) {
 			deferred++;
 			continue;
 		}
Signature · 1 line
2.53.0
author maintainer
#11 lore raw

PATCH v5 7/8 fs: Add throttling to deferred inode reclaim

In reply to Jan Kara

Deferring difficult inode reclaim from prune_icache_sb() to a workqueue removes the natural feedback loop of blocking tasks in direct reclaim until they make space for new allocations. This can result in the list of deferred inodes to grow beyond any bounds and possibly push the machine to a reclaim storm or OOM.

Add a throttling mechanism that makes tasks calling mark_inode_reclaim_deferred() wait on exit to userspace if the number of deferred inodes to reclaim for a superblock grows over limit. We measure average time it takes to reclaim inode on deferred list for a superblock and block tasks proportionally to that.

The mechanism to block tasks on exit to userspace is a bit simplistic but I don't expect more than one inode to be deferred per syscall and I expect throttling to be rare so it should be fine. If we wanted something more advanced, we could store the delay in task_struct and just wait for it when returning to userspace similarly as blkcg throttling does it but so far I consider the space in task_struct a waste for this purpose.

---
 fs/inode.c                       | 150 ++++++++++++++++++++++++++++---
 include/linux/fs/super_types.h   |   2 +
 include/trace/events/writeback.h |  51 +++++++++++
 3 files changed, 189 insertions(+), 14 deletions(-)
fs/inode.c +136 -14
index 5cc36e3df2e8..6b9c63f21307 100644
@@ -23,6 +23,7 @@
 #include <linux/rw_hint.h>
 #include <linux/seq_file.h>
 #include <linux/debugfs.h>
+#include <linux/task_work.h>
 #include <trace/events/writeback.h>
 #define CREATE_TRACE_POINTS
 #include <trace/events/timestamp.h>
@@ -1143,23 +1144,55 @@ static int get_inode_reclaim_batch(int *id, struct list_head *list)
 	return count;
 }
 
+static void inode_reclaim_update_stat(struct super_block *sb, unsigned int n,
+				      u64 start)
+{
+	u64 delay;
+
+	delay = div_u64(ktime_get_ns() - start, n);
+	/*
+	 * Smooth delay updates with exponential moving average. Updates can
+	 * get lost if workers race but we don't really care.
+	 */
+	WRITE_ONCE(sb->s_deferred_reclaim_delay,
+		   (63 * READ_ONCE(sb->s_deferred_reclaim_delay) + delay) / 64);
+
+	trace_inode_reclaim_update_stat(sb, n, delay,
+				READ_ONCE(sb->s_deferred_reclaim_delay));
+}
+
+static void sb_deferred_reclaim_put(struct super_block *sb, int n)
+{
+	/*
+	 * The elevated s_deferred_reclaim_count keeps sb alive until we drop
+	 * it. Use RCU to make sure sb isn't freed before the wakeup.
+	 */
+	rcu_read_lock();
+	if (!atomic_sub_return(n, &sb->s_deferred_reclaim_count))
+		wake_up_var(&sb->s_deferred_reclaim_count);
+	rcu_read_unlock();
+}
 
 static void inode_reclaim_deferred(struct work_struct *work)
 {
 	struct inode *inode;
 	LIST_HEAD(inode_batch);
+	u64 start;
+	int id, count;
+	struct super_block *sb;
+
 	/*
 	 * We start with the list corresponding to the work but rolling a dice
 	 * would work as well
 	 */
-	int id = work - deferred_reclaim.work;
+	id = work - deferred_reclaim.work;
 
 	while (1) {
 		if (!get_inode_reclaim_batch(&id, &inode_batch))
 			break;
-		while (!list_empty(&inode_batch)) {
-			struct super_block *sb;
+		sb = NULL;
 
+		while (!list_empty(&inode_batch)) {
 			/*
 			 * inode_batch list is private and I_FREEING flags
 			 * protect us from anybody else trying to remove the
@@ -1167,20 +1200,27 @@ static void inode_reclaim_deferred(struct work_struct *work)
 			 */
 			inode = list_first_entry(&inode_batch, struct inode,
 						 i_lru);
+			if (inode->i_sb != sb) {
+				if (sb) {
+					inode_reclaim_update_stat(sb, count,
+								  start);
+					sb_deferred_reclaim_put(sb, count);
+				}
+
+				sb = inode->i_sb;
+				count = 0;
+				start = ktime_get_ns();
+			}
+			count++;
 			list_del_init(&inode->i_lru);
-			sb = inode->i_sb;
 			evict(inode);
-			/*
-			 * The elevated s_deferred_reclaim_count keeps sb alive
-			 * until we drop it. Use RCU to keep sb alive until
-			 * the wakeup is done.
-			 */
-			rcu_read_lock();
-			if (atomic_dec_and_test(&sb->s_deferred_reclaim_count))
-				wake_up_var(&sb->s_deferred_reclaim_count);
-			rcu_read_unlock();
 			cond_resched();
 		}
+
+		if (sb) {
+			inode_reclaim_update_stat(sb, count, start);
+			sb_deferred_reclaim_put(sb, count);
+		}
 	}
 }
 
@@ -1216,6 +1256,80 @@ static void __init deferred_reclaim_init(void)
 	}
 }
 
+struct deferred_reclaim_delay {
+	struct callback_head task_work;
+	u64 delay;
+};
+
+static void deferred_delay_work(struct callback_head *work)
+{
+	struct deferred_reclaim_delay *dd =
+		container_of(work, struct deferred_reclaim_delay, task_work);
+
+	schedule_timeout_killable(nsecs_to_jiffies(dd->delay));
+	kfree(dd);
+}
+
+/*
+ * Size of deferred reclaim list from which we start throttling tasks creating
+ * inodes marked for deferred reclaim.
+ */
+#define INODE_DEFERRED_RECLAIM_LIMIT 8192
+
+static void throttle_inode_deferred_reclaim(struct inode *inode)
+{
+	struct super_block *sb = inode->i_sb;
+	unsigned int len;
+
+	/*
+	 * Don't throttle kthreads. They are doing work for somebody else
+	 * anyway so throttling is counterproductive.
+	 */
+	if (current->flags & PF_KTHREAD)
+		return;
+
+	/*
+	 * If inodes with deferred reclaim are accumulating too much, slow down
+	 * tasks creating them. This doesn't provide any kind of guarantee on
+	 * the length of the deferred list since lots of inodes with
+	 * I_DEFER_RECLAIM can be already present in the inode cache and we
+	 * have no control when they reach the deferred list. But if the
+	 * pressure on the deferred list is sustained, the balance should
+	 * eventually be established.
+	 */
+	len = atomic_read(&sb->s_deferred_reclaim_count);
+	if (len > INODE_DEFERRED_RECLAIM_LIMIT) {
+		u64 delay = READ_ONCE(sb->s_deferred_reclaim_delay);
+		struct deferred_reclaim_delay *dd;
+
+		/*
+		 * Scale the delay based on how much we exceed the limit. Wait
+		 * at most 4x as long as estimated time to reclaim the inode.
+		 */
+		len = min(len, 5 * INODE_DEFERRED_RECLAIM_LIMIT);
+		delay = div_u64(delay * (len - INODE_DEFERRED_RECLAIM_LIMIT),
+				INODE_DEFERRED_RECLAIM_LIMIT);
+		if (!delay)
+			return;
+
+		dd = kmalloc_obj(*dd, GFP_NOFS | __GFP_NORETRY);
+		/*
+		 * If the allocation failed, don't bother. Throttling is
+		 * approximate anyway and next time we'll throttle more.
+		 */
+		if (!dd)
+			return;
+
+		trace_mark_inode_reclaim_deferred_throttle(inode, len, delay);
+
+		dd->delay = delay;
+		init_task_work(&dd->task_work, deferred_delay_work);
+		/* This shouldn't fail. If it does, just cleanly bail. */
+		if (task_work_add(current, &dd->task_work, TWA_RESUME) < 0)
+			kfree(dd);
+	}
+}
+
 /*
  * Mark inode for deferred reclaim. When slab reclaim path will be freeing the
  * inode, it will not call evict() directly but rather offload it to a worker
@@ -1232,12 +1346,20 @@ static void __init deferred_reclaim_init(void)
  */
 void mark_inode_reclaim_deferred(struct inode *inode)
 {
+	bool throttle = false;
+
 	if (inode_state_read_once(inode) & I_DEFER_RECLAIM)
 		return;
 
 	spin_lock(&inode->i_lock);
-	inode_state_set(inode, I_DEFER_RECLAIM);
+	if (!(inode_state_read(inode) & I_DEFER_RECLAIM)) {
+		inode_state_set(inode, I_DEFER_RECLAIM);
+		throttle = true;
+	}
 	spin_unlock(&inode->i_lock);
+
+	if (throttle)
+		throttle_inode_deferred_reclaim(inode);
 }
 EXPORT_SYMBOL_GPL(mark_inode_reclaim_deferred);
 
include/linux/fs/super_types.h +2 -0
index fc8f7f2261e2..fe952ef02b96 100644
@@ -241,6 +241,8 @@ struct super_block {
 
 	/* Number of inodes queued for deferred reclaim */
 	atomic_t				s_deferred_reclaim_count;
+	/* Average time to reclaim one deferred inode */
+	u64					s_deferred_reclaim_delay;
 
 	/* Number of inodes with nlink == 0 but still referenced */
 	atomic_long_t				s_remove_count;
include/trace/events/writeback.h +51 -0

57 lines not on this page · raw message

Signature · 1 line
2.53.0
#12 lore raw

Re: [PATCH v5 7/8] fs: Add throttling to deferred inode reclaim

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] fs: sub-jiffy delay truncates to 0 in deferred_delay_work() - [Medium] fs: missing PF_EXITING…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] fs: sub-jiffy delay truncates to 0 in deferred_delay_work()
- [Medium] fs: missing PF_EXITING checks in deferred inode reclaim throttling
- [Low] fs: missing __GFP_NOWARN in throttle_inode_deferred_reclaim() allocation
--

commit 9f0a0ebfbed99db0ac1abb610f2f8e9a97ee5e15
Author: Jan Kara <[email protected]>

fs: Add throttling to deferred inode reclaim

This commit tracks the average per-inode deferred reclaim duration per superblock and throttles tasks calling mark_inode_reclaim_deferred() via TWA_RESUME task_work when the deferred reclaim queue exceeds a threshold.

Quoted 4 lines
fs/inode.c +0 -0
index 581d8b9888ac0..d2ae950bba6bd 100644

[ ... ]

Quoted 7 lines
fs/inode.c +3 -0
@@ -1217,6 +1257,80 @@ static void __init deferred_reclaim_init(void)
 	}
 }
 
+struct deferred_reclaim_delay {
+	struct callback_head task_work;
+	u64 delay;

fs/inode.c static void __init deferred_reclaim_init(void) · line 1272

Quoted 10 lines
fs/inode.c +10 -0
+};
+
+static void deferred_delay_work(struct callback_head *work)
+{
+	struct deferred_reclaim_delay *dd =
+		container_of(work, struct deferred_reclaim_delay, task_work);
+
+	schedule_timeout_killable(nsecs_to_jiffies(dd->delay));
+	kfree(dd);
+}

[Severity: Medium]
Does passing nsecs_to_jiffies(dd->delay) to schedule_timeout_killable() cause any sub-jiffy nanosecond delay to sleep for a full jiffy?

throttle_inode_deferred_reclaim() checks whether the scaled delay is non-zero in nanoseconds, so any delay between 1 ns and TICK_NSEC - 1 ns queues deferred_delay_work(). nsecs_to_jiffies() truncates sub-jiffy values to 0, and schedule_timeout(0) does not return immediately:

kernel/time/sleep_timeout.c:schedule_timeout() {
    ...
	expire = timeout + jiffies;

	timer.task = current;
	timer_setup_on_stack(&timer.timer, process_timeout, 0);
	timer.timer.expires = expire;
	add_timer(&timer.timer);
	schedule();
    ...
}

As a result, any non-zero sub-jiffy delay sleeps until the next timer tick instead of scaling proportionally with the queue length or respecting the 4x reclaim time cap. Using schedule_hrtimeout() (similar to blkcg_maybe_throttle_blkg()) or checking the converted jiffies value for zero before queuing task_work would avoid this.

Quoted 8 lines
fs/inode.c +8 -0
+
+/*
+ * Size of deferred reclaim list from which we start throttling tasks creating
+ * inodes marked for deferred reclaim.
+ */
+#define INODE_DEFERRED_RECLAIM_LIMIT 8192
+
+static void throttle_inode_deferred_reclaim(struct inode *inode)

fs/inode.c static void __init deferred_reclaim_init(void) · line 1289

Quoted 10 lines
fs/inode.c +10 -0
+{
+	struct super_block *sb = inode->i_sb;
+	unsigned int len;
+
+	/*
+	 * Don't throttle kthreads. They are doing work for somebody else
+	 * anyway so throttling is counterproductive.
+	 */
+	if (current->flags & PF_KTHREAD)
+		return;

[Severity: Medium]
Should throttle_inode_deferred_reclaim() and deferred_delay_work() also bail out when current->flags & PF_EXITING is set?

If mark_inode_reclaim_deferred() is called right before a task enters do_exit() without returning to userspace (for example during vfs_coredump() in get_signal()) or during do_exit() before exit_task_work() runs (such as acct_process()), deferred_delay_work() will be executed from exit_task_work(). By that point exit_signals() has already set PF_EXITING and flushed pending signals including SIGKILL, so schedule_timeout_killable() sleeps uninterruptibly on a task that is already exiting.

Quoted 16 lines
fs/inode.c +16 -0
+
+	/*
+	 * If inodes with deferred reclaim are accumulating too much, slow down
+	 * tasks creating them. This doesn't provide any kind of guarantee on
+	 * the length of the deferred list since lots of inodes with
+	 * I_DEFER_RECLAIM can be already present in the inode cache and we
+	 * have no control when they reach the deferred list. But if the
+	 * pressure on the deferred list is sustained, the balance should
+	 * eventually be established.
+	 */
+	len = atomic_read(&sb->s_deferred_reclaim_count);
+	if (len > INODE_DEFERRED_RECLAIM_LIMIT) {
+		u64 delay = READ_ONCE(sb->s_deferred_reclaim_delay);
+		struct deferred_reclaim_delay *dd;
+
+		/*

fs/inode.c static void __init deferred_reclaim_init(void) · line 1315

Quoted 10 lines
fs/inode.c +10 -0
+		 * Scale the delay based on how much we exceed the limit. Wait
+		 * at most 4x as long as estimated time to reclaim the inode.
+		 */
+		len = min(len, 5 * INODE_DEFERRED_RECLAIM_LIMIT);
+		delay = div_u64(delay * (len - INODE_DEFERRED_RECLAIM_LIMIT),
+				INODE_DEFERRED_RECLAIM_LIMIT);
+		if (!delay)
+			return;
+
+		dd = kmalloc_obj(*dd, GFP_NOFS | __GFP_NORETRY);

[Severity: Low]
Should this opportunistic allocation include __GFP_NOWARN? Because allocation failure is expected and ignored under memory pressure, omitting __GFP_NOWARN allows the page and slab allocators to emit allocation failure warnings and backtraces when __GFP_NORETRY gives up.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
author maintainer
#13 lore raw

PATCH v5 8/8 ext4: Defer inode reclaim if it has preallocations

In reply to Jan Kara

When we have to free preallocations during inode eviction, we need to load block bitmaps and run transaction to modify them. This takes time and also requires GFP_NOFAIL allocations. Mark inodes with preallocated blocks as needing offloading of inode reclaim to a workqueue so that we don't block reclaim for long and potentially deadlock MM subsystem.

We do the marking in ext4_mb_regular_allocator() to reliably catch all the cases adding preallocated blocks to the inode and additionally when adding delay allocated blocks (which will very likely result in preallocated blocks in the future) so that deferred reclaim throttling has a chance of throttling tasks generating the work.

---
 fs/ext4/inode.c   | 9 ++++++++-
 fs/ext4/mballoc.c | 7 +++++++
 2 files changed, 15 insertions(+), 1 deletion(-)
fs/ext4/inode.c +8 -1
index e3129353d4ed..efc2f8ebe7ba 100644
@@ -2113,8 +2113,15 @@ static int ext4_da_map_blocks(struct inode *inode, struct ext4_map_blocks *map)
 
 	map->m_flags |= EXT4_MAP_DELAYED | EXT4_MAP_NEW;
 	retval = ext4_insert_delayed_blocks(inode, map->m_lblk, map->m_len);
-	if (!retval)
+	if (!retval) {
 		map->m_seq = READ_ONCE(EXT4_I(inode)->i_es_seq);
+		/*
+		 * Inode will likely have preallocations which are hard to
+		 * reclaim. Mark is for deferred reclaim early so that deferred
+		 * reclaim throttling hits the task causing the work.
+		 */
+		mark_inode_reclaim_deferred(inode);
+	}
 	up_write(&EXT4_I(inode)->i_data_sem);
 
 	return retval;
fs/ext4/mballoc.c +7 -0
index a15285224cdf..d138c4b697b3 100644
@@ -3113,6 +3113,13 @@ ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
 	if (ac->ac_prefetch_nr)
 		ext4_mb_prefetch_fini(sb, ac->ac_prefetch_grp, ac->ac_prefetch_nr);
 
+	/*
+	 * Freeing preallocations requires loading bitmaps and running
+	 * transactions. Defer inode reclaim to a workqueue.
+	 */
+	if (!RB_EMPTY_ROOT(&EXT4_I(ac->ac_inode)->i_prealloc_node))
+		mark_inode_reclaim_deferred(ac->ac_inode);
+
 	return err;
 }
 
Signature · 1 line
2.53.0