CSAPP 速查表 (Quick Reference)

1. 計算機系統漫遊(A Tour of Computer Systems)

資訊表示與程式翻譯 → 資訊表示與程式翻譯

概念 重點
一切都是 bits 資料物件的意義由 context 決定;同一串 bytes 可為整數、浮點數、字串或指令
編譯系統四階段 Preprocessing (cpp) → Compilation (cc1) → Assembly (as) → Linking (ld);gcc 為 compiler driver
副檔名鏈 .c → .i → .s(text)→ .o → executable(binary);text/binary 分界在 assembler
relocatable object .o 不能直接執行,必須經 linking 成 executable object file
理解編譯系統三理由 最佳化效能、理解 link-time 錯誤、避免 buffer overflow 安全漏洞

(本筆記無公式)

硬體組織與程式執行 → 硬體組織與程式執行

概念 重點
四大硬體 buses、I/O devices、main memory (DRAM)、processor(含 PC、register file、ALU)
CPU 四種基本操作 Load、Store、Operate、Jump;PC 存下一條指令位址,CPU 不斷「執行、更新 PC」
DMA 磁碟資料直達主記憶體、不經 CPU;系統大量時間花在搬移資料
cache 與 locality SRAM cache 靠 locality 兼得大記憶體與快記憶體;懂 cache 可提升一個數量級
memory hierarchy L0=registers、L1~L3=SRAM、L4=main memory、L5=disk、L6=remote;每層是下層的 cache

(本筆記無公式)

作業系統抽象與網路 → 作業系統抽象與網路

概念 重點
三大抽象 files → I/O devices;virtual memory → main memory + disk;processes → CPU+記憶體+I/O
Context switch Context = PC + register file + 記憶體內容;三步驟:save 舊 → restore 新 → 交出控制權
Kernel 不是 process,是常駐記憶體的 code 與資料結構;應用程式經 system call 進入
位址空間五區 code/data → heap → shared libraries → user stack → kernel(user 不可讀寫)
File 就是位元組序列;所有 I/O 裝置(含網路)都建模成 file

公式

Amdahl 定律與並行主題 → Amdahl 定律與並行主題

概念 重點
Amdahl's Law 整體加速受改善部分佔比 α 與局部加速 k 共同限制;未改善的 (1−α) 是不可逾越瓶頸
Concurrency vs Parallelism concurrency = 多個同時活動;parallelism = 利用 concurrency 讓系統更快
平行三層次 thread-level → instruction-level(pipelining/superscalar)→ SIMD
Hyperthreading 複製 PC、register file 等,不複製浮點單元;逐週期切換 thread
四大抽象 ISA 抽象處理器、files 抽象 I/O、virtual memory 抽象記憶體、processes 抽象執行中程式

公式

2. 資訊的表示與處理(Representing and Manipulating Information)

資訊儲存與位元運算 → 資訊儲存與位元運算

概念 重點
byte 與 hex 最小可定址單位是 byte;1 hex digit = 4 bits;C 以 0x 前綴表示
endianness little endian 低位 byte 在低位址(Intel/ARM);big endian 高位在前
位元 vs 邏輯運算 & | ~ ^ 逐位運算;&& || ! 只回傳 0/1 且短路求值
移位 左移補 0;右移分 logical(補 0)與 arithmetic(補 MSB);unsigned 必為 logical
C 字串 ASCII 字元陣列 + null 結尾;文字資料與 endianness/word size 無關,最可攜

公式

整數表示 → 整數表示

概念 重點
B2U / B2T 無號每 bit 權重 2i;二補數 sign bit 權重 2w1;皆為雙射
cast 不變位元 signed/unsigned cast 位元樣式不變、只改解讀;混合運算時 signed 隱式轉 unsigned
擴展 unsigned 用 zero extension;two's complement 用 sign extension;先改大小再改型別
截斷 丟高位 = overflow:unsigned 為 xmod2k;signed 為 U2Tk(xmod2k)
經典 bug i <= length-1(length=0 wrap 成 UMax)、strlen(s)-strlen(t) > 0 永非負

公式

整數算術 → 整數算術

概念 重點
modular arithmetic w-bit 運算結果一律截斷為 mod 2w;C 對 overflow 不發任何訊號
溢位偵測 unsigned:s < x 即溢位;signed:兩正得非正 / 兩負得非負
位元層級相同 加減乘與左移在 unsigned 與 two's complement 位元層級完全相同
乘除最佳化 乘常數改寫成 shift+add/sub;除以 2k signed 須加 bias 才是向零捨入
安全漏洞 FreeBSD getpeername(負長度轉 size_t)、Sun XDR(malloc 乘法溢位)

公式

浮點數 → 浮點數

