Study guide

7.6 Managing Swap Space: mkswap, swapon & swapoff (104.1/104.2)

LPIC-1 Linux Administrator — Exam 101 101-500

Track your progress as you read

Finished sections get a check mark.

1 Exam Overview & Study Strategy

1.1 LPIC-1 101-500 Exam Structure & Blueprint 1.2 Command Line & Shell Fundamentals for Exam Success 1.3 Fill-in-the-Blank Strategies & Common Traps

2 Topic 101: System Architecture

2.1 Hardware Discovery, Sysfs, Procfs & Kernel Modules (101.1) 2.2 Udev, Dbus & Device Management (101.1) 2.3 BIOS vs. UEFI & System Boot Process (101.2) 2.4 Kernel Initialization, Initramfs & System Logs (101.2) 2.5 Systemd Boot Targets & Unit Management (101.3) 2.6 SysVinit Runlevels, Telinit & System Shutdown (101.3)

3 Topic 102: Linux Installation & Boot Management

3.1 Hard Disk Layout, Partition Schemes & Swap Design (102.1) 3.2 LVM & Standard Mount Point Allocation (102.1) 3.3 GRUB 2 Configuration & Troubleshooting (102.2) 3.4 Legacy GRUB & Alternative Boot Loaders (102.2) 3.5 Managing Shared Libraries & ldconfig (102.3) 3.6 Linux as a Virtualization Guest & Cloud Instances (102.6)

4 Topic 102: Package Management Systems

4.1 Debian Low-Level Package Management with dpkg (102.4) 4.2 High-Level Debian Package Management: apt, apt-get & apt-cache (102.4) 4.3 RPM Package Management with rpm (102.5) 4.4 YUM, DNF & Zypper Package Management (102.5) 4.5 Package Repositories & Integrity Verification (102.4/102.5) 4.6 Universal Linux Packages: Snap, Flatpak & AppImage (102.4/102.5)

5 Topic 103: Command Line & Text Processing

5.1 Shell Environment, Environment Variables & Aliases (103.1) 5.2 Command History, Quoting & Expansion (103.1) 5.3 Basic Text Filters: cat, head, tail, cut, paste, nl, od (103.2) 5.4 Advanced Text Filters: sort, uniq, wc, tr, split, less & Checksums (103.2) 5.5 Stream Editing with sed (103.2) 5.6 Basic File Management: cp, mv, rm, touch, mkdir, rmdir (103.3) 5.7 Archiving and Compression: tar, gzip, bzip2, xz, cpio & dd (103.3)

6 Topic 103: Streams, Processes, Regex & Vi

6.1 Standard Streams, Redirection & File Descriptors (103.4) 6.2 Pipelines, tee & xargs (103.4) 6.3 Process Monitoring: ps, top, free, watch, pgrep, pstree & uptime (103.5) 6.4 Signals, kill, Job Control, nohup, screen & tmux (103.5) 6.5 Process Priorities: nice & renice (103.6) 6.6 Regular Expressions & grep, egrep, fgrep (103.7) 6.7 vi / vim Modes, plus nano, Emacs & EDITOR Awareness (103.8)

7 Topic 104: Devices, Partitions & Filesystems

7.1 Block Devices, fdisk & gdisk (104.1) 7.2 GNU Parted & Partition Table Management (104.1) 7.3 Creating Filesystems: mkfs, ext4, XFS, VFAT/exFAT & Btrfs (104.1) 7.4 Filesystem Integrity: fsck, e2fsck, xfs_repair, xfs_fsr & xfs_db (104.2) 7.5 Monitoring Disk Usage: df, du & tune2fs (104.2) 7.6 Managing Swap Space: mkswap, swapon & swapoff (104.1/104.2)

8 Topic 104: Mounts, Permissions, Links & FHS

8.1 Mounting and Unmounting Filesystems: mount & umount (104.3) 8.2 Persistent Mounts: /etc/fstab, UUIDs & systemd mount units (104.3) 8.3 Standard File Permissions: chmod, chown, chgrp & umask (104.5) 8.4 Special Permissions: SUID, SGID & Sticky Bit (104.5) 8.5 Hard Links vs. Symbolic Links: ln & Inodes (104.6) 8.6 Filesystem Hierarchy Standard (FHS) & File Location (104.7)

7.6 Managing Swap Space: mkswap, swapon & swapoff (104.1/104.2)

Key Takeaways Explain This Topic AI

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.

Last updated: August 2026

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 to 0600 , and control runtime activation using swapon and swapoff .

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 ), swapon will emit a security warning ( insecure permissions 0644, 0600 suggested ), and unprivileged local users can read raw memory dumps of other users' processes! Always run chmod 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 chmod to ensure maximum security? Answer: 600 (or 0600 )

Loading diagram... Swap Priority & Striping Across Multiple Storage Channels

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 executing swapoff , 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, swapoff will fail with Cannot allocate memory or 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 none or swap (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 by dump ).

Fsck Pass Number (Field 6): Always 0 (swap is never checked by fsck ).

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