Scheduling? I am familiar with it. Do we often hear it. Yes, we have heard of scheduling, such as traffic control scheduling. No, this is hot in summer, and the slogans are well pasted: It's awkward to be a civilized citizen in China's power grid dispatching system! No. If you still don't understand it, let's talk about it again, go home in the new year, and go home with the beautiful GF, and even get a scalper ticket for an ordinary hard-seat ticket, what do you say in your mouth: XX, what train station, what Spring Festival scheduling! Alas, this time you mentioned it.
To sum up, scheduling is to achieve the maximum effect of system resources through reasonable scheduling of the scheduling program. This is exactly the result of multi-process concurrency. In fact, the principle is not complex at all, and the principle is as simple as that: as long as the process can be executed, there will always be processes being executed. However, simple problems will also be complicated. For example, if we buy a ticket and complain about scheduling, we will be grateful for the man-sea tactics of the year. (to say more, there are actually a lot of real problems. One man-sea tactic will solve all of them, this tactic is the most handy for Chinese people ). Normally, the number of processes in the system is always more than the number of processors, so competition is inevitable, and the scheduling problem is concentrated on solving the competition problem.
There are not many types of problems: preemption and non-preemption. Linux provides a preemptible multi-task mode. In the next stage, the scheduler determines who gets the CPU execution time. How can we decide whether to invite a visitor or drink. Sorry, I am open-source and fair to everyone. I have my own set of principles (strategy. Let's talk about it later ). The above process is called preemption, and the process obtains the CPU execution opportunity. This time is called a time slice, which is defined by the system. Later we will see that the linux scheduler uses the dynamic method to calculate the time slice. If you say "preemption" or "non-preemption", it means that no one will compete with you. Unless you give up, you can run it on your own. The process voluntarily gives up and suspends itself. This kind of mechanism seems very harmonious (Don't be harmonious), but there are many problems, such as the system does not know how long each process takes to execute. And once a suspension process does not want to or forget to make concessions, the system will collapse, my money, my future, and my lover will never go forever.
After talking about that, I started my topic. Principles, everything has principles, linux principles. Before starting the principle, let's look at the process we mentioned earlier. In fact, the process is far less simple than it was previously. There are also types of processes, at least IO and CPU. IO refers to the process that spends most of its time submitting I/O requests or waiting for I/O requests. Such a process is annoying. It usually runs for a while, because it always blocks when waiting for more I/O requests. It corresponds to a CPU-type process. Such processes put most of their time on code execution. Unless they are preemptible, they have been greedy for running. Because they do not have too many IO requests. Because they are not I/O drivers, there is no issue of user interaction (I/O drivers refer not only to disks, but also to the keyboard and mouse). In terms of system interaction response speed, the scheduler should not run them frequently. That is, they can reduce their running frequency and prolong their running time. The principle mentioned here is that the scheduling policy should make a difficult decision between rapid process response (short response time) and high process throughput. This principle is sometimes unfair and cruel. It is cruel and hard to understand. If you do not know low priorities, it is sometimes unfair. Because interactive processes are IO-type processes, the scheduling policy is skewed to IO-type for linux to ensure interactive applications.
As mentioned above, the most basic type of scheduling algorithm is priority-based scheduling. Relatively simple: the task runs first with a higher priority, and the task runs in rotation mode with the same priority. A process with a higher priority takes a long time. The scheduler always selects the process with the highest priority and the time slice is not used up. This statement means that users and systems can respond to System Scheduling by setting the priority of processes. Based on this, linux designs a dynamic priority scheduling method. First, set a basic priority for the process. However, it allows the scheduler to add or remove priorities as needed. The Linux Kernel provides two sets of independent priority ranges. The first is the nice value, which ranges from-20 to 19. The default value is 0. The larger the nice value, the smaller the priority. In addition, the nice value is also used to determine the length of the time slice allocated to the process. The second range is the real-time priority. The default range is from 0 to 99. Any real-time priority is higher than the normal priority. Let's talk about this later.
Speaking of so many time slices, it is not difficult to say. It is not difficult to make it clear. A time slice is a numerical value that indicates the duration for a process to continue running before being preemptible. The default time slice is 20 ms, which is short. The linux scheduler can dynamically adjust the time slice assigned to the scheduler based on the priority of the process. In particular, a process does not have to use all the time slices allocated to it at a time. Once the time slice of the process is exhausted, the process is deemed to have expired. A process without a time slice will no longer run. Unless other processes consume their time slices, the time slices of all processes will be recalculated.
When a process enters the TASK_RUNNING status, the kernel checks whether the priority of the process is higher than that of the currently running process. If yes, the scheduler will be awakened and re-select a new process for execution (the process that has just entered the running state in the form of a book ). In addition, when the time slice of a process changes to 0, it will be preemptible, And the scheduler will be awakened to select a new process. (For specific examples, refer to Chapter 3.1.5 on page p28 of the book)
The scheduling program in linux is defined in kernel/sched. c. The scheduling program in the 2.6 kernel is very different from that in the past, as shown below:
1. Fully implement O (1) scheduling. This should be understandable.
2. As a multi-core processor today, linux is not outdated, fully implementing SMP scalability. Each processor has its own lock and its own executable queue
3. Enhance SMP affinity. This is a description of the CPU affinity of multiple cores. I am currently studying this. I will detail it in a blog post later.
4. Enhance interaction capabilities.
5. ensure fairness.
6. Although the most common optimization condition is that only 1 ~ Two processes that can run, but the optimization is also fully capable of scaling to a system that has multiple processors and runs multiple processes on each processor. |
The second executable queue is the most basic data structure in the scheduler. It is defined in kernel/sched. c and is represented by the runquene structure. It is a linked list of executable processes on a given processor. Each processor maintains one. Each process that can be put into operation is unique to an executable queue. In addition, the executable queue also contains the scheduling information of each processor. The specific structure is not provided here. You must have the ability to view the source code. Macro cpu_rq (processor) is used to return the pointer to the executable queue of the given processor. this_rq () is used to return the executable queue of the current processor. task_rq (task) returns the queue pointer of the given task.
When its owner reads or modifies its queue members, the locks contained in the queue can be executed to prevent the queue from being changed by other code. Because each executable queue uniquely corresponds to one processor, therefore, it is rare that one processor needs to lock the executable queues of other processors, but this situation exists. The most common situation is when a specific task is executed in the running queue. In this case, the task_rq_lock () and task_rq_unlock () functions need to be used, or this_rq_lock () can be used to lock the current executable queue and rq_unlock (struct runqueue * rq) release the lock on the given queue. About the lock operation, we floated over again. Why? On the one hand, this is beyond the focus of this section. I have made a detailed description of how to add and unlock the two in the linux driver theory post. I will discuss the three in detail later. So, that sentence is really too truth: temporarily put down, is to pick up again.
From the structure of the running queue, we found two arrays related to priority (defined in kernel/sched. in c, the name is prio_array. Let's take a look at it.): active and past. These two arrays are the data structures that implement the O (1)-level algorithms. The priority array enables each type of priority of the processor to contain a corresponding queue, which contains the list of executable processes with the corresponding priority. The priority bitmap in the structure is designed to help improve the efficiency of searching executable processes with the highest priority in the current system. For the defined constants in the structure, MAX_PRIO defines the number of priorities owned by the system. The default value is 140, and BITMAP_SIZE is the size of the Priority bitmap array. The value is 5, which can be calculated. For example, the bitmap array is of the unsigned long type and has a length of 32 bits. Assume that each bits represent a priority (4*32 = 128 <140 ), five such long integers are required for representation. Therefore, bitmap exactly contains five array items.
At the beginning, all bits of Bitmap members are cleared to 0. When a priority process starts to prepare for execution, the corresponding bits in the bitmap are set to 1, the highest priority in the search system becomes the first priority set in the search bitmap. Given the fixed value of the number of priorities, the search time is not affected by the number of executable processes in the system. The corresponding function for the bitmap quick search algorithm is sched_find_first_bit ().
The list_head queue of the Priority array is a linked list, which contains all runnable threads with the corresponding priority on the processor. To locate the next task to run, select the next element from the linked list. For a given priority, the task is scheduled in rotation mode. The nr_active counter of the Priority array, which saves the number of executable processes in the priority array.
Next, I mentioned the topic of time slice over and over again. What happens if all the time slice of all processes is used up? You can't go down the system, fortunately, the operating system provides an explicit method to recalculate the time slice of each process. A typical example is to access each process cyclically. Here is an example of borrowing a book:
For (each task in the System ){
Recalculate priority
Recalculate the time slice
} |
This method is simple, but has many drawbacks:
1. It may take quite a long time.
2. The lock mechanism must be used to protect the task queue and the descriptor of each process. This will obviously aggravate lock contention and affect system performance.
3. The timing of recalculating the time slice is uncertain.
4. The implementation looks rough. |
Now we use a new scheduling method. Each processor has two priority arrays mentioned above. The processes in the active array have time slice surplus, and the processes in the expired array consume time slice, when a process's time slice is exhausted, it will move to the expired array, but before that, the time slice has been re-computed for it, and re-computing the time slice is now very simple, you only need to switch back and forth between the activity and the expired array. Because arrays are accessed through pointers, the time required to exchange them is the time required to exchange pointers. This action is completed by schedule:
Struct prio_array * array = rq-> active;
If (! Array-> nr_active ){
Rq-> active = rq-> expired;
Rq-> expired = array;
} |
This exchange is the core of O (1)-level scheduling programs. The O (1)-level scheduler does not need to re-calculate the time slice from start to end. It only needs to complete one or two steps to switch the array, this solution perfectly solves all the drawbacks listed above. The linux scheduler is implemented in the schedule () function. When the kernel code wants to sleep, it will directly call this function. If any process is preemptible, it will also be invoked for execution. The first step of scheduling is to determine who is the process with the highest priority:
Struct task_struct * prev, * next;
Struct list_head * queue;
Struct prio_array array;
Int idx;
Prev = current;
Array = rq-> active;
Idx = sched_find_first_bit (array-> bitmpa );
Queue = array-> queue + idx;
Next = list_entry (queue-> next, struct task_struct, run_list ); |
Analyze the code above. First, find the first bit in the activity priority array, which corresponds to the highest executable process. Then, the scheduler selects the first process in the list of levels. This process is the executable program with the highest priority in the system and will be scheduled immediately. The prev and next parameters in the preceding section indicate that the selected process is not the current process. In this case, you must call context_switch to switch the process. The last point is that there are no factors that affect the length of schedule (), because the front side says that the time used is constant.
The front side has said many times that the scheduler uses Priority and time slice to make a decision. Next let's take a look at the implementation method of the actual code. The process struct tells us that the process has an initial priority, called the nice value. The lowest priority is 19 and the highest priority is 20. The static_prio field of the struct stores this value, static means that this is specified by the user at the beginning and cannot be changed. The Dynamic Priority used by the scheduler is expressed in the prio field. The relationship between the two is calculated by a function about static priority and process interaction. What is process interaction? This is a new word. For the first time, let's talk about the difference between I/O consumable and CPU consumable processes. process interaction refers to IO consumable processes, the interaction with the user means that the computer IO interacts with the user, such as the mouse and keyboard. But how can we determine the interaction strength of a process? The most obvious criterion is to predict the duration of computing process sleep. The process that is sleeping most of the time is of course IO-consuming. If a process spends almost all its time on CPU execution, it will not be said. In linux, The sleep_avg field in the value tast_struct records the time for a process to sleep and run, ranging from 0 ~ MAX_SLEEP_AVG. The default value is 10 ms. When a process resumes from sleep to execution, sleep_avg increases to the maximum value based on its sleep duration. On the contrary, if a process does not run a clock cycle, sleep_avg will decrease accordingly until 0. This method not only rewards highly interactive processes, but also punishes time-consuming processes of the processor. In addition, rewards and punishments are based on the nice value as the base, and all users can adjust program scheduling by changing the nice index. The effective_prio () function returns the Dynamic Priority of a process. This function is based on the nice value, plus the interactive process reward points from-5 to + 5 we mentioned above.
Once the above dynamic priority is reached, it is much easier to recalculate the time slice. In addition, when a process is created, the newly created sub-process and parent process share the remaining time slice of the parent process. Such distribution is very average and prevents users from constantly capturing time slices by creating new processes. The task_timeslice () function returns a new time slice for a given task. To calculate a time slice, you only need to scale the priority in proportion so that it can meet the Numerical range requirements of the time slice. The maximum time slice length (MAX_TIMESLICE) obtained by the process with the highest priority is 200 ms, and the minimum time slice (MIN_TIMESLICE) is 10 ms. By default, the time slice length obtained by a process with a priority (nice value of 0 without interactive rewards and penalty scores) is 100 ms. As mentioned above, when the time slice of processes in the executable queue in the active array is exhausted, it will be transplanted to the expired array. However, if a process is highly interactive and particularly interactive, the scheduler supports another mechanism to support such interactive processes: when the time slice is used up, it will be placed in the activity array instead of the expired array. Recall the implementation mechanism of the O (1) scheduler above: After the process uses up its time slice, it will be moved to the expired array. When there are no remaining processes in the active array, in this case, the two arrays will be exchanged. However, before such exchange, a highly interactive process may already be in an expired array. When an interactive process is required, the array interaction may not have occurred, therefore, interaction cannot be performed. In this case, re-inserting a process with a particularly strong interaction into the active array can avoid this problem. Note: although it is put back to the activity array, it will not run immediately and it will run in turn with other processes with the same priority. This logic is implemented in scheduler_tick (), and the function will be called by the timer. See the following implementation code:
Struct task_struct * task = current;
Struct runqueue * rq = this_rq ();
If (! -Task-> time_slice ){
If (! TASK_INTERACTIVE (task) | (EXPIRED_STARVING (rq )))
Enqueue_task (task, rq-> expired );
Else
Enqueue_task (task, rq-> active );
} |
This code first reduces the value of the process time slice. Macro TASK_INTERACTIVE mainly checks whether the process is highly interactive based on the nice value of the process. The macro EXPIRED_STARVING is responsible for checking whether the processes in the expired array are in the hunger State and whether array exchange has not occurred for a long time. If the switchover has not occurred recently, placing the current process in the active array will further delay the switchover. The processes in the expired array will become increasingly hungry. as long as this happens, the process will be reset in the active array; otherwise, the process will be placed in the expired array.
I don't need to talk about sleep. The kernel processes sleep in the same way: the process marks itself as sleep, removes itself from the executable queue, puts it in the waiting queue, and then calls schedule () select and execute another process. The wake-up process is the opposite. One thing to understand is that even if you sleep, there are two process states: TASK_INTERRUPTIBLE and TASK_UNINTERRUPTIBLE. If the former receives a signal, it will be awakened in advance and respond to the signal, and the latter ignores the signal. The two processes are located in the same waiting queue (wake_queue_head_t), waiting for some things and cannot run. For more information about waiting queues, skip this step (I have already talked about it in the Linux driver development theory post and read it myself). Now, the recommended sleep operations in the kernel are much more complicated than before, but more secure:
1. Call DECLARE_WAITQUEUE () to create an item waiting for the queue.
2. Call add_wait_queue () to add the user to the class with a pair column.
3. Change the Process status to TASK_INTERRUPTIBLE or TASK_UNINTERRUPTIBLE.
4. Check whether the conditions are true. If yes, there is no need to sleep. If it is not true, schedule () is called ().
5. When the process is awakened, it checks again whether the condition is true. If yes, it will exit the loop. If not, it will call schedule () again and repeat this step.
6. when the conditions are met, the process sets itself as TASK_RUNNING and calls remove_wait_queue to remove itself from the waiting queue. |
If the conditions have been met before the process starts to sleep, the loop will exit and the process will not mistakenly enter sleep. If sleep is enabled, wake up is performed through wake_up. She wakes up all processes in the specified waiting queue. It calls try_to_wake_up, which sets the process to the TASK_RUNNING status, and CALLS active_task () to put the process into the executable queue, if the priority of the wake-up process is higher than that of the process currently being executed, set the need_resched flag. Programming skills, which code usually leads to the waiting condition fulfillment, it is responsible for subsequently calling the wake_up function. Note: There is a false wake-up. Sometimes the process is awakened not because the conditions it is waiting for have been met, so a loop processing is required to ensure that the conditions it waits for truly arrive.
Start a new problem. Now on the market, if you say single-core CPU, you have no face to face. What is the current era? multi-core era? Look, I have core i7 (quad-core ), my server lab platform is 8 cores. What does it have to do with me? What does it have to do with what I'm talking about today. The relationship is too big. As mentioned earlier, the linux scheduler has prepared separate executable queues and locks for each processor of the symmetric multi-processor system. For efficiency considerations, the entire scheduling system is independent from each processor. So what should we do? One processor has five processes, and the other processor has only one process in the queue. At this time, it is obvious that the system load is not balanced. What should I do? It is implemented by the Server Load balancer program (the load_balance of kernel/sched. c ). It has two call methods. When schedule is executed, it will be called as long as the current executable pair column is empty. In addition, it is also called by the timer, which is called every 1 ms when the system is idle or in other cases every Ms. In a single system, it will not be called, or even compiled into the kernel, because there is only one executable queue, there is no need to balance the load. When load_balances is called, the executable queue of the current processor needs to be locked and interrupted to avoid concurrent access to the executable queue. The steps are as follows:
1. load_balance () calls find_busiest_queue (), finds the busiest executable Queue (the maximum number of processes), and returns this queue. If no process in the executable queue exists
The number of queues is 25% or more than 25%. It returns NULL, and load_balance also returns.
2. load_balance selects a priority array from the busiest running queue to extract processes. It is best to use an expired array. If the expired array is empty, you can only select an active array.
3. load_balance finds the linked list with the highest priority of processes, because it is the most important to scatter the processes with the highest priority.
4. All the processes with the same priority found in the analysis will not be executed, nor will they be moved due to processor relevance, and will not be in the cache. For example
If yes, pull_task is called to extract it from the busiest queue to the current queue.
5. As long as the number of executable queues is still unbalanced, repeat the above two steps to eliminate the imbalance. Then, unlock the current running queue and return from load_balance
Back. |
The context switch we will refer to later is to switch from an executable process to another executable process, which is handled by the context_switch function defined in kernel/sched. c. Schedule calls this function whenever a new process is selected to be ready for running. It mainly completes the following two tasks:
1. Call the switch_mm () defined in include/asm/mmu_context.h. This function is responsible for switching the virtual memory from the previous process ing to the new process.
2. The call is defined in the include/asm/system. h switch_to (). This function is responsible for switching from the processor status of the previous process to the processor status of the new process, including saving and restoring
Stack information and register information. |
The kernel must also know when to call schedule (). By relying on the user code to show that schedule () is called, they may always execute schedule (). On the contrary, the kernel provides a need_resched flag to indicate whether a new scheduling is required. When a process consumes its time slice, scheduler_tick () sets this flag. When a high-priority process enters the executable state, try_to_wake_up () also sets this flag. The following table lists the functions used to access and operate need_resched.
|
Function |
Description |
| Set_tsk_need_resched (task) |
Set the need_resched flag in the specified process |
| Clear_tsk_need_resched (task) |
Clear the nedd_resched flag in the specified process |
| Need_resched () |
Check the value of the need_resched flag. If set, true is returned. Otherwise, false is returned. |
The kernel will also check the need_resched flag when the user space is returned and the return from the interrupt. If the flag has been set, the kernel will call the scheduler before it continues to run. Finally, each process contains a need_resched flag, this is because the value in the access process descriptor is faster than accessing a global variable (because the current macro is fast and the descriptor is usually in the cache ). In the 2.6 kernel, it is moved to the thread_info struct, which is different from the previous one.
Preemption or preemption! We are always unable to escape the topic of preemption. When the kernel is put back to the user space, if the need_resched flag is set, schedule () is called. In short, user preemption occurs in the following situations: From System Call return to user space and from interrupt handler return to user space.
In the linux2.6 kernel, the kernel introduces internal preemption forces. The first change to support kernel preemption is to introduce the preempt_count counter for thread_info of each process. The counter is initially 0, and the value is reduced by 1 when the lock is used. When the value is 0, the kernel can be preemptible. When the kernel space is returned from the interrupt, the kernel checks the need_resched and preempt_count values. If need_resched is set and the preempt_count is 0, this indicates that a more important task needs to be executed and securely preemptible. At this time, the scheduler will be scheduled. If the value of preempt_count is not 0, it indicates that the current task holds a lock and the preemption is insecure. In this case, you will want to directly return the current execution process from the interruption as usual. If the locks held by the current process are released, the preempt_count value is 0 again. In this case, the code for releasing the lock will check whether the need_sheduled is set. If yes, the scheduler will be called. Some kernels need to allow or disable kernel preemption, which will be analyzed in detail later. If the process in the kernel is blocked, or it explicitly calls schedule (), kernel preemption also occurs. This type of kernel preemption is always supported, because no additional logic is required to ensure that the kernel can be securely preemptible, if the Code shows that schedule () is called, it knows that it can be securely reinforced.
We talk about common non-real-time scheduling policies (SCHED_OTHER). Linux also supports two real-time scheduling policies (SCHED_FIFO and SCHED_RR ). SCHED_FIFO is also known from the name. It does not use time slice. Processes at this level are scheduled before any SCHED_OTHER-level process. Once a SCHED_FIFO-level process can be executed, it will continue until it is blocked or explicitly released. Because it is not based on time slice, it will continue to be executed. When multiple SCHED_FIFO-level processes exist, they take turns. In addition, as long as a SCHED_FIFO-level process exists, the normal-level process level can only be executed after it is completed. SCHED_RR is a SCHED_FIFO with time slice. The preceding two real-time scheduling algorithms are implemented with static priorities. The kernel does not calculate the dynamic priority for real-time processes. In this way, real-time processes with a given priority level can always preemptible processes with a lower priority.
Linux real-time scheduling algorithms include soft real-time and hard real-time. The meaning of Soft Real-time is that the kernel scheduling process tries its best to execute the process before its limited time arrives, but the kernel will not pat it down and say: I can guarantee it. Correspondingly, the real-time hardware will be so loyal to you. In linux, real-time scheduling is not guaranteed. As long as the real-time process can be executed, it should be executed as far as possible. Now, the effect is good.
The real-time priority ranges from 0 ~ MAX_RT_PRIO-1. By default, the nice value of a MAX_RT_PRIO process of the 100. SCHED_OTHER level shares this value. The value range is from MAX_RT_PRIO to MAX_RT_PRIO + 40. That is to say, the nice value ranges from-20 to + 19, which corresponds to the real-time priority range from 100 to 140.
Finally, there are some system calls related to scheduling. I will not talk about them. I feel like function calls are meaningless. Let's take a look. It's just a book in hand, so everything goes well.