Chapter 2.3 - Memory Management and Swap
Learning Objectives
By the end of this chapter, you will be able to:
- Understand how Linux manages memory
- Explain virtual memory and paging
- Understand swap and its role
- Monitor memory usage
- Optimize memory usage
What is Memory Management?
Linux uses a sophisticated memory management system that combines physical memory (RAM) and virtual memory (swap) to optimize performance and allow more processes to run than the available RAM.
Physical Memory vs Virtual Memory
Physical Memory (RAM)
- Fast: Direct access by the CPU
- Limited: Fixed amount installed
- Volatile: Lost on reboot
- Costly: More expensive than disk storage
Virtual Memory
- Abstract: Each process sees a virtual memory space
- Paging: Divided into pages (usually 4KB)
- Mapping: Virtual pages mapped to RAM or swap
- Protection: Isolation between processes
Paging and MMU
The MMU (Memory Management Unit) handles address translation:
Swap
Swap is disk space used as an extension of RAM:
Roles:
- Extending available memory
- Supporting more processes
- Improving stability
Types:
- Swap partition: Dedicated partition (recommended)
- Swap file: Swap file (more flexible)
Configuration:
# View swap
free -h
swapon --show
# Create a swap file
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
# Enable at boot
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Memory Monitoring
Monitoring Commands
# Overview
free -h
# Details per process
top
htop
# Detailed statistics
cat /proc/meminfo
# Usage by process
ps aux --sort=-%mem | head
Interpretation
- MemTotal: Total RAM
- MemFree: Free RAM
- MemAvailable: Available RAM (free + reclaimable cache)
- SwapTotal: Total swap
- SwapFree: Free swap
Memory Optimization
Best Practices
-
Monitor regularly
- Use
free,top,htop - Identify resource-intensive processes
- Use
-
Adjust swap
- Recommended size: 1-2x RAM
- More if server with a lot of RAM
-
Limit processes
- Use
ulimitto limit memory - Configure OOM killer
- Use
-
Clean cache
# Free cache (if necessary)
sync
echo 3 | sudo tee /proc/sys/vm/drop_caches
Summary
In this chapter, you learned:
Memory Management: RAM + Swap to optimize performance
Virtual Memory: Abstraction for each process
Paging: Division into pages, managed by MMU
Swap: Extension of RAM on disk
Monitoring: free, top, htop, /proc/meminfo
Optimization: Monitoring, swap adjustment, limits
Next Steps
Chapter 2.4: Virtual File System (VFS)
Chapter 2.5: Process Management
Chapter created on: December 2024