AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/11/11 22:18 flow patch-triage
3m Args:
null

Results:
{
  "EnableConfigs": [
    "XSWAP",
    "ZSWAP",
    "ZSWAP_DEFAULT_ON",
    "SWAP"
  ],
  "FocusSymbols": [
    "xswap_create",
    "xswap_destroy",
    "xswap_create_store",
    "xswap_destroy_store",
    "xswap_grow",
    "xswap_try_shrink",
    "xswap_shrink_work_fn",
    "xswap_map_clusters",
    "xswap_unmap_clusters",
    "xswap_destroy_by_name"
  ],
  "KMSANReasoning": "The patch series introduces 'xswap', an extendable file-less swap device backed by zswap using a sparse vmalloc area (VM_SPARSE) to dynamically allocate and map swap cluster metadata (swap_cluster_info) in chunks.\n\nAn evaluation of memory sanitizer applicability indicates that a dedicated KMSAN fuzzing session is not warranted:\n1. No uninitialized memory exposure to userspace: The new sysfs interfaces ('create' and 'destroy') are write-only (mode 0200), and debugfs/procfs interfaces ('/sys/kernel/debug/xswap/xswap\u003cid\u003e' and '/proc/swaps') format plain text output exclusively using scnprintf() and seq_printf()/seq_puts() bounded by returned string lengths. There are no binary kernel structs or padding copied to userspace via copy_to_user, put_user, netlink, or ioctl.\n2. Initialization of all newly allocated buffers and structures: The sparse backing pages for swap_cluster_info are allocated with alloc_page(... | __GFP_ZERO), ensuring all pointer and integer fields start fully zeroed. Cluster spinlocks are explicitly initialized via spin_lock_init() upon mapping. All new struct swap_info_struct fields, stack buffers (e.g., in xswap_parse_size, xswap_destroy_by_name, xswap_debugfs_read), and work structs are properly initialized before use.\n3. No branching or logic dependent on uninitialized data: In the swap fast/slow allocation and readahead paths, new branching flags (such as may_zswap and zswap_checked) are explicitly initialized locals.\n4. Nature of potential risks: The failure modes and risks introduced by this change center around locking hierarchies (xswap_lock, swap_lock, si-\u003elock, ci-\u003elock), RCU grace period synchronization during cluster unmapping, and concurrency races between growth, shrinking, swapoff, and folio allocation/swapin. These are standard locking, use-after-free, and out-of-bounds risks that are fully covered by KASAN, LOCKDEP, and page fault handling.\n\nBecause there are no uninitialized memory risks or info-leaks unique to KMSAN, a dedicated KMSAN run is not justified.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch introduces xswap, a file-less virtual swap device backed by zswap, into the core memory management subsystem. It adds new sysfs interfaces (/sys/kernel/mm/xswap/create and destroy), modifies the swapoff syscall, and adds complex dynamic allocation, growing, and shrinking logic using VM_SPARSE vmalloc areas, RCU synchronization, and workqueues. These reachable code paths in core mm should be fuzzed for concurrency issues, memory leaks, and invariant violations.",
  "WorthFuzzing": true
}

