U-Boot启动流程分析

零、前言

u-boot 是在芯片上电后、加载系统之前要运行的一段程序,本文主要是详细的分析一下 u-boot 的启动流程,理清 u-boot 是如何启动的。通过对 u-boot 启动流程的梳理,我们就可以掌握一些外设是在哪里被初始化的,这样当我们需要修改这些外设驱动的时候就会心里有数。另外,通过分析 u-boot 的启动流程我们也可以了解 Linux 内核是如何被启动的。

硬件信息:

1
2
3
4
开发板:orangepi 5 pro
主控芯片:rockchip rk3588s
芯片架构:ARM64
u-boot版本:v2017.09

一、启动方式

如下是板子上的存储配置:

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
┌────────────────────────────────────────────────────────────┐
│ RK3588 芯片内部结构 │
│────────────────────────────────────────────────────────────│
│ │
│ ┌──────────┐ │
│ │ CPU核群 │ ← Cortex-A76/A55 │
│ └─────┬────┘ │
│ │ │
│ ┌─────┴──────────────────────────────────────────┐ │
│ │ 片上总线(AXI / AHB) │ │
│ └─────┬──────────────┬────────────┬──────────────┘ │
│ │ │ │ │
│ │ │ │ │
│ ┌─────┴────┐ ┌────┴────┐ ┌────┴──────────┐ │
│ │ BootROM │ │ SRAM │ │ DDR 控制器 │ │
│ │ (128KB) │ │ (200KB) │ │ (需TPL初始化)│ │
│ │ 出厂固化 │ │ 上电可用 │ └────┬──────────┘ │
│ └──────────┘ └─────────┘ │ │
│ │ │
│ ┌──────┴───────────────┐ │
│ │ 外部DDR内存 (4~16GB) │ ← PCB焊接 │
│ └──────────────────────┘ │
│ │
│────────────────────────────────────────────────────────────│
│ │
│ 外部存储接口控制器(Boot介质接口) │
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ SPI控制器(SFC)│ │ SD控制器(SDMMC)│ │ eMMC控制器(SDIO)│ │
│ └──────┬────────┘ └──────┬────────┘ └──────┬────────┘ │
│ │ │ │ │
└─────────┼───────────────────┼───────────────────┼────────────┘
│ │ │
│ │ │
▼ ▼ ▼
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ SPI Flash │ │ SD卡槽 │ │ eMMC存储 │
│ 固定焊接16MB │ │ 可插拔 │ │ 焊接32GB │
└──────────────┘ └──────────────┘ └──────────────┘
↑ ↑ ↑
│ │ │
└─────── 外部介质,通过BootROM检测 ──────┘

那么现在有一个问题:CPU上电后要执行代码,但代码在哪里?怎么执行?

这里引入一个概念:XIP(eXecute In Place,原地执行)。

XIP 指 CPU 直接从某个存储器取指令执行,不需要先把代码拷贝到别的地方。

支持 XIP 的存储:

  • ROM:支持。BootROM 代码就是 CPU 直接从 ROM 执行的
  • SRAM:支持。代码可以直接在 SRAM 中执行
  • DDR:支持。但前提是 DDR 已经初始化完成
  • SPI NOR Flash:支持 XIP(通过 Memory-Mapped 模式,CPU 可以直接从 SPI NOR 取指令执行)

不支持 XIP 的存储:

  • eMMC/SD 卡:不支持。CPU 无法直接从 SDIO 总线取指令

那么现在回到板子上:

  1. 上电时只有 ROM 和 SRAM 可用。DDR 还没初始化,SPI Flash 和 SD 卡更是需要驱动程序才能访问
  2. 完整的 U-Boot 代码存储在 SPI Flash 或 SD 卡里,容量有几百 KB 到几 MB
  3. 这些存储设备不支持 XIP,必须先把代码读到 RAM(SRAM 或 DDR)里,CPU 才能执行
  4. 但 SRAM 只有 200KB,根本放不下完整的 U-Boot

这就是问题所在:你需要一个程序去初始化DDR、去读取存储设备,但这个程序本身也需要空间来运行。

针对这个问题,唯一的办法就是:把启动过程拆解成多个小阶段,每个阶段只做必需的最少工作,然后把接力棒交给下一个阶段。

采用三阶段设计:

  1. TPL(Tiny Program Loader,精简程序加载器):
    • 运行位置:SRAM
    • 代码大小:精简到极致,只有几十 KB
    • 唯一任务:初始化 DDR 内存
    • 完成后的效果:DDR 可用了,系统有了几GB的可用内存
  2. SPL(Secondary Program Loader,二级程序加载器):
    • 运行位置:DDR(因为 DDR 已经可用了)
    • 代码大小:100KB 左右,包含基本的驱动
    • 主要任务:初始化存储设备,从 SPI Flash 或 SD 卡读取 U-Boot 主程序到 DDR
    • 完成后的效果:U-Boot 主程序已经在 DDR 中了
  3. U-Boot 主程序:
    • 运行位置:DDR
    • 代码大小:几百 KB 到几 MB,功能完整
    • 主要任务:初始化所有外设,提供命令行界面,加载 Linux 内核和设备树,启动操作系统

每个阶段都在前一个阶段创造的条件基础上工作,像接力赛一样把系统一步步启动起来。

二、程序入口

2.1 u-boot.lds

程序的链接是由链接脚本来决定的,所以通过链接脚本可以找到程序的入口,链接脚本为 arch/arm/cpu/armv8/u-boot.lds,它描述了如何生成最终的二进制文件,其中就包含程序入口。

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
/*
* (C) Copyright 2013
* David Feng <fenghua@phytium.com.cn>
*
* (C) Copyright 2002
* Gary Jennejohn, DENX Software Engineering, <garyj@denx.de>
*
* SPDX-License-Identifier: GPL-2.0+
*/

#include <config.h>
#include <asm/psci.h>

