xv6 完整的启动链路
flowchart TD
A["上电<br/>CPU 从 0xfffffff0 取指"] --> B["BIOS(主板 ROM,非 xv6)<br/>磁盘第 0 扇区 → 0x7c00<br/>校验 0x55AA 签名后跳转"]
B --> C["bootasm.S · 引导扇区 512B<br/>16位实模式 → 32位保护模式<br/>cli · 开 A20 · lgdt · ljmp"]
C --> D["bootmain.c<br/>PIO 读磁盘(端口 0x1F0~0x1F7)<br/>解析 ELF,逐段加载内核<br/>.bss 清零 → 跳 entry"]
D --> E["entry.S · 内核入口<br/>CR4.PSE + CR3=entrypgdir<br/>开分页 → 设内核栈<br/>jmp main()"]
E --> F["main() · 内核初始化<br/>kinit / seginit / tvinit / ideinit...<br/>startothers 唤醒其他 CPU<br/>最后调 userinit()"]
F --> G["userinit()<br/>allocproc:内核栈三层布局<br/>inituvm:内嵌 initcode → 地址0<br/>伪造 trapframe<br/>eip=0 · esp=PGSIZE · Ring3"]
G --> H["scheduler()<br/>swtch → forkret → trapret<br/>iret 返回用户态"]
H --> I["initcode.S · 第一个用户程序<br/>push argv / push init / push 0<br/>eax=SYS_exec → int 64"]
I --> J["内核 sys_exec → exec()<br/>加载 /init 的 ELF<br/>改写 tf->eip 与 tf->esp"]
J --> K["init.c · pid=1 常驻<br/>open/dup 控制台(0,1,2)<br/>循环 fork + exec sh"]
K --> L["sh · 命令行 shell<br/>init 守护它,死了就重启"]
第 0 步:上电 → BIOS(不是 xv6)
CPU 上电后从 0xfffffff0 开始执行,那里是主板 ROM 里的 BIOS 固件。BIOS 完成自检后,把硬盘第 0 扇区(512 字节)读到物理地址 0x7c00,检查最后两字节是否为签名 0x55AA(sign.pl 干的事),是则跳过去。从此 xv6 接管。
第 1 步:bootasm.S —— 引导扇区,xv6 最早执行的代码
# Start the first CPU: switch to 32-bit protected mode, jump into C.
# The BIOS loads this code from the first sector of the hard disk into
# memory at physical address 0x7c00 and starts executing in real mode
# with %cs=0 %ip=7c00.
此刻 CPU 还在 16 位实模式(%cs=0, %ip=0x7c00),这段代码要干三件事:
① 关中断 + 清零数据段寄存器
start:
cli # BIOS enabled interrupts; disable
# Zero data segment registers DS, ES, and SS.
xorw %ax,%ax
movw %ax,%ds # -> Data Segment
movw %ax,%es
movw %ax,%ss
② 打开 A20 地址线(早期 PC 的地址线被强制拉低,需要往键盘控制器端口写命令解锁,否则访问不了 1MB 以上内存):
seta20.2:
inb $0x64,%al # Wait for not busy
testb $0x2,%al
jnz seta20.2
movb $0xdf,%al # 0xdf -> port 0x60
outb %al,$0x60
③ 加载临时 GDT → 打开保护模式 → 长跳转刷新 %cs → 设段寄存器 → call C
lgdt gdtdesc
movl %cr0, %eax
orl $CR0_PE, %eax
movl %eax, %cr0
ljmp $(SEG_KCODE<<3), $start32
.code32
start32:
movw $(SEG_KDATA<<3), %ax
...
movl $start, %esp
call bootmain
注意这里的 GDT 是”引导专用”的,段基址都是 0,所以虚拟地址 = 物理地址(恒等映射),切换到保护模式后内存布局没变,代码才能继续往下跑。最后 movl $start, %esp 把栈顶放在 start 标签处(栈向下生长,start 是代码开头,即 0x7c00,所以栈空间是 [0x7000, 0x7c00) 之间,没碰代码)。
关键约束:这个文件被链接在 0x7C00,最终只保留 .text 段,总大小必须 ≤ 512 字节(引导扇区就一扇区):
bootblock: bootasm.S bootmain.c
$(CC) $(CFLAGS) -fno-pic -O -nostdinc -I. -c bootmain.c
$(CC) $(CFLAGS) -fno-pic -nostdinc -I. -c bootasm.S
$(LD) $(LDFLAGS) -N -e start -Ttext 0x7C00 -o bootblock.o bootasm.o bootmain.o
$(OBJCOPY) -S -O binary -j .text bootblock.o bootblock
./sign.pl bootblock
第 2 步:bootmain.c —— 从磁盘把内核读进内存
bootasm.S 自己只占 512 字节,装不下内核,所以它 call bootmain 进入 C 代码,让 C 去读磁盘。
void
bootmain(void)
{
struct elfhdr *elf;
...
elf = (struct elfhdr*)0x10000; // scratch space
// Read 1st page off disk
readseg((uchar*)elf, 4096, 0);
// Is this an ELF executable?
if(elf->magic != ELF_MAGIC)
return;
// Load each program segment (ignores ph flags).
ph = (struct proghdr*)((uchar*)elf + elf->phoff);
eph = ph + elf->phnum;
for(; ph < eph; ph++){
pa = (uchar*)ph->paddr;
readseg(pa, ph->filesz, ph->off);
if(ph->memsz > ph->filesz)
stosb(pa + ph->filesz, 0, ph->memsz - ph->filesz);
}
// Call the entry point from the ELF header.
entry = (void(*)(void))(elf->entry);
entry();
}
- 磁盘第 1 扇区起就是内核 ELF 文件(Makefile:
dd if=kernel of=xv6.img seek=1)。 readseg里有个细节:offset = (offset / SECTSIZE) + 1,这个+1就是跳过第 0 扇区的引导块。- 按 ELF 的程序头逐段加载,
memsz > filesz时用stosb把.bss段清零(未初始化全局变量必须归零)。 - 最后跳到 ELF 头里写的
entry—— 就是entry.S。
底层读写用的是最原始的 PIO 方式(轮询 IDE 寄存器端口 0x1F0-0x1F7),waitdisk 就是等磁盘就绪标志:
readsect(void *dst, uint offset)
{
waitdisk();
outb(0x1F2, 1); // count = 1
outb(0x1F3, offset);
...
outb(0x1F7, 0x20); // cmd 0x20 - read sectors
waitdisk();
insl(0x1F0, dst, SECTSIZE/4);
}
第 3 步:entry.S —— 内核入口,开分页
main.c 开头注释说 “Bootstrap processor starts running C code here”,但跳到 C 之前 entry.S 还要开分页。
# By convention, the _start symbol specifies the ELF entry point.
# Since we haven't set up virtual memory yet, our entry point is
# the physical address of 'entry'.
.globl _start
_start = V2P_WO(entry)
.globl entry
entry:
# Turn on page size extension for 4Mbyte pages
movl %cr4, %eax
orl $(CR4_PSE), %eax
movl %eax, %cr4
# Set page directory
movl $(V2P_WO(entrypgdir)), %eax
movl %eax, %cr3
# Turn on paging.
movl %cr0, %eax
orl $(CR0_PG|CR0_WP), %eax
movl %eax, %cr0
# Set up the stack pointer.
movl $(stack + KSTACKSIZE), %esp
# Jump to main(), and switch to executing at high addresses.
mov $main, %eax
jmp *%eax
_start = V2P_WO(entry):分页还没开,CPU 只能访问物理地址,所以 ELF 入口必须用”去虚拟化”后的物理地址。- 用了
entrypgdir(在main.c第 102-108 行定义):把 VA [0,4MB) 和 VA [KERNBASE, KERNBASE+4MB) 都映射到 PA [0,4MB),用 4MB 大页(PTE_PS)。这样 entry.S 执行时还在低地址,一旦jmp *%eax跳进main(高地址),分页一开就自然切换到大地址空间。 - 内核 C 代码里所有指针都是
KERNBASE+物理地址(如P2V()),有了这个页表它们才成立。
第 4 步:main() —— 内核初始化 + 创建第一个进程
int
main(void)
{
kinit1(end, P2V(4*1024*1024)); // phys page allocator
kvmalloc(); // kernel page table
mpinit(); // detect other processors
lapicinit(); // interrupt controller
seginit(); // segment descriptors
picinit(); // disable pic
ioapicinit(); // another interrupt controller
consoleinit(); // console hardware
uartinit(); // serial port
pinit(); // process table
tvinit(); // trap vectors
binit(); // buffer cache
fileinit(); // file table
ideinit(); // disk
startothers(); // start other processors
kinit2(P2V(4*1024*1024), P2V(PHYSTOP)); // must come after startothers()
userinit(); // first user process
mpmain(); // finish this processor's setup
}
一长串初始化:物理内存分配器 → 内核页表 → 多处理器检测 → 两个中断控制器 → 控制台/串口 → 进程表 → 陷阱向量(IDT) → 缓冲区缓存 → 文件表 → IDE 磁盘 → 唤醒其他 CPU → 内存分配器扩容 → userinit() 创建第一个用户进程。
然后 mpmain() 最终进入 scheduler()(进程调度器,永不返回):
mpmain(void)
{
cprintf("cpu%d: starting %d\n", cpuid(), cpuid());
idtinit(); // load idt register
xchg(&(mycpu()->started), 1);
scheduler(); // start running processes
}
第 5 步:userinit() —— 手工捏出第一个进程
这是理解整条链的核心。第一个进程从未被创建过(没有 fork),所以它的一切都是伪造的。
① 分配 PCB + 内核栈(allocproc)
// Allocate kernel stack.
if((p->kstack = kalloc()) == 0){ ... }
sp = p->kstack + KSTACKSIZE;
// Leave room for trap frame.
sp -= sizeof *p->tf;
p->tf = (struct trapframe*)sp;
// Set up new context to start executing at forkret,
// which returns to trapret.
sp -= 4;
*(uint*)sp = (uint)trapret;
sp -= sizeof *p->context;
p->context = (struct context*)sp;
memset(p->context, 0, sizeof *p->context);
p->context->eip = (uint)forkret;
内核栈从顶往下依次铺三层:trapframe → trapret 地址 → context(eip=forkret)。这就是之前讲过的”套娃”:进程第一次被调度时,swtch 弹出 forkret 的入口,forkret 结束时 ret 会弹到 trapret,trapret 再 iret 弹回用户态。
② 复制 initcode 到用户地址 0 + 伪造 trapframe
p = allocproc();
initproc = p;
if((p->pgdir = setupkvm()) == 0)
panic("userinit: out of memory?");
inituvm(p->pgdir, _binary_initcode_start, (int)_binary_initcode_size);
p->sz = PGSIZE;
memset(p->tf, 0, sizeof(*p->tf));
p->tf->cs = (SEG_UCODE << 3) | DPL_USER;
p->tf->ds = (SEG_UDATA << 3) | DPL_USER;
p->tf->es = p->tf->ds;
p->tf->ss = p->tf->ds;
p->tf->eflags = FL_IF;
p->tf->esp = PGSIZE;
p->tf->eip = 0; // beginning of initcode.S
_binary_initcode_start就是 Makefile 里-b binary initcode嵌入内核的那个二进制 blob;inituvm把它复制到用户虚拟地址 0,用户栈顶是PGSIZE;p->tf手动填成”这个进程刚被硬件中断过“的样子:代码段选择子是用户代码段(DPL_USER,Ring 3)、eflags开中断、eip=0指向 initcode。稍后iret一执行,就”凭空”进入了用户态。
最后把状态置为 RUNNABLE,交给调度器:
acquire(&ptable.lock);
p->state = RUNNABLE;
release(&ptable.lock);
第 6 步:调度器选中它,initcode 在用户态跑起来
scheduler() 找到 RUNNABLE 的 initcode 进程,switchuvm 切到它的页表并更新 TSS,然后 swtch 切过去:
c->proc = p;
switchuvm(p);
p->state = RUNNING;
swtch(&(c->scheduler), p->context);
switchkvm();
执行路径:swtch 弹出 context->eip = forkret → forkret 里 iinit/initlog 初始化文件系统(这是第一次有”进程上下文”,可以安全调用会 sleep 的函数),然后函数 ret 弹到栈上预先放好的 trapret → trapret 按 p->tf 恢复寄存器 → iret 跳到 eip=0,用户态 Ring 3。第一个用户程序 initcode.S 开始执行:
# exec(init, argv)
.globl start
start:
pushl $argv
pushl $init
pushl $0 // where caller pc would be
movl $SYS_exec, %eax
int $T_SYSCALL
# for(;;) exit();
exit:
movl $SYS_exit, %eax
int $T_SYSCALL
jmp exit
# char init[] = "/init\0";
init:
.string "/init\0"
# char *argv[] = { init, 0 };
argv:
.long init
.long 0
三个 pushl 按 cdecl 从右往左压好 exec 的三个参数,int $64 进内核,syscall() 看 eax=SYS_exec 调 sys_exec,取出 path="/init" 和 argv,调用真正的 exec()。
第 7 步:exec("/init") —— 加载磁盘上的 init
exec 从文件系统(fs.img)读出 /init 的 ELF,重新分配页表加载程序段,并在新用户栈上构造 argc/argv 和返回地址:
// Push argument strings, prepare rest of stack in ustack.
for(argc = 0; argv[argc]; argc++) {
if(argc >= MAXARG)
return -1;
sp = (sp - (strlen(argv[argc]) + 1)) & ~3;
if(copyout(pgdir, sp, argv[argc], strlen(argv[argc]) + 1) < 0)
return -1;
ustack[argc] = sp;
}
ustack[argc] = 0;
...
sp = (sp - (argc+1) * 4) & ~3;
if(copyout(pgdir, sp, ustack, (argc+1)*4) < 0)
return -1;
p->tf->eip = elf.entry; // elf.entry = 0x1000 附近
p->tf->esp = sp;
注意这里 initcode 的使命完成了:它的 eip 被改写为 init 的入口,esp 指向新栈,之后 trapret 一 iret,initcode 的代码就被 init 的代码替换了(exec 不返回)。
第 8 步:init.c —— 第一个常驻的系统程序
init 是整个系统里第一个”正规的、会一直活着”的用户进程(pid=1)。它做的事:绑定控制台为标准输入输出,然后无限循环拉起来 shell:
char *argv[] = { "sh", 0 };
int
main(void)
{
int pid, wpid;
if(open("console", O_RDWR) < 0){
mknod("console", 1, 1);
open("console", O_RDWR);
}
dup(0); // stdout
dup(0); // stderr
for(;;){
printf(1, "init: starting sh\n");
pid = fork();
...
if(pid == 0){
exec("sh", argv);
printf(1, "init: exec sh failed\n");
exit();
}
while((wpid=wait()) >= 0 && wpid != pid)
printf(1, "zombie!\n");
}
}
shell 崩了或被退出,wait 返回,init 再 fork 一个新的 —— 这就是”守护”:init 是所有孤儿进程的收养者,也是系统里唯一不允许 exit 的进程(proc.c 的 exit() 里有 if(curproc == initproc) panic("init exiting"))。
一句话总览
BIOS 非 xv6,加载 0 扇区
bootasm.S 512 字节引导块:实模式 → 保护模式,call bootmain
bootmain.c PIO 读磁盘 ELF 内核,跳到 entry
entry.S 开分页(entrypgdir),跳到 main
main() 初始化一切硬件/子系统,userinit()
userinit() 伪造 trapframe,把内嵌的 initcode blob 放到用户地址 0
scheduler→forkret→trapret→iret initcode 在 Ring 3 执行
initcode exec("/init"),一次性跳板
init.c pid=1 常驻,循环拉起 sh
这条链的本质是层层”交接棒”:每个程序只做最少的事,把更复杂的活交给下一个——bootasm 交给 bootmain,bootmain 交给内核,内核伪造现场交给第一个用户程序,第一个用户程序又把镜像换成 /init。
留下评论