1/1 2026/11/11 22:18 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit 21d9e31bbc41c3f61fd71c0b9d6875ed18c6cfc9\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Wed Nov 11 22:18:28 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/Documentation/ABI/testing/sysfs-kernel-mm-xswap b/Documentation/ABI/testing/sysfs-kernel-mm-xswap\nnew file mode 100644\nindex 00000000000000..f7e7f3e4d2164d\n--- /dev/null\n+++ b/Documentation/ABI/testing/sysfs-kernel-mm-xswap\n@@ -0,0 +1,43 @@\n+What:\t\t/sys/kernel/mm/xswap/\n+Date:\t\tOctober 2026\n+Contact:\tLinux memory management mailing list \u003clinux-mm@kvack.org\u003e\n+Description:\tFile-less swap devices backed by zswap.\n+\n+\t\tAn xswap device has no backing file.  Its slots are backed\n+\t\tby the zswap pool, and the device size is set at boot with\n+\t\txswap.max= or CONFIG_XSWAP_DEFAULT_MAX.  The size is fixed\n+\t\tfor the lifetime of the device.\n+\n+\t\tThe name shown in /proc/swaps, xswap\u003cid\u003e, is synthetic and\n+\t\tis not a path. swapoff(2) accepts it, so both \"swapoff\n+\t\txswap\u003cid\u003e\" and swapoff -a tear the device down. A real\n+\t\tfile or directory with that name takes precedence: if it\n+\t\topens, it is looked up as a swap file and the synthetic\n+\t\tdevice is not used. Only a name that cannot be opened\n+\t\tbecause it does not exist, including a dangling symlink,\n+\t\tis treated as an xswap device. Use the destroy attribute\n+\t\tfor an unambiguous teardown.\n+\n+\t\tAn xswap device requires zswap.  Disabling zswap at runtime\n+\t\t(enabled=0, or max_pool_percent=0) while xswap devices\n+\t\texist leaves them without backing: existing entries can\n+\t\tstill be read, but new pages cannot be stored.  Destroy the\n+\t\txswap devices before disabling zswap.\n+\n+What:\t\t/sys/kernel/mm/xswap/create\n+Date:\t\tOctober 2026\n+Contact:\tLinux memory management mailing list \u003clinux-mm@kvack.org\u003e\n+Description:\tCreate an xswap device.\n+\n+\t\tWrite an optional priority (0..32767), or write nothing for\n+\t\tthe default priority.  The write fails if zswap is disabled\n+\t\tor if the configured size is smaller than one cluster.\n+\n+What:\t\t/sys/kernel/mm/xswap/destroy\n+Date:\t\tOctober 2026\n+Contact:\tLinux memory management mailing list \u003clinux-mm@kvack.org\u003e\n+Description:\tDestroy an xswap device.\n+\n+\t\tWrite the device's stable id.  The id is the number after\n+\t\t\"xswap\" in /proc/swaps, for example 1 for xswap1.  It is\n+\t\tnot a swap type and is never reused.\ndiff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt\nindex a1fb40e5000977..95b5ba9ee4f8aa 100644\n--- a/Documentation/admin-guide/kernel-parameters.txt\n+++ b/Documentation/admin-guide/kernel-parameters.txt\n@@ -8752,3 +8752,11 @@ Kernel parameters\n \t\t\t\tmemory, and other data can't be written using\n \t\t\t\txmon commands.\n \t\t\toff\txmon is disabled.\n+\n+\txswap.max=\t[KNL,SWAP]\n+\t\t\tMaximum size of a new xswap device. The value is a\n+\t\t\tsize in bytes with an optional KMGTPE suffix, a\n+\t\t\tpercentage of RAM, or \"max\" for the largest size\n+\t\t\tthe device can address. The default is set by\n+\t\t\tCONFIG_XSWAP_DEFAULT_MAX.\n+\t\t\tFormat: \u003csize\u003e[KMGTPE] | \u003cpercent\u003e% | max\ndiff --git a/Documentation/admin-guide/mm/zswap.rst b/Documentation/admin-guide/mm/zswap.rst\nindex 2464425c783de2..886b50ca90b1ae 100644\n--- a/Documentation/admin-guide/mm/zswap.rst\n+++ b/Documentation/admin-guide/mm/zswap.rst\n@@ -136,3 +136,12 @@ selected.\n A debugfs interface is provided for various statistic about pool size, number\n of pages stored, same-value filled pages and various counters for the reasons\n pages are rejected.\n+\n+xswap devices\n+-------------\n+\n+An xswap device is a file-less swap device backed by zswap.  While such a\n+device exists, do not disable zswap at runtime (``enabled=0``) or set\n+``max_pool_percent`` to 0.  The device would have no backing: pages already\n+in zswap can still be read, but new pages cannot be stored.  Destroy the\n+xswap devices first.\ndiff --git a/MAINTAINERS b/MAINTAINERS\nindex ce05a3253baaea..c97ecdd39a8a56 100644\n--- a/MAINTAINERS\n+++ b/MAINTAINERS\n@@ -17907,6 +17907,7 @@ R:\tYoungjun Park \u003cyoungjun.park@lge.com\u003e\n L:\tlinux-mm@kvack.org\n S:\tMaintained\n F:\tDocumentation/ABI/testing/sysfs-kernel-mm-swap\n+F:\tDocumentation/ABI/testing/sysfs-kernel-mm-xswap\n F:\tDocumentation/mm/swap-table.rst\n F:\tinclude/linux/swap.h\n F:\tinclude/linux/swap_ops.h\ndiff --git a/include/linux/swap.h b/include/linux/swap.h\nindex 4f686709d71f00..1e552a8b421b68 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,26 @@ 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+\tu64\t\t\txswap_id;\t/* stable id, shown to userspace */\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 +390,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 afff1b25b54387..902e3b1a6e35cc 100644\n--- a/mm/Kconfig\n+++ b/mm/Kconfig\n@@ -122,6 +122,26 @@ 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 is mapped lazily\n+\t  in chunks, avoiding static pre-allocation overhead.\n+\n+config XSWAP_DEFAULT_MAX\n+\tstring \"Default maximum size of a new xswap device\"\n+\tdepends on XSWAP\n+\tdefault \"200%\"\n+\thelp\n+\t  The maximum size of a newly created xswap device. It accepts a\n+\t  percentage of RAM (for example \"200%\"), a size (for example \"2T\"),\n+\t  or \"max\" for the largest size the device can address.\n+\n+\t  xswap.max= on the kernel command line overrides this value.\n+\n config ZSMALLOC\n \ttristate\n \ndiff --git a/mm/page_io.c b/mm/page_io.c\nindex a57cdcf2892dfa..2285fb1735b383 100644\n--- a/mm/page_io.c\n+++ b/mm/page_io.c\n@@ -258,6 +258,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@@ -515,6 +524,16 @@ void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio)\n \tif (zswap_load(folio) != -ENOENT)\n \t\treturn;\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\treturn;\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 da65d75ceead12..4c965cf99809be 100644\n--- a/mm/swap_state.c\n+++ b/mm/swap_state.c\n@@ -899,6 +899,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@@ -984,6 +988,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@@ -992,6 +997,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 fcda5eba171402..2d6c13d510672d 100644\n--- a/mm/swapfile.c\n+++ b/mm/swapfile.c\n@@ -14,8 +14,11 @@\n #include \u003clinux/mman.h\u003e\n #include \u003clinux/slab.h\u003e\n #include \u003clinux/kernel_stat.h\u003e\n+#include \u003clinux/overflow.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@@ -31,6 +34,7 @@\n #include \u003clinux/backing-dev.h\u003e\n #include \u003clinux/mutex.h\u003e\n #include \u003clinux/capability.h\u003e\n+#include \u003clinux/ctype.h\u003e\n #include \u003clinux/syscalls.h\u003e\n #include \u003clinux/memcontrol.h\u003e\n #include \u003clinux/poll.h\u003e\n@@ -42,6 +46,7 @@\n #include \u003clinux/suspend.h\u003e\n #include \u003clinux/zswap.h\u003e\n #include \u003clinux/plist.h\u003e\n+#include \u003clinux/debugfs.h\u003e\n \n #include \u003casm/tlbflush.h\u003e\n #include \u003clinux/leafops.h\u003e\n@@ -49,6 +54,260 @@\n #include \"internal.h\"\n #include \"swap.h\"\n \n+#define DEF_SWAP_PRIO  -1\n+\n+/*\n+ * The highest priority a real swap device can use: one ahead of xswap\n+ * would take the page directly, and taking that slot is what xswap\n+ * exists to avoid.  At equal priority the list is FIFO, so a real device\n+ * that asks for this priority too and is added first wins.\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+/* 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+ * Shrink thresholds, as a percentage of the mapped range in use.  The stop\n+ * point sits inside (SHRINK_WHEN, GROW_WHEN), so shrinking cannot leave the\n+ * range in a state that wakes the grow up.\n+ */\n+#define XSWAP_SHRINK_WHEN\t50\n+#define XSWAP_SHRINK_UNTIL\t70\n+\n+/*\n+ * Grow thresholds, as a percentage of the mapped range in use.  The target\n+ * sits above the point where the shrink starts looking (50%) and below the\n+ * next grow trigger (85%), so a grow cannot leave the range in a state the\n+ * shrink would undo.\n+ */\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+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(u64 id);\n+static int xswap_destroy_by_name(const char *name);\n+\n+/* Stable device id, assigned at create and never reused. */\n+static atomic64_t xswap_id_counter = ATOMIC64_INIT(0);\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+\tconst char *p;\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+\tp = skip_spaces(buf);\n+\tif (*p \u0026\u0026 *p != '\\n') {\n+\t\terr = kstrtoint(p, 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+\tu64 id;\n+\tint err;\n+\n+\tif (!capable(CAP_SYS_ADMIN))\n+\t\treturn -EPERM;\n+\n+\terr = kstrtoull(buf, 0, \u0026id);\n+\tif (err)\n+\t\treturn err;\n+\n+\terr = xswap_destroy(id);\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+/*\n+ * Size of a new device, from xswap.max=.  A percentage unless bytes is\n+ * set; \"max\" asks for the largest size the device can address.\n+ */\n+static unsigned int xswap_size_pct = 200;\n+static unsigned long xswap_size_bytes;\n+static bool xswap_size_max;\n+static bool xswap_size_set;\t/* xswap.max= was given */\n+\n+/*\n+ * Parse \"200%\", \"2T\" or \"max\". @str is not modified. @cmdline tells an\n+ * explicit xswap.max= from the build-time default, which is clamped\n+ * instead of refused when it is too large.\n+ */\n+static int __init xswap_parse_size(const char *str, const char *what,\n+\t\t\t\t   bool cmdline)\n+{\n+\tconst char *pct;\n+\tchar buf[16];\n+\tunsigned int pct_val;\n+\tunsigned long bytes;\n+\tchar *end;\n+\n+\tpct = strchr(str, '%');\n+\tif (!strcmp(str, \"max\")) {\n+\t\txswap_size_max = true;\n+\t\txswap_size_pct = 0;\n+\t\txswap_size_bytes = 0;\n+\t} else if (pct) {\n+\t\tsize_t len = pct - str;\n+\n+\t\tif (pct[1] || !len || len \u003e= sizeof(buf))\n+\t\t\tgoto bad;\n+\t\tmemcpy(buf, str, len);\n+\t\tbuf[len] = '\\0';\n+\t\tif (kstrtouint(buf, 0, \u0026pct_val) || !pct_val)\n+\t\t\tgoto bad;\n+\t\txswap_size_pct = pct_val;\n+\t\txswap_size_bytes = 0;\n+\t\txswap_size_max = false;\n+\t} else {\n+\t\tbytes = memparse(str, \u0026end);\n+\t\tif (*end || bytes \u003c PAGE_SIZE)\n+\t\t\tgoto bad;\n+\t\t/* A default below one cluster would fail every create. */\n+\t\tif (!cmdline \u0026\u0026 bytes \u003c (unsigned long)SWAPFILE_CLUSTER * PAGE_SIZE)\n+\t\t\tgoto bad;\n+\t\txswap_size_bytes = bytes;\n+\t\txswap_size_pct = 0;\n+\t\txswap_size_max = false;\n+\t}\n+\n+\tif (cmdline)\n+\t\txswap_size_set = true;\n+\treturn 0;\n+bad:\n+\tpr_err(\"xswap: bad %s=%s\\n\", what, str);\n+\treturn -EINVAL;\n+}\n+\n+static int __init xswap_max_setup(char *str)\n+{\n+\txswap_parse_size(str, \"xswap.max\", true);\n+\treturn 1;\n+}\n+__setup(\"xswap.max=\", xswap_max_setup);\n+\n+/*\n+ * The most a device can address, whatever xswap.max= asked for.  An xswap\n+ * slot is still a swap entry, so the swap offset limit applies even though\n+ * the data never goes through a physical address.\n+ */\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+\tunsigned long long pages;\n+\n+\tif (xswap_size_max)\n+\t\treturn xswap_size_limit();\n+\n+\tif (xswap_size_bytes)\n+\t\treturn xswap_size_bytes \u003e\u003e PAGE_SHIFT;\n+\n+\t/* Let xswap_create() refuse a size that does not fit in the type. */\n+\tif (check_mul_overflow((unsigned long long)totalram_pages(),\n+\t\t\t       (unsigned long long)xswap_size_pct, \u0026pages))\n+\t\treturn ULONG_MAX;\n+\n+\treturn div_u64(pages, 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+\n+static inline int xswap_destroy_by_name(const char *name)\n+{\n+\treturn -ENOENT;\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 static bool folio_swapcache_freeable(struct folio *folio);\n@@ -66,6 +325,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 +336,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 +663,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@@ -654,6 +915,16 @@ 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/*\n+\t * Only xswap devices, and not while the device is being torn down.\n+\t * A racing swapoff can still clear SWP_WRITEOK after this check;\n+\t * the work function checks it again, so a late schedule is benign.\n+\t */\n+\tif ((READ_ONCE(si-\u003eflags) \u0026 (SWP_XSWAP | SWP_WRITEOK)) ==\n+\t    (SWP_XSWAP | SWP_WRITEOK))\n+\t\tschedule_work(\u0026si-\u003exswap_shrink_work);\n+#endif\n }\n \n /*\n@@ -775,7 +1046,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@@ -852,7 +1124,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@@ -1034,11 +1306,12 @@ static bool swap_prefer_free_cluster(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@@ -1048,6 +1321,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@@ -1076,6 +1352,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@@ -1085,12 +1362,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@@ -1119,6 +1396,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@@ -1143,6 +1423,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@@ -1173,7 +1454,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@@ -1182,6 +1463,18 @@ 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 (si-\u003eflags \u0026 SWP_WRITEOK) \u0026\u0026\n+\t    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@@ -1254,6 +1547,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@@ -1277,6 +1576,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@@ -1310,6 +1614,14 @@ static void add_to_avail_list(struct swap_info_struct *si, bool swapon)\n \tif (swapon) {\n \t\tlockdep_assert_held(\u0026si-\u003elock);\n \t\tsi-\u003eflags |= SWP_WRITEOK;\n+\t\t/*\n+\t\t * Count the device here, not after adding it to the list: a\n+\t\t * full device is still active and skips the add below.\n+\t\t */\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} else {\n \t\tif (!(READ_ONCE(si-\u003eflags) \u0026 SWP_WRITEOK))\n \t\t\tgoto skip;\n@@ -1323,10 +1635,11 @@ static void add_to_avail_list(struct swap_info_struct *si, bool swapon)\n \t/*\n \t * When device is full and device is on the plist, only one updater will\n \t * see (inuse_pages == si-\u003epages) and will call del_from_avail_list. If\n-\t * that updater happen to be here, just skip adding.\n+\t * that updater happen to be here, just skip adding.  @val still has\n+\t * the off-list bit, so compare its counter part.\n \t */\n \tpages = si-\u003epages;\n-\tif (val == pages) {\n+\tif ((val \u0026 SWAP_USAGE_COUNTER_MASK) == pages) {\n \t\t/* Just like the cmpxchg in del_from_avail_list */\n \t\tif (atomic_long_try_cmpxchg(\u0026si-\u003einuse_pages, \u0026pages,\n \t\t\t\t\t    pages | SWAP_USAGE_OFFLIST_BIT))\n@@ -1431,21 +1744,51 @@ 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+#ifdef CONFIG_XSWAP\n+\tif (si-\u003eflags \u0026 SWP_XSWAP) {\n+\t\t/*\n+\t\t * The cached offset can outlive a shrink that did not see\n+\t\t * it, and the cluster_info page it indexes may be unmapped.\n+\t\t * Fail the fast path; the slow path picks a live cluster.\n+\t\t */\n+\t\tunsigned long mapped;\n+\n+\t\t/* Pairs with the release store in xswap_unmap_clusters_locked(). */\n+\t\tmapped = smp_load_acquire(\u0026si-\u003enr_clusters_mapped);\n+\n+\t\tif (offset / SWAPFILE_CLUSTER \u003e= mapped) {\n+\t\t\tput_swap_device(si);\n+\t\t\trcu_read_unlock();\n+\t\t\treturn false;\n+\t\t}\n+\t}\n+#endif\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@@ -1457,17 +1800,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@@ -1790,6 +2140,17 @@ static int swap_dup_entries_cluster(struct swap_info_struct *si,\n \treturn err;\n }\n \n+/* Can the folio's cgroup take another zswap page? */\n+static bool folio_may_zswap(struct folio *folio)\n+{\n+\tstruct obj_cgroup *objcg = get_obj_cgroup_from_folio(folio);\n+\tbool may_zswap = !objcg || obj_cgroup_may_zswap(objcg);\n+\n+\tif (objcg)\n+\t\tobj_cgroup_put(objcg);\n+\treturn may_zswap;\n+}\n+\n /**\n  * folio_alloc_swap - allocate swap space for a folio\n  * @folio: folio we want to move to swap\n@@ -1806,10 +2167,23 @@ int folio_alloc_swap(struct folio *folio)\n {\n \tunsigned int order = folio_order(folio);\n \tunsigned int size = 1 \u003c\u003c order;\n+\t/* True unless the gate below finds an xswap device to route away from. */\n+\tbool may_zswap = true;\n+\tbool zswap_checked = false;\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; a device that\n+\t * appears before we pick one is handled after the allocation.\n+\t */\n+\tif (atomic_read(\u0026nr_xswap_files)) {\n+\t\tmay_zswap = folio_may_zswap(folio);\n+\t\tzswap_checked = true;\n+\t}\n+\n \tif (order) {\n \t\t/*\n \t\t * Reject large allocation when THP_SWAP is disabled. Check below\n@@ -1830,8 +2204,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@@ -1839,6 +2213,22 @@ int folio_alloc_swap(struct folio *folio)\n \t\t\tgoto again;\n \t}\n \n+\t/*\n+\t * The xswap gate was skipped because there was no device when we\n+\t * looked. One may have appeared since; check before keeping the\n+\t * xswap slot the allocator may have picked.\n+\t */\n+\tif (unlikely(!zswap_checked \u0026\u0026 atomic_read(\u0026nr_xswap_files) \u0026\u0026\n+\t\t     folio_test_swapcache(folio) \u0026\u0026\n+\t\t     (__swap_entry_to_info(folio-\u003eswap)-\u003eflags \u0026 SWP_XSWAP))) {\n+\t\tzswap_checked = true;\n+\t\tmay_zswap = folio_may_zswap(folio);\n+\t\tif (!may_zswap) {\n+\t\t\tswap_cache_del_folio(folio);\n+\t\t\tgoto again;\n+\t\t}\n+\t}\n+\n \t/* Need to call this even if allocation failed, for MEMCG_SWAP_FAIL. */\n \tif (unlikely(mem_cgroup_try_charge_swap(folio))) {\n \t\tswap_cache_del_folio(folio);\n@@ -2249,8 +2639,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@@ -2260,6 +2653,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@@ -2301,6 +2695,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@@ -2488,6 +2885,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@@ -2527,9 +2926,15 @@ unsigned int count_swap_pages(int type, int free)\n \n \t\tspin_lock(\u0026sis-\u003elock);\n \t\tif (sis-\u003eflags \u0026 SWP_WRITEOK) {\n-\t\t\tn = sis-\u003epages;\n-\t\t\tif (free)\n-\t\t\t\tn -= swap_usage_in_pages(sis);\n+\t\t\t/* Hibernation only; it never selects an xswap device. */\n+\t\t\tif (unlikely(sis-\u003eflags \u0026 SWP_XSWAP)) {\n+\t\t\t\tWARN_ON_ONCE(1);\n+\t\t\t\tn = 0;\n+\t\t\t} else {\n+\t\t\t\tn = sis-\u003epages;\n+\t\t\t\tif (free)\n+\t\t\t\t\tn -= swap_usage_in_pages(sis);\n+\t\t\t}\n \t\t}\n \t\tspin_unlock(\u0026sis-\u003elock);\n \t}\n@@ -2850,14 +3255,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@@ -2865,11 +3287,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@@ -2879,13 +3301,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@@ -2895,7 +3317,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@@ -2905,7 +3326,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@@ -3193,20 +3614,72 @@ 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/*\n+\t\t * Pairs with the smp_store_release() in xswap_map_clusters().\n+\t\t * A grow may publish after this read, but no slot comes from\n+\t\t * those clusters once WRITEOK is clear.  Cached clusters are\n+\t\t * inside the range; try_to_unuse()'s rescan catches any slot\n+\t\t * taken after the walk.\n+\t\t */\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\t/* A late schedule must not be pending when the work is reinitialized. */\n+\t\tdisable_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/*\n+\t\t * free_vm_area() drops the mapping without freeing the\n+\t\t * pages, and the unmap helper handles an empty range.\n+\t\t */\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@@ -3218,11 +3691,14 @@ 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- * Called after swap device's reference count is dead, so\n- * neither scan nor allocation will use it.\n+ * Invalidate the per-cpu cluster cache for @si.  A caller that has not\n+ * already killed @si-\u003eusers and waited must follow with synchronize_rcu()\n+ * before unmapping cluster_info, since a reader may already have loaded\n+ * a cached offset.\n  */\n static void flush_percpu_swap_cluster(struct swap_info_struct *si)\n {\n@@ -3231,25 +3707,20 @@ static void flush_percpu_swap_cluster(struct swap_info_struct *si)\n \n \tfor_each_possible_cpu(cpu) {\n \t\tpcp_si = per_cpu_ptr(percpu_swap_cluster.si, cpu);\n-\t\t/*\n-\t\t * Invalidate the percpu swap cluster cache, si-\u003eusers\n-\t\t * is dead, so no new user will point to it, just flush\n-\t\t * any existing user.\n-\t\t */\n+\t\t/* Invalidate the per-cpu swap cluster cache for @si. */\n \t\tfor (i = 0; i \u003c SWAP_NR_ORDERS; i++)\n \t\t\tcmpxchg(\u0026pcp_si[i], si, NULL);\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@@ -3259,14 +3730,27 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)\n \n \tCLASS(filename, pathname)(specialfile);\n \tvictim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0);\n-\tif (IS_ERR(victim))\n-\t\treturn PTR_ERR(victim);\n+\tif (IS_ERR(victim)) {\n+\t\t/*\n+\t\t * An xswap device has no file, so /proc/swaps shows a name\n+\t\t * that cannot be opened. Accept it here so swapoff -a works.\n+\t\t * Only a missing name is taken for a device; a real file or\n+\t\t * directory that failed for another reason must not match.\n+\t\t */\n+\t\tif (PTR_ERR(victim) != -ENOENT)\n+\t\t\treturn PTR_ERR(victim);\n+\n+\t\terr = xswap_destroy_by_name(pathname-\u003ename);\n+\t\tif (err == -ENOENT)\n+\t\t\treturn PTR_ERR(victim);\n+\t\treturn err;\n+\t}\n \n \tmapping = victim-\u003ef_mapping;\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@@ -3285,20 +3769,66 @@ 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+\t/*\n+\t * The device's pages are its address space, not backing storage.\n+\t * The commit limit it added may have been committed against, so\n+\t * skip the probe until the limit stops counting that space.\n+\t */\n+\tif (!(p-\u003eflags \u0026 SWP_XSWAP)) {\n+\t\tif (!security_vm_enough_memory_mm(current-\u003emm, p-\u003epages))\n+\t\t\tvm_unacct_memory(p-\u003epages);\n+\t\telse\n+\t\t\treturn -ENOMEM;\n+\t}\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@@ -3309,7 +3839,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@@ -3330,7 +3860,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@@ -3340,10 +3871,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@@ -3351,14 +3878,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@@ -3369,13 +3904,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@@ -3406,7 +3938,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@@ -3427,7 +3960,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@@ -3440,6 +3974,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@@ -3456,11 +4003,23 @@ 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[32];\n+\n+#ifdef CONFIG_XSWAP\n+\t\tlen = scnprintf(name, sizeof(name), \"xswap%llu\",\n+\t\t\t\t(unsigned long long)si-\u003exswap_id);\n+#else\n+\t\t/* CONFIG_XSWAP=n has no file-less devices; keep the type. */\n+\t\tlen = scnprintf(name, sizeof(name), \"xswap%d\", si-\u003etype);\n+#endif\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@@ -3671,12 +4230,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@@ -3693,29 +4248,636 @@ static unsigned long read_swap_header(struct swap_info_struct *si,\n \treturn maxpages;\n }\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+#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 nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);\n-\tstruct swap_cluster_info *cluster_info;\n-\tint err = -ENOMEM;\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-\tcluster_info = kvzalloc_objs(*cluster_info, nr_clusters);\n-\tif (!cluster_info)\n-\t\tgoto err;\n-\n-\tfor (i = 0; i \u003c nr_clusters; i++)\n-\t\tspin_lock_init(\u0026cluster_info[i].lock);\n+\tmutex_lock(\u0026si-\u003exswap_lock);\n \n-\tif (!(si-\u003eflags \u0026 SWP_SOLIDSTATE)) {\n-\t\tsi-\u003eglobal_cluster = kmalloc_obj(*si-\u003eglobal_cluster);\n-\t\tif (!si-\u003eglobal_cluster)\n-\t\t\tgoto err;\n-\t\tfor (i = 0; i \u003c SWAP_NR_ORDERS; i++)\n-\t\t\tsi-\u003eglobal_cluster-\u003enext[i] = SWAP_ENTRY_INVALID;\n-\t\tspin_lock_init(\u0026si-\u003eglobal_cluster_lock);\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+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+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(\u0026this_cpu_ptr(\u0026percpu_swap_cluster)-\u003elock);\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+\tif (!nr_new)\n+\t\treturn 0;\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+\t/*\n+\t * Link the clusters even if swapoff cleared SWP_WRITEOK while we\n+\t * mapped. The caller keeps the device alive, and nothing takes a\n+\t * cluster while WRITEOK is clear. If try_to_unuse() fails, the\n+\t * reinserted device needs them.\n+\t */\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+/*\n+ * Caller must hold si-\u003exswap_lock.  Cannot fail.  @wait drains the per-cpu\n+ * cluster cache and waits one RCU grace period before unmapping.\n+ */\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+\t\t\t\t\tbool wait)\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+\t/*\n+\t * Publish the smaller range before its memory goes away.  Readers\n+\t * that use nr_clusters_mapped without xswap_lock pair with this\n+\t * store using smp_load_acquire().\n+\t */\n+\tsmp_store_release(\u0026si-\u003enr_clusters_mapped, start_idx);\n+\n+\tif (vm_start \u003e= vm_end) {\n+\t\t/*\n+\t\t * The clusters sit inside one page that the preceding\n+\t\t * cluster shares, so there is nothing to unmap.  The page\n+\t\t * goes away with that cluster; publishing the smaller\n+\t\t * cluster count is still correct.\n+\t\t */\n+\t\treturn;\n+\t}\n+\n+\tif (wait) {\n+\t\t/*\n+\t\t * A per-cpu cluster cache can still hold an offset in this\n+\t\t * range.  Invalidate those references, then wait out the\n+\t\t * readers that have already loaded one, so that nobody can\n+\t\t * dereference cluster_info past this point.\n+\t\t */\n+\t\tflush_percpu_swap_cluster(si);\n+\t\tsynchronize_rcu();\n+\t}\n+\n+\tnpages = (vm_end - vm_start) \u003e\u003e PAGE_SHIFT;\n+\n+\t/*\n+\t * vm_area_unmap_pages() refuses a range above totalram_pages() and\n+\t * returns without clearing the PTEs.  Freeing those pages would\n+\t * leave dangling mappings, so use the batch path for that case.\n+\t */\n+\tif (npages \u003c= totalram_pages()) {\n+\t\t/* Reclaim here would re-enter xswap_map_clusters() and its lock. */\n+\t\tnoreclaim_flags = memalloc_noreclaim_save();\n+\t\tpages = kvmalloc_array(npages, sizeof(*pages),\n+\t\t\t\t       GFP_KERNEL | __GFP_NOMEMALLOC);\n+\t\tmemalloc_noreclaim_restore(noreclaim_flags);\n+\t\tif (pages) {\n+\t\t\txswap_unmap_range(si, vm_start, vm_end, pages, npages);\n+\t\t\tkvfree(pages);\n+\t\t\treturn;\n+\t\t}\n+\t}\n+\n+\t/* No memory for the array, or too large a range: unmap in batches. */\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+\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+\t/*\n+\t * The teardown caller has already drained and waited in __swapoff();\n+\t * the create failure path has no readers.\n+\t */\n+\txswap_unmap_clusters_locked(si, start_idx, nr, false);\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+\t/* The mapped range is a prefix, so the first hole ends it. */\n+\tif (!pte_present(ptep_get(pte)))\n+\t\treturn 1;\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 two RCU grace periods\n+ * it 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 two RCU grace periods.\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 * An allocation can enter a cluster from the per-cpu cache without\n+\t * going through the lists, so drain the cache first.  xswap devices\n+\t * are SWP_SOLIDSTATE, so the per-cpu cache is the only cache.  Only\n+\t * then do the checks below hold: a cluster taken from a list takes\n+\t * si-\u003elock, which is what the check holds.\n+\t *\n+\t * The unmap helper below drains the cache and waits again: a cluster\n+\t * can be taken and freed between this recheck and the unmap, putting\n+\t * it back in the per-cpu cache.\n+\t */\n+\tflush_percpu_swap_cluster(si);\n+\tsynchronize_rcu();\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 * move_cluster() takes si-\u003elock under ci-\u003elock, so ci-\u003elock is\n+\t * taken with trylock here to avoid the reverse order.\n+\t *\n+\t * With si-\u003elock held, the writes below need no ci-\u003elock: a FREE\n+\t * cluster leaves the free list only in isolate_lock_cluster(),\n+\t * every move_cluster() caller holds ci-\u003elock (the trylock above\n+\t * catches one), a FREE cluster's count is 0 and only falls, and\n+\t * the drained cache holds no FREE cluster.\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+\t/*\n+\t * A cluster can be taken and freed between the recheck above and the\n+\t * unmap, putting it back in the per-cpu cache.  Drain and wait again.\n+\t */\n+\txswap_unmap_clusters_locked(si, start_idx, nr_unmap, true);\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\"type %d\\nclusters_max %lu\\nclusters_mapped %lu\\nusage_pages %lu\\ntail_free %lu\\ngrows %lu\\nshrinks %lu\\n\",\n+\t\t\tsi-\u003etype, READ_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[32];\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), \"xswap%llu\",\n+\t\t (unsigned long long)si-\u003exswap_id);\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+{\n+\tunsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);\n+\tstruct swap_cluster_info *cluster_info;\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\treturn 0;\n+\n+err_unmap:\n+\t\t/* swap_cluster_setup_bad_slot() allocates cluster 0's table. */\n+\t\tswap_cluster_free_table(\u0026si-\u003ecluster_info[0]);\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+\tif (!(si-\u003eflags \u0026 SWP_SOLIDSTATE)) {\n+\t\tsi-\u003eglobal_cluster = kmalloc_obj(*si-\u003eglobal_cluster);\n+\t\tif (!si-\u003eglobal_cluster)\n+\t\t\tgoto err;\n+\t\tfor (i = 0; i \u003c SWAP_NR_ORDERS; i++)\n+\t\t\tsi-\u003eglobal_cluster-\u003enext[i] = SWAP_ENTRY_INVALID;\n+\t\tspin_lock_init(\u0026si-\u003eglobal_cluster_lock);\n \t}\n \n \t/*\n@@ -3769,10 +4931,190 @@ 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+\tunsigned long limit;\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/*\n+\t * Refuse an explicitly requested size the device cannot address;\n+\t * clamp the default size, which nobody asked for.\n+\t */\n+\tlimit = xswap_size_limit();\n+\tmaxpages = xswap_size_pages();\n+\tif (xswap_size_set \u0026\u0026 maxpages \u003e limit) {\n+\t\tpr_err(\"xswap: xswap.max is larger than the device can address\\n\");\n+\t\treturn -EINVAL;\n+\t}\n+\tmaxpages = min(maxpages, limit);\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+\tINIT_WORK(\u0026si-\u003exswap_shrink_work, xswap_shrink_work_fn);\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-\u003eswap_file = NULL;\n+\tsi-\u003eflags |= SWP_XSWAP | SWP_SOLIDSTATE;\n+\tsi-\u003emax = maxpages;\n+\tsi-\u003epages = maxpages - 1;\n+\t/*\n+\t * Set before the device is enabled, for debugfs; destroy only matches\n+\t * a WRITEOK device, so the create window is not reachable.\n+\t */\n+\tsi-\u003exswap_id = atomic64_inc_return(\u0026xswap_id_counter);\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+\terror = zswap_swapon(si-\u003etype, si-\u003emax);\n+\tif (error)\n+\t\tgoto bad_swap;\n+\n+\tmutex_lock(\u0026swapon_mutex);\n+\t/* Two creates would race to make the root directory. */\n+\txswap_debugfs_add(si);\n+\tsi-\u003eprio = prio;\n+\tsi-\u003elist.prio = -si-\u003eprio;\n+\tsi-\u003eavail_list.prio = -si-\u003eprio;\n+\tenable_swap_info(si);\n+\tpr_info(\"xswap: adding extendable swap device xswap%llu (prio %d, %lu pages)\\n\",\n+\t\t(unsigned long long)si-\u003exswap_id, 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 stable id. */\n+static int xswap_destroy(u64 id)\n+{\n+\tstruct swap_info_struct *p = NULL;\n+\tunsigned int type;\n+\tint err;\n+\n+\tspin_lock(\u0026swap_lock);\n+\t/*\n+\t * Match only a device that is fully enabled: one still being created\n+\t * is not WRITEOK yet, and one being destroyed has lost it. Neither\n+\t * is a valid target, so both read as \"no such device\".\n+\t */\n+\tfor (type = 0; type \u003c nr_swapfiles; type++) {\n+\t\tstruct swap_info_struct *q = swap_info[type];\n+\n+\t\tif (q \u0026\u0026 (q-\u003eflags \u0026 (SWP_XSWAP | SWP_WRITEOK)) ==\n+\t\t\t (SWP_XSWAP | SWP_WRITEOK) \u0026\u0026 q-\u003exswap_id == id) {\n+\t\t\tp = q;\n+\t\t\tbreak;\n+\t\t}\n+\t}\n+\tif (!p) {\n+\t\tspin_unlock(\u0026swap_lock);\n+\t\treturn -ENODEV;\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+\n+static int xswap_destroy_by_name(const char *name)\n+{\n+\tconst char *p;\n+\tchar buf[24];\n+\tu64 id;\n+\tint err;\n+\n+\t/* Strictly \"xswap\u003cdigits\u003e\": no sign, no trailing newline. */\n+\tif (strncmp(name, \"xswap\", 5))\n+\t\treturn -ENOENT;\n+\n+\tp = name + 5;\n+\tif (!isdigit((unsigned char)*p))\n+\t\treturn -ENOENT;\n+\twhile (isdigit((unsigned char)*p))\n+\t\tp++;\n+\tif (*p)\n+\t\treturn -ENOENT;\n+\n+\tif (strscpy(buf, name + 5, sizeof(buf)) \u003c 0)\n+\t\treturn -ENOENT;\n+\n+\terr = kstrtou64(buf, 10, \u0026id);\n+\tif (err)\n+\t\treturn -ENOENT;\n+\n+\terr = xswap_destroy(id);\n+\tif (err == -ENODEV)\n+\t\treturn -ENOENT;\n+\treturn err;\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@@ -3877,7 +5219,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@@ -3968,7 +5310,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@@ -3991,7 +5333,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@@ -4104,6 +5446,13 @@ static int __init swapfile_init(void)\n {\n \tswapfile_maximum_size = arch_max_swapfile_size();\n \n+#ifdef CONFIG_XSWAP\n+\t/* xswap.max= on the command line overrides the build-time default. */\n+\tif (!xswap_size_set)\n+\t\txswap_parse_size(CONFIG_XSWAP_DEFAULT_MAX,\n+\t\t\t\t \"CONFIG_XSWAP_DEFAULT_MAX\", false);\n+#endif\n+\n \t/*\n \t * Once a cluster is freed, it's swap table content is read\n \t * only, and all swap cache readers (swap_cache_*) verifies\n@@ -4119,6 +5468,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 37d217860a6b2e..cef142d2ff8560 100644\n--- a/mm/zswap.c\n+++ b/mm/zswap.c\n@@ -1095,6 +1095,11 @@ static int zswap_writeback_entry(struct swap_io_ctx *ctx,\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@@ -1601,7 +1606,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@@ -1671,7 +1678,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/11/11 22:18 agent patch-evaluator
1m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "XSWAP",
    "ZSWAP",
    "ZSWAP_DEFAULT_ON",
    "SWAP"
  ],
  "FocusSymbols": [
    "xswap_create",
    "xswap_destroy",
    "xswap_create_store",
    "xswap_destroy_store",
    "xswap_grow",
    "xswap_try_shrink",
    "xswap_shrink_work_fn",
    "xswap_map_clusters",
    "xswap_unmap_clusters",
    "xswap_destroy_by_name"
  ],
  "Reasoning": "The patch introduces xswap, a file-less virtual swap device backed by zswap, into the core memory management subsystem. It adds new sysfs interfaces (/sys/kernel/mm/xswap/create and destroy), modifies the swapoff syscall, and adds complex dynamic allocation, growing, and shrinking logic using VM_SPARSE vmalloc areas, RCU synchronization, and workqueues. These reachable code paths in core mm should be fuzzed for concurrency issues, memory leaks, and invariant violations.",
  "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 21d9e31bbc41c3f61fd71c0b9d6875ed18c6cfc9
Author: syz-cluster <triage@syzkaller.com>
Date:   Wed Nov 11 22:18:28 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/ABI/testing/sysfs-kernel-mm-xswap b/Documentation/ABI/testing/sysfs-kernel-mm-xswap
new file mode 100644
index 00000000000000..f7e7f3e4d2164d
--- /dev/null
+++ b/Documentation/ABI/testing/sysfs-kernel-mm-xswap
@@ -0,0 +1,43 @@
+What:		/sys/kernel/mm/xswap/
+Date:		October 2026
+Contact:	Linux memory management mailing list <linux-mm@kvack.org>
+Description:	File-less swap devices backed by zswap.
+
+		An xswap device has no backing file.  Its slots are backed
+		by the zswap pool, and the device size is set at boot with
+		xswap.max= or CONFIG_XSWAP_DEFAULT_MAX.  The size is fixed
+		for the lifetime of the device.
+
+		The name shown in /proc/swaps, xswap<id>, is synthetic and
+		is not a path. swapoff(2) accepts it, so both "swapoff
+		xswap<id>" and swapoff -a tear the device down. A real
+		file or directory with that name takes precedence: if it
+		opens, it is looked up as a swap file and the synthetic
+		device is not used. Only a name that cannot be opened
+		because it does not exist, including a dangling symlink,
+		is treated as an xswap device. Use the destroy attribute
+		for an unambiguous teardown.
+
+		An xswap device requires zswap.  Disabling zswap at runtime
+		(enabled=0, or max_pool_percent=0) while xswap devices
+		exist leaves them without backing: existing entries can
+		still be read, but new pages cannot be stored.  Destroy the
+		xswap devices before disabling zswap.
+
+What:		/sys/kernel/mm/xswap/create
+Date:		October 2026
+Contact:	Linux memory management mailing list <linux-mm@kvack.org>
+Description:	Create an xswap device.
+
+		Write an optional priority (0..32767), or write nothing for
+		the default priority.  The write fails if zswap is disabled
+		or if the configured size is smaller than one cluster.
+
+What:		/sys/kernel/mm/xswap/destroy
+Date:		October 2026
+Contact:	Linux memory management mailing list <linux-mm@kvack.org>
+Description:	Destroy an xswap device.
+
+		Write the device's stable id.  The id is the number after
+		"xswap" in /proc/swaps, for example 1 for xswap1.  It is
+		not a swap type and is never reused.
diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt
index a1fb40e5000977..95b5ba9ee4f8aa 100644
--- a/Documentation/admin-guide/kernel-parameters.txt
+++ b/Documentation/admin-guide/kernel-parameters.txt
@@ -8752,3 +8752,11 @@ Kernel parameters
 				memory, and other data can't be written using
 				xmon commands.
 			off	xmon is disabled.