/* 指定输出可执行文件: "elf 32位 小端格式 arm指令" */
OUTPUT_FORMAT("elf64-littleaarch64", "elf64-littleaarch64", "elf64-littleaarch64")
/* 指定输出可执行文件的目标架构:"arm64" */
OUTPUT_ARCH(aarch64)
/* 指定输出可执行文件的起始地址为:"_start" */
ENTRY(_start)
SECTIONS
{
#ifdef CONFIG_ARMV8_SECURE_BASE
/DISCARD/ : { *(.rela._secure*) }
#endif

/*
* 指定可执行文件(image)的全局入口地址,通常都放在ROM(flash)0x0位置
* 设置 0 的原因是 arm 内核的处理器,上电后默认是从 0x00000000 处启动
*/
. = 0x00000000;

. = ALIGN(8); /* 中断向量表 */
.text :
{
/* u-boot 的设计中需要将 u-boot 的镜像拷贝到 ram(sdram,ddr....)中执行,这里表示复制的开始地址 */
*(.__image_copy_start)
CPUDIR/start.o (.text*) /* CPUDIR/start.o 中的所有.text 段 */
*(.text*)
}

#ifdef CONFIG_ARMV8_PSCI
.__secure_start :
#ifndef CONFIG_ARMV8_SECURE_BASE
ALIGN(CONSTANT(COMMONPAGESIZE))
#endif
{
KEEP(*(.__secure_start))
}

#ifndef CONFIG_ARMV8_SECURE_BASE
#define CONFIG_ARMV8_SECURE_BASE
#define __ARMV8_PSCI_STACK_IN_RAM
#endif
.secure_text CONFIG_ARMV8_SECURE_BASE :
AT(ADDR(.__secure_start) + SIZEOF(.__secure_start))
{
*(._secure.text)
}

.secure_data : AT(LOADADDR(.secure_text) + SIZEOF(.secure_text))
{
*(._secure.data)
}

.secure_stack ALIGN(ADDR(.secure_data) + SIZEOF(.secure_data),
CONSTANT(COMMONPAGESIZE)) (NOLOAD) :
#ifdef __ARMV8_PSCI_STACK_IN_RAM
AT(ADDR(.secure_stack))
#else
AT(LOADADDR(.secure_data) + SIZEOF(.secure_data))
#endif
{
KEEP(*(.__secure_stack_start))

. = . + CONFIG_ARMV8_PSCI_NR_CPUS * ARM_PSCI_STACK_SIZE;

. = ALIGN(CONSTANT(COMMONPAGESIZE));

KEEP(*(.__secure_stack_end))
}

#ifndef __ARMV8_PSCI_STACK_IN_RAM
. = LOADADDR(.secure_stack);
#endif

.__secure_end : AT(ADDR(.__secure_end)) {
KEEP(*(.__secure_end))
LONG(0x1d1071c); /* Must output something to reset LMA */
}
#endif

/*
* .rodata 段,确保是以8字节对齐
*/
. = ALIGN(8);
.rodata : { *(SORT_BY_ALIGNMENT(SORT_BY_NAME(.rodata*))) }

/*
* data段,确保是以8字节对齐
*/
. = ALIGN(8);
.data : {
*(.data*)
}

. = ALIGN(8);

. = .;

/*
* u_boot_list 段,确保是以 8 字节对齐
* 这里存放的都是 u_boot_list 中的函数
*/
. = ALIGN(8);
.u_boot_list : {
KEEP(*(SORT(.u_boot_list*)));
}

. = ALIGN(8);

.efi_runtime : {
__efi_runtime_start = .;
*(efi_runtime_text)
*(efi_runtime_data)
__efi_runtime_stop = .;
}

.efi_runtime_rel : {
__efi_runtime_rel_start = .;
*(.relaefi_runtime_text)
*(.relaefi_runtime_data)
__efi_runtime_rel_stop = .;
}

/*
* __image_copy_end 也是个符号表示一个结束地址,确保是以8字节对齐
*/
. = ALIGN(8);

/* u-boot 的设计中需要将 u-boot 的镜像拷贝到ram(sdram,ddr....)中执行,这里表示复制的结束地址 */
.image_copy_end :
{
*(.__image_copy_end)
}

. = ALIGN(8);

.rel_dyn_start : /* .rel.dyn 段起始地址 */
{
*(.__rel_dyn_start)
}

.rela.dyn : {
*(.rela*)
}

.rel_dyn_end : /* .rel.dyn 段结束地址 */
{
*(.__rel_dyn_end)
}

_end = .;

. = ALIGN(8);

.bss_start : { /* .bss段起始地址 */
KEEP(*(.__bss_start));
}

.bss : {
*(.bss*)
. = ALIGN(8);
}

.bss_end : { /* .bss段结束地址 */
KEEP(*(.__bss_end));
}

/DISCARD/ : { *(.dynsym) }
/DISCARD/ : { *(.dynstr*) }
/DISCARD/ : { *(.dynamic*) }
/DISCARD/ : { *(.plt*) }
/DISCARD/ : { *(.interp*) }
/DISCARD/ : { *(.gnu*) }
}

通过上面的分析可以看出:由于在链接脚本中规定了文件 start.o(对应于 start.S)作为整个 uboot 的起始点,因此启动 uboot 时会执行首先执行 start.S。一般来说,内存空间可分为代码段、数据段、全局变量段、未初始化变量区、栈区、堆区等.其中,栈区由指针 SP 决定,堆区实质上是由 C 代码实现的,其它段则由编译器决定。从上面的分析可以看出,从 0x00000000 地址开始,编译器首先将代码段放在最开始的位置,然后是数据段,然后是 bss 段(未初始化变量区)。

2.2 u-boot.map

u-boot.map 是 uboot 的映射文件,可以从此文件看到某个文件或者函数链接到了哪个地址,下面打开 u-boot.map,查看各个段的起始地址和结束分别是多少:

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
Memory Configuration

Name Origin Length Attributes
*default* 0x0000000000000000 0xffffffffffffffff

Linker script and memory map

// 命令行 -Ttext 0x200000(或 CONFIG_SYS_TEXT_BASE=0x200000)覆盖了脚本里的 . = 0
Address of section .text set to 0x200000
0x0000000000000000 . = 0x0
0x0000000000000000 . = ALIGN (0x8)

.text 0x0000000000200000 0xc961c
*(.__image_copy_start)
.__image_copy_start
0x0000000000200000 0x0 arch/arm/lib/built-in.o
0x0000000000200000 __image_copy_start
arch/arm/cpu/armv8/start.o(.text*)
.text 0x0000000000200000 0x138 arch/arm/cpu/armv8/start.o
0x0000000000200000 _start
0x0000000000200008 _TEXT_BASE
0x0000000000200010 _end_ofs
0x0000000000200018 _bss_start_ofs
0x0000000000200020 _bss_end_ofs
0x000000000020002c save_boot_params_ret
0x0000000000200094 apply_core_errata
0x00000000002000b8 lowlevel_init
0x00000000002000d4 smp_kick_all_cpus
0x00000000002000e0 c_runtime_cpu_setup
0x0000000000200118 save_boot_params
*(.text*)
*fill* 0x0000000000200138 0x6c8
.text 0x0000000000200800 0x6d4 arch/arm/cpu/armv8/built-in.o
0x0000000000200800 vectors
0x0000000000200cec __arm_smccc_smc
0x0000000000200d18 __arm_smccc_hvc
0x0000000000200d48 cpu_suspend
0x0000000000200de8 cpu_do_suspend
0x0000000000200e54 cpu_resume
0x0000000000200e74 cpu_do_resume
......

各段的位置:

