atomic 原子操作

前言

修改一个变量会经过读、修改、写的操作序列。但有时该操作序列在执行完毕前会被其他任务或事件打断。
比如在多CPU体系结构中,运行在两个CPU上的两个内核控制路径同时并行执行上面操作序列,有可能发生下面的场景:
在这里插入图片描述
在单CPU上也会由于有多个内核控制路径的交错而导致这种情况:
在这里插入图片描述

atomic_t定义

linux专门定义了一种只进行原子操作的类型atomic_t

166 typedef struct {
167     int counter;
168 } atomic_t;

具体的接口API函数整理如下:
在这里插入图片描述

内核中的实现

armv7的实现

 36 #define ATOMIC_OP(op, c_op, asm_op)                 \
 37 static inline void arch_atomic_##op(int i, atomic_t *v)         \
 38 {                                   \
 39     unsigned long tmp;                      \
 40     int result;                         \
 41                                     \
 42     prefetchw(&v->counter);                     \
 43     __asm__ __volatile__("@ atomic_" #op "\n"           \
 44 "1: ldrex   %0, [%3]\n"                     \
 45 "   " #asm_op " %0, %0, %4\n"                   \
 46 "   strex   %1, %0, [%3]\n"                     \
 47 "   teq %1, #0\n"                       \
 48 "   bne 1b"                         \
 49     : "=&r" (result), "=&r" (tmp), "+Qo" (v->counter)       \
 50     : "r" (&v->counter), "Ir" (i)                   \
 51     : "cc");                            \
 52 } 

ARMv6之前的CPU并不支持SMP,原子操作就是通过关闭CPU中断来完成的。ARMv6之后的ARM架构都是支持SMP的。ARM V7之后的LDREX、STREX指令可以解决这个问题。它保证2个读-修改-写序列有交叉的时候,只有1个可以写成功,另外一个则再次尝试。

汇编嵌入c代码的语法:嵌入式汇编的语法格式是:asm(code : output operand list : input operand list : clobber list)。output operand list 和 input operand list是c代码和嵌入式汇编代码的接口,clobber list描述了汇编代码对寄存器的修改情况。大家对着上面的code就可以分开各段内容了。@符号标识该行是注释。这里的__volatile__主要是用来防止编译器优化的。

我们先看ldrex和strex这两条汇编指令的使用方法。ldr和str这两条指令大家都是非常的熟悉了,后缀的ex表示Exclusive,是ARMv7提供的为了实现同步的汇编指令。
STREX指令,除了把寄存器的值写入一个地址以外,还可以返回这次写是否成功.

STREXEQ r0, r1, [LockAddr]
上述指令把r1写入地址LockAddr,如果写入成功,则r0=0,否则r0不等于0。如果r0不等于0,证明写入失败,那么需要重新来ldrex,重新来修改和写。官方解释如下:

The STREX instruction performs a conditionalstore of a word to memory. If the exclusive monitor(s) permit thestore, the operation updates the memory location and returns the value0 in the destination register, indicating that the operation succeeded.If the exclusive monitor(s) do not permit the store, the operationdoes not update the memory location and returns the value 1 in thedestination register. This makes it possible to implement conditionalexecution paths based on the success or failure of the memory operation.For example, STREX R2, R1, [R0] performs a Store-Exclusiveoperation to the address in R0, conditionallystoring the value from R1 and indicating successor failure in R2.

当两个LDREX,STREX序列交错的时候,谁先STREX,谁成功,第2个STREX失败,重新来LDREX。

armv8的实现

在ARMv8 架构下对应的是LDXR (load exclusive register 和STXR (store exclusiveregister)及其变种指令。

 32 /*
 33  * AArch64 UP and SMP safe atomic ops.  We use load exclusive and
 34  * store exclusive to ensure that these are atomic.  We may loop
 35  * to ensure that the update happens.
 36  */
 37 
 38 #define ATOMIC_OP(op, asm_op, constraint)               \
 39 static inline void                          \
 40 __ll_sc_atomic_##op(int i, atomic_t *v)                 \
 41 {                                   \
 42     unsigned long tmp;                      \
 43     int result;                         \
 44                                     \
 45     asm volatile("// atomic_" #op "\n"              \
 46     __LL_SC_FALLBACK(                       \
 47 "   prfm    pstl1strm, %2\n"                    \
 48 "1: ldxr    %w0, %2\n"                      \
 49 "   " #asm_op " %w0, %w0, %w3\n"                \
 50 "   stxr    %w1, %w0, %2\n"                     \
 51 "   cbnz    %w1, 1b\n")                     \
 52     : "=&r" (result), "=&r" (tmp), "+Q" (v->counter)        \
 53     : __stringify(constraint) "r" (i));             \
 54 }

LDXR/ STXR和一般的LDR/STR的区别就在于LDXR除了向memory发起load请求外,还会记录该memory所在地址的状态(一般ARM处理器在同一个cache line大小,也就是64 byte的地址范围内共用一个状态),那就是Open和Exclusive。
我们可以认为一个叫做exclusive monitor的模块来记录。根据CPU访问内存地址的属性(在页表里面定义),这个组件可能在处理器 L1 memory system, 处理器cluster level, 或者总线,DDR controller上。

下面是Arm ARM架构 [1] 文档定义的状态转换图

在这里插入图片描述
实例说明:
1)thread1发起了一个LDXR的读操作,记录当前的状态为Exclusive

2)thread2发起了一个LDXR的读操作,当前的状态为Exclusive,保持不变

3)thread2发起了一个STXR的写操作,状态从Exclusive变成Open,同时数据回写到DDR

