U-Boot · source analysis

RISC-V relocation, trap frame과 secondary hart

relocate_code가 목적지 주소에 따라 image copy·.rela.dyn fixup·tvec 갱신을 선택하고, BSS와 SMP 조건부 IPI·cache helper를 거쳐 board_init_r로 분기하는 경계를 읽습니다.

표의 버전은 소스 분석 기준이며 최신 보안 버전 권고가 아닙니다. 제품 적용 시 사용 플랫폼의 errata를 확인하세요.

Series
22 / 22
Baseline
v2026.07
Commit
ece349ade297
Source
arch/riscv/cpu/start.S:269-460 (발췌 범위)

목적지가 다른 경우 RISC-V image를 복사하고, 조건부 pointer·trap vector·secondary hart relocation을 거쳐 board_init_r로 가는 순서는 무엇인가?

image byte copy와 pointer relocation, trap-vector relocation, secondary hart relocation은 서로 다른 작업이다. 주소 비교와 SMP 설정에 따라 생략되는 단계를 먼저 확인한다. IPI와 cache helper의 실제 가시성은 보드 구현까지 대조한다.

board_init_r로 분기할 때 PC와 SP, 전달할 GD 주소, 적용 대상 relocation이 목적지 주소 체계에 맞아야 한다. tvec 갱신은 relocation entry가 있는 경로에서 실행되며, secondary 이행은 SMP 설정에 따른다. 이 문장을 기준으로 코드를 위에서 아래로 읽으면, 함수 이름을 외우는 대신 어느 시점에 어떤 상태를 신뢰할 수 있는지 판단할 수 있다.

진입 인자와 조건부 relocation

그림 1. 세 인자는 진입 즉시 보존되고 주소 비교가 실행 경로를 가른다
진입과 stack분기 조건공통 마무리
01 · ENTRYs2 ← a0 (SP)
s3 ← a1 (GD)
s4 ← a2 (목적지)
02 · STACKSMP: hart별 SP
그 외: SP = s2
03 · TESTt6 = s4 − _start
s4 == _start?
04 · OPTIONAL다른 주소: copy·rela
tvec은 rela가 있을 때
05 · COMMONBSS clear
SMP이면 secondary IPI
06 · HANDOFFI/D cache helper
board_init_r + t6
CONTRACT

CONFIG_XPL_BUILD 밖의 relocate_code 경로다. 목적지가 현재 _start와 같으면 copy·rela·tvec 갱신만 건너뛰며 BSS와 뒤 단계는 실행한다.

U-Boot v2026.07 start.S 274–422행의 레지스터 보존·주소 비교·공통 tail을 표시했다. secondary IPI는 CONFIG_SMP에서만 있다.

실행 흐름

그림 2. 목적지 비교에서 갈라진 뒤 BSS에서 다시 합류
진입: a0/a1/a2
→ s2/s3/s4
SP 설정
t6 = s4 − _start
s4 == _start
주소 비교
같은 주소 · t6 = 0copy·rela·tvec 건너뜀

beq t0, s4, clear_bss가 곧바로 공통 BSS 단계로 간다.

다른 주소image copy → .rela.dyn 검사

entry가 있으면 fixup 후 tvec 갱신. __rel_dyn_start == __rel_dyn_end이면 tvec 갱신 없이 BSS로 간다.

↓ clear_bss에서 합류 ↓
BSS clear
(빈 범위면 건너뜀)
SMP에서만
secondary IPI
I-cache invalidate
D-cache flush
a0=s3, a1=s4
jr board_init_r+t6

소스 순서는 start.S 283–422행 기준이다. smp_call_function 실패는 hang으로 가며 cache helper는 그 호출 뒤에 있다. 플랫폼별 cache 구현과 secondary 측 가시성은 별도 확인 대상이다.

주소 조건과 단계별 상태

s2/s3/s4는 copy나 fixup의 결과가 아니라 relocate_code 진입 인자의 즉시 보존값이다. 아래 조건부 행은 모든 빌드가 통과하는 직렬 목록이 아니다.

#조건원문 명령 / 단계이후 상태와 다음 위치
01비-XPL 진입mv s2,a0; mv s3,a1; mv s4,a2새 SP·GD·목적지를 copy 전에 보존한다.
02SMP 여부stack_setup, t6=s4−_startSMP면 hart offset을 뺀 SP, 아니면 sp=s2.
03s4 == _startbeq ... clear_bsscopy·rela·tvec를 건너뛰고 BSS로 합류한다.
04s4 != _startcopy_loop_start..__bss_start image byte를 목적지에 복사한다.
05rela entry 존재fix_rela_dyn → csrw tvecfixup 뒤 trap vector를 trap_entry+t6로 갱신한다. entry가 없으면 BSS로 분기한다.
06공통clear_bss목적지 BSS를 0으로 만든다. 빈 범위면 loop를 생략한다.
07CONFIG_SMP만smp_call_functionsecondary relocation IPI 전송; 실패하면 hang.
08공통I-cache invalidate → D-cache flush → jra0=s3, a1=s4로 board_init_r+t6에 분기한다.

