免費詳解 / 台大 / 硬體 / 104

104 台大資工所考古題解答|硬體逐題詳解

104 台大資工所硬體考古題的逐題詳解,共 10 題,免費公開。

逐題詳解

110%

Computer Architecture 1 ISA (INSTRUCTION SET ARCHITECTURE) (10%)

ISANumber of General registersNumber of FP registers
Intel X86 (80386)8 (eax to esp)8 (ST0 to ST7)
Intel X86-641632 ZMM registers
Intel Itanium128128
ARMv7 (VPFv2)1616
ARMv83132

The above table shows the number of registers provided by Intel x86, Intel/HP Itanium, and ARM ISA (Instruction Set Architecture).

A. (1 point) Please list one or more ISAs that provide no registers at all.

B. (5 points) Registers are usually used to hold temporaries. Modern compilers also use registers to hold frequently used local variables, pointers, and so on. Ideally, the more the registers, the more objects could be allocated to registers and memory references to those objects could be saved. The trend of ISA has clearly shown that new architectures tend to have more registers. So is it a good idea to take a quantum leap to go for 1024 registers in an ISA. You must argue for your answer, just say yes or no will get no credits.

C. (2 points) In each ISA's calling convention, the set of general purpose registers is usually divided into caller-save and callee-save two subsets. Which type of procedures could benefit most from such a register partition?

D. (2 points) Most ISAs have separate register files: general purpose registers, floating point registers, and SIMD (e.g. Intel SSE/ZMM and ARM Neon) registers. Why do most modern ISAs provide different set of registers? Would it be better to use just one set of general purpose registers? For example, we could have instructions such like: Add R1,R2,R3 /* integer add */, FADD R1,R2,R3 /* Floating point add */, PADD R1,R2,R3 /* SIMD Add */. Although these are different type of instructions, they could use the same general purpose registers.

A. stack machine 型的 ISA:運算元放在 stack 頂、運算結果放回 stack,指令不指定暫存器(例:Java bytecode/JVM、WebAssembly、Burroughs B5000)。memory-to-memory 的 ISA 也沒有暫存器

stack machine(如 JVM bytecode)

B. 不是好主意:

① 指令編碼:1024 個要 10 bit,三運算元(add rd,rs,rt)就用掉 30 bit,32-bit 指令只剩 2 bit 給 opcode 等欄位,指令得變長

② register file 越大越慢、越耗電、越佔面積:位址解碼與 bit line 變長,加上要多個 read/write port,面積約隨 port 數平方成長 → 可能拉長 clock cycle,抵銷少存取記憶體的好處

③ 報酬遞減:compiler 能同時放進暫存器的活著的變數有限,從 16 到 32 個已降低大多數 spill;再多也用不到

④ context switch、interrupt、procedure call 要存回/還原的狀態變成 1024 個暫存器,延遲與 stack 流量變大(callee-save 規定更貴)

NO:編碼位元、存取時間/功耗、報酬遞減、context switch 成本都會變差

C. leaf procedure(不再呼叫別的 procedure)受益最大:可直接使用 caller-save 暫存器,不用在 entry/exit 存回與還原,沒有任何 stack 存取;non-leaf procedure 把跨越 call 還活著的值放在 callee-save 暫存器,只在 entry 存一次,不必在每次 call 前後存取

leaf procedure

D. 分開比較好:

① 資料寬度不同:整數 32/64 bit、FP 32/64 bit、SIMD 128~512 bit;合成一個 file 要全部做到最寬,浪費面積

② port 數與頻寬:整數、FP、SIMD 單元各用自己的小 register file,同時存取,不必擠在一個多 port 的大 file(越多 port 越慢、越大)

③ 接線距離:register file 放在各自的 execution unit 旁,延遲短

④ context switch 時沒用到 FP/SIMD 的 process 可不存這些暫存器(lazy save)

缺點:兩個 file 之間搬資料要多一道 move 指令;共用一個 file 時暫存器分配比較有彈性,但上面的代價更大

