Barebox · source analysis

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

priority와 remaining_attempts로 대상을 고른 뒤, 조건부 횟수 감소·저장·재시도를 구분해 읽습니다.

v2026.06.1은 이 글의 소스 분석 기준입니다. 실제 제품에는 사용하는 Barebox 버전과 저장 백엔드의 전원 차단 내성을 별도로 검증하세요.

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

Bootchooser는 언제 다음 A/B 슬롯을 선택하는가?

대상은 우선순위 순으로 정렬한 뒤 priority > 0과 remaining_attempts > 0을 모두 만족하는 첫 항목을 고른다. attempts_locked가 켜지면 선택 규칙은 그대로지만 시도 횟수는 줄지 않는다.

선택 함수는 감소 뒤 bootchooser_save()를 호출하고도 반환값을 확인하지 않는다. 따라서 “저장 호출”과 “전원 차단 뒤에도 남는 기록”을 구분해야 한다. 같은 호출에서 B를 시도하는 것은 retry=1일 때의 경로다.

정책과 저장소의 경계

그림 1. 설정, 후보 목록, 저장소와 선택 결과
설정·저장메모리의 후보선택·기록
01 · BACKENDstate_prefix 설정: state
미설정: NV fallback
02 · LOADtarget별 priority·remaining_attempts
03 · ORDERpriority 내림차순 목록
04 · SELECT두 값이 0보다 큰 첫 target
저장 경계

선택 뒤의 bootchooser_save()는 state 또는 NV에 저장을 시도한다. NV fallback은 전원 차단 안전성이 없어 생산 환경에 권장되지 않는다.

이 구조에서 attempts_locked는 후보 필터가 아니라 선택 후 감소 여부를 제어한다. 동일 우선순위에 대한 별도 2차 정렬 키는 이 함수에 없다.

선택과 재시도의 순서

그림 2. bootchooser_get_target()에서 bootchooser_boot()까지
정렬된 target 중 유효한 첫 항목 검색
잠금이 꺼졌을 때만 attempts 감소
last_chosen 설정·저장 호출
선택한 boot entry 시도
실패 시 retry=1이면 첫 유효 대상 재탐색

유효 후보가 없으면 -ENOENT를 반환한다. retry=1도 매번 목록의 첫 유효 대상을 다시 찾으므로, 남은 횟수가 있으면 A를 재시도한 뒤 B로 넘어간다. retry=0이면 첫 실패 뒤 이 호출을 끝낸다.

단계별 상태와 검증 경계

선택과 저장을 같은 성공 사건으로 묶지 않고, 소스에서 보이는 변화와 장치에서 확인할 사항을 나누었다.

#단계입력 조건소스에서 바뀌는 상태확인할 결과
01대상 로드설정된 targets와 state/NVtarget을 생성해 priority 내림차순 목록에 추가priority, attempts, 정렬 결과
02후보 선택priority ≠ 0, attempts ≠ 0조건에 맞는 첫 target 반환 경로0인 target은 건너뛰는지
03시도 횟수attempts_locked꺼져 있으면 1 감소, 켜져 있으면 유지잠금 설정과 선택 전후 값
04저장 시도선택한 targetlast_chosen 설정, bootchooser_save() 호출백엔드 오류 로그와 재부팅 뒤 값
05부팅·재시도boot entry 결과와 retry실패 시 retry=1이면 첫 유효 대상부터 재탐색A 재시도·B 전환 시점과 별도 recovery 구성

④의 호출 지점은 저장 성공을 검증하지 않는다. 특히 NV fallback에서 전원 차단 뒤의 내구성을 가정하지 않는다.

한 번의 선택과 다음 부팅의 갈림길

다음 도식은 Barebox v2026.06.1의 함수 경계를 따라 그렸다. 저장 성공, 전원 차단 안전성, 같은 호출의 retry는 서로 다른 조건이다.

그림 3. A를 고른 한 번의 호출에서 확실히 일어나는 일

예: A의 priority=20, attempts=2; B의 priority=10, attempts=3. 두 대상 모두 유효하다.

