Pinning Android threads with raw syscalls

How CoreTaskOptimizer finds Android's critical threads at boot and moves them onto the right CPU cores with sched_setaffinity, SCHED_FIFO and ioprio_set, and the five things I would change now.

On this page
  1. Why a binary instead of a script
  2. Three groups of threads
  3. Finding every thread
  4. The four syscalls
  5. Telling big cores from little cores
  6. What I would change now

Why a binary instead of a script

Most Android tuning modules are shell scripts. They loop over pgrep, call renice, and write to files under /proc. That works, but each call spawns a process, it depends on which toybox or busybox applets the ROM ships, and renice changes the priority of a process, not of the threads inside it.

CoreTaskOptimizer is a small C++17 binary that does the same job with direct syscalls. A Magisk service.sh waits for boot to finish, sleeps 30 seconds so the system settles, runs the binary once and exits. Nothing stays resident.

until [ "$(getprop sys.boot_completed)" -eq 1 ]; do
  sleep 1
done
sleep 30
"$MODDIR/bin/task_optimizer"

Three groups of threads

The policy is a static table of process names in three groups:

Group Processes What it gets
High priority system_server, surfaceflinger, zygote, composer, kblockd, writeback nice −10 on the performance cores
Real-time kgsl_worker_thread, crtc_commit, crtc_event, pp_event, touch-panel workers SCHED_FIFO priority 50 on the performance cores
Background f2fs_gc, wlan_logging_th nice +5 on the efficiency cores, idle I/O class

The reasoning is the usual one for interactive systems. The threads that draw frames (surfaceflinger, the composer, the Adreno GPU's kgsl_worker_thread, the display commit threads) and the threads that read the touch panel should never wait behind garbage collection on the filesystem or Wi-Fi logging.

Finding every thread

A process name only gets you the thread group leader. The interesting work in surfaceflinger happens on its other threads, so the binary walks /proc/<pid>/task and applies the policy to each thread ID:

for (pid_t pid : ProcessUtils::getProcessIDs(pattern)) {
  for (pid_t tid : ProcessUtils::getThreadIDs(pid)) {
    if (optimizer(tid)) stats.recordSuccess();
    else stats.recordFailure();
  }
}

Linux scheduling calls accept a thread ID wherever they say "pid", which is what makes this work. sched_setaffinity(tid, …) moves one thread, not the whole process.

The four syscalls

Each operation is a thin wrapper with up to three retries 50 ms apart, because threads appear and disappear during the first minute after boot.

sched_setaffinity(tid, sizeof(cpu_set_t), &mask);   // which cores
setpriority(PRIO_PROCESS, tid, -10);                 // CFS nice value
struct sched_param param;
param.sched_priority = 50;
sched_setscheduler(tid, SCHED_FIFO, &param);         // real-time class
syscall(SYS_ioprio_set, IOPRIO_WHO_PROCESS, tid, 3 << 13);  // idle I/O

ioprio_set has no libc wrapper on Bionic, hence the raw syscall. The value packs the I/O class into the top bits: class 3 shifted left by 13 is IOPRIO_CLASS_IDLE, so f2fs_gc only gets disk time when nothing else wants it.

Telling big cores from little cores

Modern phones mix core types, and the numbering differs between SoCs. Instead of hard-coding "cores 4 to 7 are fast", the binary reads each core's maximum frequency from sysfs and treats anything above 2 GHz as a performance core:

std::ifstream freq("/sys/devices/system/cpu/cpu" + std::to_string(i)
                   + "/cpufreq/cpuinfo_max_freq");
freq >> maxFreq;
if (maxFreq > 2000000) info.perfCores.push_back(i);
else info.effCores.push_back(i);

At the end it logs a summary to the module directory, rotating the file at 1 MB:

Operations: 84 | Success: 81 | Failed: 3

What I would change now

Reading the code again two years later, these are the things I would fix first.

1. The frequency threshold is a guess. On a mid-range SoC whose big cores top out at 2.0 GHz, every core lands in the efficiency group and the performance mask is empty. On a flagship where even the small cores pass 2 GHz, the efficiency mask is empty. sched_setaffinity rejects an empty mask with EINVAL, so the whole group silently fails. The kernel already publishes a better signal in /sys/devices/system/cpu/cpuN/cpu_capacity. Grouping cores by that value, or by the distinct cpufreq policies, would work on any layout.

2. The fallback never runs. Detection is wrapped in try/catch with a sensible default of cores 0–3 and 4–7. But std::ifstream doesn't throw unless you ask it to, so an unreadable file just ends the loop and the default is dead code. The loop also stops at the first core it can't read, which skips every core after an offline one.

3. The PID check is too strict. isValidPID rejects anything above 99,999. On 64-bit kernels pid_max can be raised to 4,194,304, and on such a device the binary would quietly skip valid threads. Checking that /proc/<tid> exists is enough.

4. SCHED_FIFO needs a guard rail. A FIFO thread at priority 50 runs until it blocks. If a vendor's touch worker ever spins, it can starve everything else on that core. The kernel's real-time throttling (sched_rt_runtime_us) limits the damage, but SCHED_RR or a high-priority SCHED_OTHER with uclamp would be a safer default for threads I don't control.

5. One-shot is also a weakness. Running once means zero overhead, but surfaceflinger restarts after a crash and gets a new PID with default settings. A small inotify or netlink watch on process creation would keep the policy applied without returning to a polling loop.

None of these show up on the phones I tested, which is why they are worth writing down. The project's job is to apply a narrow policy safely on hardware I don't own, and every silent failure above is one a user can't see.