forked from torvalds/linux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory-barriers.txt
2952 lines (2229 loc) · 135 KB
/
memory-barriers.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
NOTE:
This is a version of Documentation/memory-barriers.txt translated into Korean.
This document is maintained by SeongJae Park <sj@kernel.org>.
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
의 한글 번역입니다.
역자: 박성재 <sj@kernel.org>
=================================
=========================
리눅스 커널 메모리 배리어
=========================
저자: David Howells <dhowells@redhat.com>
Paul E. McKenney <paulmck@linux.ibm.com>
Will Deacon <will.deacon@arm.com>
Peter Zijlstra <peterz@infradead.org>
========
면책조항
========
이 문서는 명세서가 아닙니다; 이 문서는 완벽하지 않은데, 간결성을 위해 의도된
부분도 있고, 의도하진 않았지만 사람에 의해 쓰였다보니 불완전한 부분도 있습니다.
이 문서는 리눅스에서 제공하는 다양한 메모리 배리어들을 사용하기 위한
안내서입니다만, 뭔가 이상하다 싶으면 (그런게 많을 겁니다) 질문을 부탁드립니다.
일부 이상한 점들은 공식적인 메모리 일관성 모델과 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);
메모리 배리어 시퀀스의 예
-------------------------
첫째, 쓰기 배리어는 스토어 오퍼레이션들의 부분적 순서 세우기로 동작합니다.