Barebox · source analysis

BBU update handler와 self-update

보드가 등록한 update handler를 선택하고 새 Barebox image를 검증해 boot medium에 기록하는 흐름을 읽습니다.

표의 버전은 소스 분석 기준이며 최신 보안 버전 권고가 아닙니다. TF-A LTS 2.14.3 이후에는 보안 수정이 있습니다. 제품 적용 시 공식 변경 기록과 사용 플랫폼의 errata를 확인하세요.

Series
19 / 19
Baseline
v2026.06.1
Commit
314c679eea2d
Source
common/bbu.c:290-378 (발췌 범위)

BBU update handler와 self-update 단계에서 실제로 바뀌는 상태는 무엇인가?

generic BBU와 SoC/board handler의 책임을 나눈다. force flag가 건너뛰는 검사, erase granularity와 redundant boot copy 정책을 확인한다.

새 image가 검증되고 완전히 기록되기 전에는 현재 부팅 가능한 copy를 잃지 않아야 한다. 이 문장을 기준으로 코드를 위에서 아래로 읽으면, 함수 이름을 외우는 대신 어느 시점에 어떤 상태를 신뢰할 수 있는지 판단할 수 있다.

객체와 주소가 놓이는 구조

그림 1. BBU update handler와 self-update에서 입력, 내부 상태, 출력의 경계
입력과 전제내부 상태외부로 공개되는 결과
01bbu_handler
02input image
03target cdev
04update flags

struct bbu_handler / target cdev / update image를 중심에 놓고 왼쪽의 입력이 어떤 검사를 거쳐 오른쪽 결과로 공개되는지 표시했다. 실제 디버깅에서는 각 블록의 주소와 크기를 로그에 대입한다.

실행 흐름

그림 2. 정상 경로의 주요 호출과 상태 전달
board init
register handler
barebox-update
image validation
erase/write/verify

화살표는 단순 호출 순서만 뜻하지 않는다. 각 단계가 성공을 반환할 때 다음 단계가 읽을 수 있는 상태가 무엇인지 함께 확인한다. 오류 반환이 발생하면 바로 다음 화살표로 진행하지 않고 해당 단계의 정리 경로를 따라간다.

단계별 입력과 출력

각 단계의 입력과 처리 후 바뀌는 상태를 정리한 표다. 사용 중인 소스 버전에서 다른 필드를 변경한다면 그에 맞춰 표도 수정한다.

#단계진입 시 신뢰할 상태성공 뒤 남아야 할 상태다음 소비자
01board init부트 CPU의 동기 실행 문맥bbu_handlerregister handler
02register handlerboard init 완료 상태input imagebarebox-update
03barebox-updateregister handler 완료 상태target cdevimage validation
04image validationbarebox-update 완료 상태update flagserase/write/verify
05erase/write/verifyimage validation 완료 상태update flags이 단계의 처리 결과를 사용하는 코드

분석 범위의 전제와 비교해, 다음 단계에 잘못된 입력을 넘긴 부분부터 조사한다.

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

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

그림 3. barebox-update가 부팅 가능한 copy를 교체하는 순서

호출 이름만 나열하지 않고, 각 단계가 다음 단계에 넘기는 상태를 기준으로 실행 순서를 표시한다.

01handler 선택
02device·image type 확인
03force policy
04target range 계산
05erase
06payload write
07readback/flush
08metadata commit
그림 4. 단일 copy update와 redundant update

두 열의 객체는 이름이 비슷해도 생성 시점, 사용 가능한 API와 해제 책임이 다르다.

Single copy

01구현 단순

02erase 순간 위험

03복구 매체 필요

04전원 차단 취약

05ROM fallback 의존

Redundant

01inactive copy write

02readback 검증

03선택 metadata commit

04이전 copy 유지

05세대·우선순위 필요

원본 코드

아래 코드는 Barebox v2026.06.1의 common/bbu.c에서 290-378줄을 그대로 가져온 것이다. 설명을 위해 실제 코드를 가짜 의사 코드로 바꾸지 않았다.

