Chapter 03-2:CPU Multitasking
===
:::info
雖然現代作業系統早已捨棄 x86 CPU 原生支援的 multitasking,但是我們仍然可以透過這個章節的範例,一窺當初 80386 設計的 CPU level multitasking。
  1. LDT
  2. Task Gate and TSS
:::
>[time=Sat, Sep 6, 2025 11:47 PM]
---
https://youtu.be/tACT3xxqcE4
<iframe width="560" height="315" src="https://www.youtube.com/embed/tACT3xxqcE4?si=nsvri2hA9n_kC2wR" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
>[!Note] Overview of Segment Descriptors

# LDT
>Reference: [使用Local Descriptor Table (LDT)](https://jasonblog.github.io/note/os/1415.html)
>[!Note] LDT segment descriptor
>
>
>[!Note] LLDT: Load LDT
>
>[!Note] Memory Layout
>
>[!Note] Code Flow
>
## Source Code
https://github.com/srhuang/a-os/commit/248e558b13d57bfdfdb98e9b017d9115723c2144
## Compile
```sh
nasm boot/loader.s -I boot/ -o out/loader.bin
```
## Put on hard disk
```sh
dd if=../code/out/loader.bin of=./60mb.img bs=512 count=4 seek=1 conv=notrunc
```
## Checkpoint


# Task Gate
>[!Note] Task State Segment (TSS)
>Reference: [Task State Segment](https://pdos.csail.mit.edu/6.828/2004/readings/i386/s07_01.htm)
>
>[!Note] TSS Descriptor
>Reference: [Task Gate Descriptor](https://pdos.csail.mit.edu/6.828/2004/readings/i386/s07_04.htm)
>
>[!Note] Task Gate Descriptor
>
>[!Note] call task gate steps
>Reference: [Task Switching](https://pdos.csail.mit.edu/6.828/2004/readings/i386/s07_05.htm)
>1. Get new TSS Selector from task gate.
>2. Get new TSS Descriptor from GDT.
>3. Check new TSS Descriptor: P should be `1`, B should be `0`.
>4. Get old TSS position from TR Register and backup all registers.
>5. Load new TSS position to TR Register and restore all registers.
>6. Set new TSS Descriptor: B = `1`.
>7. Set Register elfags: NT = `1`.
>8. Set new TSS: `BACK LINK TO PREVIOUS TSS`.
>9. Jump to new TSS.
>[!Note] iret steps
>1. Set Register eflags: NT = `0`.
>2. Set current TSS Descriptor: B = `0`.
>3. Get current TSS position from TR Register and backup all registers.
>4. Get `BACK LINK TO PREVIOUS TSS`, and load it to TR register, and restore all registers.
>5. Jump to previous TSS.
>[!Note] Memory Layout
>
>[!Note] Code Flow
>
## Source Code
https://github.com/srhuang/a-os/commit/e8b9c9e13367e306fd4a011d4416145d82cbb571
## Compile
```sh
nasm boot/loader.s -I boot/ -o out/loader.bin
```
## Put on hard disk
```sh
dd if=../code/out/loader.bin of=./60mb.img bs=512 count=4 seek=1 conv=notrunc
```
## Checkpoint