1
2
3
4
5
6
7
8
9
10
.__image_copy_start 0x0000000000200000  0x0
.__image_copy_end 0x000000000032d328 0x0
.text 0x0000000000200000 0x0c961c ← 从 0x200000 开始,823KB
.rodata 0x00000000002c9620 0x051653
.data 0x000000000031ac90 0x00bc48
.u_boot_list 0x00000000003268f8 0x006a30 ← U_BOOT_CMD 注册表
.rel_dyn_start 0x000000000032d328 0x0
.rela.dyn 0x000000000032d328 0x01e960 ← 重定位表,125KB!
.rel_dyn_end 0x000000000034bc88 0x0
.bss 0x000000000034bcc0 0x188e88 ← 1.6MB

上面的变量除了 __image_copy_start 以外,其他的变量值每次编译的时候可能会变化。修改 uboot 代码、配置等都会影响到这些值。所以,一切以实际值为准。

2.3 start.S

为了方便阅读,下面对源文件做了一些删减,取出了一些不必要的宏:

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
/*
* (C) Copyright 2013
* David Feng <fenghua@phytium.com.cn>
*
* SPDX-License-Identifier: GPL-2.0+
*/

#include <asm-offsets.h>
#include <config.h>
#include <linux/linkage.h>
#include <asm/macro.h>
#include <asm/armv8/mmu.h>

/*************************************************************************
*
* Startup Code (reset vector)
*
*************************************************************************/

.globl _start
_start:
b reset

#if !CONFIG_IS_ENABLED(TINY_FRAMEWORK)
.align 3

.globl _TEXT_BASE
_TEXT_BASE:
#if defined(CONFIG_SPL_BUILD)
.quad CONFIG_SPL_TEXT_BASE
#else
.quad CONFIG_SYS_TEXT_BASE
#endif

/*
* These are defined in the linker script.
*/
.globl _end_ofs
_end_ofs:
.quad _end - _start

.globl _bss_start_ofs
_bss_start_ofs:
.quad __bss_start - _start

.globl _bss_end_ofs
_bss_end_ofs:
.quad __bss_end - _start

reset:
/* Allow the board to save important registers */
b save_boot_params
.globl save_boot_params_ret
save_boot_params_ret:
/*
* Could be EL3/EL2/EL1, Initial State:
* Little Endian, MMU Disabled, i/dCache Disabled
*/
adr x0, vectors /* 设置中断向量表 */
switch_el x1, 3f, 2f, 1f
3: msr vbar_el3, x0
mrs x0, scr_el3
orr x0, x0, #0xf /* SCR_EL3.NS|IRQ|FIQ|EA */
msr scr_el3, x0
msr cptr_el3, xzr /* Enable FP/SIMD */
#ifdef COUNTER_FREQUENCY
ldr x0, =COUNTER_FREQUENCY
msr cntfrq_el0, x0 /* Initialize CNTFRQ */
#endif
b 0f
2: msr vbar_el2, x0
mov x0, #0x33ff
msr cptr_el2, x0 /* Enable FP/SIMD */
b 0f
1: msr vbar_el1, x0
mov x0, #3 << 20
msr cpacr_el1, x0 /* Enable FP/SIMD */
0:

/* Apply ARM core specific erratas */
bl apply_core_errata

/*
* Cache/BPB/TLB Invalidate
* i-cache is invalidated before enabled in icache_enable()
* tlb is invalidated before mmu is enabled in dcache_enable()
* d-cache is invalidated before enabled in dcache_enable()
*/

/* Processor specific initialization */
bl lowlevel_init

#if defined(CONFIG_ARMV8_SPIN_TABLE) && !defined(CONFIG_SPL_BUILD)
branch_if_master x0, x1, master_cpu
b spin_table_secondary_jump
/* never return */
#elif defined(CONFIG_ARMV8_MULTIENTRY)
branch_if_master x0, x1, master_cpu

/*
* Slave CPUs
*/
slave_cpu: /* 从核 */
wfe
ldr x1, =CPU_RELEASE_ADDR
ldr x0, [x1]
cbz x0, slave_cpu
br x0 /* branch to the given address */
#endif /* CONFIG_ARMV8_MULTIENTRY */
master_cpu: /* 主核 */
bl _main

/*-----------------------------------------------------------------------*/

WEAK(apply_core_errata)

mov x29, lr /* Save LR */
/* For now, we support Cortex-A57 specific errata only */

/* Check if we are running on a Cortex-A57 core */
branch_if_a57_core x0, apply_a57_core_errata
0:
mov lr, x29 /* Restore LR */
ret

/*-----------------------------------------------------------------------*/

WEAK(lowlevel_init)
mov x29, lr /* Save LR */

#if CONFIG_IS_ENABLED(IRQ)
branch_if_slave x0, 1f
ldr x0, =GICD_BASE
bl gic_init_secure
1:
#if defined(CONFIG_GICV3)
ldr x0, =GICR_BASE
bl gic_init_secure_percpu
#elif defined(CONFIG_GICV2)
ldr x0, =GICD_BASE
ldr x1, =GICC_BASE
bl gic_init_secure_percpu
#endif
#endif

#ifdef CONFIG_ARMV8_MULTIENTRY
branch_if_master x0, x1, 2f

/*
* Slave should wait for master clearing spin table.
* This sync prevent salves observing incorrect
* value of spin table and jumping to wrong place.
*/
#if defined(CONFIG_GICV2) || defined(CONFIG_GICV3)
#ifdef CONFIG_GICV2
ldr x0, =GICC_BASE
#endif
bl gic_wait_for_interrupt
#endif

/*
* All slaves will enter EL2 and optionally EL1.
*/
adr x4, lowlevel_in_el2
ldr x5, =ES_TO_AARCH64
bl armv8_switch_to_el2

lowlevel_in_el2:
#ifdef CONFIG_ARMV8_SWITCH_TO_EL1
adr x4, lowlevel_in_el1
ldr x5, =ES_TO_AARCH64
bl armv8_switch_to_el1

lowlevel_in_el1:
#endif

#endif /* CONFIG_ARMV8_MULTIENTRY */

2:
mov lr, x29 /* Restore LR */
ret
ENDPROC(lowlevel_init)

WEAK(smp_kick_all_cpus)
/* Kick secondary cpus up by SGI 0 interrupt */
#if defined(CONFIG_GICV2) || defined(CONFIG_GICV3)
ldr x0, =GICD_BASE
b gic_kick_secondary_cpus
#endif
ret
ENDPROC(smp_kick_all_cpus)

/*-----------------------------------------------------------------------*/

ENTRY(c_runtime_cpu_setup)
/* Relocate vBAR */
adr x0, vectors
switch_el x1, 3f, 2f, 1f
3: msr vbar_el3, x0
b 0f
2: msr vbar_el2, x0
b 0f
1: msr vbar_el1, x0
0:

ret
ENDPROC(c_runtime_cpu_setup)

WEAK(save_boot_params)
b save_boot_params_ret /* back to my caller */
ENDPROC(save_boot_params)
#endif

整体启动流程图:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
BootROM 跳 0x200000 (_start)
│
├─(可选) boot0.h 钩子 / b reset
▼
reset:
b save_boot_params ──(WEAK,可保存寄存器)──► save_boot_params_ret
▼
(可选) pie_fixup: 修正 .rela.dyn 重定位
▼
设置 VBAR_ELx = vectors,EL3 设 SCR/CPTR/CNTFRQ
▼
(可选) SMPEN 一致性位
▼
apply_core_errata (A57 errata,RK3588S 跳过)
▼
lowlevel_init (GIC 初始化;从核在此分流)
▼
主核? ──否──► spin_table / wfe 等待唤醒
│是
▼
master_cpu: bl _main ──► 进入 C 语言 (_main → board_init_f → ...)

2.4 reset

在 start.S 中可以看到,程序首先调用了 reset 函数,而 reset 函数又调用了 save_boot_params 函数,save_boot_params 又调用了 save_boot_params_ret 函数:

1
2
3
4
5
reset:
b save_boot_params
.globl save_boot_params_ret
save_boot_params_ret:
...

从 save_boot_params_ret 函数开始,程序将一路走到 bl _main 进入 C 世界。

程序首先设置了中断向量表:

1
2
adr	x0, vectors
switch_el x1, 3f, 2f, 1f
  • adr x0, vectors:把异常向量表 vectors 的运行时地址装入 x0。用 adr(PC 相对)而不是 ldr =,因为此时还没重定位,必须用位置无关方式取址。
  • switch_el x1, 3f, 2f, 1f:读当前异常等级(CurrentEL),按 EL3/EL2/EL1 分别跳到标签 3f/2f/1f。同时把等级值存到 x1。

接下来是 EL3、EL2、EL1 这三个分支。

然后进行板级底层初始化:

1
2
/* Processor specific initialization */
bl lowlevel_init

然后是主核/从核分流:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#if defined(CONFIG_ARMV8_SPIN_TABLE) && !defined(CONFIG_SPL_BUILD)
branch_if_master x0, x1, master_cpu
b spin_table_secondary_jump
/* never return */
#elif defined(CONFIG_ARMV8_MULTIENTRY)
branch_if_master x0, x1, master_cpu

slave_cpu: /* 从核 */
wfe
ldr x1, =CPU_RELEASE_ADDR
ldr x0, [x1]
cbz x0, slave_cpu
br x0 /* branch to the given address */
#endif /* CONFIG_ARMV8_MULTIENTRY */
master_cpu: /* 主核 */
bl _main

这里根据配置走不同路径,但核心是判断自己是主核还是从核:

  • 情况 A:CONFIG_ARMV8_SPIN_TABLE(且非 SPL)
1
2
branch_if_master x0, x1, master_cpu
b spin_table_secondary_jump
  • branch_if_master:读 MPIDR 判断是否主核(如 Aff0==0 等),是 → 跳 master_cpu。

  • 不是主核 → b spin_table_secondary_jump,进入 spin-table 等待逻辑,不再返回(注释明说 never return)。

  • 情况 B:CONFIG_ARMV8_MULTIENTRY

1
2
3
4
5
6
7
8
	branch_if_master x0, x1, master_cpu

slave_cpu: /* 从核 */
wfe
ldr x1, =CPU_RELEASE_ADDR
ldr x0, [x1]
cbz x0, slave_cpu
br x0
  • 主核 → master_cpu。
  • 从核进入 slave_cpu 循环:
    1. wfe:等待事件(低功耗睡眠,等 SEV 事件唤醒)。
    2. ldr x1, =CPU_RELEASE_ADDR:取"释放地址变量"的地址。
    3. ldr x0, [x1]:读该变量的值(由主核/BL31 写入)。
    4. cbz x0, slave_cpu:值为 0 → 还没被释放,回到 wfe 继续等。
    5. br x0:值非 0 → 跳到该地址执行(通常是内核的从核入口,如 Linux 的 secondary_startup)。

这是"从核自旋等待被唤醒"的经典模式:从核不往下走,而是睡在 wfe,反复检查 CPU_RELEASE_ADDR,被写入跳转地址后跳过去。

下面就进入到 _main 中。

2.5 补充:exceptions.S

这是 U-Boot ARMv8 的异常向量表与异常处理入口,文件通常是 arch/arm/cpu/armv8/exceptions.S。它负责两件事:

  1. 定义异常向量表 vectors(就是你在 start.S 里 adr x0, vectors 设置到 VBAR 的那张表);
  2. 定义异常的进入/退出流程:保存现场 → 调 C 处理函数 → 恢复现场 → eret 返回。
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
/*
* (C) Copyright 2013
* David Feng <fenghua@phytium.com.cn>
*
* SPDX-License-Identifier: GPL-2.0+
*/

#include <asm-offsets.h>
#include <config.h>
#include <asm/ptrace.h>
#include <asm/macro.h>
#include <linux/linkage.h>

