The CPU Scheduler – Part 1
local graph
Chapter 10 — The CPU Scheduler – Part 1
Section titled “Chapter 10 — The CPU Scheduler – Part 1”The previous two chapters delved pretty deep into aspects of Linux memory management, with a focus on how exactly you, as a kernel/driver developer, can efficiently dynamically allocate and deallocate kernel memory (besides the APIs, we covered interesting stuff like MGLRU, DAMON, and the OOM killer!).
In this chapter and the next, you will dive into the details regarding a key OS topic – that is, CPU (or task) scheduling on the Linux OS. I will try and keep the learning both conceptual and hands-on, by asking (and answering) typical questions and performing common tasks related to scheduling. Understanding how CPU scheduling works at the level of the OS is not only important from a kernel (and driver) developer viewpoint, it will also automatically make you a better system architect, even for user space applications.
We shall begin by covering essential background material; this will include the notion of the Kernel Schedulable Entity (KSE) on Linux, as well as the POSIX scheduling policies that Linux implements. We will then move on to using tools – perf and others – to visualize the flow of control as the OS runs tasks on CPUs and switches between them. This can prove very useful when you need to profile apps as well!
After that, we will dive deeper into the details of how exactly CPU scheduling works on Linux (within kernel space), covering modular scheduling classes, including Completely Fair Scheduling (CFS), the running of the core schedule function, the “who” and “when” of it, and so on. Along the way, we will also cover how you can programmatically and dynamically query the scheduling policy and priority of any thread on the system.
Something to point out at the onset: as you know, the CPUs on a system are a resource shared among the users, processes, and threads that execute upon them. The CPU (or task) scheduler is of course a way to arbitrate access to this precious resource. Still, CPUs are but one resource; memory, IO devices, networking, and more are also shared resources. The Linux kernel has an advanced, deeply ingrained framework for a more highly abstracted, practically important resource-sharing feature: cgroups (control groups)! (In fact, our very first diagram, Figure 10.1, alludes to it!). A detailed internal understanding of CPU scheduling must also include the key role that cgroups can play as well; worry not – we shall cover some key details on cgroups in the following chapter.
In this chapter, we will cover the following areas:
- Learning about the CPU scheduling internals – part 1 – essential background
- Visualizing the flow
- Learning about the CPU scheduling internals – part 2
- Querying a given thread’s scheduling policy and priority
- Learning about the CPU scheduling internals – part 3
Now, let’s get started with this interesting topic!
Technical requirements
Section titled “Technical requirements”I assume that you have gone through Online Chapter, Kernel Workspace Setup, and have appropriately prepared a guest Virtual Machine (VM) running Ubuntu 22.04 LTS (or a later stable release) and installed all the required packages. If not, I highly recommend you do this first.
To get the most out of this book, I strongly recommend you first set up the workspace environment, including cloning this book’s GitHub repository for the code and working on it in a hands-on fashion. The repository can be found here: https://github.com/PacktPublishing/Linux-Kernel-Programming_2E.
Learning about the CPU scheduling internals – part 1 – essential background
Section titled “Learning about the CPU scheduling internals – part 1 – essential background”Let’s take a quick look at the essential background information we require to understand CPU scheduling on Linux.
Note that, in this book, we do not intend to cover material that competent (user space) system programmers on Linux should already be well aware of; this includes basics such as process (or thread) states, basic information on what real time is, the POSIX scheduling policies, and so on. This (and more) has been covered in some detail in my earlier book, Hands-On System Programming with Linux, published by Packt in October 2018. Nevertheless, we do touch upon some of the basics here.
What is the KSE on Linux?
Section titled “What is the KSE on Linux?”As you learned in Chapter 6, Kernel Internals Essentials – Processes and Threads, in the Organizing processes, threads, and their stacks – user and kernel space section, every (user mode) thread alive on the system is bestowed with a task structure (struct task_struct) and both a user-mode and a kernel-mode stack. As we’ve learned, kernel threads do have a task structure but only a kernel-mode stack.
Every OS needs to perform task scheduling of course. Modern operating systems – Linux/Unix/Windows/Mac – have the notion of processes and threads. Now, the key question to ask is: when task scheduling is performed, what “object” does it act upon? In other words, what is the Kernel Schedulable Entity, the KSE? On Linux, the KSE is a thread, not a process (of course, every process contains a minimum of one thread). Thus, the thread is the granularity level at which scheduling is performed.
An example – along with a diagram (Figure 10.1) – will help explain this: if we have a hypothetical situation where we have just one CPU core and three user space processes alive (P1, P2, and P3), consisting of one, two and five threads each respectively, plus a few kernel threads (say, three of them), then we have a total of (1+2+5+3), which equals 11 threads.

Figure 10.1: A conceptual diagram showing the kernel layout of a few processes and their threads, stacks, and kthreads within the kernel (for now, ignore the “cgroups” abstraction at the very top; we will get to it in the following chapter)
Okay, I’m asking you to ignore the elephant in the room. The very top portion of Figure 10.1 shows an abstracted, highly conceptual view of the cgroups kernel framework, a framework that is now deeply embedded inside the very fabric of the kernel. Here, what I’m asking you to visualize – without worrying at all about the “why/how/who/when/…” questions – is that this cgroups layer, if you will, is pretty much ever-present in modern Linux, and it certainly can have an impact on CPU scheduling. For now, just be aware it exists; details – and trying it out! – are covered in the following chapter.
With respect to Figure 10.1, each thread – except for the kernel threads – has a user and kernel stack and a task structure (the kernel threads only have kernel stacks and task structures; all of this was thoroughly explained in Chapter 6, Kernel Internals Essentials – Processes and Threads, in the Organizing processes, threads, and their stacks – user and kernel space section). Now, if all these 11 threads are in a runnable state, that is, they’re ready-to-run, then they all compete for the single processor core. (Although it’s unlikely that they’re all runnable simultaneously, let’s just consider it for the sake of discussion). It’s key to understand that we now have 11 threads in competition for the CPU resource, not three processes and three kernel threads. A more realistic scenario is, of the 11 threads alive, perhaps four are runnable, i.e., they’re in the runqueue and they want to run, while the remaining seven threads are in various other states (sleeping (in a blocking call) or are stopped (frozen)); these remaining seven are not even candidates for the scheduler.
Now that we understand that the KSE is a thread, we will (almost) always refer to the thread in the context of scheduling. Let’s now move on to the so-called Linux process state machine.
The Linux process state machine
Section titled “The Linux process state machine”On the Linux OS, every process or thread runs through a variety of definite states, and by encoding these, we can form the state machine of a process (or thread) on the Linux OS (do refer to Figure 10.2 while reading this).
Since we now understand that the KSE on the Linux OS is a thread and not a process, we shall ignore convention, which uses the word “process,” and instead use the word “thread” when describing the entity that cycles through various states of the state machine. (If it’s more comfortable, you could always, in your mind, substitute the word ‘process’ in lieu of ‘thread’ in the following text.)
The states that a Linux thread can cycle through are as follows (the ps utility encodes the state via the letters shown here):
- R: Ready-to-run or Running (or “runnable”)
- Sleeping:
- S: Interruptible Sleep
- D: Uninterruptible Sleep
- S: Interruptible Sleep
- T: Stopped (or suspended/frozen)
- Z: Zombie (or defunct)
- X: Dead
When a thread is newly created either via the fork() or c lone() system calls, or the pthread_create() API, and once the OS determines that the thread is fully born, it informs the scheduler of its existence by putting the thread into a runnable (R) state. A thread in the R state is either actually running on a CPU core or is in the ready-to-run state. What we need to understand is that in both cases, the thread is enqueued on a data structure within the OS called a runqueue. Linux maintains one runqueue per CPU core on the system (actually, the reality is even more nuanced; we will get to that soon enough). The threads in the runqueue are the valid candidates to run on a given CPU core; no thread can possibly run unless it is enqueued on an OS runqueue. Linux does not explicitly distinguish between the ready-to-run and actually running state; it merely marks the thread in either state as R. Of course, as we learned in Chapter 6, Kernel Internals Essentials – Processes and Threads, it’s a member within the task structure (unsigned int __state;) that is set to an appropriate value to mark the thread being in a particular state.
The following diagram represents the Linux state machine for any process or thread:

Figure 10.2: The Linux process/thread state machine
The preceding diagram shows transitions between states via (red) arrows. Do note that for clarity, some transitions (for example, a thread can be killed while asleep or stopped) are not explicitly shown in the preceding diagram. (FYI, a process that dies but isn’t waited for by its parent ends up in a half-dead, half-alive state, termed a zombie or defunct process; it’s meant to be a transient state. The rule to be followed to prevent zombies remaining on the system forever, is that every fork() requires a corresponding wait*() system call. (Linux, as usual, has a neat trick: killing the parent of a zombie(s), has the zombie(s) ‘reaped’ (die) as well.)
We know that every thread alive (both user and kernel) has its own task structure. Thus, at the level of the code, the task structure member named __state (it was earlier named state) holds the “state” of the task – the thread – in the so-called “state machine.” When runnable, it will be set to the value TASK_RUNNING (represented by the “R” overall, and internally by the Rr and Rcpu states in Figure 10.2).
A wait queue is a data structure where tasks that are in a sleep state are enqueued – that is, they’re waiting for an event (in effect, they land up here within a blocking call). Linux has two possibilities for a sleeping thread; the thread can be in an:
- Interruptible sleep:
__state = TASK_INTERRUPTIBLE: it “sleeps,” waiting on a certain event; however, any signal delivered to the process/thread will awaken it and run the signal handler (represented by the letter ‘S’ in Figure 10.2) - Uninterruptible sleep:
__state = TASK_UNINTERRUPTIBLE: it “sleeps,” waiting on a certain event; any/all signal(s) delivered to the process/thread will have no effect on it (represented by the letter ‘D’ in Figure 10.2).
When the event it was waiting upon arises, the OS will issue it a wakeup call, causing it to become runnable (dequeued from its wait queue and enqueued in a runqueue) again. Note that the thread won’t run instantaneously; it will become runnable (Rr in Figure 10.2) and a candidate for the scheduler; soon enough, it will get a chance and actually run on the CPU (Rcpu).
A common misconception is to think that the OS maintains one run queue and one wait queue. The Linux kernel maintains one run queue per CPU. Wait queues are often created and used by device drivers (as well as the kernel); thus, there can be any number of them.
With these basics out of the way, let’s get going!
The POSIX scheduling policies
Section titled “The POSIX scheduling policies”Think of the term scheduling policy as being roughly equivalent to scheduling algorithm. It’s important to realize that the Linux kernel does not have just one policy that implements CPU scheduling; the fact is that the POSIX standard specifies a minimum of three scheduling policies (algorithms, in effect) that a POSIX-compliant OS must adhere to. Linux goes above and beyond, implementing these three as well as more, with a powerful design called scheduling classes (covered in the Understanding modular scheduling classes section later in this chapter).
For now, let’s just briefly summarize the POSIX scheduling policies and what effect they have in the following table; before that though, it’s key to understand that every thread alive (both user and kernel space) is associated with exactly one of these scheduling policies at any given point in time (it can be changed at runtime). Here’s the table:
| Scheduling policy | Key points | Priority scale |
|---|---|---|
SCHED_OTHER or SCHED_NORMAL | Always the default; threads with this policy are non-real-time; they are internally implemented as a Completely Fair Scheduling (CFS) class (seen in the upcoming The working of the Completely Fair Scheduling (CFS) class in brief section). The motivation behind this scheduling policy is fairness (as in, “be fair to all runnable threads, and avoid starving anyone of CPU time”) and overall throughput. | Threads with this policy have a real-time priority of 0. The non-real-time priority is called the nice value; it ranges from -20 to +19 (a lower number implies superior priority) with a base (initial) value of 0 |
SCHED_RR | The motivation behind this scheduling policy is to provide a (soft) real-time policy that’s moderately aggressive. Threads belonging to this sched class have a finite timeslice (typically defaulting to 100 ms). A SCHED_RR thread will yield the processor IFF (if and only if): - It blocks on I/O (goes to sleep). - It stops or dies. - A higher-priority real-time thread becomes runnable (which will preempt this one). - Its timeslice expires. | (Soft) real-time: 1 to 99 (a higher number implies superior priority) |
SCHED_FIFO | The motivation behind this scheduling policy is to provide a (soft) real-time policy that’s (by comparison to SCHED_RR, very) aggressive. A SCHED_FIFO thread will yield the processor IFF: - It blocks on I/O (goes to sleep). - It stops or dies. - A higher-priority real-time thread becomes runnable (which will preempt this one). It has, in effect, infinite timeslice. | (The same as SCHED_RR) |
SCHED_BATCH | The motivation behind this scheduling policy is one that’s suitable for low-priority non-interactive batch jobs, with less preemption. | Nice value range (-20 to +19) |
SCHED_IDLE | Special case: typically, the PID 0 kernel thread (traditionally called the swapper; in reality, it’s the per CPU idle thread) uses this policy. It’s always guaranteed to be the lowest-priority thread on the system and only runs when no other thread wants the CPU. | The lowest priority of all (think of it as being of even lower priority than nice value +19) |
Table 10.1: The Linux (POSIX-compliant) scheduling policies and their meaning in brief
It’s important to note that when we say real-time in the preceding table, we mean soft (or at best, firm) real-time and not hard real-time, as in a Real-Time Operating System (RTOS). Linux is a general-purpose OS (GPOS), not an RTOS. Having said that, you can convert vanilla Linux into a true hard real-time RTOS by applying an external patch series (called RTL, supported by the Linux Foundation); you’ll learn how to do precisely this in the following chapter, in the Converting mainline Linux into an RTOS section.
Study the table carefully; notice that a SCHED_FIFO thread has, in effect, infinite timeslice and can thus run on a CPU core for as long as it wishes to; it gets preempted (taken off the CPU) when one of the preceding mentioned conditions comes true. Also, other key differences between SCHED_FIFO and SCHED_RR include:
- While a
SCHED_FIFOthread effectively has infinite timeslice, aSCHED_RRthread has a finite timeslice (tunable via the/proc/sys/kernel/sched_rr_timeslice_mssysctl; 100 ms by default) SCHED_RRthreads at the same priority level are scheduled in a round robin fashion (thus allowing otherSCHED_RRthreads to get a share of the processor). WithSCHED_FIFOthreads, this isn’t the case – the one preempted will go back to being the next task to run (thus denying others at the same priority level the processor). Thus, when employingSCHED_FIFO, you should avoid keeping threads at the same priority level (we cover more on this in the following chapter, in the Setting the policy and priority within the kernel – on a kernel thread section).
At this point, it’s important to understand that on an OS such as Linux, the reality is that hardware (and software) interrupts are always superior to and will always preempt even (kernel or user space) SCHED_FIFO threads! (Do refer back to Figure 6.1 in Chapter 6, Kernel Internals Essentials – Processes and Threads, to see this. If you’d like to delve into the topic of hardware interrupts in detail, please see the (free!) Linux Kernel Programming, Part 2 book, Chapter 4, Handling Hardware Interrupts). For our discussion here, we will ignore interrupts for the time being. Now, let’s look into per-thread priority values in more detail.
Thread priorities
Section titled “Thread priorities”The priority scaling for threads is simple (the following is from lower to higher priority; refer to Figure 10.3):
- Non-real-time threads (
SCHED_OTHER) have a real-time priority of0; this ensures that they cannot even compete with real-time threads; they’re not even on the same playing field! Then, how would one distinguish, priority-wise, between all the non-real-time threads?
Easy – they use an (old UNIX-style) priority value called the nice value, which ranges from -20 to +19, with -20 being the highest priority, 0 the base or default, and +19 the lowest. (Appropriate interfaces on both the command line and APIs are present to query and set them; we’ll deal with these in the upcoming Querying a given thread’s scheduling policy and priority section as well as in Chapter 11, The CPU Scheduler – Part 2.(Something to take into account: many distros enable a kernel feature called autogroups (CONFIG_SCHED_AUTOGROUP); it helps speed up interactive response time for the foreground terminal process(es) and their threads. When enabled, traditional notions of nice value aren’t really used (under the hood, cgroups is leveraged). See more on this in the Further reading section.)
- Real-time threads (having a policy of
SCHED_FIFOorSCHED_RR) have a real-time priority scale from 1 to 99, 1 being the least and 99 being the highest priority. Think of it this way: on a non-preemptible kernel with one CPU, aSCHED_FIFOpriority 99 thread spinning in an unbreakable infinite loop will effectively hang the machine! (Of course, even this too can be preempted by interrupts – both hard and soft; see Chapter 6, Kernel Internals Essentials – Processes and Threads, Figure 6.1.) Figure 10.2 reveals the thread priority scale on Linux:
Figure 10.3: Thread priority scale for SCHED_OTHER, SCHED_RR / SCHED_FIFO policies
The scheduling policy is (loosely) specified via a member within the task structure, the scheduling class. Also, the thread policy and priorities (both the static nice value and real-time priority) are members of the task structure (as Figure 10.1 clearly shows). Note that the scheduling class that a thread belongs to is exclusive; a thread can only belong to one scheduling class at a given point in time (worry not – we’ll cover scheduling classes in some detail later, in the upcoming Learning about the CPU scheduling internals – part 2 section).
Also, you should realize that on a modern Linux kernel, there are other scheduling classes (stop-sched and deadline) that are superior (in priority) to the FIFO/RR ones we’ve been seeing (again, more on this follows). Now that you have an idea of the basics, let’s move on to something interesting: how we can visualize the flow of threads as they execute. Read on!
Visualizing the flow
Section titled “Visualizing the flow”Multicore systems have led to processes – well, threads really (both user - and kernel-space ones) – executing concurrently on different processors. This is useful for gaining higher throughput and thus performance, but it also causes synchronization headaches when they work with shared writable data (we shall deal in depth with the really important topic of kernel synchronization in this book’s last two chapters).
So, for example, on a hardware platform with, say, six processor cores, we can expect processes (threads) to execute in parallel on them; this is nothing new. Is there a way, though, to actually see which processes or threads are executing on which CPU core – that is, a way to visualize a processor timeline? It turns out there are indeed a few ways to do so. In the following sections, we will look at a couple of interesting ways: with the gnome-system-monitor GUI program, perf, as well as other possibilities.
Using the gnome-system-monitor GUI to visualize the flow
Section titled “Using the gnome-system-monitor GUI to visualize the flow”The GNOME project provides a superb GUI to view and monitor system activity, appropriate for laptop, desktop, and server class systems (indeed, for any system powerful enough to run the GNOME GUI environment): the gnome-system-monitor application.
To quickly test using it to see the flow of work across a few CPU cores, let’s first run a few processes concurrently. For our simple test case here, a process that continually executes on the CPU – i.e., a CPU-bound one – is called for. A good candidate’s the simple utility named yes, which merely prints the character y continually to stdout (try it out!). So, let’s say we run it three times, in the background. To make this experiment meaningful, we’d like to affine (tie)each process to a particular CPU core on the system. The nproc command reveals the number of cores; they’re numbered starting at 0. On my x86_64 Fedora 38 VM:
$ nproc6Right, I have six CPU cores here (numbered 0–5). We leverage the useful taskset utility (it belongs to the util-linux package, which we specified installing back in Chapter 1). Running taskset with the -c option allows us to specify which CPU core(s) the command is to run upon; thus, if we do this
taskset -c 2 yes >/dev/nullit has yes run upon CPU core #2 only (we redirect stdout to the null device so that we don’t have to see y continually)!
So, let’s quickly rig up a test case: we’ll run the yes utility three times (in the background of course), with each process instance on a different CPU core – for example, like this:
taskset -c 1 yes >/dev/null &taskset -c 2 yes >/dev/null &taskset -c 3 yes >/dev/null &(Of course, you must have a system with at least four cores for the above to work (as core numbering starts at 0).) While they’re alive and running (like heck), run the gnome-system-monitor application (we assume you’re on a system with it installed, in GUI mode). The screenshot shows the typical output:

Figure 10.4: Screenshot showing the gnome-system-monitor GUI app; our three “yes” processes can be seen hammering away at 100% CPU usage on their three designated CPU cores (CPU2, CPU3, and CPU4)
Notice that the gnome-system-monitor GUI application numbers the CPU cores starting from 1 (not 0). Now, doing
pkill yeswill have all three yes process instances terminate. So, in Figure 10.4 (in the upper CPU pane), you can literally see the concurrency, and the parallelism, while they execute on different CPU cores. (Also, as you can see, besides the Resources tab, it also has Processes and File Systems tab views).
Right, let’s now move on to using the powerful perf utility to see the flow of processes/threads on CPU cores!
Using perf to visualize the flow
Section titled “Using perf to visualize the flow”Linux, with its vast arsenal of developer and Quality Assurance (QA) tools, has a really powerful one in perf. In a nutshell, the perf toolset is one of the ways to perform CPU profiling on a Linux box. (Besides a few tips, we do not cover perf in any detail in this book.)
Akin to the venerable top (and the newer htop) utility, to get a “thousand-foot view” of what’s eating the CPU (in a lot more detail than top), the perf set of utilities is excellent. Do note, though, that, quite unusually for an app, perf is tightly coupled with the kernel that it runs upon. It’s important that (on Ubuntu at least), to get perf, you install the linux-tools-$(uname -r) package. Also, the perf -related distribution packages will not be available for the custom 6.1 kernel we have built; so, when using perf, I suggest you boot your guest VM with one of the standard (or distro) kernels, install the linux-tools-$(uname -r) package, and then try using perf. (Of course, you can always manually build perf from within the kernel source tree, under the tools/perf/ folder.)
With perf installed and running, you could try out these perf top -related commands (refer to the man page or tutorials for details):
sudo perf topsudo perf top --sort comm,dsosudo perf top -r 90 --sort pid,comm,dso,symbolThe aforementioned perf top variants help us not only get a birds-eye view of what’s eating the CPU but also see what code paths they’re executing, even allowing us to zoom into each task to see further details (something traditional tooling typically doesn’t let us do). By the way, comm implies the name of the command/process, and dso is an abbreviation for dynamic shared object. The man page on perf(1) provides the details; use the man perf-<foo> notation – for example, man perf-top – to get help with perf top.
But back to our main point: one way to use perf is to obtain a clear picture of exactly what task(s) are running on what CPU core; this is done via the sched map sub-command in perf. First, though, you must record events using perf, which can be done both system-wide as well as for a specific process. To record events, run the following command:
sudo perf sched record [command]With no parameter following the record keyword, it records events system-wide; passing a parameter makes it record events for only that command process, and its descendants. Terminate the recording session with the SIGINT signal (^C). This will generate a binary data file named perf.data by default; we’ll soon see how it can be intuitively interpreted.
Trying it out – the command-line approach
Section titled “Trying it out – the command-line approach”Firstly, of course, lets run our CPU exerciser process – yes – concurrently, each instance affined to different CPU cores. To make the job easy, I’ve set up a couple of simple wrapper scripts in this folder: ch10/concurrent_exercise/. Let’s do a sample run and see, from within your copy of this book’s GitHub repo (available at https://github.com/PacktPublishing/Linux-Kernel-Programming_2E):
cd ch10/concurrent_exerciseAs the VM we’re running upon (an x86_64 Fedora 38) is configured with six CPU cores, we’ll instruct the script to spawn off six yes processes, each of which will be affixed to one CPU core:
$ ./concurrency 6concurrency: spawning a 'yes' process on ...... CPU core #0 now ...... CPU core #1 now ...... CPU core #2 now ...... CPU core #3 now ...... CPU core #4 now ...... CPU core #5 now ...Now (in another Terminal window), start recording (sampling, CPU profiling) with perf (note that we’re performing system-wide recording; that’s fine):
sudo perf sched record(As an aside, viewing the Resources tab of the gnome-system-monitor app is interesting at this point, though it can skew the ‘benchmark’.)
Next, after letting the processes run for a bit (half a minute should be more than enough), we shut down the concurrent processes and get perf to give us a detailed map of CPU usage, as seen during the recording:
$ pkill yesTerminatedTerminatedTerminatedTerminatedTerminatedTerminatedPress ^C in the Terminal where the perf record command is running to have it stop recording. Then, do this to generate a report:
$ sudo perf sched map > mymap.txtDone. Let’s look up the results!
The report file, mymap.txt here, is formatted as follows (as the columns aren’t explicitly labelled, I’ve inserted an annotation at the top of Figure 10.5):
- From the left, each column represents a CPU core, starting with 0 (please ignore the line numbers at the extreme left).
- After the CPU core columns (there will be six here as we have six CPUs), comes a Timestamp column (with the system uptime expressed in the
sec.usformat). - Then comes the Legend column. Here, each thread that executes is assigned a two-character name; in our run, as a good example (see Figure 10.5),
A0is thekthreadnamedmigration/0:18,B0is one of ouryesthreads (yes:6428),C0is anotherkthread migration/1:23, and so on.
Figure 10.5: Screenshot of the upper portion of the map file captured via perf sched map (with an annotation inserted at the very top) and our yes processes highlighted
So, we can see that our six yes processes (which are single-threaded of course), are the ones labeled B0, D0, F0, H0, J0, and K0. To make the visualization easier, I opened the map file in vim and searched to match them with a regular expression, like this:
/B0..D0..F0..H0..J0..K0It’s worked! You can see them highlighted in both Figure 10.5 and Figure 10.6. Now,the yes processes – here, B0, D0, F0, H0, J0, and K0 – all being in one line indicates that all six were running concurrently, in parallel, on CPU cores 0 to 5, respectively (as row numbers 11, 13, and 15 in Figure 10.5 clearly show)! Nice.

Figure 10.6: Screenshot of another portion of the perf map file, showing our six yes processes running concurrently on the six CPU cores on the box
(FYI, an asterisk indicates that a change of context, typically a context-switch on that core, occurred.) It’s instructive to see how other threads also run at different points; obviously, it’s not just our yes-men that want to run!
Again, you don’t have to do exactly what we did here to test this; any sufficiently CPU-bound application can be executed (benchmarking programs like stress-ng, the kernel build itself, and so on are decent candidates), and the perf commands we showed can be run to capture and report details.
We’ve just used perf to get a command-line (or console) based “view” of threads executing on our CPU cores; now, let’s leverage perf to show the same thing graphically!
Trying it out – the graphical approach
Section titled “Trying it out – the graphical approach”The steps to carry out here remain identical to those in the previous section except for the last command (the sudo perf sched map > mymap.txt command); instead, we generate a graphical representation of CPU scheduling with the following perf command:
sudo perf timechart -i ./perf.dataThis command generates a Scalable Vector Graphics (SVG) file named output.svg by default! It can be viewed with vector drawing utilities (such as Inkscape, or via the display command in ImageMagick) or simply within a web browser. It can be useful to study the time chart; try it out. However, do note that the vector images can be quite large and, therefore, take a while to open.
FYI, it is possible to configure perf to work with non-root access. The SVG was generated using the same perf.data file from our run in the previous section and is seen within a browser:

Figure 10.7: Partial screenshot of the SVG file generated by perf using the data from the previous run
You can zoom in and out of this SVG file, studying the scheduling and CPU events that are recorded by default by perf. Clearly, our six concurrent yes processes are hammering away on the six CPU cores (the blue color represents the Running state, as can be seen in the legend, the first line). Other processes (mostly asleep) show up below them.
The following figure is another partial screenshot when zoomed in 400% to the top-left region of the preceding screenshot; again, it’s pretty clear that the yes processes are the ones on the CPU:

Figure 10.8: Partial screenshot of perf timechart’s SVG file, when zoomed in 400% to the top-left region
What else? By using the -I option switch to perf timechart record, you can request that only system-wide disk I/O (and network, apparently) events be recorded. This could be especially useful as, often, real performance bottlenecks are caused by I/O activity (not CPU). The man page on perf-timechart(1) details further useful options.
You can convert perf ‘s binary perf.data record file into the popular Common Trace Format (CTF) file format, using perf data convert --all –-to-ctf <dir>, where the last argument is the directory where the CTF file(s) get stored. Why is this useful? CTF is the native data format used by powerful GUI visualizers and analyzer tools such as Trace Compass. (I find that this works on Fedora, whereas Ubuntu seems to have some nagging issues.)
Visualizing the flow via alternate approaches
Section titled “Visualizing the flow via alternate approaches”There are, of course, alternate ways to visualize what’s running on each processor. A quick overview follows.
The fact is several of these visualization tools are covered in a lot more detail in the Linux Kernel Debugging book, in Chapter 9, Tracing the Kernel Flow. Hence, we don’t repeat the same information here but do provide a quick overview.
Let’s first mention a few console-based visualization tools:
- perf-tools: Brendan Gregg has a very useful series of scripts that perform a lot of the hard work required when monitoring production Linux systems using
perf; do take a look at them here: https://github.com/brendangregg/perf-tools (some distributions include them as a package calledperf-tools[-unstable]). - Ftrace: a very powerful kernel tracer system built into the fabric of the Linux kernel (of course, it has to be enabled; most distros do enable Ftrace by default):
- Raw ftrace can be used to trace (almost) every single function, as it executes deep inside the kernel; the information gleaned includes the timestamp, the CPU core that it’s executing upon, the context that’s performing the execution, the interrupt state, and the function name.
- A front-end to raw Ftrace is the superb trace-cmd utility; it provides essentially the same information as raw Ftrace while being much simpler to use. It can also be configured to show the parameters being passed to kernel functions. (I have built a simple front-end to it, named trccmd (https://github.com/kaiwan/trccmd); do give it a spin.)
- Raw ftrace can be used to trace (almost) every single function, as it executes deep inside the kernel; the information gleaned includes the timestamp, the CPU core that it’s executing upon, the context that’s performing the execution, the interrupt state, and the function name.
- Some simple Bash scripting can show what’s executing on a given core (via a simple wrapper over
ps). In the following snippet, we show sample Bash functions; for example, the followingc0()function shows what is currently executing on CPU core#0, whilec1()does the same for core#1(this does imply that you’re using the regular GNUpsand not an abbreviated variant likebusybox ps):# Show thread(s) running on cpu core 'n' - func c'n'()function c0(){ps -eLF | awk '{ if($5==0) print $0}'}function c1(){ps -eLF | awk '{ if($5==1) print $0}'} - LTTng: The Linux Trace Toolkit – next generation (LTTng) is a powerful and popular open-source tracing system for the Linux kernel as well as user space apps and libraries. Its original version (LTT) dates to 2005, and LTTng is actively maintained. It has made a name for itself in helping track down performance and debug issues on multicore parallel and real-time systems.
A few GUI visualization tools are here:
- KernelShark: A good GUI front-end to the data generated by raw Ftrace and by
trace-cmd. (For raw Ftrace, you’d have to first do atrace-cmd extractto get the data into a file format recognized by it.) - TraceCompass: An excellent GUI front-end to visualize the traces generated by LTTng; in fact, it works with the popular CTF format, so any traces in this format can be imported and thus visualized by it.
Do give these alternatives a try!
Right, now that you’ve learned how you can visualize the flow of processes/threads on CPU cores by various means, let’s move our focus back to the kernel internals side for a while.
Learning about the CPU scheduling internals – part 2
Section titled “Learning about the CPU scheduling internals – part 2”This section delves into kernel CPU scheduling internals in some detail, the emphasis being on the core aspect of modern design, modular scheduling classes.
Understanding modular scheduling classes
Section titled “Understanding modular scheduling classes”Ingo Molnar, a key kernel developer (along with others), redesigned the internal structure of the kernel scheduler, introducing a new approach called scheduling classes (this was back in October 2007 with the release of the 2.6.23 kernel).
As a side note, the word class in scheduler classes isn’t a coincidence; many Linux kernel features are intrinsically, and quite naturally, designed with an object-oriented nature. The C language, of course, does not allow us to express this directly in code (hence the preponderance of structures with both data and function pointer members, emulating a class). Nevertheless, the design is very often object-oriented (as you shall quite clearly see with the driver model in the Linux Kernel Programming – Part 2 book). Please see the Further reading section of this chapter for more details on this aspect.
A layer of abstraction was introduced into the core scheduling code, the function kernel/sched/core.c:schedule(). This layer in schedule() is generically called the scheduling classes and is modular in design.
Note that the word modular here implies that scheduler classes can be added or removed from the in-tree kernel code; it has nothing to do with the Loadable Kernel Module (LKM) framework.
The basic idea is this: the Linux kernel (as of 6.1, and, as of this writing, the latest 6.7 kernel in fact), contains five scheduling classes, each of which is associated with a priority level. When the core scheduler code – the schedule() function (itself a thin wrapper over __schedule()) – is invoked, it iterates over each of the classes in a predefined priority order, asking each one if it has a thread that’s ready to run (how exactly, we shall soon see). Of the five scheduling classes present, it’s guaranteed that one of them will answer in the affirmative and pick a candidate thread to run next; as soon as this occurs, the core scheduling code context-switches to that lucky thread (skipping any remaining scheduling classes), and the job is done. The following flow diagram encapsulates this design:

Figure 10.9: Flow diagram of the core scheduling code paths, showing the overall modular scheduler class architecture (this diagram’s a key one!)
You, being alert, have spotted the connector labeled S at the very top of Figure 10.9; what does it imply? It’s there to answer a key question: “Who calls, and when exactly, is the core scheduler function, schedule(), called?” (This is answered in detail in an upcoming section, Learning about the CPU scheduling internals – part 3; relax – we’ll get there!)
As of the 6.1 Linux kernel (and, as of this writing, the latest 6.7 kernel in fact), these are the five scheduler classes within the kernel, listed in priority order, with the highest priority shown first:
| Scheduling policy | Scheduler class | sched_class data structure name | Defined in (via the DEFINE_SCHED_CLASS() macro) |
|---|---|---|---|
- | Stop-task / Stop-sched (__sched_class_highest) | stop_sched_class | kernel/sched/stop_task.c |
SCHED_DEADLINE | (Early) Deadline First | dl_sched_class | kernel/sched/deadline.c |
SCHED_FIFO / SCHED_RR | RT (real-time) | rt_sched_class | kernel/sched/rt.c |
SCHED_OTHER (or SCHED_NORMAL): the default | CFS | fair_sched_class | kernel/sched/fair.c |
SCHED_IDLE | Idle (__sched_class_lowest) | idle_sched_class | kernel/sched/idle.c |
Table 10.2: The five modular scheduling classes
So, there we have the five modular scheduler classes – stop-task, deadline, (soft) real-time (RT), fair (CFS), and idle – in highest to lowest priority order. The data structures that abstract these scheduler classes, struct sched_class, are strung together on a singly linked list, which the core scheduling code iterates over. (We’ll come to what the sched_class structure is later; ignore it for now.)
Every thread is associated with its unique task structure (struct task_struct); within the task structure (as we saw in Chapter 6, you can look it up here: https://elixir.bootlin.com/linux/v6.1.25/source/include/linux/sched.h#L737), the following applies:
- The member
struct sched_class *holds the pointer to the modular scheduling class that the thread belongs to; it’s exclusive – a thread can only belong to one scheduling class at any given point (it will be one of those mentioned in Table 10.2, third column). By default, it will point to CFS (fair_sched_class). - The
policymember specifies the scheduling policy that the thread adheres to (it will be one of those mentioned in Table 10.2, first column). It too is exclusive – a thread can only adhere to one scheduling policy at any given point in time (it can be changed though). - The thread priority value(s); the members incorporating them are
prio,static_prio,normal_prio, andrt_priority. - Both the scheduling policy and priority are dynamic and can be queried and set programmatically (or via utilities; you will soon see this).
FYI, threads belonging to the stop-sched classare very few; this is because it’s an extreme priority level. When a stop-sched thread gains the processor, the kernel turns off execution (as well as anything locking related, interrupts, and everything else) on all other cores on the system. Thus, the stop-sched class thread executes - on a core where all interrupts and kernel preemptions are masked - literally alone, with absolutely no chance of being preempted. Who needs this level of priority and non-preemptability? Well, one example is the Ftrace kernel tracing subsystem; another is live kernel patching. Also, the next priority sched class – Deadline – is meant for real-time tasks that have an associated deadline they must meet (in classic RTOS-like fashion). As stop-sched and deadline threads tend to be rare, we focus on the RT, and – mostly – fair (CFS) threads; the “fair class” threads are the ones typically alive and running.
So, knowing this, you will now realize that all threads that adhere to either the SCHED_FIFO or SCHED_RR scheduling policy map to the rt_sched_class (via the sched_class member within their task structures), all threads that are SCHED_OTHER (or SCHED_NORMAL) map to the fair_sched_class, and the CPU idle threads (swapper/n, where n is the CPU number starting from 0) always map to the idle_sched_class scheduling class.
When the kernel needs to schedule, this is the essential call sequence:
schedule() --> __schedule() --> pick_next_task()The actual iteration over the preceding scheduling classes occurs here; see the (partial) code of pick_next_task(), as follows: https://elixir.bootlin.com/linux/v6.1.25/source/kernel/sched/core.c#L5850:
static inline struct task_struct *__pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf){ const struct sched_class *class; struct task_struct *p; /* * Optimization: [ ... ] */ [ ... ] put_prev_task_balance(rq, prev, rf); for_each_class(class) { p = class->pick_next_task(rq); if (p) return p; } BUG(); /* The idle class should always have a runnable task. */}(The reality is that a good amount of optimization goes into the task picking code logic; for clarity, we will skip it and focus upon the canonical case.) The preceding for_each_class() macro sets up a for loop to iterate over all scheduling classes. Its implementation is as follows:
kernel/sched/sched.h
#define for_class_range(class, _from, _to) \ for (class = (_from); class < (_to); class++)#define for_each_class(class) \ for_class_range(class, __sched_class_highest, __sched_class_lowest)You can see from the preceding code snippets that it results in each class, from __sched_class_highest to __sched_class_lowest, being “asked” via the class->pick_next_task() “method” who to schedule next (as Figure 10.9 conceptually shows). Now, it’s left to the scheduling class code to determine whether it has any candidates that want to execute. How? That’s simple actually; it merely looks up its runqueue data structure.
Now, this is a key point: the kernel maintains one runqueue for every processor core and for every scheduling class! So, if we have a system with, say, six CPU cores, then we will have 6 cores * 5 sched classes = 30 runqueues! (There is an exception: on Uniprocessor (UP) systems, the stop-sched class does not exist.) Runqueues are implemented per scheduling class; here’s, for example, the runqueue for CFS: struct cfs_rq (https://elixir.bootlin.com/linux/v6.1.25/source/kernel/sched/sched.h#L550); similarly, for the RT class, it’s struct rt_rq, and so on. The following diagram is an attempt to present this information:

Graphical user interface, diagram Description automatically generated
Figure 10.10: There is 1 runqueue per CPU core and per scheduling class
Please note that in the preceding diagram, the way I show the runqueues makes them perhaps appear to be arrays. That isn’t the intention at all; it’s merely a conceptual diagram. The actual runqueue data structure used depends on the scheduling class (the class code implements the runqueue after all). It could be an array of linked lists (as with the real-time class), a tree – a red-black (rb) tree, in fact –with the fair class, and so on.
A conceptual example to help understand scheduling classes
Section titled “A conceptual example to help understand scheduling classes”To help better understand the scheduler class model, we will devise an example: let’s say, on a Symmetric Multi Processor (SMP) or multicore system, we have 100 threads alive (in both user and kernel space). Among them, we have a few competing for the CPUs; that is, they are in the ready-to-run (Rr) state, implying they are runnable and thus enqueued on runqueue data structures (see Figure 10.2, the state machine). Let’s say the runnable threads fall into various scheduling classes as follows:
- One stop-sched (SS) class thread, S1
- Two Deadline (DL) class threads, D1 and D2
- Two Real Time (RT) class threads, RT1 and RT2
- Three Completely Fair Scheduling (CFS) (or fair) class threads, F1, F2, and F3
- One idle class thread I1
Now let’s imagine that, to begin with, thread F2 is on a processor core, happily executing code. At some point, the kernel wishes to context switch to some other task on that CPU. (What triggers this? You shall soon see.) On the scheduling code path, the kernel code ultimately ends up in the core scheduling code kernel/sched/core.c:void schedule(void) kernel routine (again, code-level details follow later). What’s important to understand for now is that the pick_next_task() routine, invoked by schedule(), which becomes __schedule(), iterates over the linked list of scheduler classes, asking each whether it has a candidate to run (again, refer to Figure 10.9). Its code path (conceptually, of course) looks something like this:
- Core scheduler code (__
schedule()): “ Hey, SS (stop-sched class), do you have any threads that want to run?” - SS class code: Iterates over its runqueue and does find a runnable thread (S1); it thus replies: “ Yes, I do; it’s thread S1.”
- Core scheduler code (
__schedule()): “ Okay, great; let’s context switch to S1.”
And the job is done (for this scheduling round or epoch, at least). But let’s change the scenario a bit: what if there is no runnable thread S1 on the SS runqueue for that processor (or it has gone to sleep, or is stopped, or it’s on another CPU’s runqueue)? Then, SS will say “ no,” and the next most important scheduling class, Deadline (DL), will be asked. If it has potential candidate threads that want to run (D1 and D2, in our example), its class code will run its algorithm to identify which of D1 or D2 should run, return that thread task structure pointer to __schedule(), and the kernel scheduler will faithfully context switch to it. This process continues for the Real-time (RT) and Fair (CFS) scheduling classes. (A picture is worth a thousand words, right? See Figure 10.11.)
It’s likely that (on your typical moderately loaded Linux system), there will be no SS, DL, or RT candidate threads that want to run on the CPU in question, and there often will be at least one fair (CFS) thread that will want to run.
Hence, the competition is typically between the fair (CFS) runnable threads; the one picked by the fair class implementation (CFS) will be the one that is context-switched to.
If there are really no threads that want to run (no SS/DL/RT/CFS class thread wants to run), it implies that the system is presently idle (lazy chap). Now, the Idle class is asked whether it wants to run; it always says yes! This makes sense; after all, it is the CPU idle thread’s job to run on the processor when no one else needs/wants to. Hence, in such a case, the kernel switches context to the idle thread, typically labelled swapper/n, where n is the CPU number that it’s executing upon (starting from 0; and yes, I know what you’re probably thinking: why is it called “swapper”?… it’s just old Unix history coming back to haunt us – nothing else).
Also, note that the swapper/n (CPU idle) kernel thread does not show up in the ps listing, even though it’s always present (recall the code we demonstrated in Chapter 6, Kernel Internals Essentials – Processes and Threads, here: ch6/foreach/thrd_showall/thrd_showall.c (https://github.com/PacktPublishing/Linux-Kernel-Programming_2E/blob/main/ch6/foreach/thrd_showall/thrd_showall.c) There, we wrote a disp_idle_thread() routine to show some details of the CPU idle thread, as even the kernel’s do_each_thread() { ... } while_each_thread() loop that we employed there does not show the idle thread.
The following diagram neatly sums up the way the core scheduling code invokes the scheduling classes in priority order, context-switching to the ultimately selected “next” thread:

Diagram Description automatically generated
Figure 10.11: Core scheduler code iterating over every scheduling class to pick the task that will run next
Asking the scheduling class
Section titled “Asking the scheduling class”How exactly does the core scheduler code (in pick_next_task()) ask the scheduling classes whether they have any threads that want to run? We have already seen this, but I feel it’s worthwhile repeating the following code fragment for clarity (called mostly from __schedule() and also from the thread migration code path):
kernel/sched/core.c
static inline struct task_struct *__pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf){ const struct sched_class *class; struct task_struct *p; /* * Optimization: [ ... ] */ [ ... ] put_prev_task_balance(rq, prev, rf); for_each_class(class) { p = class->pick_next_task(rq); if (p) return p; } [ … ]Notice the object orientation in action: the class->pick_next_task(rq) code, for all practical purposes, invokes a method, pick_next_task(), of the scheduling class class! The return value, conveniently and deliberately, is the pointer to the task structure of the picked task, which the code can now context-switch to. As can also be seen, pick_next_task() returning NULL implies that the current class does not have any candidate to schedule; so we move onto the next class and ask it. The loop will always terminate as, if nothing else, the idle class will always return a non-null candidate to schedule, the idle thread for that core.
The preceding code and paragraph implies, of course, that there is a pre-populated class structure per scheduling class, embodying what we really mean by the scheduling class. Indeed, this is the case: it contains all possible operations, as well as useful hooks, that you might require in a scheduling class. It’s (surprisingly) called the sched_class structure:
https://elixir.bootlin.com/linux/v6.1.25/source/kernel/sched/sched.h#L2147
struct sched_class { [ ... ] void (*enqueue_task) (struct rq *rq, struct task_struct *p, int flags); void (*dequeue_task) (struct rq *rq, struct task_struct *p, int flags); [ ... ] struct task_struct *(*pick_next_task)(struct rq *rq); void (*task_tick)(struct rq *rq, struct task_struct *p, int queued); void (*task_fork)(struct task_struct *p); [ ... ]};(There are many more members of this structure than we’ve shown here; do look it up in the kernel code.) As should be obvious by now, each scheduling class instantiates this structure, appropriately populating it with methods (via function pointers, of course). The core scheduling code, iterating over the linked list of scheduling classes (as well as elsewhere in the kernel), invokes – as long as it’s not NULL – the methods and hook functions as required (again, Figure 10.9 and Figure 10.11 remind us of this).
As an example, let’s consider how the fair scheduling class (CFS) implements its scheduling class:
https://elixir.bootlin.com/linux/v6.1.25/source/kernel/sched/fair.c#L12365
DEFINE_SCHED_CLASS(fair) = { .enqueue_task = enqueue_task_fair, .dequeue_task = dequeue_task_fair, [ ... ] .pick_next_task = __pick_next_task_fair, [ ... ] .task_tick = task_tick_fair, .task_fork = task_fork_fair, .prio_changed = prio_changed_fair, [ ... ]};(Earlier, the structure was directly defined; from 5.11, the DEFINE_SCHED_CLASS() macro’s used to do so. To see why, read the commit: https://github.com/torvalds/linux/commit/43c31ac0e665d942fcaba83a725a8b1aeeb7adf0.)
So, now you see it: the code used by the fair sched class to pick the next task to run (when asked by the core scheduler) is the function __pick_next_task_fair() (a thin wrapper over pick_next_task_fair()). FYI, the task_tick and task_fork members are good examples of scheduling class hooks; these functions will be invoked by the scheduler core on every timer tick (that is, each timer interrupt, which fires – in theory, at least – CONFIG_HZ times a second) and when a thread belonging to this scheduling class forks, respectively.
An interesting in-depth Linux kernel project, perhaps: create your own scheduling class with its particular methods and hooks, implementing its internal scheduling algorithm(s). Link all the bits and pieces as required (into the scheduling classes linked list, inserted at the desired priority, and so on) and test! Now, you’ll see why they’re called modular scheduling classes.
Great – now that you understand the architecture behind how the modern modular CPU scheduler works, let’s take a brief look at the algorithm behind CFS, perhaps the most used scheduling class on generic Linux.
The workings of the Completely Fair Scheduling (CFS) class in brief
Section titled “The workings of the Completely Fair Scheduling (CFS) class in brief”Since version 2.6.23 (back in 2007), CFS has been the de facto kernel CPU scheduling code for regular threads; most threads on Linux tend to belong to the SCHED_OTHER policy by default, which is driven by CFS. The driver behind the CFS algorithm is to provide fairness and overall throughput.
It’s implementation, in a nutshell, is this: the kernel keeps track of the actual CPU runtime (at nanosecond granularity) of every runnable CFS (SCHED_OTHER / SCHED_NORMAL) thread; the thread with the smallest runtime is the thread that most deserves to run and will be awarded the processor on the next scheduling cycle or epoch (the word “epoch” denotes “the beginning of a period in the history of someone or something”). Conversely, threads that continually hammer on the processor will accumulate a large amount of runtime and will thus be penalized (it’s quite karmic, really)!
We divide this discussion into two sections: the first briefly looks at the CFS concepts of vruntime and its internal rb-tree runqueue, and the second looks at how CFS dynamic timeslices work. Let’s, of course, begin with the first.
A note on the CFS vruntime value and its runqueue
Section titled “A note on the CFS vruntime value and its runqueue”Without delving into too many details regarding the internals of the CFS implementation, embedded within the task structure is another data structure, struct sched_entity, which contains within it an unsigned 64-bit value called vruntime (or virtual runtime) (https://elixir.bootlin.com/linux/v6.1.25/source/include/linux/sched.h#L556). This is, at a simplistic level, the monotonic counter that keeps track of the amount of time, in nanoseconds, that the thread has accumulated (run) on the processor.
In practice, in implementation, a lot of code-level tweaks, checks and balances are required. For example, often, the kernel will reset the vruntime value to 0, triggering another scheduling epoch. As well, there are various tunables (or sysctls) under /proc/sys/kernel/sched_*, helping to better fine-tune the CPU scheduler behavior (some of them are documented here: https://www.kernel.org/doc/html/latest/admin-guide/sysctl/kernel.html).
How CFS picks the next task to run is encapsulated in the kernel/sched/fair.c:pick_next_task_fair() function. In theory, the way CFS works is simplicity itself: enqueue all runnable tasks (for that CPU) onto the CFS runqueue, which is an rb-tree (a type of self-balancing binary search tree), in such a manner that the task that has spent the least amount of time on the processor is the leftmost leaf node on the tree, with succeeding (leaf) nodes to the right representing the next task to run, and then the one after that.
In effect, scanning the tree from left to right gives a timeline of future task execution. How is this assured? By using the aforementioned vruntime value as the key via which tasks are enqueued onto the rb-tree!
Why is it called vruntime and not just runtime? It’s because the vruntime member’s value isn’t simply the time spent on the processor by the thread; it’s more nuanced: it takes the thread’s priority – the nice value – into account when calculating this all-important number (after all, the thread’s “position” in the CFS rb-tree run queue is based on this vruntime quantity). So here’s what’s done: the lower the nice value (the higher the priority), the more the vruntime value is scaled down, thus having it enqueued more to the left; the higher the nice value (the lower the priority), the more the vruntime value is scaled up, thus having it enqueued more to the right. (This approach to task scheduling is broadly called a weighted fair queuing scheduler.)
When the core scheduler needs to schedule, and it asks CFS “ do you have any threads that want to run?”, the CFS class code – which we’ve already mentioned (the pick_next_task_fair() function) – runs and simply picks the leftmost leaf node on the tree, returning the pointer to the task structure pointer embedded there. Think about it – it is, by definition, the task with the lowest vruntime value, so effectively, the one that has run the least! (Traversing a tree is an O(log n) time-complexity algorithm, but due to some code optimization and clever caching of the leftmost leaf node, the implementation effectively has a very desirable O(1) time complexity.) Of course, the actual code is a lot more complex than is let on here; it requires several checks and balances. We won’t delve into all the gory details here.
We refer those of you that are interested in learning more about CFS to the kernel documentation on the topic, at https://www.kernel.org/doc/html/v6.1/scheduler/sched-design-CFS.html.
Also, the kernel contains several tunables (sysctls) under /proc/sys/kernel/sched_* that have a direct impact on scheduling. Notes on these and how to use them can be found here: Analyzing the impact of sysctl scheduler tunables, IBM LTC: https://events.static.linuxfound.org/slides/2011/linuxcon/lcna2011_rajan.pdf, and an excellent real-world use case can be found in the article at https://www.scylladb.com/2016/06/10/read-latency-and-scylla-jmx-process/.
Further, several of these kernel-level scheduling tunables have more recently moved to debugfs here: /sys/kernel/debug/sched/*. You will therefore, of course, need root access to see/change them.
A note on the CFS scheduling period and timeslice
Section titled “A note on the CFS scheduling period and timeslice”Did you notice? Unlike traditional OS schedulers, with CFS, timeslices are dynamic! Tasks that sip on the CPU (the so-called IO-bound ones) automatically accumulate less vruntime and thus migrate toward the left of the CFS rb-tree. The opposite happens for CPU-bound tasks; they (by having bigger vruntime values) move toward the right, lessening their chance of gaining the CPU quickly.
In the scheduler context, the scheduling period (sometimes confusingly called “scheduling latency”), refers to the time for which a complete scheduling cycle (or epoch) runs; within this time period, the OS guarantees that every thread will be given a chance to run on the CPU. So what is it? The default value is in the sysctl /sys/kernel/debug/sched/latency_ns (with a typical default of 24 ms on Ubuntu 22.04 and 18 ms on Fedora 38/39). Further, at runtime, it can change – it itself is dynamic (more on this soon follows) – and is calculated as follows:
Scheduling Period length = min_granularity_ns * nr_running ;Here, nr_running is the number of tasks currently runnable (this is on a per-runqueue basis). These scheduler tunables, in recent kernels, are found in debugfs; let’s look up some values on x86_64 Ubuntu 22.04 LTS. (The grep . <files-spec> syntax used here is a fantastic way to both list the (single - line) tunable and see its current value! Of course, the grep -v syntax is used to negate some matches.)
# grep -E . /sys/kernel/debug/sched/* 2>/dev/null | grep -v -E "^\/sys\/kernel\/debug\/sched\/debug\:|features"/sys/kernel/debug/sched/idle_min_granularity_ns:750000/sys/kernel/debug/sched/latency_ns:24000000/sys/kernel/debug/sched/latency_warn_ms:100/sys/kernel/debug/sched/latency_warn_once:1/sys/kernel/debug/sched/migration_cost_ns:500000/sys/kernel/debug/sched/min_granularity_ns:3000000/sys/kernel/debug/sched/nr_migrate:32/sys/kernel/debug/sched/preempt:none (voluntary) full/sys/kernel/debug/sched/tunable_scaling:1/sys/kernel/debug/sched/verbose:N/sys/kernel/debug/sched/wakeup_granularity_ns:4000000The above grep command line also filters out the tunables named debug and features. Okay, here’s the meaning of some relevant tunables:
latency_ns: This is the current calculated “period” value (in nanoseconds (ns)); so, being 24,000,000 ns, the default scheduling period here is 24 ms, i.e., each thread is guaranteed it gets a chance to run at least once every 24 ms!min_granularity_ns: This is the minimum required “distance” between nodes on the CFS rb-tree; in effect, this is the minimum timeslice guaranteed for each CFS thread when it runs (default: 3 ms).
Here are a couple of points to note before moving on:
- The defaults can and do vary across systems (kernels)! On my x86_64 Fedora 38 VM, the period and minimum granularity (the minimum timeslice) is 18 ms and 2.25 ms, respectively. Check what it is on your system.
- The above scheduler tunables are created in the function
sched_init_debug()(called during system initialization here: https://elixir.bootlin.com/linux/v6.1.25/source/kernel/sched/debug.c#L299).
Think about it – the number of currently runnable tasks (nr_running) directly influences the period (and thus the timeslice as well). So, given these facts:
- The equation Scheduling Period length = min_granularity_ns * nr_running (as we saw)
- The
min_granularity_nsis, in effect, the CFS (dynamic) timeslice value - Given a default
min_granularity_nsvalue of 3 ms, and a period (latency_ns) of 24 ms (as is the case on my Ubuntu 22.04 (and 23.10) box), to see how this works, we provide the calculations of the effective timeslice and scheduling period for a set of sample values, as shown in the following table.
| Number of runnable threads in the CFS runqueue (nr_running) | Effective timeslice (ms) = Scheduling Latency (ms) / nr_running. Is it less than the minimal granularity or timeslice (min_granularity_ns)? | Scheduling period (epoch duration) = min_granularity_ns * nr_running (ms) |
|---|---|---|
| 3 | 24/3 = 8 ms // okay | 3*3 = 9 ms |
| 6 | 24/6 = 4 ms // okay | 6*3 = 18 ms |
| 8 | 24/8 = 3 ms // minimum allowed! (as per min_granularity_ns) | 8*3 = 24 ms |
| 12 | 24/12 = 2 ms /* less than min_granularity_ns; => untenable! recalculate period */ | 12 *3 = 36 ms |
Table 10.3: Effective CFS task timeslice based on the number of runnable threads
The effective timeslice is calculated and seen in the second column; as long as its value is within the min_granularity_ns value (3 ms), all’s well. However, as can be seen, when the number of runnable threads gets sufficiently large, the situation obviously becomes untenable (the last row of Table 10.3); now, the scheduler, instead of giving up, cleverly and dynamically adjusts the scheduling period, recalculating it! (Well, that’s one way to put it; the cunning kernel goes: “Did I promise you a chance on the CPU at least once in every 24 ms period? No, no, you’re mistaken; I meant once in every 36 ms period…”.)
More technically, the check done is this (pseudocode):
effective_timeslice (ms) = latency_ns (ms) / nr_runningif effective_timeslice < min_granularity_ns recalculate the scheduling periodPut another way:
if nr_running > (latency_ns / min_granularity_ns) recalculate the scheduling period(The terminology can be confusing; remember, latency_ns is the scheduling period.) Check out the Further reading section for more on CFS and these scheduler-related tunables. Let’s now move on to the (brief) topic of looking up task scheduling statistics maintained by the kernel (if so configured).
Scheduling statistics
Section titled “Scheduling statistics”Can you see the state of scheduling, both at system and process granularity? Indeed, when configured (requires CONFIG_SCHEDSTATS=y), the kernel makes available these pseudofiles under proc:
/proc/schedstat: System-wide scheduling statistics. These have been around a long time; they display per-CPU scheduling statistics (as well as domain - CPU / micro-architecture hierarchy - information on SMP). The information includes the number of times the scheduler (and thetry_to_wake_up()function) was called (on that CPU core), the cumulative sum of all time spent running/ waiting by tasks on the core, and the number of timeslices on that core. It’s best to refer to the official kernel documentation on it: https://elixir.bootlin.com/linux/v6.1.25/source/Documentation/scheduler/sched-stats.rst./proc/PID/schedstatand/proc/PID/sched: Process/thread-level granularity:- The
/proc/PID/schedstatcontent consists of three whitespace-delimited numbers, all with regard to the thread with the process ID PID:- The time spent on the CPU (nanoseconds) - The time spent waiting on a runqueue (nanoseconds) - The number of timeslices run on this CPU
- The
/proc/PID/schedcontent is pretty detailed; it includes many fields of the task’ssched_entitystructure (shown asse.foo; this includes the taskvruntime(in nanoseconds) asse.vruntime!), context-switching statistics, the scheduling policy and priority, as well as some NUMA statistics. Quick tip: Try this to keep a “watch” on the fields as they change. As an interesting experiment, runyesin the background (yes >/dev/null &), note its PID, and then do this:watch -d -n1 'cat /proc/<PID_of_yes>/sched'Break off with^C.
- The
The Linux kernel’s always evolving (that’s really its secret sauce!); task (CPU) scheduling hasn’t been spared. From the 6.6 kernel (October 2023), a new scheduler replaces the venerable CFS for the fair class; it’s named EEVDF – the Earliest Eligible Virtual Deadline First scheduler (Peter Zijlstra is one of its key developers). Interestingly, the overall approach is similar to that of CFS – both use a virtual time-based or weighted fair queuing approach. EEVDF addresses limitations of CFS and brings certain advantages; among these, it addresses the tight latency requirements that some threads have (enabling them to run in shorter bursts but more often on the processor, with lower latency); it’s also considered to be a cleaner implementation (getting rid of several heuristics that CFS relies upon). As we focus on the 6.1 (S)LTS kernel, this edition doesn’t go into further details; as always, see the Further reading section for more on EEVDF.
Now, let’s move on to learning how to query the scheduling policy and priority of any given thread.
Querying a given thread’s scheduling policy and priority
Section titled “Querying a given thread’s scheduling policy and priority”In this section, you’ll learn how to query the scheduling policy and priority of any given thread on the system via the command line. (But what about programmatically querying and setting the same? We defer that discussion to Chapter 11, The CPU Scheduler – Part 2, in the Querying and setting a thread’s scheduling policy and priority section.)
We learned that, on Linux, the thread is the KSE; it’s what gets scheduled and runs on the processor. Also, Linux has several choices for the scheduling policy (or algorithm) to use. Both the scheduling policy and priority is assigned on a per-thread basis, with the default policy always being SCHED_OTHER and the default real-time priority being 0 (in other words, it’s a non-real-time thread; see Table 10.1).
On a given Linux system, we can always see all processes alive (via a simple ps -A), or, with GNU ps, even every thread alive (one way is with ps -LA). However, this does not reveal a key fact: what scheduling policy and priority these tasks run under. How do we query that?
This turns out to be pretty simple: on the shell, the chrt utility is admirably suited to query and set a given process’ scheduling policy and/or priority. Issuing chrt with the -p option switch and providing the PID as a parameter has it display both the scheduling policy as well as the real-time priority of the task in question; for example, let’s query this for the init process (or systemd) PID 1:
$ chrt -p 1pid 1's current scheduling policy: SCHED_OTHERpid 1's current scheduling priority: 0It’s quite clear: the PID 1 process (typically, its systemd,of course) has the SCHED_OTHER scheduling policy (which CFS drives) and a real-time priority of 0 (as it isn’t a real-time task; see Figure 10.3 to be reminded of the priority scale). As usual, the man page on chrt(1) provides all the option switches and their usage; do take a peek at it.
In the following (partial) screenshot, we show a run of a simple Bash script (ch10/query_task_sched.sh, a wrapper over chrt, essentially) that iterates over, queries, and displays the scheduling policy and priority (both nice and (soft)real-time) of all threads currently alive (on my x86_64 Fedora 38 VM):

Figure 10.12: (Partial) screenshot of our ch10/query_task_sched.sh Bash script in action
A few things to notice:
- In our script, by using GNU
ps, via invocation of theps -LAcommand, we’re able to capture all the threads that are alive on the system; their PIDs and TIDs are displayed. As you learned in Chapter 6, Kernel Internals Essentials – Processes and Threads, the PID is the user space equivalent of the kernel TGID, and the TID is the user space equivalent of the kernel PID. We can thus conclude the following:- If the PID and TID match, it – the thread seen in that row (the third column has its name) – is the
main()thread of the process.- If the PID and TID match and the PID shows up only once, it’s a single-threaded process.
- If the PID repeats (the leftmost column) with varying TIDs (the second column), the process is multithreaded and those (the TIDs) are the children (more accurately, the worker) threads of the process. Our script shows this by indenting the TID number a bit to the right (in the truncated screenshot of Figure 10.12, you can’t see it, as this occurs later).
- If the PID and TID match, it – the thread seen in that row (the third column has its name) – is the
- Notice how the vast majority of threads on a typical Linux box (desktop, server, or even embedded), will tend to be non-real-time (belonging to the policy
SCHED_OTHER). A few (soft) real-time threads (SCHED_FIFO/SCHED_RR) may show up as well. Deadline (DL) and Stop-Sched (SS) threads are rare indeed (though of course, things like this tend to be project specific). - Do notice the following observations regarding the real-time threads that showed up in the preceding output:
- Our script highlights any real-time threads (one with Sched Policy, the fourth column, as
SCHED_FIFOorSCHED_RR) by displaying an asterisk in the (sixth) column, labeled*RT.- Moreover, any soft real-time threads with a real-time priority of 99 (the maximum possible value) will have three asterisks in this same column (these tend to be specialized kernel threads).
- Our script highlights any real-time threads (one with Sched Policy, the fourth column, as
- The
SCHED_RESET_ON_FORKflag, when Boolean ORed with the scheduling policy, has the effect of disallowing any children (viafork()) from inheriting a privileged scheduling policy (a security measure). - The penultimate column is the thread’s “nice” value (recall, the range is -20 to +19, with -20 being the best priority and 19 the worst, with a default value of 0). Note that the nice value’s only valid for threads with the scheduling policy
SCHED_OTHER(as well as the batch and idle ones). - The far-right column shows the CPU affinity mask (in hexadecimal), again a per-thread attribute! This implies that you can set the CPU cores that the thread can possibly be scheduled upon (we cover this aspect in detail in the following chapter). As an example, the mask value 0x3f in binary is 0011 1111, implying that this thread can run on any of the cores set to 1, and thus here, on any core (as there are a total of six cores on the system).
Quick quiz: what does the CPU affinity mask value 0x8 imply?
- Changing the scheduling policy and/or priority of a thread can be performed with
chrt; however, you should realize that this is a sensitive operation requiring root privileges (or, nowadays, the preferred mechanism would be via the capabilities model, withCAP_SYS_NICEbeing the required capability bit in question).
We will leave it to you to examine the code of the script (ch10/query_task_sched.sh). Also, be aware that performance and shell scripting do not really go together (so don’t expect much in terms of performance here). Think about it – every external command issued within a shell script (and we have several here, such as awk, grep, and cut) involves a fork-exec-wait semantic and context-switching. Also, these all execute within a loop.
The tuna(8) program, a powerful GUI-based (or console-mode) system monitoring, tuning, and profile management tool, can be used to both query and set various attributes; this includes process-/thread-level scheduling policy/priority and the CPU affinity mask, as well as IRQ affinity. It’s a well-designed GUI; do check it out! (Installing tuna: https://tuna.readthedocs.io/en/stable/installation.html).
Also, the schedtool utility is somewhat similar to chrt and can be used to query and set any or all task scheduling parameters on given threads; the man page on schedtool(8) covers its usage.
You might wonder, will the (few) threads with the SCHED_FIFO policy and a real-time priority of 99 always hog the system’s processors? No, not really; the reality is that these threads are typically asleep most of the time. When the kernel does require them to perform some work, it wakes them up. Now, precisely due to their real-time policy and very high priority, it’s pretty much guaranteed that they will more or less immediately get a CPU core and execute for as long as is required (going back to sleep once the work is done). The key point is, when they require the processor, they will get it (somewhat akin to an RTOS, but without the iron-clad guarantees, low scheduling latency, and determinism that an RTOS delivers).
How exactly does the chrt utility query (and set) the real-time scheduling policy/priority? Ah, that should be obvious: as they reside within the task structure in the kernel Virtual Address Space (VAS), the chrt process must issue a system call. There are several system call variations that perform these tasks: the one used by chrt to query the scheduling policy and priority is sched_getattr(), and the sched_setattr() system call is used to set the scheduling policy and priority. (Be sure to look up the man page on sched(7) for details on these and more scheduler-related system calls.) A quick strace run on chrt will indeed verify this!
$ strace chrt -p 1[ … ]sched_getattr(1, {size=56, sched_policy=SCHED_OTHER, sched_flags=0, sched_nice=0, sched_priority=0, sched_runtime=0, sched_deadline=0, sched_period=0, sched_util_min=0, sched_util_max=0}, 56, 0) = 0newfstatat(1, "", {st_mode=S_IFCHR|0620, st_rdev=makedev(0x88, 0), ...}, AT_EMPTY_PATH) = 0write(1, "pid 1's current scheduling polic"..., 47pid 1's current scheduling policy: SCHED_OTHER) = 47write(1, "pid 1's current scheduling prior"..., 39pid 1's current scheduling priority: 0) = 39[ … ]Now that you have the practical knowledge to query a thread’s scheduling policy/priority and CPU affinity mask, it’s time to dig a bit deeper. In the following section, we delve further into the internal workings of Linux’s CPU scheduler.
We shall understand the basics of user and kernel preemption, figuring out who exactly runs the code of the kernel task scheduler and when it runs. Curious? I hope so! Read on!
Learning about the CPU scheduling internals – part 3
Section titled “Learning about the CPU scheduling internals – part 3”Let’s begin by exploring the topic of preemption.
Preemptible kernel
Section titled “Preemptible kernel”Please visualize this hypothetical situation: you’re running on a system with just one CPU core. An analog clock app is running on the GUI along with a C program, a.out, whose one line of code is (groan) while (1);. So, what do you think: will the CPU - hogger while 1 process indefinitely hog the CPU, thus causing the GUI clock app to stop ticking (will its second hand stop moving altogether)?
A little thought (and experimentation) will reveal that, indeed, the GUI clock app keeps ticking in spite of the naughty CPU hogger app! This is really the whole point of having an OS-level scheduler: it can, and does, preempt (kick out!) the CPU-hogging user space process. (We briefly discussed the CFS algorithm previously; CFS will cause the aggressive CPU-bound process to accumulate a huge vruntime value and thus move more to the right on its rb-tree runqueue, thus penalizing itself of the processor!) All modern OSes support this type of preemption – it’s called user-mode preemption.
But now consider this: what if you write a kernel module that performs the same while(1) infinite loop on a single core system? This poses a problem: the system will now simply hang. Why? Because, by default, most OS kernels are non-preemptible; that is, they cannot preempt themselves!
Besides this trivial example, real-world cases definitely exist where, if and when the kernel’s non-preemptible, it can have a negative impact on (real-time) thread scheduling. Think about it: what if your high - priority thread is on a runqueue (and thus runnable) and needs to run urgently, but the kernel’s stuck processing some long winding loop in a non-preemptible section of kernel (or kernel module/driver) code? Alternatively, a hardware interrupt occurs but can’t be serviced, due to interrupts being masked in, again, a long - running non-preemptible section of code… Locking plays a role here (as you’ll learn in a lot more detail in the last two chapters); in fact, for many years, the kernel had a notorious, very coarse-grained (and recursive) lock nicknamed the Big Kernel Lock (BKL); when held, it kept the kernel in a non-preemptible state for long-ish periods of time (with interrupts masked), thus wreaking havoc with performance and latency response. It was (finally!) completely removed in the 2.6.39 kernel.
So, the question arises: can, when required, the kernel preempt itself? Well, guess what: for many years now, Linux has provided a build-time configuration option to make the kernel preemptible; it’s called CONFIG_PREEMPT. (Actually, this is merely evolution toward the long-term goal of cutting down latencies and improving the kernel and scheduler response. A large body of this work came from earlier, and some ongoing, efforts: the Low Latency (LowLat) patches, (the old) RTLinux work, and particularly, the RTL (Real-Time Linux) project (where Linux runs as a true RTOS! We will cover a bit on setting up RTL in the following chapter).)
Once this CONFIG_PREEMPT kernel config option is enabled and the kernel is built and booted into, we run on a preemptible kernel – where, at most points, the OS has the ability to preempt itself!
To check out this option, within the make menuconfig UI, navigate to General Setup | Preemption Model.
Actually, there’s more to it; by default, modern Linux kernels have three kernel config options available as far as kernel preemption goes:
| Preemption type | Characteristics |
|---|---|
CONFIG_PREEMPT_NONE | Traditional model, geared toward high overall throughput (meant for servers). Though occasional long(er) delays can occur, this is the option to select to “maximize the raw processing power of the kernel, irrespective of scheduling latencies.” (Here, kernel preemption’s limited to only where explicit cond_resched() calls are invoked.) |
CONFIG_PREEMPT_VOLUNTARY | Preemptible kernel (meant for desktop/laptop); more explicit preemption opportunity points within the OS (those points where cond_resched() and might_sleep() calls are invoked). Leads to lower scheduling latencies and better app response, at the cost of slightly lower throughput. Often the default for distros. |
CONFIG_PREEMPT | Aka the LowLat kernel; (almost) the entire kernel is preemptible (meant for a desktop/laptop/powerful embedded system). Selecting this option implies that involuntary preemption of even kernel code paths is now possible (any/all sections of kernel code where preemption isn’t explicitly disabled are now preemptible). Yields even lower scheduling latencies (a tens to low hundreds microseconds range on average) at the cost of slightly lower throughput and slight runtime overhead. Select this if you are building a kernel for a desktop or embedded system with latency requirements in the milliseconds range |
Table 10.4: Linux OS kernel preemption – the available configuration options
The kernel/Kconfig.preempt kbuild configuration file contains the relevant menu entries for the preemptible kernel options. (As you will see in the following chapter, when building Linux as an RTOS, a fourth choice for kernel preemption, named CONFIG_PREEMPT_RT, appears.)
Wouldn’t it be nice if we could dynamically select the kernel-preemption behavior at boot? The following section shows you how!
The dynamic preemptible kernel feature
Section titled “The dynamic preemptible kernel feature”From the 5.12 kernel, a new dynamic preemptible kernel feature (CONFIG_PREEMPT_DYNAMIC) was introduced. Having this feature enabled allows you to tune the kernel’s preemption behavior (or mode) at boot by passing a kernel parameter (via the bootloader of course); it’s named preempt=.
The values that it can be set to are as follows (refer Table 10.4):
preempt=none: The kernel preemption behavior is the same asCONFIG_PREEMPT_NONE.preempt=voluntary: The kernel preemption behavior is close to that ofCONFIG_PREEMPT_VOLUNTARY.preempt=full[default]: The kernel preemption behavior is the same as that ofCONFIG_PREEMPT.
A typical intended use case is to allow distributions to ship one kernel binary image – built with CONFIG_PREEMPT, with (almost) full kernel preemption baked in – but be able to allow the end user to modify the kernel preemption mode at boot, thus allowing the user to select whether to run it as a typical server class system (with preempt=none), desktop (preempt=voluntary), or with full preemption enabled. This way, the distro (or product) doesn’t have to ship and maintain different kernel images to serve differing use cases.
The kernel config is named CONFIG_PREEMPT_DYNAMIC; setting it to y enables the feature. (To do so within the make menuconfig UI, go to General Setup | Preemption behaviour defined on boot. It’s a Boolean; turn it on, rebuild, and reboot, passing along the preempt=<value> parameter.)
FYI, uname -a as well as /proc/version will show this feature, if enabled (for example, I enabled it on a custom 6.1 kernel (on my Fedora VM)):
$ uname -aLinux fedora 6.1.25-onfc38 #4 SMP PREEMPT_DYNAMIC Wed Jul 26 21:49:07 IST 2023 x86_64 GNU/LinuxSuggested exercise: Enable CONFIG_PREEMPT_DYNAMIC on your 6.1 LTS custom kernel; build it, and then boot with different values for the preempt = kernel parameter (and verify that it’s been passed along by looking up /proc/cmdline).
Right, with that done, we will get back to some more details on the internal aspects. Let’s very briefly summarize some key points we’ve learned in the preceding sections. You learned that the core kernel scheduling code is anchored within the void schedule(void) function, a thin wrapper over the worker function, __schedule(), and that it iterates over the modular scheduler classes in priority order, ending up with a thread picked (by one of the underlying scheduling class’s code) to be context-switched to. All of this is fine; a couple of key questions now are: who exactly calls this “task scheduling” core code path, and when exactly is it run? (Precisely what was alluded to by the connector labelled “S” at the very top of Figure 10.9!) The following sections attempt to answer these questions; on, on!
Who runs the scheduler code?
Section titled “Who runs the scheduler code?”A subtle yet key misconception regarding how scheduling works is unfortunately held by many: we imagine that some kind of kernel thread (or some such entity) called the “scheduler” is present, which periodically runs and schedules tasks. This is just plain wrong; in a monolithic OS such as Linux, scheduling is carried out by the process contexts themselves, the regular threads that run on the CPU in kernel mode!
In fact, the scheduling code is always run by the process context that is currently executing the code of the kernel – in other words, by current (we covered what exactly current is back in Chapter 6, Kernel Internals Essentials – Processes and Threads, in the Accessing the task structure with current section).
This may also be an appropriate time to remind you of what we shall call one of the golden rules of the Linux kernel: the scheduler must never ever run in any kind of atomic context (which includes interrupt context).
In other words, atomic (literally, indivisible) and/or interrupt context code must be guaranteed to be non-blocking and atomic – it must run to completion without interruption. This is why you cannot call schedule(), as it doesn’t make any sense. (How can a code path be atomic when we put the caller to sleep? It can’t, so don’t call it.) Alternatively, as another example, calling kmalloc() with the GFP_KERNEL flag in any atomic context is wrong – as the GFP_KERNEL flag says it might block! But with the GFP_ATOMIC flag, it’s all right, as that instructs the kernel memory management code to never block.
It’s also important to realize that, in a preemptible kernel, kernel preemption is disabled while the schedule code paths run; this makes sense as well.
A quick summary of the key points learned here: the core task scheduling code on Linux – the code of [__]schedule() and all that it invokes – is run in process context by the process (thread, really) that’s going to kick itself off the CPU by ultimately context-switching to some other thread! And this thread is what? Why, it’s current, of course! (Relook at Figure 10.9 and Figure 10.11; the code paths there – except the last box at the bottom where the “next” thread runs on the core – will be run by current). Also, there’s a “rule”: never call schedule() in any kind of atomic context (which includes interrupt context).
But when does this occur, IOW, when exactly is schedule() invoked? Read on to find out…
I’ll understand if you find the following sections a bit dense on first reading… that’s okay. If you prefer, you could skim the details for now (and perhaps peek at the CPU scheduler entry points – a summary section to digest the summary). Come back to the details when you’re ready.
When does schedule() run?
Section titled “When does schedule() run?”The job of the OS scheduler is to arbitrate access to the processor (CPU) resources, sharing it between competing entities (threads) that want to use it. But what if the system is busy, with many threads continually competing for and acquiring and then relinquishing the processor(s)? More correctly, what we’re really getting at is this: in order to ensure fair sharing of the CPU resources between tasks, you must ensure that the policeman in the picture, the scheduler itself, runs periodically on the processor. Sounds good, but how exactly can you ensure that?
Here’s a (seemingly) logical way to go about it: have the OS hook into the timer chip’s interrupt at boot and, as part of the “housekeeping” done in the interrupt handler routine when the timer interrupt fires, invoke the scheduler! Now, (a bit simplistically) in contrast to what we’ve learned before, the timer interrupt “fires” CONFIG_HZ times a second.
So if we call schedule() here, it gets a chance to run CONFIG_HZ times a second (which is often set to the value 250 on x86_64 Ubuntu, and 1,000 on x86_64 Fedora)! Hang on, though, we learned a golden rule in Chapter 8, Kernel Memory Allocation for Module Authors – Part 1, in the Never sleep in interrupt or atomic contexts section: you cannot invoke the scheduler in any kind of atomic (including interrupt ) context (as was again just mentioned). So, going by this rule, we simply cannot invoke the scheduler code path within the timer interrupt (doing so would immediately lead to a kernel bug).
So what does the OS do? We’ll get to it, but first, we need to cover some basics on a structure called thread_info.
Minimally understanding the thread_info structure
Section titled “Minimally understanding the thread_info structure”To clearly understand the following points, you’ll need to know the basics regarding an arch-dependent per-thread data structure named thread_info. This structure is small, containing a few key “hotspot” members (that used to originally be within the task structure). The reason for this thread_info structure is the usual one – performance; looking up thread_info content is much faster than looking up the content of a large task structure, as it’s much smaller and is typically designed to fit within a single CPU cacheline. (Well, on both the x86_64 and AArch64 at least, this is the case: its size is just 24 bytes. Also, this structure’s leveraged in the calculation of current in the AArch32.)
The thread_info structure has a colorful placement history. In early Linux, it was a separate entity altogether; from 2.6 Linux, for 32-bit platforms (x86-32 and AArch32 at least), it lived within the kernel-mode stack of each thread. On more recent Linux versions (from 4.0 or 4.4) and for some arches, when CONFIG_THREAD_INFO_IN_TASK=y, it has become a member of the task structure itself (mostly due to security issues).
You can see the definition of thread_info for the x86[_64] at https://elixir.bootlin.com/linux/v6.1.25/source/arch/x86/include/asm/thread_info.h#L56 and for the AArch64 at https://elixir.bootlin.com/linux/v6.1.25/source/arch/arm64/include/asm/thread_info.h#L24.
For our immediate purposes, just one of the members of thread_info is meaningful – a bitmask: unsigned long flags. As you can guess, it’s a bitmask of various flag values (all in the style TIF_<FOO>, where TIF is an abbreviation for ‘thread_info flag’). You’ll find all the TIF_* flag macros defined here in the code base: https://elixir.bootlin.com/linux/v6.1.25/source/arch/x86/include/asm/thread_info.h#L76. Among the many flags that exist, the key one in our discussion on task scheduling is TIF_NEED_RESCHED. As will shortly be explained, if set, it implies the kernel “needs to reschedule ASAP”; if cleared, it doesn’t need to reschedule.
Another topic that tends to (occasionally) come up in these discussions is that of hardware interrupts and their handling (hardirqs and softirqs) on Linux. Again, the (free!) Linux Kernel Programming, Part 2 book, in Chapter 4, Handling Hardware Interrupts, covers these areas in depth; do check it out if you need to.
Right, now that you have understood these basics with regard to the thread_info structure, let’s jump back to our discussions! The “when” of the scheduling code path (schedule()) and everything it calls is divided into two parts: one, when is the TIF_NEED_RESCHED bit set?
And, two, when is the TIF_NEED_RESCHED bit checked? Let’s see:
- When is the “need-resched” (
TIF_NEED_RESCHED) bit set?
The thread_info.flags:TIF_NEED_RESCHED bit (this isn’t meant to be C code; it’s just to show the “need resched” bit conceptually), when set, is effectively akin to a red flag informing the kernel that (re)scheduling must be performed ASAP (in effect, current must be preempted now!). This flag can be set in the following contexts:
- (Timer) Interrupt housekeeping: On every timer interrupt (technically, in the timer
softirqcode path), scheduler-related “housekeeping” is performed; among the work done here, a key question is: doescurrentneed to be preempted? If yes, set theTIF_NEED_RESCHEDbit. (Caution: only the bit’s set;schedule()isn’t called here, as that’s not allowed.) - Task awakening: When a task’s awoken, it’s enqueued in an appropriate runqueue; now, if it’s determined that it must preempt
current, set thethread_info.flags:TIF_NEED_RESCHEDbit. - When is the “need-resched” (
TIF_NEED_RESCHED) bit checked?
Scheduling Opportunity – Process context recognition: Have current check for the thread_info.flags:TIF_NEED_RESCHED bit being set at certain well-designed process context “opportunity points”; if the bit’s set, invoke the schedule code path; otherwise, continue as usual.
Did you notice? In both the (Timer) Interrupt housekeeping and the Task awakening cases, even if we run in interrupt context, nothing goes wrong. This is because we do not invoke schedule() here and now; we merely set the TIF_NEED_RESCHED flag to inform the kernel that we need to reschedule ASAP, and that a reschedule must occur at the next available “opportunity point”! We expand on this discussion in the following few sections.
The timer interrupt housekeeping – setting TIF_NEED_RESCHED
Section titled “The timer interrupt housekeeping – setting TIF_NEED_RESCHED”Within the timer interrupt (in the code of kernel/sched/core.c:scheduler_tick(), wherein interrupts are disabled on the local core), the kernel performs the meta-work (the housekeeping) necessary to keep scheduling running smoothly; this involves the constant updating of the per - CPU runqueues as appropriate, task load balancing work, and so on. Please be aware that the actual schedule() function is never called here. At best, the scheduling class hook function (for the process context current that was interrupted), sched_class:task_tick(), if non-null, is invoked (refer Figure 10.13). For example, for any thread belonging to the fair (CFS) class, the update of the vruntime member (the virtual runtime), and the (priority-biased) time spent on the processor by the task is done here, in the hook function named task_tick_fair().
More technically, all this work described in the preceding paragraph, the code of scheduler_tick(), runs within the timer interrupt softirq code path, TIMER_SOFTIRQ.
Now (besides the other sched-related housekeeping), while within this timer interrupt (softirq) context, we must decide: does current needs to be preempted or not? This key decision is made by checking the following conditions and preempting current if any of them are true:
- Has
currentexceeded its time quantum? Furthermore, is it exceeded by a large-enough threshold to its neighbor? This is precisely what the tunable (or sysctl)/sys/kernel/debug/sched/min_granularity_nsholds; it’s the effective CFS timeslice. The defaults vary (it’s 3 ms on x86_64 Ubuntu 22.04, and 2.25 ms on Fedora 38/39. As a quick reminder, we covered information on this, the effective CFS timeslice, in the A note on the CFS scheduling period and timeslice section). - Does a newly born and run, or recently woken, task (on this CFS runqueue) have superior priority to
current? - Does the CFS rb-tree have a task with a lower
vruntimethancurrent(in other words, iscurrentno longer the leftmost leaf node on this tree)?
(Thinking about it, the first and third points are quite alike; if the time quantum is exceeded, it’s very likely the vruntime value would have increased to the extent that it’s no longer the left-most leaf node in the runqueue.)
Let’s say the kernel code paths just described have decided that a new task deserves the CPU more; then what? Does it call schedule()? No! As just explained above, we can’t call schedule() in interrupt context. The kernel now merely “marks” the fact that we need to reschedule as soon as is feasible, at the “next scheduling opportunity point,” by setting a “global” flag – the thread_info->flags ‘s TIF_NEED_RESCHED bit. (The reason we put the word global within quotes is that it’s not really a kernel-wide global; it’s actually simply a bit within the current instance’s thread_info->flags bitmask, named TIF_NEED_RESCHED. Why? It’s faster to access the bit that way rather than via a global!) Furthermore, it bears keeping in mind that if a newborn or recently woken task needs to be scheduled, it is placed into an appropriate runqueue, and it isn’t run just yet; it will run in the near future when the next scheduling opportunity arrives.

Figure 10.13: A conceptual diagram showing the setting of the thread_info->flags.TIF_NEED_RESCHED bit within the context of the timer softirq
Figure 10.13 shows this in a conceptual fashion. When the timer interrupt (or IRQ) fires, the fast-and-small so-called top-half or hardirq handler portion runs, very quickly performing its work; when done, the kernel invokes the timer bottom-half or softirq handler (the left portion of Figure 10.13). Here, a portion of work is the timer housekeeping tasks, as already described. We show the CFS rb-tree conceptually, with node x representing the left-most leaf node and c being the node representing current (the middle portion of Figure 10.13). So, in this diagram, current isn’t the left-most leaf node any longer (implying that its vruntime value is higher than that of x). The code in the timer (scheduler-related) housekeeping code paths detects this case and sets the TIF_NEED_RESCHED bit (ti is the abbreviation for thread_info, which, in modern Linux, is within the task structure, as the right portion of Figure 10.13 shows).
The other place where similar checks are made is when a task is awoken. When this occurs, it’s dequeued from the wait queue it was on and enqueued in a CPU runqueue. Now, if it’s found that the recently woken task (on that core:runqueue) must preempt current (due to it having superior priority, less vruntime, or whatever), the TIF_NEED_RESCHED bit is set. (We discuss this case in more detail in the upcoming CPU scheduler entry points – a summary section.)
It’s also worth emphasizing that, in the typical (likely) case, when running the timer softirq code paths, there will typically be no need to preempt current, and thus there is no need to set the thread_info.flags:TIF_NEED_RESCHED bit; it will remain clear. If set, scheduler activation will occur soon, but when exactly? Do read on…
The process context part – checking TIF_NEED_RESCHED
Section titled “The process context part – checking TIF_NEED_RESCHED”One side of the coin, the just-described timer interrupt (softirq) portion of the scheduling housekeeping work, where it possibly sets the thread_info:TIF_NEED_RESCHED bit to “signal” to the kernel that the schedule code should be called as soon as possible, is continually carried out, as the system runs.
The other side of the coin is checking or recognizing whether this bit is set and invoking schedule() if so; this latter portion – the invoking of schedule() – is, note carefully:
- performed in process context only, and
- only at certain specific “opportunity points” that are sprinkled throughout the kernel code paths
The following are the typical so-called opportunity points where thread_info->flags.TIF_NEED_RESCHED is checked (often via the need_resched() helper):
- On return from the system call code path.
- On return from the interrupt code path.
- In general, any switch from non-preemptible to preemptible mode within the kernel is an opportunity point (when
preempt_enable()is called). A typical one is when a spinlock is unlocked.
So, think about it: every time any thread running in user space issues a system call, that thread is (context-) switched to kernel mode and then runs code within the kernel, with kernel privilege (this is the monolithic kernel design). Of course, system calls are finite in length; when done, there is a well-known return path that they will follow in order to switch back to user mode and continue execution there.
On this return path in the kernel, a scheduling opportunity point is introduced: a check is done to see whether the TIF_NEED_RESCHED bit (within the thread_info structure’s flags member) is set. If yes, the scheduler is activated, by having the process context call schedule().
The other places where schedule() can be invoked are:
- Any explicit (or implicit) call to
schedule()(e.g. when a blocking call’s issued) - Any calls to
cond_resched*()functions can result inschedule()being invoked.
Obviously, an explicit or implicit invocation of schedule() while in the process context will trigger it being run. Further, the kernel provides a few “conditional schedule” APIs (like cond_resched()), allowing, say, a driver to check: am I eating up too much CPU? If so, yield… They lead to schedule() being invoked as and when required (in effect, only if the current->ti->flags.TIF_NEED_RESCHED bit is set).
Regarding the return-from-kernel-to-user-mode code path, here’s the flow that activates the scheduling code path:
#define EXIT_TO_USER_MODE_WORK \ (_TIF_SIGPENDING | _TIF_NOTIFY_RESUME | _TIF_UPROBE | \ _TIF_NEED_RESCHED | _TIF_PATCH_PENDING | _TIF_NOTIFY_SIGNAL | \ ARCH_EXIT_TO_USER_MODE_WORK)Notice that it’s not just for scheduling that the kernel can prepare to switch back to user mode; it includes several other things that it must take care of (in effect, this is an opportunity point for even these other things – like handling pending signals, uprobes, kernel live patching, and more). If any of the above bits are set, the EXIT_TO_USER_MODE_WORK macro returns True; the kernel then sets up for the exit-to-user-mode and calls schedule(); here’s the code view:
kernel/entry/common.cstatic void exit_to_user_mode_prepare(struct pt_regs *regs){ … ti_work = read_thread_flags(); if (unlikely(ti_work & EXIT_TO_USER_MODE_WORK)) ti_work = exit_to_user_mode_loop(regs, ti_work);[ … ]static unsigned long exit_to_user_mode_loop(struct pt_regs *regs, unsigned long ti_work){ /* * Before returning to user space ensure that all pending work * items have been completed. */ while (ti_work & EXIT_TO_USER_MODE_WORK) { local_irq_enable_exit_to_user(ti_work); if (ti_work & _TIF_NEED_RESCHED) schedule(); [ … ] if (ti_work & (_TIF_SIGPENDING | _TIF_NOTIFY_SIGNAL)) arch_do_signal_or_restart(regs); [ … ]Similarly, the same can occur after handling an (any) hardware interrupt (and any associated softirq handlers that needed to be run). While handling any hardware interrupt, the kernel is of course set to be non-preemptible; but once the handling’s done, it’s reset back to be preemptible. Here lies an opportunity point: the kernel checks the TIF_NEED_RESCHED bit, and if it is set, schedule() is invoked. (By the way, the same opportunity arises when a spinlock is unlocked, as then, the kernel is set to be preemptible!)
The following diagram (Figure 10.14) attempts to conceptually show this work in action. The top portion (points 1A to 5A; read them sequentially to follow what occurs) shows the checking of the TIF_NEED_RESCHED bit in the “return from system call” code path opportunity point; the bottom portion (points 1B to 3B) shows the “hardware interrupt (hardirq) return path opportunity point”:

Figure 10.14: A conceptual diagram showing the checking of the TIF_NEED_RESCHED bit within the context of both the process-driven system call return path and the IRQ return path opportunity points
CPU scheduler entry points – a summary
Section titled “CPU scheduler entry points – a summary”Here, we summarize the preceding discussions on the setting and recognition of the TIF_NEED_RESCHED bit; in effect, we precisely answer the questions of when exactly schedule() is entered, or when exactly scheduling is activated (relooking at Figure 10.9, Figure 10.13,and Figure 10.14 can be useful while reading this); so, schedule() is invoked (or the core scheduler activated):
- When any explicit blocking call is made by a process/thread: this makes sense. Blocking APIs end up calling
schedule(), as the caller is required to wait on some event (when that event arises, the kernel (or driver that put it to sleep), will awaken it). - User-mode preemption from timer housekeeping: if any of the three conditions described in the The timer interrupt housekeeping – setting TIF_NEED_RESCHED section come true; let’s quickly restate them (see Figure 10.13):
- Has
currentexceeded its time quantum (it’s effective timeslice) by a sufficient amount (the valuemin_granularity_ns)?- Does a newborn, or recently woken, task have superior priority to
current(the task currently executing the kernel code paths)? - Does the CFS rb-tree have a task with a lower
vruntimethancurrent(in other words, iscurrentno longer the left-most leaf node on this tree)?
- Does a newborn, or recently woken, task have superior priority to
- Has
- Timer (softirq) housekeeping: check if the
TIF_NEED_RESCHEDbit needs to be set (the check is carried out in the timer softirq context functionscheduler_tick(); see Figure 10.13). Note that theTIF_NEED_RESCHEDbit can be set here butschedule()will never be invoked here. - A summary of all so-called “opportunity points”: here, we check whether the
TIF_NEED_RESCHEDbit is set. The following are the “opportunity points” where the check’s carried out in the process context (see Figure 10.14):- On the system call return path
- On the interrupt return path
- On the system call return path
- Other points where scheduling’s activated (a bit of repetition here):
- any call to
schedule()- any
cond_resched*()calls that can result inschedule()being invoked - (in general, any switch from non-preemptible to preemptible mode within the kernel).
- any
- any call to
- Wakeups occurring: this scenario has a task added to a runqueue. Must this task preempt
current? If yes, setTIF_NEED_RESCHED, and invokeschedule()at the next opportunity point:- In a preemptible kernel: at any kernel preemption point (in effect, anytime
preempt_enable()is called – for example, a spinlock being unlocked):- in any system call, when returning
- in any hardware interrupt, when returning
- In a preemptible kernel: at any kernel preemption point (in effect, anytime
- In a non-preemptible kernel, at the next:
- return from system call to user space
- return from interrupt to user space
- any
cond_resched*()calls - any explicit call to
schedule()
- return from system call to user space
The detailed comments present just before the core kernel scheduling function kernel/sched/core.c:__schedule() are well worth reading through; they specify all the possible entry points to the kernel CPU scheduler (as we’ve just learned). For the 6.1 kernel code base, you’ll find them here; do take a look: https://elixir.bootlin.com/linux/v6.1.25/source/kernel/sched/core.c#L6396.
The core scheduler code in brief
Section titled “The core scheduler code in brief”As stated earlier, always keep in mind that the scheduler code is being run in process context by the process (the thread, really) that’s going to kick itself off the CPU by ultimately context-switching to some other thread! And this thread is what? Why, it’s current, of course!
The __schedule() function has (among others) two local variables, pointers to struct task_struct named prev and next. The pointer named prev is set to rq->curr, which is nothing but current! The pointer named next will be set to the task that’s going to be context-switched to and that’s going to run next! So you see, current runs the scheduler code, calling itself the previous task, performing the work of running the pick-next-task for that modular scheduling class (the scheduling algorithm in effect), and then kicking itself off the processor by context-switching to next! Again, it’s worth relooking at Figure 10.9, realizing that the code paths there – except for the last box at the bottom where the “next” thread runs on the core – are run by none other than current!
A few snippets from the core scheduling code follow (with annotations << like this >> reiterating the points we have discussed): https://elixir.bootlin.com/linux/v6.1.25/source/kernel/sched/core.c#L6435.
static void __sched notrace __schedule(unsigned int sched_mode){ struct task_struct *prev, *next; unsigned long *switch_count; unsigned long prev_state; struct rq_flags rf; struct rq *rq; int cpu; cpu = smp_processor_id(); rq = cpu_rq(cpu); prev = rq->curr; << this is current ! >> [ ... ] next = pick_next_task(rq, prev, &rf); << Here we 'pick' the task to run next in an 'object- oriented' manner, as discussed earlier in detail... >> clear_tsk_need_resched(prev); clear_preempt_need_resched(); [ ... ] if (likely(prev != next)) { << switching to another thread's likely… >> [ ... ] /* Also unlocks the rq: */ rq = context_switch(rq, prev, next, &rf); [ ... ]}A quick word on the actual context switch follows.
The context switch
Section titled “The context switch”To finish this chapter, let’s take a quick look at the (CPU scheduler) context switch. The job of the context switch (in the context of the CPU/task scheduler) is quite obvious: before simply switching to the next task, the OS must save the state of the previous, that is, the currently executing task (in other words, the state of current). The task structure holds another structure embedded within it to store/retrieve the thread’s hardware context; it’s the member struct thread_struct thread (on the x86, it’s always the very last member of the task structure).
In Linux, an inline function, kernel/sched/core.c:context_switch(), performs the job of context-switching; you will by now realize of course that its code is run by current, which is considered to be the “previous” task. It performs the work of switching from the prev task (from current) to the next task, the winner of this scheduling round or preemption battle. This context switch is essentially performed in two, very arch-specific, stages:
- The memory (MM) switch: Switch an arch-specific CPU register to point to the memory descriptor structure (
struct mm_struct) ofnext. On the x86[_64], this register is called CR3 (Control Register 3); on ARM (AArch32), it’s called the TTBR0 (Translation Table Base Register 0) register. Why? Because it’s from themm_struct, where the kernel can “see” the entire memory picture of the process, including, importantly, the pointer to the base of its paging tables; setting this pointer correctly will thus make the MMU refer tonext‘s paging tables when it performs address translation asnextexecutes! - The actual CPU switch: Switch from
prevtonextby saving the stack and CPU register state ofprevand restoring the stack and CPU register state ofnextto the processor; this is done within theswitch_to()macro. This will havenextresume processing precisely where it left off…
A more detailed implementation of the context switch is not something we shall cover here; do check out the Further reading section for more resources.
Finally, something very interesting: the kernel provides a way to isolate a given set of processors from disturbances – in effect, from the effect of scheduler classes and SMP load balancing! This is achieved by specifying a kernel parameter, isolcpus=[flag-list,]<cpu-list>.
The flag-list defaults to domain; when specified – and as default – all CPU cores in the cpu - list specified are isolated from “the general SMP balancing and scheduling algorithms.” (This tends to be useful for some types of real-time applications.)
Hang on a moment though: the isolcpus = kernel parameter is now considered deprecated; in its place, you’re advised to leverage the more powerful and flexible cpusets cgroups (v2) controller instead. Worry not – we shall cover many details on cgroups in the coming chapter.
Summary
Section titled “Summary”In this chapter, you learned about several areas and facets of the versatile Linux kernel’s CPU (or task) scheduler. Firstly, you saw how the actual KSE is a thread and not a process. We also learned that, in a monolithic OS like Linux, there is no “scheduler” thread within the kernel: scheduling is performed by a process context thread – the current thread – running the scheduling code paths, itself context-switching to the next task when done (thereby kicking itself off the processor – of course, the timer interrupt softirq housekeeping code paths have a key role to play in scheduler-related housekeeping as well!).
We then gained an appreciation of the available scheduling policies that the OS implements. Next, you understood that to support multiple CPUs in a superbly scalable fashion, the kernel powerfully mirrors this with a design that employs one runqueue per CPU core per modular scheduling class (again, the cgroups framework implies there’s more to this, as we’ll learn later). How to query any given thread’s scheduling policy and priority, and more in-depth details on the internal implementation of the CPU scheduler, were then covered. We focused on how the modern scheduler leverages the modular scheduling class design, who exactly runs the actual scheduler code (current!) and when, and ended with a brief note on the internal code implementation of the core scheduling code and the context switch.
The next chapter continues on this very interesting journey, gaining more insight into and details about the inner workings of the kernel-level CPU scheduler. I suggest you first fully digest this chapter’s content, work on the questions and exercises given, and then move on to the next chapter. Great going! Let’s schedule the next session soon!
Questions
Section titled “Questions”As we conclude, here is a list of questions for you to test your knowledge regarding this chapter’s material: https://github.com/PacktPublishing/Linux-Kernel-Programming_2E/blob/main/questions/ch10_qs_assignments.txt. You will find some of the questions answered in the book’s GitHub repo: https://github.com/PacktPublishing/Linux-Kernel-Programming_2E/tree/main/solutions_to_assgn.
Further reading
Section titled “Further reading”To help you delve deeper into the subject with useful materials, we provide a rather detailed list of online references and links (and, at times, even books) in a Further reading document in this book’s GitHub repository, available here: https://github.com/PacktPublishing/Linux-Kernel-Programming_2E/blob/main/Further_Reading.md.