이 표는 고정된 v2026.07 구현의 순서다. IPI와 cache helper의 실제 가시성 계약은 보드·아키텍처 구현과 함께 검증한다.

주소와 객체의 이동을 그림으로 읽기

아래 그림은 주소, 객체를 사용하는 기간, 제어권을 넘기는 시점을 중심으로 정리했다. 실제 주소와 크기는 사용 중인 보드의 bdinfo, 맵 파일과 링커 심벌로 확인한다.

그림 3. board_init_f의 예약 순서와 relocate_code 인자

이 도식은 호출 순서다. old image·새 image·stack의 공간상 상하 배치를 뜻하지 않는다.

01reserve_uboot
목적지 image 영역
02reserve_malloc
malloc 영역 예약
03reserve_board
→ reserve_global_data
04reserve_fdt
조건부 FDT 영역
05기타 설정별 예약
bootstage·bloblist·arch
06reserve_stacks
새 SP 계산
그림 4. 주소 비교와 SMP 설정에 따른 tail

진입 인자 세 개를 먼저 보존한다. 아래 조건부 구간을 지나면 모두 BSS label과 공통 tail로 합류한다.

같은 주소 · t6 = 0

01s2/s3/s4 보존·SP 설정

02copy·rela·tvec 생략

03BSS clear로 직접 이동

다른 주소 · t6 ≠ 0

01image copy

02.rela.dyn 있으면 fixup·tvec 갱신

03BSS clear로 합류

그림 5. trap 전후 register frame

trap_entry는 GPR을 stack frame에 저장하고 handle_trap의 반환 EPC를 CSR에 쓴 뒤 같은 frame을 복원한다. cause·epc·tval은 frame slot이 아니라 a0–a2 인자다.

Trap entry

01x1-x31 stack 저장

02cause/epc/tval 읽기

03frame pointer를 a3로 전달

04handle_trap 호출

05새 epc 반환

Trap return

01epc CSR 갱신

02x1·x3–x31 복원; x2는 SP 해제로 복귀

03stack frame 해제

04mret 또는 sret

05중단된 context 재개

원본 코드

아래 코드는 U-Boot v2026.07의 arch/riscv/cpu/start.S에서 269-460줄을 그대로 가져온 것이다.

commitece349ade2973e220f524ce59e59711cc919263fanchor · L283relocate_code:
269	mv	a0, zero
270	mv	a1, zero
271	j	board_init_r
272#endif
273
274#if !defined(CONFIG_XPL_BUILD)
275/*
276 * void relocate_code(addr_sp, gd, addr_moni)
277 *
278 * This "function" does not return, instead it continues in RAM
279 * after relocating the monitor code.
280 *
281 */
282.globl relocate_code
283relocate_code:
284	mv	s2, a0			/* save addr_sp */
285	mv	s3, a1			/* save addr of gd */
286	mv	s4, a2			/* save addr of destination */
287
288/*
289 *Set up the stack
290 */
291stack_setup:
292#if CONFIG_IS_ENABLED(SMP)
293	/* tp: hart id */
294	slli	t0, tp, CONFIG_STACK_SIZE_SHIFT
295	sub	sp, s2, t0
296#else
297	mv	sp, s2
298#endif
299
300	la	t0, _start
301	sub	t6, s4, t0		/* t6 <- relocation offset */
302	beq	t0, s4, clear_bss	/* skip relocation */
303
304	mv	t1, s4			/* t1 <- scratch for copy_loop */
305	la	t2, __bss_start		/* t2 <- source end address */
306
307copy_loop:
308	LREG	t5, 0(t0)
309	addi	t0, t0, REGBYTES
310	SREG	t5, 0(t1)
311	addi	t1, t1, REGBYTES
312	blt	t0, t2, copy_loop
313
314/*
315 * Update dynamic relocations after board_init_f
316 */
317fix_rela_dyn:
318	la	t1, __rel_dyn_start
319	la	t2, __rel_dyn_end
320	beq	t1, t2, clear_bss
321	add	t1, t1, t6		/* t1 <- rela_dyn_start in RAM */
322	add	t2, t2, t6		/* t2 <- rela_dyn_end in RAM */
323
3246:
325	LREG	t5, REGBYTES(t1)	/* t5 <-- relocation info:type */
326	li	t3, R_RISCV_RELATIVE	/* reloc type R_RISCV_RELATIVE */
327	bne	t5, t3, 8f		/* skip non-RISCV_RELOC entries */
328	LREG	t3, 0(t1)
329	LREG	t5, (REGBYTES * 2)(t1)	/* t5 <-- addend */
330	add	t5, t5, t6		/* t5 <-- location to fix up in RAM */
331	add	t3, t3, t6		/* t3 <-- location to fix up in RAM */
332	SREG	t5, 0(t3)
333	j	10f
334
3358:
336	la	t4, __dyn_sym_start
337	add	t4, t4, t6
338
3399:
340	srli	t0, t5, SYM_INDEX	/* t0 <--- sym table index */
341	andi	t5, t5, 0xFF		/* t5 <--- relocation type */
342	li	t3, RELOC_TYPE
343	bne	t5, t3, 10f		/* skip non-addned entries */
344
345	LREG	t3, 0(t1)
346	li	t5, SYM_SIZE
347	mul	t0, t0, t5
348	add	s5, t4, t0
349	LREG	t0, (REGBYTES * 2)(t1)	/* t0 <-- addend */
350	LREG	t5, REGBYTES(s5)
351	add	t5, t5, t0
352	add	t5, t5, t6		/* t5 <-- location to fix up in RAM */
353	add	t3, t3, t6		/* t3 <-- location to fix up in RAM */
354	SREG	t5, 0(t3)
35510:
356	addi	t1, t1, (REGBYTES * 3)
357	blt	t1, t2, 6b
358
359/*
360 * trap update
361*/
362	la	t0, trap_entry
363	add	t0, t0, t6
364	csrw	MODE_PREFIX(tvec), t0
365
366clear_bss:
367	la	t0, __bss_start		/* t0 <- rel __bss_start in FLASH */
368	add	t0, t0, t6		/* t0 <- rel __bss_start in RAM */
369	la	t1, __bss_end		/* t1 <- rel __bss_end in FLASH */
370	add	t1, t1, t6		/* t1 <- rel __bss_end in RAM */
371	beq	t0, t1, relocate_secondary_harts
372
373clbss_l:
374	SREG	zero, 0(t0)		/* clear loop... */
375	addi	t0, t0, REGBYTES
376	blt	t0, t1, clbss_l
377
378relocate_secondary_harts:
379#if CONFIG_IS_ENABLED(SMP)
380	/* send relocation IPI */
381	la	t0, secondary_hart_relocate
382	add	a0, t0, t6
383
384	/* store relocation offset */
385	mv	s5, t6
386
387	mv	a1, s2
388	mv	a2, s3
389	mv	a3, zero
390	jal	smp_call_function
391
392	/* hang if relocation of secondary harts has failed */
393	beqz	a0, 1f
394	mv	a1, a0
395	la	a0, secondary_harts_relocation_error
396	jal	printf
397	jal	hang
398
399	/* restore relocation offset */
4001:	mv	t6, s5
401#endif
402
403/*
404 * We are done. Do not return, instead branch to second part of board
405 * initialization, now running from RAM.
406 */
407call_board_init_r:
408	jal	invalidate_icache_all
409	jal	flush_dcache_all
410	la	t0, board_init_r        /* offset of board_init_r() */
411	add	t4, t0, t6		/* real address of board_init_r() */
412/*
413 * setup parameters for board_init_r
414 */
415	mv	a0, s3			/* gd_t */
416	mv	a1, s4			/* dest_addr */
417	mv	s0, zero		/* fp == NULL */
418
419/*
420 * jump to it ...
421 */
422	jr	t4			/* jump to board_init_r() */
423#endif /* !defined(CONFIG_XPL_BUILD) */
424
425#if CONFIG_IS_ENABLED(SMP)
426hart_out_of_bounds_loop:
427	/* Harts in this loop are out of bounds, increase CONFIG_NR_CPUS. */
428	wfi
429	j	hart_out_of_bounds_loop
430
431/* SMP relocation entry */
432secondary_hart_relocate:
433	/* a1: new sp */
434	/* a2: new gd */
435	/* tp: hart id */
436
437	/* setup stack */
438	slli	t0, tp, CONFIG_STACK_SIZE_SHIFT
439	sub	sp, a1, t0
440
441	/* update global data pointer */
442	mv	gp, a2
443#endif
444
445/*
446 * Interrupts are disabled globally, but they can still be read from m/sip. The
447 * wfi function will wake us up if we get an IPI, even if we do not trap.
448 */
449secondary_hart_loop:
450	wfi
451
452#if CONFIG_IS_ENABLED(SMP)
453	csrr	t0, MODE_PREFIX(ip)
454#if CONFIG_IS_ENABLED(RISCV_MMODE)
455	andi	t0, t0, MIE_MSIE
456#else
457	andi	t0, t0, SIE_SSIE
458#endif
459	beqz	t0, secondary_hart_loop
460

발췌 범위와 읽기 기준

원문 269-460줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 relocate_code:은 L283에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.

image byte copy와 pointer relocation, trap-vector relocation, secondary hart relocation은 서로 다른 작업이다. 이 소스의 SMP IPI는 boot hart cache helper 호출보다 앞선다. 다른 hart의 instruction fetch 가시성은 IPI와 플랫폼 cache 구현까지 대조한다.

283relocate_code:

a0=new SP, a1=new gd, a2=destination을 받아 RISC-V image copy와 ELF relocation을 시작한다.

332 SREG t5, 0(t3)

계산된 새 pointer를 destination image의 relocation target slot에 XLEN 폭으로 기록한다.

354 SREG t5, 0(t3)

계산된 새 pointer를 destination image의 relocation target slot에 XLEN 폭으로 기록한다.

363 add t0, t0, t6

old image의 trap_entry link address를 destination handler address로 바꾼다. 바로 뒤 CSR write 전에 mode bit 처리도 확인한다.

364 csrw MODE_PREFIX(tvec), t0

trap vector에도 relocation offset을 반영해 새 image handler를 가리키게 한다.

함께 읽어야 하는 원본 코드

첫 코드 조각만으로 동작이 완성되지 않는 경우 호출 매크로, 객체 정의와 실제 실행 목록을 같은 페이지에 묶었다. 각 조각은 같은 기준 commit에서 가져왔다.

01. trap frame을 저장하고 handle_trap으로 넘기는 entry

arch/riscv/cpu/mtrap.S 18-103줄이다.

filearch/riscv/cpu/mtrap.Sanchor · L31trap_entry:
18#define SREG		sw
19#define REGBYTES	4
20#else
21#define LREG		ld
22#define SREG		sd
23#define REGBYTES	8
24#endif
25
26	.text
27
28	/* trap entry */
29	.align 6
30	.global trap_entry
31trap_entry:
32	addi sp, sp, -32 * REGBYTES
33	SREG x1,   1 * REGBYTES(sp)
34	SREG x2,   2 * REGBYTES(sp)
35	SREG x3,   3 * REGBYTES(sp)
36	SREG x4,   4 * REGBYTES(sp)
37	SREG x5,   5 * REGBYTES(sp)
38	SREG x6,   6 * REGBYTES(sp)
39	SREG x7,   7 * REGBYTES(sp)
40	SREG x8,   8 * REGBYTES(sp)
41	SREG x9,   9 * REGBYTES(sp)
42	SREG x10, 10 * REGBYTES(sp)
43	SREG x11, 11 * REGBYTES(sp)
44	SREG x12, 12 * REGBYTES(sp)
45	SREG x13, 13 * REGBYTES(sp)
46	SREG x14, 14 * REGBYTES(sp)
47	SREG x15, 15 * REGBYTES(sp)
48	SREG x16, 16 * REGBYTES(sp)
49	SREG x17, 17 * REGBYTES(sp)
50	SREG x18, 18 * REGBYTES(sp)
51	SREG x19, 19 * REGBYTES(sp)
52	SREG x20, 20 * REGBYTES(sp)
53	SREG x21, 21 * REGBYTES(sp)
54	SREG x22, 22 * REGBYTES(sp)
55	SREG x23, 23 * REGBYTES(sp)
56	SREG x24, 24 * REGBYTES(sp)
57	SREG x25, 25 * REGBYTES(sp)
58	SREG x26, 26 * REGBYTES(sp)
59	SREG x27, 27 * REGBYTES(sp)
60	SREG x28, 28 * REGBYTES(sp)
61	SREG x29, 29 * REGBYTES(sp)
62	SREG x30, 30 * REGBYTES(sp)
63	SREG x31, 31 * REGBYTES(sp)
64	csrr a0, MODE_PREFIX(cause)
65	csrr a1, MODE_PREFIX(epc)
66	csrr a2, MODE_PREFIX(tval)
67	mv a3, sp
68	jal handle_trap
69	csrw MODE_PREFIX(epc), a0
70
71	LREG x1,   1 * REGBYTES(sp)
72	LREG x3,   3 * REGBYTES(sp)
73	LREG x4,   4 * REGBYTES(sp)
74	LREG x5,   5 * REGBYTES(sp)
75	LREG x6,   6 * REGBYTES(sp)
76	LREG x7,   7 * REGBYTES(sp)
77	LREG x8,   8 * REGBYTES(sp)
78	LREG x9,   9 * REGBYTES(sp)
79	LREG x10, 10 * REGBYTES(sp)
80	LREG x11, 11 * REGBYTES(sp)
81	LREG x12, 12 * REGBYTES(sp)
82	LREG x13, 13 * REGBYTES(sp)
83	LREG x14, 14 * REGBYTES(sp)
84	LREG x15, 15 * REGBYTES(sp)
85	LREG x16, 16 * REGBYTES(sp)
86	LREG x17, 17 * REGBYTES(sp)
87	LREG x18, 18 * REGBYTES(sp)
88	LREG x19, 19 * REGBYTES(sp)
89	LREG x20, 20 * REGBYTES(sp)
90	LREG x21, 21 * REGBYTES(sp)
91	LREG x22, 22 * REGBYTES(sp)
92	LREG x23, 23 * REGBYTES(sp)
93	LREG x24, 24 * REGBYTES(sp)
94	LREG x25, 25 * REGBYTES(sp)
95	LREG x26, 26 * REGBYTES(sp)
96	LREG x27, 27 * REGBYTES(sp)
97	LREG x28, 28 * REGBYTES(sp)
98	LREG x29, 29 * REGBYTES(sp)
99	LREG x30, 30 * REGBYTES(sp)
100	LREG x31, 31 * REGBYTES(sp)
101	LREG x2,   2 * REGBYTES(sp)
102	addi sp, sp, 32 * REGBYTES
103	MODE_PREFIX(ret)

