Cut Idle RAM on Fedora Linux: A Complete Service Controller, ZRAM Tuning & x86-64-v4 Compilation Guide

2026-11-24来源 dev.toEnglish
Cut Idle RAM on Fedora Linux: A Complete Service Controller, ZRAM Tuning & x86-64-v4 Compilation Guide

Fedora Workstation is one of the best-engineered Linux desktops out there, but out of the box it ships like a Swiss Army knife built for every enterprise and consumer hardware scenario imaginable.

Even if you are running a modern single-NVMe laptop with no printer, no smartcard reader, no cellular modem, and no RAID array, Fedora quietly runs over a dozen background daemons, D-Bus watchers, and metadata pollers. Together, services like PackageKit, gnome-software, localsearch-3, abrt, colord, and cups routinely consume 600 MB to 1.2+ GB of idle RAM and trigger constant CPU wakeups that drain battery life.

A high-contrast digital illustration of a sleek modern laptop on a dark, tech-infused background of server racks and circuit boards, featuring the glowing blue Fedora Linux logo on the top right.

Instead of running scattered systemctl commands that you will forget next week—or risking breaking system dependencies—I built a single, reversible Python CLI (service_control.py) to manage hardware services, reclaim RAM on demand, and toggle between Maximum Performance and Ultra-Battery modes without rebooting.

In this guide, we will cover:

  1. Which Fedora background services are safe to cut (and how much RAM they save).
  2. Kernel & ZRAM memory tuning to squeeze more multitasking headroom out of 8 GB and 16 GB laptops.
  3. How the controller works (mask vs. disable and state snapshots) + the complete drop-in source code.
  4. How to download source code and recompile apps with x86-64-v4 (AVX-512) on Fedora—including the real-world pros and cons.

1. What Gets Cut & How Much RAM You Reclaim

By default, systemd uses socket activation and D-Bus activation. Even if you run systemctl disable, another process can silently wake a daemon back up in the background. Using systemctl mask symlinks the unit to /dev/null, guaranteeing 0 MB RAM and 0% CPU until you explicitly unmask it.

Here are the safe, high-impact targets managed by the controller:

Target Key Systemd Unit(s) Scope What It Does & Why You Probably Don't Need It Typical RAM Saved
packagekit packagekit.service System Background DNF metadata daemon used by GNOME Software; locks DNF and eats huge RAM. 150 – 400 MB
indexer localsearch-3.service User Tracker/LocalSearch file content indexer; spikes CPU/disk I/O when downloading files. 80 – 250 MB
abrt abrtd, abrt-oops, abrt-xorg System Fedora's Automatic Bug Reporting Tool; constantly watches system journals for crashes. 40 – 90 MB
cups cups.service, .socket, .path System Local printing server; unnecessary if you rarely or never print. 25 – 60 MB
bluetooth bluetooth.service System Bluetooth stack and radio controller; keep masked when using wired peripherals. 15 – 30 MB
modem-manager ModemManager.service System Mobile broadband / cellular SIM hardware manager. 25 – 45 MB
color-profile colord.service System Display colorimeter & printer ICC profile daemon. 15 – 30 MB
avahi avahi-daemon.service, .socket System ZeroConf/mDNS local .local network discovery; reduces network wakeups on public Wi-Fi. 10 – 20 MB
geoclue geoclue.service System System-wide geolocation tracking service. 15 – 25 MB
usb-media gvfs-gphoto2, gvfs-afc, gvfs-mtp User Auto-mount watchers for digital cameras, iPhones, and MTP devices. 20 – 40 MB
smartcard gsd-smartcard.service User Corporate CAC / physical smartcard insertion watcher. 10 – 15 MB
wwan gsd-wwan.service User GNOME cellular WWAN settings daemon. 10 – 15 MB
stratis stratisd.service System Enterprise Stratis storage pool daemon (unused on Fedora's default Btrfs). 15 – 25 MB
dnf-poller dnf-makecache.timer / .service System Wakes up every few hours to download repository metadata in the background. Bandwidth + Wakeups
raid-check raid-check.timer / .service System Weekly software RAID array scrub (pointless on single-NVMe laptops). Disk I/O

Note: On top of these systemd units, killing the background gnome-software --gapplication-service resident process (handled automatically by the script's trim-ram command) immediately frees another 250 – 500 MB of RAM.

2. Beyond Services: Kernel, ZRAM & Power Optimizations

Cutting daemons is only half the story. Fedora uses ZRAM (a compressed block device in RAM) instead of a traditional disk swap partition. Many Linux users mistakenly apply old hard-drive swap tweaks (vm.swappiness=10), which actually hurts performance on ZRAM systems.

The upgraded controller includes a trim-ram command that applies three major memory and power optimizations:

  1. ZRAM-Optimal Kernel VM Tuning:
    • vm.swappiness=150: Encourages the kernel to compress cold, inactive anonymous pages into ZRAM early, leaving fast uncompressed RAM free for active applications and compilers.
    • vm.page-cluster=0: Disables swap read-ahead (which is designed for spinning HDDs, not zero-latency RAM).
    • vm.vfs_cache_pressure=50: Keeps filesystem directory/inode caches slightly longer so file searches stay snappy without ballooning memory.
  2. On-Demand PageCache & Bloat Purge (trim-ram):
    • Flushes dirty disk buffers (sync), drops clean kernel PageCache/dentries/inodes (/proc/sys/vm/drop_caches), and terminates resident gnome-software background processes before you launch a heavy workload.
  3. Instant Hardware Uncapping (uncap vs. cap):
    • Uses Fedora's native TuneD daemon (throughput-performance vs. powersave) alongside PCIe Active State Power Management (ASPM) (default vs. powersupersave) so your NVMe SSD and Wi-Fi card enter deep L1 sleep on battery, or run at zero bus latency when plugged in.

3. Architecture & Workflow Before You Copy the Code

Before dropping the script into your home directory, here is how it is structured so you never lock yourself out of hardware you actually need:

  • Zero Third-Party Dependencies: Uses only Python's standard library (sys, os, json, subprocess) and built-in Fedora tools (systemctl, tuned-adm, nmcli, upower, sysctl).
  • Smart State Snapshots (~/.service_control_state.json): When you run mask-all, the script records which services were originally active/enabled on your machine. Running unmask-all restores your exact prior state rather than blindly enabling daemons you never used.
  • Granular On-Demand Toggles: Need to pair Bluetooth headphones or print a document? Run enable bluetooth or enable cups, do your work, and run disable bluetooth when finished.

Daily Usage Examples

# 1. Mask all redundant background daemons & timers python3 ~/service_control.py mask-all # 2. Check live service states and active TuneD profile python3 ~/service_control.py status # 3. Reclaim cached RAM, kill gnome-software bloat, and tune ZRAM VM params python3 ~/service_control.py trim-ram # 4. Inspect detailed RAM, ZRAM compression ratio, and top memory hogs python3 ~/service_control.py ram # 5. Uncap CPU Turbo Boost & disable PCIe sleep for compiling/gaming python3 ~/service_control.py uncap # 6. Switch back to Ultra-Battery mode & check live discharge wattage python3 ~/service_control.py cap python3 ~/service_control.py power # 7. Temporarily re-enable Bluetooth when needed python3 ~/service_control.py enable bluetooth 

4. Complete Source Code: service_control.py

Save this file as ~/service_control.py and make it executable (chmod +x ~/service_control.py).

#!/usr/bin/env python3 """ service_control.py - Master hardware, RAM, service, performance & battery CLI for Fedora Linux. Includes: - Instant Uncap (Maximum Performance mode) vs. Cap (Ultra-Battery mode) - Hardware & service masking/unmasking with automatic state snapshots - Kernel ZRAM tuning, PageCache purging, and resident bloat cleanup (trim-ram) - Live RAM/ZRAM telemetry & battery wattage inspection - Emergency Wi-Fi & NetworkManager reset """ import sys import os import json import subprocess STATE_FILE = os.path.expanduser("~/.service_control_state.json") # Service & Timer definitions: SERVICES = { "packagekit": { "name": "PackageKit Daemon", "description": "Background DNF metadata service for GNOME Software (major RAM hog)", "scope": "system", "units": ["packagekit.service"] }, "abrt": { "name": "ABRT Crash Reporter", "description": "Automatic Bug Reporting Tool daemons watching system journals", "scope": "system", "units": ["abrtd.service", "abrt-oops.service", "abrt-xorg.service"] }, "cups": { "name": "CUPS Print Server", "description": "Background printing spooler & socket listener", "scope": "system", "units": ["cups.service", "cups.socket", "cups.path"] }, "printing": { "name": "Printer Notifications", "description": "GNOME background printer discovery & queue notification daemon", "scope": "user", "units": ["org.gnome.SettingsDaemon.PrintNotifications.service"] }, "bluetooth": { "name": "Bluetooth Service", "description": "Bluetooth daemon & radio adapter controller", "scope": "system", "units": ["bluetooth.service"] }, "modem-manager": { "name": "ModemManager", "description": "Mobile broadband & cellular modem hardware manager", "scope": "system", "units": ["ModemManager.service"] }, "color-profile": { "name": "Color Management", "description": "Display colorimeter & printer ICC profile daemon (colord)", "scope": "system", "units": ["colord.service"] }, "avahi": { "name": "Avahi mDNS/Zeroconf", "description": "Local .local network discovery daemon (saves RAM & network wakeups)", "scope": "system", "units": ["avahi-daemon.service", "avahi-daemon.socket"] }, "geoclue": { "name": "Geoclue Location", "description": "System-wide geolocation tracking daemon", "scope": "system", "units": ["geoclue.service"] }, "smartcard": { "name": "Smartcard Reader", "description": "Physical corporate CAC/smartcard insertion watcher", "scope": "user", "units": ["org.gnome.SettingsDaemon.Smartcard.service"] }, "wwan": { "name": "Cellular WWAN", "description": "GNOME mobile broadband / cellular SIM daemon", "scope": "user", "units": ["org.gnome.SettingsDaemon.Wwan.service"] }, "stratis": { "name": "Stratis Storage", "description": "Stratis enterprise storage daemon (unneeded for standard Btrfs)", "scope": "system", "units": ["stratisd.service"] }, "usb-media": { "name": "USB Device Auto-Monitors", "description": "GVFS daemons for cameras (PTP/GPhoto), iPhones (AFC), and MTP", "scope": "user", "units": [ "gvfs-gphoto2-volume-monitor.service", "gvfs-afc-volume-monitor.service", "gvfs-mtp-volume-monitor.service" ] }, "indexer": { "name": "LocalSearch File Indexer", "description": "Background file indexing daemon for GNOME search (Tracker/LocalSearch)", "scope": "user", "units": ["localsearch-3.service"] }, "dnf-poller": { "name": "DNF Auto-Cache Timer", "description": "Background network poller refreshing package lists every few hours", "scope": "system", "units": ["dnf-makecache.timer", "dnf-makecache.service"] }, "raid-check": { "name": "RAID Integrity Checker", "description": "Checks software RAID arrays (useless on single NVMe laptops)", "scope": "system", "units": ["raid-check.timer", "raid-check.service"] } } def run_cmd(cmd_list): """Executes a command quickly and returns (returncode, stdout, stderr).""" try: res = subprocess.run(cmd_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) return res.returncode, res.stdout.strip(), res.stderr.strip() except Exception as e: return 1, "", str(e) def get_unit_status(unit, scope): base_cmd = ["systemctl"] if scope == "user": base_cmd.append("--user") _, out, _ = run_cmd(base_cmd + ["is-active", unit]) active = out if out else "unknown" _, out_en, _ = run_cmd(base_cmd + ["is-enabled", unit]) enabled = out_en if out_en else "unknown" return active, enabled def save_snapshot(): """Saves pre-masking service states so unmask-all can restore accurately.""" if os.path.exists(STATE_FILE): return snapshot = {} for key, info in SERVICES.items(): snapshot[key] = {} for u in info["units"]: act, en = get_unit_status(u, info["scope"]) snapshot[key][u] = {"active": act, "enabled": en} try: with open(STATE_FILE, "w", encoding="utf-8") as f: json.dump(snapshot, f, indent=2) except OSError: pass def load_snapshot(): if not os.path.exists(STATE_FILE): return None try: with open(STATE_FILE, "r", encoding="utf-8") as f: return json.load(f) except OSError: return None def print_help(): print(""" ==================================================================================== ⚡ service_control.py - Master Fedora Hardware, RAM & Performance Controller ==================================================================================== USAGE: python3 ~/service_control.py [COMMAND] [TARGET] 🚀 PERFORMANCE & RAM MODES (NO RESTART NEEDED): uncap Unleash MAXIMUM PERFORMANCE (Turbo active, PCIe bus active) cap Switch back to ULTRA-BATTERY mode (Powersave, PCIe L1 sleep) trim-ram Drop clean PageCache, kill GNOME Software bloat & tune ZRAM fix-wifi Emergency 1-click Wi-Fi reset (restarts NetworkManager & radio) 📊 SYSTEM INSPECTION: status Show live status of all managed services & timers ram Show RAM, ZRAM compression stats, VM params & top memory hogs power Show current battery discharge rate (Watts) and runtime estimate help Display this help guide ⚙️ SERVICE & TIMER CONTROL: mask-all Mask ALL redundant services & timers (Max RAM & battery savings) unmask-all Restore and unmask services back to pre-masking state disable <target> Stop and mask a specific service or timer enable <target> Unmask and start a specific service or timer AVAILABLE TARGETS: packagekit Background DNF/PackageKit daemon (saves 150-400 MB RAM) abrt Automatic Bug Reporting Tool crash daemons cups CUPS background print spooler & socket printing GNOME printer notification daemon bluetooth Bluetooth daemon & radio adapter controller modem-manager Cellular/mobile broadband ModemManager daemon color-profile Color calibration daemon (colord) avahi Avahi mDNS/Zeroconf local network discovery geoclue System geolocation service smartcard Corporate smartcard reader watcher wwan GNOME cellular WWAN daemon stratis Stratis enterprise storage daemon usb-media USB camera (PTP), iPhone (AFC), and MTP media sync daemons indexer LocalSearch GNOME background file indexer dnf-poller DNF background update cache poller raid-check Software RAID array integrity checker EXAMPLES: python3 ~/service_control.py mask-all # Cut all redundant Fedora bloat python3 ~/service_control.py trim-ram # Reclaim RAM & optimize ZRAM VM python3 ~/service_control.py uncap # Max CPU/PCIe speed for compiling python3 ~/service_control.py cap # Back to Ultra-Battery mode python3 ~/service_control.py enable bluetooth # Turn on Bluetooth when needed ==================================================================================== """) def cmd_uncap(): print("\n🚀 Switching to MAXIMUM PERFORMANCE MODE (Uncapping)...") subprocess.run(["sudo", "-v"], check=True) run_cmd(["sudo", "tuned-adm", "profile", "throughput-performance"]) aspm_path = "/sys/module/pcie_aspm/parameters/policy" if os.path.exists(aspm_path): subprocess.run(f"echo default | sudo tee {aspm_path} > /dev/null 2>&1", shell=True) print("✓ TuneD Profile: throughput-performance (Max Turbo Boost & low scheduler latency)") print("✓ PCIe ASPM: default (Zero bus sleep latency for NVMe & GPU)") print("✓ Status: UNCAPPED. System is running at MAXIMUM raw speed.\n") def cmd_cap(): print("\n🔋 Switching to ULTRA-BATTERY MODE (Capping)...") subprocess.run(["sudo", "-v"], check=True) run_cmd(["sudo", "tuned-adm", "profile", "powersave"]) aspm_path = "/sys/module/pcie_aspm/parameters/policy" if os.path.exists(aspm_path): subprocess.run(f"echo powersupersave | sudo tee {aspm_path} > /dev/null 2>&1", shell=True) print("✓ TuneD Profile: powersave (Aggressive frequency downclocking at idle)") print("✓ PCIe ASPM: powersupersave (NVMe & Wi-Fi enter L1 deep sleep)") print("✓ Status: CAPPED. Maximum battery life active.\n") def cmd_trim_ram(): print("\n🧹 Running Deep RAM Reclamation & Fedora ZRAM Optimization...") subprocess.run(["sudo", "-v"], check=True) # 1. Flush dirty buffers and drop clean PageCache, dentries, and inodes run_cmd(["sync"]) subprocess.run("echo 3 | sudo tee /proc/sys/vm/drop_caches > /dev/null", shell=True) print("✓ Dropped clean Linux PageCache, dentries, and inodes.") # 2. Terminate resident gnome-software background service if running code, _, _ = run_cmd(["pkill", "-f", "gnome-software"]) if code == 0: print("✓ Terminated resident gnome-software background process (~250-500 MB freed).") else: print("✓ gnome-software background process not running.") # 3. Apply Fedora ZRAM-optimized kernel virtual memory parameters vm_tweaks = { "vm.swappiness": "150", "vm.vfs_cache_pressure": "50", "vm.page-cluster": "0" } for param, val in vm_tweaks.items(): run_cmd(["sudo", "sysctl", "-w", f"{param}={val}"]) print("✓ Tuned ZRAM VM parameters (swappiness=150, page-cluster=0, vfs_cache_pressure=50).\n") def cmd_ram(): print("\n🧠 Live Fedora Memory & ZRAM Telemetry:") print("-" * 70) _, free_out, _ = run_cmd(["free", "-h"]) print(free_out) print("\n📦 ZRAM Swap Device:") code, zram_out, _ = run_cmd(["zramctl"]) print(zram_out if (code == 0 and zram_out) else "No active ZRAM device found.") print("\n⚙️ Kernel VM Parameters:") for param in ["vm.swappiness", "vm.vfs_cache_pressure", "vm.page-cluster"]: _, val, _ = run_cmd(["sysctl", "-n", param]) print(f" {param} = {val}") print("\n🔥 Top 5 RAM-Consuming Processes:") _, ps_out, _ = run_cmd(["ps", "-eo", "pid,rss,comm", "--sort=-rss"]) for line in ps_out.splitlines()[:6]: parts = line.split(None, 2) if len(parts) == 3 and parts[1].isdigit(): mb = int(parts[1]) / 1024 print(f" PID {parts[0]:<7} {mb:>7.1f} MB {parts[2]}") else: print(f" {line}") print("-" * 70 + "\n") def cmd_fix_wifi(): print("\n📶 Running Emergency Wi-Fi & Network Reset...") subprocess.run(["sudo", "-v"], check=True) run_cmd(["nmcli", "radio", "wifi", "off"]) run_cmd(["sudo", "systemctl", "restart", "NetworkManager.service"]) run_cmd(...

原文:https://www.a8q9.cn/en/article/cut-idle-ram-on-fedora-linux-a-complete-service-controller-zram-tuning-x86-64-v4-e16da0.html

相关文章