Linux Summary-First lecture-interrupts and exceptions

Source: Internet
Author: User

Interrupts and exceptions, interrupts (generalized): The order in which the processor executes instructions is changed, usually relative to the electrical signals generated by the internal or external hardware circuitry of the CPU chip
    1. Interrupt-Asynchronous: randomly generated by hardware and may occur at any time during program execution
    2. Exception-synchronous: generated by the CPU control unit when a (special or faulty) instruction is executed
    3. We use an "interrupt signal" to make a generic term for these two types of interrupts.
Second, the role of interrupt signal
    1. Interrupt signals provide a special way for the CPU to go outside of the normal program to run code
    2. When an interrupt signal arrives, the CPU must stop what it is currently doing and switch to a new activity
      1. The current value of the program counter is stored in the kernel-state stack of the process (i.e. EIP and CS register) to return to the breakpoint correctly when the interrupt is processed
      2. And put an address associated with the interrupt signal into the program counter, so as to enter the processing of interrupts
Third, the principle of the interruption signal processing
    1. The goal of the kernel is to make the interrupt as fast as possible, and to defer more processing to the best of its ability.
    2. Allows nesting of different types of interrupts to occur so that more I/O devices are busy
    3. Although the kernel can accept a new interrupt while processing an interrupt, there are some critical sections in the kernel code that must be disabled in the critical section
Iv. Interrupt Context
    1. Interrupt context differs from process context
      1. The code that the interrupt or exception handler executes is not a process. It is a kernel-controlled path that represents the execution of a process that is running when an interrupt occurs
      2. As the kernel control path for a process, the interrupt handler is lighter than a process (the interrupt context contains only a limited number of registers, and the time required to establish and terminate the context is minimal)
Because Linux does not set process Context,a for interrupt handlers, it can only use C's kernel stack as its own run stack
    1. In any case, Linux interrupt context A will never be preempted by a process C or D!!!
    2. This is due to the fact that all interrupt contexts that have been started, whether switching between interrupt contexts or executing code in a interrupt context, are never likely to insert a call to the scheduler schedule routine.
    3. Unless the interrupt context actively or passively blocks into sleep, evoking scheduler, but this must be avoided, the danger is shown in the 3rd note
      1. First of all, interrupt context does not have a process context,a interrupt is "borrowing" the context of C run, if you allow a "blocking" or "sleep", then C will be forced to block or sleep, only when a is "awakened" C is awakened, and "wake", A will be dispatched according to the order of C in the ready queue. This has both harmed the interests of a and polluted the C kernel stack.
      2. Second, if interrupt context A is asleep due to blocking or other causes, the external response to the system will become intolerable.
What about the relationship between interrupt context A and B?
    1. Because the IF flag flag of the CPU may be turned on in a step of the interrupt context, this allows the IRQ line of B to trigger the PIC in the process of a, triggering the CPU IRQ PIN, causing the CPU to execute interrupt B's Interrupt Context, which is the nesting process for interrupt contexts.
    2. Normally Linux does not prioritize different interrupt contexts, and this arbitrary nesting is allowed
    3. Of course, one real-time Linux patch would not allow a low-priority interrupt context to preempt a high-priority interrupt context

How I/O devices cause CPU outages

Vii. interruption is divided into:
    1. Shielded interrupt (maskable interrupt)
      1. All interrupt requests (IRQ) issued by the I/O device can produce a masked interrupt.
      2. Shielded interrupts can be in two states: shielded (masked) and unshielded (unmasked)
    2. unshielded Interrupt (nonmaskable interrupt)
      1. Only a few specific critical events cause an unshielded interrupt. such as hardware failure or power-down
Eight, the exception is divided into:
    1. Processor Detection exception
      1. Generated when an abnormal condition is detected by the CPU when executing instructions, such as overflow, except 0 error, etc.
    2. Programming exceptions
      1. Generated by a specific request made by the programmer, usually triggered by an int class directive
      2. Usually called a "soft break": for example, a system call
Nine, for the processor detection exception, according to the exception when the value of the EIP stored in the kernel stack can be further divided into:
    1. Fault (fault): eip= The address of the instruction that caused the failure
      1. It can usually be corrected, and when the exception is processed, the instruction is re-executed: for example, a missing pages exception
    2. Trap: eip= The address of the instruction to be executed later.
    3. Exception Abort (abort): eip=???
      1. A serious error has occurred. EIP value is invalid, only the affected process is forced to terminate
