본문으로 건너뛰기
Modern Embedded Recipes · 22/152

ARM Memory Barrier 실전 — DMB·DSB·ISB·DMA·MMIO

· Hawk · 5분 읽기
recipes memory-barrier dmb dsb isb dma

#한 줄 요약

**“DMB는 memory ordering, DSB는 이전 명령·memory access의 완료 대기, ISB는 instruction stream 동기화”**입니다. 정확한 선택은 access 종류와 architecture 상태 변경 여부에 따라 달라집니다.

#3 가지 Barrier

Barrier의미Cycle 비용
DMB이전·이후 memory access의 관찰 순서를 제어구현·memory system에 따라 상이
DSB이전 명령과 명시적 memory access가 완료될 때까지 동기화구현·memory system에 따라 상이
ISBinstruction stream을 동기화하고 이후 명령을 다시 fetch구현·pipeline에 따라 상이

#DMB — Data Memory Ordering

shared_data = compute();
__DMB();
flag = 1; /* shared_data write가 flag write *전*에 가시 */

적절한 atomic release/acquire 연산과 결합하면 memory ordering을 구성할 수 있지만, DMB 하나가 C/C++ atomic 연산을 대체하지는 않습니다.

#언제 DMB 필요?

  • Lock-free queue producer/consumer
  • ISR↔task shared variable
  • SMP cross-core data sharing
  • Atomic 명령 사이

#예 — ISR↔Task

volatile uint32_t data;
volatile bool ready;
/* ISR */
data = sample;
__DMB(); /* data write가 ready 변경 전 가시 보장 */
ready = true;
/* Task */
while (!ready);
__DMB(); /* ready read 후 data read */
process(data);

#DSB — Sync (강한 fence)

/* Clock 활성화 후 register access */
RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;
__DSB(); /* clock enable 완료 대기 */
TIM2->CR1 = 1; /* safe */

DSB는 이전 명령의 효과와 명시된 memory access가 필요한 시점까지 완료되도록 동기화합니다. 단순히 DMB보다 “더 강한 데이터 fence”라고만 이해하지 말고 Arm의 access·completion 정의를 확인해야 합니다.

#언제 DSB?

  • Clock·power configuration 후
  • MPU·MMU 설정 변경 후
  • DMA setup 전 (buffer flush 보장)
  • WFI·WFE 전 (state save 완료)

#예 — DMA Start

fill_buffer(tx_buf, len);
SCB_CleanDCache_by_Addr(tx_buf, len); /* cacheable buffer라면 먼저 clean */
__DSB(); /* memory access 완료 순서 동기화 */
DMA->CR = DMA_START; /* DMA가 fresh data 봄 */

#ISB — Pipeline Flush

/* Self-modifying code */
flash_write(addr, new_code);
SCB_CleanDCache_by_Addr(addr, size);
SCB_InvalidateICache_by_Addr(addr, size);
__DSB(); __ISB(); /* pipeline 안 *옛 명령* 클리어 */
call((void*)addr);

ISB는 fetched instructions 폐기 + refetch를 수행합니다. CPU state·MPU·VFP 활성화 후 필수입니다.

#언제 ISB?

  • Self-modifying code (FW update, JIT)
  • CONTROL register 변경 (privileged mode 전환)
  • MPU 활성화·변경 후
  • FPU 활성화 후 (CPACR write)

#예 — FPU 활성화

SCB->CPACR |= (0xF << 20); /* FPU enable */
__DSB(); __ISB(); /* settle + pipeline flush */
float x = compute_fp(); /* safe */

#DMB Variant (ARMv8)

__DMB(); /* full system — slowest */
__DMB_ISH(); /* Inner Shareable — SMP cluster 안 */
__DMB_NSH(); /* Non-shareable — same CPU */
__DMB_OSH(); /* Outer Shareable — across clusters */

좁은 scope일수록 더 빠릅니다. SMP cluster 내 sync는 ISH로 충분합니다.

/* Linux smp_mb() = DMB ISH */
smp_mb();

#Cortex-M Single Core — Barrier 적은 사용

