SC.W

RISC-V SC.W 指令详解

指令手册R-type

在预留有效时原子条件存储32位字;成功写内存并令 rd=0,失败不写内存并令 rd 为非零

指令语法

sc.w rd, rs2, (rs1)
操作数说明
目标寄存器 rd:存放运算结果的通用寄存器。
源寄存器 rs1:第一个操作数寄存器。
源寄存器 rs2:第二个操作数寄存器。
AZalrsc原子操作

指令行为说明

SC.W 将 rs2 的低 32 位作为候选写入值,只有当最近的 LR 建立的预留仍有效且预留集包含目标字节时才写入 rs1 指向的内存。成功时 rd 写入 0;失败时不写内存,rd 写入非零失败码。无论成功或失败,SC.W 都会使当前 hart 的预留失效。

SC.W 原子指令解析与执行动画

展示 A-extension word 原子指令的字段解析、aq/rl 排序位、预留与权限检查和 条件存储 状态更新。

rd
rs2
rs1
sc.w
,
,(
)
执行环境

该教学开关只选择 SC 的成功或失败结果;成功仍取决于最近 LR 的预留及其他架构条件,失败码只保证为非零。

31..27
26
25
24..20
19..15
14..12
11..7
6..0
00011
funct5
0
aq
1
rl
01011
rs2
01010
rs1
010
funct3
00110
rd
0101111
opcode
原子数据路径
instruction
0x1AB5232F
opcode
0101111 -> AMO
funct3
010 -> word width
funct5
00011 -> SC.W
aq / rl
0/1 -> release
rd / rs2 / rs1
t1(x6) / a1(x11)=0x00000009 / a0(x10)=0x00001000
reservation / permissions
check the most recent LR reservation and store permissions for 0x00001000; no old-memory value is architecturally exposed
condition
SC succeeds -> store 0x00000009
rd / memory / reservation
t1(x6) = 0x00000000; mem[0x00001000] = 0x00000009; reservation invalidated
当前步骤

概念步骤:拿到 32-bit 原子指令编码

A 扩展 word 原子指令使用 32-bit 编码;动画先展示字段切分。

encoding: 0x1AB5232F
syntax : sc.w t1(x6), a1(x11), (a0(x10))
result : t1(x6) = 0x00000000; mem[0x00001000] = 0x00000009; reservation invalidated
32-bit word 结果视图
31
30
29
28
27
26
25
24
23
22
21
20
19
18
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
1
write word
write
write
write
write
write
write
write
write
write
write
write
write
write
write
write
write
write
write
write
write
write
write
write
write
write
write
write
write
write
write
write
write
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

该动画展示 ISA 可见的原子读改写、比较并交换、LR/SC 预留状态和内存排序位,不表示任何特定 CPU 的缓存一致性实现、流水线或时序。

快速理解与检索要点

SC.W 是 LR/SC 序列的判定点:它不是无条件 store。成功时写内存并把 0 写入 rd;失败时内存保持不变,并把非零失败码写入 rd。

funct5=00011、funct3=010、opcode=0101111 识别 SC.W;rd 是状态结果寄存器,不是被存入内存的数据。
rs2 提供写入内存的 32 位候选数据;rd 接收 0 或非零的成功/失败状态。
SC.W 失败时不会写内存;成功和失败都会使当前 hart 的预留失效。
官方语义只要求失败码非零;可移植软件不应依赖具体非零数值。

常见使用场景

原子与同步

结合 «sc.w.rl t0, a1, (a0) # try store a1 to *a0 with release ordering, t0=0 on success» 等实际代码理解该场景。

使用前检查清单

语法检查
  • 确认 rd、rs1、rs2(及 rs3)是合法 GPR。
  • 确认 funct3 与 funct7 字段编码正确。
语义检查
  • 确认结果是否会影响后续分支或地址计算。
  • 确认 rd 寄存器不会被其他指令覆盖。

容易混淆 / 常见误区

可能伪失败(spurious failure),需循环重试
失败码应仅检查非零,不要依赖具体值
若要依赖受限 LR/SC 循环的最终前进保证,循环代码必须满足其约束
地址必须4字节对齐

常见问题

SC.W 成功时 rd 为什么是 0?

SC.W 的 rd 是状态结果寄存器。官方语义定义成功写 0,失败写非零值,软件据此决定是否退出或重试 LR/SC 循环。

SC.W 失败时会改内存吗?

不会。SC.W 失败时不执行内存写入,只把非零失败码写入 rd,并使当前预留失效。