Ten, interrupt vector
    1. Each interrupt and exception is identified by a number (8-bit) between 0~255, which Intel calls the interrupt vector.
    2. The vectors of the unshielded interrupts and the vector of the anomalies are fixed
    3. A vector that can mask interrupts can be changed by programming the interrupt Controller
Xi. the generation of interrupts
    1. Each hardware device controller that can make an interrupt request has an output line called an IRQ (Interrupt request).
    2. All IRQ lines are connected to an input pin of an interrupt controller
    3. The interrupt controller is connected to the INTR pin of the CPU
12. The interrupt Controller performs the following actions:
    1. Monitor IRQ lines to trigger a signal check
    2. If a trigger signal appears on the IRQ line
      1. Convert this signal to the corresponding interrupt vector
      2. Store this vector in an I/O port on the interrupt controller, allowing the CPU to read this vector over the data bus
      3. Sends a trigger signal to the processor's INTR pin, which generates an interrupt
      4. Wait until the CPU responds to the signal; After receiving the answer, clear the intr pin
    3. Return to the first step (a)
13. IRQ number and interrupt vector number
    1. Interrupt controller number of input IRQ lines starting from 0
    2. The interrupt vector number that Intel assigns to the interrupt controller starts at 32, and the interrupt vectors for the above IRQ lines are: 32+0, 32+1 、...
    3. The interrupt controller can be programmed:
      1. Modifies the value of the starting interrupt vector, or
      2. Selective masking/activating of each IRQ line
    4. Shielded interrupts are not lost
      1. Once activated, the interrupt controller sends them to the CPU
    5. Selective masking/activating IRQ line ≠ global masking/activation
      1. The former is realized by programming the interrupt controller.
      2. The latter operates the state word in the CPU through specific instructions
14, I386: Open Interrupt and Guanzhong fault
    1. The CPU can block all the shielded terminals
    2. The IF flag in EFlags:

      0= off interrupt;
      1= Open interrupt.

    3. The CPU does not respond to any interrupt requests released by the interrupt controller when the gateway is broken

    4. The kernel uses the CLI and STI directives to clear and set the flag separately
XV, 8259A: Disable/Activate an IRQ line

16. Interrupt Descriptor Descriptor (Interrupt descriptor Table,idt)
    1. The Interrupt Descriptor table is a system chart that is associated with each of the broken or anomalous vectors.
      1. Each vector has a corresponding interrupt in the table or an entry address for the exception handler.
      2. Each descriptor has 8 bytes, a total of 256 items, and occupies 2KB of space.
      3. The kernel must initialize IDT properly before allowing interrupts to occur
    2. The IDTR register of the CPU points to the physical base address of the IDT table
      1. Before an interrupt is allowed, the IDTR must be initialized with the Lidt assembly instruction.
17. IDT contains 3 types of descriptors

A
b
C

x86 how the CPU handles interrupt signals at the hardware level

18. Interrupts and abnormal hardware processing into interrupts/exceptions
  1. Assumption: The kernel is initialized and the CPU is running in protected mode
  2. normal operation of the CPU:
    1. When an instruction is executed, the register of CS and EIP contains the logical address of the next instruction to be executed.
    2. Before executing this instruction, the CPU control unit checks to see if an interrupt or exception occurred while running the previous instruction.
    3. If an interrupt or exception occurs, the CPU control unit performs the following actions:
      1. determine the vector i (0~255)
      2. Read IDTR Register that is associated with the interrupt or exception in the IDT table that is pointed to in item I
      3. obtains the base address of the GDT from the GDTR register and looks in the GDT to read the segment descriptor identified by the segment selector in the IDT table entry
      4. to determine that the interrupt was emitted by the source of the authorization.
        1. Interrupt: The privilege of the interrupt handler must not be lower than the privilege of the program that caused the interrupt (the CPL
        2. programming exception in the DPL VS CS Register in the GDT table entry): Also compare the CPL with the dpl
      5. checks whether a change in the privilege level has occurred, typically by the user state in the kernel state. If the user state is trapped in the kernel state, the control unit must start using the stack
        1. read TR register associated with the new privilege level, accessing the TSS segment of the running process
        2. loading SS and ESP registers with the stack and stack pointers associated with the new privilege level. These values can be found in the TSS segment of the process
        3. saves the previous values of SS and ESP in the new stack, indicating the logical address of the stack associated with the old privilege level
      6. If a failure occurs, modify CS with the command address that caused the exception And the value of the EIP register so that this instruction can be executed again at the end of the exception processing
      7. to save the contents of EFlags, CS, and EIP in the stack
      8. if the exception generates a hardware error code, save it in the stack
      9. load CS and E The IP register, whose values are the segment selector and offset fields for the I-entry gate descriptor in the IDT table, respectively. This pair of register values gives the interrupt or the first specified logical address of the exception handler
  3. The process kernel-state stack at this time
