Linux 核心101:cache組織策略

liaochangjiang發表於2019-04-22

本文參考了:

簡述

上篇文章 講了 cache 的一些基本知識,提到了一種最基本的 cache 組織策略:Direct Mapped Cache。這種策略優點是實現簡單,速度快(這裡指的速度快是說定位 cache 位置的速度,因為一個 main memory address對應在 cache 中的位置是固定的),但是有一個嚴重的缺陷,就是 cache miss 率高。為什麼呢?還是看下面這個圖,假如 CPU 恰好依次需要0、4、8、12這四個 main memory address 的速度,之後的 block 都會把前面 block 的擠佔掉!(儘管現在 cache 中還有很多空餘空間)

Linux 核心101:cache組織策略

本文將介紹另外兩種 cache 組織策略:Fully Associative CacheSet Associative Cache

Fully Associative Cache

Fully Associative Cache是解決了Direct Mapped Cache cache miss 高的缺陷。它是怎麼實現的呢?

Linux 核心101:cache組織策略

對比一下Direct Mapped Cache的示意圖,Fully Associative Cache中就沒有 index 這個位了,main memory 中的一個block 可以被 map 到 cache 中的任意位置。這種方法,定位main memory block 在 cache 中位置是通過 tag 位來判斷的。因為沒有 index,所以在 cache 中定位的時候,就需要對比 cache 中每一條記錄的 tag,That’s a lot of comparators!

Linux 核心101:cache組織策略

所以,Fully Associative Cache只適用於小的 cache,比如某些 Intel CPU 中的 TLB cache就是Full Associative的。這裡說的非常小,頂多也就幾十個 entry。雖然這種方法應用也不是很廣泛,但是給了我們一種很好的思路:Direct Mapped Cache 定位快,但是 cache miss 機率高;Fully Associative Cache 定位慢,但是 cache miss 率低。那麼,可以取一箇中間值,使得定位 速度足夠快,同時cache miss機率足夠低。

Set Associative Cache

Linux 核心101:cache組織策略

Set Associative Cache是Direct mapped cache 和 Fully associative cache的一種取捨。cache 被分成了多個 set,每個 set 裡面有多個 cache line。一個 memory block 會先被 map 到其中一個 set,然後置於此 set 中的任一cache line。

Direct mapped cache 可以看做 n * 1的矩陣(n 個set,每個 set 含有一個 entry),Fully associative cache可以看做1 * m 的矩陣,而Set Associative Cache就是 n * m 的矩陣。Direct mapped cache實質上可以看作是 1-way Associative Cache,而Fully associative cache是 m-way Associative Cache。

Linux 核心101:cache組織策略

那麼現實生活中,該採用 ?-way Associative Cache呢?一般選擇8-way 就足夠了,下圖的資料可以得到一個直觀地感覺。

Linux 核心101:cache組織策略

總結一下

Direct Mapped Cache實現最簡單,但是 cache miss 率太高,實際生產幾乎不會使用。Fully Associative Cache cache miss 機率最低(理論上可以達到0),但是如何快速定位cache line 所在位置成了個大問題,所以只適用於很小的cache,比如TLB cache。Set Associative Cache是二者的權衡,普遍採用的是8-way Associative Cache。

相關文章