+
+	xswap.max=	[KNL,SWAP]
+			Maximum size of a new xswap device. The value is a
+			size in bytes with an optional KMGTPE suffix, a
+			percentage of RAM, or "max" for the largest size
+			the device can address. The default is set by
+			CONFIG_XSWAP_DEFAULT_MAX.
+			Format: <size>[KMGTPE] | <percent>% | max
diff --git a/Documentation/admin-guide/mm/zswap.rst b/Documentation/admin-guide/mm/zswap.rst
index 2464425c783de2..886b50ca90b1ae 100644
--- a/Documentation/admin-guide/mm/zswap.rst
+++ b/Documentation/admin-guide/mm/zswap.rst
@@ -136,3 +136,12 @@ selected.
 A debugfs interface is provided for various statistic about pool size, number
 of pages stored, same-value filled pages and various counters for the reasons
 pages are rejected.
+
+xswap devices
+-------------
+
+An xswap device is a file-less swap device backed by zswap.  While such a
+device exists, do not disable zswap at runtime (``enabled=0``) or set
+``max_pool_percent`` to 0.  The device would have no backing: pages already
+in zswap can still be read, but new pages cannot be stored.  Destroy the
+xswap devices first.
diff --git a/MAINTAINERS b/MAINTAINERS
index ce05a3253baaea..c97ecdd39a8a56 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -17907,6 +17907,7 @@ R:	Youngjun Park <youngjun.park@lge.com>
 L:	linux-mm@kvack.org
 S:	Maintained
 F:	Documentation/ABI/testing/sysfs-kernel-mm-swap
+F:	Documentation/ABI/testing/sysfs-kernel-mm-xswap
 F:	Documentation/mm/swap-table.rst
 F:	include/linux/swap.h
 F:	include/linux/swap_ops.h
diff --git a/include/linux/swap.h b/include/linux/swap.h
index 4f686709d71f00..1e552a8b421b68 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,26 @@ 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 */
+	u64			xswap_id;	/* stable id, shown to userspace */
+	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 +390,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 afff1b25b54387..902e3b1a6e35cc 100644
--- a/mm/Kconfig
+++ b/mm/Kconfig
@@ -122,6 +122,26 @@ 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 is mapped lazily
+	  in chunks, avoiding static pre-allocation overhead.
+
+config XSWAP_DEFAULT_MAX
+	string "Default maximum size of a new xswap device"
+	depends on XSWAP
+	default "200%"
+	help
+	  The maximum size of a newly created xswap device. It accepts a
+	  percentage of RAM (for example "200%"), a size (for example "2T"),
+	  or "max" for the largest size the device can address.
+
+	  xswap.max= on the kernel command line overrides this value.
+
 config ZSMALLOC
 	tristate
 
diff --git a/mm/page_io.c b/mm/page_io.c
index a57cdcf2892dfa..2285fb1735b383 100644
--- a/mm/page_io.c
+++ b/mm/page_io.c
@@ -258,6 +258,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:
@@ -515,6 +524,16 @@ void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio)
 	if (zswap_load(folio) != -ENOENT)
 		return;
 
+	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);
+		return;
+	}
+
 	/* 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 da65d75ceead12..4c965cf99809be 100644
--- a/mm/swap_state.c
+++ b/mm/swap_state.c
@@ -899,6 +899,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;
@@ -984,6 +988,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;
@@ -992,6 +997,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 fcda5eba171402..2d6c13d510672d 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -14,8 +14,11 @@
 #include <linux/mman.h>
 #include <linux/slab.h>
 #include <linux/kernel_stat.h>
+#include <linux/overflow.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>
@@ -31,6 +34,7 @@
 #include <linux/backing-dev.h>
 #include <linux/mutex.h>
 #include <linux/capability.h>
+#include <linux/ctype.h>
 #include <linux/syscalls.h>
 #include <linux/memcontrol.h>
 #include <linux/poll.h>
@@ -42,6 +46,7 @@
 #include <linux/suspend.h>
 #include <linux/zswap.h>
 #include <linux/plist.h>
+#include <linux/debugfs.h>
 
 #include <asm/tlbflush.h>
 #include <linux/leafops.h>
@@ -49,6 +54,260 @@
 #include "internal.h"
 #include "swap.h"
 
+#define DEF_SWAP_PRIO  -1
+
+/*
+ * The highest priority a real swap device can use: one ahead of xswap
+ * would take the page directly, and taking that slot is what xswap
+ * exists to avoid.  At equal priority the list is FIFO, so a real device
+ * that asks for this priority too and is added first wins.
+ */
+#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)
+
+/* 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)
+/*
+ * Shrink thresholds, as a percentage of the mapped range in use.  The stop
+ * point sits inside (SHRINK_WHEN, GROW_WHEN), so shrinking cannot leave the
+ * range in a state that wakes the grow up.
+ */
+#define XSWAP_SHRINK_WHEN	50
+#define XSWAP_SHRINK_UNTIL	70
+
+/*
+ * Grow thresholds, as a percentage of the mapped range in use.  The target
+ * sits above the point where the shrink starts looking (50%) and below the
+ * next grow trigger (85%), so a grow cannot leave the range in a state the
+ * shrink would undo.
+ */
+#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);
+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(u64 id);
+static int xswap_destroy_by_name(const char *name);
+
+/* Stable device id, assigned at create and never reused. */
+static atomic64_t xswap_id_counter = ATOMIC64_INIT(0);
+
+static ssize_t xswap_create_store(struct kobject *kobj,
+				  struct kobj_attribute *attr,
+				  const char *buf, size_t count)
+{
+	int prio = DEF_XSWAP_PRIO;
+	const char *p;
+	int err;
+
+	if (!capable(CAP_SYS_ADMIN))
+		return -EPERM;
+
+	/* "[<prio>]" is optional; a lower one is allowed, not a higher. */
+	p = skip_spaces(buf);
+	if (*p && *p != '\n') {
+		err = kstrtoint(p, 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)
+{
+	u64 id;
+	int err;
+
+	if (!capable(CAP_SYS_ADMIN))
+		return -EPERM;
+
+	err = kstrtoull(buf, 0, &id);
+	if (err)
+		return err;
+
+	err = xswap_destroy(id);
+	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; "max" asks for the largest size the device can address.
+ */
+static unsigned int xswap_size_pct = 200;
+static unsigned long xswap_size_bytes;
+static bool xswap_size_max;
+static bool xswap_size_set;	/* xswap.max= was given */
+
+/*
+ * Parse "200%", "2T" or "max". @str is not modified. @cmdline tells an
+ * explicit xswap.max= from the build-time default, which is clamped
+ * instead of refused when it is too large.
+ */
+static int __init xswap_parse_size(const char *str, const char *what,
+				   bool cmdline)
+{
+	const char *pct;
+	char buf[16];
+	unsigned int pct_val;
+	unsigned long bytes;
+	char *end;
+
+	pct = strchr(str, '%');
+	if (!strcmp(str, "max")) {
+		xswap_size_max = true;
+		xswap_size_pct = 0;
+		xswap_size_bytes = 0;
+	} else if (pct) {
+		size_t len = pct - str;
+
+		if (pct[1] || !len || len >= sizeof(buf))
+			goto bad;
+		memcpy(buf, str, len);
+		buf[len] = '\0';
+		if (kstrtouint(buf, 0, &pct_val) || !pct_val)
+			goto bad;
+		xswap_size_pct = pct_val;
+		xswap_size_bytes = 0;
+		xswap_size_max = false;
+	} else {
+		bytes = memparse(str, &end);
+		if (*end || bytes < PAGE_SIZE)
+			goto bad;
+		/* A default below one cluster would fail every create. */
+		if (!cmdline && bytes < (unsigned long)SWAPFILE_CLUSTER * PAGE_SIZE)
+			goto bad;
+		xswap_size_bytes = bytes;
+		xswap_size_pct = 0;
+		xswap_size_max = false;
+	}
+
+	if (cmdline)
+		xswap_size_set = true;
+	return 0;
+bad:
+	pr_err("xswap: bad %s=%s\n", what, str);
+	return -EINVAL;
+}
+
+static int __init xswap_max_setup(char *str)
+{
+	xswap_parse_size(str, "xswap.max", true);
+	return 1;
+}
+__setup("xswap.max=", xswap_max_setup);
+
+/*
+ * The most a device can address, whatever xswap.max= asked for.  An xswap
+ * slot is still a swap entry, so the swap offset limit applies even though
+ * the data never goes through a physical address.
+ */
+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)
+{
+	unsigned long long pages;
+
+	if (xswap_size_max)
+		return xswap_size_limit();
+
+	if (xswap_size_bytes)
+		return xswap_size_bytes >> PAGE_SHIFT;
+
+	/* Let xswap_create() refuse a size that does not fit in the type. */
+	if (check_mul_overflow((unsigned long long)totalram_pages(),
+			       (unsigned long long)xswap_size_pct, &pages))
+		return ULONG_MAX;
+
+	return div_u64(pages, 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)
+{
+}
+
+static inline int xswap_destroy_by_name(const char *name)
+{
+	return -ENOENT;
+}
+#endif /* CONFIG_XSWAP */
+
 static void swap_range_alloc(struct swap_info_struct *si,
 			     unsigned int nr_entries);
 static bool folio_swapcache_freeable(struct folio *folio);
@@ -66,6 +325,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 +336,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 +663,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)
@@ -654,6 +915,16 @@ 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.
+	 * A racing swapoff can still clear SWP_WRITEOK after this check;
+	 * the work function checks it again, so a late schedule is benign.
+	 */
+	if ((READ_ONCE(si->flags) & (SWP_XSWAP | SWP_WRITEOK)) ==
+	    (SWP_XSWAP | SWP_WRITEOK))
+		schedule_work(&si->xswap_shrink_work);
+#endif
 }
 
 /*
@@ -775,7 +1046,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)) {
@@ -852,7 +1124,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;
 	}
 	/*
@@ -1034,11 +1306,12 @@ static bool swap_prefer_free_cluster(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;
@@ -1048,6 +1321,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;
 
@@ -1076,6 +1352,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);
@@ -1085,12 +1362,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);
@@ -1119,6 +1396,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--;
@@ -1143,6 +1423,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;
 
@@ -1173,7 +1454,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
@@ -1182,6 +1463,18 @@ 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) && (si->flags & SWP_WRITEOK) &&
+	    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);
@@ -1254,6 +1547,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);
@@ -1277,6 +1576,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 {
 		/*
@@ -1310,6 +1614,14 @@ static void add_to_avail_list(struct swap_info_struct *si, bool swapon)
 	if (swapon) {
 		lockdep_assert_held(&si->lock);
 		si->flags |= SWP_WRITEOK;
+		/*
+		 * Count the device here, not after adding it to the list: a
+		 * full device is still active and skips the add below.
+		 */
+		if (si->flags & SWP_XSWAP)
+			atomic_add(1, &nr_xswap_files);
+		else
+			atomic_add(1, &nr_real_swapfiles);
 	} else {
 		if (!(READ_ONCE(si->flags) & SWP_WRITEOK))
 			goto skip;
@@ -1323,10 +1635,11 @@ static void add_to_avail_list(struct swap_info_struct *si, bool swapon)
 	/*
 	 * When device is full and device is on the plist, only one updater will
 	 * see (inuse_pages == si->pages) and will call del_from_avail_list. If
-	 * that updater happen to be here, just skip adding.
+	 * that updater happen to be here, just skip adding.  @val still has
+	 * the off-list bit, so compare its counter part.
 	 */
 	pages = si->pages;
-	if (val == pages) {
+	if ((val & SWAP_USAGE_COUNTER_MASK) == pages) {
 		/* Just like the cmpxchg in del_from_avail_list */
 		if (atomic_long_try_cmpxchg(&si->inuse_pages, &pages,
 					    pages | SWAP_USAGE_OFFLIST_BIT))
@@ -1431,21 +1744,51 @@ 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;
+	}
+#ifdef CONFIG_XSWAP
+	if (si->flags & SWP_XSWAP) {
+		/*
+		 * The cached offset can outlive a shrink that did not see
+		 * it, and the cluster_info page it indexes may be unmapped.
+		 * Fail the fast path; the slow path picks a live cluster.
+		 */
+		unsigned long mapped;
+
+		/* Pairs with the release store in xswap_unmap_clusters_locked(). */
+		mapped = smp_load_acquire(&si->nr_clusters_mapped);
+
+		if (offset / SWAPFILE_CLUSTER >= mapped) {
+			put_swap_device(si);
+			rcu_read_unlock();
+			return false;
+		}
+	}
+#endif
+	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)) {
@@ -1457,17 +1800,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);
@@ -1790,6 +2140,17 @@ static int swap_dup_entries_cluster(struct swap_info_struct *si,
 	return err;
 }
 
+/* Can the folio's cgroup take another zswap page? */
+static bool folio_may_zswap(struct folio *folio)
+{
+	struct obj_cgroup *objcg = get_obj_cgroup_from_folio(folio);
+	bool may_zswap = !objcg || obj_cgroup_may_zswap(objcg);
+
+	if (objcg)
+		obj_cgroup_put(objcg);
+	return may_zswap;
+}
+
 /**
  * folio_alloc_swap - allocate swap space for a folio
  * @folio: folio we want to move to swap
@@ -1806,10 +2167,23 @@ int folio_alloc_swap(struct folio *folio)
 {
 	unsigned int order = folio_order(folio);
 	unsigned int size = 1 << order;
+	/* True unless the gate below finds an xswap device to route away from. */
+	bool may_zswap = true;
+	bool zswap_checked = false;
 
 	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; a device that
+	 * appears before we pick one is handled after the allocation.
+	 */
+	if (atomic_read(&nr_xswap_files)) {
+		may_zswap = folio_may_zswap(folio);
+		zswap_checked = true;
+	}
+
 	if (order) {
 		/*
 		 * Reject large allocation when THP_SWAP is disabled. Check below
@@ -1830,8 +2204,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))) {
@@ -1839,6 +2213,22 @@ int folio_alloc_swap(struct folio *folio)
 			goto again;
 	}
 
+	/*
+	 * The xswap gate was skipped because there was no device when we
+	 * looked. One may have appeared since; check before keeping the
+	 * xswap slot the allocator may have picked.
+	 */
+	if (unlikely(!zswap_checked && atomic_read(&nr_xswap_files) &&
+		     folio_test_swapcache(folio) &&
+		     (__swap_entry_to_info(folio->swap)->flags & SWP_XSWAP))) {
+		zswap_checked = true;
+		may_zswap = folio_may_zswap(folio);
+		if (!may_zswap) {
+			swap_cache_del_folio(folio);
+			goto again;
+		}
+	}
+
 	/* Need to call this even if allocation failed, for MEMCG_SWAP_FAIL. */
 	if (unlikely(mem_cgroup_try_charge_swap(folio))) {
 		swap_cache_del_folio(folio);
@@ -2249,8 +2639,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) {
@@ -2260,6 +2653,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);
@@ -2301,6 +2695,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);
@@ -2488,6 +2885,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;
@@ -2527,9 +2926,15 @@ unsigned int count_swap_pages(int type, int free)
 
 		spin_lock(&sis->lock);
 		if (sis->flags & SWP_WRITEOK) {
-			n = sis->pages;
-			if (free)
-				n -= swap_usage_in_pages(sis);
+			/* Hibernation only; it never selects an xswap device. */
+			if (unlikely(sis->flags & SWP_XSWAP)) {
+				WARN_ON_ONCE(1);
+				n = 0;
+			} else {
+				n = sis->pages;
+				if (free)
+					n -= swap_usage_in_pages(sis);
+			}
 		}
 		spin_unlock(&sis->lock);
 	}
@@ -2850,14 +3255,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
@@ -2865,11 +3287,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.
@@ -2879,13 +3301,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;
@@ -2895,7 +3317,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;
@@ -2905,7 +3326,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;
@@ -3193,20 +3614,72 @@ 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().
+		 * A grow may publish after this read, but no slot comes from
+		 * those clusters once WRITEOK is clear.  Cached clusters are
+		 * inside the range; try_to_unuse()'s rescan catches any slot
+		 * taken after the walk.
+		 */
+		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;
+
+		/* A late schedule must not be pending when the work is reinitialized. */
+		disable_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, and the unmap helper handles an empty range.
+		 */
+		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 */
@@ -3218,11 +3691,14 @@ static void free_swap_cluster_info(struct swap_cluster_info *cluster_info,
 		spin_unlock(&ci->lock);
 	}
 	kvfree(cluster_info);
+	si->cluster_info = NULL;
 }
 
 /*
- * Called after swap device's reference count is dead, so
- * neither scan nor allocation will use it.
+ * Invalidate the per-cpu cluster cache for @si.  A caller that has not
+ * already killed @si->users and waited must follow with synchronize_rcu()
+ * before unmapping cluster_info, since a reader may already have loaded
+ * a cached offset.
  */
 static void flush_percpu_swap_cluster(struct swap_info_struct *si)
 {
@@ -3231,25 +3707,20 @@ static void flush_percpu_swap_cluster(struct swap_info_struct *si)
 
 	for_each_possible_cpu(cpu) {
 		pcp_si = per_cpu_ptr(percpu_swap_cluster.si, cpu);
-		/*
-		 * Invalidate the percpu swap cluster cache, si->users
-		 * is dead, so no new user will point to it, just flush
-		 * any existing user.
-		 */
+		/* Invalidate the per-cpu swap cluster cache for @si. */
 		for (i = 0; i < SWAP_NR_ORDERS; i++)
 			cmpxchg(&pcp_si[i], si, NULL);
 	}
 }
 
+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))
@@ -3259,14 +3730,27 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 
 	CLASS(filename, pathname)(specialfile);
 	victim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0);
-	if (IS_ERR(victim))
-		return PTR_ERR(victim);
+	if (IS_ERR(victim)) {
+		/*
+		 * An xswap device has no file, so /proc/swaps shows a name
+		 * that cannot be opened. Accept it here so swapoff -a works.
+		 * Only a missing name is taken for a device; a real file or
+		 * directory that failed for another reason must not match.
+		 */
+		if (PTR_ERR(victim) != -ENOENT)
+			return PTR_ERR(victim);
+
+		err = xswap_destroy_by_name(pathname->name);
+		if (err == -ENOENT)
+			return PTR_ERR(victim);
+		return err;
+	}
 
 	mapping = victim->f_mapping;
 	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;
 			}
@@ -3285,20 +3769,66 @@ 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)
+{
+	/*
+	 * The device's pages are its address space, not backing storage.
+	 * The commit limit it added may have been committed against, so
+	 * skip the probe until the limit stops counting that space.
+	 */
+	if (!(p->flags & SWP_XSWAP)) {
+		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);
 
@@ -3309,7 +3839,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;
 	}
 
 	/*
@@ -3330,7 +3860,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);
@@ -3340,10 +3871,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);
@@ -3351,14 +3878,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
@@ -3369,13 +3904,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
@@ -3406,7 +3938,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;
@@ -3427,7 +3960,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;
 	}
@@ -3440,6 +3974,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;
@@ -3456,11 +4003,23 @@ 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[32];
+
+#ifdef CONFIG_XSWAP
+		len = scnprintf(name, sizeof(name), "xswap%llu",
+				(unsigned long long)si->xswap_id);
+#else
+		/* CONFIG_XSWAP=n has no file-less devices; keep the type. */
+		len = scnprintf(name, sizeof(name), "xswap%d", si->type);
+#endif
+		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);
@@ -3671,12 +4230,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;
@@ -3693,29 +4248,636 @@ static unsigned long read_swap_header(struct swap_info_struct *si,
 	return maxpages;
 }
 
