14 32-bit protected mode

32-bit protected mode 與 16-bit real mode 的差別:

  • register 變成 32 bit
  • 多了兩個 general purpose 的 segment register,fsgs
  • 可以用 32-bit memory offset 了,所以可以 reference 到 4 GB 的 memory
  • memory segmentation 的機制變得更好,有以下優點:
    • 在 priviledge 比較高的 segment 的程式可以終止在 priviledge 比較低的 segment 的程式。
    • CPU 可以為 user process 使用 virtual memory 機制(像是 page),可以讓 memory 有更有效率的使用。
  • interrupt 變得更完善

要進入 32 bit protected mode,我們必須設置 GDT(global descriptor table),它定義了 memory segment 們跟它們的 protected-mode attribute。

另外進入 32 bit mode 後,就不能用 BIOS 了。因為進到 32 bit 沒有 BIOS 可用,32 bit OS 必須要自己提供所有硬體的 driver,才能使用這些硬體。

如何在螢幕上顯示訊息

我們要使用 32 bit mode 又沒有 BIOS 的情況下,首先遇到一個問題:怎麼在螢幕上顯示訊息呢?就像前面的 print_string routine。

display device 可以被設定成 text 模式與 graphics 模式兩種。而什麼東西會顯示在螢幕上——也就是螢幕的哪個 pixel 要亮——是由一塊表示螢幕上每個 pixel 的 memory 區域控制的。因此我們要在螢幕上顯示東西,等同在那塊 memory 寫入資料。兩種模式會用不同的 memory 區域,操作時要注意。

在 text 模式下,我們只需要在一塊特定的 memory 裡指定我們要印的字元以及其 attribute 即可畫出一個字元。這塊 memory 從 0xb8000 開始,用兩個 bit 表示一個字元,第一個 bit 是要印字元的 ASCII code,第二個 bit 則是 attribute,例如顏色。

[bits 32]

VIDEO_MEMORY equ 0xb8000
WHITE_ON_BLACK equ 0x0f

print_string_pm:
pusha
mov edx, VIDEO_MEMORY

print_string_pm_loop:
mov al, [ebx]
mov ah, WHITE_ON_BLACK

; if encounter null terminate
cmp al, 0
je print_string_pm_done

; write data into video memory, 1 char has 2 bits in video memory
mov [edx], ax

; index of string and video memory
add ebx, 1
add edx, 2

jmp print_string_pm_loop

print_string_pm_done:
popa
ret