分開(寬度、port 與延遲、面積、context switch 成本);不建議合成一個 general purpose register file

27%

2 DATA REPRESENTATION (7%)

On a MIPS machine (Fig. 1) running UNIX, we observed the following binary string stored in memory location x.

0011 1111 0111 0000 0000 0000 0000 0000

This binary could mean many different things,

A. (1 point) If this is an integer number, what value is it?

B. (1 point) If this is a single precision floating point number, what value is it?

C. (1 point) If this is an instruction, what instruction is it?

D. (1 point) If this is a C string, what string is it?

E. (1 point) If this binary string was observed on your x86 desktop, what would be your answer for (D)?

F. (2 points) Suppose we have three variables a, b and c. Give a case where (a+b)+c computes a different value than a + (b+c) on a MIPS microprocessor.

(原題附 Fig. 1:MIPS Reference Data,含 opcode 表、IEEE 754、記憶體配置、資料對齊「Big Endian」、例外碼)

十六進位:\(0011\ 1111\ 0111\ 0000\ldots=\) 0x3F700000

A. \(0x3F7\times2^{20}=(3\cdot256+15\cdot16+7)\times2^{20}=1015\times1{,}048{,}576\)

\(1{,}064{,}304{,}640\)

B. sign \(=0\);exponent \(=0111\ 1110_2=126\);fraction \(=111_2\)(\(=0.875\))

\(1.111_2\times2^{126-127}=1.875\times\tfrac12\)

\(0.9375\)

C. 拆欄位:opcode(31:26)\(=001111\);rs(25:21)\(=11011\);rt(20:16)\(=10000\);immediate(15:0)\(=0\)

opcode 001111 是 lui(參考卡:lui R[rt]={imm,16'b0});rt \(=16=\)$s0;rs 欄位 lui 不使用

lui $s0, 0

D. MIPS(參考卡的 data alignment 標 Big Endian):最高位元組在最低位址,記憶體由低到高是 3F 70 00 00 → '?'(0x3F)、'p'(0x70)、NUL 結束

"?p"

E. x86 是 little-endian:同一個 32-bit 值,最低位元組在最低位址,記憶體由低到高是 00 00 70 3F → 第一個位元組就是 NUL

空字串 ""

F. 浮點數加法不滿足結合律(單精度尾數只有 24 bit,大數旁邊的小數會被吃掉):

\(a=-1.5\times10^{38},\ b=1.5\times10^{38},\ c=1.0\)

\((a+b)+c=0+1.0=1.0\);\(a+(b+c)\):\(b+c=1.5\times10^{38}\)(\(1.0\) 比 \(b\) 的最低位還小,被捨去),再加 \(a\) 得 \(0\)

單精度下 (a+b)+c 得 1.0、a+(b+c) 得 0.0。整數(two's complement)加法即使 overflow 也滿足結合律,所以反例要用浮點

\(a=-1.5\times10^{38},\ b=1.5\times10^{38},\ c=1.0\):\((a+b)+c=1.0\),\(a+(b+c)=0\)

38%

3 BRANCH PREDICTION (8%)

For pipelined processors, control hazards could significantly decrease the performance. Dynamic branch prediction techniques have been successfully adopted in many modern processors to reduce performance penalty caused by control hazards. However, unlike direct branches (e.g. BEQ L1 in ARM or BEQ $t0,$t1, L1 in MIPS), indirect branches are usually difficult to predict.

A. (2 points) Please give at least one static and one dynamic branch prediction scheme used for direct branches in microprocessors.

B. (4 points) List conditions where indirect branches, instead of direct branches, are used? Which one of the listed cases is most frequent?

C. (2 points) Please explain why indirect branches are hard to predict?

A. static:always not taken;或 BTFN(backward taken, forward not taken:往回跳的多半是 loop)

dynamic:branch history table 配 2-bit saturating counter(再進階有 correlating/two-level、gshare、tournament predictor)

static:always-not-taken/BTFN;dynamic:2-bit saturating counter

B. 目標位址要到 run time 才知道的情況:

① procedure return(jr $ra) ② switch/case 用 jump table ③ function pointer/callback ④ virtual function call(透過 vtable) ⑤ interpreter/VM 的 bytecode dispatch ⑥ dynamic linking(經 PLT/GOT 跳轉)

最常出現的是 procedure return

return、switch jump table、function pointer、virtual call 等;最常見是 procedure return

C. direct branch 只要猜「跳或不跳」,目標位址寫在指令裡;indirect branch 要猜跳到哪裡,而目標存在暫存器或記憶體,要到執行階段才算出來,同一個 branch 還可能跳到很多個不同位址(switch 的各個 case、不同呼叫處的 return);branch target buffer 只記上一次的目標,目標一變就猜錯

目標位址不固定、要等到運算後才知道,需要預測 target 而不只是 taken/not taken

410%

4 (10%)

Cache block size is an important design parameter for cache architecture. Assume a 1-CPI (Cycle-per-Instruction) machine with an average of 1.4 memory references (both instruction and data) per instruction. Assume the CPU stalls for cache misses.

Answer the following questions using the cache miss rates for different block sizes listed in the following table.

Block Size (Bytes)81632
Miss rate8%4%3%

A. (5 points) If the miss penalty is 24+B (block size in bytes) cycles, what is the optimal cache block size? Please show how you derive the answer.

B. (5 points) If critical-word-first is implemented in the cache, what is the optimal cache block size? Please show how you derive the answer.

\(\text{CPI}=1+1.4\times\text{miss rate}\times\text{miss penalty}\)

A. penalty \(=24+B\):

blockmiss ratemiss penaltyCPI
8 B8%32\(1+1.4\times0.08\times32=4.584\)
16 B4%40\(1+1.4\times0.04\times40=3.240\)
32 B3%56\(1+1.4\times0.03\times56=3.352\)

16 bytes(CPI 3.24 最小)

B. critical-word-first:block 裡 CPU 要的那個 word 先送回,CPU 馬上繼續,剩下的 word 在背景填入 → CPU 等待的 miss penalty 只剩「第一個 word 的延遲」,不隨 block size 變大(三種 block size 相同)

penalty 一樣 → CPI 只看 miss rate → 選 miss rate 最低的

32 bytes(miss rate 3%)

510%

5 (10%)

You are given a task to parallelize the following problem in a multi-core architecture:

for (i = 0; i < N; i = i+1)
    for (j = 0; j < N; j = j+1) {
        r = 0;
        for (k = 0; k < N; k = k+1)
            r = r + y[i][k]*z[k][j];
        x[i][j] = r;
    };

A. (5 points) Is this a weak-scaling or strong-scaling problem? Please explain your answer.

B. (5 points) Is it possible to partition this problem among cores such that there are no cache coherency misses? Please explain your answer.

A. strong scaling:矩陣大小 \(N\) 固定,總工作量 \(N^3\) 次乘加不變;增加 core 數是要把同一份工作分給更多 core 做、看執行時間縮多少(speedup)。weak scaling 是 core 數增加時問題規模也跟著放大、看每個 core 的工作量不變時時間是否維持

strong scaling(問題大小固定,用更多 core 縮短時間)

B. 可以:

\(y\)、\(z\) 只讀 → 多個 core 的 cache 可同時有同一份拷貝(shared 狀態),不會被 invalidate;\(r\) 是每個 core 自己的區域變數(放暫存器);只有 \(x\) 被寫入

分工:把 \(x\) 的列(\(i\) 迴圈)切成連續的區塊分給各 core,每個 core 只寫自己的那幾列 → 沒有兩個 core 寫同一個 \(x[i][j]\)(沒有 true sharing)

列與列的交界若不是 cache line 的整數倍,相鄰兩個 core 會寫同一條 cache line(false sharing)→ 讓每列起點對齊 cache line、或每個 core 的區塊夠大/加 padding

第一次載入造成的 miss 是 compulsory miss,不算 coherence miss

可以:依 \(x\) 的列切給各 core(且對齊 cache line),\(y\)、\(z\) 唯讀、\(r\) 私有 → 沒有 coherence miss

65%

6 (5%)

(5 points) In current disk storages, the operating system generally completes all I/Os asynchronously via interrupts. But recent studies show that for future NVM (Non-Volatile Memory) storage system, which has significantly lower access latency than disks, the synchronous approach (i.e., polling) could be more efficient than the interrupt approach. Please provide rationale behind this.

interrupt 方式的固定成本:送出 I/O → process 睡眠、context switch 到別的 process;完成時 interrupt、進 handler、wake up、再 context switch 回來,加上 cache/TLB 被污染。這些成本約數 μs~十幾 μs

磁碟:一次 I/O 約 5–10 ms,interrupt 的成本只占約 0.1%,睡眠把 CPU 讓給別人很划算;polling 要空轉幾 ms,浪費 CPU

NVM:一次存取只要約 μs 等級(甚至更短),比 interrupt+context switch 的成本還短 → 睡眠、被喚醒的時間比 I/O 本身還久;直接 polling(busy-wait)幾 μs 就拿到資料,延遲更低,CPU 空轉的時間也很短

NVM 的 I/O 延遲小到不比 interrupt/context switch 的開銷長,polling 空轉的成本小於睡眠、喚醒的成本,所以 polling 更有效率

715%

Operating System 7 (15%)

Consider short-term process scheduling. Please answer the following two problems:

A. (10 points) The Round Robin scheduling algorithm (RR) lets every process run for a given time quantum and then switch to another process so as to have more fair sharing of the CPU time. Please give me your argument why a small time quantum is bad to the average turnaround time, where the turnaround time of a process is the difference between its completion time and its ready time of the process.

B. (5 points) Why having processor affinity is good to processes in using data or instruction cache.

A. 兩個原因:

① context switch 的成本:每過一個 quantum 就切換一次,次數約 \(\dfrac{\text{總 burst}}{q}\);\(q\) 越小切換越多,CPU 花在切換的時間越多,每個 process 的完成時間都被往後推

② 即使切換成本是 0,\(q\) 小也不好:process 變成輪流一點一點前進,大家幾乎同時在最後才做完。例:3 個 process,各需 10 單位:

\(q\)完成時間平均 turnaround
\(q\ge10\)(等於 FCFS)10、20、3020
\(q=1\)28、29、3029

\(n\) 個一樣長的 process 時,\(q\to0\) 的平均 turnaround 趨近 \(nL\),FCFS 只有 \(\tfrac{n+1}2L\),大約差一倍

quantum 小 → context switch 開銷變大,且 process 同時拖到最後才做完,平均 turnaround 變長

B. processor affinity:process 盡量一直在同一顆 processor 上跑。上次執行留在這顆 processor 的 L1/L2 cache 裡的 instruction 與 data,下次還在,cache hit 率高

換到別顆 processor:新 cache 是冷的,要重新載入(一堆 cold miss);舊 cache 的內容失效(cache line 要 invalidate/搬移),花時間又佔記憶體頻寬

留在同一 processor,之前載入 cache 的 instruction/data 可以重複使用,避免遷移後重新填 cache 的 miss

810%

8 (10%)

(10 points) Consider a process synchronization problem, in which we have 5 people competing for 4 chairs, and each chair can be used by one person at a time. Let the competing go by rounds. That is, 5 people compete for 4 chairs in the beginning of each round, and the 4 winners release their chairs at the end of each round so that the next round starts. Please use semaphores to write programs for the entry and exit sections of the 5 people so that every person will win at least one time in competing the chairs for every 3 consecutive rounds.

每輪恰有 1 個人落選。要每 3 個連續的輪次人人至少贏一次,只要「沒有人連續輸 3 輪」。做法:讓落選的人輪流,第 \(r\) 輪落選的是 \(r \bmod 5\),同一個人兩次落選相隔 5 輪,任何連續 3 輪人人至少贏 2 次

semaphore:chairs=4(4 把椅子)、gate[i]=個人的「本輪參加」許可、mutex=保護計數、全域 round、finished

semaphore chairs = 4;
semaphore gate[5] = {0, 1, 1, 1, 1};   // 第 0 輪由 person 0 落選
semaphore mutex = 1;
int round = 0, finished = 0;

person(i):
  while (true) {
      /* entry section */
      wait(gate[i]);          // 沒輪到這個人的話在這裡等(落選)
      wait(chairs);           // 4 個參加者各拿一把椅子
      sit();                  // 本輪使用椅子
      /* exit section */
      signal(chairs);         // 釋放椅子
      wait(mutex);
      finished++;
      if (finished == 4) {            // 4 個贏家都做完,本輪結束
          finished = 0;
          round++;
          int out = round % 5;        // 下一輪落選的人
          for (p = 0; p < 5; p++)
              if (p != out) signal(gate[p]);   // 其他 4 人可以開始下一輪
      }
      signal(mutex);
  }

為什麼成立:\(gate\) 保證每輪只有 4 個人往下走,所以 4 把椅子夠、沒人搶不到;下一輪的 4 個許可要等 4 個贏家全部做完才發出(finished == 4),所以輪與輪不會重疊;落選者每輪不同,連續 3 輪落選的人最多一次

另一種做法是用 FIFO 的 strong semaphore,讓上一輪落選的人排在 queue 最前面、下一輪優先;但只要有人晚進 queue,連輸 3 輪仍可能發生,所以這裡明確指定每輪落選的人

用 gate[i] 每輪輪流指定 1 人落選(round % 5),chairs=4,finished 計數到 4 才發下一輪的許可

915%

9 (15%)

If the number of frames allocated to a low-priority process falls below the minimum number required by the computer architecture, we must suspend the execution of that process. We should then page out its remaining pages, freeing all its allocated frames. A process is thrashing if it is spending more time paging than execution.

A. (3 points) For a system supporting virtual memory with unlimited swap space, how do we make a process to be thrashing?

B. (3 points) If we do not allow a thrashing process to steal frames from other processes, will the other processes finish soon and the thrashing process eventually get enough frames to run? Why?

C. (3 points) Why does working set model prevent thrashing?

D. (3 points) Would working set model prevent thrashing totally? Why?

E. (3 points) If processes in a virtual machine are thrashing, how does it affect the performance of the other virtual machines?

A. 讓它分到的 frame 少於它目前 locality 需要的 page 數(working set)。例:同時放進很多 process(multiprogramming degree 太高),每個分到的 frame 都不夠;或一個 process 用 LRU/FIFO 反覆走訪 \(n+1\) 個 page 卻只有 \(n\) 個 frame,每次存取都 page fault。swap 空間夠大,所以不會因為放不下而被擋掉

frame 數 \(\lt\) working set(例如 degree of multiprogramming 過高)

B. 不一定:用 local replacement 讓它不偷別人的 frame,其他 process 的 frame 不被搶,但 thrashing 的 process 還是大部分時間排在 paging device 的 queue 裡 → 其他 process 發生 page fault 時,paging device 的排隊時間拉長,page fault 的平均服務時間變長,它們也跑得比較慢

thrashing 的 process 要等其他 process 做完、釋放 frame,OS 再重新配給它,才有可能拿到足夠的 frame;沒有重新配置之前它一直 thrashing

不會很快:paging device 被占用,其他 process 的 page fault 也變慢;thrashing 的 process 要等別人結束釋放 frame 並重新分配

C. working set \(WS_i\)=process \(i\) 最近 \(\Delta\) 次存取用到的 page 集合,\(D=\sum|WS_i|\);\(m\) 是可用 frame 數

OS 給每個 process 它的 working set 那麼多 frame(整個 locality 都在記憶體 → page fault 少);若 \(D\gt m\),就 suspend(swap out)一個 process 把 frame 還給其他人,若 \(D\lt m\) 才再啟動新 process → 不會讓總需求超過實體記憶體,避免全面 thrashing

每個執行中的 process 都分到足以容納目前 locality 的 frame;總需求超過就暫停部分 process

D. 不能:① working set 是用最近 \(\Delta\) 的存取估計的,locality 切換(transition)時,新 locality 的 page 還沒載入,會短暫大量 page fault;② \(\Delta\) 選太大或太小估不準;③ 追蹤 working set 有成本(定期掃 reference bit);④ 若單一 process 的 working set 就大於全部記憶體,還是會 thrash

不能:locality 轉換時的短暫 thrashing、\(\Delta\) 估不準、追蹤成本

E. VM 裡的 thrashing 會產生大量 virtual disk 的 I/O(paging),這些 I/O 最後落在 host 共用的實體磁碟與 I/O 通道,其他 VM 的 I/O 排隊時間變長;hypervisor 為了模擬這些 I/O 也花 CPU 時間;若 host 把記憶體 overcommit(VM 總記憶體大於實體記憶體),host 自己也開始 swap,所有 VM 一起變慢

共用的 I/O 與 CPU(與可能 overcommit 的記憶體)被占用,其他 VM 的延遲變長、效能下降

1010%

10 (10%)

Vectored I/O or scatter-gather I/O allows one system call to perform multiple I/O operations involving multiple locations.

A. (5 points) Please describe the advantages using vectored I/O with a real application scenario.

B. (5 points) When we implement a system call for vectored I/O, such as readv or writev in POSIX, what need to be considered to avoid the disadvantages using a vectored I/O.

A. 情境:web server 回應一個 HTTP request,要送出 header(記憶體裡的字串)與 body(讀進另一塊 buffer 的檔案內容)

不用 vectored I/O:兩次 write,或先把兩塊複製成一塊連續 buffer 再一次 write

writev(fd, iov, 2)(iov[0]=header、iov[1]=body):

① 一次 system call,少一次 user/kernel 切換 ② 不用先複製拼成連續 buffer,省一次 memory copy ③ 一次 call 內送出,header 與 body 可以合在同一個 TCP segment(兩次 write 常拆成兩個封包) ④ 這次傳輸對同一個 file descriptor 是 atomic,不會被別的 writer 的資料插在中間

其他例:資料庫寫 log(header+records)、網路協定堆疊組封包(協定 header+payload)

一次 system call 傳多塊不連續的 buffer:省 system call 次數與資料複製,封包一次送出,且 atomic

B. 實作要注意:

① 限制:iovec 數量上限(IOV_MAX)與總長度不能 overflow、不超過 SSIZE_MAX,否則 kernel 要配置的暫存空間與檢查會失控

② 安全:kernel 要把 iovec 陣列從 user space 複製進來,逐一檢查每個 buffer 位址與長度有效(無效回 EFAULT),不能信任 user 傳來的指標

③ partial transfer:可能只傳了一部分(socket 緩衝滿、被 signal 中斷);回傳值要精確表示已傳的 byte 數,並定義 iovec 跨 buffer 的進度,避免重複傳或漏傳

④ 效能:很多零碎小 buffer,要 pin/檢查很多 page,成本會抵銷好處;若裝置沒有 scatter-gather DMA,kernel 還是得複製成連續 buffer,優點就沒了

限制 iovec 數量與總長度、驗證每個 user buffer、精確回報 partial transfer,並確認底層(scatter-gather DMA)真的能省複製

109–115 的詳解也是這樣寫的。

國立臺灣大學 109–115 的詳解收錄在付費版;106–115 全年度完整詳解共 367 頁,逐題推導。

購買 · NT$ 850 看台大其他免費詳解

其他年度與考科

同一年的其他科

同一科的其他年度

聯絡我們

題目有錯、詳解看不懂,都歡迎來信

想許願補哪一份、對購買有疑問也可以,收到後會盡快回覆。

william.chou.123123@gmail.com