-static int setup_swap_clusters_info(struct swap_info_struct *si,
-				    union swap_header *swap_header,
-				    unsigned long maxpages)
+#ifdef CONFIG_XSWAP
+static int xswap_map_clusters(struct swap_info_struct *si,
+			      unsigned long start_idx, unsigned long nr)
 {
-	unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
-	struct swap_cluster_info *cluster_info;
-	int err = -ENOMEM;
+	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;
 
-	cluster_info = kvzalloc_objs(*cluster_info, nr_clusters);
-	if (!cluster_info)
-		goto err;
-
-	for (i = 0; i < nr_clusters; i++)
-		spin_lock_init(&cluster_info[i].lock);
+	mutex_lock(&si->xswap_lock);
 
-	if (!(si->flags & SWP_SOLIDSTATE)) {
-		si->global_cluster = kmalloc_obj(*si->global_cluster);
-		if (!si->global_cluster)
-			goto err;
-		for (i = 0; i < SWAP_NR_ORDERS; i++)
-			si->global_cluster->next[i] = SWAP_ENTRY_INVALID;
-		spin_lock_init(&si->global_cluster_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;
+}
+
+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]);
+}
+
+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(&this_cpu_ptr(&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);
+	if (!nr_new)
+		return 0;
+
+	/*
+	 * 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;
+
+	/*
+	 * Link the clusters even if swapoff cleared SWP_WRITEOK while we
+	 * mapped. The caller keeps the device alive, and nothing takes a
+	 * cluster while WRITEOK is clear. If try_to_unuse() fails, the
+	 * reinserted device needs them.
+	 */
+	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;
+}
+
+/*
+ * Caller must hold si->xswap_lock.  Cannot fail.  @wait drains the per-cpu
+ * cluster cache and waits one RCU grace period before unmapping.
+ */
+static void xswap_unmap_clusters_locked(struct swap_info_struct *si,
+					unsigned long start_idx, unsigned long nr,
+					bool wait)
+{
+	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;
+
+	/*
+	 * Publish the smaller range before its memory goes away.  Readers
+	 * that use nr_clusters_mapped without xswap_lock pair with this
+	 * store using smp_load_acquire().
+	 */
+	smp_store_release(&si->nr_clusters_mapped, start_idx);
+
+	if (vm_start >= vm_end) {
+		/*
+		 * The clusters sit inside one page that the preceding
+		 * cluster shares, so there is nothing to unmap.  The page
+		 * goes away with that cluster; publishing the smaller
+		 * cluster count is still correct.
+		 */
+		return;
+	}
+
+	if (wait) {
+		/*
+		 * 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.
+		 */
+		flush_percpu_swap_cluster(si);
+		synchronize_rcu();
+	}
+
+	npages = (vm_end - vm_start) >> PAGE_SHIFT;
+
+	/*
+	 * vm_area_unmap_pages() refuses a range above totalram_pages() and
+	 * returns without clearing the PTEs.  Freeing those pages would
+	 * leave dangling mappings, so use the batch path for that case.
+	 */
+	if (npages <= totalram_pages()) {
+		/* Reclaim here would re-enter xswap_map_clusters() and its lock. */
+		noreclaim_flags = memalloc_noreclaim_save();
+		pages = kvmalloc_array(npages, sizeof(*pages),
+				       GFP_KERNEL | __GFP_NOMEMALLOC);
+		memalloc_noreclaim_restore(noreclaim_flags);
+		if (pages) {
+			xswap_unmap_range(si, vm_start, vm_end, pages, npages);
+			kvfree(pages);
+			return;
+		}
+	}
+
+	/* No memory for the array, or too large a range: unmap in batches. */
+	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));
+	}
+}
+
+static void xswap_unmap_clusters(struct swap_info_struct *si,
+				 unsigned long start_idx, unsigned long nr)
+{
+	mutex_lock(&si->xswap_lock);
+	/*
+	 * The teardown caller has already drained and waited in __swapoff();
+	 * the create failure path has no readers.
+	 */
+	xswap_unmap_clusters_locked(si, start_idx, nr, false);
+	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;
+
+	/* The mapped range is a prefix, so the first hole ends it. */
+	if (!pte_present(ptep_get(pte)))
+		return 1;
+	*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 two RCU grace periods
+ * 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 two RCU grace periods.
+	 */
+	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;
+
+	/*
+	 * An allocation can enter a cluster from the per-cpu cache without
+	 * going through the lists, so drain the cache first.  xswap devices
+	 * are SWP_SOLIDSTATE, so the per-cpu cache is the only cache.  Only
+	 * then do the checks below hold: a cluster taken from a list takes
+	 * si->lock, which is what the check holds.
+	 *
+	 * The unmap helper below drains the cache and waits again: a cluster
+	 * can be taken and freed between this recheck and the unmap, putting
+	 * it back in the per-cpu cache.
+	 */
+	flush_percpu_swap_cluster(si);
+	synchronize_rcu();
+
+	/*
+	 * Only shrink a run that reaches the mapped end; otherwise
+	 * truncating nr_clusters_mapped would orphan the active tail.
+	 * move_cluster() takes si->lock under ci->lock, so ci->lock is
+	 * taken with trylock here to avoid the reverse order.
+	 *
+	 * With si->lock held, the writes below need no ci->lock: a FREE
+	 * cluster leaves the free list only in isolate_lock_cluster(),
+	 * every move_cluster() caller holds ci->lock (the trylock above
+	 * catches one), a FREE cluster's count is 0 and only falls, and
+	 * the drained cache holds no FREE cluster.
+	 */
+	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);
+
+	/*
+	 * A cluster can be taken and freed between the recheck above and the
+	 * unmap, putting it back in the per-cpu cache.  Drain and wait again.
+	 */
+	xswap_unmap_clusters_locked(si, start_idx, nr_unmap, true);
+	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),
+			"type %d\nclusters_max %lu\nclusters_mapped %lu\nusage_pages %lu\ntail_free %lu\ngrows %lu\nshrinks %lu\n",
+			si->type, 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[32];
+
+	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), "xswap%llu",
+		 (unsigned long long)si->xswap_id);
+	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)
+{
+	unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
+	struct swap_cluster_info *cluster_info;
+	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);
+			}
+		}
+
+		return 0;
+
+err_unmap:
+		/* swap_cluster_setup_bad_slot() allocates cluster 0's table. */
+		swap_cluster_free_table(&si->cluster_info[0]);
+		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);
+
+	if (!(si->flags & SWP_SOLIDSTATE)) {
+		si->global_cluster = kmalloc_obj(*si->global_cluster);
+		if (!si->global_cluster)
+			goto err;
+		for (i = 0; i < SWAP_NR_ORDERS; i++)
+			si->global_cluster->next[i] = SWAP_ENTRY_INVALID;
+		spin_lock_init(&si->global_cluster_lock);
 	}
 
 	/*
@@ -3769,10 +4931,190 @@ 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;
+	unsigned long limit;
+	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 an explicitly requested size the device cannot address;
+	 * clamp the default size, which nobody asked for.
+	 */
+	limit = xswap_size_limit();
+	maxpages = xswap_size_pages();
+	if (xswap_size_set && maxpages > limit) {
+		pr_err("xswap: xswap.max is larger than the device can address\n");
+		return -EINVAL;
+	}
+	maxpages = min(maxpages, limit);
+	/*
+	 * 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);
+	INIT_WORK(&si->xswap_shrink_work, xswap_shrink_work_fn);
+
+	/* Cluster-aligned, so no cluster holds a slot past si->max. */
+	maxpages = rounddown(maxpages, SWAPFILE_CLUSTER);
+
+	si->bdev = NULL;
+	si->swap_file = NULL;
+	si->flags |= SWP_XSWAP | SWP_SOLIDSTATE;
+	si->max = maxpages;
+	si->pages = maxpages - 1;
+	/*
+	 * Set before the device is enabled, for debugfs; destroy only matches
+	 * a WRITEOK device, so the create window is not reachable.
+	 */
+	si->xswap_id = atomic64_inc_return(&xswap_id_counter);
+	/*
+	 * 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;
+
+	error = zswap_swapon(si->type, si->max);
+	if (error)
+		goto bad_swap;
+
+	mutex_lock(&swapon_mutex);
+	/* Two creates would race to make the root directory. */
+	xswap_debugfs_add(si);
+	si->prio = prio;
+	si->list.prio = -si->prio;
+	si->avail_list.prio = -si->prio;
+	enable_swap_info(si);
+	pr_info("xswap: adding extendable swap device xswap%llu (prio %d, %lu pages)\n",
+		(unsigned long long)si->xswap_id, 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 stable id. */
+static int xswap_destroy(u64 id)
+{
+	struct swap_info_struct *p = NULL;
+	unsigned int type;
+	int err;
+
+	spin_lock(&swap_lock);
+	/*
+	 * Match only a device that is fully enabled: one still being created
+	 * is not WRITEOK yet, and one being destroyed has lost it. Neither
+	 * is a valid target, so both read as "no such device".
+	 */
+	for (type = 0; type < nr_swapfiles; type++) {
+		struct swap_info_struct *q = swap_info[type];
+
+		if (q && (q->flags & (SWP_XSWAP | SWP_WRITEOK)) ==
+			 (SWP_XSWAP | SWP_WRITEOK) && q->xswap_id == id) {
+			p = q;
+			break;
+		}
+	}
+	if (!p) {
+		spin_unlock(&swap_lock);
+		return -ENODEV;
+	}
+	/* 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);
+}
+
+static int xswap_destroy_by_name(const char *name)
+{
+	const char *p;
+	char buf[24];
+	u64 id;
+	int err;
+
+	/* Strictly "xswap<digits>": no sign, no trailing newline. */
+	if (strncmp(name, "xswap", 5))
+		return -ENOENT;
+
+	p = name + 5;
+	if (!isdigit((unsigned char)*p))
+		return -ENOENT;
+	while (isdigit((unsigned char)*p))
+		p++;
+	if (*p)
+		return -ENOENT;
+
+	if (strscpy(buf, name + 5, sizeof(buf)) < 0)
+		return -ENOENT;
+
+	err = kstrtou64(buf, 10, &id);
+	if (err)
+		return -ENOENT;
+
+	err = xswap_destroy(id);
+	if (err == -ENODEV)
+		return -ENOENT;
+	return err;
+}
+#endif /* CONFIG_XSWAP */
+
 SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 {
 	struct swap_info_struct *si;
@@ -3877,7 +5219,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;
 	}
@@ -3968,7 +5310,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" : "",
@@ -3991,7 +5333,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
@@ -4104,6 +5446,13 @@ static int __init swapfile_init(void)
 {
 	swapfile_maximum_size = arch_max_swapfile_size();
 
+#ifdef CONFIG_XSWAP
+	/* xswap.max= on the command line overrides the build-time default. */
+	if (!xswap_size_set)
+		xswap_parse_size(CONFIG_XSWAP_DEFAULT_MAX,
+				 "CONFIG_XSWAP_DEFAULT_MAX", false);
+#endif
+
 	/*
 	 * Once a cluster is freed, it's swap table content is read
 	 * only, and all swap cache readers (swap_cache_*) verifies
@@ -4119,6 +5468,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 37d217860a6b2e..cef142d2ff8560 100644
--- a/mm/zswap.c
+++ b/mm/zswap.c
@@ -1095,6 +1095,11 @@ static int zswap_writeback_entry(struct swap_io_ctx *ctx,
 	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);
@@ -1601,7 +1606,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;
@@ -1671,7 +1678,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/11/11 22:18 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 31998
							output: 29
							thoughts: 1369
						

Thoughts:
**Xswap Patch Evaluation: A Deep Dive**

Okay, let's break down this xswap patch series for the amd64 architecture Linux kernel. My initial thought is, this looks significant. I need to understand exactly what this patch does, how it works, and most importantly, how we can test it thoroughly.

First, I see the core functionality revolves around a new, extendable, file-less swap device backed by zswap, called "xswap". It's introducing new sysfs interfaces for creation and destruction (`/sys/kernel/mm/xswap/create`, `/sys/kernel/mm/xswap/destroy`), which immediately makes it user-accessible. There are new kernel configs (`CONFIG_XSWAP`, `CONFIG_XSWAP_DEFAULT_MAX`), suggesting a feature that can be enabled or disabled. It modifies a whole host of existing core memory management functions: allocation, readahead, reclamation, the swapoff syscall, cluster info mapping, locking, and more. This is deep in the guts of the memory management subsystem.

Reading through the diff, it touches several files: Documentation (ABI, admin guide), the MAINTAINERS file, the main swap header file, the kernel Kconfig file, and critical files for handling page I/O, swap state, swap files, and zswap. The introduction of `SWP_XSWAP` in `swap.h` is a key indicator of its scope. The new xswap implementation in `mm/swapfile.c` is extensive. It seems like the core logic lives there. The interactions with `zswap.c` are also noteworthy. The changes to `page_io.c` are important as they change the behavior in `swap_writeout` and `swap_read_folio`, and the inclusion of `xswap_shrink_work_fn` in `mm/swapfile.c` suggests asynchronous operations.

Is this reachable? Yes, absolutely. We can interact with it through sysfs, the `swapoff` syscall, and, crucially, through memory pressure that triggers swap-out/swap-in. This is a standard virtualized environment on x86_64, QEMU or GCE is fine.

Is it worth fuzzing? Without a doubt, yes! This is exactly the kind of patch that screams for fuzzing. It's touching core memory management, which means complex locking mechanisms, RCU, workqueues, vmalloc area mapping and unmapping, reference counting, and all kinds of opportunities for race conditions. The addition of asynchronous operations is a huge red flag. This also meets the positive criteria for fuzzing.

Now, let's nail down the configurations. The Kconfig entry in `mm/Kconfig` is key: `CONFIG_XSWAP` depends on `SWAP && 64BIT && ZSWAP && SYSFS`. This means we'll need to enable those upstream as prerequisites. Then we will need to explore what ZSWAP requires, which depends on others. I'll need to use my grepper tool to analyze the `mm/Kconfig` file and trace the dependencies of `ZSWAP` carefully. I have to find the correct configuration recipe.



4/2 2026/11/11 22:18 tool grepper
0m Args:
{
  "Expression": "config ZSWAP",
  "PathPrefixes": [
    "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--\nmm/Kconfig-34-\nmm/Kconfig:35:config ZSWAP_DEFAULT_ON\nmm/Kconfig-36-\tbool \"Enable the compressed cache for swap pages by default\"\n--\nmm/Kconfig-44-\nmm/Kconfig:45:config ZSWAP_SHRINKER_DEFAULT_ON\nmm/Kconfig-46-\tbool \"Shrink the zswap pool on memory pressure\"\n--\nmm/Kconfig=59=choice\n--\nmm/Kconfig-76-\nmm/Kconfig:77:config ZSWAP_COMPRESSOR_DEFAULT_DEFLATE\nmm/Kconfig-78-\tbool \"Deflate\"\n--\nmm/Kconfig-82-\nmm/Kconfig:83:config ZSWAP_COMPRESSOR_DEFAULT_LZO\nmm/Kconfig-84-\tbool \"LZO\"\n--\nmm/Kconfig-88-\nmm/Kconfig:89:config ZSWAP_COMPRESSOR_DEFAULT_842\nmm/Kconfig-90-\tbool \"842\"\n--\nmm/Kconfig-94-\nmm/Kconfig:95:config ZSWAP_COMPRESSOR_DEFAULT_LZ4\nmm/Kconfig-96-\tbool \"LZ4\"\n--\nmm/Kconfig-100-\nmm/Kconfig:101:config ZSWAP_COMPRESSOR_DEFAULT_LZ4HC\nmm/Kconfig-102-\tbool \"LZ4HC\"\n--\nmm/Kconfig-106-\nmm/Kconfig:107:config ZSWAP_COMPRESSOR_DEFAULT_ZSTD\nmm/Kconfig-108-\tbool \"zstd\"\n--\nmm/Kconfig=112=endchoice\nmm/Kconfig-113-\nmm/Kconfig:114:config ZSWAP_COMPRESSOR_DEFAULT\nmm/Kconfig-115-       string\n"
}

5/2 2026/11/11 22:18 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 34611
							output: 31
							thoughts: 17
						

Thoughts:
Okay, here's my summary, presented as a stream of thought:

**Checking the ZSWAP Configuration in mm/Kconfig**

Alright, let's get down to it. Time to dive into the kernel configuration, specifically the `ZSWAP` option. I need to refresh my memory on the surrounding code, the dependencies, and any potential gotchas. I'll need to locate where `config ZSWAP` is defined, which should be in `mm/Kconfig`. Let's see what else is nearby. I'm going to look at the lines immediately before and after the `ZSWAP` definition to get a good contextual understanding. I'm especially interested in dependencies, help text, and default values. I'll be looking for clues on how the kernel decides whether or not to include this feature, and what other options are impacted by its inclusion. This should give me a solid foundation before I delve any deeper into the code using this configuration. Right, let's get to it.



6/2 2026/11/11 22:18 tool read-file
0m Args:
{
  "File": "mm/Kconfig",
  "FirstLine": 18,
  "LineCount": 40
}

Results:
{
  "Contents": "  18:\t\t  for so called swap devices or swap files in your kernel that are\n  19:\t\t  used to provide more virtual memory than the actual RAM present\n  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  45:\tconfig ZSWAP_SHRINKER_DEFAULT_ON\n  46:\t\tbool \"Shrink the zswap pool on memory pressure\"\n  47:\t\tdepends on ZSWAP\n  48:\t\tdefault n\n  49:\t\thelp\n  50:\t\t  If selected, the zswap shrinker will be enabled, and the pages\n  51:\t\t  stored in the zswap pool will become available for reclaim (i.e\n  52:\t\t  written back to the backing swap device) on memory pressure.\n  53:\t\n  54:\t\t  This means that zswap writeback could happen even if the pool is\n  55:\t\t  not yet full, or the cgroup zswap limit has not been reached,\n  56:\t\t  reducing the chance that cold pages will reside in the zswap pool\n  57:\t\t  and consume memory indefinitely.\n"
}

7/2 2026/11/11 22:18 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 35467
							output: 40
							thoughts: 195
						

Thoughts:
**Examining the Dependencies of Extendable Swap (XSWAP)**

Okay, let's dive into this `config XSWAP` setting. I need to understand its dependencies. Looking at the configuration, it seems pretty straightforward: `XSWAP` requires `SWAP`, `64BIT`, `ZSWAP`, and `SYSFS`. That makes sense; we're talking about an extendable virtual swap, so it needs the core swap functionality, 64-bit addressing, zswap for compression, and the system file system interface.

Now, let's see how this ties into the `xswap_create` function. Ah, here it is, the `zswap_is_enabled()` check. It looks like `xswap` *relies* on `zswap` to function.  If `zswap` isn't active, `xswap_create()` returns `-EOPNOTSUPP`. That's critical. So the existence and usability of `XSWAP` depends directly on having `ZSWAP` operational.

Therefore, for this to work as intended, we need to ensure `zswap` is enabled by default.  The configuration says that `zswap` is enabled if `CONFIG_ZSWAP_DEFAULT_ON` is set or the `zswap.enabled=1` kernel parameter is passed. So if `ZSWAP_DEFAULT_ON` is selected in the configs it ensures this doesn't come up as an issue. We should check what `zswap_is_enabled()` actually does to confirm this assumption.



8/2 2026/11/11 22:18 tool grepper
0m Args:
{
  "Expression": "zswap_is_enabled",
  "PathPrefixes": [
    "include/linux/zswap.h",
    "mm/"
  ]
}

Results:
{
  "Output": "include/linux/zswap.h=35=void zswap_folio_swapin(struct folio *folio);\ninclude/linux/zswap.h:36:bool zswap_is_enabled(void);\ninclude/linux/zswap.h-37-bool zswap_never_enabled(void);\n--\ninclude/linux/zswap.h=65=static inline void zswap_folio_swapin(struct folio *folio) {}\ninclude/linux/zswap.h-66-\ninclude/linux/zswap.h:67:static inline bool zswap_is_enabled(void)\ninclude/linux/zswap.h-68-{\n--\nmm/memcontrol.c=6398=bool mem_cgroup_zswap_writeback_enabled(const struct mem_cgroup *memcg)\n--\nmm/memcontrol.c-6400-\t/* if zswap is disabled, do not block pages going to the swapping device */\nmm/memcontrol.c:6401:\tif (!zswap_is_enabled())\nmm/memcontrol.c-6402-\t\treturn true;\n--\nmm/swapfile.c=4940=static int xswap_create(int prio)\n--\nmm/swapfile.c-4951-\t/* xswap has no backing store, it relies on zswap. */\nmm/swapfile.c:4952:\tif (!zswap_is_enabled())\nmm/swapfile.c-4953-\t\treturn -EOPNOTSUPP;\n--\nmm/zswap.c=125=module_param_named(shrinker_enabled, zswap_shrinker_enabled, bool, 0644);\nmm/zswap.c-126-\nmm/zswap.c:127:bool zswap_is_enabled(void)\nmm/zswap.c-128-{\n"
}

9/2 2026/11/11 22:18 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 36505
							output: 34
							thoughts: 21
						

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

**Investigating Zswap Activation**

Alright, let's dive in. My immediate thought is to check `zswap_is_enabled` within `mm/zswap.c`. We're talking about the core of the Zswap functionality, and this function will be the gatekeeper to understanding whether the feature is actually active or disabled in the system at this point in time. I'm assuming there's a reason we want to know, possibly debugging a performance issue or validating a configuration setting. Knowing the state of that flag, and the conditions under which it's set or cleared, will be crucial for any in-depth analysis of Zswap behavior and how it's affecting memory management. Let's see what the code reveals about its current state.



10/2 2026/11/11 22:19 tool read-file
0m Args:
{
  "File": "mm/zswap.c",
  "FirstLine": 126,
  "LineCount": 10
}

Results:
{
  "Contents": " 126:\t\n 127:\tbool zswap_is_enabled(void)\n 128:\t{\n 129:\t\treturn zswap_enabled;\n 130:\t}\n 131:\t\n 132:\tbool zswap_never_enabled(void)\n 133:\t{\n 134:\t\treturn !static_branch_maybe(CONFIG_ZSWAP_DEFAULT_ON, \u0026zswap_ever_enabled);\n 135:\t}\n"
}

11/2 2026/11/11 22:19 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 36876
							output: 249
							thoughts: 3103
						

Thoughts:
**Xswap Configuration and FocusSymbol Selection for Fuzzing**

Alright, let's break this down. First, we need to ensure the correct kernel configurations are in place. Since `zswap_enabled` is on by default if `CONFIG_ZSWAP_DEFAULT_ON` is enabled, the key configs for xswap are `XSWAP`, `ZSWAP`, `ZSWAP_DEFAULT_ON`, `SWAP`, and `SYSFS`. Debugfs is optional, as `xswap` doesn't strictly depend on `DEBUG_FS`, but the code includes hooks for it. `XSWAP`'s dependency chain is `SWAP && 64BIT && ZSWAP && SYSFS`, and critically, `ZSWAP_DEFAULT_ON` ensures `zswap_is_enabled()` is true which is essential to have XSWAP devices created at all.

Now, the important part: focus symbols for fuzzing. The goal is to identify functions that specifically implement the new xswap feature and avoid "ubiquitous lifecycle hot-paths" like general memory allocators or core synchronization primitives. We want to target the specific feature logic and entry points.

I need to focus on the code that's *added* or *heavily modified* for xswap. I've gone through the code and I've identified key functions:

*   **Sysfs Entrypoints:** `xswap_create_store`, `xswap_destroy_store`
*   **Device Creation/Destruction:** `xswap_create`, `xswap_destroy`, `xswap_destroy_by_name`
*   **Dynamic cluster management:** `xswap_grow`, `xswap_try_shrink`, `xswap_shrink_work_fn`, `xswap_map_clusters`, `xswap_unmap_clusters`
*   **Low-Level Helpers:** `xswap_unmap_clusters_locked`, `xswap_destroy_by_name`
*   **System Calls:** `__swapoff` (or `swapoff`)
*   **Debugfs Functions:** `xswap_debugfs_read`, `xswap_debugfs_add`

I've checked whether these functions are static or inlined, since those aren't directly addressable by the fuzzer. All listed are not-inlined symbols in vmlinux, and are the entry points for the new feature.

`folio_alloc_swap` is a potential candidate, as it is a helper in memory allocation; however, `folio_alloc_swap` is specifically swap allocation, not general memory allocator. In context, `folio_alloc_swap` is called during swap out, so its impact is far narrower and highly specific to xswap, and thus useful.

The `swapoff` syscall is modified to call `xswap_destroy_by_name` if an xswap device is specified. `xswap_destroy_by_name` then calls `xswap_destroy`, implementing the desired semantics, so this makes sense to include it in the corpus.

I'm confident these are the right functions to focus on. They are neither generic nor ubiquitous. The selection ensures the fuzzer targets the core logic of xswap, including device creation, destruction, size management, the sysfs entry points, and interactions with the swap subsystem.



12/2 2026/11/11 22:19 tool set-results
0m Args:
{
  "EnableConfigs": [
    "XSWAP",
    "ZSWAP",
    "ZSWAP_DEFAULT_ON",
    "SWAP"
  ],
  "FocusSymbols": [
    "xswap_create",
    "xswap_destroy",
    "xswap_create_store",
    "xswap_destroy_store",
    "xswap_grow",
    "xswap_try_shrink",
    "xswap_shrink_work_fn",
    "xswap_map_clusters",
    "xswap_unmap_clusters",
    "xswap_destroy_by_name"
  ],
  "Reasoning": "The patch introduces xswap, a file-less virtual swap device backed by zswap, into the core memory management subsystem. It adds new sysfs interfaces (/sys/kernel/mm/xswap/create and destroy), modifies the swapoff syscall, and adds complex dynamic allocation, growing, and shrinking logic using VM_SPARSE vmalloc areas, RCU synchronization, and workqueues. These reachable code paths in core mm should be fuzzed for concurrency issues, memory leaks, and invariant violations.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "XSWAP",
    "ZSWAP",
    "ZSWAP_DEFAULT_ON",
    "SWAP"
  ],
  "FocusSymbols": [
    "xswap_create",
    "xswap_destroy",
    "xswap_create_store",
    "xswap_destroy_store",
    "xswap_grow",
    "xswap_try_shrink",
    "xswap_shrink_work_fn",
    "xswap_map_clusters",
    "xswap_unmap_clusters",
    "xswap_destroy_by_name"
  ],
  "Reasoning": "The patch introduces xswap, a file-less virtual swap device backed by zswap, into the core memory management subsystem. It adds new sysfs interfaces (/sys/kernel/mm/xswap/create and destroy), modifies the swapoff syscall, and adds complex dynamic allocation, growing, and shrinking logic using VM_SPARSE vmalloc areas, RCU synchronization, and workqueues. These reachable code paths in core mm should be fuzzed for concurrency issues, memory leaks, and invariant violations.",
  "WorthFuzzing": true
}

13/1 2026/11/11 22:19 action If
2m Args:
{
  "WorthFuzzing": true
}

Results:
null

14/2 2026/11/11 22:19 agent kmsan-evaluator
2m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch series introduces 'xswap', an extendable file-less swap device backed by zswap using a sparse vmalloc area (VM_SPARSE) to dynamically allocate and map swap cluster metadata (swap_cluster_info) in chunks.\n\nAn evaluation of memory sanitizer applicability indicates that a dedicated KMSAN fuzzing session is not warranted:\n1. No uninitialized memory exposure to userspace: The new sysfs interfaces ('create' and 'destroy') are write-only (mode 0200), and debugfs/procfs interfaces ('/sys/kernel/debug/xswap/xswap\u003cid\u003e' and '/proc/swaps') format plain text output exclusively using scnprintf() and seq_printf()/seq_puts() bounded by returned string lengths. There are no binary kernel structs or padding copied to userspace via copy_to_user, put_user, netlink, or ioctl.\n2. Initialization of all newly allocated buffers and structures: The sparse backing pages for swap_cluster_info are allocated with alloc_page(... | __GFP_ZERO), ensuring all pointer and integer fields start fully zeroed. Cluster spinlocks are explicitly initialized via spin_lock_init() upon mapping. All new struct swap_info_struct fields, stack buffers (e.g., in xswap_parse_size, xswap_destroy_by_name, xswap_debugfs_read), and work structs are properly initialized before use.\n3. No branching or logic dependent on uninitialized data: In the swap fast/slow allocation and readahead paths, new branching flags (such as may_zswap and zswap_checked) are explicitly initialized locals.\n4. Nature of potential risks: The failure modes and risks introduced by this change center around locking hierarchies (xswap_lock, swap_lock, si-\u003elock, ci-\u003elock), RCU grace period synchronization during cluster unmapping, and concurrency races between growth, shrinking, swapoff, and folio allocation/swapin. These are standard locking, use-after-free, and out-of-bounds risks that are fully covered by KASAN, LOCKDEP, and page fault handling.\n\nBecause there are no uninitialized memory risks or info-leaks unique to KMSAN, a dedicated KMSAN run is not justified.",
  "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 21d9e31bbc41c3f61fd71c0b9d6875ed18c6cfc9
Author: syz-cluster <triage@syzkaller.com>
Date:   Wed Nov 11 22:18:28 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/ABI/testing/sysfs-kernel-mm-xswap b/Documentation/ABI/testing/sysfs-kernel-mm-xswap
new file mode 100644
index 00000000000000..f7e7f3e4d2164d
--- /dev/null
+++ b/Documentation/ABI/testing/sysfs-kernel-mm-xswap
@@ -0,0 +1,43 @@
+What:		/sys/kernel/mm/xswap/
+Date:		October 2026
+Contact:	Linux memory management mailing list <linux-mm@kvack.org>
+Description:	File-less swap devices backed by zswap.
+
+		An xswap device has no backing file.  Its slots are backed
+		by the zswap pool, and the device size is set at boot with
+		xswap.max= or CONFIG_XSWAP_DEFAULT_MAX.  The size is fixed
+		for the lifetime of the device.
+
+		The name shown in /proc/swaps, xswap<id>, is synthetic and
+		is not a path. swapoff(2) accepts it, so both "swapoff
+		xswap<id>" and swapoff -a tear the device down. A real
+		file or directory with that name takes precedence: if it
+		opens, it is looked up as a swap file and the synthetic
+		device is not used. Only a name that cannot be opened
+		because it does not exist, including a dangling symlink,
+		is treated as an xswap device. Use the destroy attribute
+		for an unambiguous teardown.
+
+		An xswap device requires zswap.  Disabling zswap at runtime
+		(enabled=0, or max_pool_percent=0) while xswap devices
+		exist leaves them without backing: existing entries can
+		still be read, but new pages cannot be stored.  Destroy the
+		xswap devices before disabling zswap.
+
+What:		/sys/kernel/mm/xswap/create
+Date:		October 2026
+Contact:	Linux memory management mailing list <linux-mm@kvack.org>
+Description:	Create an xswap device.
+
+		Write an optional priority (0..32767), or write nothing for
+		the default priority.  The write fails if zswap is disabled
+		or if the configured size is smaller than one cluster.
+
+What:		/sys/kernel/mm/xswap/destroy
+Date:		October 2026
+Contact:	Linux memory management mailing list <linux-mm@kvack.org>
+Description:	Destroy an xswap device.
+
+		Write the device's stable id.  The id is the number after
+		"xswap" in /proc/swaps, for example 1 for xswap1.  It is
+		not a swap type and is never reused.
diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt
index a1fb40e5000977..95b5ba9ee4f8aa 100644
--- a/Documentation/admin-guide/kernel-parameters.txt
+++ b/Documentation/admin-guide/kernel-parameters.txt
@@ -8752,3 +8752,11 @@ Kernel parameters
 				memory, and other data can't be written using
 				xmon commands.
 			off	xmon is disabled.
+
+	xswap.max=	[KNL,SWAP]
+			Maximum size of a new xswap device. The value is a
+			size in bytes with an optional KMGTPE suffix, a
+			percentage of RAM, or "max" for the largest size
+			the device can address. The default is set by
+			CONFIG_XSWAP_DEFAULT_MAX.
+			Format: <size>[KMGTPE] | <percent>% | max
diff --git a/Documentation/admin-guide/mm/zswap.rst b/Documentation/admin-guide/mm/zswap.rst
index 2464425c783de2..886b50ca90b1ae 100644
--- a/Documentation/admin-guide/mm/zswap.rst
+++ b/Documentation/admin-guide/mm/zswap.rst
@@ -136,3 +136,12 @@ selected.
 A debugfs interface is provided for various statistic about pool size, number
 of pages stored, same-value filled pages and various counters for the reasons
 pages are rejected.
+
+xswap devices
+-------------
+
+An xswap device is a file-less swap device backed by zswap.  While such a
+device exists, do not disable zswap at runtime (``enabled=0``) or set
+``max_pool_percent`` to 0.  The device would have no backing: pages already
+in zswap can still be read, but new pages cannot be stored.  Destroy the
+xswap devices first.
diff --git a/MAINTAINERS b/MAINTAINERS
index ce05a3253baaea..c97ecdd39a8a56 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -17907,6 +17907,7 @@ R:	Youngjun Park <youngjun.park@lge.com>
 L:	linux-mm@kvack.org
 S:	Maintained
 F:	Documentation/ABI/testing/sysfs-kernel-mm-swap
+F:	Documentation/ABI/testing/sysfs-kernel-mm-xswap
 F:	Documentation/mm/swap-table.rst
 F:	include/linux/swap.h
 F:	include/linux/swap_ops.h
diff --git a/include/linux/swap.h b/include/linux/swap.h
index 4f686709d71f00..1e552a8b421b68 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,26 @@ 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 */
+	u64			xswap_id;	/* stable id, shown to userspace */
+	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 +390,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 afff1b25b54387..902e3b1a6e35cc 100644
--- a/mm/Kconfig
+++ b/mm/Kconfig
@@ -122,6 +122,26 @@ 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 is mapped lazily
+	  in chunks, avoiding static pre-allocation overhead.
+
+config XSWAP_DEFAULT_MAX
+	string "Default maximum size of a new xswap device"
+	depends on XSWAP
+	default "200%"
+	help
+	  The maximum size of a newly created xswap device. It accepts a
+	  percentage of RAM (for example "200%"), a size (for example "2T"),
+	  or "max" for the largest size the device can address.
+
+	  xswap.max= on the kernel command line overrides this value.
+
 config ZSMALLOC
 	tristate
 
diff --git a/mm/page_io.c b/mm/page_io.c
index a57cdcf2892dfa..2285fb1735b383 100644
--- a/mm/page_io.c
+++ b/mm/page_io.c
@@ -258,6 +258,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:
@@ -515,6 +524,16 @@ void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio)
 	if (zswap_load(folio) != -ENOENT)
 		return;
 
