20135201 Li Chenxi The eighth week of Linux kernel analysis process switching and general execution of the system

Source: Internet
Author: User

Li Chenxi Original works reproduced please specify the source "Linux kernel Analysis" MOOC course http://mooc.study.163.com/course/USTC-1000029000

I. Analysis of key code SWITCH_TO for process switching 1. Timing analysis of process scheduling and process scheduling
    1. Process Classifications

          1. i/o-bound: Waiting for I/O
          2. cpu-bound: CPU Intensive calculation
        1. 2.
        1. Interactive process (shell)
        2. Real-time process
        3. batch process
    2. process Tune Degree Policy
      • a set of rules that determine when a process is selected
      • scheduling for Linux is based on ticks and priority policies: The
        1. process is queued according to the priority (the system is calculated based on the specific algorithm).
        2. the value of this priority indicates how the CPU is allocated appropriately;
        3. The
        4. Scheduler dynamically adjusts the priority based on the running cycle of the process;
        5. such as nice and other system calls, you can manually adjust the priority
      • The
      • scheduling policy is essentially an algorithm that, from an implementation perspective, selects only a new process from the run queue, using different strategies in the process of selection
      • The scheduling algorithm related code in the kernel uses a policy pattern similar to that in Ood
    3. timing of process scheduling
      • interrupt processing (including clock interrupts, I/O interrupts, system calls, and exceptions), call schedule () directly, or call schedule () based on the need_resched tag when returning to the user state (i.e., The user-state process can only be dispatched passively); the
      • kernel thread can call schedule () for process switching, or it can be dispatched during interrupt processing, which means that kernel threads can be scheduled or passively dispatched as a special class of processes.
      • The

        User-state process cannot implement active scheduling, and can only be dispatched by a point in time after it has been trapped in the kernel state, that is, scheduling during interrupt processing.

        2. Related code for the process switching context

        1. Concept:

    • In order to control the execution of the process, the kernel must have the ability to suspend a process that is executing on the CPU and resume execution of a previously suspended process, called process switching (suspending a process that is executing on the CPU, which is different from the Save field at the time of the outage, and before and after the interrupt is in the same process context. Just from the user state to the kernel state execution)
    • The process context contains all the information required by the process execution
      • User address space: Includes program code, data, user stack, etc.
      • Control information: Process descriptor, kernel stack, etc.
      • The hardware context (interrupts also save the hardware context is only a different method of saving, interrupts are solved by pressing the stack, and this is done through the schedule function)

Schedule () Function code Analysis

1. Create some local variables

struct Task_struct *prev, *next;//the current process and the process structure of a process unsigned long *switch_count;//process switches struct RQ *rq;//ready queue int CPU;

2. Turn off kernel preemption and initialize part of the variables

Need_resched:preempt_disable ();//shutdown kernel preemption CPU = smp_processor_id (); RQ = CPU_RQ (CPU);//CPU-related runqueue saved in RQ Rcu_note_ Context_switch (CPU);p rev = rq->curr;//assigns Runqueue current value to prev

3. Select Next Process

Next = Pick_next_task (RQ, prev);//Select one of the highest priority tasks queued clear_tsk_need_resched (prev);//Clear prev tif_need_resched flag. Clear_preempt_need_resched ();

4. Completing the scheduling of the process

Next = Pick_next_task (RQ, prev);//Select one of the highest priority tasks queued clear_tsk_need_resched (prev);//Clear prev tif_need_resched flag. Clear_preempt_need_resched ();

5.schedule () function Select a new process to run

Next = Pick_next_task (RQ, prev); clear_tsk_need_resched (prev); clear_preempt_need_resched (); rq->skip_clock_ Update = 0;

6. Completing the process context switch via Context_switch

2336context_switch (struct RQ *rq, struct task_struct *prev,2337           struct task_struct *next) 2338{2339    struct MM_ struct *mm, *oldmm;23402341    prepare_task_switch (RQ, Prev, next); 23422343    mm = next->mm;2344    OLDMM = prev->active_mm;2350    Arch_start_context_switch (prev); 23512352    if (!mm) {2353        next->active_mm = oldmm;2354        atomic_inc (&oldmm->mm_count); 2355        enter_lazy_tlb (OLDMM, next); 2356    } else2357        switch_mm (OLDMM, MM, next), 23582359    if (!prev->mm) {2360        prev->active_mm = null;2361        rq- >prev_mm = oldmm;2362    }2369    spin_release (&rq->lock.dep_map, 1, _this_ip_); 23702371    Context_tracking_task_switch (prev, next); 2373    switch_to (prev, Next, prev); 23742375    Barrier (); 2381    Finish_task_switch (This_rq (), prev); 2382}

Second, the general implementation of the Linux system processAnalysis of general execution process of Linux system

