How does the kernel know what is the current thread?

前端 未结 2 1413
情书的邮戳
情书的邮戳 2021-02-05 10:47

Can someone please explain me this snippet of code here taken from linux kernel?

/*
  * how to get the thread information struct from C
 */
 static inline struct         


        
2条回答
  •  悲&欢浪女
    2021-02-05 11:31

    The kernel stacks in Linux have a fixed size (THREAD_SIZE - 2 pages, or 8KB on x86). The struct thread_info for a thread is kept at the bottom of the stack's memory block. Keep in mind the stack works downward, so the stack pointer is initially pointing to the end of the memory block and as data is pushed on to the stack, the stack pointer moves toward the bottom of the memory block. Of course other CPU architectures may use other techniques.

    So if you take the current stack pointer value, and mask off the lower order bits, you get a pointer to the struct thread_info for the thread using the current stack.

    The line:

    register unsigned long sp asm ("sp");
    

    tells GCC to map the variable sp to the CPU register sp (it seems strange to me that 16 bit register name is being used here - is this from an actual Linux source tree?).

    __attribute_const__ is generally defined to be __attribute__((__const__)) when GCC is the compiler (is it ever anything else for the linux kernel?). That tells GCC that the function has no side effects - actually it's a bit stronger than that: the function uses only the arguments and returns a value based on only those arguments. This may afford some optimization opportunities for the compiler - it can assume that no globals are changed, or even read (so the compiler would be free to postpone updating memory that it might need to update for 'normal' function calls).

提交回复
热议问题