我正在閱讀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'並給出編譯器的確切版本...... –