概念 重點
IEEE 754 三欄位 sign / exp(k bits)/ frac(n bits);float: k=8, n=23;double: k=11, n=52
三類值 normalized(implied leading 1)、denormalized(exp 全 0,±0 與 gradual underflow)、特殊值(∞ / NaN)
捨入 預設 round-to-even:僅 halfway 時取偶數 LSB;另有 toward-zero / down / up
運算性質 加法與乘法可交換但不可結合、不可分配;具單調性(NaN 除外)→ 編譯器最佳化必須保守
C 轉型 float/double→int 向零截斷,溢位得 TMin;int→float 可能捨入;double→float 可能成 ±∞

公式

3. 程式的機器層級表示(Machine-Level Representation of Programs)

程式編碼與資料格式 → 程式編碼與資料格式

概念 重點
x86-64 演進 每代 backward compatible;AMD 率先推 x86-64,Intel 實作稱 EM64T
可見狀態 PC (%rip)、16 個 64-bit 整數暫存器、condition codes、vector registers
指令編碼 長 1–15 bytes;固定起點有唯一解碼;objdump -d 反組譯只靠位元組序列
尾碼 b/w/l/q 對應 1/2/4/8 bytes;int=4 (l)、long 與指標=8 (q)
-Og 產生貼近原始 C 結構的機器碼,學習用;-O1/-O2 效能較佳但難對映

公式

資料搬移與算術運算 → 資料搬移與算術運算

概念 重點
暫存器規則 產生 4-byte 結果時高 4 bytes 清 0;1/2-byte 結果其餘 bytes 不變
mov 限制 兩 operand 不可同為 memory;movq immediate 限 32-bit(符號延伸),64-bit 用 movabsq
延伸 movz 零延伸、movs 符號延伸;無 movzlq(直接用 movl);cltq ≡ movslq %eax,%rax
leaq 只算 effective address 不碰記憶體,常用於乘加運算 a + b*s + Imm
右移分兩種 sar 算術右移補符號位、shr 邏輯右移補 0;唯一需區分 signed/unsigned 的運算

公式

控制流 → 控制流

概念 重點
Condition codes CF(unsigned overflow)、ZF(零)、SF(負)、OF(signed overflow);leaq 不改旗標
cmp / test cmp 依 S2−S1 設旗標(同 sub 不寫回);test 依 S1&S2(同 and 不寫回)
cmov 兩邊都求值再選,免 branch prediction;有副作用或可能出錯時不可用
迴圈翻譯 -Og 用 jump-to-middle;-O1 用 guarded-do(初始測試 + do-while)
switch jump table,執行時間與 case 數無關;範圍檢查以 unsigned 一條 ja 攔截兩邊

公式

程序與執行時堆疊 → 程序與執行時堆疊

概念 重點
三機制 passing control、passing data、allocating/deallocating memory;用不到的一律省略
stack 成長 向低位址成長,%rsp 指 stack top;return address 屬 caller 的 frame
傳參 前 6 個整數引數:%rdi %rsi %rdx %rcx %r8 %r9;回傳值 %rax;第 7 個起放 stack
callee-saved %rbx %rbp %r12–%r15 共 6 個,callee 須 push 保存、反序 pop 還原
遞迴 每次呼叫有私有 stack frame,LIFO 天然匹配 call-return;leaf procedure 免 frame

公式

陣列與異質資料結構 → 陣列與異質資料結構

概念 重點
陣列定址 T A[N] 連續 LN bytes;A[i] ≡(A+i);指標運算自動依型別大小縮放
二維陣列 row-major;VLA 需 imulq、固定大小只用 leaq/shift-add(組語判別法)
struct 欄位以編譯期 byte offset 定位;機器碼不含欄位名稱
union 所有欄位 offset 皆 0;可重新詮釋位元樣式;不同大小欄位有 endianness 陷阱
對齊 K-byte 物件位址須為 K 倍數;struct 插 gap、尾端 padding;SSE 強制 16-byte

公式

緩衝區溢位與指標安全 → 緩衝區溢位與指標安全

概念 重點
buffer overflow C 無邊界檢查,區域緩衝區與 return address 同在 stack,越界寫可覆寫返回位址
危險函式 gets/strcpy/strcat/sprintf 不知目標大小;應改用 fgets
防線一 ASLR stack 位址隨機化;可被 nop sled + 暴力破解
防線二 canary buf 與 saved state 間放隨機 canary(%fs:40),失敗呼叫 __stack_chk_fail
防線三 NX bit stack 可讀寫但不可執行,硬體檢查無效能代價

公式

浮點程式碼 → 浮點程式碼

概念 重點
暫存器 %xmm0–%xmm7 依序傳最多 8 個浮點參數(與整數分開計數);回傳值 %xmm0;全部 caller-saved
轉換 FP→整數 vcvttss2si 一律截斷;整數→FP vcvtsi2ss 三運算元格式
常數 AVX 浮點不能用 immediate;常數以 label(%rip) PC-relative 讀取
位元運算 vxorps 自 xor 得 0.0、and 遮罩做 fabs、xor sign bit 取負
比較 ucomiss/ucomisd 設 CF/ZF/PF;PF=1 表 unordered(NaN);搭配 ja/jb 而非 jg/jl

