内核栈与thread_info结构详解

本文转载自内核栈与thread_info结构详解

什么是进程的内核栈?

在内核态(比如应用进程执行系统调用)时,进程运行需要自己的堆栈信息(不是原用户空间中的栈),而是使用内核空间中的栈,这个栈就是进程的内核栈

进程的内核栈在计算机中是如何描述的?

linux中进程使用task_struct数据结构描述,其中有一个stack指针

struct task_struct
{
    // ...
    void *stack;    //  指向内核栈的指针
    // ...
};

task_struct数据结构中的stack成员指向thread_union结构(Linux内核通过thread_union联合体来表示进程的内核栈)

union thread_union {
	struct thread_info thread_info;
	unsigned long stack[THREAD_SIZE/sizeof(long)];  
};

struct thread_info是记录部分进程信息的结构体,其中包括了进程上下文信息:

struct thread_info {
	struct pcb_struct	pcb;		/* palcode state */
 
	struct task_struct	*task;		/* main task structure */  /*这里很重要,task指针指向的是所创建的进程的struct task_struct
	unsigned int		flags;		/* low level flags */
	unsigned int		ieee_state;	/* see fpu.h */
 
	struct exec_domain	*exec_domain;	/* execution domain */  /*表了当前进程是属于哪一种规范的可执行程序,
                                                                        //不同的系统产生的可执行文件的差异存放在变量exec_domain中
	mm_segment_t		addr_limit;	/* thread address space */
	unsigned		cpu;		/* current CPU */
	int			preempt_count; /* 0 => preemptable, <0 => BUG */
 
	int bpt_nsaved;
	unsigned long bpt_addr[2];		/* breakpoint handling  */
	unsigned int bpt_insn[2];
 
	struct restart_block	restart_block;
};

img

从用户态刚切换到内核态以后,进程的内核栈总是空的。因此,esp寄存器指向这个栈的顶端,一旦数据写入堆栈,esp的值就递减

thread_info的作用是?

这个结构体保存了进程描述符中中频繁访问和需要快速访问的字段,内核依赖于该数据结构来获得当前进程的描述符(为了获取当前CPU上运行进程的task_struct结构,内核提供了current宏。

    #define get_current() (current_thread_info()->task)
    #define current get_current()

内核还需要存储每个进程的PCB信息, linux内核是支持不同体系的的, 但是不同的体系结构可能进程需要存储的信息不尽相同,

这就需要我们实现一种通用的方式, 我们将体系结构相关的部分和无关的部门进行分离,用一种通用的方式来描述进程, 这就是struct task_struct, 而thread_info

就保存了特定体系结构的汇编代码段需要访问的那部分进程的数据,我们在thread_info中嵌入指向task_struct的指针, 则我们可以很方便的通过thread_info来查找task_struct

内核栈的大小?

进程通过alloc_thread_info函数分配它的内核栈,通过free_thread_info函数释放所分配的内核栈,查看源码

alloc_thread_info函数通过调用__get_free_pages函数分配2个页的内存(8192字节)

posted @ 2020-06-01 10:56  Yungyu  阅读(2407)  评论(0编辑  收藏  举报