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

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

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

逐題詳解

125%

PART I: COMPUTER ARCHITECTURE

1. (25 pts) The advance of computer architecture is enabling big data analytics, machine learning and new smart applications. Please read the following article before answering the questions:

Nvidia Announces New Drive PX 2 'Supercomputer in A Lunchbox' For Self-Driving Cars (Source: techcrunch.com, 2016/01/04)

Following last year's Drive CX, Nvidia just announced an updated version of its computing platform for self-driving cars, the Drive PX 2. Compared to last year's model, this is a much more powerful beast, able to process data from 12 video cameras and other sensors in real time to make educated driving decisions. The company calls it a supercomputer, and it's the size of a lunchbox.

Behind the scene, the Drive PX 2 features 12 different cores representing 8 teraflops of calculation power, 24 deep learning tera operations per second. The company is using a 16nm architecture, and it's a hungry beast as it requires 250W of power. Finally, Nvidia is using a liquid-cooling system. Because the PX 2 will be used in cars, that's not too much of a problem and Nvidia argues that car manufacturers will just plug the device into their existing cooling solutions.

Nvidia co-founder and CEO Jen-Hsun Huang said that the PX 2 was as powerful as 150 MacBook Pros. The company is certainly comparing GPU power with the 13-inch MacBook Pro, which currently sports an Intel Iris Graphics 6100 chip. The PX 2 features two next-gen Tegra processors, as well as a Pascal-based GPU. In total, the system can push up to 8 teraflops and recognize up to 2,800 images per second using the AlexNet neural network-based deep learning algorithm.

The company also announced Nvidia Drivenet, its own deep neural network. It has the equivalent of 37 million neurons and was trained 120 million objects so far. Like other deep neural networks, it gets better over time. Companies will be able to leverage this network, but Nvidia also insisted in saying that car makers would want to control their own neural network. The company is promoting a platform approach, meaning that it wants to work with as many car makers as possible to kickstart their self-driving efforts. Volvo is going to be the first partner shipping Drive PX 2 in about 100 upcoming test cars. Nvidia has also partnered with Audi, Daimler, BMW and Ford to develop and test the PX 2.

As Huang showed during today's keynote, all of this power is needed to enable self-driving cars to know enough about their environment — and interpret it — to safely drive in traffic. In one demo, Nvidia showed a new dashboard that can use this data to show drivers whether there are other cars around them at any given time. Thanks to this, "we soon won't need rear-view mirrors anymore," Huang joked. As Nvidia clearly noted, though, identifying objects and planning basic paths is only the beginning. Looking ahead, making self-driving cars work in the real world also means that cars can recognize circumstances as well. Not every truck is the same, after all — some are ambulances, for example, and you better make space for those.

Please answer the following questions:

(a) [2 pts] Nvidia is famous for making Graphics Processing Units (GPU's). Can GPU's be used for general purpose computing? How?

(b) [2 pts] Which category does this PX 2 platform belongs: desktop, server, embedded, or supercomputer?

(c) [2 pts] What is the power efficiency of the PX 2 platform, in terms of teraflops/watt?

(d) [2 pts] Nvidia said that the PX 2 was as powerful as 150 MacBook Pros. Why don't we use it to make desktop computers? (In addition to answering yes/now, please give an explanation).

The PX 2 is designed to accelerate "deep learning" or "deep neural network" algorithms with GPU's. The following figure is an example of deep neural network, where data are received by the input layer from the left, processed through 3 hidden layers, and finally delivered to the output layer to produce the results. Each circle represents a functional node which receives multiple input data from the previous layer, computes a result with a function, and deliver the result to the nodes in the next layer.

(原題附圖:全連接的 deep neural network——input layer、hidden layer 1、2、3、output layer,共 5 層,相鄰兩層的每個 node 兩兩相連)

(e) [2 pts] Please explain why GPU may be useful for accelerating such an algorithm?

(f) [2 pts] Can the deep neural network shown above be implemented by a pipelined datapath? Draw a picture to show how the pipelined data path works.

(g) [2 pts] How would pipelining affect the performance, in terms of throughput and latency?

(h) [2 pts] As opposed to Nvidia's GPU approach, do you think it is a good idea to design a chip entirely for deep learning? What would be the advantages and disadvantages?

(i) [2 pts] For a very large deep neural network, we may want to accelerate it with multiple machines by partitioning the input data. Suppose we have two machines connected with Ethernet, and each machine receives half of the input data. For simplicity, assume every layer has N nodes and each node sends its output data (1 floating point number) to every node in the next layer. How many floating point numbers need to be exchanged between the two machines for one set of input data?

(j) [2 pts] Following the previous question, suppose each node takes A nanoseconds to complete its function, each machine has Q processor cores, and the Ethernet has 10Gbps duplex bandwidth (i.e. each direction can transfer at 10Gbits/sec). Please estimate the speedup of the execution time with two machines. (Ignore the network delay and the other overhead in this case).

(k) [2 pts] Following the previous question, if we have P machines instead of 2 machines, please estimate the limit of speedup of the execution time, as P approaches infinity.

(l) [3 pts] Based on the above, please discuss how you would design system architectures for small, medium, and large deep neural network for best cost-performance? You may use CPUs, GPU, custom-designed chips, FPGA, clusters, etc.

(a) 可以(GPGPU):把一般計算寫成 kernel(CUDA/OpenCL),由成千上萬個 thread 同時在 GPU 的 SIMD/SIMT 核心上跑;適合資料彼此獨立、每筆做同樣運算的工作(矩陣運算、影像處理、科學模擬)

可以,用 CUDA/OpenCL 把 data-parallel 的計算寫成 kernel 丟給 GPU

(b) 裝在車內、為特定的即時任務服務,是 embedded(不是通用的 desktop/server,也不是集中的 supercomputer)

embedded

(c) \(\dfrac{8\ \text{TFLOPS}}{250\ \text{W}}=0.032\ \text{TFLOPS/W}\)

\(0.032\) TFLOPS/W = 32 GFLOPS/W

(d) 不適合:

① 「150 台 MacBook Pro」比的是特定的 deep-learning/GPU 吞吐量;desktop 常見的工作(網頁、辦公、編譯)是循序、少平行,用不到那麼多 GPU 核心,加速不成比例

② 250 W、要液冷:desktop 用空冷、要安靜,電源與散熱的成本與體積都撐不住

③ 價格高;而且軟體生態(x86/Windows 應用程式)、顯示輸出與周邊介面都和 desktop 不同

No:加速只對 deep learning 這類高度平行的負載成立,加上功耗 250 W、需液冷、成本高、軟體生態不同

(e) 同一層的每個 node 做的是「對上一層的輸出做乘加」(內積+激活函數),各 node 之間互相獨立、運算完全相同 → data-level parallelism;整層就是矩陣乘以向量(或多筆輸入時是矩陣乘矩陣)。GPU 有上千個簡單核心與高記憶體頻寬,剛好同時算完一整層

每層的 node 運算相同又互相獨立(矩陣乘法),GPU 的大量核心與高頻寬能同時算完

(f) 可以:每一層當成一個 pipeline stage,stage 之間放 register;上一筆資料進到下一層時,下一筆資料就能進入這一層

InputlayerRHiddenlayer 1RHiddenlayer 2RHiddenlayer 3ROutputlayerR=stage 之間的 pipeline register(每個 clock 把上一層的 N 個輸出鎖住,交給下一層)資料 1

t1t2t3t4t5t6t7
資料 1L1L2L3L4L5
資料 2L1L2L3L4L5
資料 3L1L2L3L4L5

可以:每層一個 stage,之間用 register 隔開;填滿後 5 筆資料同時在 5 層中

(g) throughput 提高:填滿 pipeline 後每個 stage 時間就產生一筆輸出,最多接近 stage 數倍(受最慢的 stage 限制)。latency(單筆資料從進入到出來)不會變短:仍要走過全部 5 層,加上 pipeline register 的延遲,還會稍微變長

throughput 上升,單筆 latency 不變或略增

(h) 值得(DNN 這類固定、規則的運算量大到有規模):

優點:專用的矩陣乘法單元、低精度(8/16 bit)、把權重放在 on-chip memory,拿掉圖形用不到的電路 → performance per watt 與 throughput 都比 GPU 高、延遲低、可做成車內小型低功耗晶片

缺點:設計與製造成本(NRE)很高,要有夠大的量才攤得回來;演算法一變(新的網路結構、運算)就不好適應,彈性低;軟體工具與生態系要自己建

可以:換到 performance per watt;代價是高 NRE、彈性差、軟體生態

(i) 每台 machine 負責每層 \(N/2\) 個 node(接收一半的輸入資料)

相鄰兩層之間,一台 machine 上的 \(N/2\) 個 node 各要傳 1 個數給對面 machine 的 \(N/2\) 個 node:\(\dfrac N2\cdot\dfrac N2=\dfrac{N^2}{4}\) 個;兩個方向合計 \(\dfrac{N^2}2\)

圖有 5 層 → 相鄰層之間 4 組:\(4\times\dfrac{N^2}2\)

\(2N^2\) 個 floating point numbers(每組相鄰層 \(N^2/2\),每個方向 \(N^2/4\))

(j) 假設 floating point 是 32 bit、層與層之間依序進行、計算與傳輸不重疊

單機:5 層 \(\times\) 每層 \(N\) 個 node \(\times A\) ns,由 \(Q\) 核分攤:\(T_1=\dfrac{5AN}{Q}\)

兩台:每台每層只算 \(N/2\) 個:計算 \(\dfrac{5AN}{2Q}\)

傳輸:每組相鄰層每個方向 \(N^2/4\) 個 \(\times32\) bit \(=8N^2\) bit;duplex 兩個方向同時走,各 10 Gbit/s = 10 bit/ns → \(0.8N^2\) ns;4 組依序 → \(3.2N^2\) ns

\(T_2=\dfrac{5AN}{2Q}+3.2N^2\)

\(\text{speedup}=\dfrac{T_1}{T_2}=\dfrac{5AN/Q}{5AN/(2Q)+3.2N^2}=\dfrac{2}{1+1.28\,NQ/A}\)

要大於 1 需要 \(A\gt1.28\,NQ\),也就是每個 node 的計算時間要遠大於「核心數 \(\times\) 每層 node 數」那麼多 ns,否則用 Ethernet 把網路拆到兩台反而比較慢

(k) \(P\) 台共用同一條 Ethernet:每台每層 \(N/P\) 個 node,計算 \(\dfrac{5AN}{PQ}\);跨 machine 的 node 配對有 \(N^2(1-\tfrac1P)\) 個(每組相鄰層),全部經過同一條 Ethernet(兩個方向合計 20 Gbit/s,用 \(P=2\) 時同樣的算法):每組 \(\dfrac{32N^2(1-1/P)}{20}=1.6N^2(1-\tfrac1P)\) ns,4 組共 \(6.4N^2(1-\tfrac1P)\)

\(T_P=\dfrac{5AN}{PQ}+6.4N^2\Big(1-\dfrac1P\Big)\)(\(P=2\) 代入得 \(\dfrac{5AN}{2Q}+3.2N^2\),與 (j) 相同)

\(P\to\infty\):計算項 \(\to0\),傳輸項 \(\to6.4N^2\),不再下降

\(\text{speedup}\to\dfrac{5AN/Q}{6.4N^2}=\dfrac{25A}{32\,NQ}\approx0.78\dfrac{A}{NQ}\)

如果每台 machine 都有自己的 10 Gbit/s link、經非阻塞 switch 連接,每台的傳輸量也隨 \(1/P\) 下降,這個上限就不存在;這裡照題目的「the Ethernet」當成共用的一條

(l) 由 (j)(k):網路傳輸的量是 \(N^2\),計算量是 \(AN/Q\);只有計算遠大於傳輸時,拆到多台機器才划算,而且 Ethernet 的頻寬很快變成瓶頸

規模建議理由
small一顆 CPU(或手機等級的 GPU)運算量小,單機放得下;不需要特別的硬體,成本最低
medium一張(或數張)GPU;網路固定、要低延遲低功耗時用 FPGAGPU 的 throughput 與成本比最好、軟體成熟;FPGA 可針對固定網路客製、效率較高
large多 GPU 伺服器叢集,用高速互連(NVLink、InfiniBand 等);量夠大且模型穩定時,用客製 ASIC單機放不下或要縮短訓練時間;Ethernet 太慢,要靠高速互連;ASIC 的高 NRE 要用大量使用才攤得回來

small:CPU;medium:GPU(固定網路可用 FPGA);large:GPU 叢集+高速互連,量大且穩定時用客製 ASIC

210%

2. (10 pts) Please answer the following questions. Note that if you don't explain why, you get 0 point.

(a) [2 pts] Do bus reads take longer than bus writes in Write-Invalidate Bus-Snooping Protocol for write-through cache? Answer YES or NO. Explain why.

(b) [2 pts] You are using a cache with a block size of eight words, with a single word alternatively written and read by two processors. Assume both processors are accessing different variables. Will this cause false sharing? Answer YES or NO. Explain why.

(c) [2 pts] Understanding interface is essential in studying Computer Organization. Computer Organization is about hardware/software interface. In comparison, on 12-30-2015, Google announced that next-generation Android will use OpenJDK for Java APIs (Application Programming Interface). Is Application Binary Interface (ABI) higher level than API? Answer YES or NO. Explain why you answer this way.

(d) [2 pts] When Google decided to use Java Virtual Machine for Android, did Google make abstraction level (or interface level) higher than C? Answer YES or NO, and explain why.

(e) [2 pts] Note that Android devices mostly use ARM processors. Does Java Virtual Machine help Android port to different architectures? Answer YES or NO, and explain why.

(a) YES。write-through:memory 永遠是最新的,read miss 由 memory 供應整個 block,bus 上要經過 arbitration、位址、memory 存取延遲、再把一個 block 搬回來,而且 CPU 要等到資料回來。bus write 只是把位址與一個 word 送上 bus,其他 cache 在 snoop 時把自己的拷貝 invalidate,不需要等回應(再加上 write buffer,CPU 甚至不用等)

YES:read 要等 memory 存取並搬回一個 block,write 只是廣播一個 word

(b) YES。兩個 processor 存取的是不同的變數,但若兩個變數落在同一個 8-word 的 cache block:一方寫入就會 invalidate 另一方的整個 block,另一方再讀自己的變數時 miss、把 block 搬回,兩邊的 block 來回搬(ping-pong),而其實兩者沒有真正共用資料

YES:不同變數在同一個 block,寫入互相 invalidate

(c) NO。API 是原始碼層級的介面(函式名稱、參數);ABI 是二進位層級:暫存器用法、calling convention、system call 編號、資料對齊與格式,更貼近硬體與 OS,層級比 API 低

NO:ABI 比 API 低階

(d) YES。Java 程式編成與硬體無關的 bytecode,由 JVM 負責 memory 管理(GC)、執行緒與底層 ISA/OS 的對應;程式不必面對指標、機器碼與 OS 呼叫的細節。C 直接編成特定 ISA 的機器碼,抽象層級比較低

YES:用 bytecode+JVM 隔開 ISA 與 OS

(e) YES。同一份 bytecode 可以在任何實作了 JVM(ART/Dalvik)的 architecture 上跑(ARM、x86、MIPS);移植到新 architecture 主要是移植 JVM 與底層 runtime,application 不用重編。(用 NDK 寫的 native code 還是要重新編譯)

YES:bytecode 與 architecture 無關,只要移植 JVM

311%

3. (11 pts) Draw a finite state transition diagram for Snooping Protocols for multiprocessors (from CPU angle). Please use 3 states (Invalid, Shared, Exclusive) and 4 CPU request types (CPU local-read request, CPU remote-read request, CPU local-write request, and CPU remote-write request). When you observe a performance problem due to false sharing, how to avoid false sharing?

local = 這顆 CPU 自己發出的 read/write;remote = snoop 到別顆 CPU 發出的 read/write(同一個 block)

InvalidSharedExclusivelocal readremote writelocal writeremote readlocal writeremote write(先寫回)

目前狀態local readremote readlocal writeremote write
Invalid→ Shared(read miss,取回 block)Invalid→ Exclusive(write miss,取回 block 並通知其他人 invalidate)Invalid
SharedShared(hit)Shared→ Exclusive(在 bus 上送出 invalidate,其他拷貝失效)→ Invalid
ExclusiveExclusive(hit)→ Shared(把 block 寫回/供應給對方)Exclusive(hit)→ Invalid(先寫回)

Exclusive 的 block 是唯一最新的拷貝(dirty),所以別人要讀時要由這顆 CPU 供應或寫回;任何有效狀態遇到 remote write 都要失效

3 個狀態、4 種 request 的轉移如上圖與表

避免 false sharing:不同 CPU 會寫入的變數不要放在同一個 cache block:

① 對齊與 padding:每個 thread 專用的變數用 alignas(64) 或補空位,讓它們各占一條 cache line ② 資料結構改成 per-thread 的區域拷貝,最後再合併(例:每個 thread 先累加到自己的區域變數,最後才寫共用結果) ③ array of structs 改成 structs of arrays,把被不同 thread 寫的欄位分開

對齊並 padding,讓不同 thread 寫入的變數落在不同的 cache line;或用 thread-local 副本最後合併

44%

4. (4 pts) On 2016-01-28, the editorial of Commercial Times (工商時報) expresses the urgency for Taiwan to apply the Blockchain technology. Two popular blockchains are (1) Bitcoin blockchain and (2) Ethereum, which are briefly explained below.

(1) Bitcoin blockchain needs repeated invocation of the following hashing computation, in pseudo code. Note that you don't need to understand the details of each line below.

Process the message in successive 512-bit chunks:
break message into 512-bit chunks
for each chunk
    create a 64-entry message schedule array w[0..63] of 32-bit words
    copy chunk into first 16 words w[0..15] of the message schedule array
    for i from 16 to 63
        s0 := (w[i-15] rightrotate 7) xor (w[i-15] rightrotate 18)
              xor (w[i-15] rightshift 3)
        s1 := (w[i-2] rightrotate 17) xor (w[i-2] rightrotate 19)
              xor (w[i-2] rightshift 10)
        w[i] := w[i-16] + s0 + w[i-7] + s1
    Initialize working variables to current hash value:
    a := h0   b := h1   c := h2   d := h3   e := h4   f := h5   g := h6   h := h7
    Compression function main loop:
    for i from 0 to 63
        S1 := (e rightrotate 6) xor (e rightrotate 11) xor (e rightrotate 25)
        ch := (e and f) xor ((not e) and g)
        temp1 := h + S1 + ch + k[i] + w[i]
        S0 := (a rightrotate 2) xor (a rightrotate 13) xor (a rightrotate 22)
        maj := (a and b) xor (a and c) xor (b and c)
        temp2 := S0 + maj
        h := g   g := f   f := e   e := d + temp1   d := c   c := b   b := a   a := temp1 + temp2

(2) Ethereum needs repeated invocation of the hashing computation that is memory hard, making it basically ASIC (Application-Specific Integrated Circuit) resistant. The code is irregular and involves graph building:

def produce_dag(params, seed, length):
    P = params["P"]
    picker = init = pow(sha3(seed), params["w"], P)
    o = [init]
    for i in range(1, length):
        x = picker = (picker * init) % P
        for _ in range(params["k"]):
            x ^= o[x % i]
        o.append(pow(x, params["w"], P))
    return o

(Details are on github: …/Dagger-Hashimoto.md、…/go-ethereum/tree/master/pow/dagger)

Please answer the following questions:

(a) [2 pts] Compared with Ethereum, is Bitcoin blockchain's hashing more suitable for GPU (or ASIC)?

(b) [2 pts] Is Ethereum more suitable for CPU than GPU?

(a) YES。Bitcoin 的 hash(SHA-256)全是固定的位元運算(rotate、xor、and、加法),每個 chunk 做 64 輪、控制流程固定,工作集很小(\(w\) 64 個 word 加幾個變數),不同的 nonce 可以完全獨立同時計算 → 規則的 data-parallel,GPU 的大量 ALU 吃得滿,固定功能的電路更是可以直接做成 ASIC

YES

(b) YES。Ethereum 的程式是 memory-hard 且不規則:x ^= o[x % i] 的位址由資料決定(隨機存取一個大的 DAG),每一步依賴前一步的結果(pointer chasing 式的相依),ALU 運算反而很少;GPU 的 SIMD/SIMT 要靠規則、運算密集的負載才能發揮,這種不規則的相依存取讓大部分執行單元閒置,優勢縮小;CPU 有大的 cache 與大記憶體、能處理不規則存取與分支,相對適合

memory-hard 的目的就是讓只堆運算單元的專用硬體(ASIC)失去優勢;實務上 GPU 靠高記憶體頻寬挖 Ethereum 仍比 Bitcoin 的 hash 受限更多

YES

53%

PART II – OPERATING SYSTEMS

NOTE that in the question, it is intended to provide redundant or miss certain assumption to disguise you. Please make your own assumption if necessary to answer the questions.

Bob is designing his cloud-based storage services, called BobBox and similar to Dropbox, to store the files on his desktop computer, laptop computer, and smart phones to a single cloud storage. Later, he will also open this service for his friends. Hence, the storage services will support multiple users and multiple devices. The service consists of two applications: BoxBoxClient (BBC) on the client devices and BobBoxServer (BBS) on the server. Please answer the following questions.

5. (3 pts) One shortcoming of existing Dropbox service is conflict resolving: many conflicted files are stored when file folder is shared with multiple users and multiple devices. Please describe the possible causes of the conflicts among file synchronization. Hint: you may consider the connectivity between BBS and BBC, and time instances to synchronize the files on BBS and BBC.

① 離線修改:device 沒連上 BBS 時改了檔案,重新連線時 BBS 已經有別人(或自己另一個 device)上傳的較新版本,兩份都從同一個較早的版本改出來

② 同步的時間差:兩個 BBC 在 BBS 還沒把對方的改動推送過來前,各自修改並上傳(同步有延遲、不是即時)

③ 連線不穩:上傳或下載中途斷線,只同步到一部分內容或 metadata,下次同步看到的版本互相不一致

④ 各 device 的時鐘不一致:單靠修改時間(timestamp)無法判斷誰先誰後,把版本的先後弄錯

離線/延遲同步時多個 device 從同一個較早的版本各自修改,加上連線中斷與時鐘不一致,造成版本分叉

616%

6. (16 pts) BBC has several options to transmit the files on client devices to BBS. On BBC, the files are read from local storage devices and send to network handler.

(a) [8 pts] There are two types of Input/Output (IO) libraries provided by operating systems: Buffered IO and Unbuffered IO. Please describe these two types of the IO libraries (4 points) and compare the number of memory copy operations from storage subsystem to application memory (4 points).

(b) [8 pts] BBC should upload/download several files to/from the server:

i. [2 pts] Should the access to local storage system be sequential access or random access? Please explain your answer.

ii. [6 pts] BBC may use blocking synchronous IO or non-blocking asynchronous IO models to access storage systems. Please describe the above two IO models and choose one to increase application throughput, i.e., avoiding unnecessary waiting and operations.

(a) Unbuffered I/O:應用程式直接呼叫 system call(read/write),資料在 kernel(page/buffer cache)與應用程式給的 buffer 之間傳送,每次呼叫都進一次 kernel,函式庫沒有自己的 buffer

Buffered I/O:C 函式庫(fread/fwrite)在 user space 另外維護一塊 buffer,應用程式的小量讀寫先在這塊 buffer 裡處理,buffer 空了/滿了才呼叫 system call 一次搬大量資料 → system call 次數少,適合很多小 I/O

memory copy 次數(storage → 應用程式記憶體,DMA 把資料送進 kernel buffer 不算 CPU 的複製):

路徑CPU memory copy
Unbufferedkernel buffer → 應用程式 buffer1 次
Bufferedkernel buffer → library buffer → 應用程式 buffer2 次

連 DMA 那一次一起算就是 2 次對 3 次;用 O_DIRECT 讓 DMA 直接寫進應用程式 buffer 則 CPU copy 為 0 次,但要自己對齊 buffer、也沒有 kernel 的 read-ahead

unbuffered:1 次複製;buffered:多一層 library buffer,2 次複製(但 system call 次數較少)

(b-i) sequential access:每個檔案從頭到尾依序讀(或寫),可以用 kernel 的 read-ahead、少 seek(對硬碟差距很大);網路傳輸本身也是依序組裝封包,所以按 offset 連續讀最順。多個檔案可以一個接一個、或各自依序進行,不要在檔案之間隨機跳讀

sequential:利用 read-ahead、減少 seek,與網路依序傳輸的方式吻合

(b-ii) blocking synchronous I/O:thread 呼叫 read 後睡到資料備妥才回來,期間什麼都不能做;先讀完一塊、再傳一塊,儲存裝置與網路輪流閒置,一次只處理一個檔案的一個 request

non-blocking asynchronous I/O:送出 I/O request(aio、io_uring、epoll+non-blocking,或 I/O thread pool)立刻返回,thread 繼續做別的事,完成時用 event、callback 或 completion queue 通知

選 non-blocking asynchronous:同時有好幾個檔案要傳,可以在等某個檔案的磁碟讀取時,把另一個檔案已讀好的資料送上網路,儲存與網路 I/O 重疊,也不用為每個檔案開一個睡覺的 thread;throughput 較高,代價是程式比較複雜

選 non-blocking asynchronous I/O:重疊 storage 與 network 的等待,提高 throughput

76%

7. (6 pts) BBS needs to serve concurrent synchronization requests from multiple devices and multiple accounts. Suppose multiple threads are used in BBS to serve concurrent requests. Please describe thread pool model and explain how it may limit the resources used by BBS while serving concurrent requests.

thread pool:BBS 啟動時先建好固定數量(例如 \(M\) 個)的 worker thread;request 進來先放進 queue,閒置的 worker 取出一個處理,做完回到 pool 等下一個,不會每個 request 新建、結束後銷毀 thread

如何限制資源:

① thread 數有上限 \(M\):stack 記憶體、kernel 的 thread 資料結構、context switch 與 scheduler 的負擔都有上限,同時處理的 request 不會超過 \(M\) 個

② request 暴增時多出來的在 queue 裡等(queue 設上限,滿了就拒絕或要求 client 稍後再試),伺服器不會因為建立過多 thread 而耗盡記憶體或 CPU

③ 省掉每個 request 建立與銷毀 thread 的成本

固定大小的 worker pool+有上限的 request queue:同時執行的 thread 數、記憶體與 context switch 成本都被限制住

820%

8. (20 pts) Suppose a thread serves only a request. To avoid conflicted files, some file locking mechanism might be applied to block threads not holding the lock. After the file is unlocked, all blocked threads start to compete for the lock again.

(a) [10 pts] A smart engineer designs a barrier data type of 2 semaphores and a counter and a barrier_wait function to help design the competing mechanism so that all threads calling barrier_wait will be blocked and all blocked threads will be unblocked when the number of blocked threads reaches n. Please complete the following codes for barrier and barrier_wait in C-like language where mutex(1) stands for the semaphore mutex is initially 1.

typedef struct {
    semaphore mutex(1), ...
    ...
} barrier;

barrier_wait (barrier *b, int n) {
    ...
}

(b) [10 pts] For the unblocked threads to compete for the lock with the most user satisfaction, especially for good friends, first come first serve might not be the best policy, however, no one would like to wait for a long time. The priority of friends might change dynamically depending on which files are requested. How do you design your scheduling policy? (5 points) How do you implement your policy? (5 points) Hint: describe which parts in the system, application, or else need to be modified. No code is needed.

(a) 2 個 semaphore:mutex(保護 counter)、gate(初值 0,擋住先到的 thread);counter 記已經到達的 thread 數。最後一個到的把 gate 打開,之後每個被放行的 thread 再把 gate 打開給下一個(baton passing):

typedef struct {
    semaphore mutex(1);       // 保護 count
    semaphore gate(0);        // 還沒湊滿 n 個之前擋住所有 thread
    int count = 0;            // 已經到達 barrier 的 thread 數
} barrier;

barrier_wait (barrier *b, int n) {
    wait(&b->mutex);
    b->count++;
    if (b->count == n)         // 第 n 個到達:全部放行
        signal(&b->gate);
    signal(&b->mutex);

    wait(&b->gate);          // 先到的在這裡等;gate 打開後通過
    signal(&b->gate);        // 把 gate 傳給下一個等待的 thread
}

前 \(n-1\) 個 thread 在 wait(gate) 睡著;第 \(n\) 個把 gate 設成 1,第一個醒來的 thread 通過之後 signal(gate) 叫醒下一個,一個接一個,全部 \(n\) 個都會通過

這是一次性的 barrier(count 沒有歸零、gate 一直是開著)。要重複使用就要再多一個 turnstile(兩道門:第一道湊滿 \(n\) 個才放行,第二道等所有人通過才關回去),或用 n−1 次 signal 的寫法並在最後一個通過時把 count 歸零

mutex(1)、gate(0)、count=0;最後一個到的 signal(gate),其餘的 wait(gate) 後再 signal(gate)

(b) policy:priority scheduling 加上 aging,取代 FIFO:

每個等待 lock 的 request 有一個有效優先權 \(=\) 這個使用者對這個檔案的關係權重(file owner 設定的好友等級、這個檔案的存取權限、request 類型,例如讀比寫優先)+隨等待時間增加的 aging 補償;關係權重是跟「哪一個檔案」綁定的,所以同一個朋友在不同檔案的優先權不同、可隨時變動

aging 讓優先權低的人等越久加分越多,最後一定輪到,沒有人會一直等下去(避免 starvation)

依「使用者對該檔案的優先權+等待時間(aging)」排序,而不是先來先服務

implementation:要改的地方:

① lock 實作(作業系統或 BBS 的 lock manager):每個檔案的 lock 不用 FIFO 的 wait queue,改成 priority queue(heap);unlock 時取出有效優先權最高的 waiter,把 lock 交給它並喚醒(condition variable 或 semaphore)

② application(BBC/BBS):送出 lock request 時帶上 user ID 與 file ID;BBS 查檔案的好友關係表(ACL)算出這個 request 的優先權

③ BBS 的資料:儲存各檔案的好友等級;等待時間由 lock manager 記錄每個 waiter 的進入時間,定期(或在 unlock 時)更新 aging

④ 優先權變動時(owner 修改關係):更新 queue 中該 waiter 的位置

lock manager 改成 priority queue+aging;request 帶 user/file ID,由 BBS 依檔案的好友關係表計算優先權

95%

9. (5 pts) Since the files might be shared by friends, how do you design the access control mechanism to be user-friendly and very efficient, especially the files might be accessed in different devices with different sizes of memory, storage, and screen. Hint: different friends might have different access rights on different files.

權限模型:每個檔案(或資料夾,子檔案繼承)一份 access control list(ACL):誰(使用者或群組)有哪些權限(read、write、share)。朋友分群組(家人、好友、同事),權限對群組設定,不用逐人逐檔設定 → 使用者好設定;不同朋友對不同檔案可以有不同權限

效率:權限判斷在 BBS 進行(單一依據,改權限立即生效);BBC 拿到一個短時效的 token/capability(含檔案 ID 與權限),在有效期內傳輸資料不用每次都查 ACL;ACL 與群組資訊快取在 server memory

不同裝置:權限的判斷與裝置無關(同一份 server-side 規則);傳輸內容依裝置調整:小螢幕、小儲存的手機先給縮圖與中繼資料,要看再分段下載(partial download),不必整個檔案同步到每個裝置

server 端的 per-file ACL(群組權限、資料夾繼承)+短時效 token;依裝置能力調整傳輸的內容,不改變權限判斷

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

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

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

其他年度與考科

同一年的其他科

同一科的其他年度

聯絡我們

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

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

william.chou.123123@gmail.com