我正在阅读Linux内核源代码(3.12.5 x86_64)以了解如何处理进程描述符。在Linux内核中使用修饰符“P”和约束“p”在“m”上的gcc内联汇编
我发现得到当前进程的描述符,我可以使用current_thread_info()函数,该函数执行如下:
static inline struct thread_info *current_thread_info(void)
{
struct thread_info *ti;
ti = (void *)(this_cpu_read_stable(kernel_stack) +
KERNEL_STACK_OFFSET - THREAD_SIZE);
return ti;
}
然后我看着this_cpu_read_stable()
:
#define this_cpu_read_stable(var) percpu_from_op("mov", var, "p" (&(var)))
#define percpu_from_op(op, var, constraint) \
({ \
typeof(var) pfo_ret__; \
switch (sizeof(var)) { \
...
case 8: \
asm(op "q "__percpu_arg(1)",%0" \
: "=r" (pfo_ret__) \
: constraint); \
break; \
default: __bad_percpu_size(); \
} \
pfo_ret__; \
})
#define __percpu_arg(x) __percpu_prefix "%P" #x
#ifdef CONFIG_SMP
#define __percpu_prefix "%%"__stringify(__percpu_seg)":"
#else
#define __percpu_prefix ""
#endif
#ifdef CONFIG_X86_64
#define __percpu_seg gs
#else
#define __percpu_seg fs
#endif
扩展宏应该是内联汇编代码:
asm("movq %%gs:%P1,%0" : "=r" (pfo_ret__) : "p"(&(kernel_stack)));
根据this post,输入约束用于“m”(kernel_stack),这对我很有意义。但显然,以提高性能莱纳斯改变了约束至“P”,并通过变量的地址:“
Added the magical undocumented "P" modifier to UP __percpu_arg()
to force gcc to dereference the pointer value passed in via the
"p" input constraint. Without this, percpu_read_stable() returns
the address of the percpu variable. Also added comment explaining
the difference between percpu_read() and percpu_read_stable().
但随着合并修改我的实验:
It uses a "p" (&var) constraint instead of a "m" (var) one, to make gcc
think there is no actual "load" from memory. This obviously _only_ works
for percpu variables that are stable within a thread, but 'current' and
'kernel_stack' should be that way.
在
post
而且Tejun许做这个评论P“修饰符和约束”p(& var)“不起作用。如果未指定段寄存器,“%P1”将始终返回变量的地址。指针并未解除引用。我必须使用括号来解引用它,如“(%P1)”。如果指定了段寄存器,不使用括号gcc就不会编译。我的测试代码如下:
#include <stdio.h>
#define current(var) ({\
typeof(var) pfo_ret__;\
asm(\
"movq %%es:%P1, %0\n"\
: "=r"(pfo_ret__)\
: "p" (&(var))\
);\
pfo_ret__;\
})
int main() {
struct foo {
int field1;
int field2;
} a = {
.field1 = 100,
.field2 = 200,
};
struct foo *var = &a;
printf ("field1: %d\n", current(var)->field1);
printf ("field2: %d\n", current(var)->field2);
return 0;
}
我的代码有什么问题吗?或者我需要为gcc添加一些选项?当我使用gcc -S生成汇编代码时,我没有看到通过在“m”上使用“p”来优化。任何答复或评论非常感谢。
询问'gcc-help @ gcc.gnu.org'并给出编译器的确切版本...... –