Kernel sysctl, OOM Killer and Safe Kernel Upgrade Procedures

Last Verified On: Kernel 6.8 / 6.12 LTS / Ubuntu 24.04 LTS & Debian 12/13 Moderate (Service Restart) Exit Code: 137

Direct Answer / TL;DR

OOM deaths come from memory overcommit — the kernel SIGKILLs the highest-badness RSS+swap process (exit 137); confirm with dmesg -T | grep -i 'out of memory', fix the leak or set MemoryMax=/OOMScoreAdjust. Identical on Ubuntu 24.04, Debian 12 and RHEL 9: persist sysctls in /etc/sysctl.d/, keep a fallback kernel, upgrade with apt/dnf, reboot.

dmesg -T | grep -Ei 'oom-killer|out of memory|killed process'
Out of memory: Killed process 21487 (mysqld) total-vm:9324508kB, anon-rss:7002318kB, shmem-rss:24576kB, UID:999, pgtables:24580kB, oom_score_adj:0

Core Architecture & Mechanics

Every runtime kernel knob is a file under /proc/sys (procfs). The procps-ng tool sysctl(8) and systemd’s systemd-sysctl(8) are only writers: the kernel validates on write() and silently clamps out-of-range input (since kernel 6.8 vm.swappiness accepts 0-200; older kernels cap at 100). Keys are grouped by subtree: kernel.*, vm.*, net.*, fs.*, user.*, debug.*, abi.*. The net.* subtree is per-network-namespace, so containers may set namespaced keys (net.ipv4.ip_forward, net.core.somaxconn) independently; almost everything under kernel.*, vm.* and fs.* is host-global and read-only inside unprivileged containers.

Persistence is a file-merge problem: systemd-sysctl.service applies /usr/lib/sysctl.d, /run/sysctl.d and /etc/sysctl.d at boot, sorted lexicographically by filename, with the /etc copy of a duplicate filename winning; the legacy /etc/sysctl.conf is applied last. sysctl --system replays that order manually; sysctl -p loads its argument file (default /etc/sysctl.conf). Pure runtime writes (sysctl -w) evaporate at reboot. Editorial rule: one dedicated drop-in per concern — e.g. /etc/sysctl.d/99-memory.conf — previewed with systemd-sysctl --cat-config, applied with sysctl --system.

Unknown keys never abort the boot: systemd-sysctl logs per-key warnings under journalctl -u systemd-sysctl, procps prints cannot stat /proc/sys/...: No such file or directory. Kernels add and drop keys across versions and module loads (net.bridge.* exists only after modprobe br_netfilter). Distro patching diverges too: Debian carries kernel.unprivileged_userns_clone, while Ubuntu 24.04 instead ships kernel.apparmor_restrict_unprivileged_userns (default 1) — copying another distro’s sysctl file without checking key existence produces recurring boot warnings.

The OOM killer is mm/‘s last-resort reclaim. When direct reclaim, compaction and the oom notifier cannot free pages for a faulting allocation, out_of_memory() scores every candidate: points = 1000 x (RSS + swap + page tables) / total usable memory, plus the oom_score_adj shift scaled in the same percentage terms. The highest-scoring task group receives SIGKILL (shells report exit status 137). pid 1, kernel threads and tasks pinned at oom_score_adj -1000 are exempt. Because the adjustment is inherited across fork(), systemd exposes it tree-wide as OOMScoreAdjust=; the human-readable view is /proc/<pid>/oom_score (0-1000).

Allocation policy gates everything: vm.overcommit_memory=0 (heuristic overcommit, default), 1 (malloc() nearly always succeeds, then SIGKILL arrives later), or 2 (strict: Committed_AS may not exceed CommitLimit = swap + RAM x vm.overcommit_ratio%/100, otherwise ENOMEM — the mode that converts OOM kills into polite malloc failures for databases and HPC). vm.panic_on_oom=1 trades the kill for a kernel panic; pair with kernel.panic=10 for auto-reboot, or with kdump’s crashkernel reservation for a full memory dump.