公式

4. 處理器架構(Processor Architecture)

Y86-64 指令集架構 → Y86-64 指令集架構

概念 重點
可見狀態 15 個 64-bit registers(無 %r15)+ ZF/SF/OF + PC + memory + Stat
movq 四拆 irmovq/rrmovq/mrmovq/rmmovq;不允許 memory-to-memory 與 immediate-to-memory
OPq addq/subq/andq/xorq 只能 register-register,且是唯一設 condition codes 的指令
Stat 狀態碼 AOK=1、HLT=2、ADR=3、INS=4;非 AOK 即停機
CISC/RISC 混血 變長編碼、CC、stack 返回位址(CISC)+ load/store、register 傳參(RISC)

公式

邏輯設計與 HCL → 邏輯設計與 HCL

概念 重點
三要素 combinational logic 計算、memory elements 儲存、clock 控制更新時機
組合電路限制 每個閘輸入恰接一個來源、輸出不可相接、網路必須 acyclic;無短路求值
clocked register 只在 clock 上升緣載入新狀態,是組合邏輯區塊間的屏障
register file 2 讀取埠 + 1 寫入埠;讀取像組合邏輯、寫入由 clock 控制;0xF 表不寫入
case expression 依序求值取第一個為 1 的 case;選擇條件不需互斥

公式

循序 SEQ 實作 → 循序 SEQ 實作

概念 重點
六階段 Fetch → Decode → Execute → Memory → Write back → PC update;每 cycle 一整條指令
new PC 三來源 valP(循序)、valC(call 與 taken jXX)、valM(ret)
No reading back 指令永不讀回自己剛更新的狀態;pushq 以 valE 同時當寫回資料與寫入位址
時序 只有 PC、CC、data memory、register file 需時序控制,由單一 clock 驅動
缺點 cycle time 由最長路徑決定(如 ret 四次串聯存取),引出 pipelining

公式

管線化原理 → 管線化原理

概念 重點
pipelining 切多個 stage、以 pipeline register 分隔;提高 throughput 但略增 latency
不均勻切割 週期被最慢 stage 綁死;ALU / 記憶體往往不可再細分
深管線遞減 register 延遲是固定 overhead;現代處理器 15+ stage 拉高時脈
feedback path 天真管線化會改變行為,違反 ISA 模型不可接受
SEQ+ 把 PC 計算移到週期開頭,用 pIcode/pCnd 等暫存器保存上一指令訊號

公式

PIPE 管線實作與冒險 → PIPE 管線實作與冒險

概念 重點
分支預測 call/jmp 用 valC、條件 jXX always taken(~60%)、ret 不預測直接 stall
forwarding 5 來源 (e_valE, m_valM, M_valE, W_valM, W_valE) → 2 目的地;execute > memory > write-back
load/use hazard m_valM 太晚,需 load interlock = stall 1 cycle + forwarding
control hazard ret 注入 3 bubbles;mispredicted branch squash 2 條誤抓指令
exception stat 隨指令流至 write-back 才生效;管線最深者優先;被 squash 者一併取消

公式

5. 最佳化程式效能(Optimizing Program Performance)

最佳化編譯器與其限制 → 最佳化編譯器與其限制

概念 重點
safe optimization 最佳化後在所有情況下行為必須相同,編譯器只能假設最壞情況
兩大 blockers memory aliasing(指標可能同址)與函式呼叫 side effects
code motion 把不變計算(vec_length、strlen)移出迴圈;編譯器不敢自動做
區域變數累加 combine4 用 acc 常駐暫存器,記憶體操作 2 讀 1 寫降為 1 讀
O(n²) 陷阱 lower1 在迴圈條件呼叫 strlen;移出後成線性,快逾 50 萬倍

公式

現代處理器運作 → 現代處理器運作

概念 重點
兩個下界 latency bound(嚴格循序相依)與 throughput bound(功能單元算力極限)
superscalar + OoO ICU 產生 micro-ops、EU 平行執行,retirement unit 保證循序語意
register renaming tag 轉發取值免經 register file,支撐 speculative execution
功能單元三參數 latency、issue time、capacity;issue=1 稱 fully pipelined;除法不 pipeline
critical path 跨迭代相依鏈決定效能下界;直接法勝 Horner 法的原因

公式

迴圈展開與平行度 → 迴圈展開與平行度