01 · ORDERA가 B보다 앞
02 · FILTERA의 두 값이 0보다 큼
03 · LOCK잠금 OFF면 A: 2→1
ON이면 2 유지
04 · SAVElast_chosen=A
저장 호출
05 · BOOTA의 boot entry 시도
그림 4. 저장 및 재시도 설정에 따라 달라지는 결과

A의 남은 횟수가 있는 동안에는 retry가 켜져 있어도 A를 다시 고른다. 두 열은 조건부 경로이며 자동 보증이 아니다.

기록이 남은 경우

01state 백엔드 저장 결과를 확인

02A 실패 뒤 retry=1이면 A의 남은 횟수 동안 A 재시도, 0이면 B 탐색

03retry=0이면 호출 종료, 다음 부팅에서 A/B 재선택

04성공 시 외부에서 attempts 복원 또는 성공 처리

저장이 실패하거나 안전하지 않은 경우

01저장 오류 반환이 선택 경로에서 무시될 수 있음

02NV fallback은 전원 차단 안전성을 보장하지 않음

03reset 뒤 이전 attempts가 보이면 A 재선택 가능

04복구 boot target도 별도로 설정해야 함

원본 코드

아래 코드는 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에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.

이 발췌는 백엔드 선택과 대상 로드 일부를 보여 준다. 실제 선택·저장·재시도는 아래 관련 원본의 bootchooser_get_target(), bootchooser_save(), bootchooser_boot()에서 확인한다.

bootchooser -s는 last_boot_successful 메모리 flag를 세운다. 그 호출 자체가 현재 target의 attempts를 즉시 복원하는 것은 아니다. 새 인스턴스를 초기화하는 다음 bootchooser_get()가 저장된 last_chosen과 이 flag를 보고 기본 attempts를 적용한다. 이미 살아 있는 인스턴스는 참조만 늘리는 빠른 경로를 타므로 복원 시점도 구분한다.

함께 읽어야 하는 원본 코드

첫 코드 조각만으로 동작이 완성되지 않는 경우 호출 매크로, 객체 정의와 실제 실행 목록을 같은 페이지에 묶었다. 각 조각은 같은 기준 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

백엔드를 먼저 확정한다

state_prefix가 비어 있을 때만 NV fallback을 선택하며 전원 차단 안전성이 없다는 경고를 출력한다. 접두사가 설정되어 있으면 state 백엔드를 사용한다. 이때 CONFIG_STATE가 꺼져 있거나 지정한 state 인스턴스가 없으면 -ENODEV를 반환한다.

02

대상 목록은 우선순위로 정렬한다

bootchooser_get()은 각 target의 현재 priority와 remaining_attempts를 읽어 목록에 넣는다. bootchooser_get_target()은 정렬된 목록에서 두 값이 모두 0이 아닌 첫 대상을 고른다. 동률에 대한 별도 정책은 제품 설정과 실제 목록 순서로 검증한다.

03

잠금은 선택 이후의 감소만 막는다

attempts_locked가 참이어도 같은 유효성 검사를 한다. 단지 선택한 대상의 remaining_attempts--를 건너뛴다. 잠금과 retry=1을 함께 쓰면 실패한 슬롯을 계속 다시 고를 수 있으므로 제품 정책에서 조합을 확인한다.

04

저장 호출과 성공을 분리한다

선택 뒤 last_chosen을 기록하고 bootchooser_save(bc)를 호출하지만 그 반환값은 버린다. 저장 함수는 state/NV 오류를 반환하거나 로그에 남길 수 있다. 나중의 bootchooser_put()도 저장을 재시도하므로 어느 저장이 실제 성공했는지 보드에서 확인해야 한다.

05

실패 뒤의 다음 선택은 retry와 남은 횟수에 달렸다

bootchooser_boot_one()이 부팅할 entry를 찾지 못하거나 부팅이 실패하면 재시도 신호를 준다. retry=1이면 선택 함수를 다시 호출해 A의 남은 횟수부터 소진할 수 있다. retry=0이면 한 번의 실패로 끝낸다. recovery는 별도로 구성한 boot target이다.

