AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/10/03 10:12 flow patch-triage
1m Args:
null

Results:
{
  "EnableConfigs": [
    "XSWAP",
    "ZSWAP",
    "ZSWAP_DEFAULT_ON"
  ],
  "FocusSymbols": [
    "xswap_create_store",
    "xswap_destroy_store",
    "xswap_create",
    "xswap_destroy",
    "xswap_map_clusters",
    "xswap_grow",
    "xswap_try_shrink",
    "xswap_shrink_work_fn",
    "xswap_unmap_clusters_locked",
    "swap_read_folio",
    "swap_writeout",
    "zswap_writeback_entry"
  ],
  "KMSANReasoning": "The patch introduces CONFIG_XSWAP, an extendable virtual swap device that relies on zswap without physical backing storage, dynamically mapping and unmapping cluster_info metadata via a sparse vmalloc area (VM_SPARSE).\n\n1. Memory Initialization:\n- All pages backing the cluster_info array are explicitly allocated using `alloc_page(... | __GFP_ZERO)`, ensuring all `struct swap_cluster_info` structures start fully zeroed before use. All spinlocks within these structures are initialized using `spin_lock_init()`.\n- The `swap_info_struct` is zero-allocated via `kvzalloc_obj()` in `alloc_swap_info()`, and all newly added fields under CONFIG_XSWAP (`cluster_vm`, `nr_clusters_max`, `nr_clusters_mapped`, `xswap_lock`, `xswap_shrink_work`, `xswap_grows`, `xswap_shrinks`) are explicitly initialized upon device creation.\n\n2. User-Space Exposure / Info-Leaks:\n- The sysfs interfaces (`create` and `destroy`) are write-only handlers that parse scalar input via `kstrtoint` and `kstrtoul`.\n- Procfs (`/proc/swaps`) and debugfs (`/sys/kernel/debug/xswap/type*`) read handlers format their output into stack buffers using `scnprintf()` and copy only the formatted length via `seq_puts()` or `simple_read_from_buffer()`. No kernel structures or uninitialized buffer paddings are copied to user space.\n\n3. KASAN vs KMSAN Applicability:\n- Any risks introduced by this change relate to VM_SPARSE page mapping/unmapping concurrency, RCU synchronization, locking between grow/shrink/swapoff, or invalid address dereferences if an unmapped cluster is accessed. These are detected by KASAN, LOCKDEP, or the kernel's fault handler.\n- There are no uninitialized stack/heap reads, uninitialized memory branch conditions, or info-leak risks that would specifically necessitate a dedicated KMSAN session.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch series introduces 'xswap' (extendable virtual swap device), modifying core memory management (mm/swapfile.c, mm/page_io.c, mm/swap_state.c, mm/zswap.c). It adds sysfs attributes (/sys/kernel/mm/xswap/create and destroy) to dynamically create and destroy virtual swap devices backed by zswap and a sparse vmalloc area, complete with dynamic mapping/unmapping, deferred shrinking work, synchronization via RCU and mutexes, and newly added WARN_ON_ONCE assertions. This code is fully reachable in virtualized QEMU environments and warrants fuzzing.",
  "WorthFuzzing": true
}