概念 重點
k × 1 展開 只減 loop overhead;critical path 仍 n 個運算,卡在 latency bound
k × k 多累加器 拆 k 組獨立累加,critical path 剩 n/k → CPE ≈ L/k,首次突破 latency bound
reassociation k × 1a 只改括號,元素互乘不在相依鏈 → CPE ≈ L/2
浮點注意 二補數加乘溢位仍 associative;浮點不可結合,重排可能改變結果
register spilling 展開因子過大 accumulator 溢到 stack,20×20 反比 10×10 慢

公式

限制因素與記憶體效能 → 限制因素與記憶體效能

概念 重點
分支 可預測分支幾乎零成本;不可預測分支改 functional style 促成 cmov
load 2 個 load units → CPE ≥ k/2;位址相依鏈(linked list)使 CPE = load latency
store fully pipelined;write/read dependency 同址時須等 store buffer 轉發
gprof -pg 編譯 → 執行 → gprof;interval counting <1 秒不準,呼叫計數可靠
優化三層次 高階設計(演算法)→ 基本編碼原則 → 低階優化(unrolling、cmov)

公式

6. 記憶體階層(The Memory Hierarchy)

儲存技術 → 儲存技術

概念 重點
SRAM vs DRAM SRAM 六電晶體、免 refresh、快 ~10 倍貴 ~1000 倍(cache);DRAM 1 電容 1 電晶體(主記憶體)
DRAM 讀取 RAS 送列位址複製整列進 row buffer → CAS 送行位址取 supercell
磁碟存取 seek + rotational latency 支配;首 byte 貴、其餘幾乎免費
DMA + interrupt CPU 下命令 → disk controller DMA 直寫記憶體 → 完成後 interrupt
SSD flash + FTL;寫入須整 block 先抹除;wear leveling 延長壽命

公式

區域性與記憶體階層 → 區域性與記憶體階層

概念 重點
兩種 locality temporal(剛用過很快再用)與 spatial(鄰近位址很快被用)
stride stride-1 空間區域性最佳;C 陣列 row-major,依列掃描才是 stride-1
階層中心思想 第 k 層是第 k+1 層的 cache,以 block 為傳輸單位;離 CPU 愈遠 block 愈大
三種 miss cold(空 cache 必 miss)、conflict(映射同位置)、capacity(working set 過大)
管理者 registers 由 compiler、L1-L3 由硬體、virtual memory 由 OS + 硬體

公式

快取記憶體 → 快取記憶體

概念 重點
(S, E, B, m) S 個 set、每 set E 條 line、每 line B bytes block;位址切 tag / set index / offset
三種組織 E=1 direct-mapped;1<E<C/B set associative;E=C/B fully associative(TLB)
conflict miss 2 的冪陣列交替存取互逐(thrashing);解法陣列尾端 padding B bytes
寫入策略 write-through + no-write-allocate 或 write-back + write-allocate(假設後者)
Core i7 L1 i/d 各 32KB 8-way(4 cy)、L2 256KB(10 cy)、L3 8MB 共享(40-75 cy);block 64B

公式

快取友善程式碼與記憶體山 → 快取友善程式碼與記憶體山

概念 重點
兩原則 讓 common case 快(專注 inner loop)+ 最小化 inner loop 的 cache miss
memory mountain throughput 對 size(temporal)與 stride(spatial)的 2D 函數;四條稜線 = L1/L2/L3/Mem
prefetching stride-1 平坦稜線來自 hardware prefetch,自動辨識循序模式
矩陣乘法 六版本分 AB(1.25)/ AC(2.00)/ BC(0.50)misses/iter;BC 最快近 40 倍
三守則 專注 inner loops、stride-1 循序讀、資料重複使用最大化 temporal locality

公式

7. 連結(Linking)

靜態連結與目的檔 → 靜態連結與目的檔

概念 重點
linker 兩大任務 symbol resolution(參照對應恰好一個定義)+ relocation(指派位址並修補參照)
目的檔三形式 relocatable / executable / shared;Linux 用 ELF 格式
section 分配 已初始化全域 → .data;未初始化全域 → COMMON;static 未初始化與初始化為 0 → .bss(不占檔案空間)
符號三類 global(本模組定義)、external(他模組定義)、local(static 僅模組內可見)
偽節 ABS、UNDEF、COMMON 只存在於 relocatable object file

(本筆記無公式)

符號解析與重定位 → 符號解析與重定位

概念 重點
強弱符號 函式與已初始化全域 = strong;未初始化全域 = weak
三規則 Rule 1 多強 → 錯誤;Rule 2 一強多弱 → 選強(無提示!);Rule 3 多弱 → 任選
靜態函式庫 archive (.a);linker 只複製被參照的 member;命令列順序有意義,函式庫放尾端
E/U/D 三集合 E 併入執行檔、U 未解析、D 已定義;掃描完 U 非空即報錯
relocation entry Elf64_Rela = {offset, type, symbol, addend};放 .rel.text / .rel.data

公式

