Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the kernel know what is the current thread?

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 thread_info *current_thread_info(void) __attribute_const__;

 static inline struct thread_info *current_thread_info(void)
 {
        register unsigned long sp asm ("sp");
        return (struct thread_info *)(sp & ~(THREAD_SIZE - 1));
}

Questions:

  1. what is __attribute_const__ ?
  2. what does this do register unsigned long sp asm ("sp");
  3. why (struct thread_info *)(sp & ~(THREAD_SIZE - 1)); return a pointer to the struct?
like image 746
0x90 Avatar asked Aug 30 '12 08:08

0x90


Video Answer


1 Answers

  1. Attribute const means that the returned pointer will remain the same for the duration of the program. In practice, this is true only in the scope of the one thread, but I can't think of any situation where a compiler would even try to optimize accesses between threads.

  2. Using register and asm("sp") binds a variable to the hardware register called sp, i.e. current stack pointer. This way the code does not have to be written in assembler to access this register directly.

  3. THREAD_SIZE is a constant, which gives the amount of memory allocated for the thread's stack. I assume that it always has to be a power of 2, e.g. 8 kilobytes might be a typical value.

    The expression ~(THREAD_SIZE - 1) then gives a bitmask for getting rid of the actual stack address. For 8 kB stack, it would be 0xffffe000.

    By taking a bitwise and with the stack pointer value, we get the lowest address allocated for the stack. On this architecture, the thread information is stored there. This is simply a design decision, they could have used some other place for storing the information.

    The stack pointer is useful for getting the thread information because each thread will always have its own stack.

like image 50
jpa Avatar answered Oct 16 '22 01:10

jpa