Cortex-M3/M4:

  • Pipeline in-order
  • No store buffer reorder for same address
  • Single core — no SMP sync

DMB 필요 케이스:

  • MMIO·DMA 와의 ordering
  • Atomic 명령 (LDREX/STREX) 후
  • Self-modifying code (DSB + ISB)

Single core에서도 ISR·DMA·MMIO ordering이 있으면 barrier가 필요할 수 있습니다. volatile만으로 lock-free 동기화의 원자성·ordering이 보장되는 것은 아닙니다.

#Cortex-A SMP — Barrier 필수

/* SMP — DMB ISH 또는 LDAR/STLR */
/* C11 atomic — 자동 처리 */
atomic_store_explicit(&head, next, memory_order_release);
/* → STLR */

ARMv8은 acquire/release 단일 명령(LDAR/STLR)을 제공합니다. 그래서 DMB 수동 사용이 줄어듭니다.

#Lock-Free Queue with Barriers

/* C 명시 barrier 버전 */
bool push(ring_t *r, uint8_t b) {
uint16_t h = r->head;
uint16_t next = (h + 1) & MASK;
if (next == r->tail) return false;
r->buf[h] = b;
__DMB(); /* buf write 후 head update — release */
r->head = next;
return true;
}
bool pop(ring_t *r, uint8_t *out) {
uint16_t t = r->tail;
if (t == r->head) return false;
__DMB(); /* head check 후 buf read — acquire */
*out = r->buf[t];
r->tail = (t + 1) & MASK;
return true;
}

atomic_store/load 사용을 권장합니다. 컴파일러가 효율적 명령을 선택해 줍니다.

#DMA + Cache Maintenance

/* TX path */
fill_data(buf, len);
SCB_CleanDCache_by_Addr(buf, len); /* cache → memory */
__DSB();
DMA_start(buf, len);
/* RX path */
DMA_start(buf, len);
/* DMA writes memory */
wait_dma_done();
SCB_InvalidateDCache_by_Addr(buf, len); /* cache stale data 폐기 */
__DSB();
read_data(buf);

Cortex-M7 D-cache + DMA는 coherent하지 않습니다. 명시적 maintenance가 필요합니다.

#Self-Modifying Code — FW Update

void flash_write_and_jump(uint32_t addr, uint8_t *code, size_t len) {
/* 1. Write to flash */
flash_unlock();
flash_erase(addr);
for (size_t i = 0; i < len; i += 4) {
flash_program_word(addr + i, *(uint32_t*)(code + i));
}
flash_lock();
/* 2. Cache maintenance */
SCB_CleanInvalidateDCache_by_Addr((uint32_t*)addr, len);
SCB_InvalidateICache_by_Addr((uint32_t*)addr, len);
/* 3. Barriers */
__DSB();
__ISB();
/* 4. Jump */
((void(*)())(addr | 1))();
}

전체 흐름은 5 단계입니다. write + D-cache flush + I-cache invalidate + DSB + ISB + jump.

#STM32 Bootloader — Vector Table 변경

SCB->VTOR = NEW_VECTOR_BASE;
__DSB(); /* settle */
__ISB(); /* pipeline flush */
/* 이제 IRQ가 새 vector 사용 */

VTOR 변경 후 DSB+ISB가 없으면 다음 IRQ가 옛 vector를 사용해 crash가 발생합니다.

#Multi-Core Wakeup

/* Core 0 — boot core 1 */
core1_entry_addr = (uint32_t)core1_main;
__DSB(); /* entry addr write 완료 */
core1_wake(); /* core 1 reset release */
/* Core 1 — reset handler */
void core1_reset(void) {
while (core1_entry_addr == 0); /* wait */
__DMB(); /* read complete */
((void(*)())core1_entry_addr)();
}

Cortex-A multi-core boot의 표준 패턴입니다.

#자주 하는 실수

⚠️ DSB·ISB가 필요한 곳에 DMB만 사용합니다

SCB->VTOR = new_addr;
__DMB(); /* ← 부족 — DSB·ISB 필요 */

→ system register에는 DSB+ISB를 사용합니다.

⚠️ Barrier 위치를 잘못 잡습니다