可執行檔載入與動態連結 → 可執行檔載入與動態連結

概念 重點
可執行檔差異 多 entry point、program header table、.init;少 .rel sections(已完全重定位)
啟動流程 execve → loader → entry point _start(crt1.o)→ __libc_start_main → main
shared library .so 兩層共享:檔案系統僅一份、記憶體 .text 單一複本;gcc -shared -fpic
dynamic linker loader 見 .interp section 先執行 ld-linux.so 完成三項 relocation
PIC 資料引用經 GOT(data segment、8-byte entry);函式呼叫用 PLT + lazy binding

公式

函式庫插入與目的檔工具 → 函式庫插入與目的檔工具

概念 重點
interpositioning 攔截 shared library 函式呼叫,改執行同 prototype 的 wrapper
三種時機 compile-time(巨集 + -I.)、link-time(--wrap f)、run-time(LD_PRELOAD)
dlsym run-time wrapper 用 dlsym(RTLD_NEXT, "malloc") 取真版本,否則無限遞迴
binutils ar、strings、strip、nm、size、readelf、objdump(反組譯);ldd 列 shared libraries

公式

8. 例外控制流(Exceptional Control Flow)

例外 → 例外

概念 重點
exception 對 processor state 變化的回應;經 exception table 呼叫 handler;結果:回 I_curr / I_next / abort
四大類 Interrupt(async,回 I_next)、Trap(蓄意,回 I_next)、Fault(可能重執行 I_curr)、Abort(永不返回)
system call trap 是 user 進入 kernel mode 的受控入口;跑 kernel mode、用 kernel stack
常考編號 divide error=0、GPF=13、page fault=14、machine check=18;syscall:read=0, write=1, fork=57, execve=59, _exit=60

公式

行程與上下文切換 → 行程與上下文切換

概念 重點
process 定義 執行中程式的實例,在 context 中執行;兩大抽象:獨立邏輯控制流 + 私有位址空間
concurrent vs parallel 兩流時間區間重疊即 concurrent(與核心數無關);parallel 是其真子集(不同 core/機器)
user/kernel mode mode bit 控制;唯一升權途徑是例外(interrupt/fault/trap);違規 → fatal protection fault
context switch 三步驟:save 舊 context → restore 新 context → pass control;由 scheduler 決策
kernel 非行程 kernel 永遠「代表某行程」執行,切換中只是代表的對象改變

公式

Unix 錯誤處理 → Unix 錯誤處理

概念 重點
Unix-style 回傳 −1 + 設 errno;strerror(errno) 轉文字;錯誤碼與有用結果重載同一回傳值
Posix-style 回傳 0 成功 / 非零即錯誤碼;結果由參考引數帶回;用 strerror(retcode)
GAI-style getaddrinfo 系:非零 + gai_strerror(retcode),不能用 strerror
wrapper 慣例 首字母大寫 Foo:失敗印訊息後 exit,成功行為與基底完全相同(csapp.c/h)

(本筆記無公式)

行程控制 → 行程控制

概念 重點
fork call once, return twice:子得 0、父得子 PID;位址空間相同但獨立副本;共享 open file descriptors
回收 終止未被 reap = zombie;init(PID 1)收養孤兒;wait(&s) ≡ waitpid(-1, &s, 0)
waitpid pid>0 等單一子、pid=-1 等全部;WNOHANG 不阻塞回 0;WIFEXITED/WEXITSTATUS 判讀 status
execve call once, never return(成功);覆寫位址空間但 PID 不變、file descriptor 保留
shell eval:parseline → builtin? → Fork + execve;前景 waitpid、背景不等(需 SIGCHLD 回收)

公式

訊號 → 訊號

概念 重點
pending 不排隊 同型別至多一個 pending,多的直接丟棄;訊號不能計數事件;SIGCHLD handler 須 while(waitpid(...)>0)
不可攔截 SIGKILL (9) 與 SIGSTOP (19) 不能 catch/ignore
傳送 kill(pid,sig):pid=0 送自己群組全部、pid<0 送群組 |pid|;Ctrl+C/Ctrl+Z 送前景 process group
handler 準則 G0 簡單、G1 只用 async-signal-safe(printf 不安全,用 write/Sio)、G2 保存 errno、G3 阻擋訊號、G4 volatile、G5 sig_atomic_t
race 消除 fork 前阻擋 SIGCHLD、addjob 後解除;子行程先解除再 execve;等訊號用 sigsuspend

公式

非區域跳轉 → 非區域跳轉

概念 重點
setjmp/longjmp setjmp 呼叫一次、回傳多次(初次 0);longjmp 呼叫一次、永不回傳
應用 深層巢狀錯誤直接跳回集中 handler(小心 memory leak);signal handler 內 soft restart 用 sigsetjmp/siglongjmp
限制 rc = setjmp(env) 是錯誤寫法;siglongjmp 可達的程式碼只能呼叫 async-signal-safe 函式
對應 C++/Java 的 try-catch ≈ setjmp、throw ≈ longjmp;ECF 四層:硬體 exceptions → OS processes → signals → nonlocal jumps

