简体   繁体   English

Linux内核中的current_thread_info()内联函数?

[英]current_thread_info() inline function in Linux kernel?

I learned thread_info is stored in the bottom of stack. 我了解到thread_info存储在堆栈的底部。 While looking in the source code of kernel, I'm trying to understand how to get current thread_info in linux kernel? 在查看内核的源代码时,我试图了解如何在linux内核中获取当前的thread_info?
Source code below is 13bits masking of current_stack_pointer. 下面的源代码是current_stack_pointer的13位屏蔽。

This is what I cannot get it. 这是我无法得到的。 I don't understand that the position of thread_info changes. 我不明白th​​read_info的位置会发生变化。 Why is it current stack pointer instead of start of stack? 为什么它是当前的堆栈指针而不是堆栈的开始?

Please help me to understand this code 请帮我理解这段代码

/*
 * 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. 您总是可以从平台特定的堆栈指针寄存器中获取当前堆栈指针,但是您无法轻松找到堆栈的开头 - 它就不存在了。

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. 为此,您可以限制线程堆栈在内存中的位置:堆栈始终在内存中按其大小保持对齐,其大小始终为2的幂。 This way if stack size is 2^n , then zeroing out lower n gives you start of the stack. 这样,如果堆栈大小为2^n ,则将较低的n归零可以启动堆栈。

In modern Linux stack is usually 8 KiB and is always 8 KiB aligned (lower 13 bits of its address are always 0). 在现代Linux堆栈中,通常为8 KiB,并且始终为8 KiB对齐(其地址的低13位始终为0)。 Zeroing out lower 13 bits of the current stack pointer gives you start of the stack. 将当前堆栈指针的低13位归零可以启动堆栈。

This is exactly what expression current_stack_pointer & ~(THREAD_SIZE - 1) does: finds start of the current stack. 这正是表达式current_stack_pointer & ~(THREAD_SIZE - 1)作用:查找当前堆栈的开始。 It does not mean that struct thread_info moves in memory - it doesn't. 这并不意味着struct thread_info在内存中移动 - 它不会。 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. 这就是为什么它也用__attribute_const__标记,它扩展为__attribute__((const))并告诉GCC这个函数总是返回相同的值,这样就可以省略对这个函数的多次调用。


PS: As stack grows downwards, by "start of the current stack" I mean the lowest address. PS:当堆栈向下增长时,“当前堆栈的开始”是指最低地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM