免費詳解 / 成大 / 硬體 / 103

103 成大資工所考古題解答|硬體逐題詳解

103 成大資工所硬體考古題的逐題詳解,共 9 題,免費公開。

逐題詳解

110%

[10%] Explain the following term in English. For each term, please use less than 100 words.

(a) [2%] Power Wall (b) [2%] GPGPU (c) [2%] Restartable instruction (d) [2%] Write-allocate policy (e) [2%] NUMA

(a) Power Wall:Chip power (dynamic power \(P\approx\tfrac12CV^2f\)) and the heat it produces are limited by what air cooling can remove. Supply voltage can no longer be lowered, so raising the clock rate raises power too much; since about 2004 designers stopped scaling frequency and moved to multiple cores.

(b) GPGPU (general-purpose computing on a GPU):Using a graphics processor, with hundreds or thousands of simple cores running the same program on many threads (SIMT), to do non-graphics, data-parallel work (CUDA, OpenCL).

(c) Restartable instruction:An instruction that can be stopped by an exception such as a page fault, have the fault handled, and then be re-executed from its start with the correct result. Demand paging needs it, so the machine must not leave partial side effects.

(d) Write-allocate policy:On a write miss, the block is first fetched from the next level into the cache, then the write is done in the cache. It is usually paired with write-back; the alternative, no-write-allocate, writes straight to memory without loading the block.

(e) NUMA (non-uniform memory access):A shared-address-space multiprocessor in which the access time to a memory word depends on where the word is: the processor's local memory is faster than remote memory attached to other processors.

五個名詞如上,每個 100 字以內

210%

[10%] Suppose we have developed new versions of a processor with the following characteristics.

VersionVoltageClock rate
Version 11.2 V810 MHz
Version 21 V1 GHz

(a) [5%] How much has the dynamic power been reduced if the capacitive load does not change?

(b) [5%] Assuming that the capacitive load of version 2 is 80% the capacitive load of version 1, find the voltage for version 2 if the dynamic power of version 2 is reduced by 20% from version 1.

動態功率 \(P=\tfrac12CV^2f\)

(a) \(\dfrac{P_2}{P_1}=\dfrac{V_2^2f_2}{V_1^2f_1}=\dfrac{1^2\times1000}{1.2^2\times810}=\dfrac{1000}{1166.4}\approx0.857\)

  降到原來的 85.7%,少了約 14.3%

(b) \(C_2=0.8C_1\),\(P_2=0.8P_1\):\(0.8C_1V_2^2f_2=0.8\,C_1V_1^2f_1\)

  \(V_2^2=V_1^2\dfrac{f_1}{f_2}=1.44\times0.81=1.1664\) → \(V_2=1.08\ \text{V}\)

(a) 降到 85.7%(少約 14.3%) (b) \(V_2=1.08\) V

35%

[5%] Translate the following C code to MIPS instructions. Assume that the variables \(c\) and \(d\) are assigned to registers $s0 and $s1, respectively. Assume that the base address of the arrays \(A\) and \(B\) are in registers $s6 and $s7, respectively.

c = d - A[B[2]];

lw   $t0, 8($s7)       # $t0 = B[2]    (2*4 = 8)
sll  $t0, $t0, 2        # B[2]*4
add  $t0, $t0, $s6      # &A[B[2]]
lw   $t1, 0($t0)        # $t1 = A[B[2]]
sub  $s0, $s1, $t1      # c = d - A[B[2]]

45%

[5%] What decimal number does the following bit pattern represent if it is a floating point number? Use the IEEE 754 standard.

101011111011010000000000

題目這串只有 24 位,IEEE 754 single precision 是 32 位。後面省掉的是一串 0,右邊補 8 個 0 成 32 位:

1 | 01011111 | 01101000000000000000000

sign \(=1\) → 負

exponent \(=01011111_2=95\),真正的指數 \(95-127=-32\)

fraction \(=0.01101_2=\tfrac14+\tfrac18+\tfrac1{32}=0.40625\),尾數 \(1.40625=\tfrac{45}{32}\)

值 \(=-1.40625\times2^{-32}=-\dfrac{45}{2^{37}}\approx-3.27\times10^{-10}\)

這串位元(補成 32 位是 0xAFB40000)剛好也是 MIPS 的 sw $s4, 0($sp) 機器碼,題目把它當 float 讀

\(-1.40625\times2^{-32}\approx-3.27\times10^{-10}\)

520%

[20%] Assume an instruction pipeline for a high-speed, load/store processor with the following instruction classes:

ALUALUop Rdst, Rsrc1, Rsrc2
ALUimmediateALUiop Rdst, Rsrc1, imm
LoadMEMop Rdst, n(Rsrc)
StoreMEMop n(Rsrc2), Rsrc1
Conditional branchBRop Rsrc1, Rsrc2, offset
JumpsJMP Rdst

Each instruction takes one machine word. The only memory-addressing mode supported is base register plus a signed offset. Conditional branches compare the two branch source operand values using the ALU. The branch target address is computed on a separate address generation adder contained in the control unit of the machine. Register file writes occur in the first half of a cycle and register file reads occur in the second half.

The machine uses virtual memory address, with separate instruction and data TLBs. It also has a physical addressed (tagged) direct mapped L1 Icache and a physically addressed set associate L1 Dcache (Accesses that miss in the L1 cache cause the instruction pipeline to stall.) The ALU used during the EX cycle is pipelined and takes one cycle to complete an addition/subtraction/logical operations and two cycles to complete a multiplication. The time taken by the key components (that already includes the pipeline register write time, the interconnect delay, and any necessary multiplexors) is as follows:

I or D TLB access1 ns
Icache access2 ns
Instruction decode1 ns
Address adder1 ns
Dcache access2 ns
ALU pipe stage2 ns
RegFile read/write2 ns per 2 port access (e.g. a 2-read and 2-write port RegFile takes 2 ns, a 4-read-4-write port RegFile takes 4 ns, etc.)

Answer the following questions about your pipeline.

(a) [7%] Draw the shortest possible instruction pipeline (i.e. the pipeline with the fewest stages) while ensuring that there are no structural hazards. For your pipeline, give a name for each stage along with a short description of what activities occur during that stage.

(b) [3%] What is its clock rate?

(c) [5%] Give a MIPS instruction example of two different data hazards that can be solved by forwarding (both data hazards should be different in that the forwarding is handled from different pipeline register stages). For each, explain which data are forwarded.

(d) [5%] Give a MIPS instruction example of two different data hazards that cannot be solved by forwarding. For each, indicate how many stalls are incurred before the hazard is resolved.

(a) 哪些資源會被兩條指令在同一 cycle 搶:

  • 記憶體:Icache/ITLB 與 Dcache/DTLB 是分開的,取指令與 load/store 不衝突

  • register file:WB 在 cycle 前半寫、ID 在後半讀,同一 cycle 一寫一讀不衝突(2 read+1 write 在 2 ns 內)

  • ALU:算術、load/store 位址、branch 比較都只在 EX 用,一 cycle 一條,不衝突;branch target 用控制單元自己的加法器

  每條指令的工作依序是「取指令、解碼讀暫存器、運算或算位址、存取資料記憶體、寫回暫存器」,每一段要用不同的硬體,各切一個 stage:

IF3 nsID2 nsEX2 nsMEM3 nsWB2 ns

  IF:用 PC 查 ITLB(1 ns)、讀 Icache(2 ns),PC+4 = 3 ns

  ID:decode 與讀 register file 同時做(decode 1 ns、讀 RF 2 ns,在 cycle 後半);branch/jump 的 target 用位址加法器算(decode 1+adder 1) = 2 ns

  EX:ALU(2 ns):ALU 運算、load/store 位址(base+offset)、branch 兩個運算元比較;multiply 要 2 cycle

  MEM:load/store 用位址查 DTLB(1 ns)、讀寫 Dcache(2 ns) = 3 ns;其他指令直接通過

  WB:把結果寫回 register file(2 ns,在 cycle 前半)

(b) cycle time 取最慢的 stage:IF、MEM 都是 3 ns → clock \(=\dfrac1{3\,\text{ns}}\approx333\) MHz

把 EX 與 MEM 併成一段會變成 \(2+3=5\) ns,stage 變 4 段但 clock 變 200 MHz;5 段是在不增加 cycle time 下的最少段數

(c) 可以靠 forwarding(結果在 EX 末就出來):

  ① 緊接著用:add $t0,$s1,$s2,下一條 sub $t3,$t0,$s4。資料從 EX/MEM pipeline register(add 的 ALU 結果)送到 sub 的 ALU 輸入

指令123456
add $t0,$s1,$s2IFIDEXMEMWB
sub $t3,$t0,$s4IFIDEXMEMWB

  ② 隔一條再用:add $t0,$s1,$s2、or $t5,$s6,$s7、sub $t3,$t0,$s4。add 的結果此時在 MEM/WB pipeline register,送到 sub 的 ALU 輸入

指令1234567
add $t0,$s1,$s2IFIDEXMEMWB
or $t5,$s6,$s7IFIDEXMEMWB
sub $t3,$t0,$s4IFIDEXMEMWB

  (第 4 條再用,WB 前半寫、ID 後半讀,從 register file 直接讀到,不需 forwarding)

(d) 資料在 MEM 末才有(load),或結果要多個 cycle 才出來(multiply),forwarding 追不到:

  ① load-use:lw $t0,0($s1),下一條 add $t2,$t0,$t1。資料 cycle 4 末才從 Dcache 出來,add 在 cycle 3 就要進 EX → 1 次 stall,之後 MEM/WB → EX forwarding

指令1234567
lw $t0,0($s1)IFIDEXMEMWB
add $t2,$t0,$t1IFIDstallEXMEMWB

  ② 乘法的兩 cycle 延遲:mul $t0,$s1,$s2,下一條 add $t3,$t0,$s4。題目的 ALU 做乘法要 2 個 cycle,結果在第 2 個 EX cycle 末才有,add 緊接著進 EX 就差 1 個 cycle → forwarding 追不到,1 次 stall

指令1234567
mul $t0,$s1,$s2IFIDEX1EX2MEMWB
add $t3,$t0,$s4IFIDstallEXMEMWB

另一個例子:lw $t0,0($s1) 後面緊接 JMP $t0。JMP 在 ID 就要 \(t0\) 當 target,資料 cycle 4 末才有,JMP 要等到 cycle 5 才能在 ID 拿到,要 2 次 stall

(a) IF/ID/EX/MEM/WB 五段 (b) 3 ns,約 333 MHz (c) EX/MEM → EX、MEM/WB → EX (d) load-use 1 stall、mul 後緊接使用 1 stall

610%

[10%] Consider the following page reference string: {1, 2, 3, 4, 2, 1, 5, 6, 2, 1, 2, 3, 7, 6, 3, 2, 1, 2, 3, 6}.

(a) [5%] In the LRU page-replacement algorithm, how many page faults would occur when we have 'one', 'two', 'three' page frames? Please indicate the number of page faults individually. Assume that all frames are initially empty, and therefore your first access to each unique page will cause one fault.

(b) [5%] In the optimal page-replacement algorithm, how many page faults would occur when we have 'one', 'two', 'three' page frames? Please indicate the number of page faults individually. Assume that all frames are initially empty, and therefore your first access to each unique page will cause one fault.

(a) LRU:每次踢最久沒用的

1 frame:相鄰兩個 reference 都不同,每次都 fault → 20

2 frames:

ref12342156212376321236
frame 111332255222277331133
frame 22244116611336622226
faultFFFFFFFFFFFFFFFFFF

3 frames:

ref12342156212376321236
frame 111144455511177722222
frame 22222226666333333333
frame 3333111222226661116
faultFFFFFFFFFFFFFFF

(b) OPT:每次踢「最久以後才會再用到(或不再用到)」的

1 frame:20

2 frames:

ref12342156212376321236
frame 111344156611333331136
frame 22222222222276622222
faultFFFFFFFFFFFFFFF

3 frames:

ref12342156212376321236
frame 111111111111333333336
frame 22222222222277722222
frame 3344456666666661111
faultFFFFFFFFFFF

(a) LRU:20、18、15 (b) OPT:20、15、11

710%

[10%] Choose the correct answers for each of the following 5 questions.

(a) [2%] The Banker's Algorithm is proposed to support the technique of: (1) deadlock detection (2) deadlock recovery (3) deadlock avoidance (4) deadlock identification

(b) [2%] For two processes accessing a shared variable, Peterson's algorithm must satisfy: (1) semaphores (2) mutual exclusion (3) synchronization (4) progress (5) bounded-waiting

(c) [2%] Indefinite blocking may occur if we add and remove processes from the list associated with a semaphore in ________ order. (1) first in, first out (2) first in, last out (3) last in, first out (4) last in, last out

(d) [2%] A CPU-bound process ________. (1) infrequently requests I/O operations and spends more of its time performing computational work (2) frequently requests I/O operations and spends more of its time performing computational work (3) infrequently requests I/O operations and spends less of its time performing computational work (4) frequently requests I/O operations and spends less of its time performing computational work

(e) [2%] ________ increases CPU utilization by organizing jobs (code and data) so that the CPU always has one to execute. (1) Multithreading (2) CPU scheduling (3) Swapping (4) Multiprogramming

(a) Banker's algorithm 事前檢查每次配置後是否仍在 safe state → deadlock avoidance → (3)

(b) Peterson's solution 要滿足 critical-section 問題的三個條件:mutual exclusion、progress、bounded waiting → (2)(4)(5);semaphore 是別的工具、synchronization 是目的,不是條件

(c) semaphore 的 waiting list 用 LIFO,先等的 process 可能一直被後來的插隊,永遠輪不到(starvation) → (3)

(d) CPU-bound:很少 I/O、大部分時間在計算 → (1)

(e) 讓 CPU 隨時有 job 可跑 → multiprogramming → (4)

(a) 3 (b) 2、4、5 (c) 3 (d) 1 (e) 4

815%

[15%] To create a new process from processes, the multitasking operating systems such as Unix-like systems provide a "fork" system call. The fork function will create a copy of itself to a child process, and then other programs are executed in the child process.

(a) [5%] In the following example with the fork function, how many lines of "NCKU" will be shown in the console?

int main(int agrc, char **argv)
{
    int i;
    for (i=0; i<5; i++)
    {
        fork();
    }
    printf("NCKU\n");
    return 0;
}

(b) [5%] In the following example with the fork function, how many lines of "NCKU" will be shown in the console?

int main(int agrc, char **argv)
{
    int i;
    for (i=0; i<10; i++)
    {
        printf("NCKU\n");
        fork();
    }
    return 0;
}

(c) [5%] In the following example with the fork function, what content will be printed in the console?

int main(int agrc, char **argv)
{
    int x=0, i=0;
    for (i=0; i<3; i++)
    {
        fork();
        x=x+5;
    }
    printf("x = %d\n", x);
    return 0;
}

每次 fork() 讓 process 數目變 2 倍(父與子都從 fork 後面繼續跑同一段迴圈)

(a) 迴圈 5 次 fork,process 數 \(2^5=32\);printf 在迴圈外,每個 process 印 1 次 → 32 行

(b) printf 在迴圈內、fork 之前。第 \(i\) 輪(\(i=0..9\))有 \(2^i\) 個 process,各印 1 行:\(\sum_{i=0}^{9}2^i=2^{10}-1=1023\) 行

  (輸出到 console 是 line buffered,每行 \n 就送出,fork 時 buffer 是空的;若導向檔案成 fully buffered,fork 會把沒送出的 buffer 複製給子 process,行數會更多)

(c) 迴圈 3 次,最後有 \(2^3=8\) 個 process;每個 process 都跑完 3 輪 x=x+5(父、子 fork 時各有自己的一份 \(x\)) → 每個 \(x=15\)

  印出 8 行:

x = 15
x = 15
x = 15
x = 15
x = 15
x = 15
x = 15
x = 15

(a) 32 行 (b) 1023 行 (c) 8 行 x = 15

915%

[15%] The following implementation in Java is created for a specific system utility.

(a) [7%] Could you figure out what is the system utility that can be provided from 'Manager' class? Please also simply discuss its corresponding methodology.

(b) [8%] Consider 'Manager' is used in the multi-threading mode. Is the implementation logically risky? If it is risky, please clearly point out those incorrect methods or lines, and also revise the code (written in Java). If it is not risky, please clarify your answer.

public interface ObjA
{
    /* check if the object is expired */
    public boolean isExpired();
    /* return the key in the string type */
    public String getIdentifier();
}
 1 public class Manager {
 2     private static java.util.HashMap map = new java.util.HashMap();
 3     private static Object lock = new Object(); /* This object 'lock' can act as a semaphore */
 4
 5     static { /* The following code will create a background thread invoked periodically */
 6         try {
 7             Thread th_1 = new Thread(new Runnable() {
 8                 int sleepTime = 5000;
 9                 public void run() {
10                     try {
11                         while (true) { /* Sets up an infinite loop */
12                             /* An iterator is used to look through all objects */
13                             java.util.Iterator keys = map.keySet().iterator();
14                             while (keys.hasNext()) {
15                                 /* Retrieve each individual key */
16                                 String key = (String) keys.next();
17                                 ObjA value = (ObjA) map.get(key);
18                                 if (value.isExpired()) {
19                                     map.remove(key);
20                                 }
21                             }
22                             Thread.sleep(sleepTime); /* thread will sleep 5000 ms */
23                         }
24                     } catch (Exception e) {
25                         e.printStackTrace();
26                     }
27                 } /* End of the run method */
28             }); /* End of the thread code */
29
30             th_1.start(); /* Starts the thread */
31         } catch (Exception e) {
32             e.printStackTrace();
33         }
34     } /* End static block */
35
36     /* put object into the map */
37     public static void putObjA(ObjA object) {
38         map.put(object.getIdentifier(), object);
39     }
40     /* return the object if the key is found in the map */
41     public static ObjA getObjA(String identifier) {
42         ObjA obj = null;
43         /* 'synchronized(lock)' can ensure that no more than one thread can lock the object
44            'lock' simultaneously */
45         synchronized (lock) {
46             obj = (ObjA) map.get(identifier);
47         }
48         if (obj == null)
49             return null;
50         if (obj.isExpired()) {
51             map.remove(identifier);
52             return null;
53         } else {
54             return obj;
55         }
56     }
57 }

(a) 有時效的 cache(expiring cache/object manager):物件放在以 identifier 為 key 的 map 裡,每個物件自己知道有沒有過期。

  方法:① 惰性清除(lazy eviction)— getObjA 取出時檢查 isExpired(),過期的就從 map 移除並回傳 null;② 定期清除 — 背景 thread 每 5000 ms 掃描整個 map,移除所有過期物件,避免沒人讀的過期物件一直佔記憶體。

(b) 有風險。共用的 HashMap 不是 thread-safe,所有存取(put、get、remove、遍歷)都要用同一把 lock,現在只有一小段有鎖:

  • 第 13–21 行(背景 thread):沒拿 lock 就遍歷 map,與其他 thread 的 put/get/remove 同時進行;且遍歷 keySet().iterator() 時直接呼叫 map.remove(key)(第 19 行),會讓 iterator 失效,下一次 keys.next() 丟 ConcurrentModificationException(單 thread 也會)

  • 第 24 行:catch 在 while(true) 外面,例外一發生背景 thread 就結束,從此再也沒人清除過期物件

  • 第 37–39 行 putObjA:map.put 沒有 synchronized,與 get/清除並行時會破壞 HashMap 內部結構(遺失更新、無窮迴圈)

  • 第 48–55 行 getObjA:鎖在第 47 行就結束了,取出 obj 後的「檢查是否過期、map.remove(identifier)」在鎖外,是 check-then-act 的 race:thread A 看到過期要移除時,thread B 可能已經 put 了同 key 的新物件,A 把新物件誤刪

修正:map 所有存取都放在同一把 lock 裡;清除用 Iterator.remove();例外在迴圈內處理,背景 thread 設為 daemon:

public class Manager {
    private static final java.util.HashMap<String, ObjA> map = new java.util.HashMap<>();
    private static final Object lock = new Object();

    static {
        Thread th_1 = new Thread(new Runnable() {
            int sleepTime = 5000;
            public void run() {
                while (true) {
                    try {
                        synchronized (lock) {                 // 遍歷與刪除整段上鎖
                            java.util.Iterator<java.util.Map.Entry<String, ObjA>> it
                                = map.entrySet().iterator();
                            while (it.hasNext()) {
                                if (it.next().getValue().isExpired())
                                    it.remove();              // 用 iterator 自己的 remove
                            }
                        }
                        Thread.sleep(sleepTime);
                    } catch (InterruptedException e) {
                        return;
                    } catch (Exception e) {
                        e.printStackTrace();                  // 例外不讓 thread 結束
                    }
                }
            }
        });
        th_1.setDaemon(true);
        th_1.start();
    }

    public static void putObjA(ObjA object) {
        synchronized (lock) {
            map.put(object.getIdentifier(), object);
        }
    }

    public static ObjA getObjA(String identifier) {
        synchronized (lock) {                                 // 取出、檢查、移除在同一個鎖內
            ObjA obj = map.get(identifier);
            if (obj == null) return null;
            if (obj.isExpired()) {
                map.remove(identifier);
                return null;
            }
            return obj;
        }
    }
}

也可以把 HashMap 換成 ConcurrentHashMap,清除用 map.values().removeIf(ObjA::isExpired);但 get 裡「檢查過期+移除」仍要用 map.remove(key, obj) 之類的 conditional remove,才不會誤刪新物件

(a) 有 expiration 的 cache(lazy+定期清除) (b) 有風險,上列第 13–21、24、37–39、48–55 行;修正如上

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

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

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

其他年度與考科

同一年的其他科

同一科的其他年度

聯絡我們

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

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

william.chou.123123@gmail.com