N-way set associative 是什么?

<aside> 💡 一种 Cache 的组织方式; 在 N-way set associative cache 中, Cache 被分成一些 Sets, 每个 SetN 个 **Cache Lines(or Cache Blocks)**组成; 当CPU访问一个内存地址的时候,先通过内存地址计算出 Set Index,然后再在这个 Set 中找到具体的 Cache Line(Cache Block); 除了 N-way set associative 还有和 direct-mapped cache(N=1), fully associative cache

</aside>

N-way set associative cache is a specific organization and mapping technique used in CPU caches.

It is a compromise between direct-mapped cache and fully associative cache, aiming to balance performance and complexity. The idea is to reduce cache misses while still maintaining a manageable level of hardware complexity.

In an N-way set associative cache, the cache is divided into a number of sets, and each set contains N cache lines (also called cache blocks).

When the CPU needs to access a particular memory address, it calculates the set index, using a specific formula based on the memory address, and then searches for the data within that set.

The cache can store N different memory blocks with the same set index, which is the reason for calling it N-way set associative.

As a result, the chance of cache conflicts (two different memory addresses mapping to the same cache location) is reduced, leading to fewer cache misses compared to direct-mapped caches.

<aside> 💡 Cache 的组织结构如下, S 个 sets , 每个 set 有 E 个 cache lines, 每个 cache line可以存放 B 字节数据(图中的 E 就是 N-way 的 N);

</aside>

Untitled

<aside> 💡 Intel Core i7 Haswell 的 Cache 就是 32 kB 8-way set associative with 64 bytes/block; 即每个Set 有 8 个 Cache Lines(blocks), 共 8 * 64 = 512 bytes; 因此一共 32kB/512bytes = 64 个 Sets; 所以 Set 和 Cache Line(block) 都需要 6 bit 作为 index (2^6 = 64); (图中 47 bit address range 应该是只考虑用户态地址是 0x00007.. 开头的,有17个 bit 都固定是 0?)

</aside>

Untitled

<aside> 💡 用 C 代码大致模拟一下这个结构

</aside>