A/B 정책에서 놓치기 쉬운 조건

01

priority 0과 attempts 0은 각각 제외 조건

priority가 높아도 attempts가 0이면 건너뛴다. reset_attempts와 reset_priorities 정책을 평가한 뒤에도 유효 후보가 없으면 -ENOENT다. Recovery는 boot.default="bootchooser recovery"처럼 별도로 구성할 수 있다.

02

시도 횟수 감소만으로 내구성이 생기지 않는다

선택 함수의 저장 오류 무시와 NV fallback의 전원 차단 위험을 함께 봐야 한다. state 백엔드라도 실제 저장 완료와 reset 뒤의 값을 시험 장치에서 검증한다.

03

성공 표시는 별도 동작이다

Barebox는 부팅한 시스템이 건강한지 스스로 판정하지 않는다. Linux userspace의 state 갱신, 또는 제품의 reset-reason 정책에 따른 bootchooser -s 등으로 남은 횟수를 명시적으로 복원해야 한다.

메모리와 저장 상태의 수명

대상만들어지는 시점유효 범위확인할 조건
struct bootchooserbootchooser_get()참조가 0이 되는 bootchooser_put()까지state 또는 NV 백엔드 선택
bootchooser_target 목록설정된 이름마다 생성·정렬최종 bootchooser_put()에서 해제priority, attempts, 정렬 순서
last_chosen대상을 고른 직후메모리 상태와 저장된 id를 구분저장 오류 및 재부팅 뒤 조회 값
state/NV의 runtime 값bootchooser_save() 시도백엔드와 전원 차단 조건에 의존저장 로그, 실제 재부팅 뒤 priority·attempts

실패 지점과 증상

#조건관찰되는 증상먼저 볼 단계
01저장 오류 또는 NV 전원 차단reset 뒤 횟수가 이전 값으로 보일 수 있음bootchooser_save()와 백엔드
02attempts_locked=1선택은 되지만 횟수가 줄지 않음잠금과 target 출력
03retry=0실패 뒤 같은 호출에서 재시도하지 않음bootchooser_boot()
04reset 정책 평가 뒤에도 유효 target 없음-ENOENT; recovery는 설정에 의존priority·attempts와 boot.default

저장 호출의 성공 여부와 장치에서 재부팅 뒤 읽히는 값을 별도로 기록해야 한다.

보드에서 확인할 증거

아래 명령과 계측은 시험 장치에서 수행한다. bootchooser -i도 참조 해제 시 저장 경로를 거치므로 운영 장치에서 무변경 조회라고 가정하지 않는다.

#목적명령 또는 계측판정 기준
01현재 후보bootchooser -i우선순위, 남은 횟수, disabled 이유, last chosen, 잠금 상태
02정책 설정global.bootchooser.targets, retry, reset_attempts, state_prefix, boot.default 확인A 재시도, B 전환, recovery 조건이 명시됐는지
03저장 오류Cannot save state 또는 Cannot save nv variables 로그 계측호출 뒤 저장 오류가 있었는지
04재부팅 뒤 값선택 직전·직후와 reset 뒤 bootchooser -i 비교선택된 슬롯의 attempts·last_chosen 변화가 실제로 남는지

시험 장치에서 확인할 실험

  1. 01
    후보 선택표

    A/B의 priority와 attempts에 0, 양수를 넣고 bootchooser -i의 순서를 비교한다. 동률에서는 실제 목록 순서를 기록한다.

  2. 02
    잠금과 retry를 분리

    동일한 실패 조건에서 attempts_locked와 retry를 각각 바꿔 감소 여부와 같은 호출의 다음 target 시도를 따로 관찰한다.

  3. 03
    백엔드와 reset 검증

    state/NV 설정, 저장 오류 로그, reset 뒤의 값을 나란히 기록한다. 의도적인 전원 차단 주입은 복구 가능한 시험 장치에서만 수행한다.

  4. 04
    성공·복구 경로

    명시적인 성공 표시 후 attempts 복원과, 모든 후보가 소진됐을 때 별도 recovery target 진입을 확인한다.

원문과 다음 글