7.6 Managing Swap Space: mkswap, swapon & swapoff (104.1/104.2)
Key Takeaways
- Linux swap space extends physical RAM via secondary storage, preventing out-of-memory (OOM) crashes, enabling inactive memory offloading, and supporting suspend-to-disk hibernation.
- Swap areas are initialized on dedicated partitions or regular files using `mkswap [options] device-or-file`, writing the `SWAPSPACE2` signature.
- Swap files require strict root-only permissions (`chmod 600 /swapfile`) to prevent unprivileged users from reading plaintext memory pages and cryptographic secrets.
- Swap activation is managed via `swapon` (`-a` for all fstab entries, `-s`/`--show` for summary, `-p` for priority) and deactivated via `swapoff` (`-a` for all).
- Configuring equal priorities on multiple swap devices enables parallel striping (round-robin paging), increasing overall virtual memory I/O throughput.
7.6 Managing Swap Space: mkswap, swapon & swapoff
Quick Summary: The Linux virtual memory architecture utilizes swap space as an auxiliary backing store on secondary storage devices. When physical RAM is heavily utilized, the Linux kernel's memory management subsystem migrates inactive, anonymous memory pages out of RAM and into swap space, freeing up physical memory for active processes and high-throughput kernel page caches. Administrators format swap partitions or dedicated swap files using
mkswap, secure file permissions to0600, and control runtime activation usingswaponandswapoff.
1. Linux Swap Subsystem Architecture
In modern operating systems, physical Random Access Memory (RAM) is managed in fixed-size units known as pages (typically 4096 bytes on x86_64 architectures). The Linux virtual memory manager divides pages into two primary categories:
- File-Backed Pages: Memory pages corresponding directly to files on disk (such as executable binaries, shared libraries, and cached file data). When memory is pressured, the kernel can discard clean file-backed pages immediately without writing to swap, as they can be re-read from disk on demand.
- Anonymous Pages: Memory pages allocated dynamically on the heap or stack of running processes that have no backing file on the filesystem (such as variable data, program states, and runtime heaps). In the absence of swap space, anonymous pages cannot be paged out.
Linux Virtual Memory Management & Swap Architecture:
┌────────────────────────────────────────────────────────┐
│ Physical RAM │
│ ┌───────────────────────┐ ┌───────────────────────┐ │
│ │ Active Process Pages │ │ Kernel Page Cache │ │
│ └───────────────────────┘ └───────────────────────┘ │
│ ▲ │ │
│ │ Page In │ Page Out │
│ │ (Demand Fault) │ (Memory Low) │
└─────────────────┼──────────────────────┼───────────────┘
│ ▼
┌────────────────────────────────────────────────────────┐
│ Swap Space │
│ (/dev/sda3 partition OR /swapfile on disk) │
└────────────────────────────────────────────────────────┘
Primary Operational Roles of Swap Space
- Preventing Out-of-Memory (OOM) Invocations: If RAM is exhausted and no swap exists, the kernel's OOM Killer abruptly terminates memory-heavy processes (such as database or web daemons) to protect system stability.
- Optimizing System Cache Efficiency: Swap allows the kernel to evict cold, dormant background process pages to disk, maximizing the physical RAM available for read/write I/O caching.
- Enabling System Hibernation (Suspend-to-Disk): During ACPI S4 hibernation, the entire contents of physical RAM are written into swap space before powering off. Hibernation requires a swap space at least equal to physical RAM size.
- Swap Partitions vs. Swap Files: Modern Linux kernels (2.6+) access swap files with direct physical block mapping, achieving identical I/O performance to raw dedicated swap partitions.
2. Formatting Swap Areas with mkswap
The mkswap command initializes a swap area on a designated block partition (e.g., /dev/sdb2) or regular file (e.g., /swapfile), writing the standardized Linux swap header and magic signature (SWAPSPACE2) at the beginning of the space.
Command Syntax:
mkswap [options] <device-or-file> [size]
Essential mkswap Command Options Reference
| Option Flag | Long Option | Detailed Operational Description |
|---|---|---|
-L <label> | --label <label> | Assigns a volume label to the swap area (e.g., mkswap -L SWAP_VOL /dev/sdb2). |
-U <UUID> | --uuid <UUID> | Explicitly assigns a custom UUID (default automatically generates a random UUID). |
-c | --check | Scans the storage area for physical bad blocks prior to formatting. |
-f | --force | Forces swap initialization even if the partition contains active filesystem signatures. |
-p <size> | --pagesize <size> | Specifies page size in bytes (defaults to kernel architecture page size, 4096). |
# Initialize a swap partition on /dev/sdb2 with a volume label
# mkswap -L "SWAP_DRIVE" /dev/sdb2
Setting up swapspace version 1, size = 4 GiB (4294963200 bytes)
LABEL=SWAP_DRIVE, UUID=d1e02934-8c01-4478-b112-998877665544
3. Creating & Securing a Dedicated Swap File
Creating a dynamic swap file avoids the complexity of repartitioning disks. The process consists of four mandatory administrative steps:
Step-by-Step Swap File Creation Walkthrough
Step 1: Allocate Contiguous File Storage
Allocate space using dd (writing actual zeros) or fallocate (fast preallocation on supported filesystems):
# Allocate a 2 GiB file using dd (guaranteed contiguous zeroed blocks):
# dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
# Or allocate instantly using fallocate:
# fallocate -l 2G /swapfile
Step 2: Restrict File Permissions (CRITICAL SECURITY STEP)
Swap space contains unencrypted, raw application memory dumps, which may include plaintext passwords, SSH private keys, and session tokens.
# Restrict permissions strictly to root read/write only (0600)
# chmod 600 /swapfile
⚠️ LPIC-1 Trap & Security Warning — Swap File Permissions: If a swap file has permissions other than
0600(e.g.,0644),swaponwill emit a security warning (insecure permissions 0644, 0600 suggested), and unprivileged local users can read raw memory dumps of other users' processes! Always runchmod 600 /swapfile.
Step 3: Format the Swap File with mkswap
# Format the allocated file as a swap signature area
# mkswap /swapfile
Setting up swapspace version 1, size = 2 GiB (2147479552 bytes)
no label, UUID=a5b6c7d8-1122-3344-5566-778899aabbcc
Step 4: Activate the Swap File with swapon
# Enable the swap file immediately in the running kernel
# swapon /swapfile
💡 LPIC-1 Exam Fill-in-the-Blank Alert: What octal permission mode must be applied to a Linux swap file using
chmodto ensure maximum security? Answer:600(or0600)
4. Managing Swap Activation: swapon & swapoff
The Linux kernel maintains an active runtime table of all enabled swap devices. Administrators manage this state using swapon and swapoff.
The swapon Command Reference
Command Syntax:
swapon [options] [specialfile...]
| Option Flag | Long Option | Detailed Operational Description |
|---|---|---|
| (device/file) | (none) | Enables the specified swap partition or file (e.g., swapon /dev/sda3). |
-a | --all | Enables all swap spaces defined in /etc/fstab marked with the swap filesystem type. |
-s | --summary | Displays a summary table of all active swap spaces (legacy syntax, reads /proc/swaps). |
--show | [columns] | Displays a formatted table of active swap devices (device name, type, size, used, priority). |
-p <N> | --priority <N> | Sets the swap priority integer (-1 to 32767). Higher numbers indicate higher priority. |
-v | --verbose | Verbose mode; displays detailed diagnostic messages during activation. |
-e | --ifexists | Silently skips nonexistent devices when executing swapon -a. |
Swap Priority Mechanics & Disk Striping
- Sequential Allocation (Different Priorities): Swap spaces with higher priority values are filled first. Lower priority spaces remain unused until the higher-priority swap is completely exhausted (e.g., prioritizing fast NVMe swap over a slow mechanical SATA disk).
- Parallel Striping (Equal Priorities): If two or more swap devices share the same priority (e.g.,
pri=10), the Linux kernel interleaves (stripes) swap pages across them in a round-robin fashion, doubling virtual memory write/read bandwidth across separate physical disks!
# Inspect active swap spaces with swapon --show
$ swapon --show
NAME TYPE SIZE USED PRIO
/dev/sda3 partition 4G 512M 10
/swapfile file 2G 0B 10
The swapoff Command
The swapoff utility disables swapping on designated devices or files, transferring all currently swapped memory pages back into physical RAM before deactivating the backing store.
# Disable a specific swap partition (moves resident pages back into RAM)
# swapoff /dev/sdb2
# Disable all active swap spaces across the entire system
# swapoff -a
⚠️ LPIC-1 Trap — Memory Exhaustion During
swapoff: When executingswapoff, the Linux kernel must read every memory page stored in the swap space and allocate physical RAM for it. If the server does not have enough free physical RAM to accommodate the swapped data,swapoffwill fail withCannot allocate memoryor trigger the Out-Of-Memory (OOM) killer!
5. Persistent Swap Configuration in /etc/fstab
To ensure swap partitions and swap files activate automatically during the system boot sequence, they must be registered in the /etc/fstab configuration file.
/etc/fstab Swap Record Syntax
# <file system> <mount point> <type> <options> <dump> <pass>
/dev/sda3 none swap defaults 0 0
UUID=d1e02934-8c01-4478-b112-998877665544 none swap sw 0 0
/swapfile none swap defaults 0 0
/dev/sdb2 none swap sw,pri=10 0 0
Fields Breakdown for Swap Entries
- Device Identifier (Field 1): Physical device path (
/dev/sda3), UUID (UUID=...), or absolute swap file path (/swapfile). - Mount Point (Field 2): Must be specified as
noneorswap(swap is not mounted into the directory hierarchy). - Filesystem Type (Field 3): Must be set to
swap. - Mount Options (Field 4): Standard defaults (
defaults,sw), optionally accompanied by priority settings (e.g.,sw,pri=100). - Dump Flag (Field 5): Always
0(swap is never backed up bydump). - Fsck Pass Number (Field 6): Always
0(swap is never checked byfsck).
6. Monitoring Swap & Memory Metrics
System administrators monitor virtual memory and swap utilization using command-line utilities and the /proc/ virtual filesystem:
1. The free Utility
free parses /proc/meminfo to display physical RAM and swap statistics:
# Inspect memory and swap in human-readable units with wide layout (-h -w)
$ free -h -w
total used free shared buffers cache available
Mem: 15Gi 3.8Gi 7.2Gi 420Mi 280Mi 4.1Gi 11Gi
Swap: 4.0Gi 512Mi 3.5Gi
free Flag | Operational Function |
|---|---|
-h | Human-readable units (GiB, MiB). |
-m | Displays metrics in mebibytes (MiB). |
-g | Displays metrics in gibibytes (GiB). |
-s <N> | Continuously refreshes the display every <N> seconds. |
-t | Displays a total summary row combining physical RAM and Swap. |
-w | Wide mode; separates buffers and cache into distinct columns. |
2. Kernel Virtual Interfaces: /proc/swaps and /proc/meminfo
# Query active swap partitions directly from kernel procfs
$ cat /proc/swaps
Filename Type Size Used Priority
/dev/sda3 partition 4194300 524288 10
/swapfile file 2097148 0 10
# Query detailed memory statistics
$ grep -i swap /proc/meminfo
SwapCached: 48120 kB
SwapTotal: 6291448 kB
SwapFree: 5767160 kB
3. Tuning Swap Aggressiveness with vm.swappiness
The kernel parameter vm.swappiness (ranging from 0 to 100, default 60) dictates how aggressively the kernel migrates anonymous memory to swap relative to reclaiming page cache:
# View current swappiness value
$ cat /proc/sys/vm/swappiness
60
# Temporarily adjust swappiness to 10 (prefer keeping memory in physical RAM)
# sysctl vm.swappiness=10
A Linux administrator creates a new swap file at /swapfile using dd and executes mkswap /swapfile. Which file permission mode must be applied to /swapfile before activating it to maintain system security?
An administrator adds a new swap partition /dev/sdb2 to /etc/fstab. Which command activates all swap partitions and files configured in /etc/fstab in a single operation?
What occurs when an administrator executes swapoff /dev/sda3 on a system with active swap usage?