Received: from mail-wm1-f44.google.com (mail-wm1-f44.google.com [209.85.128.44]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 43150267B07 for ; Sat, 14 Mar 2026 15:25:41 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.44 ARC-Seal:i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773501942; cv=none; b=Uj0gxhxEwBotIRsnXQiRYb6oumEyHN9l7k1icpEvxjib6UUAcqBSKAtqE/r6TOBrjk/XtJFHQsbq23d3wMtJn83sCjFv52osSZggnnfBnXXsfSig7iJcnodwgn1Epc0Ct2U2b9Bc5vljKK77PVCupGEsMotM1hp+mht+wepcMuw= ARC-Message-Signature:i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773501942; c=relaxed/simple; bh=Me0+LHvzrrU4T7BnxevXSB8BUxlAz3QsegCCdnKqDBI=; h=From:To:Cc:Subject:Date:Message-ID:MIME-Version:Content-Type; b=OogxTpafNmhGcmmSepY/P6YkZw8tv8IvVT1wDxqCeC35Xyrha0o3AfZoBvO4vcNaeUpgPOaNRorD77GmHWvWC1HCN7wsafQ8Z5ZIqD4zbBaOXuztNaHXToaH5sP4rBmc4aBgMpcgWFDspVbq7d/YsJUWQmK0cWlVjaRtPLPaQ/Y= ARC-Authentication-Results:i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=UDPxJyN8; arc=none smtp.client-ip=209.85.128.44 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="UDPxJyN8" Received: by mail-wm1-f44.google.com with SMTP id 5b1f17b1804b1-4853c3c2fe7so18988175e9.0 for ; Sat, 14 Mar 2026 08:25:41 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1773501940; x=1774106740; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:message-id:date:subject:cc :to:from:from:to:cc:subject:date:message-id:reply-to; bh=0Kz3y41fQXpan3/BGcLXZfi5NToemQqFGHgZng3qvUQ=; b=UDPxJyN8oshQYnkFlOTyxJ8NL5GbrGzlmN2KqU5YEfA6IN6VxL6gO8qR0AIIUztS7i 1p8+v9Fl5jMJj41DIA7DVw7+NWUwlPrFGYy2Mlj6T13Rxh5Uk81wnlsnJK9D6SZ26EwK keGlpofwExgMVrcDrn4McHL76KZUsjtQxpbRByRYITz8qhAA398afLMtd6EPJ3LzL5mn RZvnzvZMCKWvgRCEzwYpwzLVsdV9LXi600iwAEsWKiZE1rR0RTvPUGRyNn6AdJB8mdgN R1Bqy7BLsbiddySnJPd7IPH0/4iPPNZUJmRBhIGx2XfN4mewMm6U3rROo1wemvI4m/tt FoqQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20251104; t=1773501940; x=1774106740; h=content-transfer-encoding:mime-version:message-id:date:subject:cc :to:from:x-gm-gg:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to; bh=0Kz3y41fQXpan3/BGcLXZfi5NToemQqFGHgZng3qvUQ=; b=L5ZQ5AabKXbZcaoHrxPbfyq2c8wlSRSFP2vo9v6v+RUHlsJ8cUN6mhTGk4s9SJjR0L pbx6SPnMJchsN0/nwv3AkyqQbHe9uF03+zUwwOisIRJsZaiQSpWYEEXrlcm6NkiZcriP 82skeI1bYRR374aunp8VxovmMkRPyYRudpR6fwDYVMLOveg5TQihxXl17TIZSK4EuR39 i2tAx3LS9Jy5pw+Rse5FmCCgXA3/b5txozJr9TPj/Koxko4bsRNjFqUtUa3F5KNyUZ6F wUnXqPj97o6XM1at/mJ1DYBtyosxxUloIPieqLFoRz4ghe8MuFoU2xzkckIXcZIq3yGt /eVQ== X-Forwarded-Encrypted: i=1; AJvYcCXAXBdJUjg186pZ8MjMe0ZQxwDajFlbCNGrvxUmo+ewpxR6tJZ/C0sCABEuk2joigIPPHUyfiKTJb4=@vger.kernel.org X-Gm-Message-State: AOJu0YyLKKQ9b4zbcQnYSzLVvVJSKkVMNnXYxin6+gUx7RPxqmRunyH4 WBubeircfRwtf81qIlhBCTVwnvSZRxGXaKOsgXynxDMIrEOd6nJDUnX/ X-Gm-Gg: ATEYQzw41U89qrlqvjPpyQIe09wBj+OUK/Gvt/sa5x/qV2eoprCx88hjZWB+RHJy8Tb n9QGkKlg02/U/nO380CF3vM/oP24BYBGmZU+DAL/MVLd2fOHfD7oGsbdUKL+L3FQRdXRWmS5iJX kgwqCON9evqQLGzhxgdvOycp/kknN1uaoAgIO/l4AawGN1OWtvDGy69Pav38TNepCqnLZtKnXK3 Qh9wPXQNmTqTSHZJn8nSzw6+x21H03Gm9wfJ9dQeRqOD49jNE/MT1BF7GHCzsIR2eiNNmEC3P7J YbfcAge1be3UVyG5hChMW47ZKmB+iE6+ZzppiJHFtOR2OQ+wOWXl0UmQePxRoUkfpSJA0X2IBs0 VEuPOkjD5kvMWq8HlgyuF3fJKvNyfqZytAk2jim8JClBCuwVTM4l7+5rLNauF/ZycBGb4gEhha0 DR8GcW0CGfrc3mSbzHbN7K7dBbQEPUxC/EHhKhEYiYfEpj5z2FSVXDhEgpVBE1YrLgLZG8ZEDT1 JQRE40lZ3evyiEUd5VpNSTR7oOcmo1lXSYBpSHl X-Received: by 2002:a05:600c:3ba4:b0:485:3f72:3230 with SMTP id 5b1f17b1804b1-485566d936dmr123975255e9.15.1773501938817; Sat, 14 Mar 2026 08:25:38 -0700 (PDT) Received: from DESKTOP-TILNSD1.localdomain ([139.47.104.103]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-439fe1a78cesm25752310f8f.11.2026.03.14.08.25.37 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sat, 14 Mar 2026 08:25:38 -0700 (PDT) From: Kit Dallege To: akpm@linux-foundation.org, david@kernel.org, corbet@lwn.net Cc: linux-mm@kvack.org, linux-doc@vger.kernel.org, Kit Dallege Subject: [PATCH] Docs/mm: document Swap Date: Sat, 14 Mar 2026 16:25:36 +0100 Message-ID: <20260314152536.100531-1-xaum.io@gmail.com> X-Mailer: git-send-email 2.53.0 Precedence: bulk X-Mailing-List: linux-doc@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fill in the swap.rst stub created in commit 481cc97349d6 ("mm,doc: Add new documentation structure") as part of the structured memory management documentation following Mel Gorman's book outline. Signed-off-by: Kit Dallege --- Documentation/mm/swap.rst | 154 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) diff --git a/Documentation/mm/swap.rst b/Documentation/mm/swap.rst index 78819bd4d745..89a93cc081d4 100644 --- a/Documentation/mm/swap.rst +++ b/Documentation/mm/swap.rst @@ -3,3 +3,157 @@ ==== Swap ==== + +Swap allows the kernel to evict anonymous pages (those not backed by a +file) to a swap device so that physical memory can be reused. When the +pages are needed again, they are read back in. The swap subsystem spans +several files: ``mm/swapfile.c`` manages swap devices, ``mm/swap_state.c`` +implements the swap cache, ``mm/page_io.c`` handles disk I/O, and +``mm/zswap.c`` provides an optional compressed cache layer. + +.. contents:: :local: + +Swap Entries +============ + +A swap entry is a compact identifier that encodes which swap device to use +and the offset within that device. When a page is swapped out, its page +table entry is replaced with a swap entry so that the kernel knows where to +find the data on a subsequent fault. Swap entries are also used internally +as keys into the swap cache. + +Swap Devices +============ + +A swap device is a disk partition or file registered with the ``swapon()`` +system call. Each device is described by a ``swap_info_struct`` that holds +the device's extent map, cluster state, and per-CPU allocation hints. + +The kernel maps virtual swap offsets to disk locations through a tree of +``swap_extent`` structures. For raw partitions the mapping is trivial +(one extent covering the whole device); for swap files the mapping follows +the file's block layout on disk. + +Cluster Allocation +------------------ + +Swap space is allocated in clusters (groups of contiguous slots, typically +32 pages). Each cluster tracks which slots are free and whether it has +pending discards. Per-CPU hints point to the most recently used cluster +so that allocations from the same CPU tend to land in the same cluster, +improving spatial locality for both SSDs and spinning disks. + +When a cluster is full, the allocator scans for a new one. Under heavy +swap pressure, it may also reclaim slots from full clusters if the pages +they reference have since been freed or swapped back in. + +TRIM / Discard +-------------- + +For SSD-backed swap, the kernel can issue discard (TRIM) commands when +swap slots are freed. This is batched per-cluster: once all slots in a +cluster are free, a single discard is issued for the entire range. This +avoids the overhead of per-page discards while still informing the device +that the blocks are unused. + +Swap counts +----------- + +Each swap slot has a reference count tracking how many page table entries +point to it (due to ``fork()`` and copy-on-write). For slots referenced +by very many processes, a continuation mechanism extends the counter +beyond its inline capacity. + +Swap Cache +========== + +The swap cache keeps recently swapped-in (or about to be swapped-out) +pages in memory, indexed by their swap entry. This serves several +purposes: + +- **Deduplication**: when multiple processes share a swapped page (via + ``fork()``), only one copy is read from disk; subsequent faults find + the page in the swap cache. +- **Write coalescing**: if a page is modified and swapped out again before + the previous write completes, the swap cache absorbs the update without + issuing a new write. +- **Readahead**: when one page is swapped in, adjacent swap entries are + speculatively read to exploit spatial and temporal locality. + +The swap cache is implemented as a per-cluster array of pointers +(the "swap table"), providing O(1) lookup by swap entry. +See also Documentation/mm/swap-table.rst. + +Readahead +--------- + +Swap readahead pre-fetches pages from swap before they are faulted in. +Two strategies are used: + +- **Cluster readahead**: reads a window of swap entries around the faulting + entry, betting on spatial locality in the swap device. +- **VMA readahead**: uses the virtual address layout to predict which swap + entries will be needed next, which is more effective when the access + pattern follows the process's address space layout rather than the swap + device layout. + +``vm.page-cluster`` controls the readahead window size (as a power of two). + +Compressed Swap (zswap) +======================= + +zswap (``mm/zswap.c``) is an optional write-behind compressed cache that +sits between the reclaim path and the swap device. When reclaim evicts a +page, zswap attempts to compress it and store the compressed data in a +RAM-based pool (using the zsmalloc allocator). + +If the page is faulted back in before the pool fills, no disk I/O occurs — +the page is decompressed directly from memory. This is significantly +faster than reading from even an SSD. + +Pool Management +--------------- + +Each zswap pool pairs a compression algorithm (lzo, lz4, zstd, etc.) with +a zsmalloc memory pool. Per-CPU compression contexts avoid lock +contention during compression and decompression. + +When the pool reaches its size limit (controlled by +``/sys/module/zswap/parameters/max_pool_percent``), the oldest entries are +evicted: zswap writes them out to the backing swap device, falling back to +the normal swap I/O path. An LRU list tracks entries for this purpose. + +Writeback +--------- + +zswap writeback decompresses the page, allocates a swap slot, and writes +the uncompressed page to the swap device. This is the slow path — +ideally most pages are either faulted back in from the compressed cache +or freed without ever reaching disk. + +Zero-Filled Pages +================= + +``mm/page_io.c`` maintains a bitmap (``swap_zeromap``) tracking swap slots +that contained zero-filled pages. When such a page is swapped in, the +kernel returns a zeroed page without performing any I/O. When a zero +page is swapped out, the bitmap bit is set instead of issuing a write. +This optimization is significant for workloads that allocate large amounts +of memory that is never written to. + +Swap I/O +======== + +``mm/page_io.c`` handles the mechanics of reading and writing pages to +swap. The I/O path checks three layers in order before falling through to +disk: + +1. The zero page bitmap — if the slot is known to be zero-filled, return + a zeroed page (read) or set the bit (write) with no I/O. +2. zswap — if enabled, attempt to store/load the page in the compressed + cache. +3. Block I/O — submit a bio to the swap device, using the swap extent + tree to map the slot to a disk sector. + +For swap files (as opposed to raw partitions), the I/O follows the +filesystem's block mapping rather than issuing direct device I/O. -- 2.53.0