/*
* Exception vectors.
*/
.align 11 /* 2KB(2^11)对齐,这是 ARMv8 架构硬性要求:VBAR_ELx 的低 11 位必须为 0 */
.globl vectors
vectors:
.align 7 /* Current EL Synchronous Thread */
stp x29, x30, [sp, #-16]!
bl _exception_entry
bl do_bad_sync
b exception_exit

.align 7 /* Current EL IRQ Thread */
stp x29, x30, [sp, #-16]!
bl _exception_entry
bl do_bad_irq
b exception_exit

.align 7 /* Current EL FIQ Thread */
stp x29, x30, [sp, #-16]!
bl _exception_entry
bl do_bad_fiq
b exception_exit

.align 7 /* Current EL Error Thread */
stp x29, x30, [sp, #-16]!
bl _exception_entry
bl do_bad_error
b exception_exit

.align 7 /* Current EL Synchronous Handler */
stp x29, x30, [sp, #-16]!
bl _exception_entry
bl do_sync
b exception_exit

.align 7 /* Current EL IRQ Handler */
stp x29, x30, [sp, #-16]!
bl _exception_entry
bl do_irq
b exception_exit

.align 7 /* Current EL FIQ Handler */
stp x29, x30, [sp, #-16]!
bl _exception_entry
bl do_fiq
b exception_exit

.align 7 /* Current EL Error Handler */
stp x29, x30, [sp, #-16]!
bl _exception_entry
bl do_error
b exception_exit

/*
* Enter Exception.
* This will save the processor state that is ELR/X0~X30
* to the stack frame.
*/
_exception_entry:
stp x27, x28, [sp, #-16]!
stp x25, x26, [sp, #-16]!
stp x23, x24, [sp, #-16]!
stp x21, x22, [sp, #-16]!
stp x19, x20, [sp, #-16]!
stp x17, x18, [sp, #-16]!
stp x15, x16, [sp, #-16]!
stp x13, x14, [sp, #-16]!
stp x11, x12, [sp, #-16]!
stp x9, x10, [sp, #-16]!
stp x7, x8, [sp, #-16]!
stp x5, x6, [sp, #-16]!
stp x3, x4, [sp, #-16]!
stp x1, x2, [sp, #-16]!

/* Could be running at EL3/EL2/EL1 */
switch_el x11, 3f, 2f, 1f
3: mrs x1, esr_el3
mrs x2, elr_el3
mrs x3, daif
mrs x4, vbar_el3
mrs x5, spsr_el3
sub x6, sp, #(8*30)
mrs x7, sctlr_el3
mrs x8, scr_el3
mrs x9, ttbr0_el3
b 0f
2: mrs x1, esr_el2
mrs x2, elr_el2
mrs x3, daif
mrs x4, vbar_el2
mrs x5, spsr_el2
sub x6, sp, #(8*30)
mrs x7, sctlr_el2
mrs x8, hcr_el2
mrs x9, ttbr0_el2
b 0f

1: mrs x1, esr_el1
mrs x2, elr_el1
mrs x3, daif
mrs x4, vbar_el1
mrs x5, spsr_el1
sub x6, sp, #(8*30)
mrs x7, sctlr_el1
mov x8, #0 /* Not used, EL1 don't have register, like 'scr_el1' */
mrs x9, ttbr0_el1
0:
stp x2, x0, [sp, #-16]!
stp x3, x1, [sp, #-16]!
stp x5, x4, [sp, #-16]!
stp x7, x6, [sp, #-16]!
stp x9, x8, [sp, #-16]!
mov x0, sp
ret


exception_exit:
add sp, sp, #(8*8)/* see: sys registers size of struct pt_regs */
ldp x2, x0, [sp],#16
switch_el x11, 3f, 2f, 1f
3: msr elr_el3, x2
b 0f
2: msr elr_el2, x2
b 0f
1: msr elr_el1, x2
0:
ldp x1, x2, [sp],#16
ldp x3, x4, [sp],#16
ldp x5, x6, [sp],#16
ldp x7, x8, [sp],#16
ldp x9, x10, [sp],#16
ldp x11, x12, [sp],#16
ldp x13, x14, [sp],#16
ldp x15, x16, [sp],#16
ldp x17, x18, [sp],#16
ldp x19, x20, [sp],#16
ldp x21, x22, [sp],#16
ldp x23, x24, [sp],#16
ldp x25, x26, [sp],#16
ldp x27, x28, [sp],#16
ldp x29, x30, [sp],#16
eret

三、lowlevel_init 函数

这是目录 arch/arm/cpu/armv8/lowlevel_init.S 下的 lowlevel_init。注意:它和之前看的 start.S 里那个 WEAK 的 lowlevel_init(做 GIC 初始化)不是同一个——那个是弱符号、可被覆盖;这个文件里的是强符号通用实现,专门负责建立临时栈再调 C 函数 s_init。

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
/*
* A lowlevel_init function that sets up the stack to call a C function to
* perform further init.
*
* SPDX-License-Identifier: GPL-2.0+
*/

#include <asm-offsets.h>
#include <config.h>
#include <linux/linkage.h>

ENTRY(lowlevel_init)
/*
* Setup a temporary stack. Global data is not available yet.
*/
#if defined(CONFIG_SPL_BUILD) && defined(CONFIG_SPL_STACK)
ldr w0, =CONFIG_SPL_STACK
#else
ldr w0, =CONFIG_SYS_INIT_SP_ADDR
#endif
bic sp, x0, #0xf /* 16-byte alignment for ABI compliance */

/*
* Save the old LR(passed in x29) and the current LR to stack
*/
stp x29, x30, [sp, #-16]!

/*
* Call the very early init function. This should do only the
* absolute bare minimum to get started. It should not:
*
* - set up DRAM
* - use global_data
* - clear BSS
* - try to start a console
*
* For boards with SPL this should be empty since SPL can do all of
* this init in the SPL board_init_f() function which is called
* immediately after this.
*/
bl s_init
ldp x29, x30, [sp]
ret
ENDPROC(lowlevel_init)

lowlevel_init 主要做了这几件事:

  1. 选择临时栈地址
    • SPL 构建且定义了 CONFIG_SPL_STACK → 用 CONFIG_SPL_STACK。
    • 否则 → 用 CONFIG_SYS_INIT_SP_ADDR。
  2. 设置并 16 字节对齐 SP
    • bic sp, x0, #0xf,满足 AAPCS64 ABI 对栈对齐的要求。
    • 此时 global_data、BSS、正式栈都还不可用,只能用这个"临时栈"。
  3. 保存 FP/LR
    • stp x29, x30, [sp, #-16]!,因为接下来 bl s_init 会覆盖 LR。
  4. 调用 s_init
    • 做最早期、最少量的 SoC/板级初始化。
    • 明确不做:初始化 DRAM、用 global_data、清 BSS、起控制台。
    • SPL 板子通常为空;非 SPL 板子做少量必要初始化(时钟、引脚、最早串口等)。
  5. 恢复 FP/LR 并返回
    • ldp x29, x30, [sp] + ret。
    • SP 不后增(有意简化),因为返回后 _main 会重设正式栈。

四、_main

_main 函数在文件 arch/arm/lib/crt0_64.S 中有定义, 是汇编世界进入 C 世界、并完成重定位的枢纽。它承接 start.S 最后的 bl _main,一路走到 board_init_r,之后不再返回。_main 函数执行可以大致分为如下4个部分:

  • 设置初始化 C 运行环境并调用 board_init_f 函数
  • 设置新的 sp 指针和 gd 指针,设置中间环境位,调用代码重定位
  • 重定位向量表
  • 设置最后的运行环境并调用 board_init_r 函数
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
ENTRY(_main)
/*
* 使能 I-cache,栈指针,对齐检查、SError
*/
#ifdef CONFIG_SPL_BUILD
mov x1, #CR_I
#else
mov x1, #0
#endif
switch_el x2, 3f, 2f, 1f
3: mrs x0, sctlr_el3
orr x0, x0, x1
msr sctlr_el3, x0
#ifndef CONFIG_SUPPORT_USBPLUG
msr daifclr, #4 /* Enable SError. SCR_EL3.EA=1 was already set in start.S */
#endif
b 0f
2: mrs x0, sctlr_el2
orr x0, x0, x1
msr sctlr_el2, x0

mrs x0, hcr_el2
orr x0, x0, #HCR_EL2_TGE
orr x0, x0, #HCR_EL2_AMO
#if CONFIG_IS_ENABLED(IRQ)
orr x0, x0, #HCR_EL2_IMO
#endif
msr hcr_el2, x0
msr daifclr, #4
b 0f
1: mrs x0, sctlr_el1
orr x0, x0, x1
msr sctlr_el1, x0
msr daifclr, #4
0:
isb

/*
* 建立 C 初始运行环境
*/
#if defined(CONFIG_TPL_BUILD) && defined(CONFIG_TPL_NEEDS_SEPARATE_STACK)
ldr x0, =(CONFIG_TPL_STACK)
#elif defined(CONFIG_SPL_BUILD) && defined(CONFIG_SPL_STACK)
ldr x0, =(CONFIG_SPL_STACK)
#else
ldr x0, =(CONFIG_SYS_INIT_SP_ADDR)
#endif
bic sp, x0, #0xf /* 16-byte alignment for ABI compliance */
mov x0, sp
bl board_init_f_alloc_reserve
mov sp, x0
/* set up gd here, outside any C code */
mov x18, x0 /* arm64 U-Boot 的 ABI 约定是 x18 = gd */
bl board_init_f_init_reserve
bl board_init_f_boot_flags

bl board_init_f

#if (defined(CONFIG_SPL_BUILD) && !defined(CONFIG_TPL_BUILD) && !defined(CONFIG_SPL_SKIP_RELOCATE)) || \
!defined(CONFIG_SPL_BUILD)
/*
* Set up intermediate environment (new sp and gd) and call
* relocate_code(addr_moni). Trick here is that we'll return
* 'here' but relocated.
*/
ldr x0, [x18, #GD_START_ADDR_SP] /* x0 <- gd->start_addr_sp */
bic sp, x0, #0xf /* 16-byte alignment for ABI compliance */
ldr x18, [x18, #GD_NEW_GD] /* x18 <- gd->new_gd */

#ifndef CONFIG_SKIP_RELOCATE_UBOOT
adr lr, relocation_return
#if CONFIG_POSITION_INDEPENDENT
/* Add in link-vs-runtime offset */
adr x0, _start /* x0 <- Runtime value of _start */
ldr x9, _TEXT_BASE /* x9 <- Linked value of _start */
sub x9, x9, x0 /* x9 <- Run-vs-link offset */
add lr, lr, x9
#endif
/* Add in link-vs-relocation offset */
ldr x9, [x18, #GD_RELOC_OFF] /* x9 <- gd->reloc_off */
add lr, lr, x9 /* new return address after relocation */
ldr x0, [x18, #GD_RELOCADDR] /* x0 <- gd->relocaddr */
b relocate_code
#endif

relocation_return:

/*
* SPL 专属的 gd/栈切换
*/
bl c_runtime_cpu_setup /* still call old routine */
#endif /* !CONFIG_SPL_BUILD */
#if defined(CONFIG_SPL_BUILD)
bl spl_relocate_stack_gd /* may return NULL */
/* set up gd here, outside any C code, if new stack is returned */
cmp x0, #0
csel x18, x0, x18, ne
/*
* Perform 'sp = (x0 != NULL) ? x0 : sp' while working
* around the constraint that conditional moves can not
* have 'sp' as an operand
*/
mov x1, sp
cmp x0, #0
csel x0, x0, x1, ne
mov sp, x0
#endif

/*
* 清空bss(写0)
*/
ldr x0, =__bss_start /* this is auto-relocated! */
ldr x1, =__bss_end /* this is auto-relocated! */
clear_loop:
str xzr, [x0], #8
cmp x0, x1
b.lo clear_loop

/* call board_init_r(gd_t *id, ulong dest_addr) */
mov x0, x18 /* gd_t */
ldr x1, [x18, #GD_RELOCADDR] /* dest_addr */
b board_init_r /* PC relative jump */

/* NOTREACHED - board_init_r() does not return */

ENDPROC(_main)

五、relocate_code

relocate_code 把 U-Boot 从当前地址整体拷贝到目标地址,用 _TEXT_BASE(链接基址常量)算出重定位偏移,遍历 .rela.dyn 只修正 R_AARCH64_RELATIVE 项(目标位置和 addend 都加偏移),再按需失效 I-cache、刷 D-cache,最后 ret 借助 _main 预先改好的 LR 跳到新位置的 relocation_return——它是"U-Boot 搬家"的执行者,也是链接脚本里 __image_copy_*、__rel_dyn_*、_TEXT_BASE 这些符号的实际消费者。

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
ENTRY(relocate_code)
stp x29, x30, [sp, #-32]! /* create a stack frame */
mov x29, sp
str x0, [sp, #16]
/*
* 将u-boot从flash拷贝到RAM
*/
adrp x1, __image_copy_start /* x1 <- address bits [31:12] */
add x1, x1, :lo12:__image_copy_start/* x1 <- address bits [11:00] */
subs x9, x0, x1 /* x9 <- Run to copy offset */
b.eq relocate_done /* skip relocation */
/*
* 计算"链接地址 vs 当前地址"的偏移
*/
ldr x1, _TEXT_BASE /* x1 <- Linked &__image_copy_start */
subs x9, x0, x1 /* x9 <- Link to copy offset */

/* 拷贝镜像 */
adrp x1, __image_copy_start /* x1 <- address bits [31:12] */
add x1, x1, :lo12:__image_copy_start/* x1 <- address bits [11:00] */
adrp x2, __image_copy_end /* x2 <- address bits [31:12] */
add x2, x2, :lo12:__image_copy_end /* x2 <- address bits [11:00] */
copy_loop:
ldp x10, x11, [x1], #16 /* copy from source address [x1] */
stp x10, x11, [x0], #16 /* copy to target address [x0] */
cmp x1, x2 /* until source end address [x2] */
b.lo copy_loop
str x0, [sp, #24]

/*
* 修正.rela.dyn重定位表
*/
adrp x2, __rel_dyn_start /* x2 <- address bits [31:12] */
add x2, x2, :lo12:__rel_dyn_start /* x2 <- address bits [11:00] */
adrp x3, __rel_dyn_end /* x3 <- address bits [31:12] */
add x3, x3, :lo12:__rel_dyn_end /* x3 <- address bits [11:00] */
fixloop:
ldp x0, x1, [x2], #16 /* (x0,x1) <- (SRC location, fixup) */
ldr x4, [x2], #8 /* x4 <- addend */
and x1, x1, #0xffffffff
cmp x1, #R_AARCH64_RELATIVE
bne fixnext

/* relative fix: store addend plus offset at dest location */
add x0, x0, x9
add x4, x4, x9
str x4, [x0]
fixnext:
cmp x2, x3
b.lo fixloop

relocate_done:
switch_el x1, 3f, 2f, 1f
bl hang
3: mrs x0, sctlr_el3
b 0f
2: mrs x0, sctlr_el2
b 0f
1: mrs x0, sctlr_el1
0: tbz w0, #2, 5f /* skip flushing cache if disabled */
tbz w0, #12, 4f /* skip invalidating i-cache if disabled */
ic iallu /* i-cache invalidate all */
isb sy
4: ldp x0, x1, [sp, #16]
bl __asm_flush_dcache_range
5: ldp x29, x30, [sp],#32
ret
ENDPROC(relocate_code)

整体执行流:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
relocate_code(x0 = 目标地址):
1. 建栈帧,存目标地址
2. 若 目标 == 当前镜像起点 → 跳过(已就位)
3. x9 = 目标 - _TEXT_BASE(链接基址)= 重定位偏移
4. 拷贝 [__image_copy_start, __image_copy_end) → 目标地址
5. 遍历 .rela.dyn:
R_AARCH64_RELATIVE 项:
目标位置 += x9
addend += x9
写回
6. 若 D-cache 使能:
失效 I-cache
刷 [目标地址, 目标结束) 的 D-cache
7. 恢复 FP/LR,ret → 跳到新位置的 relocation_return

六、board_init_f_init_reserve、board_init_f_boot_flag

board_init_f_init_reserve 和 board_init_f_alloc_reserve 函数,在 common/init/board_init.c 文件中定义,如下:

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
void board_init_f_init_reserve(ulong base)
{
struct global_data *gd_ptr;

/*
* 取gd指针
*/
gd_ptr = (struct global_data *)base;
/* 清零gd */
memset(gd_ptr, '\0', sizeof(*gd));
/* set GD unless architecture did it already */

/* 计算下一个可用地址,base 往后挪 sizeof(struct global_data) 向上取整到 16 字节 */
base += roundup(sizeof(struct global_data), 16);

/*
* record early malloc arena start.
* Use gd as it is now properly set for all architectures.
*/

#if CONFIG_VAL(SYS_MALLOC_F_LEN)
/* go down one 'early malloc arena' */
gd->malloc_base = base;
/* next alloc will be higher by one 'early malloc arena' size */
base += CONFIG_VAL(SYS_MALLOC_F_LEN);
#endif
}

/*
* Board-specific Platform code can init boot flags if needed
*/
__weak int board_init_f_boot_flags(void)
{
gd->baudrate = CONFIG_BAUDRATE; // 控制台波特率
gd->serial.baudrate = CONFIG_BAUDRATE; // 串口设备波特率
gd->serial.addr = CONFIG_DEBUG_UART_BASE; // 调试串口基地址
gd->serial.using_pre_serial = 0; // 是否使用pre-relocation串口,初始0

return 0;
}

board_init_f_alloc_reserve 函数的作用是根据传入参数是栈顶地址,计算出预留空间的底部,并将其返回。 主要是留出早期的 malloc 内存区域和gd内存区域。如果宏 CONFIG_MALLOC_F_ADDR 没有被定义,则为 malloc 预留部分内存空间,大小为 CONFIG_SYS_MALLOC_F_LEN;其次为 GD 变量(global_data 结构体类型)预留空间,并且对齐到 16 个字节的倍数。

board_init_f_boot_flags 则是弱符号钩子,默认往 gd 里填波特率和调试串口地址,供随后 board_init_f 使用。

六、board_init_f

这是 U-Boot 第一阶段初始化(pre-relocation)的总调度函数,位于 common/board_f.c。它的核心是按 init_sequence_f 列表依次执行所有初始化函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void board_init_f(ulong boot_flags)
{
gd->flags = boot_flags;
gd->have_console = 0;

if (initcall_run_list(init_sequence_f))
hang();

#if !defined(CONFIG_ARM) && !defined(CONFIG_SANDBOX) && \
!defined(CONFIG_EFI_APP) && !CONFIG_IS_ENABLED(X86_64)
/* NOTREACHED - jump_to_copy() does not return */
hang();
#endif
}

init_sequence_f 是一个函数指针数组,定义在同一文件里,类型通常是 init_fnc_t(返回 int)。数组里按严格顺序排列着第一阶段要做的所有事,例如(简化摘录):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
static init_fnc_t init_sequence_f[] = {
setup_mon_len, /* 设置gd的mon_len成员变量,也就是整个代码的长度 */
fdtdec_setup, /* 解析设备树 */
arch_cpu_init, /* CPU 初始化 */
mach_cpu_init, /* SoC 特定初始化 */
...
serial_init, /* 串口初始化 */
console_init_f, /* 早期控制台 */
...
dram_init, /* DRAM 初始化 */
...
reserve_round_4k, /* 预留空间(gd、malloc、栈、页表等) */
...
setup_reloc, /* 计算重定位地址/偏移 */
...
NULL,
};

以 NULL 结尾,作为遍历终止标志。注意:顺序不能乱:后面的函数依赖前面的结果(如 dram_init 后才能算重定位地址)。

下面是 initcall_run_list 的简化实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
int initcall_run_list(const init_fnc_t init_sequence[])
{
const init_fnc_t *init_fnc_ptr;

for (init_fnc_ptr = init_sequence; *init_fnc_ptr; ++init_fnc_ptr) {
int ret;
if ((ret = (*init_fnc_ptr)()) != 0) {
debug("initcall failed: %d\n", ret);
return ret;
}
}
return 0;
}

任何一个初始化函数失败 → initcall_run_list 返回非 0 → hang() 死循环(打印错误后停住,或直接卡死),等待挂起等待调试/复位。

七、board_init_r

这是 U-Boot 第二阶段初始化(post-relocation)的总调度函数,位于 common/board_r.c。它是 _main 最后 b board_init_r 跳进来的地方,此后永不返回——跑完初始化就进入主循环(命令行/引导内核)。

它和 board_init_f 是一对:board_init_f 是"搬家前",board_init_r 是"搬家后"。

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
void board_init_r(gd_t *new_gd, ulong dest_addr)
{
/*
* 设置新的 gd 指针
*/
#if CONFIG_IS_ENABLED(X86_64)
arch_setup_gd(new_gd);
#endif

#ifdef CONFIG_NEEDS_MANUAL_RELOC
int i;
#endif

#if !defined(CONFIG_X86) && !defined(CONFIG_ARM) && !defined(CONFIG_ARM64)
gd = new_gd;
#endif
gd->flags &= ~GD_FLG_LOG_READY;

#ifdef CONFIG_NEEDS_MANUAL_RELOC
for (i = 0; i < ARRAY_SIZE(init_sequence_r); i++)
init_sequence_r[i] += gd->reloc_off;
#endif

// 执行第二阶段初始化列表
if (initcall_run_list(init_sequence_r))
hang();

/* NOTREACHED - run_main_loop() does not return */
hang();
}

board_init_f 函数中,会初始化一些外设和 gd 的成员变量,但并没有初始化所有的外设,还需要一些后续工作,这些工作就是由 board_init_r 函数完成的,调用 initcall_run_list 函数执行初始化序列 init_sequence_r,init_sequence_r 是一个函数表,也定义在该文件中,部分代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
static init_fnc_t init_sequence_r[] = {
initr_trace, /* 初始化 trace */
initr_reloc, /* 标记重定位完成 */
initr_caches, /* 使能 cache */
initr_malloc, /* 初始化正式 malloc */
initr_bootstage, /* 启动阶段统计 */
initr_dm, /* 初始化驱动模型 (DM) */
initr_env, /* 初始化环境变量 */
initr_serial, /* 串口 */
initr_console_record, /* 控制台记录 */
...
initr_net, /* 网络 */
initr_mmc, /* MMC */
initr_usb, /* USB */
...
run_main_loop, /* 进入主循环(不返回) */
NULL,
};

八、run_main_loop

注意上一节中 init_sequence_r 的最后一个函数:run_main_loop, 在 common/board_r.c 文件定义,具体代码如下:

1
2
3
4
5
6
7
8
9
10
static int run_main_loop(void)
{
#ifdef CONFIG_SANDBOX
sandbox_main_loop_init();
#endif
/* main_loop() can return to retry autoboot, if so just run it again */
for (;;)
main_loop();
return 0;
}

uboot 启动以后会进入 3 秒倒计时,如果在 3 秒倒计时结束之前按下按下回车键,那么就会进入 uboot 的命令模式,如果倒计时结束以后都没有按下回车键,那么就会自动启动 Linux 内核,这个功能就是由 run_main_loop 函数来完成的。 main_loop 函数,在 common/main.c 文件中定义,具体代码如下:

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
void main_loop(void)
{
const char *s;

bootstage_mark_name(BOOTSTAGE_ID_MAIN_LOOP, "main_loop");

#ifdef CONFIG_VERSION_VARIABLE
env_set("ver", version_string); /* set version variable */
#endif /* CONFIG_VERSION_VARIABLE */

cli_init();

run_preboot_environment_command();

#if defined(CONFIG_UPDATE_TFTP)
update_tftp(0UL, NULL, NULL);
#endif /* CONFIG_UPDATE_TFTP */

s = bootdelay_process();
if (cli_process_fdt(&s))
cli_secure_boot_cmd(s);

autoboot_command(s);

cli_loop();
panic("No CLI available");
}

main_loop 函数主要工作:

  1. 调用 bootstage_mark_name 函数,打印出启动进度

  2. 如果宏 CONFIG_VERSION_VARIABLE 定义了就会执行函数 setenv,设置换将变量 ver 的值为 version_string,也就是设置版本号环境变量;

  3. 调用 cli_init 函数,初始化 hushshell 相关的变量

  4. 调用 bootdelay_process 函数,此函数会读取环境变量 bootdelay 和 bootcmd 的内容,然后将 bootdelay 的值赋值给全局变量 stored_bootdelay,返回值为环境变量 bootcmd 的值。

  5. autoboot_command 函数,此函数就是检查倒计时是否结束?倒计时结束之前有没有被打断?在文件common/autoboot.c 文件中定义,具体代码如下:

    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
    void autoboot_command(const char *s)
    {
    debug("### main_loop: bootcmd=\"%s\"\n", s ? s : "<UNDEFINED>");

    if (s && (stored_bootdelay == -2 ||
    (stored_bootdelay != -1 && !abortboot(stored_bootdelay)))) {
    bool lock;
    int prev;

    lock = autoboot_keyed() &&
    !IS_ENABLED(CONFIG_AUTOBOOT_KEYED_CTRLC);
    if (lock)
    prev = disable_ctrlc(1); /* disable Ctrl-C checking */

    run_command_list(s, -1, 0);

    if (lock)
    disable_ctrlc(prev); /* restore Ctrl-C checking */
    }

    if (IS_ENABLED(CONFIG_AUTOBOOT_USE_MENUKEY) &&
    menukey == AUTOBOOT_MENUKEY) {
    s = env_get("menucmd");
    if (s)
    run_command_list(s, -1, 0);
    }
    }

abortboot 函数,在文件 common/autoboot.c 文件中定义,具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
static int abortboot(int bootdelay)
{
int abort = 0;

if (bootdelay >= 0) {
if (autoboot_keyed())
abort = abortboot_key_sequence(bootdelay);
else
abort = abortboot_single_key(bootdelay);
}

if (IS_ENABLED(CONFIG_SILENT_CONSOLE) && abort)
gd->flags &= ~GD_FLG_SILENT;

return abort;
}

在倒计时结束之前有按键按下则执行函数 abortboot_single_key,abortboot_single_key 函数在 common/autoboot.c 文件中定义,具体代码如下:

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
static int abortboot_single_key(int bootdelay)
{
int abort = 0;
unsigned long ts;

printf("Hit any key to stop autoboot: %2d ", bootdelay);

/*
* Check if key already pressed
*/
if (tstc()) { /* we got a key press */
getchar(); /* consume input */
puts("\b\b\b 0");
abort = 1; /* don't auto boot */
}

while ((bootdelay > 0) && (!abort)) {
--bootdelay;
/* delay 1000 ms */
ts = get_timer(0);
do {
if (tstc()) { /* we got a key press */
int key;

abort = 1; /* don't auto boot */
bootdelay = 0; /* no more delay */
key = getchar();/* consume input */
if (IS_ENABLED(CONFIG_AUTOBOOT_USE_MENUKEY))
menukey = key;
break;
}
udelay(10000);
} while (!abort && get_timer(ts) < 1000);

printf("\b\b\b%2d ", bootdelay);
}

putc('\n');

return abort;
}

abortboot_single_key 函数主要工作:

  1. 倒计时的具体实现;

  2. 判断键盘是否有按下,也就是是否打断了倒计时,如果键盘按下的话就执行相应的分支。比如设置 abort 为 1,设置 bootdelay 为 0 等,最后跳出倒计时循环;

  3. 返回 abort 的值,如果倒计时自然结束,没有被打断 abort 就为 0,否则的话 abort 的值就为 1;

  4. 在 autoboot_command 函数中,如果倒计时自然结束那么就执行函数 run_command_list,此函数会执行参数 s 指定的一系列命令,也就是环境变量 bootcmd 的命令,bootcmd 里面保存着默认的启动命令,此时 Linux 内核正式启动!


U-Boot启动流程分析
http://example.com/2026/09/02/U-Boot启动流程分析/
作者
Yu xin
发布于
2026年9月2日
许可协议