公式

9. 虛擬記憶體(Virtual Memory)

位址空間與 VM 快取機制 → 位址空間與 VM 快取機制

概念 重點
虛擬定址 CPU 產生 VA,MMU 即時翻譯成 PA;page table 存主記憶體、由 OS 維護
VM = disk 的 DRAM cache 巨大 miss 成本 → fully associative + write-back + 大 page(4 KB–2 MB)
PTE 判讀 valid=1 → Cached;valid=0 + null → Unallocated;valid=0 + disk 位址 → Uncached
page fault DRAM cache miss;handler 換頁後重新執行 faulting instruction;demand paging
working set 放得進實體記憶體就高效;放不下 → thrashing

公式

VM 記憶體管理與保護 → VM 記憶體管理與保護

概念 重點
每行程一張表 一個 process = 一張 page table = 一個獨立虛擬位址空間;隔離是預設、共享是例外
簡化四事 linking(統一映像、code 起於 0x400000)、loading(零複製,demand paging)、sharing(多 VP 映同一 PP)、allocation(連續虛擬頁映任意實體頁)
權限位元 PTE 加 SUP / READ / WRITE,每次轉譯時硬體順路檢查,零額外成本
違規流程 general protection fault → kernel handler → SIGSEGV → "segmentation fault"

公式

位址轉譯與 TLB → 位址轉譯與 TLB

概念 重點
轉譯機制 PTBR 找 page table,VPN 索引 PTE,PPN 串接 VPO 得 PA;PPO = VPO 免轉譯
TLB MMU 內小型 virtually addressed PTE cache;hit 全在晶片內完成
多層 page table null 上層 PTE → 子表不存在;只有 level 1 須常駐;TLB cache 各層 PTE
Core i7 48-bit VA、52-bit PA;4 層表;CR3 存 L1 表基底(屬行程 context);A/D bit 由 MMU 設、kernel 清
Linux VM task_struct → mm_struct(pgd, mmap)→ vm_area_struct 串列;page fault 三段檢查:area? → 權限? → 正常換頁

公式

記憶體映射 → 記憶體映射

概念 重點
兩種來源 regular file 與 anonymous file(demand-zero pages,無實際磁碟傳輸)
shared vs private shared object 實體僅一份、寫入可見並回寫;private 用 copy-on-write,只複製被寫的那頁
fork 複製 mm_struct/area/page tables,雙方頁標 read-only + private COW,不立即複製
execve 四步 刪舊 user areas → 映射 private areas → 映射 shared areas → 設 PC 指 entry point

公式

動態記憶體配置 → 動態記憶體配置

概念 重點
heap demand-zero 區域,brk 指標記錄頂端;allocator 分 explicit(malloc/free)與 implicit(GC)
碎片化 internal(block > payload)易量化;external(總量夠但無單一夠大 free block)難量化
implicit free list header = size | alloc;prologue/epilogue 消除邊界條件;搜尋線性
boundary tags footer 為 header 複本,使合併前一 block 為常數時間(四種 case)
進階組織 explicit free list(pred/succ)、segregated fits(GNU malloc)、buddy system

公式

垃圾回收與記憶體錯誤 → 垃圾回收與記憶體錯誤

概念 重點
可達圖 root nodes(暫存器、stack、全域)指向 heap nodes;不可達的已配置區塊 = garbage
Mark&Sweep mark 遞迴標記可達;sweep 線性掃 heap free 未標記者;works in place 適合 C
conservative GC C 記憶體不帶型別,int 可偽裝成指標 → 只能保守標記,可能漏收
經典 bug scanf 忘 &、heap 不清零、sizeof 誤用、*size--、指標算術單位、回傳區域變數位址、memory leak

公式

10. 系統層級 I/O(System-Level I/O)

Unix I/O 與檔案 → Unix I/O 與檔案

概念 重點
統一模型 所有裝置皆檔案(位元組序列),open/read/write/close 統一操作
descriptor open 回傳目前未開啟的最小非負整數;0=stdin、1=stdout、2=stderr
file position kernel 維護 k;k ≥ m 時 read 回 0 = EOF(無 EOF 字元)
short count 不是錯誤;成因:EOF、終端機逐行、socket/pipe 緩衝;網路程式須反覆 read/write
open flags O_RDONLY/O_WRONLY/O_RDWR 三選一,可 OR O_CREAT/O_TRUNC/O_APPEND

公式

RIO 套件與檔案中繼資料 → RIO 套件與檔案中繼資料