Three OOM sources overlap on a modern systemd host with different fingerprints: (1) global kernel OOM — Out of memory: Killed process ... in journalctl -k, gated by kernel.dmesg_restrict; (2) cgroup v2 OOM — Memory cgroup out of memory plus counters in /sys/fs/cgroup/.../memory.events, where memory.oom.group=1 (Docker default) widens one bad task’s kill to the whole container; (3) systemd-oomd — enabled by default on Ubuntu 24.04, it kills user slices on sustained PSI pressure (/proc/pressure/memory) long before the kernel is desperate, logging via journalctl -u systemd-oomd. Swap-less hosts hit the kernel OOM much earlier; the 6.8-era vm.swappiness ceiling of 200 also re-scales swap tuning.

A packaged kernel is a signed artifact chain: vmlinuz plus System.map and config, the module tree /lib/modules/<kernel-version>/, a generated initramfs (update-initramfs, dracut, mkinitcpio, mkinitfs) and boot entries (Debian-family regenerates grub.cfg via /etc/kernel/postinst.d/zz-update-grub; RHEL 9 maintains BLS drop-ins in /boot/loader/entries/ through kernel install hooks and grubby(8)). Retention policy is distro-specific: Ubuntu keeps the last two linux-image-* and offers apt-get autoremove; RHEL caps installed kernels with installonly_limit=3 in /etc/dnf/dnf.conf; Arch replaces vmlinuz-linux in place on package upgrade (install linux-lts first as the rescue kernel); Alpine regenerates the initramfs through mkinitfs apk triggers. DKMS modules are rebuilt by package hooks; Secure Boot requires signed kernels plus enrolled MOK keys for custom modules (mokutil --sb-state). Nothing switches until reboot: uname -r stays stale; Debian sets /var/run/reboot-required, RHEL’s needs-restarting -r exits 1. kexec -l followed by systemctl kexec and livepatch services (Ubuntu Pro livepatch, RHEL kpatch) are the only no-firmware-reboot upgrade paths.

Complete Reference Table / Diagnostic Matrix

The sysctls below account for the majority of production OOM, panic and post-upgrade incidents; apply via /etc/sysctl.d/ drop-ins, never by editing /proc/sys and hoping.

Item / Code / FlagBehaviorCommon Cause / Use Case
vm.overcommit_memory0 = heuristic overcommit (default); 1 = allocations always succeed; 2 = strict CommitLimit accountingRepeated OOM kills under JVM/Kafka: test mode 2 plus vm.overcommit_ratio on database hosts
vm.overcommit_ratioPercent of RAM counted toward CommitLimit in mode 2 (default 50)Raise to 80-100 for swapless DB hosts hitting spurious ENOMEM
vm.swappinessAnonymous vs page-cache reclaim bias; range 0-200 since kernel 6.8, default 60About 10 on database hosts (0 does not disable swap); 100+ favors zram desktops
vm.min_free_kbytesLow-water free-page reserve watermarkGFP_ATOMIC drops under network bursts on large-RAM hosts: raise toward a 256MB-class reserve
vm.max_map_countmmap/VMA cap per process (default 65530)Elasticsearch/Chromium print mmap failed: Cannot allocate memory despite free RAM
vm.panic_on_oom0 = invoke OOM killer; 1 = kernel panic on global OOM instead of killingHA pairs that fail over faster than they can degrade; pair with kernel.panic=10
kernel.panicSeconds before auto-reboot after a panic (0 = wait forever)Cloud fleets set 10-30 alongside panic_on_oom
/proc/<pid>/oom_score_adj-1000..1000 victim weight, inherited by fork; -1000 = exempt from OOM selectionProtect sshd/monitoring/systemd: OOMScoreAdjust= in unit drop-ins
vm.oom_kill_disable + memory.oom.groupBlock OOM allocations (v1) or widen one kill to the full cgroup (cgroup v2)Docker default memory.oom.group=1: one runaway task kills the entire container
kernel.dmesg_restrict1 = kernel ring buffer readable only with CAP_SYSLOGMulti-tenant hardening; OOM forensics then require sudo dmesg
kernel.kptr_restrict0/1/2 control of %pK pointer leaksBaseline 1 or 2 on exposed hosts (kernel addresses leak via logs/tracepoints)
kernel.sysrqMagic SysRq bitmask (438 is a common distro default)Emergency sync/kill/reboot via /proc/sysrq-trigger when the console still works
kernel.core_patternCoredump sink; systemd default pipes to systemd-coredumpPostmortem of dying services: coredumpctl list / coredumpctl info <pid>
kernel.numa_balancingAutomatic NUMA page migration (1 = enabled)Set 0 for latency-pinned services; leave 1 for batch throughput
vm.dirty_background_bytes / vm.dirty_bytesAbsolute writeback thresholds, overriding ratio-based defaultsNVMe bulk ingest stalls: replace dirty_ratio tuning to stop write storms pausing allocators
net.* subtreePer-netns keys (net.core.somaxconn, net.ipv4.ip_forward, …)Only namespaced keys pass docker/podman –sysctl; everything else lives on the host