General: The current system is in progress, there is a user-state process x, need to switch to the user-state process Y (Process policy decision):

1. Running user-state process X

2. Interrupt--save Cs:eip/esp/eflags (current) to kernel Stack,then load Cs:eip (entry of a specific ISR (interrupt Service Routine entry, For system calls is System_call) and SS:ESP (point to Kernel stack).//These save and load are CPU auto-complete

3.save_all//Save site

4. Schedule () is invoked during interrupt processing or before an interrupt is returned, where SWITCH_TO does a critical process context switch

5. After the label 1 begins to run the user-state process y (here Y has been switched out through the above steps, that is, Next has done prev, so you can continue from the label 1)

The 6.restore_all//y process recovers from its interruption in the field

7.iret-pop cs:eip/ss:esp/eflags from kernel stack//pops up from the kernel stack of the Y process

8. Continue to run the user-state process y//execute the next instruction at the point where the interrupt occurred

Key: Interrupt context switching (CPU context switching when interrupts and interrupts are returned) and process context switching (during process scheduling, switching from one process's kernel stack to the kernel stack of another process)

Several special cases in the process of Linux system execution

1. By interrupting the timing of the processing process, the user-state process and kernel threads switch between each other and the kernel threads switch to each other, and the most common situation is very similar, but the kernel thread is running in the process of interruption without process user state and kernel state conversion;

2. Kernel thread actively calls schedule (), only the process context switch, there is no interrupt context switch, and the most general situation is slightly abbreviated;//user-state process cannot be called actively

3.fork: The system call that creates the subprocess in the child process starts at the execution point (next_ ip = ret_ from_ fork) Returns the user state, the process returns is not executed from the label 1, jumps directly to the ret_ From_fork executes and then returns to the user state;

4. When a new executable program is loaded and returned to the user state, such as EXECVE, the interrupt context is modified within the EXECVE system call;

Address switching:

    1. The address space of the process is a total of 4G, where 0--3g is user-configurable, and more than 3G can be accessed only by the kernel state
    2. The kernel is equivalent to a taxi and can provide a kernel-to-user conversion for each "wave" process.
    3. No process needs to be "hosted" when the kernel enters the IDLE0 process for "idling". When a user process has a requirement, the kernel breaks, helping the user process complete the request before returning to the user process. It's like taxi the user after a lap and then puts the user down.
    4. More than 3G is the "Taxi", which is shared by all processes, and is easier to switch between the kernel states
    5. The kernel is a collection of various interrupt handlers and kernel threads.

Three. Overview of the LINUX system architecture and execution Process 1. Execute the LS command

1. The concept of interruption, terminal console device drivers.

2. Procedure: Shell analysis-Call the system call Fork to generate a copy of the shell itself--call the exec system call to load the LS executable into memory--back from the system call

2.CPU and memory view of Linux system execution
    1. Execute the gets () function;
    2. Execute system call, fall into kernel;
    3. Waiting for input, the CPU dispatches other processes to execute while wait for an I/O interrupt;
    4. Hit LS, send I/O interrupt to the CPU, interrupt processing program for on-site storage, pressure stack and so on;
    5. The interrupt handler discovers that the X process is waiting for this I/O (at which point X has become blocked) and the handler sets X to Wake_up;
    6. Process management may set process X to the next process so that the get system invokes the data and returns to the user-state stack
    7. From a memory point of view, all physical addresses are mapped to more than 3G of address space: Because this part is shared for all processes
Four. Experiments

1. Build the Environment:

cd LinuxKernel   rm menu -rfgit clone https://github.com/mengning/menu.gitcd menumv test_exec.c test.cmake rootfs

2.GDB Commissioning

qemu -kernel linux-3.18.6/arch/x86/boot/bzImage -initrd rootfs.img -s -Sgdbfile ../linux-3.18.6/vmlinuxtarget remote:1234设置断点:b scheduleb pick_next_taskb context_switchb switch_to

实验步骤
1. Self-debugging Schedule function
      1. Enter the lab building virtual machine environment;
      2. Boot the kernel and enter the debug state
      3. Set a breakpoint at schedule and click C to run. "You can see that the frozen kernel starts running until schedule"
      4. 4.list View the code snippet where the breakpoint is located. can be compared with control, found schedule () function
        C then press N to step through until you encounter the __schedule function and enter it to view

      Continue execution until you find the Context_switch function
Five. Summary

Linux system General Execution process:

1. The process scheduling algorithm is only an abstraction, focusing on understanding the process scheduling timing and process switching mechanism.

2.Linux System General Execution process: The current system is in progress, there is a user-state process x, need to switch to the user state process Y (Process policy decision)

20135201 Li Chenxi The eighth week of Linux kernel analysis process switching and general execution of the system

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.