Barebox · source analysis

Bootchooser의 A/B 시도 횟수와 우선순위

state에 저장한 priority와 remaining attempts로 target을 선택하고 실패 시 다음 slot으로 이동하는 정책을 읽습니다.

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

Series
16 / 19
Baseline
v2026.06.1
Commit
314c679eea2d
Source
common/bootchooser.c:326-414 (발췌 범위)

Bootchooser의 A/B 시도 횟수와 우선순위 단계에서 실제로 바뀌는 상태는 무엇인가?

선택 알고리즘과 영속 저장 시점을 함께 봐야 reset loop를 이해할 수 있다. 성공 판정 주체가 userspace인지 bootloader인지도 제품 정책으로 분리한다.

부팅을 시도한 target의 attempts 감소가 제어권 이전 전에 내구성 있게 저장되어야 무한 재시도를 막을 수 있다. 이 문장을 기준으로 코드를 위에서 아래로 읽으면, 함수 이름을 외우는 대신 어느 시점에 어떤 상태를 신뢰할 수 있는지 판단할 수 있다.

객체와 주소가 놓이는 구조

그림 1. Bootchooser의 A/B 시도 횟수와 우선순위에서 입력, 내부 상태, 출력의 경계
입력과 전제내부 상태외부로 공개되는 결과
01bootchooser
02target array
03priority/attempts
04state backend

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

실행 흐름

그림 2. 정상 경로의 주요 호출과 상태 전달
persistent state
load targets
filter attempts
choose priority
boot and decrement

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

단계별 입력과 출력

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

#단계진입 시 신뢰할 상태성공 뒤 남아야 할 상태다음 소비자
01persistent state부트 CPU의 동기 실행 문맥bootchooserload targets
02load targetspersistent state 완료 상태target arrayfilter attempts
03filter attemptsload targets 완료 상태priority/attemptschoose priority
04choose priorityfilter attempts 완료 상태state backendboot and decrement
05boot and decrementchoose priority 완료 상태state backend이 단계의 처리 결과를 사용하는 코드

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

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

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

그림 3. A/B target 선택과 attempts 저장

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

01state load
02target priority
03attempts > 0 filter
04tie-break
05attempts 감소
06state durable save
07target boot
08성공/next
그림 4. 정상 A/B 진행과 reset loop

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

정상

01A attempts 감소

02state commit

03A 실패 감지

04B 선택

05userspace 성공 표시

Reset loop

01RAM에서만 감소

02commit 전 reset

03A attempts 원복

04A 재선택

05복구 진입 불가

원본 코드

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