19. Return from interrupt/exception
    1. After interrupt/exception processing, the corresponding handler executes a iret assembly instruction that allows the CPU control unit to do the following things:
      1. Load CS, EIP, and eflags registers with values stored in the stack. If a hardware error code has been pressed into the stack, then this hardware error code pops up
      2. Check that the privilege level of the handler is equal to the lowest two-bit value in CS (this means that the process is running in a kernel state or a user state when it is interrupted). If, iret terminates execution; otherwise, transfer to 3
      3. Loads the SS and ESP registers from the stack. This step means returning to the stack associated with the old privilege level
      4. Check the contents of the DS, ES, FS, and GS segment registers, and if one of the registers contains selectors that are a segment descriptor and the privilege level is higher than the current privilege level, clear the appropriate registers. This is done to prevent malicious user programs from using these registers to access the kernel space

Software-level interrupt processing and its data structure in Linux kernel

20. Nested execution of interrupts and exception handlers
    1. A new kernel control path is started when the kernel handles an interrupt or exception
    2. Linux does not allow process switching when the CPU is executing an interrupt-related kernel control path. However, an interrupt handler can be interrupted by another interrupt handler, which is the nested execution of the interrupt.
21. Preemption Principle
    1. Normal processes can be interrupted or interrupted by an exception handler
    2. Exception handlers can be interrupted by interrupted programs
    3. The interrupt program can only be interrupted by another interrupt program.
22. Why Linux is allowed to interrupt nesting
    1. Increased throughput for programmable interrupt controllers and device controllers
    2. Implementation of an outage model with no priority
23. Initialize Interrupt Descriptor Descriptor
    1. The IDT must be initialized before the kernel initiates an interrupt, and then the IDT base address is loaded into the IDTR register
    2. The INT directive allows a user process to emit an interrupt signal whose value can be any vector of 0-255.
      1. User-state program Privilege level: 3. The kernel state is: 0.
    3. Break gates, trap doors, and system gate definitions in Linux
      1. Interrupt Gate
        1. An Intel interrupt gate that the user-state process cannot access (Privilege level 0), all interrupts are activated through the interrupt gate, and all are in the kernel state
      2. System Door
        1. The user-state process can access an Intel Trap Gate (Privilege level 3) that activates 4 Linux exception handlers through the system gate, with vectors of 3,4,5 and 128. Therefore, the int3,into,bound and int $0x80 Four assembly instructions can be published in the user state
      3. Trap Door
        1. A user-configured process cannot access an Intel Trap Gate (Privilege Level 0), most Linux exception handlers are activated through trap gates
    4. Pre-initialization of the IDT table before entering protected mode: Setup_idt ()
24. Exception Handling
    1. Most of the exceptions generated by the CPU are interpreted by Linux as error conditions.

      When an exception occurs, the kernel sends a signal to the process that caused the exception to notify it that an abnormal condition has occurred.

    2. Exception handling has a standard structure, consisting of three parts

      1. Saving the contents of most registers in the kernel-state stack
      2. Functions that call the C language
      3. Exit from exception handler by Ret_from_exception ()
    3. Entry_32.s in Error_code () The main function of this function:
      1. Follow the stack data format defined by the PT_REGS structure to complete the storage of the site.
      2. The address of the Do_handler_name () function in the stack address is loaded into the EDI register, and the FS value is written at this location, so that the stack structure is further identical to the PT_REGS structure.
      3. Finally execute the call *%edi command