+	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);
+		return;
+	}
+
 	/* 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 da65d75ceead12..4c965cf99809be 100644
--- a/mm/swap_state.c
+++ b/mm/swap_state.c
@@ -899,6 +899,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;
@@ -984,6 +988,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;
@@ -992,6 +997,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 fcda5eba171402..2d6c13d510672d 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -14,8 +14,11 @@
 #include <linux/mman.h>
 #include <linux/slab.h>
 #include <linux/kernel_stat.h>
+#include <linux/overflow.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>
@@ -31,6 +34,7 @@
 #include <linux/backing-dev.h>
 #include <linux/mutex.h>
 #include <linux/capability.h>
+#include <linux/ctype.h>
 #include <linux/syscalls.h>
 #include <linux/memcontrol.h>
 #include <linux/poll.h>
@@ -42,6 +46,7 @@
 #include <linux/suspend.h>
 #include <linux/zswap.h>
 #include <linux/plist.h>
+#include <linux/debugfs.h>
 
 #include <asm/tlbflush.h>
 #include <linux/leafops.h>
@@ -49,6 +54,260 @@
 #include "internal.h"
 #include "swap.h"
 
+#define DEF_SWAP_PRIO  -1
+
+/*
+ * The highest priority a real swap device can use: one ahead of xswap
+ * would take the page directly, and taking that slot is what xswap
+ * exists to avoid.  At equal priority the list is FIFO, so a real device
+ * that asks for this priority too and is added first wins.
+ */
+#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)
+
+/* 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)
+/*
+ * Shrink thresholds, as a percentage of the mapped range in use.  The stop
+ * point sits inside (SHRINK_WHEN, GROW_WHEN), so shrinking cannot leave the
+ * range in a state that wakes the grow up.
+ */
+#define XSWAP_SHRINK_WHEN	50
+#define XSWAP_SHRINK_UNTIL	70
+
+/*
+ * Grow thresholds, as a percentage of the mapped range in use.  The target
+ * sits above the point where the shrink starts looking (50%) and below the
+ * next grow trigger (85%), so a grow cannot leave the range in a state the
+ * shrink would undo.
+ */
+#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);
+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(u64 id);
+static int xswap_destroy_by_name(const char *name);
+
+/* Stable device id, assigned at create and never reused. */
+static atomic64_t xswap_id_counter = ATOMIC64_INIT(0);
+
+static ssize_t xswap_create_store(struct kobject *kobj,
+				  struct kobj_attribute *attr,
+				  const char *buf, size_t count)
+{
+	int prio = DEF_XSWAP_PRIO;
+	const char *p;
+	int err;
+
+	if (!capable(CAP_SYS_ADMIN))
+		return -EPERM;
+
+	/* "[<prio>]" is optional; a lower one is allowed, not a higher. */
+	p = skip_spaces(buf);
+	if (*p && *p != '\n') {
+		err = kstrtoint(p, 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)
+{
+	u64 id;
+	int err;
+
+	if (!capable(CAP_SYS_ADMIN))
+		return -EPERM;
+
+	err = kstrtoull(buf, 0, &id);
+	if (err)
+		return err;
+
+	err = xswap_destroy(id);
+	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; "max" asks for the largest size the device can address.
+ */
+static unsigned int xswap_size_pct = 200;
+static unsigned long xswap_size_bytes;
+static bool xswap_size_max;
+static bool xswap_size_set;	/* xswap.max= was given */
+
+/*
+ * Parse "200%", "2T" or "max". @str is not modified. @cmdline tells an
+ * explicit xswap.max= from the build-time default, which is clamped
+ * instead of refused when it is too large.
+ */
+static int __init xswap_parse_size(const char *str, const char *what,
+				   bool cmdline)
+{
+	const char *pct;
+	char buf[16];
+	unsigned int pct_val;
+	unsigned long bytes;
+	char *end;
+
+	pct = strchr(str, '%');
+	if (!strcmp(str, "max")) {
+		xswap_size_max = true;
+		xswap_size_pct = 0;
+		xswap_size_bytes = 0;
+	} else if (pct) {
+		size_t len = pct - str;
+
+		if (pct[1] || !len || len >= sizeof(buf))
+			goto bad;
+		memcpy(buf, str, len);
+		buf[len] = '\0';
+		if (kstrtouint(buf, 0, &pct_val) || !pct_val)
+			goto bad;
+		xswap_size_pct = pct_val;
+		xswap_size_bytes = 0;
+		xswap_size_max = false;
+	} else {
+		bytes = memparse(str, &end);
+		if (*end || bytes < PAGE_SIZE)
+			goto bad;
+		/* A default below one cluster would fail every create. */
+		if (!cmdline && bytes < (unsigned long)SWAPFILE_CLUSTER * PAGE_SIZE)
+			goto bad;
+		xswap_size_bytes = bytes;
+		xswap_size_pct = 0;
+		xswap_size_max = false;
+	}
+
+	if (cmdline)
+		xswap_size_set = true;
+	return 0;
+bad:
+	pr_err("xswap: bad %s=%s\n", what, str);
+	return -EINVAL;
+}
+
+static int __init xswap_max_setup(char *str)
+{
+	xswap_parse_size(str, "xswap.max", true);
+	return 1;
+}
+__setup("xswap.max=", xswap_max_setup);
+
+/*
+ * The most a device can address, whatever xswap.max= asked for.  An xswap
+ * slot is still a swap entry, so the swap offset limit applies even though
+ * the data never goes through a physical address.
+ */
+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)
+{
+	unsigned long long pages;
+
+	if (xswap_size_max)
+		return xswap_size_limit();
+
+	if (xswap_size_bytes)
+		return xswap_size_bytes >> PAGE_SHIFT;
+
+	/* Let xswap_create() refuse a size that does not fit in the type. */
+	if (check_mul_overflow((unsigned long long)totalram_pages(),
+			       (unsigned long long)xswap_size_pct, &pages))
+		return ULONG_MAX;
+
+	return div_u64(pages, 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)
+{
+}
+
+static inline int xswap_destroy_by_name(const char *name)
+{
+	return -ENOENT;
+}
+#endif /* CONFIG_XSWAP */
+
 static void swap_range_alloc(struct swap_info_struct *si,
 			     unsigned int nr_entries);
 static bool folio_swapcache_freeable(struct folio *folio);
@@ -66,6 +325,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 +336,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 +663,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)
@@ -654,6 +915,16 @@ 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.
+	 * A racing swapoff can still clear SWP_WRITEOK after this check;
+	 * the work function checks it again, so a late schedule is benign.
+	 */
+	if ((READ_ONCE(si->flags) & (SWP_XSWAP | SWP_WRITEOK)) ==
+	    (SWP_XSWAP | SWP_WRITEOK))
+		schedule_work(&si->xswap_shrink_work);
+#endif
 }
 
 /*
@@ -775,7 +1046,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)) {
@@ -852,7 +1124,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;
 	}
 	/*
@@ -1034,11 +1306,12 @@ static bool swap_prefer_free_cluster(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;
@@ -1048,6 +1321,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;
 
@@ -1076,6 +1352,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);
@@ -1085,12 +1362,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);
@@ -1119,6 +1396,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--;
@@ -1143,6 +1423,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;
 
@@ -1173,7 +1454,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
@@ -1182,6 +1463,18 @@ 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) && (si->flags & SWP_WRITEOK) &&
+	    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);
@@ -1254,6 +1547,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);
@@ -1277,6 +1576,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 {
 		/*
@@ -1310,6 +1614,14 @@ static void add_to_avail_list(struct swap_info_struct *si, bool swapon)
 	if (swapon) {
 		lockdep_assert_held(&si->lock);
 		si->flags |= SWP_WRITEOK;
+		/*
+		 * Count the device here, not after adding it to the list: a
+		 * full device is still active and skips the add below.
+		 */
+		if (si->flags & SWP_XSWAP)
+			atomic_add(1, &nr_xswap_files);
+		else
+			atomic_add(1, &nr_real_swapfiles);
 	} else {
 		if (!(READ_ONCE(si->flags) & SWP_WRITEOK))
 			goto skip;
@@ -1323,10 +1635,11 @@ static void add_to_avail_list(struct swap_info_struct *si, bool swapon)
 	/*
 	 * When device is full and device is on the plist, only one updater will
 	 * see (inuse_pages == si->pages) and will call del_from_avail_list. If
-	 * that updater happen to be here, just skip adding.
+	 * that updater happen to be here, just skip adding.  @val still has
+	 * the off-list bit, so compare its counter part.
 	 */
 	pages = si->pages;
-	if (val == pages) {
+	if ((val & SWAP_USAGE_COUNTER_MASK) == pages) {
 		/* Just like the cmpxchg in del_from_avail_list */
 		if (atomic_long_try_cmpxchg(&si->inuse_pages, &pages,
 					    pages | SWAP_USAGE_OFFLIST_BIT))
@@ -1431,21 +1744,51 @@ 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;
+	}
+#ifdef CONFIG_XSWAP
+	if (si->flags & SWP_XSWAP) {
+		/*
+		 * The cached offset can outlive a shrink that did not see
+		 * it, and the cluster_info page it indexes may be unmapped.
+		 * Fail the fast path; the slow path picks a live cluster.
+		 */
+		unsigned long mapped;
+
+		/* Pairs with the release store in xswap_unmap_clusters_locked(). */
+		mapped = smp_load_acquire(&si->nr_clusters_mapped);
+
+		if (offset / SWAPFILE_CLUSTER >= mapped) {
+			put_swap_device(si);
+			rcu_read_unlock();
+			return false;
+		}
+	}
+#endif
+	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)) {
@@ -1457,17 +1800,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);
@@ -1790,6 +2140,17 @@ static int swap_dup_entries_cluster(struct swap_info_struct *si,
 	return err;
 }
 
+/* Can the folio's cgroup take another zswap page? */
+static bool folio_may_zswap(struct folio *folio)
+{
+	struct obj_cgroup *objcg = get_obj_cgroup_from_folio(folio);
+	bool may_zswap = !objcg || obj_cgroup_may_zswap(objcg);
+
+	if (objcg)
+		obj_cgroup_put(objcg);
+	return may_zswap;
+}
+
 /**
  * folio_alloc_swap - allocate swap space for a folio
  * @folio: folio we want to move to swap
@@ -1806,10 +2167,23 @@ int folio_alloc_swap(struct folio *folio)
 {
 	unsigned int order = folio_order(folio);
 	unsigned int size = 1 << order;
+	/* True unless the gate below finds an xswap device to route away from. */
+	bool may_zswap = true;
+	bool zswap_checked = false;
 
 	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; a device that
+	 * appears before we pick one is handled after the allocation.
+	 */
+	if (atomic_read(&nr_xswap_files)) {
+		may_zswap = folio_may_zswap(folio);
+		zswap_checked = true;
+	}
+
 	if (order) {
 		/*
 		 * Reject large allocation when THP_SWAP is disabled. Check below
@@ -1830,8 +2204,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))) {
@@ -1839,6 +2213,22 @@ int folio_alloc_swap(struct folio *folio)
 			goto again;
 	}
 
+	/*
+	 * The xswap gate was skipped because there was no device when we
+	 * looked. One may have appeared since; check before keeping the
+	 * xswap slot the allocator may have picked.
+	 */
+	if (unlikely(!zswap_checked && atomic_read(&nr_xswap_files) &&
+		     folio_test_swapcache(folio) &&
+		     (__swap_entry_to_info(folio->swap)->flags & SWP_XSWAP))) {
+		zswap_checked = true;
+		may_zswap = folio_may_zswap(folio);
+		if (!may_zswap) {
+			swap_cache_del_folio(folio);
+			goto again;
+		}
+	}
+
 	/* Need to call this even if allocation failed, for MEMCG_SWAP_FAIL. */
 	if (unlikely(mem_cgroup_try_charge_swap(folio))) {
 		swap_cache_del_folio(folio);
@@ -2249,8 +2639,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) {
@@ -2260,6 +2653,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);
@@ -2301,6 +2695,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);
@@ -2488,6 +2885,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;
@@ -2527,9 +2926,15 @@ unsigned int count_swap_pages(int type, int free)
 
 		spin_lock(&sis->lock);
 		if (sis->flags & SWP_WRITEOK) {
-			n = sis->pages;
-			if (free)
-				n -= swap_usage_in_pages(sis);
+			/* Hibernation only; it never selects an xswap device. */
+			if (unlikely(sis->flags & SWP_XSWAP)) {
+				WARN_ON_ONCE(1);
+				n = 0;
+			} else {
+				n = sis->pages;
+				if (free)
+					n -= swap_usage_in_pages(sis);
+			}
 		}
 		spin_unlock(&sis->lock);
 	}