1/1 2026/10/03 10:12 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit 640f9f65f614b8fb4b5c591ccbebc221bf9640d3\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Sat Oct 3 10:12:35 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/include/linux/swap.h b/include/linux/swap.h\nindex 4f686709d71f0..ae2e49386443c 100644\n--- a/include/linux/swap.h\n+++ b/include/linux/swap.h\n@@ -201,6 +201,7 @@ enum {\n \tSWP_STABLE_WRITES = (1 \u003c\u003c 11),\t/* no overwrite PG_writeback pages */\n \tSWP_SYNCHRONOUS_IO = (1 \u003c\u003c 12),\t/* synchronous IO is efficient */\n \tSWP_HIBERNATION = (1 \u003c\u003c 13),\t/* pinned for hibernation */\n+\tSWP_XSWAP\t= (1 \u003c\u003c 14),\t/* extendable swap device */\n \t\t\t\t\t/* add others here before... */\n };\n \n@@ -239,15 +240,25 @@ struct swap_info_struct {\n \tsigned short\tprio;\t\t/* swap priority of this type */\n \tstruct plist_node list;\t\t/* entry in swap_active_head */\n \tsigned char\ttype;\t\t/* strange name for an index */\n-\tunsigned int\tmax;\t\t/* size of this swap device */\n+\tunsigned long\tmax;\t\t/* size of this swap device */\n \tstruct swap_cluster_info *cluster_info; /* array, one entry per cluster */\n+#ifdef CONFIG_XSWAP\n+\tstruct vm_struct\t*cluster_vm;\t/* VM_SPARSE area for cluster_info */\n+\tunsigned long\t\tnr_clusters_max;/* total clusters in the xswap address space */\n+\tunsigned long\t\tnr_clusters_mapped; /* currently mapped cluster count */\n+\tstruct work_struct\txswap_shrink_work; /* deferred shrink trigger */\n+\tstruct mutex\t\txswap_lock;\t/* serialize map/unmap operations */\n+\tstruct dentry\t\t*xswap_debugfs;\t/* mapped range and counters */\n+\tatomic_long_t\t\txswap_grows;\t/* grow operations so far */\n+\tatomic_long_t\t\txswap_shrinks;\t/* shrink operations so far */\n+#endif\n \tstruct list_head free_clusters; /* free clusters list */\n \tstruct list_head full_clusters; /* full clusters list */\n \tstruct list_head nonfull_clusters[SWAP_NR_ORDERS];\n \t\t\t\t\t/* list of cluster that contains at least one free slot */\n \tstruct list_head frag_clusters[SWAP_NR_ORDERS];\n \t\t\t\t\t/* list of cluster that are fragmented or contented */\n-\tunsigned int pages;\t\t/* total of usable pages of swap */\n+\tunsigned long pages;\t\t/* total of usable pages of swap */\n \tatomic_long_t inuse_pages;\t/* number of those currently in use */\n \tstruct swap_sequential_cluster *global_cluster; /* Use one global cluster for rotating device */\n \tspinlock_t global_cluster_lock;\t/* Serialize usage of global cluster */\n@@ -378,6 +389,7 @@ void free_folio_and_swap_cache(struct folio *folio);\n void free_pages_and_swap_cache(struct encoded_page **, int);\n /* linux/mm/swapfile.c */\n extern atomic_long_t nr_swap_pages;\n+extern atomic_t nr_real_swapfiles;\n extern long total_swap_pages;\n extern atomic_t nr_rotate_swap;\n \ndiff --git a/mm/Kconfig b/mm/Kconfig\nindex acefc994d9a8b..39927b5c75aca 100644\n--- a/mm/Kconfig\n+++ b/mm/Kconfig\n@@ -122,6 +122,15 @@ config ZSWAP_COMPRESSOR_DEFAULT\n        default \"zstd\" if ZSWAP_COMPRESSOR_DEFAULT_ZSTD\n        default \"\"\n \n+config XSWAP\n+\tbool \"Extendable (virtual) swap device\"\n+\tdepends on SWAP \u0026\u0026 64BIT \u0026\u0026 ZSWAP \u0026\u0026 SYSFS\n+\thelp\n+\t  Adds support for extendable swap devices (xswap) that decouple\n+\t  PTE swap entries from physical backing storage. The cluster_info\n+\t  array is backed by a sparse vmalloc area that grows and shrinks\n+\t  on demand, avoiding static pre-allocation overhead.\n+\n config ZSMALLOC\n \ttristate\n \ndiff --git a/mm/page_io.c b/mm/page_io.c\nindex c6824fcd483e0..25fa9b82ed46b 100644\n--- a/mm/page_io.c\n+++ b/mm/page_io.c\n@@ -248,6 +248,15 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)\n \t}\n \trcu_read_unlock();\n \n+\t/*\n+\t * xswap has no backing store: keep the folio.  ctx-\u003esis is not set\n+\t * yet, so look the device up from the entry.\n+\t */\n+\tif (unlikely(__swap_entry_to_info(folio-\u003eswap)-\u003eflags \u0026 SWP_XSWAP)) {\n+\t\tfolio_mark_dirty(folio);\n+\t\treturn AOP_WRITEPAGE_ACTIVATE;\n+\t}\n+\n \t__swap_writeout(ctx, folio);\n \treturn 0;\n out_unlock:\n@@ -486,6 +495,16 @@ void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio)\n \tif (zswap_load(folio) != -ENOENT)\n \t\tgoto finish;\n \n+\tif (unlikely(sis-\u003eflags \u0026 SWP_XSWAP)) {\n+\t\t/*\n+\t\t * An xswap entry only ever lives in zswap, so zswap_load()\n+\t\t * must have found it.  Unlock and let the caller retry.\n+\t\t */\n+\t\tWARN_ON_ONCE(1);\n+\t\tfolio_unlock(folio);\n+\t\tgoto finish;\n+\t}\n+\n \t/* We have to read from slower devices. Increase zswap protection. */\n \tzswap_folio_swapin(folio);\n \tswap_add_folio(ctx, folio, READ);\ndiff --git a/mm/swap_state.c b/mm/swap_state.c\nindex ebef568cd62ee..3a4e9e447b0b2 100644\n--- a/mm/swap_state.c\n+++ b/mm/swap_state.c\n@@ -884,6 +884,10 @@ struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask,\n \tstruct blk_plug plug;\n \tswp_entry_t ra_entry;\n \n+\t/* xswap entries live only in zswap; readahead does not help. */\n+\tif (si-\u003eflags \u0026 SWP_XSWAP)\n+\t\tgoto skip;\n+\n \tmask = swapin_nr_pages(offset) - 1;\n \tif (!mask)\n \t\tgoto skip;\n@@ -969,6 +973,7 @@ static int swap_vma_ra_win(struct vm_fault *vmf, unsigned long *start,\n static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,\n \t\tstruct mempolicy *mpol, pgoff_t targ_ilx, struct vm_fault *vmf)\n {\n+\tstruct swap_info_struct *si = __swap_entry_to_info(targ_entry);\n \tstruct swap_io_ctx ctx = {};\n \tstruct blk_plug plug;\n \tstruct folio *folio;\n@@ -977,6 +982,10 @@ static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,\n \tunsigned long start, end, addr;\n \tpgoff_t ilx = targ_ilx;\n \n+\t/* xswap entries live only in zswap; readahead does not help. */\n+\tif (si-\u003eflags \u0026 SWP_XSWAP)\n+\t\tgoto skip;\n+\n \twin = swap_vma_ra_win(vmf, \u0026start, \u0026end);\n \tif (win == 1)\n \t\tgoto skip;\ndiff --git a/mm/swapfile.c b/mm/swapfile.c\nindex c3288910b3e35..bf95663c2593a 100644\n--- a/mm/swapfile.c\n+++ b/mm/swapfile.c\n@@ -16,6 +16,8 @@\n #include \u003clinux/kernel_stat.h\u003e\n #include \u003clinux/swap.h\u003e\n #include \u003clinux/vmalloc.h\u003e\n+#include \u003clinux/kobject.h\u003e\n+#include \u003clinux/sysfs.h\u003e\n #include \u003clinux/pagemap.h\u003e\n #include \u003clinux/namei.h\u003e\n #include \u003clinux/shmem_fs.h\u003e\n@@ -47,7 +49,202 @@\n #include \u003clinux/leafops.h\u003e\n #include \"swap_table.h\"\n #include \"internal.h\"\n+#include \u003clinux/debugfs.h\u003e\n+\n #include \"swap.h\"\n+#define DEF_SWAP_PRIO  -1\n+\n+/*\n+ * Above every real swap device: one ahead of xswap would take the page\n+ * directly, and taking that slot is what xswap exists to avoid.\n+ */\n+#define DEF_XSWAP_PRIO\tSWAP_FLAG_PRIO_MASK\n+\n+#ifdef CONFIG_XSWAP\n+/*\n+ * xswap: dynamically grow and shrink the cluster_info array via a\n+ * VM_SPARSE area.\n+ *\n+ * XSWAP_GROW_CLUSTERS is the number of clusters to map/unmap in one\n+ * grow/shrink operation: the number of cluster_info structs that fit in\n+ * a single page (at least 16), so that the vmalloc page table overhead\n+ * is proportional to the number of clusters mapped.\n+ */\n+#define XSWAP_GROW_CLUSTERS \\\n+\tmax_t(unsigned long, PAGE_SIZE / sizeof(struct swap_cluster_info), 16)\n+\n+/*\n+ * Grow and shrink thresholds, as a percentage of the mapped range in use.\n+ * Each one lands inside (SHRINK_WHEN, GROW_WHEN), so neither can leave the\n+ * range in a state that wakes the other up.\n+ */\n+#define XSWAP_SHRINK_WHEN\t50\n+#define XSWAP_SHRINK_UNTIL\t70\n+#define XSWAP_GROW_UNTIL\t65\n+#define XSWAP_GROW_WHEN\t\t85\n+#define XSWAP_GROW_CHUNKS\t4\n+\n+static bool xswap_should_grow(struct swap_info_struct *si);\n+static unsigned long xswap_grow(struct swap_info_struct *si);\n+static void xswap_debugfs_del(struct swap_info_struct *si);\n+\n+/* Batch size for the fallback unmap; keeps the stack array small. */\n+#define XSWAP_UNMAP_BATCH_PAGES\t\t16\n+#define XSWAP_UNMAP_BATCH_CLUSTERS\t\t\t\t\t\\\n+\tmax_t(unsigned long,\t\t\t\t\t\t\\\n+\t      ((XSWAP_UNMAP_BATCH_PAGES * PAGE_SIZE) /\t\t\\\n+\t       sizeof(struct swap_cluster_info)), 16)\n+\n+static int xswap_map_clusters(struct swap_info_struct *si,\n+\t\t\t      unsigned long start_idx, unsigned long nr);\n+static void xswap_unmap_clusters(struct swap_info_struct *si,\n+\t\t\t\t unsigned long start_idx, unsigned long nr);\n+static int xswap_mapped_end(pte_t *pte, unsigned long addr, void *data);\n+static void xswap_try_shrink(struct swap_info_struct *si);\n+\n+static int xswap_create(int prio);\n+static int xswap_destroy(int type);\n+\n+static ssize_t xswap_create_store(struct kobject *kobj,\n+\t\t\t\t  struct kobj_attribute *attr,\n+\t\t\t\t  const char *buf, size_t count)\n+{\n+\tint prio = DEF_XSWAP_PRIO;\n+\tint err;\n+\n+\tif (!capable(CAP_SYS_ADMIN))\n+\t\treturn -EPERM;\n+\n+\t/* \"[\u003cprio\u003e]\" is optional; a lower one is allowed, not a higher. */\n+\tif (*skip_spaces(buf)) {\n+\t\terr = kstrtoint(buf, 10, \u0026prio);\n+\t\tif (err)\n+\t\t\treturn err;\n+\t}\n+\n+\terr = xswap_create(prio);\n+\tif (err \u003c 0)\n+\t\treturn err;\n+\n+\treturn count;\n+}\n+\n+static struct kobj_attribute xswap_create_attr = __ATTR(create, 0200, NULL,\n+\t\t\t\t\t\t\txswap_create_store);\n+\n+static ssize_t xswap_destroy_store(struct kobject *kobj,\n+\t\t\t\t   struct kobj_attribute *attr,\n+\t\t\t\t   const char *buf, size_t count)\n+{\n+\tunsigned long type;\n+\tint err;\n+\n+\tif (!capable(CAP_SYS_ADMIN))\n+\t\treturn -EPERM;\n+\n+\terr = kstrtoul(buf, 0, \u0026type);\n+\tif (err)\n+\t\treturn err;\n+\tif (type \u003e= MAX_SWAPFILES)\n+\t\treturn -EINVAL;\n+\n+\terr = xswap_destroy(type);\n+\tif (err)\n+\t\treturn err;\n+\n+\treturn count;\n+}\n+\n+static struct kobj_attribute xswap_destroy_attr = __ATTR(destroy, 0200, NULL,\n+\t\t\t\t\t\t\t xswap_destroy_store);\n+\n+static struct attribute *xswap_attrs[] = {\n+\t\u0026xswap_create_attr.attr,\n+\t\u0026xswap_destroy_attr.attr,\n+\tNULL,\n+};\n+\n+/* Size of a new device, from xswap.max=.  A percentage unless bytes is set. */\n+static unsigned int xswap_size_pct = 200;\n+static unsigned long xswap_size_bytes;\n+\n+static int __init xswap_max_setup(char *str)\n+{\n+\tunsigned int pct;\n+\tchar *end;\n+\n+\tend = strchr(str, '%');\n+\tif (end) {\n+\t\tif (end[1]) {\n+\t\t\tpr_err(\"xswap: bad xswap.max=%s\\n\", str);\n+\t\t\treturn 1;\n+\t\t}\n+\t\t*end = '\\0';\t/* writable copy, see parse_args() */\n+\t\tif (kstrtouint(str, 0, \u0026pct) || !pct) {\n+\t\t\tpr_err(\"xswap: bad xswap.max=%s%%\\n\", str);\n+\t\t\treturn 1;\n+\t\t}\n+\t\txswap_size_pct = pct;\n+\t\txswap_size_bytes = 0;\n+\t\treturn 1;\n+\t}\n+\n+\txswap_size_bytes = memparse(str, \u0026end);\n+\tif (*end || xswap_size_bytes \u003c PAGE_SIZE) {\n+\t\tpr_err(\"xswap: bad xswap.max=%s\\n\", str);\n+\t\txswap_size_bytes = 0;\n+\t\treturn 1;\n+\t}\n+\txswap_size_pct = 0;\n+\treturn 1;\n+}\n+__setup(\"xswap.max=\", xswap_max_setup);\n+\n+/* The most a device can address, whatever xswap.max= asked for. */\n+static unsigned long xswap_size_limit(void)\n+{\n+\tunsigned long limit = swapfile_maximum_size;\n+\n+\t/* A cluster index is an unsigned int. */\n+\tif (limit / SWAPFILE_CLUSTER \u003e UINT_MAX)\n+\t\tlimit = (unsigned long)UINT_MAX * SWAPFILE_CLUSTER;\n+\n+\treturn limit;\n+}\n+\n+static unsigned long xswap_size_pages(void)\n+{\n+\tif (xswap_size_bytes)\n+\t\treturn xswap_size_bytes \u003e\u003e PAGE_SHIFT;\n+\n+\treturn div_u64((unsigned long long)totalram_pages() * xswap_size_pct,\n+\t\t       100);\n+}\n+\n+static const struct attribute_group xswap_attr_group = {\n+\t.attrs = xswap_attrs,\n+};\n+\n+static struct kobject *xswap_kobj;\n+\n+static void xswap_sysfs_init(void)\n+{\n+\txswap_kobj = kobject_create_and_add(\"xswap\", mm_kobj);\n+\tif (!xswap_kobj) {\n+\t\tpr_err(\"xswap: failed to create sysfs kobject\\n\");\n+\t\treturn;\n+\t}\n+\tif (sysfs_create_group(xswap_kobj, \u0026xswap_attr_group)) {\n+\t\tpr_err(\"xswap: failed to create sysfs group\\n\");\n+\t\tkobject_put(xswap_kobj);\n+\t\txswap_kobj = NULL;\n+\t}\n+}\n+#else /* !CONFIG_XSWAP */\n+static inline void xswap_sysfs_init(void)\n+{\n+}\n+#endif /* CONFIG_XSWAP */\n \n static void swap_range_alloc(struct swap_info_struct *si,\n \t\t\t     unsigned int nr_entries);\n@@ -66,6 +263,9 @@ static void move_cluster(struct swap_info_struct *si,\n static DEFINE_SPINLOCK(swap_lock);\n static unsigned int nr_swapfiles;\n atomic_long_t nr_swap_pages;\n+atomic_t nr_real_swapfiles;\n+/* Active xswap devices, as in nr_real_swapfiles. */\n+static atomic_t nr_xswap_files;\n /*\n  * Some modules use swappable objects and may try to swap them out under\n  * memory pressure (via the shrinker). Before doing so, they may wish to\n@@ -74,7 +274,6 @@ atomic_long_t nr_swap_pages;\n EXPORT_SYMBOL_GPL(nr_swap_pages);\n /* protected with swap_lock. reading in vm_swap_full() doesn't need lock */\n long total_swap_pages;\n-#define DEF_SWAP_PRIO  -1\n unsigned long swapfile_maximum_size;\n #ifdef CONFIG_MIGRATION\n bool swap_migration_ad_supported;\n@@ -402,10 +601,10 @@ static inline unsigned int cluster_index(struct swap_info_struct *si,\n \treturn ci - si-\u003ecluster_info;\n }\n \n-static inline unsigned int cluster_offset(struct swap_info_struct *si,\n-\t\t\t\t\t  struct swap_cluster_info *ci)\n+static inline unsigned long cluster_offset(struct swap_info_struct *si,\n+\t\t\t\t\t   struct swap_cluster_info *ci)\n {\n-\treturn cluster_index(si, ci) * SWAPFILE_CLUSTER;\n+\treturn (unsigned long)cluster_index(si, ci) * SWAPFILE_CLUSTER;\n }\n \n static void swap_cluster_free_table_folio_rcu_cb(struct rcu_head *head)\n@@ -617,6 +816,11 @@ static void __free_cluster(struct swap_info_struct *si, struct swap_cluster_info\n \tswap_cluster_free_table(ci);\n \tmove_cluster(si, ci, \u0026si-\u003efree_clusters, CLUSTER_FLAG_FREE);\n \tci-\u003eorder = 0;\n+#ifdef CONFIG_XSWAP\n+\t/* Only xswap devices, and not while the device is being torn down. */\n+\tif ((si-\u003eflags \u0026 SWP_XSWAP) \u0026\u0026 (si-\u003eflags \u0026 SWP_WRITEOK))\n+\t\tschedule_work(\u0026si-\u003exswap_shrink_work);\n+#endif\n }\n \n /*\n@@ -733,7 +937,8 @@ static void free_cluster(struct swap_info_struct *si, struct swap_cluster_info *\n \t/*\n \t * If the swap is discardable, prepare discard the cluster\n \t * instead of free it immediately. The cluster will be freed\n-\t * after discard.\n+\t * after discard.  xswap has no bdev and never sets\n+\t * SWP_PAGE_DISCARD, so it always takes the free path below.\n \t */\n \tif ((si-\u003eflags \u0026 (SWP_WRITEOK | SWP_PAGE_DISCARD)) ==\n \t    (SWP_WRITEOK | SWP_PAGE_DISCARD)) {\n@@ -803,7 +1008,7 @@ static int swap_cluster_setup_bad_slot(struct swap_info_struct *si,\n \n \t/* si-\u003emax may got shrunk by swap swap_activate() */\n \tif (offset \u003e= si-\u003emax \u0026\u0026 !mask) {\n-\t\tpr_debug(\"Ignoring bad slot %u (max: %u)\\n\", offset, si-\u003emax);\n+\t\tpr_debug(\"Ignoring bad slot %u (max: %lu)\\n\", offset, si-\u003emax);\n \t\treturn 0;\n \t}\n \t/*\n@@ -969,11 +1174,12 @@ static bool __swap_cluster_alloc_entries(struct swap_info_struct *si,\n }\n \n /* Try use a new cluster for current CPU and allocate from it. */\n-static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,\n-\t\t\t\t\t    struct swap_cluster_info *ci,\n-\t\t\t\t\t    struct folio *folio, unsigned long offset)\n+static unsigned long alloc_swap_scan_cluster(struct swap_info_struct *si,\n+\t\t\t\t\t     struct swap_cluster_info *ci,\n+\t\t\t\t\t     struct folio *folio,\n+\t\t\t\t\t     unsigned long offset)\n {\n-\tunsigned int next = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID;\n+\tunsigned long next = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID;\n \tunsigned long start = ALIGN_DOWN(offset, SWAPFILE_CLUSTER);\n \tunsigned int order = likely(folio) ? folio_order(folio) : 0;\n \tunsigned long end = start + SWAPFILE_CLUSTER;\n@@ -983,6 +1189,9 @@ static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,\n \tlockdep_assert_held(\u0026ci-\u003elock);\n \tVM_WARN_ON(!cluster_is_usable(ci, order));\n \n+\t/* ci is used without ci-\u003elock; an xswap unmap waits for this. */\n+\trcu_read_lock();\n+\n \tif (end \u003c nr_pages || ci-\u003ecount + nr_pages \u003e SWAPFILE_CLUSTER)\n \t\tgoto out;\n \n@@ -1011,6 +1220,7 @@ static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,\n out:\n \trelocate_cluster(si, ci);\n \tswap_cluster_unlock(ci);\n+\trcu_read_unlock();\n \tif (si-\u003eflags \u0026 SWP_SOLIDSTATE) {\n \t\tthis_cpu_write(percpu_swap_cluster.offset[order], next);\n \t\tthis_cpu_write(percpu_swap_cluster.si[order], si);\n@@ -1020,12 +1230,12 @@ static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,\n \treturn found;\n }\n \n-static unsigned int alloc_swap_scan_list(struct swap_info_struct *si,\n-\t\t\t\t\t struct list_head *list,\n-\t\t\t\t\t struct folio *folio,\n-\t\t\t\t\t bool scan_all)\n+static unsigned long alloc_swap_scan_list(struct swap_info_struct *si,\n+\t\t\t\t\t  struct list_head *list,\n+\t\t\t\t\t  struct folio *folio,\n+\t\t\t\t\t  bool scan_all)\n {\n-\tunsigned int found = SWAP_ENTRY_INVALID;\n+\tunsigned long found = SWAP_ENTRY_INVALID;\n \n \tdo {\n \t\tstruct swap_cluster_info *ci = isolate_lock_cluster(si, list);\n@@ -1054,6 +1264,9 @@ static void swap_reclaim_full_clusters(struct swap_info_struct *si, bool force)\n \t\tto_scan = swap_usage_in_pages(si) / SWAPFILE_CLUSTER;\n \n \twhile ((ci = isolate_lock_cluster(si, \u0026si-\u003efull_clusters))) {\n+\t\t/* As in alloc_swap_scan_cluster(). */\n+\t\trcu_read_lock();\n+\n \t\toffset = cluster_offset(si, ci);\n \t\tend = min(si-\u003emax, offset + SWAPFILE_CLUSTER);\n \t\tto_scan--;\n@@ -1078,6 +1291,7 @@ static void swap_reclaim_full_clusters(struct swap_info_struct *si, bool force)\n \t\t\trelocate_cluster(si, ci);\n \n \t\tswap_cluster_unlock(ci);\n+\t\trcu_read_unlock();\n \t\tif (to_scan \u003c= 0)\n \t\t\tbreak;\n \n@@ -1108,7 +1322,7 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,\n {\n \tstruct swap_cluster_info *ci;\n \tunsigned int order = likely(folio) ? folio_order(folio) : 0;\n-\tunsigned int offset = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID;\n+\tunsigned long offset = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID;\n \n \t/*\n \t * Swapfile is not block device so unable\n@@ -1117,6 +1331,17 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,\n \tif (order \u0026\u0026 !(si-\u003eflags \u0026 SWP_BLKDEV))\n \t\treturn 0;\n \n+#ifdef CONFIG_XSWAP\n+\t/*\n+\t * Top the range up early.  Every path below leaves through `done`,\n+\t * so this has to come first; mapping pages can sleep, and doing it\n+\t * from the allocation that would otherwise fail leaves nothing to\n+\t * fall back on.\n+\t */\n+\tif ((si-\u003eflags \u0026 SWP_XSWAP) \u0026\u0026 xswap_should_grow(si))\n+\t\txswap_grow(si);\n+#endif\n+\n \tif (!(si-\u003eflags \u0026 SWP_SOLIDSTATE)) {\n \t\t/* Serialize HDD SWAP allocation for each device. */\n \t\tspin_lock(\u0026si-\u003eglobal_cluster_lock);\n@@ -1193,6 +1418,12 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,\n \t\tif (found)\n \t\t\tgoto done;\n \t}\n+\n+#ifdef CONFIG_XSWAP\n+\t/* A concurrent free or grow may have added clusters; retry once. */\n+\tif (!found \u0026\u0026 (si-\u003eflags \u0026 SWP_XSWAP))\n+\t\tfound = alloc_swap_scan_list(si, \u0026si-\u003efree_clusters, folio, false);\n+#endif\n done:\n \tif (!(si-\u003eflags \u0026 SWP_SOLIDSTATE))\n \t\tspin_unlock(\u0026si-\u003eglobal_cluster_lock);\n@@ -1216,6 +1447,11 @@ static void del_from_avail_list(struct swap_info_struct *si, bool swapoff)\n \t\t */\n \t\tlockdep_assert_held(\u0026si-\u003elock);\n \t\tsi-\u003eflags \u0026= ~SWP_WRITEOK;\n+\t\t/* Count active devices, not merely those on the avail list. */\n+\t\tif (si-\u003eflags \u0026 SWP_XSWAP)\n+\t\t\tatomic_sub(1, \u0026nr_xswap_files);\n+\t\telse\n+\t\t\tatomic_sub(1, \u0026nr_real_swapfiles);\n \t\tatomic_long_or(SWAP_USAGE_OFFLIST_BIT, \u0026si-\u003einuse_pages);\n \t} else {\n \t\t/*\n@@ -1273,6 +1509,12 @@ static void add_to_avail_list(struct swap_info_struct *si, bool swapon)\n \t}\n \n \tplist_add(\u0026si-\u003eavail_list, \u0026swap_avail_head);\n+\tif (swapon) {\n+\t\tif (si-\u003eflags \u0026 SWP_XSWAP)\n+\t\t\tatomic_add(1, \u0026nr_xswap_files);\n+\t\telse\n+\t\t\tatomic_add(1, \u0026nr_real_swapfiles);\n+\t}\n \n skip:\n \tspin_unlock(\u0026swap_avail_lock);\n@@ -1370,21 +1612,32 @@ static bool get_swap_device_info(struct swap_info_struct *si)\n  * Fast path try to get swap entries with specified order from current\n  * CPU's swap entry pool (a cluster).\n  */\n-static bool swap_alloc_fast(struct folio *folio)\n+static bool swap_alloc_fast(struct folio *folio, bool may_zswap)\n {\n \tunsigned int order = folio_order(folio);\n \tstruct swap_cluster_info *ci;\n \tstruct swap_info_struct *si;\n-\tunsigned int offset;\n+\tunsigned long offset;\n \n \t/*\n \t * Once allocated, swap_info_struct will never be completely freed,\n \t * so checking it's liveness by get_swap_device_info is enough.\n+\t *\n+\t * The cached offset indexes si-\u003ecluster_info, which xswap can\n+\t * unmap; cover both the read and the use with RCU.\n \t */\n+\trcu_read_lock();\n \tsi = this_cpu_read(percpu_swap_cluster.si[order]);\n \toffset = this_cpu_read(percpu_swap_cluster.offset[order]);\n-\tif (!si || !offset || !get_swap_device_info(si))\n+\tif (!si || !offset || !get_swap_device_info(si)) {\n+\t\trcu_read_unlock();\n+\t\treturn false;\n+\t}\n+\tif (!may_zswap \u0026\u0026 (si-\u003eflags \u0026 SWP_XSWAP)) {\n+\t\tput_swap_device(si);\n+\t\trcu_read_unlock();\n \t\treturn false;\n+\t}\n \n \tci = swap_cluster_lock(si, offset);\n \tif (cluster_is_usable(ci, order)) {\n@@ -1396,17 +1649,24 @@ static bool swap_alloc_fast(struct folio *folio)\n \t}\n \n \tput_swap_device(si);\n+\trcu_read_unlock();\n \treturn folio_test_swapcache(folio);\n }\n \n /* Rotate the device and switch to a new cluster */\n-static void swap_alloc_slow(struct folio *folio)\n+static void swap_alloc_slow(struct folio *folio, bool may_zswap)\n {\n \tstruct swap_info_struct *si, *next;\n \n \tspin_lock(\u0026swap_avail_lock);\n start_over:\n \tplist_for_each_entry_safe(si, next, \u0026swap_avail_head, avail_list) {\n+\t\t/*\n+\t\t * Do not rotate a skipped device: the walk follows the\n+\t\t * rotation and would spin forever.\n+\t\t */\n+\t\tif (!may_zswap \u0026\u0026 (si-\u003eflags \u0026 SWP_XSWAP))\n+\t\t\tcontinue;\n \t\t/* Rotate the device and switch to a new cluster */\n \t\tplist_requeue(\u0026si-\u003eavail_list, \u0026swap_avail_head);\n \t\tspin_unlock(\u0026swap_avail_lock);\n@@ -1745,10 +2005,24 @@ int folio_alloc_swap(struct folio *folio)\n {\n \tunsigned int order = folio_order(folio);\n \tunsigned int size = 1 \u003c\u003c order;\n+\tstruct obj_cgroup *objcg;\n+\t/* True unless the gate below finds an xswap device to route away from. */\n+\tbool may_zswap = true;\n \n \tVM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);\n \tVM_BUG_ON_FOLIO(!folio_test_uptodate(folio), folio);\n \n+\t/*\n+\t * A folio that zswap will not take must not get an xswap slot. With\n+\t * no xswap device to route away from, skip the lookup.\n+\t */\n+\tif (atomic_read(\u0026nr_xswap_files)) {\n+\t\tobjcg = get_obj_cgroup_from_folio(folio);\n+\t\tmay_zswap = !objcg || obj_cgroup_may_zswap(objcg);\n+\t\tif (objcg)\n+\t\t\tobj_cgroup_put(objcg);\n+\t}\n+\n \tif (order) {\n \t\t/*\n \t\t * Reject large allocation when THP_SWAP is disabled. Check below\n@@ -1769,8 +2043,8 @@ int folio_alloc_swap(struct folio *folio)\n \n again:\n \tlocal_lock(\u0026percpu_swap_cluster.lock);\n-\tif (!swap_alloc_fast(folio))\n-\t\tswap_alloc_slow(folio);\n+\tif (!swap_alloc_fast(folio, may_zswap))\n+\t\tswap_alloc_slow(folio, may_zswap);\n \tlocal_unlock(\u0026percpu_swap_cluster.lock);\n \n \tif (!order \u0026\u0026 unlikely(!folio_test_swapcache(folio))) {\n@@ -2186,8 +2460,11 @@ swp_entry_t swap_alloc_hibernation_slot(int type)\n \t/*\n \t * Try the local cluster first if it matches the device. If\n \t * not, try grab a new cluster and override local cluster.\n+\t *\n+\t * Same RCU requirement as swap_alloc_fast().\n \t */\n \tlocal_lock(\u0026percpu_swap_cluster.lock);\n+\trcu_read_lock();\n \tpcp_si = this_cpu_read(percpu_swap_cluster.si[0]);\n \tpcp_offset = this_cpu_read(percpu_swap_cluster.offset[0]);\n \tif (pcp_si == si \u0026\u0026 pcp_offset) {\n@@ -2197,6 +2474,7 @@ swp_entry_t swap_alloc_hibernation_slot(int type)\n \t\telse\n \t\t\tswap_cluster_unlock(ci);\n \t}\n+\trcu_read_unlock();\n \tif (!offset)\n \t\toffset = cluster_alloc_swap_entry(si, NULL);\n \tlocal_unlock(\u0026percpu_swap_cluster.lock);\n@@ -2249,6 +2527,9 @@ static int __find_hibernation_swap_type(dev_t device, sector_t offset)\n \n \t\tif (!(sis-\u003eflags \u0026 SWP_WRITEOK))\n \t\t\tcontinue;\n+\t\t/* xswap has no bdev to match a resume device */\n+\t\tif (sis-\u003eflags \u0026 SWP_XSWAP)\n+\t\t\tcontinue;\n \n \t\tif (device == sis-\u003ebdev-\u003ebd_dev) {\n \t\t\tstruct swap_extent *se = first_se(sis);\n@@ -2436,6 +2717,8 @@ int find_first_swap(dev_t *device)\n \n \t\tif (!(sis-\u003eflags \u0026 SWP_WRITEOK))\n \t\t\tcontinue;\n+\t\tif (sis-\u003eflags \u0026 SWP_XSWAP)\n+\t\t\tcontinue;\n \t\t*device = sis-\u003ebdev-\u003ebd_dev;\n \t\tspin_unlock(\u0026swap_lock);\n \t\treturn type;\n@@ -2788,14 +3071,31 @@ static int unuse_mm(struct mm_struct *mm, unsigned int type)\n  * Return 0 if there are no inuse entries after prev till end of\n  * the map.\n  */\n-static unsigned int find_next_to_unuse(struct swap_info_struct *si,\n-\t\t\t\t\tunsigned int prev)\n+static unsigned long find_next_to_unuse(struct swap_info_struct *si,\n+\t\t\t\t\tunsigned long prev)\n {\n \tstruct swap_cluster_info *ci;\n-\tunsigned long i, end;\n+\tunsigned long i, cluster_end, end;\n \tunsigned int ci_off;\n \tunsigned long swp_tb;\n \n+\tend = si-\u003emax;\n+#ifdef CONFIG_XSWAP\n+\t/*\n+\t * An xswap device maps its cluster_info in chunks as it grows, so\n+\t * the tail past nr_clusters_mapped has nothing behind it.\n+\t */\n+\tif (si-\u003eflags \u0026 SWP_XSWAP) {\n+\t\tunsigned long mapped_end;\n+\n+\t\t/* Pairs with the smp_store_release() in xswap_map_clusters(). */\n+\t\tmapped_end = smp_load_acquire(\u0026si-\u003enr_clusters_mapped) *\n+\t\t\t     SWAPFILE_CLUSTER;\n+\t\tif (mapped_end \u003c end)\n+\t\t\tend = mapped_end;\n+\t}\n+#endif\n+\n \t/*\n \t * No need for swap_lock here: we're just looking\n \t * for whether an entry is in use, not modifying it; false\n@@ -2803,11 +3103,11 @@ static unsigned int find_next_to_unuse(struct swap_info_struct *si,\n \t * allocations from this area (while holding swap_lock).\n \t */\n \ti = prev + 1;\n-\twhile (i \u003c si-\u003emax) {\n+\twhile (i \u003c end) {\n \t\tci = __swap_offset_to_cluster(si, i);\n-\t\tend = min_t(unsigned long,\n-\t\t\t    ALIGN_DOWN(i, SWAPFILE_CLUSTER) + SWAPFILE_CLUSTER,\n-\t\t\t    si-\u003emax);\n+\t\tcluster_end = min_t(unsigned long,\n+\t\t\t\t    ALIGN_DOWN(i, SWAPFILE_CLUSTER) + SWAPFILE_CLUSTER,\n+\t\t\t\t    end);\n \n \t\t/*\n \t\t * An empty cluster has no slot in use, so skip it whole.\n@@ -2817,13 +3117,13 @@ static unsigned int find_next_to_unuse(struct swap_info_struct *si,\n \t\t * enough, unlike in every other cluster_is_empty() caller.\n \t\t */\n \t\tif (!READ_ONCE(ci-\u003ecount)) {\n-\t\t\ti = end;\n+\t\t\ti = cluster_end;\n \t\t\tcond_resched();\n \t\t\tcontinue;\n \t\t}\n \n \t\tci_off = i % SWAPFILE_CLUSTER;\n-\t\tfor (; i \u003c end; ci_off++, i++) {\n+\t\tfor (; i \u003c cluster_end; ci_off++, i++) {\n \t\t\tswp_tb = swap_table_get(ci, ci_off);\n \t\t\tif (!swp_tb_is_null(swp_tb) \u0026\u0026 !swp_tb_is_bad(swp_tb))\n \t\t\t\treturn i;\n@@ -2833,7 +3133,6 @@ static unsigned int find_next_to_unuse(struct swap_info_struct *si,\n \n \treturn 0;\n }\n-\n static int try_to_unuse(unsigned int type)\n {\n \tstruct mm_struct *prev_mm;\n@@ -2843,7 +3142,7 @@ static int try_to_unuse(unsigned int type)\n \tstruct swap_info_struct *si = swap_info[type];\n \tstruct folio *folio;\n \tswp_entry_t entry;\n-\tunsigned int i;\n+\tunsigned long i;\n \n \tif (!swap_usage_in_pages(si))\n \t\tgoto success;\n@@ -3131,20 +3430,62 @@ static void wait_for_allocation(struct swap_info_struct *si)\n \n \tBUG_ON(si-\u003eflags \u0026 SWP_WRITEOK);\n \n+#ifdef CONFIG_XSWAP\n+\tif (si-\u003eflags \u0026 SWP_XSWAP) {\n+\t\t/* Pairs with the smp_store_release() in xswap_map_clusters(). */\n+\t\tend = min(end, smp_load_acquire(\u0026si-\u003enr_clusters_mapped) *\n+\t\t\t  SWAPFILE_CLUSTER);\n+\t}\n+#endif\n+\n \tfor (offset = 0; offset \u003c end; offset += SWAPFILE_CLUSTER) {\n \t\tci = swap_cluster_lock(si, offset);\n \t\tswap_cluster_unlock(ci);\n \t}\n }\n \n-static void free_swap_cluster_info(struct swap_cluster_info *cluster_info,\n-\t\t\t\t   unsigned long maxpages)\n+static void free_swap_cluster_info(struct swap_info_struct *si)\n {\n+\tstruct swap_cluster_info *cluster_info = si-\u003ecluster_info;\n+\tunsigned long maxpages = si-\u003emax;\n \tstruct swap_cluster_info *ci;\n-\tint i, nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);\n+\tunsigned long i, nr_clusters;\n \n \tif (!cluster_info)\n \t\treturn;\n+\n+#ifdef CONFIG_XSWAP\n+\tif (si-\u003eflags \u0026 SWP_XSWAP) {\n+\t\tunsigned long nr_mapped;\n+\n+\t\tcancel_work_sync(\u0026si-\u003exswap_shrink_work);\n+\t\t/*\n+\t\t * Cluster 0 keeps the bad header slot, so it never empties\n+\t\t * and __free_cluster() never frees its table.\n+\t\t */\n+\t\t/* Pairs with the smp_store_release() in xswap_map_clusters(). */\n+\t\tnr_mapped = smp_load_acquire(\u0026si-\u003enr_clusters_mapped);\n+\t\tfor (i = 0; i \u003c nr_mapped; i++) {\n+\t\t\tci = \u0026cluster_info[i];\n+\t\t\tspin_lock(\u0026ci-\u003elock);\n+\t\t\tif (cluster_table_is_alloced(ci)) {\n+\t\t\t\tswap_cluster_assert_empty(ci, 0, SWAPFILE_CLUSTER, true);\n+\t\t\t\tswap_cluster_free_table(ci);\n+\t\t\t}\n+\t\t\tspin_unlock(\u0026ci-\u003elock);\n+\t\t}\n+\t\t/* free_vm_area() drops the mapping without freeing the pages. */\n+\t\txswap_unmap_clusters(si, 0, si-\u003enr_clusters_mapped);\n+\t\txswap_debugfs_del(si);\n+\t\tfree_vm_area(si-\u003ecluster_vm);\n+\t\tsi-\u003ecluster_vm = NULL;\n+\t\tsi-\u003ecluster_info = NULL;\n+\t\tsi-\u003enr_clusters_mapped = 0;\n+\t\treturn;\n+\t}\n+#endif\n+\n+\tnr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);\n \tfor (i = 0; i \u003c nr_clusters; i++) {\n \t\tci = cluster_info + i;\n \t\t/* Cluster with bad marks count will have a remaining table */\n@@ -3156,6 +3497,7 @@ static void free_swap_cluster_info(struct swap_cluster_info *cluster_info,\n \t\tspin_unlock(\u0026ci-\u003elock);\n \t}\n \tkvfree(cluster_info);\n+\tsi-\u003ecluster_info = NULL;\n }\n \n /*\n@@ -3179,15 +3521,14 @@ static void flush_percpu_swap_cluster(struct swap_info_struct *si)\n \t}\n }\n \n+static int swap_info_remove(struct swap_info_struct *p);\n+static int __swapoff(struct swap_info_struct *p);\n \n SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)\n {\n \tstruct swap_info_struct *p = NULL;\n-\tstruct swap_cluster_info *cluster_info;\n-\tstruct file *swap_file, *victim;\n+\tstruct file *victim;\n \tstruct address_space *mapping;\n-\tstruct inode *inode;\n-\tunsigned int maxpages;\n \tint err, found = 0;\n \n \tif (!capable(CAP_SYS_ADMIN))\n@@ -3204,7 +3545,7 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)\n \tspin_lock(\u0026swap_lock);\n \tplist_for_each_entry(p, \u0026swap_active_head, list) {\n \t\tif (p-\u003eflags \u0026 SWP_WRITEOK) {\n-\t\t\tif (p-\u003eswap_file-\u003ef_mapping == mapping) {\n+\t\t\tif (p-\u003eswap_file \u0026\u0026 p-\u003eswap_file-\u003ef_mapping == mapping) {\n \t\t\t\tfound = 1;\n \t\t\t\tbreak;\n \t\t\t}\n@@ -3223,20 +3564,59 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)\n \t\tgoto out_dput;\n \t}\n \n-\tif (!security_vm_enough_memory_mm(current-\u003emm, p-\u003epages))\n-\t\tvm_unacct_memory(p-\u003epages);\n-\telse {\n-\t\terr = -ENOMEM;\n+\terr = swap_info_remove(p);\n+\tif (err) {\n \t\tspin_unlock(\u0026swap_lock);\n \t\tgoto out_dput;\n \t}\n+\tspin_unlock(\u0026swap_lock);\n+\n+\terr = __swapoff(p);\n+\n+out_dput:\n+\tfilp_close(victim, NULL);\n+\treturn err;\n+}\n+\n+/*\n+ * Drop @p from the avail and active lists and undo its accounting.  The\n+ * caller must hold swap_lock and have checked that @p is WRITEOK and not\n+ * pinned for hibernation.\n+ *\n+ * Returns 0, or -ENOMEM with swap_lock still held.\n+ */\n+static int swap_info_remove(struct swap_info_struct *p)\n+{\n+\tif (!security_vm_enough_memory_mm(current-\u003emm, p-\u003epages))\n+\t\tvm_unacct_memory(p-\u003epages);\n+\telse\n+\t\treturn -ENOMEM;\n+\n \tspin_lock(\u0026p-\u003elock);\n \tdel_from_avail_list(p, true);\n \tplist_del(\u0026p-\u003elist, \u0026swap_active_head);\n \tatomic_long_sub(p-\u003epages, \u0026nr_swap_pages);\n \ttotal_swap_pages -= p-\u003epages;\n \tspin_unlock(\u0026p-\u003elock);\n-\tspin_unlock(\u0026swap_lock);\n+\treturn 0;\n+}\n+\n+/* Common swap teardown after list removal; shared by sys_swapoff() and\n+ * xswap_destroy().\n+ */\n+static int __swapoff(struct swap_info_struct *p)\n+{\n+\tstruct file *swap_file = NULL;\n+\tint err;\n+\n+#ifdef CONFIG_XSWAP\n+\tif (p-\u003eflags \u0026 SWP_XSWAP) {\n+\t\tcancel_work_sync(\u0026p-\u003exswap_shrink_work);\n+\t\t/* Wait out a shrink racing us from the sysfs write path. */\n+\t\tmutex_lock(\u0026p-\u003exswap_lock);\n+\t\tmutex_unlock(\u0026p-\u003exswap_lock);\n+\t}\n+#endif\n \n \twait_for_allocation(p);\n \n@@ -3247,7 +3627,7 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)\n \tif (err) {\n \t\t/* re-insert swap space back into swap_list */\n \t\treinsert_swap_info(p);\n-\t\tgoto out_dput;\n+\t\treturn err;\n \t}\n \n \t/*\n@@ -3268,7 +3648,8 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)\n \n \tdestroy_swap_extents(p, p-\u003eswap_file);\n \n-\tif (!(p-\u003eflags \u0026 SWP_SOLIDSTATE))\n+\tif (!(p-\u003eflags \u0026 SWP_XSWAP) \u0026\u0026\n+\t    !(p-\u003eflags \u0026 SWP_SOLIDSTATE))\n \t\tatomic_dec(\u0026nr_rotate_swap);\n \n \tmutex_lock(\u0026swapon_mutex);\n@@ -3278,10 +3659,6 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)\n \n \tswap_file = p-\u003eswap_file;\n \tp-\u003eswap_file = NULL;\n-\tmaxpages = p-\u003emax;\n-\tcluster_info = p-\u003ecluster_info;\n-\tp-\u003emax = 0;\n-\tp-\u003ecluster_info = NULL;\n \tspin_unlock(\u0026p-\u003elock);\n \tspin_unlock(\u0026swap_lock);\n \tarch_swap_invalidate_area(p-\u003etype);\n@@ -3289,14 +3666,22 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)\n \tmutex_unlock(\u0026swapon_mutex);\n \tkfree(p-\u003eglobal_cluster);\n \tp-\u003eglobal_cluster = NULL;\n-\tfree_swap_cluster_info(cluster_info, maxpages);\n+\tfree_swap_cluster_info(p);\n+\t/*\n+\t * The device is off swap_active_head and no longer WRITEOK, so no\n+\t * reader can observe these; clearing them here needs no lock.\n+\t */\n+\tp-\u003emax = 0;\n+\tp-\u003ecluster_info = NULL;\n \n-\tinode = mapping-\u003ehost;\n+\tif (swap_file) {\n+\t\tstruct inode *inode = swap_file-\u003ef_mapping-\u003ehost;\n \n-\tinode_lock(inode);\n-\tinode-\u003ei_flags \u0026= ~S_SWAPFILE;\n-\tinode_unlock(inode);\n-\tfilp_close(swap_file, NULL);\n+\t\tinode_lock(inode);\n+\t\tinode-\u003ei_flags \u0026= ~S_SWAPFILE;\n+\t\tinode_unlock(inode);\n+\t\tfilp_close(swap_file, NULL);\n+\t}\n \n \t/*\n \t * Clear the SWP_USED flag after all resources are freed so that swapon\n@@ -3307,13 +3692,10 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)\n \tp-\u003eflags = 0;\n \tspin_unlock(\u0026swap_lock);\n \n-\terr = 0;\n \tatomic_inc(\u0026proc_poll_event);\n \twake_up_interruptible(\u0026proc_poll_wait);\n \n-out_dput:\n-\tfilp_close(victim, NULL);\n-\treturn err;\n+\treturn 0;\n }\n \n #ifdef CONFIG_PROC_FS\n@@ -3344,7 +3726,8 @@ static void *swap_start(struct seq_file *swap, loff_t *pos)\n \t\treturn SEQ_START_TOKEN;\n \n \tfor (type = 0; (si = swap_type_to_info(type)); type++) {\n-\t\tif (!(si-\u003eswap_file))\n+\t\tif (!si-\u003eswap_file \u0026\u0026\n+\t\t    !((si-\u003eflags \u0026 SWP_XSWAP) \u0026\u0026 (si-\u003eflags \u0026 SWP_WRITEOK)))\n \t\t\tcontinue;\n \t\tif (!--l)\n \t\t\treturn si;\n@@ -3365,7 +3748,8 @@ static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)\n \n \t++(*pos);\n \tfor (; (si = swap_type_to_info(type)); type++) {\n-\t\tif (!(si-\u003eswap_file))\n+\t\tif (!si-\u003eswap_file \u0026\u0026\n+\t\t    !((si-\u003eflags \u0026 SWP_XSWAP) \u0026\u0026 (si-\u003eflags \u0026 SWP_WRITEOK)))\n \t\t\tcontinue;\n \t\treturn si;\n \t}\n@@ -3378,6 +3762,19 @@ static void swap_stop(struct seq_file *swap, void *v)\n \tmutex_unlock(\u0026swapon_mutex);\n }\n \n+static const char *swap_type_str(struct swap_info_struct *si)\n+{\n+\tstruct file *file = si-\u003eswap_file;\n+\n+\tif (si-\u003eflags \u0026 SWP_XSWAP)\n+\t\treturn \"xswap\\t\";\n+\n+\tif (S_ISBLK(file_inode(file)-\u003ei_mode))\n+\t\treturn \"partition\";\n+\n+\treturn \"file\\t\";\n+}\n+\n static int swap_show(struct seq_file *swap, void *v)\n {\n \tstruct swap_info_struct *si = v;\n@@ -3394,11 +3791,17 @@ static int swap_show(struct seq_file *swap, void *v)\n \tinuse = K(swap_usage_in_pages(si));\n \n \tfile = si-\u003eswap_file;\n-\tlen = seq_file_path(swap, file, \" \\t\\n\\\\\");\n+\tif (file)\n+\t\tlen = seq_file_path(swap, file, \" \\t\\n\\\\\");\n+\telse {\n+\t\tchar name[16];\n+\n+\t\tlen = scnprintf(name, sizeof(name), \"xswap%d\", si-\u003etype);\n+\t\tseq_puts(swap, name);\n+\t}\n \tseq_printf(swap, \"%*s%s\\t%lu\\t%s%lu\\t%s%d\\n\",\n \t\t\tlen \u003c 40 ? 40 - len : 1, \" \",\n-\t\t\tS_ISBLK(file_inode(file)-\u003ei_mode) ?\n-\t\t\t\t\"partition\" : \"file\\t\",\n+\t\t\tswap_type_str(si),\n \t\t\tbytes, bytes \u003c 10000000 ? \"\\t\" : \"\",\n \t\t\tinuse, inuse \u003c 10000000 ? \"\\t\" : \"\",\n \t\t\tsi-\u003eprio);\n@@ -3609,12 +4012,8 @@ static unsigned long read_swap_header(struct swap_info_struct *si,\n \t\tpr_warn(\"Truncating oversized swap area, only using %luk out of %luk\\n\",\n \t\t\tK(maxpages), K(last_page));\n \t}\n-\tif (maxpages \u003e last_page) {\n+\tif (maxpages \u003e last_page)\n \t\tmaxpages = last_page + 1;\n-\t\t/* p-\u003emax is an unsigned int: don't overflow it */\n-\t\tif ((unsigned int)maxpages == 0)\n-\t\t\tmaxpages = UINT_MAX;\n-\t}\n \n \tif (!maxpages)\n \t\treturn 0;\n@@ -3631,6 +4030,483 @@ static unsigned long read_swap_header(struct swap_info_struct *si,\n \treturn maxpages;\n }\n \n+#ifdef CONFIG_XSWAP\n+static int xswap_map_clusters(struct swap_info_struct *si,\n+\t\t\t      unsigned long start_idx, unsigned long nr)\n+{\n+\tunsigned long start_addr = (unsigned long)si-\u003ecluster_info +\n+\t\t\t\t   (size_t)start_idx * sizeof(struct swap_cluster_info);\n+\tunsigned long end_addr = start_addr + (size_t)nr * sizeof(struct swap_cluster_info);\n+\tunsigned long vm_start = PAGE_ALIGN(start_addr);\n+\tunsigned long vm_end = PAGE_ALIGN(end_addr);\n+\tunsigned int noreclaim_flags;\n+\tunsigned long mapped_end;\n+\tunsigned long npages;\n+\tstruct page **pages;\n+\tunsigned long i;\n+\tint err;\n+\n+\tmutex_lock(\u0026si-\u003exswap_lock);\n+\n+\t/* Refuse a stale range: the boundary moved since the caller read it. */\n+\tif (start_idx != READ_ONCE(si-\u003enr_clusters_mapped)) {\n+\t\tmutex_unlock(\u0026si-\u003exswap_lock);\n+\t\treturn -EAGAIN;\n+\t}\n+\tif (start_idx + nr \u003e si-\u003enr_clusters_max) {\n+\t\tmutex_unlock(\u0026si-\u003exswap_lock);\n+\t\treturn -EAGAIN;\n+\t}\n+\n+\t/*\n+\t * Page-granular mapping can cover clusters past the previous chunk.\n+\t * Find the already-mapped prefix and map only the rest.\n+\t */\n+\tmapped_end = vm_start;\n+\tif (vm_start \u003c vm_end)\n+\t\tapply_to_existing_page_range(\u0026init_mm, vm_start,\n+\t\t\t\t\t     vm_end - vm_start,\n+\t\t\t\t\t     xswap_mapped_end, \u0026mapped_end);\n+\tif (vm_start \u003e= vm_end || mapped_end == vm_end)\n+\t\tgoto mapped;\n+\tvm_start = mapped_end;\n+\n+\tnpages = (vm_end - vm_start) \u003e\u003e PAGE_SHIFT;\n+\n+\t/* Prevent recursive reclaim during vmap page table allocation. */\n+\tnoreclaim_flags = memalloc_noreclaim_save();\n+\n+\tpages = kmalloc_array(npages, sizeof(*pages),\n+\t\t\t      __GFP_HIGH | __GFP_NOMEMALLOC | GFP_KERNEL);\n+\tif (!pages) {\n+\t\tmemalloc_noreclaim_restore(noreclaim_flags);\n+\t\tmutex_unlock(\u0026si-\u003exswap_lock);\n+\t\treturn -ENOMEM;\n+\t}\n+\n+\tfor (i = 0; i \u003c npages; i++) {\n+\t\t/* __GFP_ZERO: cluster_info pointer fields must start NULL. */\n+\t\tpages[i] = alloc_page(__GFP_HIGH | __GFP_NOMEMALLOC |\n+\t\t\t\t      GFP_KERNEL | __GFP_ZERO);\n+\t\tif (!pages[i])\n+\t\t\tgoto fail;\n+\t}\n+\n+\terr = vm_area_map_pages(si-\u003ecluster_vm, vm_start, vm_end, pages);\n+\tif (err) {\n+\t\ti = npages;\n+\t\tgoto fail;\n+\t}\n+\n+\tfor (i = start_idx; i \u003c start_idx + nr; i++)\n+\t\tspin_lock_init(\u0026si-\u003ecluster_info[i].lock);\n+\n+\tkfree(pages);\n+\tmemalloc_noreclaim_restore(noreclaim_flags);\n+\n+\t/*\n+\t * Publish the new mappings and cluster lock initialization before\n+\t * the count; walkers without xswap_lock use smp_load_acquire().\n+\t */\n+\tsmp_store_release(\u0026si-\u003enr_clusters_mapped, start_idx + nr);\n+\tmutex_unlock(\u0026si-\u003exswap_lock);\n+\treturn 0;\n+\n+mapped:\n+\tfor (i = start_idx; i \u003c start_idx + nr; i++)\n+\t\tspin_lock_init(\u0026si-\u003ecluster_info[i].lock);\n+\n+\t/* Publish the advanced count. */\n+\tsmp_store_release(\u0026si-\u003enr_clusters_mapped, start_idx + nr);\n+\tmutex_unlock(\u0026si-\u003exswap_lock);\n+\treturn 0;\n+\n+fail:\n+\t/* Clear PTEs vm_area_map_pages() may have left before freeing pages. */\n+\tvm_area_unmap_pages(si-\u003ecluster_vm, vm_start, vm_end);\n+\twhile (i \u003e 0) {\n+\t\ti--;\n+\t\tif (pages[i])\n+\t\t\t__free_page(pages[i]);\n+\t}\n+\tmemalloc_noreclaim_restore(noreclaim_flags);\n+\tkfree(pages);\n+\tmutex_unlock(\u0026si-\u003exswap_lock);\n+\treturn -ENOMEM;\n+}\n+\n+static bool xswap_should_grow(struct swap_info_struct *si)\n+{\n+\tunsigned long mapped = READ_ONCE(si-\u003enr_clusters_mapped);\n+\n+\tif (mapped \u003e= READ_ONCE(si-\u003enr_clusters_max))\n+\t\treturn false;\n+\n+\treturn swap_usage_in_pages(si) * 100 \u003e=\n+\t       mapped * SWAPFILE_CLUSTER * XSWAP_GROW_WHEN;\n+}\n+\n+/*\n+ * Map more of the cluster_info array, up to GROW_UNTIL in use.  The caller\n+ * holds percpu_swap_cluster.lock, which this drops while it sleeps.\n+ */\n+static unsigned long xswap_grow(struct swap_info_struct *si)\n+{\n+\tunsigned long mapped = READ_ONCE(si-\u003enr_clusters_mapped);\n+\tunsigned long nr_new, want, i;\n+\tint ret;\n+\n+\t/* The unmap below is paired with the caller's lock. */\n+\tlockdep_assert_held(\u0026percpu_swap_cluster.lock);\n+\n+\twant = DIV_ROUND_UP(swap_usage_in_pages(si) * 100,\n+\t\t\t    XSWAP_GROW_UNTIL * SWAPFILE_CLUSTER);\n+\tif (want \u003c= mapped)\n+\t\treturn 0;\n+\n+\tnr_new = rounddown(want - mapped, XSWAP_GROW_CLUSTERS);\n+\tif (!nr_new)\n+\t\tnr_new = XSWAP_GROW_CLUSTERS;\n+\tif (nr_new \u003e XSWAP_GROW_CHUNKS * XSWAP_GROW_CLUSTERS)\n+\t\tnr_new = XSWAP_GROW_CHUNKS * XSWAP_GROW_CLUSTERS;\n+\tnr_new = min(nr_new, READ_ONCE(si-\u003enr_clusters_max) - mapped);\n+\n+\t/*\n+\t * Mapping pages can sleep.  The lock only guards the per-cpu\n+\t * cluster cache, which this path does not touch.\n+\t */\n+\tlocal_unlock(\u0026percpu_swap_cluster.lock);\n+\tret = xswap_map_clusters(si, mapped, nr_new);\n+\tlocal_lock(\u0026percpu_swap_cluster.lock);\n+\tif (ret)\n+\t\treturn 0;\n+\n+\tfor (i = mapped; i \u003c mapped + nr_new; i++) {\n+\t\tstruct swap_cluster_info *ci = \u0026si-\u003ecluster_info[i];\n+\n+\t\t/*\n+\t\t * A concurrent grower may have taken these already;\n+\t\t * only add the off-list ones.\n+\t\t */\n+\t\tspin_lock(\u0026ci-\u003elock);\n+\t\tif (ci-\u003eflags == CLUSTER_FLAG_NONE)\n+\t\t\tmove_cluster(si, ci, \u0026si-\u003efree_clusters,\n+\t\t\t\t     CLUSTER_FLAG_FREE);\n+\t\tspin_unlock(\u0026ci-\u003elock);\n+\t}\n+\n+\tatomic_long_inc(\u0026si-\u003exswap_grows);\n+\treturn nr_new;\n+}\n+\n+struct xswap_page_data {\n+\tstruct page **pages;\n+\tunsigned long nr;\n+\tunsigned long max;\n+};\n+\n+static int xswap_collect_page(pte_t *pte, unsigned long addr, void *data)\n+{\n+\tstruct xswap_page_data *xpd = data;\n+\tpte_t pteval = ptep_get(pte);\n+\n+\tif (!pte_present(pteval))\n+\t\treturn 0;\n+\tif (WARN_ON_ONCE(xpd-\u003enr \u003e= xpd-\u003emax))\n+\t\treturn 0;\n+\txpd-\u003epages[xpd-\u003enr++] = pte_page(pteval);\n+\treturn 0;\n+}\n+\n+/*\n+ * Free the backing pages mapped in [vm_start, vm_end) and clear the PTEs.\n+ * @pages must have room for @max pointers.\n+ */\n+static void xswap_unmap_range(struct swap_info_struct *si,\n+\t\t\t      unsigned long vm_start, unsigned long vm_end,\n+\t\t\t      struct page **pages, unsigned long max)\n+{\n+\tstruct xswap_page_data xpd = {\n+\t\t.pages\t= pages,\n+\t\t.max\t= max,\n+\t};\n+\tunsigned long i;\n+\n+\tapply_to_existing_page_range(\u0026init_mm, vm_start, vm_end - vm_start,\n+\t\t\t\t     xswap_collect_page, \u0026xpd);\n+\tvm_area_unmap_pages(si-\u003ecluster_vm, vm_start, vm_end);\n+\n+\tfor (i = 0; i \u003c xpd.nr; i++)\n+\t\t__free_page(pages[i]);\n+}\n+\n+/* Caller must hold si-\u003exswap_lock.  Cannot fail. */\n+static void xswap_unmap_clusters_locked(struct swap_info_struct *si,\n+\t\t\t\t\tunsigned long start_idx, unsigned long nr)\n+{\n+\tunsigned long start_addr = (unsigned long)si-\u003ecluster_info +\n+\t\t\t\t   (size_t)start_idx * sizeof(struct swap_cluster_info);\n+\tunsigned long end_addr = start_addr +\n+\t\t\t\t (size_t)nr * sizeof(struct swap_cluster_info);\n+\tunsigned long vm_start = PAGE_ALIGN(start_addr);\n+\tunsigned long vm_end = PAGE_ALIGN(end_addr);\n+\tstruct page **pages;\n+\tunsigned int noreclaim_flags;\n+\tunsigned long npages, idx;\n+\n+\tif (vm_start \u003e= vm_end) {\n+\t\tWRITE_ONCE(si-\u003enr_clusters_mapped, start_idx);\n+\t\treturn;\n+\t}\n+\n+\t/*\n+\t * A per-cpu cluster cache can still hold an offset in this range.\n+\t * Invalidate those references, then wait out the readers that have\n+\t * already loaded one, so that nobody can dereference cluster_info\n+\t * past this point.  swapoff() needs the same before it releases.\n+\t */\n+\tflush_percpu_swap_cluster(si);\n+\tsynchronize_rcu();\n+\n+\tnpages = (vm_end - vm_start) \u003e\u003e PAGE_SHIFT;\n+\n+\t/* Reclaim here would re-enter xswap_map_clusters() and its lock. */\n+\tnoreclaim_flags = memalloc_noreclaim_save();\n+\tpages = kvmalloc_array(npages, sizeof(*pages), GFP_KERNEL);\n+\tmemalloc_noreclaim_restore(noreclaim_flags);\n+\tif (pages) {\n+\t\txswap_unmap_range(si, vm_start, vm_end, pages, npages);\n+\t\tkvfree(pages);\n+\t\tWRITE_ONCE(si-\u003enr_clusters_mapped, start_idx);\n+\t\treturn;\n+\t}\n+\n+\t/* No memory for the array: unmap in bounded batches instead. */\n+\tfor (idx = start_idx; idx \u003c start_idx + nr; idx += XSWAP_UNMAP_BATCH_CLUSTERS) {\n+\t\tunsigned long batch = min(start_idx + nr - idx,\n+\t\t\t\t\t  XSWAP_UNMAP_BATCH_CLUSTERS);\n+\t\tunsigned long addr = (unsigned long)si-\u003ecluster_info +\n+\t\t\t\t     (size_t)idx * sizeof(struct swap_cluster_info);\n+\t\tunsigned long bstart = PAGE_ALIGN(addr);\n+\t\tunsigned long bend = PAGE_ALIGN(addr + (size_t)batch *\n+\t\t\t\t\t       sizeof(struct swap_cluster_info));\n+\t\tstruct page *batch_pages[XSWAP_UNMAP_BATCH_PAGES + 1];\n+\n+\t\tif (bstart \u003c bend)\n+\t\t\txswap_unmap_range(si, bstart, bend, batch_pages,\n+\t\t\t\t\t  ARRAY_SIZE(batch_pages));\n+\t}\n+\n+\tWRITE_ONCE(si-\u003enr_clusters_mapped, start_idx);\n+}\n+\n+static void xswap_unmap_clusters(struct swap_info_struct *si,\n+\t\t\t\t unsigned long start_idx, unsigned long nr)\n+{\n+\tmutex_lock(\u0026si-\u003exswap_lock);\n+\txswap_unmap_clusters_locked(si, start_idx, nr);\n+\tmutex_unlock(\u0026si-\u003exswap_lock);\n+}\n+\n+/* Track the end of the run of pages that is already mapped. */\n+static int xswap_mapped_end(pte_t *pte, unsigned long addr, void *data)\n+{\n+\tunsigned long *mapped_end = data;\n+\n+\tif (!pte_present(ptep_get(pte)))\n+\t\treturn 0;\n+\t*mapped_end = addr + PAGE_SIZE;\n+\treturn 0;\n+}\n+\n+/*\n+ * Automatic reclaim: leave one chunk of the free tail mapped as slack, so\n+ * that the next allocation has somewhere to land, and only unmap once\n+ * several chunks can go, so the unmap is worth the RCU grace period it\n+ * costs.\n+ */\n+#define XSWAP_SHRINK_SLACK\tXSWAP_GROW_CLUSTERS\n+#define XSWAP_SHRINK_MIN\t(XSWAP_GROW_CLUSTERS * 8)\n+\n+static void xswap_shrink_work_fn(struct work_struct *work)\n+{\n+\tstruct swap_info_struct *si = container_of(work,\n+\t\t\tstruct swap_info_struct, xswap_shrink_work);\n+\n+\tif (!(READ_ONCE(si-\u003eflags) \u0026 SWP_WRITEOK))\n+\t\treturn;\n+\txswap_try_shrink(si);\n+}\n+\n+/*\n+ * Try to shrink the cluster_info tail: unmap contiguous free clusters\n+ * at the end of the mapped range.\n+ */\n+static void xswap_try_shrink(struct swap_info_struct *si)\n+{\n+\tstruct swap_cluster_info *ci;\n+\tunsigned long nr_mapped, nr_tail, keep, nr_unmap, start_idx, i;\n+\n+\tif (!(si-\u003eflags \u0026 SWP_XSWAP))\n+\t\treturn;\n+\n+\tmutex_lock(\u0026si-\u003exswap_lock);\n+\n+\t/* A swapoff raced us and is about to walk this mapping. */\n+\tif (!(READ_ONCE(si-\u003eflags) \u0026 SWP_WRITEOK))\n+\t\tgoto out_unlock;\n+\n+\tnr_mapped = READ_ONCE(si-\u003enr_clusters_mapped);\n+\tif (nr_mapped \u003c= 1)\t/* keep cluster 0 */\n+\t\tgoto out_unlock;\n+\n+\t/*\n+\t * Reclaim on our own, but only once the mapped range is at most\n+\t * SHRINK_WHEN in use: growth is demand driven, so reclaiming on a\n+\t * smaller dip would only map the same clusters again, and every\n+\t * unmap costs an RCU grace period.\n+\t */\n+\tif (swap_usage_in_pages(si) * 100 \u003e\n+\t    nr_mapped * SWAPFILE_CLUSTER * XSWAP_SHRINK_WHEN)\n+\t\tgoto out_unlock;\n+\n+\t/*\n+\t * Count the free clusters at the tail of the mapped range.  Scanned,\n+\t * not tracked: the count must be exact to size the unmap, and an\n+\t * incremental count falls behind on out-of-order frees.\n+\t */\n+\tnr_tail = 0;\n+\twhile (nr_mapped - nr_tail \u003e 1) {\n+\t\tci = \u0026si-\u003ecluster_info[nr_mapped - nr_tail - 1];\n+\t\tif (READ_ONCE(ci-\u003ecount) ||\n+\t\t    READ_ONCE(ci-\u003eflags) != CLUSTER_FLAG_FREE)\n+\t\t\tbreak;\n+\t\tnr_tail++;\n+\t}\n+\tif (nr_tail \u003c XSWAP_SHRINK_SLACK + XSWAP_SHRINK_MIN)\n+\t\tgoto out_unlock;\n+\n+\t/*\n+\t * Stop at SHRINK_UNTIL rather than at the end of the tail, or the\n+\t * range comes out full enough for the grow to be woken.  Below the\n+\t * tail everything stays mapped, and one chunk of tail with it.\n+\t */\n+\tkeep = DIV_ROUND_UP(swap_usage_in_pages(si) * 100,\n+\t\t\t    XSWAP_SHRINK_UNTIL * SWAPFILE_CLUSTER);\n+\tif (keep \u003c nr_mapped - nr_tail + XSWAP_SHRINK_SLACK)\n+\t\tkeep = nr_mapped - nr_tail + XSWAP_SHRINK_SLACK;\n+\n+\tif (nr_mapped \u003c keep + XSWAP_SHRINK_MIN)\n+\t\tgoto out_unlock;\n+\n+\tnr_unmap = rounddown(nr_mapped - keep, XSWAP_GROW_CLUSTERS);\n+\tif (!nr_unmap)\n+\t\tgoto out_unlock;\n+\tstart_idx = nr_mapped - nr_unmap;\n+\n+\t/*\n+\t * Only shrink a run that reaches the mapped end; otherwise\n+\t * truncating nr_clusters_mapped would orphan the active tail.\n+\t */\n+\tspin_lock(\u0026si-\u003elock);\n+\tfor (i = start_idx; i \u003c nr_mapped; i++) {\n+\t\tci = \u0026si-\u003ecluster_info[i];\n+\t\tif (READ_ONCE(ci-\u003eflags) != CLUSTER_FLAG_FREE)\n+\t\t\tbreak;\n+\t\tif (!spin_trylock(\u0026ci-\u003elock)) {\n+\t\t\tspin_unlock(\u0026si-\u003elock);\n+\t\t\tgoto out_unlock;\n+\t\t}\n+\t\tspin_unlock(\u0026ci-\u003elock);\n+\t}\n+\tif (i != nr_mapped) {\n+\t\tspin_unlock(\u0026si-\u003elock);\n+\t\tgoto out_unlock;\n+\t}\n+\n+\tfor (i = start_idx; i \u003c nr_mapped; i++) {\n+\t\tci = \u0026si-\u003ecluster_info[i];\n+\t\tlist_del_init(\u0026ci-\u003elist);\n+\t\tWRITE_ONCE(ci-\u003eflags, CLUSTER_FLAG_NONE);\n+\t}\n+\tspin_unlock(\u0026si-\u003elock);\n+\n+\txswap_unmap_clusters_locked(si, start_idx, nr_unmap);\n+\tatomic_long_inc(\u0026si-\u003exswap_shrinks);\n+\n+out_unlock:\n+\tmutex_unlock(\u0026si-\u003exswap_lock);\n+}\n+\n+/* Not an interface: how far the mapped range has moved, for testing. */\n+static ssize_t xswap_debugfs_read(struct file *file, char __user *buf,\n+\t\t\t\t  size_t count, loff_t *ppos)\n+{\n+\tstruct swap_info_struct *si = file-\u003eprivate_data;\n+\tstruct swap_cluster_info *ci;\n+\tunsigned long mapped, tail = 0;\n+\tchar tmp[192];\n+\tint len;\n+\n+\t/*\n+\t * The same scan the shrink does.  xswap_lock is what keeps\n+\t * cluster_info from being unmapped under it.\n+\t */\n+\tmutex_lock(\u0026si-\u003exswap_lock);\n+\tmapped = READ_ONCE(si-\u003enr_clusters_mapped);\n+\tif (si-\u003ecluster_info) {\n+\t\twhile (mapped - tail \u003e 1) {\n+\t\t\tci = \u0026si-\u003ecluster_info[mapped - tail - 1];\n+\t\t\tif (READ_ONCE(ci-\u003ecount) ||\n+\t\t\t    READ_ONCE(ci-\u003eflags) != CLUSTER_FLAG_FREE)\n+\t\t\t\tbreak;\n+\t\t\ttail++;\n+\t\t}\n+\t}\n+\tlen = scnprintf(tmp, sizeof(tmp),\n+\t\t\t\"clusters_max %lu\\nclusters_mapped %lu\\nusage_pages %lu\\ntail_free %lu\\ngrows %lu\\nshrinks %lu\\n\",\n+\t\t\tREAD_ONCE(si-\u003enr_clusters_max), mapped,\n+\t\t\tswap_usage_in_pages(si), tail,\n+\t\t\tatomic_long_read(\u0026si-\u003exswap_grows),\n+\t\t\tatomic_long_read(\u0026si-\u003exswap_shrinks));\n+\tmutex_unlock(\u0026si-\u003exswap_lock);\n+\n+\treturn simple_read_from_buffer(buf, count, ppos, tmp, len);\n+}\n+\n+static const struct file_operations xswap_debugfs_fops = {\n+\t.read\t= xswap_debugfs_read,\n+\t.open\t= simple_open,\n+\t.llseek\t= default_llseek,\n+};\n+\n+static struct dentry *xswap_debugfs_root;\n+\n+static void xswap_debugfs_add(struct swap_info_struct *si)\n+{\n+\tchar name[16];\n+\n+\tif (!xswap_debugfs_root)\n+\t\txswap_debugfs_root = debugfs_create_dir(\"xswap\", NULL);\n+\tif (IS_ERR_OR_NULL(xswap_debugfs_root))\n+\t\treturn;\n+\n+\t/* debugfs_create_file() takes the name as it is; no formatting. */\n+\tsnprintf(name, sizeof(name), \"type%d\", si-\u003etype);\n+\tsi-\u003exswap_debugfs = debugfs_create_file(name, 0444,\n+\t\t\t\t\t\txswap_debugfs_root, si,\n+\t\t\t\t\t\t\u0026xswap_debugfs_fops);\n+\tif (IS_ERR(si-\u003exswap_debugfs))\n+\t\tsi-\u003exswap_debugfs = NULL;\n+}\n+\n+static void xswap_debugfs_del(struct swap_info_struct *si)\n+{\n+\tdebugfs_remove(si-\u003exswap_debugfs);\n+\tsi-\u003exswap_debugfs = NULL;\n+}\n+#endif /* CONFIG_XSWAP */\n+\n static int setup_swap_clusters_info(struct swap_info_struct *si,\n \t\t\t\t    union swap_header *swap_header,\n \t\t\t\t    unsigned long maxpages)\n@@ -3640,10 +4516,76 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,\n \tint err = -ENOMEM;\n \tunsigned long i;\n \n+#ifdef CONFIG_XSWAP\n+\tif (si-\u003eflags \u0026 SWP_XSWAP) {\n+\t\tunsigned long size = PAGE_ALIGN(nr_clusters * sizeof(*cluster_info));\n+\t\tstruct vm_struct *vm;\n+\n+\t\tvm = get_vm_area(size, VM_SPARSE);\n+\t\tif (!vm)\n+\t\t\tgoto err;\n+\n+\t\tcluster_info = vm-\u003eaddr;\n+\t\tsi-\u003ecluster_vm = vm;\n+\t\tsi-\u003enr_clusters_max = nr_clusters;\n+\t\tsi-\u003ecluster_info = cluster_info;\n+\n+\t\t/* Must be initialized before xswap_map_clusters() locks it. */\n+\t\tmutex_init(\u0026si-\u003exswap_lock);\n+\n+\t\tif (xswap_map_clusters(si, 0, min_t(unsigned long,\n+\t\t\t\t\tXSWAP_GROW_CLUSTERS, nr_clusters)))\n+\t\t\tgoto err_free_vm;\n+\n+\t\t/* xswap: only cluster 0 slot 0 is bad */\n+\t\terr = swap_cluster_setup_bad_slot(si, cluster_info, 0, false);\n+\t\tif (err)\n+\t\t\tgoto err_unmap;\n+\n+\t\tINIT_LIST_HEAD(\u0026si-\u003efree_clusters);\n+\t\tINIT_LIST_HEAD(\u0026si-\u003efull_clusters);\n+\t\tINIT_LIST_HEAD(\u0026si-\u003ediscard_clusters);\n+\t\tfor (i = 0; i \u003c SWAP_NR_ORDERS; i++) {\n+\t\t\tINIT_LIST_HEAD(\u0026si-\u003enonfull_clusters[i]);\n+\t\t\tINIT_LIST_HEAD(\u0026si-\u003efrag_clusters[i]);\n+\t\t}\n+\n+\t\t/*\n+\t\t * Cluster 0 holds the header slot, which is marked bad, so it\n+\t\t * is not entirely free.  si-\u003emax is cluster aligned, so no\n+\t\t * cluster holds a slot past the end of the device.\n+\t\t */\n+\t\tfor (i = 0; i \u003c si-\u003enr_clusters_mapped; i++) {\n+\t\t\tstruct swap_cluster_info *ci = \u0026cluster_info[i];\n+\n+\t\t\tif (ci-\u003ecount) {\n+\t\t\t\tci-\u003eflags = CLUSTER_FLAG_NONFULL;\n+\t\t\t\tlist_add_tail(\u0026ci-\u003elist, \u0026si-\u003enonfull_clusters[0]);\n+\t\t\t} else {\n+\t\t\t\tci-\u003eflags = CLUSTER_FLAG_FREE;\n+\t\t\t\tlist_add_tail(\u0026ci-\u003elist, \u0026si-\u003efree_clusters);\n+\t\t\t}\n+\t\t}\n+\n+\t\tINIT_WORK(\u0026si-\u003exswap_shrink_work, xswap_shrink_work_fn);\n+\t\treturn 0;\n+\n+err_unmap:\n+\t\txswap_unmap_clusters(si, 0, si-\u003enr_clusters_mapped);\n+err_free_vm:\n+\t\tfree_vm_area(si-\u003ecluster_vm);\n+\t\tsi-\u003ecluster_vm = NULL;\n+\t\tsi-\u003ecluster_info = NULL;\n+\t\treturn err;\n+\t}\n+#endif /* CONFIG_XSWAP */\n+\n \tcluster_info = kvzalloc_objs(*cluster_info, nr_clusters);\n \tif (!cluster_info)\n \t\tgoto err;\n \n+\tsi-\u003ecluster_info = cluster_info;\n+\n \tfor (i = 0; i \u003c nr_clusters; i++)\n \t\tspin_lock_init(\u0026cluster_info[i].lock);\n \n@@ -3707,10 +4649,135 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,\n \tsi-\u003ecluster_info = cluster_info;\n \treturn 0;\n err:\n-\tfree_swap_cluster_info(cluster_info, maxpages);\n+\tfree_swap_cluster_info(si);\n \treturn err;\n }\n \n+#ifdef CONFIG_XSWAP\n+/* Create a file-less xswap device, sized at twice RAM. */\n+static int xswap_create(int prio)\n+{\n+\tstruct swap_info_struct *si;\n+\tunsigned long maxpages;\n+\tint error;\n+\n+\tif (prio != DEF_XSWAP_PRIO \u0026\u0026\n+\t    (prio \u003c 0 || prio \u003e SWAP_FLAG_PRIO_MASK))\n+\t\treturn -EINVAL;\n+\n+\t/* xswap has no backing store, it relies on zswap. */\n+\tif (!zswap_is_enabled())\n+\t\treturn -EOPNOTSUPP;\n+\n+\t/* Refuse rather than clamp: xswap.max= should give what was asked. */\n+\tmaxpages = xswap_size_pages();\n+\tif (maxpages \u003e xswap_size_limit()) {\n+\t\tpr_err(\"xswap: xswap.max is larger than the device can address\\n\");\n+\t\treturn -EINVAL;\n+\t}\n+\t/*\n+\t * Below one cluster the device is not cluster-aligned, so its only\n+\t * cluster would hold slots past si-\u003emax.  Nothing masks those, and a\n+\t * slot allocated there is past the end of the device: it can never be\n+\t * read back or given up again.\n+\t */\n+\tif (maxpages \u003c SWAPFILE_CLUSTER) {\n+\t\tpr_err(\"xswap: xswap.max is smaller than one cluster\\n\");\n+\t\treturn -EINVAL;\n+\t}\n+\n+\tsi = alloc_swap_info();\n+\tif (IS_ERR(si))\n+\t\treturn PTR_ERR(si);\n+\n+\tINIT_WORK(\u0026si-\u003ediscard_work, swap_discard_work);\n+\tINIT_WORK(\u0026si-\u003ereclaim_work, swap_reclaim_work);\n+\n+\t/* Cluster-aligned, so no cluster holds a slot past si-\u003emax. */\n+\tmaxpages = rounddown(maxpages, SWAPFILE_CLUSTER);\n+\n+\tsi-\u003ebdev = NULL;\n+\tsi-\u003eflags |= SWP_XSWAP | SWP_SOLIDSTATE;\n+\tsi-\u003emax = maxpages;\n+\tsi-\u003epages = maxpages - 1;\n+\t/*\n+\t * No backing file: setup_swap_extents() is only reachable from the\n+\t * file-backed swapon() path, so set ops here.  Only ops-\u003eflags is\n+\t * used, by may_enter_fs(); the IO methods are never called because\n+\t * swap_writeout()/swap_read_folio() short circuit xswap.\n+\t */\n+\tsi-\u003eops = \u0026swap_bdev_ops;\n+\n+\tsi-\u003exswap_debugfs = NULL;\n+\tatomic_long_set(\u0026si-\u003exswap_grows, 0);\n+\tatomic_long_set(\u0026si-\u003exswap_shrinks, 0);\n+\n+\terror = setup_swap_clusters_info(si, NULL, maxpages);\n+\tif (error)\n+\t\tgoto bad_swap;\n+\n+\txswap_debugfs_add(si);\n+\n+\terror = zswap_swapon(si-\u003etype, si-\u003emax);\n+\tif (error)\n+\t\tgoto bad_swap;\n+\n+\tmutex_lock(\u0026swapon_mutex);\n+\tsi-\u003eprio = prio;\n+\tsi-\u003elist.prio = -si-\u003eprio;\n+\tsi-\u003eavail_list.prio = -si-\u003eprio;\n+\t/* si-\u003eswap_file stays NULL: this is a file-less device */\n+\tenable_swap_info(si);\n+\tpr_info(\"xswap: adding extendable swap type %d (prio %d, %lu pages)\\n\",\n+\t\tsi-\u003etype, prio, si-\u003epages);\n+\tmutex_unlock(\u0026swapon_mutex);\n+\tatomic_inc(\u0026proc_poll_event);\n+\twake_up_interruptible(\u0026proc_poll_wait);\n+\n+\treturn si-\u003etype;\n+\n+bad_swap:\n+\tkfree(si-\u003eglobal_cluster);\n+\tsi-\u003eglobal_cluster = NULL;\n+\tdestroy_swap_extents(si, NULL);\t/* safe: xswap never sets SWP_ACTIVATED */\n+\tfree_swap_cluster_info(si);\n+\tsi-\u003ecluster_info = NULL;\n+\tspin_lock(\u0026swap_lock);\n+\tsi-\u003eflags = 0;\n+\tspin_unlock(\u0026swap_lock);\n+\treturn error;\n+}\n+\n+/* Tear down a file-less xswap device by its swap type. */\n+static int xswap_destroy(int type)\n+{\n+\tstruct swap_info_struct *p;\n+\tint err;\n+\n+\tp = swap_type_to_info(type);\n+\tif (!p)\n+\t\treturn -EINVAL;\n+\n+\tspin_lock(\u0026swap_lock);\n+\tif (!(p-\u003eflags \u0026 SWP_WRITEOK) || !(p-\u003eflags \u0026 SWP_XSWAP)) {\n+\t\tspin_unlock(\u0026swap_lock);\n+\t\treturn -EINVAL;\n+\t}\n+\t/* Refuse swapoff while the device is pinned for hibernation */\n+\tif (p-\u003eflags \u0026 SWP_HIBERNATION) {\n+\t\tspin_unlock(\u0026swap_lock);\n+\t\treturn -EBUSY;\n+\t}\n+\n+\terr = swap_info_remove(p);\n+\tspin_unlock(\u0026swap_lock);\n+\tif (err)\n+\t\treturn err;\n+\n+\treturn __swapoff(p);\n+}\n+#endif /* CONFIG_XSWAP */\n+\n SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)\n {\n \tstruct swap_info_struct *si;\n@@ -3815,7 +4882,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)\n \t\tgoto bad_swap_unlock_inode;\n \t}\n \tif (si-\u003epages != si-\u003emax - 1) {\n-\t\tpr_err(\"swap:%u != (max:%u - 1)\\n\", si-\u003epages, si-\u003emax);\n+\t\tpr_err(\"swap:%lu != (max:%lu - 1)\\n\", si-\u003epages, si-\u003emax);\n \t\terror = -EINVAL;\n \t\tgoto bad_swap_unlock_inode;\n \t}\n@@ -3906,7 +4973,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)\n \t/* Sets SWP_WRITEOK, resurrect the percpu ref, expose the swap device */\n \tenable_swap_info(si);\n \n-\tpr_info(\"Adding %uk swap on %s.  Priority:%d extents:%d across:%lluk %s%s%s%s\\n\",\n+\tpr_info(\"Adding %luk swap on %s.  Priority:%d extents:%d across:%lluk %s%s%s%s\\n\",\n \t\tK(si-\u003epages), name-\u003ename, si-\u003eprio, nr_extents,\n \t\tK((unsigned long long)span),\n \t\t(si-\u003eflags \u0026 SWP_SOLIDSTATE) ? \"SS\" : \"\",\n@@ -3929,7 +4996,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)\n \tsi-\u003eglobal_cluster = NULL;\n \tinode = NULL;\n \tdestroy_swap_extents(si, swap_file);\n-\tfree_swap_cluster_info(si-\u003ecluster_info, si-\u003emax);\n+\tfree_swap_cluster_info(si);\n \tsi-\u003ecluster_info = NULL;\n \t/*\n \t * Clear the SWP_USED flag after all resources are freed so\n@@ -4057,6 +5124,8 @@ static int __init swapfile_init(void)\n \t\tswap_migration_ad_supported = true;\n #endif\t/* CONFIG_MIGRATION */\n \n+\txswap_sysfs_init();\n+\n \treturn 0;\n }\n subsys_initcall(swapfile_init);\ndiff --git a/mm/zswap.c b/mm/zswap.c\nindex ae19e301fced7..7fe25f0b157ce 100644\n--- a/mm/zswap.c\n+++ b/mm/zswap.c\n@@ -1018,6 +1018,11 @@ static int zswap_writeback_entry(struct zswap_entry *entry,\n \tif (IS_ERR_OR_NULL(si))\n \t\treturn -ENOENT;\n \n+\tif (si-\u003eflags \u0026 SWP_XSWAP) {\n+\t\tput_swap_device(si);\n+\t\treturn -EINVAL;\n+\t}\n+\n \tmpol = get_task_policy(current);\n \tfolio = __swap_cache_alloc_folio(swpentry, GFP_KERNEL, BIT(0), NULL, mpol,\n \t\t\t\t\t NO_INTERLEAVE_INDEX);\n@@ -1511,7 +1516,9 @@ static bool zswap_store_page(struct folio *folio, long index,\n \tentry-\u003ereferenced = true;\n \tif (entry-\u003elength) {\n \t\tINIT_LIST_HEAD(\u0026entry-\u003elru);\n-\t\tzswap_lru_add(entry);\n+\t\t/* No backing store: nothing to write these back to. */\n+\t\tif (!(__swap_entry_to_info(page_swpentry)-\u003eflags \u0026 SWP_XSWAP))\n+\t\t\tzswap_lru_add(entry);\n \t}\n \n \treturn true;\n@@ -1581,7 +1588,7 @@ bool zswap_store(struct folio *folio)\n \tzswap_pool_put(pool);\n put_objcg:\n \tobj_cgroup_put(objcg);\n-\tif (!ret \u0026\u0026 zswap_pool_reached_full)\n+\tif (!ret \u0026\u0026 zswap_pool_reached_full \u0026\u0026 atomic_read(\u0026nr_real_swapfiles))\n \t\tqueue_work(shrink_wq, \u0026zswap_shrink_work);\n check_old:\n \t/*\n"
}

