Skip to contentSkip to conversation

f2fs: retain clean node blocks in a compressed cache

RFC PATCH New Wenjie Qi 1 participant 7 messages Sep 29 F2FS file system

lore
Share & tools
lore

Wenjie Qi

author
#0 lore raw

cover f2fs: retain clean node blocks in a compressed cache

Hi,

This RFC adds a reclaimable compressed representation for clean node-cache entries on top of the F2FS metadata cache.

The node cache avoids repeated NAT and node-block reads, but retaining a raw node still consumes one filesystem block. A large raw cache therefore has a substantial memory footprint, while reclaiming entries early causes later accesses to issue node reads again.

This series provides a middle ground:

- active or recently accessed nodes remain in the raw representation;
- a background worker compresses colder clean nodes into small private-slab

    objects;

- a compressed entry keeps its NID identity;
- access restores the raw block before normal node validation;
- compressed data remains a discardable optimization, and restore or validation failure falls back to the ordinary disk-read path; and
- both raw and compressed entries remain reclaimable by the F2FS shrinker.

Compressed representation
=========================

When the feature is enabled, NODE_CACHE uses an extended entry to retain the compressed payload length, private-slab allocation size, CRC of the original node block, and compression-context ownership.

Compressed payloads use per-superblock private slabs with three object sizes:

256 bytes
512 bytes
1024 bytes

A result that exceeds either the configured threshold or the 1024-byte limit is not retained. Raw entries stay on the existing node LRU. Compressed entries are placed on separate 256-, 512-, and 1024-byte queues according to their allocation size.

Ownership and restore
=====================

The conversion path may briefly hold both the raw block and a newly allocated compressed object. After publication, however, the entry owns only one representation. Compressed bytes are never submitted directly to BIO.

Restore runs while the entry lock and lookup reference still exclude normal concurrent byte users. It validates:

allocation size
compressed payload length
LZ4 output length
raw-block CRC
node footer
inode checksum
requested node type

A raw-buffer allocation failure leaves the compressed representation intact so that a caller may retry. A malformed payload or later semantic validation failure discards the optimization and uses the normal disk-read path. The compressed cache therefore does not replace the on-disk source of truth.

Background worker
=================

The series reuses the existing per-superblock cache thread instead of adding a new kernel thread. Writeback and compression keep separate due times, but execute serially in that shared thread.

Each worker pass is bounded by:

maximum raw scan: 1024 entries
maximum candidates: 256 entries
reschedule batch: 32 entries

The series adds two sysfs controls:

node_compress_threshold
node_compress_interval

The threshold is the maximum retained compressed payload as a percentage of the original block; zero disables compression. The interval range is 100--30000 ms, with a default of 1000 ms.

Reclaim policy
==============

The series lets the node shrinker reclaim raw and compressed queues independently, so every compressed entry created by the worker remains reclaimable.

The shrinker uses fixed reclaim weights. A raw entry has a larger weight because it occupies a full block. Compressed entries are retained preferentially, but remain reclaimable under sustained pressure.

The same weights are used for:

- the effective shrinker count; and
- per-queue scan quotas.

Quota rounding credit is carried across shrinker invocations. If a queue reaches its population cap, unused quota is redistributed to the other queues.

REFERENCED second chance
========================

The worker and shrinker use the same REFERENCED rule:

test REFERENCED
clear REFERENCED
move the entry to the tail of its current queue
skip it in the current pass

The worker remembers the original raw-list tail so entries moved during a pass are not revisited in that pass.

If an entry is accessed after compression completes but before publication, the temporary compressed object is discarded and the entry receives the same second chance.

NVMe-backed QEMU test
====================

The test environment was:

x86_64 KVM
4 vCPUs
3 GiB guest memory
2 GiB raw F2FS image
host backing filesystem: /dev/nvme0n1p2
guest block device: /dev/nvme0n1
QEMU device: nvme
cache=none
aio=native

Each test suite created its own empty, formatted 2 GiB seed image. For every guest boot, the host copied that seed into an independent sparse image, and the guest rebuilt the same file set:

/mnt/bench/

  |-- files/
  |   |-- d-0/f-0 ... f-63
  |   |-- d-1/f-0 ... f-63
  |   `-- d-255/f-0 ... f-63
  |-- shaped/
  |   |-- b-1-0 ... b-1-3
  |   |-- b-32-0 ... b-32-3
  |   |-- b-80-0 ... b-80-3
  |   |-- b-128-0 ... b-128-3
  |   |-- b-192-0 ... b-192-3
  |   |-- b-256-0 ... b-256-3
  |   |-- b-384-0 ... b-384-3
  |   `-- b-512-0 ... b-512-3