概念 重點
RIO 自動處理 short count 與 EINTR 重啟;rio_readn/rio_writen 無緩衝、rio_readlineb/rio_readnb 緩衝
混用限制 緩衝函式可互相交錯,但不可與無緩衝 rio_readn 混用同一 descriptor
stat/fstat 填 struct stat;重點 st_mode(權限+類型)與 st_size
readdir 錯誤與 end-of-stream 都回 NULL:呼叫前 errno=0、結束後檢查 errno

公式

檔案共享、重導向與標準 I/O → 檔案共享、重導向與標準 I/O

概念 重點
三張表 descriptor table(每 process)、open file table(共享,含 position 與 refcnt)、v-node table
fork 子複製 descriptor table,父子共享 file table entry(共享 position),refcnt 加倍
dup2 複製 oldfd → newfd;shell 的 > 重導向即靠此
三守則 G1 磁碟/終端機用 standard I/O;G2 binary 檔勿用 scanf/rio_readlineb;G3 socket 一律用 RIO(lseek 非法)

公式

11. 網路程式設計(Network Programming)

主從式模型與網路 → 主從式模型與網路

概念 重點
transaction 四步 client 送 request → server 處理 → server 回 response → client 處理
process 而非機器 client/server 是 process;一台 host 可同時跑多個;網路對 host 只是另一個 I/O device
網路階層 Ethernet segment(hub)→ bridged LAN → WAN → internet(router)
encapsulation LAN frame 的 payload 是 internet packet,packet 的 payload 才是使用者資料

公式

全球 IP 網際網路 → 全球 IP 網際網路

概念 重點
TCP/IP 分層 IP 不可靠 host-to-host;UDP 擴到 process(仍不可靠);TCP 可靠 full-duplex 連線
IP address unsigned 32-bit,network byte order(big-endian);htonl/ntohl、htons/ntohs 轉換
DNS 分散式資料庫,域名 ↔ IP 多對多;localhost → 127.0.0.1
connection point-to-point、full duplex、reliable;client 用 ephemeral port、server 用 well-known port

公式

Socket 介面 → Socket 介面

概念 重點
建線流程 client:socket → connect;server:socket → bind → listen → accept
兩種 descriptor listening(活整個生命期)vs connected(每次 accept 建立)——支援 concurrent server
getaddrinfo 字串 → addrinfo linked list,走訪至成功;protocol-independent、reentrant;錯誤用 gai_strerror
open_listenfd setsockopt(SO_REUSEADDR) 消除 Address already in use
EOF 不是字元,是 kernel 偵測的條件;read/rio_readlineb 回 0 得知

公式

Web 伺服器與 Tiny → Web 伺服器與 Tiny

概念 重點
HTTP 文字式協定,每行以 CRLF 結尾;request line = method URI version
內容 static 讀磁碟檔;dynamic 執行 CGI 程式:fork → setenv QUERY_STRING → dup2 → execve
status codes 200 OK / 301 Moved / 400 Bad request / 403 Forbidden / 404 Not found / 501 Not implemented / 505 Version not supported
Tiny ~250 行 iterative HTTP/1.0,只支援 GET;serve_static 用 mmap + Close + Rio_writen + Munmap
SIGPIPE 對已關閉連線第二次 write 觸發 SIGPIPE;忽略後 write 回 −1 且 errno=EPIPE

(本筆記無公式)

12. 並行程式設計(Concurrent Programming)

行程與事件驅動並行 → 行程與事件驅動並行

概念 重點
三種途徑 processes(kernel 排程、私有空間)、I/O multiplexing(自行排程、單行程)、threads(混合)
process-based accept 後 fork;child close listenfd、parent close connfd;SIGCHLD 用 while 迴圈收割
select 阻塞至 read set 有描述子 ready;有副作用,每輪前須 ready_set = read_set
event-driven 每邏輯流是狀態機;優點:排程控制、共享易、可 gdb;缺點:複雜、難用多核

公式

執行緒 → 執行緒

概念 重點
thread context TID、stack、SP、PC、暫存器、condition codes;code/data/heap/open files 全共享
pool of peers 無父子階層,任何 peer 可 kill/join 任何 peer;context switch 比 process 快
終止四途徑 routine return、pthread_exit、exit(殺整個 process)、pthread_cancel
detach 預設 joinable 須 reap;伺服器慣用 pthread_detach(pthread_self()) 自我分離
傳 connfd 必須各自 Malloc,傳區域變數位址會與下一次 accept race

(本筆記無公式)

共享變數與號誌 → 共享變數與號誌

概念 重點
shared 定義 變數的某個 instance 被多於一個 thread 參考;registers 永不共享、VM 永遠共享
cnt++ 三步 Load-Update-Store;交錯造成 lost update;progress graph 的 unsafe region
semaphore 非負整數;P 為零則掛起、非零原子遞減;V 遞增並重啟一個等待者
mutex / sbuf mutex 初始 1(P=lock、V=unlock);bounded buffer:mutex=1、slots=n、items=0
prethreading master producer accept + sbuf_insert;worker pool consumer sbuf_remove

