x86架构上下文切换时段选择器存储位置及现代OS相关技术疑问
Great questions—let's unpack these clearly, since segment handling in x86 can feel a bit arcane once you move past the basics.
1. Where are segment selectors stored during context switching in x86?
In classic x86 protected mode, there are two primary mechanisms for this:
- Hardware-assisted task switching: The CPU relies on a Task State Segment (TSS) for each task or thread. When a context switch is triggered (via
CALL/JMPto a task gate, or an interrupt), the CPU automatically saves the current values of all segment registers (CS, DS, SS, etc.) into the active task's TSS. It then loads the new task's segment selector values from its corresponding TSS into the registers. - Software-implemented context switching (used by nearly all modern operating systems): The OS bypasses the hardware TSS system entirely. Instead, it saves segment register values (alongside other register state) into a thread control block (TCB) or process control block (PCB)—a kernel-managed data structure dedicated to each thread/process. When switching back to the thread, the OS loads these saved values back into the segment registers.
2. What about modern OSes like Windows/Linux where CS/DS seem unused?
First, a quick correction: They aren’t completely unused—we just use a flat memory model that makes their effect invisible in most scenarios. Here’s the breakdown:
- In 32-bit mode, all user-space segments have a base address of 0 and a limit of 4GB, so every pointer maps directly to physical memory (via paging). Kernel segments follow the same pattern but operate at a higher privilege level. The segment selectors still exist, but they’re standardized (e.g., user CS is 0x23, kernel CS is 0x08 on Linux x86).
- In 64-bit mode (long mode), most segment registers (DS, ES, FS, GS) are effectively ignored—their base is treated as 0, and limits are disregarded. Only CS and SS still matter for privilege level checks (user mode vs. kernel mode).
Where are the segment selectors stored now?
Just like in the classic case: They’re saved in each thread’s TCB/PCB as part of the thread’s full context state. Even if the values are identical across most threads (e.g., all user threads use the same user CS selector), the OS still saves and restores them during context switching to maintain correct register state.
Does each thread have independent segment selectors?
For standard flat model segments (CS, DS, SS, ES): No—threads running at the same privilege level share identical selectors. For example, every user-space thread on Linux uses the same CS (0x23) and DS (0x2B) selectors.
The exception is Thread-Local Storage (TLS): On 32-bit systems, some OSes use dedicated segment selectors per thread for TLS. On 64-bit systems, we use the GS register (with its base set via a model-specific register, MSR) instead of segment selectors, but the core idea is the same—each thread has its own isolated TLS space.
内容的提问来源于stack exchange,提问作者c.critter

