← Kernel Series DUJINLABS.COM

Memory · Linux 6.18.37 LTS · source + diagram note

memblock

최신 LTS 기준: kernel.org longterm 6.18.37 기준으로 파일 좌표와 링크를 맞춘 문C식 독해 노트입니다. buddy allocator 전 early physical memory 관리. 박사 과정/커널 연구자 기준으로, API 설명보다 invariant, 동시성, lifetime, 성능 모델을 중심에 둔다.

읽는 지도

메모리 코드는 address translation, physical page ownership, reclaim policy, allocation latency가 한꺼번에 얽힌다. 이 층을 박사급으로 읽는다는 것은 '어느 page가 지금 누구 소유인가'와 '그 소유권을 어떤 lock/refcount가 증명하는가'를 끝까지 추적한다는 뜻이다.

먼저 볼 것

함수 이름보다 입력 객체와 출력 객체를 먼저 본다. 이 토픽에서 어떤 구조체가 생성, 연결, publish, retire되는지 표시한다.

다음에 볼 것

정상 경로와 실패 경로를 같은 무게로 본다. kernel code의 품질은 성공 path보다 error unwind, hotplug, teardown에서 더 잘 드러난다.

그림 1. memblock 이 kernel 안에서 놓이는 위치
virtual addressVMA, fault, kernel mapping
page tablePTE/PMD/PUD, TLB maintenance
struct page/foliorefcount, mapcount, flags
allocator/reclaimzone, LRU, compaction, writeback

왼쪽은 입력 또는 상위 계층이고, 오른쪽으로 갈수록 실제 상태 변경이 커진다. 문C식으로 읽을 때는 이 그림을 먼저 머리에 놓고 코드 조각을 끼워 넣는다.

원본 코드 좌표

Linux 6.18.37 LTS에서 열 파일

원본 코드:
Linux 6.18.37 LTS: mm/memblock.c
Linux 6.18.37 LTS: include/linux/memblock.h
Linux 6.18.37 LTS: arch/arm64/mm/init.c

설명: 첫 파일은 보통 진입 함수가 있는 곳이고, 나머지는 구조체 정의, architecture glue, callback 구현을 확인할 때 같이 연다. 파일을 여러 개 놓고 봐야 이 토픽의 boundary가 보인다.

대표 코드

memblock_add

원본 코드: mm/memblock.c, around line 66
 * arrays during addition of new regions. This feature should be used
 * with care so that memory allocated for the region array will not
 * overlap with areas that should be reserved, for example initrd.
 *
 * The early architecture setup should tell memblock what the physical
 * memory layout is by using memblock_add() or memblock_add_node()
 * functions. The first function does not assign the region to a NUMA
 * node and it is appropriate for UMA systems. Yet, it is possible to
 * use it on NUMA systems as well and assign the region to a NUMA node
 * later in the setup process using memblock_set_node(). The
 * memblock_add_node() performs such an assignment directly.
 *
 * Once memblock is setup the memory can be allocated using one of the
 * API variants:
 *
 * * memblock_phys_alloc*() - these functions return the **physical**
 *   address of the allocated memory
 * * memblock_alloc*() - these functions return the **virtual** address
 *   of the allocated memory.
 *
 * Note, that both API variants use implicit assumptions about allowed
 * memory ranges and the fallback methods. Consult the documentation
 * of memblock_alloc_internal() and memblock_alloc_range_nid()
 * functions for more elaborate description.
 *
 * As the system boot progresses, the architecture specific mem_init()
 * function frees all the memory to the buddy page allocator.
 *
 * Unless an architecture enables %CONFIG_ARCH_KEEP_MEMBLOCK, the
 * memblock data structures (except "physmem") will be discarded after the
 * system initialization completes.
 */

#ifndef CONFIG_NUMA
struct pglist_data __refdata contig_page_data;
EXPORT_SYMBOL(contig_page_data);
#endif

unsigned long max_low_pfn;
unsigned long min_low_pfn;

읽는 법: 이 절편에서 먼저 볼 것은 return 값이 아니라 상태 변경이다. 어떤 lock을 잡은 뒤 어떤 필드를 바꾸는지, 실패하면 어느 label로 빠지는지, 그리고 바뀐 상태를 다음 호출자가 어떤 전제로 소비하는지 표시한다.

memblock_reserve

원본 코드: mm/memblock.c, around line 105
unsigned long min_low_pfn;
unsigned long max_pfn;
unsigned long long max_possible_pfn;

static struct memblock_region memblock_memory_init_regions[INIT_MEMBLOCK_MEMORY_REGIONS] __initdata_memblock;
static struct memblock_region memblock_reserved_init_regions[INIT_MEMBLOCK_RESERVED_REGIONS] __initdata_memblock;
#ifdef CONFIG_HAVE_MEMBLOCK_PHYS_MAP
static struct memblock_region memblock_physmem_init_regions[INIT_PHYSMEM_REGIONS];
#endif

struct memblock memblock __initdata_memblock = {
	.memory.regions		= memblock_memory_init_regions,
	.memory.cnt		= 1,	/* empty dummy entry */
	.memory.max		= INIT_MEMBLOCK_MEMORY_REGIONS,
	.memory.name		= "memory",

