我一直试图围绕 xv6 引导加载程序的 C 部分(问题在代码下方)
void
bootmain(void)
{
struct elfhdr *elf;
struct proghdr *ph, *eph;
void (*entry)(void);
uchar* pa;
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; // let bootasm.S handle error
// 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.
// Does not return!
entry = (void(*)(void))(elf->entry);
entry();
}
void
waitdisk(void)
{
// Wait for disk ready.
while((inb(0x1F7) & 0xC0) != 0x40)
;
}
// Read a single sector at offset into dst.
void
readsect(void *dst, uint offset)
{
// Issue command.
waitdisk();
outb(0x1F2, 1); // count = 1
outb(0x1F3, offset);
outb(0x1F4, offset >> 8);
outb(0x1F5, offset >> 16);
outb(0x1F6, (offset >> 24) | 0xE0);
outb(0x1F7, 0x20); // cmd 0x20 - read sectors
// Read data.
waitdisk();
insl(0x1F0, dst, SECTSIZE/4);
}
// Read 'count' bytes at 'offset' from kernel into physical address 'pa'.
// Might copy more than asked.
void
readseg(uchar* pa, uint count, uint offset)
{
uchar* epa;
epa = pa + count;
// Round down to sector boundary.
pa -= offset % SECTSIZE;
// Translate from bytes to sectors; kernel starts at sector 1.
offset = (offset / SECTSIZE) + 1;
// If this is too slow, we could read lots of sectors at a time.
// We'd write more to memory than asked, but it doesn't matter --
// we load in increasing order.
for(; pa < epa; pa += SECTSIZE, offset++)
readsect(pa, offset);
}
所以它使用CHS 寻址方案,即将扇区索引、柱面编号和磁头编号输出到磁盘端口并发出读取命令(请参阅 参考资料readsect(dst, offset)
)。
该offset
函数采用的参数应该包含从磁盘起始扇区开始的偏移量。例如,如果您0x01000203
作为偏移量(16777731
十进制)传递,它会将其拆分0x03
为扇区索引、0x0002
柱面编号和0x01
磁头编号。问题是扇区索引不能从0x00
to 0xFF
,它只能从0x01
to 0x3F
(十进制的1
to 63
),所以这个寻址方案是不连续的。例如, anoffset
0x100002EE
将是无效的,因为没有扇区索引0xEE
。
我真的不明白内核是如何成功加载到内存中的。在readseg()
函数中,很明显您可以将任何内存偏移量传递给它,它会将其转换为扇区偏移量并传递给readsect()
,可能会传递无效的扇区索引。如果内核大小永远不会超过63 * 512 = 32256
字节,那就没问题了,因此永远不会达到无效的扇区索引,但它实际上是 170k 左右。
到底是怎么回事?