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

IRQ Affinity 튜닝 — smp_affinity·isolcpus·irqbalance

· Hawk · 5분 읽기

#한 줄 요약

“IRQ Affinity = 인터럽트를 어느 코어에 보낼지 선택하는 것.” RT core 격리, NIC RX 분배, cache locality 모두 같은 도구로 해결합니다.

#어떤 상황에서 쓰나

산업·자동차 ECU에서 한 코어를 RT 제어 루프에 통째로 내어 주는 일이 흔합니다. 그 코어로 일반 IRQ가 한 번 들어오면 cyclictest의 max latency가 수십 µs 단위로 튀어 오릅니다. RT core에 인터럽트가 닿지 않도록 모든 IRQ를 다른 코어로 밀어야 합니다.

10 GbE 이상의 NIC에서는 반대로 분산이 목표입니다. RX queue를 여러 개 만들고 각 queue의 IRQ를 다른 코어에 매핑해야 single core가 병목이 되지 않습니다. 두 시나리오 모두 /proc/irq/N/smp_affinity 한 줄에서 시작합니다.

#핵심 개념

경로내용
/proc/interruptsIRQ별 코어별 카운트
/proc/irq/N/smp_affinitybitmask (예: 0x2 = CPU1)
/proc/irq/N/smp_affinity_list사람이 읽기 쉬운 형식 (예: 1-3)
/proc/irq/N/affinity_hintdriver가 제안하는 mask

smp_affinitykernel hint입니다. irqbalance daemon이 켜져 있으면 자동으로 덮어쓸 수 있습니다. 수동 pinning이 필요하면 irqbalance를 끄거나 ban 목록을 지정합니다.

isolcpus는 한 단계 더 강한 도구입니다. 부팅 시 cmdline으로 코어를 격리하면 일반 scheduler가 그 코어에 task를 배치하지 않고, IRQ도 명시 affinity가 없는 한 들어가지 않습니다. PREEMPT_RT에서는 IRQ가 threaded로 변환되어 일반 task처럼 priority와 affinity를 따로 조정할 수 있습니다.

#코드 / 실제 사용 예

#현재 상태 확인

Terminal window
$ cat /proc/interrupts
CPU0 CPU1 CPU2 CPU3
16: 12 345 678 901 GICv3 timer
23: 123456 0 0 0 GICv3 eth0
24: 4321 8765 0 0 GICv3 spi0
56: 0 0 234567 0 GICv3 custom
$ cat /proc/irq/23/smp_affinity
00000000,00000000,00000000,00000001
$ cat /proc/irq/23/smp_affinity_list
0

eth0가 CPU0 한 곳으로 몰리고 있습니다. 분산을 위해 mask를 바꿔 줍니다.

#수동 affinity 설정

Terminal window
# CPU 1만
echo 2 > /proc/irq/23/smp_affinity
# CPU 2,3
echo c > /proc/irq/23/smp_affinity
# list 형식이 더 안전
echo 2-3 > /proc/irq/23/smp_affinity_list

변경 후 다시 /proc/interrupts로 카운트가 늘어나는 코어가 바뀌었는지 확인합니다. 변경이 반영되지 않는다면 driver가 IRQ_NO_BALANCING 플래그를 걸어 두었거나, 일부 platform IRQ controller가 특정 코어로의 routing만 허용하는 경우입니다.

#irqbalance 다루기

Terminal window
# 자동 분산 daemon
systemctl status irqbalance
# RT 시스템에서는 보통 끈다
sudo systemctl stop irqbalance
sudo systemctl disable irqbalance
# 또는 특정 IRQ만 ban
echo "IRQBALANCE_BANNED_CPUS=0xc" >> /etc/default/irqbalance
echo "IRQBALANCE_ARGS=\"--banirq=23 --banirq=24\"" >> /etc/default/irqbalance

irqbalance는 일반 server에서는 합리적인 기본값을 만들어 주지만, manual affinity와는 충돌합니다. 둘 중 하나를 선택해야 합니다.

#isolcpus로 RT core 분리

# /boot/cmdline 또는 GRUB
isolcpus=2,3 nohz_full=2,3 rcu_nocbs=2,3 irqaffinity=0-1

irqaffinity=0-1이 핵심입니다. 명시 affinity가 없는 모든 IRQ의 기본 mask가 01로 묶이니, isolated CPU 23에 잘못된 IRQ가 들어가지 않습니다.