4)thread1发起了一个STXR的写操作,因为当前的exclusive monitor状态为Open,写失败(假如程序这时用STR操作来写,写会成功,但是这个不是原子操作函数的本意,属于编程错误)
在这里插入图片描述
假如有多个CPU,同时对一个处于Exclusive的memory region来进行写,CPU有内部逻辑来保证串行化。

Monitor的状态除了STXR会清掉,从Exclusive变成Open之外,还有其他因素也可以导致monitor的状态被清掉,所以软件在实现spinlock的时候,一般会用一个loop循环来实现,所谓“spin”。

Exclusive monitor实现所处的位置

根据LDXR/STXR 访问的memory的属性,需要的monitor可以在CPU内部,总线,也可以DDR controller(例如ARM DMC-400 [2]在每个memory interface 支持8个 exclusive access monitors)。

一般Memory属性配置为 normal cacheable, shareable,这种情形下,CPU发起的exclusive access会终结在CPU cluster内部,对外的表现,比如cacheline fill和line eviction和正常的读写操作产生的外部行为是一样的。具体实现上,需要结合local monitor的状态管理和cache coherency 的处理逻辑,比如MESI/MOESI的cacheline的状态管理来。

为方便大家理解,下面划出一个monitor在一个假象SOC里面的逻辑图(在一个真实芯片里面,不是所有monitor都会实现,需要和SOC vendor确认)
在这里插入图片描述

External exclusive monitor

对于normal non-cacheable,或者Device类型的memory属性的memory地址,cpu会发出exclusive access的AXI 访问(AxLOCK signals )到总线上去,总线需要有对应的External exclusive monitor支持,否则会返回错误。例如, 假如某个SOC不支持外部global exclusivemonitor,软件把MMU disabled的情况下,启动SMP Linux,系统是没法启动起来的,在spinlock处会挂掉。
AMBA AXI/ACE 规范:

The exclusive access mechanism can provide semaphore-type operations without requiring the bus to remain dedicated to a particular master for the duration of the operation. This means the semaphore-type operations do not impact either the bus access latency or the maximum achievable bandwidth.

The AxLOCK signals select exclusive access, and the RRESP and BRESP signals indicate the success or failure of the exclusive access read or write respectively.

The slave requires additional logic to support exclusive access. The AXI protocol provides a mechanism to indicate when a master attempts an exclusive access to a slave that does not support it. 

Atomic指令的支持

处理器,支持cache coherency协议的总线,或者DDR controller可以增加了一些简单的运算,比如,在读写指令产生的memory访问的过程中一并把简单的运算给做了。

AMBA 5 [3] 里面增加了对Atomic transactions的支持:

AMBA 5 introduces Atomic transactions, which perform more than just a single access, and have some form of operation that is associated with the transaction.

Atomic transactions are suited to situations where the data is located a significant distance from the agent that must perform the operation. Previously, performing an operation that is atomically required pulling the data towards the agent, performing the operation, and then pushing the result back.

Atomic transactions enable sending the operation to the data, permitting the operation to be performed closer to where the data is located.

The key advantage of this approach is that it reduces the amount of time during which the data must be made inaccessible to other agents in the system

支持4种Atomic transaction:AtomicStore ,AtomicLoad,AtomicSwap 和AtomicCompare

QA

(1) Local monitor和Global monitor的使用场景

  • Local monitor适用于访问的memory属为normal cacheable, shareable或者non-shareable的情况.

  • Global monitor ,准确来说,external global exclusive monitor (处理器之外,在外部总线上)用于normal noncacheable或者device memory类型。比如可以用于一个Cortex-A处理器和一个Cortex-M 处理器(没有内部cache)之间的同步。

(2) 多CPU下,多个LDREX,和STREX的排他性实现

  • 各个处理器和总线的实现不同,可以从软件上理解为和data coherency实现相结合,比如M(O)ESI协议[5],这是一种 Invalidate-based cache coherence protocol, 其中的key point就是当多个CPU在读同一个cacheline的时候,在每个CPU的内部cache里面都有cacheline allocation, cacheline的状态会变成Shared;但是当某个CPU做写的时候,会把其它CPU里面的cacheline数据给invalidate掉,然后写自己的cacheline数据,同时设置为Modified状态,从而保证了数据的一致性。

  • LDREX,本质上是一个LDR,CPU1做cache linefill,然后设置该line为E状态(Exclusive),额外的一个作用是设置exclusive monitor的状态为Exclusive;其他cpu做LDREX,该line也会分配到它的内部cache里面,状态都设置为Shared ,也会设置本CPU的monitor的状态。当一个CPU 做STREX时候,这个Write操作会把其它CPU里面的cacheline数据给invalidate掉。同时也把monitor的状态清掉,从Exclusive变成Open的状态,这个MESI协议导致cachline的状态在多CPU的变化,是执行Write操作一次性改变的。这样在保证数据一致性的同时,也保证了montitor的状态更新同步改变。

(3) 比如举一个多核的场景,一个核ldrex了,如果本核的local monitor会发生什么,外部的global monitor发生什么,开不开mmu,cache不cache,区别和影响是什么。

Ldrex/strex本来就是针对多核的场景来设计的,local monitor的状态发生改变,不会影响外部的global monitor状态。但是external global monitor的状态发生改变,可以告诉处理器,把local monitor的状态清掉。

Data coherency是通过硬件来支持的。对于normal cacheable类型的memory, MMU和DCache必须使能,否则CPU会把exclusive类型的数据请求发出处理器,这时需要外部monitor的支持。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值