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:
__attribute_const__
?register unsigned long sp asm ("sp");
(struct thread_info *)(sp & ~(THREAD_SIZE - 1));
return a
pointer to the struct?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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With