下面开启A20地址线
操作系统从实模式转换成保护模式时需要开启A20地址线,那什么是A20地址线呢?
在8086/8088CPU中,地址线只有20根,而寄存器都是16位的,为了能够使用20位地址线,它采用段地址:偏移地址的形式,寻址范围就可以达到1M,但是到了80286地址线达到24根,80386达到32根寻址能力达到4GB。为了向后兼容,IBM采用了一个控制方法:用键盘
控制器上的一个空闲的控制线来控制。即A20控制线。当A20打开时可以使用20-31的地址线,如果A20没有打开,后面的地址线就不可以使用,全部为0。
所以,激活A20地址线的流程为:
1.关闭中断;
2.等待8042 Input buffer为空;
3.发送禁止键盘操作命令;
4.等待8042 Input buffer为空;
5.发送读取8042 Output Port命令;
6.等待8042 Output buffer有数据;
7.读取8042 Output buffer,并保存得到的字节;
8.等待8042 Input buffer为空;
9.发送Write 8042 Output Port命令到8042 Input buffer;
10.等待8042 Input buffer为空;
11.将从8042 Output Port得到的字节的第2位置1(或清0),然后写入8042 Input buffer;
12.等待,直到8042 Input buffer为空为止;
13.发送允许键盘操作命令到8042 Input buffer;
14. 打开中断。
下面是as86的汇编代码(linux0.11内核中)
- call empty_8042
- mov al,#0xD1 ! command write
- out #0x64,al
- call empty_8042
- mov al,#0xDF ! A20 on
- out #0x60,al
- call empty_8042
- mpty_8042:
- .word 0x00eb,0x00eb
- in al,#0x64 ! 8042 status port
- test al,#2 ! is input buffer full?
- jnz empty_8042 ! yes - loop
- ret
然后对中断进行编程
实际上就是设置8259中断控制器的ICW字
- mov $0x11, %al # initialization sequence(ICW1)
- # ICW4 needed(1),CASCADE mode,Level-triggered
- out %al, $0x20 # send it to 8259A-1
- .word 0x00eb,0x00eb # jmp $+2, jmp $+2
- out %al, $0xA0 # and to 8259A-2
- .word 0x00eb,0x00eb
- mov $0x20, %al # start of hardware int's (0x20)(ICW2)
- out %al, $0x21 # from 0x20-0x27
- .word 0x00eb,0x00eb
- mov $0x28, %al # start of hardware int's 2 (0x28)
- out %al, $0xA1 # from 0x28-0x2F
- .word 0x00eb,0x00eb # IR 7654 3210
- mov $0x04, %al # 8259-1 is master(0000 0100) --/
- out %al, $0x21 # |
- .word 0x00eb,0x00eb # INT /
- mov $0x02, %al # 8259-2 is slave( 010 --> 2)
- out %al, $0xA1
- .word 0x00eb,0x00eb
- mov $0x01, %al # 8086 mode for both
- out %al, $0x21
- .word 0x00eb,0x00eb
- out %al, $0xA1
- .word 0x00eb,0x00eb
- mov $0xFF, %al # mask off all interrupts for now
- out %al, $0x21
- .word 0x00eb,0x00eb
- out %al, $0xA1
其中.word 0x00eb是直接进跳转指令的操作码,带一个字节的相对移位值,移动范围是-127--+127CPU通过将这个移位值加到EIP寄
存器,形成新的地址。实际上就是起到延迟的作用。
最后,进入32位的保护模式运行,首先加载机器状态字,CR0,其比特位0置1表示CPU工作在保护模式下。
下面分别是AS86格式和AT&T汇编格式
- mov ax,#0x0001 ! protected mode (PE) bit
- lmsw ax ! This is it!
- jmpi 0,8 ! jmp offset 0 of segment 8 (cs)
- mov %cr0, %eax # get machine status(cr0|MSW)
- bts $0, %eax # turn on the PE-bit
- mov %eax, %cr0 # protection enabled
- # segment-descriptor (INDEX:TI:RPL)
- .equ sel_cs0, 0x0008 # select for code segment 0 ( 001:0 :00)
- ljmp $sel_cs0, $0 # jmp offset 0 of code segment 0 in gdt
