← Documents Documentation/memory-barriers.txt GitHub 원문 ↗

Linux 6.18.37 · Core memory ordering

Linux Kernel Memory Barriers

Compiler와 CPU의 memory ordering, explicit·implicit barrier, dependency, multicopy atomicity, cache coherence를 설명하는 Linux kernel의 핵심 안내서입니다.

Source pathDocumentation/memory-barriers.txt
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약·해설

memory-barriers.txt:1-3016

이 문서는 명세 자체가 아니라 Linux가 제공하는 barrier의 최소 보장과 올바른 사용법을 설명하는 안내서입니다. 의문이 있으면 tools/memory-model/의 formal model과 architecture 문서를 함께 확인해야 합니다.

핵심은 한 CPU의 program order가 compiler, cache, interconnect, speculative execution을 거쳐 다른 CPU에 같은 순서로 보인다고 가정할 수 없다는 점입니다. 필요한 ordering은 barrier를 짝지어 명시해야 합니다.

smp_mb(), smp_rmb(), smp_wmb(), acquire·release, lock, interrupt, sleep·wake-up primitive는 서로 다른 보장을 제공합니다. READ_ONCE(), WRITE_ONCE(), data·address·control dependency의 범위도 구분해야 합니다.

CPU, memory, device가 공유하는 추상 메모리 시스템
CPU 1MemoryCPU 2
CPU 1DeviceCPU 2
MemoryDevice

CPU와 장치는 서로 직접 값을 전달하지 않고 memory system과 interconnect를 거쳐 load/store 결과를 관찰합니다.

두 CPU의 store/load가 관찰될 수 있는 순서
CPU 1CPU 2관찰 결과
01 STORE A=3LOAD Bx=2 또는 4
02 STORE B=4LOAD Ay=1 또는 3
03 store 순서 완화load 순서 완화네 가지 x/y 조합 가능

프로그램 순서만으로 다른 CPU가 두 store를 같은 순서로 관찰한다고 보장할 수 없습니다.

Write barrier가 store 전달 순서를 나누는 지점
CPU 1 실행전파 대기열다른 CPU에 보이는 순서
01 STORE A/B/Cbarrier 앞 그룹그룹 내부 순서는 완화 가능
02 WRITE BARRIER경계앞 그룹 완료 후 뒤 그룹 전달
03 STORE D/Ebarrier 뒤 그룹A/B/C보다 뒤에 관찰

write barrier는 앞쪽 store의 내부 순서를 정하지 않지만 뒤쪽 store보다 먼저 전파되게 합니다.

Address dependency barrier가 없을 때
CPU 1메모리 관찰CPU 2
01 STORE B=2B의 새 값과 C의 옛 주소가 따로 도착LOAD C -> &Y
02 STORE C=&B전달 순서 불일치LOAD *C -> Y의 값 8
03 나중에 B=2 도착의존 load가 잘못된 대상을 읽음

주소를 제공하는 load와 그 주소를 사용하는 load 사이에 순서가 없으면 새 pointer와 이전 대상 값이 조합될 수 있습니다.

Address dependency barrier가 있을 때
CPU 1CPU 2 orderingCPU 2 결과
01 STORE B=2LOAD C -> &B주소 획득
02 STORE C=&BADDRESS DEPENDENCY BARRIER의존 load 대기
03 LOAD *CB=2 관찰

pointer를 읽은 뒤 barrier를 통과해야 해당 pointer가 가리키는 값의 load가 앞서 실행되지 않습니다.

Read barrier가 없을 때 load 관찰
CPU 1 storeCPU 2 관찰 대기열CPU 2 load
01 STORE A=1A의 옛 값 0LOAD A -> 0
02 WRITE BARRIERB의 새 값 2LOAD B -> 2
03 STORE B=2A의 새 값 1은 늦게 도착서로 다른 시점 관찰

상대 CPU의 write barrier만으로 현재 CPU의 load 순서가 고정되지는 않습니다.

Read barrier로 load 순서를 맞춘 경우
CPU 1CPU 2보장
01 STORE A=1LOAD B -> 2B의 새 값을 관찰
02 WRITE BARRIERREAD BARRIER앞 load 완료
03 STORE B=2LOAD A -> 1A의 앞선 store도 관찰

B=2를 읽은 뒤 read barrier를 지나 A를 읽으면 write barrier 앞의 A=1이 보이도록 순서를 연결합니다.

같은 주소를 두 번 읽을 때 첫 load의 한계
CPU 1CPU 2 첫 loadCPU 2 두 번째 load
01 STORE A=1A -> 0 가능
02 WRITE BARRIERLOAD B -> 2READ BARRIER
03 STORE B=2A -> 1 보장

barrier 뒤의 두 번째 A load에는 보장이 적용되지만 앞의 첫 번째 A load 결과까지 소급해 바꾸지는 않습니다.

A의 새 값이 이미 도착한 경우
메모리 전파CPU 2 첫 loadCPU 2 두 번째 load
01 A=1 도착A -> 1
02 B=2 도착LOAD B -> 2READ BARRIER
03 A -> 1 유지

첫 load가 이미 새 값을 읽었다면 barrier 뒤의 두 번째 load도 그보다 오래된 값으로 되돌아가지 않습니다.

Barrier가 없을 때 speculative load
CPU 2 명령추측 실행완료
01 LOAD BB -> 2
02 DIVIDELOAD A를 미리 실행A -> 0을 임시 보관
03 DIVIDE추측값 재사용LOAD A 즉시 완료

긴 연산 동안 뒤의 load가 먼저 실행되어 오래된 cache 값을 잡아둘 수 있습니다.

Read barrier가 speculative value를 검증하는 경우
CPU 2검증결과
01 LOAD A 추측 -> 0값과 coherence 상태 기록임시값
02 READ BARRIER변경 여부 검사변경 없음
03 LOAD A추측값 사용 가능A -> 0

barrier는 추측 자체를 반드시 막지 않고 cache line이 바뀌지 않았는지 검증한 뒤 값을 사용하게 합니다.

추측 뒤 cache line이 무효화된 경우
CPU 2Coherence최종 load
01 LOAD A 추측 -> 0다른 CPU의 A=1 도착추측값 무효
02 READ BARRIERinvalidation 확인다시 읽기
03 LOAD A새 cache line 사용A -> 1

다른 CPU의 update가 도착하면 speculative value를 버리고 최신 값을 다시 읽습니다.

Sleeper와 waker 사이의 암시적 barrier
CPU 1 SleeperCPU 2 Waker
01 set_current_state()STORE event_indicated
02 smp_store_mb()wake_up()
03 STORE current->state조건부 LOAD task->state
04 LOAD event_indicatedSTORE task->state = RUNNING

task state store와 wake-up 관찰 사이의 ordering을 set_current_state()와 wake_up() 경로의 barrier가 연결합니다.

CPU cache와 memory coherence 경로
CPU Core 0Memory Access Queue 0CPU Cache 0Cache CoherencyMemory
CPU Core 1Memory Access Queue 1CPU Cache 1Cache CoherencyDevice

CPU core의 요청은 access queue와 private cache를 거쳐 coherence mechanism에 합류한 뒤 memory 또는 device에 도달합니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 ============================
2 LINUX KERNEL MEMORY BARRIERS
3 ============================
4
5 By: David Howells <[email protected]>
6 Paul E. McKenney <[email protected]>
7 Will Deacon <[email protected]>
8 Peter Zijlstra <[email protected]>
9
10 ==========
11 DISCLAIMER
12 ==========
13
14 This document is not a specification; it is intentionally (for the sake of
15 brevity) and unintentionally (due to being human) incomplete. This document is
16 meant as a guide to using the various memory barriers provided by Linux, but
17 in case of any doubt (and there are many) please ask. Some doubts may be
18 resolved by referring to the formal memory consistency model and related
19 documentation at tools/memory-model/. Nevertheless, even this memory
20 model should be viewed as the collective opinion of its maintainers rather
21 than as an infallible oracle.
22
23 To repeat, this document is not a specification of what Linux expects from
24 hardware.
25
26 The purpose of this document is twofold:
27
28 (1) to specify the minimum functionality that one can rely on for any
29 particular barrier, and
30
31 (2) to provide a guide as to how to use the barriers that are available.
32
33 Note that an architecture can provide more than the minimum requirement
34 for any particular barrier, but if the architecture provides less than
35 that, that architecture is incorrect.
36
37 Note also that it is possible that a barrier may be a no-op for an
38 architecture because the way that arch works renders an explicit barrier
39 unnecessary in that case.
40
41
42 ========
43 CONTENTS
44 ========
45
46 (*) Abstract memory access model.
47
48 - Device operations.
49 - Guarantees.
50
51 (*) What are memory barriers?
52
53 - Varieties of memory barrier.
54 - What may not be assumed about memory barriers?
55 - Address-dependency barriers (historical).
56 - Control dependencies.
57 - SMP barrier pairing.
58 - Examples of memory barrier sequences.
59 - Read memory barriers vs load speculation.
60 - Multicopy atomicity.
61
62 (*) Explicit kernel barriers.
63
64 - Compiler barrier.
65 - CPU memory barriers.
66
67 (*) Implicit kernel memory barriers.
68
69 - Lock acquisition functions.
70 - Interrupt disabling functions.
71 - Sleep and wake-up functions.
72 - Miscellaneous functions.
73
74 (*) Inter-CPU acquiring barrier effects.
75
76 - Acquires vs memory accesses.
77
78 (*) Where are memory barriers needed?
79
80 - Interprocessor interaction.
81 - Atomic operations.
82 - Accessing devices.
83 - Interrupts.
84
85 (*) Kernel I/O barrier effects.
86
87 (*) Assumed minimum execution ordering model.
88
89 (*) The effects of the cpu cache.
90
91 - Cache coherency vs DMA.
92 - Cache coherency vs MMIO.
93
94 (*) The things CPUs get up to.
95
96 - And then there's the Alpha.
97 - Virtual Machine Guests.
98
99 (*) Example uses.
100
101 - Circular buffers.
102
103 (*) References.
104
105
106 ============================
107 ABSTRACT MEMORY ACCESS MODEL
108 ============================
109
110 Consider the following abstract model of the system:
111
112 : :
113 : :
114 : :
115 +-------+ : +--------+ : +-------+
116 | | : | | : | |
117 | | : | | : | |
118 | CPU 1 |<----->| Memory |<----->| CPU 2 |
119 | | : | | : | |
120 | | : | | : | |
121 +-------+ : +--------+ : +-------+
122 ^ : ^ : ^
123 | : | : |
124 | : | : |
125 | : v : |
126 | : +--------+ : |
127 | : | | : |
128 | : | | : |
129 +---------->| Device |<----------+
130 : | | :
131 : | | :
132 : +--------+ :
133 : :
134
135 Each CPU executes a program that generates memory access operations. In the
136 abstract CPU, memory operation ordering is very relaxed, and a CPU may actually
137 perform the memory operations in any order it likes, provided program causality
138 appears to be maintained. Similarly, the compiler may also arrange the
139 instructions it emits in any order it likes, provided it doesn't affect the
140 apparent operation of the program.
141
142 So in the above diagram, the effects of the memory operations performed by a
143 CPU are perceived by the rest of the system as the operations cross the
144 interface between the CPU and rest of the system (the dotted lines).
145
146
147 For example, consider the following sequence of events:
148
149 CPU 1 CPU 2
150 =============== ===============
151 { A == 1; B == 2 }
152 A = 3; x = B;
153 B = 4; y = A;
154
155 The set of accesses as seen by the memory system in the middle can be arranged
156 in 24 different combinations:
157
158 STORE A=3, STORE B=4, y=LOAD A->3, x=LOAD B->4
159 STORE A=3, STORE B=4, x=LOAD B->4, y=LOAD A->3
160 STORE A=3, y=LOAD A->3, STORE B=4, x=LOAD B->4
161 STORE A=3, y=LOAD A->3, x=LOAD B->2, STORE B=4
162 STORE A=3, x=LOAD B->2, STORE B=4, y=LOAD A->3
163 STORE A=3, x=LOAD B->2, y=LOAD A->3, STORE B=4
164 STORE B=4, STORE A=3, y=LOAD A->3, x=LOAD B->4
165 STORE B=4, ...
166 ...
167
168 and can thus result in four different combinations of values:
169
170 x == 2, y == 1
171 x == 2, y == 3
172 x == 4, y == 1
173 x == 4, y == 3
174
175
176 Furthermore, the stores committed by a CPU to the memory system may not be
177 perceived by the loads made by another CPU in the same order as the stores were
178 committed.
179
180
181 As a further example, consider this sequence of events:
182
183 CPU 1 CPU 2
184 =============== ===============
185 { A == 1, B == 2, C == 3, P == &A, Q == &C }
186 B = 4; Q = P;
187 P = &B; D = *Q;
188
189 There is an obvious address dependency here, as the value loaded into D depends
190 on the address retrieved from P by CPU 2. At the end of the sequence, any of
191 the following results are possible:
192
193 (Q == &A) and (D == 1)
194 (Q == &B) and (D == 2)
195 (Q == &B) and (D == 4)
196
197 Note that CPU 2 will never try and load C into D because the CPU will load P
198 into Q before issuing the load of *Q.
199
200
201 DEVICE OPERATIONS
202 -----------------
203
204 Some devices present their control interfaces as collections of memory
205 locations, but the order in which the control registers are accessed is very
206 important. For instance, imagine an ethernet card with a set of internal
207 registers that are accessed through an address port register (A) and a data
208 port register (D). To read internal register 5, the following code might then
209 be used:
210
211 *A = 5;
212 x = *D;
213
214 but this might show up as either of the following two sequences:
215
216 STORE *A = 5, x = LOAD *D
217 x = LOAD *D, STORE *A = 5
218
219 the second of which will almost certainly result in a malfunction, since it set
220 the address _after_ attempting to read the register.
221
222
223 GUARANTEES
224 ----------
225
226 There are some minimal guarantees that may be expected of a CPU:
227
228 (*) On any given CPU, dependent memory accesses will be issued in order, with
229 respect to itself. This means that for:
230
231 Q = READ_ONCE(P); D = READ_ONCE(*Q);
232
233 the CPU will issue the following memory operations:
234
235 Q = LOAD P, D = LOAD *Q
236
237 and always in that order. However, on DEC Alpha, READ_ONCE() also
238 emits a memory-barrier instruction, so that a DEC Alpha CPU will
239 instead issue the following memory operations:
240
241 Q = LOAD P, MEMORY_BARRIER, D = LOAD *Q, MEMORY_BARRIER
242
243 Whether on DEC Alpha or not, the READ_ONCE() also prevents compiler
244 mischief.
245
246 (*) Overlapping loads and stores within a particular CPU will appear to be
247 ordered within that CPU. This means that for:
248
249 a = READ_ONCE(*X); WRITE_ONCE(*X, b);
250
251 the CPU will only issue the following sequence of memory operations:
252
253 a = LOAD *X, STORE *X = b
254
255 And for:
256
257 WRITE_ONCE(*X, c); d = READ_ONCE(*X);
258
259 the CPU will only issue:
260
261 STORE *X = c, d = LOAD *X
262
263 (Loads and stores overlap if they are targeted at overlapping pieces of
264 memory).
265
266 And there are a number of things that _must_ or _must_not_ be assumed:
267
268 (*) It _must_not_ be assumed that the compiler will do what you want
269 with memory references that are not protected by READ_ONCE() and
270 WRITE_ONCE(). Without them, the compiler is within its rights to
271 do all sorts of "creative" transformations, which are covered in
272 the COMPILER BARRIER section.
273
274 (*) It _must_not_ be assumed that independent loads and stores will be issued
275 in the order given. This means that for:
276
277 X = *A; Y = *B; *D = Z;
278
279 we may get any of the following sequences:
280
281 X = LOAD *A, Y = LOAD *B, STORE *D = Z
282 X = LOAD *A, STORE *D = Z, Y = LOAD *B
283 Y = LOAD *B, X = LOAD *A, STORE *D = Z
284 Y = LOAD *B, STORE *D = Z, X = LOAD *A
285 STORE *D = Z, X = LOAD *A, Y = LOAD *B
286 STORE *D = Z, Y = LOAD *B, X = LOAD *A
287
288 (*) It _must_ be assumed that overlapping memory accesses may be merged or
289 discarded. This means that for:
290
291 X = *A; Y = *(A + 4);
292
293 we may get any one of the following sequences:
294
295 X = LOAD *A; Y = LOAD *(A + 4);
296 Y = LOAD *(A + 4); X = LOAD *A;
297 {X, Y} = LOAD {*A, *(A + 4) };
298
299 And for:
300
301 *A = X; *(A + 4) = Y;
302
303 we may get any of:
304
305 STORE *A = X; STORE *(A + 4) = Y;
306 STORE *(A + 4) = Y; STORE *A = X;
307 STORE {*A, *(A + 4) } = {X, Y};
308
309 And there are anti-guarantees:
310
311 (*) These guarantees do not apply to bitfields, because compilers often
312 generate code to modify these using non-atomic read-modify-write
313 sequences. Do not attempt to use bitfields to synchronize parallel
314 algorithms.
315
316 (*) Even in cases where bitfields are protected by locks, all fields
317 in a given bitfield must be protected by one lock. If two fields
318 in a given bitfield are protected by different locks, the compiler's
319 non-atomic read-modify-write sequences can cause an update to one
320 field to corrupt the value of an adjacent field.
321
322 (*) These guarantees apply only to properly aligned and sized scalar
323 variables. "Properly sized" currently means variables that are
324 the same size as "char", "short", "int" and "long". "Properly
325 aligned" means the natural alignment, thus no constraints for
326 "char", two-byte alignment for "short", four-byte alignment for
327 "int", and either four-byte or eight-byte alignment for "long",
328 on 32-bit and 64-bit systems, respectively. Note that these
329 guarantees were introduced into the C11 standard, so beware when
330 using older pre-C11 compilers (for example, gcc 4.6). The portion
331 of the standard containing this guarantee is Section 3.14, which
332 defines "memory location" as follows:
333
334 memory location
335 either an object of scalar type, or a maximal sequence
336 of adjacent bit-fields all having nonzero width
337
338 NOTE 1: Two threads of execution can update and access
339 separate memory locations without interfering with
340 each other.
341
342 NOTE 2: A bit-field and an adjacent non-bit-field member
343 are in separate memory locations. The same applies
344 to two bit-fields, if one is declared inside a nested
345 structure declaration and the other is not, or if the two
346 are separated by a zero-length bit-field declaration,
347 or if they are separated by a non-bit-field member
348 declaration. It is not safe to concurrently update two
349 bit-fields in the same structure if all members declared
350 between them are also bit-fields, no matter what the
351 sizes of those intervening bit-fields happen to be.
352
353
354 =========================
355 WHAT ARE MEMORY BARRIERS?
356 =========================
357
358 As can be seen above, independent memory operations are effectively performed
359 in random order, but this can be a problem for CPU-CPU interaction and for I/O.
360 What is required is some way of intervening to instruct the compiler and the
361 CPU to restrict the order.
362
363 Memory barriers are such interventions. They impose a perceived partial
364 ordering over the memory operations on either side of the barrier.
365
366 Such enforcement is important because the CPUs and other devices in a system
367 can use a variety of tricks to improve performance, including reordering,
368 deferral and combination of memory operations; speculative loads; speculative
369 branch prediction and various types of caching. Memory barriers are used to
370 override or suppress these tricks, allowing the code to sanely control the
371 interaction of multiple CPUs and/or devices.
372
373
374 VARIETIES OF MEMORY BARRIER
375 ---------------------------
376
377 Memory barriers come in four basic varieties:
378
379 (1) Write (or store) memory barriers.
380
381 A write memory barrier gives a guarantee that all the STORE operations
382 specified before the barrier will appear to happen before all the STORE
383 operations specified after the barrier with respect to the other
384 components of the system.
385
386 A write barrier is a partial ordering on stores only; it is not required
387 to have any effect on loads.
388
389 A CPU can be viewed as committing a sequence of store operations to the
390 memory system as time progresses. All stores _before_ a write barrier
391 will occur _before_ all the stores after the write barrier.
392
393 [!] Note that write barriers should normally be paired with read or
394 address-dependency barriers; see the "SMP barrier pairing" subsection.
395
396
397 (2) Address-dependency barriers (historical).
398 [!] This section is marked as HISTORICAL: it covers the long-obsolete
399 smp_read_barrier_depends() macro, the semantics of which are now
400 implicit in all marked accesses. For more up-to-date information,
401 including how compiler transformations can sometimes break address
402 dependencies, see Documentation/RCU/rcu_dereference.rst.
403
404 An address-dependency barrier is a weaker form of read barrier. In the
405 case where two loads are performed such that the second depends on the
406 result of the first (eg: the first load retrieves the address to which
407 the second load will be directed), an address-dependency barrier would
408 be required to make sure that the target of the second load is updated
409 after the address obtained by the first load is accessed.
410
411 An address-dependency barrier is a partial ordering on interdependent
412 loads only; it is not required to have any effect on stores, independent
413 loads or overlapping loads.
414
415 As mentioned in (1), the other CPUs in the system can be viewed as
416 committing sequences of stores to the memory system that the CPU being
417 considered can then perceive. An address-dependency barrier issued by
418 the CPU under consideration guarantees that for any load preceding it,
419 if that load touches one of a sequence of stores from another CPU, then
420 by the time the barrier completes, the effects of all the stores prior to
421 that touched by the load will be perceptible to any loads issued after
422 the address-dependency barrier.
423
424 See the "Examples of memory barrier sequences" subsection for diagrams
425 showing the ordering constraints.
426
427 [!] Note that the first load really has to have an _address_ dependency and
428 not a control dependency. If the address for the second load is dependent
429 on the first load, but the dependency is through a conditional rather than
430 actually loading the address itself, then it's a _control_ dependency and
431 a full read barrier or better is required. See the "Control dependencies"
432 subsection for more information.
433
434 [!] Note that address-dependency barriers should normally be paired with
435 write barriers; see the "SMP barrier pairing" subsection.
436
437 [!] Kernel release v5.9 removed kernel APIs for explicit address-
438 dependency barriers. Nowadays, APIs for marking loads from shared
439 variables such as READ_ONCE() and rcu_dereference() provide implicit
440 address-dependency barriers.
441
442 (3) Read (or load) memory barriers.
443
444 A read barrier is an address-dependency barrier plus a guarantee that all
445 the LOAD operations specified before the barrier will appear to happen
446 before all the LOAD operations specified after the barrier with respect to
447 the other components of the system.
448
449 A read barrier is a partial ordering on loads only; it is not required to
450 have any effect on stores.
451
452 Read memory barriers imply address-dependency barriers, and so can
453 substitute for them.
454
455 [!] Note that read barriers should normally be paired with write barriers;
456 see the "SMP barrier pairing" subsection.
457
458
459 (4) General memory barriers.
460
461 A general memory barrier gives a guarantee that all the LOAD and STORE
462 operations specified before the barrier will appear to happen before all
463 the LOAD and STORE operations specified after the barrier with respect to
464 the other components of the system.
465
466 A general memory barrier is a partial ordering over both loads and stores.
467
468 General memory barriers imply both read and write memory barriers, and so
469 can substitute for either.
470
471
472 And a couple of implicit varieties:
473
474 (5) ACQUIRE operations.
475
476 This acts as a one-way permeable barrier. It guarantees that all memory
477 operations after the ACQUIRE operation will appear to happen after the
478 ACQUIRE operation with respect to the other components of the system.
479 ACQUIRE operations include LOCK operations and both smp_load_acquire()
480 and smp_cond_load_acquire() operations.
481
482 Memory operations that occur before an ACQUIRE operation may appear to
483 happen after it completes.
484
485 An ACQUIRE operation should almost always be paired with a RELEASE
486 operation.
487
488
489 (6) RELEASE operations.
490
491 This also acts as a one-way permeable barrier. It guarantees that all
492 memory operations before the RELEASE operation will appear to happen
493 before the RELEASE operation with respect to the other components of the
494 system. RELEASE operations include UNLOCK operations and
495 smp_store_release() operations.
496
497 Memory operations that occur after a RELEASE operation may appear to
498 happen before it completes.
499
500 The use of ACQUIRE and RELEASE operations generally precludes the need
501 for other sorts of memory barrier. In addition, a RELEASE+ACQUIRE pair is
502 -not- guaranteed to act as a full memory barrier. However, after an
503 ACQUIRE on a given variable, all memory accesses preceding any prior
504 RELEASE on that same variable are guaranteed to be visible. In other
505 words, within a given variable's critical section, all accesses of all
506 previous critical sections for that variable are guaranteed to have
507 completed.
508
509 This means that ACQUIRE acts as a minimal "acquire" operation and
510 RELEASE acts as a minimal "release" operation.
511
512 A subset of the atomic operations described in atomic_t.txt have ACQUIRE and
513 RELEASE variants in addition to fully-ordered and relaxed (no barrier
514 semantics) definitions. For compound atomics performing both a load and a
515 store, ACQUIRE semantics apply only to the load and RELEASE semantics apply
516 only to the store portion of the operation.
517
518 Memory barriers are only required where there's a possibility of interaction
519 between two CPUs or between a CPU and a device. If it can be guaranteed that
520 there won't be any such interaction in any particular piece of code, then
521 memory barriers are unnecessary in that piece of code.
522
523
524 Note that these are the _minimum_ guarantees. Different architectures may give
525 more substantial guarantees, but they may _not_ be relied upon outside of arch
526 specific code.
527
528
529 WHAT MAY NOT BE ASSUMED ABOUT MEMORY BARRIERS?
530 ----------------------------------------------
531
532 There are certain things that the Linux kernel memory barriers do not guarantee:
533
534 (*) There is no guarantee that any of the memory accesses specified before a
535 memory barrier will be _complete_ by the completion of a memory barrier
536 instruction; the barrier can be considered to draw a line in that CPU's
537 access queue that accesses of the appropriate type may not cross.
538
539 (*) There is no guarantee that issuing a memory barrier on one CPU will have
540 any direct effect on another CPU or any other hardware in the system. The
541 indirect effect will be the order in which the second CPU sees the effects
542 of the first CPU's accesses occur, but see the next point:
543
544 (*) There is no guarantee that a CPU will see the correct order of effects
545 from a second CPU's accesses, even _if_ the second CPU uses a memory
546 barrier, unless the first CPU _also_ uses a matching memory barrier (see
547 the subsection on "SMP Barrier Pairing").
548
549 (*) There is no guarantee that some intervening piece of off-the-CPU
550 hardware[*] will not reorder the memory accesses. CPU cache coherency
551 mechanisms should propagate the indirect effects of a memory barrier
552 between CPUs, but might not do so in order.
553
554 [*] For information on bus mastering DMA and coherency please read:
555
556 Documentation/driver-api/pci/pci.rst
557 Documentation/core-api/dma-api-howto.rst
558 Documentation/core-api/dma-api.rst
559
560
561 ADDRESS-DEPENDENCY BARRIERS (HISTORICAL)
562 ----------------------------------------
563 [!] This section is marked as HISTORICAL: it covers the long-obsolete
564 smp_read_barrier_depends() macro, the semantics of which are now implicit
565 in all marked accesses. For more up-to-date information, including
566 how compiler transformations can sometimes break address dependencies,
567 see Documentation/RCU/rcu_dereference.rst.
568
569 As of v4.15 of the Linux kernel, an smp_mb() was added to READ_ONCE() for
570 DEC Alpha, which means that about the only people who need to pay attention
571 to this section are those working on DEC Alpha architecture-specific code
572 and those working on READ_ONCE() itself. For those who need it, and for
573 those who are interested in the history, here is the story of
574 address-dependency barriers.
575
576 [!] While address dependencies are observed in both load-to-load and
577 load-to-store relations, address-dependency barriers are not necessary
578 for load-to-store situations.
579
580 The requirement of address-dependency barriers is a little subtle, and
581 it's not always obvious that they're needed. To illustrate, consider the
582 following sequence of events:
583
584 CPU 1 CPU 2
585 =============== ===============
586 { A == 1, B == 2, C == 3, P == &A, Q == &C }
587 B = 4;
588 <write barrier>
589 WRITE_ONCE(P, &B);
590 Q = READ_ONCE_OLD(P);
591 D = *Q;
592
593 [!] READ_ONCE_OLD() corresponds to READ_ONCE() of pre-4.15 kernel, which
594 doesn't imply an address-dependency barrier.
595
596 There's a clear address dependency here, and it would seem that by the end of
597 the sequence, Q must be either &A or &B, and that:
598
599 (Q == &A) implies (D == 1)
600 (Q == &B) implies (D == 4)
601
602 But! CPU 2's perception of P may be updated _before_ its perception of B, thus
603 leading to the following situation:
604
605 (Q == &B) and (D == 2) ????
606
607 While this may seem like a failure of coherency or causality maintenance, it
608 isn't, and this behaviour can be observed on certain real CPUs (such as the DEC
609 Alpha).
610
611 To deal with this, READ_ONCE() provides an implicit address-dependency barrier
612 since kernel release v4.15:
613
614 CPU 1 CPU 2
615 =============== ===============
616 { A == 1, B == 2, C == 3, P == &A, Q == &C }
617 B = 4;
618 <write barrier>
619 WRITE_ONCE(P, &B);
620 Q = READ_ONCE(P);
621 <implicit address-dependency barrier>
622 D = *Q;
623
624 This enforces the occurrence of one of the two implications, and prevents the
625 third possibility from arising.
626
627
628 [!] Note that this extremely counterintuitive situation arises most easily on
629 machines with split caches, so that, for example, one cache bank processes
630 even-numbered cache lines and the other bank processes odd-numbered cache
631 lines. The pointer P might be stored in an odd-numbered cache line, and the
632 variable B might be stored in an even-numbered cache line. Then, if the
633 even-numbered bank of the reading CPU's cache is extremely busy while the
634 odd-numbered bank is idle, one can see the new value of the pointer P (&B),
635 but the old value of the variable B (2).
636
637
638 An address-dependency barrier is not required to order dependent writes
639 because the CPUs that the Linux kernel supports don't do writes until they
640 are certain (1) that the write will actually happen, (2) of the location of
641 the write, and (3) of the value to be written.
642 But please carefully read the "CONTROL DEPENDENCIES" section and the
643 Documentation/RCU/rcu_dereference.rst file: The compiler can and does break
644 dependencies in a great many highly creative ways.
645
646 CPU 1 CPU 2
647 =============== ===============
648 { A == 1, B == 2, C = 3, P == &A, Q == &C }
649 B = 4;
650 <write barrier>
651 WRITE_ONCE(P, &B);
652 Q = READ_ONCE_OLD(P);
653 WRITE_ONCE(*Q, 5);
654
655 Therefore, no address-dependency barrier is required to order the read into
656 Q with the store into *Q. In other words, this outcome is prohibited,
657 even without an implicit address-dependency barrier of modern READ_ONCE():
658
659 (Q == &B) && (B == 4)
660
661 Please note that this pattern should be rare. After all, the whole point
662 of dependency ordering is to -prevent- writes to the data structure, along
663 with the expensive cache misses associated with those writes. This pattern
664 can be used to record rare error conditions and the like, and the CPUs'
665 naturally occurring ordering prevents such records from being lost.
666
667
668 Note well that the ordering provided by an address dependency is local to
669 the CPU containing it. See the section on "Multicopy atomicity" for
670 more information.
671
672
673 The address-dependency barrier is very important to the RCU system,
674 for example. See rcu_assign_pointer() and rcu_dereference() in
675 include/linux/rcupdate.h. This permits the current target of an RCU'd
676 pointer to be replaced with a new modified target, without the replacement
677 target appearing to be incompletely initialised.
678
679
680 CONTROL DEPENDENCIES
681 --------------------
682
683 Control dependencies can be a bit tricky because current compilers do
684 not understand them. The purpose of this section is to help you prevent
685 the compiler's ignorance from breaking your code.
686
687 A load-load control dependency requires a full read memory barrier, not
688 simply an (implicit) address-dependency barrier to make it work correctly.
689 Consider the following bit of code:
690
691 q = READ_ONCE(a);
692 <implicit address-dependency barrier>
693 if (q) {
694 /* BUG: No address dependency!!! */
695 p = READ_ONCE(b);
696 }
697
698 This will not have the desired effect because there is no actual address
699 dependency, but rather a control dependency that the CPU may short-circuit
700 by attempting to predict the outcome in advance, so that other CPUs see
701 the load from b as having happened before the load from a. In such a case
702 what's actually required is:
703
704 q = READ_ONCE(a);
705 if (q) {
706 <read barrier>
707 p = READ_ONCE(b);
708 }
709
710 However, stores are not speculated. This means that ordering -is- provided
711 for load-store control dependencies, as in the following example:
712
713 q = READ_ONCE(a);
714 if (q) {
715 WRITE_ONCE(b, 1);
716 }
717
718 Control dependencies pair normally with other types of barriers.
719 That said, please note that neither READ_ONCE() nor WRITE_ONCE()
720 are optional! Without the READ_ONCE(), the compiler might combine the
721 load from 'a' with other loads from 'a'. Without the WRITE_ONCE(),
722 the compiler might combine the store to 'b' with other stores to 'b'.
723 Either can result in highly counterintuitive effects on ordering.
724
725 Worse yet, if the compiler is able to prove (say) that the value of
726 variable 'a' is always non-zero, it would be well within its rights
727 to optimize the original example by eliminating the "if" statement
728 as follows:
729
730 q = a;
731 b = 1; /* BUG: Compiler and CPU can both reorder!!! */
732
733 So don't leave out the READ_ONCE().
734
735 It is tempting to try to enforce ordering on identical stores on both
736 branches of the "if" statement as follows:
737
738 q = READ_ONCE(a);
739 if (q) {
740 barrier();
741 WRITE_ONCE(b, 1);
742 do_something();
743 } else {
744 barrier();
745 WRITE_ONCE(b, 1);
746 do_something_else();
747 }
748
749 Unfortunately, current compilers will transform this as follows at high
750 optimization levels:
751
752 q = READ_ONCE(a);
753 barrier();
754 WRITE_ONCE(b, 1); /* BUG: No ordering vs. load from a!!! */
755 if (q) {
756 /* WRITE_ONCE(b, 1); -- moved up, BUG!!! */
757 do_something();
758 } else {
759 /* WRITE_ONCE(b, 1); -- moved up, BUG!!! */
760 do_something_else();
761 }
762
763 Now there is no conditional between the load from 'a' and the store to
764 'b', which means that the CPU is within its rights to reorder them:
765 The conditional is absolutely required, and must be present in the
766 assembly code even after all compiler optimizations have been applied.
767 Therefore, if you need ordering in this example, you need explicit
768 memory barriers, for example, smp_store_release():
769
770 q = READ_ONCE(a);
771 if (q) {
772 smp_store_release(&b, 1);
773 do_something();
774 } else {
775 smp_store_release(&b, 1);
776 do_something_else();
777 }
778
779 In contrast, without explicit memory barriers, two-legged-if control
780 ordering is guaranteed only when the stores differ, for example:
781
782 q = READ_ONCE(a);
783 if (q) {
784 WRITE_ONCE(b, 1);
785 do_something();
786 } else {
787 WRITE_ONCE(b, 2);
788 do_something_else();
789 }
790
791 The initial READ_ONCE() is still required to prevent the compiler from
792 proving the value of 'a'.
793
794 In addition, you need to be careful what you do with the local variable 'q',
795 otherwise the compiler might be able to guess the value and again remove
796 the needed conditional. For example:
797
798 q = READ_ONCE(a);
799 if (q % MAX) {
800 WRITE_ONCE(b, 1);
801 do_something();
802 } else {
803 WRITE_ONCE(b, 2);
804 do_something_else();
805 }
806
807 If MAX is defined to be 1, then the compiler knows that (q % MAX) is
808 equal to zero, in which case the compiler is within its rights to
809 transform the above code into the following:
810
811 q = READ_ONCE(a);
812 WRITE_ONCE(b, 2);
813 do_something_else();
814
815 Given this transformation, the CPU is not required to respect the ordering
816 between the load from variable 'a' and the store to variable 'b'. It is
817 tempting to add a barrier(), but this does not help. The conditional
818 is gone, and the barrier won't bring it back. Therefore, if you are
819 relying on this ordering, you should make sure that MAX is greater than
820 one, perhaps as follows:
821
822 q = READ_ONCE(a);
823 BUILD_BUG_ON(MAX <= 1); /* Order load from a with store to b. */
824 if (q % MAX) {
825 WRITE_ONCE(b, 1);
826 do_something();
827 } else {
828 WRITE_ONCE(b, 2);
829 do_something_else();
830 }
831
832 Please note once again that the stores to 'b' differ. If they were
833 identical, as noted earlier, the compiler could pull this store outside
834 of the 'if' statement.
835
836 You must also be careful not to rely too much on boolean short-circuit
837 evaluation. Consider this example:
838
839 q = READ_ONCE(a);
840 if (q || 1 > 0)
841 WRITE_ONCE(b, 1);
842
843 Because the first condition cannot fault and the second condition is
844 always true, the compiler can transform this example as following,
845 defeating control dependency:
846
847 q = READ_ONCE(a);
848 WRITE_ONCE(b, 1);
849
850 This example underscores the need to ensure that the compiler cannot
851 out-guess your code. More generally, although READ_ONCE() does force
852 the compiler to actually emit code for a given load, it does not force
853 the compiler to use the results.
854
855 In addition, control dependencies apply only to the then-clause and
856 else-clause of the if-statement in question. In particular, it does
857 not necessarily apply to code following the if-statement:
858
859 q = READ_ONCE(a);
860 if (q) {
861 WRITE_ONCE(b, 1);
862 } else {
863 WRITE_ONCE(b, 2);
864 }
865 WRITE_ONCE(c, 1); /* BUG: No ordering against the read from 'a'. */
866
867 It is tempting to argue that there in fact is ordering because the
868 compiler cannot reorder volatile accesses and also cannot reorder
869 the writes to 'b' with the condition. Unfortunately for this line
870 of reasoning, the compiler might compile the two writes to 'b' as
871 conditional-move instructions, as in this fanciful pseudo-assembly
872 language:
873
874 ld r1,a
875 cmp r1,$0
876 cmov,ne r4,$1
877 cmov,eq r4,$2
878 st r4,b
879 st $1,c
880
881 A weakly ordered CPU would have no dependency of any sort between the load
882 from 'a' and the store to 'c'. The control dependencies would extend
883 only to the pair of cmov instructions and the store depending on them.
884 In short, control dependencies apply only to the stores in the then-clause
885 and else-clause of the if-statement in question (including functions
886 invoked by those two clauses), not to code following that if-statement.
887
888
889 Note well that the ordering provided by a control dependency is local
890 to the CPU containing it. See the section on "Multicopy atomicity"
891 for more information.
892
893
894 In summary:
895
896 (*) Control dependencies can order prior loads against later stores.
897 However, they do -not- guarantee any other sort of ordering:
898 Not prior loads against later loads, nor prior stores against
899 later anything. If you need these other forms of ordering,
900 use smp_rmb(), smp_wmb(), or, in the case of prior stores and
901 later loads, smp_mb().
902
903 (*) If both legs of the "if" statement begin with identical stores to
904 the same variable, then those stores must be ordered, either by
905 preceding both of them with smp_mb() or by using smp_store_release()
906 to carry out the stores. Please note that it is -not- sufficient
907 to use barrier() at beginning of each leg of the "if" statement
908 because, as shown by the example above, optimizing compilers can
909 destroy the control dependency while respecting the letter of the
910 barrier() law.
911
912 (*) Control dependencies require at least one run-time conditional
913 between the prior load and the subsequent store, and this
914 conditional must involve the prior load. If the compiler is able
915 to optimize the conditional away, it will have also optimized
916 away the ordering. Careful use of READ_ONCE() and WRITE_ONCE()
917 can help to preserve the needed conditional.
918
919 (*) Control dependencies require that the compiler avoid reordering the
920 dependency into nonexistence. Careful use of READ_ONCE() or
921 atomic{,64}_read() can help to preserve your control dependency.
922 Please see the COMPILER BARRIER section for more information.
923
924 (*) Control dependencies apply only to the then-clause and else-clause
925 of the if-statement containing the control dependency, including
926 any functions that these two clauses call. Control dependencies
927 do -not- apply to code following the if-statement containing the
928 control dependency.
929
930 (*) Control dependencies pair normally with other types of barriers.
931
932 (*) Control dependencies do -not- provide multicopy atomicity. If you
933 need all the CPUs to see a given store at the same time, use smp_mb().
934
935 (*) Compilers do not understand control dependencies. It is therefore
936 your job to ensure that they do not break your code.
937
938
939 SMP BARRIER PAIRING
940 -------------------
941
942 When dealing with CPU-CPU interactions, certain types of memory barrier should
943 always be paired. A lack of appropriate pairing is almost certainly an error.
944
945 General barriers pair with each other, though they also pair with most
946 other types of barriers, albeit without multicopy atomicity. An acquire
947 barrier pairs with a release barrier, but both may also pair with other
948 barriers, including of course general barriers. A write barrier pairs
949 with an address-dependency barrier, a control dependency, an acquire barrier,
950 a release barrier, a read barrier, or a general barrier. Similarly a
951 read barrier, control dependency, or an address-dependency barrier pairs
952 with a write barrier, an acquire barrier, a release barrier, or a
953 general barrier:
954
955 CPU 1 CPU 2
956 =============== ===============
957 WRITE_ONCE(a, 1);
958 <write barrier>
959 WRITE_ONCE(b, 2); x = READ_ONCE(b);
960 <read barrier>
961 y = READ_ONCE(a);
962
963 Or:
964
965 CPU 1 CPU 2
966 =============== ===============================
967 a = 1;
968 <write barrier>
969 WRITE_ONCE(b, &a); x = READ_ONCE(b);
970 <implicit address-dependency barrier>
971 y = *x;
972
973 Or even:
974
975 CPU 1 CPU 2
976 =============== ===============================
977 r1 = READ_ONCE(y);
978 <general barrier>
979 WRITE_ONCE(x, 1); if (r2 = READ_ONCE(x)) {
980 <implicit control dependency>
981 WRITE_ONCE(y, 1);
982 }
983
984 assert(r1 == 0 || r2 == 0);
985
986 Basically, the read barrier always has to be there, even though it can be of
987 the "weaker" type.
988
989 [!] Note that the stores before the write barrier would normally be expected to
990 match the loads after the read barrier or the address-dependency barrier, and
991 vice versa:
992
993 CPU 1 CPU 2
994 =================== ===================
995 WRITE_ONCE(a, 1); }---- --->{ v = READ_ONCE(c);
996 WRITE_ONCE(b, 2); } \ / { w = READ_ONCE(d);
997 <write barrier> \ <read barrier>
998 WRITE_ONCE(c, 3); } / \ { x = READ_ONCE(a);
999 WRITE_ONCE(d, 4); }---- --->{ y = READ_ONCE(b);
1002 EXAMPLES OF MEMORY BARRIER SEQUENCES
1003 ------------------------------------
1005 Firstly, write barriers act as partial orderings on store operations.
1006 Consider the following sequence of events:
1008 CPU 1
1009 =======================
1010 STORE A = 1
1011 STORE B = 2
1012 STORE C = 3
1013 <write barrier>
1014 STORE D = 4
1015 STORE E = 5
1017 This sequence of events is committed to the memory coherence system in an order
1018 that the rest of the system might perceive as the unordered set of { STORE A,
1019 STORE B, STORE C } all occurring before the unordered set of { STORE D, STORE E
1020 }:
1022 +-------+ : :
1023 | | +------+
1024 | |------>| C=3 | } /\
1025 | | : +------+ }----- \ -----> Events perceptible to
1026 | | : | A=1 | } \/ the rest of the system
1027 | | : +------+ }
1028 | CPU 1 | : | B=2 | }
1029 | | +------+ }
1030 | | wwwwwwwwwwwwwwww } <--- At this point the write barrier
1031 | | +------+ } requires all stores prior to the
1032 | | : | E=5 | } barrier to be committed before
1033 | | : +------+ } further stores may take place
1034 | |------>| D=4 | }
1035 | | +------+
1036 +-------+ : :
1037 |
1038 | Sequence in which stores are committed to the
1039 | memory system by CPU 1
1040 V
1043 Secondly, address-dependency barriers act as partial orderings on address-
1044 dependent loads. Consider the following sequence of events:
1046 CPU 1 CPU 2
1047 ======================= =======================
1048 { B = 7; X = 9; Y = 8; C = &Y }
1049 STORE A = 1
1050 STORE B = 2
1051 <write barrier>
1052 STORE C = &B LOAD X
1053 STORE D = 4 LOAD C (gets &B)
1054 LOAD *C (reads B)
1056 Without intervention, CPU 2 may perceive the events on CPU 1 in some
1057 effectively random order, despite the write barrier issued by CPU 1:
1059 +-------+ : : : :
1060 | | +------+ +-------+ | Sequence of update
1061 | |------>| B=2 |----- --->| Y->8 | | of perception on
1062 | | : +------+ \ +-------+ | CPU 2
1063 | CPU 1 | : | A=1 | \ --->| C->&Y | V
1064 | | +------+ | +-------+
1065 | | wwwwwwwwwwwwwwww | : :
1066 | | +------+ | : :
1067 | | : | C=&B |--- | : : +-------+
1068 | | : +------+ \ | +-------+ | |
1069 | |------>| D=4 | ----------->| C->&B |------>| |
1070 | | +------+ | +-------+ | |
1071 +-------+ : : | : : | |
1072 | : : | |
1073 | : : | CPU 2 |
1074 | +-------+ | |
1075 Apparently incorrect ---> | | B->7 |------>| |
1076 perception of B (!) | +-------+ | |
1077 | : : | |
1078 | +-------+ | |
1079 The load of X holds ---> \ | X->9 |------>| |
1080 up the maintenance \ +-------+ | |
1081 of coherence of B ----->| B->2 | +-------+
1082 +-------+
1083 : :
1086 In the above example, CPU 2 perceives that B is 7, despite the load of *C
1087 (which would be B) coming after the LOAD of C.
1089 If, however, an address-dependency barrier were to be placed between the load
1090 of C and the load of *C (ie: B) on CPU 2:
1092 CPU 1 CPU 2
1093 ======================= =======================
1094 { B = 7; X = 9; Y = 8; C = &Y }
1095 STORE A = 1
1096 STORE B = 2
1097 <write barrier>
1098 STORE C = &B LOAD X
1099 STORE D = 4 LOAD C (gets &B)
1100 <address-dependency barrier>
1101 LOAD *C (reads B)
1103 then the following will occur:
1105 +-------+ : : : :
1106 | | +------+ +-------+
1107 | |------>| B=2 |----- --->| Y->8 |
1108 | | : +------+ \ +-------+
1109 | CPU 1 | : | A=1 | \ --->| C->&Y |
1110 | | +------+ | +-------+
1111 | | wwwwwwwwwwwwwwww | : :
1112 | | +------+ | : :
1113 | | : | C=&B |--- | : : +-------+
1114 | | : +------+ \ | +-------+ | |
1115 | |------>| D=4 | ----------->| C->&B |------>| |
1116 | | +------+ | +-------+ | |
1117 +-------+ : : | : : | |
1118 | : : | |
1119 | : : | CPU 2 |
1120 | +-------+ | |
1121 | | X->9 |------>| |
1122 | +-------+ | |
1123 Makes sure all effects ---> \ aaaaaaaaaaaaaaaaa | |
1124 prior to the store of C \ +-------+ | |
1125 are perceptible to ----->| B->2 |------>| |
1126 subsequent loads +-------+ | |
1127 : : +-------+
1130 And thirdly, a read barrier acts as a partial order on loads. Consider the
1131 following sequence of events:
1133 CPU 1 CPU 2
1134 ======================= =======================
1135 { A = 0, B = 9 }
1136 STORE A=1
1137 <write barrier>
1138 STORE B=2
1139 LOAD B
1140 LOAD A
1142 Without intervention, CPU 2 may then choose to perceive the events on CPU 1 in
1143 some effectively random order, despite the write barrier issued by CPU 1:
1145 +-------+ : : : :
1146 | | +------+ +-------+
1147 | |------>| A=1 |------ --->| A->0 |
1148 | | +------+ \ +-------+
1149 | CPU 1 | wwwwwwwwwwwwwwww \ --->| B->9 |
1150 | | +------+ | +-------+
1151 | |------>| B=2 |--- | : :
1152 | | +------+ \ | : : +-------+
1153 +-------+ : : \ | +-------+ | |
1154 ---------->| B->2 |------>| |
1155 | +-------+ | CPU 2 |
1156 | | A->0 |------>| |
1157 | +-------+ | |
1158 | : : +-------+
1159 \ : :
1160 \ +-------+
1161 ---->| A->1 |
1162 +-------+
1163 : :
1166 If, however, a read barrier were to be placed between the load of B and the
1167 load of A on CPU 2:
1169 CPU 1 CPU 2
1170 ======================= =======================
1171 { A = 0, B = 9 }
1172 STORE A=1
1173 <write barrier>
1174 STORE B=2
1175 LOAD B
1176 <read barrier>
1177 LOAD A
1179 then the partial ordering imposed by CPU 1 will be perceived correctly by CPU
1180 2:
1182 +-------+ : : : :
1183 | | +------+ +-------+
1184 | |------>| A=1 |------ --->| A->0 |
1185 | | +------+ \ +-------+
1186 | CPU 1 | wwwwwwwwwwwwwwww \ --->| B->9 |
1187 | | +------+ | +-------+
1188 | |------>| B=2 |--- | : :
1189 | | +------+ \ | : : +-------+
1190 +-------+ : : \ | +-------+ | |
1191 ---------->| B->2 |------>| |
1192 | +-------+ | CPU 2 |
1193 | : : | |
1194 | : : | |
1195 At this point the read ----> \ rrrrrrrrrrrrrrrrr | |
1196 barrier causes all effects \ +-------+ | |
1197 prior to the storage of B ---->| A->1 |------>| |
1198 to be perceptible to CPU 2 +-------+ | |
1199 : : +-------+
1202 To illustrate this more completely, consider what could happen if the code
1203 contained a load of A either side of the read barrier:
1205 CPU 1 CPU 2
1206 ======================= =======================
1207 { A = 0, B = 9 }
1208 STORE A=1
1209 <write barrier>
1210 STORE B=2
1211 LOAD B
1212 LOAD A [first load of A]
1213 <read barrier>
1214 LOAD A [second load of A]
1216 Even though the two loads of A both occur after the load of B, they may both
1217 come up with different values:
1219 +-------+ : : : :
1220 | | +------+ +-------+
1221 | |------>| A=1 |------ --->| A->0 |
1222 | | +------+ \ +-------+
1223 | CPU 1 | wwwwwwwwwwwwwwww \ --->| B->9 |
1224 | | +------+ | +-------+
1225 | |------>| B=2 |--- | : :
1226 | | +------+ \ | : : +-------+
1227 +-------+ : : \ | +-------+ | |
1228 ---------->| B->2 |------>| |
1229 | +-------+ | CPU 2 |
1230 | : : | |
1231 | : : | |
1232 | +-------+ | |
1233 | | A->0 |------>| 1st |
1234 | +-------+ | |
1235 At this point the read ----> \ rrrrrrrrrrrrrrrrr | |
1236 barrier causes all effects \ +-------+ | |
1237 prior to the storage of B ---->| A->1 |------>| 2nd |
1238 to be perceptible to CPU 2 +-------+ | |
1239 : : +-------+
1242 But it may be that the update to A from CPU 1 becomes perceptible to CPU 2
1243 before the read barrier completes anyway:
1245 +-------+ : : : :
1246 | | +------+ +-------+
1247 | |------>| A=1 |------ --->| A->0 |
1248 | | +------+ \ +-------+
1249 | CPU 1 | wwwwwwwwwwwwwwww \ --->| B->9 |
1250 | | +------+ | +-------+
1251 | |------>| B=2 |--- | : :
1252 | | +------+ \ | : : +-------+
1253 +-------+ : : \ | +-------+ | |
1254 ---------->| B->2 |------>| |
1255 | +-------+ | CPU 2 |
1256 | : : | |
1257 \ : : | |
1258 \ +-------+ | |
1259 ---->| A->1 |------>| 1st |
1260 +-------+ | |
1261 rrrrrrrrrrrrrrrrr | |
1262 +-------+ | |
1263 | A->1 |------>| 2nd |
1264 +-------+ | |
1265 : : +-------+
1268 The guarantee is that the second load will always come up with A == 1 if the
1269 load of B came up with B == 2. No such guarantee exists for the first load of
1270 A; that may come up with either A == 0 or A == 1.
1273 READ MEMORY BARRIERS VS LOAD SPECULATION
1274 ----------------------------------------
1276 Many CPUs speculate with loads: that is they see that they will need to load an
1277 item from memory, and they find a time where they're not using the bus for any
1278 other loads, and so do the load in advance - even though they haven't actually
1279 got to that point in the instruction execution flow yet. This permits the
1280 actual load instruction to potentially complete immediately because the CPU
1281 already has the value to hand.
1283 It may turn out that the CPU didn't actually need the value - perhaps because a
1284 branch circumvented the load - in which case it can discard the value or just
1285 cache it for later use.
1287 Consider:
1289 CPU 1 CPU 2
1290 ======================= =======================
1291 LOAD B
1292 DIVIDE } Divide instructions generally
1293 DIVIDE } take a long time to perform
1294 LOAD A
1296 Which might appear as this:
1298 : : +-------+
1299 +-------+ | |
1300 --->| B->2 |------>| |
1301 +-------+ | CPU 2 |
1302 : :DIVIDE | |
1303 +-------+ | |
1304 The CPU being busy doing a ---> --->| A->0 |~~~~ | |
1305 division speculates on the +-------+ ~ | |
1306 LOAD of A : : ~ | |
1307 : :DIVIDE | |
1308 : : ~ | |
1309 Once the divisions are complete --> : : ~-->| |
1310 the CPU can then perform the : : | |
1311 LOAD with immediate effect : : +-------+
1314 Placing a read barrier or an address-dependency barrier just before the second
1315 load:
1317 CPU 1 CPU 2
1318 ======================= =======================
1319 LOAD B
1320 DIVIDE
1321 DIVIDE
1322 <read barrier>
1323 LOAD A
1325 will force any value speculatively obtained to be reconsidered to an extent
1326 dependent on the type of barrier used. If there was no change made to the
1327 speculated memory location, then the speculated value will just be used:
1329 : : +-------+
1330 +-------+ | |
1331 --->| B->2 |------>| |
1332 +-------+ | CPU 2 |
1333 : :DIVIDE | |
1334 +-------+ | |
1335 The CPU being busy doing a ---> --->| A->0 |~~~~ | |
1336 division speculates on the +-------+ ~ | |
1337 LOAD of A : : ~ | |
1338 : :DIVIDE | |
1339 : : ~ | |
1340 : : ~ | |
1341 rrrrrrrrrrrrrrrr~ | |
1342 : : ~ | |
1343 : : ~-->| |
1344 : : | |
1345 : : +-------+
1348 but if there was an update or an invalidation from another CPU pending, then
1349 the speculation will be cancelled and the value reloaded:
1351 : : +-------+
1352 +-------+ | |
1353 --->| B->2 |------>| |
1354 +-------+ | CPU 2 |
1355 : :DIVIDE | |
1356 +-------+ | |
1357 The CPU being busy doing a ---> --->| A->0 |~~~~ | |
1358 division speculates on the +-------+ ~ | |
1359 LOAD of A : : ~ | |
1360 : :DIVIDE | |
1361 : : ~ | |
1362 : : ~ | |
1363 rrrrrrrrrrrrrrrrr | |
1364 +-------+ | |
1365 The speculation is discarded ---> --->| A->1 |------>| |
1366 and an updated value is +-------+ | |
1367 retrieved : : +-------+
1370 MULTICOPY ATOMICITY
1371 --------------------
1373 Multicopy atomicity is a deeply intuitive notion about ordering that is
1374 not always provided by real computer systems, namely that a given store
1375 becomes visible at the same time to all CPUs, or, alternatively, that all
1376 CPUs agree on the order in which all stores become visible. However,
1377 support of full multicopy atomicity would rule out valuable hardware
1378 optimizations, so a weaker form called ``other multicopy atomicity''
1379 instead guarantees only that a given store becomes visible at the same
1380 time to all -other- CPUs. The remainder of this document discusses this
1381 weaker form, but for brevity will call it simply ``multicopy atomicity''.
1383 The following example demonstrates multicopy atomicity:
1385 CPU 1 CPU 2 CPU 3
1386 ======================= ======================= =======================
1387 { X = 0, Y = 0 }
1388 STORE X=1 r1=LOAD X (reads 1) LOAD Y (reads 1)
1389 <general barrier> <read barrier>
1390 STORE Y=r1 LOAD X
1392 Suppose that CPU 2's load from X returns 1, which it then stores to Y,
1393 and CPU 3's load from Y returns 1. This indicates that CPU 1's store
1394 to X precedes CPU 2's load from X and that CPU 2's store to Y precedes
1395 CPU 3's load from Y. In addition, the memory barriers guarantee that
1396 CPU 2 executes its load before its store, and CPU 3 loads from Y before
1397 it loads from X. The question is then "Can CPU 3's load from X return 0?"
1399 Because CPU 3's load from X in some sense comes after CPU 2's load, it
1400 is natural to expect that CPU 3's load from X must therefore return 1.
1401 This expectation follows from multicopy atomicity: if a load executing
1402 on CPU B follows a load from the same variable executing on CPU A (and
1403 CPU A did not originally store the value which it read), then on
1404 multicopy-atomic systems, CPU B's load must return either the same value
1405 that CPU A's load did or some later value. However, the Linux kernel
1406 does not require systems to be multicopy atomic.
1408 The use of a general memory barrier in the example above compensates
1409 for any lack of multicopy atomicity. In the example, if CPU 2's load
1410 from X returns 1 and CPU 3's load from Y returns 1, then CPU 3's load
1411 from X must indeed also return 1.
1413 However, dependencies, read barriers, and write barriers are not always
1414 able to compensate for non-multicopy atomicity. For example, suppose
1415 that CPU 2's general barrier is removed from the above example, leaving
1416 only the data dependency shown below:
1418 CPU 1 CPU 2 CPU 3
1419 ======================= ======================= =======================
1420 { X = 0, Y = 0 }
1421 STORE X=1 r1=LOAD X (reads 1) LOAD Y (reads 1)
1422 <data dependency> <read barrier>
1423 STORE Y=r1 LOAD X (reads 0)
1425 This substitution allows non-multicopy atomicity to run rampant: in
1426 this example, it is perfectly legal for CPU 2's load from X to return 1,
1427 CPU 3's load from Y to return 1, and its load from X to return 0.
1429 The key point is that although CPU 2's data dependency orders its load
1430 and store, it does not guarantee to order CPU 1's store. Thus, if this
1431 example runs on a non-multicopy-atomic system where CPUs 1 and 2 share a
1432 store buffer or a level of cache, CPU 2 might have early access to CPU 1's
1433 writes. General barriers are therefore required to ensure that all CPUs
1434 agree on the combined order of multiple accesses.
1436 General barriers can compensate not only for non-multicopy atomicity,
1437 but can also generate additional ordering that can ensure that -all-
1438 CPUs will perceive the same order of -all- operations. In contrast, a
1439 chain of release-acquire pairs do not provide this additional ordering,
1440 which means that only those CPUs on the chain are guaranteed to agree
1441 on the combined order of the accesses. For example, switching to C code
1442 in deference to the ghost of Herman Hollerith:
1444 int u, v, x, y, z;
1446 void cpu0(void)
1447 {
1448 r0 = smp_load_acquire(&x);
1449 WRITE_ONCE(u, 1);
1450 smp_store_release(&y, 1);
1451 }
1453 void cpu1(void)
1454 {
1455 r1 = smp_load_acquire(&y);
1456 r4 = READ_ONCE(v);
1457 r5 = READ_ONCE(u);
1458 smp_store_release(&z, 1);
1459 }
1461 void cpu2(void)
1462 {
1463 r2 = smp_load_acquire(&z);
1464 smp_store_release(&x, 1);
1465 }
1467 void cpu3(void)
1468 {
1469 WRITE_ONCE(v, 1);
1470 smp_mb();
1471 r3 = READ_ONCE(u);
1472 }
1474 Because cpu0(), cpu1(), and cpu2() participate in a chain of
1475 smp_store_release()/smp_load_acquire() pairs, the following outcome
1476 is prohibited:
1478 r0 == 1 && r1 == 1 && r2 == 1
1480 Furthermore, because of the release-acquire relationship between cpu0()
1481 and cpu1(), cpu1() must see cpu0()'s writes, so that the following
1482 outcome is prohibited:
1484 r1 == 1 && r5 == 0
1486 However, the ordering provided by a release-acquire chain is local
1487 to the CPUs participating in that chain and does not apply to cpu3(),
1488 at least aside from stores. Therefore, the following outcome is possible:
1490 r0 == 0 && r1 == 1 && r2 == 1 && r3 == 0 && r4 == 0
1492 As an aside, the following outcome is also possible:
1494 r0 == 0 && r1 == 1 && r2 == 1 && r3 == 0 && r4 == 0 && r5 == 1
1496 Although cpu0(), cpu1(), and cpu2() will see their respective reads and
1497 writes in order, CPUs not involved in the release-acquire chain might
1498 well disagree on the order. This disagreement stems from the fact that
1499 the weak memory-barrier instructions used to implement smp_load_acquire()
1500 and smp_store_release() are not required to order prior stores against
1501 subsequent loads in all cases. This means that cpu3() can see cpu0()'s
1502 store to u as happening -after- cpu1()'s load from v, even though
1503 both cpu0() and cpu1() agree that these two operations occurred in the
1504 intended order.
1506 However, please keep in mind that smp_load_acquire() is not magic.
1507 In particular, it simply reads from its argument with ordering. It does
1508 -not- ensure that any particular value will be read. Therefore, the
1509 following outcome is possible:
1511 r0 == 0 && r1 == 0 && r2 == 0 && r5 == 0
1513 Note that this outcome can happen even on a mythical sequentially
1514 consistent system where nothing is ever reordered.
1516 To reiterate, if your code requires full ordering of all operations,
1517 use general barriers throughout.
1520 ========================
1521 EXPLICIT KERNEL BARRIERS
1522 ========================
1524 The Linux kernel has a variety of different barriers that act at different
1525 levels:
1527 (*) Compiler barrier.
1529 (*) CPU memory barriers.
1532 COMPILER BARRIER
1533 ----------------
1535 The Linux kernel has an explicit compiler barrier function that prevents the
1536 compiler from moving the memory accesses either side of it to the other side:
1538 barrier();
1540 This is a general barrier -- there are no read-read or write-write
1541 variants of barrier(). However, READ_ONCE() and WRITE_ONCE() can be
1542 thought of as weak forms of barrier() that affect only the specific
1543 accesses flagged by the READ_ONCE() or WRITE_ONCE().
1545 The barrier() function has the following effects:
1547 (*) Prevents the compiler from reordering accesses following the
1548 barrier() to precede any accesses preceding the barrier().
1549 One example use for this property is to ease communication between
1550 interrupt-handler code and the code that was interrupted.
1552 (*) Within a loop, forces the compiler to load the variables used
1553 in that loop's conditional on each pass through that loop.
1555 The READ_ONCE() and WRITE_ONCE() functions can prevent any number of
1556 optimizations that, while perfectly safe in single-threaded code, can
1557 be fatal in concurrent code. Here are some examples of these sorts
1558 of optimizations:
1560 (*) The compiler is within its rights to reorder loads and stores
1561 to the same variable, and in some cases, the CPU is within its
1562 rights to reorder loads to the same variable. This means that
1563 the following code:
1565 a[0] = x;
1566 a[1] = x;
1568 Might result in an older value of x stored in a[1] than in a[0].
1569 Prevent both the compiler and the CPU from doing this as follows:
1571 a[0] = READ_ONCE(x);
1572 a[1] = READ_ONCE(x);
1574 In short, READ_ONCE() and WRITE_ONCE() provide cache coherence for
1575 accesses from multiple CPUs to a single variable.
1577 (*) The compiler is within its rights to merge successive loads from
1578 the same variable. Such merging can cause the compiler to "optimize"
1579 the following code:
1581 while (tmp = a)
1582 do_something_with(tmp);
1584 into the following code, which, although in some sense legitimate
1585 for single-threaded code, is almost certainly not what the developer
1586 intended:
1588 if (tmp = a)
1589 for (;;)
1590 do_something_with(tmp);
1592 Use READ_ONCE() to prevent the compiler from doing this to you:
1594 while (tmp = READ_ONCE(a))
1595 do_something_with(tmp);
1597 (*) The compiler is within its rights to reload a variable, for example,
1598 in cases where high register pressure prevents the compiler from
1599 keeping all data of interest in registers. The compiler might
1600 therefore optimize the variable 'tmp' out of our previous example:
1602 while (tmp = a)
1603 do_something_with(tmp);
1605 This could result in the following code, which is perfectly safe in
1606 single-threaded code, but can be fatal in concurrent code:
1608 while (a)
1609 do_something_with(a);
1611 For example, the optimized version of this code could result in
1612 passing a zero to do_something_with() in the case where the variable
1613 a was modified by some other CPU between the "while" statement and
1614 the call to do_something_with().
1616 Again, use READ_ONCE() to prevent the compiler from doing this:
1618 while (tmp = READ_ONCE(a))
1619 do_something_with(tmp);
1621 Note that if the compiler runs short of registers, it might save
1622 tmp onto the stack. The overhead of this saving and later restoring
1623 is why compilers reload variables. Doing so is perfectly safe for
1624 single-threaded code, so you need to tell the compiler about cases
1625 where it is not safe.
1627 (*) The compiler is within its rights to omit a load entirely if it knows
1628 what the value will be. For example, if the compiler can prove that
1629 the value of variable 'a' is always zero, it can optimize this code:
1631 while (tmp = a)
1632 do_something_with(tmp);
1634 Into this:
1636 do { } while (0);
1638 This transformation is a win for single-threaded code because it
1639 gets rid of a load and a branch. The problem is that the compiler
1640 will carry out its proof assuming that the current CPU is the only
1641 one updating variable 'a'. If variable 'a' is shared, then the
1642 compiler's proof will be erroneous. Use READ_ONCE() to tell the
1643 compiler that it doesn't know as much as it thinks it does:
1645 while (tmp = READ_ONCE(a))
1646 do_something_with(tmp);
1648 But please note that the compiler is also closely watching what you
1649 do with the value after the READ_ONCE(). For example, suppose you
1650 do the following and MAX is a preprocessor macro with the value 1:
1652 while ((tmp = READ_ONCE(a)) % MAX)
1653 do_something_with(tmp);
1655 Then the compiler knows that the result of the "%" operator applied
1656 to MAX will always be zero, again allowing the compiler to optimize
1657 the code into near-nonexistence. (It will still load from the
1658 variable 'a'.)
1660 (*) Similarly, the compiler is within its rights to omit a store entirely
1661 if it knows that the variable already has the value being stored.
1662 Again, the compiler assumes that the current CPU is the only one
1663 storing into the variable, which can cause the compiler to do the
1664 wrong thing for shared variables. For example, suppose you have
1665 the following:
1667 a = 0;
1668 ... Code that does not store to variable a ...
1669 a = 0;
1671 The compiler sees that the value of variable 'a' is already zero, so
1672 it might well omit the second store. This would come as a fatal
1673 surprise if some other CPU might have stored to variable 'a' in the
1674 meantime.
1676 Use WRITE_ONCE() to prevent the compiler from making this sort of
1677 wrong guess:
1679 WRITE_ONCE(a, 0);
1680 ... Code that does not store to variable a ...
1681 WRITE_ONCE(a, 0);
1683 (*) The compiler is within its rights to reorder memory accesses unless
1684 you tell it not to. For example, consider the following interaction
1685 between process-level code and an interrupt handler:
1687 void process_level(void)
1688 {
1689 msg = get_message();
1690 flag = true;
1691 }
1693 void interrupt_handler(void)
1694 {
1695 if (flag)
1696 process_message(msg);
1697 }
1699 There is nothing to prevent the compiler from transforming
1700 process_level() to the following, in fact, this might well be a
1701 win for single-threaded code:
1703 void process_level(void)
1704 {
1705 flag = true;
1706 msg = get_message();
1707 }
1709 If the interrupt occurs between these two statement, then
1710 interrupt_handler() might be passed a garbled msg. Use WRITE_ONCE()
1711 to prevent this as follows:
1713 void process_level(void)
1714 {
1715 WRITE_ONCE(msg, get_message());
1716 WRITE_ONCE(flag, true);
1717 }
1719 void interrupt_handler(void)
1720 {
1721 if (READ_ONCE(flag))
1722 process_message(READ_ONCE(msg));
1723 }
1725 Note that the READ_ONCE() and WRITE_ONCE() wrappers in
1726 interrupt_handler() are needed if this interrupt handler can itself
1727 be interrupted by something that also accesses 'flag' and 'msg',
1728 for example, a nested interrupt or an NMI. Otherwise, READ_ONCE()
1729 and WRITE_ONCE() are not needed in interrupt_handler() other than
1730 for documentation purposes. (Note also that nested interrupts
1731 do not typically occur in modern Linux kernels, in fact, if an
1732 interrupt handler returns with interrupts enabled, you will get a
1733 WARN_ONCE() splat.)
1735 You should assume that the compiler can move READ_ONCE() and
1736 WRITE_ONCE() past code not containing READ_ONCE(), WRITE_ONCE(),
1737 barrier(), or similar primitives.
1739 This effect could also be achieved using barrier(), but READ_ONCE()
1740 and WRITE_ONCE() are more selective: With READ_ONCE() and
1741 WRITE_ONCE(), the compiler need only forget the contents of the
1742 indicated memory locations, while with barrier() the compiler must
1743 discard the value of all memory locations that it has currently
1744 cached in any machine registers. Of course, the compiler must also
1745 respect the order in which the READ_ONCE()s and WRITE_ONCE()s occur,
1746 though the CPU of course need not do so.
1748 (*) The compiler is within its rights to invent stores to a variable,
1749 as in the following example:
1751 if (a)
1752 b = a;
1753 else
1754 b = 42;
1756 The compiler might save a branch by optimizing this as follows:
1758 b = 42;
1759 if (a)
1760 b = a;
1762 In single-threaded code, this is not only safe, but also saves
1763 a branch. Unfortunately, in concurrent code, this optimization
1764 could cause some other CPU to see a spurious value of 42 -- even
1765 if variable 'a' was never zero -- when loading variable 'b'.
1766 Use WRITE_ONCE() to prevent this as follows:
1768 if (a)
1769 WRITE_ONCE(b, a);
1770 else
1771 WRITE_ONCE(b, 42);
1773 The compiler can also invent loads. These are usually less
1774 damaging, but they can result in cache-line bouncing and thus in
1775 poor performance and scalability. Use READ_ONCE() to prevent
1776 invented loads.
1778 (*) For aligned memory locations whose size allows them to be accessed
1779 with a single memory-reference instruction, prevents "load tearing"
1780 and "store tearing," in which a single large access is replaced by
1781 multiple smaller accesses. For example, given an architecture having
1782 16-bit store instructions with 7-bit immediate fields, the compiler
1783 might be tempted to use two 16-bit store-immediate instructions to
1784 implement the following 32-bit store:
1786 p = 0x00010002;
1788 Please note that GCC really does use this sort of optimization,
1789 which is not surprising given that it would likely take more
1790 than two instructions to build the constant and then store it.
1791 This optimization can therefore be a win in single-threaded code.
1792 In fact, a recent bug (since fixed) caused GCC to incorrectly use
1793 this optimization in a volatile store. In the absence of such bugs,
1794 use of WRITE_ONCE() prevents store tearing in the following example:
1796 WRITE_ONCE(p, 0x00010002);
1798 Use of packed structures can also result in load and store tearing,
1799 as in this example:
1801 struct __attribute__((__packed__)) foo {
1802 short a;
1803 int b;
1804 short c;
1805 };
1806 struct foo foo1, foo2;
1807 ...
1809 foo2.a = foo1.a;
1810 foo2.b = foo1.b;
1811 foo2.c = foo1.c;
1813 Because there are no READ_ONCE() or WRITE_ONCE() wrappers and no
1814 volatile markings, the compiler would be well within its rights to
1815 implement these three assignment statements as a pair of 32-bit
1816 loads followed by a pair of 32-bit stores. This would result in
1817 load tearing on 'foo1.b' and store tearing on 'foo2.b'. READ_ONCE()
1818 and WRITE_ONCE() again prevent tearing in this example:
1820 foo2.a = foo1.a;
1821 WRITE_ONCE(foo2.b, READ_ONCE(foo1.b));
1822 foo2.c = foo1.c;
1824 All that aside, it is never necessary to use READ_ONCE() and
1825 WRITE_ONCE() on a variable that has been marked volatile. For example,
1826 because 'jiffies' is marked volatile, it is never necessary to
1827 say READ_ONCE(jiffies). The reason for this is that READ_ONCE() and
1828 WRITE_ONCE() are implemented as volatile casts, which has no effect when
1829 its argument is already marked volatile.
1831 Please note that these compiler barriers have no direct effect on the CPU,
1832 which may then reorder things however it wishes.
1835 CPU MEMORY BARRIERS
1836 -------------------
1838 The Linux kernel has seven basic CPU memory barriers:
1840 TYPE MANDATORY SMP CONDITIONAL
1841 ======================= =============== ===============
1842 GENERAL mb() smp_mb()
1843 WRITE wmb() smp_wmb()
1844 READ rmb() smp_rmb()
1845 ADDRESS DEPENDENCY READ_ONCE()
1848 All memory barriers except the address-dependency barriers imply a compiler
1849 barrier. Address dependencies do not impose any additional compiler ordering.
1851 Aside: In the case of address dependencies, the compiler would be expected
1852 to issue the loads in the correct order (eg. `a[b]` would have to load
1853 the value of b before loading a[b]), however there is no guarantee in
1854 the C specification that the compiler may not speculate the value of b
1855 (eg. is equal to 1) and load a[b] before b (eg. tmp = a[1]; if (b != 1)
1856 tmp = a[b]; ). There is also the problem of a compiler reloading b after
1857 having loaded a[b], thus having a newer copy of b than a[b]. A consensus
1858 has not yet been reached about these problems, however the READ_ONCE()
1859 macro is a good place to start looking.
1861 SMP memory barriers are reduced to compiler barriers on uniprocessor compiled
1862 systems because it is assumed that a CPU will appear to be self-consistent,
1863 and will order overlapping accesses correctly with respect to itself.
1864 However, see the subsection on "Virtual Machine Guests" below.
1866 [!] Note that SMP memory barriers _must_ be used to control the ordering of
1867 references to shared memory on SMP systems, though the use of locking instead
1868 is sufficient.
1870 Mandatory barriers should not be used to control SMP effects, since mandatory
1871 barriers impose unnecessary overhead on both SMP and UP systems. They may,
1872 however, be used to control MMIO effects on accesses through relaxed memory I/O
1873 windows. These barriers are required even on non-SMP systems as they affect
1874 the order in which memory operations appear to a device by prohibiting both the
1875 compiler and the CPU from reordering them.
1878 There are some more advanced barrier functions:
1880 (*) smp_store_mb(var, value)
1882 This assigns the value to the variable and then inserts a full memory
1883 barrier after it. It isn't guaranteed to insert anything more than a
1884 compiler barrier in a UP compilation.
1887 (*) smp_mb__before_atomic();
1888 (*) smp_mb__after_atomic();
1890 These are for use with atomic RMW functions that do not imply memory
1891 barriers, but where the code needs a memory barrier. Examples for atomic
1892 RMW functions that do not imply a memory barrier are e.g. add,
1893 subtract, (failed) conditional operations, _relaxed functions,
1894 but not atomic_read or atomic_set. A common example where a memory
1895 barrier may be required is when atomic ops are used for reference
1896 counting.
1898 These are also used for atomic RMW bitop functions that do not imply a
1899 memory barrier (such as set_bit and clear_bit).
1901 As an example, consider a piece of code that marks an object as being dead
1902 and then decrements the object's reference count:
1904 obj->dead = 1;
1905 smp_mb__before_atomic();
1906 atomic_dec(&obj->ref_count);
1908 This makes sure that the death mark on the object is perceived to be set
1909 *before* the reference counter is decremented.
1911 See Documentation/atomic_{t,bitops}.txt for more information.
1914 (*) dma_wmb();
1915 (*) dma_rmb();
1916 (*) dma_mb();
1918 These are for use with consistent memory to guarantee the ordering
1919 of writes or reads of shared memory accessible to both the CPU and a
1920 DMA capable device. See Documentation/core-api/dma-api.rst file for more
1921 information about consistent memory.
1923 For example, consider a device driver that shares memory with a device
1924 and uses a descriptor status value to indicate if the descriptor belongs
1925 to the device or the CPU, and a doorbell to notify it when new
1926 descriptors are available:
1928 if (desc->status != DEVICE_OWN) {
1929 /* do not read data until we own descriptor */
1930 dma_rmb();
1932 /* read/modify data */
1933 read_data = desc->data;
1934 desc->data = write_data;
1936 /* flush modifications before status update */
1937 dma_wmb();
1939 /* assign ownership */
1940 desc->status = DEVICE_OWN;
1942 /* Make descriptor status visible to the device followed by
1943 * notify device of new descriptor
1944 */
1945 writel(DESC_NOTIFY, doorbell);
1946 }
1948 The dma_rmb() allows us to guarantee that the device has released ownership
1949 before we read the data from the descriptor, and the dma_wmb() allows
1950 us to guarantee the data is written to the descriptor before the device
1951 can see it now has ownership. The dma_mb() implies both a dma_rmb() and
1952 a dma_wmb().
1954 Note that the dma_*() barriers do not provide any ordering guarantees for
1955 accesses to MMIO regions. See the later "KERNEL I/O BARRIER EFFECTS"
1956 subsection for more information about I/O accessors and MMIO ordering.
1958 (*) pmem_wmb();
1960 This is for use with persistent memory to ensure that stores for which
1961 modifications are written to persistent storage reached a platform
1962 durability domain.
1964 For example, after a non-temporal write to pmem region, we use pmem_wmb()
1965 to ensure that stores have reached a platform durability domain. This ensures
1966 that stores have updated persistent storage before any data access or
1967 data transfer caused by subsequent instructions is initiated. This is
1968 in addition to the ordering done by wmb().
1970 For load from persistent memory, existing read memory barriers are sufficient
1971 to ensure read ordering.
1973 (*) io_stop_wc();
1975 For memory accesses with write-combining attributes (e.g. those returned
1976 by ioremap_wc()), the CPU may wait for prior accesses to be merged with
1977 subsequent ones. io_stop_wc() can be used to prevent the merging of
1978 write-combining memory accesses before this macro with those after it when
1979 such wait has performance implications.
1981 ===============================
1982 IMPLICIT KERNEL MEMORY BARRIERS
1983 ===============================
1985 Some of the other functions in the linux kernel imply memory barriers, amongst
1986 which are locking and scheduling functions.
1988 This specification is a _minimum_ guarantee; any particular architecture may
1989 provide more substantial guarantees, but these may not be relied upon outside
1990 of arch specific code.
1993 LOCK ACQUISITION FUNCTIONS
1994 --------------------------
1996 The Linux kernel has a number of locking constructs:
1998 (*) spin locks
1999 (*) R/W spin locks
2000 (*) mutexes
2001 (*) semaphores
2002 (*) R/W semaphores
2004 In all cases there are variants on "ACQUIRE" operations and "RELEASE" operations
2005 for each construct. These operations all imply certain barriers:
2007 (1) ACQUIRE operation implication:
2009 Memory operations issued after the ACQUIRE will be completed after the
2010 ACQUIRE operation has completed.
2012 Memory operations issued before the ACQUIRE may be completed after
2013 the ACQUIRE operation has completed.
2015 (2) RELEASE operation implication:
2017 Memory operations issued before the RELEASE will be completed before the
2018 RELEASE operation has completed.
2020 Memory operations issued after the RELEASE may be completed before the
2021 RELEASE operation has completed.
2023 (3) ACQUIRE vs ACQUIRE implication:
2025 All ACQUIRE operations issued before another ACQUIRE operation will be
2026 completed before that ACQUIRE operation.
2028 (4) ACQUIRE vs RELEASE implication:
2030 All ACQUIRE operations issued before a RELEASE operation will be
2031 completed before the RELEASE operation.
2033 (5) Failed conditional ACQUIRE implication:
2035 Certain locking variants of the ACQUIRE operation may fail, either due to
2036 being unable to get the lock immediately, or due to receiving an unblocked
2037 signal while asleep waiting for the lock to become available. Failed
2038 locks do not imply any sort of barrier.
2040 [!] Note: one of the consequences of lock ACQUIREs and RELEASEs being only
2041 one-way barriers is that the effects of instructions outside of a critical
2042 section may seep into the inside of the critical section.
2044 An ACQUIRE followed by a RELEASE may not be assumed to be full memory barrier
2045 because it is possible for an access preceding the ACQUIRE to happen after the
2046 ACQUIRE, and an access following the RELEASE to happen before the RELEASE, and
2047 the two accesses can themselves then cross:
2049 *A = a;
2050 ACQUIRE M
2051 RELEASE M
2052 *B = b;
2054 may occur as:
2056 ACQUIRE M, STORE *B, STORE *A, RELEASE M
2058 When the ACQUIRE and RELEASE are a lock acquisition and release,
2059 respectively, this same reordering can occur if the lock's ACQUIRE and
2060 RELEASE are to the same lock variable, but only from the perspective of
2061 another CPU not holding that lock. In short, a ACQUIRE followed by an
2062 RELEASE may -not- be assumed to be a full memory barrier.
2064 Similarly, the reverse case of a RELEASE followed by an ACQUIRE does
2065 not imply a full memory barrier. Therefore, the CPU's execution of the
2066 critical sections corresponding to the RELEASE and the ACQUIRE can cross,
2067 so that:
2069 *A = a;
2070 RELEASE M
2071 ACQUIRE N
2072 *B = b;
2074 could occur as:
2076 ACQUIRE N, STORE *B, STORE *A, RELEASE M
2078 It might appear that this reordering could introduce a deadlock.
2079 However, this cannot happen because if such a deadlock threatened,
2080 the RELEASE would simply complete, thereby avoiding the deadlock.
2082 Why does this work?
2084 One key point is that we are only talking about the CPU doing
2085 the reordering, not the compiler. If the compiler (or, for
2086 that matter, the developer) switched the operations, deadlock
2087 -could- occur.
2089 But suppose the CPU reordered the operations. In this case,
2090 the unlock precedes the lock in the assembly code. The CPU
2091 simply elected to try executing the later lock operation first.
2092 If there is a deadlock, this lock operation will simply spin (or
2093 try to sleep, but more on that later). The CPU will eventually
2094 execute the unlock operation (which preceded the lock operation
2095 in the assembly code), which will unravel the potential deadlock,
2096 allowing the lock operation to succeed.
2098 But what if the lock is a sleeplock? In that case, the code will
2099 try to enter the scheduler, where it will eventually encounter
2100 a memory barrier, which will force the earlier unlock operation
2101 to complete, again unraveling the deadlock. There might be
2102 a sleep-unlock race, but the locking primitive needs to resolve
2103 such races properly in any case.
2105 Locks and semaphores may not provide any guarantee of ordering on UP compiled
2106 systems, and so cannot be counted on in such a situation to actually achieve
2107 anything at all - especially with respect to I/O accesses - unless combined
2108 with interrupt disabling operations.
2110 See also the section on "Inter-CPU acquiring barrier effects".
2113 As an example, consider the following:
2115 *A = a;
2116 *B = b;
2117 ACQUIRE
2118 *C = c;
2119 *D = d;
2120 RELEASE
2121 *E = e;
2122 *F = f;
2124 The following sequence of events is acceptable:
2126 ACQUIRE, {*F,*A}, *E, {*C,*D}, *B, RELEASE
2128 [+] Note that {*F,*A} indicates a combined access.
2130 But none of the following are:
2132 {*F,*A}, *B, ACQUIRE, *C, *D, RELEASE, *E
2133 *A, *B, *C, ACQUIRE, *D, RELEASE, *E, *F
2134 *A, *B, ACQUIRE, *C, RELEASE, *D, *E, *F
2135 *B, ACQUIRE, *C, *D, RELEASE, {*F,*A}, *E
2139 INTERRUPT DISABLING FUNCTIONS
2140 -----------------------------
2142 Functions that disable interrupts (ACQUIRE equivalent) and enable interrupts
2143 (RELEASE equivalent) will act as compiler barriers only. So if memory or I/O
2144 barriers are required in such a situation, they must be provided from some
2145 other means.
2148 SLEEP AND WAKE-UP FUNCTIONS
2149 ---------------------------
2151 Sleeping and waking on an event flagged in global data can be viewed as an
2152 interaction between two pieces of data: the task state of the task waiting for
2153 the event and the global data used to indicate the event. To make sure that
2154 these appear to happen in the right order, the primitives to begin the process
2155 of going to sleep, and the primitives to initiate a wake up imply certain
2156 barriers.
2158 Firstly, the sleeper normally follows something like this sequence of events:
2160 for (;;) {
2161 set_current_state(TASK_UNINTERRUPTIBLE);
2162 if (event_indicated)
2163 break;
2164 schedule();
2165 }
2167 A general memory barrier is interpolated automatically by set_current_state()
2168 after it has altered the task state:
2170 CPU 1
2171 ===============================
2172 set_current_state();
2173 smp_store_mb();
2174 STORE current->state
2175 <general barrier>
2176 LOAD event_indicated
2178 set_current_state() may be wrapped by:
2180 prepare_to_wait();
2181 prepare_to_wait_exclusive();
2183 which therefore also imply a general memory barrier after setting the state.
2184 The whole sequence above is available in various canned forms, all of which
2185 interpolate the memory barrier in the right place:
2187 wait_event();
2188 wait_event_interruptible();
2189 wait_event_interruptible_exclusive();
2190 wait_event_interruptible_timeout();
2191 wait_event_killable();
2192 wait_event_timeout();
2193 wait_on_bit();
2194 wait_on_bit_lock();
2195 wait_event_cmd();
2196 wait_event_exclusive_cmd();
2199 Secondly, code that performs a wake up normally follows something like this:
2201 event_indicated = 1;
2202 wake_up(&event_wait_queue);
2204 or:
2206 event_indicated = 1;
2207 wake_up_process(event_daemon);
2209 A general memory barrier is executed by wake_up() if it wakes something up.
2210 If it doesn't wake anything up then a memory barrier may or may not be
2211 executed; you must not rely on it. The barrier occurs before the task state
2212 is accessed, in particular, it sits between the STORE to indicate the event
2213 and the STORE to set TASK_RUNNING:
2215 CPU 1 (Sleeper) CPU 2 (Waker)
2216 =============================== ===============================
2217 set_current_state(); STORE event_indicated
2218 smp_store_mb(); wake_up();
2219 STORE current->state ...
2220 <general barrier> <general barrier>
2221 LOAD event_indicated if ((LOAD task->state) & TASK_NORMAL)
2222 STORE task->state
2224 where "task" is the thread being woken up and it equals CPU 1's "current".
2226 To repeat, a general memory barrier is guaranteed to be executed by wake_up()
2227 if something is actually awakened, but otherwise there is no such guarantee.
2228 To see this, consider the following sequence of events, where X and Y are both
2229 initially zero:
2231 CPU 1 CPU 2
2232 =============================== ===============================
2233 X = 1; Y = 1;
2234 smp_mb(); wake_up();
2235 LOAD Y LOAD X
2237 If a wakeup does occur, one (at least) of the two loads must see 1. If, on
2238 the other hand, a wakeup does not occur, both loads might see 0.
2240 wake_up_process() always executes a general memory barrier. The barrier again
2241 occurs before the task state is accessed. In particular, if the wake_up() in
2242 the previous snippet were replaced by a call to wake_up_process() then one of
2243 the two loads would be guaranteed to see 1.
2245 The available waker functions include:
2247 complete();
2248 wake_up();
2249 wake_up_all();
2250 wake_up_bit();
2251 wake_up_interruptible();
2252 wake_up_interruptible_all();
2253 wake_up_interruptible_nr();
2254 wake_up_interruptible_poll();
2255 wake_up_interruptible_sync();
2256 wake_up_interruptible_sync_poll();
2257 wake_up_locked();
2258 wake_up_locked_poll();
2259 wake_up_nr();
2260 wake_up_poll();
2261 wake_up_process();
2263 In terms of memory ordering, these functions all provide the same guarantees of
2264 a wake_up() (or stronger).
2266 [!] Note that the memory barriers implied by the sleeper and the waker do _not_
2267 order multiple stores before the wake-up with respect to loads of those stored
2268 values after the sleeper has called set_current_state(). For instance, if the
2269 sleeper does:
2271 set_current_state(TASK_INTERRUPTIBLE);
2272 if (event_indicated)
2273 break;
2274 __set_current_state(TASK_RUNNING);
2275 do_something(my_data);
2277 and the waker does:
2279 my_data = value;
2280 event_indicated = 1;
2281 wake_up(&event_wait_queue);
2283 there's no guarantee that the change to event_indicated will be perceived by
2284 the sleeper as coming after the change to my_data. In such a circumstance, the
2285 code on both sides must interpolate its own memory barriers between the
2286 separate data accesses. Thus the above sleeper ought to do:
2288 set_current_state(TASK_INTERRUPTIBLE);
2289 if (event_indicated) {
2290 smp_rmb();
2291 do_something(my_data);
2292 }
2294 and the waker should do:
2296 my_data = value;
2297 smp_wmb();
2298 event_indicated = 1;
2299 wake_up(&event_wait_queue);
2302 MISCELLANEOUS FUNCTIONS
2303 -----------------------
2305 Other functions that imply barriers:
2307 (*) schedule() and similar imply full memory barriers.
2310 ===================================
2311 INTER-CPU ACQUIRING BARRIER EFFECTS
2312 ===================================
2314 On SMP systems locking primitives give a more substantial form of barrier: one
2315 that does affect memory access ordering on other CPUs, within the context of
2316 conflict on any particular lock.
2319 ACQUIRES VS MEMORY ACCESSES
2320 ---------------------------
2322 Consider the following: the system has a pair of spinlocks (M) and (Q), and
2323 three CPUs; then should the following sequence of events occur:
2325 CPU 1 CPU 2
2326 =============================== ===============================
2327 WRITE_ONCE(*A, a); WRITE_ONCE(*E, e);
2328 ACQUIRE M ACQUIRE Q
2329 WRITE_ONCE(*B, b); WRITE_ONCE(*F, f);
2330 WRITE_ONCE(*C, c); WRITE_ONCE(*G, g);
2331 RELEASE M RELEASE Q
2332 WRITE_ONCE(*D, d); WRITE_ONCE(*H, h);
2334 Then there is no guarantee as to what order CPU 3 will see the accesses to *A
2335 through *H occur in, other than the constraints imposed by the separate locks
2336 on the separate CPUs. It might, for example, see:
2338 *E, ACQUIRE M, ACQUIRE Q, *G, *C, *F, *A, *B, RELEASE Q, *D, *H, RELEASE M
2340 But it won't see any of:
2342 *B, *C or *D preceding ACQUIRE M
2343 *A, *B or *C following RELEASE M
2344 *F, *G or *H preceding ACQUIRE Q
2345 *E, *F or *G following RELEASE Q
2348 =================================
2349 WHERE ARE MEMORY BARRIERS NEEDED?
2350 =================================
2352 Under normal operation, memory operation reordering is generally not going to
2353 be a problem as a single-threaded linear piece of code will still appear to
2354 work correctly, even if it's in an SMP kernel. There are, however, four
2355 circumstances in which reordering definitely _could_ be a problem:
2357 (*) Interprocessor interaction.
2359 (*) Atomic operations.
2361 (*) Accessing devices.
2363 (*) Interrupts.
2366 INTERPROCESSOR INTERACTION
2367 --------------------------
2369 When there's a system with more than one processor, more than one CPU in the
2370 system may be working on the same data set at the same time. This can cause
2371 synchronisation problems, and the usual way of dealing with them is to use
2372 locks. Locks, however, are quite expensive, and so it may be preferable to
2373 operate without the use of a lock if at all possible. In such a case
2374 operations that affect both CPUs may have to be carefully ordered to prevent
2375 a malfunction.
2377 Consider, for example, the R/W semaphore slow path. Here a waiting process is
2378 queued on the semaphore, by virtue of it having a piece of its stack linked to
2379 the semaphore's list of waiting processes:
2381 struct rw_semaphore {
2382 ...
2383 spinlock_t lock;
2384 struct list_head waiters;
2385 };
2387 struct rwsem_waiter {
2388 struct list_head list;
2389 struct task_struct *task;
2390 };
2392 To wake up a particular waiter, the up_read() or up_write() functions have to:
2394 (1) read the next pointer from this waiter's record to know as to where the
2395 next waiter record is;
2397 (2) read the pointer to the waiter's task structure;
2399 (3) clear the task pointer to tell the waiter it has been given the semaphore;
2401 (4) call wake_up_process() on the task; and
2403 (5) release the reference held on the waiter's task struct.
2405 In other words, it has to perform this sequence of events:
2407 LOAD waiter->list.next;
2408 LOAD waiter->task;
2409 STORE waiter->task;
2410 CALL wakeup
2411 RELEASE task
2413 and if any of these steps occur out of order, then the whole thing may
2414 malfunction.
2416 Once it has queued itself and dropped the semaphore lock, the waiter does not
2417 get the lock again; it instead just waits for its task pointer to be cleared
2418 before proceeding. Since the record is on the waiter's stack, this means that
2419 if the task pointer is cleared _before_ the next pointer in the list is read,
2420 another CPU might start processing the waiter and might clobber the waiter's
2421 stack before the up*() function has a chance to read the next pointer.
2423 Consider then what might happen to the above sequence of events:
2425 CPU 1 CPU 2
2426 =============================== ===============================
2427 down_xxx()
2428 Queue waiter
2429 Sleep
2430 up_yyy()
2431 LOAD waiter->task;
2432 STORE waiter->task;
2433 Woken up by other event
2434 <preempt>
2435 Resume processing
2436 down_xxx() returns
2437 call foo()
2438 foo() clobbers *waiter
2439 </preempt>
2440 LOAD waiter->list.next;
2441 --- OOPS ---
2443 This could be dealt with using the semaphore lock, but then the down_xxx()
2444 function has to needlessly get the spinlock again after being woken up.
2446 The way to deal with this is to insert a general SMP memory barrier:
2448 LOAD waiter->list.next;
2449 LOAD waiter->task;
2450 smp_mb();
2451 STORE waiter->task;
2452 CALL wakeup
2453 RELEASE task
2455 In this case, the barrier makes a guarantee that all memory accesses before the
2456 barrier will appear to happen before all the memory accesses after the barrier
2457 with respect to the other CPUs on the system. It does _not_ guarantee that all
2458 the memory accesses before the barrier will be complete by the time the barrier
2459 instruction itself is complete.
2461 On a UP system - where this wouldn't be a problem - the smp_mb() is just a
2462 compiler barrier, thus making sure the compiler emits the instructions in the
2463 right order without actually intervening in the CPU. Since there's only one
2464 CPU, that CPU's dependency ordering logic will take care of everything else.
2467 ATOMIC OPERATIONS
2468 -----------------
2470 While they are technically interprocessor interaction considerations, atomic
2471 operations are noted specially as some of them imply full memory barriers and
2472 some don't, but they're very heavily relied on as a group throughout the
2473 kernel.
2475 See Documentation/atomic_t.txt for more information.
2478 ACCESSING DEVICES
2479 -----------------
2481 Many devices can be memory mapped, and so appear to the CPU as if they're just
2482 a set of memory locations. To control such a device, the driver usually has to
2483 make the right memory accesses in exactly the right order.
2485 However, having a clever CPU or a clever compiler creates a potential problem
2486 in that the carefully sequenced accesses in the driver code won't reach the
2487 device in the requisite order if the CPU or the compiler thinks it is more
2488 efficient to reorder, combine or merge accesses - something that would cause
2489 the device to malfunction.
2491 Inside of the Linux kernel, I/O should be done through the appropriate accessor
2492 routines - such as inb() or writel() - which know how to make such accesses
2493 appropriately sequential. While this, for the most part, renders the explicit
2494 use of memory barriers unnecessary, if the accessor functions are used to refer
2495 to an I/O memory window with relaxed memory access properties, then _mandatory_
2496 memory barriers are required to enforce ordering.
2498 See Documentation/driver-api/device-io.rst for more information.
2501 INTERRUPTS
2502 ----------
2504 A driver may be interrupted by its own interrupt service routine, and thus the
2505 two parts of the driver may interfere with each other's attempts to control or
2506 access the device.
2508 This may be alleviated - at least in part - by disabling local interrupts (a
2509 form of locking), such that the critical operations are all contained within
2510 the interrupt-disabled section in the driver. While the driver's interrupt
2511 routine is executing, the driver's core may not run on the same CPU, and its
2512 interrupt is not permitted to happen again until the current interrupt has been
2513 handled, thus the interrupt handler does not need to lock against that.
2515 However, consider a driver that was talking to an ethernet card that sports an
2516 address register and a data register. If that driver's core talks to the card
2517 under interrupt-disablement and then the driver's interrupt handler is invoked:
2519 LOCAL IRQ DISABLE
2520 writew(ADDR, 3);
2521 writew(DATA, y);
2522 LOCAL IRQ ENABLE
2523 <interrupt>
2524 writew(ADDR, 4);
2525 q = readw(DATA);
2526 </interrupt>
2528 The store to the data register might happen after the second store to the
2529 address register if ordering rules are sufficiently relaxed:
2531 STORE *ADDR = 3, STORE *ADDR = 4, STORE *DATA = y, q = LOAD *DATA
2534 If ordering rules are relaxed, it must be assumed that accesses done inside an
2535 interrupt disabled section may leak outside of it and may interleave with
2536 accesses performed in an interrupt - and vice versa - unless implicit or
2537 explicit barriers are used.
2539 Normally this won't be a problem because the I/O accesses done inside such
2540 sections will include synchronous load operations on strictly ordered I/O
2541 registers that form implicit I/O barriers.
2544 A similar situation may occur between an interrupt routine and two routines
2545 running on separate CPUs that communicate with each other. If such a case is
2546 likely, then interrupt-disabling locks should be used to guarantee ordering.
2549 ==========================
2550 KERNEL I/O BARRIER EFFECTS
2551 ==========================
2553 Interfacing with peripherals via I/O accesses is deeply architecture and device
2554 specific. Therefore, drivers which are inherently non-portable may rely on
2555 specific behaviours of their target systems in order to achieve synchronization
2556 in the most lightweight manner possible. For drivers intending to be portable
2557 between multiple architectures and bus implementations, the kernel offers a
2558 series of accessor functions that provide various degrees of ordering
2559 guarantees:
2561 (*) readX(), writeX():
2563 The readX() and writeX() MMIO accessors take a pointer to the
2564 peripheral being accessed as an __iomem * parameter. For pointers
2565 mapped with the default I/O attributes (e.g. those returned by
2566 ioremap()), the ordering guarantees are as follows:
2568 1. All readX() and writeX() accesses to the same peripheral are ordered
2569 with respect to each other. This ensures that MMIO register accesses
2570 by the same CPU thread to a particular device will arrive in program
2571 order.
2573 2. A writeX() issued by a CPU thread holding a spinlock is ordered
2574 before a writeX() to the same peripheral from another CPU thread
2575 issued after a later acquisition of the same spinlock. This ensures
2576 that MMIO register writes to a particular device issued while holding
2577 a spinlock will arrive in an order consistent with acquisitions of
2578 the lock.
2580 3. A writeX() by a CPU thread to the peripheral will first wait for the
2581 completion of all prior writes to memory either issued by, or
2582 propagated to, the same thread. This ensures that writes by the CPU
2583 to an outbound DMA buffer allocated by dma_alloc_coherent() will be
2584 visible to a DMA engine when the CPU writes to its MMIO control
2585 register to trigger the transfer.
2587 4. A readX() by a CPU thread from the peripheral will complete before
2588 any subsequent reads from memory by the same thread can begin. This
2589 ensures that reads by the CPU from an incoming DMA buffer allocated
2590 by dma_alloc_coherent() will not see stale data after reading from
2591 the DMA engine's MMIO status register to establish that the DMA
2592 transfer has completed.
2594 5. A readX() by a CPU thread from the peripheral will complete before
2595 any subsequent delay() loop can begin execution on the same thread.
2596 This ensures that two MMIO register writes by the CPU to a peripheral
2597 will arrive at least 1us apart if the first write is immediately read
2598 back with readX() and udelay(1) is called prior to the second
2599 writeX():
2601 writel(42, DEVICE_REGISTER_0); // Arrives at the device...
2602 readl(DEVICE_REGISTER_0);
2603 udelay(1);
2604 writel(42, DEVICE_REGISTER_1); // ...at least 1us before this.
2606 The ordering properties of __iomem pointers obtained with non-default
2607 attributes (e.g. those returned by ioremap_wc()) are specific to the
2608 underlying architecture and therefore the guarantees listed above cannot
2609 generally be relied upon for accesses to these types of mappings.
2611 (*) readX_relaxed(), writeX_relaxed():
2613 These are similar to readX() and writeX(), but provide weaker memory
2614 ordering guarantees. Specifically, they do not guarantee ordering with
2615 respect to locking, normal memory accesses or delay() loops (i.e.
2616 bullets 2-5 above) but they are still guaranteed to be ordered with
2617 respect to other accesses from the same CPU thread to the same
2618 peripheral when operating on __iomem pointers mapped with the default
2619 I/O attributes.
2621 (*) readsX(), writesX():
2623 The readsX() and writesX() MMIO accessors are designed for accessing
2624 register-based, memory-mapped FIFOs residing on peripherals that are not
2625 capable of performing DMA. Consequently, they provide only the ordering
2626 guarantees of readX_relaxed() and writeX_relaxed(), as documented above.
2628 (*) inX(), outX():
2630 The inX() and outX() accessors are intended to access legacy port-mapped
2631 I/O peripherals, which may require special instructions on some
2632 architectures (notably x86). The port number of the peripheral being
2633 accessed is passed as an argument.
2635 Since many CPU architectures ultimately access these peripherals via an
2636 internal virtual memory mapping, the portable ordering guarantees
2637 provided by inX() and outX() are the same as those provided by readX()
2638 and writeX() respectively when accessing a mapping with the default I/O
2639 attributes.
2641 Device drivers may expect outX() to emit a non-posted write transaction
2642 that waits for a completion response from the I/O peripheral before
2643 returning. This is not guaranteed by all architectures and is therefore
2644 not part of the portable ordering semantics.
2646 (*) insX(), outsX():
2648 As above, the insX() and outsX() accessors provide the same ordering
2649 guarantees as readsX() and writesX() respectively when accessing a
2650 mapping with the default I/O attributes.
2652 (*) ioreadX(), iowriteX():
2654 These will perform appropriately for the type of access they're actually
2655 doing, be it inX()/outX() or readX()/writeX().
2657 With the exception of the string accessors (insX(), outsX(), readsX() and
2658 writesX()), all of the above assume that the underlying peripheral is
2659 little-endian and will therefore perform byte-swapping operations on big-endian
2660 architectures.
2663 ========================================
2664 ASSUMED MINIMUM EXECUTION ORDERING MODEL
2665 ========================================
2667 It has to be assumed that the conceptual CPU is weakly-ordered but that it will
2668 maintain the appearance of program causality with respect to itself. Some CPUs
2669 (such as i386 or x86_64) are more constrained than others (such as powerpc or
2670 frv), and so the most relaxed case (namely DEC Alpha) must be assumed outside
2671 of arch-specific code.
2673 This means that it must be considered that the CPU will execute its instruction
2674 stream in any order it feels like - or even in parallel - provided that if an
2675 instruction in the stream depends on an earlier instruction, then that
2676 earlier instruction must be sufficiently complete[*] before the later
2677 instruction may proceed; in other words: provided that the appearance of
2678 causality is maintained.
2680 [*] Some instructions have more than one effect - such as changing the
2681 condition codes, changing registers or changing memory - and different
2682 instructions may depend on different effects.
2684 A CPU may also discard any instruction sequence that winds up having no
2685 ultimate effect. For example, if two adjacent instructions both load an
2686 immediate value into the same register, the first may be discarded.
2689 Similarly, it has to be assumed that compiler might reorder the instruction
2690 stream in any way it sees fit, again provided the appearance of causality is
2691 maintained.
2694 ============================
2695 THE EFFECTS OF THE CPU CACHE
2696 ============================
2698 The way cached memory operations are perceived across the system is affected to
2699 a certain extent by the caches that lie between CPUs and memory, and by the
2700 memory coherence system that maintains the consistency of state in the system.
2702 As far as the way a CPU interacts with another part of the system through the
2703 caches goes, the memory system has to include the CPU's caches, and memory
2704 barriers for the most part act at the interface between the CPU and its cache
2705 (memory barriers logically act on the dotted line in the following diagram):
2707 <--- CPU ---> : <----------- Memory ----------->
2708 :
2709 +--------+ +--------+ : +--------+ +-----------+
2710 | | | | : | | | | +--------+
2711 | CPU | | Memory | : | CPU | | | | |
2712 | Core |--->| Access |----->| Cache |<-->| | | |
2713 | | | Queue | : | | | |--->| Memory |
2714 | | | | : | | | | | |
2715 +--------+ +--------+ : +--------+ | | | |
2716 : | Cache | +--------+
2717 : | Coherency |
2718 : | Mechanism | +--------+
2719 +--------+ +--------+ : +--------+ | | | |
2720 | | | | : | | | | | |
2721 | CPU | | Memory | : | CPU | | |--->| Device |
2722 | Core |--->| Access |----->| Cache |<-->| | | |
2723 | | | Queue | : | | | | | |
2724 | | | | : | | | | +--------+
2725 +--------+ +--------+ : +--------+ +-----------+
2726 :
2727 :
2729 Although any particular load or store may not actually appear outside of the
2730 CPU that issued it since it may have been satisfied within the CPU's own cache,
2731 it will still appear as if the full memory access had taken place as far as the
2732 other CPUs are concerned since the cache coherency mechanisms will migrate the
2733 cacheline over to the accessing CPU and propagate the effects upon conflict.
2735 The CPU core may execute instructions in any order it deems fit, provided the
2736 expected program causality appears to be maintained. Some of the instructions
2737 generate load and store operations which then go into the queue of memory
2738 accesses to be performed. The core may place these in the queue in any order
2739 it wishes, and continue execution until it is forced to wait for an instruction
2740 to complete.
2742 What memory barriers are concerned with is controlling the order in which
2743 accesses cross from the CPU side of things to the memory side of things, and
2744 the order in which the effects are perceived to happen by the other observers
2745 in the system.
2747 [!] Memory barriers are _not_ needed within a given CPU, as CPUs always see
2748 their own loads and stores as if they had happened in program order.
2750 [!] MMIO or other device accesses may bypass the cache system. This depends on
2751 the properties of the memory window through which devices are accessed and/or
2752 the use of any special device communication instructions the CPU may have.
2755 CACHE COHERENCY VS DMA
2756 ----------------------
2758 Not all systems maintain cache coherency with respect to devices doing DMA. In
2759 such cases, a device attempting DMA may obtain stale data from RAM because
2760 dirty cache lines may be resident in the caches of various CPUs, and may not
2761 have been written back to RAM yet. To deal with this, the appropriate part of
2762 the kernel must flush the overlapping bits of cache on each CPU (and maybe
2763 invalidate them as well).
2765 In addition, the data DMA'd to RAM by a device may be overwritten by dirty
2766 cache lines being written back to RAM from a CPU's cache after the device has
2767 installed its own data, or cache lines present in the CPU's cache may simply
2768 obscure the fact that RAM has been updated, until at such time as the cacheline
2769 is discarded from the CPU's cache and reloaded. To deal with this, the
2770 appropriate part of the kernel must invalidate the overlapping bits of the
2771 cache on each CPU.
2773 See Documentation/core-api/cachetlb.rst for more information on cache
2774 management.
2777 CACHE COHERENCY VS MMIO
2778 -----------------------
2780 Memory mapped I/O usually takes place through memory locations that are part of
2781 a window in the CPU's memory space that has different properties assigned than
2782 the usual RAM directed window.
2784 Amongst these properties is usually the fact that such accesses bypass the
2785 caching entirely and go directly to the device buses. This means MMIO accesses
2786 may, in effect, overtake accesses to cached memory that were emitted earlier.
2787 A memory barrier isn't sufficient in such a case, but rather the cache must be
2788 flushed between the cached memory write and the MMIO access if the two are in
2789 any way dependent.
2792 =========================
2793 THE THINGS CPUS GET UP TO
2794 =========================
2796 A programmer might take it for granted that the CPU will perform memory
2797 operations in exactly the order specified, so that if the CPU is, for example,
2798 given the following piece of code to execute:
2800 a = READ_ONCE(*A);
2801 WRITE_ONCE(*B, b);
2802 c = READ_ONCE(*C);
2803 d = READ_ONCE(*D);
2804 WRITE_ONCE(*E, e);
2806 they would then expect that the CPU will complete the memory operation for each
2807 instruction before moving on to the next one, leading to a definite sequence of
2808 operations as seen by external observers in the system:
2810 LOAD *A, STORE *B, LOAD *C, LOAD *D, STORE *E.
2813 Reality is, of course, much messier. With many CPUs and compilers, the above
2814 assumption doesn't hold because:
2816 (*) loads are more likely to need to be completed immediately to permit
2817 execution progress, whereas stores can often be deferred without a
2818 problem;
2820 (*) loads may be done speculatively, and the result discarded should it prove
2821 to have been unnecessary;
2823 (*) loads may be done speculatively, leading to the result having been fetched
2824 at the wrong time in the expected sequence of events;
2826 (*) the order of the memory accesses may be rearranged to promote better use
2827 of the CPU buses and caches;
2829 (*) loads and stores may be combined to improve performance when talking to
2830 memory or I/O hardware that can do batched accesses of adjacent locations,
2831 thus cutting down on transaction setup costs (memory and PCI devices may
2832 both be able to do this); and
2834 (*) the CPU's data cache may affect the ordering, and while cache-coherency
2835 mechanisms may alleviate this - once the store has actually hit the cache
2836 - there's no guarantee that the coherency management will be propagated in
2837 order to other CPUs.
2839 So what another CPU, say, might actually observe from the above piece of code
2840 is:
2842 LOAD *A, ..., LOAD {*C,*D}, STORE *E, STORE *B
2844 (Where "LOAD {*C,*D}" is a combined load)
2847 However, it is guaranteed that a CPU will be self-consistent: it will see its
2848 _own_ accesses appear to be correctly ordered, without the need for a memory
2849 barrier. For instance with the following code:
2851 U = READ_ONCE(*A);
2852 WRITE_ONCE(*A, V);
2853 WRITE_ONCE(*A, W);
2854 X = READ_ONCE(*A);
2855 WRITE_ONCE(*A, Y);
2856 Z = READ_ONCE(*A);
2858 and assuming no intervention by an external influence, it can be assumed that
2859 the final result will appear to be:
2861 U == the original value of *A
2862 X == W
2863 Z == Y
2864 *A == Y
2866 The code above may cause the CPU to generate the full sequence of memory
2867 accesses:
2869 U=LOAD *A, STORE *A=V, STORE *A=W, X=LOAD *A, STORE *A=Y, Z=LOAD *A
2871 in that order, but, without intervention, the sequence may have almost any
2872 combination of elements combined or discarded, provided the program's view
2873 of the world remains consistent. Note that READ_ONCE() and WRITE_ONCE()
2874 are -not- optional in the above example, as there are architectures
2875 where a given CPU might reorder successive loads to the same location.
2876 On such architectures, READ_ONCE() and WRITE_ONCE() do whatever is
2877 necessary to prevent this, for example, on Itanium the volatile casts
2878 used by READ_ONCE() and WRITE_ONCE() cause GCC to emit the special ld.acq
2879 and st.rel instructions (respectively) that prevent such reordering.
2881 The compiler may also combine, discard or defer elements of the sequence before
2882 the CPU even sees them.
2884 For instance:
2886 *A = V;
2887 *A = W;
2889 may be reduced to:
2891 *A = W;
2893 since, without either a write barrier or an WRITE_ONCE(), it can be
2894 assumed that the effect of the storage of V to *A is lost. Similarly:
2896 *A = Y;
2897 Z = *A;
2899 may, without a memory barrier or an READ_ONCE() and WRITE_ONCE(), be
2900 reduced to:
2902 *A = Y;
2903 Z = Y;
2905 and the LOAD operation never appear outside of the CPU.
2908 AND THEN THERE'S THE ALPHA
2909 --------------------------
2911 The DEC Alpha CPU is one of the most relaxed CPUs there is. Not only that,
2912 some versions of the Alpha CPU have a split data cache, permitting them to have
2913 two semantically-related cache lines updated at separate times. This is where
2914 the address-dependency barrier really becomes necessary as this synchronises
2915 both caches with the memory coherence system, thus making it seem like pointer
2916 changes vs new data occur in the right order.
2918 The Alpha defines the Linux kernel's memory model, although as of v4.15
2919 the Linux kernel's addition of smp_mb() to READ_ONCE() on Alpha greatly
2920 reduced its impact on the memory model.
2923 VIRTUAL MACHINE GUESTS
2924 ----------------------
2926 Guests running within virtual machines might be affected by SMP effects even if
2927 the guest itself is compiled without SMP support. This is an artifact of
2928 interfacing with an SMP host while running an UP kernel. Using mandatory
2929 barriers for this use-case would be possible but is often suboptimal.
2931 To handle this case optimally, low-level virt_mb() etc macros are available.
2932 These have the same effect as smp_mb() etc when SMP is enabled, but generate
2933 identical code for SMP and non-SMP systems. For example, virtual machine guests
2934 should use virt_mb() rather than smp_mb() when synchronizing against a
2935 (possibly SMP) host.
2937 These are equivalent to smp_mb() etc counterparts in all other respects,
2938 in particular, they do not control MMIO effects: to control
2939 MMIO effects, use mandatory barriers.
2942 ============
2943 EXAMPLE USES
2944 ============
2946 CIRCULAR BUFFERS
2947 ----------------
2949 Memory barriers can be used to implement circular buffering without the need
2950 of a lock to serialise the producer with the consumer. See:
2952 Documentation/core-api/circular-buffers.rst
2954 for details.
2957 ==========
2958 REFERENCES
2959 ==========
2961 Alpha AXP Architecture Reference Manual, Second Edition (Sites & Witek,
2962 Digital Press)
2963 Chapter 5.2: Physical Address Space Characteristics
2964 Chapter 5.4: Caches and Write Buffers
2965 Chapter 5.5: Data Sharing
2966 Chapter 5.6: Read/Write Ordering
2968 AMD64 Architecture Programmer's Manual Volume 2: System Programming
2969 Chapter 7.1: Memory-Access Ordering
2970 Chapter 7.4: Buffering and Combining Memory Writes
2972 ARM Architecture Reference Manual (ARMv8, for ARMv8-A architecture profile)
2973 Chapter B2: The AArch64 Application Level Memory Model
2975 IA-32 Intel Architecture Software Developer's Manual, Volume 3:
2976 System Programming Guide
2977 Chapter 7.1: Locked Atomic Operations
2978 Chapter 7.2: Memory Ordering
2979 Chapter 7.4: Serializing Instructions
2981 The SPARC Architecture Manual, Version 9
2982 Chapter 8: Memory Models
2983 Appendix D: Formal Specification of the Memory Models
2984 Appendix J: Programming with the Memory Models
2986 Storage in the PowerPC (Stone and Fitzgerald)
2988 UltraSPARC Programmer Reference Manual
2989 Chapter 5: Memory Accesses and Cacheability
2990 Chapter 15: Sparc-V9 Memory Models
2992 UltraSPARC III Cu User's Manual
2993 Chapter 9: Memory Models
2995 UltraSPARC IIIi Processor User's Manual
2996 Chapter 8: Memory Models
2998 UltraSPARC Architecture 2005
2999 Chapter 9: Memory
3000 Appendix D: Formal Specifications of the Memory Models
3002 UltraSPARC T1 Supplement to the UltraSPARC Architecture 2005
3003 Chapter 8: Memory Models
3004 Appendix F: Caches and Cache Coherency
3006 Solaris Internals, Core Kernel Architecture, p63-68:
3007 Chapter 3.3: Hardware Considerations for Locks and
3008 Synchronization
3010 Unix Systems for Modern Architectures, Symmetric Multiprocessing and Caching
3011 for Kernel Programmers:
3012 Chapter 13: Other Memory Models
3014 Intel Itanium Architecture Software Developer's Manual: Volume 1:
3015 Section 2.6: Speculation
3016 Section 4.4: Memory Access

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

리눅스 커널 메모리 배리어 전문

1-3016

아래 한국어 전문은 동일한 Linux v6.18.37 source tree에 포함된 kernel.org 공식 ko_KR 번역입니다. 번역 유지관리 안내, 문단, 코드, 함수명, symbol, 표, 참고 문헌을 빠짐없이 보존했습니다.

NOTE:
This is a version of Documentation/memory-barriers.txt translated into Korean.
This document is maintained by SeongJae Park <[email protected]>.
If you find any difference between this document and the original file or
a problem with the translation, please contact the maintainer of this file.

Please also note that the purpose of this file is to be easier to
read for non English (read: Korean) speakers and is not intended as
a fork.  So if you have any comments or updates for this file please
update the original English file first.  The English version is
definitive, and readers should look there if they have any doubt.

=================================
이 문서는
Documentation/memory-barriers.txt
의 한글 번역입니다.

역자: 박성재 <[email protected]>
=================================


			 =========================
			 리눅스 커널 메모리 배리어
			 =========================

저자: David Howells <[email protected]>
      Paul E. McKenney <[email protected]>
      Will Deacon <[email protected]>
      Peter Zijlstra <[email protected]>

========
면책조항
========

이 문서는 명세서가 아닙니다; 이 문서는 완벽하지 않은데, 간결성을 위해 의도된
부분도 있고, 의도하진 않았지만 사람에 의해 쓰였다보니 불완전한 부분도 있습니다.
이 문서는 리눅스에서 제공하는 다양한 메모리 배리어들을 사용하기 위한
안내서입니다만, 뭔가 이상하다 싶으면 (그런게 많을 겁니다) 질문을 부탁드립니다.
일부 이상한 점들은 공식적인 메모리 일관성 모델과 tools/memory-model/ 에 있는
관련 문서를 참고해서 해결될 수 있을 겁니다.  그러나, 이 메모리 모델조차도 그
관리자들의 의견의 집합으로 봐야지, 절대 옳은 예언자로 신봉해선 안될 겁니다.

다시 말하지만, 이 문서는 리눅스가 하드웨어에 기대하는 사항에 대한 명세서가
아닙니다.

이 문서의 목적은 두가지입니다:

 (1) 어떤 특정 배리어에 대해 기대할 수 있는 최소한의 기능을 명세하기 위해서,
     그리고

 (2) 사용 가능한 배리어들에 대해 어떻게 사용해야 하는지에 대한 안내를 제공하기
     위해서.

어떤 아키텍쳐는 특정한 배리어들에 대해서는 여기서 이야기하는 최소한의
요구사항들보다 많은 기능을 제공할 수도 있습니다만, 여기서 이야기하는
요구사항들을 충족하지 않는 아키텍쳐가 있다면 그 아키텍쳐가 잘못된 것이란 점을
알아두시기 바랍니다.

또한, 특정 아키텍쳐에서 일부 배리어는 해당 아키텍쳐의 특수한 동작 방식으로 인해
해당 배리어의 명시적 사용이 불필요해서 no-op 이 될수도 있음을 알아두시기
바랍니다.

역자: 본 번역 역시 완벽하지 않은데, 이 역시 부분적으로는 의도된 것이기도
합니다.  여타 기술 문서들이 그렇듯 완벽한 이해를 위해서는 번역문과 원문을 함께
읽으시되 번역문을 하나의 가이드로 활용하시길 추천드리며, 발견되는 오역 등에
대해서는 언제든 의견을 부탁드립니다.  과한 번역으로 인한 오해를 최소화하기 위해
애매한 부분이 있을 경우에는 어색함이 있더라도 원래의 용어를 차용합니다.


=====
목차:
=====

 (*) 추상 메모리 액세스 모델.

     - 디바이스 오퍼레이션.
     - 보장사항.

 (*) 메모리 배리어란 무엇인가?

     - 메모리 배리어의 종류.
     - 메모리 배리어에 대해 가정해선 안될 것.
     - 주소 데이터 의존성 배리어 (역사적).
     - 컨트롤 의존성.
     - SMP 배리어 짝맞추기.
     - 메모리 배리어 시퀀스의 예.
     - 읽기 메모리 배리어 vs 로드 예측.
     - Multicopy 원자성.

 (*) 명시적 커널 배리어.

     - 컴파일러 배리어.
     - CPU 메모리 배리어.

 (*) 암묵적 커널 메모리 배리어.

     - 락 Acquisition 함수.
     - 인터럽트 비활성화 함수.
     - 슬립과 웨이크업 함수.
     - 그외의 함수들.

 (*) CPU 간 ACQUIRING 배리어의 효과.

     - Acquire vs 메모리 액세스.

 (*) 메모리 배리어가 필요한 곳

     - 프로세서간 상호 작용.
     - 어토믹 오퍼레이션.
     - 디바이스 액세스.
     - 인터럽트.

 (*) 커널 I/O 배리어의 효과.

 (*) 가정되는 가장 완화된 실행 순서 모델.

 (*) CPU 캐시의 영향.

     - 캐시 일관성.
     - 캐시 일관성 vs DMA.
     - 캐시 일관성 vs MMIO.

 (*) CPU 들이 저지르는 일들.

     - 그리고, Alpha 가 있다.
     - 가상 머신 게스트.

 (*) 사용 예.

     - 순환식 버퍼.

 (*) 참고 문헌.


=======================
추상 메모리 액세스 모델
=======================

다음과 같이 추상화된 시스템 모델을 생각해 봅시다:

		            :                :
		            :                :
		            :                :
		+-------+   :   +--------+   :   +-------+
		|       |   :   |        |   :   |       |
		|       |   :   |        |   :   |       |
		| CPU 1 |<----->| Memory |<----->| CPU 2 |
		|       |   :   |        |   :   |       |
		|       |   :   |        |   :   |       |
		+-------+   :   +--------+   :   +-------+
		    ^       :       ^        :       ^
		    |       :       |        :       |
		    |       :       |        :       |
		    |       :       v        :       |
		    |       :   +--------+   :       |
		    |       :   |        |   :       |
		    |       :   |        |   :       |
		    +---------->| Device |<----------+
		            :   |        |   :
		            :   |        |   :
		            :   +--------+   :
		            :                :

프로그램은 여러 메모리 액세스 오퍼레이션을 발생시키고, 각각의 CPU 는 그런
프로그램들을 실행합니다.  추상화된 CPU 모델에서 메모리 오퍼레이션들의 순서는
매우 완화되어 있고, CPU 는 프로그램이 인과관계를 어기지 않는 상태로 관리된다고
보일 수만 있다면 메모리 오퍼레이션을 자신이 원하는 어떤 순서대로든 재배치해
동작시킬 수 있습니다.  비슷하게, 컴파일러 또한 프로그램의 정상적 동작을 해치지
않는 한도 내에서는 어떤 순서로든 자신이 원하는 대로 인스트럭션을 재배치 할 수
있습니다.

따라서 위의 다이어그램에서 한 CPU가 동작시키는 메모리 오퍼레이션이 만들어내는
변화는 해당 오퍼레이션이 CPU 와 시스템의 다른 부분들 사이의 인터페이스(점선)를
지나가면서 시스템의 나머지 부분들에 인지됩니다.


예를 들어, 다음의 일련의 이벤트들을 생각해 봅시다:

	CPU 1		CPU 2
	===============	===============
	{ A == 1; B == 2 }
	A = 3;		x = B;
	B = 4;		y = A;

다이어그램의 가운데에 위치한 메모리 시스템에 보여지게 되는 액세스들은 다음의 총
24개의 조합으로 재구성될 수 있습니다:

	STORE A=3,	STORE B=4,	y=LOAD A->3,	x=LOAD B->4
	STORE A=3,	STORE B=4,	x=LOAD B->4,	y=LOAD A->3
	STORE A=3,	y=LOAD A->3,	STORE B=4,	x=LOAD B->4
	STORE A=3,	y=LOAD A->3,	x=LOAD B->2,	STORE B=4
	STORE A=3,	x=LOAD B->2,	STORE B=4,	y=LOAD A->3
	STORE A=3,	x=LOAD B->2,	y=LOAD A->3,	STORE B=4
	STORE B=4,	STORE A=3,	y=LOAD A->3,	x=LOAD B->4
	STORE B=4, ...
	...

따라서 다음의 네가지 조합의 값들이 나올 수 있습니다:

	x == 2, y == 1
	x == 2, y == 3
	x == 4, y == 1
	x == 4, y == 3


한발 더 나아가서, 한 CPU 가 메모리 시스템에 반영한 스토어 오퍼레이션들의 결과는
다른 CPU 에서의 로드 오퍼레이션을 통해 인지되는데, 이 때 스토어가 반영된 순서와
다른 순서로 인지될 수도 있습니다.


예로, 아래의 일련의 이벤트들을 생각해 봅시다:

	CPU 1		CPU 2
	===============	===============
	{ A == 1, B == 2, C == 3, P == &A, Q == &C }
	B = 4;		Q = P;
	P = &B		D = *Q;

D 로 읽혀지는 값은 CPU 2 에서 P 로부터 읽혀진 주소값에 의존적이기 때문에 여기엔
분명한 주소 의존성이 있습니다.  하지만 이 이벤트들의 실행 결과로는 아래의
결과들이 모두 나타날 수 있습니다:

	(Q == &A) and (D == 1)
	(Q == &B) and (D == 2)
	(Q == &B) and (D == 4)

CPU 2 는 *Q 의 로드를 요청하기 전에 P 를 Q 에 넣기 때문에 D 에 C 를 집어넣는
일은 없음을 알아두세요.


디바이스 오퍼레이션
-------------------

일부 디바이스는 자신의 컨트롤 인터페이스를 메모리의 특정 영역으로 매핑해서
제공하는데(Memory mapped I/O), 해당 컨트롤 레지스터에 접근하는 순서는 매우
중요합니다.  예를 들어, 어드레스 포트 레지스터 (A) 와 데이터 포트 레지스터 (D)
를 통해 접근되는 내부 레지스터 집합을 갖는 이더넷 카드를 생각해 봅시다.  내부의
5번 레지스터를 읽기 위해 다음의 코드가 사용될 수 있습니다:

	*A = 5;
	x = *D;

하지만, 이건 다음의 두 조합 중 하나로 만들어질 수 있습니다:

	STORE *A = 5, x = LOAD *D
	x = LOAD *D, STORE *A = 5

두번째 조합은 데이터를 읽어온 _후에_ 주소를 설정하므로, 오동작을 일으킬 겁니다.


보장사항
--------

CPU 에게 기대할 수 있는 최소한의 보장사항 몇가지가 있습니다:

 (*) 어떤 CPU 든, 의존성이 존재하는 메모리 액세스들은 해당 CPU 자신에게
     있어서는 순서대로 메모리 시스템에 수행 요청됩니다. 즉, 다음에 대해서:

	Q = READ_ONCE(P); D = READ_ONCE(*Q);

     CPU 는 다음과 같은 메모리 오퍼레이션 시퀀스를 수행 요청합니다:

	Q = LOAD P, D = LOAD *Q

     그리고 그 시퀀스 내에서의 순서는 항상 지켜집니다.  하지만, DEC Alpha 에서
     READ_ONCE() 는 메모리 배리어 명령도 내게 되어 있어서, DEC Alpha CPU 는
     다음과 같은 메모리 오퍼레이션들을 내놓게 됩니다:

	Q = LOAD P, MEMORY_BARRIER, D = LOAD *Q, MEMORY_BARRIER

     DEC Alpha 에서 수행되든 아니든, READ_ONCE() 는 컴파일러로부터의 악영향
     또한 제거합니다.

 (*) 특정 CPU 내에서 겹치는 영역의 메모리에 행해지는 로드와 스토어 들은 해당
     CPU 안에서는 순서가 바뀌지 않은 것으로 보여집니다.  즉, 다음에 대해서:

	a = READ_ONCE(*X); WRITE_ONCE(*X, b);

     CPU 는 다음의 메모리 오퍼레이션 시퀀스만을 메모리에 요청할 겁니다:

	a = LOAD *X, STORE *X = b

     그리고 다음에 대해서는:

	WRITE_ONCE(*X, c); d = READ_ONCE(*X);

     CPU 는 다음의 수행 요청만을 만들어 냅니다:

	STORE *X = c, d = LOAD *X

     (로드 오퍼레이션과 스토어 오퍼레이션이 겹치는 메모리 영역에 대해
     수행된다면 해당 오퍼레이션들은 겹친다고 표현됩니다).

그리고 _반드시_ 또는 _절대로_ 가정하거나 가정하지 말아야 하는 것들이 있습니다:

 (*) 컴파일러가 READ_ONCE() 나 WRITE_ONCE() 로 보호되지 않은 메모리 액세스를
     당신이 원하는 대로 할 것이라는 가정은 _절대로_ 해선 안됩니다.  그것들이
     없다면, 컴파일러는 컴파일러 배리어 섹션에서 다루게 될, 모든 "창의적인"
     변경들을 만들어낼 권한을 갖게 됩니다.

 (*) 개별적인 로드와 스토어들이 주어진 순서대로 요청될 것이라는 가정은 _절대로_
     하지 말아야 합니다.  이 말은 곧:

	X = *A; Y = *B; *D = Z;

     는 다음의 것들 중 어느 것으로든 만들어질 수 있다는 의미입니다:

	X = LOAD *A,  Y = LOAD *B,  STORE *D = Z
	X = LOAD *A,  STORE *D = Z, Y = LOAD *B
	Y = LOAD *B,  X = LOAD *A,  STORE *D = Z
	Y = LOAD *B,  STORE *D = Z, X = LOAD *A
	STORE *D = Z, X = LOAD *A,  Y = LOAD *B
	STORE *D = Z, Y = LOAD *B,  X = LOAD *A

 (*) 겹치는 메모리 액세스들은 합쳐지거나 버려질 수 있음을 _반드시_ 가정해야
     합니다.  다음의 코드는:

	X = *A; Y = *(A + 4);

     다음의 것들 중 뭐든 될 수 있습니다:

	X = LOAD *A; Y = LOAD *(A + 4);
	Y = LOAD *(A + 4); X = LOAD *A;
	{X, Y} = LOAD {*A, *(A + 4) };

     그리고:

	*A = X; *(A + 4) = Y;

     는 다음 중 뭐든 될 수 있습니다:

	STORE *A = X; STORE *(A + 4) = Y;
	STORE *(A + 4) = Y; STORE *A = X;
	STORE {*A, *(A + 4) } = {X, Y};

그리고 보장사항에 반대되는 것들(anti-guarantees)이 있습니다:

 (*) 이 보장사항들은 bitfield 에는 적용되지 않는데, 컴파일러들은 bitfield 를
     수정하는 코드를 생성할 때 원자성 없는(non-atomic) 읽고-수정하고-쓰는
     인스트럭션들의 조합을 만드는 경우가 많기 때문입니다.  병렬 알고리즘의
     동기화에 bitfield 를 사용하려 하지 마십시오.

 (*) bitfield 들이 여러 락으로 보호되는 경우라 하더라도, 하나의 bitfield 의
     모든 필드들은 하나의 락으로 보호되어야 합니다.  만약 한 bitfield 의 두
     필드가 서로 다른 락으로 보호된다면, 컴파일러의 원자성 없는
     읽고-수정하고-쓰는 인스트럭션 조합은 한 필드에의 업데이트가 근처의
     필드에도 영향을 끼치게 할 수 있습니다.

 (*) 이 보장사항들은 적절하게 정렬되고 크기가 잡힌 스칼라 변수들에 대해서만
     적용됩니다.  "적절하게 크기가 잡힌" 이라함은 현재로써는 "char", "short",
     "int" 그리고 "long" 과 같은 크기의 변수들을 의미합니다.  "적절하게 정렬된"
     은 자연스런 정렬을 의미하는데, 따라서 "char" 에 대해서는 아무 제약이 없고,
     "short" 에 대해서는 2바이트 정렬을, "int" 에는 4바이트 정렬을, 그리고
     "long" 에 대해서는 32-bit 시스템인지 64-bit 시스템인지에 따라 4바이트 또는
     8바이트 정렬을 의미합니다.  이 보장사항들은 C11 표준에서 소개되었으므로,
     C11 전의 오래된 컴파일러(예를 들어, gcc 4.6) 를 사용할 때엔 주의하시기
     바랍니다.  표준에 이 보장사항들은 "memory location" 을 정의하는 3.14
     섹션에 다음과 같이 설명되어 있습니다:
     (역자: 인용문이므로 번역하지 않습니다)

	memory location
		either an object of scalar type, or a maximal sequence
		of adjacent bit-fields all having nonzero width

		NOTE 1: Two threads of execution can update and access
		separate memory locations without interfering with
		each other.

		NOTE 2: A bit-field and an adjacent non-bit-field member
		are in separate memory locations. The same applies
		to two bit-fields, if one is declared inside a nested
		structure declaration and the other is not, or if the two
		are separated by a zero-length bit-field declaration,
		or if they are separated by a non-bit-field member
		declaration. It is not safe to concurrently update two
		bit-fields in the same structure if all members declared
		between them are also bit-fields, no matter what the
		sizes of those intervening bit-fields happen to be.


=========================
메모리 배리어란 무엇인가?
=========================

앞에서 봤듯이, 상호간 의존성이 없는 메모리 오퍼레이션들은 실제로는 무작위적
순서로 수행될 수 있으며, 이는 CPU 와 CPU 간의 상호작용이나 I/O 에 문제가 될 수
있습니다.  따라서 컴파일러와 CPU 가 순서를 바꾸는데 제약을 걸 수 있도록 개입할
수 있는 어떤 방법이 필요합니다.

메모리 배리어는 그런 개입 수단입니다.  메모리 배리어는 배리어를 사이에 둔 앞과
뒤 양측의 메모리 오퍼레이션들 간에 부분적 순서가 존재하도록 하는 효과를 줍니다.

시스템의 CPU 들과 여러 디바이스들은 성능을 올리기 위해 명령어 재배치, 실행
유예, 메모리 오퍼레이션들의 조합, 예측적 로드(speculative load), 브랜치
예측(speculative branch prediction), 다양한 종류의 캐싱(caching) 등의 다양한
트릭을 사용할 수 있기 때문에 이런 강제력은 중요합니다.  메모리 배리어들은 이런
트릭들을 무효로 하거나 억제하는 목적으로 사용되어져서 코드가 여러 CPU 와
디바이스들 간의 상호작용을 정상적으로 제어할 수 있게 해줍니다.


메모리 배리어의 종류
--------------------

메모리 배리어는 네개의 기본 타입으로 분류됩니다:

 (1) 쓰기 (또는 스토어) 메모리 배리어.

     쓰기 메모리 배리어는 시스템의 다른 컴포넌트들에 해당 배리어보다 앞서
     명시된 모든 STORE 오퍼레이션들이 해당 배리어 뒤에 명시된 모든 STORE
     오퍼레이션들보다 먼저 수행된 것으로 보일 것을 보장합니다.

     쓰기 배리어는 스토어 오퍼레이션들에 대한 부분적 순서 세우기입니다; 로드
     오퍼레이션들에 대해서는 어떤 영향도 끼치지 않습니다.

     CPU 는 시간의 흐름에 따라 메모리 시스템에 일련의 스토어 오퍼레이션들을
     하나씩 요청해 집어넣습니다.  쓰기 배리어 앞의 모든 스토어 오퍼레이션들은
     쓰기 배리어 뒤의 모든 스토어 오퍼레이션들보다 _앞서_ 수행될 겁니다.

     [!] 쓰기 배리어들은 읽기 또는 주소 의존성 배리어와 함께 짝을 맞춰
     사용되어야만 함을 알아두세요; "SMP 배리어 짝맞추기" 서브섹션을 참고하세요.


 (2) 주소 의존성 배리어 (역사적).

     주소 의존성 배리어는 읽기 배리어의 보다 완화된 형태입니다.  두개의 로드
     오퍼레이션이 있고 두번째 것이 첫번째 것의 결과에 의존하고 있을 때(예:
     두번째 로드가 참조할 주소를 첫번째 로드가 읽는 경우), 두번째 로드가 읽어올
     데이터는 첫번째 로드에 의해 그 주소가 얻어진 뒤에 업데이트 됨을 보장하기
     위해서 주소 의존성 배리어가 필요할 수 있습니다.

     주소 의존성 배리어는 상호 의존적인 로드 오퍼레이션들 사이의 부분적 순서
     세우기입니다; 스토어 오퍼레이션들이나 독립적인 로드들, 또는 중복되는
     로드들에 대해서는 어떤 영향도 끼치지 않습니다.

     (1) 에서 언급했듯이, 시스템의 CPU 들은 메모리 시스템에 일련의 스토어
     오퍼레이션들을 던져 넣고 있으며, 거기에 관심이 있는 다른 CPU 는 그
     오퍼레이션들을 메모리 시스템이 실행한 결과를 인지할 수 있습니다.  이처럼
     다른 CPU 의 스토어 오퍼레이션의 결과에 관심을 두고 있는 CPU 가 수행 요청한
     주소 의존성 배리어는, 배리어 앞의 어떤 로드 오퍼레이션이 다른 CPU 에서
     던져 넣은 스토어 오퍼레이션과 같은 영역을 향했다면, 그런 스토어
     오퍼레이션들이 만들어내는 결과가 주소 의존성 배리어 뒤의 로드
     오퍼레이션들에게는 보일 것을 보장합니다.

     이 순서 세우기 제약에 대한 그림을 보기 위해선 "메모리 배리어 시퀀스의 예"
     서브섹션을 참고하시기 바랍니다.

     [!] 첫번째 로드는 반드시 _주소_ 의존성을 가져야지 컨트롤 의존성을 가져야
     하는게 아님을 알아두십시오.  만약 두번째 로드를 위한 주소가 첫번째 로드에
     의존적이지만 그 의존성은 조건적이지 그 주소 자체를 가져오는게 아니라면,
     그것은 _컨트롤_ 의존성이고, 이 경우에는 읽기 배리어나 그보다 강력한
     무언가가 필요합니다.  더 자세한 내용을 위해서는 "컨트롤 의존성" 서브섹션을
     참고하시기 바랍니다.

     [!] 주소 의존성 배리어는 보통 쓰기 배리어들과 함께 짝을 맞춰 사용되어야
     합니다; "SMP 배리어 짝맞추기" 서브섹션을 참고하세요.

     [!] 커널 v5.9 릴리즈에서 명시적 주소 의존성 배리어를 위한 커널 API 들이
     삭제되었습니다.  오늘날에는 공유된 변수들의 로드를 표시하는 READ_ONCE() 나
     rcu_dereference() 와 같은 API 들은 묵시적으로 주소 의존성 배리어를 제공합니다.


 (3) 읽기 (또는 로드) 메모리 배리어.

     읽기 배리어는 주소 의존성 배리어 기능의 보장사항에 더해서 배리어보다 앞서
     명시된 모든 LOAD 오퍼레이션들이 배리어 뒤에 명시되는 모든 LOAD
     오퍼레이션들보다 먼저 행해진 것으로 시스템의 다른 컴포넌트들에 보여질 것을
     보장합니다.

     읽기 배리어는 로드 오퍼레이션에 행해지는 부분적 순서 세우기입니다; 스토어
     오퍼레이션에 대해서는 어떤 영향도 끼치지 않습니다.

     읽기 메모리 배리어는 주소 의존성 배리어를 내장하므로 주소 의존성 배리어를
     대신할 수 있습니다.

     [!] 읽기 배리어는 일반적으로 쓰기 배리어들과 함께 짝을 맞춰 사용되어야
     합니다; "SMP 배리어 짝맞추기" 서브섹션을 참고하세요.


 (4) 범용 메모리 배리어.

     범용(general) 메모리 배리어는 배리어보다 앞서 명시된 모든 LOAD 와 STORE
     오퍼레이션들이 배리어 뒤에 명시된 모든 LOAD 와 STORE 오퍼레이션들보다
     먼저 수행된 것으로 시스템의 나머지 컴포넌트들에 보이게 됨을 보장합니다.

     범용 메모리 배리어는 로드와 스토어 모두에 대한 부분적 순서 세우기입니다.

     범용 메모리 배리어는 읽기 메모리 배리어, 쓰기 메모리 배리어 모두를
     내장하므로, 두 배리어를 모두 대신할 수 있습니다.


그리고 두개의 명시적이지 않은 타입이 있습니다:

 (5) ACQUIRE 오퍼레이션.

     이 타입의 오퍼레이션은 단방향의 투과성 배리어처럼 동작합니다.  ACQUIRE
     오퍼레이션 뒤의 모든 메모리 오퍼레이션들이 ACQUIRE 오퍼레이션 후에
     일어난 것으로 시스템의 나머지 컴포넌트들에 보이게 될 것이 보장됩니다.
     LOCK 오퍼레이션과 smp_load_acquire(), smp_cond_load_acquire() 오퍼레이션도
     ACQUIRE 오퍼레이션에 포함됩니다.

     ACQUIRE 오퍼레이션 앞의 메모리 오퍼레이션들은 ACQUIRE 오퍼레이션 완료 후에
     수행된 것처럼 보일 수 있습니다.

     ACQUIRE 오퍼레이션은 거의 항상 RELEASE 오퍼레이션과 짝을 지어 사용되어야
     합니다.


 (6) RELEASE 오퍼레이션.

     이 타입의 오퍼레이션들도 단방향 투과성 배리어처럼 동작합니다.  RELEASE
     오퍼레이션 앞의 모든 메모리 오퍼레이션들은 RELEASE 오퍼레이션 전에 완료된
     것으로 시스템의 다른 컴포넌트들에 보여질 것이 보장됩니다.  UNLOCK 류의
     오퍼레이션들과 smp_store_release() 오퍼레이션도 RELEASE 오퍼레이션의
     일종입니다.

     RELEASE 오퍼레이션 뒤의 메모리 오퍼레이션들은 RELEASE 오퍼레이션이
     완료되기 전에 행해진 것처럼 보일 수 있습니다.

     ACQUIRE 와 RELEASE 오퍼레이션의 사용은 일반적으로 다른 메모리 배리어의
     필요성을 없앱니다.  또한, RELEASE+ACQUIRE 조합은 범용 메모리 배리어처럼
     동작할 것을 보장하지 -않습니다-.  하지만, 어떤 변수에 대한 RELEASE
     오퍼레이션을 앞서는 메모리 액세스들의 수행 결과는 이 RELEASE 오퍼레이션을
     뒤이어 같은 변수에 대해 수행된 ACQUIRE 오퍼레이션을 뒤따르는 메모리
     액세스에는 보여질 것이 보장됩니다.  다르게 말하자면, 주어진 변수의
     크리티컬 섹션에서는, 해당 변수에 대한 앞의 크리티컬 섹션에서의 모든
     액세스들이 완료되었을 것을 보장합니다.

     즉, ACQUIRE 는 최소한의 "취득" 동작처럼, 그리고 RELEASE 는 최소한의 "공개"
     처럼 동작한다는 의미입니다.

atomic_t.txt 에 설명된 어토믹 오퍼레이션들 중 일부는 완전히 순서잡힌 것들과
(배리어를 사용하지 않는) 완화된 순서의 것들 외에 ACQUIRE 와 RELEASE 부류의
것들도 존재합니다.  로드와 스토어를 모두 수행하는 조합된 어토믹 오퍼레이션에서,
ACQUIRE 는 해당 오퍼레이션의 로드 부분에만 적용되고 RELEASE 는 해당
오퍼레이션의 스토어 부분에만 적용됩니다.

메모리 배리어들은 두 CPU 간, 또는 CPU 와 디바이스 간에 상호작용의 가능성이 있을
때에만 필요합니다.  만약 어떤 코드에 그런 상호작용이 없을 것이 보장된다면, 해당
코드에서는 메모리 배리어를 사용할 필요가 없습니다.


이것들은 _최소한의_ 보장사항들임을 알아두세요.  다른 아키텍쳐에서는 더 강력한
보장사항을 제공할 수도 있습니다만, 그런 보장사항은 아키텍쳐 종속적 코드 이외의
부분에서는 신뢰되지 _않을_ 겁니다.


메모리 배리어에 대해 가정해선 안될 것
-------------------------------------

리눅스 커널 메모리 배리어들이 보장하지 않는 것들이 있습니다:

 (*) 메모리 배리어 앞에서 명시된 어떤 메모리 액세스도 메모리 배리어 명령의 수행
     완료 시점까지 _완료_ 될 것이란 보장은 없습니다; 배리어가 하는 일은 CPU 의
     액세스 큐에 특정 타입의 액세스들은 넘을 수 없는 선을 긋는 것으로 생각될 수
     있습니다.

 (*) 한 CPU 에서 메모리 배리어를 수행하는게 시스템의 다른 CPU 나 하드웨어에
     어떤 직접적인 영향을 끼친다는 보장은 존재하지 않습니다.  배리어 수행이
     만드는 간접적 영향은 두번째 CPU 가 첫번째 CPU 의 액세스들의 결과를
     바라보는 순서가 됩니다만, 다음 항목을 보세요:

 (*) 첫번째 CPU 가 두번째 CPU 의 메모리 액세스들의 결과를 바라볼 때, _설령_
     두번째 CPU 가 메모리 배리어를 사용한다 해도, 첫번째 CPU _또한_ 그에 맞는
     메모리 배리어를 사용하지 않는다면 ("SMP 배리어 짝맞추기" 서브섹션을
     참고하세요) 그 결과가 올바른 순서로 보여진다는 보장은 없습니다.

 (*) CPU 바깥의 하드웨어[*] 가 메모리 액세스들의 순서를 바꾸지 않는다는 보장은
     존재하지 않습니다.  CPU 캐시 일관성 메커니즘은 메모리 배리어의 간접적
     영향을 CPU 사이에 전파하긴 하지만, 순서대로 전파하지는 않을 수 있습니다.

	[*] 버스 마스터링 DMA 와 일관성에 대해서는 다음을 참고하시기 바랍니다:

	    Documentation/driver-api/pci/pci.rst
	    Documentation/core-api/dma-api-howto.rst
	    Documentation/core-api/dma-api.rst


주소 의존성 배리어 (역사적)
---------------------------

리눅스 커널 v4.15 기준으로, smp_mb() 가 DEC Alpha 용 READ_ONCE() 코드에
추가되었는데, 이는 이 섹션에 주의를 기울여야 하는 사람들은 DEC Alpha 아키텍쳐
전용 코드를 만드는 사람들과 READ_ONCE() 자체를 만드는 사람들 뿐임을 의미합니다.
그런 분들을 위해, 그리고 역사에 관심 있는 분들을 위해, 여기 주소 의존성
배리어에 대한 이야기를 적습니다.

[!] 주소 의존성은 로드에서 로드로와 로드에서 스토어로의 관계들 모두에서
나타나지만, 주소 의존성 배리어는 로드에서 스토어로의 상황에서는 필요하지
않습니다.

주소 의존성 배리어의 사용에 있어 지켜야 하는 사항들은 약간 미묘하고, 데이터
의존성 배리어가 사용되어야 하는 상황도 항상 명백하지는 않습니다.  설명을 위해
다음의 이벤트 시퀀스를 생각해 봅시다:

	CPU 1		      CPU 2
	===============	      ===============
	{ A == 1, B == 2, C == 3, P == &A, Q == &C }
	B = 4;
	<쓰기 배리어>
	WRITE_ONCE(P, &B)
			      Q = READ_ONCE_OLD(P);
			      D = *Q;

[!] READ_ONCE_OLD() 는 4.15 커널 전의 버전에서의, 주소 의존성 배리어를 내포하지
않는 READ_ONCE() 에 해당합니다.

여기엔 분명한 주소 의존성이 존재하므로, 이 시퀀스가 끝났을 때 Q 는 &A 또는 &B
일 것이고, 따라서:

	(Q == &A) 는 (D == 1) 를,
	(Q == &B) 는 (D == 4) 를 의미합니다.

하지만!  CPU 2 는 B 의 업데이트를 인식하기 전에 P 의 업데이트를 인식할 수 있고,
따라서 다음의 결과가 가능합니다:

	(Q == &B) and (D == 2) ????

이런 결과는 일관성이나 인과 관계 유지가 실패한 것처럼 보일 수도 있겠지만,
그렇지 않습니다, 그리고 이 현상은 (DEC Alpha 와 같은) 여러 CPU 에서 실제로
발견될 수 있습니다.

이 문제 상황을 제대로 해결하기 위해, READ_ONCE() 는 커널 v4.15 릴리즈 부터
묵시적 주소 의존성 배리어를 제공합니다:

	CPU 1		      CPU 2
	===============	      ===============
	{ A == 1, B == 2, C == 3, P == &A, Q == &C }
	B = 4;
	<쓰기 배리어>
	WRITE_ONCE(P, &B);
			      Q = READ_ONCE(P);
			      <묵시적 주소 의존성 배리어>
			      D = *Q;

이 변경은 앞의 처음 두가지 결과 중 하나만이 발생할 수 있고, 세번째의 결과는
발생할 수 없도록 합니다.


[!] 이 상당히 반직관적인 상황은 분리된 캐시를 가지는 기계들에서 가장 잘
발생하는데, 예를 들면 한 캐시 뱅크는 짝수 번호의 캐시 라인들을 처리하고, 다른
뱅크는 홀수 번호의 캐시 라인들을 처리하는 경우임을 알아두시기 바랍니다.  포인터
P 는 짝수 번호 캐시 라인에 저장되어 있고, 변수 B 는 홀수 번호 캐시 라인에
저장되어 있을 수 있습니다.  여기서 값을 읽어오는 CPU 의 캐시의 홀수 번호 처리
뱅크는 열심히 일감을 처리중인 반면 홀수 번호 처리 뱅크는 할 일 없이 한가한
중이라면 포인터 P (&B) 의 새로운 값과 변수 B 의 기존 값 (2) 를 볼 수 있습니다.


의존적 쓰기들의 순서를 맞추는데에는 주소 의존성 배리어가 필요치 않은데, 이는
리눅스 커널이 지원하는 CPU 들은 (1) 쓰기가 정말로 일어날지, (2) 쓰기가 어디에
이루어질지, 그리고 (3) 쓰여질 값을 확실히 알기 전까지는 쓰기를 수행하지 않기
때문입니다.  하지만 "컨트롤 의존성" 섹션과
Documentation/RCU/rcu_dereference.rst 파일을 주의 깊게 읽어 주시기 바랍니다:
컴파일러는 매우 창의적인 많은 방법으로 종속성을 깰 수 있습니다.

	CPU 1		      CPU 2
	===============	      ===============
	{ A == 1, B == 2, C = 3, P == &A, Q == &C }
	B = 4;
	<쓰기 배리어>
	WRITE_ONCE(P, &B);
			      Q = READ_ONCE_OLD(P);
			      WRITE_ONCE(*Q, 5);

따라서, Q 로의 읽기와 *Q 로의 쓰기 사이에는 주소 의존성 배리어가 필요치
않습니다.  달리 말하면, 오늘날의 READ_ONCE() 의 묵시적 주소 의존성 배리어가
없더라도 다음 결과는 생기지 않습니다:

	(Q == &B) && (B == 4)

이런 패턴은 드물게 사용되어야 함을 알아 두시기 바랍니다.  무엇보다도, 의존성
순서 규칙의 의도는 쓰기 작업을 -예방- 해서 그로 인해 발생하는 비싼 캐시 미스도
없애려는 것입니다.  이 패턴은 드물게 발생하는 에러 조건 같은것들을 기록하는데
사용될 수 있으며, CPU의 자연적인 순서 보장이 그런 기록들을 사라지지 않게
해줍니다.


주소 의존성에 의해 제공되는 이 순서규칙은 이를 포함하고 있는 CPU 에
지역적임을 알아두시기 바랍니다.  더 많은 정보를 위해선 "Multicopy 원자성"
섹션을 참고하세요.


주소 의존성 배리어는 매우 중요한데, 예를 들어 RCU 시스템에서 그렇습니다.
include/linux/rcupdate.h 의 rcu_assign_pointer() 와 rcu_dereference() 를
참고하세요.  이것들은 RCU 로 관리되는 포인터의 타겟을 현재 타겟에서 수정된
새로운 타겟으로 바꾸는 작업에서 새로 수정된 타겟이 초기화가 완료되지 않은 채로
보여지는 일이 일어나지 않게 해줍니다.

더 많은 예를 위해선 "캐시 일관성" 서브섹션을 참고하세요.


컨트롤 의존성
-------------

현재의 컴파일러들은 컨트롤 의존성을 이해하고 있지 않기 때문에 컨트롤 의존성은
약간 다루기 어려울 수 있습니다.  이 섹션의 목적은 여러분이 컴파일러의 무시로
인해 여러분의 코드가 망가지는 걸 막을 수 있도록 돕는겁니다.

로드-로드 컨트롤 의존성은 (묵시적인) 주소 의존성 배리어만으로는 정확히 동작할
수가 없어서 읽기 메모리 배리어를 필요로 합니다.  아래의 코드를 봅시다:

	q = READ_ONCE(a);
	<묵시적 주소 의존성 배리어>
	if (q) {
		/* BUG: No address dependency!!! */
		p = READ_ONCE(b);
	}

이 코드는 원하는 대로의 효과를 내지 못할 수 있는데, 이 코드에는 주소 의존성이
아니라 컨트롤 의존성이 존재하기 때문으로, 이런 상황에서 CPU 는 실행 속도를 더
빠르게 하기 위해 분기 조건의 결과를 예측하고 코드를 재배치 할 수 있어서 다른
CPU 는 b 로부터의 로드 오퍼레이션이 a 로부터의 로드 오퍼레이션보다 먼저 발생한
걸로 인식할 수 있습니다.  여기에 정말로 필요했던 건 다음과 같습니다:

	q = READ_ONCE(a);
	if (q) {
		<읽기 배리어>
		p = READ_ONCE(b);
	}

하지만, 스토어 오퍼레이션은 예측적으로 수행되지 않습니다.  즉, 다음 예에서와
같이 로드-스토어 컨트롤 의존성이 존재하는 경우에는 순서가 -지켜진다-는
의미입니다.

	q = READ_ONCE(a);
	if (q) {
		WRITE_ONCE(b, 1);
	}

컨트롤 의존성은 보통 다른 타입의 배리어들과 짝을 맞춰 사용됩니다.  그렇다곤
하나, READ_ONCE() 도 WRITE_ONCE() 도 선택사항이 아니라 필수사항임을 부디
명심하세요!  READ_ONCE() 가 없다면, 컴파일러는 'a' 로부터의 로드를 'a' 로부터의
또다른 로드와 조합할 수 있습니다.  WRITE_ONCE() 가 없다면, 컴파일러는 'b' 로의
스토어를 'b' 로의 또라느 스토어들과 조합할 수 있습니다.  두 경우 모두 순서에
있어 상당히 비직관적인 결과를 초래할 수 있습니다.

이걸로 끝이 아닌게, 컴파일러가 변수 'a' 의 값이 항상 0이 아니라고 증명할 수
있다면, 앞의 예에서 "if" 문을 없애서 다음과 같이 최적화 할 수도 있습니다:

	q = a;
	b = 1;  /* BUG: Compiler and CPU can both reorder!!! */

그러니 READ_ONCE() 를 반드시 사용하세요.

다음과 같이 "if" 문의 양갈래 브랜치에 모두 존재하는 동일한 스토어에 대해 순서를
강제하고 싶은 경우가 있을 수 있습니다:

	q = READ_ONCE(a);
	if (q) {
		barrier();
		WRITE_ONCE(b, 1);
		do_something();
	} else {
		barrier();
		WRITE_ONCE(b, 1);
		do_something_else();
	}

안타깝게도, 현재의 컴파일러들은 높은 최적화 레벨에서는 이걸 다음과 같이
바꿔버립니다:

	q = READ_ONCE(a);
	barrier();
	WRITE_ONCE(b, 1);  /* BUG: No ordering vs. load from a!!! */
	if (q) {
		/* WRITE_ONCE(b, 1); -- moved up, BUG!!! */
		do_something();
	} else {
		/* WRITE_ONCE(b, 1); -- moved up, BUG!!! */
		do_something_else();
	}

이제 'a' 에서의 로드와 'b' 로의 스토어 사이에는 조건적 관계가 없기 때문에 CPU
는 이들의 순서를 바꿀 수 있게 됩니다: 이런 경우에 조건적 관계는 반드시
필요한데, 모든 컴파일러 최적화가 이루어지고 난 후의 어셈블리 코드에서도
마찬가지입니다.  따라서, 이 예에서 순서를 지키기 위해서는 smp_store_release()
와 같은 명시적 메모리 배리어가 필요합니다:

	q = READ_ONCE(a);
	if (q) {
		smp_store_release(&b, 1);
		do_something();
	} else {
		smp_store_release(&b, 1);
		do_something_else();
	}

반면에 명시적 메모리 배리어가 없다면, 이런 경우의 순서는 스토어 오퍼레이션들이
서로 다를 때에만 보장되는데, 예를 들면 다음과 같은 경우입니다:

	q = READ_ONCE(a);
	if (q) {
		WRITE_ONCE(b, 1);
		do_something();
	} else {
		WRITE_ONCE(b, 2);
		do_something_else();
	}

처음의 READ_ONCE() 는 컴파일러가 'a' 의 값을 증명해내는 것을 막기 위해 여전히
필요합니다.

또한, 로컬 변수 'q' 를 가지고 하는 일에 대해 주의해야 하는데, 그러지 않으면
컴파일러는 그 값을 추측하고 또다시 필요한 조건관계를 없애버릴 수 있습니다.
예를 들면:

	q = READ_ONCE(a);
	if (q % MAX) {
		WRITE_ONCE(b, 1);
		do_something();
	} else {
		WRITE_ONCE(b, 2);
		do_something_else();
	}

만약 MAX 가 1 로 정의된 상수라면, 컴파일러는 (q % MAX) 는 0이란 것을 알아채고,
위의 코드를 아래와 같이 바꿔버릴 수 있습니다:

	q = READ_ONCE(a);
	WRITE_ONCE(b, 2);
	do_something_else();

이렇게 되면, CPU 는 변수 'a' 로부터의 로드와 변수 'b' 로의 스토어 사이의 순서를
지켜줄 필요가 없어집니다.  barrier() 를 추가해 해결해 보고 싶겠지만, 그건
도움이 안됩니다.  조건 관계는 사라졌고, barrier() 는 이를 되돌리지 못합니다.
따라서, 이 순서를 지켜야 한다면, MAX 가 1 보다 크다는 것을, 다음과 같은 방법을
사용해 분명히 해야 합니다:

	q = READ_ONCE(a);
	BUILD_BUG_ON(MAX <= 1); /* Order load from a with store to b. */
	if (q % MAX) {
		WRITE_ONCE(b, 1);
		do_something();
	} else {
		WRITE_ONCE(b, 2);
		do_something_else();
	}

'b' 로의 스토어들은 여전히 서로 다름을 알아두세요.  만약 그것들이 동일하면,
앞에서 이야기했듯, 컴파일러가 그 스토어 오퍼레이션들을 'if' 문 바깥으로
끄집어낼 수 있습니다.

또한 이진 조건문 평가에 너무 의존하지 않도록 조심해야 합니다.  다음의 예를
봅시다:

	q = READ_ONCE(a);
	if (q || 1 > 0)
		WRITE_ONCE(b, 1);

첫번째 조건만으로는 브랜치 조건 전체를 거짓으로 만들 수 없고 두번째 조건은 항상
참이기 때문에, 컴파일러는 이 예를 다음과 같이 바꿔서 컨트롤 의존성을 없애버릴
수 있습니다:

	q = READ_ONCE(a);
	WRITE_ONCE(b, 1);

이 예는 컴파일러가 코드를 추측으로 수정할 수 없도록 분명히 해야 한다는 점을
강조합니다.  조금 더 일반적으로 말해서, READ_ONCE() 는 컴파일러에게 주어진 로드
오퍼레이션을 위한 코드를 정말로 만들도록 하지만, 컴파일러가 그렇게 만들어진
코드의 수행 결과를 사용하도록 강제하지는 않습니다.

또한, 컨트롤 의존성은 if 문의 then 절과 else 절에 대해서만 적용됩니다.  상세히
말해서, 컨트롤 의존성은 if 문을 뒤따르는 코드에는 적용되지 않습니다:

	q = READ_ONCE(a);
	if (q) {
		WRITE_ONCE(b, 1);
	} else {
		WRITE_ONCE(b, 2);
	}
	WRITE_ONCE(c, 1);  /* BUG: No ordering against the read from 'a'. */

컴파일러는 volatile 타입에 대한 액세스를 재배치 할 수 없고 이 조건 하의 'b'
로의 쓰기를 재배치 할 수 없기 때문에 여기에 순서 규칙이 존재한다고 주장하고
싶을 겁니다.  불행히도 이 경우에, 컴파일러는 다음의 가상의 pseudo-assembly 언어
코드처럼 'b' 로의 두개의 쓰기 오퍼레이션을 conditional-move 인스트럭션으로
번역할 수 있습니다:

	ld r1,a
	cmp r1,$0
	cmov,ne r4,$1
	cmov,eq r4,$2
	st r4,b
	st $1,c

완화된 순서 규칙의 CPU 는 'a' 로부터의 로드와 'c' 로의 스토어 사이에 어떤
종류의 의존성도 갖지 않을 겁니다.  이 컨트롤 의존성은 두개의 cmov 인스트럭션과
거기에 의존하는 스토어 에게만 적용될 겁니다.  짧게 말하자면, 컨트롤 의존성은
주어진 if 문의 then 절과 else 절에게만 (그리고 이 두 절 내에서 호출되는
함수들에게까지) 적용되지, 이 if 문을 뒤따르는 코드에는 적용되지 않습니다.


컨트롤 의존성에 의해 제공되는 이 순서규칙은 이를 포함하고 있는 CPU 에
지역적입니다.  더 많은 정보를 위해선 "Multicopy 원자성" 섹션을 참고하세요.


요약하자면:

  (*) 컨트롤 의존성은 앞의 로드들을 뒤의 스토어들에 대해 순서를 맞춰줍니다.
      하지만, 그 외의 어떤 순서도 보장하지 -않습니다-: 앞의 로드와 뒤의 로드들
      사이에도, 앞의 스토어와 뒤의 스토어들 사이에도요.  이런 다른 형태의
      순서가 필요하다면 smp_rmb() 나 smp_wmb()를, 또는, 앞의 스토어들과 뒤의
      로드들 사이의 순서를 위해서는 smp_mb() 를 사용하세요.

  (*) "if" 문의 양갈래 브랜치가 같은 변수에의 동일한 스토어로 시작한다면, 그
      스토어들은 각 스토어 앞에 smp_mb() 를 넣거나 smp_store_release() 를
      사용해서 스토어를 하는 식으로 순서를 맞춰줘야 합니다.  이 문제를 해결하기
      위해 "if" 문의 양갈래 브랜치의 시작 지점에 barrier() 를 넣는 것만으로는
      충분한 해결이 되지 않는데, 이는 앞의 예에서 본것과 같이, 컴파일러의
      최적화는 barrier() 가 의미하는 바를 지키면서도 컨트롤 의존성을 손상시킬
      수 있기 때문이라는 점을 부디 알아두시기 바랍니다.

  (*) 컨트롤 의존성은 앞의 로드와 뒤의 스토어 사이에 최소 하나의, 실행
      시점에서의 조건관계를 필요로 하며, 이 조건관계는 앞의 로드와 관계되어야
      합니다.  만약 컴파일러가 조건 관계를 최적화로 없앨수 있다면, 순서도
      최적화로 없애버렸을 겁니다.  READ_ONCE() 와 WRITE_ONCE() 의 주의 깊은
      사용은 주어진 조건 관계를 유지하는데 도움이 될 수 있습니다.

  (*) 컨트롤 의존성을 위해선 컴파일러가 조건관계를 없애버리는 것을 막아야
      합니다.  주의 깊은 READ_ONCE() 나 atomic{,64}_read() 의 사용이 컨트롤
      의존성이 사라지지 않게 하는데 도움을 줄 수 있습니다.  더 많은 정보를
      위해선 "컴파일러 배리어" 섹션을 참고하시기 바랍니다.

  (*) 컨트롤 의존성은 컨트롤 의존성을 갖는 if 문의 then 절과 else 절과 이 두 절
      내에서 호출되는 함수들에만 적용됩니다.  컨트롤 의존성은 컨트롤 의존성을
      갖는 if 문을 뒤따르는 코드에는 적용되지 -않습니다-.

  (*) 컨트롤 의존성은 보통 다른 타입의 배리어들과 짝을 맞춰 사용됩니다.

  (*) 컨트롤 의존성은 multicopy 원자성을 제공하지 -않습니다-.  모든 CPU 들이
      특정 스토어를 동시에 보길 원한다면, smp_mb() 를 사용하세요.

  (*) 컴파일러는 컨트롤 의존성을 이해하고 있지 않습니다.  따라서 컴파일러가
      여러분의 코드를 망가뜨리지 않도록 하는건 여러분이 해야 하는 일입니다.


SMP 배리어 짝맞추기
--------------------

CPU 간 상호작용을 다룰 때에 일부 타입의 메모리 배리어는 항상 짝을 맞춰
사용되어야 합니다.  적절하게 짝을 맞추지 않은 코드는 사실상 에러에 가깝습니다.

범용 배리어들은 범용 배리어끼리도 짝을 맞추지만 multicopy 원자성이 없는
대부분의 다른 타입의 배리어들과도 짝을 맞춥니다.  ACQUIRE 배리어는 RELEASE
배리어와 짝을 맞춥니다만, 둘 다 범용 배리어를 포함해 다른 배리어들과도 짝을
맞출 수 있습니다.  쓰기 배리어는 주소 의존성 배리어나 컨트롤 의존성, ACQUIRE
배리어, RELEASE 배리어, 읽기 배리어, 또는 범용 배리어와 짝을 맞춥니다.
비슷하게 읽기 배리어나 컨트롤 의존성, 또는 주소 의존성 배리어는 쓰기 배리어나
ACQUIRE 배리어, RELEASE 배리어, 또는 범용 배리어와 짝을 맞추는데, 다음과
같습니다:

	CPU 1		      CPU 2
	===============	      ===============
	WRITE_ONCE(a, 1);
	<쓰기 배리어>
	WRITE_ONCE(b, 2);     x = READ_ONCE(b);
			      <읽기 배리어>
			      y = READ_ONCE(a);

또는:

	CPU 1		      CPU 2
	===============	      ===============================
	a = 1;
	<쓰기 배리어>
	WRITE_ONCE(b, &a);    x = READ_ONCE(b);
			      <묵시적 주소 의존성 배리어>
			      y = *x;

또는:

	CPU 1		      CPU 2
	===============	      ===============================
	r1 = READ_ONCE(y);
	<범용 배리어>
	WRITE_ONCE(x, 1);     if (r2 = READ_ONCE(x)) {
			         <묵시적 컨트롤 의존성>
			         WRITE_ONCE(y, 1);
			      }

	assert(r1 == 0 || r2 == 0);

기본적으로, 여기서의 읽기 배리어는 "더 완화된" 타입일 순 있어도 항상 존재해야
합니다.

[!] 쓰기 배리어 앞의 스토어 오퍼레이션은 일반적으로 읽기 배리어나 주소 의존성
배리어 뒤의 로드 오퍼레이션과 매치될 것이고, 반대도 마찬가지입니다:

	CPU 1                               CPU 2
	===================                 ===================
	WRITE_ONCE(a, 1);    }----   --->{  v = READ_ONCE(c);
	WRITE_ONCE(b, 2);    }    \ /    {  w = READ_ONCE(d);
	<쓰기 배리어>              \        <읽기 배리어>
	WRITE_ONCE(c, 3);    }    / \    {  x = READ_ONCE(a);
	WRITE_ONCE(d, 4);    }----   --->{  y = READ_ONCE(b);


메모리 배리어 시퀀스의 예
-------------------------

첫째, 쓰기 배리어는 스토어 오퍼레이션들의 부분적 순서 세우기로 동작합니다.
아래의 이벤트 시퀀스를 보세요:

	CPU 1
	=======================
	STORE A = 1
	STORE B = 2
	STORE C = 3
	<쓰기 배리어>
	STORE D = 4
	STORE E = 5

이 이벤트 시퀀스는 메모리 일관성 시스템에 원소끼리의 순서가 존재하지 않는 집합
{ STORE A, STORE B, STORE C } 가 역시 원소끼리의 순서가 존재하지 않는 집합
{ STORE D, STORE E } 보다 먼저 일어난 것으로 시스템의 나머지 요소들에 보이도록
전달됩니다:

	+-------+       :      :
	|       |       +------+
	|       |------>| C=3  |     }     /\
	|       |  :    +------+     }-----  \  -----> 시스템의 나머지 요소에
	|       |  :    | A=1  |     }        \/       보여질 수 있는 이벤트들
	|       |  :    +------+     }
	| CPU 1 |  :    | B=2  |     }
	|       |       +------+     }
	|       |   wwwwwwwwwwwwwwww }   <--- 여기서 쓰기 배리어는 배리어 앞의
	|       |       +------+     }        모든 스토어가 배리어 뒤의 스토어
	|       |  :    | E=5  |     }        전에 메모리 시스템에 전달되도록
	|       |  :    +------+     }        합니다
	|       |------>| D=4  |     }
	|       |       +------+
	+-------+       :      :
	                   |
	                   | CPU 1 에 의해 메모리 시스템에 전달되는
	                   | 일련의 스토어 오퍼레이션들
	                   V


둘째, 주소 의존성 배리어는 데이터 의존적 로드 오퍼레이션들의 부분적 순서
세우기로 동작합니다.  다음 일련의 이벤트들을 보세요:

	CPU 1			CPU 2
	=======================	=======================
		{ B = 7; X = 9; Y = 8; C = &Y }
	STORE A = 1
	STORE B = 2
	<쓰기 배리어>
	STORE C = &B		LOAD X
	STORE D = 4		LOAD C (gets &B)
				LOAD *C (reads B)

여기에 별다른 개입이 없다면, CPU 1 의 쓰기 배리어에도 불구하고 CPU 2 는 CPU 1
의 이벤트들을 완전히 무작위적 순서로 인지하게 됩니다:

	+-------+       :      :                :       :
	|       |       +------+                +-------+  | CPU 2 에 인지되는
	|       |------>| B=2  |-----       --->| Y->8  |  | 업데이트 이벤트
	|       |  :    +------+     \          +-------+  | 시퀀스
	| CPU 1 |  :    | A=1  |      \     --->| C->&Y |  V
	|       |       +------+       |        +-------+
	|       |   wwwwwwwwwwwwwwww   |        :       :
	|       |       +------+       |        :       :
	|       |  :    | C=&B |---    |        :       :       +-------+
	|       |  :    +------+   \   |        +-------+       |       |
	|       |------>| D=4  |    ----------->| C->&B |------>|       |
	|       |       +------+       |        +-------+       |       |
	+-------+       :      :       |        :       :       |       |
	                               |        :       :       |       |
	                               |        :       :       | CPU 2 |
	                               |        +-------+       |       |
	    분명히 잘못된        --->  |        | B->7  |------>|       |
	    B 의 값 인지 (!)           |        +-------+       |       |
	                               |        :       :       |       |
	                               |        +-------+       |       |
	    X 의 로드가 B 의    --->    \       | X->9  |------>|       |
	    일관성 유지를                \      +-------+       |       |
	    지연시킴                      ----->| B->2  |       +-------+
	                                        +-------+
	                                        :       :


앞의 예에서, CPU 2 는 (B 의 값이 될) *C 의 값 읽기가 C 의 LOAD 뒤에 이어짐에도
B 가 7 이라는 결과를 얻습니다.

하지만, 만약 주소 의존성 배리어가 C 의 로드와 *C (즉, B) 의 로드 사이에
있었다면:

	CPU 1			CPU 2
	=======================	=======================
		{ B = 7; X = 9; Y = 8; C = &Y }
	STORE A = 1
	STORE B = 2
	<쓰기 배리어>
	STORE C = &B		LOAD X
	STORE D = 4		LOAD C (gets &B)
				<주소 의존성 배리어>
				LOAD *C (reads B)

다음과 같이 됩니다:

	+-------+       :      :                :       :
	|       |       +------+                +-------+
	|       |------>| B=2  |-----       --->| Y->8  |
	|       |  :    +------+     \          +-------+
	| CPU 1 |  :    | A=1  |      \     --->| C->&Y |
	|       |       +------+       |        +-------+
	|       |   wwwwwwwwwwwwwwww   |        :       :
	|       |       +------+       |        :       :
	|       |  :    | C=&B |---    |        :       :       +-------+
	|       |  :    +------+   \   |        +-------+       |       |
	|       |------>| D=4  |    ----------->| C->&B |------>|       |
	|       |       +------+       |        +-------+       |       |
	+-------+       :      :       |        :       :       |       |
	                               |        :       :       |       |
	                               |        :       :       | CPU 2 |
	                               |        +-------+       |       |
	                               |        | X->9  |------>|       |
	                               |        +-------+       |       |
	  C 로의 스토어 앞의     --->   \   aaaaaaaaaaaaaaaaa   |       |
	  모든 이벤트 결과가             \      +-------+       |       |
	  뒤의 로드에게                   ----->| B->2  |------>|       |
	  보이게 강제한다                       +-------+       |       |
	                                        :       :       +-------+


셋째, 읽기 배리어는 로드 오퍼레이션들에의 부분적 순서 세우기로 동작합니다.
아래의 일련의 이벤트를 봅시다:

	CPU 1			CPU 2
	=======================	=======================
		{ A = 0, B = 9 }
	STORE A=1
	<쓰기 배리어>
	STORE B=2
				LOAD B
				LOAD A

CPU 1 은 쓰기 배리어를 쳤지만, 별다른 개입이 없다면 CPU 2 는 CPU 1 에서 행해진
이벤트의 결과를 무작위적 순서로 인지하게 됩니다.

	+-------+       :      :                :       :
	|       |       +------+                +-------+
	|       |------>| A=1  |------      --->| A->0  |
	|       |       +------+      \         +-------+
	| CPU 1 |   wwwwwwwwwwwwwwww   \    --->| B->9  |
	|       |       +------+        |       +-------+
	|       |------>| B=2  |---     |       :       :
	|       |       +------+   \    |       :       :       +-------+
	+-------+       :      :    \   |       +-------+       |       |
	                             ---------->| B->2  |------>|       |
	                                |       +-------+       | CPU 2 |
	                                |       | A->0  |------>|       |
	                                |       +-------+       |       |
	                                |       :       :       +-------+
	                                 \      :       :
	                                  \     +-------+
	                                   ---->| A->1  |
	                                        +-------+
	                                        :       :


하지만, 만약 읽기 배리어가 B 의 로드와 A 의 로드 사이에 존재한다면:

	CPU 1			CPU 2
	=======================	=======================
		{ A = 0, B = 9 }
	STORE A=1
	<쓰기 배리어>
	STORE B=2
				LOAD B
				<읽기 배리어>
				LOAD A

CPU 1 에 의해 만들어진 부분적 순서가 CPU 2 에도 그대로 인지됩니다:

	+-------+       :      :                :       :
	|       |       +------+                +-------+
	|       |------>| A=1  |------      --->| A->0  |
	|       |       +------+      \         +-------+
	| CPU 1 |   wwwwwwwwwwwwwwww   \    --->| B->9  |
	|       |       +------+        |       +-------+
	|       |------>| B=2  |---     |       :       :
	|       |       +------+   \    |       :       :       +-------+
	+-------+       :      :    \   |       +-------+       |       |
	                             ---------->| B->2  |------>|       |
	                                |       +-------+       | CPU 2 |
	                                |       :       :       |       |
	                                |       :       :       |       |
	  여기서 읽기 배리어는   ---->   \  rrrrrrrrrrrrrrrrr   |       |
	  B 로의 스토어 전의              \     +-------+       |       |
	  모든 결과를 CPU 2 에             ---->| A->1  |------>|       |
	  보이도록 한다                         +-------+       |       |
	                                        :       :       +-------+


더 완벽한 설명을 위해, A 의 로드가 읽기 배리어 앞과 뒤에 있으면 어떻게 될지
생각해 봅시다:

	CPU 1			CPU 2
	=======================	=======================
		{ A = 0, B = 9 }
	STORE A=1
	<쓰기 배리어>
	STORE B=2
				LOAD B
				LOAD A [first load of A]
				<읽기 배리어>
				LOAD A [second load of A]

A 의 로드 두개가 모두 B 의 로드 뒤에 있지만, 서로 다른 값을 얻어올 수
있습니다:

	+-------+       :      :                :       :
	|       |       +------+                +-------+
	|       |------>| A=1  |------      --->| A->0  |
	|       |       +------+      \         +-------+
	| CPU 1 |   wwwwwwwwwwwwwwww   \    --->| B->9  |
	|       |       +------+        |       +-------+
	|       |------>| B=2  |---     |       :       :
	|       |       +------+   \    |       :       :       +-------+
	+-------+       :      :    \   |       +-------+       |       |
	                             ---------->| B->2  |------>|       |
	                                |       +-------+       | CPU 2 |
	                                |       :       :       |       |
	                                |       :       :       |       |
	                                |       +-------+       |       |
	                                |       | A->0  |------>| 1st   |
	                                |       +-------+       |       |
	  여기서 읽기 배리어는   ---->   \  rrrrrrrrrrrrrrrrr   |       |
	  B 로의 스토어 전의              \     +-------+       |       |
	  모든 결과를 CPU 2 에             ---->| A->1  |------>| 2nd   |
	  보이도록 한다                         +-------+       |       |
	                                        :       :       +-------+


하지만 CPU 1 에서의 A 업데이트는 읽기 배리어가 완료되기 전에도 보일 수도
있긴 합니다:

	+-------+       :      :                :       :
	|       |       +------+                +-------+
	|       |------>| A=1  |------      --->| A->0  |
	|       |       +------+      \         +-------+
	| CPU 1 |   wwwwwwwwwwwwwwww   \    --->| B->9  |
	|       |       +------+        |       +-------+
	|       |------>| B=2  |---     |       :       :
	|       |       +------+   \    |       :       :       +-------+
	+-------+       :      :    \   |       +-------+       |       |
	                             ---------->| B->2  |------>|       |
	                                |       +-------+       | CPU 2 |
	                                |       :       :       |       |
	                                 \      :       :       |       |
	                                  \     +-------+       |       |
	                                   ---->| A->1  |------>| 1st   |
	                                        +-------+       |       |
	                                    rrrrrrrrrrrrrrrrr   |       |
	                                        +-------+       |       |
	                                        | A->1  |------>| 2nd   |
	                                        +-------+       |       |
	                                        :       :       +-------+


여기서 보장되는 건, 만약 B 의 로드가 B == 2 라는 결과를 봤다면, A 에의 두번째
로드는 항상 A == 1 을 보게 될 것이라는 겁니다.  A 에의 첫번째 로드에는 그런
보장이 없습니다; A == 0 이거나 A == 1 이거나 둘 중 하나의 결과를 보게 될겁니다.


읽기 메모리 배리어 VS 로드 예측
-------------------------------

많은 CPU들이 로드를 예측적으로 (speculatively) 합니다: 어떤 데이터를 메모리에서
로드해야 하게 될지 예측을 했다면, 해당 데이터를 로드하는 인스트럭션을 실제로는
아직 만나지 않았더라도 다른 로드 작업이 없어 버스 (bus) 가 아무 일도 하고 있지
않다면, 그 데이터를 로드합니다.  이후에 실제 로드 인스트럭션이 실행되면 CPU 가
이미 그 값을 가지고 있기 때문에 그 로드 인스트럭션은 즉시 완료됩니다.

해당 CPU 는 실제로는 그 값이 필요치 않았다는 사실이 나중에 드러날 수도 있는데 -
해당 로드 인스트럭션이 브랜치로 우회되거나 했을 수 있겠죠 - , 그렇게 되면 앞서
읽어둔 값을 버리거나 나중의 사용을 위해 캐시에 넣어둘 수 있습니다.

다음을 생각해 봅시다:

	CPU 1			CPU 2
	=======================	=======================
				LOAD B
				DIVIDE		} 나누기 명령은 일반적으로
				DIVIDE		} 긴 시간을 필요로 합니다
				LOAD A

는 이렇게 될 수 있습니다:

	                                        :       :       +-------+
	                                        +-------+       |       |
	                                    --->| B->2  |------>|       |
	                                        +-------+       | CPU 2 |
	                                        :       :DIVIDE |       |
	                                        +-------+       |       |
	나누기 하느라 바쁜       --->       --->| A->0  |~~~~   |       |
	CPU 는 A 의 LOAD 를                     +-------+   ~   |       |
	예측해서 수행한다                       :       :   ~   |       |
	                                        :       :DIVIDE |       |
	                                        :       :   ~   |       |
	나누기가 끝나면       --->     --->     :       :   ~-->|       |
	CPU 는 해당 LOAD 를                     :       :       |       |
	즉각 완료한다                           :       :       +-------+


읽기 배리어나 주소 의존성 배리어를 두번째 로드 직전에 놓는다면:

	CPU 1			CPU 2
	=======================	=======================
				LOAD B
				DIVIDE
				DIVIDE
				<읽기 배리어>
				LOAD A

예측으로 얻어진 값은 사용된 배리어의 타입에 따라서 해당 값이 옳은지 검토되게
됩니다.  만약 해당 메모리 영역에 변화가 없었다면, 예측으로 얻어두었던 값이
사용됩니다:

	                                        :       :       +-------+
	                                        +-------+       |       |
	                                    --->| B->2  |------>|       |
	                                        +-------+       | CPU 2 |
	                                        :       :DIVIDE |       |
	                                        +-------+       |       |
	나누기 하느라 바쁜       --->       --->| A->0  |~~~~   |       |
	CPU 는 A 의 LOAD 를                     +-------+   ~   |       |
	예측한다                                :       :   ~   |       |
	                                        :       :DIVIDE |       |
	                                        :       :   ~   |       |
	                                        :       :   ~   |       |
	                                    rrrrrrrrrrrrrrrr~   |       |
	                                        :       :   ~   |       |
	                                        :       :   ~-->|       |
	                                        :       :       |       |
	                                        :       :       +-------+


하지만 다른 CPU 에서 업데이트나 무효화가 있었다면, 그 예측은 무효화되고 그 값은
다시 읽혀집니다:

	                                        :       :       +-------+
	                                        +-------+       |       |
	                                    --->| B->2  |------>|       |
	                                        +-------+       | CPU 2 |
	                                        :       :DIVIDE |       |
	                                        +-------+       |       |
	나누기 하느라 바쁜       --->       --->| A->0  |~~~~   |       |
	CPU 는 A 의 LOAD 를                     +-------+   ~   |       |
	예측한다                                :       :   ~   |       |
	                                        :       :DIVIDE |       |
	                                        :       :   ~   |       |
	                                        :       :   ~   |       |
	                                    rrrrrrrrrrrrrrrrr   |       |
	                                        +-------+       |       |
	예측성 동작은 무효화 되고    --->   --->| A->1  |------>|       |
	업데이트된 값이 다시 읽혀진다           +-------+       |       |
	                                        :       :       +-------+


MULTICOPY 원자성
----------------

Multicopy 원자성은 실제의 컴퓨터 시스템에서 항상 제공되지는 않는, 순서 맞추기에
대한 상당히 직관적인 개념으로, 특정 스토어가 모든 CPU 들에게 동시에 보여지게
됨을, 달리 말하자면 모든 CPU 들이 모든 스토어들이 보여지는 순서를 동의하게 되는
것입니다.  하지만, 완전한 multicopy 원자성의 사용은 가치있는 하드웨어
최적화들을 무능하게 만들어버릴 수 있어서, 보다 완화된 형태의 ``다른 multicopy
원자성'' 라는 이름의, 특정 스토어가 모든 -다른- CPU 들에게는 동시에 보여지게
하는 보장을 대신 제공합니다.  이 문서의 뒷부분들은 이 완화된 형태에 대해 논하게
됩니다만, 단순히 ``multicopy 원자성'' 이라고 부르겠습니다.

다음의 예가 multicopy 원자성을 보입니다:

	CPU 1			CPU 2			CPU 3
	=======================	=======================	=======================
		{ X = 0, Y = 0 }
	STORE X=1		r1=LOAD X (reads 1)	LOAD Y (reads 1)
				<범용 배리어>		<읽기 배리어>
				STORE Y=r1		LOAD X

CPU 2 의 Y 로의 스토어에 사용되는 X 로드의 결과가 1 이었고 CPU 3 의 Y 로드가
1을 리턴했다고 해봅시다.  이는 CPU 1 의 X 로의 스토어가 CPU 2 의 X 로부터의
로드를 앞서고 CPU 2 의 Y 로의 스토어가 CPU 3 의 Y 로부터의 로드를 앞섬을
의미합니다.  또한, 여기서의 메모리 배리어들은 CPU 2 가 자신의 로드를 자신의
스토어 전에 수행하고, CPU 3 가 Y 로부터의 로드를 X 로부터의 로드 전에 수행함을
보장합니다.  그럼 "CPU 3 의 X 로부터의 로드는 0 을 리턴할 수 있을까요?"

CPU 3 의 X 로드가 CPU 2 의 로드보다 뒤에 이루어졌으므로, CPU 3 의 X 로부터의
로드는 1 을 리턴한다고 예상하는게 당연합니다.  이런 예상은 multicopy
원자성으로부터 나옵니다: CPU B 에서 수행된 로드가 CPU A 의 같은 변수로부터의
로드를 뒤따른다면 (그리고 CPU A 가 자신이 읽은 값으로 먼저 해당 변수에 스토어
하지 않았다면) multicopy 원자성을 제공하는 시스템에서는, CPU B 의 로드가 CPU A
의 로드와 같은 값 또는 그 나중 값을 리턴해야만 합니다.  하지만, 리눅스 커널은
시스템들이 multicopy 원자성을 제공할 것을 요구하지 않습니다.

앞의 범용 메모리 배리어의 사용은 모든 multicopy 원자성의 부족을 보상해줍니다.
앞의 예에서, CPU 2 의 X 로부터의 로드가 1 을 리턴했고 CPU 3 의 Y 로부터의
로드가 1 을 리턴했다면, CPU 3 의 X 로부터의 로드는 1을 리턴해야만 합니다.

하지만, 의존성, 읽기 배리어, 쓰기 배리어는 항상 non-multicopy 원자성을 보상해
주지는 않습니다.  예를 들어, CPU 2 의 범용 배리어가 앞의 예에서 사라져서
아래처럼 데이터 의존성만 남게 되었다고 해봅시다:

	CPU 1			CPU 2			CPU 3
	=======================	=======================	=======================
		{ X = 0, Y = 0 }
	STORE X=1		r1=LOAD X (reads 1)	LOAD Y (reads 1)
				<데이터 의존성>		<읽기 배리어>
				STORE Y=r1		LOAD X (reads 0)

이 변화는 non-multicopy 원자성이 만연하게 합니다: 이 예에서, CPU 2 의 X
로부터의 로드가 1을 리턴하고, CPU 3 의 Y 로부터의 로드가 1 을 리턴하는데, CPU 3
의 X 로부터의 로드가 0 을 리턴하는게 완전히 합법적입니다.

핵심은, CPU 2 의 데이터 의존성이 자신의 로드와 스토어를 순서짓지만, CPU 1 의
스토어에 대한 순서는 보장하지 않는다는 것입니다.  따라서, 이 예제가 CPU 1 과
CPU 2 가 스토어 버퍼나 한 수준의 캐시를 공유하는, multicopy 원자성을 제공하지
않는 시스템에서 수행된다면 CPU 2 는 CPU 1 의 쓰기에 이른 접근을 할 수도
있습니다.  따라서, 모든 CPU 들이 여러 접근들의 조합된 순서에 대해서 동의하게
하기 위해서는 범용 배리어가 필요합니다.

범용 배리어는 non-multicopy 원자성만 보상할 수 있는게 아니라, -모든- CPU 들이
-모든- 오퍼레이션들의 순서를 동일하게 인식하게 하는 추가적인 순서 보장을
만들어냅니다.  반대로, release-acquire 짝의 연결은 이런 추가적인 순서는
제공하지 않는데, 해당 연결에 들어있는 CPU 들만이 메모리 접근의 조합된 순서에
대해 동의할 것으로 보장됨을 의미합니다.  예를 들어, 존경스런 Herman Hollerith
의 코드를 C 코드로 변환하면:

	int u, v, x, y, z;

	void cpu0(void)
	{
		r0 = smp_load_acquire(&x);
		WRITE_ONCE(u, 1);
		smp_store_release(&y, 1);
	}

	void cpu1(void)
	{
		r1 = smp_load_acquire(&y);
		r4 = READ_ONCE(v);
		r5 = READ_ONCE(u);
		smp_store_release(&z, 1);
	}

	void cpu2(void)
	{
		r2 = smp_load_acquire(&z);
		smp_store_release(&x, 1);
	}

	void cpu3(void)
	{
		WRITE_ONCE(v, 1);
		smp_mb();
		r3 = READ_ONCE(u);
	}

cpu0(), cpu1(), 그리고 cpu2() 는 smp_store_release()/smp_load_acquire() 쌍의
연결에 참여되어 있으므로, 다음과 같은 결과는 나오지 않을 겁니다:

	r0 == 1 && r1 == 1 && r2 == 1

더 나아가서, cpu0() 와 cpu1() 사이의 release-acquire 관계로 인해, cpu1() 은
cpu0() 의 쓰기를 봐야만 하므로, 다음과 같은 결과도 없을 겁니다:

	r1 == 1 && r5 == 0

하지만, release-acquire 에 의해 제공되는 순서는 해당 연결에 동참한 CPU 들에만
적용되므로 cpu3() 에, 적어도 스토어들 외에는 적용되지 않습니다.  따라서, 다음과
같은 결과가 가능합니다:

	r0 == 0 && r1 == 1 && r2 == 1 && r3 == 0 && r4 == 0

비슷하게, 다음과 같은 결과도 가능합니다:

	r0 == 0 && r1 == 1 && r2 == 1 && r3 == 0 && r4 == 0 && r5 == 1

cpu0(), cpu1(), 그리고 cpu2() 는 그들의 읽기와 쓰기를 순서대로 보게 되지만,
release-acquire 체인에 관여되지 않은 CPU 들은 그 순서에 이견을 가질 수
있습니다.  이런 이견은 smp_load_acquire() 와 smp_store_release() 의 구현에
사용되는 완화된 메모리 배리어 인스트럭션들은 항상 배리어 앞의 스토어들을 뒤의
로드들에 앞세울 필요는 없다는 사실에서 기인합니다.  이 말은 cpu3() 는 cpu0() 의
u 로의 스토어를 cpu1() 의 v 로부터의 로드 뒤에 일어난 것으로 볼 수 있다는
뜻입니다, cpu0() 와 cpu1() 은 이 두 오퍼레이션이 의도된 순서대로 일어났음에
모두 동의하는데도 말입니다.

하지만, smp_load_acquire() 는 마술이 아님을 명심하시기 바랍니다.  구체적으로,
이 함수는 단순히 순서 규칙을 지키며 인자로부터의 읽기를 수행합니다.  이것은
어떤 특정한 값이 읽힐 것인지는 보장하지 -않습니다-.  따라서, 다음과 같은 결과도
가능합니다:

	r0 == 0 && r1 == 0 && r2 == 0 && r5 == 0

이런 결과는 어떤 것도 재배치 되지 않는, 순차적 일관성을 가진 가상의
시스템에서도 일어날 수 있음을 기억해 두시기 바랍니다.

다시 말하지만, 당신의 코드가 모든 오퍼레이션들의 완전한 순서를 필요로 한다면,
범용 배리어를 사용하십시오.


==================
명시적 커널 배리어
==================

리눅스 커널은 서로 다른 단계에서 동작하는 다양한 배리어들을 가지고 있습니다:

  (*) 컴파일러 배리어.

  (*) CPU 메모리 배리어.


컴파일러 배리어
---------------

리눅스 커널은 컴파일러가 메모리 액세스를 재배치 하는 것을 막아주는 명시적인
컴파일러 배리어를 가지고 있습니다:

	barrier();

이건 범용 배리어입니다 -- barrier() 의 읽기-읽기 나 쓰기-쓰기 변종은 없습니다.
하지만, READ_ONCE() 와 WRITE_ONCE() 는 특정 액세스들에 대해서만 동작하는
barrier() 의 완화된 형태로 볼 수 있습니다.

barrier() 함수는 다음과 같은 효과를 갖습니다:

 (*) 컴파일러가 barrier() 뒤의 액세스들이 barrier() 앞의 액세스보다 앞으로
     재배치되지 못하게 합니다.  예를 들어, 인터럽트 핸들러 코드와 인터럽트 당한
     코드 사이의 통신을 신중히 하기 위해 사용될 수 있습니다.

 (*) 루프에서, 컴파일러가 루프 조건에 사용된 변수를 매 이터레이션마다
     메모리에서 로드하지 않아도 되도록 최적화 하는걸 방지합니다.

READ_ONCE() 와 WRITE_ONCE() 함수는 싱글 쓰레드 코드에서는 문제 없지만 동시성이
있는 코드에서는 문제가 될 수 있는 모든 최적화를 막습니다.  이런 류의 최적화에
대한 예를 몇가지 들어보면 다음과 같습니다:

 (*) 컴파일러는 같은 변수에 대한 로드와 스토어를 재배치 할 수 있고, 어떤
     경우에는 CPU가 같은 변수로부터의 로드들을 재배치할 수도 있습니다.  이는
     다음의 코드가:

	a[0] = x;
	a[1] = x;

     x 의 예전 값이 a[1] 에, 새 값이 a[0] 에 있게 할 수 있다는 뜻입니다.
     컴파일러와 CPU가 이런 일을 못하게 하려면 다음과 같이 해야 합니다:

	a[0] = READ_ONCE(x);
	a[1] = READ_ONCE(x);

     즉, READ_ONCE() 와 WRITE_ONCE() 는 여러 CPU 에서 하나의 변수에 가해지는
     액세스들에 캐시 일관성을 제공합니다.

 (*) 컴파일러는 같은 변수에 대한 연속적인 로드들을 병합할 수 있습니다.  그런
     병합 작업으로 컴파일러는 다음의 코드를:

	while (tmp = a)
		do_something_with(tmp);

     다음과 같이, 싱글 쓰레드 코드에서는 말이 되지만 개발자의 의도와 전혀 맞지
     않는 방향으로 "최적화" 할 수 있습니다:

	if (tmp = a)
		for (;;)
			do_something_with(tmp);

     컴파일러가 이런 짓을 하지 못하게 하려면 READ_ONCE() 를 사용하세요:

	while (tmp = READ_ONCE(a))
		do_something_with(tmp);

 (*) 예컨대 레지스터 사용량이 많아 컴파일러가 모든 데이터를 레지스터에 담을 수
     없는 경우, 컴파일러는 변수를 다시 로드할 수 있습니다.  따라서 컴파일러는
     앞의 예에서 변수 'tmp' 사용을 최적화로 없애버릴 수 있습니다:

	while (tmp = a)
		do_something_with(tmp);

     이 코드는 다음과 같이 싱글 쓰레드에서는 완벽하지만 동시성이 존재하는
     경우엔 치명적인 코드로 바뀔 수 있습니다:

	while (a)
		do_something_with(a);

     예를 들어, 최적화된 이 코드는 변수 a 가 다른 CPU 에 의해 "while" 문과
     do_something_with() 호출 사이에 바뀌어 do_something_with() 에 0을 넘길
     수도 있습니다.

     이번에도, 컴파일러가 그런 짓을 하는걸 막기 위해 READ_ONCE() 를 사용하세요:

	while (tmp = READ_ONCE(a))
		do_something_with(tmp);

     레지스터가 부족한 상황을 겪는 경우, 컴파일러는 tmp 를 스택에 저장해둘 수도
     있습니다.  컴파일러가 변수를 다시 읽어들이는건 이렇게 저장해두고 후에 다시
     읽어들이는데 드는 오버헤드 때문입니다.  그렇게 하는게 싱글 쓰레드
     코드에서는 안전하므로, 안전하지 않은 경우에는 컴파일러에게 직접 알려줘야
     합니다.

 (*) 컴파일러는 그 값이 무엇일지 알고 있다면 로드를 아예 안할 수도 있습니다.
     예를 들어, 다음의 코드는 변수 'a' 의 값이 항상 0임을 증명할 수 있다면:

	while (tmp = a)
		do_something_with(tmp);

     이렇게 최적화 되어버릴 수 있습니다:

	do { } while (0);

     이 변환은 싱글 쓰레드 코드에서는 도움이 되는데 로드와 브랜치를 제거했기
     때문입니다.  문제는 컴파일러가 'a' 의 값을 업데이트 하는건 현재의 CPU 하나
     뿐이라는 가정 위에서 증명을 했다는데 있습니다.  만약 변수 'a' 가 공유되어
     있다면, 컴파일러의 증명은 틀린 것이 될겁니다.  컴파일러는 그 자신이
     생각하는 것만큼 많은 것을 알고 있지 못함을 컴파일러에게 알리기 위해
     READ_ONCE() 를 사용하세요:

	while (tmp = READ_ONCE(a))
		do_something_with(tmp);

     하지만 컴파일러는 READ_ONCE() 뒤에 나오는 값에 대해서도 눈길을 두고 있음을
     기억하세요.  예를 들어, 다음의 코드에서 MAX 는 전처리기 매크로로, 1의 값을
     갖는다고 해봅시다:

	while ((tmp = READ_ONCE(a)) % MAX)
		do_something_with(tmp);

     이렇게 되면 컴파일러는 MAX 를 가지고 수행되는 "%" 오퍼레이터의 결과가 항상
     0이라는 것을 알게 되고, 컴파일러가 코드를 실질적으로는 존재하지 않는
     것처럼 최적화 하는 것이 허용되어 버립니다.  ('a' 변수의 로드는 여전히
     행해질 겁니다.)

 (*) 비슷하게, 컴파일러는 변수가 저장하려 하는 값을 이미 가지고 있다는 것을
     알면 스토어 자체를 제거할 수 있습니다.  이번에도, 컴파일러는 현재의 CPU
     만이 그 변수에 값을 쓰는 오로지 하나의 존재라고 생각하여 공유된 변수에
     대해서는 잘못된 일을 하게 됩니다.  예를 들어, 다음과 같은 경우가 있을 수
     있습니다:

	a = 0;
	... 변수 a 에 스토어를 하지 않는 코드 ...
	a = 0;

     컴파일러는 변수 'a' 의 값은 이미 0이라는 것을 알고, 따라서 두번째 스토어를
     삭제할 겁니다.  만약 다른 CPU 가 그 사이 변수 'a' 에 다른 값을 썼다면
     황당한 결과가 나올 겁니다.

     컴파일러가 그런 잘못된 추측을 하지 않도록 WRITE_ONCE() 를 사용하세요:

	WRITE_ONCE(a, 0);
	... 변수 a 에 스토어를 하지 않는 코드 ...
	WRITE_ONCE(a, 0);

 (*) 컴파일러는 하지 말라고 하지 않으면 메모리 액세스들을 재배치 할 수
     있습니다.  예를 들어, 다음의 프로세스 레벨 코드와 인터럽트 핸들러 사이의
     상호작용을 생각해 봅시다:

	void process_level(void)
	{
		msg = get_message();
		flag = true;
	}

	void interrupt_handler(void)
	{
		if (flag)
			process_message(msg);
	}

     이 코드에는 컴파일러가 process_level() 을 다음과 같이 변환하는 것을 막을
     수단이 없고, 이런 변환은 싱글쓰레드에서라면 실제로 훌륭한 선택일 수
     있습니다:

	void process_level(void)
	{
		flag = true;
		msg = get_message();
	}

     이 두개의 문장 사이에 인터럽트가 발생한다면, interrupt_handler() 는 의미를
     알 수 없는 메세지를 받을 수도 있습니다.  이걸 막기 위해 다음과 같이
     WRITE_ONCE() 를 사용하세요:

	void process_level(void)
	{
		WRITE_ONCE(msg, get_message());
		WRITE_ONCE(flag, true);
	}

	void interrupt_handler(void)
	{
		if (READ_ONCE(flag))
			process_message(READ_ONCE(msg));
	}

     interrupt_handler() 안에서도 중첩된 인터럽트나 NMI 와 같이 인터럽트 핸들러
     역시 'flag' 와 'msg' 에 접근하는 또다른 무언가에 인터럽트 될 수 있다면
     READ_ONCE() 와 WRITE_ONCE() 를 사용해야 함을 기억해 두세요.  만약 그런
     가능성이 없다면, interrupt_handler() 안에서는 문서화 목적이 아니라면
     READ_ONCE() 와 WRITE_ONCE() 는 필요치 않습니다.  (근래의 리눅스 커널에서
     중첩된 인터럽트는 보통 잘 일어나지 않음도 기억해 두세요, 실제로, 어떤
     인터럽트 핸들러가 인터럽트가 활성화된 채로 리턴하면 WARN_ONCE() 가
     실행됩니다.)

     컴파일러는 READ_ONCE() 와 WRITE_ONCE() 뒤의 READ_ONCE() 나 WRITE_ONCE(),
     barrier(), 또는 비슷한 것들을 담고 있지 않은 코드를 움직일 수 있을 것으로
     가정되어야 합니다.

     이 효과는 barrier() 를 통해서도 만들 수 있지만, READ_ONCE() 와
     WRITE_ONCE() 가 좀 더 안목 높은 선택입니다: READ_ONCE() 와 WRITE_ONCE()는
     컴파일러에 주어진 메모리 영역에 대해서만 최적화 가능성을 포기하도록
     하지만, barrier() 는 컴파일러가 지금까지 기계의 레지스터에 캐시해 놓은
     모든 메모리 영역의 값을 버려야 하게 하기 때문입니다.  물론, 컴파일러는
     READ_ONCE() 와 WRITE_ONCE() 가 일어난 순서도 지켜줍니다, CPU 는 당연히
     그 순서를 지킬 의무가 없지만요.

 (*) 컴파일러는 다음의 예에서와 같이 변수에의 스토어를 날조해낼 수도 있습니다:

	if (a)
		b = a;
	else
		b = 42;

     컴파일러는 아래와 같은 최적화로 브랜치를 줄일 겁니다:

	b = 42;
	if (a)
		b = a;

     싱글 쓰레드 코드에서 이 최적화는 안전할 뿐 아니라 브랜치 갯수를
     줄여줍니다.  하지만 안타깝게도, 동시성이 있는 코드에서는 이 최적화는 다른
     CPU 가 'b' 를 로드할 때, -- 'a' 가 0이 아닌데도 -- 가짜인 값, 42를 보게
     되는 경우를 가능하게 합니다.  이걸 방지하기 위해 WRITE_ONCE() 를
     사용하세요:

	if (a)
		WRITE_ONCE(b, a);
	else
		WRITE_ONCE(b, 42);

     컴파일러는 로드를 만들어낼 수도 있습니다.  일반적으로는 문제를 일으키지
     않지만, 캐시 라인 바운싱을 일으켜 성능과 확장성을 떨어뜨릴 수 있습니다.
     날조된 로드를 막기 위해선 READ_ONCE() 를 사용하세요.

 (*) 정렬된 메모리 주소에 위치한, 한번의 메모리 참조 인스트럭션으로 액세스
     가능한 크기의 데이터는 하나의 큰 액세스가 여러개의 작은 액세스들로
     대체되는 "로드 티어링(load tearing)" 과 "스토어 티어링(store tearing)" 을
     방지합니다.  예를 들어, 주어진 아키텍쳐가 7-bit imeediate field 를 갖는
     16-bit 스토어 인스트럭션을 제공한다면, 컴파일러는 다음의 32-bit 스토어를
     구현하는데에 두개의 16-bit store-immediate 명령을 사용하려 할겁니다:

	p = 0x00010002;

     스토어 할 상수를 만들고 그 값을 스토어 하기 위해 두개가 넘는 인스트럭션을
     사용하게 되는, 이런 종류의 최적화를 GCC 는 실제로 함을 부디 알아 두십시오.
     이 최적화는 싱글 쓰레드 코드에서는 성공적인 최적화 입니다.  실제로, 근래에
     발생한 (그리고 고쳐진) 버그는 GCC 가 volatile 스토어에 비정상적으로 이
     최적화를 사용하게 했습니다.  그런 버그가 없다면, 다음의 예에서
     WRITE_ONCE() 의 사용은 스토어 티어링을 방지합니다:

	WRITE_ONCE(p, 0x00010002);

     Packed 구조체의 사용 역시 다음의 예처럼  로드 / 스토어 티어링을 유발할 수
     있습니다:

	struct __attribute__((__packed__)) foo {
		short a;
		int b;
		short c;
	};
	struct foo foo1, foo2;
	...

	foo2.a = foo1.a;
	foo2.b = foo1.b;
	foo2.c = foo1.c;

     READ_ONCE() 나 WRITE_ONCE() 도 없고 volatile 마킹도 없기 때문에,
     컴파일러는 이 세개의 대입문을 두개의 32-bit 로드와 두개의 32-bit 스토어로
     변환할 수 있습니다.  이는 'foo1.b' 의 값의 로드 티어링과 'foo2.b' 의
     스토어 티어링을 초래할 겁니다.  이 예에서도 READ_ONCE() 와 WRITE_ONCE()
     가 티어링을 막을 수 있습니다:

	foo2.a = foo1.a;
	WRITE_ONCE(foo2.b, READ_ONCE(foo1.b));
	foo2.c = foo1.c;

그렇지만, volatile 로 마크된 변수에 대해서는 READ_ONCE() 와 WRITE_ONCE() 가
필요치 않습니다.  예를 들어, 'jiffies' 는 volatile 로 마크되어 있기 때문에,
READ_ONCE(jiffies) 라고 할 필요가 없습니다.  READ_ONCE() 와 WRITE_ONCE() 가
실은 volatile 캐스팅으로 구현되어 있어서 인자가 이미 volatile 로 마크되어
있다면 또다른 효과를 내지는 않기 때문입니다.

이 컴파일러 배리어들은 CPU 에는 직접적 효과를 전혀 만들지 않기 때문에, 결국은
재배치가 일어날 수도 있음을 부디 기억해 두십시오.


CPU 메모리 배리어
-----------------

리눅스 커널은 다음의 일곱개 기본 CPU 메모리 배리어를 가지고 있습니다:

	TYPE		MANDATORY		SMP CONDITIONAL
	===============	=======================	===============
	범용		mb()			smp_mb()
	쓰기		wmb()			smp_wmb()
	읽기		rmb()			smp_rmb()
	주소 의존성				READ_ONCE()


주소 의존성 배리어를 제외한 모든 메모리 배리어는 컴파일러 배리어를 포함합니다.
주소 의존성은 컴파일러에의 추가적인 순서 보장을 포함하지 않습니다.

방백: 주소 의존성이 있는 경우, 컴파일러는 해당 로드를 올바른 순서로 일으킬
것으로 (예: `a[b]` 는 a[b] 를 로드 하기 전에 b 의 값을 먼저 로드한다)
기대되지만, C 언어 사양에는 컴파일러가 b 의 값을 추측 (예: 1 과 같음) 해서
b  로드 전에 a 로드를 하는 코드 (예: tmp = a[1]; if (b != 1) tmp = a[b]; ) 를
만들지 않아야 한다는 내용 같은 건 없습니다.  또한 컴파일러는 a[b] 를 로드한
후에 b 를 또다시 로드할 수도 있어서, a[b] 보다 최신 버전의 b 값을 가질 수도
있습니다.  이런 문제들의 해결책에 대한 의견 일치는 아직 없습니다만, 일단
READ_ONCE() 매크로부터 보기 시작하는게 좋은 시작이 될겁니다.

SMP 메모리 배리어들은 유니프로세서로 컴파일된 시스템에서는 컴파일러 배리어로
바뀌는데, 하나의 CPU 는 스스로 일관성을 유지하고, 겹치는 액세스들 역시 올바른
순서로 행해질 것으로 생각되기 때문입니다.  하지만, 아래의 "Virtual Machine
Guests" 서브섹션을 참고하십시오.

[!] SMP 시스템에서 공유메모리로의 접근들을 순서 세워야 할 때, SMP 메모리
배리어는 _반드시_ 사용되어야 함을 기억하세요, 그대신 락을 사용하는 것으로도
충분하긴 하지만 말이죠.

Mandatory 배리어들은 SMP 시스템에서도 UP 시스템에서도 SMP 효과만 통제하기에는
불필요한 오버헤드를 갖기 때문에 SMP 효과만 통제하면 되는 곳에는 사용되지 않아야
합니다.  하지만, 느슨한 순서 규칙의 메모리 I/O 윈도우를 통한 MMIO 의 효과를
통제할 때에는 mandatory 배리어들이 사용될 수 있습니다.  이 배리어들은
컴파일러와 CPU 모두 재배치를 못하도록 함으로써 메모리 오퍼레이션들이 디바이스에
보여지는 순서에도 영향을 주기 때문에, SMP 가 아닌 시스템이라 할지라도 필요할 수
있습니다.


일부 고급 배리어 함수들도 있습니다:

 (*) smp_store_mb(var, value)

     이 함수는 특정 변수에 특정 값을 대입하고 범용 메모리 배리어를 칩니다.
     UP 컴파일에서는 컴파일러 배리어보다 더한 것을 친다고는 보장되지 않습니다.


 (*) smp_mb__before_atomic();
 (*) smp_mb__after_atomic();

     이것들은 메모리 배리어를 내포하지 않는 어토믹 RMW 함수를 사용하지만 코드에
     메모리 배리어가 필요한 경우를 위한 것들입니다.  메모리 배리어를 내포하지
     않는 어토믹 RMW 함수들의 예로는 더하기, 빼기, (실패한) 조건적
     오퍼레이션들, _relaxed 함수들이 있으며, atomic_read 나 atomic_set 은 이에
     해당되지 않습니다.  메모리 배리어가 필요해지는 흔한 예로는 어토믹
     오퍼레이션을 사용해 레퍼런스 카운트를 수정하는 경우를 들 수 있습니다.

     이것들은 또한 (set_bit 과 clear_bit 같은) 메모리 배리어를 내포하지 않는
     어토믹 RMW bitop 함수들을 위해서도 사용될 수 있습니다.

     한 예로, 객체 하나를 무효한 것으로 표시하고 그 객체의 레퍼런스 카운트를
     감소시키는 다음 코드를 보세요:

	obj->dead = 1;
	smp_mb__before_atomic();
	atomic_dec(&obj->ref_count);

     이 코드는 객체의 업데이트된 death 마크가 레퍼런스 카운터 감소 동작
     *전에* 보일 것을 보장합니다.

     더 많은 정보를 위해선 Documentation/atomic_{t,bitops}.txt 문서를
     참고하세요.


 (*) dma_wmb();
 (*) dma_rmb();
 (*) dma_mb();

     이것들은 CPU 와 DMA 가능한 디바이스에서 모두 액세스 가능한 공유 메모리의
     읽기, 쓰기 작업들의 순서를 보장하기 위해 consistent memory 에서 사용하기
     위한 것들입니다.

     예를 들어, 디바이스와 메모리를 공유하며, 디스크립터 상태 값을 사용해
     디스크립터가 디바이스에 속해 있는지 아니면 CPU 에 속해 있는지 표시하고,
     공지용 초인종(doorbell) 을 사용해 업데이트된 디스크립터가 디바이스에 사용
     가능해졌음을 공지하는 디바이스 드라이버를 생각해 봅시다:

	if (desc->status != DEVICE_OWN) {
		/* 디스크립터를 소유하기 전에는 데이터를 읽지 않음 */
		dma_rmb();

		/* 데이터를 읽고 씀 */
		read_data = desc->data;
		desc->data = write_data;

		/* 상태 업데이트 전 수정사항을 반영 */
		dma_wmb();

		/* 소유권을 수정 */
		desc->status = DEVICE_OWN;

		/* 업데이트된 디스크립터의 디바이스에 공지 */
		writel(DESC_NOTIFY, doorbell);
	}

     dma_rmb() 는 디스크립터로부터 데이터를 읽어오기 전에 디바이스가 소유권을
     내려놓았을 것을 보장하고, dma_wmb() 는 디바이스가 자신이 소유권을 다시
     가졌음을 보기 전에 디스크립터에 데이터가 쓰였을 것을 보장합니다.  dma_mb()
     는 dma_rmb() 와 dma_wmb() 를 모두 내포합니다.  참고로, writel() 을
     사용하면 캐시 일관성이 있는 메모리 (cache coherent memory) 쓰기가 MMIO
     영역에의 쓰기 전에 완료되었을 것을 보장하므로 writel() 앞에 wmb() 를
     실행할 필요가 없음을 알아두시기 바랍니다.  writel() 보다 비용이 저렴한
     writel_relaxed() 는 이런 보장을 제공하지 않으므로 여기선 사용되지 않아야
     합니다.

     writel_relaxed() 와 같은 완화된 I/O 접근자들에 대한 자세한 내용을 위해서는
     "커널 I/O 배리어의 효과" 섹션을, consistent memory 에 대한 자세한 내용을
     위해선 Documentation/core-api/dma-api.rst 문서를 참고하세요.

 (*) pmem_wmb();

     이것은 persistent memory 를 위한 것으로, persistent 저장소에 가해진 변경
     사항이 플랫폼 연속성 도메인에 도달했을 것을 보장하기 위한 것입니다.

     예를 들어, 임시적이지 않은 pmem 영역으로의 쓰기 후, 우리는 쓰기가 플랫폼
     연속성 도메인에 도달했을 것을 보장하기 위해 pmem_wmb() 를 사용합니다.
     이는 쓰기가 뒤따르는 instruction 들이 유발하는 어떠한 데이터 액세스나
     데이터 전송의 시작 전에 persistent 저장소를 업데이트 했을 것을 보장합니다.
     이는 wmb() 에 의해 이뤄지는 순서 규칙을 포함합니다.

     Persistent memory 에서의 로드를 위해선 현재의 읽기 메모리 배리어로도 읽기
     순서를 보장하는데 충분합니다.

  (*) io_stop_wc();

     쓰기와 결합된 특성을 갖는 메모리 액세스의 경우 (예: ioremap_wc() 에 의해
     리턴되는 것들), CPU 는 앞의 액세스들이 뒤따르는 것들과 병합되게끔 기다릴
     수 있습니다.  io_stop_wc() 는 그런 기다림이 성능에 영향을 끼칠 수 있을 때,
     이 매크로 앞의 쓰기-결합된 메모리 액세스들이 매크로 뒤의 것들과 병합되는
     것을 방지하기 위해 사용될 수 있습니다.

=========================
암묵적 커널 메모리 배리어
=========================

리눅스 커널의 일부 함수들은 메모리 배리어를 내장하고 있는데, 락(lock)과
스케쥴링 관련 함수들이 대부분입니다.

여기선 _최소한의_ 보장을 설명합니다; 특정 아키텍쳐에서는 이 설명보다 더 많은
보장을 제공할 수도 있습니다만 해당 아키텍쳐에 종속적인 코드 외의 부분에서는
그런 보장을 기대해선 안될겁니다.


락 ACQUISITION 함수
-------------------

리눅스 커널은 다양한 락 구성체를 가지고 있습니다:

 (*) 스핀 락
 (*) R/W 스핀 락
 (*) 뮤텍스
 (*) 세마포어
 (*) R/W 세마포어

각 구성체마다 모든 경우에 "ACQUIRE" 오퍼레이션과 "RELEASE" 오퍼레이션의 변종이
존재합니다.  이 오퍼레이션들은 모두 적절한 배리어를 내포하고 있습니다:

 (1) ACQUIRE 오퍼레이션의 영향:

     ACQUIRE 뒤에서 요청된 메모리 오퍼레이션은 ACQUIRE 오퍼레이션이 완료된
     뒤에 완료됩니다.

     ACQUIRE 앞에서 요청된 메모리 오퍼레이션은 ACQUIRE 오퍼레이션이 완료된 후에
     완료될 수 있습니다.

 (2) RELEASE 오퍼레이션의 영향:

     RELEASE 앞에서 요청된 메모리 오퍼레이션은 RELEASE 오퍼레이션이 완료되기
     전에 완료됩니다.

     RELEASE 뒤에서 요청된 메모리 오퍼레이션은 RELEASE 오퍼레이션 완료 전에
     완료될 수 있습니다.

 (3) ACQUIRE vs ACQUIRE 영향:

     어떤 ACQUIRE 오퍼레이션보다 앞에서 요청된 모든 ACQUIRE 오퍼레이션은 그
     ACQUIRE 오퍼레이션 전에 완료됩니다.

 (4) ACQUIRE vs RELEASE implication:

     어떤 RELEASE 오퍼레이션보다 앞서 요청된 ACQUIRE 오퍼레이션은 그 RELEASE
     오퍼레이션보다 먼저 완료됩니다.

 (5) 실패한 조건적 ACQUIRE 영향:

     ACQUIRE 오퍼레이션의 일부 락(lock) 변종은 락이 곧바로 획득하기에는
     불가능한 상태이거나 락이 획득 가능해지도록 기다리는 도중 시그널을 받거나
     해서 실패할 수 있습니다.  실패한 락은 어떤 배리어도 내포하지 않습니다.

[!] 참고: 락 ACQUIRE 와 RELEASE 가 단방향 배리어여서 나타나는 현상 중 하나는
크리티컬 섹션 바깥의 인스트럭션의 영향이 크리티컬 섹션 내부로도 들어올 수
있다는 것입니다.

RELEASE 후에 요청되는 ACQUIRE 는 전체 메모리 배리어라 여겨지면 안되는데,
ACQUIRE 앞의 액세스가 ACQUIRE 후에 수행될 수 있고, RELEASE 후의 액세스가
RELEASE 전에 수행될 수도 있으며, 그 두개의 액세스가 서로를 지나칠 수도 있기
때문입니다:

	*A = a;
	ACQUIRE M
	RELEASE M
	*B = b;

는 다음과 같이 될 수도 있습니다:

	ACQUIRE M, STORE *B, STORE *A, RELEASE M

ACQUIRE 와 RELEASE 가 락 획득과 해제라면, 그리고 락의 ACQUIRE 와 RELEASE 가
같은 락 변수에 대한 것이라면, 해당 락을 쥐고 있지 않은 다른 CPU 의 시야에는
이와 같은 재배치가 일어나는 것으로 보일 수 있습니다.  요약하자면, ACQUIRE 에
이어 RELEASE 오퍼레이션을 순차적으로 실행하는 행위가 전체 메모리 배리어로
생각되어선 -안됩니다-.

비슷하게, 앞의 반대 케이스인 RELEASE 와 ACQUIRE 두개 오퍼레이션의 순차적 실행
역시 전체 메모리 배리어를 내포하지 않습니다.  따라서, RELEASE, ACQUIRE 로
규정되는 크리티컬 섹션의 CPU 수행은 RELEASE 와 ACQUIRE 를 가로지를 수 있으므로,
다음과 같은 코드는:

	*A = a;
	RELEASE M
	ACQUIRE N
	*B = b;

다음과 같이 수행될 수 있습니다:

	ACQUIRE N, STORE *B, STORE *A, RELEASE M

이런 재배치는 데드락을 일으킬 수도 있을 것처럼 보일 수 있습니다.  하지만, 그런
데드락의 조짐이 있다면 RELEASE 는 단순히 완료될 것이므로 데드락은 존재할 수
없습니다.

	이게 어떻게 올바른 동작을 할 수 있을까요?

	우리가 이야기 하고 있는건 재배치를 하는 CPU 에 대한 이야기이지,
	컴파일러에 대한 것이 아니란 점이 핵심입니다.  컴파일러 (또는, 개발자)
	가 오퍼레이션들을 이렇게 재배치하면, 데드락이 일어날 수 -있습-니다.

	하지만 CPU 가 오퍼레이션들을 재배치 했다는걸 생각해 보세요.  이 예에서,
	어셈블리 코드 상으로는 언락이 락을 앞서게 되어 있습니다.  CPU 가 이를
	재배치해서 뒤의 락 오퍼레이션을 먼저 실행하게 됩니다.  만약 데드락이
	존재한다면, 이 락 오퍼레이션은 그저 스핀을 하며 계속해서 락을
	시도합니다 (또는, 한참 후에겠지만, 잠듭니다).  CPU 는 언젠가는
	(어셈블리 코드에서는 락을 앞서는) 언락 오퍼레이션을 실행하는데, 이 언락
	오퍼레이션이 잠재적 데드락을 해결하고, 락 오퍼레이션도 뒤이어 성공하게
	됩니다.

	하지만 만약 락이 잠을 자는 타입이었다면요?  그런 경우에 코드는
	스케쥴러로 들어가려 할 거고, 여기서 결국은 메모리 배리어를 만나게
	되는데, 이 메모리 배리어는 앞의 언락 오퍼레이션이 완료되도록 만들고,
	데드락은 이번에도 해결됩니다.  잠을 자는 행위와 언락 사이의 경주 상황
	(race) 도 있을 수 있겠습니다만, 락 관련 기능들은 그런 경주 상황을 모든
	경우에 제대로 해결할 수 있어야 합니다.

락과 세마포어는 UP 컴파일된 시스템에서의 순서에 대해 보장을 하지 않기 때문에,
그런 상황에서 인터럽트 비활성화 오퍼레이션과 함께가 아니라면 어떤 일에도 - 특히
I/O 액세스와 관련해서는 - 제대로 사용될 수 없을 겁니다.

"CPU 간 ACQUIRING 배리어 효과" 섹션도 참고하시기 바랍니다.


예를 들어, 다음과 같은 코드를 생각해 봅시다:

	*A = a;
	*B = b;
	ACQUIRE
	*C = c;
	*D = d;
	RELEASE
	*E = e;
	*F = f;

여기선 다음의 이벤트 시퀀스가 생길 수 있습니다:

	ACQUIRE, {*F,*A}, *E, {*C,*D}, *B, RELEASE

	[+] {*F,*A} 는 조합된 액세스를 의미합니다.

하지만 다음과 같은 건 불가능하죠:

	{*F,*A}, *B,	ACQUIRE, *C, *D,	RELEASE, *E
	*A, *B, *C,	ACQUIRE, *D,		RELEASE, *E, *F
	*A, *B,		ACQUIRE, *C,		RELEASE, *D, *E, *F
	*B,		ACQUIRE, *C, *D,	RELEASE, {*F,*A}, *E



인터럽트 비활성화 함수
----------------------

인터럽트를 비활성화 하는 함수 (ACQUIRE 와 동일) 와 인터럽트를 활성화 하는 함수
(RELEASE 와 동일) 는 컴파일러 배리어처럼만 동작합니다.  따라서, 별도의 메모리
배리어나 I/O 배리어가 필요한 상황이라면 그 배리어들은 인터럽트 비활성화 함수
외의 방법으로 제공되어야만 합니다.


슬립과 웨이크업 함수
--------------------

글로벌 데이터에 표시된 이벤트에 의해 프로세스를 잠에 빠트리는 것과 깨우는 것은
해당 이벤트를 기다리는 태스크의 태스크 상태와 그 이벤트를 알리기 위해 사용되는
글로벌 데이터, 두 데이터간의 상호작용으로 볼 수 있습니다.  이것이 옳은 순서대로
일어남을 분명히 하기 위해, 프로세스를 잠에 들게 하는 기능과 깨우는 기능은
몇가지 배리어를 내포합니다.

먼저, 잠을 재우는 쪽은 일반적으로 다음과 같은 이벤트 시퀀스를 따릅니다:

	for (;;) {
		set_current_state(TASK_UNINTERRUPTIBLE);
		if (event_indicated)
			break;
		schedule();
	}

set_current_state() 에 의해, 태스크 상태가 바뀐 후 범용 메모리 배리어가
자동으로 삽입됩니다:

	CPU 1
	===============================
	set_current_state();
	  smp_store_mb();
	    STORE current->state
	    <범용 배리어>
	LOAD event_indicated

set_current_state() 는 다음의 것들로 감싸질 수도 있습니다:

	prepare_to_wait();
	prepare_to_wait_exclusive();

이것들 역시 상태를 설정한 후 범용 메모리 배리어를 삽입합니다.
앞의 전체 시퀀스는 다음과 같은 함수들로 한번에 수행 가능한데, 이것들은 모두
올바른 장소에 메모리 배리어를 삽입합니다:

	wait_event();
	wait_event_interruptible();
	wait_event_interruptible_exclusive();
	wait_event_interruptible_timeout();
	wait_event_killable();
	wait_event_timeout();
	wait_on_bit();
	wait_on_bit_lock();


두번째로, 깨우기를 수행하는 코드는 일반적으로 다음과 같을 겁니다:

	event_indicated = 1;
	wake_up(&event_wait_queue);

또는:

	event_indicated = 1;
	wake_up_process(event_daemon);

wake_up() 이 무언가를 깨우게 되면, 이 함수는 범용 메모리 배리어를 수행합니다.
이 함수가 아무것도 깨우지 않는다면 메모리 배리어는 수행될 수도, 수행되지 않을
수도 있습니다; 이 경우에 메모리 배리어를 수행할 거라 오해해선 안됩니다.  이
배리어는 태스크 상태가 접근되기 전에 수행되는데, 자세히 말하면 이 이벤트를
알리기 위한 STORE 와 TASK_RUNNING 으로 상태를 쓰는 STORE 사이에 수행됩니다:

	CPU 1 (Sleeper)			CPU 2 (Waker)
	===============================	===============================
	set_current_state();		STORE event_indicated
	  smp_store_mb();		wake_up();
	    STORE current->state	  ...
	    <범용 배리어>		  <범용 배리어>
	LOAD event_indicated		  if ((LOAD task->state) & TASK_NORMAL)
					    STORE task->state

여기서 "task" 는 깨어나지는 쓰레드이고 CPU 1 의 "current" 와 같습니다.

반복하지만, wake_up() 이 무언가를 정말 깨운다면 범용 메모리 배리어가 수행될
것이 보장되지만, 그렇지 않다면 그런 보장이 없습니다.  이걸 이해하기 위해, X 와
Y 는 모두 0 으로 초기화 되어 있다는 가정 하에 아래의 이벤트 시퀀스를 생각해
봅시다:

	CPU 1				CPU 2
	===============================	===============================
	X = 1;				Y = 1;
	smp_mb();			wake_up();
	LOAD Y				LOAD X

정말로 깨우기가 행해졌다면, 두 로드 중 (최소한) 하나는 1 을 보게 됩니다.
반면에, 실제 깨우기가 행해지지 않았다면, 두 로드 모두 0을 볼 수도 있습니다.

wake_up_process() 는 항상 범용 메모리 배리어를 수행합니다.  이 배리어 역시
태스크 상태가 접근되기 전에 수행됩니다.  특히, 앞의 예제 코드에서 wake_up() 이
wake_up_process() 로 대체된다면 두 로드 중 하나는 1을 볼 것이 보장됩니다.

사용 가능한 깨우기류 함수들로 다음과 같은 것들이 있습니다:

	complete();
	wake_up();
	wake_up_all();
	wake_up_bit();
	wake_up_interruptible();
	wake_up_interruptible_all();
	wake_up_interruptible_nr();
	wake_up_interruptible_poll();
	wake_up_interruptible_sync();
	wake_up_interruptible_sync_poll();
	wake_up_locked();
	wake_up_locked_poll();
	wake_up_nr();
	wake_up_poll();
	wake_up_process();

메모리 순서규칙 관점에서, 이 함수들은 모두 wake_up() 과 같거나 보다 강한 순서
보장을 제공합니다.

[!] 잠재우는 코드와 깨우는 코드에 내포되는 메모리 배리어들은 깨우기 전에
이루어진 스토어를 잠재우는 코드가 set_current_state() 를 호출한 후에 행하는
로드에 대해 순서를 맞추지 _않는다는_ 점을 기억하세요.  예를 들어, 잠재우는
코드가 다음과 같고:

	set_current_state(TASK_INTERRUPTIBLE);
	if (event_indicated)
		break;
	__set_current_state(TASK_RUNNING);
	do_something(my_data);

깨우는 코드는 다음과 같다면:

	my_data = value;
	event_indicated = 1;
	wake_up(&event_wait_queue);

event_indecated 에의 변경이 잠재우는 코드에게 my_data 에의 변경 후에 이루어진
것으로 인지될 것이라는 보장이 없습니다.  이런 경우에는 양쪽 코드 모두 각각의
데이터 액세스 사이에 메모리 배리어를 직접 쳐야 합니다.  따라서 앞의 재우는
코드는 다음과 같이:

	set_current_state(TASK_INTERRUPTIBLE);
	if (event_indicated) {
		smp_rmb();
		do_something(my_data);
	}

그리고 깨우는 코드는 다음과 같이 되어야 합니다:

	my_data = value;
	smp_wmb();
	event_indicated = 1;
	wake_up(&event_wait_queue);


그외의 함수들
-------------

그외의 배리어를 내포하는 함수들은 다음과 같습니다:

 (*) schedule() 과 그 유사한 것들이 완전한 메모리 배리어를 내포합니다.


==============================
CPU 간 ACQUIRING 배리어의 효과
==============================

SMP 시스템에서의 락 기능들은 더욱 강력한 형태의 배리어를 제공합니다: 이
배리어는 동일한 락을 사용하는 다른 CPU 들의 메모리 액세스 순서에도 영향을
끼칩니다.


ACQUIRE VS 메모리 액세스
------------------------

다음의 예를 생각해 봅시다: 시스템은 두개의 스핀락 (M) 과 (Q), 그리고 세개의 CPU
를 가지고 있습니다; 여기에 다음의 이벤트 시퀀스가 발생합니다:

	CPU 1				CPU 2
	===============================	===============================
	WRITE_ONCE(*A, a);		WRITE_ONCE(*E, e);
	ACQUIRE M			ACQUIRE Q
	WRITE_ONCE(*B, b);		WRITE_ONCE(*F, f);
	WRITE_ONCE(*C, c);		WRITE_ONCE(*G, g);
	RELEASE M			RELEASE Q
	WRITE_ONCE(*D, d);		WRITE_ONCE(*H, h);

*A 로의 액세스부터 *H 로의 액세스까지가 어떤 순서로 CPU 3 에게 보여질지에
대해서는 각 CPU 에서의 락 사용에 의해 내포되어 있는 제약을 제외하고는 어떤
보장도 존재하지 않습니다.  예를 들어, CPU 3 에게 다음과 같은 순서로 보여지는
것이 가능합니다:

	*E, ACQUIRE M, ACQUIRE Q, *G, *C, *F, *A, *B, RELEASE Q, *D, *H, RELEASE M

하지만 다음과 같이 보이지는 않을 겁니다:

	*B, *C or *D preceding ACQUIRE M
	*A, *B or *C following RELEASE M
	*F, *G or *H preceding ACQUIRE Q
	*E, *F or *G following RELEASE Q


=========================
메모리 배리어가 필요한 곳
=========================

설령 SMP 커널을 사용하더라도 싱글 쓰레드로 동작하는 코드는 올바르게 동작하는
것으로 보여질 것이기 때문에, 평범한 시스템 운영중에 메모리 오퍼레이션 재배치는
일반적으로 문제가 되지 않습니다.  하지만, 재배치가 문제가 _될 수 있는_ 네가지
환경이 있습니다:

 (*) 프로세서간 상호 작용.

 (*) 어토믹 오퍼레이션.

 (*) 디바이스 액세스.

 (*) 인터럽트.


프로세서간 상호 작용
--------------------

두개 이상의 프로세서를 가진 시스템이 있다면, 시스템의 두개 이상의 CPU 는 동시에
같은 데이터에 대한 작업을 할 수 있습니다.  이는 동기화 문제를 일으킬 수 있고,
이 문제를 해결하는 일반적 방법은 락을 사용하는 것입니다.  하지만, 락은 상당히
비용이 비싸서 가능하면 락을 사용하지 않고 일을 처리하는 것이 낫습니다.  이런
경우, 두 CPU 모두에 영향을 끼치는 오퍼레이션들은 오동작을 막기 위해 신중하게
순서가 맞춰져야 합니다.

예를 들어, R/W 세마포어의 느린 수행경로 (slow path) 를 생각해 봅시다.
세마포어를 위해 대기를 하는 하나의 프로세스가 자신의 스택 중 일부를 이
세마포어의 대기 프로세스 리스트에 링크한 채로 있습니다:

	struct rw_semaphore {
		...
		spinlock_t lock;
		struct list_head waiters;
	};

	struct rwsem_waiter {
		struct list_head list;
		struct task_struct *task;
	};

특정 대기 상태 프로세스를 깨우기 위해, up_read() 나 up_write() 함수는 다음과
같은 일을 합니다:

 (1) 다음 대기 상태 프로세스 레코드는 어디있는지 알기 위해 이 대기 상태
     프로세스 레코드의 next 포인터를 읽습니다;

 (2) 이 대기 상태 프로세스의 task 구조체로의 포인터를 읽습니다;

 (3) 이 대기 상태 프로세스가 세마포어를 획득했음을 알리기 위해 task
     포인터를 초기화 합니다;

 (4) 해당 태스크에 대해 wake_up_process() 를 호출합니다; 그리고

 (5) 해당 대기 상태 프로세스의 task 구조체를 잡고 있던 레퍼런스를 해제합니다.

달리 말하자면, 다음 이벤트 시퀀스를 수행해야 합니다:

	LOAD waiter->list.next;
	LOAD waiter->task;
	STORE waiter->task;
	CALL wakeup
	RELEASE task

그리고 이 이벤트들이 다른 순서로 수행된다면, 오동작이 일어날 수 있습니다.

한번 세마포어의 대기줄에 들어갔고 세마포어 락을 놓았다면, 해당 대기 프로세스는
락을 다시는 잡지 않습니다; 대신 자신의 task 포인터가 초기화 되길 기다립니다.
그 레코드는 대기 프로세스의 스택에 있기 때문에, 리스트의 next 포인터가 읽혀지기
_전에_ task 포인터가 지워진다면, 다른 CPU 는 해당 대기 프로세스를 시작해 버리고
up*() 함수가 next 포인터를 읽기 전에 대기 프로세스의 스택을 마구 건드릴 수
있습니다.

그렇게 되면 위의 이벤트 시퀀스에 어떤 일이 일어나는지 생각해 보죠:

	CPU 1				CPU 2
	===============================	===============================
					down_xxx()
					Queue waiter
					Sleep
	up_yyy()
	LOAD waiter->task;
	STORE waiter->task;
					Woken up by other event
	<preempt>
					Resume processing
					down_xxx() returns
					call foo()
					foo() clobbers *waiter
	</preempt>
	LOAD waiter->list.next;
	--- OOPS ---

이 문제는 세마포어 락의 사용으로 해결될 수도 있겠지만, 그렇게 되면 깨어난 후에
down_xxx() 함수가 불필요하게 스핀락을 또다시 얻어야만 합니다.

이 문제를 해결하는 방법은 범용 SMP 메모리 배리어를 추가하는 겁니다:

	LOAD waiter->list.next;
	LOAD waiter->task;
	smp_mb();
	STORE waiter->task;
	CALL wakeup
	RELEASE task

이 경우에, 배리어는 시스템의 나머지 CPU 들에게 모든 배리어 앞의 메모리 액세스가
배리어 뒤의 메모리 액세스보다 앞서 일어난 것으로 보이게 만듭니다.  배리어 앞의
메모리 액세스들이 배리어 명령 자체가 완료되는 시점까지 완료된다고는 보장하지
_않습니다_.

(이게 문제가 되지 않을) 단일 프로세서 시스템에서 smp_mb() 는 실제로는 그저
컴파일러가 CPU 안에서의 순서를 바꾸거나 하지 않고 주어진 순서대로 명령을
내리도록 하는 컴파일러 배리어일 뿐입니다.  오직 하나의 CPU 만 있으니, CPU 의
의존성 순서 로직이 그 외의 모든것을 알아서 처리할 겁니다.


어토믹 오퍼레이션
-----------------

어토믹 오퍼레이션은 기술적으로 프로세서간 상호작용으로 분류되며 그 중 일부는
전체 메모리 배리어를 내포하고 또 일부는 내포하지 않지만, 커널에서 상당히
의존적으로 사용하는 기능 중 하나입니다.

더 많은 내용을 위해선 Documentation/atomic_t.txt 를 참고하세요.


디바이스 액세스
---------------

많은 디바이스가 메모리 매핑 기법으로 제어될 수 있는데, 그렇게 제어되는
디바이스는 CPU 에는 단지 특정 메모리 영역의 집합처럼 보이게 됩니다.  드라이버는
그런 디바이스를 제어하기 위해 정확히 올바른 순서로 올바른 메모리 액세스를
만들어야 합니다.

하지만, 액세스들을 재배치 하거나 조합하거나 병합하는게 더 효율적이라 판단하는
영리한 CPU 나 컴파일러들을 사용하면 드라이버 코드의 조심스럽게 순서 맞춰진
액세스들이 디바이스에는 요청된 순서대로 도착하지 못하게 할 수 있는 - 디바이스가
오동작을 하게 할 - 잠재적 문제가 생길 수 있습니다.

리눅스 커널 내부에서, I/O 는 어떻게 액세스들을 적절히 순차적이게 만들 수 있는지
알고 있는, - inb() 나 writel() 과 같은 - 적절한 액세스 루틴을 통해 이루어져야만
합니다.  이것들은 대부분의 경우에는 명시적 메모리 배리어 와 함께 사용될 필요가
없습니다만, 완화된 메모리 액세스 속성으로 I/O 메모리 윈도우로의 참조를 위해
액세스 함수가 사용된다면 순서를 강제하기 위해 _mandatory_ 메모리 배리어가
필요합니다.

더 많은 정보를 위해선 Documentation/driver-api/device-io.rst 를 참고하십시오.


인터럽트
--------

드라이버는 자신의 인터럽트 서비스 루틴에 의해 인터럽트 당할 수 있기 때문에
드라이버의 이 두 부분은 서로의 디바이스 제어 또는 액세스 부분과 상호 간섭할 수
있습니다.

스스로에게 인터럽트 당하는 걸 불가능하게 하고, 드라이버의 크리티컬한
오퍼레이션들을 모두 인터럽트가 불가능하게 된 영역에 집어넣거나 하는 방법 (락의
한 형태) 으로 이런 상호 간섭을 - 최소한 부분적으로라도 - 줄일 수 있습니다.
드라이버의 인터럽트 루틴이 실행 중인 동안, 해당 드라이버의 코어는 같은 CPU 에서
수행되지 않을 것이며, 현재의 인터럽트가 처리되는 중에는 또다시 인터럽트가
일어나지 못하도록 되어 있으니 인터럽트 핸들러는 그에 대해서는 락을 잡지 않아도
됩니다.

하지만, 어드레스 레지스터와 데이터 레지스터를 갖는 이더넷 카드를 다루는
드라이버를 생각해 봅시다.  만약 이 드라이버의 코어가 인터럽트를 비활성화시킨
채로 이더넷 카드와 대화하고 드라이버의 인터럽트 핸들러가 호출되었다면:

	LOCAL IRQ DISABLE
	writew(ADDR, 3);
	writew(DATA, y);
	LOCAL IRQ ENABLE
	<interrupt>
	writew(ADDR, 4);
	q = readw(DATA);
	</interrupt>

만약 순서 규칙이 충분히 완화되어 있다면 데이터 레지스터에의 스토어는 어드레스
레지스터에 두번째로 행해지는 스토어 뒤에 일어날 수도 있습니다:

	STORE *ADDR = 3, STORE *ADDR = 4, STORE *DATA = y, q = LOAD *DATA


만약 순서 규칙이 충분히 완화되어 있고 묵시적으로든 명시적으로든 배리어가
사용되지 않았다면 인터럽트 비활성화 섹션에서 일어난 액세스가 바깥으로 새어서
인터럽트 내에서 일어난 액세스와 섞일 수 있다고 - 그리고 그 반대도 - 가정해야만
합니다.

그런 영역 안에서 일어나는 I/O 액세스는 묵시적 I/O 배리어를 형성하는, 엄격한
순서 규칙의 I/O 레지스터로의 로드 오퍼레이션을 포함하기 때문에 일반적으로는
문제가 되지 않습니다.


하나의 인터럽트 루틴과 별도의 CPU 에서 수행중이며 서로 통신을 하는 두 루틴
사이에도 비슷한 상황이 일어날 수 있습니다.  만약 그런 경우가 발생할 가능성이
있다면, 순서를 보장하기 위해 인터럽트 비활성화 락이 사용되어져야만 합니다.


======================
커널 I/O 배리어의 효과
======================

I/O 액세스를 통한 주변장치와의 통신은 아키텍쳐와 기기에 매우 종속적입니다.
따라서, 본질적으로 이식성이 없는 드라이버는 가능한 가장 적은 오버헤드로
동기화를 하기 위해 각자의 타겟 시스템의 특정 동작에 의존할 겁니다.  다양한
아키텍쳐와 버스 구현에 이식성을 가지려 하는 드라이버를 위해, 커널은 다양한
정도의 순서 보장을 제공하는 일련의 액세스 함수를 제공합니다.

 (*) readX(), writeX():

	readX() 와 writeX() MMIO 액세스 함수는 접근되는 주변장치로의 포인터를
	__iomem * 패러미터로 받습니다.  디폴트 I/O 기능으로 매핑되는 포인터
	(예: ioremap() 으로 반환되는 것) 의 순서 보장은 다음과 같습니다:

	1. 같은 주변장치로의 모든 readX() 와 writeX() 액세스는 각자에 대해
	   순서지어집니다.  이는 같은 CPU 쓰레드에 의한 특정 디바이스로의 MMIO
	   레지스터 액세스가 프로그램 순서대로 도착할 것을 보장합니다.

	2. 한 스핀락을 잡은 CPU 쓰레드에 의한 writeX() 는 같은 스핀락을 나중에
	   잡은 다른 CPU 쓰레드에 의해 같은 주변장치를 향해 호출된 writeX()
	   앞으로 순서지어집니다.  이는 스핀락을 잡은 채 특정 디바이스를 향해
	   호출된 MMIO 레지스터 쓰기는 해당 락의 획득에 일관적인 순서로 도달할
	   것을 보장합니다.

	3. 특정 주변장치를 향한 특정 CPU 쓰레드의 writeX() 는 먼저 해당
	   쓰레드로 전파되는, 또는 해당 쓰레드에 의해 요청된 모든 앞선 메모리
	   쓰기가 완료되기 전까지 먼저 기다립니다.  이는 dma_alloc_coherent()
	   를 통해 할당된 전송용 DMA 버퍼로의 해당 CPU 의 쓰기가 이 CPU 가 이
	   전송을 시작시키기 위해 MMIO 컨트롤 레지스터에 쓰기를 할 때 DMA
	   엔진에 보여질 것을 보장합니다.

	4. 특정 CPU 쓰레드에 의한 주변장치로의 readX() 는 같은 쓰레드에 의한
	   모든 뒤따르는 메모리 읽기가 시작되기 전에 완료됩니다.  이는
	   dma_alloc_coherent() 를 통해 할당된 수신용 DMA 버퍼로부터의 CPU 의
	   읽기는 이 DMA 수신의 완료를 표시하는 DMA 엔진의 MMIO 상태 레지스터
	   읽기 후에는 오염된 데이터를 읽지 않을 것을 보장합니다.

	5. CPU 에 의한 주변장치로의 readX() 는 모든 뒤따르는 delay() 루프가
	   수행을 시작하기 전에 완료됩니다.  이는 CPU 의 특정
	   주변장치로의 두개의 MMIO 레지스터 쓰기가 행해지는데 첫번째 쓰기가
	   readX() 를 통해 곧바로 읽어졌고 이어 두번째 writeX() 전에 udelay(1)
	   이 호출되었다면 이 두개의 쓰기는 최소 1us 의 간격을 두고 행해질 것을
	   보장합니다:

		writel(42, DEVICE_REGISTER_0); // 디바이스에 도착함...
		readl(DEVICE_REGISTER_0);
		udelay(1);
		writel(42, DEVICE_REGISTER_1); // ...이것보다 최소 1us 전에.

	디폴트가 아닌 기능을 통해 얻어지는 __iomem 포인터 (예: ioremap_wc() 를
	통해 리턴되는 것) 의 순서 속성은 실제 아키텍쳐에 의존적이어서 이런
	종류의 매핑으로의 액세스는 앞서 설명된 보장사항에 의존할 수 없습니다.

 (*) readX_relaxed(), writeX_relaxed()

	이것들은 readX() 와 writeX() 랑 비슷하지만, 더 완화된 메모리 순서
	보장을 제공합니다.  구체적으로, 이것들은 일반적 메모리 액세스나 delay()
	루프 (예:앞의 2-5 항목) 에 대해 순서를 보장하지 않습니다만 디폴트 I/O
	기능으로 매핑된 __iomem 포인터에 대해 동작할 때, 같은 CPU 쓰레드에 의한
	같은 주변장치로의 액세스에는 순서가 맞춰질 것이 보장됩니다.

 (*) readsX(), writesX():

	readsX() 와 writesX() MMIO 액세스 함수는 DMA 를 수행하는데 적절치 않은,
	주변장치 내의 메모리 매핑된 레지스터 기반 FIFO 로의 액세스를 위해
	설계되었습니다.  따라서, 이 기능들은 앞서 설명된 readX_relaxed() 와
	writeX_relaxed() 의 순서 보장만을 제공합니다.

 (*) inX(), outX():

	inX() 와 outX() 액세스 함수는 일부 아키텍쳐 (특히 x86) 에서는 특수한
	명령어를 필요로 하며 포트에 매핑되는, 과거의 유산인 I/O 주변장치로의
	접근을 위해 만들어졌습니다.

	많은 CPU 아키텍쳐가 결국은 이런 주변장치를 내부의 가상 메모리 매핑을
	통해 접근하기 때문에, inX() 와 outX() 가 제공하는 이식성 있는 순서
	보장은 디폴트 I/O 기능을 통한 매핑을 접근할 때의 readX() 와 writeX() 에
	의해 제공되는 것과 각각 동일합니다.

	디바이스 드라이버는 outX() 가 리턴하기 전에 해당 I/O 주변장치로부터의
	완료 응답을 기다리는 쓰기 트랜잭션을 만들어 낸다고 기대할 수도
	있습니다.  이는 모든 아키텍쳐에서 보장되지는 않고, 따라서 이식성 있는
	순서 규칙의 일부분이 아닙니다.

 (*) insX(), outsX():

	앞에서와 같이, insX() 와 outsX() 액세스 함수는 디폴트 I/O 기능을 통한
	매핑을 접근할 때 각각 readX() 와 writeX() 와 같은 순서 보장을
	제공합니다.

 (*) ioreadX(), iowriteX()

	이것들은 inX()/outX() 나 readX()/writeX() 처럼 실제로 수행하는 액세스의
	종류에 따라 적절하게 수행될 것입니다.

String 액세스 함수 (insX(), outsX(), readsX() 그리고 writesX()) 의 예외를
제외하고는, 앞의 모든 것이 아랫단의 주변장치가 little-endian 이라 가정하며,
따라서 big-endian 아키텍쳐에서는 byte-swapping 오퍼레이션을 수행합니다.


===================================
가정되는 가장 완화된 실행 순서 모델
===================================

컨셉적으로 CPU 는 주어진 프로그램에 대해 프로그램 그 자체에는 인과성 (program
causality) 을 지키는 것처럼 보이게 하지만 일반적으로는 순서를 거의 지켜주지
않는다고 가정되어야만 합니다.  (i386 이나 x86_64 같은) 일부 CPU 들은 코드
재배치에 (powerpc 나 frv 와 같은) 다른 것들에 비해 강한 제약을 갖지만, 아키텍쳐
종속적 코드 이외의 코드에서는 순서에 대한 제약이 가장 완화된 경우 (DEC Alpha)
를 가정해야 합니다.

이 말은, CPU 에게 주어지는 인스트럭션 스트림 내의 한 인스트럭션이 앞의
인스트럭션에 종속적이라면 앞의 인스트럭션은 뒤의 종속적 인스트럭션이 실행되기
전에 완료[*]될 수 있어야 한다는 제약 (달리 말해서, 인과성이 지켜지는 것으로
보이게 함) 외에는 자신이 원하는 순서대로 - 심지어 병렬적으로도 - 그 스트림을
실행할 수 있음을 의미합니다

 [*] 일부 인스트럭션은 하나 이상의 영향 - 조건 코드를 바꾼다던지, 레지스터나
     메모리를 바꾼다던지 - 을 만들어내며, 다른 인스트럭션은 다른 효과에
     종속적일 수 있습니다.

CPU 는 최종적으로 아무 효과도 만들지 않는 인스트럭션 시퀀스는 없애버릴 수도
있습니다.  예를 들어, 만약 두개의 연속되는 인스트럭션이 둘 다 같은 레지스터에
직접적인 값 (immediate value) 을 집어넣는다면, 첫번째 인스트럭션은 버려질 수도
있습니다.


비슷하게, 컴파일러 역시 프로그램의 인과성만 지켜준다면 인스트럭션 스트림을
자신이 보기에 올바르다 생각되는대로 재배치 할 수 있습니다.


===============
CPU 캐시의 영향
===============

캐시된 메모리 오퍼레이션들이 시스템 전체에 어떻게 인지되는지는 CPU 와 메모리
사이에 존재하는 캐시들, 그리고 시스템 상태의 일관성을 관리하는 메모리 일관성
시스템에 상당 부분 영향을 받습니다.

한 CPU 가 시스템의 다른 부분들과 캐시를 통해 상호작용한다면, 메모리 시스템은
CPU 의 캐시들을 포함해야 하며, CPU 와 CPU 자신의 캐시 사이에서의 동작을 위한
메모리 배리어를 가져야 합니다. (메모리 배리어는 논리적으로는 다음 그림의
점선에서 동작합니다):

	    <--- CPU --->         :       <----------- Memory ----------->
	                          :
	+--------+    +--------+  :   +--------+    +-----------+
	|        |    |        |  :   |        |    |           |    +--------+
	|  CPU   |    | Memory |  :   | CPU    |    |           |    |        |
	|  Core  |--->| Access |----->| Cache  |<-->|           |    |        |
	|        |    | Queue  |  :   |        |    |           |--->| Memory |
	|        |    |        |  :   |        |    |           |    |        |
	+--------+    +--------+  :   +--------+    |           |    |        |
	                          :                 | Cache     |    +--------+
	                          :                 | Coherency |
	                          :                 | Mechanism |    +--------+
	+--------+    +--------+  :   +--------+    |           |    |	      |
	|        |    |        |  :   |        |    |           |    |        |
	|  CPU   |    | Memory |  :   | CPU    |    |           |--->| Device |
	|  Core  |--->| Access |----->| Cache  |<-->|           |    |        |
	|        |    | Queue  |  :   |        |    |           |    |        |
	|        |    |        |  :   |        |    |           |    +--------+
	+--------+    +--------+  :   +--------+    +-----------+
	                          :
	                          :

특정 로드나 스토어는 해당 오퍼레이션을 요청한 CPU 의 캐시 내에서 동작을 완료할
수도 있기 때문에 해당 CPU 의 바깥에는 보이지 않을 수 있지만, 다른 CPU 가 관심을
갖는다면 캐시 일관성 메커니즘이 해당 캐시라인을 해당 CPU 에게 전달하고, 해당
메모리 영역에 대한 오퍼레이션이 발생할 때마다 그 영향을 전파시키기 때문에, 해당
오퍼레이션은 메모리에 실제로 액세스를 한것처럼 나타날 것입니다.

CPU 코어는 프로그램의 인과성이 유지된다고만 여겨진다면 인스트럭션들을 어떤
순서로든 재배치해서 수행할 수 있습니다.  일부 인스트럭션들은 로드나 스토어
오퍼레이션을 만드는데 이 오퍼레이션들은 이후 수행될 메모리 액세스 큐에 들어가게
됩니다.  코어는 이 오퍼레이션들을 해당 큐에 어떤 순서로든 원하는대로 넣을 수
있고, 다른 인스트럭션의 완료를 기다리도록 강제되기 전까지는 수행을 계속합니다.

메모리 배리어가 하는 일은 CPU 쪽에서 메모리 쪽으로 넘어가는 액세스들의 순서,
그리고 그 액세스의 결과가 시스템의 다른 관찰자들에게 인지되는 순서를 제어하는
것입니다.

[!] CPU 들은 항상 그들 자신의 로드와 스토어는 프로그램 순서대로 일어난 것으로
보기 때문에, 주어진 CPU 내에서는 메모리 배리어를 사용할 필요가 _없습니다_.

[!] MMIO 나 다른 디바이스 액세스들은 캐시 시스템을 우회할 수도 있습니다.  우회
여부는 디바이스가 액세스 되는 메모리 윈도우의 특성에 의해 결정될 수도 있고, CPU
가 가지고 있을 수 있는 특수한 디바이스 통신 인스트럭션의 사용에 의해서 결정될
수도 있습니다.


캐시 일관성 VS DMA
------------------

모든 시스템이 DMA 를 하는 디바이스에 대해서까지 캐시 일관성을 유지하지는
않습니다.  그런 경우, DMA 를 시도하는 디바이스는 RAM 으로부터 잘못된 데이터를
읽을 수 있는데, 더티 캐시 라인이 CPU 의 캐시에 머무르고 있고, 바뀐 값이 아직
RAM 에 써지지 않았을 수 있기 때문입니다.  이 문제를 해결하기 위해선, 커널의
적절한 부분에서 각 CPU 캐시의 문제되는 비트들을 플러시 (flush) 시켜야만 합니다
(그리고 그것들을 무효화 - invalidation - 시킬 수도 있겠죠).

또한, 디바이스에 의해 RAM 에 DMA 로 쓰여진 값은 디바이스가 쓰기를 완료한 후에
CPU 의 캐시에서 RAM 으로 쓰여지는 더티 캐시 라인에 의해 덮어써질 수도 있고, CPU
의 캐시에 존재하는 캐시 라인이 해당 캐시에서 삭제되고 다시 값을 읽어들이기
전까지는 RAM 이 업데이트 되었다는 사실 자체가 숨겨져 버릴 수도 있습니다.  이
문제를 해결하기 위해선, 커널의 적절한 부분에서 각 CPU 의 캐시 안의 문제가 되는
비트들을 무효화 시켜야 합니다.

캐시 관리에 대한 더 많은 정보를 위해선 Documentation/core-api/cachetlb.rst 를
참고하세요.


캐시 일관성 VS MMIO
-------------------

Memory mapped I/O 는 일반적으로 CPU 의 메모리 공간 내의 한 윈도우의 특정 부분
내의 메모리 지역에 이루어지는데, 이 윈도우는 일반적인, RAM 으로 향하는
윈도우와는 다른 특성을 갖습니다.

그런 특성 가운데 하나는, 일반적으로 그런 액세스는 캐시를 완전히 우회하고
디바이스 버스로 곧바로 향한다는 것입니다.  이 말은 MMIO 액세스는 먼저
시작되어서 캐시에서 완료된 메모리 액세스를 추월할 수 있다는 뜻입니다.  이런
경우엔 메모리 배리어만으로는 충분치 않고, 만약 캐시된 메모리 쓰기 오퍼레이션과
MMIO 액세스가 어떤 방식으로든 의존적이라면 해당 캐시는 두 오퍼레이션 사이에
비워져(flush)야만 합니다.


======================
CPU 들이 저지르는 일들
======================

프로그래머는 CPU 가 메모리 오퍼레이션들을 정확히 요청한대로 수행해 줄 것이라고
생각하는데, 예를 들어 다음과 같은 코드를 CPU 에게 넘긴다면:

	a = READ_ONCE(*A);
	WRITE_ONCE(*B, b);
	c = READ_ONCE(*C);
	d = READ_ONCE(*D);
	WRITE_ONCE(*E, e);

CPU 는 다음 인스트럭션을 처리하기 전에 현재의 인스트럭션을 위한 메모리
오퍼레이션을 완료할 것이라 생각하고, 따라서 시스템 외부에서 관찰하기에도 정해진
순서대로 오퍼레이션이 수행될 것으로 예상합니다:

	LOAD *A, STORE *B, LOAD *C, LOAD *D, STORE *E.


당연하지만, 실제로는 훨씬 엉망입니다.  많은 CPU 와 컴파일러에서 앞의 가정은
성립하지 못하는데 그 이유는 다음과 같습니다:

 (*) 로드 오퍼레이션들은 실행을 계속 해나가기 위해 곧바로 완료될 필요가 있는
     경우가 많은 반면, 스토어 오퍼레이션들은 종종 별다른 문제 없이 유예될 수
     있습니다;

 (*) 로드 오퍼레이션들은 예측적으로 수행될 수 있으며, 필요없는 로드였다고
     증명된 예측적 로드의 결과는 버려집니다;

 (*) 로드 오퍼레이션들은 예측적으로 수행될 수 있으므로, 예상된 이벤트의
     시퀀스와 다른 시간에 로드가 이뤄질 수 있습니다;

 (*) 메모리 액세스 순서는 CPU 버스와 캐시를 좀 더 잘 사용할 수 있도록 재배치
     될 수 있습니다;

 (*) 로드와 스토어는 인접한 위치에의 액세스들을 일괄적으로 처리할 수 있는
     메모리나 I/O 하드웨어 (메모리와 PCI 디바이스 둘 다 이게 가능할 수
     있습니다) 에 대해 요청되는 경우, 개별 오퍼레이션을 위한 트랜잭션 설정
     비용을 아끼기 위해 조합되어 실행될 수 있습니다; 그리고

 (*) 해당 CPU 의 데이터 캐시가 순서에 영향을 끼칠 수도 있고, 캐시 일관성
     메커니즘이 - 스토어가 실제로 캐시에 도달한다면 - 이 문제를 완화시킬 수는
     있지만 이 일관성 관리가 다른 CPU 들에도 같은 순서로 전달된다는 보장은
     없습니다.

따라서, 앞의 코드에 대해 다른 CPU 가 보는 결과는 다음과 같을 수 있습니다:

	LOAD *A, ..., LOAD {*C,*D}, STORE *E, STORE *B

	("LOAD {*C,*D}" 는 조합된 로드입니다)


하지만, CPU 는 스스로는 일관적일 것을 보장합니다: CPU _자신_ 의 액세스들은
자신에게는 메모리 배리어가 없음에도 불구하고 정확히 순서 세워진 것으로 보여질
것입니다.  예를 들어 다음의 코드가 주어졌다면:

	U = READ_ONCE(*A);
	WRITE_ONCE(*A, V);
	WRITE_ONCE(*A, W);
	X = READ_ONCE(*A);
	WRITE_ONCE(*A, Y);
	Z = READ_ONCE(*A);

그리고 외부의 영향에 의한 간섭이 없다고 가정하면, 최종 결과는 다음과 같이
나타날 것이라고 예상될 수 있습니다:

	U == *A 의 최초 값
	X == W
	Z == Y
	*A == Y

앞의 코드는 CPU 가 다음의 메모리 액세스 시퀀스를 만들도록 할겁니다:

	U=LOAD *A, STORE *A=V, STORE *A=W, X=LOAD *A, STORE *A=Y, Z=LOAD *A

하지만, 별다른 개입이 없고 프로그램의 시야에 이 세상이 여전히 일관적이라고
보인다는 보장만 지켜진다면 이 시퀀스는 어떤 조합으로든 재구성될 수 있으며, 각
액세스들은 합쳐지거나 버려질 수 있습니다.  일부 아키텍쳐에서 CPU 는 같은 위치에
대한 연속적인 로드 오퍼레이션들을 재배치 할 수 있기 때문에 앞의 예에서의
READ_ONCE() 와 WRITE_ONCE() 는 반드시 존재해야 함을 알아두세요.  그런 종류의
아키텍쳐에서 READ_ONCE() 와 WRITE_ONCE() 는 이 문제를 막기 위해 필요한 일을
뭐가 됐든지 하게 되는데, 예를 들어 Itanium 에서는 READ_ONCE() 와 WRITE_ONCE()
가 사용하는 volatile 캐스팅은 GCC 가 그런 재배치를 방지하는 특수 인스트럭션인
ld.acq 와 stl.rel 인스트럭션을 각각 만들어 내도록 합니다.

컴파일러 역시 이 시퀀스의 액세스들을 CPU 가 보기도 전에 합치거나 버리거나 뒤로
미뤄버릴 수 있습니다.

예를 들어:

	*A = V;
	*A = W;

는 다음과 같이 변형될 수 있습니다:

	*A = W;

따라서, 쓰기 배리어나 WRITE_ONCE() 가 없다면 *A 로의 V 값의 저장의 효과는
사라진다고 가정될 수 있습니다.  비슷하게:

	*A = Y;
	Z = *A;

는, 메모리 배리어나 READ_ONCE() 와 WRITE_ONCE() 없이는 다음과 같이 변형될 수
있습니다:

	*A = Y;
	Z = Y;

그리고 이 LOAD 오퍼레이션은 CPU 바깥에는 아예 보이지 않습니다.


그리고, ALPHA 가 있다
---------------------

DEC Alpha CPU 는 가장 완화된 메모리 순서의 CPU 중 하나입니다.  뿐만 아니라,
Alpha CPU 의 일부 버전은 분할된 데이터 캐시를 가지고 있어서, 의미적으로
관계되어 있는 두개의 캐시 라인이 서로 다른 시간에 업데이트 되는게 가능합니다.
이게 주소 의존성 배리어가 정말 필요해지는 부분인데, 주소 의존성 배리어는 메모리
일관성 시스템과 함께 두개의 캐시를 동기화 시켜서, 포인터 변경과 새로운 데이터의
발견을 올바른 순서로 일어나게 하기 때문입니다.

리눅스 커널의 메모리 배리어 모델은 Alpha 에 기초해서 정의되었습니다만, v4.15
부터는 Alpha 용 READ_ONCE() 코드 내에 smp_mb() 가 추가되어서 메모리 모델로의
Alpha 의 영향력이 크게 줄어들었습니다.


가상 머신 게스트
----------------

가상 머신에서 동작하는 게스트들은 게스트 자체는 SMP 지원 없이 컴파일 되었다
해도 SMP 영향을 받을 수 있습니다.  이건 UP 커널을 사용하면서 SMP 호스트와
결부되어 발생하는 부작용입니다.  이 경우에는 mandatory 배리어를 사용해서 문제를
해결할 수 있겠지만 그런 해결은 대부분의 경우 최적의 해결책이 아닙니다.

이 문제를 완벽하게 해결하기 위해, 로우 레벨의 virt_mb() 등의 매크로를 사용할 수
있습니다. 이것들은 SMP 가 활성화 되어 있다면 smp_mb() 등과 동일한 효과를
갖습니다만, SMP 와 SMP 아닌 시스템 모두에 대해 동일한 코드를 만들어냅니다.
예를 들어, 가상 머신 게스트들은 (SMP 일 수 있는) 호스트와 동기화를 할 때에는
smp_mb() 가 아니라 virt_mb() 를 사용해야 합니다.

이것들은 smp_mb() 류의 것들과 모든 부분에서 동일하며, 특히, MMIO 의 영향에
대해서는 간여하지 않습니다: MMIO 의 영향을 제어하려면, mandatory 배리어를
사용하시기 바랍니다.


=======
사용 예
=======

순환식 버퍼
-----------

메모리 배리어는 순환식 버퍼를 생성자(producer)와 소비자(consumer) 사이의
동기화에 락을 사용하지 않고 구현하는데에 사용될 수 있습니다.  더 자세한 내용을
위해선 다음을 참고하세요:

	Documentation/core-api/circular-buffers.rst


=========
참고 문헌
=========

Alpha AXP Architecture Reference Manual, Second Edition (Sites & Witek,
Digital Press)
	Chapter 5.2: Physical Address Space Characteristics
	Chapter 5.4: Caches and Write Buffers
	Chapter 5.5: Data Sharing
	Chapter 5.6: Read/Write Ordering

AMD64 Architecture Programmer's Manual Volume 2: System Programming
	Chapter 7.1: Memory-Access Ordering
	Chapter 7.4: Buffering and Combining Memory Writes

ARM Architecture Reference Manual (ARMv8, for ARMv8-A architecture profile)
	Chapter B2: The AArch64 Application Level Memory Model

IA-32 Intel Architecture Software Developer's Manual, Volume 3:
System Programming Guide
	Chapter 7.1: Locked Atomic Operations
	Chapter 7.2: Memory Ordering
	Chapter 7.4: Serializing Instructions

The SPARC Architecture Manual, Version 9
	Chapter 8: Memory Models
	Appendix D: Formal Specification of the Memory Models
	Appendix J: Programming with the Memory Models

Storage in the PowerPC (Stone and Fitzgerald)

UltraSPARC Programmer Reference Manual
	Chapter 5: Memory Accesses and Cacheability
	Chapter 15: Sparc-V9 Memory Models

UltraSPARC III Cu User's Manual
	Chapter 9: Memory Models

UltraSPARC IIIi Processor User's Manual
	Chapter 8: Memory Models

UltraSPARC Architecture 2005
	Chapter 9: Memory
	Appendix D: Formal Specifications of the Memory Models

UltraSPARC T1 Supplement to the UltraSPARC Architecture 2005
	Chapter 8: Memory Models
	Appendix F: Caches and Cache Coherency

Solaris Internals, Core Kernel Architecture, p63-68:
	Chapter 3.3: Hardware Considerations for Locks and
			Synchronization

Unix Systems for Modern Architectures, Symmetric Multiprocessing and Caching
for Kernel Programmers:
	Chapter 13: Other Memory Models

Intel Itanium Architecture Software Developer's Manual: Volume 1:
	Section 2.6: Speculation
	Section 4.4: Memory Access
                         ============================
                         LINUX KERNEL MEMORY BARRIERS
                         ============================

By: David Howells <[email protected]>
    Paul E. McKenney <[email protected]>
    Will Deacon <[email protected]>
    Peter Zijlstra <[email protected]>

==========
DISCLAIMER
==========

This document is not a specification; it is intentionally (for the sake of
brevity) and unintentionally (due to being human) incomplete. This document is
meant as a guide to using the various memory barriers provided by Linux, but
in case of any doubt (and there are many) please ask.  Some doubts may be
resolved by referring to the formal memory consistency model and related
documentation at tools/memory-model/.  Nevertheless, even this memory
model should be viewed as the collective opinion of its maintainers rather
than as an infallible oracle.

To repeat, this document is not a specification of what Linux expects from
hardware.

The purpose of this document is twofold:

 (1) to specify the minimum functionality that one can rely on for any
     particular barrier, and

 (2) to provide a guide as to how to use the barriers that are available.

Note that an architecture can provide more than the minimum requirement
for any particular barrier, but if the architecture provides less than
that, that architecture is incorrect.

Note also that it is possible that a barrier may be a no-op for an
architecture because the way that arch works renders an explicit barrier
unnecessary in that case.


========
CONTENTS
========

 (*) Abstract memory access model.

     - Device operations.
     - Guarantees.

 (*) What are memory barriers?

     - Varieties of memory barrier.
     - What may not be assumed about memory barriers?
     - Address-dependency barriers (historical).
     - Control dependencies.
     - SMP barrier pairing.
     - Examples of memory barrier sequences.
     - Read memory barriers vs load speculation.
     - Multicopy atomicity.

 (*) Explicit kernel barriers.

     - Compiler barrier.
     - CPU memory barriers.

 (*) Implicit kernel memory barriers.

     - Lock acquisition functions.
     - Interrupt disabling functions.
     - Sleep and wake-up functions.
     - Miscellaneous functions.

 (*) Inter-CPU acquiring barrier effects.

     - Acquires vs memory accesses.

 (*) Where are memory barriers needed?

     - Interprocessor interaction.
     - Atomic operations.
     - Accessing devices.
     - Interrupts.

 (*) Kernel I/O barrier effects.

 (*) Assumed minimum execution ordering model.

 (*) The effects of the cpu cache.

     - Cache coherency vs DMA.
     - Cache coherency vs MMIO.

 (*) The things CPUs get up to.

     - And then there's the Alpha.
     - Virtual Machine Guests.

 (*) Example uses.

     - Circular buffers.

 (*) References.


============================
ABSTRACT MEMORY ACCESS MODEL
============================

Consider the following abstract model of the system:

                            :                :
                            :                :
                            :                :
                +-------+   :   +--------+   :   +-------+
                |       |   :   |        |   :   |       |
                |       |   :   |        |   :   |       |
                | CPU 1 |<----->| Memory |<----->| CPU 2 |
                |       |   :   |        |   :   |       |
                |       |   :   |        |   :   |       |
                +-------+   :   +--------+   :   +-------+
                    ^       :       ^        :       ^
                    |       :       |        :       |
                    |       :       |        :       |
                    |       :       v        :       |
                    |       :   +--------+   :       |
                    |       :   |        |   :       |
                    |       :   |        |   :       |
                    +---------->| Device |<----------+
                            :   |        |   :
                            :   |        |   :
                            :   +--------+   :
                            :                :

Each CPU executes a program that generates memory access operations.  In the
abstract CPU, memory operation ordering is very relaxed, and a CPU may actually
perform the memory operations in any order it likes, provided program causality
appears to be maintained.  Similarly, the compiler may also arrange the
instructions it emits in any order it likes, provided it doesn't affect the
apparent operation of the program.

So in the above diagram, the effects of the memory operations performed by a
CPU are perceived by the rest of the system as the operations cross the
interface between the CPU and rest of the system (the dotted lines).


For example, consider the following sequence of events:

        CPU 1                CPU 2
        ===============        ===============
        { A == 1; B == 2 }
        A = 3;                x = B;
        B = 4;                y = A;

The set of accesses as seen by the memory system in the middle can be arranged
in 24 different combinations:

        STORE A=3,        STORE B=4,        y=LOAD A->3,        x=LOAD B->4
        STORE A=3,        STORE B=4,        x=LOAD B->4,        y=LOAD A->3
        STORE A=3,        y=LOAD A->3,        STORE B=4,        x=LOAD B->4
        STORE A=3,        y=LOAD A->3,        x=LOAD B->2,        STORE B=4
        STORE A=3,        x=LOAD B->2,        STORE B=4,        y=LOAD A->3
        STORE A=3,        x=LOAD B->2,        y=LOAD A->3,        STORE B=4
        STORE B=4,        STORE A=3,        y=LOAD A->3,        x=LOAD B->4
        STORE B=4, ...
        ...

and can thus result in four different combinations of values:

        x == 2, y == 1
        x == 2, y == 3
        x == 4, y == 1
        x == 4, y == 3


Furthermore, the stores committed by a CPU to the memory system may not be
perceived by the loads made by another CPU in the same order as the stores were
committed.


As a further example, consider this sequence of events:

        CPU 1                CPU 2
        ===============        ===============
        { A == 1, B == 2, C == 3, P == &A, Q == &C }
        B = 4;                Q = P;
        P = &B;                D = *Q;

There is an obvious address dependency here, as the value loaded into D depends
on the address retrieved from P by CPU 2.  At the end of the sequence, any of
the following results are possible:

        (Q == &A) and (D == 1)
        (Q == &B) and (D == 2)
        (Q == &B) and (D == 4)

Note that CPU 2 will never try and load C into D because the CPU will load P
into Q before issuing the load of *Q.


DEVICE OPERATIONS
-----------------

Some devices present their control interfaces as collections of memory
locations, but the order in which the control registers are accessed is very
important.  For instance, imagine an ethernet card with a set of internal
registers that are accessed through an address port register (A) and a data
port register (D).  To read internal register 5, the following code might then
be used:

        *A = 5;
        x = *D;

but this might show up as either of the following two sequences:

        STORE *A = 5, x = LOAD *D
        x = LOAD *D, STORE *A = 5

the second of which will almost certainly result in a malfunction, since it set
the address _after_ attempting to read the register.


GUARANTEES
----------

There are some minimal guarantees that may be expected of a CPU:

 (*) On any given CPU, dependent memory accesses will be issued in order, with
     respect to itself.  This means that for:

        Q = READ_ONCE(P); D = READ_ONCE(*Q);

     the CPU will issue the following memory operations:

        Q = LOAD P, D = LOAD *Q

     and always in that order.  However, on DEC Alpha, READ_ONCE() also
     emits a memory-barrier instruction, so that a DEC Alpha CPU will
     instead issue the following memory operations:

        Q = LOAD P, MEMORY_BARRIER, D = LOAD *Q, MEMORY_BARRIER

     Whether on DEC Alpha or not, the READ_ONCE() also prevents compiler
     mischief.

 (*) Overlapping loads and stores within a particular CPU will appear to be
     ordered within that CPU.  This means that for:

        a = READ_ONCE(*X); WRITE_ONCE(*X, b);

     the CPU will only issue the following sequence of memory operations:

        a = LOAD *X, STORE *X = b

     And for:

        WRITE_ONCE(*X, c); d = READ_ONCE(*X);

     the CPU will only issue:

        STORE *X = c, d = LOAD *X

     (Loads and stores overlap if they are targeted at overlapping pieces of
     memory).

And there are a number of things that _must_ or _must_not_ be assumed:

 (*) It _must_not_ be assumed that the compiler will do what you want
     with memory references that are not protected by READ_ONCE() and
     WRITE_ONCE().  Without them, the compiler is within its rights to
     do all sorts of "creative" transformations, which are covered in
     the COMPILER BARRIER section.

 (*) It _must_not_ be assumed that independent loads and stores will be issued
     in the order given.  This means that for:

        X = *A; Y = *B; *D = Z;

     we may get any of the following sequences:

        X = LOAD *A,  Y = LOAD *B,  STORE *D = Z
        X = LOAD *A,  STORE *D = Z, Y = LOAD *B
        Y = LOAD *B,  X = LOAD *A,  STORE *D = Z
        Y = LOAD *B,  STORE *D = Z, X = LOAD *A
        STORE *D = Z, X = LOAD *A,  Y = LOAD *B
        STORE *D = Z, Y = LOAD *B,  X = LOAD *A

 (*) It _must_ be assumed that overlapping memory accesses may be merged or
     discarded.  This means that for:

        X = *A; Y = *(A + 4);

     we may get any one of the following sequences:

        X = LOAD *A; Y = LOAD *(A + 4);
        Y = LOAD *(A + 4); X = LOAD *A;
        {X, Y} = LOAD {*A, *(A + 4) };

     And for:

        *A = X; *(A + 4) = Y;

     we may get any of:

        STORE *A = X; STORE *(A + 4) = Y;
        STORE *(A + 4) = Y; STORE *A = X;
        STORE {*A, *(A + 4) } = {X, Y};

And there are anti-guarantees:

 (*) These guarantees do not apply to bitfields, because compilers often
     generate code to modify these using non-atomic read-modify-write
     sequences.  Do not attempt to use bitfields to synchronize parallel
     algorithms.

 (*) Even in cases where bitfields are protected by locks, all fields
     in a given bitfield must be protected by one lock.  If two fields
     in a given bitfield are protected by different locks, the compiler's
     non-atomic read-modify-write sequences can cause an update to one
     field to corrupt the value of an adjacent field.

 (*) These guarantees apply only to properly aligned and sized scalar
     variables.  "Properly sized" currently means variables that are
     the same size as "char", "short", "int" and "long".  "Properly
     aligned" means the natural alignment, thus no constraints for
     "char", two-byte alignment for "short", four-byte alignment for
     "int", and either four-byte or eight-byte alignment for "long",
     on 32-bit and 64-bit systems, respectively.  Note that these
     guarantees were introduced into the C11 standard, so beware when
     using older pre-C11 compilers (for example, gcc 4.6).  The portion
     of the standard containing this guarantee is Section 3.14, which
     defines "memory location" as follows:

             memory location
                either an object of scalar type, or a maximal sequence
                of adjacent bit-fields all having nonzero width

                NOTE 1: Two threads of execution can update and access
                separate memory locations without interfering with
                each other.

                NOTE 2: A bit-field and an adjacent non-bit-field member
                are in separate memory locations. The same applies
                to two bit-fields, if one is declared inside a nested
                structure declaration and the other is not, or if the two
                are separated by a zero-length bit-field declaration,
                or if they are separated by a non-bit-field member
                declaration. It is not safe to concurrently update two
                bit-fields in the same structure if all members declared
                between them are also bit-fields, no matter what the
                sizes of those intervening bit-fields happen to be.


=========================
WHAT ARE MEMORY BARRIERS?
=========================

As can be seen above, independent memory operations are effectively performed
in random order, but this can be a problem for CPU-CPU interaction and for I/O.
What is required is some way of intervening to instruct the compiler and the
CPU to restrict the order.

Memory barriers are such interventions.  They impose a perceived partial
ordering over the memory operations on either side of the barrier.

Such enforcement is important because the CPUs and other devices in a system
can use a variety of tricks to improve performance, including reordering,
deferral and combination of memory operations; speculative loads; speculative
branch prediction and various types of caching.  Memory barriers are used to
override or suppress these tricks, allowing the code to sanely control the
interaction of multiple CPUs and/or devices.


VARIETIES OF MEMORY BARRIER
---------------------------

Memory barriers come in four basic varieties:

 (1) Write (or store) memory barriers.

     A write memory barrier gives a guarantee that all the STORE operations
     specified before the barrier will appear to happen before all the STORE
     operations specified after the barrier with respect to the other
     components of the system.

     A write barrier is a partial ordering on stores only; it is not required
     to have any effect on loads.

     A CPU can be viewed as committing a sequence of store operations to the
     memory system as time progresses.  All stores _before_ a write barrier
     will occur _before_ all the stores after the write barrier.

     [!] Note that write barriers should normally be paired with read or
     address-dependency barriers; see the "SMP barrier pairing" subsection.


 (2) Address-dependency barriers (historical).
     [!] This section is marked as HISTORICAL: it covers the long-obsolete
     smp_read_barrier_depends() macro, the semantics of which are now
     implicit in all marked accesses.  For more up-to-date information,
     including how compiler transformations can sometimes break address
     dependencies, see Documentation/RCU/rcu_dereference.rst.

     An address-dependency barrier is a weaker form of read barrier.  In the
     case where two loads are performed such that the second depends on the
     result of the first (eg: the first load retrieves the address to which
     the second load will be directed), an address-dependency barrier would
     be required to make sure that the target of the second load is updated
     after the address obtained by the first load is accessed.

     An address-dependency barrier is a partial ordering on interdependent
     loads only; it is not required to have any effect on stores, independent
     loads or overlapping loads.

     As mentioned in (1), the other CPUs in the system can be viewed as
     committing sequences of stores to the memory system that the CPU being
     considered can then perceive.  An address-dependency barrier issued by
     the CPU under consideration guarantees that for any load preceding it,
     if that load touches one of a sequence of stores from another CPU, then
     by the time the barrier completes, the effects of all the stores prior to
     that touched by the load will be perceptible to any loads issued after
     the address-dependency barrier.

     See the "Examples of memory barrier sequences" subsection for diagrams
     showing the ordering constraints.

     [!] Note that the first load really has to have an _address_ dependency and
     not a control dependency.  If the address for the second load is dependent
     on the first load, but the dependency is through a conditional rather than
     actually loading the address itself, then it's a _control_ dependency and
     a full read barrier or better is required.  See the "Control dependencies"
     subsection for more information.

     [!] Note that address-dependency barriers should normally be paired with
     write barriers; see the "SMP barrier pairing" subsection.

     [!] Kernel release v5.9 removed kernel APIs for explicit address-
     dependency barriers.  Nowadays, APIs for marking loads from shared
     variables such as READ_ONCE() and rcu_dereference() provide implicit
     address-dependency barriers.

 (3) Read (or load) memory barriers.

     A read barrier is an address-dependency barrier plus a guarantee that all
     the LOAD operations specified before the barrier will appear to happen
     before all the LOAD operations specified after the barrier with respect to
     the other components of the system.

     A read barrier is a partial ordering on loads only; it is not required to
     have any effect on stores.

     Read memory barriers imply address-dependency barriers, and so can
     substitute for them.

     [!] Note that read barriers should normally be paired with write barriers;
     see the "SMP barrier pairing" subsection.


 (4) General memory barriers.

     A general memory barrier gives a guarantee that all the LOAD and STORE
     operations specified before the barrier will appear to happen before all
     the LOAD and STORE operations specified after the barrier with respect to
     the other components of the system.

     A general memory barrier is a partial ordering over both loads and stores.

     General memory barriers imply both read and write memory barriers, and so
     can substitute for either.


And a couple of implicit varieties:

 (5) ACQUIRE operations.

     This acts as a one-way permeable barrier.  It guarantees that all memory
     operations after the ACQUIRE operation will appear to happen after the
     ACQUIRE operation with respect to the other components of the system.
     ACQUIRE operations include LOCK operations and both smp_load_acquire()
     and smp_cond_load_acquire() operations.

     Memory operations that occur before an ACQUIRE operation may appear to
     happen after it completes.

     An ACQUIRE operation should almost always be paired with a RELEASE
     operation.


 (6) RELEASE operations.

     This also acts as a one-way permeable barrier.  It guarantees that all
     memory operations before the RELEASE operation will appear to happen
     before the RELEASE operation with respect to the other components of the
     system. RELEASE operations include UNLOCK operations and
     smp_store_release() operations.

     Memory operations that occur after a RELEASE operation may appear to
     happen before it completes.

     The use of ACQUIRE and RELEASE operations generally precludes the need
     for other sorts of memory barrier.  In addition, a RELEASE+ACQUIRE pair is
     -not- guaranteed to act as a full memory barrier.  However, after an
     ACQUIRE on a given variable, all memory accesses preceding any prior
     RELEASE on that same variable are guaranteed to be visible.  In other
     words, within a given variable's critical section, all accesses of all
     previous critical sections for that variable are guaranteed to have
     completed.

     This means that ACQUIRE acts as a minimal "acquire" operation and
     RELEASE acts as a minimal "release" operation.

A subset of the atomic operations described in atomic_t.txt have ACQUIRE and
RELEASE variants in addition to fully-ordered and relaxed (no barrier
semantics) definitions.  For compound atomics performing both a load and a
store, ACQUIRE semantics apply only to the load and RELEASE semantics apply
only to the store portion of the operation.

Memory barriers are only required where there's a possibility of interaction
between two CPUs or between a CPU and a device.  If it can be guaranteed that
there won't be any such interaction in any particular piece of code, then
memory barriers are unnecessary in that piece of code.


Note that these are the _minimum_ guarantees.  Different architectures may give
more substantial guarantees, but they may _not_ be relied upon outside of arch
specific code.


WHAT MAY NOT BE ASSUMED ABOUT MEMORY BARRIERS?
----------------------------------------------

There are certain things that the Linux kernel memory barriers do not guarantee:

 (*) There is no guarantee that any of the memory accesses specified before a
     memory barrier will be _complete_ by the completion of a memory barrier
     instruction; the barrier can be considered to draw a line in that CPU's
     access queue that accesses of the appropriate type may not cross.

 (*) There is no guarantee that issuing a memory barrier on one CPU will have
     any direct effect on another CPU or any other hardware in the system.  The
     indirect effect will be the order in which the second CPU sees the effects
     of the first CPU's accesses occur, but see the next point:

 (*) There is no guarantee that a CPU will see the correct order of effects
     from a second CPU's accesses, even _if_ the second CPU uses a memory
     barrier, unless the first CPU _also_ uses a matching memory barrier (see
     the subsection on "SMP Barrier Pairing").

 (*) There is no guarantee that some intervening piece of off-the-CPU
     hardware[*] will not reorder the memory accesses.  CPU cache coherency
     mechanisms should propagate the indirect effects of a memory barrier
     between CPUs, but might not do so in order.

        [*] For information on bus mastering DMA and coherency please read:

            Documentation/driver-api/pci/pci.rst
            Documentation/core-api/dma-api-howto.rst
            Documentation/core-api/dma-api.rst


ADDRESS-DEPENDENCY BARRIERS (HISTORICAL)
----------------------------------------
[!] This section is marked as HISTORICAL: it covers the long-obsolete
smp_read_barrier_depends() macro, the semantics of which are now implicit
in all marked accesses.  For more up-to-date information, including
how compiler transformations can sometimes break address dependencies,
see Documentation/RCU/rcu_dereference.rst.

As of v4.15 of the Linux kernel, an smp_mb() was added to READ_ONCE() for
DEC Alpha, which means that about the only people who need to pay attention
to this section are those working on DEC Alpha architecture-specific code
and those working on READ_ONCE() itself.  For those who need it, and for
those who are interested in the history, here is the story of
address-dependency barriers.

[!] While address dependencies are observed in both load-to-load and
load-to-store relations, address-dependency barriers are not necessary
for load-to-store situations.

The requirement of address-dependency barriers is a little subtle, and
it's not always obvious that they're needed.  To illustrate, consider the
following sequence of events:

        CPU 1                      CPU 2
        ===============              ===============
        { A == 1, B == 2, C == 3, P == &A, Q == &C }
        B = 4;
        <write barrier>
        WRITE_ONCE(P, &B);
                              Q = READ_ONCE_OLD(P);
                              D = *Q;

[!] READ_ONCE_OLD() corresponds to READ_ONCE() of pre-4.15 kernel, which
doesn't imply an address-dependency barrier.

There's a clear address dependency here, and it would seem that by the end of
the sequence, Q must be either &A or &B, and that:

        (Q == &A) implies (D == 1)
        (Q == &B) implies (D == 4)

But!  CPU 2's perception of P may be updated _before_ its perception of B, thus
leading to the following situation:

        (Q == &B) and (D == 2) ????

While this may seem like a failure of coherency or causality maintenance, it
isn't, and this behaviour can be observed on certain real CPUs (such as the DEC
Alpha).

To deal with this, READ_ONCE() provides an implicit address-dependency barrier
since kernel release v4.15:

        CPU 1                      CPU 2
        ===============              ===============
        { A == 1, B == 2, C == 3, P == &A, Q == &C }
        B = 4;
        <write barrier>
        WRITE_ONCE(P, &B);
                              Q = READ_ONCE(P);
                              <implicit address-dependency barrier>
                              D = *Q;

This enforces the occurrence of one of the two implications, and prevents the
third possibility from arising.


[!] Note that this extremely counterintuitive situation arises most easily on
machines with split caches, so that, for example, one cache bank processes
even-numbered cache lines and the other bank processes odd-numbered cache
lines.  The pointer P might be stored in an odd-numbered cache line, and the
variable B might be stored in an even-numbered cache line.  Then, if the
even-numbered bank of the reading CPU's cache is extremely busy while the
odd-numbered bank is idle, one can see the new value of the pointer P (&B),
but the old value of the variable B (2).


An address-dependency barrier is not required to order dependent writes
because the CPUs that the Linux kernel supports don't do writes until they
are certain (1) that the write will actually happen, (2) of the location of
the write, and (3) of the value to be written.
But please carefully read the "CONTROL DEPENDENCIES" section and the
Documentation/RCU/rcu_dereference.rst file:  The compiler can and does break
dependencies in a great many highly creative ways.

        CPU 1                      CPU 2
        ===============              ===============
        { A == 1, B == 2, C = 3, P == &A, Q == &C }
        B = 4;
        <write barrier>
        WRITE_ONCE(P, &B);
                              Q = READ_ONCE_OLD(P);
                              WRITE_ONCE(*Q, 5);

Therefore, no address-dependency barrier is required to order the read into
Q with the store into *Q.  In other words, this outcome is prohibited,
even without an implicit address-dependency barrier of modern READ_ONCE():

        (Q == &B) && (B == 4)

Please note that this pattern should be rare.  After all, the whole point
of dependency ordering is to -prevent- writes to the data structure, along
with the expensive cache misses associated with those writes.  This pattern
can be used to record rare error conditions and the like, and the CPUs'
naturally occurring ordering prevents such records from being lost.


Note well that the ordering provided by an address dependency is local to
the CPU containing it.  See the section on "Multicopy atomicity" for
more information.


The address-dependency barrier is very important to the RCU system,
for example.  See rcu_assign_pointer() and rcu_dereference() in
include/linux/rcupdate.h.  This permits the current target of an RCU'd
pointer to be replaced with a new modified target, without the replacement
target appearing to be incompletely initialised.


CONTROL DEPENDENCIES
--------------------

Control dependencies can be a bit tricky because current compilers do
not understand them.  The purpose of this section is to help you prevent
the compiler's ignorance from breaking your code.

A load-load control dependency requires a full read memory barrier, not
simply an (implicit) address-dependency barrier to make it work correctly.
Consider the following bit of code:

        q = READ_ONCE(a);
        <implicit address-dependency barrier>
        if (q) {
                /* BUG: No address dependency!!! */
                p = READ_ONCE(b);
        }

This will not have the desired effect because there is no actual address
dependency, but rather a control dependency that the CPU may short-circuit
by attempting to predict the outcome in advance, so that other CPUs see
the load from b as having happened before the load from a.  In such a case
what's actually required is:

        q = READ_ONCE(a);
        if (q) {
                <read barrier>
                p = READ_ONCE(b);
        }

However, stores are not speculated.  This means that ordering -is- provided
for load-store control dependencies, as in the following example:

        q = READ_ONCE(a);
        if (q) {
                WRITE_ONCE(b, 1);
        }

Control dependencies pair normally with other types of barriers.
That said, please note that neither READ_ONCE() nor WRITE_ONCE()
are optional! Without the READ_ONCE(), the compiler might combine the
load from 'a' with other loads from 'a'.  Without the WRITE_ONCE(),
the compiler might combine the store to 'b' with other stores to 'b'.
Either can result in highly counterintuitive effects on ordering.

Worse yet, if the compiler is able to prove (say) that the value of
variable 'a' is always non-zero, it would be well within its rights
to optimize the original example by eliminating the "if" statement
as follows:

        q = a;
        b = 1;  /* BUG: Compiler and CPU can both reorder!!! */

So don't leave out the READ_ONCE().

It is tempting to try to enforce ordering on identical stores on both
branches of the "if" statement as follows:

        q = READ_ONCE(a);
        if (q) {
                barrier();
                WRITE_ONCE(b, 1);
                do_something();
        } else {
                barrier();
                WRITE_ONCE(b, 1);
                do_something_else();
        }

Unfortunately, current compilers will transform this as follows at high
optimization levels:

        q = READ_ONCE(a);
        barrier();
        WRITE_ONCE(b, 1);  /* BUG: No ordering vs. load from a!!! */
        if (q) {
                /* WRITE_ONCE(b, 1); -- moved up, BUG!!! */
                do_something();
        } else {
                /* WRITE_ONCE(b, 1); -- moved up, BUG!!! */
                do_something_else();
        }

Now there is no conditional between the load from 'a' and the store to
'b', which means that the CPU is within its rights to reorder them:
The conditional is absolutely required, and must be present in the
assembly code even after all compiler optimizations have been applied.
Therefore, if you need ordering in this example, you need explicit
memory barriers, for example, smp_store_release():

        q = READ_ONCE(a);
        if (q) {
                smp_store_release(&b, 1);
                do_something();
        } else {
                smp_store_release(&b, 1);
                do_something_else();
        }

In contrast, without explicit memory barriers, two-legged-if control
ordering is guaranteed only when the stores differ, for example:

        q = READ_ONCE(a);
        if (q) {
                WRITE_ONCE(b, 1);
                do_something();
        } else {
                WRITE_ONCE(b, 2);
                do_something_else();
        }

The initial READ_ONCE() is still required to prevent the compiler from
proving the value of 'a'.

In addition, you need to be careful what you do with the local variable 'q',
otherwise the compiler might be able to guess the value and again remove
the needed conditional.  For example:

        q = READ_ONCE(a);
        if (q % MAX) {
                WRITE_ONCE(b, 1);
                do_something();
        } else {
                WRITE_ONCE(b, 2);
                do_something_else();
        }

If MAX is defined to be 1, then the compiler knows that (q % MAX) is
equal to zero, in which case the compiler is within its rights to
transform the above code into the following:

        q = READ_ONCE(a);
        WRITE_ONCE(b, 2);
        do_something_else();

Given this transformation, the CPU is not required to respect the ordering
between the load from variable 'a' and the store to variable 'b'.  It is
tempting to add a barrier(), but this does not help.  The conditional
is gone, and the barrier won't bring it back.  Therefore, if you are
relying on this ordering, you should make sure that MAX is greater than
one, perhaps as follows:

        q = READ_ONCE(a);
        BUILD_BUG_ON(MAX <= 1); /* Order load from a with store to b. */
        if (q % MAX) {
                WRITE_ONCE(b, 1);
                do_something();
        } else {
                WRITE_ONCE(b, 2);
                do_something_else();
        }

Please note once again that the stores to 'b' differ.  If they were
identical, as noted earlier, the compiler could pull this store outside
of the 'if' statement.

You must also be careful not to rely too much on boolean short-circuit
evaluation.  Consider this example:

        q = READ_ONCE(a);
        if (q || 1 > 0)
                WRITE_ONCE(b, 1);

Because the first condition cannot fault and the second condition is
always true, the compiler can transform this example as following,
defeating control dependency:

        q = READ_ONCE(a);
        WRITE_ONCE(b, 1);

This example underscores the need to ensure that the compiler cannot
out-guess your code.  More generally, although READ_ONCE() does force
the compiler to actually emit code for a given load, it does not force
the compiler to use the results.

In addition, control dependencies apply only to the then-clause and
else-clause of the if-statement in question.  In particular, it does
not necessarily apply to code following the if-statement:

        q = READ_ONCE(a);
        if (q) {
                WRITE_ONCE(b, 1);
        } else {
                WRITE_ONCE(b, 2);
        }
        WRITE_ONCE(c, 1);  /* BUG: No ordering against the read from 'a'. */

It is tempting to argue that there in fact is ordering because the
compiler cannot reorder volatile accesses and also cannot reorder
the writes to 'b' with the condition.  Unfortunately for this line
of reasoning, the compiler might compile the two writes to 'b' as
conditional-move instructions, as in this fanciful pseudo-assembly
language:

        ld r1,a
        cmp r1,$0
        cmov,ne r4,$1
        cmov,eq r4,$2
        st r4,b
        st $1,c

A weakly ordered CPU would have no dependency of any sort between the load
from 'a' and the store to 'c'.  The control dependencies would extend
only to the pair of cmov instructions and the store depending on them.
In short, control dependencies apply only to the stores in the then-clause
and else-clause of the if-statement in question (including functions
invoked by those two clauses), not to code following that if-statement.


Note well that the ordering provided by a control dependency is local
to the CPU containing it.  See the section on "Multicopy atomicity"
for more information.


In summary:

  (*) Control dependencies can order prior loads against later stores.
      However, they do -not- guarantee any other sort of ordering:
      Not prior loads against later loads, nor prior stores against
      later anything.  If you need these other forms of ordering,
      use smp_rmb(), smp_wmb(), or, in the case of prior stores and
      later loads, smp_mb().

  (*) If both legs of the "if" statement begin with identical stores to
      the same variable, then those stores must be ordered, either by
      preceding both of them with smp_mb() or by using smp_store_release()
      to carry out the stores.  Please note that it is -not- sufficient
      to use barrier() at beginning of each leg of the "if" statement
      because, as shown by the example above, optimizing compilers can
      destroy the control dependency while respecting the letter of the
      barrier() law.

  (*) Control dependencies require at least one run-time conditional
      between the prior load and the subsequent store, and this
      conditional must involve the prior load.  If the compiler is able
      to optimize the conditional away, it will have also optimized
      away the ordering.  Careful use of READ_ONCE() and WRITE_ONCE()
      can help to preserve the needed conditional.

  (*) Control dependencies require that the compiler avoid reordering the
      dependency into nonexistence.  Careful use of READ_ONCE() or
      atomic{,64}_read() can help to preserve your control dependency.
      Please see the COMPILER BARRIER section for more information.

  (*) Control dependencies apply only to the then-clause and else-clause
      of the if-statement containing the control dependency, including
      any functions that these two clauses call.  Control dependencies
      do -not- apply to code following the if-statement containing the
      control dependency.

  (*) Control dependencies pair normally with other types of barriers.

  (*) Control dependencies do -not- provide multicopy atomicity.  If you
      need all the CPUs to see a given store at the same time, use smp_mb().

  (*) Compilers do not understand control dependencies.  It is therefore
      your job to ensure that they do not break your code.


SMP BARRIER PAIRING
-------------------

When dealing with CPU-CPU interactions, certain types of memory barrier should
always be paired.  A lack of appropriate pairing is almost certainly an error.

General barriers pair with each other, though they also pair with most
other types of barriers, albeit without multicopy atomicity.  An acquire
barrier pairs with a release barrier, but both may also pair with other
barriers, including of course general barriers.  A write barrier pairs
with an address-dependency barrier, a control dependency, an acquire barrier,
a release barrier, a read barrier, or a general barrier.  Similarly a
read barrier, control dependency, or an address-dependency barrier pairs
with a write barrier, an acquire barrier, a release barrier, or a
general barrier:

        CPU 1                      CPU 2
        ===============              ===============
        WRITE_ONCE(a, 1);
        <write barrier>
        WRITE_ONCE(b, 2);     x = READ_ONCE(b);
                              <read barrier>
                              y = READ_ONCE(a);

Or:

        CPU 1                      CPU 2
        ===============              ===============================
        a = 1;
        <write barrier>
        WRITE_ONCE(b, &a);    x = READ_ONCE(b);
                              <implicit address-dependency barrier>
                              y = *x;

Or even:

        CPU 1                      CPU 2
        ===============              ===============================
        r1 = READ_ONCE(y);
        <general barrier>
        WRITE_ONCE(x, 1);     if (r2 = READ_ONCE(x)) {
                                 <implicit control dependency>
                                 WRITE_ONCE(y, 1);
                              }

        assert(r1 == 0 || r2 == 0);

Basically, the read barrier always has to be there, even though it can be of
the "weaker" type.

[!] Note that the stores before the write barrier would normally be expected to
match the loads after the read barrier or the address-dependency barrier, and
vice versa:

        CPU 1                               CPU 2
        ===================                 ===================
        WRITE_ONCE(a, 1);    }----   --->{  v = READ_ONCE(c);
        WRITE_ONCE(b, 2);    }    \ /    {  w = READ_ONCE(d);
        <write barrier>            \        <read barrier>
        WRITE_ONCE(c, 3);    }    / \    {  x = READ_ONCE(a);
        WRITE_ONCE(d, 4);    }----   --->{  y = READ_ONCE(b);


EXAMPLES OF MEMORY BARRIER SEQUENCES
------------------------------------

Firstly, write barriers act as partial orderings on store operations.
Consider the following sequence of events:

        CPU 1
        =======================
        STORE A = 1
        STORE B = 2
        STORE C = 3
        <write barrier>
        STORE D = 4
        STORE E = 5

This sequence of events is committed to the memory coherence system in an order
that the rest of the system might perceive as the unordered set of { STORE A,
STORE B, STORE C } all occurring before the unordered set of { STORE D, STORE E
}:

        +-------+       :      :
        |       |       +------+
        |       |------>| C=3  |     }     /\
        |       |  :    +------+     }-----  \  -----> Events perceptible to
        |       |  :    | A=1  |     }        \/       the rest of the system
        |       |  :    +------+     }
        | CPU 1 |  :    | B=2  |     }
        |       |       +------+     }
        |       |   wwwwwwwwwwwwwwww }   <--- At this point the write barrier
        |       |       +------+     }        requires all stores prior to the
        |       |  :    | E=5  |     }        barrier to be committed before
        |       |  :    +------+     }        further stores may take place
        |       |------>| D=4  |     }
        |       |       +------+
        +-------+       :      :
                           |
                           | Sequence in which stores are committed to the
                           | memory system by CPU 1
                           V


Secondly, address-dependency barriers act as partial orderings on address-
dependent loads.  Consider the following sequence of events:

        CPU 1                        CPU 2
        =======================        =======================
                { B = 7; X = 9; Y = 8; C = &Y }
        STORE A = 1
        STORE B = 2
        <write barrier>
        STORE C = &B                LOAD X
        STORE D = 4                LOAD C (gets &B)
                                LOAD *C (reads B)

Without intervention, CPU 2 may perceive the events on CPU 1 in some
effectively random order, despite the write barrier issued by CPU 1:

        +-------+       :      :                :       :
        |       |       +------+                +-------+  | Sequence of update
        |       |------>| B=2  |-----       --->| Y->8  |  | of perception on
        |       |  :    +------+     \          +-------+  | CPU 2
        | CPU 1 |  :    | A=1  |      \     --->| C->&Y |  V
        |       |       +------+       |        +-------+
        |       |   wwwwwwwwwwwwwwww   |        :       :
        |       |       +------+       |        :       :
        |       |  :    | C=&B |---    |        :       :       +-------+
        |       |  :    +------+   \   |        +-------+       |       |
        |       |------>| D=4  |    ----------->| C->&B |------>|       |
        |       |       +------+       |        +-------+       |       |
        +-------+       :      :       |        :       :       |       |
                                       |        :       :       |       |
                                       |        :       :       | CPU 2 |
                                       |        +-------+       |       |
            Apparently incorrect --->  |        | B->7  |------>|       |
            perception of B (!)        |        +-------+       |       |
                                       |        :       :       |       |
                                       |        +-------+       |       |
            The load of X holds --->    \       | X->9  |------>|       |
            up the maintenance           \      +-------+       |       |
            of coherence of B             ----->| B->2  |       +-------+
                                                +-------+
                                                :       :


In the above example, CPU 2 perceives that B is 7, despite the load of *C
(which would be B) coming after the LOAD of C.

If, however, an address-dependency barrier were to be placed between the load
of C and the load of *C (ie: B) on CPU 2:

        CPU 1                        CPU 2
        =======================        =======================
                { B = 7; X = 9; Y = 8; C = &Y }
        STORE A = 1
        STORE B = 2
        <write barrier>
        STORE C = &B                LOAD X
        STORE D = 4                LOAD C (gets &B)
                                <address-dependency barrier>
                                LOAD *C (reads B)

then the following will occur:

        +-------+       :      :                :       :
        |       |       +------+                +-------+
        |       |------>| B=2  |-----       --->| Y->8  |
        |       |  :    +------+     \          +-------+
        | CPU 1 |  :    | A=1  |      \     --->| C->&Y |
        |       |       +------+       |        +-------+
        |       |   wwwwwwwwwwwwwwww   |        :       :
        |       |       +------+       |        :       :
        |       |  :    | C=&B |---    |        :       :       +-------+
        |       |  :    +------+   \   |        +-------+       |       |
        |       |------>| D=4  |    ----------->| C->&B |------>|       |
        |       |       +------+       |        +-------+       |       |
        +-------+       :      :       |        :       :       |       |
                                       |        :       :       |       |
                                       |        :       :       | CPU 2 |
                                       |        +-------+       |       |
                                       |        | X->9  |------>|       |
                                       |        +-------+       |       |
          Makes sure all effects --->   \   aaaaaaaaaaaaaaaaa   |       |
          prior to the store of C        \      +-------+       |       |
          are perceptible to              ----->| B->2  |------>|       |
          subsequent loads                      +-------+       |       |
                                                :       :       +-------+


And thirdly, a read barrier acts as a partial order on loads.  Consider the
following sequence of events:

        CPU 1                        CPU 2
        =======================        =======================
                { A = 0, B = 9 }
        STORE A=1
        <write barrier>
        STORE B=2
                                LOAD B
                                LOAD A

Without intervention, CPU 2 may then choose to perceive the events on CPU 1 in
some effectively random order, despite the write barrier issued by CPU 1:

        +-------+       :      :                :       :
        |       |       +------+                +-------+
        |       |------>| A=1  |------      --->| A->0  |
        |       |       +------+      \         +-------+
        | CPU 1 |   wwwwwwwwwwwwwwww   \    --->| B->9  |
        |       |       +------+        |       +-------+
        |       |------>| B=2  |---     |       :       :
        |       |       +------+   \    |       :       :       +-------+
        +-------+       :      :    \   |       +-------+       |       |
                                     ---------->| B->2  |------>|       |
                                        |       +-------+       | CPU 2 |
                                        |       | A->0  |------>|       |
                                        |       +-------+       |       |
                                        |       :       :       +-------+
                                         \      :       :
                                          \     +-------+
                                           ---->| A->1  |
                                                +-------+
                                                :       :


If, however, a read barrier were to be placed between the load of B and the
load of A on CPU 2:

        CPU 1                        CPU 2
        =======================        =======================
                { A = 0, B = 9 }
        STORE A=1
        <write barrier>
        STORE B=2
                                LOAD B
                                <read barrier>
                                LOAD A

then the partial ordering imposed by CPU 1 will be perceived correctly by CPU
2:

        +-------+       :      :                :       :
        |       |       +------+                +-------+
        |       |------>| A=1  |------      --->| A->0  |
        |       |       +------+      \         +-------+
        | CPU 1 |   wwwwwwwwwwwwwwww   \    --->| B->9  |
        |       |       +------+        |       +-------+
        |       |------>| B=2  |---     |       :       :
        |       |       +------+   \    |       :       :       +-------+
        +-------+       :      :    \   |       +-------+       |       |
                                     ---------->| B->2  |------>|       |
                                        |       +-------+       | CPU 2 |
                                        |       :       :       |       |
                                        |       :       :       |       |
          At this point the read ---->   \  rrrrrrrrrrrrrrrrr   |       |
          barrier causes all effects      \     +-------+       |       |
          prior to the storage of B        ---->| A->1  |------>|       |
          to be perceptible to CPU 2            +-------+       |       |
                                                :       :       +-------+


To illustrate this more completely, consider what could happen if the code
contained a load of A either side of the read barrier:

        CPU 1                        CPU 2
        =======================        =======================
                { A = 0, B = 9 }
        STORE A=1
        <write barrier>
        STORE B=2
                                LOAD B
                                LOAD A [first load of A]
                                <read barrier>
                                LOAD A [second load of A]

Even though the two loads of A both occur after the load of B, they may both
come up with different values:

        +-------+       :      :                :       :
        |       |       +------+                +-------+
        |       |------>| A=1  |------      --->| A->0  |
        |       |       +------+      \         +-------+
        | CPU 1 |   wwwwwwwwwwwwwwww   \    --->| B->9  |
        |       |       +------+        |       +-------+
        |       |------>| B=2  |---     |       :       :
        |       |       +------+   \    |       :       :       +-------+
        +-------+       :      :    \   |       +-------+       |       |
                                     ---------->| B->2  |------>|       |
                                        |       +-------+       | CPU 2 |
                                        |       :       :       |       |
                                        |       :       :       |       |
                                        |       +-------+       |       |
                                        |       | A->0  |------>| 1st   |
                                        |       +-------+       |       |
          At this point the read ---->   \  rrrrrrrrrrrrrrrrr   |       |
          barrier causes all effects      \     +-------+       |       |
          prior to the storage of B        ---->| A->1  |------>| 2nd   |
          to be perceptible to CPU 2            +-------+       |       |
                                                :       :       +-------+


But it may be that the update to A from CPU 1 becomes perceptible to CPU 2
before the read barrier completes anyway:

        +-------+       :      :                :       :
        |       |       +------+                +-------+
        |       |------>| A=1  |------      --->| A->0  |
        |       |       +------+      \         +-------+
        | CPU 1 |   wwwwwwwwwwwwwwww   \    --->| B->9  |
        |       |       +------+        |       +-------+
        |       |------>| B=2  |---     |       :       :
        |       |       +------+   \    |       :       :       +-------+
        +-------+       :      :    \   |       +-------+       |       |
                                     ---------->| B->2  |------>|       |
                                        |       +-------+       | CPU 2 |
                                        |       :       :       |       |
                                         \      :       :       |       |
                                          \     +-------+       |       |
                                           ---->| A->1  |------>| 1st   |
                                                +-------+       |       |
                                            rrrrrrrrrrrrrrrrr   |       |
                                                +-------+       |       |
                                                | A->1  |------>| 2nd   |
                                                +-------+       |       |
                                                :       :       +-------+


The guarantee is that the second load will always come up with A == 1 if the
load of B came up with B == 2.  No such guarantee exists for the first load of
A; that may come up with either A == 0 or A == 1.


READ MEMORY BARRIERS VS LOAD SPECULATION
----------------------------------------

Many CPUs speculate with loads: that is they see that they will need to load an
item from memory, and they find a time where they're not using the bus for any
other loads, and so do the load in advance - even though they haven't actually
got to that point in the instruction execution flow yet.  This permits the
actual load instruction to potentially complete immediately because the CPU
already has the value to hand.

It may turn out that the CPU didn't actually need the value - perhaps because a
branch circumvented the load - in which case it can discard the value or just
cache it for later use.

Consider:

        CPU 1                        CPU 2
        =======================        =======================
                                LOAD B
                                DIVIDE                } Divide instructions generally
                                DIVIDE                } take a long time to perform
                                LOAD A

Which might appear as this:

                                                :       :       +-------+
                                                +-------+       |       |
                                            --->| B->2  |------>|       |
                                                +-------+       | CPU 2 |
                                                :       :DIVIDE |       |
                                                +-------+       |       |
        The CPU being busy doing a --->     --->| A->0  |~~~~   |       |
        division speculates on the              +-------+   ~   |       |
        LOAD of A                               :       :   ~   |       |
                                                :       :DIVIDE |       |
                                                :       :   ~   |       |
        Once the divisions are complete -->     :       :   ~-->|       |
        the CPU can then perform the            :       :       |       |
        LOAD with immediate effect              :       :       +-------+


Placing a read barrier or an address-dependency barrier just before the second
load:

        CPU 1                        CPU 2
        =======================        =======================
                                LOAD B
                                DIVIDE
                                DIVIDE
                                <read barrier>
                                LOAD A

will force any value speculatively obtained to be reconsidered to an extent
dependent on the type of barrier used.  If there was no change made to the
speculated memory location, then the speculated value will just be used:

                                                :       :       +-------+
                                                +-------+       |       |
                                            --->| B->2  |------>|       |
                                                +-------+       | CPU 2 |
                                                :       :DIVIDE |       |
                                                +-------+       |       |
        The CPU being busy doing a --->     --->| A->0  |~~~~   |       |
        division speculates on the              +-------+   ~   |       |
        LOAD of A                               :       :   ~   |       |
                                                :       :DIVIDE |       |
                                                :       :   ~   |       |
                                                :       :   ~   |       |
                                            rrrrrrrrrrrrrrrr~   |       |
                                                :       :   ~   |       |
                                                :       :   ~-->|       |
                                                :       :       |       |
                                                :       :       +-------+


but if there was an update or an invalidation from another CPU pending, then
the speculation will be cancelled and the value reloaded:

                                                :       :       +-------+
                                                +-------+       |       |
                                            --->| B->2  |------>|       |
                                                +-------+       | CPU 2 |
                                                :       :DIVIDE |       |
                                                +-------+       |       |
        The CPU being busy doing a --->     --->| A->0  |~~~~   |       |
        division speculates on the              +-------+   ~   |       |
        LOAD of A                               :       :   ~   |       |
                                                :       :DIVIDE |       |
                                                :       :   ~   |       |
                                                :       :   ~   |       |
                                            rrrrrrrrrrrrrrrrr   |       |
                                                +-------+       |       |
        The speculation is discarded --->   --->| A->1  |------>|       |
        and an updated value is                 +-------+       |       |
        retrieved                               :       :       +-------+


MULTICOPY ATOMICITY
--------------------

Multicopy atomicity is a deeply intuitive notion about ordering that is
not always provided by real computer systems, namely that a given store
becomes visible at the same time to all CPUs, or, alternatively, that all
CPUs agree on the order in which all stores become visible.  However,
support of full multicopy atomicity would rule out valuable hardware
optimizations, so a weaker form called ``other multicopy atomicity''
instead guarantees only that a given store becomes visible at the same
time to all -other- CPUs.  The remainder of this document discusses this
weaker form, but for brevity will call it simply ``multicopy atomicity''.

The following example demonstrates multicopy atomicity:

        CPU 1                        CPU 2                        CPU 3
        =======================        =======================        =======================
                { X = 0, Y = 0 }
        STORE X=1                r1=LOAD X (reads 1)        LOAD Y (reads 1)
                                <general barrier>        <read barrier>
                                STORE Y=r1                LOAD X

Suppose that CPU 2's load from X returns 1, which it then stores to Y,
and CPU 3's load from Y returns 1.  This indicates that CPU 1's store
to X precedes CPU 2's load from X and that CPU 2's store to Y precedes
CPU 3's load from Y.  In addition, the memory barriers guarantee that
CPU 2 executes its load before its store, and CPU 3 loads from Y before
it loads from X.  The question is then "Can CPU 3's load from X return 0?"

Because CPU 3's load from X in some sense comes after CPU 2's load, it
is natural to expect that CPU 3's load from X must therefore return 1.
This expectation follows from multicopy atomicity: if a load executing
on CPU B follows a load from the same variable executing on CPU A (and
CPU A did not originally store the value which it read), then on
multicopy-atomic systems, CPU B's load must return either the same value
that CPU A's load did or some later value.  However, the Linux kernel
does not require systems to be multicopy atomic.

The use of a general memory barrier in the example above compensates
for any lack of multicopy atomicity.  In the example, if CPU 2's load
from X returns 1 and CPU 3's load from Y returns 1, then CPU 3's load
from X must indeed also return 1.

However, dependencies, read barriers, and write barriers are not always
able to compensate for non-multicopy atomicity.  For example, suppose
that CPU 2's general barrier is removed from the above example, leaving
only the data dependency shown below:

        CPU 1                        CPU 2                        CPU 3
        =======================        =======================        =======================
                { X = 0, Y = 0 }
        STORE X=1                r1=LOAD X (reads 1)        LOAD Y (reads 1)
                                <data dependency>        <read barrier>
                                STORE Y=r1                LOAD X (reads 0)

This substitution allows non-multicopy atomicity to run rampant: in
this example, it is perfectly legal for CPU 2's load from X to return 1,
CPU 3's load from Y to return 1, and its load from X to return 0.

The key point is that although CPU 2's data dependency orders its load
and store, it does not guarantee to order CPU 1's store.  Thus, if this
example runs on a non-multicopy-atomic system where CPUs 1 and 2 share a
store buffer or a level of cache, CPU 2 might have early access to CPU 1's
writes.  General barriers are therefore required to ensure that all CPUs
agree on the combined order of multiple accesses.

General barriers can compensate not only for non-multicopy atomicity,
but can also generate additional ordering that can ensure that -all-
CPUs will perceive the same order of -all- operations.  In contrast, a
chain of release-acquire pairs do not provide this additional ordering,
which means that only those CPUs on the chain are guaranteed to agree
on the combined order of the accesses.  For example, switching to C code
in deference to the ghost of Herman Hollerith:

        int u, v, x, y, z;

        void cpu0(void)
        {
                r0 = smp_load_acquire(&x);
                WRITE_ONCE(u, 1);
                smp_store_release(&y, 1);
        }

        void cpu1(void)
        {
                r1 = smp_load_acquire(&y);
                r4 = READ_ONCE(v);
                r5 = READ_ONCE(u);
                smp_store_release(&z, 1);
        }

        void cpu2(void)
        {
                r2 = smp_load_acquire(&z);
                smp_store_release(&x, 1);
        }

        void cpu3(void)
        {
                WRITE_ONCE(v, 1);
                smp_mb();
                r3 = READ_ONCE(u);
        }

Because cpu0(), cpu1(), and cpu2() participate in a chain of
smp_store_release()/smp_load_acquire() pairs, the following outcome
is prohibited:

        r0 == 1 && r1 == 1 && r2 == 1

Furthermore, because of the release-acquire relationship between cpu0()
and cpu1(), cpu1() must see cpu0()'s writes, so that the following
outcome is prohibited:

        r1 == 1 && r5 == 0

However, the ordering provided by a release-acquire chain is local
to the CPUs participating in that chain and does not apply to cpu3(),
at least aside from stores.  Therefore, the following outcome is possible:

        r0 == 0 && r1 == 1 && r2 == 1 && r3 == 0 && r4 == 0

As an aside, the following outcome is also possible:

        r0 == 0 && r1 == 1 && r2 == 1 && r3 == 0 && r4 == 0 && r5 == 1

Although cpu0(), cpu1(), and cpu2() will see their respective reads and
writes in order, CPUs not involved in the release-acquire chain might
well disagree on the order.  This disagreement stems from the fact that
the weak memory-barrier instructions used to implement smp_load_acquire()
and smp_store_release() are not required to order prior stores against
subsequent loads in all cases.  This means that cpu3() can see cpu0()'s
store to u as happening -after- cpu1()'s load from v, even though
both cpu0() and cpu1() agree that these two operations occurred in the
intended order.

However, please keep in mind that smp_load_acquire() is not magic.
In particular, it simply reads from its argument with ordering.  It does
-not- ensure that any particular value will be read.  Therefore, the
following outcome is possible:

        r0 == 0 && r1 == 0 && r2 == 0 && r5 == 0

Note that this outcome can happen even on a mythical sequentially
consistent system where nothing is ever reordered.

To reiterate, if your code requires full ordering of all operations,
use general barriers throughout.


========================
EXPLICIT KERNEL BARRIERS
========================

The Linux kernel has a variety of different barriers that act at different
levels:

  (*) Compiler barrier.

  (*) CPU memory barriers.


COMPILER BARRIER
----------------

The Linux kernel has an explicit compiler barrier function that prevents the
compiler from moving the memory accesses either side of it to the other side:

        barrier();

This is a general barrier -- there are no read-read or write-write
variants of barrier().  However, READ_ONCE() and WRITE_ONCE() can be
thought of as weak forms of barrier() that affect only the specific
accesses flagged by the READ_ONCE() or WRITE_ONCE().

The barrier() function has the following effects:

 (*) Prevents the compiler from reordering accesses following the
     barrier() to precede any accesses preceding the barrier().
     One example use for this property is to ease communication between
     interrupt-handler code and the code that was interrupted.

 (*) Within a loop, forces the compiler to load the variables used
     in that loop's conditional on each pass through that loop.

The READ_ONCE() and WRITE_ONCE() functions can prevent any number of
optimizations that, while perfectly safe in single-threaded code, can
be fatal in concurrent code.  Here are some examples of these sorts
of optimizations:

 (*) The compiler is within its rights to reorder loads and stores
     to the same variable, and in some cases, the CPU is within its
     rights to reorder loads to the same variable.  This means that
     the following code:

        a[0] = x;
        a[1] = x;

     Might result in an older value of x stored in a[1] than in a[0].
     Prevent both the compiler and the CPU from doing this as follows:

        a[0] = READ_ONCE(x);
        a[1] = READ_ONCE(x);

     In short, READ_ONCE() and WRITE_ONCE() provide cache coherence for
     accesses from multiple CPUs to a single variable.

 (*) The compiler is within its rights to merge successive loads from
     the same variable.  Such merging can cause the compiler to "optimize"
     the following code:

        while (tmp = a)
                do_something_with(tmp);

     into the following code, which, although in some sense legitimate
     for single-threaded code, is almost certainly not what the developer
     intended:

        if (tmp = a)
                for (;;)
                        do_something_with(tmp);

     Use READ_ONCE() to prevent the compiler from doing this to you:

        while (tmp = READ_ONCE(a))
                do_something_with(tmp);

 (*) The compiler is within its rights to reload a variable, for example,
     in cases where high register pressure prevents the compiler from
     keeping all data of interest in registers.  The compiler might
     therefore optimize the variable 'tmp' out of our previous example:

        while (tmp = a)
                do_something_with(tmp);

     This could result in the following code, which is perfectly safe in
     single-threaded code, but can be fatal in concurrent code:

        while (a)
                do_something_with(a);

     For example, the optimized version of this code could result in
     passing a zero to do_something_with() in the case where the variable
     a was modified by some other CPU between the "while" statement and
     the call to do_something_with().

     Again, use READ_ONCE() to prevent the compiler from doing this:

        while (tmp = READ_ONCE(a))
                do_something_with(tmp);

     Note that if the compiler runs short of registers, it might save
     tmp onto the stack.  The overhead of this saving and later restoring
     is why compilers reload variables.  Doing so is perfectly safe for
     single-threaded code, so you need to tell the compiler about cases
     where it is not safe.

 (*) The compiler is within its rights to omit a load entirely if it knows
     what the value will be.  For example, if the compiler can prove that
     the value of variable 'a' is always zero, it can optimize this code:

        while (tmp = a)
                do_something_with(tmp);

     Into this:

        do { } while (0);

     This transformation is a win for single-threaded code because it
     gets rid of a load and a branch.  The problem is that the compiler
     will carry out its proof assuming that the current CPU is the only
     one updating variable 'a'.  If variable 'a' is shared, then the
     compiler's proof will be erroneous.  Use READ_ONCE() to tell the
     compiler that it doesn't know as much as it thinks it does:

        while (tmp = READ_ONCE(a))
                do_something_with(tmp);

     But please note that the compiler is also closely watching what you
     do with the value after the READ_ONCE().  For example, suppose you
     do the following and MAX is a preprocessor macro with the value 1:

        while ((tmp = READ_ONCE(a)) % MAX)
                do_something_with(tmp);

     Then the compiler knows that the result of the "%" operator applied
     to MAX will always be zero, again allowing the compiler to optimize
     the code into near-nonexistence.  (It will still load from the
     variable 'a'.)

 (*) Similarly, the compiler is within its rights to omit a store entirely
     if it knows that the variable already has the value being stored.
     Again, the compiler assumes that the current CPU is the only one
     storing into the variable, which can cause the compiler to do the
     wrong thing for shared variables.  For example, suppose you have
     the following:

        a = 0;
        ... Code that does not store to variable a ...
        a = 0;

     The compiler sees that the value of variable 'a' is already zero, so
     it might well omit the second store.  This would come as a fatal
     surprise if some other CPU might have stored to variable 'a' in the
     meantime.

     Use WRITE_ONCE() to prevent the compiler from making this sort of
     wrong guess:

        WRITE_ONCE(a, 0);
        ... Code that does not store to variable a ...
        WRITE_ONCE(a, 0);

 (*) The compiler is within its rights to reorder memory accesses unless
     you tell it not to.  For example, consider the following interaction
     between process-level code and an interrupt handler:

        void process_level(void)
        {
                msg = get_message();
                flag = true;
        }

        void interrupt_handler(void)
        {
                if (flag)
                        process_message(msg);
        }

     There is nothing to prevent the compiler from transforming
     process_level() to the following, in fact, this might well be a
     win for single-threaded code:

        void process_level(void)
        {
                flag = true;
                msg = get_message();
        }

     If the interrupt occurs between these two statement, then
     interrupt_handler() might be passed a garbled msg.  Use WRITE_ONCE()
     to prevent this as follows:

        void process_level(void)
        {
                WRITE_ONCE(msg, get_message());
                WRITE_ONCE(flag, true);
        }

        void interrupt_handler(void)
        {
                if (READ_ONCE(flag))
                        process_message(READ_ONCE(msg));
        }

     Note that the READ_ONCE() and WRITE_ONCE() wrappers in
     interrupt_handler() are needed if this interrupt handler can itself
     be interrupted by something that also accesses 'flag' and 'msg',
     for example, a nested interrupt or an NMI.  Otherwise, READ_ONCE()
     and WRITE_ONCE() are not needed in interrupt_handler() other than
     for documentation purposes.  (Note also that nested interrupts
     do not typically occur in modern Linux kernels, in fact, if an
     interrupt handler returns with interrupts enabled, you will get a
     WARN_ONCE() splat.)

     You should assume that the compiler can move READ_ONCE() and
     WRITE_ONCE() past code not containing READ_ONCE(), WRITE_ONCE(),
     barrier(), or similar primitives.

     This effect could also be achieved using barrier(), but READ_ONCE()
     and WRITE_ONCE() are more selective:  With READ_ONCE() and
     WRITE_ONCE(), the compiler need only forget the contents of the
     indicated memory locations, while with barrier() the compiler must
     discard the value of all memory locations that it has currently
     cached in any machine registers.  Of course, the compiler must also
     respect the order in which the READ_ONCE()s and WRITE_ONCE()s occur,
     though the CPU of course need not do so.

 (*) The compiler is within its rights to invent stores to a variable,
     as in the following example:

        if (a)
                b = a;
        else
                b = 42;

     The compiler might save a branch by optimizing this as follows:

        b = 42;
        if (a)
                b = a;

     In single-threaded code, this is not only safe, but also saves
     a branch.  Unfortunately, in concurrent code, this optimization
     could cause some other CPU to see a spurious value of 42 -- even
     if variable 'a' was never zero -- when loading variable 'b'.
     Use WRITE_ONCE() to prevent this as follows:

        if (a)
                WRITE_ONCE(b, a);
        else
                WRITE_ONCE(b, 42);

     The compiler can also invent loads.  These are usually less
     damaging, but they can result in cache-line bouncing and thus in
     poor performance and scalability.  Use READ_ONCE() to prevent
     invented loads.

 (*) For aligned memory locations whose size allows them to be accessed
     with a single memory-reference instruction, prevents "load tearing"
     and "store tearing," in which a single large access is replaced by
     multiple smaller accesses.  For example, given an architecture having
     16-bit store instructions with 7-bit immediate fields, the compiler
     might be tempted to use two 16-bit store-immediate instructions to
     implement the following 32-bit store:

        p = 0x00010002;

     Please note that GCC really does use this sort of optimization,
     which is not surprising given that it would likely take more
     than two instructions to build the constant and then store it.
     This optimization can therefore be a win in single-threaded code.
     In fact, a recent bug (since fixed) caused GCC to incorrectly use
     this optimization in a volatile store.  In the absence of such bugs,
     use of WRITE_ONCE() prevents store tearing in the following example:

        WRITE_ONCE(p, 0x00010002);

     Use of packed structures can also result in load and store tearing,
     as in this example:

        struct __attribute__((__packed__)) foo {
                short a;
                int b;
                short c;
        };
        struct foo foo1, foo2;
        ...

        foo2.a = foo1.a;
        foo2.b = foo1.b;
        foo2.c = foo1.c;

     Because there are no READ_ONCE() or WRITE_ONCE() wrappers and no
     volatile markings, the compiler would be well within its rights to
     implement these three assignment statements as a pair of 32-bit
     loads followed by a pair of 32-bit stores.  This would result in
     load tearing on 'foo1.b' and store tearing on 'foo2.b'.  READ_ONCE()
     and WRITE_ONCE() again prevent tearing in this example:

        foo2.a = foo1.a;
        WRITE_ONCE(foo2.b, READ_ONCE(foo1.b));
        foo2.c = foo1.c;

All that aside, it is never necessary to use READ_ONCE() and
WRITE_ONCE() on a variable that has been marked volatile.  For example,
because 'jiffies' is marked volatile, it is never necessary to
say READ_ONCE(jiffies).  The reason for this is that READ_ONCE() and
WRITE_ONCE() are implemented as volatile casts, which has no effect when
its argument is already marked volatile.

Please note that these compiler barriers have no direct effect on the CPU,
which may then reorder things however it wishes.


CPU MEMORY BARRIERS
-------------------

The Linux kernel has seven basic CPU memory barriers:

        TYPE                        MANDATORY        SMP CONDITIONAL
        =======================        ===============        ===============
        GENERAL                        mb()                smp_mb()
        WRITE                        wmb()                smp_wmb()
        READ                        rmb()                smp_rmb()
        ADDRESS DEPENDENCY                        READ_ONCE()


All memory barriers except the address-dependency barriers imply a compiler
barrier.  Address dependencies do not impose any additional compiler ordering.

Aside: In the case of address dependencies, the compiler would be expected
to issue the loads in the correct order (eg. `a[b]` would have to load
the value of b before loading a[b]), however there is no guarantee in
the C specification that the compiler may not speculate the value of b
(eg. is equal to 1) and load a[b] before b (eg. tmp = a[1]; if (b != 1)
tmp = a[b]; ).  There is also the problem of a compiler reloading b after
having loaded a[b], thus having a newer copy of b than a[b].  A consensus
has not yet been reached about these problems, however the READ_ONCE()
macro is a good place to start looking.

SMP memory barriers are reduced to compiler barriers on uniprocessor compiled
systems because it is assumed that a CPU will appear to be self-consistent,
and will order overlapping accesses correctly with respect to itself.
However, see the subsection on "Virtual Machine Guests" below.

[!] Note that SMP memory barriers _must_ be used to control the ordering of
references to shared memory on SMP systems, though the use of locking instead
is sufficient.

Mandatory barriers should not be used to control SMP effects, since mandatory
barriers impose unnecessary overhead on both SMP and UP systems. They may,
however, be used to control MMIO effects on accesses through relaxed memory I/O
windows.  These barriers are required even on non-SMP systems as they affect
the order in which memory operations appear to a device by prohibiting both the
compiler and the CPU from reordering them.


There are some more advanced barrier functions:

 (*) smp_store_mb(var, value)

     This assigns the value to the variable and then inserts a full memory
     barrier after it.  It isn't guaranteed to insert anything more than a
     compiler barrier in a UP compilation.


 (*) smp_mb__before_atomic();
 (*) smp_mb__after_atomic();

     These are for use with atomic RMW functions that do not imply memory
     barriers, but where the code needs a memory barrier. Examples for atomic
     RMW functions that do not imply a memory barrier are e.g. add,
     subtract, (failed) conditional operations, _relaxed functions,
     but not atomic_read or atomic_set. A common example where a memory
     barrier may be required is when atomic ops are used for reference
     counting.

     These are also used for atomic RMW bitop functions that do not imply a
     memory barrier (such as set_bit and clear_bit).

     As an example, consider a piece of code that marks an object as being dead
     and then decrements the object's reference count:

        obj->dead = 1;
        smp_mb__before_atomic();
        atomic_dec(&obj->ref_count);

     This makes sure that the death mark on the object is perceived to be set
     *before* the reference counter is decremented.

     See Documentation/atomic_{t,bitops}.txt for more information.


 (*) dma_wmb();
 (*) dma_rmb();
 (*) dma_mb();

     These are for use with consistent memory to guarantee the ordering
     of writes or reads of shared memory accessible to both the CPU and a
     DMA capable device. See Documentation/core-api/dma-api.rst file for more
     information about consistent memory.

     For example, consider a device driver that shares memory with a device
     and uses a descriptor status value to indicate if the descriptor belongs
     to the device or the CPU, and a doorbell to notify it when new
     descriptors are available:

        if (desc->status != DEVICE_OWN) {
                /* do not read data until we own descriptor */
                dma_rmb();

                /* read/modify data */
                read_data = desc->data;
                desc->data = write_data;

                /* flush modifications before status update */
                dma_wmb();

                /* assign ownership */
                desc->status = DEVICE_OWN;

                /* Make descriptor status visible to the device followed by
                 * notify device of new descriptor
                 */
                writel(DESC_NOTIFY, doorbell);
        }

     The dma_rmb() allows us to guarantee that the device has released ownership
     before we read the data from the descriptor, and the dma_wmb() allows
     us to guarantee the data is written to the descriptor before the device
     can see it now has ownership.  The dma_mb() implies both a dma_rmb() and
     a dma_wmb().

     Note that the dma_*() barriers do not provide any ordering guarantees for
     accesses to MMIO regions.  See the later "KERNEL I/O BARRIER EFFECTS"
     subsection for more information about I/O accessors and MMIO ordering.

 (*) pmem_wmb();

     This is for use with persistent memory to ensure that stores for which
     modifications are written to persistent storage reached a platform
     durability domain.

     For example, after a non-temporal write to pmem region, we use pmem_wmb()
     to ensure that stores have reached a platform durability domain. This ensures
     that stores have updated persistent storage before any data access or
     data transfer caused by subsequent instructions is initiated. This is
     in addition to the ordering done by wmb().

     For load from persistent memory, existing read memory barriers are sufficient
     to ensure read ordering.

 (*) io_stop_wc();

     For memory accesses with write-combining attributes (e.g. those returned
     by ioremap_wc()), the CPU may wait for prior accesses to be merged with
     subsequent ones. io_stop_wc() can be used to prevent the merging of
     write-combining memory accesses before this macro with those after it when
     such wait has performance implications.

===============================
IMPLICIT KERNEL MEMORY BARRIERS
===============================

Some of the other functions in the linux kernel imply memory barriers, amongst
which are locking and scheduling functions.

This specification is a _minimum_ guarantee; any particular architecture may
provide more substantial guarantees, but these may not be relied upon outside
of arch specific code.


LOCK ACQUISITION FUNCTIONS
--------------------------

The Linux kernel has a number of locking constructs:

 (*) spin locks
 (*) R/W spin locks
 (*) mutexes
 (*) semaphores
 (*) R/W semaphores

In all cases there are variants on "ACQUIRE" operations and "RELEASE" operations
for each construct.  These operations all imply certain barriers:

 (1) ACQUIRE operation implication:

     Memory operations issued after the ACQUIRE will be completed after the
     ACQUIRE operation has completed.

     Memory operations issued before the ACQUIRE may be completed after
     the ACQUIRE operation has completed.

 (2) RELEASE operation implication:

     Memory operations issued before the RELEASE will be completed before the
     RELEASE operation has completed.

     Memory operations issued after the RELEASE may be completed before the
     RELEASE operation has completed.

 (3) ACQUIRE vs ACQUIRE implication:

     All ACQUIRE operations issued before another ACQUIRE operation will be
     completed before that ACQUIRE operation.

 (4) ACQUIRE vs RELEASE implication:

     All ACQUIRE operations issued before a RELEASE operation will be
     completed before the RELEASE operation.

 (5) Failed conditional ACQUIRE implication:

     Certain locking variants of the ACQUIRE operation may fail, either due to
     being unable to get the lock immediately, or due to receiving an unblocked
     signal while asleep waiting for the lock to become available.  Failed
     locks do not imply any sort of barrier.

[!] Note: one of the consequences of lock ACQUIREs and RELEASEs being only
one-way barriers is that the effects of instructions outside of a critical
section may seep into the inside of the critical section.

An ACQUIRE followed by a RELEASE may not be assumed to be full memory barrier
because it is possible for an access preceding the ACQUIRE to happen after the
ACQUIRE, and an access following the RELEASE to happen before the RELEASE, and
the two accesses can themselves then cross:

        *A = a;
        ACQUIRE M
        RELEASE M
        *B = b;

may occur as:

        ACQUIRE M, STORE *B, STORE *A, RELEASE M

When the ACQUIRE and RELEASE are a lock acquisition and release,
respectively, this same reordering can occur if the lock's ACQUIRE and
RELEASE are to the same lock variable, but only from the perspective of
another CPU not holding that lock.  In short, a ACQUIRE followed by an
RELEASE may -not- be assumed to be a full memory barrier.

Similarly, the reverse case of a RELEASE followed by an ACQUIRE does
not imply a full memory barrier.  Therefore, the CPU's execution of the
critical sections corresponding to the RELEASE and the ACQUIRE can cross,
so that:

        *A = a;
        RELEASE M
        ACQUIRE N
        *B = b;

could occur as:

        ACQUIRE N, STORE *B, STORE *A, RELEASE M

It might appear that this reordering could introduce a deadlock.
However, this cannot happen because if such a deadlock threatened,
the RELEASE would simply complete, thereby avoiding the deadlock.

        Why does this work?

        One key point is that we are only talking about the CPU doing
        the reordering, not the compiler.  If the compiler (or, for
        that matter, the developer) switched the operations, deadlock
        -could- occur.

        But suppose the CPU reordered the operations.  In this case,
        the unlock precedes the lock in the assembly code.  The CPU
        simply elected to try executing the later lock operation first.
        If there is a deadlock, this lock operation will simply spin (or
        try to sleep, but more on that later).        The CPU will eventually
        execute the unlock operation (which preceded the lock operation
        in the assembly code), which will unravel the potential deadlock,
        allowing the lock operation to succeed.

        But what if the lock is a sleeplock?  In that case, the code will
        try to enter the scheduler, where it will eventually encounter
        a memory barrier, which will force the earlier unlock operation
        to complete, again unraveling the deadlock.  There might be
        a sleep-unlock race, but the locking primitive needs to resolve
        such races properly in any case.

Locks and semaphores may not provide any guarantee of ordering on UP compiled
systems, and so cannot be counted on in such a situation to actually achieve
anything at all - especially with respect to I/O accesses - unless combined
with interrupt disabling operations.

See also the section on "Inter-CPU acquiring barrier effects".


As an example, consider the following:

        *A = a;
        *B = b;
        ACQUIRE
        *C = c;
        *D = d;
        RELEASE
        *E = e;
        *F = f;

The following sequence of events is acceptable:

        ACQUIRE, {*F,*A}, *E, {*C,*D}, *B, RELEASE

        [+] Note that {*F,*A} indicates a combined access.

But none of the following are:

        {*F,*A}, *B,        ACQUIRE, *C, *D,        RELEASE, *E
        *A, *B, *C,        ACQUIRE, *D,                RELEASE, *E, *F
        *A, *B,                ACQUIRE, *C,                RELEASE, *D, *E, *F
        *B,                ACQUIRE, *C, *D,        RELEASE, {*F,*A}, *E



INTERRUPT DISABLING FUNCTIONS
-----------------------------

Functions that disable interrupts (ACQUIRE equivalent) and enable interrupts
(RELEASE equivalent) will act as compiler barriers only.  So if memory or I/O
barriers are required in such a situation, they must be provided from some
other means.


SLEEP AND WAKE-UP FUNCTIONS
---------------------------

Sleeping and waking on an event flagged in global data can be viewed as an
interaction between two pieces of data: the task state of the task waiting for
the event and the global data used to indicate the event.  To make sure that
these appear to happen in the right order, the primitives to begin the process
of going to sleep, and the primitives to initiate a wake up imply certain
barriers.

Firstly, the sleeper normally follows something like this sequence of events:

        for (;;) {
                set_current_state(TASK_UNINTERRUPTIBLE);
                if (event_indicated)
                        break;
                schedule();
        }

A general memory barrier is interpolated automatically by set_current_state()
after it has altered the task state:

        CPU 1
        ===============================
        set_current_state();
          smp_store_mb();
            STORE current->state
            <general barrier>
        LOAD event_indicated

set_current_state() may be wrapped by:

        prepare_to_wait();
        prepare_to_wait_exclusive();

which therefore also imply a general memory barrier after setting the state.
The whole sequence above is available in various canned forms, all of which
interpolate the memory barrier in the right place:

        wait_event();
        wait_event_interruptible();
        wait_event_interruptible_exclusive();
        wait_event_interruptible_timeout();
        wait_event_killable();
        wait_event_timeout();
        wait_on_bit();
        wait_on_bit_lock();
        wait_event_cmd();
        wait_event_exclusive_cmd();


Secondly, code that performs a wake up normally follows something like this:

        event_indicated = 1;
        wake_up(&event_wait_queue);

or:

        event_indicated = 1;
        wake_up_process(event_daemon);

A general memory barrier is executed by wake_up() if it wakes something up.
If it doesn't wake anything up then a memory barrier may or may not be
executed; you must not rely on it.  The barrier occurs before the task state
is accessed, in particular, it sits between the STORE to indicate the event
and the STORE to set TASK_RUNNING:

        CPU 1 (Sleeper)                        CPU 2 (Waker)
        ===============================        ===============================
        set_current_state();                STORE event_indicated
          smp_store_mb();                wake_up();
            STORE current->state          ...
            <general barrier>                  <general barrier>
        LOAD event_indicated                  if ((LOAD task->state) & TASK_NORMAL)
                                            STORE task->state

where "task" is the thread being woken up and it equals CPU 1's "current".

To repeat, a general memory barrier is guaranteed to be executed by wake_up()
if something is actually awakened, but otherwise there is no such guarantee.
To see this, consider the following sequence of events, where X and Y are both
initially zero:

        CPU 1                                CPU 2
        ===============================        ===============================
        X = 1;                                Y = 1;
        smp_mb();                        wake_up();
        LOAD Y                                LOAD X

If a wakeup does occur, one (at least) of the two loads must see 1.  If, on
the other hand, a wakeup does not occur, both loads might see 0.

wake_up_process() always executes a general memory barrier.  The barrier again
occurs before the task state is accessed.  In particular, if the wake_up() in
the previous snippet were replaced by a call to wake_up_process() then one of
the two loads would be guaranteed to see 1.

The available waker functions include:

        complete();
        wake_up();
        wake_up_all();
        wake_up_bit();
        wake_up_interruptible();
        wake_up_interruptible_all();
        wake_up_interruptible_nr();
        wake_up_interruptible_poll();
        wake_up_interruptible_sync();
        wake_up_interruptible_sync_poll();
        wake_up_locked();
        wake_up_locked_poll();
        wake_up_nr();
        wake_up_poll();
        wake_up_process();

In terms of memory ordering, these functions all provide the same guarantees of
a wake_up() (or stronger).

[!] Note that the memory barriers implied by the sleeper and the waker do _not_
order multiple stores before the wake-up with respect to loads of those stored
values after the sleeper has called set_current_state().  For instance, if the
sleeper does:

        set_current_state(TASK_INTERRUPTIBLE);
        if (event_indicated)
                break;
        __set_current_state(TASK_RUNNING);
        do_something(my_data);

and the waker does:

        my_data = value;
        event_indicated = 1;
        wake_up(&event_wait_queue);

there's no guarantee that the change to event_indicated will be perceived by
the sleeper as coming after the change to my_data.  In such a circumstance, the
code on both sides must interpolate its own memory barriers between the
separate data accesses.  Thus the above sleeper ought to do:

        set_current_state(TASK_INTERRUPTIBLE);
        if (event_indicated) {
                smp_rmb();
                do_something(my_data);
        }

and the waker should do:

        my_data = value;
        smp_wmb();
        event_indicated = 1;
        wake_up(&event_wait_queue);


MISCELLANEOUS FUNCTIONS
-----------------------

Other functions that imply barriers:

 (*) schedule() and similar imply full memory barriers.


===================================
INTER-CPU ACQUIRING BARRIER EFFECTS
===================================

On SMP systems locking primitives give a more substantial form of barrier: one
that does affect memory access ordering on other CPUs, within the context of
conflict on any particular lock.


ACQUIRES VS MEMORY ACCESSES
---------------------------

Consider the following: the system has a pair of spinlocks (M) and (Q), and
three CPUs; then should the following sequence of events occur:

        CPU 1                                CPU 2
        ===============================        ===============================
        WRITE_ONCE(*A, a);                WRITE_ONCE(*E, e);
        ACQUIRE M                        ACQUIRE Q
        WRITE_ONCE(*B, b);                WRITE_ONCE(*F, f);
        WRITE_ONCE(*C, c);                WRITE_ONCE(*G, g);
        RELEASE M                        RELEASE Q
        WRITE_ONCE(*D, d);                WRITE_ONCE(*H, h);

Then there is no guarantee as to what order CPU 3 will see the accesses to *A
through *H occur in, other than the constraints imposed by the separate locks
on the separate CPUs.  It might, for example, see:

        *E, ACQUIRE M, ACQUIRE Q, *G, *C, *F, *A, *B, RELEASE Q, *D, *H, RELEASE M

But it won't see any of:

        *B, *C or *D preceding ACQUIRE M
        *A, *B or *C following RELEASE M
        *F, *G or *H preceding ACQUIRE Q
        *E, *F or *G following RELEASE Q


=================================
WHERE ARE MEMORY BARRIERS NEEDED?
=================================

Under normal operation, memory operation reordering is generally not going to
be a problem as a single-threaded linear piece of code will still appear to
work correctly, even if it's in an SMP kernel.  There are, however, four
circumstances in which reordering definitely _could_ be a problem:

 (*) Interprocessor interaction.

 (*) Atomic operations.

 (*) Accessing devices.

 (*) Interrupts.


INTERPROCESSOR INTERACTION
--------------------------

When there's a system with more than one processor, more than one CPU in the
system may be working on the same data set at the same time.  This can cause
synchronisation problems, and the usual way of dealing with them is to use
locks.  Locks, however, are quite expensive, and so it may be preferable to
operate without the use of a lock if at all possible.  In such a case
operations that affect both CPUs may have to be carefully ordered to prevent
a malfunction.

Consider, for example, the R/W semaphore slow path.  Here a waiting process is
queued on the semaphore, by virtue of it having a piece of its stack linked to
the semaphore's list of waiting processes:

        struct rw_semaphore {
                ...
                spinlock_t lock;
                struct list_head waiters;
        };

        struct rwsem_waiter {
                struct list_head list;
                struct task_struct *task;
        };

To wake up a particular waiter, the up_read() or up_write() functions have to:

 (1) read the next pointer from this waiter's record to know as to where the
     next waiter record is;

 (2) read the pointer to the waiter's task structure;

 (3) clear the task pointer to tell the waiter it has been given the semaphore;

 (4) call wake_up_process() on the task; and

 (5) release the reference held on the waiter's task struct.

In other words, it has to perform this sequence of events:

        LOAD waiter->list.next;
        LOAD waiter->task;
        STORE waiter->task;
        CALL wakeup
        RELEASE task

and if any of these steps occur out of order, then the whole thing may
malfunction.

Once it has queued itself and dropped the semaphore lock, the waiter does not
get the lock again; it instead just waits for its task pointer to be cleared
before proceeding.  Since the record is on the waiter's stack, this means that
if the task pointer is cleared _before_ the next pointer in the list is read,
another CPU might start processing the waiter and might clobber the waiter's
stack before the up*() function has a chance to read the next pointer.

Consider then what might happen to the above sequence of events:

        CPU 1                                CPU 2
        ===============================        ===============================
                                        down_xxx()
                                        Queue waiter
                                        Sleep
        up_yyy()
        LOAD waiter->task;
        STORE waiter->task;
                                        Woken up by other event
        <preempt>
                                        Resume processing
                                        down_xxx() returns
                                        call foo()
                                        foo() clobbers *waiter
        </preempt>
        LOAD waiter->list.next;
        --- OOPS ---

This could be dealt with using the semaphore lock, but then the down_xxx()
function has to needlessly get the spinlock again after being woken up.

The way to deal with this is to insert a general SMP memory barrier:

        LOAD waiter->list.next;
        LOAD waiter->task;
        smp_mb();
        STORE waiter->task;
        CALL wakeup
        RELEASE task

In this case, the barrier makes a guarantee that all memory accesses before the
barrier will appear to happen before all the memory accesses after the barrier
with respect to the other CPUs on the system.  It does _not_ guarantee that all
the memory accesses before the barrier will be complete by the time the barrier
instruction itself is complete.

On a UP system - where this wouldn't be a problem - the smp_mb() is just a
compiler barrier, thus making sure the compiler emits the instructions in the
right order without actually intervening in the CPU.  Since there's only one
CPU, that CPU's dependency ordering logic will take care of everything else.


ATOMIC OPERATIONS
-----------------

While they are technically interprocessor interaction considerations, atomic
operations are noted specially as some of them imply full memory barriers and
some don't, but they're very heavily relied on as a group throughout the
kernel.

See Documentation/atomic_t.txt for more information.


ACCESSING DEVICES
-----------------

Many devices can be memory mapped, and so appear to the CPU as if they're just
a set of memory locations.  To control such a device, the driver usually has to
make the right memory accesses in exactly the right order.

However, having a clever CPU or a clever compiler creates a potential problem
in that the carefully sequenced accesses in the driver code won't reach the
device in the requisite order if the CPU or the compiler thinks it is more
efficient to reorder, combine or merge accesses - something that would cause
the device to malfunction.

Inside of the Linux kernel, I/O should be done through the appropriate accessor
routines - such as inb() or writel() - which know how to make such accesses
appropriately sequential.  While this, for the most part, renders the explicit
use of memory barriers unnecessary, if the accessor functions are used to refer
to an I/O memory window with relaxed memory access properties, then _mandatory_
memory barriers are required to enforce ordering.

See Documentation/driver-api/device-io.rst for more information.


INTERRUPTS
----------

A driver may be interrupted by its own interrupt service routine, and thus the
two parts of the driver may interfere with each other's attempts to control or
access the device.

This may be alleviated - at least in part - by disabling local interrupts (a
form of locking), such that the critical operations are all contained within
the interrupt-disabled section in the driver.  While the driver's interrupt
routine is executing, the driver's core may not run on the same CPU, and its
interrupt is not permitted to happen again until the current interrupt has been
handled, thus the interrupt handler does not need to lock against that.

However, consider a driver that was talking to an ethernet card that sports an
address register and a data register.  If that driver's core talks to the card
under interrupt-disablement and then the driver's interrupt handler is invoked:

        LOCAL IRQ DISABLE
        writew(ADDR, 3);
        writew(DATA, y);
        LOCAL IRQ ENABLE
        <interrupt>
        writew(ADDR, 4);
        q = readw(DATA);
        </interrupt>

The store to the data register might happen after the second store to the
address register if ordering rules are sufficiently relaxed:

        STORE *ADDR = 3, STORE *ADDR = 4, STORE *DATA = y, q = LOAD *DATA


If ordering rules are relaxed, it must be assumed that accesses done inside an
interrupt disabled section may leak outside of it and may interleave with
accesses performed in an interrupt - and vice versa - unless implicit or
explicit barriers are used.

Normally this won't be a problem because the I/O accesses done inside such
sections will include synchronous load operations on strictly ordered I/O
registers that form implicit I/O barriers.


A similar situation may occur between an interrupt routine and two routines
running on separate CPUs that communicate with each other.  If such a case is
likely, then interrupt-disabling locks should be used to guarantee ordering.


==========================
KERNEL I/O BARRIER EFFECTS
==========================

Interfacing with peripherals via I/O accesses is deeply architecture and device
specific. Therefore, drivers which are inherently non-portable may rely on
specific behaviours of their target systems in order to achieve synchronization
in the most lightweight manner possible. For drivers intending to be portable
between multiple architectures and bus implementations, the kernel offers a
series of accessor functions that provide various degrees of ordering
guarantees:

 (*) readX(), writeX():

        The readX() and writeX() MMIO accessors take a pointer to the
        peripheral being accessed as an __iomem * parameter. For pointers
        mapped with the default I/O attributes (e.g. those returned by
        ioremap()), the ordering guarantees are as follows:

        1. All readX() and writeX() accesses to the same peripheral are ordered
           with respect to each other. This ensures that MMIO register accesses
           by the same CPU thread to a particular device will arrive in program
           order.

        2. A writeX() issued by a CPU thread holding a spinlock is ordered
           before a writeX() to the same peripheral from another CPU thread
           issued after a later acquisition of the same spinlock. This ensures
           that MMIO register writes to a particular device issued while holding
           a spinlock will arrive in an order consistent with acquisitions of
           the lock.

        3. A writeX() by a CPU thread to the peripheral will first wait for the
           completion of all prior writes to memory either issued by, or
           propagated to, the same thread. This ensures that writes by the CPU
           to an outbound DMA buffer allocated by dma_alloc_coherent() will be
           visible to a DMA engine when the CPU writes to its MMIO control
           register to trigger the transfer.

        4. A readX() by a CPU thread from the peripheral will complete before
           any subsequent reads from memory by the same thread can begin. This
           ensures that reads by the CPU from an incoming DMA buffer allocated
           by dma_alloc_coherent() will not see stale data after reading from
           the DMA engine's MMIO status register to establish that the DMA
           transfer has completed.

        5. A readX() by a CPU thread from the peripheral will complete before
           any subsequent delay() loop can begin execution on the same thread.
           This ensures that two MMIO register writes by the CPU to a peripheral
           will arrive at least 1us apart if the first write is immediately read
           back with readX() and udelay(1) is called prior to the second
           writeX():

                writel(42, DEVICE_REGISTER_0); // Arrives at the device...
                readl(DEVICE_REGISTER_0);
                udelay(1);
                writel(42, DEVICE_REGISTER_1); // ...at least 1us before this.

        The ordering properties of __iomem pointers obtained with non-default
        attributes (e.g. those returned by ioremap_wc()) are specific to the
        underlying architecture and therefore the guarantees listed above cannot
        generally be relied upon for accesses to these types of mappings.

 (*) readX_relaxed(), writeX_relaxed():

        These are similar to readX() and writeX(), but provide weaker memory
        ordering guarantees. Specifically, they do not guarantee ordering with
        respect to locking, normal memory accesses or delay() loops (i.e.
        bullets 2-5 above) but they are still guaranteed to be ordered with
        respect to other accesses from the same CPU thread to the same
        peripheral when operating on __iomem pointers mapped with the default
        I/O attributes.

 (*) readsX(), writesX():

        The readsX() and writesX() MMIO accessors are designed for accessing
        register-based, memory-mapped FIFOs residing on peripherals that are not
        capable of performing DMA. Consequently, they provide only the ordering
        guarantees of readX_relaxed() and writeX_relaxed(), as documented above.

 (*) inX(), outX():

        The inX() and outX() accessors are intended to access legacy port-mapped
        I/O peripherals, which may require special instructions on some
        architectures (notably x86). The port number of the peripheral being
        accessed is passed as an argument.

        Since many CPU architectures ultimately access these peripherals via an
        internal virtual memory mapping, the portable ordering guarantees
        provided by inX() and outX() are the same as those provided by readX()
        and writeX() respectively when accessing a mapping with the default I/O
        attributes.

        Device drivers may expect outX() to emit a non-posted write transaction
        that waits for a completion response from the I/O peripheral before
        returning. This is not guaranteed by all architectures and is therefore
        not part of the portable ordering semantics.

 (*) insX(), outsX():

        As above, the insX() and outsX() accessors provide the same ordering
        guarantees as readsX() and writesX() respectively when accessing a
        mapping with the default I/O attributes.

 (*) ioreadX(), iowriteX():

        These will perform appropriately for the type of access they're actually
        doing, be it inX()/outX() or readX()/writeX().

With the exception of the string accessors (insX(), outsX(), readsX() and
writesX()), all of the above assume that the underlying peripheral is
little-endian and will therefore perform byte-swapping operations on big-endian
architectures.


========================================
ASSUMED MINIMUM EXECUTION ORDERING MODEL
========================================

It has to be assumed that the conceptual CPU is weakly-ordered but that it will
maintain the appearance of program causality with respect to itself.  Some CPUs
(such as i386 or x86_64) are more constrained than others (such as powerpc or
frv), and so the most relaxed case (namely DEC Alpha) must be assumed outside
of arch-specific code.

This means that it must be considered that the CPU will execute its instruction
stream in any order it feels like - or even in parallel - provided that if an
instruction in the stream depends on an earlier instruction, then that
earlier instruction must be sufficiently complete[*] before the later
instruction may proceed; in other words: provided that the appearance of
causality is maintained.

 [*] Some instructions have more than one effect - such as changing the
     condition codes, changing registers or changing memory - and different
     instructions may depend on different effects.

A CPU may also discard any instruction sequence that winds up having no
ultimate effect.  For example, if two adjacent instructions both load an
immediate value into the same register, the first may be discarded.


Similarly, it has to be assumed that compiler might reorder the instruction
stream in any way it sees fit, again provided the appearance of causality is
maintained.


============================
THE EFFECTS OF THE CPU CACHE
============================

The way cached memory operations are perceived across the system is affected to
a certain extent by the caches that lie between CPUs and memory, and by the
memory coherence system that maintains the consistency of state in the system.

As far as the way a CPU interacts with another part of the system through the
caches goes, the memory system has to include the CPU's caches, and memory
barriers for the most part act at the interface between the CPU and its cache
(memory barriers logically act on the dotted line in the following diagram):

            <--- CPU --->         :       <----------- Memory ----------->
                                  :
        +--------+    +--------+  :   +--------+    +-----------+
        |        |    |        |  :   |        |    |           |    +--------+
        |  CPU   |    | Memory |  :   | CPU    |    |           |    |        |
        |  Core  |--->| Access |----->| Cache  |<-->|           |    |        |
        |        |    | Queue  |  :   |        |    |           |--->| Memory |
        |        |    |        |  :   |        |    |           |    |        |
        +--------+    +--------+  :   +--------+    |           |    |        |
                                  :                 | Cache     |    +--------+
                                  :                 | Coherency |
                                  :                 | Mechanism |    +--------+
        +--------+    +--------+  :   +--------+    |           |    |              |
        |        |    |        |  :   |        |    |           |    |        |
        |  CPU   |    | Memory |  :   | CPU    |    |           |--->| Device |
        |  Core  |--->| Access |----->| Cache  |<-->|           |    |        |
        |        |    | Queue  |  :   |        |    |           |    |        |
        |        |    |        |  :   |        |    |           |    +--------+
        +--------+    +--------+  :   +--------+    +-----------+
                                  :
                                  :

Although any particular load or store may not actually appear outside of the
CPU that issued it since it may have been satisfied within the CPU's own cache,
it will still appear as if the full memory access had taken place as far as the
other CPUs are concerned since the cache coherency mechanisms will migrate the
cacheline over to the accessing CPU and propagate the effects upon conflict.

The CPU core may execute instructions in any order it deems fit, provided the
expected program causality appears to be maintained.  Some of the instructions
generate load and store operations which then go into the queue of memory
accesses to be performed.  The core may place these in the queue in any order
it wishes, and continue execution until it is forced to wait for an instruction
to complete.

What memory barriers are concerned with is controlling the order in which
accesses cross from the CPU side of things to the memory side of things, and
the order in which the effects are perceived to happen by the other observers
in the system.

[!] Memory barriers are _not_ needed within a given CPU, as CPUs always see
their own loads and stores as if they had happened in program order.

[!] MMIO or other device accesses may bypass the cache system.  This depends on
the properties of the memory window through which devices are accessed and/or
the use of any special device communication instructions the CPU may have.


CACHE COHERENCY VS DMA
----------------------

Not all systems maintain cache coherency with respect to devices doing DMA.  In
such cases, a device attempting DMA may obtain stale data from RAM because
dirty cache lines may be resident in the caches of various CPUs, and may not
have been written back to RAM yet.  To deal with this, the appropriate part of
the kernel must flush the overlapping bits of cache on each CPU (and maybe
invalidate them as well).

In addition, the data DMA'd to RAM by a device may be overwritten by dirty
cache lines being written back to RAM from a CPU's cache after the device has
installed its own data, or cache lines present in the CPU's cache may simply
obscure the fact that RAM has been updated, until at such time as the cacheline
is discarded from the CPU's cache and reloaded.  To deal with this, the
appropriate part of the kernel must invalidate the overlapping bits of the
cache on each CPU.

See Documentation/core-api/cachetlb.rst for more information on cache
management.


CACHE COHERENCY VS MMIO
-----------------------

Memory mapped I/O usually takes place through memory locations that are part of
a window in the CPU's memory space that has different properties assigned than
the usual RAM directed window.

Amongst these properties is usually the fact that such accesses bypass the
caching entirely and go directly to the device buses.  This means MMIO accesses
may, in effect, overtake accesses to cached memory that were emitted earlier.
A memory barrier isn't sufficient in such a case, but rather the cache must be
flushed between the cached memory write and the MMIO access if the two are in
any way dependent.


=========================
THE THINGS CPUS GET UP TO
=========================

A programmer might take it for granted that the CPU will perform memory
operations in exactly the order specified, so that if the CPU is, for example,
given the following piece of code to execute:

        a = READ_ONCE(*A);
        WRITE_ONCE(*B, b);
        c = READ_ONCE(*C);
        d = READ_ONCE(*D);
        WRITE_ONCE(*E, e);

they would then expect that the CPU will complete the memory operation for each
instruction before moving on to the next one, leading to a definite sequence of
operations as seen by external observers in the system:

        LOAD *A, STORE *B, LOAD *C, LOAD *D, STORE *E.


Reality is, of course, much messier.  With many CPUs and compilers, the above
assumption doesn't hold because:

 (*) loads are more likely to need to be completed immediately to permit
     execution progress, whereas stores can often be deferred without a
     problem;

 (*) loads may be done speculatively, and the result discarded should it prove
     to have been unnecessary;

 (*) loads may be done speculatively, leading to the result having been fetched
     at the wrong time in the expected sequence of events;

 (*) the order of the memory accesses may be rearranged to promote better use
     of the CPU buses and caches;

 (*) loads and stores may be combined to improve performance when talking to
     memory or I/O hardware that can do batched accesses of adjacent locations,
     thus cutting down on transaction setup costs (memory and PCI devices may
     both be able to do this); and

 (*) the CPU's data cache may affect the ordering, and while cache-coherency
     mechanisms may alleviate this - once the store has actually hit the cache
     - there's no guarantee that the coherency management will be propagated in
     order to other CPUs.

So what another CPU, say, might actually observe from the above piece of code
is:

        LOAD *A, ..., LOAD {*C,*D}, STORE *E, STORE *B

        (Where "LOAD {*C,*D}" is a combined load)


However, it is guaranteed that a CPU will be self-consistent: it will see its
_own_ accesses appear to be correctly ordered, without the need for a memory
barrier.  For instance with the following code:

        U = READ_ONCE(*A);
        WRITE_ONCE(*A, V);
        WRITE_ONCE(*A, W);
        X = READ_ONCE(*A);
        WRITE_ONCE(*A, Y);
        Z = READ_ONCE(*A);

and assuming no intervention by an external influence, it can be assumed that
the final result will appear to be:

        U == the original value of *A
        X == W
        Z == Y
        *A == Y

The code above may cause the CPU to generate the full sequence of memory
accesses:

        U=LOAD *A, STORE *A=V, STORE *A=W, X=LOAD *A, STORE *A=Y, Z=LOAD *A

in that order, but, without intervention, the sequence may have almost any
combination of elements combined or discarded, provided the program's view
of the world remains consistent.  Note that READ_ONCE() and WRITE_ONCE()
are -not- optional in the above example, as there are architectures
where a given CPU might reorder successive loads to the same location.
On such architectures, READ_ONCE() and WRITE_ONCE() do whatever is
necessary to prevent this, for example, on Itanium the volatile casts
used by READ_ONCE() and WRITE_ONCE() cause GCC to emit the special ld.acq
and st.rel instructions (respectively) that prevent such reordering.

The compiler may also combine, discard or defer elements of the sequence before
the CPU even sees them.

For instance:

        *A = V;
        *A = W;

may be reduced to:

        *A = W;

since, without either a write barrier or an WRITE_ONCE(), it can be
assumed that the effect of the storage of V to *A is lost.  Similarly:

        *A = Y;
        Z = *A;

may, without a memory barrier or an READ_ONCE() and WRITE_ONCE(), be
reduced to:

        *A = Y;
        Z = Y;

and the LOAD operation never appear outside of the CPU.


AND THEN THERE'S THE ALPHA
--------------------------

The DEC Alpha CPU is one of the most relaxed CPUs there is.  Not only that,
some versions of the Alpha CPU have a split data cache, permitting them to have
two semantically-related cache lines updated at separate times.  This is where
the address-dependency barrier really becomes necessary as this synchronises
both caches with the memory coherence system, thus making it seem like pointer
changes vs new data occur in the right order.

The Alpha defines the Linux kernel's memory model, although as of v4.15
the Linux kernel's addition of smp_mb() to READ_ONCE() on Alpha greatly
reduced its impact on the memory model.


VIRTUAL MACHINE GUESTS
----------------------

Guests running within virtual machines might be affected by SMP effects even if
the guest itself is compiled without SMP support.  This is an artifact of
interfacing with an SMP host while running an UP kernel.  Using mandatory
barriers for this use-case would be possible but is often suboptimal.

To handle this case optimally, low-level virt_mb() etc macros are available.
These have the same effect as smp_mb() etc when SMP is enabled, but generate
identical code for SMP and non-SMP systems.  For example, virtual machine guests
should use virt_mb() rather than smp_mb() when synchronizing against a
(possibly SMP) host.

These are equivalent to smp_mb() etc counterparts in all other respects,
in particular, they do not control MMIO effects: to control
MMIO effects, use mandatory barriers.


============
EXAMPLE USES
============

CIRCULAR BUFFERS
----------------

Memory barriers can be used to implement circular buffering without the need
of a lock to serialise the producer with the consumer.  See:

        Documentation/core-api/circular-buffers.rst

for details.


==========
REFERENCES
==========

Alpha AXP Architecture Reference Manual, Second Edition (Sites & Witek,
Digital Press)
        Chapter 5.2: Physical Address Space Characteristics
        Chapter 5.4: Caches and Write Buffers
        Chapter 5.5: Data Sharing
        Chapter 5.6: Read/Write Ordering

AMD64 Architecture Programmer's Manual Volume 2: System Programming
        Chapter 7.1: Memory-Access Ordering
        Chapter 7.4: Buffering and Combining Memory Writes

ARM Architecture Reference Manual (ARMv8, for ARMv8-A architecture profile)
        Chapter B2: The AArch64 Application Level Memory Model

IA-32 Intel Architecture Software Developer's Manual, Volume 3:
System Programming Guide
        Chapter 7.1: Locked Atomic Operations
        Chapter 7.2: Memory Ordering
        Chapter 7.4: Serializing Instructions

The SPARC Architecture Manual, Version 9
        Chapter 8: Memory Models
        Appendix D: Formal Specification of the Memory Models
        Appendix J: Programming with the Memory Models

Storage in the PowerPC (Stone and Fitzgerald)

UltraSPARC Programmer Reference Manual
        Chapter 5: Memory Accesses and Cacheability
        Chapter 15: Sparc-V9 Memory Models

UltraSPARC III Cu User's Manual
        Chapter 9: Memory Models

UltraSPARC IIIi Processor User's Manual
        Chapter 8: Memory Models

UltraSPARC Architecture 2005
        Chapter 9: Memory
        Appendix D: Formal Specifications of the Memory Models

UltraSPARC T1 Supplement to the UltraSPARC Architecture 2005
        Chapter 8: Memory Models
        Appendix F: Caches and Cache Coherency

Solaris Internals, Core Kernel Architecture, p63-68:
        Chapter 3.3: Hardware Considerations for Locks and
                        Synchronization

Unix Systems for Modern Architectures, Symmetric Multiprocessing and Caching
for Kernel Programmers:
        Chapter 13: Other Memory Models

Intel Itanium Architecture Software Developer's Manual: Volume 1:
        Section 2.6: Speculation
        Section 4.4: Memory Access