	.reserved.regions	= memblock_reserved_init_regions,
	.reserved.cnt		= 1,	/* empty dummy entry */
	.reserved.max		= INIT_MEMBLOCK_RESERVED_REGIONS,
	.reserved.name		= "reserved",

	.bottom_up		= false,
	.current_limit		= MEMBLOCK_ALLOC_ANYWHERE,
};

#ifdef CONFIG_HAVE_MEMBLOCK_PHYS_MAP
struct memblock_type physmem = {
	.regions		= memblock_physmem_init_regions,
	.cnt			= 1,	/* empty dummy entry */
	.max			= INIT_PHYSMEM_REGIONS,
	.name			= "physmem",
};
#endif

/*
 * keep a pointer to &memblock.memory in the text section to use it in
 * __next_mem_range() and its helpers.
 *  For architectures that do not keep memblock data after init, this
 * pointer will be reset to NULL at memblock_discard()
 */

읽는 법: 이 절편에서 먼저 볼 것은 return 값이 아니라 상태 변경이다. 어떤 lock을 잡은 뒤 어떤 필드를 바꾸는지, 실패하면 어느 label로 빠지는지, 그리고 바뀐 상태를 다음 호출자가 어떤 전제로 소비하는지 표시한다.

함수별 독해

buddy allocator 이전에 RAM과 reserved 영역을 interval set으로 관리하는 early physical memory allocator다.

이 섹션은 원본 코드 발췌를 함수 이름 단위로 끊어, 각 함수가 어떤 전제 조건을 만들고 다음 함수가 무엇을 소비하는지 추적한다.

그림 2. memblock 함수 체인과 관찰 지점
entrycaller가 넘기는 객체와 context를 확정
memblock_addFDT/e820/arch code가 memory interval 등록
memblock_reserve겹치는 구간이 잘라짐
observable statetracepoint, counter, sysfs/proc에서 확인되는 결과

각 노드는 독립 함수가 아니라 전제 조건을 생산하고 소비하는 연결점이다. 코드를 읽을 때는 노드 사이에서 어떤 필드가 바뀌는지 표시한다.

1. memblock_add

memblock_add 주변에서는 memblock.memory를 중심으로 본다. 이 필드는 사용 가능한 RAM 구간 역할을 하므로, 함수가 끝날 때 RAM added 상태가 실제로 성립했는지 확인해야 한다.

원본 코드에서 볼 순서는 입력 범위 검증, 중심 필드 갱신, 다른 계층에 보이는 publish 지점, 실패 시 되돌림 순서다. 이 네 칸이 맞아야 다음 함수가 FDT/e820/arch code가 memory interval 등록을 전제로 삼을 수 있다.

자주 틀리는 해석: memblock을 일반 allocator처럼 free list로 상상함

2. memblock_reserve

memblock_reserve 주변에서는 memblock.reserved를 중심으로 본다. 이 필드는 kernel, DTB, initrd, CMA 등의 제외 구간 역할을 하므로, 함수가 끝날 때 reserved split 상태가 실제로 성립했는지 확인해야 한다.

원본 코드에서 볼 순서는 입력 범위 검증, 중심 필드 갱신, 다른 계층에 보이는 publish 지점, 실패 시 되돌림 순서다. 이 네 칸이 맞아야 다음 함수가 겹치는 구간이 잘라짐을 전제로 삼을 수 있다.

자주 틀리는 해석: reserved와 unavailable을 같은 의미로 봄

함수입력상태 변경검증 질문
memblock_addmemblock.memory, caller context, subsystem 전제 조건RAM added: FDT/e820/arch code가 memory interval 등록memblock을 일반 allocator처럼 free list로 상상함 문제를 코드상 어느 조건문 또는 error label에서 분리하는가
memblock_reservememblock.reserved, caller context, subsystem 전제 조건reserved split: 겹치는 구간이 잘라짐reserved와 unavailable을 같은 의미로 봄 문제를 코드상 어느 조건문 또는 error label에서 분리하는가

구조체 / 필드 해설

여기서는 “어떤 구조체가 있다”가 아니라 그 필드가 어느 단계에서 쓰기 가능하고 어느 단계부터 관찰 가능한지를 본다. 박사급 리뷰에서는 필드의 뜻보다 보호 규칙이 먼저다.

그림 3. memblock 핵심 필드 연결
memblock.memory사용 가능한 RAM 구간
memblock.reservedkernel, DTB, initrd, CMA 등의 제외 구간
current_limitearly allocation 상한
bottom_upallocation 방향 정책

필드는 구조체 안에 흩어져 있지만, 실제 실행에서는 위 순서로 의미가 이어진다.

필드읽는 법확인
memblock.memory사용 가능한 RAM 구간누가 쓰고, 누가 보호하고, 언제 lifetime이 끝나는지 원본 코드에서 확인
memblock.reservedkernel, DTB, initrd, CMA 등의 제외 구간누가 쓰고, 누가 보호하고, 언제 lifetime이 끝나는지 원본 코드에서 확인
current_limitearly allocation 상한누가 쓰고, 누가 보호하고, 언제 lifetime이 끝나는지 원본 코드에서 확인
bottom_upallocation 방향 정책누가 쓰고, 누가 보호하고, 언제 lifetime이 끝나는지 원본 코드에서 확인