commit314c679eea2d0ca847c64d1b646a1cf91225c0ecanchor · L314int bbu_register_handler(struct bbu_handler *handler)
290}
291EXPORT_SYMBOL(bbu_handlers_available);
292
293/*
294 * print a list of all registered update handlers
295 */
296void bbu_handlers_list(void)
297{
298	struct bbu_handler *handler;
299
300	if (list_empty(&bbu_image_handlers))
301		printf("(none)\n");
302
303	list_for_each_entry(handler, &bbu_image_handlers, list)
304		printf("%s%-11s -> %-10s\n",
305				handler->flags & BBU_HANDLER_FLAG_DEFAULT ?
306				"* " : "  ",
307				handler->name,
308				handler->devicefile);
309}
310
311/*
312 * register a new update handler
313 */
314int bbu_register_handler(struct bbu_handler *handler)
315{
316	if (bbu_find_handler_by_name(handler->name))
317		return -EBUSY;
318
319	if (handler->flags & BBU_HANDLER_FLAG_DEFAULT &&
320	    bbu_find_handler_by_name(NULL))
321		return -EBUSY;
322
323	list_add_tail(&handler->list, &bbu_image_handlers);
324
325	return 0;
326}
327
328struct bbu_std {
329	struct bbu_handler handler;
330	enum filetype filetype;
331};
332
333int bbu_mmcboot_handler(struct bbu_handler *handler, struct bbu_data *data,
334			int (*chained_handler)(struct bbu_handler *, struct bbu_data *))
335{
336	struct bbu_data _data = *data;
337	int ret;
338	char *devicefile = NULL, *bootpartvar = NULL, *bootackvar = NULL;
339	const char *bootpart;
340	const char *devname = devpath_to_name(data->devicefile);
341
342	ret = device_detect_by_name(devname);
343	if (ret) {
344		pr_err("Couldn't detect device '%s'\n", devname);
345		return ret;
346	}
347
348	ret = asprintf(&bootpartvar, "%s.boot", devname);
349	if (ret < 0)
350		return ret;
351
352	bootpart = getenv(bootpartvar);
353	if (!bootpart) {
354		ret = -ENOENT;
355		goto out;
356	}
357
358	if (!strcmp(bootpart, "boot0")) {
359		bootpart = "boot1";
360	} else {
361		bootpart = "boot0";
362	}
363
364	ret = asprintf(&devicefile, "/dev/%s.%s", devname, bootpart);
365	if (ret < 0)
366		goto out;
367
368	_data.devicefile = devicefile;
369
370	ret = chained_handler(handler, &_data);
371	if (ret < 0)
372		goto out;
373
374	if (handler->flags & BBU_HANDLER_FLAG_MMC_BOOT_ACK) {
375		ret = asprintf(&bootackvar, "%s.boot_ack", devname);
376		if (ret < 0)
377			goto out;
378

발췌 범위와 읽기 기준

원문 290-378줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 int bbu_register_handler(struct bbu_handler *handler)은 L314에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.

generic BBU와 SoC/board handler의 책임을 나눈다. force flag가 건너뛰는 검사, erase granularity와 redundant boot copy 정책을 확인한다.

함께 읽어야 하는 원본 코드

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

01. handler 선택 뒤 metadata 검사와 update를 수행

common/bbu.c 244-328줄이다.

filecommon/bbu.canchor · L254int barebox_update
244	ret = imd_verify_crc32((void *)data->image, data->len);
245	if (ret == -EILSEQ && !(data->flags & BBU_FLAG_FORCE))
246		return ret;
247
248	return 0;
249}
250
251/*
252 * do a barebox update with data from *data
253 */
254int barebox_update(struct bbu_data *data, struct bbu_handler *handler)
255{
256	int ret;
257
258	if (!data->image && !data->imagefile &&
259	    !(handler->flags & BBU_HANDLER_CAN_REFRESH)) {
260		pr_err("No Image file given\n");
261		return -EINVAL;
262	}
263
264	if (!data->handler_name)
265		data->handler_name = handler->name;
266
267	if (!data->devicefile)
268		data->devicefile = handler->devicefile;
269
270	ret = bbu_check_metadata(data);
271	if (ret)
272		return ret;
273
274	ret = handler->handler(handler, data);
275	if (ret) {
276		printf("update %s\n", (ret == -EINTR) ? "aborted" : "failed");
277		return ret;
278	}
279
280	printf("update succeeded\n");
281	return 0;
282}
283
284/*
285 * report whether any update handlers have been registered so far
286 */
287bool bbu_handlers_available(void)
288{
289	return !list_empty(&bbu_image_handlers);
290}
291EXPORT_SYMBOL(bbu_handlers_available);
292
293/*
294 * print a list of all registered update handlers
295 */
296void bbu_handlers_list(void)
297{
298	struct bbu_handler *handler;
299
300	if (list_empty(&bbu_image_handlers))
301		printf("(none)\n");
302
303	list_for_each_entry(handler, &bbu_image_handlers, list)
304		printf("%s%-11s -> %-10s\n",
305				handler->flags & BBU_HANDLER_FLAG_DEFAULT ?
306				"* " : "  ",
307				handler->name,
308				handler->devicefile);
309}
310
311/*
312 * register a new update handler
313 */
314int bbu_register_handler(struct bbu_handler *handler)
315{
316	if (bbu_find_handler_by_name(handler->name))
317		return -EBUSY;
318
319	if (handler->flags & BBU_HANDLER_FLAG_DEFAULT &&
320	    bbu_find_handler_by_name(NULL))
321		return -EBUSY;
322
323	list_add_tail(&handler->list, &bbu_image_handlers);
324
325	return 0;
326}
327
328struct bbu_std {

내부 동작을 더 깊게 읽기

01

진입 조건을 먼저 고정한다

board init에서 들어온 실행은 부트 CPU의 동기 실행 문맥에 놓여 있다. 이때 interrupt, MMU/cache, stack, heap 중 무엇이 이미 준비되었는지 소스의 호출자까지 올라가 확인한다. 같은 함수라도 SPL, relocation 전후, app thread처럼 호출 문맥이 달라지면 허용되는 API와 지연 시간이 달라진다.

generic BBU와 SoC/board handler의 책임을 나눈다. force flag가 건너뛰는 검사, erase granularity와 redundant boot copy 정책을 확인한다.

02

중심 객체의 생성과 공개를 나눈다

이 글의 중심 객체는 struct bbu_handler / target cdev / update image다. 메모리를 확보한 시점, 필드를 채운 시점, 전역 list나 다른 subsystem에 공개한 시점을 구분한다. 공개 뒤 오류가 발생한다면 목록에서 제거하고 child, buffer, reference를 역순으로 정리하는지 확인한다.

빌드 산출물 관점에서는 최종 부트로더 이미지 안에 해당 symbol과 section이 실제로 포함되었는지도 map과 objdump로 검증한다.

03

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

부트 코드에서는 주소 계산 오류를 주의해야 한다. 원본과 목적지의 주소 범위, 헤더에 기록된 데이터 크기, 블록·페이지 단위를 표로 정리하고 각 구간의 끝 주소를 계산한다. 끝 주소가 start + size - 1처럼 마지막 바이트를 가리키는지, 구간 바로 다음 주소를 가리키는지는 API 규약에서 확인한다.

04

성공 flag와 실제 완료 시점을 맞춘다

register handler → barebox-update → image validation 구간에서는 부분 초기화 상태가 생길 수 있다. flag, list insertion, callback 등록, storage write 완료 중 무엇이 성공의 기준인지 찾는다. hardware write나 DMA가 포함되면 함수 반환과 장치 완료가 같은 시점인지도 확인한다.

다른 CPU, 인터럽트 처리기, USB 완료 콜백, 셸 명령에서도 이 상태를 읽는다면 메모리 접근 순서와 잠금 범위를 함께 확인한다.

05

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

정상 경로는 erase/write/verify에서 끝난다. 이 단계가 함수 반환인지, scheduler 전환인지, 다른 image로의 비복귀 분기인지 구분한다. 비복귀 handoff라면 cache clean/invalidate, interrupt disable, 장치 quiesce, argument register와 FDT 또는 image address가 최종 점검 항목이다.

호출한 함수로 돌아오는 경로라면 오류와 일부 처리만 완료된 상태를 구분하는지 확인한다. 이어서 다음 후보를 시도할지, 복구 절차를 실행할지 살펴본다.

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

01

generic BBU와 board handler의 책임을 나눈다

공통 layer는 handler 선택, image open과 flags를 관리하고 board/SoC handler는 ROM format, target offset, erase/write와 redundancy를 안다. force flag가 어떤 validation만 건너뛰는지 확인한다.

handler name과 default 여부가 여러 boot medium에서 모호하지 않아야 한다.

02

현재 부팅 가능한 copy를 마지막까지 보존한다

단일 copy를 erase한 뒤 write하는 방식은 power cut에 취약하다. inactive slot에 새 image를 완전히 기록·검증하고 boot selector를 마지막에 원자적으로 바꾸는 순서를 선호한다.

redundant header나 SoC boot copy가 있다면 generation과 fallback 동작을 실제 reset으로 검증한다.

03

image validation과 storage verify는 다른 검사다

header와 architecture를 확인해도 write 과정의 bit error, 잘못된 offset과 cache flush는 잡지 못한다. write 뒤 readback hash와 ROM이 읽는 최종 byte layout을 확인한다.

erase, write, verify, selector update 각 지점에 오류와 reset을 주입해 부팅 가능한 copy가 남는지 표로 기록한다.

객체와 수명

대상만들어지는 시점유효 범위확인할 조건
struct bbu_handler / target cdev / update imageregister handlererase/write/verify 또는 오류 정리 완료까지진입 전제와 상태 계약
입력 buffer / metadataboard initparse와 검증이 끝날 때까지길이, 정렬, 소유권, 변조 가능성
등록된 list / descriptorbarebox-update하위 시스템을 종료하거나 다음 이미지에 제어권을 넘길 때까지중복 등록, 해제된 객체를 가리키는 포인터, 오류 후 자원 정리
hardware 또는 persistent state실제 write/probe가 완료된 뒤reset 또는 명시적 해제·갱신까지쓰기 완료, 시간 초과, 전원 차단, 이전 상태 복원
최종 부트로더 이미지link/image 생성 시점다음 stage가 새 image로 교체할 때까지적재 주소, 진입점, 섹션, 헤더의 일치 여부

실패 지점과 증상

#조건관찰되는 증상먼저 볼 단계
01잘못된 handler 선택다른 medium overwriteregister handler
02erase 후 write 실패부팅 불가barebox-update
03image type 검사 우회ROM이 거부image validation

로그가 끊긴 함수뿐 아니라 그 함수에 주소, 크기, 플래그를 전달한 앞 단계도 조사한다. 오류 처리 후 등록된 객체나 하드웨어 설정이 그대로 남아 있는지도 확인한다.

소스 밖에서 확인할 증거

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

#목적명령 또는 계측판정 기준
01빌드 구성make <board>_defconfig && make V=1Kconfig, linker section과 최종 barebox image 생성 명령을 보관한다.
02symbol과 section${CROSS_COMPILE}nm -n barebox | grep 'int bbu_register_handler'initcall, command, driver descriptor가 image에 남았는지 확인한다.
03주소와 resourceiomemimage, malloc, stack, device resource와 reserved 영역의 겹침을 확인한다.
04device 상태devinfo; drvinfo; of_dumpDT node 생성, device 등록, driver probe를 서로 구분한다.
05boot 정책boot -d -v; state -dentry 탐색 결과와 persistent state가 실제 선택에 미친 영향을 확인한다.

직접 확인할 실험

  1. 01
    barebox-update -l로 handler 목록 확인

    register handler 진입 전후에 bbu_handler의 주소·크기·반환값과 timestamp를 함께 남긴다.

  2. 02
    dry-run 또는 작은 test cdev로 offset 검증

    barebox-update 진입 전후에 input image의 주소·크기·반환값과 timestamp를 함께 남긴다.

  3. 03
    write 중 reset을 주입해 redundant copy 부팅 확인

    image validation 진입 전후에 target cdev의 주소·크기·반환값과 timestamp를 함께 남긴다.

원문과 다음 글