Multi-Distro Implementation Differences

The sysctl layer is identical everywhere (procps-ng + systemd on the four systemd distros, OpenRC glue on Alpine); the kernel packaging, bootloader rewrite and retention policy are what differ.

Ubuntu / Debian

# sysctl: one drop-in per concern; systemd-sysctl applies at boot
sudo tee /etc/sysctl.d/99-memory.conf >/dev/null <<'EOF'
vm.swappiness=10
vm.vfs_cache_pressure=50
vm.max_map_count=262144
EOF
systemd-sysctl --cat-config | grep -A99 '99-memory'   # preview only, no writes
sudo sysctl -p /etc/sysctl.d/99-memory.conf           # apply now (runtime)

# kernel: Ubuntu 24.04 base is 6.8 (linux-generic); apt retains the last 2 images
sudo apt update
sudo apt full-upgrade
dpkg -l 'linux-image-*' | awk '/^ii/{print $2, $3}'
cat /var/run/reboot-required 2>/dev/null              # file present = reboot pending
sudo update-grub                                      # only if GRUB entries look wrong

RHEL / AlmaLinux / Rocky

# sysctl: identical mechanics (procps-ng + systemd-sysctl)
sudo sysctl -p /etc/sysctl.d/99-memory.conf

# kernel: RHEL 9 ships 5.14, RHEL 10 ships 6.12; dnf keeps installonly_limit (default 3)
sudo dnf update kernel
grep installonly_limit /etc/dnf/dnf.conf
grubby --default-kernel
grubby --info=ALL | grep -E '^(index|title)'
sudo grubby --set-default /boot/vmlinuz-<old-version>   # rollback boot default
rpm -q kernel
needs-restarting -r; echo rc=$?                          # rc=1 means reboot required

Arch Linux

# sysctl: same /etc/sysctl.d convention on systemd hosts
sudo sysctl -p /etc/sysctl.d/99-memory.conf

# kernel: pacman REPLACES /boot/vmlinuz-linux in place — fit a rescue kernel first
sudo pacman -S --needed linux-lts
sudo grub-mkconfig -o /boot/grub/grub.cfg
sudo pacman -Syu                                        # atomic full sync, never partial
ls -l /boot/vmlinuz-linux* /boot/initramfs-linux*.img   # img + fallback must exist
pacman -Q linux linux-lts

Alpine / Containers

# host: sysctl via the OpenRC sysctl service (/etc/sysctl.conf + /etc/sysctl.d/)
rc-update show | grep sysctl
rc-service sysctl start
apk info linux-lts

# kernel: linux-lts or linux-virt; mkinitfs hooks run inside apk transactions
apk upgrade linux-lts
ls /boot

# containers: kernel.* and vm.* are host-global; only namespaced keys pass --sysctl
docker run --rm --sysctl net.ipv4.ip_unprivileged_port_start=80 alpine 
  sysctl net.ipv4.ip_unprivileged_port_start