flag = 1;
__DMB(); /* ← 너무 늦음 — flag가 이미 가시화 */
data = compute();

→ data write 후, flag write 전에 DMB를 배치합니다.

⚠️ 모든 atomic에 manual barrier를 답니다

atomic_store(&x, 1);
__DMB(); /* ← atomic 자체가 acquire/release — 중복 */

→ C11 atomic만 신뢰합니다.

⚠️ Cortex-M에서 DMB ISH를 씁니다

__DMB_ISH(); /* ← Cortex-M에는 share domain 개념 없음 */

→ Cortex-M에서는 단일 __DMB()만 씁니다. Variant는 Cortex-A 전용입니다.

#정리

  • DMB는 data ordering, DSB는 거기에 sync를 더한 것, ISB는 pipeline flush입니다.
  • Cortex-M single core에서는 MMIO·DMA·atomic에만 씁니다.
  • SMP Cortex-A에서는 acquire/release pair가 필수입니다.
  • DMA TX에서는 clean + DSB, RX에서는 invalidate + DSB를 씁니다.
  • Self-modifying에는 D/I cache maintenance + DSB + ISB를 모두 적용합니다.
  • C11 atomic_* + memory_order_*를 쓰면 컴파일러가 최적 barrier를 선택해 줍니다.

다음 편은 Wait-Free입니다.

#관련 항목

