内存未来技术:事务内存、延迟隐藏与向量化
程序员应该知道的内存:未来技术
本文是系列第 8 篇,讨论 atomic operation 的扩展瓶颈、transactional memory、不断增加的 memory latency,以及 vector operation 的发展方向。
TL;DR
- 核心判断:处理器频率增长放缓后,更多性能来自并行执行、隐藏 latency 和减少同步,而不是单纯提高 clock frequency。
- 同步瓶颈:共享 counter 上的 atomic operation 会串行化 ownership;transactional memory 试图让一组读写以 transaction 形式提交。
- 延迟问题:memory latency 继续增加时,软件需要更多并行 memory operation 才能保持 pipeline 忙碌。
- 实践边界:transaction 可能 abort,vector operation 需要连续、对齐、适合批处理的数据;这些技术不能替代良好的 data layout。
目录
| 章节 | 说明 |
|---|---|
| 8 Upcoming Technology | 技术趋势总览 |
| 8.1 Atomic Operation 的问题 | 共享状态的扩展瓶颈 |
| 8.2 Transactional Memory | 用 transaction 组织并发更新 |
| 8.3 Increasing Latency | 用并行性隐藏内存延迟 |
| 8.4 Vector Operations | SIMD 与批量数据处理 |
8 Upcoming Technology
前文讨论多处理器时已经看到:CPU 或 core 数量增加后,系统会出现明显的性能问题。然而,未来恰恰还要继续扩大这种规模。processor 会拥有越来越多的 core;由于 single-core performance 不会再像过去那样快速增长,程序必须具备更高程度的并行性,才能利用 processor 增加的潜力。
8.1 Atomic Operation 的问题
传统上,同步访问 shared data structure 有两种方式:使用 mutual exclusion,通常借助 system runtime 提供的功能;或者使用 lock-free data structure。
lock-free data structure 的问题在于,processor 必须提供能够以 atomic 方式完成整个操作的 primitive,而这种支持是有限的。大多数 architecture 只保证对一个 word 进行 atomic read 和 atomic write。基本实现方式有两种:atomic compare-and-exchange(CAS),以及 load lock/store conditional(LL/SC)指令对。
CAS 可以很容易地用 LL/SC 指令实现,因此 CAS 成了大多数 atomic operation 和 lock-free data structure 的基础。x86 与 x86-64 提供了更丰富的 atomic operation,其中许多是针对特定用途对 CAS 的优化。例如,对一个 memory location 做 atomic increment,理论上可以用 CAS 或 LL/SC 实现,但 x86/x86-64 的原生 atomic increment 更快。
这两个 architecture 的一个重要扩展是 double-word CAS(DCAS)。它对部分应用很有价值,但并非对所有应用都有帮助。下面用一个基于 array 的 lock-free stack(LIFO)说明问题。
struct elem { data_t d; struct elem *c; };
struct elem *top;
void push (struct elem *n)
{
n->c = top;
top = n;
}
struct elem *pop (void)
{
struct elem *res = top;
if (res != NULL)
top = res->c;
return res;
}
图 8.1:非 thread-safe 的 LIFO
这段代码显然不是 thread-safe 的。不同 thread 并发访问时,会在不考虑其他 thread 修改的情况下更新全局变量 top;element 可能丢失,已经移除的 element 也可能突然重新出现。可以用 mutual exclusion 解决,但这里尝试只使用 atomic operation。
第一次改进是在安装或移除 list element 时使用 CAS:
#define CAS __sync_bool_compare_and_swap
struct elem { data_t d; struct elem *c; };
struct elem *top;
void push (struct elem *n)
{
do
n->c = top;
while (!CAS (&top, n->c, n));
}
struct elem *pop (void)
{
struct elem *res;
while ((res = top) != NULL)
if (CAS (&top, res, res->c))
break;
return res;
}
图 8.2:使用 CAS 的 LIFO
乍看之下,这似乎已经可以工作:只有当 top 仍然等于操作开始时 LIFO 顶部的 element,top 才会被修改。但并发问题必须在所有层面上考虑。另一个 thread 可能恰好在 pop 的 CAS 之前被调度,并执行:
l = pop();
push (newelem);
push (l);
最终,原来的 top element 又回到了顶部,但第二个 element 已经不同。第一个 thread 恢复执行后,由于 top 的值没有变化,CAS 会成功;然而 res->c 已经不是正确的指针,它仍指向原 LIFO 的第二个 element,而不是 newelem。于是新 element 丢失,这就是 ABA problem。
一种建议是使用 x86 和 x86-64 的 DCAS,在指向 top 的指针旁边增加 generation counter:
struct lifo { struct elem *top; size_t gen; } l;
void push (struct elem *n)
{
struct lifo old, new;
do {
old = l;
new.top = n->c = old.top;
new.gen = old.gen + 1;
} while (!CAS (&l, old, new));
}
struct elem *pop (void)
{
struct lifo old, new;
do {
old = l;
if (old.top == NULL)
return NULL;
new.top = old.top->c;
new.gen = old.gen + 1;
} while (!CAS (&l, old, new));
return old.top;
}
图 8.3:使用 double-word CAS 的 LIFO
每次 push 或 pop 都会递增 generation counter,因此 top 指针即便回到原值,整个 struct lifo 也已经不同。第一个 thread 恢复时,CAS 会因为 counter 的变化而失败,下一轮循环会重新读取正确的 element。这个例子在当时是 pseudo-code,因为 GCC intrinsic 并不接受把结构体作为 CAS 操作数。
但 DCAS 并不是普遍解决方案。假设某个 thread 执行 pop,在检查 old.top == NULL 后被中断;第二个 thread 完成 pop 并获得原来的第一个 element,它可以修改 element 的所有字段,甚至释放这块动态分配的内存。第一个 thread 恢复后,old.top 仍然指向已被移除的 element;执行 old.top->c 时可能解引用已经释放的内存,导致进程崩溃。
要修复这个问题,通常必须永不释放这些内存,或者在释放前确认没有任何 thread 仍在引用它们。对本应更快、更并发的 lock-free data structure 来说,这些额外要求可能完全抵消其优势。支持 garbage collection 的语言可以解决内存回收问题,但 garbage collection 也有自己的成本。更复杂的 data structure 情况通常更糟:现有 x86/x86-64 的 CAS 只能修改内存中连续的两个 word,无法原子地在 double-linked list 的任意位置添加或删除 element。
根本问题是,一个操作往往涉及多个 memory address;只有当这些 address 中没有任何一个被并发修改时,整个操作才能成功。这是 database transaction 中的经典概念,也正是 transactional memory 方案的来源。
把 counter 拆成每线程或每 node 的 local counter,再在需要时归并,通常可以减少这个瓶颈。代价是读取总数时需要聚合,并且结果可能不是每一时刻都精确一致。设计时应根据统计精度和更新频率做权衡。
8.2 Transactional Memory
Herlihy 和 Moss 在 1993 年的论文中提出:既然 software 单独无法高效解决这个问题,就在 hardware 中为 memory operation 实现 transaction。其原则与 database transaction 相同:transaction 的结果要么一次性全部可见,要么 transaction abort,所有值保持不变。
8.2.1 Load Lock/Store Conditional Implementation
Transactional memory 是 atomic operation 的替代和扩展,尤其适合 lock-free data structure。它听起来很复杂,但某些 processor 已经实现了相似机制:LL/SC 指令对本身就形成一个 transaction;如果 memory location 在期间被修改,SC 会 abort,否则 commit。Transactional memory 把这套机制扩展为由多条 instruction 组成的 transaction。
8.2.2 Transactional Memory Operations
一般来说,一个 transaction 不应在第一条 store instruction 后立即结束,而应允许执行若干 load 和 store,因此需要独立的 COMMIT 和 ABORT operation,还需要一个检查 transaction 当前状态的 operation。memory operation 可以分成三类:普通 read;之后还会被写入的 read;write。第二类 read 需要以 exclusive 方式取得 Cache line,普通 read 则可以从 MESI 的 E 或 S state 得到满足。
8.2.3 Example Code Using Transactional Memory
下面是使用 transactional memory 的 LIFO 示例:
struct elem { data_t d; struct elem *c; };
struct elem *top;
void push (struct elem *n)
{
while (1) {
n->c = LTX (top);
ST (&top, n);
if (COMMIT ())
return;
/* delay */
}
}
struct elem *pop (void)
{
while (1) {
struct elem *res = LTX (top);
if (VALIDATE ()) {
if (res != NULL)
ST (&top, res->c);
if (COMMIT ())
return res;
}
/* delay */
}
}
图 8.4:使用 transactional memory 的 LIFO
这里的 LT 请求普通 read,LTX 请求 exclusive read,ST 写入 transactional memory,VALIDATE 检查 transaction 是否仍可提交。若 transaction 已经被标记为 abort,VALIDATE 会实际终止它;下一条 transactional memory instruction 会开始新的 transaction,因此调用者必须跳过旧 transaction 剩余的代码。
COMMIT 结束 transaction,成功时返回 true;失败时通常需要重新执行整个代码序列。失败后应当插入 delay,否则 thread 可能陷入浪费能耗并使 CPU 过热的 busy loop。LT、LTX 和 ST 可能失败却不直接报告失败;程序只能通过 VALIDATE 或 COMMIT 得知结果。尤其是 load 失败时,寄存器中读到的值可能是无效值,因此示例在解引用指针前必须先 VALIDATE。
8.2.4 Bus Protocol for Transactional Memory
transaction cache 很可能与 L1d 并行存在,而不是作为一块独立的主内存。它会比 L1d 小得多,甚至可以是 fully associative,其容量由一个 transaction 允许包含的 operation 数量决定。transaction cache 与 L1d 是 exclusive 的:同一条 Cache line 最多位于其中一个 cache 中。transaction 中对同一条 line 的后续访问可以命中 transaction cache;只有开始新 transaction 或向仍然成功的 transaction 加入新的 Cache line 时,才需要总线操作。
更具体地说,transaction cache 的每个 slot 除了拥有 MESI state,还需要 transaction state。EMPTY 表示 slot 没有数据,MESI state 必然是 I;NORMAL 表示已经 commit 的数据,它也可以同时存在于 L1d,MESI state 可以是 M、E 或 S;XABORT 表示 transaction 产生、abort 时必须丢弃的数据;XCOMMIT 表示 transaction 修改前保存的旧数据,commit 时可以丢弃。transaction 产生的新值在 commit 前不会写入 main memory,这既限制了 transaction 的最大 working set,也避免了失败时再从主内存恢复。
当 LT 访问一个尚未位于 transaction cache 的 address 时,processor 会发出类似普通 read 的 T_READ bus request;区别在于,如果该 Cache line 正被另一个 processor 的 active transaction 使用,T_READ 会直接失败,不传输数据,当前 transaction 被标记为 failed,load 得到的值也可能是 undefined。因此,transaction 中读取的值在使用前必须通过 VALIDATE 检查。LTX 与之类似,但发出的是 T_RFO,要求独占 Cache line;如果本地已经以 M 或 E 持有该 line,就不需要再次发出请求。
ST 会先在本地 transaction cache 中取得独占副本,再保存旧值并写入新值:旧值成为 XCOMMIT,新值成为 XABORT。如果 transaction 已经 abort,或者隐含的 LTX 失败,就不会写入任何内容。VALIDATE 和 COMMIT 本身不会自动产生 bus operation;abort 时只需把 XABORT slot 标记为空、把 XCOMMIT slot 变回 NORMAL,commit 成功时则反过来处理。这些都是 transaction cache 内部很快的状态操作,不需要向其他 processor 发送显式通知。
因此,transaction operation 只会在开始 transaction,或向仍然成功的 transaction 加入一条尚未缓存的 Cache line 时产生 bus traffic。失败 transaction 的后续 operation 不会继续制造 bus request。若 transaction cache 足够容纳 working set,反复操作同一个 memory location 时,访问可以一直命中 transaction cache,速度接近 L1d;而普通 atomic operation 可能每轮都要进行一次或多次主内存级别的 ownership transfer。
从 LL/SC 的实现可以理解这种机制。LL 把 memory location 的 value 读入 register,同时把对应 Cache line 装入 L1d;之后的 SC 只有在该 value 没有被破坏时才能成功。如果另一个 processor 修改了该 location,根据 MESI protocol,第一个 processor 的 L1d copy 必须被撤销;当它执行 SC 时,就能发现这条 line 已经不再处于预期状态。context switch、同一 processor 上的其他修改,以及写操作后 Cache line 被重新加载等边界情况,还需要额外的状态位、flush policy 或为 LL/SC 保留的 Cache line,但总体而言,这种能力可以复用 Cache coherency 的基础设施。
transaction 中至少需要区分三种 memory operation:普通 read;之后会被写入的 read(需要先取得 exclusive ownership);以及 write。除此之外还需要 COMMIT、ABORT 和用于检查 transaction 是否仍然有效的 VALIDATE。普通 read 可以从 MESI 的 E 或 S state 得到满足,而第二种 read 必须取得 E state,因为后续 write 需要保证其他 processor 不会同时使用旧副本。
这意味着多个 thread 同时尝试使用相同内存时,不会像普通 atomic operation 那样不断造成 Cache line ping-pong。失败 transaction 的 VALIDATE 和 COMMIT 只需清理或恢复 transaction cache 中的状态位,不必向其他 processor 发送显式通知。
这套设计并不是基于某一款已经存在的硬件,而是根据早期 transactional memory 设计和 Cache coherency protocol 推导出的实现模型。transaction cache 可能只有 16 个 entry,甚至更少;transaction 能覆盖的 operation 数量因此受硬件上限约束。实现也可能支持多个同时活跃的 transaction,但需要相应增加 slot 数量,复杂度和硬件成本都会上升。
上面的 T_READ、T_RFO 和 transaction cache 状态共同构成一种可能的 bus protocol。transaction operation 只会在开始 transaction,或向仍然成功的 transaction 加入一条尚未缓存的 Cache line 时产生 bus traffic;VALIDATE 和 COMMIT 本身只改变本地状态,不需要显式 bus notification。
8.2.5 Other Considerations
transaction 也有边界:thread 被 deschedule、收到 signal、执行 system call 或发生 ring level change 时,transaction 可能被 abort。I/O 等不可回滚的副作用不能放入 transaction。由于 transaction cache 也按 Cache line 工作,transaction data 与 non-transactional data 共用一条 line 会造成问题;普通访问可能把 line 从 transaction cache 中移走并 abort transaction。因此,未来 Cache line alignment 不仅是性能问题,也可能关系到正确性。不同 transaction 使用的数据也应尽量放在不同 Cache line 中。
这也是 transactional memory 与今天的 atomic operation 之间的重要区别。若多个 thread 使用彼此独立的 memory,传统上为了安全而加入的 atomic operation 可能会无谓地发出昂贵的 RFO;transaction 只在确实发生跨 CPU 的并发或连续冲突时才付出这项成本。但如果 transaction 与普通访问共享一条 Cache line,普通访问可能把该 line 从 transaction cache 移走并立即 abort transaction。实现未来或许会采用更精细的 tracking,避免这种情况,但那就不能只依靠 MESI state,硬件复杂度会进一步增加。
这种机制可以让程序员避免为每个细粒度字段设计锁,但它不是魔法。transaction 覆盖的数据越多,冲突和 abort 的机会越大;transaction 持续时间越长,硬件需要追踪的 read/write set 越大;遇到 I/O、不可回滚的副作用或系统中断时,也可能无法直接放在 transaction 内。
transactional memory 最适合短小、冲突较少、可重试的 critical section。高冲突 workload 仍需要分片、减少共享写入或采用更合适的数据结构。
8.3 Increasing Latency
memory technology 的 latency 几乎肯定会继续上升。DDR3 的 latency 可能高于 DDR2;如果 FB-DRAM module 级联,request 和 result 经过多个 module 也会增加 latency。
NUMA 的普及是另一个来源。多个 processor 的 AMD Opteron 是 NUMA machine:每个 CPU 有自己的 memory controller 和 local memory,访问其他 CPU 的 memory 必须经过 HyperTransport。Intel 的 CSI 也采取类似方式。即使每个 socket 的 core 数量增加,多 socket motherboard 仍然需要维持多个高速 Ethernet port 等设备的 bandwidth。
第三个来源是 co-processor。Intel Geneseo、AMD Torrenza 允许第三方硬件更靠近 CPU 集成到 motherboard,而不是通过 PCIe card 连接,因此能够获得更多 bandwidth。IBM Cell 则在 PowerPC core 之外集成 8 个 Synergistic Processing Unit(SPU),主要用于 floating-point computation。
co-processor 和 SPU 的共同点是,它们的 memory logic 往往比通用 processor 更慢,部分原因是它们省略了复杂的 Cache handling、prefetching 和 Cache coherency。Cell 的理论峰值约为 210 GFLOPS,而高端 CPU 约为 50–60 GFLOPS;当时的 GPU 已超过 500 GFLOPS。高性能程序会越来越依赖这些 co-processor,因此 prefetching 会变得更加重要,甚至对 co-processor 来说是绝对必要的。CPU 也需要通过高效使用 prefetch instruction,持续让 FSB 保持忙碌,而不是成批堆积 request。
指针追逐、依赖链和串行算法难以隐藏 latency,因为下一次地址要等上一次 load 返回后才能计算。数组扫描、批量查询和适度的 software prefetch 更容易提供并行 memory operation。优化目标不是盲目增加并发,而是打断不必要的依赖链并保持足够的 memory-level parallelism。
8.4 Vector Operations
当时 mainstream processor 的 multimedia extension 只提供了有限的 vector operation。与 scalar operation 相比,四个 float 或两个 double 同时计算已经是进步,但距离 Cray-1 等 vector computer 或 IBM 3090 的 vector unit 仍然很远。由于单条 instruction 能处理的 element 数量有限,外围 loop 必须执行更多次;第 9.1 节的矩阵乘法示例中,每条 Cache line 就需要 SM 次迭代。
更宽的 vector register 可以减少 loop iteration。这不仅能减少 instruction decode 等开销,也会改善 memory behavior:一条 instruction 一次 load/store 更多数据时,processor 能更清楚地了解程序的 memory use,不必从许多独立 instruction 的行为中拼出同样的信息。若 vector register 足够宽,可以容纳一条或多条 Cache line,那么 non-temporal load/store 也更有用;对只有 16 byte 的 SSE load 来说,uncached load 可能迫使之后的访问再次从 memory 读取同一 Cache line,但对更宽的 vector 则不一定如此。
大 vector register 不一定会增加 instruction latency。vector unit 不必等所有数据读取完才开始计算;如果能识别代码流,vector 中已经到达的部分可以先执行。例如,vector register 正在加载、随后所有 element 都要乘以同一个 scalar 时,乘法可以在第一部分数据到达后立即开始。这说明 vector register 理论上可以变得非常宽,但通用 multi-process、多-thread OS 需要保存和恢复 register,context switch cost 会限制它的实际宽度。
更宽的 vector 还会暴露非连续内存访问问题:matrix 可能是 sparse 的,也可能按 column 而不是 row 访问。旧式 vector unit 通常提供两种方式:使用 striding,指定相邻 vector element 之间的固定间隔,这样可以一条 instruction 读取 matrix 的一列;或者使用 indirection,传入包含 address 或 offset 的数组,从而产生任意访问模式。今天的 multimedia instruction 通常做不到这一点,只能逐个 load 再拼成 vector register。
未来 mainstream processor 是否会重新提供真正的 vector operation 尚不确定,也可能由 co-processor 承担。但如果这类能力出现,代码就应当从现在开始按可向量化的方式组织:将 vectorizable code 封装为可替换模块,并提供足够通用的 interface。例如,interface 应支持对整个 matrix 做加法,而不是只能对 row、column 或更小的 element group 操作。building block 越大,使用 vector operation 的机会越多。
vector operation 也有现实代价。更大的 register set 会增加 context switch 时间;很长的 vector instruction 还会延迟 interrupt 响应,因为 processor 必须在中途停止并且能够恢复执行。若 instruction 不可 restart,就很难接受这种延迟。另一些 processor,特别是部分 RISC processor,对 memory alignment 有严格要求,因而从 multimedia instruction 扩展到完整 vector operation 并不简单。striding 和 indirection 带来的潜在收益很大,因此仍然值得期待。
vectorization 不会消除 memory bottleneck。如果数据无法从 Cache 或 memory bus 足够快地供给 vector unit,计算单元会等待;如果算法包含大量分支、随机访问或指针跳转,自动 vectorization 也可能失败。因此,vector operation 应与 blocking、data layout、prefetch 和 bandwidth 测量一起使用。
小结
未来处理器会更依赖并行性来隐藏 latency。atomic operation、transactional memory 和 vector operation 都只是工具,最终收益仍取决于共享状态、数据布局、访问依赖和冲突概率。程序员需要设计能暴露独立工作的数据结构,而不是只等待硬件自动优化。
参考资料
- Memory part 8: Future technologies
- LWN.net FAQ:文章内容许可
- Creative Commons BY-SA 4.0
- 本文作者:Ulrich Drepper;中文翻译:ChatGPT;根据 CC BY-SA 4.0 发布。
评论 (0)