2011年9月16日 星期五

x86 Segment Translation

Purpose
Virtual memory的目的是為了提供
1. abstraction of contiguous, isolated memory to a program.
2. prevent illegal operation

x86 processor modes

1. real mode: 20-bit address space (1MB), direct memory access, segmentation available
2. protected mode: 這時候就有segmentation and paging, 加上user / kernel space
3. long mode: 64-bit mode for x86-64
機器一開機後先進入real mode, boot loader轉成protected mode之後交給OS

x86 segmentation
a segment has: base address (linear addr), length, and type (code, data, etc)
a segment for: code, data, stack, and some extra...
一個program最多可以有6個segments, ex: CS, DS, SS, ES, FS, GS

利用不同的instruction type來推測現在是使用甚麼segment register
1. Control flow: CS
2. Stack management: SS
3. Most load/stores: DS
segment register有16bit, 包含index, 指向table裡面的entry.
所以當值行這些instruction時, processor自動去把相對映的segment selector load進來, 然後把base address, limit, type從Descriptor table中讀出 (see 5.1.4, ref2)


為何OS要定義segment?
1. memory protection (similar to paging)
2. 每個segment都有自己的permission, ex: CS: read-only
3. Process只能對特定的segment做特定的存取, ex: write to CS會造成segmentation fault!
4. provide location information in memory and flag to indicate whether it resides in memory.
MMU: 用來做virtual to physical memory位址轉換
reference: http://en.wikipedia.org/wiki/Memory_segmentation

Memory management register
"The processor provides four memory-management registers (GDTR, LDTR, IDTR, and TR) that specify the locations of the data structures which control segmented memory management" -- IA-32
x86 processor定義了四個register: gdtr, ldtr, idtr, and tr. 目的是為了方便存取這些table, 由這些table去拿到linear address.
GDT: any process can use these segments
LDT: segment definitions for a specific process

From: IA-32 chapter2
1. Exception發生: idtr -> trap gate -> LDT -> exception handler
2. Interrupt發生: IDT -> GDT-> interrupt handler
3. Process context switch: TR -> GDT -> TSS (把資料存下後 context switch)

Interrupt分為三種: Interrupt Gate, Trap Gate, and Task Gate
Interrupt發生時先根據IRQ number查IDT, 然後到GDT裡面拿到要執行code的segment. 之後就下instruction "CALL CS:IP"跳到handler
Gate通常指的是從一種privilege跳到另一個level of privilege.








 Reference:
1. CSE506 slides by Don Porter
2. http://www.cs.sunysb.edu/~porter/courses/cse506/f11/ref/i386/s05_01.htm

沒有留言:

張貼留言