25. Interrupt Processing
  1. Interrupts are different from exceptions, it does not mean that the program is wrong, but the hardware device is acting, so it is not easy to send a signal to the current process is OK
  2. There are three main types of interrupts
    1. I/O device makes an interrupt request
    2. Clock interrupt
    3. Interrupt between processors
  3. The handler performs four identical basic operations
    1. Save IRQ values and register contents in the kernel-state stack
    2. Sends an answer to the pic that is being given to the IRQ line service, which will allow pic to further interrupt
    3. Perform interrupt service routines for all devices that share this IRQ
    4. Jump to the address of ret_from_intr () and break jump
  4. When the system is initialized, call the INIT_IRQ () function to replace the temporary interrupt gate with the new interrupt gate to update IDT. (Call the INIT_IRQ () function to set the interrupt-handling snippet address of the interrupt description schedule to the interrupt array, which points to the same function handling Common_interrupt)
  5. Features of the Common_interrupt:
    1. Save_all movl%esp,%eax Call DO_IRQ jmp $ret _from_intr
  6. DO_IRQ () function function
  7. Irqaction Data structure
    1. Used to share the IRQ, maintain a specific device with a shared IRQ, and a specific interrupt, all the links that share an IRQ are in an action table, and the action pointer in the interrupt descriptor points to
  8. Interrupt Service Routines
    1. An interrupt service routine implements a specific device operation, and the handle_irq_evnet () function calls these device routines in turn
    2. This function essentially executes the following core code:
  9. Interrupt Program Registration: Registering an external interrupt
    1. A module is expected to request an interrupt channel (or IRQ, for interrupt requests), register it before using it, and release it at the end. function declarations are
26. Soft interrupt, Tasklet and lower part
    1. For the kernel, delayed interrupts are not urgent and can be extracted from the interrupt processing routines to ensure short interrupt response times
    2. The Linux2.6 offers three ways of
      1. Functions that can be deferred
        1. Soft Interrupt, Tasklet
          1. The Tasklet is implemented on top of soft interrupts
          2. General principle: Soft interrupts on the same CPU/tasklet not nested
          3. Soft interrupts are statically allocated by the kernel (determined at compile time)
          4. Tasklet can be assigned and initialized at run time (e.g. when loading a kernel module)
      2. Working queue (Work queues)
27. In general, 4 operations can be performed on a deferred function
    1. Initialize: Defines a new deferred function, usually when the kernel is initialized
    2. Activate: Set the deferred function to execute in the next round of processing
    3. Masking: selective masking of a deferred function so that it will not be run even if it is activated
    4. Execute: Perform a deferred function at a specific time
28, the soft interrupt processing mechanism:
    1. Softirq_init and Net_dev_init, blk_dev_init, etc. are initialized by OPEN_SOFTIRQ () respectively.
29, at some specific time, will check whether there is a soft interrupt is suspended
    1. When calling Local_bh_enable to reactivate a soft interrupt
    2. When the DO_IRQ completes the I/O interrupt processing
    3. When that particular process KSOFTIRQD is awakened
30, Tasklet
    1. Tasklet is the preferred way to implement a deferred function in an I/O driver
    2. Built on soft interrupts such as HI_SOFTIRQ and TASKLET_SOFTIRQ
    3. Tasklet and high-priority tasklet
      1. stored in the Tasklet_vec and Tasklet_hi_vec arrays, respectively
        1. Each item of the array is for a CPU, which represents the Tasklet list on this CPU
      2. Handled by Tasklet_action and Tasklet_hi_action, respectively
        1. Find the CPU corresponding to the item, traverse the execution
31, the use of Tasklet
    1. Assign a Tasklet data structure and initialize the = = equivalent Declaration (definition) of a tasklet
    2. You can disable/allow this tasklet==== equivalent to defining a window that allows the use of Tasklet
    3. This tasklet==== can be activated on the linked list of the corresponding CPU that the Tasklet is plugged into Task_vec or Task_hi_vec, and will be processed at the right time.
      1. Ways to activate Tasklet
        1. Tasklet_schedule
        2. Tasklet_hi_schedule
32. Work Queue Workqueue
    1. The main differences between the two lower-half mechanisms of the work queue and the Tasklet are:
      1. Tasklet runs in the context of soft interrupts, all code must be atomic, cannot sleep, cannot use semaphores, or other functions that produce blocking;
      2. The Task force is listed in a kernel thread context and can be executed after a certain amount of time is delayed, with more flexibility to use functions such as semaphores that can sleep.

Resources:
Deep understanding of the Linux kernel
Note:
Reprint Please specify source: http://blog.csdn.net/wsyw126/article/details/51803727
WSYW126

Linux Summary-First lecture-interrupts and exceptions

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.