`-- sentinel

The files/ tree contains 256 directories with 64 files each, for 16,384 replay files. These files build a fixed inode, dentry, and node-page population and are accessed later in a fixed manifest order.

The shaped/ tree contains 32 zero-filled files ranging from 1 to 512 blocks. Their different extent and block-address densities diversify node-page contents and compression outcomes. They contribute to the initial cache population and subsequent compression and reclaim, but are excluded from the timed replay, which remains limited to the 16,384 uniform small files. The sentinel is used only for clean unmount, remount, and content verification after the measured workload.

The workload compares memory use and replay latency at equal node counts, and retained nodes, node reads, and replay latency at equal node-cache memory.

For the results below, compression-off means compression admission is disabled at runtime, while compression-on means background conversion is enabled. Attributed node-cache memory is the sum of cache-entry bytes, raw block buffers or compressed private-slab slots, and known fixed context bytes. It is an accounting metric, not measured physical RSS, and excludes allocator metadata.

At equal node counts, both modes retained 16,676 nodes:

compression-off attributed memory: 69,792,344 bytes
compression-on attributed memory: 6,008,152 bytes
memory reduction: 91.391%

The paired median foreground replay regression was 0.845%.

At equal node counts, the compressed representation substantially reduced attributed memory while typical replay latency remained close.

At an approximately 3 MiB attributed node-cache budget:

compression-off: 3,199,800 bytes, 760 nodes
compression-on: 3,207,992 bytes, 9,208 nodes
retained-node ratio: 12.116x

Node reads were:

compression-off: 15,668 reads / 64,176,128 bytes
compression-on: 7,209 reads / 29,528,064 bytes
reduction: 53.989%

The compression-on configuration also completed 9,175 compressed restores. For the one-pass foreground replay, those restores plus 7,209 node reads equal the 16,384 per-file node retrievals. These counters cover F2FS node retrievals, not all guest filesystem I/O.

The paired median foreground replay delta was -24.984%.

At the same node-cache memory budget, the compressed representation retained more nodes, reduced node reads, and improved replay latency in this workload.

Android phone test
==================

The mechanism was also exercised on a real Android phone with application, memory-pressure, and cache-lifecycle workloads.

Each successful trial performed:

reboot
launch 18 applications for a seed pass pre-pressure normalization
allocate and hold 1 GiB of memory pressure for 30 seconds release pressure
launch 18 applications for measured pass 1 launch the same 18 applications for measured pass 2 restore the original policy
clean up and run an offline audit

The seed pass was excluded from the reported measured launch-time results. It populated the post-reboot F2FS node cache with application-related node entries so that background compression, pressure reclaim, and later restore operated on a non-empty cache.

The application set included messaging, short-video, shopping, social-media, browser, and video applications. Each application record retained the package, Activity, PID, process start time, launch timing, and F2FS node-cache counters.

In the snapshot statistics below, attached node entries are the current raw and compressed cache entries. Attached raw bytes count 4 KiB raw buffers, while compressed slot bytes count allocated private-slab bucket sizes. Node-cache logical bytes combine entry, raw-buffer, and slot accounting; they are not measured physical RSS.

After restoring the original sysfs policy, the final snapshots showed these trial-level means. Restoring the policy did not flush existing cache entries:

compression-off:
attached node entries: 14,509
compressed entries: 0
attached raw bytes: 59,430,229
node-cache logical bytes: 60,823,125

compression-on:

    attached node entries:      25,331
    compressed entries:         16,402
    attached raw bytes:      36,573,184
    compressed slot bytes:    8,769,877
    node-cache logical bytes: 47,774,805

At the same final snapshots, the mean compressed-entry distribution per trial, rounded to the nearest entry, was:

256-byte: 373 entries ( 2.27%)
512-byte: 15,116 entries (92.16%)
1024-byte: 913 entries ( 5.57%)

Under the F2FS node-cache accounting model, compression-on changed the above values by:

retained node entries: +74.59%
raw bytes: -38.46%
logical cache bytes: -21.45%

The node-read count is the filesystem-wide F2FS FS_NODE_READ_IO count for the /data mount. Each event represents a submitted 4 KiB node-block read. It includes activity from the measured applications and concurrent Android services, and is neither a per-application attribution nor a count of all storage I/O. The counts were:

compression-off mean: 309,360
compression-on mean: 287,417
difference: -7.09%

The compression-on trials also exercised raw-to-compressed conversion, compressed restore, compressed-queue reclaim, and REFERENCED clear-and-move. Each compression-on trial completed about 70,441--76,786 conversions and retained a mean of 16,402 compressed entries in the final snapshots after policy restoration.

In this Android workload, the compressed representation reduced node-cache accounting memory, retained more node entries, and showed a lower filesystem- wide node-read counter. Raw and compressed entries continued to be reclaimed under pressure, followed by restore and recompression during application replay. The observed node-read reduction describes the direction in this workload rather than a strict per-application causal measurement.

Patch layout
============

Patch 1 generalizes metadata-cache shrinking to accept explicit lists while preserving the behavior of existing caches.

Patch 2 adds the extended node entry, private slabs, compressed queues, ownership, and memory accounting.

Patch 3 connects queue-aware reclaim, fixed reclaim weights, and carried rounding credit.

Patch 4 adds restore, length and CRC validation, complete node validation, and disk fallback.

Patch 5 adds the bounded background worker to the cache thread and exposes the threshold and interval controls.

Patch 6 gives the worker and shrinker the same REFERENCED clear-and-move behavior.

This series is based on F2FS dev-test commit:

1b629035be4a ("f2fs: rename nr_pages_to_skip with nr_caches_to_skip")

I would especially appreciate feedback on:

1. whether per-superblock 256-, 512-, and 1024-byte private slabs are an

     appropriate allocator boundary;

2. whether fixed reclaim weights for raw blocks and compressed slots are a reasonable initial reclaim policy; and
3. whether the threshold and interval provide a sufficient initial control interface.

Thanks,
Wenjie

Wenjie Qi (6):
f2fs: generalize metadata cache shrinking to explicit lists
f2fs: add compressed clean node cache representation
f2fs: bias node cache reclaim toward raw entries
f2fs: restore compressed node cache entries before access
f2fs: compress clean node cache entries in background
f2fs: give referenced node cache entries a shared second chance

 Documentation/ABI/testing/sysfs-fs-f2fs |  22 +
 fs/f2fs/Kconfig                         |  12 +
 fs/f2fs/Makefile                        |   2 +
 fs/f2fs/cache.c                         | 145 +++-
 fs/f2fs/cache.h                         |  52 +-
 fs/f2fs/data.c                          |   5 +-
 fs/f2fs/debug.c                         |  47 +-
 fs/f2fs/f2fs.h                          |  17 +
 fs/f2fs/inode.c                         |  20 +-
 fs/f2fs/node.c                          |  55 +-
 fs/f2fs/node_cache_compress.c           | 915 ++++++++++++++++++++++++
 fs/f2fs/node_cache_compress.h           | 144 ++++
 fs/f2fs/node_cache_policy.c             | 211 ++++++
 fs/f2fs/node_cache_policy.h             |  54 ++
 fs/f2fs/shrinker.c                      |   3 +-
 fs/f2fs/super.c                         |   4 +
 fs/f2fs/sysfs.c                         |  59 ++
 17 files changed, 1713 insertions(+), 54 deletions(-)
 create mode 100644 fs/f2fs/node_cache_compress.c
 create mode 100644 fs/f2fs/node_cache_compress.h
 create mode 100644 fs/f2fs/node_cache_policy.c
 create mode 100644 fs/f2fs/node_cache_policy.h

base-commit: 1b629035be4a085f59d47edc62f4e695c763a94d

Signature · 1 line
2.43.0
author
#1 lore raw

RFC PATCH 1/6 f2fs: generalize metadata cache shrinking to explicit lists

The metadata-cache shrinker currently operates on cache->lru_list. Node-cache compression needs separate raw and compressed queues, while keeping the existing isolation, truncation and refcount rules.

Move the common shrink loop to f2fs_shrink_cache_list(), and pass it an explicit list, population and scan budget. Existing caches continue to use their current LRU lists.

Also return the number of examined entries for queue-specific reclaim accounting.

---
 fs/f2fs/cache.c | 30 +++++++++++++++++++++---------
 fs/f2fs/cache.h |  6 +++++-
 2 files changed, 26 insertions(+), 10 deletions(-)
fs/f2fs/cache.c +21 -9
index 38fc5eb17f92..8f81aed132ed 100644
@@ -547,8 +547,10 @@ void f2fs_destroy_cache(struct f2fs_cached_block_list *cache)
 	goto next;
 }
 
-static unsigned long f2fs_do_shrink_cache(struct f2fs_cached_block_list *cache,
-						unsigned long nr_to_scan)
+unsigned long
+f2fs_shrink_cache_list(struct f2fs_cached_block_list *cache,
+		       struct list_head *head, unsigned long nr_entries,
+		       unsigned long nr_to_scan, unsigned long *nr_scanned)
 {
 	struct f2fs_cached_block *entry, *next;
 	LIST_HEAD(dispose_list);
@@ -558,15 +560,15 @@ static unsigned long f2fs_do_shrink_cache(struct f2fs_cached_block_list *cache,
 
 	/* Phase 1: Isolate candidate entries from LRU list into dispose_list */
 	spin_lock(&cache->list_lock);
-	list_for_each_entry_safe(entry, next, &cache->lru_list, list) {
-		if (scanned >= cache->num_entries)
-			break;
-		if (scanned++ >= nr_to_scan)
+	nr_entries = min(nr_entries, cache->num_entries);
+	list_for_each_entry_safe(entry, next, head, list) {
+		if (scanned >= nr_entries || scanned >= nr_to_scan)
 			break;
+		scanned++;
 
 		/* If accessed, give it a second chance to rotate to tail */
 		if (f2fs_cache_test_and_clear_referenced(entry)) {
-			list_move_tail(&entry->list, &cache->lru_list);
+			list_move_tail(&entry->list, head);
 			continue;
 		}
 
@@ -620,16 +622,26 @@ static unsigned long f2fs_do_shrink_cache(struct f2fs_cached_block_list *cache,
 			freed++;
 	}
 
-	/* Phase 3: Splice un-reclaimed entries back onto cache->lru_list */
+	/* Phase 3: Splice un-reclaimed entries back onto the scanned list */
 	if (!list_empty(&keep_list)) {
 		spin_lock(&cache->list_lock);
-		list_splice_tail(&keep_list, &cache->lru_list);
+		list_splice_tail(&keep_list, head);
 		spin_unlock(&cache->list_lock);
 	}
+	if (nr_scanned)
+		*nr_scanned = scanned;
 
 	return freed;
 }
 
+static unsigned long
+f2fs_do_shrink_cache(struct f2fs_cached_block_list *cache,
+		     unsigned long nr_to_scan)
+{
+	return f2fs_shrink_cache_list(cache, &cache->lru_list, ULONG_MAX,
+			nr_to_scan, NULL);
+}
+
 unsigned long f2fs_shrink_cache(struct f2fs_sb_info *sbi,
 					unsigned long nr_to_scan)
 {
fs/f2fs/cache.h +5 -1
index 6c4db910d767..c4c3d09a0008 100644
@@ -222,7 +222,11 @@ void f2fs_drop_cache_range(struct f2fs_cached_block_list *cache,
 	f2fs_drop_cache_range(NODE_CACHE(sbi), start, len, true)
 
 unsigned long f2fs_shrink_cache(struct f2fs_sb_info *sbi,
-				unsigned long nr_to_scan);
+					unsigned long nr_to_scan);
+unsigned long
+f2fs_shrink_cache_list(struct f2fs_cached_block_list *cache,
+		       struct list_head *head, unsigned long nr_entries,
+		       unsigned long nr_to_scan, unsigned long *nr_scanned);
 
 #define DEF_DIRTY_CACHE_TIMEOUT 5000
 #define MIN_DIRTY_CACHE_TIMEOUT 100
Signature · 1 line
2.43.0
author
#2 lore raw

RFC PATCH 2/6 f2fs: add compressed clean node cache representation

In reply to Wenjie Qi

A clean node-cache entry currently retains a full block until it is reclaimed. Add an optional compressed representation that keeps the entry and its NID in memory with a smaller payload.

Use an extended NODE_CACHE entry and per-mount 256, 512 and 1024-byte private slabs. Raw entries remain on the existing LRU, while compressed entries use one queue per allocation size.

Keep raw and compressed ownership exclusive, and make detach and teardown aware of the compressed queues. If the compression resources cannot be initialized, leave node compression disabled instead of failing the mount. The generic entry layout remains unchanged when the feature is disabled.

---
 fs/f2fs/Kconfig               |  12 ++
 fs/f2fs/Makefile              |   1 +
 fs/f2fs/cache.c               |  27 ++-
 fs/f2fs/cache.h               |   8 +
 fs/f2fs/debug.c               |  10 +-
 fs/f2fs/f2fs.h                |   7 +
 fs/f2fs/node_cache_compress.c | 303 ++++++++++++++++++++++++++++++++++
 fs/f2fs/node_cache_compress.h |  78 +++++++++
 fs/f2fs/node_cache_policy.h   |  23 +++
 fs/f2fs/super.c               |   4 +
 10 files changed, 462 insertions(+), 11 deletions(-)
 create mode 100644 fs/f2fs/node_cache_compress.c
 create mode 100644 fs/f2fs/node_cache_compress.h
 create mode 100644 fs/f2fs/node_cache_policy.h
fs/f2fs/Kconfig +12 -0
index 5916a02fb46d..5aa54916e594 100644
@@ -99,6 +99,18 @@ config F2FS_FS_COMPRESSION
 	  Enable filesystem-level compression on f2fs regular files,
 	  multiple back-end compression algorithms are supported.
 
+config F2FS_FS_NODE_CACHE_COMPRESSION
+	bool "F2FS clean node cache compression"
+	depends on F2FS_FS
+	select LZ4_COMPRESS
+	select LZ4_DECOMPRESS
+	default n
+	help
+	  Retain clean node-cache blocks in a private compressed store.
+	  This is independent of file-data compression and COMPRESS_CACHE.
+	  The store uses 256, 512 and 1024 byte slab buckets.
+	  Compression is disabled at runtime until a nonzero threshold is set.
+
 config F2FS_FS_LZO
 	bool "LZO compression support"
 	depends on F2FS_FS_COMPRESSION
fs/f2fs/Makefile +1 -0
index fbf49c30b066..e1e4b98707e9 100644
@@ -9,4 +9,5 @@ f2fs-$(CONFIG_F2FS_FS_XATTR) += xattr.o
 f2fs-$(CONFIG_F2FS_FS_POSIX_ACL) += acl.o
 f2fs-$(CONFIG_FS_VERITY) += verity.o
 f2fs-$(CONFIG_F2FS_FS_COMPRESSION) += compress.o
+f2fs-$(CONFIG_F2FS_FS_NODE_CACHE_COMPRESSION) += node_cache_compress.o
 f2fs-$(CONFIG_F2FS_IOSTAT) += iostat.o
fs/f2fs/cache.c +21 -6
index 8f81aed132ed..3d1d530cdd82 100644
@@ -17,6 +17,7 @@
 #include "node.h"
 #include <trace/events/f2fs.h>
 #include "segment.h"
+#include "node_cache_compress.h"
 
 void f2fs_cache_wait_writeback_cond(struct f2fs_cached_block *entry,
 					enum page_type type)
@@ -127,7 +128,7 @@ static int f2fs_cache_refcount(struct f2fs_cached_block *entry)
 
 static void f2fs_do_free_cache(struct f2fs_cached_block *entry)
 {
-	kfree(entry->data);
+	f2fs_nc_free_data(entry);
 	kfree(entry);
 }
 
@@ -159,6 +160,7 @@ static struct f2fs_cached_block *f2fs_create_cache(
 {
 	struct f2fs_sb_info *sbi = cache->sbi;
 	struct f2fs_cached_block *entry;
+	size_t entry_size = f2fs_nc_entry_alloc_size(cache);
 	unsigned int flags = GFP_NOFS;
 
 	if (index == ULONG_MAX)
@@ -166,10 +168,10 @@ static struct f2fs_cached_block *f2fs_create_cache(
 
 	if (nofail) {
 		flags |= __GFP_NOFAIL;
-		entry = kzalloc_obj(*entry, flags);
+		entry = kzalloc(entry_size, flags);
 		entry->data = kmalloc(sbi->blocksize, flags);
 	} else {
-		entry = f2fs_kzalloc(sbi, sizeof(*entry), flags);
+		entry = f2fs_kzalloc(sbi, entry_size, flags);
 		if (!entry)
 			return ERR_PTR(-ENOMEM);
 
@@ -220,6 +222,7 @@ static struct f2fs_cached_block *f2fs_insert_cache(
 		f2fs_bug_on(cache->sbi, !list_empty(&e->list));
 		list_add_tail(&e->list, &cache->lru_list);
 		cache->num_entries++;
+		f2fs_nc_entry_attached(e);
 	}
 	f2fs_cache_get(e);
 	spin_unlock_irqrestore(&cache->tree_lock, flags);
@@ -429,8 +432,9 @@ static void f2fs_do_truncate_cache(struct f2fs_cached_block *entry,
 	if (!radix_tree_delete(&cache->root, entry->index))
 		f2fs_bug_on(cache->sbi, !entry->cache);
 
-	entry->cache = NULL;
 	cache->num_entries--;
+	f2fs_nc_entry_detached(entry);
+	entry->cache = NULL;
 
 	atomic_dec(&entry->refcount);
 	f2fs_bug_on(cache->sbi, !f2fs_cache_refcount(entry));
@@ -514,14 +518,24 @@ int f2fs_init_cache(struct f2fs_sb_info *sbi,
 
 void f2fs_destroy_cache(struct f2fs_cached_block_list *cache)
 {
-	struct list_head *head = &cache->lru_list;
+	struct list_head *head;
 	struct f2fs_cached_block *entry;
 	unsigned long flags;
+	unsigned int queue;
 
 	f2fs_cache_wait_on_all_writeback(cache);
 next:
 	spin_lock(&cache->list_lock);
-	if (list_empty(head)) {
+	head = NULL;
+	for (queue = 0; queue < F2FS_NC_NR_QUEUES; queue++) {
+		struct list_head *candidate = f2fs_nc_queue_head(cache, queue);
+
+		if (candidate && !list_empty(candidate)) {
+			head = candidate;
+			break;
+		}
+	}
+	if (!head) {
 		spin_unlock(&cache->list_lock);
 		return;
 	}
@@ -530,6 +544,7 @@ void f2fs_destroy_cache(struct f2fs_cached_block_list *cache)
 	spin_lock_irqsave(&cache->tree_lock, flags);
 	radix_tree_delete(&cache->root, entry->index);
 	cache->num_entries--;
+	f2fs_nc_entry_detached(entry);
 	list_del_init(&entry->list);
 	spin_unlock_irqrestore(&cache->tree_lock, flags);
 
fs/f2fs/cache.h +8 -0
index c4c3d09a0008..8a1eab71b1ae 100644
@@ -64,6 +64,9 @@ enum f2fs_cached_state {
 	F2FS_BLOCK_WRITEBACK,		/* cache data is writeback state */
 	F2FS_BLOCK_REFERENCED,		/* cache was accessed recently, shrinker will skip it for once */
 	F2FS_BLOCK_INLINE_DATA,		/* indicate inline data */
+#ifdef CONFIG_F2FS_FS_NODE_CACHE_COMPRESSION
+	F2FS_BLOCK_COMPRESSED,
+#endif
 };
 
 enum {
@@ -144,6 +147,11 @@ F2FS_CACHE_FLAG_CLEAR_FUNC(inline, INLINE_DATA);
 F2FS_CACHE_FLAG_TEST_FUNC(referenced, REFERENCED);
 F2FS_CACHE_FLAG_SET_FUNC(referenced, REFERENCED);
 F2FS_CACHE_FLAG_TEST_AND_CLEAR_FUNC(referenced, REFERENCED);
+#ifdef CONFIG_F2FS_FS_NODE_CACHE_COMPRESSION
+F2FS_CACHE_FLAG_TEST_FUNC(compressed, COMPRESSED);
+F2FS_CACHE_FLAG_SET_FUNC(compressed, COMPRESSED);
+F2FS_CACHE_FLAG_CLEAR_FUNC(compressed, COMPRESSED);
+#endif
 
 static inline void *cache_address(const struct f2fs_cached_block *entry)
 {
fs/f2fs/debug.c +5 -5
index 6fe606e2c70d..a6096537b495 100644
@@ -19,6 +19,7 @@
 #include "node.h"
 #include "segment.h"
 #include "gc.h"
+#include "node_cache_compress.h"
 
 static LIST_HEAD(f2fs_stat_list);
 static DEFINE_SPINLOCK(f2fs_stat_lock);
@@ -297,6 +298,7 @@ static void update_general_status(struct f2fs_sb_info *sbi)
 static void update_mem_info(struct f2fs_sb_info *sbi)
 {
 	struct f2fs_stat_info *si = F2FS_STAT(sbi);
+	struct f2fs_nc_memory node_memory;
 	int i;
 
 	if (si->base_mem)
@@ -386,11 +388,9 @@ static void update_mem_info(struct f2fs_sb_info *sbi)
 	si->cache_data_mem[F2FS_META_CACHE] =
 		(unsigned long long)META_CACHE(sbi)->num_entries * sbi->blocksize;
 
-	si->cache_entry_mem[F2FS_NODE_CACHE] =
-		(unsigned long long)NODE_CACHE(sbi)->num_entries *
-		sizeof(struct f2fs_cached_block);
-	si->cache_data_mem[F2FS_NODE_CACHE] =
-		(unsigned long long)NODE_CACHE(sbi)->num_entries * sbi->blocksize;
+	f2fs_nc_memory_usage(sbi, &node_memory);
+	si->cache_entry_mem[F2FS_NODE_CACHE] = node_memory.entry_bytes;
+	si->cache_data_mem[F2FS_NODE_CACHE] = node_memory.data_bytes;
 
 	si->cache_mem += si->cache_entry_mem[F2FS_META_CACHE] +
 			 si->cache_entry_mem[F2FS_NODE_CACHE];
fs/f2fs/f2fs.h +7 -0
index 089a62c054ea..16cc050124dd 100644
@@ -26,6 +26,10 @@
 #include <linux/part_stat.h>
 #include <linux/rw_hint.h>
 
+#ifdef CONFIG_F2FS_FS_NODE_CACHE_COMPRESSION
+struct f2fs_nc_ctx;
+#endif
+
 #include <linux/fscrypt.h>
 #include <linux/fsverity.h>
 
@@ -2106,6 +2110,9 @@ struct f2fs_sb_info {
 	struct f2fs_cached_block_list meta_blocks;
 	struct f2fs_cached_block_list node_blocks;
 	struct f2fs_cached_block_list compress_blocks;
+#ifdef CONFIG_F2FS_FS_NODE_CACHE_COMPRESSION
+	struct f2fs_nc_ctx *node_compress;
+#endif
 
 	/* internal cache flush thread */
 	struct f2fs_cache_kthread cache_thread;
fs/f2fs/node_cache_compress.c new file +303 -0

303 lines not on this page · raw message

fs/f2fs/node_cache_compress.h new file +78 -0

78 lines not on this page · raw message

fs/f2fs/node_cache_policy.h new file +23 -0
new file mode 100644
index 000000000000..efe906bfcc58
@@ -0,0 +1,23 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __F2FS_NODE_CACHE_POLICY_H__
+#define __F2FS_NODE_CACHE_POLICY_H__
+
+#include <linux/types.h>
+
+#define F2FS_NC_BUCKET_256_SIZE		256U
+#define F2FS_NC_BUCKET_512_SIZE		512U
+#define F2FS_NC_BUCKET_1024_SIZE	1024U
+#define F2FS_NC_MAX_OBJECT_SIZE		F2FS_NC_BUCKET_1024_SIZE
+
+/*
+ * Keep compressed queues in the same order as f2fs_nc_bucket_sizes[].
+ * Raw entries remain on NODE_CACHE(sbi)->lru_list.
+ */
+enum f2fs_nc_queue {
+	F2FS_NC_RAW,
+	F2FS_NC_256,
+	F2FS_NC_512,
+	F2FS_NC_1024,
+	F2FS_NC_NR_QUEUES,
+};
+#endif /* __F2FS_NODE_CACHE_POLICY_H__ */
fs/f2fs/super.c +4 -0
index 294f6f2c28a5..461209293dba 100644
@@ -32,6 +32,7 @@
 #include <linux/fserror.h>
 
 #include "f2fs.h"
+#include "node_cache_compress.h"
 #include "node.h"
 #include "segment.h"
 #include "xattr.h"
@@ -2071,6 +2072,7 @@ static void f2fs_put_super(struct super_block *sb)
 
 	f2fs_destroy_cache(COMPRESS_CACHE(sbi));
 	f2fs_destroy_cache(NODE_CACHE(sbi));
+	f2fs_nc_destroy(sbi);
 	f2fs_destroy_cache(META_CACHE(sbi));
 
 	/* Should check the page counts after dropping all node/meta pages */
@@ -5263,6 +5265,7 @@ static int f2fs_fill_super(struct super_block *sb, struct fs_context *fc)
 	f2fs_init_cache(sbi, META_CACHE(sbi), F2FS_META_CACHE);
 	f2fs_init_cache(sbi, NODE_CACHE(sbi), F2FS_NODE_CACHE);
 	f2fs_init_cache(sbi, COMPRESS_CACHE(sbi), F2FS_COMPRESS_CACHE);
+	f2fs_nc_init(sbi);
 
 	err = f2fs_get_valid_checkpoint(sbi);
 	if (err) {
@@ -5581,6 +5584,7 @@ static int f2fs_fill_super(struct super_block *sb, struct fs_context *fc)
 free_compress_cache:
 	f2fs_destroy_cache(COMPRESS_CACHE(sbi));
 	f2fs_destroy_cache(NODE_CACHE(sbi));
+	f2fs_nc_destroy(sbi);
 	f2fs_destroy_cache(META_CACHE(sbi));
 	f2fs_destroy_page_array_cache(sbi);
 free_percpu:
Signature · 1 line
2.43.0
author
#3 lore raw

RFC PATCH 3/6 f2fs: bias node cache reclaim toward raw entries

In reply to Wenjie Qi

Raw and compressed node-cache entries have very different memory costs. Counting every entry equally would overstate pressure from compressed entries and reclaim them too aggressively.

Count and scan the raw and compressed queues separately. Give raw entries their full block weight and compressed entries 25 percent of their allocation size. Use the same weights for the shrinker count and the per-queue scan quotas.

Carry rounding credit across shrinker calls, and redistribute unused quota when a queue reaches its population limit. This favors reclaiming raw entries while keeping every compressed queue reclaimable.

---
 fs/f2fs/Makefile              |   1 +
 fs/f2fs/cache.c               |   2 +-
 fs/f2fs/node_cache_compress.c |  64 ++++++++++++-
 fs/f2fs/node_cache_compress.h |  15 ++++
 fs/f2fs/node_cache_policy.c   | 163 ++++++++++++++++++++++++++++++++++
 fs/f2fs/node_cache_policy.h   |   9 ++
 fs/f2fs/shrinker.c            |   3 +-
 7 files changed, 254 insertions(+), 3 deletions(-)
 create mode 100644 fs/f2fs/node_cache_policy.c
fs/f2fs/Makefile +1 -0
index e1e4b98707e9..79252f510daf 100644
@@ -10,4 +10,5 @@ f2fs-$(CONFIG_F2FS_FS_POSIX_ACL) += acl.o
 f2fs-$(CONFIG_FS_VERITY) += verity.o
 f2fs-$(CONFIG_F2FS_FS_COMPRESSION) += compress.o
 f2fs-$(CONFIG_F2FS_FS_NODE_CACHE_COMPRESSION) += node_cache_compress.o
+f2fs-$(CONFIG_F2FS_FS_NODE_CACHE_COMPRESSION) += node_cache_policy.o
 f2fs-$(CONFIG_F2FS_IOSTAT) += iostat.o
fs/f2fs/cache.c +1 -1
index 3d1d530cdd82..480412f6c729 100644
@@ -666,7 +666,7 @@ unsigned long f2fs_shrink_cache(struct f2fs_sb_info *sbi,
 	if (freed >= nr_to_scan)
 		return freed;
 
-	freed += f2fs_do_shrink_cache(NODE_CACHE(sbi), nr_to_scan - freed);
+	freed += f2fs_nc_shrink_nodes(sbi, nr_to_scan - freed);
 	if (freed >= nr_to_scan)
 		return freed;
 
fs/f2fs/node_cache_compress.c +63 -1

77 lines not on this page · raw message

fs/f2fs/node_cache_compress.h +15 -0
index e1a9b45d67e3..e7d6b07c1c98 100644
@@ -34,6 +34,9 @@ struct list_head *f2fs_nc_queue_head(struct f2fs_cached_block_list *cache,
 unsigned int f2fs_nc_entry_queue(const struct f2fs_cached_block *entry);
 void f2fs_nc_entry_attached(struct f2fs_cached_block *entry);
 void f2fs_nc_entry_detached(struct f2fs_cached_block *entry);
+unsigned long f2fs_nc_count_nodes(struct f2fs_sb_info *sbi);
+unsigned long f2fs_nc_shrink_nodes(struct f2fs_sb_info *sbi,
+				   unsigned long nr_to_scan);
 void f2fs_nc_memory_usage(struct f2fs_sb_info *sbi,
 			  struct f2fs_nc_memory *memory);
 #else
@@ -66,6 +69,18 @@ f2fs_nc_entry_queue(const struct f2fs_cached_block *entry)
 static inline void f2fs_nc_entry_attached(struct f2fs_cached_block *entry) { }
 static inline void f2fs_nc_entry_detached(struct f2fs_cached_block *entry) { }
 
+static inline unsigned long f2fs_nc_count_nodes(struct f2fs_sb_info *sbi)
+{
+	return NODE_CACHE(sbi)->num_entries;
+}
+
+static inline unsigned long f2fs_nc_shrink_nodes(struct f2fs_sb_info *sbi,
+						 unsigned long nr_to_scan)
+{
+	return f2fs_shrink_cache_list(NODE_CACHE(sbi),
+			&NODE_CACHE(sbi)->lru_list, ULONG_MAX, nr_to_scan, NULL);
+}
+
 static inline void f2fs_nc_memory_usage(struct f2fs_sb_info *sbi,
 					struct f2fs_nc_memory *memory)
 {
fs/f2fs/node_cache_policy.c new file +163 -0

163 lines not on this page · raw message

fs/f2fs/node_cache_policy.h +9 -0
index efe906bfcc58..42af4ad1698f 100644
@@ -8,6 +8,7 @@
 #define F2FS_NC_BUCKET_512_SIZE		512U
 #define F2FS_NC_BUCKET_1024_SIZE	1024U
 #define F2FS_NC_MAX_OBJECT_SIZE		F2FS_NC_BUCKET_1024_SIZE
+#define F2FS_NC_PERCENT_MAX		100U
 
 /*
  * Keep compressed queues in the same order as f2fs_nc_bucket_sizes[].
@@ -20,4 +21,12 @@ enum f2fs_nc_queue {
 	F2FS_NC_1024,
 	F2FS_NC_NR_QUEUES,
 };
+
+u64 f2fs_nc_effective_count(const unsigned long nr[F2FS_NC_NR_QUEUES],
+			    u32 blocksize);
+void f2fs_nc_scan_quotas(const unsigned long nr[F2FS_NC_NR_QUEUES],
+			 u32 blocksize, unsigned long requested,
+		s64 credit[F2FS_NC_NR_QUEUES],
+		unsigned long quota[F2FS_NC_NR_QUEUES]);
+
 #endif /* __F2FS_NODE_CACHE_POLICY_H__ */
fs/f2fs/shrinker.c +2 -1
index 29f488531492..a4e9e61557cc 100644
@@ -11,6 +11,7 @@
 
 #include "f2fs.h"
 #include "node.h"
+#include "node_cache_compress.h"
 
 static LIST_HEAD(f2fs_list);
 static DEFINE_SPINLOCK(f2fs_list_lock);
@@ -40,7 +41,7 @@ static unsigned long __count_extent_cache(struct f2fs_sb_info *sbi,
 static unsigned long __count_cache(struct f2fs_sb_info *sbi)
 {
 	return META_CACHE(sbi)->num_entries +
-		NODE_CACHE(sbi)->num_entries +
+		f2fs_nc_count_nodes(sbi) +
 		COMPRESS_CACHE(sbi)->num_entries;
 }
 
Signature · 1 line
2.43.0
author
#4 lore raw

RFC PATCH 4/6 f2fs: restore compressed node cache entries before access

In reply to Wenjie Qi

A node-cache lookup may find a compressed entry, but existing callers expect ordinary node bytes. Restore the raw block before returning the entry to those callers.

Perform the restore under the entry lock. Validate the allocation size, compressed length, LZ4 output size and raw-block CRC before publishing the raw representation. Move a successful restore to the raw LRU tail, and keep RESTORED set until the existing footer, inode-checksum and node-type validation has completed.

A raw-buffer allocation failure leaves the compressed entry intact for a later retry. Invalid compressed data is discarded and the lookup falls back to the normal disk-read path. The entry never owns raw and compressed storage at the same time.

---
 fs/f2fs/cache.c               |  12 ++++
 fs/f2fs/cache.h               |  20 ++++++
 fs/f2fs/data.c                |   5 +-
 fs/f2fs/f2fs.h                |  10 +++
 fs/f2fs/inode.c               |  20 +++++-
 fs/f2fs/node.c                |  55 ++++++++++++---
 fs/f2fs/node_cache_compress.c | 129 ++++++++++++++++++++++++++++++++++
 fs/f2fs/node_cache_compress.h |  13 ++++
 8 files changed, 251 insertions(+), 13 deletions(-)
fs/f2fs/cache.c +12 -0
index 480412f6c729..9cb541dd5cea 100644
@@ -64,6 +64,7 @@ bool f2fs_mark_cache_dirty(struct f2fs_cached_block *entry)
 {
 	struct f2fs_cached_block_list *cache = entry->cache;
 
+	f2fs_nc_content_changed(entry);
 	f2fs_cache_set_uptodate(entry);
 
 #ifdef CONFIG_F2FS_CHECK_FS
@@ -94,6 +95,8 @@ void f2fs_drop_cache_dirty(struct f2fs_cached_block *entry)
 				F2FS_DIRTY_META : F2FS_DIRTY_NODES;
 
 	f2fs_cache_clear_uptodate(entry);
+	if (!f2fs_cache_test_compressed(entry))
+		f2fs_nc_content_changed(entry);
 
 	if (!f2fs_cache_test_and_clear_dirty(entry))
 		return;
@@ -286,7 +289,16 @@ struct f2fs_cached_block *f2fs_grab_cache(
 	entry = f2fs_insert_cache(cache, index, new);
 found:
 	if (lock) {
+		int ret;
+
 		f2fs_lock_cache(entry);
+		if (entry->cache == cache) {
+			ret = f2fs_nc_restore(entry);
+			if (ret) {
+				f2fs_put_cache(entry, true);
+				return ERR_PTR(ret);
+			}
+		}
 		/* has been truncated */
 		if (entry->cache != cache) {
 			f2fs_put_cache(entry, true);
fs/f2fs/cache.h +20 -0
index 8a1eab71b1ae..603c5f7203b7 100644
@@ -66,6 +66,7 @@ enum f2fs_cached_state {
 	F2FS_BLOCK_INLINE_DATA,		/* indicate inline data */
 #ifdef CONFIG_F2FS_FS_NODE_CACHE_COMPRESSION
 	F2FS_BLOCK_COMPRESSED,
+	F2FS_BLOCK_RESTORED,
 #endif
 };
 
@@ -151,6 +152,25 @@ F2FS_CACHE_FLAG_TEST_AND_CLEAR_FUNC(referenced, REFERENCED);
 F2FS_CACHE_FLAG_TEST_FUNC(compressed, COMPRESSED);
 F2FS_CACHE_FLAG_SET_FUNC(compressed, COMPRESSED);
 F2FS_CACHE_FLAG_CLEAR_FUNC(compressed, COMPRESSED);
+F2FS_CACHE_FLAG_TEST_FUNC(restored, RESTORED);
+F2FS_CACHE_FLAG_SET_FUNC(restored, RESTORED);
+F2FS_CACHE_FLAG_CLEAR_FUNC(restored, RESTORED);
+#else
+static inline bool f2fs_cache_test_compressed(const struct f2fs_cached_block *entry)
+{
+	return false;
+}
+
+static inline void f2fs_cache_set_compressed(struct f2fs_cached_block *entry) { }
+static inline void f2fs_cache_clear_compressed(struct f2fs_cached_block *entry) { }
+
+static inline bool f2fs_cache_test_restored(const struct f2fs_cached_block *entry)
+{
+	return false;
+}
+
+static inline void f2fs_cache_set_restored(struct f2fs_cached_block *entry) { }
+static inline void f2fs_cache_clear_restored(struct f2fs_cached_block *entry) { }
 #endif
 
 static inline void *cache_address(const struct f2fs_cached_block *entry)
fs/f2fs/data.c +4 -1
index 6d4ba5e77906..3c07fdecbd32 100644
@@ -26,6 +26,7 @@
 #include "node.h"
 #include "segment.h"
 #include "iostat.h"
+#include "node_cache_compress.h"
 #include <trace/events/f2fs.h>
 
 #define NUM_PREALLOC_POST_READ_CTXS	128
@@ -393,8 +394,10 @@ static void f2fs_cache_read_end_io(struct bio *bio)
 				entry->index, NODE_TYPE_REGULAR, true))
 			bio->bi_status = BLK_STS_IOERR;
 
-		if (bio->bi_status == BLK_STS_OK)
+		if (bio->bi_status == BLK_STS_OK) {
+			f2fs_nc_content_changed(entry);
 			f2fs_cache_set_uptodate(entry);
+		}
 
 		dec_cache_count(sbi, io_type);
 
fs/f2fs/f2fs.h +10 -0
index 16cc050124dd..a5d8ab041aa8 100644
@@ -4001,6 +4001,16 @@ int f2fs_pin_file_control(struct inode *inode, bool inc);
  */
 void f2fs_set_inode_flags(struct inode *inode);
 bool f2fs_inode_chksum_verify(struct f2fs_sb_info *sbi, struct f2fs_cached_block *entry);
+#ifdef CONFIG_F2FS_FS_NODE_CACHE_COMPRESSION
+bool f2fs_inode_chksum_valid(struct f2fs_sb_info *sbi,
+			     struct f2fs_cached_block *entry);
+#else
+static inline bool
+f2fs_inode_chksum_valid(struct f2fs_sb_info *sbi, struct f2fs_cached_block *entry)
+{
+	return true;
+}
+#endif
 void f2fs_inode_chksum_set(struct f2fs_sb_info *sbi, struct f2fs_cached_block *entry);
 struct inode *f2fs_iget(struct super_block *sb, unsigned long ino);
 struct inode *f2fs_iget_retry(struct super_block *sb, unsigned long ino);
fs/f2fs/inode.c +18 -2
index 9164a2b5d9f0..bd4a46dd7a9e 100644
@@ -168,7 +168,9 @@ static __u32 f2fs_inode_chksum(struct f2fs_sb_info *sbi, struct f2fs_cached_bloc
 	return chksum;
 }
 
-bool f2fs_inode_chksum_verify(struct f2fs_sb_info *sbi, struct f2fs_cached_block *entry)
+static bool __f2fs_inode_chksum_verify(struct f2fs_sb_info *sbi,
+				       struct f2fs_cached_block *entry,
+					bool report)
 {
 	struct f2fs_inode *ri;
 	__u32 provided, calculated;
@@ -187,7 +189,7 @@ bool f2fs_inode_chksum_verify(struct f2fs_sb_info *sbi, struct f2fs_cached_block
 	provided = le32_to_cpu(ri->i_inode_checksum);
 	calculated = f2fs_inode_chksum(sbi, entry);
 
-	if (provided != calculated)
+	if (provided != calculated && report)
 		f2fs_warn(sbi, "checksum invalid, nid = %lu, ino_of_node = %u, %x vs. %x",
 			  entry->index, ino_of_node(sbi, entry),
 			  provided, calculated);
@@ -195,6 +197,20 @@ bool f2fs_inode_chksum_verify(struct f2fs_sb_info *sbi, struct f2fs_cached_block
 	return provided == calculated;
 }
 
+bool f2fs_inode_chksum_verify(struct f2fs_sb_info *sbi,
+			      struct f2fs_cached_block *entry)
+{
+	return __f2fs_inode_chksum_verify(sbi, entry, true);
+}
+
+#ifdef CONFIG_F2FS_FS_NODE_CACHE_COMPRESSION
+bool f2fs_inode_chksum_valid(struct f2fs_sb_info *sbi,
+			     struct f2fs_cached_block *entry)
+{
+	return __f2fs_inode_chksum_verify(sbi, entry, false);
+}
+#endif
+
 void f2fs_inode_chksum_set(struct f2fs_sb_info *sbi, struct f2fs_cached_block *entry)
 {
 	struct f2fs_inode *ri = F2FS_INODE(entry);
fs/f2fs/node.c +45 -10

120 lines not on this page · raw message

fs/f2fs/node_cache_compress.c +129 -0

147 lines not on this page · raw message

fs/f2fs/node_cache_compress.h +13 -0
index e7d6b07c1c98..faeb342b9cc3 100644
@@ -29,6 +29,10 @@ size_t f2fs_nc_entry_alloc_size(struct f2fs_cached_block_list *cache);
 void f2fs_nc_init(struct f2fs_sb_info *sbi);
 void f2fs_nc_destroy(struct f2fs_sb_info *sbi);
 void f2fs_nc_free_data(struct f2fs_cached_block *entry);
+int f2fs_nc_restore(struct f2fs_cached_block *entry);
+void f2fs_nc_validation_failed(struct f2fs_cached_block *entry);
+void f2fs_nc_validation_succeeded(struct f2fs_cached_block *entry);
+void f2fs_nc_content_changed(struct f2fs_cached_block *entry);
 struct list_head *f2fs_nc_queue_head(struct f2fs_cached_block_list *cache,
 				     unsigned int queue);
 unsigned int f2fs_nc_entry_queue(const struct f2fs_cached_block *entry);
@@ -54,6 +58,15 @@ static inline void f2fs_nc_free_data(struct f2fs_cached_block *entry)
 	kfree(entry->data);
 }
 
+static inline int f2fs_nc_restore(struct f2fs_cached_block *entry)
+{
+	return 0;
+}
+
+static inline void f2fs_nc_validation_failed(struct f2fs_cached_block *entry) { }
+static inline void f2fs_nc_validation_succeeded(struct f2fs_cached_block *entry) { }
+static inline void f2fs_nc_content_changed(struct f2fs_cached_block *entry) { }
+
 static inline struct list_head *f2fs_nc_queue_head(struct f2fs_cached_block_list *cache,
 						   unsigned int queue)
 {
Signature · 1 line
2.43.0
author
#5 lore raw

RFC PATCH 5/6 f2fs: compress clean node cache entries in background

In reply to Wenjie Qi

With the compressed representation, restore path and reclaim policy in place, add background conversion of cold clean node-cache entries.

Reuse the per-superblock cache thread. Writeback and compression keep separate due times but execute serially. Each compression pass scans at most 1024 raw entries, retains at most 256 candidates and reschedules after every 32 candidates.

Compress outside the cache list and radix-tree locks, then revalidate the entry before replacing its raw block. Expose only the compression threshold and worker interval through sysfs.

---
 Documentation/ABI/testing/sysfs-fs-f2fs |  22 ++
 fs/f2fs/cache.c                         |  61 +++-
 fs/f2fs/cache.h                         |  15 +
 fs/f2fs/debug.c                         |  37 +++
 fs/f2fs/node_cache_compress.c           | 407 +++++++++++++++++++++++-
 fs/f2fs/node_cache_compress.h           |  37 +++
 fs/f2fs/node_cache_policy.c             |  48 +++
 fs/f2fs/node_cache_policy.h             |  24 +-
 fs/f2fs/sysfs.c                         |  59 ++++
 9 files changed, 691 insertions(+), 19 deletions(-)
Documentation/ABI/testing/sysfs-fs-f2fs +22 -0
index c4746c416ac2..485d4231855f 100644
@@ -1027,3 +1027,25 @@ Contact:	"Chao Yu" <[email protected]>
 Description:	This is a writable entry to control writeback interval of
 		f2fs_writeback-x:y, the range is [100, 30000], by default the value
 		is 5000, unit is ms.
+
+What:		/sys/fs/f2fs/<disk>/node_compress_interval
+Date:		September 2026
+Contact:	"Wenjie Qi" <[email protected]>
+Description:	This is a writable entry to control how often the background
+		node-cache compression worker runs. The range is [100, 30000],
+		default value is 1000, and the unit is ms. Updating the value
+		reschedules the next worker deadline but does not synchronously
+		cancel a cycle that is already running. This entry is present only
+		when CONFIG_F2FS_FS_NODE_CACHE_COMPRESSION is enabled.
+
+What:		/sys/fs/f2fs/<disk>/node_compress_threshold
+Date:		September 2026
+Contact:	"Wenjie Qi" <[email protected]>
+Description:	This is a writable entry to set the maximum compressed payload
+		length as a percentage of the filesystem block size. The range is
+		[0, 100], default value is 0, which disables background node-cache
+		compression. The effective payload limit is also capped at 1024 bytes.
+		Updating the value affects subsequent worker scheduling and cycles;
+		it does not synchronously cancel a cycle that is already running.
+		This entry is present only when
+		CONFIG_F2FS_FS_NODE_CACHE_COMPRESSION is enabled.
fs/f2fs/cache.c +45 -16

85 lines not on this page · raw message

fs/f2fs/cache.h +15 -0
index 603c5f7203b7..3c1fdc7894b7 100644
@@ -67,6 +67,7 @@ enum f2fs_cached_state {
 #ifdef CONFIG_F2FS_FS_NODE_CACHE_COMPRESSION
 	F2FS_BLOCK_COMPRESSED,
 	F2FS_BLOCK_RESTORED,
+	F2FS_BLOCK_INCOMPRESSIBLE,
 #endif
 };
 
@@ -155,6 +156,9 @@ F2FS_CACHE_FLAG_CLEAR_FUNC(compressed, COMPRESSED);
 F2FS_CACHE_FLAG_TEST_FUNC(restored, RESTORED);
 F2FS_CACHE_FLAG_SET_FUNC(restored, RESTORED);
 F2FS_CACHE_FLAG_CLEAR_FUNC(restored, RESTORED);
+F2FS_CACHE_FLAG_TEST_FUNC(incompressible, INCOMPRESSIBLE);
+F2FS_CACHE_FLAG_SET_FUNC(incompressible, INCOMPRESSIBLE);
+F2FS_CACHE_FLAG_CLEAR_FUNC(incompressible, INCOMPRESSIBLE);
 #else
 static inline bool f2fs_cache_test_compressed(const struct f2fs_cached_block *entry)
 {
@@ -171,6 +175,14 @@ static inline bool f2fs_cache_test_restored(const struct f2fs_cached_block *entr
 
 static inline void f2fs_cache_set_restored(struct f2fs_cached_block *entry) { }
 static inline void f2fs_cache_clear_restored(struct f2fs_cached_block *entry) { }
+static inline bool
+f2fs_cache_test_incompressible(const struct f2fs_cached_block *entry)
+{
+	return false;
+}
+
+static inline void f2fs_cache_set_incompressible(struct f2fs_cached_block *entry) { }
+static inline void f2fs_cache_clear_incompressible(struct f2fs_cached_block *entry) { }
 #endif
 
 static inline void *cache_address(const struct f2fs_cached_block *entry)
@@ -264,6 +276,9 @@ struct f2fs_cache_kthread {
 	struct task_struct *cache_wb_task;
 	wait_queue_head_t cache_wb_wq;
 	unsigned int cache_wb_interval;
+#ifdef CONFIG_F2FS_FS_NODE_CACHE_COMPRESSION
+	u64 next_wb_ms;
+#endif
 };
 
 int f2fs_start_cache_wb_thread(struct f2fs_sb_info *sbi);
fs/f2fs/debug.c +37 -0
index a6096537b495..984fed727a48 100644
@@ -713,6 +713,43 @@ static int stat_show(struct seq_file *s, void *v)
 		seq_printf(s, "  - compress: %4d, hit:%8d\n", si->compress_pages, si->compress_page_hit);
 		seq_printf(s, "  - nodes: %4d in %4d\n",
 			   si->ndirty_node, si->node_caches);
+#ifdef CONFIG_F2FS_FS_NODE_CACHE_COMPRESSION
+		{
+			struct f2fs_nc_stats nc;
+
+			f2fs_nc_get_stats(sbi, &nc);
+			seq_printf(s,
+				   "NodeCacheCompress: initialized=%u threshold=%u interval=%u\n",
+				nc.initialized, nc.threshold_pct, nc.interval_ms);
+			seq_printf(s,
+				   "NCQueues: raw=%llu 256=%llu 512=%llu 1024=%llu payload=%llu/%llu/%llu slots=%llu/%llu/%llu\n",
+				nc.attached[F2FS_NC_RAW], nc.attached[F2FS_NC_256],
+				nc.attached[F2FS_NC_512], nc.attached[F2FS_NC_1024],
+				nc.payload[0], nc.payload[1], nc.payload[2],
+				nc.slots[0], nc.slots[1], nc.slots[2]);
+			seq_printf(s,
+				   "NCWorker: cycles=%llu visited=%llu candidates=%llu attempts=%llu converted=%llu candidate_refs=%llu transient=%llu alloc_fail=%llu\n",
+				nc.cycles, nc.visited, nc.candidates, nc.attempts,
+				nc.converted, nc.candidate_refs,
+				nc.transient_extra_bytes, nc.allocation_failures);
+			seq_printf(s,
+				   "NCRestore: compressed_to_raw=%llu restored_hits=%llu restore_failures=%llu\n",
+				nc.compressed_to_raw, nc.restored_hits,
+				nc.restore_failures);
+			seq_printf(s,
+				   "NCReclaim: scanned=%llu/%llu/%llu/%llu freed=%llu/%llu/%llu/%llu detached=%llu/%llu/%llu/%llu\n",
+				nc.shrink_scanned[F2FS_NC_RAW],
+				nc.shrink_scanned[F2FS_NC_256],
+				nc.shrink_scanned[F2FS_NC_512],
+				nc.shrink_scanned[F2FS_NC_1024],
+				nc.shrink_freed[F2FS_NC_RAW],
+				nc.shrink_freed[F2FS_NC_256],
+				nc.shrink_freed[F2FS_NC_512],
+				nc.shrink_freed[F2FS_NC_1024],
+				nc.detached[F2FS_NC_RAW], nc.detached[F2FS_NC_256],
+				nc.detached[F2FS_NC_512], nc.detached[F2FS_NC_1024]);
+		}
+#endif
 		seq_printf(s, "  - dents: %4d in dirs:%4d (%4d)\n",
 			   si->ndirty_dent, si->ndirty_dirs, si->ndirty_all);
 		seq_printf(s, "  - data: %4d in files:%4d\n",
fs/f2fs/node_cache_compress.c +405 -2

483 lines not on this page · raw message

fs/f2fs/node_cache_compress.h +37 -0
index faeb342b9cc3..efe2eceef352 100644
@@ -13,6 +13,33 @@ struct f2fs_nc_memory {
 	u64 data_bytes;	/* Raw buffers plus compressed slab slots. */
 };
 
+/* Snapshot used by debugfs; queue arrays use enum f2fs_nc_queue. */
+struct f2fs_nc_stats {
+	/* Current queue state; payload and slots start at F2FS_NC_256. */
+	u64 attached[F2FS_NC_NR_QUEUES];
+	u64 payload[F2FS_NC_NR_QUEUES - 1];
+	u64 slots[F2FS_NC_NR_QUEUES - 1];
+	/* Cumulative statistics since mount. */
+	u64 shrink_scanned[F2FS_NC_NR_QUEUES];
+	u64 shrink_freed[F2FS_NC_NR_QUEUES];
+	u64 detached[F2FS_NC_NR_QUEUES];
+	u64 compressed_to_raw;
+	u64 restored_hits;
+	u64 restore_failures;
+	u64 cycles;
+	u64 visited;
+	u64 candidates;
+	u64 attempts;
+	u64 converted;
+	u64 candidate_refs;		/* Worker-held references right now. */
+	u64 transient_extra_bytes;	/* Temporary raw/compressed overlap. */
+	u64 allocation_failures;
+	/* Current configuration snapshot. */
+	u32 threshold_pct;
+	u32 interval_ms;
+	bool initialized;		/* A compression context is available. */
+};
+
 #ifdef CONFIG_F2FS_FS_NODE_CACHE_COMPRESSION
 /* Extended NODE_CACHE entry; base must remain the first member. */
 struct f2fs_node_cached_block {
@@ -28,6 +55,13 @@ static_assert(offsetof(struct f2fs_node_cached_block, base) == 0);
 size_t f2fs_nc_entry_alloc_size(struct f2fs_cached_block_list *cache);
 void f2fs_nc_init(struct f2fs_sb_info *sbi);
 void f2fs_nc_destroy(struct f2fs_sb_info *sbi);
+u64 f2fs_nc_next_deadline(struct f2fs_sb_info *sbi);
+void f2fs_nc_schedule_start(struct f2fs_sb_info *sbi, u64 now_ms);
+void f2fs_nc_run(struct f2fs_sb_info *sbi);
+u64 f2fs_nc_config_value(struct f2fs_sb_info *sbi,
+			 enum f2fs_nc_param id);
+int f2fs_nc_config_update(struct f2fs_sb_info *sbi,
+			  enum f2fs_nc_param id, u64 value);
 void f2fs_nc_free_data(struct f2fs_cached_block *entry);
 int f2fs_nc_restore(struct f2fs_cached_block *entry);
 void f2fs_nc_validation_failed(struct f2fs_cached_block *entry);
@@ -43,6 +77,8 @@ unsigned long f2fs_nc_shrink_nodes(struct f2fs_sb_info *sbi,
 				   unsigned long nr_to_scan);
 void f2fs_nc_memory_usage(struct f2fs_sb_info *sbi,
 			  struct f2fs_nc_memory *memory);
+void f2fs_nc_get_stats(struct f2fs_sb_info *sbi,
+		       struct f2fs_nc_stats *stats);
 #else
 static inline size_t f2fs_nc_entry_alloc_size(struct f2fs_cached_block_list *cache)
 {
@@ -101,6 +137,7 @@ static inline void f2fs_nc_memory_usage(struct f2fs_sb_info *sbi,
 			sizeof(struct f2fs_cached_block);
 	memory->data_bytes = (u64)NODE_CACHE(sbi)->num_entries * sbi->blocksize;
 }
+
 #endif
 
 #endif /* __F2FS_NODE_CACHE_COMPRESS_H__ */
fs/f2fs/node_cache_policy.c +48 -0

54 lines not on this page · raw message

fs/f2fs/node_cache_policy.h +23 -1
index 42af4ad1698f..fb305413aad6 100644
@@ -4,11 +4,17 @@
 
 #include <linux/types.h>
 
+#define F2FS_NC_PERCENT_MAX		100U
+#define F2FS_NC_DEFAULT_THRESHOLD_PCT	0U
+#define F2FS_NC_DEFAULT_INTERVAL_MS	1000U
+#define F2FS_NC_MIN_INTERVAL_MS		100U
+#define F2FS_NC_MAX_INTERVAL_MS		30000U
+#define F2FS_NC_SCAN_MAX		1024U
+#define F2FS_NC_MAX_CANDIDATES		256U
 #define F2FS_NC_BUCKET_256_SIZE		256U
 #define F2FS_NC_BUCKET_512_SIZE		512U
 #define F2FS_NC_BUCKET_1024_SIZE	1024U
 #define F2FS_NC_MAX_OBJECT_SIZE		F2FS_NC_BUCKET_1024_SIZE
-#define F2FS_NC_PERCENT_MAX		100U
 
 /*
  * Keep compressed queues in the same order as f2fs_nc_bucket_sizes[].
@@ -22,6 +28,22 @@ enum f2fs_nc_queue {
 	F2FS_NC_NR_QUEUES,
 };
 
+enum f2fs_nc_param {
+	F2FS_NC_PARAM_THRESHOLD,
+	F2FS_NC_PARAM_INTERVAL,
+};
+
+struct f2fs_nc_config {
+	u32 compression_threshold_pct;	/* Max payload percentage; 0 disables. */
+	u32 compression_interval_ms;	/* Delay between worker passes, in ms. */
+};
+
+void f2fs_nc_config_defaults(struct f2fs_nc_config *cfg);
+int f2fs_nc_config_set(struct f2fs_nc_config *out,
+		       const struct f2fs_nc_config *old, enum f2fs_nc_param id, u64 value);
+u64 f2fs_nc_config_get(const struct f2fs_nc_config *cfg,
+		       enum f2fs_nc_param id);
+
 u64 f2fs_nc_effective_count(const unsigned long nr[F2FS_NC_NR_QUEUES],
 			    u32 blocksize);
 void f2fs_nc_scan_quotas(const unsigned long nr[F2FS_NC_NR_QUEUES],
fs/f2fs/sysfs.c +59 -0

83 lines not on this page · raw message

Signature · 1 line
2.43.0
author
#6 lore raw

RFC PATCH 6/6 f2fs: give referenced node cache entries a shared second chance

In reply to Wenjie Qi

The shrinker already gives a referenced cache entry a second chance by clearing REFERENCED and moving it to the queue tail. The compression worker only skips such entries, so it can revisit the same referenced prefix on every pass.

Use the same clear-and-move rule in both paths. The worker records the original raw-list tail so entries moved during a pass are not visited again in that pass.

If an access races with compression after candidate collection, discard the temporary compressed object and give the raw entry the same second chance.

---
 fs/f2fs/cache.c               | 15 ++++++++++++---
 fs/f2fs/cache.h               |  3 +++
 fs/f2fs/debug.c               |  4 ++--
 fs/f2fs/node_cache_compress.c | 36 ++++++++++++++++++++++++++---------
 fs/f2fs/node_cache_compress.h |  1 +
 5 files changed, 45 insertions(+), 14 deletions(-)
fs/f2fs/cache.c +12 -3
index b3158f4ab45c..2b0a6eccd3af 100644
@@ -60,6 +60,17 @@ void f2fs_cache_update_tag(struct f2fs_cached_block *entry,
 	spin_unlock_irqrestore(&cache->tree_lock, flags);
 }
 
+bool f2fs_cache_clear_referenced_and_move(struct f2fs_cached_block_list *cache,
+					  struct list_head *head,
+					  struct f2fs_cached_block *entry)
+{
+	lockdep_assert_held(&cache->list_lock);
+	if (!f2fs_cache_test_and_clear_referenced(entry))
+		return false;
+	list_move_tail(&entry->list, head);
+	return true;
+}
+
 bool f2fs_mark_cache_dirty(struct f2fs_cached_block *entry)
 {
 	struct f2fs_cached_block_list *cache = entry->cache;
@@ -594,10 +605,8 @@ f2fs_shrink_cache_list(struct f2fs_cached_block_list *cache,
 		scanned++;
 
 		/* If accessed, give it a second chance to rotate to tail */
-		if (f2fs_cache_test_and_clear_referenced(entry)) {
-			list_move_tail(&entry->list, head);
+		if (f2fs_cache_clear_referenced_and_move(cache, head, entry))
 			continue;
-		}
 
 		if (f2fs_cache_test_dirty(entry) ||
 		    f2fs_cache_test_writeback(entry) ||
fs/f2fs/cache.h +3 -0
index 3c1fdc7894b7..8acbbbaf897d 100644
@@ -232,6 +232,9 @@ void f2fs_cache_wait_writeback_cond(struct f2fs_cached_block *entry,
 void f2fs_cache_wait_writeback(struct f2fs_cached_block *entry);
 void f2fs_cache_update_tag(struct f2fs_cached_block *entry,
 		unsigned int clear_from, unsigned int set_to);
+bool f2fs_cache_clear_referenced_and_move(struct f2fs_cached_block_list *cache,
+					  struct list_head *head,
+					  struct f2fs_cached_block *entry);
 struct f2fs_cached_block *f2fs_grab_cache(struct f2fs_cached_block_list *cache,
 				unsigned long index, int flags);
 void f2fs_truncate_locked_cache(struct f2fs_cached_block *entry,
fs/f2fs/debug.c +2 -2
index 984fed727a48..8625dccc2131 100644
@@ -728,9 +728,9 @@ static int stat_show(struct seq_file *s, void *v)
 				nc.payload[0], nc.payload[1], nc.payload[2],
 				nc.slots[0], nc.slots[1], nc.slots[2]);
 			seq_printf(s,
-				   "NCWorker: cycles=%llu visited=%llu candidates=%llu attempts=%llu converted=%llu candidate_refs=%llu transient=%llu alloc_fail=%llu\n",
+				   "NCWorker: cycles=%llu visited=%llu candidates=%llu attempts=%llu converted=%llu referenced_moved=%llu candidate_refs=%llu transient=%llu alloc_fail=%llu\n",
 				nc.cycles, nc.visited, nc.candidates, nc.attempts,
-				nc.converted, nc.candidate_refs,
+				nc.converted, nc.referenced_moved, nc.candidate_refs,
 				nc.transient_extra_bytes, nc.allocation_failures);
 			seq_printf(s,
 				   "NCRestore: compressed_to_raw=%llu restored_hits=%llu restore_failures=%llu\n",
fs/f2fs/node_cache_compress.c +27 -9
index 6e474fea7241..cf13110b2961 100644
@@ -147,6 +147,7 @@ struct f2fs_nc_ctx {
 	atomic64_t candidate_count;
 	atomic64_t attempts;
 	atomic64_t converted;
+	atomic64_t referenced_moved;
 	atomic64_t candidate_refs;
 	atomic64_t transient_extra_bytes;
 	atomic64_t allocation_failures;
@@ -574,7 +575,6 @@ static bool f2fs_nc_candidate(struct f2fs_cached_block *entry,
 		!f2fs_cache_test_dirty(entry) &&
 		!f2fs_cache_test_writeback(entry) &&
 		!f2fs_cache_test_locked(entry) &&
-		!f2fs_cache_test_referenced(entry) &&
 		!f2fs_cache_test_incompressible(entry) &&
 		atomic_read(&entry->refcount) == refs;
 }
@@ -601,6 +601,7 @@ f2fs_nc_compress(struct f2fs_cached_block *entry,
 	u32 crc;
 	int bucket;
 	int len;
+	bool referenced;
 
 	if (!cache || !IS_NODE_CACHE(cache) || !cfg ||
 	    f2fs_cache_test_compressed(entry))
@@ -654,9 +655,14 @@ f2fs_nc_compress(struct f2fs_cached_block *entry,
 
 	spin_lock(&cache->list_lock);
 	spin_lock_irqsave(&cache->tree_lock, flags);
+	referenced = f2fs_cache_test_referenced(entry);
+	/* A concurrent access wins; rotate the entry and discard this result. */
+	if (referenced && entry->cache == cache &&
+	    f2fs_cache_clear_referenced_and_move(cache, &cache->lru_list, entry))
+		atomic64_inc(&ctx->referenced_moved);
 	if (entry->cache != cache || entry->data != raw ||
 	    atomic_read(&entry->refcount) != 2 || f2fs_cp_error(sbi) ||
-	    f2fs_cache_test_referenced(entry) ||
+	    referenced ||
 	    !f2fs_cache_test_uptodate(entry) || f2fs_cache_test_dirty(entry) ||
 	    f2fs_cache_test_writeback(entry) ||
 	    f2fs_cache_test_incompressible(entry)) {
@@ -693,7 +699,7 @@ void f2fs_nc_run(struct f2fs_sb_info *sbi)
 	struct f2fs_nc_ctx *ctx = sbi->node_compress;
 	struct f2fs_cached_block_list *cache = NODE_CACHE(sbi);
 	struct f2fs_nc_config cfg;
-	struct f2fs_cached_block *entry;
+	struct f2fs_cached_block *entry, *next, *scan_tail;
 	unsigned long flags;
 	u64 now_ms;
 	unsigned long raw_population;
@@ -714,15 +720,26 @@ void f2fs_nc_run(struct f2fs_sb_info *sbi)
 		goto out;
 
 	spin_lock(&cache->list_lock);
-	list_for_each_entry(entry, &cache->lru_list, list) {
+	/* Do not revisit entries rotated to the tail during this pass. */
+	scan_tail = list_empty(&cache->lru_list) ? NULL :
+		list_last_entry(&cache->lru_list, struct f2fs_cached_block, list);
+	list_for_each_entry_safe(entry, next, &cache->lru_list, list) {
 		if (visited == goal || count == F2FS_NC_MAX_CANDIDATES)
 			break;
 		visited++;
-		if (!f2fs_nc_candidate(entry, cache, 1))
-			continue;
-		f2fs_cache_get(entry);
-		ctx->candidates[count++] = entry;
-		atomic64_inc(&ctx->candidate_refs);
+		if (f2fs_nc_candidate(entry, cache, 1)) {
+			if (f2fs_cache_clear_referenced_and_move(cache,
+								 &cache->lru_list,
+								 entry)) {
+				atomic64_inc(&ctx->referenced_moved);
+			} else {
+				f2fs_cache_get(entry);
+				ctx->candidates[count++] = entry;
+				atomic64_inc(&ctx->candidate_refs);
+			}
+		}
+		if (entry == scan_tail)
+			break;
 	}
 	spin_unlock(&cache->list_lock);
 	atomic64_add(visited, &ctx->visited);
@@ -890,6 +907,7 @@ void f2fs_nc_get_stats(struct f2fs_sb_info *sbi,
 	stats->candidates = atomic64_read(&ctx->candidate_count);
 	stats->attempts = atomic64_read(&ctx->attempts);
 	stats->converted = atomic64_read(&ctx->converted);
+	stats->referenced_moved = atomic64_read(&ctx->referenced_moved);
 	stats->candidate_refs = atomic64_read(&ctx->candidate_refs);
 	stats->transient_extra_bytes =
 		atomic64_read(&ctx->transient_extra_bytes);
fs/f2fs/node_cache_compress.h +1 -0
index efe2eceef352..542093f2eca7 100644
@@ -31,6 +31,7 @@ struct f2fs_nc_stats {
 	u64 candidates;
 	u64 attempts;
 	u64 converted;
+	u64 referenced_moved;
 	u64 candidate_refs;		/* Worker-held references right now. */
 	u64 transient_extra_bytes;	/* Temporary raw/compressed overlap. */
 	u64 allocation_failures;
Signature · 1 line
2.43.0