Modern Embedded Recipes · 23 of 152

  1. 1 Modern Embedded Recipes — 모던 임베디드 실전 레시피 시리즈 소개
  2. 2 디지털 신호 기초 — Voltage Level·Edge·Setup/Hold 분석
  3. 3 임베디드 클럭과 타이밍 — Skew·Jitter·PLL·MMCM 분석
  4. 4 GPIO 내부 구조 분해 — Push-Pull·Open-Drain·Schmitt Trigger
  5. 5 UART 하드웨어 동작 분석 — Baud Rate·Framing·FIFO
  6. 6 SPI 하드웨어 분석 — Clock Mode·MOSI/MISO·Chip Select
  7. 7 I2C 하드웨어 분석 — Open-Drain·Clock Stretching·Arbitration
  8. 8 ADC 동작 원리 — SAR·Sigma-Delta·Pipelined 비교
  9. 9 DAC 동작 원리 — R-2R Ladder·Sigma-Delta·Settling Time
  10. 10 PWM 신호 생성 분석 — Duty·Frequency·Dead Time·Center-Aligned
  11. 11 CAN 버스 전기적 특성 — Differential·Termination·Dominant/Recessive
  12. 12 RS-485·RS-422 차동 신호 분석 — Termination·Biasing·Topology
  13. 13 LVDS 차동 신호 분석 — Common-Mode·Impedance·Eye Pattern
  14. 14 ARM Cortex-M 시리즈 비교 — M0·M3·M4·M7·M33·M55 분석
  15. 15 ARM Cortex-A 시리즈 비교 — A53·A55·A72·A78·X1 분석
  16. 16 ARM 레지스터 구조 분석 — R0~R15·CPSR·SPSR·Banked Registers
  17. 17 Cortex-M 예외 처리 — Vector Table·NVIC·Tail-Chaining 추적
  18. 18 ARM 메모리 맵 분석 — Normal·Device·Strongly-Ordered Region
  19. 19 ARM L1·L2 캐시 분석 — Set Associative·Inclusive·Maintenance
  20. 20 ARM MPU 활용 — Region·Attribute·Privilege Separation
  21. 21 ARM MMU 기초 분석 — Translation Table·TLB·ASID
  22. 22 ARM TrustZone-M 기초 — Secure/Non-Secure·NSC·MPC
  23. 23 ARM Memory Barrier 실전 — DMB·DSB·ISB·DMA·MMIO
  24. 24 임베디드 크로스 컴파일러 분석 — GCC·Clang·Sysroot 구성
  25. 25 C 컴파일 4단계 — Preprocess·Compile·Assemble·Link 추적
  26. 26 ELF 파일 구조 분석 — Section·Segment·Symbol Table·DWARF
  27. 27 링커 스크립트 기초 — SECTIONS·MEMORY·entry point
  28. 28 링커 스크립트 고급 — Overlay·BSS·init_array·LMA/VMA
  29. 29 임베디드 스타트업 코드 분석 — Reset_Handler·Vector Table·SystemInit
  30. 30 C 런타임 crt0 분석 — Stack·BSS Zero·Data Copy·atexit
  31. 31 임베디드 메모리 레이아웃 — .text·.rodata·.data·.bss·.heap·.stack
  32. 32 임베디드 컴파일러 최적화 분석 — -O0~-O3·-Os·-LTO 비교
  33. 33 Map 파일 분석 — Symbol·Section·Size 추적으로 코드 크기 진단
  34. 34 Make·CMake 크로스 컴파일 — Toolchain File·Sysroot 통합
  35. 35 임베디드 Bootloader 체인 — BootROM·SPL·U-Boot·Kernel·Secure Boot
  36. 36 첫 bare-metal 프로그램 작성 — Linker·Startup·main의 최소 구성
  37. 37 MMIO 레지스터 직접 접근 — volatile·Memory Map·Aliasing 분석
  38. 38 GPIO 드라이버 직접 구현 — STM32 HAL 없이 레지스터로
  39. 39 임베디드 클럭 설정 분석 — HSE·PLL·SYSCLK·AHB/APB 분주
  40. 40 Cortex-M 인터럽트 핸들링 — NVIC·Priority·Vector·EXTI
  41. 41 SysTick 타이머 활용 — 24-bit Counter·1ms Tick·delay 구현
  42. 42 UART 드라이버 구현 — polling·interrupt·DMA 3가지 방식 비교
  43. 43 SPI 드라이버 구현 — Master·Slave·CRC·DMA
  44. 44 I2C 드라이버 구현 — Master·7-bit/10-bit·Clock Stretching 처리
  45. 45 임베디드 DMA 기초 — Memory-to-Memory·Peripheral·Circular Mode
  46. 46 저전력 모드 분석 — Sleep·Stop·Standby·Wake-up Source
  47. 47 IWDG·WWDG 워치독 구현 — Independent vs Window 비교
  48. 48 임베디드 Flash 프로그래밍 — Erase·Program·Read While Write
  49. 49 DDR 초기화 실패 진단 — Timing·Calibration·Walking Bit Test
  50. 50 PWM 출력 실전 — LED 밝기·모터 속도 제어
  51. 51 DC 모터 제어 — H-Bridge·PWM Duty·Encoder Feedback
  52. 52 스테퍼 모터 제어 — Full Step·Half Step·Microstepping
  53. 53 서보 모터 제어 — PWM 1ms~2ms·Closed Loop·PID
  54. 54 Character LCD 제어 — HD44780·4-bit Mode·Custom Char
  55. 55 SPI OLED 제어 — SSD1306·Frame Buffer·Page 단위 갱신
  56. 56 TFT 디스플레이 구동 — RGB565·FSMC·LTDC·DMA2D
  57. 57 환경 센서 활용 — BME280 온습압·SHT3x 비교
  58. 58 IMU 센서 활용 — MPU6050·BMI270·Sensor Fusion
  59. 59 CAN 통신 구현 — bxCAN·Filter·Mailbox·CAN-FD
  60. 60 USB Device 기초 — Descriptor·Enumeration·Endpoint·HID/CDC
  61. 61 Ethernet MAC+PHY 통합 — RMII·lwIP·DMA Descriptor
  62. 62 SD Card + FatFs 구현 — SPI/SDIO 모드·CSD/CID·Wear
  63. 63 RTC 활용 — Calendar·Alarm·Wake-up Timer·Backup Domain
  64. 64 RTOS 도입 결정 분석 — Super Loop vs RTOS 트레이드오프
  65. 65 RTOS Task 설계 패턴 — 우선순위·스택·State Machine
  66. 66 RTOS Scheduler 동작 분석 — Tick·Context Switch·Yield
  67. 67 RTOS Semaphore 활용 — Binary·Counting·ISR Give
  68. 68 RTOS Mutex 활용 — Recursive·Priority Inheritance 적용
  69. 69 RTOS Queue 활용 — By-Value·By-Reference·Timeout 패턴
  70. 70 RTOS Event Group 활용 — Bit Wait·Sync·Notify
  71. 71 RTOS Software Timer 활용 — One-shot·Auto-reload·Daemon Task
  72. 72 ISR-Safe API 설계 — Reentrant·Atomic·Defer 패턴
  73. 73 Priority Inversion 진단·예방 — Mars Pathfinder Lesson 추적
  74. 74 Timer Wheel 분석 — Hashed·Hierarchical·O(1) Tick
  75. 75 RTOS 디버깅 기법 — Tracealyzer·SystemView·Stack 추적
  76. 76 임베디드 Linux 부팅 흐름 분석 — BootROM·U-Boot·Kernel·init
  77. 77 U-Boot 활용 — bootcmd·env·tftp·boot.scr 분석
  78. 78 Device Tree 실전 — DTS·DTB·Overlay·Phandle 추적
  79. 79 Device Tree Overlay 적용 — Runtime fragment·dtoverlay
  80. 80 임베디드 커널 빌드 — defconfig·menuconfig·Image·zImage
  81. 81 커널 모듈 기초 — init/exit·Parameter·KBuild·DKMS
  82. 82 캐릭터 드라이버 작성 — file_operations·cdev·register_chrdev
  83. 83 Platform 드라이버 작성 — probe·remove·of_match·DT 바인딩
  84. 84 mmap 4가지 모드 — Anonymous·File·Shared·Huge Page
  85. 85 epoll 실전 — LT·ET·ONESHOT·EXCLUSIVE 비교
  86. 86 UIO·VFIO 분석 — User-Space Driver와 IOMMU 격리
  87. 87 sysfs·configfs 활용 — kobject 기반 User 인터페이스
  88. 88 IRQ Affinity 튜닝 — smp_affinity·isolcpus·irqbalance
  89. 89 루트 파일시스템 구축 — Buildroot 기초·Package·Toolchain
  90. 90 임베디드 동적 메모리 — malloc 위험·결정성·대안 분석
  91. 91 메모리 정렬과 패딩 분석 — Natural·Strict Alignment·Trap
  92. 92 Cache Line Alignment — alignas·Padding·SoA 적용
  93. 93 DMA-Friendly Allocator — dma_alloc_coherent·IOMMU·Pool
  94. 94 Zero-Copy Pipeline — DMA-BUF·sendfile·io_uring·splice
  95. 95 NUMA Memory Topology — numactl·numa_alloc·HBM 적용
  96. 96 SIMD 활용 분석 — Intrinsics·Auto-Vectorization·OpenMP SIMD
  97. 97 ARM NEON 심화 — Matrix Multiply·FFT·Image Filter 적용
  98. 98 임베디드 스택 분석 — high-water·overflow 탐지
  99. 99 임베디드 코드 크기 최적화 — -Os·LTO·Section Garbage Collection
  100. 100 임베디드 전력 최적화 — Sleep Mode·Clock Gating·DVFS
  101. 101 WCET 분석 기법 — Static·Measurement·Hybrid 방법론
  102. 102 Lock-Free Ring Buffer 구현 — SPSC·Power-of-2·Memory Order
  103. 103 Wait-Free Signaling — Atomic Flag·Sequence·Latest-Value
  104. 104 RCU (Read-Copy-Update) 기초 — Quiescent State·Grace Period
  105. 105 Hazard Pointer 분석 — Lock-Free Memory Reclamation
  106. 106 Compare-And-Swap 패턴 — Stack·Counter·Linked List 적용
  107. 107 Atomic Operation 비용 분석 — Fence·Cache Line·Contention
  108. 108 Spinlock vs Mutex 결정 가이드 — Context Switch·Hold Time
  109. 109 ABA 문제 회피 — Tagged Pointer·Hazard·Generation Counter
  110. 110 False Sharing 해결 — Cache Line Padding·SoA 적용
  111. 111 MPMC Queue 구현 — Multi-producer Multi-consumer Lock-Free
  112. 112 임베디드 디버깅 마인드셋 — 가설·격리·재현·이분탐색
  113. 113 JTAG·SWD 안 붙을 때 — 핀·전압·속도·세션 진단
  114. 114 GDB 원격 디버깅 — OpenOCD·J-Link·target remote 구성
  115. 115 Cortex-M 하드폴트 분석 — Stacked Frame·CFSR 읽기
  116. 116 UART 안 찍힐 때 — Bare-metal 체크리스트
  117. 117 임베디드 부팅 실패 진단 — 단계별 Isolation
  118. 118 인터럽트 누락·중복 진단 — Priority·Pending·Re-entry 추적
  119. 119 메모리 오버플로우·오염 진단 — Canary·MPU·Pattern 분석
  120. 120 타이밍·Race 진단 — Heisenbug 잡는 법
  121. 121 통신 프로토콜 분석 — Logic Analyzer와 Protocol Decoder
  122. 122 임베디드 로깅 시스템 설계 — 레벨·버퍼·SWO·Deferred
  123. 123 임베디드 포스트모템 분석 — Core Dump와 Field Crash
  124. 124 FPGA 기초 분석 — LUT·FF·BRAM·DSP 자원 구조
  125. 125 Vivado 사용법 — Project·Constraint·Synth·Impl·Bitstream
  126. 126 PCIe BAR 매핑 분석 — Config Space·Enumeration·MMIO 접근
  127. 127 AXI 인터페이스 — AXI4·AXI4-Lite·AXI-Stream 비교
  128. 128 Zynq PS-PL 통신 — GP·HP·ACP 인터페이스 선택
  129. 129 Mailbox Protocol 분석 — Host와 Accelerator를 잇는 Doorbell
  130. 130 Command Queue·Submission Queue — NVMe·XDMA 공통 패턴
  131. 131 DMA Completion 메커니즘 — Interrupt·Polling·Completion Ring
  132. 132 PCIe Streaming 분석 — BAR Type·MSI-X·Kernel Bypass
  133. 133 Vitis HLS 분석 — Pragma·Pipeline II·Dataflow 실전 감각
  134. 134 HLS 최적화 기법 — Pipeline·Unroll·Partition·Dataflow
  135. 135 Vitis AI 분석 — DPU·xmodel·VART
  136. 136 OpenCL on FPGA — Kernel·Channel·Burst Memory 분석
  137. 137 Intel Quartus 사용법 — Platform Designer·Nios II·HLS
  138. 138 Edge Inference 분석 — Cloud vs Edge·Latency·Privacy
  139. 139 NPU 아키텍처 분석 — Ethos·Hexagon·Systolic Array 비교
  140. 140 딥러닝 Quantization 분석 — PTQ·QAT·INT8·INT4·Calibration
  141. 141 TensorRT 분석 — ONNX→Engine·FP16·INT8·DLA·Multi-Stream
  142. 142 TFLite Micro 분석 — Op Resolver·Tensor Arena·Cortex-M
  143. 143 ONNX Runtime 분석 — Execution Provider와 Cross-Platform 배포
  144. 144 Edge Thermal Management — Throttling·DVFS·Fan Curve·Sustained
  145. 145 NVIDIA Jetson 분석 — Nano·Xavier·Orin·Thor·JetPack·DLA·VPI
  146. 146 Zero-Copy Camera Pipeline — V4L2·DMA-BUF·GPU Import·NPU 직결
  147. 147 온디바이스 LLM 추론 — llama.cpp·GGUF·MLX·KV Cache·NPU Backend
  148. 148 Cortex-M33 TF-M·TrustZone — Secure Firmware·PSA·MCUboot
  149. 149 Matter·Thread 분석 — IoT 통합 표준·Commissioning·Multi-Fabric
  150. 150 PCIe → CXL 진화 — 같은 PHY 위 cache-coherent 프로토콜 추가
  151. 151 QEMU CXL Type 3 디바이스 에뮬레이션 — 노트북에서 CXL 개발 환경 구축
  152. 152 Linux CXL 드라이버 분석 — cxl_pci·cxl_core·region·DAX