LearningOS / rCore-Tutorial-Guide-2023S

GNU General Public License v3.0
12 stars 2 forks source link

rCore-Tutorial-Guide-2023S/chapter8/1thread-kernel #10

Open utterances-bot opened 1 year ago

utterances-bot commented 1 year ago

内核态的线程管理 - rCore-Tutorial-Guide-2023S 文档

https://learningos.github.io/rCore-Tutorial-Guide-2023S/chapter8/1thread-kernel.html

Unik-lif commented 1 year ago

当进程调用 thread_create 系统调用后,内核会在这个进程内部创建一个新的线程,这个线程能够访问到进程所拥有的代码段, 堆和其他数据段。但内核会给这个新线程分配一个它专有的用户态栈,这样每个线程才能相对独立地被调度和执行。

应该是为线程分配内核栈吧,我看了源码,似乎线程们创建时用到的用户栈ustack_base都是一致的,而内核会利用kstack_alloc给他们分配内核栈

Unik-lif commented 1 year ago

似乎线程们创建时用到的用户栈ustack_base都是一致的

继续往下读源码发现自己的理解有错,ustack_base是用户栈集中存放的虚拟地址基地址,并不是真正用户栈所在的位置,这个地址空间由进程TCB所对应的地址空间memory_set所管理,具体来说分配的用户栈位置可以参考函数alloc_user_res,此外,他们的trap_cx存放位置也会受tid等相关参数影响。

 pub fn alloc_user_res(&self){
        //.....................
        // alloc user stack
        let ustack_bottom = ustack_bottom_from_tid(self.ustack_base, self.tid);
        let ustack_top = ustack_bottom + USER_STACK_SIZE;
        process_inner.memory_set.insert_framed_area(
            ustack_bottom.into(),
            ustack_top.into(),
            MapPermission::R | MapPermission::W | MapPermission::U,
        );
        // alloc trap_cx
        let trap_cx_bottom = trap_cx_bottom_from_tid(self.tid);
        let trap_cx_top = trap_cx_bottom + PAGE_SIZE;
        process_inner.memory_set.insert_framed_area(
            trap_cx_bottom.into(),
            trap_cx_top.into(),
            MapPermission::R | MapPermission::W,
        );
}