commit314c679eea2d0ca847c64d1b646a1cf91225c0ecanchor · L350struct bootchooser *bootchooser_get(void)
326/**
327 * bootchooser_reset_priorities - reset priorities of targets
328 *
329 * Reset the priorities counter of all targets to their default
330 * values.
331 */
332static void bootchooser_reset_priorities(struct bootchooser *bc)
333{
334	struct bootchooser_target *target;
335
336	bootchooser_for_each_target(bc, target)
337		bootchooser_target_set_priority(target, -1);
338}
339
340static struct bootchooser *bootchooser;
341
342/**
343 * bootchooser_get - get a reference to the bootchooser
344 *
345 * When no bootchooser is initialized this function allocates the bootchooser
346 * and initializes it with the different globalvars and state variables. The
347 * bootchooser is returned. Subsequent calls will return a reference to the same
348 * bootchooser.
349 */
350struct bootchooser *bootchooser_get(void)
351{
352	struct bootchooser *bc;
353	struct bootchooser_target *target;
354	char *targets, *str, *freep = NULL, *delim;
355	int ret, id = 1;
356	uint32_t last_chosen;
357	static int attempts_resetted;
358	uint32_t locked;
359
360	if (bootchooser) {
361		bootchooser->refs++;
362		return bootchooser;
363	}
364
365	bc = xzalloc(sizeof(*bc));
366
367	if (*state_prefix) {
368		if (IS_ENABLED(CONFIG_STATE)) {
369			char *state_devname;
370
371			delim = strchr(state_prefix, '.');
372			if (delim)
373				state_devname = xstrndup(state_prefix, delim - state_prefix);
374			else
375				state_devname = xstrdup(state_prefix);
376			bc->state_prefix = xstrdup(state_prefix);
377			bc->state = state_by_name(state_devname);
378			if (!bc->state) {
379				pr_err("Cannot get state '%s'\n",
380				       state_devname);
381				free(state_devname);
382				ret = -ENODEV;
383				goto err;
384			}
385			free(state_devname);
386		} else {
387			pr_err("barebox-state backend selected (nv.bootchooser.state_prefix=%s) but CONFIG_STATE is disabled\n",
388			       state_prefix);
389
390			ret = -ENODEV;
391			goto err;
392		}
393	} else {
394		bc->state_prefix = xstrdup("nv.bootchooser");
395
396		/* NV is available as a fallback, but shouldn't be used in
397		 * production, because it's not power-fail safe.
398		 *
399		 * Thus warn the user about their configuration.
400		 */
401		pr_warn("using non-redundant NV instead of barebox-state\n");
402	}
403
404	/* this is an optional value */
405	bc->attempts_locked = attempts_locked;
406	ret = getenv_u32(bc->state_prefix, "attempts_locked", &locked);
407	if (!ret && locked)
408		bc->attempts_locked = true;
409
410	if (bc->attempts_locked)
411		pr_debug("remaining attempt counter is locked\n");
412
413	INIT_LIST_HEAD(&bc->targets);
414

발췌 범위와 읽기 기준

원문 326-414줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 struct bootchooser *bootchooser_get(void)은 L350에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.

선택 알고리즘과 영속 저장 시점을 함께 봐야 reset loop를 이해할 수 있다. 성공 판정 주체가 userspace인지 bootloader인지도 제품 정책으로 분리한다.

함께 읽어야 하는 원본 코드

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

01. priority와 remaining attempts로 다음 target 선택

common/bootchooser.c 645-737줄이다.

filecommon/bootchooser.canchor · L655static struct bootchooser_target *bootchooser_get_target
645 * bootchooser_get_target - get the target that shall be booted next
646 * @bc:		The bootchooser
647 *
648 * This is the heart of the bootchooser. This function selects the next
649 * target to boot and returns it. The remaining_attempts counter of the
650 * selected target is decreased and the bootchooser state is saved to the
651 * backend.
652 *
653 * Return: The next target
654 */
655static struct bootchooser_target *bootchooser_get_target(struct bootchooser *bc)
656{
657	struct bootchooser_target *target;
658
659	list_for_each_entry(target, &bc->targets, list) {
660		if (bootchooser_target_ok(target, NULL))
661			goto found;
662	}
663
664	pr_err("No valid targets found:\n");
665	list_for_each_entry(target, &bc->targets, list)
666		pr_target(target);
667
668	return ERR_PTR(-ENOENT);
669
670found:
671	if (!bc->attempts_locked) {
672		target->remaining_attempts--;
673		if (bc->verbose)
674			pr_info("name=%s remaining_attempts %d\n", target->name,
675				target->remaining_attempts);
676	} else {
677		pr_info("Attempts are locked, not decreasing remaining_attempts\n");
678	}
679
680	if (bc->verbose)
681		pr_info("selected target '%s', boot '%s'\n", target->name, target->boot);
682
683	bc->last_chosen = target;
684
685	bootchooser_save(bc);
686
687	return target;
688}
689
690/**
691 * bootchooser_target_name - get the name of a target
692 * @target:	The target
693 *
694 * Given a bootchooser target this function returns its name.
695 *
696 * Return: The name of the target
697 */
698const char *bootchooser_target_name(struct bootchooser_target *target)
699{
700	return target->name;
701}
702
703/**
704 * bootchooser_target_by_name - get a target from name
705 * @bc:		The bootchooser
706 * @name:	The name of the target to retrieve
707 *
708 * Given a name this function returns the corresponding target.
709 *
710 * Return: The target if found, NULL otherwise
711 */
712struct bootchooser_target *bootchooser_target_by_name(struct bootchooser *bc,
713						      const char *name)
714{
715	struct bootchooser_target *target;
716
717	bootchooser_for_each_target(bc, target)
718		if (!strcmp(target->name, name))
719			return target;
720	return NULL;
721}
722
723/**
724 * bootchooser_target_set_attempts - set remaining attempts of a target
725 * @target:	The target to change
726 * @attempts:	The number of attempts
727 *
728 * This sets the number of remaining attempts for a bootchooser target.
729 * If @attempts is < 0 then the remaining attempts is reset to the default
730 * value.
731 *
732 * Return: 0 for success, negative error code otherwise
733 */
734int bootchooser_target_set_attempts(struct bootchooser_target *target, int attempts)
735{
736	if (attempts >= 0)
737		target->remaining_attempts = attempts;

내부 동작을 더 깊게 읽기

01

진입 조건을 먼저 고정한다

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

선택 알고리즘과 영속 저장 시점을 함께 봐야 reset loop를 이해할 수 있다. 성공 판정 주체가 userspace인지 bootloader인지도 제품 정책으로 분리한다.

02

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

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

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

03

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

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

04

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

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

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

05

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

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

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

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

01

priority와 remaining attempts는 서로 다른 필터다

먼저 bootable target과 attempts가 남은 대상을 가리고 priority로 선택한 뒤 동률 규칙을 적용한다. priority가 높아도 attempts가 0이면 제외되는지, 모든 target이 제외될 때 recovery가 무엇인지 확인한다.

target 배열 순서에 의존한 동률 처리는 제품마다 slot 편향을 만든다.

02

attempt 감소는 handoff 전에 durable해야 한다

kernel로 분기한 뒤 bootloader는 돌아오지 않으므로 시도 횟수를 언제 줄이고 state_save()를 완료하는지가 reset loop를 결정한다. storage write가 실패했는데도 boot하면 같은 slot을 무한 재시도할 수 있다.

감소 write 각 단계에 reset을 주입해 다음 boot의 선택을 확인한다.

03

성공 표시는 userspace와 bootloader 사이의 protocol이다

bootloader가 시도만 기록하고 userspace가 health check 뒤 slot을 successful로 올릴 수 있다. success marker, reset cause와 attempts reset 조건을 문서화한다.

watchdog reset, manual reset, update 직후 첫 boot를 같은 실패로 계산할지 제품 정책을 분리한다.

객체와 수명

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

실패 지점과 증상

#조건관찰되는 증상먼저 볼 단계
01attempt 저장 지연reset loopload targets
02동률 tie-break 불안정slot 편향filter attempts
03모든 target invalid복구 경로 없음choose priority

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

소스 밖에서 확인할 증거

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

#목적명령 또는 계측판정 기준
01빌드 구성make <board>_defconfig && make V=1Kconfig, linker section과 최종 barebox image 생성 명령을 보관한다.
02symbol과 section${CROSS_COMPILE}nm -n barebox | grep 'struct bootchooser *bootchooser_get'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
    A/B priority와 attempts 조합 표 작성

    load targets 진입 전후에 bootchooser의 주소·크기·반환값과 timestamp를 함께 남긴다.

  2. 02
    kernel 진입 직전 reset을 반복해 감소 확인

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

  3. 03
    모든 attempts 0에서 fallback 명령 확인

    choose priority 진입 전후에 priority/attempts의 주소·크기·반환값과 timestamp를 함께 남긴다.

원문과 다음 글