@@ -2850,14 +3255,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
@@ -2865,11 +3287,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.
@@ -2879,13 +3301,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;
@@ -2895,7 +3317,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;
@@ -2905,7 +3326,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;
@@ -3193,20 +3614,72 @@ 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().
+		 * A grow may publish after this read, but no slot comes from
+		 * those clusters once WRITEOK is clear.  Cached clusters are
+		 * inside the range; try_to_unuse()'s rescan catches any slot
+		 * taken after the walk.
+		 */
+		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;
+
+		/* A late schedule must not be pending when the work is reinitialized. */
+		disable_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, and the unmap helper handles an empty range.
+		 */
+		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 */
@@ -3218,11 +3691,14 @@ static void free_swap_cluster_info(struct swap_cluster_info *cluster_info,
 		spin_unlock(&ci->lock);
 	}
 	kvfree(cluster_info);
+	si->cluster_info = NULL;
 }
 
 /*
- * Called after swap device's reference count is dead, so
- * neither scan nor allocation will use it.
+ * Invalidate the per-cpu cluster cache for @si.  A caller that has not
+ * already killed @si->users and waited must follow with synchronize_rcu()
+ * before unmapping cluster_info, since a reader may already have loaded
+ * a cached offset.
  */
 static void flush_percpu_swap_cluster(struct swap_info_struct *si)
 {
@@ -3231,25 +3707,20 @@ static void flush_percpu_swap_cluster(struct swap_info_struct *si)
 
 	for_each_possible_cpu(cpu) {
 		pcp_si = per_cpu_ptr(percpu_swap_cluster.si, cpu);
-		/*
-		 * Invalidate the percpu swap cluster cache, si->users
-		 * is dead, so no new user will point to it, just flush
-		 * any existing user.
-		 */
+		/* Invalidate the per-cpu swap cluster cache for @si. */
 		for (i = 0; i < SWAP_NR_ORDERS; i++)
 			cmpxchg(&pcp_si[i], si, NULL);
 	}
 }
 
+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))
@@ -3259,14 +3730,27 @@ SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
 
 	CLASS(filename, pathname)(specialfile);
 	victim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0);
-	if (IS_ERR(victim))
-		return PTR_ERR(victim);
+	if (IS_ERR(victim)) {
+		/*
+		 * An xswap device has no file, so /proc/swaps shows a name
+		 * that cannot be opened. Accept it here so swapoff -a works.
+		 * Only a missing name is taken for a device; a real file or
+		 * directory that failed for another reason must not match.
+		 */
+		if (PTR_ERR(victim) != -ENOENT)
+			return PTR_ERR(victim);
+
+		err = xswap_destroy_by_name(pathname->name);
+		if (err == -ENOENT)
+			return PTR_ERR(victim);
+		return err;
+	}
 
 	mapping = victim->f_mapping;
 	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;
 			}
@@ -3285,20 +3769,66 @@ 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)
+{
+	/*
+	 * The device's pages are its address space, not backing storage.
+	 * The commit limit it added may have been committed against, so
+	 * skip the probe until the limit stops counting that space.
+	 */
+	if (!(p->flags & SWP_XSWAP)) {
+		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);
 
@@ -3309,7 +3839,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;
 	}
 
 	/*
@@ -3330,7 +3860,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);
@@ -3340,10 +3871,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);
@@ -3351,14 +3878,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
@@ -3369,13 +3904,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
@@ -3406,7 +3938,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;
@@ -3427,7 +3960,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;
 	}
@@ -3440,6 +3974,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;
@@ -3456,11 +4003,23 @@ 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[32];
+
+#ifdef CONFIG_XSWAP
+		len = scnprintf(name, sizeof(name), "xswap%llu",
+				(unsigned long long)si->xswap_id);
+#else
+		/* CONFIG_XSWAP=n has no file-less devices; keep the type. */
+		len = scnprintf(name, sizeof(name), "xswap%d", si->type);
+#endif
+		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);
@@ -3671,12 +4230,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;
@@ -3693,29 +4248,636 @@ static unsigned long read_swap_header(struct swap_info_struct *si,
 	return maxpages;
 }
 