Common Failure Modes & Troubleshooting Recipes

All recipes assume elevated privileges and were verified on systemd hosts running kernels 6.8/6.12. Distinguishing the OOM source first saves the most time.

1. Exit 137 — locate the OOM victim and its cgroup

sudo dmesg -T | grep -Ei 'oom-killer|out of memory|killed process'
journalctl -k -b -g 'out of memory' -o short-precise
sudo dmesg -T | sed -n '/invoked oom-killer/,$p' | head -n 80   # full badness dump
systemctl status <unit> --no-pager                              # OOMKilled metadata on units
cat /sys/fs/cgroup/system.slice/<unit>.service/memory.events    # oom / oom_kill counters
systemd-cgtop -m --depth=2                                      # live memory leaders

Mitigate by steering, not by disabling the killer: protect the tier that must survive and cap the leak so the kernel punishes only it.

sudo systemctl edit <unit>                          # add: OOMScoreAdjust=-800
sudo systemctl set-property <unit>.service MemoryMax=4G
cat /proc/<pid>/oom_score /proc/<pid>/oom_score_adj

2. Jobs die with an empty dmesg — it is systemd-oomd, not the kernel

systemctl is-active systemd-oomd             # Ubuntu 24.04: enabled by default
journalctl -u systemd-oomd -b --no-pager     # Killed ... due to memory pressure
oomctl | head -n 30                          # monitored cgroups and current PSI
sudoedit /etc/systemd/oomd.conf              # DefaultMemoryPressureLimit / DurationSec

Do not blanket-disable the service; narrow the monitored pressure so that bursty PSI samples do not sacrifice critical slices.

3. sysctl change lost at reboot or boot-log ‘cannot stat’ spam

systemd-sysctl --cat-config | grep -B2 'vm.swappiness'    # who sets it, in merge order
sudo grep -Rsw 'vm.swappiness' /etc/sysctl.d /run/sysctl.d /usr/lib/sysctl.d /etc/sysctl.conf
journalctl -b -u systemd-sysctl --no-pager                # per-key boot failures
grep -q br_netfilter /proc/modules || sudo modprobe br_netfilter

Keep every key exactly once, in a 99- file; edit stragglers out of 50-/60- files with sudoedit instead of shadowing. Module-dependent keys like net.bridge.* exist only while the module is loaded — prune stale lines or guard them with a modprobe.

4. mmap() ENOMEM with gigabytes free

grep -E 'CommitLimit|Committed_AS' /proc/meminfo
sysctl vm.overcommit_memory vm.max_map_count
ls /proc/<pid>/maps | wc -l                    # VMA count vs vm.max_map_count
sudo sysctl -w vm.max_map_count=262144          # then persist in /etc/sysctl.d/

Under overcommit_memory=2, ENOMEM is by design: raise vm.overcommit_ratio or consciously revert to mode 0/1. VMA exhaustion is the classic Elasticsearch/Chromium failure shape with plenty of free RAM.

5. Unbootable after a kernel upgrade — two-minute recovery

# GRUB menu -> 'Advanced options' -> boot previous vmlinuz (or linux-lts)
uname -r
ls -l /boot/vmlinuz-* /boot/initramfs-*.img 2>/dev/null || ls -l /boot
sudo update-initramfs -u -k all                # Debian/Ubuntu; then: sudo update-grub
sudo dracut --regenerate-all --force           # RHEL/Alma; then: grubby --set-default-index=0
sudo mkinitcpio -P                             # Arch; then: grub-mkconfig -o /boot/grub/grub.cfg

If nothing boots, recover from a live USB against <root-dev>:

mount /dev/<root-dev> /mnt
mount --bind /dev /mnt/dev; mount --bind /proc /mnt/proc; mount --bind /sys /mnt/sys
chroot /mnt sh -c 'update-initramfs -u -k all; update-grub'

6. Fleet hygiene — running kernel vs installed kernels and /boot space

