MESI protocol

Posted by w@hidva.com on April 8, 2016

关于 MESI

  • MESI 是一种使用广泛的协议,用来实现 cache coherence 和 memory coherence.

MESI 细节

  • MESI 仅是一种协议!并没有与具体的硬件关联.

MESI 中的缓存模型

MESI 缓存模型

  • cache,cache line;cache 与 cache line 是 2 回事;其中 cache line 是固定大小(一般 64 bytes) 的缓存空间;而 cache 中存放众多 cache line 以及其他一些东西(比如:控制器).

    • 参考来源:这部分是我个人理解,并没有正是参考来源.

States

  • 在 MESI 中,将 cache line 分为 4 种 state,各自如下:
  • Modified; 表明 cache line 对应的 memory 仅在一个 Cache 中被缓存了,而且其在 Cache 中 的缓存与在内存中的值也是不一致的!
  • Exclusive; 表明 cache line 对应的 memory 仅在一个 Cache 中被缓存了,并且其在缓存中的内 容与在内存中的内容一致.
  • Shared; 表明 cache line 对应的 memory 在”多”个 Cache 中被缓存了,并且在所有缓存中的内容 与在 memory 中的内容一致.

    • Shared 状态并不是精确的.设想一下这种场景,CacheA 中的 lineA0 与 CacheB 中的 lineB0 关联着同一内存位置,此时 lineA0,lineB0 均是 Shared 状态,但是当 CacheB 由于某种关系( 如调度)而将 lineB0 丢弃,至此 lineB0 变为 Invalid 状态,而且根据 MESI 协议,此时并不 会发送通知什么的,所以 lineA0 仍然处于 Shared 状态!
  • Invalid; 表明当前 cache line 无效.

Operation

  • read;当 cache line 处在 Invalid 状态时,不可被读,此时必须要加载内容之后才能被读.其他状态 下,cache line 可被读.

  • write;仅当 cache line 处在 Modified 或 Exclusive 状态时,才能被写;

    • 当 cache line 处在 Shared;必须先发送 Request-For-Ownership 广播让其他 Cache 中关联到同一内存地址的 cache line 变为 Invalid 之后才能写.

    • 当 cache line 处在 Invalid 时,参见下面 Read-For-Ownership.

  • discard;Cache 可以随时丢弃 non-Modified cache line,从而让这些 cache line 变为 Invalid. 对于 Modified cache line,必须先将 cache line 的内容写入到内存中.

  • 若 Cache 中有一 cache line 处在 Modified 状态,则其必须能监听其他 Cache 对相应关联内存的 读操作;并且在监听到读操作之后:
    1. forcing the read back off(不知道如何翻译,大概意思就是让读操作延迟).
    2. 将处于 Modified 的 cache line 中的内容写入到关联内存地址中,并将该 cache line 置为 Shared.
  • 若 Cache 中有一 cache line 处在 Exclusive 状态,则其必须能监听其他 Cache 对相应关联内存 的读操作;并且在监听到读操作之后:
    1. 将该 cache line 的状态由 Exclusive 改为 Shared.
  • 若 Cache 中有一 cache line 处在 Shared 状态,则其必须监听其他 Cache 发送 invalidate broadcasts;并且在收到 invalidate broadcasts 之后:
    1. 丢弃该 cache line,将其状态改为 Invalid.
  • Read For Ownership;是一种将 read 操作与 invalidate broadcast 操作合并在一起的操作. 当 CPU 写处于 Shared 或 Invalid 状态的 cache line 时执行该操作.具有以下效果:
    1. 读取数据;
      • Q1: 不是很清楚当 CPU 写入处于 Shared 状态的 cache line 时,是否还会读取数据? 我觉得应该不需要.
    2. 发送 invalidate broadcasts.
    3. 被写入数据.

CPU 实现

  • MESI 简单的实现中,有以下耗时操作:

    • 写入到处于 Invalid 状态的 cache line.
    • 将一个 cache line 的状态更改为 Invalid.
      • 这个也耗时…???
  • 现代 CPU 为了提升效率采用了各种技巧,代价就是需要用户来介入,具体就是引入了 memory barriers. 大概应是用户需要在适当的地方使用 momery barriers 指令来确保 MESI 正确.

参考

转载请注明出处!谢谢