Skip to contentSkip to conversation

Guaranteed CMA

PATCH Superseded Suren Baghdasaryan 6 participants 23 messages Oct 10, 2025 – Oct 13, 2025

Subsystems (10)

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore

Suren Baghdasaryan

author reviewer
#0 lore raw

cover Guaranteed CMA

Guaranteed CMA (GCMA) is designed to improve utilization of reserved memory carveouts without compromising their advantages of:
1. Guaranteed success of allocation (as long as total allocation size is below the size of the reservation.
2. Low allocation latency.
The idea is that carved out memory when not used for its primary purpose can be donated and used as an extension of the pagecache and any donated folio can be taken back at any moment with minimal latency and guaranteed success.

To achieve this, GCMA needs to use memory that is not addressable by the kernel (can't be pinned) and that contains content that can be discarded. To provide such memory we reintroduce cleancache idea [1] with two major changes. New implementation:
1. Avoids intrusive hooks into filesystem code, limiting them to two hooks for filesystem mount/unmount events and a hook for bdev invalidation.
2. Manages inode to folio association and handles pools of donated folios inside cleancache itself, freeing backends of this burden.

Cleancache provides a simple interface to its backends which lets them donate folios to cleancache, take a folio back for own use and return the folio back to cleancache when not needed.

With cleancache in place, GCMA becomes a thin layer linking CMA allocator to cleancache, which allows existing CMA API to be used for continuous memory allocations with additional guarantees listed above. The limitation of GCMA is that its donated memory can be used only to extend file-backed pagecache. Note that both CMA and GCMA can be used at the same time.

Accounting for folios allocated from GCMA is implemented the same way as for CMA. The reasoning is that both CMA and GCMA use reserved memory for contiguous allocations with the only difference in how that memory gets donated while not in use. CMA donates its memory to the system for movable allocations with expectation that it will be returned when it is needed. GCMA donatest its memory to cleancache with the same expectation. Once CMA or GCMA use that memory for contiguous allocation, the difference between them disappears, therefore accounting at that point should not differ.

The patchset borrows some ideas and code from previous implementations of the cleancache and GCMA [2] as well as Android's reference patchset [3] implemented by Minchan Kim and used by many Android vendors.

[1] https://elixir.bootlin.com/linux/v5.16.20/source/Documentation/vm/cleancache.rst
[2] https://lore.kernel.org/lkml/[email protected]/
[3] https://android-review.googlesource.com/q/topic:%22gcma_6.12%22

Patchset is based on mm-new.

Minchan Kim (1):
mm: introduce GCMA

Suren Baghdasaryan (7):
mm: implement cleancache
mm/cleancache: add cleancache LRU for folio aging mm/cleancache: readahead support mm/cleancache: add sysfs interface mm/tests: add cleancache kunit test
add cleancache documentation
mm: integrate GCMA with CMA using dt-bindings

 Documentation/mm/cleancache.rst |  112 +++
 MAINTAINERS                     |   13 +
 block/bdev.c                    |    6 +
 fs/super.c                      |    3 +
 include/linux/cleancache.h      |   84 +++
 include/linux/cma.h             |   11 +-
 include/linux/fs.h              |    6 +
 include/linux/gcma.h            |   36 +
 include/linux/pagemap.h         |    1 +
 kernel/dma/contiguous.c         |   11 +-
 mm/Kconfig                      |   40 ++
 mm/Kconfig.debug                |   13 +
 mm/Makefile                     |    4 +
 mm/cleancache.c                 | 1144 +++++++++++++++++++++++++++++++
 mm/cleancache_sysfs.c           |  209 ++++++
 mm/cleancache_sysfs.h           |   58 ++
 mm/cma.c                        |   37 +-
 mm/cma.h                        |    1 +
 mm/cma_sysfs.c                  |   10 +
 mm/filemap.c                    |   26 +
 mm/gcma.c                       |  231 +++++++
 mm/readahead.c                  |   55 ++
 mm/tests/Makefile               |    6 +
 mm/tests/cleancache_kunit.c     |  425 ++++++++++++
 mm/truncate.c                   |    4 +
 mm/vmscan.c                     |    1 +
 26 files changed, 2534 insertions(+), 13 deletions(-)
 create mode 100644 Documentation/mm/cleancache.rst
 create mode 100644 include/linux/cleancache.h
 create mode 100644 include/linux/gcma.h
 create mode 100644 mm/cleancache.c
 create mode 100644 mm/cleancache_sysfs.c
 create mode 100644 mm/cleancache_sysfs.h
 create mode 100644 mm/gcma.c
 create mode 100644 mm/tests/Makefile
 create mode 100644 mm/tests/cleancache_kunit.c

base-commit: 70478cb9da6fc4e7b987219173ba1681d5f7dd3d

Signature · 1 line
2.51.0.740.g6adb054d12-goog
author reviewer
#1 lore raw

PATCH 1/8 mm: implement cleancache

Cleancache can be thought of as a page-granularity victim cache for clean pages that the kernel's pageframe replacement algorithm (PFRA) would like to keep around, but can't since there isn't enough memory. So when the PFRA "evicts" a page, it first attempts to use cleancache code to put the data contained in that page into "transcendent memory", memory that is not directly accessible or addressable by the kernel. Later, when the system needs to access a page in a file on disk, it first checks cleancache to see if it already contains it; if it does, the page of data is copied into the kernel and a disk access is avoided. The patchset borrows the idea, some code and documentation from previous cleancache implementation but as opposed to being a thin pass-through layer, it now implements housekeeping code to associate cleancache pages with their inodes and handling of page pools donated by the cleancache backends. If also avoids intrusive hooks into filesystem code, limiting itself to hooks in mm reclaim and page-in paths and two hooks to detect new filesystem mount/unmount events.

---
 MAINTAINERS                |   7 +
 block/bdev.c               |   6 +
 fs/super.c                 |   3 +
 include/linux/cleancache.h |  67 +++
 include/linux/fs.h         |   6 +
 include/linux/pagemap.h    |   1 +
 mm/Kconfig                 |  17 +
 mm/Makefile                |   1 +
 mm/cleancache.c            | 869 +++++++++++++++++++++++++++++++++++++
 mm/filemap.c               |  26 ++
 mm/truncate.c              |   4 +
 mm/vmscan.c                |   1 +
 12 files changed, 1008 insertions(+)
 create mode 100644 include/linux/cleancache.h
 create mode 100644 mm/cleancache.c
MAINTAINERS +7 -0
index 8f5208ad442b..de7a89cd44a0 100644
@@ -6049,6 +6049,13 @@ F:	scripts/Makefile.clang
 F:	scripts/clang-tools/
 K:	\b(?i:clang|llvm)\b
 
+CLEANCACHE
+M:	Suren Baghdasaryan <[email protected]>
+L:	[email protected]
+S:	Maintained
+F:	include/linux/cleancache.h
+F:	mm/cleancache.c
+
 CLK API
 M:	Russell King <[email protected]>
 L:	[email protected]
block/bdev.c +6 -0
index 810707cca970..8411b639d6db 100644
@@ -28,6 +28,7 @@
 #include <linux/part_stat.h>
 #include <linux/uaccess.h>
 #include <linux/stat.h>
+#include <linux/cleancache.h>
 #include "../fs/internal.h"
 #include "blk.h"
 
@@ -101,6 +102,11 @@ void invalidate_bdev(struct block_device *bdev)
 		lru_add_drain_all();	/* make sure all lru add caches are flushed */
 		invalidate_mapping_pages(mapping, 0, -1);
 	}
+	/*
+	 * 99% of the time, we don't need to flush the cleancache on the bdev.
+	 * But, for the strange corners, lets be cautious
+	 */
+	cleancache_invalidate_inode(mapping, mapping->host);
 }
 EXPORT_SYMBOL(invalidate_bdev);
 
fs/super.c +3 -0
index 5bab94fb7e03..5639dc069528 100644
@@ -31,6 +31,7 @@
 #include <linux/mutex.h>
 #include <linux/backing-dev.h>
 #include <linux/rculist_bl.h>
+#include <linux/cleancache.h>
 #include <linux/fscrypt.h>
 #include <linux/fsnotify.h>
 #include <linux/lockdep.h>