uname -r
rpm -q kernel | tail -n 2                             # RHEL/Alma
dpkg -l 'linux-image-*' | awk '/^ii/{print $2, $3}'   # Debian/Ubuntu
needs-restarting -r; echo rc=$?                       # RHEL: 0 ok / 1 reboot required
test -f /var/run/reboot-required && cat /var/run/reboot-required   # Debian/Ubuntu
df -h /boot /boot/efi                                 # a full /boot breaks every future update
sudo apt-get -s autoremove                            # simulate first, then run for real

A /boot partition filling up is the single most common silent cause of failed kernel installs: the package scripts fail writing the initramfs, leaving a vmlinuz without an initramfs match.

Production Hardening & Safety Checklist

  • Upgrade cycle order is fixed: backup, upgrade, reboot, verify, then prune old kernels — never apt-get autoremove before one successful boot of the new kernel.
  • Verify the bootable inventory after every upgrade: ls /boot must show vmlinuz and matching initramfs pairs, plus free space via df -h /boot.
  • Preview sysctl state, not just intent: systemd-sysctl --cat-config, then apply with sysctl --system; keep /etc/sysctl.d under version control.
  • Camp OOMScoreAdjust between -500 and -900 for critical units — never -1000; if every candidate is exempt, the allocator can livelock and the host panics.
  • Guard panic-based fleets with kdump: kdumpctl status (RHEL) or kdump-config show (Ubuntu, linux-crashdump) before enabling vm.panic_on_oom.
  • Keep Secure Boot coherent: distro-signed kernels only; enroll DKMS MOKs and confirm with mokutil --sb-state.
  • Rehearse rollback at least once per fleet: the GRUB previous-kernel path, one-shot grub-reboot/grub2-reboot, and grubby --set-default-index.

Safety Check: Before touching anything under /boot: back up with tar -C / -czf /root/boot-sysctl-$(date +%F).tgz boot etc/sysctl.d, confirm an older kernel entry exists (ls /boot/loader/entries/ or grep menuentry /boot/grub/grub.cfg), and simulate destructive cleanup (apt-get -s autoremove, dnf update --assumeno). Dry-run sysctls with systemd-sysctl --cat-config — never blind-apply a foreign config file. After reboot, verify uname -r matches the newest /boot/vmlinuz-* and scan the fresh boot with journalctl -b -p err --no-pager | head -n 20. Rollback: reboot into the previous GRUB entry, or one-shot grub-reboot 'Advanced options for Ubuntu>Ubuntu, with Linux <old-version>' on Debian-family hosts and grubby --set-default-index=0 on RHEL; undo sysctl changes by restoring the drop-in and rerunning sysctl --system.

Frequently Asked Edge Cases

Can I get the full command line of an OOM-killed process?

The kernel dump prints only comm and memory stats; the full argv is recoverable by PID with `journalctl _PID=` because systemd journals every unit spawn with its command line.

Is vm.swappiness=0 the way to disable swapping?

No — since kernel 3.5 it only throttles anonymous reclaim, and since 6.8 the valid range is 0-200; use ~10 for databases and 100-180 on zram-heavy desktops, or remove the swap device entirely.

Do sysctl settings survive a kernel upgrade?

The drop-in files persist, but a new kernel can drop module-dependent keys (e.g. net.bridge.*) or rename others: `journalctl -u systemd-sysctl` shows per-key warnings without failing the boot — prune unknown keys after major upgrades.

References & Upstream Docs

  1. Linux man-pages: sysctl(8), systemd-sysctl(8), proc(5) — /proc/sys/vm and oom_score_adj
  2. Kernel admin guide: Documentation/admin-guide/mm/oom.rst; Documentation/admin-guide/sysctl/{vm,kernel}.rst
  3. systemd docs: systemd-oomd(8), oomd.conf(5), systemd.exec(5) (OOMScoreAdjust=, OOMPolicy=)
  4. Distro toolchain: dnf.conf(5) installonly_limit, update-initramfs(8), dracut(8), mkinitcpio(8), mkinitfs(1), grubby(8)

Related Concepts