Linux – How does the Linux kernel schedule CPU, between user space processes/threads and kernel tasks/jobs

cpulinux-kernelprocessscheduling

I was trying to understand the Linux process management and scheduling. I know that the scheduler schedules different processes based on priority/time slicing. But there are kernel tasks (I am not mentioning the process' system calls which takes the process to kernel mode) which have to be processed as well (eg: scheduler/timers or some kernel code which runs forever). I did not understand if the scheduler schedules CPU for different processes how the kernel tasks are serviced in between.

Best Answer

Kernel tasks which aren’t run “in process” (to service a system call, or an interrupt) are handled as separate processes themselves, and you can see them in ps’s output:

root         2  0.0  0.0      0     0 ?        S    Sep16   0:02 [kthreadd]
root         3  0.0  0.0      0     0 ?        I<   Sep16   0:00 [rcu_gp]
root         4  0.0  0.0      0     0 ?        I<   Sep16   0:00 [rcu_par_gp]
root         6  0.0  0.0      0     0 ?        I<   Sep16   0:00 [kworker/0:0H-kblockd]
root         8  0.0  0.0      0     0 ?        I<   Sep16   0:00 [mm_percpu_wq]
root         9  0.0  0.0      0     0 ?        S    Sep16   9:11 [ksoftirqd/0]
root        10  0.2  0.0      0     0 ?        I    Sep16 173:25 [rcu_sched]
root        11  0.0  0.0      0     0 ?        I    Sep16   0:00 [rcu_bh]
root        12  0.0  0.0      0     0 ?        S    Sep16   0:20 [migration/0]
root        14  0.0  0.0      0     0 ?        S    Sep16   0:00 [cpuhp/0]
root        15  0.0  0.0      0     0 ?        S    Sep16   0:00 [cpuhp/1]

These processes are scheduled in the same way as processes you’re more familiar with.

A common pattern for such tasks is workqueues; the kernel documentation for those is quite good, I encourage you to read it if you’re interested in the topic.