상태 전이 그림

상태 전이를 따로 그리는 이유는 정상 path와 실패 path를 같은 표에서 보기 위해서다. 커널 regression은 흔히 마지막 상태가 아니라 중간 상태를 외부에 publish한 뒤 rollback하지 못해서 생긴다.

그림 4. memblock 상태 전이
RAM addedFDT/e820/arch code가 memory interval 등록
reserved split겹치는 구간이 잘라짐
early allocation정렬과 limit에 맞는 빈 구간 선택
handoff to buddymem_init에서 page allocator로 ownership 이동

상태 전이는 단방향처럼 그렸지만, 실패 경로에서는 대부분 역순 rollback이 붙는다.

상태의미진입 조건깨지는 지점
RAM addedFDT/e820/arch code가 memory interval 등록앞 단계 함수가 전제 조건을 만들고 error path가 정리된 뒤다음 단계가 이 상태를 너무 일찍 소비하거나 늦게 정리할 때
reserved split겹치는 구간이 잘라짐앞 단계 함수가 전제 조건을 만들고 error path가 정리된 뒤다음 단계가 이 상태를 너무 일찍 소비하거나 늦게 정리할 때
early allocation정렬과 limit에 맞는 빈 구간 선택앞 단계 함수가 전제 조건을 만들고 error path가 정리된 뒤다음 단계가 이 상태를 너무 일찍 소비하거나 늦게 정리할 때
handoff to buddymem_init에서 page allocator로 ownership 이동앞 단계 함수가 전제 조건을 만들고 error path가 정리된 뒤다음 단계가 이 상태를 너무 일찍 소비하거나 늦게 정리할 때
memblock review rule = state transition + owner transition + visibility transition

불변조건 / 실패 케이스

lifetime

memblock 의 중심 객체가 publish된 뒤에는 마지막 참조가 사라지기 전까지 teardown path가 모든 callback, timer, IRQ, worker와 경합하지 않아야 한다.

ordering

상태 필드를 바꾼 뒤 다른 CPU나 하위 계층이 관찰할 수 있다면 lock, barrier, refcount, RCU 중 어느 장치가 visibility를 보장하는지 확인한다.

error unwind

중간 단계 실패는 성공 단계의 역순으로 되돌아가야 한다. goto label이 많은 코드는 label 이름보다 어느 resource가 이미 획득됐는지를 표로 적는다.

bring-up symptom

embedded bring-up에서는 panic보다 silence, timeout, deferred probe, interrupt flood처럼 간접 증상으로 드러나는 경우가 많다.

주의

memblock을 일반 allocator처럼 free list로 상상함

주의

reserved와 unavailable을 같은 의미로 봄

주의

virtual return API와 physical return API를 섞음

계측 / 검증

계측은 printk 위치 경쟁이 아니라 가설 검증이다. 먼저 위 상태표에서 멈춘 state를 정하고, 그 state를 바꾸는 함수와 그 결과를 소비하는 함수를 동시에 본다.

도구보는 것해석
memblock=debugmemblock 의 상태 전이가 어느 지점에서 멈추는지 확인로그가 찍힌 위치를 완료 시점으로 단정하지 말고, 바로 앞뒤 필드 변경을 원본에서 확인
earlyconmemblock 의 상태 전이가 어느 지점에서 멈추는지 확인로그가 찍힌 위치를 완료 시점으로 단정하지 말고, 바로 앞뒤 필드 변경을 원본에서 확인
page_owner after bootmemblock 의 상태 전이가 어느 지점에서 멈추는지 확인로그가 찍힌 위치를 완료 시점으로 단정하지 말고, 바로 앞뒤 필드 변경을 원본에서 확인
ftrace:memblock_alloc_range_nidmemblock 의 상태 전이가 어느 지점에서 멈추는지 확인로그가 찍힌 위치를 완료 시점으로 단정하지 말고, 바로 앞뒤 필드 변경을 원본에서 확인
기본 추적 골격:
# 예시: tracefs가 켜진 보드에서 토픽별 event를 좁혀 본다.
mount -t tracefs nodev /sys/kernel/tracing
echo function_graph > /sys/kernel/tracing/current_tracer
echo ':mod:*' > /sys/kernel/tracing/set_ftrace_filter
cat /sys/kernel/tracing/trace_pipe

연구 질문

  • memblock 의 state machine을 네 단계로 줄였을 때, 실제 코드에서 빠지는 intermediate state는 무엇인가?
  • memblock 의 fast path가 생략한 검사는 어느 init path 또는 slow path에서 보증되는가?
  • 실험으로 확인한다면 'memblock을 일반 allocator처럼 free list로 상상함' 문제를 어떤 tracepoint와 counter로 분리할 수 있는가?
  • 실험으로 확인한다면 'reserved와 unavailable을 같은 의미로 봄' 문제를 어떤 tracepoint와 counter로 분리할 수 있는가?