工作方式(一句话): 引入了一个 MSR,这个 MSR 给了 8 个可以配置的空间,每个空间可以指定一个 Memory Type^。页表 PTE 当中有 3 个 bit 可以 index 到这 8 个空间,表示这个 PTE 所指向的页对应的 type。

MSR 当中这 8 个空间的位置:

![[SDM.pdf#page=3549&rect=44,336,558,432&color=annotate SDM, p.3549]]

每个空间可以配置的对应值:

![[SDM.pdf#page=3549&rect=41,101,561,279&color=annotate SDM, p.3549]]

页表当中的 3bit 能索引到的空间:

![[SDM.pdf#page=3550&rect=42,469,562,614&color=annotate SDM, p.3550]]

SDM 当中对应的章节:

[!PDF|annotate] [[SDM.pdf#page=3548&selection=56,0,58,26&color=annotate|SDM, p.3548]] 13.12 PAGE ATTRIBUTE TABLE (PAT)

The Page Attribute Table (PAT) is a processor feature available on many x86 and x86-64 CPUs.

It acts as a companion to Memory Type Range Registers (MTRRs) and provides a finer-grained control over how different areas of memory are cached.

Memory Type

Memory type 管理的是对应的内存地址进行 cache 的策略(该不该 Cache 等等)。

SDM 的这个位置:

[!PDF|annotate] [[SDM.pdf#page=3218&selection=58,0,60,24&color=annotate|SDM, p.3218]] 5.9 PAGING AND MEMORY TYPING

[!PDF|annotate] [[SDM.pdf#page=3521&selection=28,0,30,28&color=annotate|SDM, p.3521]] 13.3 METHODS OF CACHING AVAILABLE

Memory type 其实就是 type of caching。一共有六种 memory type:

![[SDM.pdf#page=3521&rect=40,134,562,343&color=annotate SDM, p.3521]]

一言以蔽之。单纯从 Cache 的行为上,这 6 个 Type 我们可以分成 5 类:

  • 不允许缓存:UC (Strong Uncacheable) 和 UC- (Uncacheable) 两种都是这个行为,所有读写都直接发往物理地址
  • 读不允许缓存写允许缓存:WC (Combined 表示的就是多次写会合并成为一个,这个合并就是在 WCB 里面做的)。WCB 是 CPU 核心里 LSU 的专用写合并硬件,在 L1d 之前、独立于缓存层级,只攒写、不缓存、不读命中,也就是 WCB 里面的内容即使是包含这个的核,读都是读取不到的。这是一个缓存可见性问题,而不是缓存一致性问题。所以它完美适配的是 MMIO / 显存这类 “只写 / 少读、无副作用” 的场景。
  • 写直达,读缓存,写不缓存(WT):几乎不用,只有极老的设备或特殊强一致场景才碰。
  • 读写都走 cache,不立刻写内存,等到 Cache 要被替换时,才一次性写回内存(WB):靠 MESI 缓存一致性保证多核安全,普通内存默认就是它。
  • WP:读走缓存,写不走缓存:适用读多写极少、且写必须立刻对所有 CPU 可见的情况。

Strong Uncacheable (UC)

System memory locations are not cached. All reads and writes appear on the system bus and are executed in program order without reordering. No speculative memory accesses, page table walks, or prefetches of speculated branch targets are made. This type of cache-control is useful for memory-mapped I/O devices. When used with normal RAM, it greatly reduces processor performance.

MMIO 因为映射到了设备内存,所以这部分地址空间不应该是能够被 Cached 的,每次访问都应该直接访问到设备。

Uncacheable (UC-)

Has same characteristics as the strong uncacheable (UC) memory type, except that this memory type can be overridden by programming the MTRRs for the WC memory type. This memory type is available in processor families starting from the Pentium III processors and can only be selected through the PAT.

Write Combining (WC)

![[SDM.pdf#page=3522&rect=42,565,561,731&color=annotate SDM, p.3522]]

适合高速连续写的 MMIO / 帧缓冲。

Write Through (WT)

Write Protected (WP)

读走缓存,写不走缓存:适用读多写极少、且写必须立刻对所有 CPU 可见的情况。MESI 协议对这种类型的内存仍然生效,保证多核之间读和写的一致性。

WP 相对于 WB 的唯一优势:写操作立刻全局可见,不需要靠 MESI 协议同步。

背景:MESI 协议只能保证多核之间的缓存一致性,不能保证设备和 CPU 之间看到数据的缓存一致性。

适用场景:一个变量被 CPU + 硬件设备同时访问。比如:设备会直接读内存,但不看 CPU 缓存。

Write Back (WB)

最常用,默认类型。