Terminal window
# 부팅 후 확인
for f in /proc/irq/*/smp_affinity_list; do
printf "%s: %s\n" "$f" "$(cat $f)"
done | head

#NIC RSS와 결합

Terminal window
# RX queue 8개 활성화
sudo ethtool -L eth0 combined 8
# 각 queue IRQ를 코어 0~7에 분배
i=0
for irq in $(grep eth0- /proc/interrupts | awk -F: '{print $1}'); do
echo $((1 << i)) > /proc/irq/$irq/smp_affinity
i=$((i + 1))
done

RSS hash가 packet을 queue별로 나누고, 각 queue가 자기 코어에서 처리됩니다. cache locality가 살아 latency도 함께 좋아집니다.

#PREEMPT_RT — threaded IRQ

Terminal window
$ ps -eo pid,pri,comm | grep irq
4321 50 irq/23-eth0
4322 49 irq/24-spi
# priority 조정
sudo chrt -f -p 80 4321
# 코어 고정
sudo taskset -pc 1 4321

PREEMPT_RT 커널은 거의 모든 IRQ를 thread로 변환합니다. RT task의 priority와 명확히 정렬해야 우선순위 역전을 피할 수 있습니다.

#Driver 측 affinity hint

const struct cpumask *m = cpumask_of(2);
irq_set_affinity_hint(irq, m);

NIC PMD나 multi-queue device는 자기가 어디서 처리되면 좋겠는지를 hint로 제공합니다. irqbalance가 이 hint를 참고합니다.

#측정 / 성능 비교

Cortex-A72 quad-core 보드에서 RT 루프(SCHED_FIFO 80, busy work)와 eth0 트래픽을 동시에 돌렸을 때입니다.

설정cyclictest p99
기본 (irqbalance, IRQ가 RT 코어에도 진입)180 µs
isolcpus=2,3 + irqaffinity=0-112 µs
isolcpus=2,3 + irqaffinity=0-1 + RT thread8 µs

x86 서버에서 NIC RSS를 활용했을 때입니다.

설정throughputCPU
single queue, CPU0 IRQ4.1 GbpsCPU0 100%
RSS 8 queue, 8 코어에 분배9.6 GbpsCPU 평균 22%

RT 시나리오에서는 단순히 IRQ를 옮기는 것만으로 p99가 10배 이상 좋아질 수 있고, throughput 시나리오에서는 분산만으로 line rate가 가까워집니다.

#자주 보는 함정

irqbalance가 manual 설정을 덮어씀

Terminal window
echo 2 > /proc/irq/23/smp_affinity
# 몇 초 뒤
cat /proc/irq/23/smp_affinity
# 1 ← irqbalance가 되돌림

irqbalance를 끄거나 ban 목록을 명시해야 manual 설정이 유지됩니다.

isolcpus만 두고 IRQ는 그대로

isolcpus=2,3 # IRQ는 여전히 어디든 갈 수 있음

irqaffinity=를 함께 지정하지 않으면 격리한 코어에 일반 IRQ가 그대로 들어옵니다. cmdline 한 줄을 빼먹지 않도록 주의합니다.

Hyperthread sibling 무시

# CPU 0,1이 같은 코어의 sibling이라면
# IRQ를 0번에, RT task를 1번에 두면 사실상 같은 자원 경합

/sys/devices/system/cpu/cpu0/topology/thread_siblings_list로 sibling 관계를 확인하고, 가능하면 RT task와 IRQ는 완전히 다른 물리 코어에 둡니다.

All-CPU mask = 사실상 affinity 없음

Terminal window
echo f > /proc/irq/23/smp_affinity # 0xf = CPU 0~3 전부

bitmask가 모든 코어를 포함하면 의미 있는 pinning이 아닙니다. 명확한 단일 코어 또는 좁은 mask를 지정합니다.

Core hotplug 후 affinity 손실

Terminal window
echo 0 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu1/online
# IRQ affinity가 초기값으로 돌아갈 수 있음

hotplug나 suspend/resume 후에는 affinity를 다시 적용하는 systemd unit이나 init 스크립트를 두는 편이 안전합니다.

#정리

  • /proc/irq/N/smp_affinity는 IRQ를 어느 코어에 보낼지 결정하는 가장 기본적인 도구입니다.
  • irqbalance는 일반 server에 유용하지만 manual 설정과 충돌하므로 RT 환경에서는 보통 끕니다.
  • isolcpus는 cmdline 한 줄로 코어를 격리하고, irqaffinity=를 함께 두어야 IRQ까지 격리됩니다.
  • NIC는 RSS로 RX queue를 늘리고 각 queue의 IRQ를 다른 코어에 매핑하면 throughput과 latency가 동시에 좋아집니다.
  • PREEMPT_RT는 IRQ를 thread로 변환하므로 chrt·taskset으로 priority와 affinity를 별도로 조정합니다.
  • Hyperthread sibling, all-CPU mask, hotplug 직후 설정 손실은 가장 흔한 함정입니다.
  • 측정은 cyclictest와 /proc/interrupts 카운트 비교가 가장 명확합니다.

Modern Embedded Recipes Part 4는 여기까지입니다.

#관련 항목

Modern Embedded Recipes · 88 of 152

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