02. secondary hart의 IPI 대기와 dispatch

arch/riscv/cpu/start.S 437-465줄이다.

filearch/riscv/cpu/start.Sanchor · L449secondary_hart_loop:
437	/* setup stack */
438	slli	t0, tp, CONFIG_STACK_SIZE_SHIFT
439	sub	sp, a1, t0
440
441	/* update global data pointer */
442	mv	gp, a2
443#endif
444
445/*
446 * Interrupts are disabled globally, but they can still be read from m/sip. The
447 * wfi function will wake us up if we get an IPI, even if we do not trap.
448 */
449secondary_hart_loop:
450	wfi
451
452#if CONFIG_IS_ENABLED(SMP)
453	csrr	t0, MODE_PREFIX(ip)
454#if CONFIG_IS_ENABLED(RISCV_MMODE)
455	andi	t0, t0, MIE_MSIE
456#else
457	andi	t0, t0, SIE_SSIE
458#endif
459	beqz	t0, secondary_hart_loop
460
461	mv	a0, tp
462	jal	handle_ipi
463#endif
464
465	j	secondary_hart_loop

03. RISC-V U-Boot linker section과 relocation table 배치

arch/riscv/cpu/u-boot.lds 46-89줄이다.

filearch/riscv/cpu/u-boot.ldsanchor · L64.rela.dyn
46	. = ALIGN(4);
47
48	__u_boot_list : {
49		KEEP(*(SORT(__u_boot_list*)));
50	}
51
52	. = ALIGN(8);
53
54	.efi_runtime_rel : {
55		__efi_runtime_rel_start = .;
56		*(.rel*.efi_runtime)
57		*(.rel*.efi_runtime.*)
58		__efi_runtime_rel_stop = .;
59	}
60
61	__image_copy_end = .;
62
63	/DISCARD/ : { *(.rela.plt*) }
64	.rela.dyn : {
65		__rel_dyn_start = .;
66		*(.rela*)
67		__rel_dyn_end = .;
68	}
69
70	. = ALIGN(8);
71
72	.dynsym : {
73		__dyn_sym_start = .;
74		*(.dynsym)
75		__dyn_sym_end = .;
76		. = ALIGN(8);
77	}
78
79	_end = .;
80
81	.bss : {
82		__bss_start = .;
83		*(.bss*)
84		. = ALIGN(8);
85		__bss_end = .;
86	}
87}
88
89ASSERT(_end % 8 == 0, "_end must be 8-byte aligned for device tree");

04. cause, epc, tval을 해석하는 C trap dispatcher

arch/riscv/lib/interrupts.c 177-248줄이다.

