Day 6: Memory I – virtual memory, page cache and page faults
Goal: understand how Linux manages main memory, read
freeand/proc/meminfocorrectly, measure the page cache, tell virtual from real memory, interpret RSS, PSS and USS, count page faults and find a process with growing memory · Duration: about 3 hours · Prerequisite: Day 0–5
Where we start
perf1 is quiet, /daten is mounted, and smem
is installed. Three short checks:
# on perf1
findmnt -no SOURCE /datenExpected:
/dev/sdb
# on perf1
command -v smemcommand -vprints the path of a program if it is installed.
Expected:
/usr/bin/smem
# on perf1
cat /proc/sys/vm/overcommit_memoryExpected:
0
This number is a setting you get to know today. Ubuntu sets it to 0.
If yours says 1, a program changed it at run time – in the author’s lab
that was a Kubernetes node that used to run on this VM (the kubelet sets
it to 1). A reboot restores the default:
sudo systemctl reboot.
Introduction
“The server has no free memory left!” – almost every administrator
has heard this sentence, and it was almost always wrong. Linux uses free
memory as a cache for files and therefore often shows a frighteningly
small number in the free column. That is not a problem but
intentional.
Memory is the resource whose numbers are misread most often. A
process that occupies 4 GB according to ps may need 300 MB.
Ten processes that occupy 100 MB each may need only 300 MB together. And
a program that does not compute at all can still be slow because on
every access to a page it has to wait until the kernel fetches it from
disk.
Today you learn the terms that keep these numbers apart: virtual and resident memory, page cache, page faults, shared memory. Tomorrow, on Day 7, it is about what happens when memory really runs short.
Today you learn:
- to read
freeand the most important fields in/proc/meminfo, - to measure the page cache at work,
- to tell virtual and resident memory (VSZ, RSS) apart, and what overcommit is,
- to tell RSS, PSS and USS apart when processes share memory,
- to count page faults and tell minor from major,
- what transparent huge pages are and how Ubuntu configures them,
- to find a process with growing memory and project when memory will run short.
Background
The picture for today: the reading room of a library
Picture main memory as a reading room with many tables of the same size. Each table is a page (4 KiB). The readers are processes, the stacks in the basement are the disk.
- Virtual memory is a reservation card. A reader can have 1,000 tables reserved. But a table is only occupied once they actually sit down. VSZ counts the reservations, RSS the occupied tables.
- Overcommit: The library hands out more reservations than there are tables – like an airline betting that not everyone will show up.
- The page cache is the returns cart. Returned books
stay next to the tables as long as there is room. If someone wants the
same book again, it is there at once. If a reader needs a table, the
cart is cleared. That is why
availablecounts, notfree. - A page fault is a trip to the librarian. If the book is on the cart or only a blank sheet is needed, it is quick (minor fault). If they have to go down to the stacks, it takes a while (major fault).
- Shared books: If three readers sit at a shared table with the same reference work, RSS counts the work fully for each of them, PSS a third for each, USS not at all.
- Transparent huge pages are large tables: one table for 512 books instead of 512 small ones – handy for heavy readers, but you first have to find a free large table.
The terms
| Term | Meaning | in the picture |
|---|---|---|
| Page | unit of memory, normally 4 KiB | table |
| VSZ | size of the virtual address space | reservations |
| RSS | part that currently lies in main memory | occupied tables |
| Overcommit | promising more memory than there is | overbooked reservations |
| Page cache | file contents in memory, reclaimable | returns cart |
| Minor / major fault | provide a page without / with disk access | cart / stacks |
| USS, PSS | own memory / with a proportional share of shared memory | own books / share of the shared work |
| THP | 2 MiB pages | large table |
Remember:
freeshows empty tables,availableempty tables plus the returns cart. Onlyavailablesays how much a new program can get.
Virtual memory and pages
Every process sees its own huge virtual address space – on x86-64 up to 128 TiB. It believes all memory belongs to it. In reality the CPU translates every address into a real address in main memory via page tables. The unit of this translation is the page, normally 4 KiB on x86-64.
The trick: a virtual page only gets real memory when the process
touches it for the first time. If a program requests 4
GB with malloc, the kernel only reserves addresses. Real
memory only flows, page by page, when the program writes into it.
That gives two sizes per process:
- VSZ (virtual size): the size of all areas in the virtual address space – reserved, mapped, used or not. Usually much larger than needed and of little use for troubleshooting.
- RSS (resident set size): the part that actually lies in main memory right now.
Page faults
If a process accesses a virtual page for which there is no translation yet, the CPU raises an exception, the page fault. The kernel steps in and provides the page. Two kinds:
- Minor fault: The kernel can provide the page without disk access – a fresh page filled with zeros for new memory, or a page that is already in the page cache. Costs microseconds.
- Major fault: The page first has to be read from disk – from a file or from swap. Costs as long as a disk access, that is milliseconds. Many major faults make a program slow without it computing.
Page faults are not errors in the usual sense but the normal way a process gets memory.
The page cache
Everything read from files is kept in main memory by the kernel as long as there is room – in the page cache. If a program reads the same file again, it comes from memory, a hundred times faster than from disk. Writes also land in the page cache first and are written to disk later in batches (dirty pages, Day 8).
The page cache takes all memory nobody else needs. If a program needs
memory, the kernel frees cache pages. That is why free memory is
wasted memory – and the free column in
free a poor metric. The right one is
available: free memory plus what can be
freed from the cache immediately.
Overcommit
Because programs often request more memory than they use, Linux
allows promising more than there is – overcommit. The
setting vm.overcommit_memory controls how generous it
is:
- 0 (default): a heuristic. Requests that obviously cannot be met (more than memory plus swap at once) are refused by the kernel, everything else is allowed.
- 1: always allow. Databases such as Redis recommend this, and Kubernetes sets it on its nodes.
- 2: strict. In total no more may be promised than
CommitLimit(swap plus a share of memory, 50 % by default).
If promised memory is actually needed and none is left, the OOM killer finally steps in and ends a process. That is the topic of Day 7.
RSS, PSS and USS
Processes share memory: program code and libraries are in main memory
only once, even if ten processes use them. RSS counts
shared pages fully for every process. If you add up the
RSS of all processes, you get more than there is memory.
Two more precise sizes help:
- USS (unique set size): only the pages that belong exclusively to this process. That much would be freed if it ended.
- PSS (proportional set size): USS plus the share of shared pages – a page shared by three processes counts a third for each. The sum of all PSS gives the memory actually in use.
smem shows all three. The kernel provides PSS in
/proc/PID/smaps_rollup.
Transparent huge pages
Instead of 4 KiB pages, the CPU can also use 2 MiB
pages. That saves entries in the page tables and in the CPU’s
translation buffer (TLB) and can speed up memory-hungry
programs. Transparent huge pages (THP) use such pages
automatically without the program having to do anything. The drawback:
the kernel has to find contiguous 2 MiB blocks and sometimes rearrange
memory for that, which can cause latency spikes. Ubuntu therefore sets
THP to madvise: only for programs that explicitly ask for
it.
Drill 1: free and /proc/meminfo
Where you are: on perf1, shortly after a reboot.
What you have afterwards: every column of
freeinterpreted, and you know which fields of/proc/meminfoit comes from.
# on perf1
free -mExpected:
total used free shared buff/cache available
Mem: 11961 434 11480 1 296 11526
Swap: 0 0 0
total– the memory the kernel can manage (somewhat less than installed, because firmware and the kernel itself reserve parts).used– occupied by programs and the kernel, without cache.free– completely unused.shared– shared memory, mainlytmpfsfile systems such as/runor/dev/shm.buff/cache– page cache and kernel buffers, reclaimable.available– what a new program could get without anything having to be swapped out.
After a reboot the cache is still small (296 MiB), so
free and available are close together. That
changes in a moment.
The raw data is in /proc/meminfo:
# on perf1
cat /proc/meminfoExpected (excerpt – the lines you need; the file has about 50):
MemTotal: 12248224 kB
MemFree: 11756412 kB
MemAvailable: 11802860 kB
Buffers: 25268 kB
Cached: 258116 kB
Active(anon): 41584 kB
Inactive(anon): 0 kB
Active(file): 190564 kB
Inactive(file): 82916 kB
Dirty: 628 kB
AnonPages: 59200 kB
Shmem: 1132 kB
Slab: 71932 kB
SReclaimable: 19876 kB
SUnreclaim: 52056 kB
CommitLimit: 6124112 kB
Committed_AS: 252892 kB
AnonHugePages: 0 kB
ShmemHugePages: 0 kB
ShmemPmdMapped: 0 kB
The fields you should remember:
Cached– the page cache (file contents).AnonPages– anonymous memory: everything that does not belong to a file – heap and stack of the programs. That is the memory that is really “used up”.Active(file),Inactive(file)– cache pages used recently or not for a while. Inactive ones are freed first. The same exists for anonymous memory.Dirty– modified cache pages that still have to go to disk.Slab– memory for kernel data structures (such as inode and directory caches);SReclaimableof it is reclaimable,SUnreclaimis not.Committed_AS– all promised memory requests together;CommitLimitthe limit, which only applies withovercommit_memory = 2. Without swap it is half of memory.AnonHugePages– anonymous memory in 2 MiB pages (THP).
free roughly computes used as
MemTotal − MemFree − Buffers − Cached − SReclaimable, and
available is MemAvailable, an estimate by the
kernel.
Remember:
AnonPagesis used memory,Cachedis borrowed.MemAvailablesays what is really still possible.
Save your progress? Sign up for free
Drill 2: The page cache at work
Where you are: on perf1.
What you have afterwards: measured how much faster a file comes from the page cache, and seen how the cache grows.
Step 1 – create a large file.
# on perf1
dd if=/dev/urandom of=/daten/gross.bin bs=1M count=1024 status=none- 1,024 blocks of 1 MiB random data, that is 1 GiB;
status=nonesuppresses the message.
Step 2 – empty the cache. First write all modified pages to disk, then discard the page cache. You know the command from Day 3 – lab only:
# on perf1
sync# on perf1
echo 3 | sudo tee /proc/sys/vm/drop_cachesteewrites into the kernel file with root rights;3means discard the page cache and slab objects.teerepeats the3on the screen.
Step 3 – how large is the cache now?
# on perf1
grep -E "^Cached" /proc/meminfo^stands for the beginning of the line – so onlyCachedmatches, notSwapCached.
Expected:
Cached: 60088 kB
Step 4 – the first read.
# on perf1
time cat /daten/gross.bin > /dev/nullcatreads the file,> /dev/nullthrows the content away – it is only about reading.
Expected:
real 0m8.470s
user 0m0.032s
sys 0m3.891s
# on perf1
grep -E "^Cached" /proc/meminfoExpected:
Cached: 1108788 kB
Step 5 – the second read.
# on perf1
time cat /daten/gross.bin > /dev/nullExpected:
real 0m0.341s
user 0m0.013s
sys 0m0.328s
# on perf1
free -mExpected:
total used free shared buff/cache available
Mem: 11961 422 10687 1 1098 11538
Swap: 0 0 0
- The first read comes from disk: 8.5 seconds for 1
GiB. Only 3.9 seconds of that were CPU time in the kernel
(
sys); for the rest,catwaited for the disk. - Afterwards
Cachedhas grown by 1 GiB: the whole file is in the page cache. - The second read takes 0.34 seconds – 25
times faster, and
real≈sys: no more waiting, only copying from memory. freehas dropped by 800 MiB, butavailablehas stayed practically the same. That is exactly what “free memory is wasted memory” means: the cache occupies space that every program gets back at any time.
For benchmarks this is the biggest pitfall (Day 10), in operations one of the biggest advantages: a database whose data fits entirely into the page cache hardly reads from disk anymore.
Remember: What was read once lies on the returns cart: the second read was 25 times faster – and
availablestayed the same.
Save your progress? Sign up for free
Drill 3: Virtual, resident and promised
Where you are: on perf1, in the directory
~/tag06.What you have afterwards: a program that requests 4 GiB and uses 300 MiB – and you have seen what
ps,/procandpmapmake of it.
Step 1 – the program.
# on perf1
mkdir -p ~/tag06# on perf1
cd ~/tag06# on perf1
nano reserviere.cContent (nano as on Day 0: Ctrl+O and Enter saves, Ctrl+X exits):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char **argv)
{
size_t reserviert = (size_t)atol(argv[1]) * 1024 * 1024;
size_t benutzt = (size_t)atol(argv[2]) * 1024 * 1024;
char *p = malloc(reserviert);
if (p == NULL) {
perror("malloc");
return 1;
}
memset(p, 1, benutzt); /* nur diesen Teil wirklich anfassen */
printf("PID %d: %zu MiB reserviert, %zu MiB benutzt (Probe: %d)\n",
getpid(), reserviert >> 20, benutzt >> 20, benutzt ? p[benutzt - 1] : 0);
fflush(stdout);
pause(); /* warten, bis jemand uns beendet */
return 0;
}# on perf1
gcc -O2 -o reserviere reserviere.cThe program takes two numbers: how many MiB it should request and how many of them it should write to.
atol(argv[1])turns the first argument into a number;* 1024 * 1024turns MiB into bytes.malloc(reserviert)requests the memory (reserviert= “reserved”). If there is none,NULLcomes back, andperrorprints the system’s error message.memset(p, 1, benutzt)writes into the firstbenutzt(“used”) bytes – only then are real pages created.- The output reads one byte back with
p[benutzt - 1](Probe= “probe”). That is necessary: without this access, the compiler at-O2recognizes that the written memory is never read and drops thememsetentirely. While building this course, RSS therefore first stayed at 1.7 MB. >> 20divides by 2²⁰, that is converts bytes to MiB.fflush(stdout)prints the line right away,pause()makes the program wait until it receives a signal.
Step 2 – request 4 GiB, use 300 MiB. The program waits afterwards; it runs in its own terminal:
# on perf1, terminal 1
./reserviere 4096 300Expected:
PID 1414: 4096 MiB reserviert, 300 MiB benutzt (Probe: 1)
The program reports its PID itself. Use it in terminal 2 instead of
PID.
Step 3 – what ps says.
# on perf1, terminal 2
ps -o pid,vsz,rss,comm -p PIDExpected:
PID VSZ RSS COMMAND
1414 4196992 308940 reserviere
Step 4 – what the kernel says.
/proc/PID/status contains the memory values of a
process:
# on perf1, terminal 2
cat /proc/PID/statusExpected (excerpt – the lines VmSize,
VmRSS, RssAnon, RssFile):
VmSize: 4196992 kB
VmRSS: 308940 kB
RssAnon: 307304 kB
RssFile: 1636 kB
Step 5 – the address space in detail.
# on perf1, terminal 2
pmap -x PIDpmap -xlists all areas in a process’s address space with size, resident and modified share.
Expected (excerpt – the last two lines with the total):
---------------- ------- ------- -------
total kB 4196996 308940 307316
Step 6 – the promise.
# on perf1, terminal 2
grep Committed_AS /proc/meminfoExpected:
Committed_AS: 4447880 kB
- VSZ = 4 GiB, RSS = 302 MiB: the process has 4 GiB of addresses, but only what is used lies in memory. Whoever looks at the VSZ column overestimates consumption thirteenfold.
RssAnonis the 300 MiB written,RssFilethe program itself and the libc.Committed_AShas risen by a good 4 GiB: the kernel promised the whole block, even though it only had to hand out a fraction.
Stop the program in terminal 1 with Ctrl+C.
Step 7 – how far does the promise go? With
overcommit_memory = 0 the kernel only refuses requests that
obviously do not fit. First 20,000 MiB:
# on perf1, terminal 1
./reserviere 20000 10Expected:
malloc: Cannot allocate memory
Then 9,000 MiB:
# on perf1, terminal 1
./reserviere 9000 10Expected:
PID 1820: 9000 MiB reserviert, 10 MiB benutzt (Probe: 1)
Stop it again with Ctrl+C.
20,000 MiB is more than all memory – refused. 9,000 MiB fit into free memory – allowed, even though only 10 MiB are used. But many processes together could be promised more this way than there is. That is the core of overcommit.
Remember:
mallocreserves, only writing occupies. VSZ counts reservations, RSS occupied tables – for consumption RSS counts (or better PSS).
If it doesn’t work
- RSS stays at about 1.7 MB: you left out the
Probein theprintfline, and the compiler dropped thememset. ./reserviere 9000 10also reportsCannot allocate memory: your VM has less than 9 GiB free. Use a number just belowavailablefromfree -m.
Save your progress? Sign up for free
Drill 4: Shared memory – RSS, PSS, USS
Where you are: on perf1.
What you have afterwards: seen for three identical processes how much memory they really occupy.
Step 1 – three identical processes. Three Python
processes that sleep for two minutes. The & at the end
starts each one in the background so you can keep typing right away:
# on perf1
python3 -c "import time; time.sleep(120)" &# on perf1
python3 -c "import time; time.sleep(120)" &# on perf1
python3 -c "import time; time.sleep(120)" &Step 2 – measure.
# on perf1
smem -k -P "python3 -c" -c "pid name uss pss rss"-kshows sizes with a unit (M).-P "python3 -c"filters by the command line.-cselects the columns.
Expected:
PID Name USS PSS RSS
76013 bash 1.4M 1.5M 3.4M
76015 python3 3.7M 4.6M 10.0M
76014 python3 3.7M 4.6M 10.1M
76016 python3 3.7M 4.6M 10.1M
76018 smem 7.5M 8.7M 14.4M
(The shell and smem itself also match the search
pattern.)
Step 3 – the total. -t adds a total
line:
# on perf1
smem -k -P "python3 -c" -c "pid name uss pss rss" -tExpected:
PID Name USS PSS RSS
76013 bash 1.4M 1.5M 3.4M
76015 python3 3.7M 4.6M 10.0M
76014 python3 3.7M 4.6M 10.1M
76016 python3 3.7M 4.7M 10.1M
76019 smem 7.5M 8.6M 14.4M
----------------------------------------------------------
5 20.2M 24.1M 48.0M
The last line is the total over all five processes.
Step 4 – clean up. %1 %2 %3 refers to
the three background jobs of this shell:
# on perf1
kill %1 %2 %3What the measurement shows: each Python process has about 10 MB RSS, but only 3.7 MB belong to it alone (USS). The rest is the interpreter and libraries that all three share. PSS divides this rest by three: 4.6 MB. So the three together do not occupy 30 MB, as the RSS sum says, but about 14 MB. For services with many processes – web servers with worker processes, databases with one process per connection – this difference amounts to gigabytes.
Remember: RSS counts the shared work fully for everyone. The sum of PSS is the real consumption, USS what is freed on exit.
Save your progress? Sign up for free
Drill 5: Counting page faults
Where you are: on perf1.
What you have afterwards: counted minor and major faults and seen why the number of major faults can be deceptive.
Step 1 – new memory creates minor faults.
# on perf1
sudo perf stat -e page-faults,major-faults,minor-faults -- python3 -c "b = bytearray(500*1024*1024)"bytearray(500*1024*1024)creates 500 MiB of memory filled with zeros.perf stat -e …counts the software events for page faults while doing so.
Expected (excerpt – the three lines with
faults):
129101 page-faults
0 major-faults
129101 minor-faults
500 MiB are 128,000 pages of 4 KiB – and indeed: 129,101 minor
faults, one per page (plus the start of the interpreter). None of them
needed the disk. That THP does not kick in here is due to the
madvise setting: Python does not ask for huge pages.
Step 2 – map a file, cold and warm. A program can
map a file into its address space with mmap. Every first
access to a page is then a page fault – and if the page is not in the
cache, a major fault:
# on perf1
nano ~/tag06/lies.pyContent:
import mmap
with open("/daten/gross.bin", "rb") as f:
m = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
s = sum(m[i] for i in range(0, len(m), 4096))- The Python program opens the file, maps it completely and read-only
with
mmap.mmap(…, 0, access=mmap.ACCESS_READ)(0means: the whole file) and reads one byte from every 4 KiB page.
Empty the cache as in Drill 2:
# on perf1
sync# on perf1
echo 3 | sudo tee /proc/sys/vm/drop_cachesNow the cold run:
# on perf1
/usr/bin/time -v python3 ~/tag06/lies.py/usr/bin/time -vprints detailed statistics after the run, among them the page faults.
Expected (excerpt – the lines Elapsed
and page faults):
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:04.84
Major (requiring I/O) page faults: 22
Minor (reclaiming a frame) page faults: 17503
And right afterwards the warm run, the same command:
# on perf1
/usr/bin/time -v python3 ~/tag06/lies.pyExpected (excerpt):
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.43
Major (requiring I/O) page faults: 0
Minor (reclaiming a frame) page faults: 17508
Cold 4.8 seconds, warm 0.43 – the same effect as in Drill 2 (disk times vary a lot in the lab). But the fault numbers are surprising: for 262,144 pages there were only 17,500 faults, and cold only 22 major faults. Two kernel mechanisms are behind this:
- Fault-around: On a fault on a file page, the kernel maps the neighboring pages that are already in the cache at the same time – 16 at once. Hence 262,144 ÷ 16 ≈ 16,400 faults.
- Readahead: On the first major fault, the kernel recognizes the read pattern and reads far ahead. Later accesses find their pages already in the cache or on their way – they count as minor faults, even if they had to wait for the disk.
The lesson: the number of major faults underestimates the waiting for the disk. The run time (and off-CPU analysis as on Day 5) tells the truth.
Step 3 – clean up.
# on perf1
rm -f /daten/gross.binRemember: Minor faults are the returns cart, major faults the trip to the stacks. Because the kernel reads ahead, the number of major faults underestimates the waiting – the run time tells the truth.
Save your progress? Sign up for free
Drill 6: Transparent huge pages
Where you are: on perf1.
What you have afterwards: read Ubuntu’s THP setting.
Step 1 – when are there huge pages?
# on perf1
cat /sys/kernel/mm/transparent_hugepage/enabledExpected:
always [madvise] never
Step 2 – when does the kernel rearrange memory for them?
# on perf1
cat /sys/kernel/mm/transparent_hugepage/defragExpected:
always defer defer+madvise [madvise] never
Step 3 – does anyone use them?
# on perf1
grep AnonHugePages /proc/meminfoExpected:
AnonHugePages: 0 kB
The value in square brackets is the active one.
enabled = madvise: huge pages only for areas for which a
program requests them with the system call
madvise(MADV_HUGEPAGE). defrag = madvise: only
for these areas does the kernel rearrange memory immediately if
necessary. On perf1 nobody uses huge pages
(AnonHugePages: 0 kB). Databases such as PostgreSQL or Java
runtimes request them specifically; some vendors (for example of Redis
or MongoDB), on the other hand, recommend turning THP off completely
because the rearranging causes latency spikes. What is right is decided
by measurement, not by habit.
Remember: Ubuntu only gives out large tables on request (
madvise). Whether huge pages help or hurt is decided by measuring your own service.
Save your progress? Sign up for free
Diagnosis task
The night shift reports: “perf1 is eating memory.
available has been dropping steadily since the session
service was deployed.” You are to find out who is growing, how fast, and
when memory will run short.
Setup.
# on perf1
nano ~/tag06/sitzungen.pyContent:
import time, uuid
cache = {}
def anfrage(n):
sitzung = str(uuid.uuid4())
cache[sitzung] = bytearray(64 * 1024) # Sitzungsdaten, werden nie entfernt
return sitzung
n = 0
while True:
for _ in range(40):
anfrage(n)
n += 1
time.sleep(0.2)# on perf1
sudo systemd-run --unit=sitzungsdienst -p User=ubuntu python3 /home/ubuntu/tag06/sitzungen.py-p User=ubuntu makes the service run as user
ubuntu instead of root.
Expected:
Running as unit: sitzungsdienst.service; invocation ID: a062c4bf1b1e4c5f9664bbf9f50dff33
Wait 30 seconds. Caution: the service fills memory in about a quarter of an hour. Stop it after ten minutes at the latest (see solution).
Task (15 minutes): Who is growing? How fast? When will memory be full? Where can you monitor this without a process ID?
Solution path
Step 1 – who? The processes sorted by RSS:
# on perf1
ps -eo pid,rss,comm --sort=-rss | head -4-eall processes,-othe columns,--sort=-rssby RSS in descending order.head -4keeps the header line and the three largest.
Expected:
PID RSS COMMAND
1575 979024 python3
393 27464 multipathd
821 23148 unattended-upgr
A Python process with almost 1 GB, far ahead of all others.
Step 2 – does it belong to the suspicious service? systemd provides the main process ID of a service directly:
# on perf1
systemctl show -p MainPID --value sitzungsdienstsystemctl show -p prints a single property,
--value only the value without the name.
Expected:
1575
Yes – the same number.
Step 3 – how fast? pidstat -r shows
memory values and page faults per process at an interval:
# on perf1
pidstat -r -p 1575 10 3-r selects the memory statistics, -p the
process; use your process ID.
Expected:
13:05:12 UID PID minflt/s majflt/s VSZ RSS %MEM Command
13:05:22 1000 1575 2961.40 0.00 756064 747776 6.11 python3
13:05:32 1000 1575 2887.10 0.00 871420 863232 7.05 python3
13:05:42 1000 1575 2862.80 0.00 986712 977792 7.98 python3
Average: 1000 1575 2903.77 0.00 871399 862933 7.05 python3
RSS grows by about 115,000 KiB every ten seconds: about 11.5 MB per second, 690 MB per minute. The roughly 2,900 minor faults per second are the new pages (11.5 MB ÷ 4 KiB). VSZ and RSS grow in lockstep – the memory is not only reserved but really used.
Step 4 – when will it be full?
# on perf1
grep MemAvailable /proc/meminfoExpected:
MemAvailable: 10825164 kB
# on perf1
grep AnonPages /proc/meminfoExpected:
AnonPages: 1042268 kB
10.8 GB available ÷ 690 MB per minute ≈ 16 minutes. Then the kernel starts sacrificing cache, and finally the OOM killer steps in (Day 7). PSI does not show any pressure yet:
# on perf1
cat /proc/pressure/memoryExpected:
some avg10=0.00 avg60=0.00 avg300=0.00 total=9006
full avg10=0.00 avg60=0.00 avg300=0.00 total=0
That is exactly what makes memory leaks treacherous: everything is fine until shortly before the end, and then it goes fast.
Step 5 – monitor without a process ID. The service can restart and get a new number. The cgroup stays. The total memory of the cgroup in bytes:
# on perf1
cat /sys/fs/cgroup/system.slice/sitzungsdienst.service/memory.currentExpected:
389771264
The breakdown:
# on perf1
cat /sys/fs/cgroup/system.slice/sitzungsdienst.service/memory.statExpected (excerpt – the lines anon,
file, kernel):
anon 388595712
file 286720
kernel 888832
anonis anonymous memory,filepage cache attributed to this cgroup,kernelkernel memory for it.
And the hard limit:
# on perf1
cat /sys/fs/cgroup/system.slice/sitzungsdienst.service/memory.maxExpected:
max
Almost everything is anon – growing data in the program,
not cache. And max means: no limit. The
service may fill the whole machine. How to prevent that with
memory.high and memory.max is shown on Day
7.
Step 6 – the history in the recording.
# on perf1
sar -r -s 13:03:00-rmemory values,-sfrom this time on. Use a time shortly before your setup.
Expected (excerpt – only the first columns, cut off on the right):
13:03:06 kbmemfree kbavail kbmemused %memused kbbuffer
13:04:08 10588364 11476392 466892 3.81 634
13:05:05 10345160 11285948 656904 5.36 916
13:06:15 9490364 10443732 1498940 12.24 1060
Average: 10141296 11068691 874245 7.14 870
kbavail drops minute by minute. In operations this curve
is the classic sight of a leak: a straight line down that does not care
about the time of day.
Step 7 – the cause in the code. Now a look at
sitzungen.py (“sessions”) pays off: every request puts 64
KiB into the dictionary cache, but nothing ever
removes them. 40 requests every 0.2 seconds × 64 KiB = 12.8 MB
per second – matches the measurement. The fix belongs in the code:
delete sessions after a while or use a bounded cache.
Step 8 – fix (for now) and clean up.
# on perf1
sudo systemctl stop sitzungsdienst# on perf1
sudo systemctl reset-failed sitzungsdienstIf the second one reports
Unit sitzungsdienst.service not loaded, the service is
already forgotten – not an error.
# on perf1
free -mExpected:
total used free shared buff/cache available
Mem: 11961 435 10591 1 1181 11525
Swap: 0 0 0
On exit, the kernel immediately gives back all of the process’s anonymous memory. So restarting the service really helps in operations – for a quarter of an hour.
If it doesn’t work
pgrep -f sitzungen.pyreturns two numbers: the search also matches the shell in which you typed the command. Usesystemctl show -p MainPID --value sitzungsdienst.pidstatprints its help: you passed several numbers separated by spaces;-pexpects them separated by commas.
Challenge
How much memory would be freed if you stopped the session service –
and how much of that is PSS, how much USS? Restart the service, wait a
minute and measure with smem. Explain the difference from
the three sleeping Python processes from Drill 4.
Solution path:
# on perf1
smem -k -P sitzungen -c "pid name uss pss rss"Expected:
PID Name USS PSS RSS
1816 bash 2.0M 2.1M 4.0M
1841 smem 7.5M 9.2M 14.4M
1837 python3 719.2M 720.6M 725.6M
After one minute USS, PSS and RSS are almost the same size. The grown memory belongs exclusively to this process; the few MB of shared interpreter no longer matter. With the sleeping processes it was the other way round: there the shared part was the largest. USS is the answer to “How much will be freed when it ends?”. Afterwards stop the service again.
Save your progress? Sign up for free
Checkpoint
# on perf1
systemctl is-active sitzungsdienstExpected: inactive.
# on perf1
pgrep -c reserviereExpected: 0.
# on perf1
ls /datenExpected: only lost+found.
# on perf1
free -mExpected: in the line Mem: a value in the column
available close to total, in the lab 11567
MiB.
Test yourself
freeshows 200 MiB free,available10 GiB. Is memory short?- A process has VSZ 4 GiB and RSS 300 MiB. How much main memory does it occupy?
- Three identical processes have 10 MB RSS each. Do they occupy 30 MB together? Which size tells you?
- What is the difference between a minor and a major fault, and why can the number of major faults be deceptive?
- How do you monitor the memory of a service whose PID changes with every restart?
Answers:
- No –
availableincludes the page cache, which the kernel frees immediately. - About 300 MiB; VSZ is only reserved addresses.
- No, the shared pages count for each of them. The sum of PSS is the real consumption (in the lab about 14 MB instead of 30 MB).
- Minor: without disk access (microseconds), major: with (milliseconds). Readahead and fault-around make later accesses count as minor even though they waited for the disk.
- Via the cgroup:
memory.currentandmemory.statunder/sys/fs/cgroup/system.slice/DIENST.service/(DIENST= service).
Interview Note
“The server only shows 200 MB of free memory. Is that a problem?” –
The expected answer: no, as long as available is high,
because Linux uses free memory as page cache. Whoever then explains when
it is a problem after all (available drops,
si/so in vmstat, PSI memory,
major faults) and cleanly separates VSZ/RSS/PSS comes across as someone
who understands memory. Bonus: being able to explain overcommit – and
why the OOM killer exists.
Enterprise Note
In data centers memory is often the most expensive resource per
server, and oversizing is the rule because nobody trusts the
used value. Whoever plans capacity should record
MemAvailable and the anonymous share
(AnonPages or memory.stat anon per service)
over weeks, not free. For services with many processes, PSS
belongs in monitoring. Memory leaks are found most reliably with a trend
rule: “memory.current of a service has been rising
monotonically for six hours” – and every service gets a memory limit so
that a leak does not take the whole host with it (Day 7 and 15).
Summary
availableis the important number infree, notfree. The page cache takes free memory and gives it back when needed./proc/meminfo:Cached,AnonPages,Dirty,Slab,Committed_ASare the fields for everyday use.- A read from the page cache was 25 times faster than from disk.
- VSZ = reserved addresses, RSS = in
memory.
mallocreserves, only writing occupies. Overcommit (default 0) promises more than there is. - USS belongs only to the process, PSS shares common memory proportionally – the sum of PSS is the real consumption.
- Minor faults cost microseconds, major faults a disk access. Readahead and fault-around make major faults appear too low.
- Ubuntu sets THP to
madvise. - Diagnosis today: a leak at 11.5 MB/s, found with
ps --sort=-rss,pidstat -r,sar -randmemory.currentof the cgroup – projected to 16 minutes until memory is full.
Commands at a glance
| Command | What it does | Parameters |
|---|---|---|
free -m |
memory overview in MiB | -m MiB |
cat /proc/meminfo /
grep FELD /proc/meminfo |
raw memory data (FELD = field) |
– |
ps -o pid,vsz,rss,comm -p PID |
virtual and resident memory | – |
ps -eo pid,rss,comm --sort=-rss |
processes by RSS | --sort=-rss descending |
cat /proc/PID/status |
memory of a process (VmSize, VmRSS,
RssAnon, RssFile) |
– |
pmap -x PID |
areas in the address space | -x with RSS and dirty |
smem -k -P MUSTER -c "pid name uss pss rss" [-t] |
USS, PSS, RSS (MUSTER = pattern) |
-k units, -P filter, -c
columns, -t total |
perf stat -e page-faults,major-faults,minor-faults |
count page faults | – |
/usr/bin/time -v BEFEHL |
run time, RSS maximum, faults (BEFEHL = command) |
-v verbose |
pidstat -r -p PID 10 3 |
memory and faults per process | -r memory |
sar -r -s ZEIT |
memory from the recording (ZEIT = time) |
– |
systemctl show -p MainPID --value DIENST |
main process of a service (DIENST = service) |
-p property, --value value only |
cat …/memory.current, memory.stat,
memory.max |
memory of a cgroup | – |
cat /sys/kernel/mm/transparent_hugepage/enabled |
THP setting | – |