Linux内核中的current_thread_info()内联函数? [英] current_thread_info() inline function in Linux kernel?
问题描述
我了解到thread_info存储在堆栈的底部.
在查看内核的源代码时,我试图了解如何在Linux内核中获取当前的thread_info?
下面的源代码是current_stack_pointer的13位屏蔽.
I learned thread_info is stored in the bottom of stack.
While looking in the source code of kernel, I'm trying to understand how to get current thread_info in linux kernel?
Source code below is 13bits masking of current_stack_pointer.
这是我无法理解的. 我不明白thread_info的位置会发生变化. 为什么它是当前的堆栈指针而不是堆栈的开始?
This is what I cannot get it. I don't understand that the position of thread_info changes. Why is it current stack pointer instead of start of stack?
请帮助我理解此代码
/*
* how to get the current stack pointer in C
*/
register unsigned long current_stack_pointer asm ("sp");
/*
* 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)
{
return (struct thread_info *)
(current_stack_pointer & ~(THREAD_SIZE - 1));
}
推荐答案
为什么它是当前堆栈指针而不是堆栈开始?
Why is it current stack pointer instead of start of stack?
您始终可以从平台特定的堆栈指针获取当前的堆栈指针 注册,但是您找不到堆栈的开始那么容易-只是不在那里.
You can always get current stack pointer from the platform specific stack pointer register, but you cannot find start of the stack so easily - it is just not there.
为此,您可以限制线程堆栈在内存中的位置:堆栈始终按其大小在内存中保持对齐,并且其大小始终为2的幂.这样,如果堆栈大小为2^n
,则将较低的n
置零可使您开始堆栈.
To do this you can restrict location of thread stack in memory: stack is always kept aligned in memory by its size and its size is always a power of two. This way if stack size is 2^n
, then zeroing out lower n
gives you start of the stack.
在现代Linux堆栈中,通常为8 KiB,并且始终保持8 KiB对齐(其地址的低13位始终为0).将当前堆栈指针的低13位清零可以使您开始堆栈.
In modern Linux stack is usually 8 KiB and is always 8 KiB aligned (lower 13 bits of its address are always 0). Zeroing out lower 13 bits of the current stack pointer gives you start of the stack.
这正是表达式current_stack_pointer & ~(THREAD_SIZE - 1)
的作用:查找当前堆栈的开始.这并不意味着struct thread_info
会在内存中移动-不会.即使堆栈指针发生变化,将低位清零也会在线程内提供相同的值.这就是为什么还要用__attribute_const__
标记它扩展为__attribute__((const))
并告诉GCC该函数始终返回相同值的原因,因此可以省略对该函数的多次调用.
This is exactly what expression current_stack_pointer & ~(THREAD_SIZE - 1)
does: finds start of the current stack. It does not mean that struct thread_info
moves in memory - it doesn't. Even if stack pointer changes, zeroing out lower bits gives you the same value within a thread. This why it is also marked with __attribute_const__
which expands to __attribute__((const))
and tells GCC that this function always returns the same value so that multiple calls to this function can be omitted.
PS:随着堆栈向下增长,当前堆栈的开始"是指最低的地址.
PS: As stack grows downwards, by "start of the current stack" I mean the lowest address.
这篇关于Linux内核中的current_thread_info()内联函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!