filearch/riscv/lib/interrupts.canchor · L185ulong handle_trap(ulong cause
177/*
178 * disable interrupts
179 */
180int disable_interrupts(void)
181{
182	return 0;
183}
184
185ulong handle_trap(ulong cause, ulong epc, ulong tval, struct pt_regs *regs)
186{
187	ulong is_irq, irq;
188
189	/* An UEFI application may have changed gd. Restore U-Boot's gd. */
190	efi_restore_gd();
191
192	if (cause == CAUSE_BREAKPOINT &&
193	    CONFIG_IS_ENABLED(SEMIHOSTING_FALLBACK)) {
194		ulong pre_addr = epc - 4, post_addr = epc + 4;
195
196		/* Check for prior and post addresses to be in same page. */
197		if ((pre_addr & ~(PAGE_SIZE - 1)) ==
198			(post_addr & ~(PAGE_SIZE - 1))) {
199			u32 pre = *(u32 *)pre_addr;
200			u32 post = *(u32 *)post_addr;
201
202			/* Check for semihosting, i.e.:
203			 * slli    zero,zero,0x1f
204			 * ebreak
205			 * srai    zero,zero,0x7
206			 */
207			if (pre == 0x01f01013 && post == 0x40705013) {
208				disable_semihosting();
209				epc += 4;
210				return epc;
211			}
212		}
213	}
214
215	is_irq = (cause & MCAUSE_INT);
216	irq = (cause & ~MCAUSE_INT);
217
218	if (is_irq) {
219		switch (irq) {
220		case IRQ_M_EXT:
221		case IRQ_S_EXT:
222			external_interrupt(0);	/* handle external interrupt */
223			break;
224		case IRQ_M_TIMER:
225		case IRQ_S_TIMER:
226			timer_interrupt(0);	/* handle timer interrupt */
227			break;
228		default:
229			_exit_trap(cause, epc, tval, regs);
230			break;
231		};
232	} else {
233		_exit_trap(cause, epc, tval, regs);
234	}
235
236	return epc;
237}
238
239/*
240 *Entry Point for PLIC Interrupt Handler
241 */
242__attribute__((weak)) void external_interrupt(struct pt_regs *regs)
243{
244}
245
246__attribute__((weak)) void timer_interrupt(struct pt_regs *regs)
247{
248}

주요 구문 해설

210 return epc;

assembly 복귀 코드가 CSR EPC에 다시 쓸 재개 주소를 반환한다. breakpoint semihosting 경로는 이 값을 4만큼 전진시킬 수 있다.

215 is_irq = (cause & MCAUSE_INT);

cause 최상위 bit만 분리해 asynchronous interrupt 여부를 만든다. 나머지 bit는 독립적인 cause number다.

216 irq = (cause & ~MCAUSE_INT);

interrupt marker를 제거해 external/timer interrupt switch에 사용할 작은 cause code를 얻는다.

236 return epc;

assembly 복귀 코드가 CSR EPC에 다시 쓸 재개 주소를 반환한다. breakpoint semihosting 경로는 이 값을 4만큼 전진시킬 수 있다.

내부 동작을 더 깊게 읽기

01

진입 조건을 먼저 고정한다

relocate_code(a0, a1, a2)에 들어온 boot hart는 새 SP·GD·목적지 인자를 보존한다. secondary IPI는 CONFIG_SMP에서만 실행한다. 이 코드는 !CONFIG_XPL_BUILD 범위에 있고, stack 선택은 CONFIG_SMP에 따라 갈린다. 호출자에게서 받은 SP·GD·목적지가 보드의 예약 주소와 맞는지 먼저 대조한다.

image copy·.rela.dyn fixup·tvec 쓰기는 주소 및 entry 조건을 따른다. BSS 뒤 secondary IPI는 SMP에서만 호출되고, boot hart의 cache helper는 그 호출 뒤에 온다.

02

image·재배치 항목·trap frame의 시점을 구분한다

목적지 image 영역은 board_init_f의 reserve_uboot에서 예약한다. 주소가 다를 때만 copy_loop가 image byte를 복사하고, 링커가 둔 .rela.dyn entry가 있으면 fixup과 tvec 갱신을 수행한다. trap frame은 trap 진입마다 mtrap.S가 현재 stack에 만든다.

실제 ELF의 _start, __bss_start, .rela.dyn 범위는 map과 objdump로 대조한다. 목적지가 현재 _start와 같으면 image 복사는 생략된다.

03

주소, 크기와 정렬을 계산한다

t6=s4−_start를 기준으로 copy 범위 _start..__bss_start와 목적지 BSS 범위 __bss_start..__bss_end를 구분한다. copy와 BSS clear는 REGBYTES씩 진행하고, .rela.dyn은 3 * REGBYTES 간격으로 순회한다. 실제 ELF 심벌과 정렬을 대조한다.

04

주소 분기와 SMP 오류 경계를 확인한다

주소가 다르면 image copy 뒤 .rela.dyn을 검사하고 entry가 있을 때 fixup·tvec 갱신을 거친다. 같은 주소면 이 구간을 건너뛴다. 두 경로 모두 BSS 단계에서 합류하며, SMP에서만 secondary IPI를 호출한 다음 cache helper를 실행한다. .rela.dyn이 비면 fixup과 tvec 쓰기를 건너뛴다. SMP에서는 smp_call_function 반환값이 0이 아니면 오류를 출력하고 hang으로 가며, 성공 경로만 cache helper와 board_init_r 분기로 이어진다.

이 호출 순서만으로 secondary hart의 instruction fetch 가시성이 증명되지는 않으므로 IPI와 보드별 cache helper 구현을 별도로 대조한다.

05

제어권을 넘기기 전에 확인할 조건을 정리한다

정상 경로는 jr t4로 board_init_r+t6 주소에 분기하며 relocate_code로 돌아오지 않는다. 분기 전 a0=s3(GD), a1=s4(목적지), s0=0과 hart별 SP, 앞선 I-cache invalidate·D-cache flush 호출을 확인한다.

SMP의 secondary relocation 실패는 오류 출력 뒤 hang으로 가므로 board_init_r에 도달하지 않는다. 목적지가 현재 _start인 경로는 image copy 없이 같은 BSS·tail 단계를 거친다.

구현을 읽을 때 놓치기 쉬운 부분

01

relocate_code의 s2, s3, s4는 새 stack, gd, destination을 끝까지 보존한다

RISC-V ABI의 saved register를 사용해 new SP, new gd, destination을 copy와 relocation loop 사이에 보존한다. 함수 호출과 macro가 임시 register를 덮어도 최종 board_init_r argument를 복구할 수 있어야 한다.

GDB에서 entry 직후 s2/s3/s4와 gd->relocaddr, gd->start_addr_sp를 비교하면 caller argument 오류와 내부 copy 오류를 분리할 수 있다.

02

copy 범위는 _start부터 __bss_start까지이며 BSS는 별도로 0으로 만든다

linker image byte가 존재하는 text/rodata/data를 destination으로 옮기고, file payload가 없는 BSS는 copy 뒤 새 주소에서 clear한다. source/destination overlap과 copy 방향은 address 비교로 검증해야 한다.

SPL/TPL 또는 XIP 설정에서는 section 배치가 달라질 수 있으므로 symbol 차이를 고정 상수로 쓰지 않고 최종 ELF에서 읽는다.

03

.rela.dyn은 R_RISCV_RELATIVE와 absolute symbol relocation을 구분한다

relocation loop는 entry type을 읽어 relative relocation이면 addend에 t6 = destination - _start 재배치 오프셋을 더하고, R_RISCV_32/64이면 symbol value·addend·t6를 더한다. 지원하지 않는 type을 조용히 같은 방식으로 처리하면 pointer 일부만 손상될 수 있다.

readelf -rW u-boot 출력의 offset, type, addend를 몇 개 골라 relocation 전 source word와 relocation 후 destination word를 계산해 본다. 이 계산이 source 분석의 가장 직접적인 검증이다.

04

tvec도 relocation offset만큼 옮겨야 새 image에서 trap을 받는다

주소가 다르고 .rela.dyn entry가 있는 경로에서 copy·fixup 뒤 trap_entry+t6을 tvec에 쓴다. 목적지가 현재 _start와 같거나 rela 구간이 비어 있으면 소스는 clear_bss로 분기하여 이 쓰기를 건너뛴다.

이 줄이 빠지면 relocation 후 fault가 발생했을 때 old flash/SRAM handler로 되돌아가 새 stack/gd와 섞인다. 정상 부팅에서는 숨고 오류 경로에서만 나타나는 전형적인 stale entry 문제다.

05

trap_entry는 GPR frame을 만들고 cause·epc·tval은 인자로 전달한다

mtrap.S는 stack에 32 register 폭의 frame을 잡고 x1부터 x31을 저장한다. cause·epc·tval은 a0–a2, frame pointer는 a3로 C handle_trap에 넘긴다. 반환된 epc를 CSR에 쓴 뒤 x1과 x3–x31을 복원하고 stack pointer를 되돌려 mret/sret한다.

trap handler가 stack이 없는 시점에 호출될 가능성을 따져야 한다. 초기 tvec 설치 전후, per-hart stack 선택 전후의 exception은 같은 handler라도 frame을 놓을 안전한 memory가 다르다.

06

secondary relocation은 SMP일 때 BSS 뒤 IPI로 이어진다

CONFIG_SMP에서 boot hart가 image/BSS 단계 뒤 smp_call_function으로 secondary relocation IPI를 보낸다. secondary는 secondary_hart_loop에서 software interrupt를 확인하고 handler가 제공한 새 실행 위치로 이동한다.

이 소스에서 boot hart의 invalidate_icache_all과 flush_dcache_all 호출은 smp_call_function 뒤에 있다. secondary의 instruction fetch 가시성은 IPI 함수와 플랫폼별 cache helper 구현까지 대조해야 한다.

07

board_init_r로 가는 jr은 relocation 함수의 마지막 소유권 이전이다

새 board_init_r 주소를 destination offset으로 계산하고 a0에 new gd, a1에 destination을 넣은 뒤 jr로 비복귀 분기한다. 새 SP와 GD를 전달한 뒤에는 이전 주소의 stack과 GD를 runtime 객체처럼 참조해서는 안 된다. 목적지가 현재 주소와 같은 경로에서는 image copy 자체가 없다.

분기 직전 PC target, SP, gp, tvec, gd, BSS sample, relocation target sample을 한 번에 기록하면 relocation 완료 여부를 객관적으로 판정할 수 있다.

08

R_RISCV_RELATIVE entry 한 건을 destination 기준으로 계산한다

source base가 0x80000000, destination base가 0x87e00000이면 t6=0x07e00000이다. relocation offset 0x8006c018의 patch address는 0x87e6c018, link-time addend 0x8002a430에 t6를 더한 기록 값은 0x87e2a430이다. RV64라면 8-byte word 전체를 기록하고 alignment와 endianness를 확인한다.

readelf -rW u-boot 결과에서 선택한 entry를 relocation loop 직전/직후 memory와 비교한다. source word가 아니라 destination word가 바뀌어야 하며, 같은 entry가 두 번 적용되면 base가 중복 가산된다.

09

trap frame offset은 XLEN과 pt_regs 정의로 검산한다

RV64에서 mtrap.S는 32 * REGBYTES (256 byte)를 stack에 잡고 x1–x31을 1–31번 slot에 저장한다. cause·epc·tval은 별도 stack slot이 아니라 a0–a2 인자다. C struct pt_regs와 assembly slot offset을 함께 검산해야 한다.

GPR slot offset이 어긋나면 C handler의 regs 해석과 복귀 시 레지스터 복원이 틀어진다. cause·epc·tval의 a0–a2 전달과 CSR 갱신도 별도로 추적하고 debugger dump와 대조한다.

10

tvec와 I-cache publication을 secondary hart 관점에서 확인한다

old trap_entry=0x80008100, relocation offset=0x07e00000이면 새 tvec는 0x87e08100이다. 이 source는 정렬된 trap_entry + t6를 그대로 쓰므로 하위 2bit가 0인 direct mode를 새로 선택한다. vectored mode를 유지하도록 확장한다면 기존 mode bit를 주소 계산과 분리해 다시 합쳐야 한다.

이 구현의 순서는 조건부 copy·fixup·tvec 갱신 → BSS → SMP일 때 smp_call_function → boot hart의 I-cache invalidate·D-cache flush → board_init_r 분기다. 다른 hart의 fetch 가시성은 smp_call_function과 cache helper 구현을 따로 확인한다. secondary가 IPI는 받았지만 old instruction을 실행하는 문제는 이 순서 중 cache visibility가 빠졌을 때 생긴다.

객체와 수명

대상만들어지는 시점유효 범위확인할 조건
목적지 image주소가 다르면 copy_loop, 같으면 현재 image 유지board_init_r 뒤 runtime주소 분기와 BSS 합류
trap frametrap 발생 때 mtrap.S가 stack에 생성mret/sret 직전까지XLEN·slot offset·SP
s2/s3/s4 인자relocate_code 진입 때 a0/a1/a2 보존board_init_r 분기까지SMP stack offset·GD·목적지 주소
.rela.dyn entry링커가 image에 배치주소가 다르고 entry가 있을 때 fixup에 사용entry type·addend·목적지 slot
tvec CSRrela entry가 있는 relocation 경로에서 trap_entry+t6 기록다음 trap-vector 설정까지같은 주소·빈 rela이면 쓰기를 건너뜀
secondary hart SP·GPSMP의 secondary_hart_relocate에서 갱신secondary가 새 실행 상태를 사용할 때hart ID offset·새 GD 전달

실패 지점과 증상

#조건관찰되는 증상먼저 볼 단계
01rela type 처리 오류특정 global pointer만 old addresscopy text and data
02tvec 미보정relocation 후 fault가 old handler로 진입apply .rela.dyn
03SMP secondary IPI 오류secondary가 새 code로 이동하지 않음smp_call_function·handler
04cache maintenance 누락hart별 stale instructionIPI 뒤 cache helper와 플랫폼 구현

relocation 직후 fault가 나면 주소 비교, copy·rela·tvec 조건, BSS, SMP IPI 반환값과 cache helper 순서를 단계별로 되짚는다. 이 소스에서 SMP relocation 실패는 오류 출력 뒤 hang으로 간다.

소스 밖에서 확인할 증거

소스에서 파악한 동작을 실제 빌드 결과와 대상 보드의 로그로 확인한다. 아래 명령의 보드 이름과 툴체인 접두사는 사용 중인 빌드 환경에 맞게 바꾼다.

#목적명령 또는 계측판정 기준
01전처리 결과make <board>_defconfig && make V=1선택된 CONFIG와 실제 compile/link 명령을 보관한다.
02symbol과 section${CROSS_COMPILE}nm -n u-boot | grep 'relocate_code'symbol 주소가 기대한 stage와 image에 들어갔는지 확인한다.
03어셈블리 대조${CROSS_COMPILE}objdump -drS u-bootstart.S의 주소 분기, relocation store, tvec CSR 쓰기와 실제 명령을 대조한다.
04주소 배치bdinforelocaddr, malloc, FDT, stack과 DRAM bank 주소를 한 번에 기록한다.
05runtime 관찰GDB/JTAG: relocate_code → clear_bss → board_init_r주소 비교, SP·GD·tvec와 SMP일 때 IPI 반환값을 기록한다.

직접 확인할 실험

  1. 01
    readelf -rW에서 RELATIVE entry 손계산

    진입 직후 a0/a1/a2 → s2/s3/s4와 t6를 기록한다. 주소가 같으면 BSS로 직접 가는지, 다르면 readelf -rW의 RELATIVE entry가 예상대로 보정되는지 확인한다.

  2. 02
    trap_entry frame에서 cause/epc/tval과 x1-x31 확인

    mtrap.S의 32-slot frame에서 x1–x31 저장 위치와 a0–a2의 cause·epc·tval, a3의 frame pointer를 기록한다.

  3. 03
    분기 직전 PC/SP/gp/tvec/gd snapshot

    분기 직전 PC/SP/gp/tvec/GD를 기록한다. SMP 여부에 따른 hart별 SP와 secondary IPI 호출, 그 뒤 cache helper 순서를 비교한다.

  4. 04
    secondary_hart_loop와 IPI handler timestamp 대조

    smp_call_function 반환값, secondary 핸들러 도달 시각, 오류 시 hang 분기를 비교한다.

원문과 다음 글