公式

平行化與執行緒安全 → 平行化與執行緒安全

概念 重點
psum 教訓 同步開銷極貴:psum-mutex 災難 → psum-array 免鎖 → psum-local 區域累加最快
四類 unsafe (1) 不保護共享變數 (2) 跨呼叫 static state(rand/strtok)(3) 回傳 static 指標(ctime)(4) 呼叫 unsafe 者
reentrant 不引用 shared data,是 thread-safe 的真子集;Linux 提供 _r 版本
deadlock mutex lock ordering rule:依 total ordering acquire、反序 release 即 deadlock-free
threads 數 超過核心數後 context switch 開銷微升 → 每核恰好一條 thread

公式

必背公式與判斷式

公式 / 判斷式 出處
S=1(1α)+α/k,S=11α(Amdahl) Amdahl 定律與並行主題
UMax=2w1;TMin=2w1;TMax=2w11;UMax=2TMax+1 整數表示
T2Uw(x)=x+2w (x<0);U2Tw(u)=u2w (u>TMax) 整數表示
unsigned 溢位:s<x;signed 溢位:兩正得非正 / 兩負得非負;-x == ~x + 1 整數算術
signed 向零除法:(x<0 ? x+(1<<k)-1 : x) >> k;x/y=(x+y1)/y 整數算術
V=(1)sM2E;Bias=2k11;norm:E=eBias,M=1+f;denorm:E=1Bias,M=f 浮點數
EA=Imm+R[rb]+R[ri]s,s{1,2,4,8} 資料搬移與算術運算
push:%rsp −= 8 再寫;pop:先讀再 %rsp += 8;call/ret 對 return address 同理 程序與執行時堆疊
signed 比較用 SF ^ OF 組合;unsigned 用 CF/ZF;PC-relative target = 下一指令位址 + offset 控制流
&D[i][j]=xD+L(Ci+j)(row-major,Eq. 3.1);對齊:K-byte 物件位址 ≡ 0 (mod K) 陣列與異質資料結構
傳參順序:%rdi %rsi %rdx %rcx %r8 %r9;回傳 %rax;浮點走 %xmm0–7 程序與執行時堆疊
Clock period = max(stage delay) + register delay;Throughput = 1/period 管線化原理
CPI=1.0+lp+mp+rp;bubbles:load/use=1、mispredict=2、ret=3 PIPE 管線實作與冒險
T=Overhead+CPE×n;latency bound CPE ≥ L、throughput bound CPE ≥ I/C 現代處理器運作
k × k 展開 CPE ≈ L/k;達 throughput bound 需 kC×L 迴圈展開與平行度
C=S×E×B;t=m(s+b);miss rate = misses/references 快取記憶體
Taccess=Tseek+Trotation+Ttransfer2×Tavg seek 儲存技術
misses/iter = min(1, word_size × k / B)(stride-k) 快取友善程式碼與記憶體山
強弱符號三規則:多強錯誤、一強多弱選強、多弱任選 符號解析與重定位
PC32 重定位:*refptr = ADDR(sym) + addend − (ADDR(s) + offset);絕對:ADDR(sym) + addend 符號解析與重定位
vaddrmodalign=offmodalign;.bss = memsz − filesz 可執行檔載入與動態連結
handler 位址 = exception table base + k × 8;syscall 錯誤:4095r1 例外
n 個 fork → 2n 個行程;可行輸出 = process graph 的 topological sort 行程控制
接收檢查 pending & ~blocked;訊號不排隊;sigsuspend = 原子版 block+pause+restore 訊號
setjmp 呼叫一次回傳多次(初次 0);longjmp 永不回傳 非區域跳轉
#PTE = 2np;PA = PPN ‖ VPO;PPO = VPO;TLBI = VPN 低 t 位 位址轉譯與 TLB
page fault:換頁後重新執行 faulting instruction;權限違規 → SIGSEGV VM 記憶體管理與保護
Uk=maxikPi/Hk;header = size | alloc;asize 向上取整 16 動態記憶體配置
permission = mode & ~umask;read 回 0 = EOF、−1 = error Unix I/O 與檔案
dup2(oldfd, newfd);file table entry 刪除條件 refcnt == 0 檔案共享、重導向與標準 I/O
socket pair (cliaddr:cliport, servaddr:servport) 唯一識別連線;htonl/ntohl 轉 byte order 全球 IP 網際網路
P(s)/V(s) 語意與 semaphore invariant s0;sbuf:mutex=1、slots=n、items=0 共享變數與號誌
Sp=T1/Tp;Ep=Sp/p;lock ordering rule 免 deadlock 平行化與執行緒安全