The Master said, “The Lord is faithful and faithful; he who does not make friends is inferior to himself, and he is not afraid to change his ways.” The Analects of Confucius: A rare chapter
A hundred blog series. This paper is: the v39. Xx HongMeng kernel source code analysis abnormal (over) | society is very simple, complex people
Hardware architecture:
- V22. Xx HongMeng kernel source code analysis (assembly) | where the CPU clock in
- V23. Xx HongMeng kernel source code analysis (assembly parameter) | how to transfer the parameters of the complex
- V36. Xx HongMeng kernel source code analysis (operating mode) | CPU is inspired, seven wives
- V38. Xx HongMeng kernel source code analysis (register) | jack Bauer is the busiest storage universe
- Abnormal v39. Xx HongMeng kernel source code analysis (over) | society is very simple, complex people
- V40. Xx HongMeng kernel source code analysis (assembly summary) | assembly and lovely as the girl next door
- V42. Xx HongMeng kernel source code analysis (interrupt switch) | system dynamic due to interrupt
- V43. Xx HongMeng kernel source code analysis (interrupt concept) | sea father-in-law’s daily work
- V44. Xx HongMeng kernel source code analysis (interrupt management) | henceforth no longer afraid of interruption
The ARM part of the series is based on the ARM720T. PDF document.
Why abnormal takeovers?
Take the growth of children for example, adults always hope that children can grow up healthily, but in the process of growth, there will always be a variety of problems, the tree is still but the wind is not broken, there are dangers on the way to grow, sometimes it is their own problems and sometimes external environment problems. Just like douyin’s latest pop song, society is simple, but people are complicated. Every time they hear it, they want to stand up and shake. Ah! What did Na do wrong?
For example: how to be bullied by other children? What’s wrong with spending money? How do you deal with puberty? Lovelorn to jump off the building again how to do? It means it’s out of its depth, it can’t solve it on its own, it needs someone with higher authority, higher intelligence to step in, help solve it, clean up the mess.
Then the application is the child, the kernel is the guardian, with higher privileges, higher intelligence. And the guardian is not only one, but six, each guardian corresponding to solve a situation, the situation happened by it to take over the handling of this matter, children you don’t mind ha, first put you in the home, deal with the safety of the outside and then put the application out to play.
Each of these six people has their own tools for solving problems, standard solutions, their own separate office space, which is the stack space (independent), and the standard solution is private code snippets, placed in a fixed location. The built-in tools are SPSR_***, SP_***, LR_** register groups. Please refer to the work patterns section of this series to briefly review the work patterns, including the child’s own (user mode).
Seven working modes
Figure come fromARM720T.pdfOn page 43, in the ARM system, the CPU works in the following seven modes:
-
User mode (usr) : this mode is the job of the user program, it runs in user mode of the operating system, it has no authority to operate other hardware resources, have only themselves to perform processing of data, also can’t switch to other mode, or switch to other mode to access hardware resources cannot be produced by soft interrupt or exception.
-
Fast interrupt mode (FIQ) : Compared with the general interrupt mode, the fast interrupt mode is used to process high-priority interrupts and time-critical interrupt requests. It is mainly used for high-speed data transmission and channel processing.
-
Common Interrupt mode (IRQ) : The common interrupt mode is also called the common interrupt mode. It is used to process common interrupt requests. The irQ mode is automatically entered after the hardware generates an interrupt signal.
-
Management mode (SVC) : The operating system protection mode, which is also entered when the CPU is powered on and reset, and when applications invoke system services by executing SVC instructions. The normal code of the operating system kernel usually works in this mode.
-
Abort mode (ABT) : This mode is entered when data or instruction prefetch terminates. Abort mode is used to support virtual memory or memory protection.
-
System Mode (SYS) The high-privileged user mode used by the operating system is similar to the user mode but has the privilege of switching directly to other modes. The user mode and the system mode use the same Register but do not have the Saved Program Statement Register (SPSR). However, the system mode has higher permissions than the user mode and can access all system resources.
-
Undefined mode (UND) : Undefined mode is used to support software emulation of a hardware coprocessor. When the CPU fails to recognize the operation of an instruction during the decoding phase, it enters undefined mode.
Except user mode, the other six working modes belong to privileged mode
- The five modes in privilege mode other than system mode are called exception mode
- Most programs run in user mode
- Privileged mode is used to handle interrupts, exceptions, or access protected system resources
- Hardware permission level: System Mode > Abnormal Mode > User Mode
- Fast interrupt (FIQ) and slow interrupt (IRQ) difference: Fast interrupt processing prohibit interrupt
Each mode has its own separate entry and separate run stack space. As described in the CPU part of this series, the CPU is ready to do its job as long as you provide entry functions and running space. The entry function solves the problem of instruction source and the running space solves the problem of instruction running place. And in the case of multiple cores, each CPU core has its own stack space for each privileged mode. Note that the privileged mode stack space is provided by the user (application).
The official concept
Exception takeover is a series of actions taken by the operating system to deal with abnormal conditions (chip hardware exceptions) during operation, such as printing the current function call stack information, CPU field information and task stack information when the exception occurs. As a means of commissioning, exception takeover can provide users with useful exception information, such as exception type and system status when an exception occurs, to facilitate users to locate and analyze problems.
When the system is abnormal, the processing action is to display the task information (including the task name, task number, stack size, etc.) that is running when the exception occurs, as well as the INFORMATION on the CPU site.
Enter and exit the exception mode
There are two things you need to do to handle an exception takeover switch:
- One is where the code should be cut to, that is, to reset the PC register. The switching mode in each exception mode is shown in the figure below:
- The other is to restore the state of each mode, i.e
CPSR(1个)
和SPSR(5 in total)
Student: RightM[4:0]
As shown in the figure:
The following is the specific operation mode of M[4:0] in each mode:
The stack frame
Each function has its own stack space, called a stack frame. When a function is called, a stack frame for the child function is created, and the function’s parameters, local variables, and registers are pushed onto the stack. The stack frame grows from the high address to the low address, that is, the bottom of the stack is the high address, the top of the stack is the bottom address. See the stack usage section of the series
In order toARM32 CPU
For architecture, this is stored in each stack framePC
,LR
,SP
andFP
The historical value of a register. The following figure shows the stack analysis principle. Actual stack information varies according to CPU architectures. The registers in different colors in the figure represent different functions. You can see how registers are saved during the function call. Through the FP register, the stack traces back to the parent function of the abnormal function, continues to parse the stack according to the rule, and derives the function call relationship, which is convenient for users to locate the problem.
Interpretation of the
-
LR Register, the Link Register, points to the return address of the function.
-
R11: Can be used as a general-purpose register or as a frame pointer register FP when certain compilation options are turned on for stack backtracking. The GNU compiler (GCC) defaults to R11 as a general-purpose register for storing variables, so FP’s stack backtracking is not available by default. To support call stack resolution, add the -fno-hope-frame-pointer option to the compile parameter to prompt the compiler to use R11 as FP.
-
FP register (Frame Point), Frame pointer register, pointing to the stack Frame start address of the parent function of the current function. By using this register, the stack frame of the parent function can be obtained, and the FP of the parent function can be obtained from the stack frame, and the stack frame of the grandfather function can be obtained, and so on, the program call stack can be traced to get the call relationship between functions. When an exception occurs in the system, the system prints the register contents saved in the stack frame of the abnormal function, as well as the LR and FP register contents in the stack frame of the parent function and grandfather function, so that users can trace the call relationship between functions and locate the cause of the exception.
Six exception pattern implementation code
/* Define exception type ID */ // There are seven operating modes of the ARM processor, all of which are called exception mode except user and system mode
#define OS_EXCEPT_RESET 0x00 // Reset function, for example, CPSR_SVC_MODE on startup
#define OS_EXCEPT_UNDEF_INSTR 0x01 // Undefined exceptions are others
#define OS_EXCEPT_SWI 0x02 / / soft interrupt
#define OS_EXCEPT_PREFETCH_ABORT 0x03 // Prefetch exception (fetch exception), instruction three steps: fetch, decode, execute,
#define OS_EXCEPT_DATA_ABORT 0x04 // Data is abnormal
#define OS_EXCEPT_FIQ 0x05 // Fast interrupt exception
#define OS_EXCEPT_ADDR_ABORT 0x06 // The address is abnormal
#define OS_EXCEPT_IRQ 0x07 // Normal interrupt exception
Copy the code
Address abort
@description: Address abort exception handler _osExceptAddrAbortHdl: @ Address abort exception handler SUB LR, LR, #8 @ LR offset to return from this exception: - 8.STMFD SP, {R0 - R7} @ Push working registers, but don t change ` SP. MOV R0, #OS_EXCEPT_ADDR_ABORT @set exception ID to OS_EXCEPT_ADDR_ABORTCopy the code
Fast Interrupt Processing (FIQ)
@description: Fast interrupt Request exception handler _osExceptFiqHdl: @ Fast interrupt exception handler SUB LR, LR, #4 @ LR offset to return from this exception: - 4.STMFD SP, {R0 - R7} @ Push working registers. MOV R0, #OS_EXCEPT_FIQ @ Set exception ID to OS_EXCEPT_FIQ. B _osExceptDispatch @ Branch to global exception handler.Copy the code
Interpretation of the
- Disable common interrupts during quick interrupt processing
Prefectch abort
@ Description: Prefectch abort exception handler
_osExceptPrefetchAbortHdl:
#ifdef LOSCFG_GDB
#if __LINUX_ARM_ARCH__ >= 7
GDB_HANDLE OsPrefetchAbortExcHandleEntry
#endif
#else
SUB LR, LR, #4 @ LR offset to return from this exception: - 4.STMFD SP, {R0 - R7} @ Push working registers, but don t change ` SP. MOV R5, LR MRS R1, SPSR MOV R0, #OS_EXCEPT_PREFETCH_ABORT @set exception ID to OS_EXCEPT_PREFETCH_ABORT. #CPSR_MASK_MODE @interrupted mode CMP R4, #CPSR_USER_MODE @user mode BEQ _osExcPageFault @branchifUser mode _osKernelExceptPrefetchAbortHdl: MOV LR, R5 _osExceptDispatch @ B Branch to global exception handler.#endif
Copy the code
Data Abort
@description: Data abort exception handler _osExceptDataAbortHdl: @ Abort Data handling#ifdef LOSCFG_GDB
#if __LINUX_ARM_ARCH__ >= 7
GDB_HANDLE OsDataAbortExcHandleEntry
#endif
#else
SUB LR, LR, #8 @ LR offset to return from this exception: - 8.STMFD SP, {R0 - R7} @ Push working registers, but don t change ` SP. MOV R5, LR MRS R1, SPSR MOV R0, #OS_EXCEPT_DATA_ABORT @set exception ID to OS_EXCEPT_DATA_ABORT#endif
Copy the code
Soft Interrupt Processing (SWI)
@description: Software exception handler _osExceptSwiHdl: @4 * 16) @ Apply first16STMIA SP, {r0-r12} @ Save the r0-r12 register values MRS R3, spsr@ read the SPSR values in this mode MOV R4, LR @ save the jump back registers LR AND R1, R3, # cpsr_mask_mode@interrupted Mode Obtains the Interrupted mode CMP R1, # cpsr_user_mode@user mode Whether the mode is a User mode BNE oskernelSvChandl@branchif not@we enter from user mode @we enter from user modewe need get the values of USER mode r13(sp) and r14(lr).
@ stmia with ^ will return the user mode registers (provided that r15 is not in the register list).mov R0, sp@ get the SP value, R0 will be used as the OsArmA32SyscallHandle parameter STMFD SP! .{R3} @save the CPSR value ADD R3, SP, #4 * 17) @offset to PC/CPSR storage jump to PC/CPSR storage STMFD R3! , {R4} @Save the CPSR and r15(pc)Save the LR register STMFD R3,{R13, R14} ^ @Save user mode r13(sp) and r14(lr)Save SP and LR registers SUB SP, SP, #4 PUSH_FPU_REGS R1@ Save interrupt mode(User mode mode)MOV FP, #0 @init Frame Pointer CPSIE I @ Open interrupt, indicating that interrupt BLX OsArmA32SyscallHandle can be responded to during a system call/* Passes the system call to C */POP_FPU_REGS R1 @ Pop the FP value to R1 ADD SP, SP, #4 @ Locate the location where the old SPSR value is saved LDMFD SP! .{R3} @ Fetch the returnSPSR Displays the old SPSR value MSR SPSR_cxsf, r3@set thereturnMode SPSR Restore the SPSR value in this mode @we are leaving to user mode, we need to restore the values of user moder13(sp) and r14(lr).
@ ldmia with ^ will return the user mode registers (provided that r15 is not in the registerlist) LDMFD SP! , {r0-r12} @ Restore user mode R13/R14 ADD SP, SP, #(2 * 4) @locate the location where the old PC value is saved LDMFD SP! , {PC}^ @ Return to user To switch back to user modeCopy the code
Common Interrupt Processing (IRQ)
OsIrqHandler: @ Hard interrupt handling, this time has switched to the hard interrupt stack SUB LR, LR, #4
/* push r0-r3 to irq stack */STMFD SP, {r0-r3} @r0-r3 SUB R0, SP #(4 * 4)@r0 = sp - 16MRS R1, SPsr@ obtain the program state control register MOV R2, LR @ R2 = LR/* disable irq, switch to svc mode */@ Super user mode (SVC mode)SWI(Software interruption) andOS(Operating system). CPSID I, #0x13@ switches to SVC mode, where everything is changed, and the subsequent instructions will be added to the SVC stack. @cpSID I is the interrupt off instruction, corresponding to CPSIE/* push spsr and pc in svc stack */STMFD SP! SP, {LR} @lr, SP does not increment AND R3, R1, #CPSR_MASK_MODE @ obtain the CPU running mode CMP R3, If the interrupt does not occur in user mode, skip to OsIrqFromKernel/* push user sp, lr in svc stack */STMFD SP, {R13, R14}^ @ SP and LR are added to SVC stackCopy the code
Interpretation of the
- Normal interrupt processing can respond to fast interrupts
Undefined exception Handling (UNDEF)
@description: Undefined instruction exception handler _osExceptUndefInstrHdl:@ Undefined instruction processing occurred#ifdef LOSCFG_GDB
GDB_HANDLE OsUndefIncExcHandleEntry
#else
@ LR offset to return from this exception: 0.STMFD SP, {R0 - R7} @ Push working registers, but don t change ` SP. MOV R0, #OS_EXCEPT_UNDEF_INSTR @ Set exception ID to OS_EXCEPT_UNDEF_INSTR. B _osExceptDispatch @ Branch to global exception handler.#endif
Copy the code
Unified handling of abnormal distribution
_osExceptDispatch: MRS R2, SPSR @ Save CPSR before exception. MOV R1, LR @ Save PC before exception. SUB R3, SP, #(8 * 4) @ the Save the start address of working registers. The MSR CPSR_c, # (CPSR_INT_DISABLE | CPSR_SVC_MODE) @ Switch to SVC mode,andDisable all Interrupts MOV R5, SP EXC_SP_SET __exc_STACK_TOP, OS_EXC_STACK_SIZE, R6, R7 STMFD SP! , {R1} @push Exception PC STMFD SP! , {LR} @push SVC LR STMFD SP! , {R5} @push SVC SP STMFD SP! , {r8-r12} @push original r12-r8, LDMFD R3! , {r4-r11} @move original r7-r0 from exception stack to original stack.stmfd SP! {R4 - R11} STMFD SP! , {R2} @push task 's CPSR (i.e. exception SPSR). CMP R0, #OS_EXCEPT_DATA_ABORT @ MRC P15, 0, R8, C6, C0, 0=C6(Memory invalid address)0(Access data failure) MRC P15,0R9, C5, C0,0 @R9=C5(Memory failure status)0(Invalid entire instruction cache) B3f@ jump to anchor point3executes1: CMP R0, #OS_EXCEPT_PREFETCH_ABORT @ BNE2f@ is not jumping to the anchor point2At the MRC P15,0R8, C6, C0,2 @R8=C6(Memory invalid address)2(Access command failure) MRC P15,0R9, C5, C0,1 @R9=C5(Memory failure status)1(virtual address) B3f@ jump to anchor point3executes2: MOV R8, #0
MOV R9, #0
3: AND R2, R2, #CPSR_MASK_MODE CMP R2, # cpsr_user_mode@user mode BNE4fSTMFD SP, {R13, R14}^ @save user mode SPand lr
4: SUB SP, SP, #4 * 2) @sp=sp-(4*2)
Copy the code
Very important ARM37 register
See the register section of the series
At the end
The above is the code processing corresponding to exception takeover. The specific scenarios and code details of each exception are too much and too complex, which will be analyzed one by one in the subsequent chapters of this series. Stay tuned!
Intensive reading of the kernel source code
Four code stores synchronous annotation kernel source code, >> view the Gitee repository
Analysis of 100 blogs. Dig deep into the core
Add comments to hongmeng kernel source code process, sort out the following article. Content based on the source code, often in life scene analogy as much as possible into the kernel knowledge of a scene, with a pictorial sense, easy to understand memory. It’s important to speak in a way that others can understand! The 100 blogs are by no means a bunch of ridiculously difficult concepts being put forward by Baidu. That’s not interesting. More hope to make the kernel become lifelike, feel more intimate. It’s hard, it’s hard, but there’s no turning back. 😛 and code bugs need to be constantly debug, there will be many mistakes and omissions in the article and annotation content, please forgive, but will be repeatedly amended, continuous update. Xx represents the number of modifications, refined, concise and comprehensive, and strive to create high-quality content.
Compile build | The fundamental tools | Loading operation | Process management |
---|---|---|---|
Compile environment The build process Environment script Build tools Designed.the gn application Ninja ninja |
Two-way linked list Bitmap management In the stack way The timer Atomic operation Time management |
The ELF format The ELF parsing Static link relocation Process image |
Process management Process concept Fork Special process Process recycling Signal production Signal consumption Shell editor Shell parsing |
Process of communication | Memory management | Ins and outs | Task management |
spinlocks The mutex Process of communication A semaphore Incident control The message queue |
Memory allocation Memory management Memory assembly The memory mapping Rules of memory Physical memory |
Total directory Scheduling the story Main memory slave The source code comments Source structure Static site |
The clock task Task scheduling Task management The scheduling queue Scheduling mechanism Thread concept Concurrent parallel The system calls Task switching |
The file system | Hardware architecture | ||
File concept The file system The index node Mount the directory Root file system Character device VFS File handle Pipeline file |
Compilation basis Assembly and the cords Working mode register Anomaly over Assembly summary Interrupt switch Interrupt concept Interrupt management |
HongMeng station | into a little bit every day, the original is not easy, welcome to reprint, please indicate the source.