2/1 2026/10/03 10:12 agent patch-evaluator
0m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "XSWAP",
    "ZSWAP",
    "ZSWAP_DEFAULT_ON"
  ],
  "FocusSymbols": [
    "xswap_create_store",
    "xswap_destroy_store",
    "xswap_create",
    "xswap_destroy",
    "xswap_map_clusters",
    "xswap_grow",
    "xswap_try_shrink",
    "xswap_shrink_work_fn",
    "xswap_unmap_clusters_locked",
    "swap_read_folio",
    "swap_writeout",
    "zswap_writeback_entry"
  ],
  "Reasoning": "The patch series introduces 'xswap' (extendable virtual swap device), modifying core memory management (mm/swapfile.c, mm/page_io.c, mm/swap_state.c, mm/zswap.c). It adds sysfs attributes (/sys/kernel/mm/xswap/create and destroy) to dynamically create and destroy virtual swap devices backed by zswap and a sparse vmalloc area, complete with dynamic mapping/unmapping, deferred shrinking work, synchronization via RCU and mutexes, and newly added WARN_ON_ONCE assertions. This code is fully reachable in virtualized QEMU environments and warrants fuzzing.",
  "WorthFuzzing": true
}

Instruction:
You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.

IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.

================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.

- REACHABILITY IS THE PRIMARY GATE:
  Fuzzing can only discover bugs in code that can actually execute in standard virtualized
  environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
  If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
  regardless of whether it adds assertions or complex logic.

- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
  Patch authors routinely label changes as "cleanups", "refactorings", or state
  "No functional change intended". Do NOT take these claims at face value.
  Code refactorings that rearrange logic, introduce helper functions, or alter state management
  in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
  If reachable executable code is modified or refactored, it MUST be fuzzed.

- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
  When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
  BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
  Even if the author believes the invariant always holds, fuzzing is essential to verify whether
  an unusual sequence of operations can violate it.

================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:

- Non-kernel and non-executable changes:
  * Modifications to Documentation/, comments, or spelling fixes.
  * User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
    that do not affect the compiled kernel image (vmlinux) or kernel modules.
  * Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
    that do not alter control flow or data structures.
  * Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
  * Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
    ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
  * Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
    physical PCI hot-unplug or manual sysfs driver unbinding.
  * Code paths exclusive to architectures other than the target architecture.

================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
  * Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
    BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
  * Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
  * Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
  * Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).

================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:

- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
  Do NOT list generic, ubiquitous functions called by almost every program in the corpus
  (including, but not limited to: general memory allocators and deallocators, page fault
  and trap handlers, or core synchronization primitives; this is not an exhaustive list).
  Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
  which severely dilutes fuzzing effort away from the actual changes.

- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
  List functions that specifically implement the logic being added or altered, or direct API entrypoints
  for the subsystem feature under review.

- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
  Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
  distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
  If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
  functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).

================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit 640f9f65f614b8fb4b5c591ccbebc221bf9640d3
Author: syz-cluster <triage@syzkaller.com>
Date:   Sat Oct 3 10:12:35 2026 +0000

    syz-cluster: applied patch under review

diff --git a/include/linux/swap.h b/include/linux/swap.h
index 4f686709d71f0..ae2e49386443c 100644
--- a/include/linux/swap.h
+++ b/include/linux/swap.h
@@ -201,6 +201,7 @@ enum {
 	SWP_STABLE_WRITES = (1 << 11),	/* no overwrite PG_writeback pages */
 	SWP_SYNCHRONOUS_IO = (1 << 12),	/* synchronous IO is efficient */
 	SWP_HIBERNATION = (1 << 13),	/* pinned for hibernation */
+	SWP_XSWAP	= (1 << 14),	/* extendable swap device */
 					/* add others here before... */
 };
 
@@ -239,15 +240,25 @@ struct swap_info_struct {
 	signed short	prio;		/* swap priority of this type */
 	struct plist_node list;		/* entry in swap_active_head */
 	signed char	type;		/* strange name for an index */
-	unsigned int	max;		/* size of this swap device */
+	unsigned long	max;		/* size of this swap device */
 	struct swap_cluster_info *cluster_info; /* array, one entry per cluster */
+#ifdef CONFIG_XSWAP
+	struct vm_struct	*cluster_vm;	/* VM_SPARSE area for cluster_info */
+	unsigned long		nr_clusters_max;/* total clusters in the xswap address space */
+	unsigned long		nr_clusters_mapped; /* currently mapped cluster count */
+	struct work_struct	xswap_shrink_work; /* deferred shrink trigger */
+	struct mutex		xswap_lock;	/* serialize map/unmap operations */
+	struct dentry		*xswap_debugfs;	/* mapped range and counters */
+	atomic_long_t		xswap_grows;	/* grow operations so far */
+	atomic_long_t		xswap_shrinks;	/* shrink operations so far */
+#endif
 	struct list_head free_clusters; /* free clusters list */
 	struct list_head full_clusters; /* full clusters list */
 	struct list_head nonfull_clusters[SWAP_NR_ORDERS];
 					/* list of cluster that contains at least one free slot */
 	struct list_head frag_clusters[SWAP_NR_ORDERS];
 					/* list of cluster that are fragmented or contented */
-	unsigned int pages;		/* total of usable pages of swap */
+	unsigned long pages;		/* total of usable pages of swap */
 	atomic_long_t inuse_pages;	/* number of those currently in use */
 	struct swap_sequential_cluster *global_cluster; /* Use one global cluster for rotating device */
 	spinlock_t global_cluster_lock;	/* Serialize usage of global cluster */
@@ -378,6 +389,7 @@ void free_folio_and_swap_cache(struct folio *folio);
 void free_pages_and_swap_cache(struct encoded_page **, int);
 /* linux/mm/swapfile.c */
 extern atomic_long_t nr_swap_pages;
+extern atomic_t nr_real_swapfiles;
 extern long total_swap_pages;
 extern atomic_t nr_rotate_swap;
 
diff --git a/mm/Kconfig b/mm/Kconfig
index acefc994d9a8b..39927b5c75aca 100644
--- a/mm/Kconfig
+++ b/mm/Kconfig
@@ -122,6 +122,15 @@ config ZSWAP_COMPRESSOR_DEFAULT
        default "zstd" if ZSWAP_COMPRESSOR_DEFAULT_ZSTD
        default ""
 
+config XSWAP
+	bool "Extendable (virtual) swap device"
+	depends on SWAP && 64BIT && ZSWAP && SYSFS
+	help
+	  Adds support for extendable swap devices (xswap) that decouple
+	  PTE swap entries from physical backing storage. The cluster_info
+	  array is backed by a sparse vmalloc area that grows and shrinks
+	  on demand, avoiding static pre-allocation overhead.
+
 config ZSMALLOC
 	tristate
 
diff --git a/mm/page_io.c b/mm/page_io.c
index c6824fcd483e0..25fa9b82ed46b 100644
--- a/mm/page_io.c
+++ b/mm/page_io.c
@@ -248,6 +248,15 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 	}
 	rcu_read_unlock();
 
+	/*
+	 * xswap has no backing store: keep the folio.  ctx->sis is not set
+	 * yet, so look the device up from the entry.
+	 */
+	if (unlikely(__swap_entry_to_info(folio->swap)->flags & SWP_XSWAP)) {
+		folio_mark_dirty(folio);
+		return AOP_WRITEPAGE_ACTIVATE;
+	}
+
 	__swap_writeout(ctx, folio);
 	return 0;
 out_unlock:
@@ -486,6 +495,16 @@ void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio)
 	if (zswap_load(folio) != -ENOENT)
 		goto finish;
 
+	if (unlikely(sis->flags & SWP_XSWAP)) {
+		/*
+		 * An xswap entry only ever lives in zswap, so zswap_load()
+		 * must have found it.  Unlock and let the caller retry.
+		 */
+		WARN_ON_ONCE(1);
+		folio_unlock(folio);
+		goto finish;
+	}
+
 	/* We have to read from slower devices. Increase zswap protection. */
 	zswap_folio_swapin(folio);
 	swap_add_folio(ctx, folio, READ);
diff --git a/mm/swap_state.c b/mm/swap_state.c
index ebef568cd62ee..3a4e9e447b0b2 100644
--- a/mm/swap_state.c
+++ b/mm/swap_state.c
@@ -884,6 +884,10 @@ struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask,
 	struct blk_plug plug;
 	swp_entry_t ra_entry;
 
+	/* xswap entries live only in zswap; readahead does not help. */
+	if (si->flags & SWP_XSWAP)
+		goto skip;
+
 	mask = swapin_nr_pages(offset) - 1;
 	if (!mask)
 		goto skip;