@@ -374,6 +375,7 @@ static struct super_block *alloc_super(struct file_system_type *type, int flags,
 	s->s_time_gran = 1000000000;
 	s->s_time_min = TIME64_MIN;
 	s->s_time_max = TIME64_MAX;
+	cleancache_add_fs(s);
 
 	s->s_shrink = shrinker_alloc(SHRINKER_NUMA_AWARE | SHRINKER_MEMCG_AWARE,
 				     "sb-%s", type->name);
@@ -469,6 +471,7 @@ void deactivate_locked_super(struct super_block *s)
 {
 	struct file_system_type *fs = s->s_type;
 	if (atomic_dec_and_test(&s->s_active)) {
+		cleancache_remove_fs(s);
 		shrinker_free(s->s_shrink);
 		fs->kill_sb(s);
 
include/linux/cleancache.h new file +67 -0

67 lines not on this page · raw message

include/linux/fs.h +6 -0
index 43f3ef76db46..a24e36913cda 100644
@@ -1582,6 +1582,12 @@ struct super_block {
 
 	spinlock_t		s_inode_wblist_lock;
 	struct list_head	s_inodes_wb;	/* writeback inodes */
+#ifdef CONFIG_CLEANCACHE
+	/*
+	 * Saved identifier for cleancache (CLEANCACHE_ID_INVALID means none)
+	 */
+	int cleancache_id;
+#endif
 } __randomize_layout;
 
 static inline struct user_namespace *i_user_ns(const struct inode *inode)
include/linux/pagemap.h +1 -0
index 09b581c1d878..7d9fa68ad0c9 100644
@@ -1269,6 +1269,7 @@ int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
 int filemap_add_folio(struct address_space *mapping, struct folio *folio,
 		pgoff_t index, gfp_t gfp);
 void filemap_remove_folio(struct folio *folio);
+void store_into_cleancache(struct address_space *mapping, struct folio *folio);
 void __filemap_remove_folio(struct folio *folio, void *shadow);
 void replace_page_cache_folio(struct folio *old, struct folio *new);
 void delete_from_page_cache_batch(struct address_space *mapping,
mm/Kconfig +17 -0
index 0e26f4fc8717..7e2482c522a0 100644
@@ -948,6 +948,23 @@ config USE_PERCPU_NUMA_NODE_ID
 config HAVE_SETUP_PER_CPU_AREA
 	bool
 
+config CLEANCACHE
+	bool "Enable cleancache to cache clean pages"
+	help
+	  Cleancache can be thought of as a page-granularity victim cache
+	  for clean pages that the kernel's pageframe replacement algorithm
+	  (PFRA) would like to keep around, but can't since there isn't enough
+	  memory.  So when the PFRA "evicts" a page, it first attempts to use
+	  cleancache code to put the data contained in that page into
+	  "transcendent memory", memory that is not directly accessible or
+	  addressable by the kernel and is of unknown and possibly
+	  time-varying size. When system wishes to access a page in a file
+	  on disk, it first checks cleancache to see if it already contains
+	  it; if it does, the page is copied into the kernel and a disk
+	  access is avoided.
+
+	  If unsure, say N.
+
 config CMA
 	bool "Contiguous Memory Allocator"
 	depends on MMU
mm/Makefile +1 -0
index 21abb3353550..b78073b87aea 100644
@@ -146,3 +146,4 @@ obj-$(CONFIG_SHRINKER_DEBUG) += shrinker_debug.o
 obj-$(CONFIG_EXECMEM) += execmem.o
 obj-$(CONFIG_TMPFS_QUOTA) += shmem_quota.o
 obj-$(CONFIG_PT_RECLAIM) += pt_reclaim.o
+obj-$(CONFIG_CLEANCACHE) += cleancache.o
mm/cleancache.c new file +869 -0

869 lines not on this page · raw message

mm/filemap.c +26 -0
index 893ba49808b7..6ed495960021 100644
@@ -36,6 +36,7 @@
 #include <linux/cpuset.h>
 #include <linux/hugetlb.h>
 #include <linux/memcontrol.h>
+#include <linux/cleancache.h>
 #include <linux/shmem_fs.h>
 #include <linux/rmap.h>
 #include <linux/delayacct.h>
@@ -213,6 +214,19 @@ static void filemap_unaccount_folio(struct address_space *mapping,
 		folio_account_cleaned(folio, inode_to_wb(mapping->host));
 }
 
+void store_into_cleancache(struct address_space *mapping, struct folio *folio)
+{
+	/*
+	 * If we're uptodate, flush out into the cleancache, otherwise
+	 * invalidate any existing cleancache entries.  We can't leave
+	 * stale data around in the cleancache once our page is gone.
+	 */
+	if (folio_test_uptodate(folio) && folio_test_mappedtodisk(folio))
+		cleancache_store_folio(mapping->host, folio);
+	else
+		cleancache_invalidate_folio(mapping, mapping->host, folio);
+}
+
 /*
  * Delete a page from the page cache and free it. Caller has to make
  * sure the page is locked and that nobody else uses it - or that usage
@@ -251,6 +265,9 @@ void filemap_remove_folio(struct folio *folio)
 	struct address_space *mapping = folio->mapping;
 
 	BUG_ON(!folio_test_locked(folio));
+
+	store_into_cleancache(mapping, folio);
+
 	spin_lock(&mapping->host->i_lock);
 	xa_lock_irq(&mapping->i_pages);
 	__filemap_remove_folio(folio, NULL);
@@ -324,6 +341,9 @@ void delete_from_page_cache_batch(struct address_space *mapping,
 	if (!folio_batch_count(fbatch))
 		return;
 
+	for (i = 0; i < folio_batch_count(fbatch); i++)
+		store_into_cleancache(mapping, fbatch->folios[i]);
+
 	spin_lock(&mapping->host->i_lock);
 	xa_lock_irq(&mapping->i_pages);
 	for (i = 0; i < folio_batch_count(fbatch); i++) {
@@ -2438,6 +2458,12 @@ static int filemap_read_folio(struct file *file, filler_t filler,
 	unsigned long pflags;
 	int error;
 
+	if (cleancache_restore_folio(folio->mapping->host, folio)) {
+		folio_mark_uptodate(folio);
+		folio_unlock(folio);
+		return 0;
+	}
+
 	/* Start the actual read. The read will unlock the page. */
 	if (unlikely(workingset))
 		psi_memstall_enter(&pflags);
mm/truncate.c +4 -0
index 91eb92a5ce4f..ed947314321b 100644
@@ -20,6 +20,7 @@
 #include <linux/pagevec.h>
 #include <linux/task_io_accounting_ops.h>
 #include <linux/shmem_fs.h>
+#include <linux/cleancache.h>
 #include <linux/rmap.h>
 #include "internal.h"
 
@@ -136,6 +137,7 @@ void folio_invalidate(struct folio *folio, size_t offset, size_t length)
 {
 	const struct address_space_operations *aops = folio->mapping->a_ops;
 
+	cleancache_invalidate_folio(folio->mapping, folio->mapping->host, folio);
 	if (aops->invalidate_folio)
 		aops->invalidate_folio(folio, offset, length);
 }
@@ -613,6 +615,8 @@ int folio_unmap_invalidate(struct address_space *mapping, struct folio *folio,
 	if (!filemap_release_folio(folio, gfp))
 		return -EBUSY;
 
+	cleancache_invalidate_folio(mapping, mapping->host, folio);
+
 	spin_lock(&mapping->host->i_lock);
 	xa_lock_irq(&mapping->i_pages);
 	if (folio_test_dirty(folio))
mm/vmscan.c +1 -0
index c80fcae7f2a1..5ff1009e68e0 100644
@@ -716,6 +716,7 @@ static int __remove_mapping(struct address_space *mapping, struct folio *folio,
 	if (folio_test_swapcache(folio)) {
 		ci = swap_cluster_get_and_lock_irq(folio);
 	} else {
+		store_into_cleancache(mapping, folio);
 		spin_lock(&mapping->host->i_lock);
 		xa_lock_irq(&mapping->i_pages);
 	}
Signature · 1 line
2.51.0.740.g6adb054d12-goog
author reviewer
#10 lore raw

PATCH 2/8 mm/cleancache: add cleancache LRU for folio aging

In reply to Suren Baghdasaryan

Once all folios in the cleancache are used to store data from previously evicted folios, no more data can be stored there. To avoid that situation we can drop older data and make space for new one.
Add an LRU for cleancache folios to reclaim the oldest folio when cleancache is full and we need to store a new folio.

---
 mm/cleancache.c | 90 +++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 88 insertions(+), 2 deletions(-)
mm/cleancache.c +88 -2
index 0023962de024..73a8b2655def 100644
@@ -19,6 +19,13 @@
  *
  *	ccinode->folios.xa_lock
  *		pool->lock
+ *
+ *	ccinode->folios.xa_lock
+ *		lru_lock
+ *
+ *	ccinode->folios.xa_lock
+ *		lru_lock
+ *			pool->lock
  */
 
 #define INODE_HASH_BITS		6
@@ -60,6 +67,8 @@ static struct kmem_cache *slab_inode; /* cleancache_inode slab */
 static struct cleancache_pool pools[CLEANCACHE_MAX_POOLS];
 static atomic_t nr_pools = ATOMIC_INIT(0);
 static DEFINE_SPINLOCK(pools_lock); /* protects pools */
+static LIST_HEAD(cleancache_lru);
+static DEFINE_SPINLOCK(lru_lock); /* protects cleancache_lru */
 
 /*
  * Folio attributes:
@@ -130,6 +139,7 @@ static inline bool is_folio_attached(struct folio *folio)
 /*
  * Folio pool helpers.
  *	Only detached folios are stored in the pool->folio_list.
+ *	Once a folio gets attached, it's placed on the cleancache LRU list.
  *
  * Locking:
  *	pool->folio_list is accessed under pool->lock.
@@ -181,6 +191,32 @@ static struct folio *pick_folio_from_any_pool(void)
 	return folio;
 }
 
+/* Folio LRU helpers. Only attached folios are stored in the cleancache_lru. */
+static void add_folio_to_lru(struct folio *folio)
+{
+	VM_BUG_ON(!list_empty(&folio->lru));
+
+	spin_lock(&lru_lock);
+	list_add(&folio->lru, &cleancache_lru);
+	spin_unlock(&lru_lock);
+}
+
+static void rotate_lru_folio(struct folio *folio)
+{
+	spin_lock(&lru_lock);
+	if (!list_empty(&folio->lru))
+		list_move(&folio->lru, &cleancache_lru);
+	spin_unlock(&lru_lock);
+}
+
+static void delete_folio_from_lru(struct folio *folio)
+{
+	spin_lock(&lru_lock);
+	if (!list_empty(&folio->lru))
+		list_del_init(&folio->lru);
+	spin_unlock(&lru_lock);
+}
+
 /* FS helpers */
 static struct cleancache_fs *get_fs(int fs_id)
 {
@@ -316,6 +352,7 @@ static void erase_folio_from_inode(struct cleancache_inode *ccinode,
 
 	removed = __xa_erase(&ccinode->folios, offset);
 	VM_BUG_ON(!removed);
+	delete_folio_from_lru(folio);
 	remove_inode_if_empty(ccinode);
 }
 
@@ -413,6 +450,48 @@ static struct cleancache_inode *add_and_get_inode(struct cleancache_fs *fs,
 	return ccinode;
 }
 
+static struct folio *reclaim_folio_from_lru(void)
+{
+	struct cleancache_inode *ccinode;
+	unsigned long offset;
+	struct folio *folio;
+
+again:
+	spin_lock(&lru_lock);
+	if (list_empty(&cleancache_lru)) {
+		spin_unlock(&lru_lock);
+		return NULL;
+	}
+	ccinode = NULL;
+	/* Get the ccinode of the folio at the LRU tail */
+	list_for_each_entry_reverse(folio, &cleancache_lru, lru) {
+		struct cleancache_pool *pool = folio_pool(folio);
+
+		/* Find and get ccinode */
+		spin_lock(&pool->lock);
+		folio_attachment(folio, &ccinode, &offset);
+		if (ccinode && !get_inode(ccinode))
+			ccinode = NULL;
+		spin_unlock(&pool->lock);
+		if (ccinode)
+			break;
+	}
+	spin_unlock(&lru_lock);
+
+	if (!ccinode)
+		return NULL; /* No ccinode to reclaim */
+
+	if (!isolate_folio_from_inode(ccinode, offset, folio)) {
+		/* Retry if the folio got erased from the ccinode */
+		put_inode(ccinode);
+		goto again;
+	}
+
+	put_inode(ccinode);
+
+	return folio;
+}
+
 static void copy_folio_content(struct folio *from, struct folio *to)
 {
 	void *src = kmap_local_folio(from, 0);
@@ -468,14 +547,19 @@ static bool store_into_inode(struct cleancache_fs *fs,
 			move_folio_from_inode_to_pool(ccinode, offset, stored_folio);
 			goto out_unlock;
 		}
+		rotate_lru_folio(stored_folio);
 	} else {
 		if (!workingset)
 			goto out_unlock;
 
 		stored_folio = pick_folio_from_any_pool();
 		if (!stored_folio) {
-			/* No free folios, TODO: try reclaiming */
-			goto out_unlock;
+			/* No free folios, try reclaiming */
+			xa_unlock(&ccinode->folios);
+			stored_folio = reclaim_folio_from_lru();
+			xa_lock(&ccinode->folios);
+			if (!stored_folio)
+				goto out_unlock;
 		}
 
 		if (!store_folio_in_inode(ccinode, offset, stored_folio)) {
@@ -487,6 +571,7 @@ static bool store_into_inode(struct cleancache_fs *fs,
 			spin_unlock(&pool->lock);
 			goto out_unlock;
 		}
+		add_folio_to_lru(stored_folio);
 	}
 	copy_folio_content(folio, stored_folio);
 
@@ -516,6 +601,7 @@ static bool load_from_inode(struct cleancache_fs *fs,
 	xa_lock(&ccinode->folios);
 	stored_folio = xa_load(&ccinode->folios, offset);
 	if (stored_folio) {
+		rotate_lru_folio(stored_folio);
 		copy_folio_content(stored_folio, folio);
 		ret = true;
 	}
Signature · 1 line
2.51.0.740.g6adb054d12-goog
author reviewer
#11 lore raw

PATCH 3/8 mm/cleancache: readahead support

In reply to Suren Baghdasaryan

Restore pages from the cleancache during readahead operation.

---
 include/linux/cleancache.h | 17 +++++++++++
 mm/cleancache.c            | 59 ++++++++++++++++++++++++++++++++++++++
 mm/readahead.c             | 55 +++++++++++++++++++++++++++++++++++
 3 files changed, 131 insertions(+)
include/linux/cleancache.h +17 -0
index 458a7a25a8af..28b6d7b25964 100644
@@ -11,6 +11,7 @@
 
 #define CLEANCACHE_KEY_MAX	6
 
+struct cleancache_inode;
 
 #ifdef CONFIG_CLEANCACHE
 
@@ -24,6 +25,14 @@ bool cleancache_invalidate_folio(struct address_space *mapping,
 bool cleancache_invalidate_inode(struct address_space *mapping,
 				 struct inode *inode);
 
+struct cleancache_inode *
+cleancache_start_inode_walk(struct address_space *mapping,
+			    struct inode *inode,
+			    unsigned long count);
+void cleancache_end_inode_walk(struct cleancache_inode *ccinode);
+bool cleancache_restore_from_inode(struct cleancache_inode *ccinode,
+				   struct folio *folio);
+
 /*
  * Backend API
  *
@@ -53,6 +62,14 @@ static inline bool cleancache_invalidate_folio(struct address_space *mapping,
 static inline bool cleancache_invalidate_inode(struct address_space *mapping,
 					       struct inode *inode)
 		{ return false; }
+static inline struct cleancache_inode *
+cleancache_start_inode_walk(struct address_space *mapping, struct inode *inode,
+			    unsigned long count)
+		{ return NULL; }
+static inline void cleancache_end_inode_walk(struct cleancache_inode *ccinode) {}
+static inline bool cleancache_restore_from_inode(struct cleancache_inode *ccinode,
+						 struct folio *folio)
+		{ return false; }
 static inline int cleancache_backend_register_pool(const char *name)
 		{ return -EOPNOTSUPP; }
 static inline int cleancache_backend_get_folio(int pool_id, struct folio *folio)
mm/cleancache.c +59 -0

65 lines not on this page · raw message

mm/readahead.c +55 -0

73 lines not on this page · raw message

Signature · 1 line
2.51.0.740.g6adb054d12-goog
author reviewer
#12 lore raw

PATCH 4/8 mm/cleancache: add sysfs interface

In reply to Suren Baghdasaryan

Create sysfs API under /sys/kernel/mm/cleancache/ to report the following metrics:

  stored      - number of successful cleancache folio stores
  skipped     - number of folios skipped during cleancache store operation
  restored    - number of successful cleancache folio restore operations
  missed      - number of failed cleancache folio restore operations
  reclaimed   - number of folios dropped due to their age
  recalled    - number of folios dropped because cleancache backend took

them back
invalidated - number of folios dropped due to invalidation
cached - number of folios currently cached in the cleancache

In addition each pool creates a /sys/kernel/mm/cleancache/<pool name> directory containing the following metrics:

  size        - number of folios in the pool
  cached      - number of folios currently cached in the pool
  recalled    - number of folios dropped from the pool because cleancache

backend took them back

---
 MAINTAINERS           |   2 +
 mm/Kconfig            |   8 ++
 mm/Makefile           |   1 +
 mm/cleancache.c       | 113 +++++++++++++++++++++--
 mm/cleancache_sysfs.c | 209 ++++++++++++++++++++++++++++++++++++++++++
 mm/cleancache_sysfs.h |  58 ++++++++++++
 6 files changed, 383 insertions(+), 8 deletions(-)
 create mode 100644 mm/cleancache_sysfs.c
 create mode 100644 mm/cleancache_sysfs.h
MAINTAINERS +2 -0
index de7a89cd44a0..f66307cd9c4b 100644
@@ -6055,6 +6055,8 @@ L:	[email protected]
 S:	Maintained
 F:	include/linux/cleancache.h
 F:	mm/cleancache.c
+F:	mm/cleancache_sysfs.c
+F:	mm/cleancache_sysfs.h
 
 CLK API
 M:	Russell King <[email protected]>
mm/Kconfig +8 -0
index 7e2482c522a0..9f4da8a848f4 100644
@@ -965,6 +965,14 @@ config CLEANCACHE
 
 	  If unsure, say N.
 
+config CLEANCACHE_SYSFS
+	bool "Cleancache information through sysfs interface"
+	depends on CLEANCACHE && SYSFS
+	help
+	  This option exposes sysfs attributes to get information from
+	  cleancache. The user space can use the interface for query cleancache
+	  and individual cleancache pool metrics.
+
 config CMA
 	bool "Contiguous Memory Allocator"
 	depends on MMU
mm/Makefile +1 -0
index b78073b87aea..a7a635f762ee 100644
@@ -147,3 +147,4 @@ obj-$(CONFIG_EXECMEM) += execmem.o
 obj-$(CONFIG_TMPFS_QUOTA) += shmem_quota.o
 obj-$(CONFIG_PT_RECLAIM) += pt_reclaim.o
 obj-$(CONFIG_CLEANCACHE) += cleancache.o
+obj-$(CONFIG_CLEANCACHE_SYSFS)	+= cleancache_sysfs.o
mm/cleancache.c +105 -8

275 lines not on this page · raw message

mm/cleancache_sysfs.c new file +209 -0

209 lines not on this page · raw message

mm/cleancache_sysfs.h new file +58 -0

58 lines not on this page · raw message

Signature · 1 line
2.51.0.740.g6adb054d12-goog
author reviewer
#13 lore raw

PATCH 5/8 mm/tests: add cleancache kunit test

In reply to Suren Baghdasaryan

Introduce a kunit test that creates fake inodes, fills them with folios with predefined content, registers a cleancache pool, allocates and donates folios to the new pool. After this initialization it runs several scenarios:
1. cleancache_restore_test - stores fake inode pages into cleancache, then restores them into auxiliary folios and checks restored content;
2. cleancache_invalidate_test - stores a folio, successfully restores it, invalidates it and tries to restore again expecting a failure;
3. cleancache_reclaim_test - fills up the cleancache, stores one more folio and verifies that the oldest folio got reclaimed;
4. cleancache_backend_api_test - takes all donated folios and puts them back verifying the results;

---
 MAINTAINERS                 |   1 +
 mm/Kconfig.debug            |  13 ++
 mm/Makefile                 |   1 +
 mm/cleancache.c             |  35 ++-
 mm/tests/Makefile           |   6 +
 mm/tests/cleancache_kunit.c | 425 ++++++++++++++++++++++++++++++++++++
 6 files changed, 480 insertions(+), 1 deletion(-)
 create mode 100644 mm/tests/Makefile
 create mode 100644 mm/tests/cleancache_kunit.c
MAINTAINERS +1 -0
index f66307cd9c4b..1c97227e7ffa 100644
@@ -6057,6 +6057,7 @@ F:	include/linux/cleancache.h
 F:	mm/cleancache.c
 F:	mm/cleancache_sysfs.c
 F:	mm/cleancache_sysfs.h
+F:	mm/tests/cleancache_kunit.c
 
 CLK API
 M:	Russell King <[email protected]>
mm/Kconfig.debug +13 -0
index 32b65073d0cc..c3482f7bc977 100644
@@ -309,3 +309,16 @@ config PER_VMA_LOCK_STATS
 	  overhead in the page fault path.
 
 	  If in doubt, say N.
+
+config CLEANCACHE_KUNIT
+	tristate "KUnit test for cleancache" if !KUNIT_ALL_TESTS
+	depends on KUNIT
+	depends on CLEANCACHE
+	default KUNIT_ALL_TESTS
+	help
+	  This builds the cleancache unit test.
+	  Tests the clencache functionality.
+	  For more information on KUnit and unit tests in general please refer
+	  to the KUnit documentation in Documentation/dev-tools/kunit/.
+
+	  If unsure, say N.
mm/Makefile +1 -0
index a7a635f762ee..845841a140e3 100644
@@ -70,6 +70,7 @@ obj-y += init-mm.o
 obj-y += memblock.o
 obj-y += $(memory-hotplug-y)
 obj-y += slub.o
+obj-y += tests/
 
 ifdef CONFIG_MMU
 	obj-$(CONFIG_ADVISE_SYSCALLS)	+= madvise.o
mm/cleancache.c +34 -1
index 56dce7e03709..fd18486b0407 100644
@@ -11,6 +11,8 @@
 #include <linux/slab.h>
 #include <linux/workqueue.h>
 #include <linux/xarray.h>
+#include <kunit/test-bug.h>
+#include <kunit/test.h>
 
 #include "cleancache_sysfs.h"
 
@@ -74,6 +76,28 @@ static DEFINE_SPINLOCK(pools_lock); /* protects pools */
 static LIST_HEAD(cleancache_lru);
 static DEFINE_SPINLOCK(lru_lock); /* protects cleancache_lru */
 
+#if IS_ENABLED(CONFIG_CLEANCACHE_KUNIT)
+
+static bool is_pool_allowed(int pool_id)
+{
+	struct kunit *test = kunit_get_current_test();
+
+	/* Restrict kunit tests to using only the test pool */
+	return test && *((int *)test->priv) == pool_id;
+}
+
+#else /* CONFIG_CLEANCACHE_KUNIT */
+
+static bool is_pool_allowed(int pool_id) { return true; }
+
+#endif /* CONFIG_CLEANCACHE_KUNIT */
+
+#if IS_MODULE(CONFIG_CLEANCACHE_KUNIT)
+#define EXPORT_SYMBOL_FOR_KUNIT(x) EXPORT_SYMBOL(x)
+#else
+#define EXPORT_SYMBOL_FOR_KUNIT(x)
+#endif
+
 /*
  * Folio attributes:
  *	folio->_mapcount - pool_id
@@ -184,7 +208,7 @@ static struct folio *pick_folio_from_any_pool(void)
 	for (int i = 0; i < count; i++) {
 		pool = &pools[i];
 		spin_lock(&pool->lock);
-		if (!list_empty(&pool->folio_list)) {
+		if (!list_empty(&pool->folio_list) && is_pool_allowed(i)) {
 			folio = list_last_entry(&pool->folio_list,
 						struct folio, lru);
 			WARN_ON(!remove_folio_from_pool(folio, pool));
@@ -747,6 +771,7 @@ void cleancache_add_fs(struct super_block *sb)
 err:
 	sb->cleancache_id = CLEANCACHE_ID_INVALID;
 }
+EXPORT_SYMBOL_FOR_KUNIT(cleancache_add_fs);
 
 void cleancache_remove_fs(struct super_block *sb)
 {
@@ -766,6 +791,7 @@ void cleancache_remove_fs(struct super_block *sb)
 	/* free the object */
 	put_fs(fs);
 }
+EXPORT_SYMBOL_FOR_KUNIT(cleancache_remove_fs);
 
 bool cleancache_store_folio(struct inode *inode, struct folio *folio)
 {
@@ -795,6 +821,7 @@ bool cleancache_store_folio(struct inode *inode, struct folio *folio)
 
 	return ret;
 }
+EXPORT_SYMBOL_FOR_KUNIT(cleancache_store_folio);
 
 bool cleancache_restore_folio(struct inode *inode, struct folio *folio)
 {
@@ -822,6 +849,7 @@ bool cleancache_restore_folio(struct inode *inode, struct folio *folio)
 
 	return ret;
 }
+EXPORT_SYMBOL_FOR_KUNIT(cleancache_restore_folio);
 
 bool cleancache_invalidate_folio(struct address_space *mapping,
 				 struct inode *inode, struct folio *folio)
@@ -853,6 +881,7 @@ bool cleancache_invalidate_folio(struct address_space *mapping,
 
 	return ret;
 }
+EXPORT_SYMBOL_FOR_KUNIT(cleancache_invalidate_folio);
 
 bool cleancache_invalidate_inode(struct address_space *mapping,
 				 struct inode *inode)
@@ -877,6 +906,7 @@ bool cleancache_invalidate_inode(struct address_space *mapping,
 
 	return count > 0;
 }
+EXPORT_SYMBOL_FOR_KUNIT(cleancache_invalidate_inode);
 
 struct cleancache_inode *
 cleancache_start_inode_walk(struct address_space *mapping, struct inode *inode,
@@ -906,6 +936,7 @@ cleancache_start_inode_walk(struct address_space *mapping, struct inode *inode,
 
 	return ccinode;
 }
+EXPORT_SYMBOL_FOR_KUNIT(cleancache_start_inode_walk);
 
 void cleancache_end_inode_walk(struct cleancache_inode *ccinode)
 {
@@ -914,6 +945,7 @@ void cleancache_end_inode_walk(struct cleancache_inode *ccinode)
 	put_inode(ccinode);
 	put_fs(fs);
 }
+EXPORT_SYMBOL_FOR_KUNIT(cleancache_end_inode_walk);
 
 bool cleancache_restore_from_inode(struct cleancache_inode *ccinode,
 				   struct folio *folio)
@@ -940,6 +972,7 @@ bool cleancache_restore_from_inode(struct cleancache_inode *ccinode,
 
 	return ret;
 }
+EXPORT_SYMBOL_FOR_KUNIT(cleancache_restore_from_inode);
 
 /* Backend API */
 /*
mm/tests/Makefile new file +6 -0
new file mode 100644
index 000000000000..fac2e964b4d5
@@ -0,0 +1,6 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# Makefile for tests of kernel mm subsystem.
+
+# KUnit tests
+obj-$(CONFIG_CLEANCACHE_KUNIT) += cleancache_kunit.o
mm/tests/cleancache_kunit.c new file +425 -0

425 lines not on this page · raw message

Signature · 1 line
2.51.0.740.g6adb054d12-goog
author reviewer
#16 lore raw

PATCH 6/8 add cleancache documentation

In reply to Suren Baghdasaryan

Document cleancache, it's APIs and sysfs interface.

---
 Documentation/mm/cleancache.rst | 112 ++++++++++++++++++++++++++++++++
 MAINTAINERS                     |   1 +
 2 files changed, 113 insertions(+)
 create mode 100644 Documentation/mm/cleancache.rst
Documentation/mm/cleancache.rst new file +112 -0
new file mode 100644
index 000000000000..deaf7de51829
@@ -0,0 +1,112 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+==========
+Cleancache
+==========
+
+Motivation
+==========
+
+Cleancache is a feature to utilize unused reserved memory for extending
+page cache.
+
+Cleancache can be thought of as a folio-granularity victim cache for clean
+file-backed pages that the kernel's pageframe replacement algorithm (PFRA)
+would like to keep around, but can't since there isn't enough memory. So
+when the PFRA "evicts" a folio, it stores the data contained in the folio
+into cleancache memory which is not directly accessible or addressable by
+the kernel (transcendent memory) and is of unknown and possibly
+time-varying size.
+
+Later, when a filesystem wishes to access a folio in a file on disk, it
+first checks cleancache to see if it already contains required data; if it
+does, the folio data is copied into the kernel and a disk access is
+avoided.
+
+The memory cleancache uses is donated by other system components, which
+reserve memory not directly addressable by the kernel. By donating this
+memory to cleancache, the memory owner enables its utilization while it
+is not used. Memory donation is done using cleancache backend API and any
+donated memory can be taken back at any time by its donor without no delay
+and with guarantees success. Since cleancache uses this memory only to
+store clean file-backed data, it can be dropped at any time and therefore
+the donor's request to take back the memory can be always satisfied.
+
+Implementation Overview
+=======================
+
+Cleancache "backend" (donor that provides transcendent memory), registers
+itself with cleancache "frontend" and received a unique pool_id which it
+can use in all later API calls to identify the pool of folios it donates.
+Once registered, backend can call cleancache_backend_put_folio() or
+cleancache_backend_put_folios() to donate memory to cleancache. Note that
+cleancache currently supports only 0-order folios and will not accept
+larger-order ones. Once the backend needs that memory back, it can get it
+by calling cleancache_backend_get_folio(). Only the original backend can
+take the folio it donated from the cleancache.
+
+Kernel uses cleancache by first calling cleancache_add_fs() to register
+each file system and then using a combination of cleancache_store_folio(),
+cleancache_restore_folio(), cleancache_invalidate_{folio|inode} to store,
+restore and invalidate folio content.
+cleancache_{start|end}_inode_walk() are used to walk over folios inside
+an inode and cleancache_restore_from_inode() is used to restore folios
+during such walks.
+
+From kernel's point of view folios which are copied into cleancache have
+an indefinite lifetime which is completely unknowable by the kernel and so
+may or may not still be in cleancache at any later time. Thus, as its name
+implies, cleancache is not suitable for dirty folios. Cleancache has
+complete discretion over what folios to preserve and what folios to discard
+and when.
+
+Cleancache Performance Metrics
+==============================
+
+If CONFIG_CLEANCACHE_SYSFS is enabled, monitoring of cleancache performance
+can be done via sysfs in the `/sys/kernel/mm/cleancache` directory.
+The effectiveness of cleancache can be measured (across all filesystems)
+with provided stats.
+Global stats are published directly under `/sys/kernel/mm/cleancache` and
+include:
+
+``stored``
+	number of successful cleancache folio stores.
+
+``skipped``
+	number of folios skipped during cleancache store operation.
+
+``restored``
+	number of successful cleancache folio restore operations.
+
+``missed``
+	number of failed cleancache folio restore operations.
+
+``reclaimed``
+	number of folios reclaimed from the cleancache due to insufficient
+	memory.
+
+``recalled``
+	number of times cleancache folio content was discarded as a result
+	of the cleancache backend taking the folio back.
+
+``invalidated``
+	number of times cleancache folio content was discarded as a result
+	of invalidation.
+
+``cached``
+	number of folios currently cached in the cleancache.
+
+Per-pool stats are published under `/sys/kernel/mm/cleancache/<pool name>`
+where "pool name" is the name pool was registered under. These stats
+include:
+
+``size``
+	number of folios donated to this pool.
+
+``cached``
+	number of folios currently cached in the pool.
+
+``recalled``
+	number of times cleancache folio content was discarded as a result
+	of the cleancache backend taking the folio back from the pool.
MAINTAINERS +1 -0
index 1c97227e7ffa..441e68c94177 100644
@@ -6053,6 +6053,7 @@ CLEANCACHE
 M:	Suren Baghdasaryan <[email protected]>
 L:	[email protected]
 S:	Maintained
+F:	Documentation/mm/cleancache.rst
 F:	include/linux/cleancache.h
 F:	mm/cleancache.c
 F:	mm/cleancache_sysfs.c
Signature · 1 line
2.51.0.740.g6adb054d12-goog
author reviewer
#19 lore raw

PATCH 7/8 mm: introduce GCMA

In reply to Suren Baghdasaryan

From: Minchan Kim <[email protected]>

This patch introduces GCMA (Guaranteed Contiguous Memory Allocator) cleacache backend which reserves some amount of memory at the boot and then donates it to store clean file-backed pages in the cleancache. GCMA aims to guarantee contiguous memory allocation success as well as low and deterministic allocation latency.

Notes:
Originally, the idea was posted by SeongJae Park and Minchan Kim [1]. Later Minchan reworked it to be used in Android as a reference for Android vendors to use [2].

[1] https://lwn.net/Articles/619865/
[2] https://android-review.googlesource.com/q/topic:%22gcma_6.12%22

---
 MAINTAINERS          |   2 +
 include/linux/gcma.h |  36 +++++++
 mm/Kconfig           |  15 +++
 mm/Makefile          |   1 +
 mm/gcma.c            | 231 +++++++++++++++++++++++++++++++++++++++++++
 5 files changed, 285 insertions(+)
 create mode 100644 include/linux/gcma.h
 create mode 100644 mm/gcma.c
MAINTAINERS +2 -0
index 441e68c94177..95b5ad26ec11 100644
@@ -16361,6 +16361,7 @@ F:	Documentation/admin-guide/mm/
 F:	Documentation/mm/
 F:	include/linux/cma.h
 F:	include/linux/dmapool.h
+F:	include/linux/gcma.h
 F:	include/linux/ioremap.h
 F:	include/linux/memory-tiers.h
 F:	include/linux/page_idle.h
@@ -16372,6 +16373,7 @@ F:	mm/dmapool.c
 F:	mm/dmapool_test.c
 F:	mm/early_ioremap.c
 F:	mm/fadvise.c
+F:	mm/gcma.c
 F:	mm/ioremap.c
 F:	mm/mapping_dirty_helpers.c
 F:	mm/memory-tiers.c
include/linux/gcma.h new file +36 -0
new file mode 100644
index 000000000000..20b2c85de87b
@@ -0,0 +1,36 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __GCMA_H__
+#define __GCMA_H__
+
+#include <linux/types.h>
+
+#ifdef CONFIG_GCMA
+
+int gcma_register_area(const char *name,
+		       unsigned long start_pfn, unsigned long count);
+
+/*
+ * NOTE: allocated pages are still marked reserved and when freeing them
+ * the caller should ensure they are isolated and not referenced by anyone
+ * other than the caller.
+ */
+int gcma_alloc_range(unsigned long start_pfn, unsigned long count, gfp_t gfp);
+int gcma_free_range(unsigned long start_pfn, unsigned long count);
+
+#else /* CONFIG_GCMA */
+
+static inline int gcma_register_area(const char *name,
+				     unsigned long start_pfn,
+				     unsigned long count)
+		{ return -EOPNOTSUPP; }
+static inline int gcma_alloc_range(unsigned long start_pfn,
+				   unsigned long count, gfp_t gfp)
+		{ return -EOPNOTSUPP; }
+
+static inline int gcma_free_range(unsigned long start_pfn,
+				   unsigned long count)
+		{ return -EOPNOTSUPP; }
+
+#endif /* CONFIG_GCMA */
+
+#endif /* __GCMA_H__ */
mm/Kconfig +15 -0
index 9f4da8a848f4..41ce5ef8db55 100644
@@ -1013,6 +1013,21 @@ config CMA_AREAS
 
 	  If unsure, leave the default value "8" in UMA and "20" in NUMA.
 
+config GCMA
+       bool "GCMA (Guaranteed Contiguous Memory Allocator)"
+       depends on CLEANCACHE
+	help
+	  This enables the Guaranteed Contiguous Memory Allocator to allow
+	  low latency guaranteed contiguous memory allocations. Memory
+	  reserved by GCMA is donated to cleancache to be used as pagecache
+	  extension. Once GCMA allocation is requested, necessary pages are
+	  taken back from the cleancache and used to satisfy the request.
+	  Cleancache guarantees low latency successful allocation as long
+	  as the total size of GCMA allocations does not exceed the size of
+	  the memory donated to the cleancache.
+
+	  If unsure, say "N".
+
 #
 # Select this config option from the architecture Kconfig, if available, to set
 # the max page order for physically contiguous allocations.
mm/Makefile +1 -0
index 845841a140e3..05aee66a8b07 100644
@@ -149,3 +149,4 @@ obj-$(CONFIG_TMPFS_QUOTA) += shmem_quota.o
 obj-$(CONFIG_PT_RECLAIM) += pt_reclaim.o
 obj-$(CONFIG_CLEANCACHE) += cleancache.o
 obj-$(CONFIG_CLEANCACHE_SYSFS)	+= cleancache_sysfs.o
+obj-$(CONFIG_GCMA)	+= gcma.o
mm/gcma.c new file +231 -0

231 lines not on this page · raw message

Signature · 1 line
2.51.0.740.g6adb054d12-goog
author reviewer
#22 lore raw

PATCH 8/8 mm: integrate GCMA with CMA using dt-bindings

In reply to Suren Baghdasaryan

Introduce a new "guarantee" property for shared-dma-pool to enable GCMA-backed memory pools. Memory allocations from such pools will have low latency and will be guaranteed to succeed as long as there is contiguous space inside the reservation.
dt-schema for shared-dma-pool [1] will need to be updated once this patch is accepted.

[1] https://github.com/devicetree-org/dt-schema/blob/main/dtschema/schemas/reserved-memory/shared-dma-pool.yaml

---
 include/linux/cma.h     | 11 +++++++++--
 kernel/dma/contiguous.c | 11 ++++++++++-
 mm/Kconfig              |  2 +-
 mm/cma.c                | 37 +++++++++++++++++++++++++++----------
 mm/cma.h                |  1 +
 mm/cma_sysfs.c          | 10 ++++++++++
 mm/gcma.c               |  2 +-
 7 files changed, 59 insertions(+), 15 deletions(-)
include/linux/cma.h +9 -2
index 62d9c1cf6326..3ec2e76a8666 100644
@@ -43,10 +43,17 @@ static inline int __init cma_declare_contiguous(phys_addr_t base,
 extern int __init cma_declare_contiguous_multi(phys_addr_t size,
 			phys_addr_t align, unsigned int order_per_bit,
 			const char *name, struct cma **res_cma, int nid);
-extern int cma_init_reserved_mem(phys_addr_t base, phys_addr_t size,
+extern int __cma_init_reserved_mem(phys_addr_t base, phys_addr_t size,
 					unsigned int order_per_bit,
 					const char *name,
-					struct cma **res_cma);
+					struct cma **res_cma, bool gcma);
+static inline int cma_init_reserved_mem(phys_addr_t base, phys_addr_t size,
+					unsigned int order_per_bit,
+					const char *name,
+					struct cma **res_cma)
+{
+	return __cma_init_reserved_mem(base, size, order_per_bit, name, res_cma, false);
+}
 extern struct page *cma_alloc(struct cma *cma, unsigned long count, unsigned int align,
 			      bool no_warn);
 extern bool cma_pages_valid(struct cma *cma, const struct page *pages, unsigned long count);
kernel/dma/contiguous.c +10 -1
index d9b9dcba6ff7..73a699ef0377 100644
@@ -461,6 +461,7 @@ static int __init rmem_cma_setup(struct reserved_mem *rmem)
 	unsigned long node = rmem->fdt_node;
 	bool default_cma = of_get_flat_dt_prop(node, "linux,cma-default", NULL);
 	struct cma *cma;
+	bool gcma;
 	int err;
 
 	if (size_cmdline != -1 && default_cma) {
@@ -478,7 +479,15 @@ static int __init rmem_cma_setup(struct reserved_mem *rmem)
 		return -EINVAL;
 	}
 
-	err = cma_init_reserved_mem(rmem->base, rmem->size, 0, rmem->name, &cma);
+	gcma = !!of_get_flat_dt_prop(node, "guarantee", NULL);
+#ifndef CONFIG_GCMA
+	if (gcma) {
+		pr_err("Reserved memory: unable to setup GCMA region, GCMA is not enabled\n");
+		return -EINVAL;
+	}
+#endif
+	err = __cma_init_reserved_mem(rmem->base, rmem->size, 0, rmem->name,
+				      &cma, gcma);
 	if (err) {
 		pr_err("Reserved memory: unable to setup CMA region\n");
 		return err;
mm/Kconfig +1 -1
index 41ce5ef8db55..729f150369cc 100644
@@ -1015,7 +1015,7 @@ config CMA_AREAS
 
 config GCMA
        bool "GCMA (Guaranteed Contiguous Memory Allocator)"
-       depends on CLEANCACHE
+       depends on CLEANCACHE && CMA
 	help
 	  This enables the Guaranteed Contiguous Memory Allocator to allow
 	  low latency guaranteed contiguous memory allocations. Memory
mm/cma.c +27 -10
index 813e6dc7b095..71fb494ef2a4 100644
@@ -28,6 +28,7 @@
 #include <linux/highmem.h>
 #include <linux/io.h>
 #include <linux/kmemleak.h>
+#include <linux/gcma.h>
 #include <trace/events/cma.h>
 
 #include "internal.h"
@@ -161,11 +162,18 @@ static void __init cma_activate_area(struct cma *cma)
 			count = early_pfn[r] - cmr->base_pfn;
 			bitmap_count = cma_bitmap_pages_to_bits(cma, count);
 			bitmap_set(cmr->bitmap, 0, bitmap_count);
+		} else {
+			count = 0;
 		}
 
-		for (pfn = early_pfn[r]; pfn < cmr->base_pfn + cmr->count;
-		     pfn += pageblock_nr_pages)
-			init_cma_reserved_pageblock(pfn_to_page(pfn));
+		if (cma->gcma) {
+			gcma_register_area(cma->name, early_pfn[r],
+					   cma->count - count);
+		} else {
+			for (pfn = early_pfn[r]; pfn < cmr->base_pfn + cmr->count;
+			     pfn += pageblock_nr_pages)
+				init_cma_reserved_pageblock(pfn_to_page(pfn));
+		}
 	}
 
 	spin_lock_init(&cma->lock);
@@ -252,7 +260,7 @@ static void __init cma_drop_area(struct cma *cma)
 }
 
 /**
- * cma_init_reserved_mem() - create custom contiguous area from reserved memory
+ * __cma_init_reserved_mem() - create custom contiguous area from reserved memory
  * @base: Base address of the reserved area
  * @size: Size of the reserved area (in bytes),
  * @order_per_bit: Order of pages represented by one bit on bitmap.
@@ -260,13 +268,14 @@ static void __init cma_drop_area(struct cma *cma)
  *        the area will be set to "cmaN", where N is a running counter of
  *        used areas.
  * @res_cma: Pointer to store the created cma region.
+ * @gcma: Flag to reserve guaranteed reserved memory area.
  *
  * This function creates custom contiguous area from already reserved memory.
  */
-int __init cma_init_reserved_mem(phys_addr_t base, phys_addr_t size,
-				 unsigned int order_per_bit,
-				 const char *name,
-				 struct cma **res_cma)
+int __init __cma_init_reserved_mem(phys_addr_t base, phys_addr_t size,
+				   unsigned int order_per_bit,
+				   const char *name,
+				   struct cma **res_cma, bool gcma)
 {
 	struct cma *cma;
 	int ret;
@@ -297,6 +306,7 @@ int __init cma_init_reserved_mem(phys_addr_t base, phys_addr_t size,
 	cma->ranges[0].count = cma->count;
 	cma->nranges = 1;
 	cma->nid = NUMA_NO_NODE;
+	cma->gcma = gcma;
 
 	*res_cma = cma;
 
@@ -836,7 +846,11 @@ static int cma_range_alloc(struct cma *cma, struct cma_memrange *cmr,
 		spin_unlock_irq(&cma->lock);
 
 		mutex_lock(&cma->alloc_mutex);
-		ret = alloc_contig_range(pfn, pfn + count, ACR_FLAGS_CMA, gfp);
+		if (cma->gcma)
+			ret = gcma_alloc_range(pfn, count, gfp);
+		else
+			ret = alloc_contig_range(pfn, pfn + count,
+						 ACR_FLAGS_CMA, gfp);
 		mutex_unlock(&cma->alloc_mutex);
 		if (!ret)
 			break;
@@ -1009,7 +1023,10 @@ bool cma_release(struct cma *cma, const struct page *pages,
 	if (r == cma->nranges)
 		return false;
 
-	free_contig_range(pfn, count);
+	if (cma->gcma)
+		gcma_free_range(pfn, count);
+	else
+		free_contig_range(pfn, count);
 	cma_clear_bitmap(cma, cmr, pfn, count);
 	cma_sysfs_account_release_pages(cma, count);
 	trace_cma_release(cma->name, pfn, pages, count);
mm/cma.h +1 -0
index c70180c36559..3b09e8619082 100644
@@ -49,6 +49,7 @@ struct cma {
 	char name[CMA_MAX_NAME];
 	int nranges;
 	struct cma_memrange ranges[CMA_MAX_RANGES];
+	bool gcma;
 #ifdef CONFIG_CMA_SYSFS
 	/* the number of CMA page successful allocations */
 	atomic64_t nr_pages_succeeded;
mm/cma_sysfs.c +10 -0
index 97acd3e5a6a5..4ecc36270a4d 100644
@@ -80,6 +80,15 @@ static ssize_t available_pages_show(struct kobject *kobj,
 }
 CMA_ATTR_RO(available_pages);
 
+static ssize_t gcma_show(struct kobject *kobj,
+			 struct kobj_attribute *attr, char *buf)
+{
+	struct cma *cma = cma_from_kobj(kobj);
+
+	return sysfs_emit(buf, "%d\n", cma->gcma);
+}
+CMA_ATTR_RO(gcma);
+
 static void cma_kobj_release(struct kobject *kobj)
 {
 	struct cma *cma = cma_from_kobj(kobj);
@@ -95,6 +104,7 @@ static struct attribute *cma_attrs[] = {
 	&release_pages_success_attr.attr,
 	&total_pages_attr.attr,
 	&available_pages_attr.attr,
+	&gcma_attr.attr,
 	NULL,
 };
 ATTRIBUTE_GROUPS(cma);
mm/gcma.c +1 -1
index 3ee0e1340db3..8e7d7a829b49 100644
@@ -119,7 +119,7 @@ int gcma_register_area(const char *name,
 		folio_set_count(folio, 0);
 		list_add(&folio->lru, &folios);
 	}
-
+	folio_zone(pfn_folio(start_pfn))->cma_pages += count;
 	cleancache_backend_put_folios(pool_id, &folios);
 
 	spin_lock(&gcma_area_lock);
Signature · 1 line
2.51.0.740.g6adb054d12-goog
author reviewer
#3 lore raw

Re: [PATCH 1/8] mm: implement cleancache

Quoted 6 lines · Andrew Morton
Quoted 1 line · On Thu, 9 Oct 2025 18:19:44 -0700 Suren Baghdasaryan <[email protected]> wrote:

Subject: [PATCH 1/8] mm: implement cleancache

Well that's confusing. We removed cleancache 3+ years ago in 0a4ee518185e.

Yes, this version is a complete rewrite. Previous version was a thin layer acting as a middleman and having hooks deep in the FS code. This version implements most of the cleancache page management inside cleancache itself and allows GCMA and future clients to be thin. It is also much less invasive, limiting its hooks mostly to the MM code. From the cover letter:

New implementation:
1. Avoids intrusive hooks into filesystem code, limiting them to two hooks for filesystem mount/unmount events and a hook for bdev invalidation.
2. Manages inode to folio association and handles pools of donated folios inside cleancache itself, freeing backends of this burden.

The idea was presented at this year's LSF/MM and RFC was posted at
https://lore.kernel.org/all/[email protected]/
earlier this year.

maintainer
#4 lore raw

Re: [PATCH 1/8] mm: implement cleancache

In reply to Suren Baghdasaryan

block/bdev.c void invalidate_bdev(struct block_device *bdev) · line 109

Quoted 5 lines · Suren Baghdasaryan
block/bdev.c +5 -0
+	/*
+	 * 99% of the time, we don't need to flush the cleancache on the bdev.
+	 * But, for the strange corners, lets be cautious
+	 */
+	cleancache_invalidate_inode(mapping, mapping->host);

Why do we need to pass in both address_space and inode?

Quoted 6 lines

+/*
+ * Backend API
+ *
+ * Cleancache does not touch page reference. Page refcount should be 1 when
+ * page is placed or returned into cleancache and pages obtained from
+ * cleancache will also have their refcount at 1.

I don't like these references to page refcount. Surely you mean folio refcount?

mm/Kconfig config USE_PERCPU_NUMA_NODE_ID · line 956

Quoted 4 lines
mm/Kconfig +4 -0
+	help
+	  Cleancache can be thought of as a page-granularity victim cache
+	  for clean pages that the kernel's pageframe replacement algorithm
+	  (PFRA) would like to keep around, but can't since there isn't enough

PFRA seems to be an acronym you've just made up. Why?

mm/cleancache.c line 44

Quoted 5 lines
mm/cleancache.c new file +5 -0
+struct cleancache_inode {
+	struct inode *inode;
+	struct hlist_node hash;
+	refcount_t ref_count;
+	struct xarray folios; /* protected by folios.xa_lock */

This is a pointless comment. All xarrays are protected by their own xa_lock.

Quoted 1 line

+static DEFINE_IDR(fs_idr);

No. The IDR is deprecated. Use an allocating XArray.

Quoted 5 lines

+/*
+ * Folio attributes:
+ * folio->_mapcount - pool_id
+ * folio->mapping - ccinode reference or NULL if folio is unused
+ * folio->index - file offset

No. Don't reuse fields for something entirely different. Put a properly named field in the union.

Quoted 1 line

+static void folio_attachment(struct folio *folio, struct cleancache_inode **ccinode,

Unnecessarily long line

author reviewer
#5 lore raw

Re: [PATCH 1/8] mm: implement cleancache

Quoted 9 lines · Matthew Wilcox

block/bdev.c void invalidate_bdev(struct block_device *bdev) · line 109

Quoted 5 lines · Suren Baghdasaryan
block/bdev.c +5 -0
+     /*
+      * 99% of the time, we don't need to flush the cleancache on the bdev.
+      * But, for the strange corners, lets be cautious
+      */
+     cleancache_invalidate_inode(mapping, mapping->host);

Why do we need to pass in both address_space and inode?

Ah, you mean why I don't use inode->i_mapping to get to its address space? I think I can. I'll try, and unless something blows up, I'll apply the change in the next version.

Quoted 10 lines
Quoted 7 lines

+/*
+ * Backend API
+ *
+ * Cleancache does not touch page reference. Page refcount should be 1 when
+ * page is placed or returned into cleancache and pages obtained from
+ * cleancache will also have their refcount at 1.

I don't like these references to page refcount. Surely you mean folio refcount?

Yes, mea culpa :) Will fix.

Quoted 7 lines

mm/Kconfig config USE_PERCPU_NUMA_NODE_ID · line 956

Quoted 5 lines
mm/Kconfig +4 -0
+     help
+       Cleancache can be thought of as a page-granularity victim cache
+       for clean pages that the kernel's pageframe replacement algorithm
+       (PFRA) would like to keep around, but can't since there isn't enough

PFRA seems to be an acronym you've just made up. Why?

Inherited from the original cleancache documentation. Will remove.

Quoted 9 lines

mm/cleancache.c line 44

Quoted 6 lines
mm/cleancache.c new file +5 -0
+struct cleancache_inode {
+     struct inode *inode;
+     struct hlist_node hash;
+     refcount_t ref_count;
+     struct xarray folios; /* protected by folios.xa_lock */

This is a pointless comment. All xarrays are protected by their own xa_lock.

Ack.

Quoted 4 lines
Quoted 2 lines

+static DEFINE_IDR(fs_idr);

No. The IDR is deprecated. Use an allocating XArray.

Ah, good to know. I'll change to xarray.

Quoted 9 lines
Quoted 6 lines

+/*
+ * Folio attributes:

+ *   folio->_mapcount - pool_id
+ *   folio->mapping - ccinode reference or NULL if folio is unused
+ *   folio->index - file offset

No. Don't reuse fields for something entirely different. Put a properly named field in the union.

Ack.

Quoted 4 lines
Quoted 2 lines

+static void folio_attachment(struct folio *folio, struct cleancache_inode **ccinode,

Unnecessarily long line

Ack.

Thanks for the feedback, Matthew!

Quoted 1 line
#17 lore raw

Re: [PATCH 6/8] add cleancache documentation

In reply to Suren Baghdasaryan

Hello Suren,

Quoted 6 lines · On Thu, 9 Oct 2025 18:19:49 -0700 Suren Baghdasaryan <[email protected]> wrote:

Document cleancache, it's APIs and sysfs interface.

---
 Documentation/mm/cleancache.rst | 112 ++++++++++++++++++++++++++++++++
 MAINTAINERS                     |   1 +

I think this great document is better to be linked on mm/index.rst.

Also, would it make sense to split the sysfs interface part and put under Documentation/admin-guide/mm/ ?

Quoted 18 lines
 2 files changed, 113 insertions(+)
 create mode 100644 Documentation/mm/cleancache.rst
Documentation/mm/cleancache.rst new file +9 -0
new file mode 100644
index 000000000000..deaf7de51829
@@ -0,0 +1,112 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+==========
+Cleancache
+==========
+
+Motivation
+==========
+

Documentation/mm/cleancache.rst line 19

Quoted 10 lines
Documentation/mm/cleancache.rst new file +10 -0
+Cleancache is a feature to utilize unused reserved memory for extending
+page cache.
+
+Cleancache can be thought of as a folio-granularity victim cache for clean
+file-backed pages that the kernel's pageframe replacement algorithm (PFRA)
+would like to keep around, but can't since there isn't enough memory. So
+when the PFRA "evicts" a folio, it stores the data contained in the folio
+into cleancache memory which is not directly accessible or addressable by
+the kernel (transcendent memory) and is of unknown and possibly
+time-varying size.

IMHO, "(transcendent memory)" better to be dropped, as it has removed by commit 814bbf49dcd0 ("xen: remove tmem driver").

Documentation/mm/cleancache.rst line 30

Quoted 11 lines
Documentation/mm/cleancache.rst new file +11 -0
+
+Later, when a filesystem wishes to access a folio in a file on disk, it
+first checks cleancache to see if it already contains required data; if it
+does, the folio data is copied into the kernel and a disk access is
+avoided.
+
+The memory cleancache uses is donated by other system components, which
+reserve memory not directly addressable by the kernel. By donating this
+memory to cleancache, the memory owner enables its utilization while it
+is not used. Memory donation is done using cleancache backend API and any
+donated memory can be taken back at any time by its donor without no delay

"without delay" or "with no delay" ?

Documentation/mm/cleancache.rst line 38

Quoted 8 lines
Documentation/mm/cleancache.rst new file +8 -0
+and with guarantees success. Since cleancache uses this memory only to
+store clean file-backed data, it can be dropped at any time and therefore
+the donor's request to take back the memory can be always satisfied.
+
+Implementation Overview
+=======================
+
+Cleancache "backend" (donor that provides transcendent memory), registers

Again, "transcendent memory" part seems better to be dropped.

Quoted 23 lines
Documentation/mm/cleancache.rst new file +23 -0
+itself with cleancache "frontend" and received a unique pool_id which it
+can use in all later API calls to identify the pool of folios it donates.
+Once registered, backend can call cleancache_backend_put_folio() or
+cleancache_backend_put_folios() to donate memory to cleancache. Note that
+cleancache currently supports only 0-order folios and will not accept
+larger-order ones. Once the backend needs that memory back, it can get it
+by calling cleancache_backend_get_folio(). Only the original backend can
+take the folio it donated from the cleancache.
+
+Kernel uses cleancache by first calling cleancache_add_fs() to register
+each file system and then using a combination of cleancache_store_folio(),
+cleancache_restore_folio(), cleancache_invalidate_{folio|inode} to store,
+restore and invalidate folio content.
+cleancache_{start|end}_inode_walk() are used to walk over folios inside
+an inode and cleancache_restore_from_inode() is used to restore folios
+during such walks.
+
+From kernel's point of view folios which are copied into cleancache have
+an indefinite lifetime which is completely unknowable by the kernel and so
+may or may not still be in cleancache at any later time. Thus, as its name
+implies, cleancache is not suitable for dirty folios. Cleancache has
+complete discretion over what folios to preserve and what folios to discard
+and when.

Documentation/mm/cleancache.rst line 71

Quoted 10 lines
Documentation/mm/cleancache.rst new file +10 -0
+
+Cleancache Performance Metrics
+==============================
+
+If CONFIG_CLEANCACHE_SYSFS is enabled, monitoring of cleancache performance
+can be done via sysfs in the `/sys/kernel/mm/cleancache` directory.
+The effectiveness of cleancache can be measured (across all filesystems)
+with provided stats.
+Global stats are published directly under `/sys/kernel/mm/cleancache` and
+include:

``/sys/kernel/mm/cleancache`` ?

Quoted 19 lines
Documentation/mm/cleancache.rst new file +19 -0
+
+``stored``
+	number of successful cleancache folio stores.
+
+``skipped``
+	number of folios skipped during cleancache store operation.
+
+``restored``
+	number of successful cleancache folio restore operations.
+
+``missed``
+	number of failed cleancache folio restore operations.
+
+``reclaimed``
+	number of folios reclaimed from the cleancache due to insufficient
+	memory.
+
+``recalled``
+	number of times cleancache folio content was discarded as a result

Documentation/mm/cleancache.rst line 100

Quoted 10 lines
Documentation/mm/cleancache.rst new file +10 -0
+	of the cleancache backend taking the folio back.
+
+``invalidated``
+	number of times cleancache folio content was discarded as a result
+	of invalidation.
+
+``cached``
+	number of folios currently cached in the cleancache.
+
+Per-pool stats are published under `/sys/kernel/mm/cleancache/<pool name>`

``/sys/kernel/mm/cleancache/<pool name>`` ?

Quoted 26 lines
Documentation/mm/cleancache.rst new file +12 -0
+where "pool name" is the name pool was registered under. These stats
+include:
+
+``size``
+	number of folios donated to this pool.
+
+``cached``
+	number of folios currently cached in the pool.
+
+``recalled``
+	number of times cleancache folio content was discarded as a result
+	of the cleancache backend taking the folio back from the pool.
MAINTAINERS +1 -0
index 1c97227e7ffa..441e68c94177 100644
@@ -6053,6 +6053,7 @@ CLEANCACHE
 M:	Suren Baghdasaryan <[email protected]>
 L:	[email protected]
 S:	Maintained
+F:	Documentation/mm/cleancache.rst
 F:	include/linux/cleancache.h
 F:	mm/cleancache.c
 F:	mm/cleancache_sysfs.c
Signature · 1 line
2.51.0.740.g6adb054d12-goog

Thanks,
SJ

#20 lore raw

Re: [PATCH 7/8] mm: introduce GCMA

In reply to Suren Baghdasaryan

Hello Suren,

Quoted 167 lines · On Thu, 9 Oct 2025 18:19:50 -0700 Suren Baghdasaryan <[email protected]> wrote:

From: Minchan Kim <[email protected]>

This patch introduces GCMA (Guaranteed Contiguous Memory Allocator) cleacache backend which reserves some amount of memory at the boot and then donates it to store clean file-backed pages in the cleancache. GCMA aims to guarantee contiguous memory allocation success as well as low and deterministic allocation latency.

Notes:
Originally, the idea was posted by SeongJae Park and Minchan Kim [1]. Later Minchan reworked it to be used in Android as a reference for Android vendors to use [2].

[1] https://lwn.net/Articles/619865/
[2] https://android-review.googlesource.com/q/topic:%22gcma_6.12%22

---
 MAINTAINERS          |   2 +
 include/linux/gcma.h |  36 +++++++
 mm/Kconfig           |  15 +++
 mm/Makefile          |   1 +
 mm/gcma.c            | 231 +++++++++++++++++++++++++++++++++++++++++++
 5 files changed, 285 insertions(+)
 create mode 100644 include/linux/gcma.h
 create mode 100644 mm/gcma.c
MAINTAINERS +2 -0
index 441e68c94177..95b5ad26ec11 100644
@@ -16361,6 +16361,7 @@ F:	Documentation/admin-guide/mm/
 F:	Documentation/mm/
 F:	include/linux/cma.h
 F:	include/linux/dmapool.h
+F:	include/linux/gcma.h
 F:	include/linux/ioremap.h
 F:	include/linux/memory-tiers.h
 F:	include/linux/page_idle.h
@@ -16372,6 +16373,7 @@ F:	mm/dmapool.c
 F:	mm/dmapool_test.c
 F:	mm/early_ioremap.c
 F:	mm/fadvise.c
+F:	mm/gcma.c
 F:	mm/ioremap.c
 F:	mm/mapping_dirty_helpers.c
 F:	mm/memory-tiers.c
include/linux/gcma.h new file +36 -0
new file mode 100644
index 000000000000..20b2c85de87b
@@ -0,0 +1,36 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __GCMA_H__
+#define __GCMA_H__
+
+#include <linux/types.h>
+
+#ifdef CONFIG_GCMA
+
+int gcma_register_area(const char *name,
+		       unsigned long start_pfn, unsigned long count);
+
+/*
+ * NOTE: allocated pages are still marked reserved and when freeing them
+ * the caller should ensure they are isolated and not referenced by anyone
+ * other than the caller.
+ */
+int gcma_alloc_range(unsigned long start_pfn, unsigned long count, gfp_t gfp);
+int gcma_free_range(unsigned long start_pfn, unsigned long count);
+
+#else /* CONFIG_GCMA */
+
+static inline int gcma_register_area(const char *name,
+				     unsigned long start_pfn,
+				     unsigned long count)
+		{ return -EOPNOTSUPP; }
+static inline int gcma_alloc_range(unsigned long start_pfn,
+				   unsigned long count, gfp_t gfp)
+		{ return -EOPNOTSUPP; }
+
+static inline int gcma_free_range(unsigned long start_pfn,
+				   unsigned long count)
+		{ return -EOPNOTSUPP; }
+
+#endif /* CONFIG_GCMA */
+
+#endif /* __GCMA_H__ */
mm/Kconfig +15 -0
index 9f4da8a848f4..41ce5ef8db55 100644
@@ -1013,6 +1013,21 @@ config CMA_AREAS
 
 	  If unsure, leave the default value "8" in UMA and "20" in NUMA.
 
+config GCMA
+       bool "GCMA (Guaranteed Contiguous Memory Allocator)"
+       depends on CLEANCACHE
+	help
+	  This enables the Guaranteed Contiguous Memory Allocator to allow
+	  low latency guaranteed contiguous memory allocations. Memory
+	  reserved by GCMA is donated to cleancache to be used as pagecache
+	  extension. Once GCMA allocation is requested, necessary pages are
+	  taken back from the cleancache and used to satisfy the request.
+	  Cleancache guarantees low latency successful allocation as long
+	  as the total size of GCMA allocations does not exceed the size of
+	  the memory donated to the cleancache.
+
+	  If unsure, say "N".
+
 #
 # Select this config option from the architecture Kconfig, if available, to set
 # the max page order for physically contiguous allocations.
mm/Makefile +1 -0
index 845841a140e3..05aee66a8b07 100644
@@ -149,3 +149,4 @@ obj-$(CONFIG_TMPFS_QUOTA) += shmem_quota.o
 obj-$(CONFIG_PT_RECLAIM) += pt_reclaim.o
 obj-$(CONFIG_CLEANCACHE) += cleancache.o
 obj-$(CONFIG_CLEANCACHE_SYSFS)	+= cleancache_sysfs.o
+obj-$(CONFIG_GCMA)	+= gcma.o
mm/gcma.c new file +36 -0
new file mode 100644
index 000000000000..3ee0e1340db3
@@ -0,0 +1,231 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * GCMA (Guaranteed Contiguous Memory Allocator)
+ *
+ */
+
+#define pr_fmt(fmt) "gcma: " fmt
+
+#include <linux/cleancache.h>
+#include <linux/gcma.h>
+#include <linux/hashtable.h>
+#include <linux/highmem.h>
+#include <linux/idr.h>
+#include <linux/slab.h>
+#include <linux/xarray.h>
+#include "internal.h"
+
+#define MAX_GCMA_AREAS		64
+#define GCMA_AREA_NAME_MAX_LEN	32
+
+struct gcma_area {
+	int pool_id;
+	unsigned long start_pfn;
+	unsigned long end_pfn;
+	char name[GCMA_AREA_NAME_MAX_LEN];
+};
+
+static struct gcma_area areas[MAX_GCMA_AREAS];
+static atomic_t nr_gcma_area = ATOMIC_INIT(0);
+static DEFINE_SPINLOCK(gcma_area_lock);
+
+static int free_folio_range(struct gcma_area *area,
+			     unsigned long start_pfn, unsigned long end_pfn)
+{
+	unsigned long scanned = 0;
+	struct folio *folio;

mm/gcma.c line 46

Quoted 10 lines
mm/gcma.c new file +10 -0
+	unsigned long pfn;
+
+	for (pfn = start_pfn; pfn < end_pfn; pfn++) {
+		int err;
+
+		if (!(++scanned % XA_CHECK_SCHED))
+			cond_resched();
+
+		folio = pfn_folio(pfn);
+		err = cleancache_backend_put_folio(area->pool_id, folio);

Why don't you use pfn_folio() directly, like alloc_folio_range() does?

mm/gcma.c line 48

Quoted 2 lines
mm/gcma.c new file +2 -0
+		if (WARN(err, "PFN %lu: folio is still in use\n", pfn))
+			return -EINVAL;

Why don't you return err, like alloc_folio_range() does?

Quoted 131 lines
mm/gcma.c new file +131 -0
+	}
+
+	return 0;
+}
+
+static int alloc_folio_range(struct gcma_area *area,
+			      unsigned long start_pfn, unsigned long end_pfn,
+			      gfp_t gfp)
+{
+	unsigned long scanned = 0;
+	unsigned long pfn;
+
+	for (pfn = start_pfn; pfn < end_pfn; pfn++) {
+		int err;
+
+		if (!(++scanned % XA_CHECK_SCHED))
+			cond_resched();
+
+		err = cleancache_backend_get_folio(area->pool_id, pfn_folio(pfn));
+		if (err) {
+			free_folio_range(area, start_pfn, pfn);
+			return err;
+		}
+	}
+
+	return 0;
+}
+
+static struct gcma_area *find_area(unsigned long start_pfn, unsigned long end_pfn)
+{
+	int nr_area = atomic_read_acquire(&nr_gcma_area);
+	int i;
+
+	for (i = 0; i < nr_area; i++) {
+		struct gcma_area *area = &areas[i];
+
+		if (area->end_pfn <= start_pfn)
+			continue;
+
+		if (area->start_pfn > end_pfn)
+			continue;
+
+		/* The entire range should belong to a single area */
+		if (start_pfn < area->start_pfn || end_pfn > area->end_pfn)
+			break;
+
+		/* Found the area containing the entire range */
+		return area;
+	}
+
+	return NULL;
+}
+
+int gcma_register_area(const char *name,
+		       unsigned long start_pfn, unsigned long count)
+{
+	LIST_HEAD(folios);
+	int i, pool_id;
+	int nr_area;
+	int ret = 0;
+
+	pool_id = cleancache_backend_register_pool(name);
+	if (pool_id < 0)
+		return pool_id;
+
+	for (i = 0; i < count; i++) {
+		struct folio *folio;
+
+		folio = pfn_folio(start_pfn + i);
+		folio_clear_reserved(folio);
+		folio_set_count(folio, 0);
+		list_add(&folio->lru, &folios);
+	}
+
+	cleancache_backend_put_folios(pool_id, &folios);
+
+	spin_lock(&gcma_area_lock);
+
+	nr_area = atomic_read(&nr_gcma_area);
+	if (nr_area < MAX_GCMA_AREAS) {
+		struct gcma_area *area = &areas[nr_area];
+
+		area->pool_id = pool_id;
+		area->start_pfn = start_pfn;
+		area->end_pfn = start_pfn + count;
+		strscpy(area->name, name);
+		/* Ensure above stores complete before we increase the count */
+		atomic_set_release(&nr_gcma_area, nr_area + 1);
+	} else {
+		ret = -ENOMEM;
+	}
+
+	spin_unlock(&gcma_area_lock);
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(gcma_register_area);
+
+int gcma_alloc_range(unsigned long start_pfn, unsigned long count, gfp_t gfp)
+{
+	unsigned long end_pfn = start_pfn + count;
+	struct gcma_area *area;
+	struct folio *folio;
+	int err, order = 0;
+
+	gfp = current_gfp_context(gfp);
+	if (gfp & __GFP_COMP) {
+		if (!is_power_of_2(count))
+			return -EINVAL;
+
+		order = ilog2(count);
+		if (order >= MAX_PAGE_ORDER)
+			return -EINVAL;
+	}
+
+	area = find_area(start_pfn, end_pfn);
+	if (!area)
+		return -EINVAL;
+
+	err = alloc_folio_range(area, start_pfn, end_pfn, gfp);
+	if (err)
+		return err;
+
+	/*
+	 * GCMA returns pages with refcount 1 and expects them to have
+	 * the same refcount 1 when they are freed.
+	 */
+	if (order) {
+		folio = pfn_folio(start_pfn);
+		set_page_count(&folio->page, 1);
+		prep_compound_page(&folio->page, order);

mm/gcma.c line 189

Quoted 10 lines
mm/gcma.c new file +10 -0
+	} else {
+		for (unsigned long pfn = start_pfn; pfn < end_pfn; pfn++) {
+			folio = pfn_folio(pfn);
+			set_page_count(&folio->page, 1);
+		}
+	}
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(gcma_alloc_range);

I'm wondering if the rule of exporting symbols only for in-tree modules that use the symbols should be applied here or not, and why.

Quoted 4 lines
mm/gcma.c new file +4 -0
+
+int gcma_free_range(unsigned long start_pfn, unsigned long count)
+{
+	unsigned long end_pfn = start_pfn + count;

mm/gcma.c line 203

Quoted 10 lines
mm/gcma.c new file +10 -0
+	struct gcma_area *area;
+	struct folio *folio;
+
+	area = find_area(start_pfn, end_pfn);
+	if (!area)
+		return -EINVAL;
+
+	folio = pfn_folio(start_pfn);
+	if (folio_test_large(folio)) {
+		int expected = folio_nr_pages(folio);

folio_nr_pages() return 'unsigned long'. Would it be better to match the type?

Quoted 9 lines
mm/gcma.c new file +9 -0
+
+		if (WARN(count != expected, "PFN %lu: count %lu != expected %d\n",
+			  start_pfn, count, expected))
+			return -EINVAL;
+
+		if (WARN(!folio_ref_dec_and_test(folio),
+			 "PFN %lu: invalid folio refcount when freeing\n", start_pfn))
+			return -EINVAL;
+

mm/gcma.c line 222

Quoted 10 lines
mm/gcma.c new file +10 -0
+		free_pages_prepare(&folio->page, folio_order(folio));
+	} else {
+		for (unsigned long pfn = start_pfn; pfn < end_pfn; pfn++) {
+			folio = pfn_folio(pfn);
+			if (folio_nr_pages(folio) == 1)
+				count--;
+
+			if (WARN(!folio_ref_dec_and_test(folio),
+				 "PFN %lu: invalid folio refcount when freeing\n", pfn))
+				return -EINVAL;

Don't we need to increase the previously decreased folio refcounts?

mm/gcma.c line 226

Quoted 4 lines
mm/gcma.c new file +4 -0
+
+			free_pages_prepare(&folio->page, 0);
+		}
+		WARN(count != 0, "%lu pages are still in use!\n", count);

Is WARN() but not returning error here ok?

Also, why don't you warn earlier above if 'folio_nr_pages(folio) != 1' ?

mm/gcma.c line 231

Quoted 5 lines
mm/gcma.c new file +5 -0
+	}
+
+	return free_folio_range(area, start_pfn, end_pfn);
+}
+EXPORT_SYMBOL_GPL(gcma_free_range);

Like the gcma_alloc_range() case, I'm curious if this symbol exporting is somewhat intended and the intention is explained.

Quoted 2 lines
Signature · 1 line
2.51.0.740.g6adb054d12-goog

Thanks,
SJ

#6 lore raw

Re: [PATCH 1/8] mm: implement cleancache

In reply to Suren Baghdasaryan
kernel test robot noticed the following build errors:

Hi Suren,

kernel test robot noticed the following build errors:

[auto build test ERROR on 70478cb9da6fc4e7b987219173ba1681d5f7dd3d]

url:    https://github.com/intel-lab-lkp/linux/commits/Suren-Baghdasaryan/mm-implement-cleancache/20251010-134501
base:   70478cb9da6fc4e7b987219173ba1681d5f7dd3d
patch link:    https://lore.kernel.org/r/20251010011951.2136980-2-surenb%40google.com
patch subject: [PATCH 1/8] mm: implement cleancache
config: loongarch-allmodconfig (https://download.01.org/0day-ci/archive/20251011/[email protected]/config)
compiler: clang version 19.1.7 (https://github.com/llvm/llvm-project cd708029e0b2869e80abe31ddb175f7c35361f90)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251011/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

>> mm/cleancache.c:119:13: error: casting from randomized structure pointer type 'struct address_space *' to 'struct cleancache_inode *'
     119 |         *ccinode = (struct cleancache_inode *)folio->mapping;
         |                    ^

1 error generated.

vim +119 mm/cleancache.c

113
114 static void folio_attachment(struct folio *folio, struct cleancache_inode **ccinode,
115 unsigned long *offset)
116 {
117 lockdep_assert_held(&(folio_pool(folio)->lock));
118

 > 119		*ccinode = (struct cleancache_inode *)folio->mapping;

120 *offset = folio->index;
121 }
122

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
author reviewer
#7 lore raw

Re: [PATCH 1/8] mm: implement cleancache

Quoted 20 lines · kernel test robot

Hi Suren,

kernel test robot noticed the following build errors:

[auto build test ERROR on 70478cb9da6fc4e7b987219173ba1681d5f7dd3d]

url:    https://github.com/intel-lab-lkp/linux/commits/Suren-Baghdasaryan/mm-implement-cleancache/20251010-134501
base:   70478cb9da6fc4e7b987219173ba1681d5f7dd3d
patch link:    https://lore.kernel.org/r/20251010011951.2136980-2-surenb%40google.com
patch subject: [PATCH 1/8] mm: implement cleancache
config: loongarch-allmodconfig (https://download.01.org/0day-ci/archive/20251011/[email protected]/config)
compiler: clang version 19.1.7 (https://github.com/llvm/llvm-project cd708029e0b2869e80abe31ddb175f7c35361f90)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251011/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

Quoted 6 lines

All errors (new ones prefixed by >>):

Quoted 1 line
Quoted 1 line

mm/cleancache.c:119:13: error: casting from randomized structure pointer type 'struct address_space *' to 'struct cleancache_inode *'

     119 |         *ccinode = (struct cleancache_inode *)folio->mapping;
         |                    ^

1 error generated.

Matthew's suggestion to use unions for members with multiple uses will remove the need for typecasting and should solve this issue.

Quoted 18 lines

vim +119 mm/cleancache.c

   113
   114  static void folio_attachment(struct folio *folio, struct cleancache_inode **ccinode,
   115                               unsigned long *offset)
   116  {
   117          lockdep_assert_held(&(folio_pool(folio)->lock));
   118
Quoted 1 line

119 *ccinode = (struct cleancache_inode *)folio->mapping;

   120          *offset = folio->index;
   121  }
   122

--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki

author reviewer
#21 lore raw

Re: [PATCH 7/8] mm: introduce GCMA

In reply to SeongJae Park
Quoted 176 lines · SeongJae Park

Hello Suren,

Quoted 171 lines · On Thu, 9 Oct 2025 18:19:50 -0700 Suren Baghdasaryan <[email protected]> wrote:

From: Minchan Kim <[email protected]>

This patch introduces GCMA (Guaranteed Contiguous Memory Allocator) cleacache backend which reserves some amount of memory at the boot and then donates it to store clean file-backed pages in the cleancache. GCMA aims to guarantee contiguous memory allocation success as well as low and deterministic allocation latency.

Notes:
Originally, the idea was posted by SeongJae Park and Minchan Kim [1]. Later Minchan reworked it to be used in Android as a reference for Android vendors to use [2].

[1] https://lwn.net/Articles/619865/
[2] https://android-review.googlesource.com/q/topic:%22gcma_6.12%22

---
 MAINTAINERS          |   2 +
 include/linux/gcma.h |  36 +++++++
 mm/Kconfig           |  15 +++
 mm/Makefile          |   1 +
 mm/gcma.c            | 231 +++++++++++++++++++++++++++++++++++++++++++
 5 files changed, 285 insertions(+)
 create mode 100644 include/linux/gcma.h
 create mode 100644 mm/gcma.c
MAINTAINERS +2 -0
index 441e68c94177..95b5ad26ec11 100644
@@ -16361,6 +16361,7 @@ F:    Documentation/admin-guide/mm/
 F:   Documentation/mm/
 F:   include/linux/cma.h
 F:   include/linux/dmapool.h
+F:   include/linux/gcma.h
 F:   include/linux/ioremap.h
 F:   include/linux/memory-tiers.h
 F:   include/linux/page_idle.h
@@ -16372,6 +16373,7 @@ F:    mm/dmapool.c
 F:   mm/dmapool_test.c
 F:   mm/early_ioremap.c
 F:   mm/fadvise.c
+F:   mm/gcma.c
 F:   mm/ioremap.c
 F:   mm/mapping_dirty_helpers.c
 F:   mm/memory-tiers.c
include/linux/gcma.h new file +36 -0
new file mode 100644
index 000000000000..20b2c85de87b
@@ -0,0 +1,36 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __GCMA_H__
+#define __GCMA_H__
+
+#include <linux/types.h>
+
+#ifdef CONFIG_GCMA
+
+int gcma_register_area(const char *name,
+                    unsigned long start_pfn, unsigned long count);
+
+/*
+ * NOTE: allocated pages are still marked reserved and when freeing them
+ * the caller should ensure they are isolated and not referenced by anyone
+ * other than the caller.
+ */
+int gcma_alloc_range(unsigned long start_pfn, unsigned long count, gfp_t gfp);
+int gcma_free_range(unsigned long start_pfn, unsigned long count);
+
+#else /* CONFIG_GCMA */
+
+static inline int gcma_register_area(const char *name,
+                                  unsigned long start_pfn,
+                                  unsigned long count)
+             { return -EOPNOTSUPP; }
+static inline int gcma_alloc_range(unsigned long start_pfn,
+                                unsigned long count, gfp_t gfp)
+             { return -EOPNOTSUPP; }
+
+static inline int gcma_free_range(unsigned long start_pfn,
+                                unsigned long count)
+             { return -EOPNOTSUPP; }
+
+#endif /* CONFIG_GCMA */
+
+#endif /* __GCMA_H__ */
mm/Kconfig +15 -0
index 9f4da8a848f4..41ce5ef8db55 100644
@@ -1013,6 +1013,21 @@ config CMA_AREAS
 
        If unsure, leave the default value "8" in UMA and "20" in NUMA.
 
+config GCMA
+       bool "GCMA (Guaranteed Contiguous Memory Allocator)"
+       depends on CLEANCACHE
+     help
+       This enables the Guaranteed Contiguous Memory Allocator to allow
+       low latency guaranteed contiguous memory allocations. Memory
+       reserved by GCMA is donated to cleancache to be used as pagecache
+       extension. Once GCMA allocation is requested, necessary pages are
+       taken back from the cleancache and used to satisfy the request.
+       Cleancache guarantees low latency successful allocation as long
+       as the total size of GCMA allocations does not exceed the size of
+       the memory donated to the cleancache.
+
+       If unsure, say "N".
+
 #
 # Select this config option from the architecture Kconfig, if available, to set
 # the max page order for physically contiguous allocations.
mm/Makefile +1 -0
index 845841a140e3..05aee66a8b07 100644
@@ -149,3 +149,4 @@ obj-$(CONFIG_TMPFS_QUOTA) += shmem_quota.o
 obj-$(CONFIG_PT_RECLAIM) += pt_reclaim.o
 obj-$(CONFIG_CLEANCACHE) += cleancache.o
 obj-$(CONFIG_CLEANCACHE_SYSFS)       += cleancache_sysfs.o
+obj-$(CONFIG_GCMA)   += gcma.o
mm/gcma.c new file +40 -0
new file mode 100644
index 000000000000..3ee0e1340db3
@@ -0,0 +1,231 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * GCMA (Guaranteed Contiguous Memory Allocator)
+ *
+ */
+
+#define pr_fmt(fmt) "gcma: " fmt
+
+#include <linux/cleancache.h>
+#include <linux/gcma.h>
+#include <linux/hashtable.h>
+#include <linux/highmem.h>
+#include <linux/idr.h>
+#include <linux/slab.h>
+#include <linux/xarray.h>
+#include "internal.h"
+
+#define MAX_GCMA_AREAS               64
+#define GCMA_AREA_NAME_MAX_LEN       32
+
+struct gcma_area {
+     int pool_id;
+     unsigned long start_pfn;
+     unsigned long end_pfn;
+     char name[GCMA_AREA_NAME_MAX_LEN];
+};
+
+static struct gcma_area areas[MAX_GCMA_AREAS];
+static atomic_t nr_gcma_area = ATOMIC_INIT(0);
+static DEFINE_SPINLOCK(gcma_area_lock);
+
+static int free_folio_range(struct gcma_area *area,
+                          unsigned long start_pfn, unsigned long end_pfn)
+{
+     unsigned long scanned = 0;
+     struct folio *folio;
+     unsigned long pfn;
+
+     for (pfn = start_pfn; pfn < end_pfn; pfn++) {
+             int err;
Quoted 8 lines

mm/gcma.c line 46

Quoted 6 lines
mm/gcma.c new file +6 -0
+
+             if (!(++scanned % XA_CHECK_SCHED))
+                     cond_resched();
+
+             folio = pfn_folio(pfn);
+             err = cleancache_backend_put_folio(area->pool_id, folio);

Why don't you use pfn_folio() directly, like alloc_folio_range() does?

Yes, that would be better. Will change.

Quoted 5 lines

mm/gcma.c line 48

Quoted 3 lines
mm/gcma.c new file +2 -0
+             if (WARN(err, "PFN %lu: folio is still in use\n", pfn))
+                     return -EINVAL;

Why don't you return err, like alloc_folio_range() does?

Ack. In my earlier version cleancache_backend_put_folio() was returning bool, so I had to convert it to int here. But now we can return err directly. Will change.

Quoted 137 lines
Quoted 137 lines
mm/gcma.c new file +136 -0
+     }
+
+     return 0;
+}
+
+static int alloc_folio_range(struct gcma_area *area,
+                           unsigned long start_pfn, unsigned long end_pfn,
+                           gfp_t gfp)
+{
+     unsigned long scanned = 0;
+     unsigned long pfn;
+
+     for (pfn = start_pfn; pfn < end_pfn; pfn++) {
+             int err;
+
+             if (!(++scanned % XA_CHECK_SCHED))
+                     cond_resched();
+
+             err = cleancache_backend_get_folio(area->pool_id, pfn_folio(pfn));
+             if (err) {
+                     free_folio_range(area, start_pfn, pfn);
+                     return err;
+             }
+     }
+
+     return 0;
+}
+
+static struct gcma_area *find_area(unsigned long start_pfn, unsigned long end_pfn)
+{
+     int nr_area = atomic_read_acquire(&nr_gcma_area);
+     int i;
+
+     for (i = 0; i < nr_area; i++) {
+             struct gcma_area *area = &areas[i];
+
+             if (area->end_pfn <= start_pfn)
+                     continue;
+
+             if (area->start_pfn > end_pfn)
+                     continue;
+
+             /* The entire range should belong to a single area */
+             if (start_pfn < area->start_pfn || end_pfn > area->end_pfn)
+                     break;
+
+             /* Found the area containing the entire range */
+             return area;
+     }
+
+     return NULL;
+}
+
+int gcma_register_area(const char *name,
+                    unsigned long start_pfn, unsigned long count)
+{
+     LIST_HEAD(folios);
+     int i, pool_id;
+     int nr_area;
+     int ret = 0;
+
+     pool_id = cleancache_backend_register_pool(name);
+     if (pool_id < 0)
+             return pool_id;
+
+     for (i = 0; i < count; i++) {
+             struct folio *folio;
+
+             folio = pfn_folio(start_pfn + i);
+             folio_clear_reserved(folio);
+             folio_set_count(folio, 0);
+             list_add(&folio->lru, &folios);
+     }
+
+     cleancache_backend_put_folios(pool_id, &folios);
+
+     spin_lock(&gcma_area_lock);
+
+     nr_area = atomic_read(&nr_gcma_area);
+     if (nr_area < MAX_GCMA_AREAS) {
+             struct gcma_area *area = &areas[nr_area];
+
+             area->pool_id = pool_id;
+             area->start_pfn = start_pfn;
+             area->end_pfn = start_pfn + count;
+             strscpy(area->name, name);
+             /* Ensure above stores complete before we increase the count */
+             atomic_set_release(&nr_gcma_area, nr_area + 1);
+     } else {
+             ret = -ENOMEM;
+     }
+
+     spin_unlock(&gcma_area_lock);
+
+     return ret;
+}
+EXPORT_SYMBOL_GPL(gcma_register_area);
+
+int gcma_alloc_range(unsigned long start_pfn, unsigned long count, gfp_t gfp)
+{
+     unsigned long end_pfn = start_pfn + count;
+     struct gcma_area *area;
+     struct folio *folio;
+     int err, order = 0;
+
+     gfp = current_gfp_context(gfp);
+     if (gfp & __GFP_COMP) {
+             if (!is_power_of_2(count))
+                     return -EINVAL;
+
+             order = ilog2(count);
+             if (order >= MAX_PAGE_ORDER)
+                     return -EINVAL;
+     }
+
+     area = find_area(start_pfn, end_pfn);
+     if (!area)
+             return -EINVAL;
+
+     err = alloc_folio_range(area, start_pfn, end_pfn, gfp);
+     if (err)
+             return err;
+
+     /*
+      * GCMA returns pages with refcount 1 and expects them to have
+      * the same refcount 1 when they are freed.
+      */
+     if (order) {
+             folio = pfn_folio(start_pfn);
+             set_page_count(&folio->page, 1);
+             prep_compound_page(&folio->page, order);
+     } else {
+             for (unsigned long pfn = start_pfn; pfn < end_pfn; pfn++) {
+                     folio = pfn_folio(pfn);
+                     set_page_count(&folio->page, 1);
+             }
Quoted 8 lines

mm/gcma.c line 189

Quoted 5 lines
mm/gcma.c new file +5 -0
+     }
+
+     return 0;
+}
+EXPORT_SYMBOL_GPL(gcma_alloc_range);

I'm wondering if the rule of exporting symbols only for in-tree modules that use the symbols should be applied here or not, and why.

In Android we use gcma_alloc_range() in vendor-defined dmabuf-heap modules. That's why I need this API to be exported.

Quoted 17 lines
Quoted 5 lines
mm/gcma.c new file +4 -0
+
+int gcma_free_range(unsigned long start_pfn, unsigned long count)
+{
+     unsigned long end_pfn = start_pfn + count;

mm/gcma.c line 203

Quoted 10 lines
mm/gcma.c new file +10 -0
+     struct gcma_area *area;
+     struct folio *folio;
+
+     area = find_area(start_pfn, end_pfn);
+     if (!area)
+             return -EINVAL;
+
+     folio = pfn_folio(start_pfn);
+     if (folio_test_large(folio)) {
+             int expected = folio_nr_pages(folio);

folio_nr_pages() return 'unsigned long'. Would it be better to match the type?

Yes! Ack.

Quoted 14 lines
Quoted 14 lines
mm/gcma.c new file +13 -0
+
+             if (WARN(count != expected, "PFN %lu: count %lu != expected %d\n",
+                       start_pfn, count, expected))
+                     return -EINVAL;
+
+             if (WARN(!folio_ref_dec_and_test(folio),
+                      "PFN %lu: invalid folio refcount when freeing\n", start_pfn))
+                     return -EINVAL;
+
+             free_pages_prepare(&folio->page, folio_order(folio));
+     } else {
+             for (unsigned long pfn = start_pfn; pfn < end_pfn; pfn++) {
+                     folio = pfn_folio(pfn);
Quoted 8 lines

mm/gcma.c line 222

Quoted 6 lines
mm/gcma.c new file +6 -0
+                     if (folio_nr_pages(folio) == 1)
+                             count--;
+
+                     if (WARN(!folio_ref_dec_and_test(folio),
+                              "PFN %lu: invalid folio refcount when freeing\n", pfn))
+                             return -EINVAL;

Don't we need to increase the previously decreased folio refcounts?

Yes, you are right. If any folio refcount is incorrect here (folio is still in use), we should restore the refcount for all folios that we have already processed. I think I'll also need to do 2 passes here:
first drop and check the refcount on all folios, then call free_pages_prepare() if all folios are unused.

And also need to remove all these WARN()'s which I had for debugging... Will remove in the next version.

Quoted 7 lines

mm/gcma.c line 226

Quoted 5 lines
mm/gcma.c new file +4 -0
+
+                     free_pages_prepare(&folio->page, 0);
+             }
+             WARN(count != 0, "%lu pages are still in use!\n", count);

Is WARN() but not returning error here ok?

No. I'll rework this loop to perform 2 passes as I mentioned before and if the first pass detects any mistake, it will restore previous refcounts and return an error.

Quoted 2 lines

Also, why don't you warn earlier above if 'folio_nr_pages(folio) != 1' ?

I'll remove all these warnings and change the code to fail and restore folios if any folio in the range does not meet our expectations.

Quoted 9 lines

mm/gcma.c line 231

Quoted 6 lines
mm/gcma.c new file +5 -0
+     }
+
+     return free_folio_range(area, start_pfn, end_pfn);
+}
+EXPORT_SYMBOL_GPL(gcma_free_range);

Like the gcma_alloc_range() case, I'm curious if this symbol exporting is somewhat intended and the intention is explained.

Same reasons. Vendor-provided dmabuf heap modules might use it.

Thanks,
Suren.

Quoted 7 lines
Quoted 3 lines

--
2.51.0.740.g6adb054d12-goog

Thanks,
SJ

author reviewer
#18 lore raw

Re: [PATCH 6/8] add cleancache documentation

In reply to SeongJae Park
Quoted 2 lines · SeongJae Park

Hello Suren,

Hi SJ!

Quoted 11 lines · On Thu, 9 Oct 2025 18:19:49 -0700 Suren Baghdasaryan <[email protected]> wrote:
Quoted 7 lines

Document cleancache, it's APIs and sysfs interface.

---
 Documentation/mm/cleancache.rst | 112 ++++++++++++++++++++++++++++++++
 MAINTAINERS                     |   1 +

I think this great document is better to be linked on mm/index.rst.

Ack.

Quoted 3 lines

Also, would it make sense to split the sysfs interface part and put under Documentation/admin-guide/mm/ ?

Hmm. I guess that makes sense.

Quoted 24 lines
Quoted 24 lines
 2 files changed, 113 insertions(+)
 create mode 100644 Documentation/mm/cleancache.rst
Documentation/mm/cleancache.rst new file +14 -0
new file mode 100644
index 000000000000..deaf7de51829
@@ -0,0 +1,112 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+==========
+Cleancache
+==========
+
+Motivation
+==========
+
+Cleancache is a feature to utilize unused reserved memory for extending
+page cache.
+
+Cleancache can be thought of as a folio-granularity victim cache for clean
+file-backed pages that the kernel's pageframe replacement algorithm (PFRA)
Quoted 8 lines

Documentation/mm/cleancache.rst line 19

Quoted 5 lines
Documentation/mm/cleancache.rst new file +5 -0
+would like to keep around, but can't since there isn't enough memory. So
+when the PFRA "evicts" a folio, it stores the data contained in the folio
+into cleancache memory which is not directly accessible or addressable by
+the kernel (transcendent memory) and is of unknown and possibly
+time-varying size.

IMHO, "(transcendent memory)" better to be dropped, as it has removed by commit 814bbf49dcd0 ("xen: remove tmem driver").

Ah, good point. Will remove.

Quoted 14 lines

Documentation/mm/cleancache.rst line 30

Quoted 12 lines
Documentation/mm/cleancache.rst new file +11 -0
+
+Later, when a filesystem wishes to access a folio in a file on disk, it
+first checks cleancache to see if it already contains required data; if it
+does, the folio data is copied into the kernel and a disk access is
+avoided.
+
+The memory cleancache uses is donated by other system components, which
+reserve memory not directly addressable by the kernel. By donating this
+memory to cleancache, the memory owner enables its utilization while it
+is not used. Memory donation is done using cleancache backend API and any
+donated memory can be taken back at any time by its donor without no delay

"without delay" or "with no delay" ?

Ack. Will change to "without delay"

Quoted 11 lines

Documentation/mm/cleancache.rst line 38

Quoted 9 lines
Documentation/mm/cleancache.rst new file +8 -0
+and with guarantees success. Since cleancache uses this memory only to
+store clean file-backed data, it can be dropped at any time and therefore
+the donor's request to take back the memory can be always satisfied.
+
+Implementation Overview
+=======================
+
+Cleancache "backend" (donor that provides transcendent memory), registers

Again, "transcendent memory" part seems better to be dropped.

Ack.

Quoted 28 lines
Quoted 28 lines
Documentation/mm/cleancache.rst new file +27 -0
+itself with cleancache "frontend" and received a unique pool_id which it
+can use in all later API calls to identify the pool of folios it donates.
+Once registered, backend can call cleancache_backend_put_folio() or
+cleancache_backend_put_folios() to donate memory to cleancache. Note that
+cleancache currently supports only 0-order folios and will not accept
+larger-order ones. Once the backend needs that memory back, it can get it
+by calling cleancache_backend_get_folio(). Only the original backend can
+take the folio it donated from the cleancache.
+
+Kernel uses cleancache by first calling cleancache_add_fs() to register
+each file system and then using a combination of cleancache_store_folio(),
+cleancache_restore_folio(), cleancache_invalidate_{folio|inode} to store,
+restore and invalidate folio content.
+cleancache_{start|end}_inode_walk() are used to walk over folios inside
+an inode and cleancache_restore_from_inode() is used to restore folios
+during such walks.
+
+From kernel's point of view folios which are copied into cleancache have
+an indefinite lifetime which is completely unknowable by the kernel and so
+may or may not still be in cleancache at any later time. Thus, as its name
+implies, cleancache is not suitable for dirty folios. Cleancache has
+complete discretion over what folios to preserve and what folios to discard
+and when.
+
+Cleancache Performance Metrics
+==============================
+
Quoted 8 lines

Documentation/mm/cleancache.rst line 71

Quoted 6 lines
Documentation/mm/cleancache.rst new file +6 -0
+If CONFIG_CLEANCACHE_SYSFS is enabled, monitoring of cleancache performance
+can be done via sysfs in the `/sys/kernel/mm/cleancache` directory.
+The effectiveness of cleancache can be measured (across all filesystems)
+with provided stats.
+Global stats are published directly under `/sys/kernel/mm/cleancache` and
+include:

``/sys/kernel/mm/cleancache`` ?

Ack.

Quoted 24 lines
Quoted 24 lines
Documentation/mm/cleancache.rst new file +23 -0
+
+``stored``
+     number of successful cleancache folio stores.
+
+``skipped``
+     number of folios skipped during cleancache store operation.
+
+``restored``
+     number of successful cleancache folio restore operations.
+
+``missed``
+     number of failed cleancache folio restore operations.
+
+``reclaimed``
+     number of folios reclaimed from the cleancache due to insufficient
+     memory.
+
+``recalled``
+     number of times cleancache folio content was discarded as a result
+     of the cleancache backend taking the folio back.
+
+``invalidated``
+     number of times cleancache folio content was discarded as a result
Quoted 8 lines

Documentation/mm/cleancache.rst line 100

Quoted 6 lines
Documentation/mm/cleancache.rst new file +6 -0
+     of invalidation.
+
+``cached``
+     number of folios currently cached in the cleancache.
+
+Per-pool stats are published under `/sys/kernel/mm/cleancache/<pool name>`

``/sys/kernel/mm/cleancache/<pool name>`` ?

Ack.

Quoted 23 lines
Quoted 23 lines
Documentation/mm/cleancache.rst new file +12 -0
+where "pool name" is the name pool was registered under. These stats
+include:
+
+``size``
+     number of folios donated to this pool.
+
+``cached``
+     number of folios currently cached in the pool.
+
+``recalled``
+     number of times cleancache folio content was discarded as a result
+     of the cleancache backend taking the folio back from the pool.
MAINTAINERS +1 -0
index 1c97227e7ffa..441e68c94177 100644
@@ -6053,6 +6053,7 @@ CLEANCACHE
 M:   Suren Baghdasaryan <[email protected]>
 L:   [email protected]
 S:   Maintained
+F:   Documentation/mm/cleancache.rst
 F:   include/linux/cleancache.h
Quoted 8 lines
Quoted 4 lines
MAINTAINERS +0 -1
 F:   mm/cleancache.c
 F:   mm/cleancache_sysfs.c
--

2.51.0.740.g6adb054d12-goog

Thanks,
SJ

Thanks for the review!

#14 lore raw

Re: [PATCH 5/8] mm/tests: add cleancache kunit test

In reply to Suren Baghdasaryan
kernel test robot noticed the following build warnings:

Hi Suren,

kernel test robot noticed the following build warnings:

[auto build test WARNING on 70478cb9da6fc4e7b987219173ba1681d5f7dd3d]

url:    https://github.com/intel-lab-lkp/linux/commits/Suren-Baghdasaryan/mm-implement-cleancache/20251010-134501
base:   70478cb9da6fc4e7b987219173ba1681d5f7dd3d
patch link:    https://lore.kernel.org/r/20251010011951.2136980-6-surenb%40google.com
patch subject: [PATCH 5/8] mm/tests: add cleancache kunit test
config: loongarch-allmodconfig (https://download.01.org/0day-ci/archive/20251011/[email protected]/config)
compiler: clang version 19.1.7 (https://github.com/llvm/llvm-project cd708029e0b2869e80abe31ddb175f7c35361f90)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251011/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All warnings (new ones prefixed by >>):

>> mm/tests/cleancache_kunit.c:358:6: warning: variable 'unused' set but not used [-Wunused-but-set-variable]
     358 |         int unused = 0;
         |             ^

1 warning generated.

vim +/unused +358 mm/tests/cleancache_kunit.c

353
354 static void cleancache_backend_api_test(struct kunit *test)
355 {
356 struct folio *folio;
357 LIST_HEAD(folios);

 > 358		int unused = 0;

359 int used = 0;
360
361 /* Store inode folios into cleancache */
362 fill_cleancache(test);
363
364 /* Get all donated folios back */
365 for (int fidx = 0; fidx < FOLIO_COUNT; fidx++) {
366 KUNIT_EXPECT_EQ(test, cleancache_backend_get_folio(test_data.pool_id,
367 test_data.pool_folios[fidx]), 0);
368 set_page_refcounted(&test_data.pool_folios[fidx]->page);
369 }
370
371 /* Try putting a refcounted folio */
372 KUNIT_EXPECT_NE(test, cleancache_backend_put_folio(test_data.pool_id,
373 test_data.pool_folios[0]), 0);
374
375 /* Put some of the folios back into cleancache */
376 for (int fidx = 0; fidx < FOLIOS_PER_INODE; fidx++) {
377 folio_ref_freeze(test_data.pool_folios[fidx], 1);
378 KUNIT_EXPECT_EQ(test, cleancache_backend_put_folio(test_data.pool_id,
379 test_data.pool_folios[fidx]), 0);
380 }
381
382 /* Put the rest back into cleancache but keep half of folios still refcounted */
383 for (int fidx = FOLIOS_PER_INODE; fidx < FOLIO_COUNT; fidx++) {
384 if (fidx % 2) {
385 folio_ref_freeze(test_data.pool_folios[fidx], 1);
386 unused++;
387 } else {
388 used++;
389 }
390 list_add(&test_data.pool_folios[fidx]->lru, &folios);
391 }
392 KUNIT_EXPECT_NE(test, cleancache_backend_put_folios(test_data.pool_id,
393 &folios), 0);
394 /* Used folios should be still in the list */
395 KUNIT_EXPECT_EQ(test, list_count_nodes(&folios), used);
396
397 /* Release refcounts and put the remaining folios into cleancache */
398 list_for_each_entry(folio, &folios, lru)
399 folio_ref_freeze(folio, 1);
400 KUNIT_EXPECT_EQ(test, cleancache_backend_put_folios(test_data.pool_id,
401 &folios), 0);
402 KUNIT_EXPECT_TRUE(test, list_empty(&folios));
403 }
404

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
author reviewer
#15 lore raw

Re: [PATCH 5/8] mm/tests: add cleancache kunit test

Quoted 20 lines · kernel test robot

Hi Suren,

kernel test robot noticed the following build warnings:

[auto build test WARNING on 70478cb9da6fc4e7b987219173ba1681d5f7dd3d]

url:    https://github.com/intel-lab-lkp/linux/commits/Suren-Baghdasaryan/mm-implement-cleancache/20251010-134501
base:   70478cb9da6fc4e7b987219173ba1681d5f7dd3d
patch link:    https://lore.kernel.org/r/20251010011951.2136980-6-surenb%40google.com
patch subject: [PATCH 5/8] mm/tests: add cleancache kunit test
config: loongarch-allmodconfig (https://download.01.org/0day-ci/archive/20251011/[email protected]/config)
compiler: clang version 19.1.7 (https://github.com/llvm/llvm-project cd708029e0b2869e80abe31ddb175f7c35361f90)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251011/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

Quoted 6 lines

All warnings (new ones prefixed by >>):

Quoted 1 line
Quoted 1 line

mm/tests/cleancache_kunit.c:358:6: warning: variable 'unused' set but not used [-Wunused-but-set-variable]

     358 |         int unused = 0;
         |             ^

1 warning generated.

Right, I'll remove it.

Quoted 60 lines

vim +/unused +358 mm/tests/cleancache_kunit.c

   353
   354  static void cleancache_backend_api_test(struct kunit *test)
   355  {
   356          struct folio *folio;
   357          LIST_HEAD(folios);
Quoted 1 line

358 int unused = 0;

   359          int used = 0;
   360
   361          /* Store inode folios into cleancache */
   362          fill_cleancache(test);
   363
   364          /* Get all donated folios back */
   365          for (int fidx = 0; fidx < FOLIO_COUNT; fidx++) {
   366                  KUNIT_EXPECT_EQ(test, cleancache_backend_get_folio(test_data.pool_id,
   367                                                  test_data.pool_folios[fidx]),  0);
   368                  set_page_refcounted(&test_data.pool_folios[fidx]->page);
   369          }
   370
   371          /* Try putting a refcounted folio */
   372          KUNIT_EXPECT_NE(test, cleancache_backend_put_folio(test_data.pool_id,
   373                                          test_data.pool_folios[0]), 0);
   374
   375          /* Put some of the folios back into cleancache */
   376          for (int fidx = 0; fidx < FOLIOS_PER_INODE; fidx++) {
   377                  folio_ref_freeze(test_data.pool_folios[fidx], 1);
   378                  KUNIT_EXPECT_EQ(test, cleancache_backend_put_folio(test_data.pool_id,
   379                                                  test_data.pool_folios[fidx]), 0);
   380          }
   381
   382          /* Put the rest back into cleancache but keep half of folios still refcounted */
   383          for (int fidx = FOLIOS_PER_INODE; fidx < FOLIO_COUNT; fidx++) {
   384                  if (fidx % 2) {
   385                          folio_ref_freeze(test_data.pool_folios[fidx], 1);
   386                          unused++;
   387                  } else {
   388                          used++;
   389                  }
   390                  list_add(&test_data.pool_folios[fidx]->lru, &folios);
   391          }
   392          KUNIT_EXPECT_NE(test, cleancache_backend_put_folios(test_data.pool_id,
   393                                          &folios), 0);
   394          /* Used folios should be still in the list */
   395          KUNIT_EXPECT_EQ(test, list_count_nodes(&folios), used);
   396
   397          /* Release refcounts and put the remaining folios into cleancache */
   398          list_for_each_entry(folio, &folios, lru)
   399                  folio_ref_freeze(folio, 1);
   400          KUNIT_EXPECT_EQ(test, cleancache_backend_put_folios(test_data.pool_id,
   401                                          &folios), 0);
   402          KUNIT_EXPECT_TRUE(test, list_empty(&folios));
   403  }
   404

--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki

#8 lore raw

Re: [PATCH 1/8] mm: implement cleancache

In reply to Suren Baghdasaryan

Please don't add abstractions just because you can. Just call directly into your gcma code instead of adding a costly abstraction with a single user. That'll also make it much eaiser to review what GCMA actually does.

author reviewer
#9 lore raw

Re: [PATCH 1/8] mm: implement cleancache

Quoted 5 lines · Christoph Hellwig

Please don't add abstractions just because you can. Just call directly into your gcma code instead of adding a costly abstraction with a single user. That'll also make it much eaiser to review what GCMA actually does.

Are you suggesting to fold cleancache into GCMA? GCMA is the first backend donating its memory to the cleancache but other memory carveout owners can do that too. The next two on my list are MTE tag storage and memory reserved by kdump.
Also note that the original GCMA proposal from 2015 [1] used both cleancache and frontswap to donate its memory. We don't have frontswap today, but this shows that it doesn't have to be a 1-to-1 relation between GCMA and cleancache.
Thanks,
Suren.

[1] https://lore.kernel.org/all/[email protected]/