-static int setup_swap_clusters_info(struct swap_info_struct *si,
-				    union swap_header *swap_header,
-				    unsigned long maxpages)
+#ifdef CONFIG_XSWAP
+static int xswap_map_clusters(struct swap_info_struct *si,
+			      unsigned long start_idx, unsigned long nr)
 {
-	unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
-	struct swap_cluster_info *cluster_info;
-	int err = -ENOMEM;
+	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;
 
-	cluster_info = kvzalloc_objs(*cluster_info, nr_clusters);
-	if (!cluster_info)
-		goto err;
-
-	for (i = 0; i < nr_clusters; i++)
-		spin_lock_init(&cluster_info[i].lock);
+	mutex_lock(&si->xswap_lock);
 
-	if (!(si->flags & SWP_SOLIDSTATE)) {
-		si->global_cluster = kmalloc_obj(*si->global_cluster);
-		if (!si->global_cluster)
-			goto err;
-		for (i = 0; i < SWAP_NR_ORDERS; i++)
-			si->global_cluster->next[i] = SWAP_ENTRY_INVALID;
-		spin_lock_init(&si->global_cluster_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;
+}
+
+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]);
+}
+
+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(&this_cpu_ptr(&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);
+	if (!nr_new)
+		return 0;
+
+	/*
+	 * 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;
+
+	/*
+	 * Link the clusters even if swapoff cleared SWP_WRITEOK while we
+	 * mapped. The caller keeps the device alive, and nothing takes a
+	 * cluster while WRITEOK is clear. If try_to_unuse() fails, the
+	 * reinserted device needs them.
+	 */
+	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;
+}
+
+/*
+ * Caller must hold si->xswap_lock.  Cannot fail.  @wait drains the per-cpu
+ * cluster cache and waits one RCU grace period before unmapping.
+ */
+static void xswap_unmap_clusters_locked(struct swap_info_struct *si,
+					unsigned long start_idx, unsigned long nr,
+					bool wait)
+{
+	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;
+
+	/*
+	 * Publish the smaller range before its memory goes away.  Readers
+	 * that use nr_clusters_mapped without xswap_lock pair with this
+	 * store using smp_load_acquire().
+	 */
+	smp_store_release(&si->nr_clusters_mapped, start_idx);
+
+	if (vm_start >= vm_end) {
+		/*
+		 * The clusters sit inside one page that the preceding
+		 * cluster shares, so there is nothing to unmap.  The page
+		 * goes away with that cluster; publishing the smaller
+		 * cluster count is still correct.
+		 */
+		return;
+	}
+
+	if (wait) {
+		/*
+		 * 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.
+		 */
+		flush_percpu_swap_cluster(si);
+		synchronize_rcu();
+	}
+
+	npages = (vm_end - vm_start) >> PAGE_SHIFT;
+
+	/*
+	 * vm_area_unmap_pages() refuses a range above totalram_pages() and
+	 * returns without clearing the PTEs.  Freeing those pages would
+	 * leave dangling mappings, so use the batch path for that case.
+	 */
+	if (npages <= totalram_pages()) {
+		/* Reclaim here would re-enter xswap_map_clusters() and its lock. */
+		noreclaim_flags = memalloc_noreclaim_save();
+		pages = kvmalloc_array(npages, sizeof(*pages),
+				       GFP_KERNEL | __GFP_NOMEMALLOC);
+		memalloc_noreclaim_restore(noreclaim_flags);
+		if (pages) {
+			xswap_unmap_range(si, vm_start, vm_end, pages, npages);
+			kvfree(pages);
+			return;
+		}
+	}
+
+	/* No memory for the array, or too large a range: unmap in batches. */
+	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));
+	}
+}
+
+static void xswap_unmap_clusters(struct swap_info_struct *si,
+				 unsigned long start_idx, unsigned long nr)
+{
+	mutex_lock(&si->xswap_lock);
+	/*
+	 * The teardown caller has already drained and waited in __swapoff();
+	 * the create failure path has no readers.
+	 */
+	xswap_unmap_clusters_locked(si, start_idx, nr, false);
+	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;
+
+	/* The mapped range is a prefix, so the first hole ends it. */
+	if (!pte_present(ptep_get(pte)))
+		return 1;
+	*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 two RCU grace periods
+ * 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 two RCU grace periods.
+	 */
+	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;
+
+	/*
+	 * An allocation can enter a cluster from the per-cpu cache without
+	 * going through the lists, so drain the cache first.  xswap devices
+	 * are SWP_SOLIDSTATE, so the per-cpu cache is the only cache.  Only
+	 * then do the checks below hold: a cluster taken from a list takes
+	 * si->lock, which is what the check holds.
+	 *
+	 * The unmap helper below drains the cache and waits again: a cluster
+	 * can be taken and freed between this recheck and the unmap, putting
+	 * it back in the per-cpu cache.
+	 */
+	flush_percpu_swap_cluster(si);
+	synchronize_rcu();
+
+	/*
+	 * Only shrink a run that reaches the mapped end; otherwise
+	 * truncating nr_clusters_mapped would orphan the active tail.
+	 * move_cluster() takes si->lock under ci->lock, so ci->lock is
+	 * taken with trylock here to avoid the reverse order.
+	 *
+	 * With si->lock held, the writes below need no ci->lock: a FREE
+	 * cluster leaves the free list only in isolate_lock_cluster(),
+	 * every move_cluster() caller holds ci->lock (the trylock above
+	 * catches one), a FREE cluster's count is 0 and only falls, and
+	 * the drained cache holds no FREE cluster.
+	 */
+	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);
+
+	/*
+	 * A cluster can be taken and freed between the recheck above and the
+	 * unmap, putting it back in the per-cpu cache.  Drain and wait again.
+	 */
+	xswap_unmap_clusters_locked(si, start_idx, nr_unmap, true);
+	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),
+			"type %d\nclusters_max %lu\nclusters_mapped %lu\nusage_pages %lu\ntail_free %lu\ngrows %lu\nshrinks %lu\n",
+			si->type, 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[32];
+
+	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), "xswap%llu",
+		 (unsigned long long)si->xswap_id);
+	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)
+{
+	unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
+	struct swap_cluster_info *cluster_info;
+	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);
+			}
+		}
+
+		return 0;
+
+err_unmap:
+		/* swap_cluster_setup_bad_slot() allocates cluster 0's table. */
+		swap_cluster_free_table(&si->cluster_info[0]);
+		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);
+
+	if (!(si->flags & SWP_SOLIDSTATE)) {
+		si->global_cluster = kmalloc_obj(*si->global_cluster);
+		if (!si->global_cluster)
+			goto err;
+		for (i = 0; i < SWAP_NR_ORDERS; i++)
+			si->global_cluster->next[i] = SWAP_ENTRY_INVALID;
+		spin_lock_init(&si->global_cluster_lock);
 	}
 
 	/*
@@ -3769,10 +4931,190 @@ 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;
+	unsigned long limit;
+	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 an explicitly requested size the device cannot address;
+	 * clamp the default size, which nobody asked for.
+	 */
+	limit = xswap_size_limit();
+	maxpages = xswap_size_pages();
+	if (xswap_size_set && maxpages > limit) {
+		pr_err("xswap: xswap.max is larger than the device can address\n");
+		return -EINVAL;
+	}
+	maxpages = min(maxpages, limit);
+	/*
+	 * 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);
+	INIT_WORK(&si->xswap_shrink_work, xswap_shrink_work_fn);
+
+	/* Cluster-aligned, so no cluster holds a slot past si->max. */
+	maxpages = rounddown(maxpages, SWAPFILE_CLUSTER);
+
+	si->bdev = NULL;
+	si->swap_file = NULL;
+	si->flags |= SWP_XSWAP | SWP_SOLIDSTATE;
+	si->max = maxpages;
+	si->pages = maxpages - 1;
+	/*
+	 * Set before the device is enabled, for debugfs; destroy only matches
+	 * a WRITEOK device, so the create window is not reachable.
+	 */
+	si->xswap_id = atomic64_inc_return(&xswap_id_counter);
+	/*
+	 * 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;
+
+	error = zswap_swapon(si->type, si->max);
+	if (error)
+		goto bad_swap;
+
+	mutex_lock(&swapon_mutex);
+	/* Two creates would race to make the root directory. */
+	xswap_debugfs_add(si);
+	si->prio = prio;
+	si->list.prio = -si->prio;
+	si->avail_list.prio = -si->prio;
+	enable_swap_info(si);
+	pr_info("xswap: adding extendable swap device xswap%llu (prio %d, %lu pages)\n",
+		(unsigned long long)si->xswap_id, 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 stable id. */
+static int xswap_destroy(u64 id)
+{
+	struct swap_info_struct *p = NULL;
+	unsigned int type;
+	int err;
+
+	spin_lock(&swap_lock);
+	/*
+	 * Match only a device that is fully enabled: one still being created
+	 * is not WRITEOK yet, and one being destroyed has lost it. Neither
+	 * is a valid target, so both read as "no such device".
+	 */
+	for (type = 0; type < nr_swapfiles; type++) {
+		struct swap_info_struct *q = swap_info[type];
+
+		if (q && (q->flags & (SWP_XSWAP | SWP_WRITEOK)) ==
+			 (SWP_XSWAP | SWP_WRITEOK) && q->xswap_id == id) {
+			p = q;
+			break;
+		}
+	}
+	if (!p) {
+		spin_unlock(&swap_lock);
+		return -ENODEV;
+	}
+	/* 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);
+}
+
+static int xswap_destroy_by_name(const char *name)
+{
+	const char *p;
+	char buf[24];
+	u64 id;
+	int err;
+
+	/* Strictly "xswap<digits>": no sign, no trailing newline. */
+	if (strncmp(name, "xswap", 5))
+		return -ENOENT;
+
+	p = name + 5;
+	if (!isdigit((unsigned char)*p))
+		return -ENOENT;
+	while (isdigit((unsigned char)*p))
+		p++;
+	if (*p)
+		return -ENOENT;
+
+	if (strscpy(buf, name + 5, sizeof(buf)) < 0)
+		return -ENOENT;
+
+	err = kstrtou64(buf, 10, &id);
+	if (err)
+		return -ENOENT;
+
+	err = xswap_destroy(id);
+	if (err == -ENODEV)
+		return -ENOENT;
+	return err;
+}
+#endif /* CONFIG_XSWAP */
+
 SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 {
 	struct swap_info_struct *si;
@@ -3877,7 +5219,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;
 	}
@@ -3968,7 +5310,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" : "",
@@ -3991,7 +5333,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
@@ -4104,6 +5446,13 @@ static int __init swapfile_init(void)
 {
 	swapfile_maximum_size = arch_max_swapfile_size();
 
+#ifdef CONFIG_XSWAP
+	/* xswap.max= on the command line overrides the build-time default. */
+	if (!xswap_size_set)
+		xswap_parse_size(CONFIG_XSWAP_DEFAULT_MAX,
+				 "CONFIG_XSWAP_DEFAULT_MAX", false);
+#endif
+
 	/*
 	 * Once a cluster is freed, it's swap table content is read
 	 * only, and all swap cache readers (swap_cache_*) verifies
@@ -4119,6 +5468,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 37d217860a6b2e..cef142d2ff8560 100644
--- a/mm/zswap.c
+++ b/mm/zswap.c
@@ -1095,6 +1095,11 @@ static int zswap_writeback_entry(struct swap_io_ctx *ctx,
 	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);
@@ -1601,7 +1606,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;
@@ -1671,7 +1678,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:
 	/*

15/3 2026/11/11 22:19 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 31210
							output: 21
							thoughts: 2006
						

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

Okay, let's break this down. My primary concern here is determining whether this patch series, introducing extendable virtual swap backed by zswap (XSWAP), necessitates a dedicated KMSAN fuzzing session. I need to be precise; KMSAN is expensive.  Given my expertise, I understand the critical difference between KASAN and KMSAN. KASAN is already robust in this kernel, covering a lot of ground. KMSAN is for catching *uninitialized* memory reads – the stuff KASAN misses. I need to only trigger a KMSAN session if KASAN, LOCKDEP, and the existing standard checks *won't* catch a bug.

Based on the rules provided, I must assess if XSWAP introduces or modifies code that could expose uninitialized memory risks, specifically: kernel data structures being sent to user space (where padding or fields might be uninitialized), conditional logic based on potentially uninitialized variables, allocation of complex data structures where uninitialized fields could be read later, or bounds checks that inadvertently expose uninitialized bytes.

So, let's dig into the code. The patch touches several files, including kernel documentation, Kconfig, and the core swap implementation. I'll focus on the files that handle user-space interaction and data structures. Specifically, I'm concerned about what's exposed to user space, and where data structures are allocated, initialized, and used.

First, `mm/swapfile.c` has `xswap_create_store` and `xswap_destroy_store` (sysfs attributes) and `xswap_debugfs_read`. `xswap_create_store` and `xswap_destroy_store` seem relatively safe. They handle integers read from user space, and the code clearly validates input. The data passed to `xswap_create` and `xswap_destroy` should be properly handled.

However, `xswap_debugfs_read` catches my attention. This is where kernel data is sent to the user. I need to confirm that `tmp` will be filled with valid and initialized data. Looking closer, the code uses `scnprintf` to format the string `tmp`, and `simple_read_from_buffer` to transfer the formatted output. It appears `scnprintf` constructs the string, and the length of the string `len` is correctly tracked. Thus, it appears safe.

Next, I need to check `swap_show` in `/proc/swaps`. The important part here is the code snippet for the `name` field, as this is data that could be read by user space. The `xswap` device is identified using `scnprintf`, so this too appears safe.

The next point to consider is how memory is allocated and initialized. Let's look at `xswap_map_clusters`. I see the `__GFP_ZERO` flag. Excellent! This is critical. The pages allocated for `si->cluster_info` are zeroed. This means that *all* fields in `struct swap_cluster_info` begin as zero. The subsequent spinlock initialization is also sound, as the lock itself is initialized in the zeroed memory. I'll also ensure zero-initialization is performed by using grep for `struct swap_cluster_info`.

So, after this thorough review, I don't see any obvious KMSAN red flags. The code uses `scnprintf` and checks lengths correctly when sending data to user space.  More importantly, memory is zero-initialized using `__GFP_ZERO` when data structures are allocated.

Therefore, my assessment is that **a dedicated KMSAN fuzzing session is likely not necessary** for this patch series. The standard KASAN and other bug detectors should be sufficient.



16/3 2026/11/11 22:19 tool grepper
0m Args:
{
  "Expression": "struct swap_cluster_info \\{"
}

Results:
{
  "Output": "mm/swap.h=39=extern struct swap_info_struct *swap_info[];\n--\nmm/swap.h-49- */\nmm/swap.h:50:struct swap_cluster_info {\nmm/swap.h-51-\tspinlock_t lock;\t/*\n"
}

17/3 2026/11/11 22:19 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 34118
							output: 32
							thoughts: 17
						

Thoughts:
Okay, let's dive into this. Here's my thought process on the matter:

**Delving into `mm/swap.h`**

Alright, I need to understand this swap implementation better. My initial thought is to zero in on a specific point of interest within the `mm/swap.h` header file. Let's start around line 50. I know this file holds a treasure trove of definitions and declarations related to the memory management subsystem's swapping mechanisms. I'm expecting to find core data structures, macro definitions, or function prototypes crucial for understanding how virtual memory pages are moved to and from swap space. Hopefully, focusing on that specific line will help me hone in on a key concept or data element. I'm aiming to quickly grasp a key data structure. I'm looking for anything that illuminates how pages are described, managed or swapped.



18/3 2026/11/11 22:20 tool read-file
0m Args:
{
  "File": "mm/swap.h",
  "FirstLine": 48,
  "LineCount": 50
}

Results:
{
  "Contents": "  48:\t * protected by cluster lock.\n  49:\t */\n  50:\tstruct swap_cluster_info {\n  51:\t\tspinlock_t lock;\t/*\n  52:\t\t\t\t\t * Protect swap_cluster_info fields\n  53:\t\t\t\t\t * other than list, and swap_info_struct-\u003eswap_map\n  54:\t\t\t\t\t * elements corresponding to the swap cluster.\n  55:\t\t\t\t\t */\n  56:\t\tu16 count;\n  57:\t\tu8 flags;\n  58:\t\tu8 order;\n  59:\t\tatomic_long_t __rcu *table;\t/* Swap table entries, see mm/swap_table.h */\n  60:\t\tunsigned int *extend_table;\t/* For large swap count, protected by ci-\u003elock */\n  61:\t#ifdef CONFIG_MEMCG\n  62:\t\tstruct swap_memcg_table *memcg_table;\t/* Swap table entries' cgroup record */\n  63:\t#endif\n  64:\t#if !SWAP_TABLE_HAS_ZEROFLAG\n  65:\t\tunsigned long *zero_bitmap;\n  66:\t#endif\n  67:\t\tstruct list_head list;\n  68:\t};\n  69:\t\n  70:\t/* All on-list cluster must have a non-zero flag. */\n  71:\tenum swap_cluster_flags {\n  72:\t\tCLUSTER_FLAG_NONE = 0, /* For temporary off-list cluster */\n  73:\t\tCLUSTER_FLAG_FREE,\n  74:\t\tCLUSTER_FLAG_NONFULL,\n  75:\t\tCLUSTER_FLAG_FRAG,\n  76:\t\t/* Clusters with flags above are allocatable */\n  77:\t\tCLUSTER_FLAG_USABLE = CLUSTER_FLAG_FRAG,\n  78:\t\tCLUSTER_FLAG_FULL,\n  79:\t\tCLUSTER_FLAG_DISCARD,\n  80:\t\tCLUSTER_FLAG_MAX,\n  81:\t};\n  82:\t\n  83:\textern int vm_swappiness;\n  84:\t\n  85:\tstatic inline int mem_cgroup_swappiness(const struct mem_cgroup *memcg)\n  86:\t{\n  87:\t#ifdef CONFIG_MEMCG_V1\n  88:\t\tif (!cgroup_subsys_on_dfl(memory_cgrp_subsys) \u0026\u0026\n  89:\t\t    !mem_cgroup_disabled() \u0026\u0026 !mem_cgroup_is_root(memcg))\n  90:\t\t\treturn READ_ONCE(memcg-\u003eswappiness);\n  91:\t#endif\n  92:\t\treturn READ_ONCE(vm_swappiness);\n  93:\t}\n  94:\t\n  95:\t#ifdef CONFIG_SWAP\n  96:\t#include \u003clinux/swapops.h\u003e /* for swp_offset */\n  97:\t#include \u003clinux/zswap.h\u003e /* for zswap_is_present */\n"
}

19/3 2026/11/11 22:20 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 35092
							output: 20
							thoughts: 83
						

Thoughts:
Okay, let's break this down.

**Diving into the `swap_cluster_info` Structure and Its Allocation**

Alright, I'm looking at this `struct swap_cluster_info` and the first thing that jumps out is that it's allocated on zeroed pages, which makes sense; we want a clean slate. The `__GFP_ZERO` flag is pretty standard for that. Then, we initialize the spinlock `ci->lock` using `spin_lock_init`. The list initialization happens later when it's moved or actively used. Makes perfect sense from a memory management perspective.

But hold on, my curiosity is piqued. I wonder how this interacts with the bigger picture of swap space management. How is this linked to the higher-level allocation? Specifically, what happens with `alloc_swap_info()`? How exactly does that allocation work in relation to this cluster info structure? I need to understand that relationship.

Time to jump into `alloc_swap_info()` and see how the pieces fit together. Let's see what the actual allocation mechanism looks like.



20/3 2026/11/11 22:20 tool grepper
0m Args:
{
  "Expression": "alloc_swap_info\\("
}

Results:
{
  "Output": "mm/swapfile.c=3819=static int __swapoff(struct swap_info_struct *p)\n--\nmm/swapfile.c-3899-\t * Clear the SWP_USED flag after all resources are freed so that swapon\nmm/swapfile.c:3900:\t * can reuse this swap_info in alloc_swap_info() safely.  It is ok to\nmm/swapfile.c-3901-\t * not hold p-\u003elock after we cleared its SWP_WRITEOK.\n--\nmm/swapfile.c=4073=late_initcall(max_swapfiles_check);\n--\nmm/swapfile.c-4075-\nmm/swapfile.c:4076:static struct swap_info_struct *alloc_swap_info(void)\nmm/swapfile.c-4077-{\n--\nmm/swapfile.c=4940=static int xswap_create(int prio)\n--\nmm/swapfile.c-4976-\nmm/swapfile.c:4977:\tsi = alloc_swap_info();\nmm/swapfile.c-4978-\tif (IS_ERR(si))\n--\nmm/swapfile.c=5118=SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)\n--\nmm/swapfile.c-5144-\t */\nmm/swapfile.c:5145:\tsi = alloc_swap_info();\nmm/swapfile.c-5146-\tif (IS_ERR(si))\n"
}

21/3 2026/11/11 22:20 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 35836
							output: 35
							thoughts: 20
						

Thoughts:
Okay, let's dive into this. I'm going to take a look at the `alloc_swap_info()` function within `mm/swapfile.c`. My primary interest here is how the kernel manages swap space allocation. I need to understand the fundamental mechanics of how swap information structures are created and initialized. I'm expecting to find details related to:

*   **Data Structures:** What structures are used to represent a swap area, beyond just the obvious `swap_info_struct`? Are there supporting structures? How are these intertwined?
*   **Initialization:** What initialization steps are taken when a new swap area is detected or enabled? What metadata is being established? Does this function handle any disk setup/format related tasks or is that abstracted elsewhere?
*   **Error Handling:** How does this function deal with allocation failures? What checks are in place to ensure the integrity of the proposed swap area and the system overall? Are there race conditions it manages?
*   **Integration:** How does `alloc_swap_info()` fit into the broader swap management framework? Is it called directly from the swap initialization sequence, or is it part of a layered process? Where does it get called from?
*   **Interaction with underlying block devices:** I want to see how these initializations map to the underlying block device for the swap area, if at all. Are there checks here?

This initial reading will serve as a foundation for understanding more complex swap operations. I need to establish the basic primitives before considering things like page migration and swapping, of course. Time to read this code.



22/3 2026/11/11 22:20 tool read-file
0m Args:
{
  "File": "mm/swapfile.c",
  "FirstLine": 4076,
  "LineCount": 45
}

Results:
{
  "Contents": "4076:\tstatic struct swap_info_struct *alloc_swap_info(void)\n4077:\t{\n4078:\t\tstruct swap_info_struct *p;\n4079:\t\tstruct swap_info_struct *defer = NULL;\n4080:\t\tunsigned int type;\n4081:\t\n4082:\t\tp = kvzalloc_obj(struct swap_info_struct);\n4083:\t\tif (!p)\n4084:\t\t\treturn ERR_PTR(-ENOMEM);\n4085:\t\n4086:\t\tif (percpu_ref_init(\u0026p-\u003eusers, swap_users_ref_free,\n4087:\t\t\t\t    PERCPU_REF_INIT_DEAD, GFP_KERNEL)) {\n4088:\t\t\tkvfree(p);\n4089:\t\t\treturn ERR_PTR(-ENOMEM);\n4090:\t\t}\n4091:\t\n4092:\t\tspin_lock(\u0026swap_lock);\n4093:\t\tfor (type = 0; type \u003c nr_swapfiles; type++) {\n4094:\t\t\tif (!(swap_info[type]-\u003eflags \u0026 SWP_USED))\n4095:\t\t\t\tbreak;\n4096:\t\t}\n4097:\t\tif (type \u003e= MAX_SWAPFILES) {\n4098:\t\t\tspin_unlock(\u0026swap_lock);\n4099:\t\t\tpercpu_ref_exit(\u0026p-\u003eusers);\n4100:\t\t\tkvfree(p);\n4101:\t\t\treturn ERR_PTR(-EPERM);\n4102:\t\t}\n4103:\t\tif (type \u003e= nr_swapfiles) {\n4104:\t\t\tp-\u003etype = type;\n4105:\t\t\t/*\n4106:\t\t\t * Publish the swap_info_struct after initializing it.\n4107:\t\t\t * Note that kvzalloc() above zeroes all its fields.\n4108:\t\t\t */\n4109:\t\t\tsmp_store_release(\u0026swap_info[type], p); /* rcu_assign_pointer() */\n4110:\t\t\tnr_swapfiles++;\n4111:\t\t} else {\n4112:\t\t\tdefer = p;\n4113:\t\t\tp = swap_info[type];\n4114:\t\t\t/*\n4115:\t\t\t * Do not memset this entry: a racing procfs swap_next()\n4116:\t\t\t * would be relying on p-\u003etype to remain valid.\n4117:\t\t\t */\n4118:\t\t}\n4119:\t\tp-\u003eswap_extent_root = RB_ROOT;\n4120:\t\tplist_node_init(\u0026p-\u003elist, 0);\n"
}

23/3 2026/11/11 22:20 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 36899
							output: 35
							thoughts: 144
						

Thoughts:
Okay, let's dive into this `alloc_swap_info()` function, focusing on how it handles `swap_info[type]`.

**Analyzing alloc_swap_info() and Swap Info Reuse**

Alright, I'm specifically keying in on how this function reuses elements of the `swap_info[type]` array. I need to understand this thoroughly. Now, looking at lines 4112-4117, that `else` block is what I'm interested in:

Okay, so if we don't need a new entry, we *reuse* an existing `swap_info[type]` entry! That `p = swap_info[type]` assignment is the key. But wait, this is interesting. I'm noting the comment: *"Do not memset this entry: a racing procfs swap_next() would be relying on p->type to remain valid."* Clearly, there's a concurrency consideration here, and `procfs` is depending on that `type` field to remain intact. This implies that some other process might be reading this memory at the same time, probably via a procfs entry. We are reusing an existing structure, and therefore we need to be careful not to initialize it, because another process could be relying on the values present in the struct. This needs further investigation.

Now, let's see what happens after that. Lines 4120 onward are what I need to look at next! This reuse pattern is fundamental, and I need to see how the system ensures everything remains consistent.


24/3 2026/11/11 22:20 tool read-file
0m Args:
{
  "File": "mm/swapfile.c",
  "FirstLine": 4120,
  "LineCount": 40
}

Results:
{
  "Contents": "4120:\t\tplist_node_init(\u0026p-\u003elist, 0);\n4121:\t\tplist_node_init(\u0026p-\u003eavail_list, 0);\n4122:\t\tp-\u003eflags = SWP_USED;\n4123:\t\tspin_unlock(\u0026swap_lock);\n4124:\t\tif (defer) {\n4125:\t\t\tpercpu_ref_exit(\u0026defer-\u003eusers);\n4126:\t\t\tkvfree(defer);\n4127:\t\t}\n4128:\t\tspin_lock_init(\u0026p-\u003elock);\n4129:\t\tatomic_long_set(\u0026p-\u003einuse_pages, SWAP_USAGE_OFFLIST_BIT);\n4130:\t\tinit_completion(\u0026p-\u003ecomp);\n4131:\t\n4132:\t\treturn p;\n4133:\t}\n4134:\t\n4135:\tstatic int claim_swapfile(struct swap_info_struct *si, struct inode *inode)\n4136:\t{\n4137:\t\tif (S_ISBLK(inode-\u003ei_mode)) {\n4138:\t\t\tsi-\u003ebdev = I_BDEV(inode);\n4139:\t\t\t/*\n4140:\t\t\t * Zoned block devices contain zones that have a sequential\n4141:\t\t\t * write only restriction.  Hence zoned block devices are not\n4142:\t\t\t * suitable for swapping.  Disallow them here.\n4143:\t\t\t */\n4144:\t\t\tif (bdev_is_zoned(si-\u003ebdev))\n4145:\t\t\t\treturn -EINVAL;\n4146:\t\t\tsi-\u003eflags |= SWP_BLKDEV;\n4147:\t\t} else if (S_ISREG(inode-\u003ei_mode)) {\n4148:\t\t\tsi-\u003ebdev = inode-\u003ei_sb-\u003es_bdev;\n4149:\t\t}\n4150:\t\n4151:\t\treturn 0;\n4152:\t}\n4153:\t\n4154:\t\n4155:\t/*\n4156:\t * Find out how many pages are allowed for a single swap device. There\n4157:\t * are two limiting factors:\n4158:\t * 1) the number of bits for the swap offset in the swp_entry_t type, and\n4159:\t * 2) the number of bits in the swap pte, as defined by the different\n"
}

25/3 2026/11/11 22:20 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 38027
							output: 28
							thoughts: 3892
						

Thoughts:
**Xswap Initialization and Usage: A Comprehensive Review**

Okay, let's break this down. My goal here is to determine if this new `xswap` implementation introduces any potential vulnerabilities related to uninitialized memory access. I'm focusing on the core aspects of how `xswap` structures are initialized, used, and torn down, particularly in relation to interacting with userspace and other kernel subsystems.

First, let's consider the `struct swap_info_struct`. I see a bunch of new fields added under `#ifdef CONFIG_XSWAP`. Important ones are `cluster_vm`, `nr_clusters_max`, `nr_clusters_mapped`, and so on.

The `xswap_create()` function is where it all begins. It allocates a `swap_info_struct` and initializes several fields, most notably, setting `si->flags |= SWP_XSWAP | SWP_SOLIDSTATE`. The critical aspect is that many of the new `xswap_` fields are initialized during the device creation process, and several are related to the cluster address space.

`setup_swap_clusters_info()` is responsible for the actual mapping and initialization of the `cluster_vm`, specifically the `cluster_info` within the `si`. The important point here is that there's a mutex initialization for `si->xswap_lock` before `xswap_map_clusters()` can do its job.

The `xswap_map_clusters()` function initializes `nr_clusters_mapped`, which is a key value. When unmapping and tearing things down, I see how `free_swap_cluster_info()` and `__swapoff()` set the fields back to zero. This seems like a reasonable way to reset the `si` structure.

Now, does a normal `swapon` mess with the `xswap_` fields? Nope, since `si->flags & SWP_XSWAP` is only set in `xswap_create()`.

Now, the real question: does this expose uninitialized memory to userspace or read uninitialized memory? Let's check the four criteria for `NeedsKMSAN=true`:

1.  **Kernel structures to userspace:** My initial review suggests we aren't directly copying complex structures to userspace.
    *   `xswap_debugfs_read` uses formatted text via `scnprintf` and `simple_read_from_buffer`. No raw data.
    *   Sysfs create/destroy calls are write-only.
    *   `/proc/swaps` uses formatted text via `seq_printf` / `seq_puts`.
    *   `swapoff` and `swapon` use standard syscalls, returning an int.

2.  **Conditional logic based on potentially uninitialized variables:** I need to analyze any new logic.
    *   `folio_alloc_swap`: `may_zswap` and `zswap_checked` are initialized to `true` and `false` respectively. Any branch conditions depending on these variables are based on initialized values. `folio_may_zswap` always returns a initialized value.
    *   `xswap_parse_size`: Properly zero terminates the `buf` before passing it to `kstrtouint`.
    *   `xswap_destroy_by_name`: Copies and zero-terminates `buf` via `strscpy`, then uses `kstrtou64`.
    *   `xswap_collect_page`: The `xpd` struct is initialized, and `nr` is tracked to avoid reading beyond the initialized pages.
    *   `xswap_unmap_range`: The `xpd` struct is initialized with designated initializers; `nr` defaults to 0. `xpd.nr` tracks how many pages were collected into `pages`. `pages[i]` are only accessed from `0` to `xpd.nr - 1`. `xswap_unmap_range` and its batch unmapping are fine.
    *   `xswap_map_clusters`: the memory is allocated and initialized with `__GFP_ZERO`. The code properly handles errors during allocation and unmaps the pages on failure and frees allocated pages in the failure case.

3.  **Complex data structures with uninitialized fields:** I've confirmed that pages for `cluster_info` are allocated with `alloc_page(__GFP_ZERO)`. The `ci` struct when added to the `free_clusters` is initialized/zeroed, and `spin_lock_init` is called.

4.  **Bounds checks exposing uninitialized data:**

    *   I see a potential issue with swap read/write paths with xswap, but this is okay because `xswap` doesn't have backing store, so it is just setting


26/3 2026/11/11 22:20 tool grepper
0m Args:
{
  "Expression": "zswap_store\\(",
  "PathPrefixes": [
    "mm/"
  ]
}

Results:
{
  "Output": "mm/page_io.c=204=int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)\n--\nmm/page_io.c-247-\nmm/page_io.c:248:\tif (zswap_store(folio)) {\nmm/page_io.c-249-\t\tcount_mthp_stat(folio_order(folio), MTHP_STAT_ZSWPOUT);\n--\nmm/zswap.c=1053=struct zswap_shrink_ctl {\n--\nmm/zswap.c-1073- * to the swap device.  We are basically resuming the same swap\nmm/zswap.c:1074: * writeback path that was intercepted with the zswap_store()\nmm/zswap.c-1075- * in the first place.  After the folio has been decompressed into\n--\nmm/zswap.c=1535=static bool zswap_store_page(struct folio *folio, long index,\n--\nmm/zswap.c-1622-\nmm/zswap.c:1623:bool zswap_store(struct folio *folio)\nmm/zswap.c-1624-{\n"
}

27/3 2026/11/11 22:20 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 43286
							output: 35
							thoughts: 23
						

Thoughts:
Okay, let's dive into this. Here's how I'd approach summarizing the prompt, given my assumed expertise:

**Inspecting `mm/page_io.c` for Context**

Alright, the request is to analyze lines 240-265 within the `mm/page_io.c` file. My immediate thought is, "Okay, this is probably related to page input/output operations." Knowing this section of the code handles I/O operations at the page level. Given the likely context, I expect to find code dealing with memory management tasks such as, reading or writing to the block device. It's highly probable this section addresses things like: handling page faults, caching strategies, direct I/O, or possibly even error handling and recovery during data transfers. I'll need to look closely at variable assignments, function calls, and any conditional logic to understand the flow. I'll be looking for clues about the specific I/O method and any synchronization primitives being used.



28/3 2026/11/11 22:20 tool read-file
0m Args:
{
  "File": "mm/page_io.c",
  "FirstLine": 240,
  "LineCount": 30
}

Results:
{
  "Contents": " 240:\t\n 241:\t\t/*\n 242:\t\t * Clear bits this folio occupies in the zeromap to prevent zero data\n 243:\t\t * being read in from any previous zero writes that occupied the same\n 244:\t\t * swap entries.\n 245:\t\t */\n 246:\t\tswap_zeromap_folio_clear(folio);\n 247:\t\n 248:\t\tif (zswap_store(folio)) {\n 249:\t\t\tcount_mthp_stat(folio_order(folio), MTHP_STAT_ZSWPOUT);\n 250:\t\t\tgoto out_unlock;\n 251:\t\t}\n 252:\t\n 253:\t\trcu_read_lock();\n 254:\t\tif (!mem_cgroup_zswap_writeback_enabled(folio_memcg(folio))) {\n 255:\t\t\trcu_read_unlock();\n 256:\t\t\tfolio_mark_dirty(folio);\n 257:\t\t\treturn AOP_WRITEPAGE_ACTIVATE;\n 258:\t\t}\n 259:\t\trcu_read_unlock();\n 260:\t\n 261:\t\t/*\n 262:\t\t * xswap has no backing store: keep the folio.  ctx-\u003esis is not set\n 263:\t\t * yet, so look the device up from the entry.\n 264:\t\t */\n 265:\t\tif (unlikely(__swap_entry_to_info(folio-\u003eswap)-\u003eflags \u0026 SWP_XSWAP)) {\n 266:\t\t\tfolio_mark_dirty(folio);\n 267:\t\t\treturn AOP_WRITEPAGE_ACTIVATE;\n 268:\t\t}\n 269:\t\n"
}

29/3 2026/11/11 22:20 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 44012
							output: 20
							thoughts: 312
						

Thoughts:
**Analyzing Zswap Read and Write Paths**

Okay, let's break down this zswap logic. In `swap_writeout`, if `zswap_store(folio)` goes through without issue, we hit `out_unlock` which correctly calls `folio_unlock(folio)`. Makes sense. But, if `zswap_store(folio)` fails, specifically when dealing with a `SWP_XSWAP` entry, it marks it dirty and returns `AOP_WRITEPAGE_ACTIVATE`. That's the expected behavior; we're activating a writeback.

Now, I'm shifting focus to `swap_read_folio`. The function first attempts `zswap_load(folio)`. If that succeeds, we bail out. But... what if `zswap_load(folio)` *fails*? The code immediately checks for `-ENOENT`. Ah, here's the kicker: it then does `folio_unlock(folio)` and *returns*. Hold on a minute... is it leaving that folio in a potentially inconsistent state? I'm specifically thinking about if the `folio` is not up-to-date with memory or the backing storage.

This raises a red flag. The code just unlocks the folio and returns if `zswap_load` fails, and the folio isn't in zswap. Is that correct? I need to understand what the *caller* of `swap_read_folio` expects. I'm going to grep the codebase now to trace the call paths to `swap_read_folio`. I need to see what happens after this function returns to verify if my suspicions about unlocked and potentially inconsistent folio are correct.



30/3 2026/11/11 22:21 tool grepper
0m Args:
{
  "Expression": "swap_read_folio\\("
}

Results:
{
  "Output": "include/linux/swap_ops.h=17=struct swap_io_ctx {\n--\ninclude/linux/swap_ops.h-21-\t/*\ninclude/linux/swap_ops.h:22:\t * Pressure window: opened by swap_read_folio() on the first folio\ninclude/linux/swap_ops.h-23-\t * of a batch, closed by swap_read_submit(). Mirrors per-task\n--\nmm/memory.c=4795=static bool can_swapin_thp(struct vm_fault *vmf, pte_t *ptep, int nr_pages)\n--\nmm/memory.c-4807-\t/*\nmm/memory.c:4808:\t * swap_read_folio() can't handle the case a large folio is hybridly\nmm/memory.c-4809-\t * from different backends. And they are likely corner cases. Similar\n--\nmm/page_io.c=357=static void swap_add_folio(struct swap_io_ctx *ctx, struct folio *folio, int rw)\n--\nmm/page_io.c-363-\t * Callers flush a batch this folio can't join before adding it,\nmm/page_io.c:364:\t * see swap_read_folio() and __swap_writeout().\nmm/page_io.c-365-\t */\n--\nmm/page_io.c=393=void __swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)\n--\nmm/page_io.c-411-\t * Flush a batch this folio can't join before adding it, as in\nmm/page_io.c:412:\t * swap_read_folio(). But the write path opens no pressure window,\nmm/page_io.c-413-\t * so there is nothing to order this against.\n--\nmm/page_io.c=450=static bool swap_read_folio_zeromap(struct folio *folio)\n--\nmm/page_io.c-482-\nmm/page_io.c:483:void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio)\nmm/page_io.c-484-{\n--\nmm/swap.h=257=int sio_pool_init(void);\nmm/swap.h:258:void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio);\nmm/swap.h-259-void swap_read_submit(struct swap_io_ctx *ctx);\n--\nmm/swap.h=395=static inline void folio_put_swap(struct folio *folio, struct page *page)\n--\nmm/swap.h-398-\nmm/swap.h:399:static inline void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio)\nmm/swap.h-400-{\n--\nmm/swap_state.c=709=static struct folio *swap_cache_read_folio(struct swap_io_ctx *ctx,\n--\nmm/swap_state.c-725-\tfolio_add_lru(folio);\nmm/swap_state.c:726:\tswap_read_folio(ctx, folio);\nmm/swap_state.c-727-\tif (readahead) {\n--\nmm/swap_state.c=751=struct folio *swapin_sync(swp_entry_t entry, gfp_t gfp, unsigned long orders,\n--\nmm/swap_state.c-767-\tfolio_add_lru(folio);\nmm/swap_state.c:768:\tswap_read_folio(\u0026ctx, folio);\nmm/swap_state.c-769-\tswap_read_submit(\u0026ctx);\n--\nmm/swapfile.c=4940=static int xswap_create(int prio)\n--\nmm/swapfile.c-5001-\t * used, by may_enter_fs(); the IO methods are never called because\nmm/swapfile.c:5002:\t * swap_writeout()/swap_read_folio() short circuit xswap.\nmm/swapfile.c-5003-\t */\n"
}

31/3 2026/11/11 22:21 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 45758
							output: 19
							thoughts: 46
						

Thoughts:
Here's my analysis of what happens after `swapin_sync()`, tailored for an expert like yourself:

**Diving Deep into `swapin_sync()` and its Callers**

Okay, so the investigation begins with `swapin_sync()`. My primary focus is on understanding the post-operation behavior within the memory management subsystem. To gain that insight, I need to delve into `mm/swap_state.c` and `mm/memory.c`. I'll analyze the function itself, of course. More importantly, I'll identify all the callers of `swapin_sync()` within these files. This is where the crucial contextual information lies.

I'm expecting to uncover the precise conditions that trigger the call to `swapin_sync()`, the preceding operations, and the subsequent actions taken once the swap-in has been synchronized. I'm looking for clues about the memory contexts, locking mechanisms (spinlocks, mutexes, etc.), and any interactions with page tables, page cache, or the reclaim mechanisms. I want to build a complete mental model of what happens to the affected memory and related data structures. I anticipate finding that these interactions will be the most significant.

I am particularly interested in the interaction between the swap cache, page cache, and the virtual memory areas, VMA, to determine if there are data structure corruption potentials that need to be understood.

Ultimately, my goal is to trace the execution flow, understand the data dependencies, and assess the potential implications of the synchronization process, especially in relation to concurrent access and potential race conditions. I'm keen to uncover details relevant to performance bottlenecks or memory coherency issues in the system.



32/3 2026/11/11 22:21 tool grepper
0m Args:
{
  "Expression": "swapin_sync\\("
}

Results:
{
  "Output": "mm/memory.c=4964=vm_fault_t do_swap_page(struct vm_fault *vmf)\n--\nmm/memory.c-5055-\t\tif (swap_entry_synchronous(si, entry))\nmm/memory.c:5056:\t\t\tfolio = swapin_sync(entry, GFP_HIGHUSER_MOVABLE,\nmm/memory.c-5057-\t\t\t\t\t    thp_swapin_suitable_orders(si, vmf) | BIT(0),\n--\nmm/shmem.c=2294=static struct folio *shmem_swap_alloc_folio(struct inode *inode,\n--\nmm/shmem.c-2308-\tmpol = shmem_get_pgoff_policy(info, index, order, \u0026ilx);\nmm/shmem.c:2309:\tfolio = swapin_sync(entry, gfp, BIT(order), vmf, mpol, ilx);\nmm/shmem.c-2310-\tmpol_cond_put(mpol);\n--\nmm/swap.h=333=struct folio *swapin_readahead(swp_entry_t entry, gfp_t flag,\nmm/swap.h-334-\t\tstruct vm_fault *vmf);\nmm/swap.h:335:struct folio *swapin_sync(swp_entry_t entry, gfp_t flag, unsigned long orders,\nmm/swap.h-336-\t\t\t   struct vm_fault *vmf, struct mempolicy *mpol, pgoff_t ilx);\n--\nmm/swap.h=427=static inline struct folio *swapin_readahead(swp_entry_t swp, gfp_t gfp_mask,\n--\nmm/swap.h-432-\nmm/swap.h:433:static inline struct folio *swapin_sync(\nmm/swap.h-434-\tswp_entry_t entry, gfp_t flag, unsigned long orders,\n--\nmm/swap_state.c=709=static struct folio *swap_cache_read_folio(struct swap_io_ctx *ctx,\n--\nmm/swap_state.c-750- */\nmm/swap_state.c:751:struct folio *swapin_sync(swp_entry_t entry, gfp_t gfp, unsigned long orders,\nmm/swap_state.c-752-\t\t\t   struct vm_fault *vmf, struct mempolicy *mpol, pgoff_t ilx)\n"
}

33/3 2026/11/11 22:21 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 46807
							output: 34
							thoughts: 26
						

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

**Diving into `do_swap_page`**

Okay, let's zero in on `do_swap_page` in `mm/memory.c`. I'm thinking specifically around line 5055. That's a key function for understanding how page swapping is handled in the kernel, and I need to refresh my understanding of the exact mechanism. I need to understand the function in its specific context, how it interacts with the VM subsystem, and the conditions that trigger its execution. I want to pay attention to the code around the actual swapping operations and how it handles page faults. Let's see how memory is really moved around here. This is crucial for performance analysis, especially when dealing with memory-intensive applications.



34/3 2026/11/11 22:21 tool read-file
0m Args:
{
  "File": "mm/memory.c",
  "FirstLine": 5065,
  "LineCount": 40
}

Results:
{
  "Contents": "5065:\t\t\t\t * while we released the pte lock.\n5066:\t\t\t\t */\n5067:\t\t\t\tvmf-\u003epte = pte_offset_map_lock(vma-\u003evm_mm, vmf-\u003epmd,\n5068:\t\t\t\t\t\tvmf-\u003eaddress, \u0026vmf-\u003eptl);\n5069:\t\t\t\tif (likely(vmf-\u003epte \u0026\u0026\n5070:\t\t\t\t\t   pte_same(ptep_get(vmf-\u003epte), vmf-\u003eorig_pte)))\n5071:\t\t\t\t\tret = VM_FAULT_OOM;\n5072:\t\t\t\tfolio = NULL;\n5073:\t\t\t\tgoto unlock;\n5074:\t\t\t}\n5075:\t\n5076:\t\t\t/* Had to read the page from swap area: Major fault */\n5077:\t\t\tret = VM_FAULT_MAJOR;\n5078:\t\t\tcount_vm_event(PGMAJFAULT);\n5079:\t\t\tcount_memcg_event_mm(vma-\u003evm_mm, PGMAJFAULT);\n5080:\t\t}\n5081:\t\n5082:\t\tswapcache = folio;\n5083:\t\tret |= folio_lock_or_retry(folio, vmf);\n5084:\t\tif (ret \u0026 VM_FAULT_RETRY)\n5085:\t\t\tgoto out_release;\n5086:\t\n5087:\t\tpage = folio_file_page(folio, swp_offset(entry));\n5088:\t\t/*\n5089:\t\t * Make sure folio_free_swap() or swapoff did not release the\n5090:\t\t * swapcache from under us.  The page pin, and pte_same test\n5091:\t\t * below, are not enough to exclude that.  Even if it is still\n5092:\t\t * swapcache, we need to check that the page's swap has not\n5093:\t\t * changed.\n5094:\t\t */\n5095:\t\tif (unlikely(!folio_matches_swap_entry(folio, entry)))\n5096:\t\t\tgoto out_page;\n5097:\t\n5098:\t\tif (unlikely(PageHWPoison(page))) {\n5099:\t\t\t/*\n5100:\t\t\t * hwpoisoned dirty swapcache pages are kept for killing\n5101:\t\t\t * owner processes (which may be unknown at hwpoison time)\n5102:\t\t\t */\n5103:\t\t\tret = VM_FAULT_HWPOISON;\n5104:\t\t\tgoto out_page;\n"
}

35/3 2026/11/11 22:21 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 47680
							output: 34
							thoughts: 28
						

Thoughts:
Okay, here's my attempt at summarizing the thought process, tailored for an expert audience, and written in the first person:

**Diving into `do_swap_page` (Lines 5105-5140)**

Right, let's get down to brass tacks. I need to understand the execution flow within `do_swap_page` between lines 5105 and 5140. This is where the core interaction with the swap space is likely happening, and I need to solidify my mental model of the crucial operations here. I'm focusing on these lines because they're probably dealing with the mechanics of getting a page swapped in or out. I'm assuming that this is where the interesting bit is, where the actual I/O happens, or perhaps where the page table entries are manipulated to reflect the swap.

I'm mentally stepping through each potential action: Is this where the page is read from or written to swap? Is there an attempt to allocate a page? Are there any locks being acquired or released to protect the relevant data structures (like the swap cache, the page itself)? What's the error handling like within this snippet? If there's an issue, I want to understand what the code does to compensate, and what can go wrong? I'm anticipating potential races or synchronization issues, especially if concurrent swap operations are possible. I'm mentally checking what data structures the code is interacting with, what the implications are for performance, and whether there might be any opportunities for optimization. I'm hoping to get a detailed understanding of the swap mechanism at this critical juncture.



36/3 2026/11/11 22:21 tool read-file
0m Args:
{
  "File": "mm/memory.c",
  "FirstLine": 5105,
  "LineCount": 35
}

Results:
{
  "Contents": "5105:\t\t}\n5106:\t\n5107:\t\t/*\n5108:\t\t * KSM sometimes has to copy on read faults, for example, if\n5109:\t\t * folio-\u003eindex of non-ksm folios would be nonlinear inside the\n5110:\t\t * anon VMA -- the ksm flag is lost on actual swapout.\n5111:\t\t */\n5112:\t\tfolio = ksm_might_need_to_copy(folio, page, vma, vmf-\u003eaddress);\n5113:\t\tif (unlikely(!folio)) {\n5114:\t\t\tret = VM_FAULT_OOM;\n5115:\t\t\tfolio = swapcache;\n5116:\t\t\tgoto out_page;\n5117:\t\t} else if (unlikely(folio == ERR_PTR(-EHWPOISON))) {\n5118:\t\t\tret = VM_FAULT_HWPOISON;\n5119:\t\t\tfolio = swapcache;\n5120:\t\t\tgoto out_page;\n5121:\t\t} else if (folio != swapcache)\n5122:\t\t\tpage = folio_page(folio, 0);\n5123:\t\n5124:\t\tfolio_throttle_swaprate(folio, GFP_KERNEL);\n5125:\t\n5126:\t\t/*\n5127:\t\t * Back out if somebody else already faulted in this pte.\n5128:\t\t */\n5129:\t\tvmf-\u003epte = pte_offset_map_lock(vma-\u003evm_mm, vmf-\u003epmd, vmf-\u003eaddress,\n5130:\t\t\t\t\u0026vmf-\u003eptl);\n5131:\t\tif (unlikely(!vmf-\u003epte || !pte_same(ptep_get(vmf-\u003epte), vmf-\u003eorig_pte)))\n5132:\t\t\tgoto out_nomap;\n5133:\t\n5134:\t\tif (unlikely(!folio_test_uptodate(folio))) {\n5135:\t\t\tret = VM_FAULT_SIGBUS;\n5136:\t\t\tgoto out_nomap;\n5137:\t\t}\n5138:\t\n5139:\t\tnr_pages = 1;\n"
}

37/3 2026/11/11 22:21 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 48646
							output: 20
							thoughts: 262
						

Thoughts:
**Analyzing Memory Management and zswap Interaction**

Okay, let's break this down. Line 5134-5137 immediately flags my attention: `if (unlikely(!folio_test_uptodate(folio))) { ret = VM_FAULT_SIGBUS; goto out_nomap; }`. So, essentially, if a folio isn't uptodate, the system throws a SIGBUS and doesn't map it into userspace. That's a critical safety net. Interesting. Now, looking at `swap_read_folio`, I see a condition related to `SWP_XSWAP` flags:

`if (unlikely(sis->flags & SWP_XSWAP)) { ... }`

This tells me that if we're dealing with an xswap entry, it *should* only exist in zswap. The code then asserts that `zswap_load()` must have already found it. If it did, it should have marked the folio as uptodate and unlocked it. However, if this condition is met, and the WARN_ONCE condition fires, something went terribly wrong. I need to understand that.

So, let's delve into what `zswap_load(folio)` *actually* does. Let's head over to `mm/zswap.c` and figure this out.



38/3 2026/11/11 22:21 tool grepper
0m Args:
{
  "Expression": "bool zswap_load\\("
}

Results:
{
  "Output": "no matches"
}

39/3 2026/11/11 22:21 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 49232
							output: 28
							thoughts: 15
						

Thoughts:
Okay, here's my summary, tailored for an expert audience, as if I'm thinking these things myself:

**Tracing the zswap Load**

Alright, let's get down to brass tacks. My initial instinct is to dig directly into the heart of the matter – the `mm/` directory. That's where I'd expect to find the core implementation for zswap, and consequently, the code responsible for managing its load. I'm thinking that `zswap_load` will likely be a function call, a variable, or possibly even a more complex data structure related to zswap's utilization. The name is pretty explicit, so locating it should be relatively straightforward within that context. From there, I can analyze the surrounding code to determine how that load metric is being calculated, updated, and potentially, utilized.



40/3 2026/11/11 22:21 tool grepper
0m Args:
{
  "Expression": "zswap_load\\(",
  "PathPrefixes": [
    "mm/"
  ]
}

Results:
{
  "Output": "mm/page_io.c=483=void swap_read_folio(struct swap_io_ctx *ctx, struct folio *folio)\n--\nmm/page_io.c-523-\nmm/page_io.c:524:\tif (zswap_load(folio) != -ENOENT)\nmm/page_io.c-525-\t\treturn;\n--\nmm/page_io.c-528-\t\t/*\nmm/page_io.c:529:\t\t * An xswap entry only ever lives in zswap, so zswap_load()\nmm/page_io.c-530-\t\t * must have found it.  Unlock and let the caller retry.\n--\nmm/zswap.c=1705=bool zswap_is_present(swp_entry_t entry, unsigned int nr)\n--\nmm/zswap.c-1725-/**\nmm/zswap.c:1726: * zswap_load() - load a folio from zswap\nmm/zswap.c-1727- * @folio: folio to load\n--\nmm/zswap.c-1741- */\nmm/zswap.c:1742:int zswap_load(struct folio *folio)\nmm/zswap.c-1743-{\n--\nmm/zswap.c-1755-\t/*\nmm/zswap.c:1756:\t * A large folio can legitimately reach zswap_load() with its whole\nmm/zswap.c-1757-\t * range on the backing device, so scan the range rather than rejecting\n"
}

41/3 2026/11/11 22:21 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 49856
							output: 35
							thoughts: 19
						

Thoughts:
Here's my attempt at summarizing the thought process, tailored for an expert audience:

**Diving into zswap_load**

Alright, time to dig into `zswap_load` within `mm/zswap.c`. I'm going to quickly refresh my understanding of where this function sits in the overall zswap architecture. I'm assuming, based on the naming, that it's likely involved with monitoring or potentially adjusting the system's zswap activity level – likely related to the balance between compressing and swapping. My first thought is to trace its call sites to quickly determine the context it's working in. Is it called periodically? Reacting to memory pressure? Or is it part of the initial setup? This will provide important context. I'll need to pay close attention to the parameters it takes and what it returns as well, as that'll tell me what kind of data it uses to make decisions. Let's see...



42/3 2026/11/11 22:21 tool read-file
0m Args:
{
  "File": "mm/zswap.c",
  "FirstLine": 1740,
  "LineCount": 40
}

Results:
{
  "Contents": "1740:\t *  locked on return.\n1741:\t */\n1742:\tint zswap_load(struct folio *folio)\n1743:\t{\n1744:\t\tswp_entry_t swp = folio-\u003eswap;\n1745:\t\tpgoff_t offset = swp_offset(swp);\n1746:\t\tstruct xarray *tree = swap_zswap_tree(swp);\n1747:\t\tstruct zswap_entry *entry;\n1748:\t\n1749:\t\tVM_WARN_ON_ONCE(!folio_test_locked(folio));\n1750:\t\tVM_WARN_ON_ONCE(!folio_test_swapcache(folio));\n1751:\t\n1752:\t\tif (zswap_never_enabled())\n1753:\t\t\treturn -ENOENT;\n1754:\t\n1755:\t\t/*\n1756:\t\t * A large folio can legitimately reach zswap_load() with its whole\n1757:\t\t * range on the backing device, so scan the range rather than rejecting\n1758:\t\t * it outright. The caller has pinned every slot, so zswap cannot start\n1759:\t\t * a store or a writeback into the range while we look.\n1760:\t\t */\n1761:\t\tif (folio_test_large(folio)) {\n1762:\t\t\tif (WARN_ON_ONCE(zswap_is_present(swp,\n1763:\t\t\t\t\t\t\t  folio_nr_pages(folio)))) {\n1764:\t\t\t\tfolio_unlock(folio);\n1765:\t\t\t\treturn -EIO;\n1766:\t\t\t}\n1767:\t\t\treturn -ENOENT;\n1768:\t\t}\n1769:\t\n1770:\t\tentry = xa_load(tree, offset);\n1771:\t\tif (!entry)\n1772:\t\t\treturn -ENOENT;\n1773:\t\n1774:\t\tif (!zswap_decompress(entry, folio)) {\n1775:\t\t\tfolio_unlock(folio);\n1776:\t\t\treturn -EIO;\n1777:\t\t}\n1778:\t\n1779:\t\tfolio_mark_uptodate(folio);\n"
}

43/3 2026/11/11 22:21 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 50694
							output: 508
							thoughts: 3370
						

Thoughts:
**Xswap Patch Analysis: No Uninitialized Memory Risks**

Okay, let's break this down. My main focus here is on whether this patch series, introducing `SWP_XSWAP` (xswap), introduces any potential for uninitialized memory to be read, copied, or otherwise leak. The initial code review highlighted several areas, and I've gone through them systematically.

First, the core functionality of `zswap_decompress` is straightforward: decompress into a `folio`, mark it uptodate on success, return an error on failure (-EIO). The concern was around how xswap might interact with this. Then, there's `zswap_store_page`. The key point is that with `SWP_XSWAP`, entries are *not* added to the LRU, and writeback is refused. This makes sense for the intended design, since the backing store *is* zswap. Hibernation and swapoff also explicitly avoid xswap devices, which seems consistent.

Then the code changes in `swapfile.c` are mostly around concurrency and control flow. The added RCU locking seems right for data races. The `CONFIG_XSWAP` conditionals were worth another look. They appear to be handling situations where xswap needs to grow and shrink, allocating clusters. The `xswap_grow` and `xswap_try_shrink` functions are related. The code ensures these clusters are tracked and freed, and it looks like RCU is used to avoid data races. Also, all the pages for the `cluster_info` are zero initialized.

The crucial part is the mapping and unmapping of pages for cluster information. It seems `alloc_page(__GFP_ZERO)` is used to allocate these. This ensures that the memory is initialized, and that includes spinlocks. The spinlock initialization happens in the `xswap_map_clusters` functions. The `xswap_destroy` cleans up cleanly, and `__swapoff` also ensures everything is reset.

Now, to explicitly address the memory safety, I considered the ways the patch series could expose or introduce these types of vulnerabilities. No kernel structures are copied to userspace and no branching on uninitialized variables, or bounds checks that could leak information. And critically, all dynamically allocated pages are initialized with `__GFP_ZERO`. All the added struct fields are explicitly set.

Finally, I checked all edge cases in places where user-provided input is parsed and formatted. `xswap_parse_size`, `xswap_destroy_by_name`, and `xswap_debugfs_read` are safe.

Considering all this, it's clear that this patch series *does not* expose or introduce uninitialized memory risks. Running KMSAN on it would provide no extra value.



44/3 2026/11/11 22:22 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch series introduces 'xswap', an extendable file-less swap device backed by zswap using a sparse vmalloc area (VM_SPARSE) to dynamically allocate and map swap cluster metadata (swap_cluster_info) in chunks.\n\nAn evaluation of memory sanitizer applicability indicates that a dedicated KMSAN fuzzing session is not warranted:\n1. No uninitialized memory exposure to userspace: The new sysfs interfaces ('create' and 'destroy') are write-only (mode 0200), and debugfs/procfs interfaces ('/sys/kernel/debug/xswap/xswap\u003cid\u003e' and '/proc/swaps') format plain text output exclusively using scnprintf() and seq_printf()/seq_puts() bounded by returned string lengths. There are no binary kernel structs or padding copied to userspace via copy_to_user, put_user, netlink, or ioctl.\n2. Initialization of all newly allocated buffers and structures: The sparse backing pages for swap_cluster_info are allocated with alloc_page(... | __GFP_ZERO), ensuring all pointer and integer fields start fully zeroed. Cluster spinlocks are explicitly initialized via spin_lock_init() upon mapping. All new struct swap_info_struct fields, stack buffers (e.g., in xswap_parse_size, xswap_destroy_by_name, xswap_debugfs_read), and work structs are properly initialized before use.\n3. No branching or logic dependent on uninitialized data: In the swap fast/slow allocation and readahead paths, new branching flags (such as may_zswap and zswap_checked) are explicitly initialized locals.\n4. Nature of potential risks: The failure modes and risks introduced by this change center around locking hierarchies (xswap_lock, swap_lock, si-\u003elock, ci-\u003elock), RCU grace period synchronization during cluster unmapping, and concurrency races between growth, shrinking, swapoff, and folio allocation/swapin. These are standard locking, use-after-free, and out-of-bounds risks that are fully covered by KASAN, LOCKDEP, and page fault handling.\n\nBecause there are no uninitialized memory risks or info-leaks unique to KMSAN, a dedicated KMSAN run is not justified.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch series introduces 'xswap', an extendable file-less swap device backed by zswap using a sparse vmalloc area (VM_SPARSE) to dynamically allocate and map swap cluster metadata (swap_cluster_info) in chunks.\n\nAn evaluation of memory sanitizer applicability indicates that a dedicated KMSAN fuzzing session is not warranted:\n1. No uninitialized memory exposure to userspace: The new sysfs interfaces ('create' and 'destroy') are write-only (mode 0200), and debugfs/procfs interfaces ('/sys/kernel/debug/xswap/xswap\u003cid\u003e' and '/proc/swaps') format plain text output exclusively using scnprintf() and seq_printf()/seq_puts() bounded by returned string lengths. There are no binary kernel structs or padding copied to userspace via copy_to_user, put_user, netlink, or ioctl.\n2. Initialization of all newly allocated buffers and structures: The sparse backing pages for swap_cluster_info are allocated with alloc_page(... | __GFP_ZERO), ensuring all pointer and integer fields start fully zeroed. Cluster spinlocks are explicitly initialized via spin_lock_init() upon mapping. All new struct swap_info_struct fields, stack buffers (e.g., in xswap_parse_size, xswap_destroy_by_name, xswap_debugfs_read), and work structs are properly initialized before use.\n3. No branching or logic dependent on uninitialized data: In the swap fast/slow allocation and readahead paths, new branching flags (such as may_zswap and zswap_checked) are explicitly initialized locals.\n4. Nature of potential risks: The failure modes and risks introduced by this change center around locking hierarchies (xswap_lock, swap_lock, si-\u003elock, ci-\u003elock), RCU grace period synchronization during cluster unmapping, and concurrency races between growth, shrinking, swapoff, and folio allocation/swapin. These are standard locking, use-after-free, and out-of-bounds risks that are fully covered by KASAN, LOCKDEP, and page fault handling.\n\nBecause there are no uninitialized memory risks or info-leaks unique to KMSAN, a dedicated KMSAN run is not justified.",
  "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)