Linux中的task_struct和核心棧
在核心2.4中堆疊是這麼定義的:
union task_union {
struct task_struct task;
unsigned long stack[INIT_TASK_SIZE/sizeof(long)];
};
而INIT_TASK_SIZE只能是8K。
核心為每個程序分配一個task_struct結構時,實際上分配兩個連續的物理頁面(8192位元組),如圖所示。底部用作task_struct結構(大小約為1K位元組),結構的上面用作核心堆疊(大小約為7K位元組)。訪問程序自身的task_struct結構,使用巨集操作current, 在2.4中定義如下:
#define current get_current()
static inline struct task_struct * get_current(void)
{
struct task_struct *current;
__asm__("andl %%esp,%0; ":"=r" (current) : "" (~8191UL));
return current;
}
~8191UL表示最低13位為0, 其餘位全為1。 %esp指向核心堆疊中,當遮蔽掉%esp的最低13後,就得到這個”兩個連續的物理頁面”的開頭,而這個開頭正好是task_struct的開始,從而得到了指向task_struct的指標。
在核心2.6中堆疊這麼定義:
union thread_union {
struct thread_info thread_info;
unsigned long stack[THREAD_SIZE/sizeof(long)];
};
根據核心的配置,THREAD_SIZE既可以是4K位元組(1個頁面)也可以是8K位元組(2個頁面)。thread_info是52個位元組長。
下圖是當設為8KB時候的核心堆疊:Thread_info在這個記憶體區的開始處,核心堆疊從末端向下增長。程序描述符不是在這個記憶體區中,而分別通過task與thread_info指標使thread_info與程序描述符互聯。所以獲得當前程序描述符的current定義如下:
#define current get_current()
static inline struct task_struct * get_current(void)
{
return current_thread_info()->task;
}
static inline struct thread_info *current_thread_info(void)
{
struct thread_info *ti;
__asm__("andl %%esp,%0; ":"=r" (ti) : "" (~(THREAD_SIZE - 1)));
return ti;
}
根據THREAD_SIZE大小,分別遮蔽掉核心棧的12-bit LSB(4K)或13-bit LSB(8K),從而獲得核心棧的起始位置。
struct thread_info {
struct task_struct *task; /* main task structure */
struct exec_domain *exec_domain; /* execution domain */
unsigned long flags; /* low level flags */
unsigned long status; /* thread-synchronous flags */
... ..
}
fork系統呼叫中呼叫dup_task_struct,其執行:
1, 執行alloc_task_struct巨集,為新程序獲取程序描述符,並將描述符放在區域性變數tsk中。
2, 執行alloc_thread_info巨集以獲取一塊空閒的記憶體區,用以存放新程序的thread_info結構和核心棧,並將這塊記憶體區欄位的地址放在區域性變數ti中(8K 或 4K, 可配置)。
3, 將current程序描述符的內容複製到tsk所指向的task_struct結構中,然後把tsk->thread_info置為ti。
4, 把current程序的thread_info描述符的內容複製到ti中,然後把ti->task置為tsk。
5, 返回新程序的描述符指標tsk。
static struct task_struct *dup_task_struct(struct task_struct *orig)
{
struct task_struct *tsk;
struct thread_info *ti;
prepare_to_copy(orig);
tsk = alloc_task_struct();
if (!tsk)
return NULL;
ti = alloc_thread_info(tsk);
if (!ti) {
free_task_struct(tsk);
return NULL;
}
*tsk = *orig;
tsk->thread_info = ti;
setup_thread_stack(tsk, orig);
…..
}
# define alloc_task_struct() kmem_cache_alloc(task_struct_cachep, GFP_KERNEL)
#define alloc_thread_info(tsk) /
((struct thread_info *) __get_free_pages(GFP_KERNEL,THREAD_ORDER))
#endif
核心棧空間大小非常有限,故在核心中寫程式時,注意儘量不要定義大的區域性變數,儘量不要使用遞迴(導致函式呼叫棧過大而導致棧溢位),當需要空間時,使用kmalloc在堆中申請。