@@ -969,6 +973,7 @@ static int swap_vma_ra_win(struct vm_fault *vmf, unsigned long *start,
 static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,
 		struct mempolicy *mpol, pgoff_t targ_ilx, struct vm_fault *vmf)
 {
+	struct swap_info_struct *si = __swap_entry_to_info(targ_entry);
 	struct swap_io_ctx ctx = {};
 	struct blk_plug plug;
 	struct folio *folio;
@@ -977,6 +982,10 @@ static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,
 	unsigned long start, end, addr;
 	pgoff_t ilx = targ_ilx;
 
+	/* xswap entries live only in zswap; readahead does not help. */
+	if (si->flags & SWP_XSWAP)
+		goto skip;
+
 	win = swap_vma_ra_win(vmf, &start, &end);
 	if (win == 1)
 		goto skip;
diff --git a/mm/swapfile.c b/mm/swapfile.c
index c3288910b3e35..bf95663c2593a 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -16,6 +16,8 @@
 #include <linux/kernel_stat.h>
 #include <linux/swap.h>
 #include <linux/vmalloc.h>
+#include <linux/kobject.h>
+#include <linux/sysfs.h>
 #include <linux/pagemap.h>
 #include <linux/namei.h>
 #include <linux/shmem_fs.h>
@@ -47,7 +49,202 @@
 #include <linux/leafops.h>
 #include "swap_table.h"
 #include "internal.h"
+#include <linux/debugfs.h>
+
 #include "swap.h"
+#define DEF_SWAP_PRIO  -1
+
+/*
+ * Above every real swap device: one ahead of xswap would take the page
+ * directly, and taking that slot is what xswap exists to avoid.
+ */
+#define DEF_XSWAP_PRIO	SWAP_FLAG_PRIO_MASK
+
+#ifdef CONFIG_XSWAP
+/*
+ * xswap: dynamically grow and shrink the cluster_info array via a
+ * VM_SPARSE area.
+ *
+ * XSWAP_GROW_CLUSTERS is the number of clusters to map/unmap in one
+ * grow/shrink operation: the number of cluster_info structs that fit in
+ * a single page (at least 16), so that the vmalloc page table overhead
+ * is proportional to the number of clusters mapped.
+ */
+#define XSWAP_GROW_CLUSTERS \
+	max_t(unsigned long, PAGE_SIZE / sizeof(struct swap_cluster_info), 16)
+
+/*
+ * Grow and shrink thresholds, as a percentage of the mapped range in use.
+ * Each one lands inside (SHRINK_WHEN, GROW_WHEN), so neither can leave the
+ * range in a state that wakes the other up.
+ */
+#define XSWAP_SHRINK_WHEN	50
+#define XSWAP_SHRINK_UNTIL	70
+#define XSWAP_GROW_UNTIL	65
+#define XSWAP_GROW_WHEN		85
+#define XSWAP_GROW_CHUNKS	4
+
+static bool xswap_should_grow(struct swap_info_struct *si);
+static unsigned long xswap_grow(struct swap_info_struct *si);
+static void xswap_debugfs_del(struct swap_info_struct *si);
+
+/* Batch size for the fallback unmap; keeps the stack array small. */
+#define XSWAP_UNMAP_BATCH_PAGES		16
+#define XSWAP_UNMAP_BATCH_CLUSTERS					\
+	max_t(unsigned long,						\
+	      ((XSWAP_UNMAP_BATCH_PAGES * PAGE_SIZE) /		\
+	       sizeof(struct swap_cluster_info)), 16)
+
+static int xswap_map_clusters(struct swap_info_struct *si,
+			      unsigned long start_idx, unsigned long nr);
+static void xswap_unmap_clusters(struct swap_info_struct *si,
+				 unsigned long start_idx, unsigned long nr);
+static int xswap_mapped_end(pte_t *pte, unsigned long addr, void *data);
+static void xswap_try_shrink(struct swap_info_struct *si);
+
+static int xswap_create(int prio);
+static int xswap_destroy(int type);
+
+static ssize_t xswap_create_store(struct kobject *kobj,
+				  struct kobj_attribute *attr,
+				  const char *buf, size_t count)
+{
+	int prio = DEF_XSWAP_PRIO;
+	int err;
+
+	if (!capable(CAP_SYS_ADMIN))
+		return -EPERM;
+
+	/* "[<prio>]" is optional; a lower one is allowed, not a higher. */
+	if (*skip_spaces(buf)) {
+		err = kstrtoint(buf, 10, &prio);
+		if (err)
+			return err;
+	}
+
+	err = xswap_create(prio);
+	if (err < 0)
+		return err;
+
+	return count;
+}
+
+static struct kobj_attribute xswap_create_attr = __ATTR(create, 0200, NULL,
+							xswap_create_store);
+
+static ssize_t xswap_destroy_store(struct kobject *kobj,
+				   struct kobj_attribute *attr,
+				   const char *buf, size_t count)
+{
+	unsigned long type;
+	int err;
+
+	if (!capable(CAP_SYS_ADMIN))
+		return -EPERM;
+
+	err = kstrtoul(buf, 0, &type);
+	if (err)
+		return err;
+	if (type >= MAX_SWAPFILES)
+		return -EINVAL;
+
+	err = xswap_destroy(type);
+	if (err)
+		return err;
+
+	return count;
+}
+
+static struct kobj_attribute xswap_destroy_attr = __ATTR(destroy, 0200, NULL,
+							 xswap_destroy_store);
+
+static struct attribute *xswap_attrs[] = {
+	&xswap_create_attr.attr,
+	&xswap_destroy_attr.attr,
+	NULL,
+};
+
+/* Size of a new device, from xswap.max=.  A percentage unless bytes is set. */
+static unsigned int xswap_size_pct = 200;
+static unsigned long xswap_size_bytes;
+
+static int __init xswap_max_setup(char *str)
+{
+	unsigned int pct;
+	char *end;
+
+	end = strchr(str, '%');
+	if (end) {
+		if (end[1]) {
+			pr_err("xswap: bad xswap.max=%s\n", str);
+			return 1;
+		}
+		*end = '\0';	/* writable copy, see parse_args() */
+		if (kstrtouint(str, 0, &pct) || !pct) {
+			pr_err("xswap: bad xswap.max=%s%%\n", str);
+			return 1;
+		}
+		xswap_size_pct = pct;
+		xswap_size_bytes = 0;
+		return 1;
+	}
+
+	xswap_size_bytes = memparse(str, &end);
+	if (*end || xswap_size_bytes < PAGE_SIZE) {
+		pr_err("xswap: bad xswap.max=%s\n", str);
+		xswap_size_bytes = 0;
+		return 1;
+	}
+	xswap_size_pct = 0;
+	return 1;
+}
+__setup("xswap.max=", xswap_max_setup);
+
+/* The most a device can address, whatever xswap.max= asked for. */
+static unsigned long xswap_size_limit(void)
+{
+	unsigned long limit = swapfile_maximum_size;
+
+	/* A cluster index is an unsigned int. */
+	if (limit / SWAPFILE_CLUSTER > UINT_MAX)
+		limit = (unsigned long)UINT_MAX * SWAPFILE_CLUSTER;
+
+	return limit;
+}
+
+static unsigned long xswap_size_pages(void)
+{
+	if (xswap_size_bytes)
+		return xswap_size_bytes >> PAGE_SHIFT;
+
+	return div_u64((unsigned long long)totalram_pages() * xswap_size_pct,
+		       100);
+}
+
+static const struct attribute_group xswap_attr_group = {
+	.attrs = xswap_attrs,
+};
+
+static struct kobject *xswap_kobj;
+
+static void xswap_sysfs_init(void)
+{
+	xswap_kobj = kobject_create_and_add("xswap", mm_kobj);
+	if (!xswap_kobj) {
+		pr_err("xswap: failed to create sysfs kobject\n");
+		return;
+	}
+	if (sysfs_create_group(xswap_kobj, &xswap_attr_group)) {
+		pr_err("xswap: failed to create sysfs group\n");
+		kobject_put(xswap_kobj);
+		xswap_kobj = NULL;
+	}
+}
+#else /* !CONFIG_XSWAP */
+static inline void xswap_sysfs_init(void)
+{
+}
+#endif /* CONFIG_XSWAP */
 
 static void swap_range_alloc(struct swap_info_struct *si,
 			     unsigned int nr_entries);
@@ -66,6 +263,9 @@ static void move_cluster(struct swap_info_struct *si,
 static DEFINE_SPINLOCK(swap_lock);
 static unsigned int nr_swapfiles;
 atomic_long_t nr_swap_pages;
+atomic_t nr_real_swapfiles;
+/* Active xswap devices, as in nr_real_swapfiles. */
+static atomic_t nr_xswap_files;
 /*
  * Some modules use swappable objects and may try to swap them out under
  * memory pressure (via the shrinker). Before doing so, they may wish to
@@ -74,7 +274,6 @@ atomic_long_t nr_swap_pages;
 EXPORT_SYMBOL_GPL(nr_swap_pages);
 /* protected with swap_lock. reading in vm_swap_full() doesn't need lock */
 long total_swap_pages;
-#define DEF_SWAP_PRIO  -1
 unsigned long swapfile_maximum_size;
 #ifdef CONFIG_MIGRATION
 bool swap_migration_ad_supported;
@@ -402,10 +601,10 @@ static inline unsigned int cluster_index(struct swap_info_struct *si,
 	return ci - si->cluster_info;
 }
 
-static inline unsigned int cluster_offset(struct swap_info_struct *si,
-					  struct swap_cluster_info *ci)
+static inline unsigned long cluster_offset(struct swap_info_struct *si,
+					   struct swap_cluster_info *ci)
 {
-	return cluster_index(si, ci) * SWAPFILE_CLUSTER;
+	return (unsigned long)cluster_index(si, ci) * SWAPFILE_CLUSTER;
 }
 
 static void swap_cluster_free_table_folio_rcu_cb(struct rcu_head *head)
@@ -617,6 +816,11 @@ static void __free_cluster(struct swap_info_struct *si, struct swap_cluster_info
 	swap_cluster_free_table(ci);
 	move_cluster(si, ci, &si->free_clusters, CLUSTER_FLAG_FREE);
 	ci->order = 0;
+#ifdef CONFIG_XSWAP
+	/* Only xswap devices, and not while the device is being torn down. */
+	if ((si->flags & SWP_XSWAP) && (si->flags & SWP_WRITEOK))
+		schedule_work(&si->xswap_shrink_work);
+#endif
 }
 
 /*
@@ -733,7 +937,8 @@ static void free_cluster(struct swap_info_struct *si, struct swap_cluster_info *
 	/*
 	 * If the swap is discardable, prepare discard the cluster
 	 * instead of free it immediately. The cluster will be freed
-	 * after discard.
+	 * after discard.  xswap has no bdev and never sets
+	 * SWP_PAGE_DISCARD, so it always takes the free path below.
 	 */
 	if ((si->flags & (SWP_WRITEOK | SWP_PAGE_DISCARD)) ==
 	    (SWP_WRITEOK | SWP_PAGE_DISCARD)) {
@@ -803,7 +1008,7 @@ static int swap_cluster_setup_bad_slot(struct swap_info_struct *si,
 
 	/* si->max may got shrunk by swap swap_activate() */
 	if (offset >= si->max && !mask) {
-		pr_debug("Ignoring bad slot %u (max: %u)\n", offset, si->max);
+		pr_debug("Ignoring bad slot %u (max: %lu)\n", offset, si->max);
 		return 0;
 	}
 	/*
@@ -969,11 +1174,12 @@ static bool __swap_cluster_alloc_entries(struct swap_info_struct *si,
 }
 
 /* Try use a new cluster for current CPU and allocate from it. */
-static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,
-					    struct swap_cluster_info *ci,
-					    struct folio *folio, unsigned long offset)
+static unsigned long alloc_swap_scan_cluster(struct swap_info_struct *si,
+					     struct swap_cluster_info *ci,
+					     struct folio *folio,
+					     unsigned long offset)
 {
-	unsigned int next = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID;
+	unsigned long next = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID;
 	unsigned long start = ALIGN_DOWN(offset, SWAPFILE_CLUSTER);
 	unsigned int order = likely(folio) ? folio_order(folio) : 0;
 	unsigned long end = start + SWAPFILE_CLUSTER;
@@ -983,6 +1189,9 @@ static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,
 	lockdep_assert_held(&ci->lock);
 	VM_WARN_ON(!cluster_is_usable(ci, order));
 
+	/* ci is used without ci->lock; an xswap unmap waits for this. */
+	rcu_read_lock();
+
 	if (end < nr_pages || ci->count + nr_pages > SWAPFILE_CLUSTER)
 		goto out;
 
@@ -1011,6 +1220,7 @@ static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,
 out:
 	relocate_cluster(si, ci);
 	swap_cluster_unlock(ci);
+	rcu_read_unlock();
 	if (si->flags & SWP_SOLIDSTATE) {
 		this_cpu_write(percpu_swap_cluster.offset[order], next);
 		this_cpu_write(percpu_swap_cluster.si[order], si);
@@ -1020,12 +1230,12 @@ static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,
 	return found;
 }
 
-static unsigned int alloc_swap_scan_list(struct swap_info_struct *si,
-					 struct list_head *list,
-					 struct folio *folio,
-					 bool scan_all)
+static unsigned long alloc_swap_scan_list(struct swap_info_struct *si,
+					  struct list_head *list,
+					  struct folio *folio,
+					  bool scan_all)
 {
-	unsigned int found = SWAP_ENTRY_INVALID;
+	unsigned long found = SWAP_ENTRY_INVALID;
 
 	do {
 		struct swap_cluster_info *ci = isolate_lock_cluster(si, list);
@@ -1054,6 +1264,9 @@ static void swap_reclaim_full_clusters(struct swap_info_struct *si, bool force)
 		to_scan = swap_usage_in_pages(si) / SWAPFILE_CLUSTER;
 
 	while ((ci = isolate_lock_cluster(si, &si->full_clusters))) {
+		/* As in alloc_swap_scan_cluster(). */
+		rcu_read_lock();
+
 		offset = cluster_offset(si, ci);
 		end = min(si->max, offset + SWAPFILE_CLUSTER);
 		to_scan--;
@@ -1078,6 +1291,7 @@ static void swap_reclaim_full_clusters(struct swap_info_struct *si, bool force)
 			relocate_cluster(si, ci);
 
 		swap_cluster_unlock(ci);
+		rcu_read_unlock();
 		if (to_scan <= 0)
 			break;
 
@@ -1108,7 +1322,7 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 {
 	struct swap_cluster_info *ci;
 	unsigned int order = likely(folio) ? folio_order(folio) : 0;
-	unsigned int offset = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID;
+	unsigned long offset = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID;
 
 	/*
 	 * Swapfile is not block device so unable
@@ -1117,6 +1331,17 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 	if (order && !(si->flags & SWP_BLKDEV))
 		return 0;
 
+#ifdef CONFIG_XSWAP
+	/*
+	 * Top the range up early.  Every path below leaves through `done`,
+	 * so this has to come first; mapping pages can sleep, and doing it
+	 * from the allocation that would otherwise fail leaves nothing to
+	 * fall back on.
+	 */
+	if ((si->flags & SWP_XSWAP) && xswap_should_grow(si))
+		xswap_grow(si);
+#endif
+
 	if (!(si->flags & SWP_SOLIDSTATE)) {
 		/* Serialize HDD SWAP allocation for each device. */
 		spin_lock(&si->global_cluster_lock);
@@ -1193,6 +1418,12 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 		if (found)
 			goto done;
 	}
+
+#ifdef CONFIG_XSWAP
+	/* A concurrent free or grow may have added clusters; retry once. */
+	if (!found && (si->flags & SWP_XSWAP))
+		found = alloc_swap_scan_list(si, &si->free_clusters, folio, false);
+#endif
 done:
 	if (!(si->flags & SWP_SOLIDSTATE))
 		spin_unlock(&si->global_cluster_lock);
@@ -1216,6 +1447,11 @@ static void del_from_avail_list(struct swap_info_struct *si, bool swapoff)
 		 */
 		lockdep_assert_held(&si->lock);
 		si->flags &= ~SWP_WRITEOK;
+		/* Count active devices, not merely those on the avail list. */
+		if (si->flags & SWP_XSWAP)
+			atomic_sub(1, &nr_xswap_files);
+		else
+			atomic_sub(1, &nr_real_swapfiles);
 		atomic_long_or(SWAP_USAGE_OFFLIST_BIT, &si->inuse_pages);
 	} else {
 		/*
@@ -1273,6 +1509,12 @@ static void add_to_avail_list(struct swap_info_struct *si, bool swapon)
 	}
 
 	plist_add(&si->avail_list, &swap_avail_head);
+	if (swapon) {
+		if (si->flags & SWP_XSWAP)
+			atomic_add(1, &nr_xswap_files);
+		else
+			atomic_add(1, &nr_real_swapfiles);
+	}
 
 skip:
 	spin_unlock(&swap_avail_lock);
@@ -1370,21 +1612,32 @@ static bool get_swap_device_info(struct swap_info_struct *si)
  * Fast path try to get swap entries with specified order from current
  * CPU's swap entry pool (a cluster).
  */
-static bool swap_alloc_fast(struct folio *folio)
+static bool swap_alloc_fast(struct folio *folio, bool may_zswap)
 {
 	unsigned int order = folio_order(folio);
 	struct swap_cluster_info *ci;
 	struct swap_info_struct *si;
-	unsigned int offset;
+	unsigned long offset;
 
 	/*
 	 * Once allocated, swap_info_struct will never be completely freed,
 	 * so checking it's liveness by get_swap_device_info is enough.
+	 *
+	 * The cached offset indexes si->cluster_info, which xswap can
+	 * unmap; cover both the read and the use with RCU.
 	 */
+	rcu_read_lock();
 	si = this_cpu_read(percpu_swap_cluster.si[order]);
 	offset = this_cpu_read(percpu_swap_cluster.offset[order]);
-	if (!si || !offset || !get_swap_device_info(si))
+	if (!si || !offset || !get_swap_device_info(si)) {
+		rcu_read_unlock();
+		return false;
+	}
+	if (!may_zswap && (si->flags & SWP_XSWAP)) {
+		put_swap_device(si);
+		rcu_read_unlock();
 		return false;
+	}
 
 	ci = swap_cluster_lock(si, offset);
 	if (cluster_is_usable(ci, order)) {
@@ -1396,17 +1649,24 @@ static bool swap_alloc_fast(struct folio *folio)
 	}
 
 	put_swap_device(si);
+	rcu_read_unlock();
 	return folio_test_swapcache(folio);
 }
 
 /* Rotate the device and switch to a new cluster */
-static void swap_alloc_slow(struct folio *folio)
+static void swap_alloc_slow(struct folio *folio, bool may_zswap)
 {
 	struct swap_info_struct *si, *next;
 
 	spin_lock(&swap_avail_lock);
 start_over:
 	plist_for_each_entry_safe(si, next, &swap_avail_head, avail_list) {
+		/*
+		 * Do not rotate a skipped device: the walk follows the
+		 * rotation and would spin forever.
+		 */
+		if (!may_zswap && (si->flags & SWP_XSWAP))
+			continue;
 		/* Rotate the device and switch to a new cluster */
 		plist_requeue(&si->avail_list, &swap_avail_head);
 		spin_unlock(&swap_avail_lock);
@@ -1745,10 +2005,24 @@ int folio_alloc_swap(struct folio *folio)
 {
 	unsigned int order = folio_order(folio);
 	unsigned int size = 1 << order;
+	struct obj_cgroup *objcg;
+	/* True unless the gate below finds an xswap device to route away from. */
+	bool may_zswap = true;
 
 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
 	VM_BUG_ON_FOLIO(!folio_test_uptodate(folio), folio);
 
+	/*
+	 * A folio that zswap will not take must not get an xswap slot. With
+	 * no xswap device to route away from, skip the lookup.
+	 */
+	if (atomic_read(&nr_xswap_files)) {
+		objcg = get_obj_cgroup_from_folio(folio);
+		may_zswap = !objcg || obj_cgroup_may_zswap(objcg);
+		if (objcg)
+			obj_cgroup_put(objcg);
+	}
+
 	if (order) {
 		/*
 		 * Reject large allocation when THP_SWAP is disabled. Check below
@@ -1769,8 +2043,8 @@ int folio_alloc_swap(struct folio *folio)
 
 again:
 	local_lock(&percpu_swap_cluster.lock);
-	if (!swap_alloc_fast(folio))
-		swap_alloc_slow(folio);
+	if (!swap_alloc_fast(folio, may_zswap))
+		swap_alloc_slow(folio, may_zswap);
 	local_unlock(&percpu_swap_cluster.lock);
 
 	if (!order && unlikely(!folio_test_swapcache(folio))) {
@@ -2186,8 +2460,11 @@ swp_entry_t swap_alloc_hibernation_slot(int type)
 	/*
 	 * Try the local cluster first if it matches the device. If
 	 * not, try grab a new cluster and override local cluster.
+	 *
+	 * Same RCU requirement as swap_alloc_fast().
 	 */
 	local_lock(&percpu_swap_cluster.lock);
+	rcu_read_lock();
 	pcp_si = this_cpu_read(percpu_swap_cluster.si[0]);
 	pcp_offset = this_cpu_read(percpu_swap_cluster.offset[0]);
 	if (pcp_si == si && pcp_offset) {
@@ -2197,6 +2474,7 @@ swp_entry_t swap_alloc_hibernation_slot(int type)
 		else
 			swap_cluster_unlock(ci);
 	}
+	rcu_read_unlock();
 	if (!offset)
 		offset = cluster_alloc_swap_entry(si, NULL);
 	local_unlock(&percpu_swap_cluster.lock);
@@ -2249,6 +2527,9 @@ static int __find_hibernation_swap_type(dev_t device, sector_t offset)
 
 		if (!(sis->flags & SWP_WRITEOK))
 			continue;
+		/* xswap has no bdev to match a resume device */
+		if (sis->flags & SWP_XSWAP)
+			continue;
 
 		if (device == sis->bdev->bd_dev) {
 			struct swap_extent *se = first_se(sis);
@@ -2436,6 +2717,8 @@ int find_first_swap(dev_t *device)
 
 		if (!(sis->flags & SWP_WRITEOK))
 			continue;
+		if (sis->flags & SWP_XSWAP)
+			continue;
 		*device = sis->bdev->bd_dev;
 		spin_unlock(&swap_lock);
 		return type;
@@ -2788,14 +3071,31 @@ static int unuse_mm(struct mm_struct *mm, unsigned int type)
  * Return 0 if there are no inuse entries after prev till end of
  * the map.
  */
-static unsigned int find_next_to_unuse(struct swap_info_struct *si,
-					unsigned int prev)
+static unsigned long find_next_to_unuse(struct swap_info_struct *si,
+					unsigned long prev)
 {
 	struct swap_cluster_info *ci;
-	unsigned long i, end;
+	unsigned long i, cluster_end, end;
 	unsigned int ci_off;
 	unsigned long swp_tb;
 
+	end = si->max;
+#ifdef CONFIG_XSWAP
+	/*
+	 * An xswap device maps its cluster_info in chunks as it grows, so
+	 * the tail past nr_clusters_mapped has nothing behind it.
+	 */
+	if (si->flags & SWP_XSWAP) {
+		unsigned long mapped_end;
+
+		/* Pairs with the smp_store_release() in xswap_map_clusters(). */
+		mapped_end = smp_load_acquire(&si->nr_clusters_mapped) *
+			     SWAPFILE_CLUSTER;
+		if (mapped_end < end)
+			end = mapped_end;
+	}
+#endif
+
 	/*
 	 * No need for swap_lock here: we're just looking
 	 * for whether an entry is in use, not modifying it; false
@@ -2803,11 +3103,11 @@ static unsigned int find_next_to_unuse(struct swap_info_struct *si,
 	 * allocations from this area (while holding swap_lock).
 	 */
 	i = prev + 1;
-	while (i < si->max) {
+	while (i < end) {
 		ci = __swap_offset_to_cluster(si, i);
-		end = min_t(unsigned long,
-			    ALIGN_DOWN(i, SWAPFILE_CLUSTER) + SWAPFILE_CLUSTER,
-			    si->max);
+		cluster_end = min_t(unsigned long,
+				    ALIGN_DOWN(i, SWAPFILE_CLUSTER) + SWAPFILE_CLUSTER,
+				    end);
 
 		/*
 		 * An empty cluster has no slot in use, so skip it whole.
@@ -2817,13 +3117,13 @@ static unsigned int find_next_to_unuse(struct swap_info_struct *si,
 		 * enough, unlike in every other cluster_is_empty() caller.
 		 */
 		if (!READ_ONCE(ci->count)) {
-			i = end;
+			i = cluster_end;
 			cond_resched();
 			continue;
 		}
 
 		ci_off = i % SWAPFILE_CLUSTER;
-		for (; i < end; ci_off++, i++) {
+		for (; i < cluster_end; ci_off++, i++) {
 			swp_tb = swap_table_get(ci, ci_off);
 			if (!swp_tb_is_null(swp_tb) && !swp_tb_is_bad(swp_tb))
 				return i;
@@ -2833,7 +3133,6 @@ static unsigned int find_next_to_unuse(struct swap_info_struct *si,
 
 	return 0;
 }
-
 static int try_to_unuse(unsigned int type)
 {
 	struct mm_struct *prev_mm;
@@ -2843,7 +3142,7 @@ static int try_to_unuse(unsigned int type)
 	struct swap_info_struct *si = swap_info[type];
 	struct folio *folio;
 	swp_entry_t entry;
-	unsigned int i;
+	unsigned long i;
 
 	if (!swap_usage_in_pages(si))
 		goto success;
@@ -3131,20 +3430,62 @@ static void wait_for_allocation(struct swap_info_struct *si)
 
 	BUG_ON(si->flags & SWP_WRITEOK);
 
+#ifdef CONFIG_XSWAP
+	if (si->flags & SWP_XSWAP) {
+		/* Pairs with the smp_store_release() in xswap_map_clusters(). */
+		end = min(end, smp_load_acquire(&si->nr_clusters_mapped) *
+			  SWAPFILE_CLUSTER);
+	}
+#endif
+
 	for (offset = 0; offset < end; offset += SWAPFILE_CLUSTER) {
 		ci = swap_cluster_lock(si, offset);
 		swap_cluster_unlock(ci);
 	}
 }
 
-static void free_swap_cluster_info(struct swap_cluster_info *cluster_info,
-				   unsigned long maxpages)
+static void free_swap_cluster_info(struct swap_info_struct *si)
 {
+	struct swap_cluster_info *cluster_info = si->cluster_info;
+	unsigned long maxpages = si->max;
 	struct swap_cluster_info *ci;
-	int i, nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
+	unsigned long i, nr_clusters;
 
 	if (!cluster_info)
 		return;
+
+#ifdef CONFIG_XSWAP
+	if (si->flags & SWP_XSWAP) {
+		unsigned long nr_mapped;
+
+		cancel_work_sync(&si->xswap_shrink_work);
+		/*
+		 * Cluster 0 keeps the bad header slot, so it never empties
+		 * and __free_cluster() never frees its table.
+		 */
+		/* Pairs with the smp_store_release() in xswap_map_clusters(). */
+		nr_mapped = smp_load_acquire(&si->nr_clusters_mapped);
+		for (i = 0; i < nr_mapped; i++) {
+			ci = &cluster_info[i];
+			spin_lock(&ci->lock);
+			if (cluster_table_is_alloced(ci)) {
+				swap_cluster_assert_empty(ci, 0, SWAPFILE_CLUSTER, true);
+				swap_cluster_free_table(ci);
+			}
+			spin_unlock(&ci->lock);
+		}
+		/* free_vm_area() drops the mapping without freeing the pages. */
+		xswap_unmap_clusters(si, 0, si->nr_clusters_mapped);
+		xswap_debugfs_del(si);
+		free_vm_area(si->cluster_vm);
+		si->cluster_vm = NULL;
+		si->cluster_info = NULL;
+		si->nr_clusters_mapped = 0;
+		return;
+	}
+#endif
+
+	nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
 	for (i = 0; i < nr_clusters; i++) {
 		ci = cluster_info + i;
 		/* Cluster with bad marks count will have a remaining table */
@@ -3156,6 +3497,7 @@ static void free_swap_cluster_info(struct swap_cluster_info *cluster_info,
 		spin_unlock(&ci->lock);
 	}
 	kvfree(cluster_info);
+	si->cluster_info = NULL;
 }
 
 /*
@@ -3179,15 +3521,14 @@ static void flush_percpu_swap_cluster(struct swap_info_struct *si)
 	}
 }
 
+static int swap_info_remove(struct swap_info_struct *p);
+static int __swapoff(struct swap_info_struct *p);
 
 SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 {
 	struct swap_info_struct *p = NULL;
-	struct swap_cluster_info *cluster_info;
-	struct file *swap_file, *victim;
+	struct file *victim;
 	struct address_space *mapping;
-	struct inode *inode;
-	unsigned int maxpages;
 	int err, found = 0;
 
 	if (!capable(CAP_SYS_ADMIN))
@@ -3204,7 +3545,7 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 	spin_lock(&swap_lock);
 	plist_for_each_entry(p, &swap_active_head, list) {
 		if (p->flags & SWP_WRITEOK) {
-			if (p->swap_file->f_mapping == mapping) {
+			if (p->swap_file && p->swap_file->f_mapping == mapping) {
 				found = 1;
 				break;
 			}
@@ -3223,20 +3564,59 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 		goto out_dput;
 	}
 
-	if (!security_vm_enough_memory_mm(current->mm, p->pages))
-		vm_unacct_memory(p->pages);
-	else {
-		err = -ENOMEM;
+	err = swap_info_remove(p);
+	if (err) {
 		spin_unlock(&swap_lock);
 		goto out_dput;
 	}
+	spin_unlock(&swap_lock);
+
+	err = __swapoff(p);
+
+out_dput:
+	filp_close(victim, NULL);
+	return err;
+}
+
+/*
+ * Drop @p from the avail and active lists and undo its accounting.  The
+ * caller must hold swap_lock and have checked that @p is WRITEOK and not
+ * pinned for hibernation.
+ *
+ * Returns 0, or -ENOMEM with swap_lock still held.
+ */
+static int swap_info_remove(struct swap_info_struct *p)
+{
+	if (!security_vm_enough_memory_mm(current->mm, p->pages))
+		vm_unacct_memory(p->pages);
+	else
+		return -ENOMEM;
+
 	spin_lock(&p->lock);
 	del_from_avail_list(p, true);
 	plist_del(&p->list, &swap_active_head);
 	atomic_long_sub(p->pages, &nr_swap_pages);
 	total_swap_pages -= p->pages;
 	spin_unlock(&p->lock);
-	spin_unlock(&swap_lock);
+	return 0;
+}
+
+/* Common swap teardown after list removal; shared by sys_swapoff() and
+ * xswap_destroy().
+ */
+static int __swapoff(struct swap_info_struct *p)
+{
+	struct file *swap_file = NULL;
+	int err;
+
+#ifdef CONFIG_XSWAP
+	if (p->flags & SWP_XSWAP) {
+		cancel_work_sync(&p->xswap_shrink_work);
+		/* Wait out a shrink racing us from the sysfs write path. */
+		mutex_lock(&p->xswap_lock);
+		mutex_unlock(&p->xswap_lock);
+	}
+#endif
 
 	wait_for_allocation(p);
 
@@ -3247,7 +3627,7 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 	if (err) {
 		/* re-insert swap space back into swap_list */
 		reinsert_swap_info(p);
-		goto out_dput;
+		return err;
 	}
 
 	/*
@@ -3268,7 +3648,8 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 
 	destroy_swap_extents(p, p->swap_file);
 
-	if (!(p->flags & SWP_SOLIDSTATE))
+	if (!(p->flags & SWP_XSWAP) &&
+	    !(p->flags & SWP_SOLIDSTATE))
 		atomic_dec(&nr_rotate_swap);
 
 	mutex_lock(&swapon_mutex);
@@ -3278,10 +3659,6 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 
 	swap_file = p->swap_file;
 	p->swap_file = NULL;
-	maxpages = p->max;
-	cluster_info = p->cluster_info;
-	p->max = 0;
-	p->cluster_info = NULL;
 	spin_unlock(&p->lock);
 	spin_unlock(&swap_lock);
 	arch_swap_invalidate_area(p->type);
@@ -3289,14 +3666,22 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 	mutex_unlock(&swapon_mutex);
 	kfree(p->global_cluster);
 	p->global_cluster = NULL;
-	free_swap_cluster_info(cluster_info, maxpages);
+	free_swap_cluster_info(p);
+	/*
+	 * The device is off swap_active_head and no longer WRITEOK, so no
+	 * reader can observe these; clearing them here needs no lock.
+	 */
+	p->max = 0;
+	p->cluster_info = NULL;
 
-	inode = mapping->host;
+	if (swap_file) {
+		struct inode *inode = swap_file->f_mapping->host;
 
-	inode_lock(inode);
-	inode->i_flags &= ~S_SWAPFILE;
-	inode_unlock(inode);
-	filp_close(swap_file, NULL);
+		inode_lock(inode);
+		inode->i_flags &= ~S_SWAPFILE;
+		inode_unlock(inode);
+		filp_close(swap_file, NULL);
+	}
 
 	/*
 	 * Clear the SWP_USED flag after all resources are freed so that swapon
@@ -3307,13 +3692,10 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 	p->flags = 0;
 	spin_unlock(&swap_lock);
 
-	err = 0;
 	atomic_inc(&proc_poll_event);
 	wake_up_interruptible(&proc_poll_wait);
 
-out_dput:
-	filp_close(victim, NULL);
-	return err;
+	return 0;
 }
 
 #ifdef CONFIG_PROC_FS
@@ -3344,7 +3726,8 @@ static void *swap_start(struct seq_file *swap, loff_t *pos)
 		return SEQ_START_TOKEN;
 
 	for (type = 0; (si = swap_type_to_info(type)); type++) {
-		if (!(si->swap_file))
+		if (!si->swap_file &&
+		    !((si->flags & SWP_XSWAP) && (si->flags & SWP_WRITEOK)))
 			continue;
 		if (!--l)
 			return si;
@@ -3365,7 +3748,8 @@ static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
 
 	++(*pos);
 	for (; (si = swap_type_to_info(type)); type++) {
-		if (!(si->swap_file))
+		if (!si->swap_file &&
+		    !((si->flags & SWP_XSWAP) && (si->flags & SWP_WRITEOK)))
 			continue;
 		return si;
 	}
@@ -3378,6 +3762,19 @@ static void swap_stop(struct seq_file *swap, void *v)
 	mutex_unlock(&swapon_mutex);
 }
 
+static const char *swap_type_str(struct swap_info_struct *si)
+{
+	struct file *file = si->swap_file;
+
+	if (si->flags & SWP_XSWAP)
+		return "xswap\t";
+
+	if (S_ISBLK(file_inode(file)->i_mode))
+		return "partition";
+
+	return "file\t";
+}
+
 static int swap_show(struct seq_file *swap, void *v)
 {
 	struct swap_info_struct *si = v;
@@ -3394,11 +3791,17 @@ static int swap_show(struct seq_file *swap, void *v)
 	inuse = K(swap_usage_in_pages(si));
 
 	file = si->swap_file;
-	len = seq_file_path(swap, file, " \t\n\\");
+	if (file)
+		len = seq_file_path(swap, file, " \t\n\\");
+	else {
+		char name[16];
+
+		len = scnprintf(name, sizeof(name), "xswap%d", si->type);
+		seq_puts(swap, name);
+	}
 	seq_printf(swap, "%*s%s\t%lu\t%s%lu\t%s%d\n",
 			len < 40 ? 40 - len : 1, " ",
-			S_ISBLK(file_inode(file)->i_mode) ?
-				"partition" : "file\t",
+			swap_type_str(si),
 			bytes, bytes < 10000000 ? "\t" : "",
 			inuse, inuse < 10000000 ? "\t" : "",
 			si->prio);
@@ -3609,12 +4012,8 @@ static unsigned long read_swap_header(struct swap_info_struct *si,
 		pr_warn("Truncating oversized swap area, only using %luk out of %luk\n",
 			K(maxpages), K(last_page));
 	}
-	if (maxpages > last_page) {
+	if (maxpages > last_page)
 		maxpages = last_page + 1;
-		/* p->max is an unsigned int: don't overflow it */
-		if ((unsigned int)maxpages == 0)
-			maxpages = UINT_MAX;
-	}
 
 	if (!maxpages)
 		return 0;
@@ -3631,6 +4030,483 @@ static unsigned long read_swap_header(struct swap_info_struct *si,
 	return maxpages;
 }
 
+#ifdef CONFIG_XSWAP
+static int xswap_map_clusters(struct swap_info_struct *si,
+			      unsigned long start_idx, unsigned long nr)
+{
+	unsigned long start_addr = (unsigned long)si->cluster_info +
+				   (size_t)start_idx * sizeof(struct swap_cluster_info);
+	unsigned long end_addr = start_addr + (size_t)nr * sizeof(struct swap_cluster_info);
+	unsigned long vm_start = PAGE_ALIGN(start_addr);
+	unsigned long vm_end = PAGE_ALIGN(end_addr);
+	unsigned int noreclaim_flags;
+	unsigned long mapped_end;
+	unsigned long npages;
+	struct page **pages;
+	unsigned long i;
+	int err;
+
+	mutex_lock(&si->xswap_lock);
+
+	/* Refuse a stale range: the boundary moved since the caller read it. */
+	if (start_idx != READ_ONCE(si->nr_clusters_mapped)) {
+		mutex_unlock(&si->xswap_lock);
+		return -EAGAIN;
+	}
+	if (start_idx + nr > si->nr_clusters_max) {
+		mutex_unlock(&si->xswap_lock);
+		return -EAGAIN;
+	}
+
+	/*
+	 * Page-granular mapping can cover clusters past the previous chunk.
+	 * Find the already-mapped prefix and map only the rest.
+	 */
+	mapped_end = vm_start;
+	if (vm_start < vm_end)
+		apply_to_existing_page_range(&init_mm, vm_start,
+					     vm_end - vm_start,
+					     xswap_mapped_end, &mapped_end);
+	if (vm_start >= vm_end || mapped_end == vm_end)
+		goto mapped;
+	vm_start = mapped_end;
+
+	npages = (vm_end - vm_start) >> PAGE_SHIFT;
+
+	/* Prevent recursive reclaim during vmap page table allocation. */
+	noreclaim_flags = memalloc_noreclaim_save();
+
+	pages = kmalloc_array(npages, sizeof(*pages),
+			      __GFP_HIGH | __GFP_NOMEMALLOC | GFP_KERNEL);
+	if (!pages) {
+		memalloc_noreclaim_restore(noreclaim_flags);
+		mutex_unlock(&si->xswap_lock);
+		return -ENOMEM;
+	}
+
+	for (i = 0; i < npages; i++) {
+		/* __GFP_ZERO: cluster_info pointer fields must start NULL. */
+		pages[i] = alloc_page(__GFP_HIGH | __GFP_NOMEMALLOC |
+				      GFP_KERNEL | __GFP_ZERO);
+		if (!pages[i])
+			goto fail;
+	}
+
+	err = vm_area_map_pages(si->cluster_vm, vm_start, vm_end, pages);
+	if (err) {
+		i = npages;
+		goto fail;
+	}
+
+	for (i = start_idx; i < start_idx + nr; i++)
+		spin_lock_init(&si->cluster_info[i].lock);
+
+	kfree(pages);
+	memalloc_noreclaim_restore(noreclaim_flags);
+
+	/*
+	 * Publish the new mappings and cluster lock initialization before
+	 * the count; walkers without xswap_lock use smp_load_acquire().
+	 */
+	smp_store_release(&si->nr_clusters_mapped, start_idx + nr);
+	mutex_unlock(&si->xswap_lock);
+	return 0;
+
+mapped:
+	for (i = start_idx; i < start_idx + nr; i++)
+		spin_lock_init(&si->cluster_info[i].lock);
+
+	/* Publish the advanced count. */
+	smp_store_release(&si->nr_clusters_mapped, start_idx + nr);
+	mutex_unlock(&si->xswap_lock);
+	return 0;
+
+fail:
+	/* Clear PTEs vm_area_map_pages() may have left before freeing pages. */
+	vm_area_unmap_pages(si->cluster_vm, vm_start, vm_end);
+	while (i > 0) {
+		i--;
+		if (pages[i])
+			__free_page(pages[i]);
+	}
+	memalloc_noreclaim_restore(noreclaim_flags);
+	kfree(pages);
+	mutex_unlock(&si->xswap_lock);
+	return -ENOMEM;
+}
+
+static bool xswap_should_grow(struct swap_info_struct *si)
+{
+	unsigned long mapped = READ_ONCE(si->nr_clusters_mapped);
+
+	if (mapped >= READ_ONCE(si->nr_clusters_max))
+		return false;
+
+	return swap_usage_in_pages(si) * 100 >=
+	       mapped * SWAPFILE_CLUSTER * XSWAP_GROW_WHEN;
+}
+
+/*
+ * Map more of the cluster_info array, up to GROW_UNTIL in use.  The caller
+ * holds percpu_swap_cluster.lock, which this drops while it sleeps.
+ */
+static unsigned long xswap_grow(struct swap_info_struct *si)
+{
+	unsigned long mapped = READ_ONCE(si->nr_clusters_mapped);
+	unsigned long nr_new, want, i;
+	int ret;
+
+	/* The unmap below is paired with the caller's lock. */
+	lockdep_assert_held(&percpu_swap_cluster.lock);
+
+	want = DIV_ROUND_UP(swap_usage_in_pages(si) * 100,
+			    XSWAP_GROW_UNTIL * SWAPFILE_CLUSTER);
+	if (want <= mapped)
+		return 0;
+
+	nr_new = rounddown(want - mapped, XSWAP_GROW_CLUSTERS);
+	if (!nr_new)
+		nr_new = XSWAP_GROW_CLUSTERS;
+	if (nr_new > XSWAP_GROW_CHUNKS * XSWAP_GROW_CLUSTERS)
+		nr_new = XSWAP_GROW_CHUNKS * XSWAP_GROW_CLUSTERS;
+	nr_new = min(nr_new, READ_ONCE(si->nr_clusters_max) - mapped);
+
+	/*
+	 * Mapping pages can sleep.  The lock only guards the per-cpu
+	 * cluster cache, which this path does not touch.
+	 */
+	local_unlock(&percpu_swap_cluster.lock);
+	ret = xswap_map_clusters(si, mapped, nr_new);
+	local_lock(&percpu_swap_cluster.lock);
+	if (ret)
+		return 0;
+
+	for (i = mapped; i < mapped + nr_new; i++) {
+		struct swap_cluster_info *ci = &si->cluster_info[i];
+
+		/*
+		 * A concurrent grower may have taken these already;
+		 * only add the off-list ones.
+		 */
+		spin_lock(&ci->lock);
+		if (ci->flags == CLUSTER_FLAG_NONE)
+			move_cluster(si, ci, &si->free_clusters,
+				     CLUSTER_FLAG_FREE);
+		spin_unlock(&ci->lock);
+	}
+
+	atomic_long_inc(&si->xswap_grows);
+	return nr_new;
+}
+
+struct xswap_page_data {
+	struct page **pages;
+	unsigned long nr;
+	unsigned long max;
+};
+
+static int xswap_collect_page(pte_t *pte, unsigned long addr, void *data)
+{
+	struct xswap_page_data *xpd = data;
+	pte_t pteval = ptep_get(pte);
+
+	if (!pte_present(pteval))
+		return 0;
+	if (WARN_ON_ONCE(xpd->nr >= xpd->max))
+		return 0;
+	xpd->pages[xpd->nr++] = pte_page(pteval);
+	return 0;
+}
+
+/*
+ * Free the backing pages mapped in [vm_start, vm_end) and clear the PTEs.
+ * @pages must have room for @max pointers.
+ */
+static void xswap_unmap_range(struct swap_info_struct *si,
+			      unsigned long vm_start, unsigned long vm_end,
+			      struct page **pages, unsigned long max)
+{
+	struct xswap_page_data xpd = {
+		.pages	= pages,
+		.max	= max,
+	};
+	unsigned long i;
+
+	apply_to_existing_page_range(&init_mm, vm_start, vm_end - vm_start,
+				     xswap_collect_page, &xpd);
+	vm_area_unmap_pages(si->cluster_vm, vm_start, vm_end);
+
+	for (i = 0; i < xpd.nr; i++)
+		__free_page(pages[i]);
+}
+
+/* Caller must hold si->xswap_lock.  Cannot fail. */
+static void xswap_unmap_clusters_locked(struct swap_info_struct *si,
+					unsigned long start_idx, unsigned long nr)
+{
+	unsigned long start_addr = (unsigned long)si->cluster_info +
+				   (size_t)start_idx * sizeof(struct swap_cluster_info);
+	unsigned long end_addr = start_addr +
+				 (size_t)nr * sizeof(struct swap_cluster_info);
+	unsigned long vm_start = PAGE_ALIGN(start_addr);
+	unsigned long vm_end = PAGE_ALIGN(end_addr);
+	struct page **pages;
+	unsigned int noreclaim_flags;
+	unsigned long npages, idx;
+
+	if (vm_start >= vm_end) {
+		WRITE_ONCE(si->nr_clusters_mapped, start_idx);
+		return;
+	}
+
+	/*
+	 * A per-cpu cluster cache can still hold an offset in this range.
+	 * Invalidate those references, then wait out the readers that have
+	 * already loaded one, so that nobody can dereference cluster_info
+	 * past this point.  swapoff() needs the same before it releases.
+	 */
+	flush_percpu_swap_cluster(si);
+	synchronize_rcu();
+
+	npages = (vm_end - vm_start) >> PAGE_SHIFT;
+
+	/* Reclaim here would re-enter xswap_map_clusters() and its lock. */
+	noreclaim_flags = memalloc_noreclaim_save();
+	pages = kvmalloc_array(npages, sizeof(*pages), GFP_KERNEL);
+	memalloc_noreclaim_restore(noreclaim_flags);
+	if (pages) {
+		xswap_unmap_range(si, vm_start, vm_end, pages, npages);
+		kvfree(pages);
+		WRITE_ONCE(si->nr_clusters_mapped, start_idx);
+		return;
+	}
+
+	/* No memory for the array: unmap in bounded batches instead. */
+	for (idx = start_idx; idx < start_idx + nr; idx += XSWAP_UNMAP_BATCH_CLUSTERS) {
+		unsigned long batch = min(start_idx + nr - idx,
+					  XSWAP_UNMAP_BATCH_CLUSTERS);
+		unsigned long addr = (unsigned long)si->cluster_info +
+				     (size_t)idx * sizeof(struct swap_cluster_info);
+		unsigned long bstart = PAGE_ALIGN(addr);
+		unsigned long bend = PAGE_ALIGN(addr + (size_t)batch *
+					       sizeof(struct swap_cluster_info));
+		struct page *batch_pages[XSWAP_UNMAP_BATCH_PAGES + 1];
+
+		if (bstart < bend)
+			xswap_unmap_range(si, bstart, bend, batch_pages,
+					  ARRAY_SIZE(batch_pages));
+	}
+
+	WRITE_ONCE(si->nr_clusters_mapped, start_idx);
+}
+
+static void xswap_unmap_clusters(struct swap_info_struct *si,
+				 unsigned long start_idx, unsigned long nr)
+{
+	mutex_lock(&si->xswap_lock);
+	xswap_unmap_clusters_locked(si, start_idx, nr);
+	mutex_unlock(&si->xswap_lock);
+}
+
+/* Track the end of the run of pages that is already mapped. */
+static int xswap_mapped_end(pte_t *pte, unsigned long addr, void *data)
+{
+	unsigned long *mapped_end = data;
+
+	if (!pte_present(ptep_get(pte)))
+		return 0;
+	*mapped_end = addr + PAGE_SIZE;
+	return 0;
+}
+
+/*
+ * Automatic reclaim: leave one chunk of the free tail mapped as slack, so
+ * that the next allocation has somewhere to land, and only unmap once
+ * several chunks can go, so the unmap is worth the RCU grace period it
+ * costs.
+ */
+#define XSWAP_SHRINK_SLACK	XSWAP_GROW_CLUSTERS
+#define XSWAP_SHRINK_MIN	(XSWAP_GROW_CLUSTERS * 8)
+
+static void xswap_shrink_work_fn(struct work_struct *work)
+{
+	struct swap_info_struct *si = container_of(work,
+			struct swap_info_struct, xswap_shrink_work);
+
+	if (!(READ_ONCE(si->flags) & SWP_WRITEOK))
+		return;
+	xswap_try_shrink(si);
+}
+
+/*
+ * Try to shrink the cluster_info tail: unmap contiguous free clusters
+ * at the end of the mapped range.
+ */
+static void xswap_try_shrink(struct swap_info_struct *si)
+{
+	struct swap_cluster_info *ci;
+	unsigned long nr_mapped, nr_tail, keep, nr_unmap, start_idx, i;
+
+	if (!(si->flags & SWP_XSWAP))
+		return;
+
+	mutex_lock(&si->xswap_lock);
+
+	/* A swapoff raced us and is about to walk this mapping. */
+	if (!(READ_ONCE(si->flags) & SWP_WRITEOK))
+		goto out_unlock;
+
+	nr_mapped = READ_ONCE(si->nr_clusters_mapped);
+	if (nr_mapped <= 1)	/* keep cluster 0 */
+		goto out_unlock;
+
+	/*
+	 * Reclaim on our own, but only once the mapped range is at most
+	 * SHRINK_WHEN in use: growth is demand driven, so reclaiming on a
+	 * smaller dip would only map the same clusters again, and every
+	 * unmap costs an RCU grace period.
+	 */
+	if (swap_usage_in_pages(si) * 100 >
+	    nr_mapped * SWAPFILE_CLUSTER * XSWAP_SHRINK_WHEN)
+		goto out_unlock;
+
+	/*
+	 * Count the free clusters at the tail of the mapped range.  Scanned,
+	 * not tracked: the count must be exact to size the unmap, and an
+	 * incremental count falls behind on out-of-order frees.
+	 */
+	nr_tail = 0;
+	while (nr_mapped - nr_tail > 1) {
+		ci = &si->cluster_info[nr_mapped - nr_tail - 1];
+		if (READ_ONCE(ci->count) ||
+		    READ_ONCE(ci->flags) != CLUSTER_FLAG_FREE)
+			break;
+		nr_tail++;
+	}
+	if (nr_tail < XSWAP_SHRINK_SLACK + XSWAP_SHRINK_MIN)
+		goto out_unlock;
+
+	/*
+	 * Stop at SHRINK_UNTIL rather than at the end of the tail, or the
+	 * range comes out full enough for the grow to be woken.  Below the
+	 * tail everything stays mapped, and one chunk of tail with it.
+	 */
+	keep = DIV_ROUND_UP(swap_usage_in_pages(si) * 100,
+			    XSWAP_SHRINK_UNTIL * SWAPFILE_CLUSTER);
+	if (keep < nr_mapped - nr_tail + XSWAP_SHRINK_SLACK)
+		keep = nr_mapped - nr_tail + XSWAP_SHRINK_SLACK;
+
+	if (nr_mapped < keep + XSWAP_SHRINK_MIN)
+		goto out_unlock;
+
+	nr_unmap = rounddown(nr_mapped - keep, XSWAP_GROW_CLUSTERS);
+	if (!nr_unmap)
+		goto out_unlock;
+	start_idx = nr_mapped - nr_unmap;
+
+	/*
+	 * Only shrink a run that reaches the mapped end; otherwise
+	 * truncating nr_clusters_mapped would orphan the active tail.
+	 */
+	spin_lock(&si->lock);
+	for (i = start_idx; i < nr_mapped; i++) {
+		ci = &si->cluster_info[i];
+		if (READ_ONCE(ci->flags) != CLUSTER_FLAG_FREE)
+			break;
+		if (!spin_trylock(&ci->lock)) {
+			spin_unlock(&si->lock);
+			goto out_unlock;
+		}
+		spin_unlock(&ci->lock);
+	}
+	if (i != nr_mapped) {
+		spin_unlock(&si->lock);
+		goto out_unlock;
+	}
+
+	for (i = start_idx; i < nr_mapped; i++) {
+		ci = &si->cluster_info[i];
+		list_del_init(&ci->list);
+		WRITE_ONCE(ci->flags, CLUSTER_FLAG_NONE);
+	}
+	spin_unlock(&si->lock);
+
+	xswap_unmap_clusters_locked(si, start_idx, nr_unmap);
+	atomic_long_inc(&si->xswap_shrinks);
+
+out_unlock:
+	mutex_unlock(&si->xswap_lock);
+}
+
+/* Not an interface: how far the mapped range has moved, for testing. */
+static ssize_t xswap_debugfs_read(struct file *file, char __user *buf,
+				  size_t count, loff_t *ppos)
+{
+	struct swap_info_struct *si = file->private_data;
+	struct swap_cluster_info *ci;
+	unsigned long mapped, tail = 0;
+	char tmp[192];
+	int len;
+
+	/*
+	 * The same scan the shrink does.  xswap_lock is what keeps
+	 * cluster_info from being unmapped under it.
+	 */
+	mutex_lock(&si->xswap_lock);
+	mapped = READ_ONCE(si->nr_clusters_mapped);
+	if (si->cluster_info) {
+		while (mapped - tail > 1) {
+			ci = &si->cluster_info[mapped - tail - 1];
+			if (READ_ONCE(ci->count) ||
+			    READ_ONCE(ci->flags) != CLUSTER_FLAG_FREE)
+				break;
+			tail++;
+		}
+	}
+	len = scnprintf(tmp, sizeof(tmp),
+			"clusters_max %lu\nclusters_mapped %lu\nusage_pages %lu\ntail_free %lu\ngrows %lu\nshrinks %lu\n",
+			READ_ONCE(si->nr_clusters_max), mapped,
+			swap_usage_in_pages(si), tail,
+			atomic_long_read(&si->xswap_grows),
+			atomic_long_read(&si->xswap_shrinks));
+	mutex_unlock(&si->xswap_lock);
+
+	return simple_read_from_buffer(buf, count, ppos, tmp, len);
+}
+
+static const struct file_operations xswap_debugfs_fops = {
+	.read	= xswap_debugfs_read,
+	.open	= simple_open,
+	.llseek	= default_llseek,
+};
+
+static struct dentry *xswap_debugfs_root;
+
+static void xswap_debugfs_add(struct swap_info_struct *si)
+{
+	char name[16];
+
+	if (!xswap_debugfs_root)
+		xswap_debugfs_root = debugfs_create_dir("xswap", NULL);
+	if (IS_ERR_OR_NULL(xswap_debugfs_root))
+		return;
+
+	/* debugfs_create_file() takes the name as it is; no formatting. */
+	snprintf(name, sizeof(name), "type%d", si->type);
+	si->xswap_debugfs = debugfs_create_file(name, 0444,
+						xswap_debugfs_root, si,
+						&xswap_debugfs_fops);
+	if (IS_ERR(si->xswap_debugfs))
+		si->xswap_debugfs = NULL;
+}
+
+static void xswap_debugfs_del(struct swap_info_struct *si)
+{
+	debugfs_remove(si->xswap_debugfs);
+	si->xswap_debugfs = NULL;
+}
+#endif /* CONFIG_XSWAP */
+
 static int setup_swap_clusters_info(struct swap_info_struct *si,
 				    union swap_header *swap_header,
 				    unsigned long maxpages)
@@ -3640,10 +4516,76 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,
 	int err = -ENOMEM;
 	unsigned long i;
 
+#ifdef CONFIG_XSWAP
+	if (si->flags & SWP_XSWAP) {
+		unsigned long size = PAGE_ALIGN(nr_clusters * sizeof(*cluster_info));
+		struct vm_struct *vm;
+
+		vm = get_vm_area(size, VM_SPARSE);
+		if (!vm)
+			goto err;
+
+		cluster_info = vm->addr;
+		si->cluster_vm = vm;
+		si->nr_clusters_max = nr_clusters;
+		si->cluster_info = cluster_info;
+
+		/* Must be initialized before xswap_map_clusters() locks it. */
+		mutex_init(&si->xswap_lock);
+
+		if (xswap_map_clusters(si, 0, min_t(unsigned long,
+					XSWAP_GROW_CLUSTERS, nr_clusters)))
+			goto err_free_vm;
+
+		/* xswap: only cluster 0 slot 0 is bad */
+		err = swap_cluster_setup_bad_slot(si, cluster_info, 0, false);
+		if (err)
+			goto err_unmap;
+
+		INIT_LIST_HEAD(&si->free_clusters);
+		INIT_LIST_HEAD(&si->full_clusters);
+		INIT_LIST_HEAD(&si->discard_clusters);
+		for (i = 0; i < SWAP_NR_ORDERS; i++) {
+			INIT_LIST_HEAD(&si->nonfull_clusters[i]);
+			INIT_LIST_HEAD(&si->frag_clusters[i]);
+		}
+
+		/*
+		 * Cluster 0 holds the header slot, which is marked bad, so it
+		 * is not entirely free.  si->max is cluster aligned, so no
+		 * cluster holds a slot past the end of the device.
+		 */
+		for (i = 0; i < si->nr_clusters_mapped; i++) {
+			struct swap_cluster_info *ci = &cluster_info[i];
+
+			if (ci->count) {
+				ci->flags = CLUSTER_FLAG_NONFULL;
+				list_add_tail(&ci->list, &si->nonfull_clusters[0]);
+			} else {
+				ci->flags = CLUSTER_FLAG_FREE;
+				list_add_tail(&ci->list, &si->free_clusters);
+			}
+		}
+
+		INIT_WORK(&si->xswap_shrink_work, xswap_shrink_work_fn);
+		return 0;
+
+err_unmap:
+		xswap_unmap_clusters(si, 0, si->nr_clusters_mapped);
+err_free_vm:
+		free_vm_area(si->cluster_vm);
+		si->cluster_vm = NULL;
+		si->cluster_info = NULL;
+		return err;
+	}
+#endif /* CONFIG_XSWAP */
+
 	cluster_info = kvzalloc_objs(*cluster_info, nr_clusters);
 	if (!cluster_info)
 		goto err;
 
+	si->cluster_info = cluster_info;
+
 	for (i = 0; i < nr_clusters; i++)
 		spin_lock_init(&cluster_info[i].lock);
 
@@ -3707,10 +4649,135 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,
 	si->cluster_info = cluster_info;
 	return 0;
 err:
-	free_swap_cluster_info(cluster_info, maxpages);
+	free_swap_cluster_info(si);
 	return err;
 }
 
+#ifdef CONFIG_XSWAP
+/* Create a file-less xswap device, sized at twice RAM. */
+static int xswap_create(int prio)
+{
+	struct swap_info_struct *si;
+	unsigned long maxpages;
+	int error;
+
+	if (prio != DEF_XSWAP_PRIO &&
+	    (prio < 0 || prio > SWAP_FLAG_PRIO_MASK))
+		return -EINVAL;
+
+	/* xswap has no backing store, it relies on zswap. */
+	if (!zswap_is_enabled())
+		return -EOPNOTSUPP;
+
+	/* Refuse rather than clamp: xswap.max= should give what was asked. */
+	maxpages = xswap_size_pages();
+	if (maxpages > xswap_size_limit()) {
+		pr_err("xswap: xswap.max is larger than the device can address\n");
+		return -EINVAL;
+	}
+	/*
+	 * Below one cluster the device is not cluster-aligned, so its only
+	 * cluster would hold slots past si->max.  Nothing masks those, and a
+	 * slot allocated there is past the end of the device: it can never be
+	 * read back or given up again.
+	 */
+	if (maxpages < SWAPFILE_CLUSTER) {
+		pr_err("xswap: xswap.max is smaller than one cluster\n");
+		return -EINVAL;
+	}
+
+	si = alloc_swap_info();
+	if (IS_ERR(si))
+		return PTR_ERR(si);
+
+	INIT_WORK(&si->discard_work, swap_discard_work);
+	INIT_WORK(&si->reclaim_work, swap_reclaim_work);
+
+	/* Cluster-aligned, so no cluster holds a slot past si->max. */
+	maxpages = rounddown(maxpages, SWAPFILE_CLUSTER);
+
+	si->bdev = NULL;
+	si->flags |= SWP_XSWAP | SWP_SOLIDSTATE;
+	si->max = maxpages;
+	si->pages = maxpages - 1;
+	/*
+	 * No backing file: setup_swap_extents() is only reachable from the
+	 * file-backed swapon() path, so set ops here.  Only ops->flags is
+	 * used, by may_enter_fs(); the IO methods are never called because
+	 * swap_writeout()/swap_read_folio() short circuit xswap.
+	 */
+	si->ops = &swap_bdev_ops;
+
+	si->xswap_debugfs = NULL;
+	atomic_long_set(&si->xswap_grows, 0);
+	atomic_long_set(&si->xswap_shrinks, 0);
+
+	error = setup_swap_clusters_info(si, NULL, maxpages);
+	if (error)
+		goto bad_swap;
+
+	xswap_debugfs_add(si);
+
+	error = zswap_swapon(si->type, si->max);
+	if (error)
+		goto bad_swap;
+
+	mutex_lock(&swapon_mutex);
+	si->prio = prio;
+	si->list.prio = -si->prio;
+	si->avail_list.prio = -si->prio;
+	/* si->swap_file stays NULL: this is a file-less device */
+	enable_swap_info(si);
+	pr_info("xswap: adding extendable swap type %d (prio %d, %lu pages)\n",
+		si->type, prio, si->pages);
+	mutex_unlock(&swapon_mutex);
+	atomic_inc(&proc_poll_event);
+	wake_up_interruptible(&proc_poll_wait);
+
+	return si->type;
+
+bad_swap:
+	kfree(si->global_cluster);
+	si->global_cluster = NULL;
+	destroy_swap_extents(si, NULL);	/* safe: xswap never sets SWP_ACTIVATED */
+	free_swap_cluster_info(si);
+	si->cluster_info = NULL;
+	spin_lock(&swap_lock);
+	si->flags = 0;
+	spin_unlock(&swap_lock);
+	return error;
+}
+
+/* Tear down a file-less xswap device by its swap type. */
+static int xswap_destroy(int type)
+{
+	struct swap_info_struct *p;
+	int err;
+
+	p = swap_type_to_info(type);
+	if (!p)
+		return -EINVAL;
+
+	spin_lock(&swap_lock);
+	if (!(p->flags & SWP_WRITEOK) || !(p->flags & SWP_XSWAP)) {
+		spin_unlock(&swap_lock);
+		return -EINVAL;
+	}
+	/* Refuse swapoff while the device is pinned for hibernation */
+	if (p->flags & SWP_HIBERNATION) {
+		spin_unlock(&swap_lock);
+		return -EBUSY;
+	}
+
+	err = swap_info_remove(p);
+	spin_unlock(&swap_lock);
+	if (err)
+		return err;
+
+	return __swapoff(p);
+}
+#endif /* CONFIG_XSWAP */
+
 SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 {
 	struct swap_info_struct *si;
@@ -3815,7 +4882,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 		goto bad_swap_unlock_inode;
 	}
 	if (si->pages != si->max - 1) {
-		pr_err("swap:%u != (max:%u - 1)\n", si->pages, si->max);
+		pr_err("swap:%lu != (max:%lu - 1)\n", si->pages, si->max);
 		error = -EINVAL;
 		goto bad_swap_unlock_inode;
 	}
@@ -3906,7 +4973,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 	/* Sets SWP_WRITEOK, resurrect the percpu ref, expose the swap device */
 	enable_swap_info(si);
 
-	pr_info("Adding %uk swap on %s.  Priority:%d extents:%d across:%lluk %s%s%s%s\n",
+	pr_info("Adding %luk swap on %s.  Priority:%d extents:%d across:%lluk %s%s%s%s\n",
 		K(si->pages), name->name, si->prio, nr_extents,
 		K((unsigned long long)span),
 		(si->flags & SWP_SOLIDSTATE) ? "SS" : "",
@@ -3929,7 +4996,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 	si->global_cluster = NULL;
 	inode = NULL;
 	destroy_swap_extents(si, swap_file);
-	free_swap_cluster_info(si->cluster_info, si->max);
+	free_swap_cluster_info(si);
 	si->cluster_info = NULL;
 	/*
 	 * Clear the SWP_USED flag after all resources are freed so
@@ -4057,6 +5124,8 @@ static int __init swapfile_init(void)
 		swap_migration_ad_supported = true;
 #endif	/* CONFIG_MIGRATION */
 
+	xswap_sysfs_init();
+
 	return 0;
 }
 subsys_initcall(swapfile_init);
diff --git a/mm/zswap.c b/mm/zswap.c
index ae19e301fced7..7fe25f0b157ce 100644
--- a/mm/zswap.c
+++ b/mm/zswap.c
@@ -1018,6 +1018,11 @@ static int zswap_writeback_entry(struct zswap_entry *entry,
 	if (IS_ERR_OR_NULL(si))
 		return -ENOENT;
 
+	if (si->flags & SWP_XSWAP) {
+		put_swap_device(si);
+		return -EINVAL;
+	}
+
 	mpol = get_task_policy(current);
 	folio = __swap_cache_alloc_folio(swpentry, GFP_KERNEL, BIT(0), NULL, mpol,
 					 NO_INTERLEAVE_INDEX);
@@ -1511,7 +1516,9 @@ static bool zswap_store_page(struct folio *folio, long index,
 	entry->referenced = true;
 	if (entry->length) {
 		INIT_LIST_HEAD(&entry->lru);
-		zswap_lru_add(entry);
+		/* No backing store: nothing to write these back to. */
+		if (!(__swap_entry_to_info(page_swpentry)->flags & SWP_XSWAP))
+			zswap_lru_add(entry);
 	}
 
 	return true;
@@ -1581,7 +1588,7 @@ bool zswap_store(struct folio *folio)
 	zswap_pool_put(pool);
 put_objcg:
 	obj_cgroup_put(objcg);
-	if (!ret && zswap_pool_reached_full)
+	if (!ret && zswap_pool_reached_full && atomic_read(&nr_real_swapfiles))
 		queue_work(shrink_wq, &zswap_shrink_work);
 check_old:
 	/*

3/2 2026/10/03 10:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 25480
							output: 28
							thoughts: 1326
						

Thoughts:
**Xswap Patch Series Evaluation**

Okay, so I'm looking at a patch series for the Linux kernel, specifically the amd64 architecture, that introduces a new "xswap" virtual swap device. Let's break this down.

First, the diff shows additions and modifications to core memory management files. We're talking about changes to `include/linux/swap.h`, `mm/Kconfig`, `mm/page_io.c`, `mm/swap_state.c`, `mm/swapfile.c`, and `mm/zswap.c`.  This hits the MM core. A new `SWP_XSWAP` flag is being introduced, along with a significant amount of infrastructure. This is a big deal, we aren't just messing with a driver, we're changing fundamental swap behavior.

The core of the change lies in `mm/swapfile.c`, where there is sysfs interaction. I see the addition of sysfs entries: `/sys/kernel/mm/xswap/create` and `/sys/kernel/mm/xswap/destroy`.  This immediately tells me there's an external API, likely requiring CAP_SYS_ADMIN. That is important from a fuzzing perspective, as it opens up external attack surface.  It also suggests boot parameter support with `xswap.max=`. VM sparse areas and cluster information are added, implying dynamic mapping and unmapping with heavy concurrency logic.  There are also changes to swap allocation and deallocation, plus `swapoff` is also updated. I also spot debugfs integration as well.

The integration with zswap is noteworthy. `mm/zswap.c` checks for the `SWP_XSWAP` flag, indicating that the new virtual swap device will work with zswap.

The `WARN_ON_ONCE` in `swap_read_folio` is another flag. This looks like a defensive check, suggesting an area that might be prone to subtle issues or race conditions. This is the code's way of saying "if we hit this, something's gone horribly wrong, but at least we'll know about it."

Given the core subsystem involvement (`mm/`), external API interaction via sysfs, and the presence of runtime assertions (specifically `WARN_ON_ONCE`), this screams "WorthFuzzing = TRUE". This also checks all the boxes for a very interesting attack surface.

The `mm/Kconfig` dependency `depends on SWAP && 64BIT && ZSWAP && SYSFS` confirms that these are critical dependencies. This new device depends on core swap functionality, a 64-bit architecture, zswap, and the system file system, it's not some add-on, it has a lot of important dependencies. I need to be sure those are set up.

Alright, time to get this into the fuzzer.



4/2 2026/10/03 10:12 tool grepper
0m Args:
{
  "Expression": "config XSWAP",
  "PathPrefix": "mm/Kconfig"
}

Results:
{
  "Output": "mm/Kconfig=114=config ZSWAP_COMPRESSOR_DEFAULT\n--\nmm/Kconfig-124-\nmm/Kconfig:125:config XSWAP\nmm/Kconfig-126-\tbool \"Extendable (virtual) swap device\"\n"
}

5/2 2026/10/03 10:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 27523
							output: 32
							thoughts: 20
						

Thoughts:
Here's a summary of my thought process, as requested:

**Diving into `mm/Kconfig`**

Okay, time to get my hands dirty. I need to understand the memory management configuration options better. Let's start by focusing on a specific section within `mm/Kconfig`. I'm going to jump to lines 120-140. I know this file is where the kernel's configuration options related to memory are defined, and this section likely contains something interesting that I need to analyze. It could be a new feature, a bug fix, or simply an option I've overlooked in the past. Time to dig in and see what's what.



6/2 2026/10/03 10:12 tool read-file
0m Args:
{
  "File": "mm/Kconfig",
  "FirstLine": 120,
  "LineCount": 20
}

Results:
{
  "Contents": " 120:\t       default \"lz4\" if ZSWAP_COMPRESSOR_DEFAULT_LZ4\n 121:\t       default \"lz4hc\" if ZSWAP_COMPRESSOR_DEFAULT_LZ4HC\n 122:\t       default \"zstd\" if ZSWAP_COMPRESSOR_DEFAULT_ZSTD\n 123:\t       default \"\"\n 124:\t\n 125:\tconfig XSWAP\n 126:\t\tbool \"Extendable (virtual) swap device\"\n 127:\t\tdepends on SWAP \u0026\u0026 64BIT \u0026\u0026 ZSWAP \u0026\u0026 SYSFS\n 128:\t\thelp\n 129:\t\t  Adds support for extendable swap devices (xswap) that decouple\n 130:\t\t  PTE swap entries from physical backing storage. The cluster_info\n 131:\t\t  array is backed by a sparse vmalloc area that grows and shrinks\n 132:\t\t  on demand, avoiding static pre-allocation overhead.\n 133:\t\n 134:\tconfig ZSMALLOC\n 135:\t\ttristate\n 136:\t\n 137:\tmenu \"Zsmalloc allocator options\"\n 138:\t\tdepends on ZSMALLOC\n 139:\t\n"
}

7/2 2026/10/03 10:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28040
							output: 30
							thoughts: 108
						

Thoughts:
**Analyzing the Dependencies of XSWAP**

Okay, let's dissect the dependencies for `XSWAP`. It looks like it directly relies on `SWAP`, `64BIT`, `ZSWAP`, and `SYSFS`. My initial thought is to make certain there are no other hidden dependencies or conditional guards lurking in the shadows. I'll need to double-check.

The target architecture is amd64, so `64BIT` is essentially a given for x86_64, which simplifies things. Now, the real meat of this analysis lies in `ZSWAP`, `SWAP`, and `SYSFS`. I'll delve into the `Kconfig` files and grep for occurrences of each of those. I'll start with `ZSWAP` and look in `mm/Kconfig`.



8/2 2026/10/03 10:12 tool grepper
0m Args:
{
  "Expression": "config ZSWAP\\b",
  "PathPrefix": "mm/Kconfig"
}

Results:
{
  "Output": "mm/Kconfig=12=menuconfig SWAP\n--\nmm/Kconfig-21-\nmm/Kconfig:22:config ZSWAP\nmm/Kconfig-23-\tbool \"Compressed cache for swap pages\"\n"
}

9/2 2026/10/03 10:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28420
							output: 31
							thoughts: 17
						

Thoughts:
Here's a summary of my thought process, as requested:

**Checking ZSWAP Dependencies in mm/Kconfig**

Okay, let's get down to brass tacks. I need to understand the configuration landscape surrounding `ZSWAP`. This means I need to dive into the `mm/Kconfig` file. I'm going to start by pulling that up, immediately. It's the central configuration hub for memory management options. My immediate goal is to map out precisely what conditions must be met, what other features or dependencies are involved, before `ZSWAP` can even be considered for inclusion. I'm talking dependencies on specific architectures, specific hardware features, or other core memory management components. I'm looking for the logical structure: the `if` statements, the `depends on` clauses, the nested relationships. This file will be key to understanding the control flow. I need to be sure I understand the complete configuration space to ensure no assumptions are made. I need to trace this carefully.



10/2 2026/10/03 10:12 tool read-file
0m Args:
{
  "File": "mm/Kconfig",
  "FirstLine": 20,
  "LineCount": 25
}

Results:
{
  "Contents": "  20:\t\t  in your computer.  If unsure say Y.\n  21:\t\n  22:\tconfig ZSWAP\n  23:\t\tbool \"Compressed cache for swap pages\"\n  24:\t\tdepends on SWAP\n  25:\t\tselect CRYPTO\n  26:\t\tselect ZSMALLOC\n  27:\t\thelp\n  28:\t\t  A lightweight compressed cache for swap pages.  It takes\n  29:\t\t  pages that are in the process of being swapped out and attempts to\n  30:\t\t  compress them into a dynamically allocated RAM-based memory pool.\n  31:\t\t  This can result in a significant I/O reduction on swap device and,\n  32:\t\t  in the case where decompressing from RAM is faster than swap device\n  33:\t\t  reads, can also improve workload performance.\n  34:\t\n  35:\tconfig ZSWAP_DEFAULT_ON\n  36:\t\tbool \"Enable the compressed cache for swap pages by default\"\n  37:\t\tdepends on ZSWAP\n  38:\t\thelp\n  39:\t\t  If selected, the compressed cache for swap pages will be enabled\n  40:\t\t  at boot, otherwise it will be disabled.\n  41:\t\n  42:\t\t  The selection made here can be overridden by using the kernel\n  43:\t\t  command line 'zswap.enabled=' option.\n  44:\t\n"
}

11/2 2026/10/03 10:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 29028
							output: 44
							thoughts: 1437
						

Thoughts:
**My Analysis of the XSWAP Implementation**

Okay, so I'm diving into this XSWAP patch. First, I noticed in `xswap_create` that it explicitly checks for `zswap_is_enabled()` and bails out if it's not. This means `ZSWAP` is a hard requirement, but more precisely that `CONFIG_ZSWAP_DEFAULT_ON` is *very* useful if it's not a hard requirement. I need to be aware of the dependencies on `ZSWAP`, `SWAP`, `64BIT`, and `SYSFS`.

I see that `XSWAP`'s debugfs interface is guarded by `CONFIG_XSWAP` which then uses debugfs functions. Debugfs is optional, as the debugfs functions are stubbed if `CONFIG_DEBUG_FS` isn't set, but I'll make sure to note that enabling `XSWAP`, `ZSWAP` and ideally `ZSWAP_DEFAULT_ON` is the best configuration.

Now, let's get down to the meat of it. I'm focusing on the functions that implement the *specific* XSWAP logic or are direct entrypoints, as I need to avoid listing ubiquitous lifecycle functions like generic memory allocators which would dilute the fuzzing effort. I'm going to look for non-static entrypoints in the `.c` files, or static functions that aren't inlined, as those will have symbol table entries.

Here's the list of functions I've identified, keeping in mind the need to focus on specific XSWAP logic and avoid generic hot-paths:

*   In `mm/swapfile.c`:
    *   `xswap_create_store`
    *   `xswap_destroy_store`
    *   `xswap_create`
    *   `xswap_destroy`
    *   `xswap_map_clusters`
    *   `xswap_unmap_clusters`
    *   `xswap_unmap_clusters_locked`
    *   `xswap_grow`
    *   `xswap_should_grow`
    *   `xswap_try_shrink`
    *   `xswap_shrink_work_fn`
    *   `xswap_debugfs_read`
    *   `xswap_debugfs_add`
    *   `xswap_debugfs_del`
    *   `xswap_mapped_end`
    *   `xswap_collect_page`
    *   `xswap_unmap_range`
    *   `xswap_size_limit`
    *   `xswap_size_pages`
    *   `xswap_sysfs_init`
    *   `free_swap_cluster_info`
    *   `swap_info_remove`
    *   `__swapoff`
    *   `__do_sys_swapoff` (or `sys_swapoff` / `swapoff`)
    *   `cluster_alloc_swap_entry`
    *   `alloc_swap_scan_cluster`
    *   `alloc_swap_scan_list`
    *   `swap_reclaim_full_clusters`
    *   `swap_alloc_fast`
    *   `swap_alloc_slow`
    *   `setup_swap_clusters_info`
    *   `swap_type_str`
    *   `swap_show`

*   In `mm/page_io.c`:
    *   `swap_writeout`
    *   `swap_read_folio`

*   In `mm/swap_state.c`:
    *   `swap_cluster_readahead`
    *   `swap_vma_readahead`

*   In `mm/zswap.c`:
    *   `zswap_writeback_entry`
    *   `zswap_store_page`
    *   `zswap_store`

I'm deliberately excluding functions like `folio_alloc_swap` as it's more generic than the specific functions above that more directly interact with XSWAP, memory reclamation, and swap operations. I want a focused list that hones in on this specific new functionality. I'm going to now investigate their definitions more closely to make sure they're relevant, and whether they might be inlined or not.



12/2 2026/10/03 10:13 tool grepper
0m Args:
{
  "Expression": "static (int|unsigned|void|ssize_t|bool) xswap_",
  "PathPrefix": "mm/swapfile.c"
}

Results:
{
  "Output": "mm/swapfile.c-86-\nmm/swapfile.c:87:static bool xswap_should_grow(struct swap_info_struct *si);\nmm/swapfile.c-88-static unsigned long xswap_grow(struct swap_info_struct *si);\nmm/swapfile.c:89:static void xswap_debugfs_del(struct swap_info_struct *si);\nmm/swapfile.c-90-\n--\nmm/swapfile.c-97-\nmm/swapfile.c:98:static int xswap_map_clusters(struct swap_info_struct *si,\nmm/swapfile.c-99-\t\t\t      unsigned long start_idx, unsigned long nr);\nmm/swapfile.c:100:static void xswap_unmap_clusters(struct swap_info_struct *si,\nmm/swapfile.c-101-\t\t\t\t unsigned long start_idx, unsigned long nr);\nmm/swapfile.c:102:static int xswap_mapped_end(pte_t *pte, unsigned long addr, void *data);\nmm/swapfile.c:103:static void xswap_try_shrink(struct swap_info_struct *si);\nmm/swapfile.c-104-\nmm/swapfile.c:105:static int xswap_create(int prio);\nmm/swapfile.c:106:static int xswap_destroy(int type);\nmm/swapfile.c-107-\nmm/swapfile.c:108:static ssize_t xswap_create_store(struct kobject *kobj,\nmm/swapfile.c-109-\t\t\t\t  struct kobj_attribute *attr,\n--\nmm/swapfile.c=132=static struct kobj_attribute xswap_create_attr = __ATTR(create, 0200, NULL,\n--\nmm/swapfile.c-134-\nmm/swapfile.c:135:static ssize_t xswap_destroy_store(struct kobject *kobj,\nmm/swapfile.c-136-\t\t\t\t   struct kobj_attribute *attr,\n--\nmm/swapfile.c=228=static struct kobject *xswap_kobj;\nmm/swapfile.c-229-\nmm/swapfile.c:230:static void xswap_sysfs_init(void)\nmm/swapfile.c-231-{\n--\nmm/swapfile.c=3974=static unsigned long read_swap_header(struct swap_info_struct *si,\n--\nmm/swapfile.c-4033-#ifdef CONFIG_XSWAP\nmm/swapfile.c:4034:static int xswap_map_clusters(struct swap_info_struct *si,\nmm/swapfile.c-4035-\t\t\t      unsigned long start_idx, unsigned long nr)\n--\nmm/swapfile.c-4137-\nmm/swapfile.c:4138:static bool xswap_should_grow(struct swap_info_struct *si)\nmm/swapfile.c-4139-{\n--\nmm/swapfile.c=4202=struct xswap_page_data {\n--\nmm/swapfile.c-4207-\nmm/swapfile.c:4208:static int xswap_collect_page(pte_t *pte, unsigned long addr, void *data)\nmm/swapfile.c-4209-{\n--\nmm/swapfile.c-4224- */\nmm/swapfile.c:4225:static void xswap_unmap_range(struct swap_info_struct *si,\nmm/swapfile.c-4226-\t\t\t      unsigned long vm_start, unsigned long vm_end,\n--\nmm/swapfile.c-4243-/* Caller must hold si-\u003exswap_lock.  Cannot fail. */\nmm/swapfile.c:4244:static void xswap_unmap_clusters_locked(struct swap_info_struct *si,\nmm/swapfile.c-4245-\t\t\t\t\tunsigned long start_idx, unsigned long nr)\n--\nmm/swapfile.c-4302-\nmm/swapfile.c:4303:static void xswap_unmap_clusters(struct swap_info_struct *si,\nmm/swapfile.c-4304-\t\t\t\t unsigned long start_idx, unsigned long nr)\n--\nmm/swapfile.c-4311-/* Track the end of the run of pages that is already mapped. */\nmm/swapfile.c:4312:static int xswap_mapped_end(pte_t *pte, unsigned long addr, void *data)\nmm/swapfile.c-4313-{\n--\nmm/swapfile.c-4330-\nmm/swapfile.c:4331:static void xswap_shrink_work_fn(struct work_struct *work)\nmm/swapfile.c-4332-{\n--\nmm/swapfile.c-4344- */\nmm/swapfile.c:4345:static void xswap_try_shrink(struct swap_info_struct *si)\nmm/swapfile.c-4346-{\n--\nmm/swapfile.c-4441-/* Not an interface: how far the mapped range has moved, for testing. */\nmm/swapfile.c:4442:static ssize_t xswap_debugfs_read(struct file *file, char __user *buf,\nmm/swapfile.c-4443-\t\t\t\t  size_t count, loff_t *ppos)\n--\nmm/swapfile.c=4483=static struct dentry *xswap_debugfs_root;\nmm/swapfile.c-4484-\nmm/swapfile.c:4485:static void xswap_debugfs_add(struct swap_info_struct *si)\nmm/swapfile.c-4486-{\n--\nmm/swapfile.c-4502-\nmm/swapfile.c:4503:static void xswap_debugfs_del(struct swap_info_struct *si)\nmm/swapfile.c-4504-{\n--\nmm/swapfile.c=4510=static int setup_swap_clusters_info(struct swap_info_struct *si,\n--\nmm/swapfile.c-4657-/* Create a file-less xswap device, sized at twice RAM. */\nmm/swapfile.c:4658:static int xswap_create(int prio)\nmm/swapfile.c-4659-{\n--\nmm/swapfile.c-4751-/* Tear down a file-less xswap device by its swap type. */\nmm/swapfile.c:4752:static int xswap_destroy(int type)\nmm/swapfile.c-4753-{\n"
}

13/2 2026/10/03 10:13 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 33194
							output: 39
							thoughts: 186
						

Thoughts:
Here's my analysis of the provided code elements, rendered as a first-person expert summary:

**Analyzing Swap Operations and Page I/O**

Okay, let's break this down. My initial scan of these function names – `xswap_create_store`, `xswap_destroy_store`, `xswap_create`, `xswap_destroy`, `xswap_map_clusters`, `xswap_grow`, `xswap_shrink_work_fn`, `xswap_try_shrink`, `xswap_unmap_clusters_locked`, `free_swap_cluster_info`, `swap_info_remove`, `__swapoff`, `swap_writeout`, and `swap_read_folio` – immediately tells me we're looking at the core of the Linux kernel's swap space management, from creation and destruction to the actual page I/O. The `xswap_` prefixed functions are likely related to an extended swap implementation or a specific feature or subsystem. I recognize the standard swap operations as well.

My immediate focus gravitates towards `swap_writeout` and `swap_read_folio`. These are the functions responsible for writing pages to and reading pages from the swap space, which is critical. I'm going to jump straight to their definitions within `mm/page_io.c` to confirm.

Ah, good. Just as expected, `swap_writeout` and `swap_read_folio` are *not* declared as static functions within `mm/page_io.c`. This is important because it means they're likely exposed as part of the kernel's swap interface, allowing other kernel components to directly interact with the swapping process. This is good to know, and I’ll want to review their usage carefully.



14/2 2026/10/03 10:13 tool grepper
0m Args:
{
  "Expression": "(swap_writeout|swap_read_folio)",
  "PathPrefix": "mm/page_io.c"
}

Results:
{
  "Output": "mm/page_io.c=183=static void swap_zeromap_folio_clear(struct folio *folio)\n--\nmm/page_io.c-203- */\nmm/page_io.c:204:int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)\nmm/page_io.c-205-{\n--\nmm/page_io.c-259-\nmm/page_io.c:260:\t__swap_writeout(ctx, folio);\nmm/page_io.c-261-\treturn 0;\n--\nmm/page_io.c=347=static void swap_add_folio(struct swap_io_ctx *ctx, struct folio *folio, int rw)\n--\nmm/page_io.c-384-\nmm/page_io.c:385:void __swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)\nmm/page_io.c-386-{\n--\nmm/page_io.c=412=static int swap_zeromap_batch(swp_entry_t entry, int max_nr,\n--\nmm/page_io.c-433-\nmm/page_io.c:434:static bool swap_read_folio_zeromap(struct folio *folio)\nmm/page_io.c-435-{\n--\nmm/page_io.c-466-\nmm/page_io.c:467:void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio)\nmm/page_io.c-468-{\n--\nmm/page_io.c-489-\nmm/page_io.c:490:\tif (swap_read_folio_zeromap(folio)) {\nmm/page_io.c-491-\t\tfolio_unlock(folio);\n"
}

15/2 2026/10/03 10:13 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 34281
							output: 293
							thoughts: 1336
						

Thoughts:
**Xswap/Zswap Analysis for Fuzzing Strategy**

Okay, let's break this down. My goal is to craft a solid fuzzing strategy for the xswap patch series. The primary focus is reachability, so let's start with how these functionalities are invoked and exposed.

First, I examine `swap_read_folio` and `swap_writeout`. These are key. `swap_read_folio` contains a critical path: if a page swapped to xswap isn't found in zswap for some reason (zswap writeback/eviction, or a race), we hit a `WARN_ON_ONCE`. This is immediately interesting for potential assertion failures. `swap_writeout` shows that xswap has no backing store, so it flags the page as dirty. These functions are likely reachable during page reclaim, which is critical for system stability. While not ubiquitous, they are definitely critical within the swap context and page management, especially in conjunction with the system's reaction to memory pressure.

Next, I delve into `zswap.c`. `zswap_writeback_entry` has a check for `SWP_XSWAP` which returns `-EINVAL`. This is interesting: we're intentionally not allowing xswap entries to be written back. `zswap_store_page` also prevents storing to the zswap LRU if xswap is set, confirming xswap has no backing store. Then, `zswap_store` is checked to see if it should queue a shrink work item. This shows the interplay between zswap and potential xswap pressure on system memory.

Now, let's explore the sysfs interaction. I see these sysfs entries: `xswap_create_store`, `xswap_destroy_store` for create and destroy, and `xswap_debugfs_read`. These give me a direct control plane to trigger various xswap operations. The other functions are core for cluster and swap management: `xswap_grow`, `xswap_map_clusters`, `xswap_try_shrink`, `xswap_shrink_work_fn`, `xswap_unmap_clusters_locked`, and `__swapoff`. I can use the sysfs to manipulate the xswap state and test the management operations.

I've identified the "FocusSymbols": the xswap specific functions listed above, along with `swap_writeout`, `swap_read_folio` and `zswap_writeback_entry`. These are the targets. I'm intentionally *not* focusing on ubiquitous symbols like `kmalloc` or generic fault handlers.

Finally, I check the `EnableConfigs`. The patch depends on `XSWAP`, `ZSWAP`, and `ZSWAP_DEFAULT_ON`. `XSWAP` itself relies on `SWAP && 64BIT && ZSWAP && SYSFS`, which means I need to make sure my fuzzing environment has these configurations.

All the requirements for a good fuzzing strategy are satisfied. The target code is reachable through sysfs manipulation, swap management and memory reclaim. There are runtime assertions and defensive checks (like the `WARN_ON_ONCE` in `swap_read_folio`) and the FocusSymbols are specific and non-ubiquitous. The EnableConfigs are also identified. I have a solid understanding of this patch series now. Time to start the fuzzing!



16/2 2026/10/03 10:13 tool set-results
0m Args:
{
  "EnableConfigs": [
    "XSWAP",
    "ZSWAP",
    "ZSWAP_DEFAULT_ON"
  ],
  "FocusSymbols": [
    "xswap_create_store",
    "xswap_destroy_store",
    "xswap_create",
    "xswap_destroy",
    "xswap_map_clusters",
    "xswap_grow",
    "xswap_try_shrink",
    "xswap_shrink_work_fn",
    "xswap_unmap_clusters_locked",
    "swap_read_folio",
    "swap_writeout",
    "zswap_writeback_entry"
  ],
  "Reasoning": "The patch series introduces 'xswap' (extendable virtual swap device), modifying core memory management (mm/swapfile.c, mm/page_io.c, mm/swap_state.c, mm/zswap.c). It adds sysfs attributes (/sys/kernel/mm/xswap/create and destroy) to dynamically create and destroy virtual swap devices backed by zswap and a sparse vmalloc area, complete with dynamic mapping/unmapping, deferred shrinking work, synchronization via RCU and mutexes, and newly added WARN_ON_ONCE assertions. This code is fully reachable in virtualized QEMU environments and warrants fuzzing.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "XSWAP",
    "ZSWAP",
    "ZSWAP_DEFAULT_ON"
  ],
  "FocusSymbols": [
    "xswap_create_store",
    "xswap_destroy_store",
    "xswap_create",
    "xswap_destroy",
    "xswap_map_clusters",
    "xswap_grow",
    "xswap_try_shrink",
    "xswap_shrink_work_fn",
    "xswap_unmap_clusters_locked",
    "swap_read_folio",
    "swap_writeout",
    "zswap_writeback_entry"
  ],
  "Reasoning": "The patch series introduces 'xswap' (extendable virtual swap device), modifying core memory management (mm/swapfile.c, mm/page_io.c, mm/swap_state.c, mm/zswap.c). It adds sysfs attributes (/sys/kernel/mm/xswap/create and destroy) to dynamically create and destroy virtual swap devices backed by zswap and a sparse vmalloc area, complete with dynamic mapping/unmapping, deferred shrinking work, synchronization via RCU and mutexes, and newly added WARN_ON_ONCE assertions. This code is fully reachable in virtualized QEMU environments and warrants fuzzing.",
  "WorthFuzzing": true
}

17/1 2026/10/03 10:13 action If
1m Args:
{
  "WorthFuzzing": true
}

Results:
null

18/2 2026/10/03 10:13 agent kmsan-evaluator
1m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch introduces CONFIG_XSWAP, an extendable virtual swap device that relies on zswap without physical backing storage, dynamically mapping and unmapping cluster_info metadata via a sparse vmalloc area (VM_SPARSE).\n\n1. Memory Initialization:\n- All pages backing the cluster_info array are explicitly allocated using `alloc_page(... | __GFP_ZERO)`, ensuring all `struct swap_cluster_info` structures start fully zeroed before use. All spinlocks within these structures are initialized using `spin_lock_init()`.\n- The `swap_info_struct` is zero-allocated via `kvzalloc_obj()` in `alloc_swap_info()`, and all newly added fields under CONFIG_XSWAP (`cluster_vm`, `nr_clusters_max`, `nr_clusters_mapped`, `xswap_lock`, `xswap_shrink_work`, `xswap_grows`, `xswap_shrinks`) are explicitly initialized upon device creation.\n\n2. User-Space Exposure / Info-Leaks:\n- The sysfs interfaces (`create` and `destroy`) are write-only handlers that parse scalar input via `kstrtoint` and `kstrtoul`.\n- Procfs (`/proc/swaps`) and debugfs (`/sys/kernel/debug/xswap/type*`) read handlers format their output into stack buffers using `scnprintf()` and copy only the formatted length via `seq_puts()` or `simple_read_from_buffer()`. No kernel structures or uninitialized buffer paddings are copied to user space.\n\n3. KASAN vs KMSAN Applicability:\n- Any risks introduced by this change relate to VM_SPARSE page mapping/unmapping concurrency, RCU synchronization, locking between grow/shrink/swapoff, or invalid address dereferences if an unmapped cluster is accessed. These are detected by KASAN, LOCKDEP, or the kernel's fault handler.\n- There are no uninitialized stack/heap reads, uninitialized memory branch conditions, or info-leak risks that would specifically necessitate a dedicated KMSAN session.",
  "NeedsKMSAN": false
}

Instruction:
You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.

CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
  a comprehensive suite of debugging tools and sanitizers, including KASAN
  (out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
  (locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
  or page allocations) and kernel-to-user memory info-leaks.

Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.

Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.

Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
   attributes, ioctl output arguments, socket options, or BPF buffers) where fields
   or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
   or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
   could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
   uninitialized bytes of existing buffers.

Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
  dereferences, locking deadlocks, or use-after-free bugs (these are already caught
  by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
  or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.

Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit 640f9f65f614b8fb4b5c591ccbebc221bf9640d3
Author: syz-cluster <triage@syzkaller.com>
Date:   Sat Oct 3 10:12:35 2026 +0000

    syz-cluster: applied patch under review

diff --git a/include/linux/swap.h b/include/linux/swap.h
index 4f686709d71f0..ae2e49386443c 100644
--- a/include/linux/swap.h
+++ b/include/linux/swap.h
@@ -201,6 +201,7 @@ enum {
 	SWP_STABLE_WRITES = (1 << 11),	/* no overwrite PG_writeback pages */
 	SWP_SYNCHRONOUS_IO = (1 << 12),	/* synchronous IO is efficient */
 	SWP_HIBERNATION = (1 << 13),	/* pinned for hibernation */
+	SWP_XSWAP	= (1 << 14),	/* extendable swap device */
 					/* add others here before... */
 };
 
@@ -239,15 +240,25 @@ struct swap_info_struct {
 	signed short	prio;		/* swap priority of this type */
 	struct plist_node list;		/* entry in swap_active_head */
 	signed char	type;		/* strange name for an index */
-	unsigned int	max;		/* size of this swap device */
+	unsigned long	max;		/* size of this swap device */
 	struct swap_cluster_info *cluster_info; /* array, one entry per cluster */
+#ifdef CONFIG_XSWAP
+	struct vm_struct	*cluster_vm;	/* VM_SPARSE area for cluster_info */
+	unsigned long		nr_clusters_max;/* total clusters in the xswap address space */
+	unsigned long		nr_clusters_mapped; /* currently mapped cluster count */
+	struct work_struct	xswap_shrink_work; /* deferred shrink trigger */
+	struct mutex		xswap_lock;	/* serialize map/unmap operations */
+	struct dentry		*xswap_debugfs;	/* mapped range and counters */
+	atomic_long_t		xswap_grows;	/* grow operations so far */
+	atomic_long_t		xswap_shrinks;	/* shrink operations so far */
+#endif
 	struct list_head free_clusters; /* free clusters list */
 	struct list_head full_clusters; /* full clusters list */
 	struct list_head nonfull_clusters[SWAP_NR_ORDERS];
 					/* list of cluster that contains at least one free slot */
 	struct list_head frag_clusters[SWAP_NR_ORDERS];
 					/* list of cluster that are fragmented or contented */
-	unsigned int pages;		/* total of usable pages of swap */
+	unsigned long pages;		/* total of usable pages of swap */
 	atomic_long_t inuse_pages;	/* number of those currently in use */
 	struct swap_sequential_cluster *global_cluster; /* Use one global cluster for rotating device */
 	spinlock_t global_cluster_lock;	/* Serialize usage of global cluster */
@@ -378,6 +389,7 @@ void free_folio_and_swap_cache(struct folio *folio);
 void free_pages_and_swap_cache(struct encoded_page **, int);
 /* linux/mm/swapfile.c */
 extern atomic_long_t nr_swap_pages;
+extern atomic_t nr_real_swapfiles;
 extern long total_swap_pages;
 extern atomic_t nr_rotate_swap;
 
diff --git a/mm/Kconfig b/mm/Kconfig
index acefc994d9a8b..39927b5c75aca 100644
--- a/mm/Kconfig
+++ b/mm/Kconfig
@@ -122,6 +122,15 @@ config ZSWAP_COMPRESSOR_DEFAULT
        default "zstd" if ZSWAP_COMPRESSOR_DEFAULT_ZSTD
        default ""
 
+config XSWAP
+	bool "Extendable (virtual) swap device"
+	depends on SWAP && 64BIT && ZSWAP && SYSFS
+	help
+	  Adds support for extendable swap devices (xswap) that decouple
+	  PTE swap entries from physical backing storage. The cluster_info
+	  array is backed by a sparse vmalloc area that grows and shrinks
+	  on demand, avoiding static pre-allocation overhead.
+
 config ZSMALLOC
 	tristate
 
diff --git a/mm/page_io.c b/mm/page_io.c
index c6824fcd483e0..25fa9b82ed46b 100644
--- a/mm/page_io.c
+++ b/mm/page_io.c
@@ -248,6 +248,15 @@ int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 	}
 	rcu_read_unlock();
 
+	/*
+	 * xswap has no backing store: keep the folio.  ctx->sis is not set
+	 * yet, so look the device up from the entry.
+	 */
+	if (unlikely(__swap_entry_to_info(folio->swap)->flags & SWP_XSWAP)) {
+		folio_mark_dirty(folio);
+		return AOP_WRITEPAGE_ACTIVATE;
+	}
+
 	__swap_writeout(ctx, folio);
 	return 0;
 out_unlock:
@@ -486,6 +495,16 @@ void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio)
 	if (zswap_load(folio) != -ENOENT)
 		goto finish;
 
+	if (unlikely(sis->flags & SWP_XSWAP)) {
+		/*
+		 * An xswap entry only ever lives in zswap, so zswap_load()
+		 * must have found it.  Unlock and let the caller retry.
+		 */
+		WARN_ON_ONCE(1);
+		folio_unlock(folio);
+		goto finish;
+	}
+
 	/* We have to read from slower devices. Increase zswap protection. */
 	zswap_folio_swapin(folio);
 	swap_add_folio(ctx, folio, READ);
diff --git a/mm/swap_state.c b/mm/swap_state.c
index ebef568cd62ee..3a4e9e447b0b2 100644
--- a/mm/swap_state.c
+++ b/mm/swap_state.c
@@ -884,6 +884,10 @@ struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask,
 	struct blk_plug plug;
 	swp_entry_t ra_entry;
 
+	/* xswap entries live only in zswap; readahead does not help. */
+	if (si->flags & SWP_XSWAP)
+		goto skip;
+
 	mask = swapin_nr_pages(offset) - 1;
 	if (!mask)
 		goto skip;
@@ -969,6 +973,7 @@ static int swap_vma_ra_win(struct vm_fault *vmf, unsigned long *start,
 static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,
 		struct mempolicy *mpol, pgoff_t targ_ilx, struct vm_fault *vmf)
 {
+	struct swap_info_struct *si = __swap_entry_to_info(targ_entry);
 	struct swap_io_ctx ctx = {};
 	struct blk_plug plug;
 	struct folio *folio;
@@ -977,6 +982,10 @@ static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,
 	unsigned long start, end, addr;
 	pgoff_t ilx = targ_ilx;
 
+	/* xswap entries live only in zswap; readahead does not help. */
+	if (si->flags & SWP_XSWAP)
+		goto skip;
+
 	win = swap_vma_ra_win(vmf, &start, &end);
 	if (win == 1)
 		goto skip;
diff --git a/mm/swapfile.c b/mm/swapfile.c
index c3288910b3e35..bf95663c2593a 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -16,6 +16,8 @@
 #include <linux/kernel_stat.h>
 #include <linux/swap.h>
 #include <linux/vmalloc.h>
+#include <linux/kobject.h>
+#include <linux/sysfs.h>
 #include <linux/pagemap.h>
 #include <linux/namei.h>
 #include <linux/shmem_fs.h>
@@ -47,7 +49,202 @@
 #include <linux/leafops.h>
 #include "swap_table.h"
 #include "internal.h"
+#include <linux/debugfs.h>
+
 #include "swap.h"
+#define DEF_SWAP_PRIO  -1
+
+/*
+ * Above every real swap device: one ahead of xswap would take the page
+ * directly, and taking that slot is what xswap exists to avoid.
+ */
+#define DEF_XSWAP_PRIO	SWAP_FLAG_PRIO_MASK
+
+#ifdef CONFIG_XSWAP
+/*
+ * xswap: dynamically grow and shrink the cluster_info array via a
+ * VM_SPARSE area.
+ *
+ * XSWAP_GROW_CLUSTERS is the number of clusters to map/unmap in one
+ * grow/shrink operation: the number of cluster_info structs that fit in
+ * a single page (at least 16), so that the vmalloc page table overhead
+ * is proportional to the number of clusters mapped.
+ */
+#define XSWAP_GROW_CLUSTERS \
+	max_t(unsigned long, PAGE_SIZE / sizeof(struct swap_cluster_info), 16)
+
+/*
+ * Grow and shrink thresholds, as a percentage of the mapped range in use.
+ * Each one lands inside (SHRINK_WHEN, GROW_WHEN), so neither can leave the
+ * range in a state that wakes the other up.
+ */
+#define XSWAP_SHRINK_WHEN	50
+#define XSWAP_SHRINK_UNTIL	70
+#define XSWAP_GROW_UNTIL	65
+#define XSWAP_GROW_WHEN		85
+#define XSWAP_GROW_CHUNKS	4
+
+static bool xswap_should_grow(struct swap_info_struct *si);
+static unsigned long xswap_grow(struct swap_info_struct *si);
+static void xswap_debugfs_del(struct swap_info_struct *si);
+
+/* Batch size for the fallback unmap; keeps the stack array small. */
+#define XSWAP_UNMAP_BATCH_PAGES		16
+#define XSWAP_UNMAP_BATCH_CLUSTERS					\
+	max_t(unsigned long,						\
+	      ((XSWAP_UNMAP_BATCH_PAGES * PAGE_SIZE) /		\
+	       sizeof(struct swap_cluster_info)), 16)
+
+static int xswap_map_clusters(struct swap_info_struct *si,
+			      unsigned long start_idx, unsigned long nr);
+static void xswap_unmap_clusters(struct swap_info_struct *si,
+				 unsigned long start_idx, unsigned long nr);
+static int xswap_mapped_end(pte_t *pte, unsigned long addr, void *data);
+static void xswap_try_shrink(struct swap_info_struct *si);
+
+static int xswap_create(int prio);
+static int xswap_destroy(int type);
+
+static ssize_t xswap_create_store(struct kobject *kobj,
+				  struct kobj_attribute *attr,
+				  const char *buf, size_t count)
+{
+	int prio = DEF_XSWAP_PRIO;
+	int err;
+
+	if (!capable(CAP_SYS_ADMIN))
+		return -EPERM;
+
+	/* "[<prio>]" is optional; a lower one is allowed, not a higher. */
+	if (*skip_spaces(buf)) {
+		err = kstrtoint(buf, 10, &prio);
+		if (err)
+			return err;
+	}
+
+	err = xswap_create(prio);
+	if (err < 0)
+		return err;
+
+	return count;
+}
+
+static struct kobj_attribute xswap_create_attr = __ATTR(create, 0200, NULL,
+							xswap_create_store);
+
+static ssize_t xswap_destroy_store(struct kobject *kobj,
+				   struct kobj_attribute *attr,
+				   const char *buf, size_t count)
+{
+	unsigned long type;
+	int err;
+
+	if (!capable(CAP_SYS_ADMIN))
+		return -EPERM;
+
+	err = kstrtoul(buf, 0, &type);
+	if (err)
+		return err;
+	if (type >= MAX_SWAPFILES)
+		return -EINVAL;
+
+	err = xswap_destroy(type);
+	if (err)
+		return err;
+
+	return count;
+}
+
+static struct kobj_attribute xswap_destroy_attr = __ATTR(destroy, 0200, NULL,
+							 xswap_destroy_store);
+
+static struct attribute *xswap_attrs[] = {
+	&xswap_create_attr.attr,
+	&xswap_destroy_attr.attr,
+	NULL,
+};
+
+/* Size of a new device, from xswap.max=.  A percentage unless bytes is set. */
+static unsigned int xswap_size_pct = 200;
+static unsigned long xswap_size_bytes;
+
+static int __init xswap_max_setup(char *str)
+{
+	unsigned int pct;
+	char *end;
+
+	end = strchr(str, '%');
+	if (end) {
+		if (end[1]) {
+			pr_err("xswap: bad xswap.max=%s\n", str);
+			return 1;
+		}
+		*end = '\0';	/* writable copy, see parse_args() */
+		if (kstrtouint(str, 0, &pct) || !pct) {
+			pr_err("xswap: bad xswap.max=%s%%\n", str);
+			return 1;
+		}
+		xswap_size_pct = pct;
+		xswap_size_bytes = 0;
+		return 1;
+	}
+
+	xswap_size_bytes = memparse(str, &end);
+	if (*end || xswap_size_bytes < PAGE_SIZE) {
+		pr_err("xswap: bad xswap.max=%s\n", str);
+		xswap_size_bytes = 0;
+		return 1;
+	}
+	xswap_size_pct = 0;
+	return 1;
+}
+__setup("xswap.max=", xswap_max_setup);
+
+/* The most a device can address, whatever xswap.max= asked for. */
+static unsigned long xswap_size_limit(void)
+{
+	unsigned long limit = swapfile_maximum_size;
+
+	/* A cluster index is an unsigned int. */
+	if (limit / SWAPFILE_CLUSTER > UINT_MAX)
+		limit = (unsigned long)UINT_MAX * SWAPFILE_CLUSTER;
+
+	return limit;
+}
+
+static unsigned long xswap_size_pages(void)
+{
+	if (xswap_size_bytes)
+		return xswap_size_bytes >> PAGE_SHIFT;
+
+	return div_u64((unsigned long long)totalram_pages() * xswap_size_pct,
+		       100);
+}
+
+static const struct attribute_group xswap_attr_group = {
+	.attrs = xswap_attrs,
+};
+
+static struct kobject *xswap_kobj;
+
+static void xswap_sysfs_init(void)
+{
+	xswap_kobj = kobject_create_and_add("xswap", mm_kobj);
+	if (!xswap_kobj) {
+		pr_err("xswap: failed to create sysfs kobject\n");
+		return;
+	}
+	if (sysfs_create_group(xswap_kobj, &xswap_attr_group)) {
+		pr_err("xswap: failed to create sysfs group\n");
+		kobject_put(xswap_kobj);
+		xswap_kobj = NULL;
+	}
+}
+#else /* !CONFIG_XSWAP */
+static inline void xswap_sysfs_init(void)
+{
+}
+#endif /* CONFIG_XSWAP */
 
 static void swap_range_alloc(struct swap_info_struct *si,
 			     unsigned int nr_entries);
@@ -66,6 +263,9 @@ static void move_cluster(struct swap_info_struct *si,
 static DEFINE_SPINLOCK(swap_lock);
 static unsigned int nr_swapfiles;
 atomic_long_t nr_swap_pages;
+atomic_t nr_real_swapfiles;
+/* Active xswap devices, as in nr_real_swapfiles. */
+static atomic_t nr_xswap_files;
 /*
  * Some modules use swappable objects and may try to swap them out under
  * memory pressure (via the shrinker). Before doing so, they may wish to
@@ -74,7 +274,6 @@ atomic_long_t nr_swap_pages;
 EXPORT_SYMBOL_GPL(nr_swap_pages);
 /* protected with swap_lock. reading in vm_swap_full() doesn't need lock */
 long total_swap_pages;
-#define DEF_SWAP_PRIO  -1
 unsigned long swapfile_maximum_size;
 #ifdef CONFIG_MIGRATION
 bool swap_migration_ad_supported;
@@ -402,10 +601,10 @@ static inline unsigned int cluster_index(struct swap_info_struct *si,
 	return ci - si->cluster_info;
 }
 
-static inline unsigned int cluster_offset(struct swap_info_struct *si,
-					  struct swap_cluster_info *ci)
+static inline unsigned long cluster_offset(struct swap_info_struct *si,
+					   struct swap_cluster_info *ci)
 {
-	return cluster_index(si, ci) * SWAPFILE_CLUSTER;
+	return (unsigned long)cluster_index(si, ci) * SWAPFILE_CLUSTER;
 }
 
 static void swap_cluster_free_table_folio_rcu_cb(struct rcu_head *head)
@@ -617,6 +816,11 @@ static void __free_cluster(struct swap_info_struct *si, struct swap_cluster_info
 	swap_cluster_free_table(ci);
 	move_cluster(si, ci, &si->free_clusters, CLUSTER_FLAG_FREE);
 	ci->order = 0;
+#ifdef CONFIG_XSWAP
+	/* Only xswap devices, and not while the device is being torn down. */
+	if ((si->flags & SWP_XSWAP) && (si->flags & SWP_WRITEOK))
+		schedule_work(&si->xswap_shrink_work);
+#endif
 }
 
 /*
@@ -733,7 +937,8 @@ static void free_cluster(struct swap_info_struct *si, struct swap_cluster_info *
 	/*
 	 * If the swap is discardable, prepare discard the cluster
 	 * instead of free it immediately. The cluster will be freed
-	 * after discard.
+	 * after discard.  xswap has no bdev and never sets
+	 * SWP_PAGE_DISCARD, so it always takes the free path below.
 	 */
 	if ((si->flags & (SWP_WRITEOK | SWP_PAGE_DISCARD)) ==
 	    (SWP_WRITEOK | SWP_PAGE_DISCARD)) {
@@ -803,7 +1008,7 @@ static int swap_cluster_setup_bad_slot(struct swap_info_struct *si,
 
 	/* si->max may got shrunk by swap swap_activate() */
 	if (offset >= si->max && !mask) {
-		pr_debug("Ignoring bad slot %u (max: %u)\n", offset, si->max);
+		pr_debug("Ignoring bad slot %u (max: %lu)\n", offset, si->max);
 		return 0;
 	}
 	/*
@@ -969,11 +1174,12 @@ static bool __swap_cluster_alloc_entries(struct swap_info_struct *si,
 }
 
 /* Try use a new cluster for current CPU and allocate from it. */
-static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,
-					    struct swap_cluster_info *ci,
-					    struct folio *folio, unsigned long offset)
+static unsigned long alloc_swap_scan_cluster(struct swap_info_struct *si,
+					     struct swap_cluster_info *ci,
+					     struct folio *folio,
+					     unsigned long offset)
 {
-	unsigned int next = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID;
+	unsigned long next = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID;
 	unsigned long start = ALIGN_DOWN(offset, SWAPFILE_CLUSTER);
 	unsigned int order = likely(folio) ? folio_order(folio) : 0;
 	unsigned long end = start + SWAPFILE_CLUSTER;
@@ -983,6 +1189,9 @@ static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,
 	lockdep_assert_held(&ci->lock);
 	VM_WARN_ON(!cluster_is_usable(ci, order));
 
+	/* ci is used without ci->lock; an xswap unmap waits for this. */
+	rcu_read_lock();
+
 	if (end < nr_pages || ci->count + nr_pages > SWAPFILE_CLUSTER)
 		goto out;
 
@@ -1011,6 +1220,7 @@ static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,
 out:
 	relocate_cluster(si, ci);
 	swap_cluster_unlock(ci);
+	rcu_read_unlock();
 	if (si->flags & SWP_SOLIDSTATE) {
 		this_cpu_write(percpu_swap_cluster.offset[order], next);
 		this_cpu_write(percpu_swap_cluster.si[order], si);
@@ -1020,12 +1230,12 @@ static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si,
 	return found;
 }
 
-static unsigned int alloc_swap_scan_list(struct swap_info_struct *si,
-					 struct list_head *list,
-					 struct folio *folio,
-					 bool scan_all)
+static unsigned long alloc_swap_scan_list(struct swap_info_struct *si,
+					  struct list_head *list,
+					  struct folio *folio,
+					  bool scan_all)
 {
-	unsigned int found = SWAP_ENTRY_INVALID;
+	unsigned long found = SWAP_ENTRY_INVALID;
 
 	do {
 		struct swap_cluster_info *ci = isolate_lock_cluster(si, list);
@@ -1054,6 +1264,9 @@ static void swap_reclaim_full_clusters(struct swap_info_struct *si, bool force)
 		to_scan = swap_usage_in_pages(si) / SWAPFILE_CLUSTER;
 
 	while ((ci = isolate_lock_cluster(si, &si->full_clusters))) {
+		/* As in alloc_swap_scan_cluster(). */
+		rcu_read_lock();
+
 		offset = cluster_offset(si, ci);
 		end = min(si->max, offset + SWAPFILE_CLUSTER);
 		to_scan--;
@@ -1078,6 +1291,7 @@ static void swap_reclaim_full_clusters(struct swap_info_struct *si, bool force)
 			relocate_cluster(si, ci);
 
 		swap_cluster_unlock(ci);
+		rcu_read_unlock();
 		if (to_scan <= 0)
 			break;
 
@@ -1108,7 +1322,7 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 {
 	struct swap_cluster_info *ci;
 	unsigned int order = likely(folio) ? folio_order(folio) : 0;
-	unsigned int offset = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID;
+	unsigned long offset = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID;
 
 	/*
 	 * Swapfile is not block device so unable
@@ -1117,6 +1331,17 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 	if (order && !(si->flags & SWP_BLKDEV))
 		return 0;
 
+#ifdef CONFIG_XSWAP
+	/*
+	 * Top the range up early.  Every path below leaves through `done`,
+	 * so this has to come first; mapping pages can sleep, and doing it
+	 * from the allocation that would otherwise fail leaves nothing to
+	 * fall back on.
+	 */
+	if ((si->flags & SWP_XSWAP) && xswap_should_grow(si))
+		xswap_grow(si);
+#endif
+
 	if (!(si->flags & SWP_SOLIDSTATE)) {
 		/* Serialize HDD SWAP allocation for each device. */
 		spin_lock(&si->global_cluster_lock);
@@ -1193,6 +1418,12 @@ static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si,
 		if (found)
 			goto done;
 	}
+
+#ifdef CONFIG_XSWAP
+	/* A concurrent free or grow may have added clusters; retry once. */
+	if (!found && (si->flags & SWP_XSWAP))
+		found = alloc_swap_scan_list(si, &si->free_clusters, folio, false);
+#endif
 done:
 	if (!(si->flags & SWP_SOLIDSTATE))
 		spin_unlock(&si->global_cluster_lock);
@@ -1216,6 +1447,11 @@ static void del_from_avail_list(struct swap_info_struct *si, bool swapoff)
 		 */
 		lockdep_assert_held(&si->lock);
 		si->flags &= ~SWP_WRITEOK;
+		/* Count active devices, not merely those on the avail list. */
+		if (si->flags & SWP_XSWAP)
+			atomic_sub(1, &nr_xswap_files);
+		else
+			atomic_sub(1, &nr_real_swapfiles);
 		atomic_long_or(SWAP_USAGE_OFFLIST_BIT, &si->inuse_pages);
 	} else {
 		/*
@@ -1273,6 +1509,12 @@ static void add_to_avail_list(struct swap_info_struct *si, bool swapon)
 	}
 
 	plist_add(&si->avail_list, &swap_avail_head);
+	if (swapon) {
+		if (si->flags & SWP_XSWAP)
+			atomic_add(1, &nr_xswap_files);
+		else
+			atomic_add(1, &nr_real_swapfiles);
+	}
 
 skip:
 	spin_unlock(&swap_avail_lock);
@@ -1370,21 +1612,32 @@ static bool get_swap_device_info(struct swap_info_struct *si)
  * Fast path try to get swap entries with specified order from current
  * CPU's swap entry pool (a cluster).
  */
-static bool swap_alloc_fast(struct folio *folio)
+static bool swap_alloc_fast(struct folio *folio, bool may_zswap)
 {
 	unsigned int order = folio_order(folio);
 	struct swap_cluster_info *ci;
 	struct swap_info_struct *si;
-	unsigned int offset;
+	unsigned long offset;
 
 	/*
 	 * Once allocated, swap_info_struct will never be completely freed,
 	 * so checking it's liveness by get_swap_device_info is enough.
+	 *
+	 * The cached offset indexes si->cluster_info, which xswap can
+	 * unmap; cover both the read and the use with RCU.
 	 */
+	rcu_read_lock();
 	si = this_cpu_read(percpu_swap_cluster.si[order]);
 	offset = this_cpu_read(percpu_swap_cluster.offset[order]);
-	if (!si || !offset || !get_swap_device_info(si))
+	if (!si || !offset || !get_swap_device_info(si)) {
+		rcu_read_unlock();
+		return false;
+	}
+	if (!may_zswap && (si->flags & SWP_XSWAP)) {
+		put_swap_device(si);
+		rcu_read_unlock();
 		return false;
+	}
 
 	ci = swap_cluster_lock(si, offset);
 	if (cluster_is_usable(ci, order)) {
@@ -1396,17 +1649,24 @@ static bool swap_alloc_fast(struct folio *folio)
 	}
 
 	put_swap_device(si);
+	rcu_read_unlock();
 	return folio_test_swapcache(folio);
 }
 
 /* Rotate the device and switch to a new cluster */
-static void swap_alloc_slow(struct folio *folio)
+static void swap_alloc_slow(struct folio *folio, bool may_zswap)
 {
 	struct swap_info_struct *si, *next;
 
 	spin_lock(&swap_avail_lock);
 start_over:
 	plist_for_each_entry_safe(si, next, &swap_avail_head, avail_list) {
+		/*
+		 * Do not rotate a skipped device: the walk follows the
+		 * rotation and would spin forever.
+		 */
+		if (!may_zswap && (si->flags & SWP_XSWAP))
+			continue;
 		/* Rotate the device and switch to a new cluster */
 		plist_requeue(&si->avail_list, &swap_avail_head);
 		spin_unlock(&swap_avail_lock);
@@ -1745,10 +2005,24 @@ int folio_alloc_swap(struct folio *folio)
 {
 	unsigned int order = folio_order(folio);
 	unsigned int size = 1 << order;
+	struct obj_cgroup *objcg;
+	/* True unless the gate below finds an xswap device to route away from. */
+	bool may_zswap = true;
 
 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
 	VM_BUG_ON_FOLIO(!folio_test_uptodate(folio), folio);
 
+	/*
+	 * A folio that zswap will not take must not get an xswap slot. With
+	 * no xswap device to route away from, skip the lookup.
+	 */
+	if (atomic_read(&nr_xswap_files)) {
+		objcg = get_obj_cgroup_from_folio(folio);
+		may_zswap = !objcg || obj_cgroup_may_zswap(objcg);
+		if (objcg)
+			obj_cgroup_put(objcg);
+	}
+
 	if (order) {
 		/*
 		 * Reject large allocation when THP_SWAP is disabled. Check below
@@ -1769,8 +2043,8 @@ int folio_alloc_swap(struct folio *folio)
 
 again:
 	local_lock(&percpu_swap_cluster.lock);
-	if (!swap_alloc_fast(folio))
-		swap_alloc_slow(folio);
+	if (!swap_alloc_fast(folio, may_zswap))
+		swap_alloc_slow(folio, may_zswap);
 	local_unlock(&percpu_swap_cluster.lock);
 
 	if (!order && unlikely(!folio_test_swapcache(folio))) {
@@ -2186,8 +2460,11 @@ swp_entry_t swap_alloc_hibernation_slot(int type)
 	/*
 	 * Try the local cluster first if it matches the device. If
 	 * not, try grab a new cluster and override local cluster.
+	 *
+	 * Same RCU requirement as swap_alloc_fast().
 	 */
 	local_lock(&percpu_swap_cluster.lock);
+	rcu_read_lock();
 	pcp_si = this_cpu_read(percpu_swap_cluster.si[0]);
 	pcp_offset = this_cpu_read(percpu_swap_cluster.offset[0]);
 	if (pcp_si == si && pcp_offset) {
@@ -2197,6 +2474,7 @@ swp_entry_t swap_alloc_hibernation_slot(int type)
 		else
 			swap_cluster_unlock(ci);
 	}
+	rcu_read_unlock();
 	if (!offset)
 		offset = cluster_alloc_swap_entry(si, NULL);
 	local_unlock(&percpu_swap_cluster.lock);
@@ -2249,6 +2527,9 @@ static int __find_hibernation_swap_type(dev_t device, sector_t offset)
 
 		if (!(sis->flags & SWP_WRITEOK))
 			continue;
+		/* xswap has no bdev to match a resume device */
+		if (sis->flags & SWP_XSWAP)
+			continue;
 
 		if (device == sis->bdev->bd_dev) {
 			struct swap_extent *se = first_se(sis);
@@ -2436,6 +2717,8 @@ int find_first_swap(dev_t *device)
 
 		if (!(sis->flags & SWP_WRITEOK))
 			continue;
+		if (sis->flags & SWP_XSWAP)
+			continue;
 		*device = sis->bdev->bd_dev;
 		spin_unlock(&swap_lock);
 		return type;
@@ -2788,14 +3071,31 @@ static int unuse_mm(struct mm_struct *mm, unsigned int type)
  * Return 0 if there are no inuse entries after prev till end of
  * the map.
  */
-static unsigned int find_next_to_unuse(struct swap_info_struct *si,
-					unsigned int prev)
+static unsigned long find_next_to_unuse(struct swap_info_struct *si,
+					unsigned long prev)
 {
 	struct swap_cluster_info *ci;
-	unsigned long i, end;
+	unsigned long i, cluster_end, end;
 	unsigned int ci_off;
 	unsigned long swp_tb;
 
+	end = si->max;
+#ifdef CONFIG_XSWAP
+	/*
+	 * An xswap device maps its cluster_info in chunks as it grows, so
+	 * the tail past nr_clusters_mapped has nothing behind it.
+	 */
+	if (si->flags & SWP_XSWAP) {
+		unsigned long mapped_end;
+
+		/* Pairs with the smp_store_release() in xswap_map_clusters(). */
+		mapped_end = smp_load_acquire(&si->nr_clusters_mapped) *
+			     SWAPFILE_CLUSTER;
+		if (mapped_end < end)
+			end = mapped_end;
+	}
+#endif
+
 	/*
 	 * No need for swap_lock here: we're just looking
 	 * for whether an entry is in use, not modifying it; false
@@ -2803,11 +3103,11 @@ static unsigned int find_next_to_unuse(struct swap_info_struct *si,
 	 * allocations from this area (while holding swap_lock).
 	 */
 	i = prev + 1;
-	while (i < si->max) {
+	while (i < end) {
 		ci = __swap_offset_to_cluster(si, i);
-		end = min_t(unsigned long,
-			    ALIGN_DOWN(i, SWAPFILE_CLUSTER) + SWAPFILE_CLUSTER,
-			    si->max);
+		cluster_end = min_t(unsigned long,
+				    ALIGN_DOWN(i, SWAPFILE_CLUSTER) + SWAPFILE_CLUSTER,
+				    end);
 
 		/*
 		 * An empty cluster has no slot in use, so skip it whole.
@@ -2817,13 +3117,13 @@ static unsigned int find_next_to_unuse(struct swap_info_struct *si,
 		 * enough, unlike in every other cluster_is_empty() caller.
 		 */
 		if (!READ_ONCE(ci->count)) {
-			i = end;
+			i = cluster_end;
 			cond_resched();
 			continue;
 		}
 
 		ci_off = i % SWAPFILE_CLUSTER;
-		for (; i < end; ci_off++, i++) {
+		for (; i < cluster_end; ci_off++, i++) {
 			swp_tb = swap_table_get(ci, ci_off);
 			if (!swp_tb_is_null(swp_tb) && !swp_tb_is_bad(swp_tb))
 				return i;
@@ -2833,7 +3133,6 @@ static unsigned int find_next_to_unuse(struct swap_info_struct *si,
 
 	return 0;
 }
-
 static int try_to_unuse(unsigned int type)
 {
 	struct mm_struct *prev_mm;
@@ -2843,7 +3142,7 @@ static int try_to_unuse(unsigned int type)
 	struct swap_info_struct *si = swap_info[type];
 	struct folio *folio;
 	swp_entry_t entry;
-	unsigned int i;
+	unsigned long i;
 
 	if (!swap_usage_in_pages(si))
 		goto success;
@@ -3131,20 +3430,62 @@ static void wait_for_allocation(struct swap_info_struct *si)
 
 	BUG_ON(si->flags & SWP_WRITEOK);
 
+#ifdef CONFIG_XSWAP
+	if (si->flags & SWP_XSWAP) {
+		/* Pairs with the smp_store_release() in xswap_map_clusters(). */
+		end = min(end, smp_load_acquire(&si->nr_clusters_mapped) *
+			  SWAPFILE_CLUSTER);
+	}
+#endif
+
 	for (offset = 0; offset < end; offset += SWAPFILE_CLUSTER) {
 		ci = swap_cluster_lock(si, offset);
 		swap_cluster_unlock(ci);
 	}
 }
 
-static void free_swap_cluster_info(struct swap_cluster_info *cluster_info,
-				   unsigned long maxpages)
+static void free_swap_cluster_info(struct swap_info_struct *si)
 {
+	struct swap_cluster_info *cluster_info = si->cluster_info;
+	unsigned long maxpages = si->max;
 	struct swap_cluster_info *ci;
-	int i, nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
+	unsigned long i, nr_clusters;
 
 	if (!cluster_info)
 		return;
+
+#ifdef CONFIG_XSWAP
+	if (si->flags & SWP_XSWAP) {
+		unsigned long nr_mapped;
+
+		cancel_work_sync(&si->xswap_shrink_work);
+		/*
+		 * Cluster 0 keeps the bad header slot, so it never empties
+		 * and __free_cluster() never frees its table.
+		 */
+		/* Pairs with the smp_store_release() in xswap_map_clusters(). */
+		nr_mapped = smp_load_acquire(&si->nr_clusters_mapped);
+		for (i = 0; i < nr_mapped; i++) {
+			ci = &cluster_info[i];
+			spin_lock(&ci->lock);
+			if (cluster_table_is_alloced(ci)) {
+				swap_cluster_assert_empty(ci, 0, SWAPFILE_CLUSTER, true);
+				swap_cluster_free_table(ci);
+			}
+			spin_unlock(&ci->lock);
+		}
+		/* free_vm_area() drops the mapping without freeing the pages. */
+		xswap_unmap_clusters(si, 0, si->nr_clusters_mapped);
+		xswap_debugfs_del(si);
+		free_vm_area(si->cluster_vm);
+		si->cluster_vm = NULL;
+		si->cluster_info = NULL;
+		si->nr_clusters_mapped = 0;
+		return;
+	}
+#endif
+
+	nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
 	for (i = 0; i < nr_clusters; i++) {
 		ci = cluster_info + i;
 		/* Cluster with bad marks count will have a remaining table */
@@ -3156,6 +3497,7 @@ static void free_swap_cluster_info(struct swap_cluster_info *cluster_info,
 		spin_unlock(&ci->lock);
 	}
 	kvfree(cluster_info);
+	si->cluster_info = NULL;
 }
 
 /*
@@ -3179,15 +3521,14 @@ static void flush_percpu_swap_cluster(struct swap_info_struct *si)
 	}
 }
 
+static int swap_info_remove(struct swap_info_struct *p);
+static int __swapoff(struct swap_info_struct *p);
 
 SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 {
 	struct swap_info_struct *p = NULL;
-	struct swap_cluster_info *cluster_info;
-	struct file *swap_file, *victim;
+	struct file *victim;
 	struct address_space *mapping;
-	struct inode *inode;
-	unsigned int maxpages;
 	int err, found = 0;
 
 	if (!capable(CAP_SYS_ADMIN))
@@ -3204,7 +3545,7 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 	spin_lock(&swap_lock);
 	plist_for_each_entry(p, &swap_active_head, list) {
 		if (p->flags & SWP_WRITEOK) {
-			if (p->swap_file->f_mapping == mapping) {
+			if (p->swap_file && p->swap_file->f_mapping == mapping) {
 				found = 1;
 				break;
 			}
@@ -3223,20 +3564,59 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 		goto out_dput;
 	}
 
-	if (!security_vm_enough_memory_mm(current->mm, p->pages))
-		vm_unacct_memory(p->pages);
-	else {
-		err = -ENOMEM;
+	err = swap_info_remove(p);
+	if (err) {
 		spin_unlock(&swap_lock);
 		goto out_dput;
 	}
+	spin_unlock(&swap_lock);
+
+	err = __swapoff(p);
+
+out_dput:
+	filp_close(victim, NULL);
+	return err;
+}
+
+/*
+ * Drop @p from the avail and active lists and undo its accounting.  The
+ * caller must hold swap_lock and have checked that @p is WRITEOK and not
+ * pinned for hibernation.
+ *
+ * Returns 0, or -ENOMEM with swap_lock still held.
+ */
+static int swap_info_remove(struct swap_info_struct *p)
+{
+	if (!security_vm_enough_memory_mm(current->mm, p->pages))
+		vm_unacct_memory(p->pages);
+	else
+		return -ENOMEM;
+
 	spin_lock(&p->lock);
 	del_from_avail_list(p, true);
 	plist_del(&p->list, &swap_active_head);
 	atomic_long_sub(p->pages, &nr_swap_pages);
 	total_swap_pages -= p->pages;
 	spin_unlock(&p->lock);
-	spin_unlock(&swap_lock);
+	return 0;
+}
+
+/* Common swap teardown after list removal; shared by sys_swapoff() and
+ * xswap_destroy().
+ */
+static int __swapoff(struct swap_info_struct *p)
+{
+	struct file *swap_file = NULL;
+	int err;
+
+#ifdef CONFIG_XSWAP
+	if (p->flags & SWP_XSWAP) {
+		cancel_work_sync(&p->xswap_shrink_work);
+		/* Wait out a shrink racing us from the sysfs write path. */
+		mutex_lock(&p->xswap_lock);
+		mutex_unlock(&p->xswap_lock);
+	}
+#endif
 
 	wait_for_allocation(p);
 
@@ -3247,7 +3627,7 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 	if (err) {
 		/* re-insert swap space back into swap_list */
 		reinsert_swap_info(p);
-		goto out_dput;
+		return err;
 	}
 
 	/*
@@ -3268,7 +3648,8 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 
 	destroy_swap_extents(p, p->swap_file);
 
-	if (!(p->flags & SWP_SOLIDSTATE))
+	if (!(p->flags & SWP_XSWAP) &&
+	    !(p->flags & SWP_SOLIDSTATE))
 		atomic_dec(&nr_rotate_swap);
 
 	mutex_lock(&swapon_mutex);
@@ -3278,10 +3659,6 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 
 	swap_file = p->swap_file;
 	p->swap_file = NULL;
-	maxpages = p->max;
-	cluster_info = p->cluster_info;
-	p->max = 0;
-	p->cluster_info = NULL;
 	spin_unlock(&p->lock);
 	spin_unlock(&swap_lock);
 	arch_swap_invalidate_area(p->type);
@@ -3289,14 +3666,22 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 	mutex_unlock(&swapon_mutex);
 	kfree(p->global_cluster);
 	p->global_cluster = NULL;
-	free_swap_cluster_info(cluster_info, maxpages);
+	free_swap_cluster_info(p);
+	/*
+	 * The device is off swap_active_head and no longer WRITEOK, so no
+	 * reader can observe these; clearing them here needs no lock.
+	 */
+	p->max = 0;
+	p->cluster_info = NULL;
 
-	inode = mapping->host;
+	if (swap_file) {
+		struct inode *inode = swap_file->f_mapping->host;
 
-	inode_lock(inode);
-	inode->i_flags &= ~S_SWAPFILE;
-	inode_unlock(inode);
-	filp_close(swap_file, NULL);
+		inode_lock(inode);
+		inode->i_flags &= ~S_SWAPFILE;
+		inode_unlock(inode);
+		filp_close(swap_file, NULL);
+	}
 
 	/*
 	 * Clear the SWP_USED flag after all resources are freed so that swapon
@@ -3307,13 +3692,10 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 	p->flags = 0;
 	spin_unlock(&swap_lock);
 
-	err = 0;
 	atomic_inc(&proc_poll_event);
 	wake_up_interruptible(&proc_poll_wait);
 
-out_dput:
-	filp_close(victim, NULL);
-	return err;
+	return 0;
 }
 
 #ifdef CONFIG_PROC_FS
@@ -3344,7 +3726,8 @@ static void *swap_start(struct seq_file *swap, loff_t *pos)
 		return SEQ_START_TOKEN;
 
 	for (type = 0; (si = swap_type_to_info(type)); type++) {
-		if (!(si->swap_file))
+		if (!si->swap_file &&
+		    !((si->flags & SWP_XSWAP) && (si->flags & SWP_WRITEOK)))
 			continue;
 		if (!--l)
 			return si;
@@ -3365,7 +3748,8 @@ static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
 
 	++(*pos);
 	for (; (si = swap_type_to_info(type)); type++) {
-		if (!(si->swap_file))
+		if (!si->swap_file &&
+		    !((si->flags & SWP_XSWAP) && (si->flags & SWP_WRITEOK)))
 			continue;
 		return si;
 	}
@@ -3378,6 +3762,19 @@ static void swap_stop(struct seq_file *swap, void *v)
 	mutex_unlock(&swapon_mutex);
 }
 
+static const char *swap_type_str(struct swap_info_struct *si)
+{
+	struct file *file = si->swap_file;
+
+	if (si->flags & SWP_XSWAP)
+		return "xswap\t";
+
+	if (S_ISBLK(file_inode(file)->i_mode))
+		return "partition";
+
+	return "file\t";
+}
+
 static int swap_show(struct seq_file *swap, void *v)
 {
 	struct swap_info_struct *si = v;
@@ -3394,11 +3791,17 @@ static int swap_show(struct seq_file *swap, void *v)
 	inuse = K(swap_usage_in_pages(si));
 
 	file = si->swap_file;
-	len = seq_file_path(swap, file, " \t\n\\");
+	if (file)
+		len = seq_file_path(swap, file, " \t\n\\");
+	else {
+		char name[16];
+
+		len = scnprintf(name, sizeof(name), "xswap%d", si->type);
+		seq_puts(swap, name);
+	}
 	seq_printf(swap, "%*s%s\t%lu\t%s%lu\t%s%d\n",
 			len < 40 ? 40 - len : 1, " ",
-			S_ISBLK(file_inode(file)->i_mode) ?
-				"partition" : "file\t",
+			swap_type_str(si),
 			bytes, bytes < 10000000 ? "\t" : "",
 			inuse, inuse < 10000000 ? "\t" : "",
 			si->prio);
@@ -3609,12 +4012,8 @@ static unsigned long read_swap_header(struct swap_info_struct *si,
 		pr_warn("Truncating oversized swap area, only using %luk out of %luk\n",
 			K(maxpages), K(last_page));
 	}
-	if (maxpages > last_page) {
+	if (maxpages > last_page)
 		maxpages = last_page + 1;
-		/* p->max is an unsigned int: don't overflow it */
-		if ((unsigned int)maxpages == 0)
-			maxpages = UINT_MAX;
-	}
 
 	if (!maxpages)
 		return 0;
@@ -3631,6 +4030,483 @@ static unsigned long read_swap_header(struct swap_info_struct *si,
 	return maxpages;
 }
 
+#ifdef CONFIG_XSWAP
+static int xswap_map_clusters(struct swap_info_struct *si,
+			      unsigned long start_idx, unsigned long nr)
+{
+	unsigned long start_addr = (unsigned long)si->cluster_info +
+				   (size_t)start_idx * sizeof(struct swap_cluster_info);
+	unsigned long end_addr = start_addr + (size_t)nr * sizeof(struct swap_cluster_info);
+	unsigned long vm_start = PAGE_ALIGN(start_addr);
+	unsigned long vm_end = PAGE_ALIGN(end_addr);
+	unsigned int noreclaim_flags;
+	unsigned long mapped_end;
+	unsigned long npages;
+	struct page **pages;
+	unsigned long i;
+	int err;
+
+	mutex_lock(&si->xswap_lock);
+
+	/* Refuse a stale range: the boundary moved since the caller read it. */
+	if (start_idx != READ_ONCE(si->nr_clusters_mapped)) {
+		mutex_unlock(&si->xswap_lock);
+		return -EAGAIN;
+	}
+	if (start_idx + nr > si->nr_clusters_max) {
+		mutex_unlock(&si->xswap_lock);
+		return -EAGAIN;
+	}
+
+	/*
+	 * Page-granular mapping can cover clusters past the previous chunk.
+	 * Find the already-mapped prefix and map only the rest.
+	 */
+	mapped_end = vm_start;
+	if (vm_start < vm_end)
+		apply_to_existing_page_range(&init_mm, vm_start,
+					     vm_end - vm_start,
+					     xswap_mapped_end, &mapped_end);
+	if (vm_start >= vm_end || mapped_end == vm_end)
+		goto mapped;
+	vm_start = mapped_end;
+
+	npages = (vm_end - vm_start) >> PAGE_SHIFT;
+
+	/* Prevent recursive reclaim during vmap page table allocation. */
+	noreclaim_flags = memalloc_noreclaim_save();
+
+	pages = kmalloc_array(npages, sizeof(*pages),
+			      __GFP_HIGH | __GFP_NOMEMALLOC | GFP_KERNEL);
+	if (!pages) {
+		memalloc_noreclaim_restore(noreclaim_flags);
+		mutex_unlock(&si->xswap_lock);
+		return -ENOMEM;
+	}
+
+	for (i = 0; i < npages; i++) {
+		/* __GFP_ZERO: cluster_info pointer fields must start NULL. */
+		pages[i] = alloc_page(__GFP_HIGH | __GFP_NOMEMALLOC |
+				      GFP_KERNEL | __GFP_ZERO);
+		if (!pages[i])
+			goto fail;
+	}
+
+	err = vm_area_map_pages(si->cluster_vm, vm_start, vm_end, pages);
+	if (err) {
+		i = npages;
+		goto fail;
+	}
+
+	for (i = start_idx; i < start_idx + nr; i++)
+		spin_lock_init(&si->cluster_info[i].lock);
+
+	kfree(pages);
+	memalloc_noreclaim_restore(noreclaim_flags);
+
+	/*
+	 * Publish the new mappings and cluster lock initialization before
+	 * the count; walkers without xswap_lock use smp_load_acquire().
+	 */
+	smp_store_release(&si->nr_clusters_mapped, start_idx + nr);
+	mutex_unlock(&si->xswap_lock);
+	return 0;
+
+mapped:
+	for (i = start_idx; i < start_idx + nr; i++)
+		spin_lock_init(&si->cluster_info[i].lock);
+
+	/* Publish the advanced count. */
+	smp_store_release(&si->nr_clusters_mapped, start_idx + nr);
+	mutex_unlock(&si->xswap_lock);
+	return 0;
+
+fail:
+	/* Clear PTEs vm_area_map_pages() may have left before freeing pages. */
+	vm_area_unmap_pages(si->cluster_vm, vm_start, vm_end);
+	while (i > 0) {
+		i--;
+		if (pages[i])
+			__free_page(pages[i]);
+	}
+	memalloc_noreclaim_restore(noreclaim_flags);
+	kfree(pages);
+	mutex_unlock(&si->xswap_lock);
+	return -ENOMEM;
+}
+
+static bool xswap_should_grow(struct swap_info_struct *si)
+{
+	unsigned long mapped = READ_ONCE(si->nr_clusters_mapped);
+
+	if (mapped >= READ_ONCE(si->nr_clusters_max))
+		return false;
+
+	return swap_usage_in_pages(si) * 100 >=
+	       mapped * SWAPFILE_CLUSTER * XSWAP_GROW_WHEN;
+}
+
+/*
+ * Map more of the cluster_info array, up to GROW_UNTIL in use.  The caller
+ * holds percpu_swap_cluster.lock, which this drops while it sleeps.
+ */
+static unsigned long xswap_grow(struct swap_info_struct *si)
+{
+	unsigned long mapped = READ_ONCE(si->nr_clusters_mapped);
+	unsigned long nr_new, want, i;
+	int ret;
+
+	/* The unmap below is paired with the caller's lock. */
+	lockdep_assert_held(&percpu_swap_cluster.lock);
+
+	want = DIV_ROUND_UP(swap_usage_in_pages(si) * 100,
+			    XSWAP_GROW_UNTIL * SWAPFILE_CLUSTER);
+	if (want <= mapped)
+		return 0;
+
+	nr_new = rounddown(want - mapped, XSWAP_GROW_CLUSTERS);
+	if (!nr_new)
+		nr_new = XSWAP_GROW_CLUSTERS;
+	if (nr_new > XSWAP_GROW_CHUNKS * XSWAP_GROW_CLUSTERS)
+		nr_new = XSWAP_GROW_CHUNKS * XSWAP_GROW_CLUSTERS;
+	nr_new = min(nr_new, READ_ONCE(si->nr_clusters_max) - mapped);
+
+	/*
+	 * Mapping pages can sleep.  The lock only guards the per-cpu
+	 * cluster cache, which this path does not touch.
+	 */
+	local_unlock(&percpu_swap_cluster.lock);
+	ret = xswap_map_clusters(si, mapped, nr_new);
+	local_lock(&percpu_swap_cluster.lock);
+	if (ret)
+		return 0;
+
+	for (i = mapped; i < mapped + nr_new; i++) {
+		struct swap_cluster_info *ci = &si->cluster_info[i];
+
+		/*
+		 * A concurrent grower may have taken these already;
+		 * only add the off-list ones.
+		 */
+		spin_lock(&ci->lock);
+		if (ci->flags == CLUSTER_FLAG_NONE)
+			move_cluster(si, ci, &si->free_clusters,
+				     CLUSTER_FLAG_FREE);
+		spin_unlock(&ci->lock);
+	}
+
+	atomic_long_inc(&si->xswap_grows);
+	return nr_new;
+}
+
+struct xswap_page_data {
+	struct page **pages;
+	unsigned long nr;
+	unsigned long max;
+};
+
+static int xswap_collect_page(pte_t *pte, unsigned long addr, void *data)
+{
+	struct xswap_page_data *xpd = data;
+	pte_t pteval = ptep_get(pte);
+
+	if (!pte_present(pteval))
+		return 0;
+	if (WARN_ON_ONCE(xpd->nr >= xpd->max))
+		return 0;
+	xpd->pages[xpd->nr++] = pte_page(pteval);
+	return 0;
+}
+
+/*
+ * Free the backing pages mapped in [vm_start, vm_end) and clear the PTEs.
+ * @pages must have room for @max pointers.
+ */
+static void xswap_unmap_range(struct swap_info_struct *si,
+			      unsigned long vm_start, unsigned long vm_end,
+			      struct page **pages, unsigned long max)
+{
+	struct xswap_page_data xpd = {
+		.pages	= pages,
+		.max	= max,
+	};
+	unsigned long i;
+
+	apply_to_existing_page_range(&init_mm, vm_start, vm_end - vm_start,
+				     xswap_collect_page, &xpd);
+	vm_area_unmap_pages(si->cluster_vm, vm_start, vm_end);
+
+	for (i = 0; i < xpd.nr; i++)
+		__free_page(pages[i]);
+}
+
+/* Caller must hold si->xswap_lock.  Cannot fail. */
+static void xswap_unmap_clusters_locked(struct swap_info_struct *si,
+					unsigned long start_idx, unsigned long nr)
+{
+	unsigned long start_addr = (unsigned long)si->cluster_info +
+				   (size_t)start_idx * sizeof(struct swap_cluster_info);
+	unsigned long end_addr = start_addr +
+				 (size_t)nr * sizeof(struct swap_cluster_info);
+	unsigned long vm_start = PAGE_ALIGN(start_addr);
+	unsigned long vm_end = PAGE_ALIGN(end_addr);
+	struct page **pages;
+	unsigned int noreclaim_flags;
+	unsigned long npages, idx;
+
+	if (vm_start >= vm_end) {
+		WRITE_ONCE(si->nr_clusters_mapped, start_idx);
+		return;
+	}
+
+	/*
+	 * A per-cpu cluster cache can still hold an offset in this range.
+	 * Invalidate those references, then wait out the readers that have
+	 * already loaded one, so that nobody can dereference cluster_info
+	 * past this point.  swapoff() needs the same before it releases.
+	 */
+	flush_percpu_swap_cluster(si);
+	synchronize_rcu();
+
+	npages = (vm_end - vm_start) >> PAGE_SHIFT;
+
+	/* Reclaim here would re-enter xswap_map_clusters() and its lock. */
+	noreclaim_flags = memalloc_noreclaim_save();
+	pages = kvmalloc_array(npages, sizeof(*pages), GFP_KERNEL);
+	memalloc_noreclaim_restore(noreclaim_flags);
+	if (pages) {
+		xswap_unmap_range(si, vm_start, vm_end, pages, npages);
+		kvfree(pages);
+		WRITE_ONCE(si->nr_clusters_mapped, start_idx);
+		return;
+	}
+
+	/* No memory for the array: unmap in bounded batches instead. */
+	for (idx = start_idx; idx < start_idx + nr; idx += XSWAP_UNMAP_BATCH_CLUSTERS) {
+		unsigned long batch = min(start_idx + nr - idx,
+					  XSWAP_UNMAP_BATCH_CLUSTERS);
+		unsigned long addr = (unsigned long)si->cluster_info +
+				     (size_t)idx * sizeof(struct swap_cluster_info);
+		unsigned long bstart = PAGE_ALIGN(addr);
+		unsigned long bend = PAGE_ALIGN(addr + (size_t)batch *
+					       sizeof(struct swap_cluster_info));
+		struct page *batch_pages[XSWAP_UNMAP_BATCH_PAGES + 1];
+
+		if (bstart < bend)
+			xswap_unmap_range(si, bstart, bend, batch_pages,
+					  ARRAY_SIZE(batch_pages));
+	}
+
+	WRITE_ONCE(si->nr_clusters_mapped, start_idx);
+}
+
+static void xswap_unmap_clusters(struct swap_info_struct *si,
+				 unsigned long start_idx, unsigned long nr)
+{
+	mutex_lock(&si->xswap_lock);
+	xswap_unmap_clusters_locked(si, start_idx, nr);
+	mutex_unlock(&si->xswap_lock);
+}
+
+/* Track the end of the run of pages that is already mapped. */
+static int xswap_mapped_end(pte_t *pte, unsigned long addr, void *data)
+{
+	unsigned long *mapped_end = data;
+
+	if (!pte_present(ptep_get(pte)))
+		return 0;
+	*mapped_end = addr + PAGE_SIZE;
+	return 0;
+}
+
+/*
+ * Automatic reclaim: leave one chunk of the free tail mapped as slack, so
+ * that the next allocation has somewhere to land, and only unmap once
+ * several chunks can go, so the unmap is worth the RCU grace period it
+ * costs.
+ */
+#define XSWAP_SHRINK_SLACK	XSWAP_GROW_CLUSTERS
+#define XSWAP_SHRINK_MIN	(XSWAP_GROW_CLUSTERS * 8)
+
+static void xswap_shrink_work_fn(struct work_struct *work)
+{
+	struct swap_info_struct *si = container_of(work,
+			struct swap_info_struct, xswap_shrink_work);
+
+	if (!(READ_ONCE(si->flags) & SWP_WRITEOK))
+		return;
+	xswap_try_shrink(si);
+}
+
+/*
+ * Try to shrink the cluster_info tail: unmap contiguous free clusters
+ * at the end of the mapped range.
+ */
+static void xswap_try_shrink(struct swap_info_struct *si)
+{
+	struct swap_cluster_info *ci;
+	unsigned long nr_mapped, nr_tail, keep, nr_unmap, start_idx, i;
+
+	if (!(si->flags & SWP_XSWAP))
+		return;
+
+	mutex_lock(&si->xswap_lock);
+
+	/* A swapoff raced us and is about to walk this mapping. */
+	if (!(READ_ONCE(si->flags) & SWP_WRITEOK))
+		goto out_unlock;
+
+	nr_mapped = READ_ONCE(si->nr_clusters_mapped);
+	if (nr_mapped <= 1)	/* keep cluster 0 */
+		goto out_unlock;
+
+	/*
+	 * Reclaim on our own, but only once the mapped range is at most
+	 * SHRINK_WHEN in use: growth is demand driven, so reclaiming on a
+	 * smaller dip would only map the same clusters again, and every
+	 * unmap costs an RCU grace period.
+	 */
+	if (swap_usage_in_pages(si) * 100 >
+	    nr_mapped * SWAPFILE_CLUSTER * XSWAP_SHRINK_WHEN)
+		goto out_unlock;
+
+	/*
+	 * Count the free clusters at the tail of the mapped range.  Scanned,
+	 * not tracked: the count must be exact to size the unmap, and an
+	 * incremental count falls behind on out-of-order frees.
+	 */
+	nr_tail = 0;
+	while (nr_mapped - nr_tail > 1) {
+		ci = &si->cluster_info[nr_mapped - nr_tail - 1];
+		if (READ_ONCE(ci->count) ||
+		    READ_ONCE(ci->flags) != CLUSTER_FLAG_FREE)
+			break;
+		nr_tail++;
+	}
+	if (nr_tail < XSWAP_SHRINK_SLACK + XSWAP_SHRINK_MIN)
+		goto out_unlock;
+
+	/*
+	 * Stop at SHRINK_UNTIL rather than at the end of the tail, or the
+	 * range comes out full enough for the grow to be woken.  Below the
+	 * tail everything stays mapped, and one chunk of tail with it.
+	 */
+	keep = DIV_ROUND_UP(swap_usage_in_pages(si) * 100,
+			    XSWAP_SHRINK_UNTIL * SWAPFILE_CLUSTER);
+	if (keep < nr_mapped - nr_tail + XSWAP_SHRINK_SLACK)
+		keep = nr_mapped - nr_tail + XSWAP_SHRINK_SLACK;
+
+	if (nr_mapped < keep + XSWAP_SHRINK_MIN)
+		goto out_unlock;
+
+	nr_unmap = rounddown(nr_mapped - keep, XSWAP_GROW_CLUSTERS);
+	if (!nr_unmap)
+		goto out_unlock;
+	start_idx = nr_mapped - nr_unmap;
+
+	/*
+	 * Only shrink a run that reaches the mapped end; otherwise
+	 * truncating nr_clusters_mapped would orphan the active tail.
+	 */
+	spin_lock(&si->lock);
+	for (i = start_idx; i < nr_mapped; i++) {
+		ci = &si->cluster_info[i];
+		if (READ_ONCE(ci->flags) != CLUSTER_FLAG_FREE)
+			break;
+		if (!spin_trylock(&ci->lock)) {
+			spin_unlock(&si->lock);
+			goto out_unlock;
+		}
+		spin_unlock(&ci->lock);
+	}
+	if (i != nr_mapped) {
+		spin_unlock(&si->lock);
+		goto out_unlock;
+	}
+
+	for (i = start_idx; i < nr_mapped; i++) {
+		ci = &si->cluster_info[i];
+		list_del_init(&ci->list);
+		WRITE_ONCE(ci->flags, CLUSTER_FLAG_NONE);
+	}
+	spin_unlock(&si->lock);
+
+	xswap_unmap_clusters_locked(si, start_idx, nr_unmap);
+	atomic_long_inc(&si->xswap_shrinks);
+
+out_unlock:
+	mutex_unlock(&si->xswap_lock);
+}
+
+/* Not an interface: how far the mapped range has moved, for testing. */
+static ssize_t xswap_debugfs_read(struct file *file, char __user *buf,
+				  size_t count, loff_t *ppos)
+{
+	struct swap_info_struct *si = file->private_data;
+	struct swap_cluster_info *ci;
+	unsigned long mapped, tail = 0;
+	char tmp[192];
+	int len;
+
+	/*
+	 * The same scan the shrink does.  xswap_lock is what keeps
+	 * cluster_info from being unmapped under it.
+	 */
+	mutex_lock(&si->xswap_lock);
+	mapped = READ_ONCE(si->nr_clusters_mapped);
+	if (si->cluster_info) {
+		while (mapped - tail > 1) {
+			ci = &si->cluster_info[mapped - tail - 1];
+			if (READ_ONCE(ci->count) ||
+			    READ_ONCE(ci->flags) != CLUSTER_FLAG_FREE)
+				break;
+			tail++;
+		}
+	}
+	len = scnprintf(tmp, sizeof(tmp),
+			"clusters_max %lu\nclusters_mapped %lu\nusage_pages %lu\ntail_free %lu\ngrows %lu\nshrinks %lu\n",
+			READ_ONCE(si->nr_clusters_max), mapped,
+			swap_usage_in_pages(si), tail,
+			atomic_long_read(&si->xswap_grows),
+			atomic_long_read(&si->xswap_shrinks));
+	mutex_unlock(&si->xswap_lock);
+
+	return simple_read_from_buffer(buf, count, ppos, tmp, len);
+}
+
+static const struct file_operations xswap_debugfs_fops = {
+	.read	= xswap_debugfs_read,
+	.open	= simple_open,
+	.llseek	= default_llseek,
+};
+
+static struct dentry *xswap_debugfs_root;
+
+static void xswap_debugfs_add(struct swap_info_struct *si)
+{
+	char name[16];
+
+	if (!xswap_debugfs_root)
+		xswap_debugfs_root = debugfs_create_dir("xswap", NULL);
+	if (IS_ERR_OR_NULL(xswap_debugfs_root))
+		return;
+
+	/* debugfs_create_file() takes the name as it is; no formatting. */
+	snprintf(name, sizeof(name), "type%d", si->type);
+	si->xswap_debugfs = debugfs_create_file(name, 0444,
+						xswap_debugfs_root, si,
+						&xswap_debugfs_fops);
+	if (IS_ERR(si->xswap_debugfs))
+		si->xswap_debugfs = NULL;
+}
+
+static void xswap_debugfs_del(struct swap_info_struct *si)
+{
+	debugfs_remove(si->xswap_debugfs);
+	si->xswap_debugfs = NULL;
+}
+#endif /* CONFIG_XSWAP */
+
 static int setup_swap_clusters_info(struct swap_info_struct *si,
 				    union swap_header *swap_header,
 				    unsigned long maxpages)
@@ -3640,10 +4516,76 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,
 	int err = -ENOMEM;
 	unsigned long i;
 
+#ifdef CONFIG_XSWAP
+	if (si->flags & SWP_XSWAP) {
+		unsigned long size = PAGE_ALIGN(nr_clusters * sizeof(*cluster_info));
+		struct vm_struct *vm;
+
+		vm = get_vm_area(size, VM_SPARSE);
+		if (!vm)
+			goto err;
+
+		cluster_info = vm->addr;
+		si->cluster_vm = vm;
+		si->nr_clusters_max = nr_clusters;
+		si->cluster_info = cluster_info;
+
+		/* Must be initialized before xswap_map_clusters() locks it. */
+		mutex_init(&si->xswap_lock);
+
+		if (xswap_map_clusters(si, 0, min_t(unsigned long,
+					XSWAP_GROW_CLUSTERS, nr_clusters)))
+			goto err_free_vm;
+
+		/* xswap: only cluster 0 slot 0 is bad */
+		err = swap_cluster_setup_bad_slot(si, cluster_info, 0, false);
+		if (err)
+			goto err_unmap;
+
+		INIT_LIST_HEAD(&si->free_clusters);
+		INIT_LIST_HEAD(&si->full_clusters);
+		INIT_LIST_HEAD(&si->discard_clusters);
+		for (i = 0; i < SWAP_NR_ORDERS; i++) {
+			INIT_LIST_HEAD(&si->nonfull_clusters[i]);
+			INIT_LIST_HEAD(&si->frag_clusters[i]);
+		}
+
+		/*
+		 * Cluster 0 holds the header slot, which is marked bad, so it
+		 * is not entirely free.  si->max is cluster aligned, so no
+		 * cluster holds a slot past the end of the device.
+		 */
+		for (i = 0; i < si->nr_clusters_mapped; i++) {
+			struct swap_cluster_info *ci = &cluster_info[i];
+
+			if (ci->count) {
+				ci->flags = CLUSTER_FLAG_NONFULL;
+				list_add_tail(&ci->list, &si->nonfull_clusters[0]);
+			} else {
+				ci->flags = CLUSTER_FLAG_FREE;
+				list_add_tail(&ci->list, &si->free_clusters);
+			}
+		}
+
+		INIT_WORK(&si->xswap_shrink_work, xswap_shrink_work_fn);
+		return 0;
+
+err_unmap:
+		xswap_unmap_clusters(si, 0, si->nr_clusters_mapped);
+err_free_vm:
+		free_vm_area(si->cluster_vm);
+		si->cluster_vm = NULL;
+		si->cluster_info = NULL;
+		return err;
+	}
+#endif /* CONFIG_XSWAP */
+
 	cluster_info = kvzalloc_objs(*cluster_info, nr_clusters);
 	if (!cluster_info)
 		goto err;
 
+	si->cluster_info = cluster_info;
+
 	for (i = 0; i < nr_clusters; i++)
 		spin_lock_init(&cluster_info[i].lock);
 
@@ -3707,10 +4649,135 @@ static int setup_swap_clusters_info(struct swap_info_struct *si,
 	si->cluster_info = cluster_info;
 	return 0;
 err:
-	free_swap_cluster_info(cluster_info, maxpages);
+	free_swap_cluster_info(si);
 	return err;
 }
 
+#ifdef CONFIG_XSWAP
+/* Create a file-less xswap device, sized at twice RAM. */
+static int xswap_create(int prio)
+{
+	struct swap_info_struct *si;
+	unsigned long maxpages;
+	int error;
+
+	if (prio != DEF_XSWAP_PRIO &&
+	    (prio < 0 || prio > SWAP_FLAG_PRIO_MASK))
+		return -EINVAL;
+
+	/* xswap has no backing store, it relies on zswap. */
+	if (!zswap_is_enabled())
+		return -EOPNOTSUPP;
+
+	/* Refuse rather than clamp: xswap.max= should give what was asked. */
+	maxpages = xswap_size_pages();
+	if (maxpages > xswap_size_limit()) {
+		pr_err("xswap: xswap.max is larger than the device can address\n");
+		return -EINVAL;
+	}
+	/*
+	 * Below one cluster the device is not cluster-aligned, so its only
+	 * cluster would hold slots past si->max.  Nothing masks those, and a
+	 * slot allocated there is past the end of the device: it can never be
+	 * read back or given up again.
+	 */
+	if (maxpages < SWAPFILE_CLUSTER) {
+		pr_err("xswap: xswap.max is smaller than one cluster\n");
+		return -EINVAL;
+	}
+
+	si = alloc_swap_info();
+	if (IS_ERR(si))
+		return PTR_ERR(si);
+
+	INIT_WORK(&si->discard_work, swap_discard_work);
+	INIT_WORK(&si->reclaim_work, swap_reclaim_work);
+
+	/* Cluster-aligned, so no cluster holds a slot past si->max. */
+	maxpages = rounddown(maxpages, SWAPFILE_CLUSTER);
+
+	si->bdev = NULL;
+	si->flags |= SWP_XSWAP | SWP_SOLIDSTATE;
+	si->max = maxpages;
+	si->pages = maxpages - 1;
+	/*
+	 * No backing file: setup_swap_extents() is only reachable from the
+	 * file-backed swapon() path, so set ops here.  Only ops->flags is
+	 * used, by may_enter_fs(); the IO methods are never called because
+	 * swap_writeout()/swap_read_folio() short circuit xswap.
+	 */
+	si->ops = &swap_bdev_ops;
+
+	si->xswap_debugfs = NULL;
+	atomic_long_set(&si->xswap_grows, 0);
+	atomic_long_set(&si->xswap_shrinks, 0);
+
+	error = setup_swap_clusters_info(si, NULL, maxpages);
+	if (error)
+		goto bad_swap;
+
+	xswap_debugfs_add(si);
+
+	error = zswap_swapon(si->type, si->max);
+	if (error)
+		goto bad_swap;
+
+	mutex_lock(&swapon_mutex);
+	si->prio = prio;
+	si->list.prio = -si->prio;
+	si->avail_list.prio = -si->prio;
+	/* si->swap_file stays NULL: this is a file-less device */
+	enable_swap_info(si);
+	pr_info("xswap: adding extendable swap type %d (prio %d, %lu pages)\n",
+		si->type, prio, si->pages);
+	mutex_unlock(&swapon_mutex);
+	atomic_inc(&proc_poll_event);
+	wake_up_interruptible(&proc_poll_wait);
+
+	return si->type;
+
+bad_swap:
+	kfree(si->global_cluster);
+	si->global_cluster = NULL;
+	destroy_swap_extents(si, NULL);	/* safe: xswap never sets SWP_ACTIVATED */
+	free_swap_cluster_info(si);
+	si->cluster_info = NULL;
+	spin_lock(&swap_lock);
+	si->flags = 0;
+	spin_unlock(&swap_lock);
+	return error;
+}
+
+/* Tear down a file-less xswap device by its swap type. */
+static int xswap_destroy(int type)
+{
+	struct swap_info_struct *p;
+	int err;
+
+	p = swap_type_to_info(type);
+	if (!p)
+		return -EINVAL;
+
+	spin_lock(&swap_lock);
+	if (!(p->flags & SWP_WRITEOK) || !(p->flags & SWP_XSWAP)) {
+		spin_unlock(&swap_lock);
+		return -EINVAL;
+	}
+	/* Refuse swapoff while the device is pinned for hibernation */
+	if (p->flags & SWP_HIBERNATION) {
+		spin_unlock(&swap_lock);
+		return -EBUSY;
+	}
+
+	err = swap_info_remove(p);
+	spin_unlock(&swap_lock);
+	if (err)
+		return err;
+
+	return __swapoff(p);
+}
+#endif /* CONFIG_XSWAP */
+
 SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 {
 	struct swap_info_struct *si;
@@ -3815,7 +4882,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 		goto bad_swap_unlock_inode;
 	}
 	if (si->pages != si->max - 1) {
-		pr_err("swap:%u != (max:%u - 1)\n", si->pages, si->max);
+		pr_err("swap:%lu != (max:%lu - 1)\n", si->pages, si->max);
 		error = -EINVAL;
 		goto bad_swap_unlock_inode;
 	}
@@ -3906,7 +4973,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 	/* Sets SWP_WRITEOK, resurrect the percpu ref, expose the swap device */
 	enable_swap_info(si);
 
-	pr_info("Adding %uk swap on %s.  Priority:%d extents:%d across:%lluk %s%s%s%s\n",
+	pr_info("Adding %luk swap on %s.  Priority:%d extents:%d across:%lluk %s%s%s%s\n",
 		K(si->pages), name->name, si->prio, nr_extents,
 		K((unsigned long long)span),
 		(si->flags & SWP_SOLIDSTATE) ? "SS" : "",
@@ -3929,7 +4996,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 	si->global_cluster = NULL;
 	inode = NULL;
 	destroy_swap_extents(si, swap_file);
-	free_swap_cluster_info(si->cluster_info, si->max);
+	free_swap_cluster_info(si);
 	si->cluster_info = NULL;
 	/*
 	 * Clear the SWP_USED flag after all resources are freed so
@@ -4057,6 +5124,8 @@ static int __init swapfile_init(void)
 		swap_migration_ad_supported = true;
 #endif	/* CONFIG_MIGRATION */
 
+	xswap_sysfs_init();
+
 	return 0;
 }
 subsys_initcall(swapfile_init);
diff --git a/mm/zswap.c b/mm/zswap.c
index ae19e301fced7..7fe25f0b157ce 100644
--- a/mm/zswap.c
+++ b/mm/zswap.c
@@ -1018,6 +1018,11 @@ static int zswap_writeback_entry(struct zswap_entry *entry,
 	if (IS_ERR_OR_NULL(si))
 		return -ENOENT;
 
+	if (si->flags & SWP_XSWAP) {
+		put_swap_device(si);
+		return -EINVAL;
+	}
+
 	mpol = get_task_policy(current);
 	folio = __swap_cache_alloc_folio(swpentry, GFP_KERNEL, BIT(0), NULL, mpol,
 					 NO_INTERLEAVE_INDEX);
@@ -1511,7 +1516,9 @@ static bool zswap_store_page(struct folio *folio, long index,
 	entry->referenced = true;
 	if (entry->length) {
 		INIT_LIST_HEAD(&entry->lru);
-		zswap_lru_add(entry);
+		/* No backing store: nothing to write these back to. */
+		if (!(__swap_entry_to_info(page_swpentry)->flags & SWP_XSWAP))
+			zswap_lru_add(entry);
 	}
 
 	return true;
@@ -1581,7 +1588,7 @@ bool zswap_store(struct folio *folio)
 	zswap_pool_put(pool);
 put_objcg:
 	obj_cgroup_put(objcg);
-	if (!ret && zswap_pool_reached_full)
+	if (!ret && zswap_pool_reached_full && atomic_read(&nr_real_swapfiles))
 		queue_work(shrink_wq, &zswap_shrink_work);
 check_old:
 	/*

19/3 2026/10/03 10:13 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 24692
							output: 31
							thoughts: 2084
						

Thoughts:
**KMSAN Evaluation for XSWAP Patch Series**

Okay, let's break this down. The task is to determine if a dedicated KMSAN fuzzing session is warranted for this "Extendable (virtual) swap device" (XSWAP) patch. My expertise tells me that KMSAN is concerned with uninitialized memory reads, particularly when data is passed to user space or when conditional logic depends on such uninitialized values.  The guiding principle is: if KASAN, LOCKDEP, or standard detectors can catch a bug, we *don't* need KMSAN. We only need KMSAN if the patch *introduces* new risks related to uninitialized memory.

Looking at the patch itself, a number of files are modified, and I need to carefully assess each change:

1.  **`include/linux/swap.h`**:  The addition of `SWP_XSWAP` and extensions to the `swap_info_struct` don't immediately scream KMSAN risk. The new struct members *could* be a concern, but only if they are not properly initialized or zeroed *before* being used or sent to user space.  The external `nr_real_swapfiles` seems like a minor addition, not a risk itself.

2.  **`mm/Kconfig`**: Adding a config option usually doesn't introduce uninitialized memory issues.

3.  **`mm/page_io.c`, `mm/swap_state.c`**: These files contain conditional logic and skipping readahead for XSWAP. The risk depends on the initialization of the `si->flags` and `folio` data. Without reviewing the other callers, I'll need to remember to pay attention to where and how these flags are set and used.

4.  **`mm/swapfile.c`**: *This* is where the KMSAN concerns start to surface.  This file is substantially modified and interacts directly with memory management.  Specifically, I'm noting:
    *   The sysfs interface additions (`xswap_create_store`, `xswap_destroy_store`). The parsing functions themselves (`kstrtoint`, `kstrtoul`) are less of a risk if standard library functions, but how the parsed data is *used* is crucial. Are the priority and type variables used as indices, etc.? I need to trace those paths.
    *   The `alloc_swap_scan_cluster` and `swap_reclaim_full_clusters` function updates, along with the changes in type definition to `unsigned long` are likely fine, but may need to be traced to make sure it is not passed to user space and no uninitialized memory is read.
    *   The function `cluster_alloc_swap_entry`:  The changes to `cluster_alloc_swap_entry` are also a red flag. The introduction of `xswap_should_grow(si)` and `xswap_grow(si)` needs deep examination.  How is `si` populated? Is there a risk of uninitialized fields being read in these calls, especially given the conditional logic?
    *   `del_from_avail_list` / `add_to_avail_list` - Keeping track of `nr_xswap_files` vs `nr_real_swapfiles` in these functions doesn't look risky.
    *   The `folio_alloc_swap` function and the usage of `may_zswap`: I need to see how these boolean values are set and used. If those values are initialized before usage, that should be fine.
    *   The `find_next_to_unuse` and `wait_for_allocation` functions which modify and use `nr_clusters_mapped`. I need to ensure the variable `si->nr_clusters_mapped` is initialized properly.
    *   The `free_swap_cluster_info` is refactored, the debugfs cleanup, unmapping and vm area freeing sound safe in the absence of other KMSAN flags.
    *   The `swapoff` syscall refactor also sounds safe.
    *   The `/proc/swaps` show changes also look safe, using seq\_printf rather than potentially unsafe sprintf.
    *   The `xswap_map_clusters` function allocates pages with `__GFP_ZERO` meaning that the allocated memory is zero-initialized. Also, spinlocks are initialized for memory protection. So this doesn't seem risky in general.
    *   The `xswap_grow` maps new clusters, which initializes spinlocks, which sounds safe.
    *   The `xswap_debugfs_read` function relies on `scnprintf` and `simple_read_from_buffer` to construct the debugfs string. The usage of those functions sounds safe


20/3 2026/10/03 10:13 tool grepper
0m Args:
{
  "Expression": "alloc_swap_info",
  "PathPrefix": "mm/swapfile.c"
}

Results:
{
  "Output": "mm/swapfile.c=3607=static int __swapoff(struct swap_info_struct *p)\n--\nmm/swapfile.c-3687-\t * Clear the SWP_USED flag after all resources are freed so that swapon\nmm/swapfile.c:3688:\t * can reuse this swap_info in alloc_swap_info() safely.  It is ok to\nmm/swapfile.c-3689-\t * not hold p-\u003elock after we cleared its SWP_WRITEOK.\n--\nmm/swapfile.c=3855=late_initcall(max_swapfiles_check);\n--\nmm/swapfile.c-3857-\nmm/swapfile.c:3858:static struct swap_info_struct *alloc_swap_info(void)\nmm/swapfile.c-3859-{\n--\nmm/swapfile.c=4658=static int xswap_create(int prio)\n--\nmm/swapfile.c-4688-\nmm/swapfile.c:4689:\tsi = alloc_swap_info();\nmm/swapfile.c-4690-\tif (IS_ERR(si))\n--\nmm/swapfile.c=4781=SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)\n--\nmm/swapfile.c-4807-\t */\nmm/swapfile.c:4808:\tsi = alloc_swap_info();\nmm/swapfile.c-4809-\tif (IS_ERR(si))\n--\nmm/swapfile.c-5002-\t * Clear the SWP_USED flag after all resources are freed so\nmm/swapfile.c:5003:\t * alloc_swap_info can reuse this si safely.\nmm/swapfile.c-5004-\t */\n"
}

21/3 2026/10/03 10:13 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28312
							output: 35
							thoughts: 16
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience:

**Diving into `alloc_swap_info()`**

Alright, let's get down to brass tacks. I need to get a handle on what's happening with `alloc_swap_info()`. My immediate approach? Let's use `read-file` to get a direct look at the source code. It's the most efficient way to start piecing together the flow and understand the specifics of this allocation process. I need to see how the kernel is handling memory management during swap operations. Let's see what we've got.



22/3 2026/10/03 10:13 tool read-file
0m Args:
{
  "File": "mm/swapfile.c",
  "FirstLine": 3855,
  "LineCount": 45
}

Results:
{
  "Contents": "3855:\tlate_initcall(max_swapfiles_check);\n3856:\t#endif\n3857:\t\n3858:\tstatic struct swap_info_struct *alloc_swap_info(void)\n3859:\t{\n3860:\t\tstruct swap_info_struct *p;\n3861:\t\tstruct swap_info_struct *defer = NULL;\n3862:\t\tunsigned int type;\n3863:\t\n3864:\t\tp = kvzalloc_obj(struct swap_info_struct);\n3865:\t\tif (!p)\n3866:\t\t\treturn ERR_PTR(-ENOMEM);\n3867:\t\n3868:\t\tif (percpu_ref_init(\u0026p-\u003eusers, swap_users_ref_free,\n3869:\t\t\t\t    PERCPU_REF_INIT_DEAD, GFP_KERNEL)) {\n3870:\t\t\tkvfree(p);\n3871:\t\t\treturn ERR_PTR(-ENOMEM);\n3872:\t\t}\n3873:\t\n3874:\t\tspin_lock(\u0026swap_lock);\n3875:\t\tfor (type = 0; type \u003c nr_swapfiles; type++) {\n3876:\t\t\tif (!(swap_info[type]-\u003eflags \u0026 SWP_USED))\n3877:\t\t\t\tbreak;\n3878:\t\t}\n3879:\t\tif (type \u003e= MAX_SWAPFILES) {\n3880:\t\t\tspin_unlock(\u0026swap_lock);\n3881:\t\t\tpercpu_ref_exit(\u0026p-\u003eusers);\n3882:\t\t\tkvfree(p);\n3883:\t\t\treturn ERR_PTR(-EPERM);\n3884:\t\t}\n3885:\t\tif (type \u003e= nr_swapfiles) {\n3886:\t\t\tp-\u003etype = type;\n3887:\t\t\t/*\n3888:\t\t\t * Publish the swap_info_struct after initializing it.\n3889:\t\t\t * Note that kvzalloc() above zeroes all its fields.\n3890:\t\t\t */\n3891:\t\t\tsmp_store_release(\u0026swap_info[type], p); /* rcu_assign_pointer() */\n3892:\t\t\tnr_swapfiles++;\n3893:\t\t} else {\n3894:\t\t\tdefer = p;\n3895:\t\t\tp = swap_info[type];\n3896:\t\t\t/*\n3897:\t\t\t * Do not memset this entry: a racing procfs swap_next()\n3898:\t\t\t * would be relying on p-\u003etype to remain valid.\n3899:\t\t\t */\n"
}

23/3 2026/10/03 10:13 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 29164
							output: 35
							thoughts: 66
						

Thoughts:
Here's my summary, as if I were thinking these thoughts:

**Analyzing `alloc_swap_info()` and Potential Reuse**

Okay, so `alloc_swap_info()` starts by allocating a `struct swap_info_struct` using `kvzalloc_obj()`, assigning it to `p`. That seems straightforward. But, I'm already anticipating a potential wrinkle. What happens in the scenario where `type` is less than `nr_swapfiles`? We know that if it is, `p` *could* get reused through `p = swap_info[type]`. I need to dig into the logic and understand the implications of this possible reuse. Specifically, I need to understand what's happening in lines 3895-3920. Let's see how the allocation and potential reuse work together. It is worth examining this logic carefully for resource leaks and concurrency issues.



24/3 2026/10/03 10:13 tool read-file
0m Args:
{
  "File": "mm/swapfile.c",
  "FirstLine": 3895,
  "LineCount": 40
}

Results:
{
  "Contents": "3895:\t\t\tp = swap_info[type];\n3896:\t\t\t/*\n3897:\t\t\t * Do not memset this entry: a racing procfs swap_next()\n3898:\t\t\t * would be relying on p-\u003etype to remain valid.\n3899:\t\t\t */\n3900:\t\t}\n3901:\t\tp-\u003eswap_extent_root = RB_ROOT;\n3902:\t\tplist_node_init(\u0026p-\u003elist, 0);\n3903:\t\tplist_node_init(\u0026p-\u003eavail_list, 0);\n3904:\t\tp-\u003eflags = SWP_USED;\n3905:\t\tspin_unlock(\u0026swap_lock);\n3906:\t\tif (defer) {\n3907:\t\t\tpercpu_ref_exit(\u0026defer-\u003eusers);\n3908:\t\t\tkvfree(defer);\n3909:\t\t}\n3910:\t\tspin_lock_init(\u0026p-\u003elock);\n3911:\t\tatomic_long_set(\u0026p-\u003einuse_pages, SWAP_USAGE_OFFLIST_BIT);\n3912:\t\tinit_completion(\u0026p-\u003ecomp);\n3913:\t\n3914:\t\treturn p;\n3915:\t}\n3916:\t\n3917:\tstatic int claim_swapfile(struct swap_info_struct *si, struct inode *inode)\n3918:\t{\n3919:\t\tif (S_ISBLK(inode-\u003ei_mode)) {\n3920:\t\t\tsi-\u003ebdev = I_BDEV(inode);\n3921:\t\t\t/*\n3922:\t\t\t * Zoned block devices contain zones that have a sequential\n3923:\t\t\t * write only restriction.  Hence zoned block devices are not\n3924:\t\t\t * suitable for swapping.  Disallow them here.\n3925:\t\t\t */\n3926:\t\t\tif (bdev_is_zoned(si-\u003ebdev))\n3927:\t\t\t\treturn -EINVAL;\n3928:\t\t\tsi-\u003eflags |= SWP_BLKDEV;\n3929:\t\t} else if (S_ISREG(inode-\u003ei_mode)) {\n3930:\t\t\tsi-\u003ebdev = inode-\u003ei_sb-\u003es_bdev;\n3931:\t\t}\n3932:\t\n3933:\t\treturn 0;\n3934:\t}\n"
}

25/3 2026/10/03 10:13 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 30064
							output: 35
							thoughts: 2138
						

Thoughts:
**Xswap Deep Dive: A Security and Performance Review**

Okay, let's break this down systematically. My primary concern here is memory safety and potential vulnerabilities, especially considering this is a swap implementation.

First, in `alloc_swap_info`, the reuse and reset behavior warrants careful review for potential race conditions or uninitialized memory exposure, especially if the reset logic is complex. The initialization of `discard_work` and `reclaim_work` seems standard, so no immediate concerns.

The `xswap_create` function is where things get interesting. The cluster alignment in `maxpages` is a good optimization, ensuring that no cluster holds a slot past si->max. The `__GFP_ZERO` flag is great, all newly mapped pages are allocated as zeroed, which is a critical defense against information leakage. The initialization of the `cluster_info` array with zeroed memory and initialized spinlocks is also good practice, preventing the use of uninitialized values. The initialization of the `mutex` before `xswap_map_clusters()` seems like a standard mutex initialization to avoid race conditions.

Next, `xswap_debugfs_read` is a primary focus. `scnprintf` followed by `simple_read_from_buffer` is a safe pattern. The `scnprintf` call writes into the `tmp` buffer, and the `simple_read_from_buffer` function reads from this buffer with the `len` argument, so only the written memory is exposed to the user, preventing uninitialized memory reads. However, the use of `READ_ONCE` and the potential for a race condition in the while loop is important. The mutex is locked to protect access to the `cluster_info` array, but the check within the loop could potentially lead to inconsistent states, if the `cluster_info` array is changed.

The `xswap_create_store` and `xswap_destroy_store` write-only sysfs attributes are a common design, but should be tested with fuzzing to ensure that invalid input doesn't lead to unexpected behavior. The `swap_show` procfs entry utilizes a safe formatting pattern with `scnprintf` and `seq_puts`, which should prevent format string vulnerabilities or information leakage.

Now, `xswap_unmap_clusters_locked` uses `xswap_unmap_range`. The `xswap_unmap_range` logic initializes the `xpd` struct, including `max` and `nr`, preventing out-of-bounds access. The `apply_to_existing_page_range` function increments `xpd->nr` only when storing a valid page, and the final loop frees memory from `0` to `xpd.nr`. This is a clear memory safety pattern.

Finally, the `swap_read_folio` and `swap_writeout` functions are crucial. The xswap-specific logic uses flags to differentiate between backing store (disk) and xswap. The code checks for SWP_XSWAP and, if it is set, assumes a zswap entry, and then WARNs if the swap entry isn't in zswap. If this check fails, then the folio is unlocked and the function exits. However, `folio_unlock(folio)` followed by a `goto finish` needs further investigation. What are the potential side effects if a zswap load fails or the entry isn't found? The `mm/page_io.c` code around line 486 requires verification to check what happens after the folio is unlocked. A possible race condition could exist at this point.

Overall, the xswap implementation appears to have good practices to prevent common vulnerabilities, but potential race conditions in the debugfs read loop, and the behavior after folio unlocking in `swap_read_folio` warrant further scrutiny. The memory safety design patterns are good, with zeroing and access control checks being common.



26/3 2026/10/03 10:13 tool read-file
0m Args:
{
  "File": "mm/page_io.c",
  "FirstLine": 480,
  "LineCount": 40
}

Results:
{
  "Contents": " 480:\t\t * Count submission time as memory stall and delay. When the device\n 481:\t\t * is congested, or the submitting cgroup IO-throttled, submission\n 482:\t\t * can be a significant part of overall IO time.\n 483:\t\t */\n 484:\t\tif (workingset) {\n 485:\t\t\tdelayacct_thrashing_start(\u0026in_thrashing);\n 486:\t\t\tpsi_memstall_enter(\u0026pflags);\n 487:\t\t}\n 488:\t\tdelayacct_swapin_start();\n 489:\t\n 490:\t\tif (swap_read_folio_zeromap(folio)) {\n 491:\t\t\tfolio_unlock(folio);\n 492:\t\t\tgoto finish;\n 493:\t\t}\n 494:\t\n 495:\t\tif (zswap_load(folio) != -ENOENT)\n 496:\t\t\tgoto finish;\n 497:\t\n 498:\t\tif (unlikely(sis-\u003eflags \u0026 SWP_XSWAP)) {\n 499:\t\t\t/*\n 500:\t\t\t * An xswap entry only ever lives in zswap, so zswap_load()\n 501:\t\t\t * must have found it.  Unlock and let the caller retry.\n 502:\t\t\t */\n 503:\t\t\tWARN_ON_ONCE(1);\n 504:\t\t\tfolio_unlock(folio);\n 505:\t\t\tgoto finish;\n 506:\t\t}\n 507:\t\n 508:\t\t/* We have to read from slower devices. Increase zswap protection. */\n 509:\t\tzswap_folio_swapin(folio);\n 510:\t\tswap_add_folio(ctx, folio, READ);\n 511:\t\n 512:\tfinish:\n 513:\t\tif (workingset) {\n 514:\t\t\tdelayacct_thrashing_end(\u0026in_thrashing);\n 515:\t\t\tpsi_memstall_leave(\u0026pflags);\n 516:\t\t}\n 517:\t\tdelayacct_swapin_end();\n 518:\t}\n 519:\t\n"
}

27/3 2026/10/03 10:13 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 33626
							output: 27
							thoughts: 55
						

Thoughts:
Okay, let me think this through.

**Analyzing the `swap_read_folio` Control Flow**

Hold on a second! I'm focusing on that `swap_read_folio` function, and I need to be meticulous. Specifically, when `swap_read_folio` hits that `goto finish;` statement, the associated `folio` should be unlocked at that point, but is the `folio_test_uptodate(folio)` flag correctly set at that time? That's the critical question. I need to understand that. To verify this, I need to understand the states of the locks and the folios at the time. I'll need to scrutinize what happens *after* the `goto` and how `folio` is handled. Let's trace this back up the call stack. Where is `swap_read_folio` being called from? I need to analyze the calling function's code flow to fully grasp the context and make sure everything is behaving as I expect it to. The caller function is key to solving this.



28/3 2026/10/03 10:13 tool grepper
0m Args:
{
  "Expression": "swap_read_folio",
  "PathPrefix": "mm/"
}

Results:
{
  "Output": "mm/memory.c=4812=static bool can_swapin_thp(struct vm_fault *vmf, pte_t *ptep, int nr_pages)\n--\nmm/memory.c-4824-\t/*\nmm/memory.c:4825:\t * swap_read_folio() can't handle the case a large folio is hybridly\nmm/memory.c-4826-\t * from different backends. And they are likely corner cases. Similar\n--\nmm/page_io.c=412=static int swap_zeromap_batch(swp_entry_t entry, int max_nr,\n--\nmm/page_io.c-433-\nmm/page_io.c:434:static bool swap_read_folio_zeromap(struct folio *folio)\nmm/page_io.c-435-{\n--\nmm/page_io.c-466-\nmm/page_io.c:467:void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio)\nmm/page_io.c-468-{\n--\nmm/page_io.c-489-\nmm/page_io.c:490:\tif (swap_read_folio_zeromap(folio)) {\nmm/page_io.c-491-\t\tfolio_unlock(folio);\n--\nmm/swap.h=256=int sio_pool_init(void);\nmm/swap.h:257:void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio);\nmm/swap.h-258-void swap_read_submit(struct swap_io_ctx *ctx);\n--\nmm/swap.h=376=static inline void folio_put_swap(struct folio *folio, struct page *page)\n--\nmm/swap.h-379-\nmm/swap.h:380:static inline void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio)\nmm/swap.h-381-{\n--\nmm/swap_state.c=694=static struct folio *swap_cache_read_folio(struct swap_io_ctx *ctx,\n--\nmm/swap_state.c-710-\tfolio_add_lru(folio);\nmm/swap_state.c:711:\tswap_read_folio(ctx, folio);\nmm/swap_state.c-712-\tif (readahead) {\n--\nmm/swap_state.c=736=struct folio *swapin_sync(swp_entry_t entry, gfp_t gfp, unsigned long orders,\n--\nmm/swap_state.c-752-\tfolio_add_lru(folio);\nmm/swap_state.c:753:\tswap_read_folio(\u0026ctx, folio);\nmm/swap_state.c-754-\tswap_read_submit(\u0026ctx);\n--\nmm/swapfile.c=3326=EXPORT_SYMBOL_GPL(add_swap_extent);\n--\nmm/swapfile.c-3330- * onto a contiguous range of disk blocks.  A rbtree of swap extents is\nmm/swapfile.c:3331: * built at swapon time and is then used at swap_writeout/swap_read_folio\nmm/swapfile.c-3332- * time for locating where on disk a page belongs.\n--\nmm/swapfile.c=4658=static int xswap_create(int prio)\n--\nmm/swapfile.c-4706-\t * used, by may_enter_fs(); the IO methods are never called because\nmm/swapfile.c:4707:\t * swap_writeout()/swap_read_folio() short circuit xswap.\nmm/swapfile.c-4708-\t */\n"
}

29/3 2026/10/03 10:13 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 34895
							output: 29
							thoughts: 504
						

Thoughts:
**Debugging a Zswap Read Scenario**

Okay, let's break this down. I'm looking at `swap_cache_read_folio` and I see this: `zswap_load(folio)`. If it's found, great, mark it up-to-date and unlock. But if it's *not* found... `WARN_ON_ONCE(1)` and unlock. Wait a second, why would `zswap_load` fail? It *shouldn't* if zswap is managing it. My initial thought is it could only fail if zswap evicted it. But that doesn't make sense.

Let me dig into the zswap code in `mm/zswap.c`. Okay, here we go:

```c
	if (entry->length) {
		INIT_LIST_HEAD(&entry->lru);
		/* No backing store: nothing to write these back to. */
		if (!(__swap_entry_to_info(page_swpentry)->flags & SWP_XSWAP))
			zswap_lru_add(entry);
	}
```

This explains that if the page is not an xswap page, it is added to the zswap LRU. It is not possible for xswap pages to be written back to zswap.

And further down:

```c
static int zswap_writeback_entry(struct zswap_entry *entry,
...
	if (si->flags & SWP_XSWAP) {
		put_swap_device(si);
		return -EINVAL;
	}
```

This confirms my intuition. If a swap entry is marked with SWP_XSWAP, zswap will return an error when it tries to write it back. This also means these pages won't be written back to the LRU.

And this check:

```c
	/*
	 * A folio that zswap will not take must not get an xswap slot. With
	 * no xswap device to route away from, skip the lookup.
	 */
	if (atomic_read(&nr_xswap_files)) {
		objcg = get_obj_cgroup_from_folio(folio);
		may_zswap = !objcg || obj_cgroup_may_zswap(objcg);
		if (objcg)
			obj_cgroup_put(objcg);
	}
```

This seems to be saying that folios are only eligible for xswap if zswap can't handle them. And if they're *not* in zswap's purview, they *won't* be added to the zswap LRU. They won't be written back. So the WARN_ON_ONCE in `swap_cache_read_folio` should be impossible.

So, if `swap_read_folio` hits the `WARN_ON_ONCE`, the folio is *not* marked up-to-date. That's the key. That implies that in page fault handling, we are handling a folio that is not uptodate. What happens then? I need to check the callers of `swap_cache_read_folio` or `do_swap_page` to trace the control flow and see how we're handling this "not up-to-date" folio. I'm pretty sure I see the bug now, but I need to see *how* it's handled to understand *why*.



30/3 2026/10/03 10:14 tool grepper
0m Args:
{
  "Expression": "swap_cache_read_folio",
  "PathPrefix": "mm/"
}

Results:
{
  "Output": "mm/swap_state.c=661=void swap_update_readahead(struct folio *folio, struct vm_area_struct *vma,\n--\nmm/swap_state.c-693-\nmm/swap_state.c:694:static struct folio *swap_cache_read_folio(struct swap_io_ctx *ctx,\nmm/swap_state.c-695-\t\tswp_entry_t entry, gfp_t gfp, struct mempolicy *mpol,\n--\nmm/swap_state.c=764=struct folio *read_swap_cache_async(struct swap_io_ctx *ctx, swp_entry_t entry,\n--\nmm/swap_state.c-776-\tmpol = get_vma_policy(vma, addr, 0, \u0026ilx);\nmm/swap_state.c:777:\tfolio = swap_cache_read_folio(ctx, entry, gfp_mask, mpol, ilx, false);\nmm/swap_state.c-778-\tmpol_cond_put(mpol);\n--\nmm/swap_state.c-783-\nmm/swap_state.c:784:static struct folio *swap_cache_read_folio_sync(swp_entry_t entry, gfp_t gfp,\nmm/swap_state.c-785-\t\tstruct mempolicy *mpol, pgoff_t ilx)\n--\nmm/swap_state.c-789-\nmm/swap_state.c:790:\tfolio = swap_cache_read_folio(\u0026ctx, entry, gfp, mpol, ilx, false);\nmm/swap_state.c-791-\tswap_read_submit(\u0026ctx);\n--\nmm/swap_state.c=874=struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask,\n--\nmm/swap_state.c-906-\t\tra_entry = swp_entry(swp_type(entry), offset);\nmm/swap_state.c:907:\t\tfolio = swap_cache_read_folio(\u0026ctx, ra_entry, gfp_mask, mpol,\nmm/swap_state.c-908-\t\t\t\tilx, offset != entry_offset);\n--\nmm/swap_state.c-915-skip:\nmm/swap_state.c:916:\treturn swap_cache_read_folio_sync(entry, gfp_mask, mpol, ilx);\nmm/swap_state.c-917-}\n--\nmm/swap_state.c=973=static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask,\n--\nmm/swap_state.c-1020-\t\t}\nmm/swap_state.c:1021:\t\tfolio = swap_cache_read_folio(\u0026ctx, entry, gfp_mask, mpol, ilx,\nmm/swap_state.c-1022-\t\t\t\t\t      addr != vmf-\u003eaddress);\n--\nmm/swap_state.c-1034-\t/* The folio was likely read above, so no need for plugging here */\nmm/swap_state.c:1035:\treturn swap_cache_read_folio_sync(targ_entry, gfp_mask, mpol, targ_ilx);\nmm/swap_state.c-1036-}\n"
}

31/3 2026/10/03 10:14 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 37051
							output: 32
							thoughts: 28
						

Thoughts:
Okay, here's my take on those thoughts, framed as my own mental processing as an expert:

**Diving into `do_swap_page` – The Aftermath of a Swap Folio Read**

Alright, so I'm in `do_swap_page` in `mm/memory.c`. I've just pulled a folio from swap space. Now, the real question is: *what's the immediate state of things after that read?* What are the implications of successfully retrieving this swapped data? My brain immediately starts running through the scenarios... I'm thinking about the implications for page table entries, the cache status, and overall memory management integrity. What needs to be updated? Does this trigger any further actions on the VM side, such as cache revalidation or demand paging? We've successfully fetched the folio from disk but what's next? This is the core logic that I need to thoroughly understand in order to be able to make any effective changes. I'm keen to examine exactly how the system ensures that the data is now correctly integrated back into the running processes and how it is updated on both the active and inactive page lists. Time to delve into the code!



32/3 2026/10/03 10:14 tool grepper
0m Args:
{
  "Expression": "folio_test_uptodate",
  "PathPrefix": "mm/memory.c"
}

Results:
{
  "Output": "mm/memory.c=4943=vm_fault_t do_swap_page(struct vm_fault *vmf)\n--\nmm/memory.c-5112-\nmm/memory.c:5113:\tif (unlikely(!folio_test_uptodate(folio))) {\nmm/memory.c-5114-\t\tret = VM_FAULT_SIGBUS;\n"
}

33/3 2026/10/03 10:14 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 37468
							output: 474
							thoughts: 3855
						

Thoughts:
**KMSAN Applicability Analysis for XSWAP Patch**

Okay, let's break this down. My analysis indicates that this patch *doesn't* introduce any risks that necessitate KMSAN (Kernel Memory Sanitizer).  I've gone through the code meticulously to pinpoint any potential issues.

Firstly, the most immediate check is whether any uninitialized memory is *read*. The `folio_test_uptodate` check immediately returns SIGBUS if a folio isn't up to date, avoiding uninitialized memory access in that function. Regarding `cluster_info` memory management, in xswap, the `cluster_info` memory is allocated using `vmalloc`, which has its own initialization. The important point here is that every allocated page is guaranteed to be zeroed via `__GFP_ZERO`.  Furthermore, all spinlocks are explicitly initialized with `spin_lock_init`. The map and unmap operations meticulously handle page allocation, zeroing, and freeing. Any access to unmapped memory results in a page fault (kernel crash/oops), which falls under out-of-bounds (OOB) access, not uninitialized memory read.

I've also meticulously examined all the variables within `xswap_map_clusters` and related functions. The `alloc_page` calls are followed by explicit checks to avoid operating on uninitialized memory, and free pages.  Even in failure paths, the code carefully frees allocated pages, preventing any uninitialized reads.

The `xswap_collect_page` and `xswap_unmap_range` functions deal with collecting and freeing pages, specifically handling data structures. In this case, `pages` is allocated on the stack (when in a batch) or uses `kvmalloc_array` and the uninitialized parts of `batch_pages` are never read.

When it comes to the debug output functions like `xswap_debugfs_read` and `swap_show`, they format strings with `scnprintf` and copy with `simple_read_from_buffer` and `seq_puts` respectively.  These format output strings and don't introduce any uninitialized memory concerns.

Now, considering the KMSAN guidance:  KMSAN is for finding uninitialized *reads* or kernel-to-user memory leaks.  KASAN, LOCKDEP, and standard bug detectors are already excellent for identifying things like out-of-bounds accesses, use-after-free conditions, locking issues, and other common kernel bugs.  My analysis shows this patch only potentially introduces bugs handled by existing sanitizers.

Looking at the specific KMSAN conditions:

1.  **Kernel structures sent to userspace:**  There aren't any structures directly copied to userspace. Debug and procfs output are formatted strings with no risk.
2.  **Conditional logic based on uninitialized variables:** There is no branch that depends on uninitialized variables.
3.  **Uninitialized data structure allocations:** All allocated data structures, especially `cluster_info` pages, are zeroed or explicitly initialized, preventing uninitialized reads.
4.  **Bounds checks exposing uninitialized data:** There aren't any cases.

So, the potential bugs in this patch boil down to: concurrency (race conditions), dereferencing unmapped addresses (page faults), use-after-free, and arithmetic overflows/underflows. **These are all bugs that are detected by existing kernel sanitizers**. No data is allocated on either the stack or heap that isn't fully initialized prior to usage. The xswap code handles error conditions gracefully to prevent information leaks.

Therefore, because this patch *doesn't* introduce uninitialized memory usage or information leaks, and because KASAN, LOCKDEP, and other bug detectors will handle all the risks, I conclude that `NeedsKMSAN = false`.  This aligns perfectly with the instructions provided, and I will call set-results with this detailed rationale.



34/3 2026/10/03 10:14 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch introduces CONFIG_XSWAP, an extendable virtual swap device that relies on zswap without physical backing storage, dynamically mapping and unmapping cluster_info metadata via a sparse vmalloc area (VM_SPARSE).\n\n1. Memory Initialization:\n- All pages backing the cluster_info array are explicitly allocated using `alloc_page(... | __GFP_ZERO)`, ensuring all `struct swap_cluster_info` structures start fully zeroed before use. All spinlocks within these structures are initialized using `spin_lock_init()`.\n- The `swap_info_struct` is zero-allocated via `kvzalloc_obj()` in `alloc_swap_info()`, and all newly added fields under CONFIG_XSWAP (`cluster_vm`, `nr_clusters_max`, `nr_clusters_mapped`, `xswap_lock`, `xswap_shrink_work`, `xswap_grows`, `xswap_shrinks`) are explicitly initialized upon device creation.\n\n2. User-Space Exposure / Info-Leaks:\n- The sysfs interfaces (`create` and `destroy`) are write-only handlers that parse scalar input via `kstrtoint` and `kstrtoul`.\n- Procfs (`/proc/swaps`) and debugfs (`/sys/kernel/debug/xswap/type*`) read handlers format their output into stack buffers using `scnprintf()` and copy only the formatted length via `seq_puts()` or `simple_read_from_buffer()`. No kernel structures or uninitialized buffer paddings are copied to user space.\n\n3. KASAN vs KMSAN Applicability:\n- Any risks introduced by this change relate to VM_SPARSE page mapping/unmapping concurrency, RCU synchronization, locking between grow/shrink/swapoff, or invalid address dereferences if an unmapped cluster is accessed. These are detected by KASAN, LOCKDEP, or the kernel's fault handler.\n- There are no uninitialized stack/heap reads, uninitialized memory branch conditions, or info-leak risks that would specifically necessitate a dedicated KMSAN session.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch introduces CONFIG_XSWAP, an extendable virtual swap device that relies on zswap without physical backing storage, dynamically mapping and unmapping cluster_info metadata via a sparse vmalloc area (VM_SPARSE).\n\n1. Memory Initialization:\n- All pages backing the cluster_info array are explicitly allocated using `alloc_page(... | __GFP_ZERO)`, ensuring all `struct swap_cluster_info` structures start fully zeroed before use. All spinlocks within these structures are initialized using `spin_lock_init()`.\n- The `swap_info_struct` is zero-allocated via `kvzalloc_obj()` in `alloc_swap_info()`, and all newly added fields under CONFIG_XSWAP (`cluster_vm`, `nr_clusters_max`, `nr_clusters_mapped`, `xswap_lock`, `xswap_shrink_work`, `xswap_grows`, `xswap_shrinks`) are explicitly initialized upon device creation.\n\n2. User-Space Exposure / Info-Leaks:\n- The sysfs interfaces (`create` and `destroy`) are write-only handlers that parse scalar input via `kstrtoint` and `kstrtoul`.\n- Procfs (`/proc/swaps`) and debugfs (`/sys/kernel/debug/xswap/type*`) read handlers format their output into stack buffers using `scnprintf()` and copy only the formatted length via `seq_puts()` or `simple_read_from_buffer()`. No kernel structures or uninitialized buffer paddings are copied to user space.\n\n3. KASAN vs KMSAN Applicability:\n- Any risks introduced by this change relate to VM_SPARSE page mapping/unmapping concurrency, RCU synchronization, locking between grow/shrink/swapoff, or invalid address dereferences if an unmapped cluster is accessed. These are detected by KASAN, LOCKDEP, or the kernel's fault handler.\n- There are no uninitialized stack/heap reads, uninitialized memory branch conditions, or info-leak risks that would specifically necessitate a dedicated KMSAN session.",
  "NeedsKMSAN": false
}

LLM Calls Summary:
Total Calls Total Tokens Avg Tokens Total Duration (Seconds) Avg Duration (Seconds)
Tool Calls Summary:
Total Calls Total Duration (Seconds) Avg Duration (Seconds)