QUESTION
State framework와 영속 변수 단계에서 실제로 바뀌는 상태는 무엇인가?
environment와 제품 상태를 구분한다. attempts, priority 같은 값의 type/width와 redundant/circular backend가 전원 차단을 견디는 방식을 본다.
새 state가 완전히 기록·검증되기 전에는 이전 유효 copy를 폐기하지 않아야 한다. 이 문장을 기준으로 코드를 위에서 아래로 읽으면, 함수 이름을 외우는 대신 어느 시점에 어떤 상태를 신뢰할 수 있는지 판단할 수 있다.
STRUCTURE
객체와 주소가 놓이는 구조
struct state / state backend buckets를 중심에 놓고 왼쪽의 입력이 어떤 검사를 거쳐 오른쪽 결과로 공개되는지 표시했다. 실제 디버깅에서는 각 블록의 주소와 크기를 로그에 대입한다.
CALL PATH
실행 흐름
화살표는 단순 호출 순서만 뜻하지 않는다. 각 단계가 성공을 반환할 때 다음 단계가 읽을 수 있는 상태가 무엇인지 함께 확인한다. 오류 반환이 발생하면 바로 다음 화살표로 진행하지 않고 해당 단계의 정리 경로를 따라간다.
STATE LEDGER
단계별 입력과 출력
각 단계의 입력과 처리 후 바뀌는 상태를 정리한 표다. 사용 중인 소스 버전에서 다른 필드를 변경한다면 그에 맞춰 표도 수정한다.
| # | 단계 | 진입 시 신뢰할 상태 | 성공 뒤 남아야 할 상태 | 다음 소비자 |
|---|---|---|---|---|
| 01 | DT state node | 부트 CPU의 동기 실행 문맥 | state object | state variables |
| 02 | state variables | DT state node 완료 상태 | typed variables | pack format |
| 03 | pack format | state variables 완료 상태 | backend format | storage buckets |
| 04 | storage buckets | pack format 완료 상태 | redundant buckets | persistent copy |
| 05 | persistent copy | storage buckets 완료 상태 | redundant buckets | 이 단계의 처리 결과를 사용하는 코드 |
분석 범위의 전제와 비교해, 다음 단계에 잘못된 입력을 넘긴 부분부터 조사한다.
VISUAL WALKTHROUGH
주소와 객체의 이동을 그림으로 읽기
아래 그림은 주소, 객체를 사용하는 기간, 제어권을 넘기는 시점을 중심으로 정리했다. 실제 주소와 크기는 사용 중인 보드의 bdinfo, 맵 파일과 링커 심벌로 확인한다.
호출 이름만 나열하지 않고, 각 단계가 다음 단계에 넘기는 상태를 기준으로 실행 순서를 표시한다.
두 열의 객체는 이름이 비슷해도 생성 시점, 사용 가능한 API와 해제 책임이 다르다.
Environment
01문자열·script 중심
02사용자 편집
03directory overlay
04saveenv 단위
05boot policy 입력
State
01DT typed schema
02고정 width
03redundant bucket
04generation/CRC
05attempts·priority
UPSTREAM SOURCE
원본 코드
아래 코드는 Barebox v2026.06.1의 common/state/state.c에서 20-108줄을 그대로 가져온 것이다. 설명을 위해 실제 코드를 가짜 의사 코드로 바꾸지 않았다.
20#include <errno.h>
21#include <fs.h>
22#include <crc.h>
23#include <init.h>
24#include <block.h>
25#include <linux/err.h>
26#include <linux/list.h>
27#include <linux/uuid.h>
28
29#include <linux/mtd/mtd-abi.h>
30#include <malloc.h>
31#include <state.h>
32#include <libbb.h>
33
34#include "state.h"
35
36/* list of all registered state instances */
37static LIST_HEAD(state_list);
38
39/**
40 * Save the state
41 * @param state
42 * @return
43 */
44int state_save(struct state *state)
45{
46 void *buf;
47 ssize_t len;
48 int ret;
49 struct state_backend_storage_bucket *bucket;
50 struct state_backend_storage *storage;
51
52 if (!state->dirty)
53 return 0;
54
55 ret = state->format->pack(state->format, state, &buf, &len);
56 if (ret) {
57 dev_err(&state->dev, "Failed to pack state with backend format %s, %d\n",
58 state->format->name, ret);
59 return ret;
60 }
61
62 storage = &state->storage;
63 if (state->keep_prev_content) {
64 bool has_content = 0;
65 list_for_each_entry(bucket, &storage->buckets, bucket_list)
66 has_content |= bucket->wrong_magic;
67 if (has_content) {
68 dev_err(&state->dev, "Found foreign content on backend, won't overwrite.\n");
69 ret = -EPERM;
70 goto out;
71 }
72 }
73
74 ret = state_storage_write(storage, buf, len);
75 if (ret) {
76 dev_err(&state->dev, "Failed to write packed state, %d\n", ret);
77 goto out;
78 }
79
80 state->dirty = 0;
81
82out:
83 free(buf);
84 return ret;
85}
86
87/**
88 * state_do_load - Loads a state from the backend
89 * @param state The state that should be updated to contain the loaded data
90 * @return 0 on success, -errno on failure. If no state is loaded the previous
91 * values remain in the state.
92 *
93 * This function uses the registered storage backend to read data. All data that
94 * we read is checked for integrity by the formatter. After that we unpack the
95 * data into our state.
96 */
97static int state_do_load(struct state *state, enum state_flags flags)
98{
99 void *buf = NULL;
100 ssize_t len;
101 int ret;
102
103 ret = state_storage_read(&state->storage, state->format,
104 state->magic, &buf, &len, flags);
105 if (ret) {
106 dev_err_state_init(&state->dev, ret, "format %s read failed\n",
107 state->format->name);
108 goto out;
READING CONTRACT
발췌 범위와 읽기 기준
원문 20-108줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 int state_save(struct state *state)은 L44에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.
environment와 제품 상태를 구분한다. attempts, priority 같은 값의 type/width와 redundant/circular backend가 전원 차단을 견디는 방식을 본다.
RELATED SOURCE
함께 읽어야 하는 원본 코드
첫 코드 조각만으로 동작이 완성되지 않는 경우 호출 매크로, 객체 정의와 실제 실행 목록을 같은 페이지에 묶었다. 각 조각은 같은 기준 commit에서 가져왔다.
01. backend에서 state를 읽고 typed variable에 반영
common/state/state.c 87-169줄이다.
87/**
88 * state_do_load - Loads a state from the backend
89 * @param state The state that should be updated to contain the loaded data
90 * @return 0 on success, -errno on failure. If no state is loaded the previous
91 * values remain in the state.
92 *
93 * This function uses the registered storage backend to read data. All data that
94 * we read is checked for integrity by the formatter. After that we unpack the
95 * data into our state.
96 */
97static int state_do_load(struct state *state, enum state_flags flags)
98{
99 void *buf = NULL;
100 ssize_t len;
101 int ret;
102
103 ret = state_storage_read(&state->storage, state->format,
104 state->magic, &buf, &len, flags);
105 if (ret) {
106 dev_err_state_init(&state->dev, ret, "format %s read failed\n",
107 state->format->name);
108 goto out;
109 }
110
111 ret = state->format->unpack(state->format, state, buf, len);
112 if (ret) {
113 dev_err(&state->dev, "Failed to unpack read data with format %s although verified, %d\n",
114 state->format->name, ret);
115 goto out;
116 }
117
118 state->init_from_defaults = 0;
119out:
120 state->dirty = !!ret; /* mark dirty on error */
121 free(buf);
122 return ret;
123}
124
125int state_load(struct state *state)
126{
127 return state_do_load(state, 0);
128}
129
130int state_load_no_auth(struct state *state)
131{
132 return state_do_load(state, STATE_FLAG_NO_AUTHENTICATION);
133}
134
135static int state_format_init(struct state *state, const char *backend_format,
136 struct device_node *node, const char *state_name)
137{
138 int ret;
139
140 if (!backend_format || !strcmp(backend_format, "raw")) {
141 ret = backend_format_raw_create(&state->format, node,
142 state_name, &state->dev);
143 } else if (!strcmp(backend_format, "dtb")) {
144 ret = backend_format_dtb_create(&state->format, &state->dev);
145 } else {
146 dev_err(&state->dev, "Invalid backend format %s\n",
147 backend_format);
148 return -EINVAL;
149 }
150
151 if (ret && ret != -EPROBE_DEFER)
152 dev_err(&state->dev, "Failed to initialize format %s, %d\n",
153 backend_format, ret);
154
155 return ret;
156}
157
158static void state_format_free(struct state_backend_format *format)
159{
160 if (!format)
161 return;
162
163 if (format->free)
164 format->free(format);
165}
166
167void state_backend_set_readonly(struct state *state)
168{
169 state_storage_set_readonly(&state->storage);
DETAILS
내부 동작을 더 깊게 읽기
진입 조건을 먼저 고정한다
DT state node에서 들어온 실행은 부트 CPU의 동기 실행 문맥에 놓여 있다. 이때 interrupt, MMU/cache, stack, heap 중 무엇이 이미 준비되었는지 소스의 호출자까지 올라가 확인한다. 같은 함수라도 SPL, relocation 전후, app thread처럼 호출 문맥이 달라지면 허용되는 API와 지연 시간이 달라진다.
environment와 제품 상태를 구분한다. attempts, priority 같은 값의 type/width와 redundant/circular backend가 전원 차단을 견디는 방식을 본다.
중심 객체의 생성과 공개를 나눈다
이 글의 중심 객체는 struct state / state backend buckets다. 메모리를 확보한 시점, 필드를 채운 시점, 전역 list나 다른 subsystem에 공개한 시점을 구분한다. 공개 뒤 오류가 발생한다면 목록에서 제거하고 child, buffer, reference를 역순으로 정리하는지 확인한다.
빌드 산출물 관점에서는 최종 부트로더 이미지 안에 해당 symbol과 section이 실제로 포함되었는지도 map과 objdump로 검증한다.
주소, 크기와 정렬을 계산한다
부트 코드에서는 주소 계산 오류를 주의해야 한다. 원본과 목적지의 주소 범위, 헤더에 기록된 데이터 크기, 블록·페이지 단위를 표로 정리하고 각 구간의 끝 주소를 계산한다. 끝 주소가 start + size - 1처럼 마지막 바이트를 가리키는지, 구간 바로 다음 주소를 가리키는지는 API 규약에서 확인한다.
성공 flag와 실제 완료 시점을 맞춘다
state variables → pack format → storage buckets 구간에서는 부분 초기화 상태가 생길 수 있다. flag, list insertion, callback 등록, storage write 완료 중 무엇이 성공의 기준인지 찾는다. hardware write나 DMA가 포함되면 함수 반환과 장치 완료가 같은 시점인지도 확인한다.
다른 CPU, 인터럽트 처리기, USB 완료 콜백, 셸 명령에서도 이 상태를 읽는다면 메모리 접근 순서와 잠금 범위를 함께 확인한다.
제어권을 넘기기 전에 확인할 조건을 정리한다
정상 경로는 persistent copy에서 끝난다. 이 단계가 함수 반환인지, scheduler 전환인지, 다른 image로의 비복귀 분기인지 구분한다. 비복귀 handoff라면 cache clean/invalidate, interrupt disable, 장치 quiesce, argument register와 FDT 또는 image address가 최종 점검 항목이다.
호출한 함수로 돌아오는 경로라면 오류와 일부 처리만 완료된 상태를 구분하는지 확인한다. 이어서 다음 후보를 시도할지, 복구 절차를 실행할지 살펴본다.
IMPLEMENTATION NOTES
구현을 읽을 때 놓치기 쉬운 부분
state variable은 DT가 정의한 type 계약을 가진다
name, type, width, enum과 default가 DT node에서 객체로 만들어지고 backend byte layout과 연결된다. signedness와 endian, field offset을 바꾸면 기존 persistent data와 호환되지 않을 수 있다.
DT schema 변경 시 version과 migration 정책을 둔다.
bucket 선택은 generation과 validity를 함께 본다
redundant/circular backend는 여러 copy의 magic, CRC와 generation을 비교해 최신 valid state를 고른다. counter wrap과 일부 header만 기록된 power-cut copy가 이전 valid copy를 이기지 않아야 한다.
각 write phase에 reset을 주입해 selection 결과를 표로 만든다.
runtime 변경과 durable commit을 구분한다
command로 variable을 바꿔도 state_save()가 성공하기 전에는 RAM 값일 뿐이다. attempts 감소처럼 boot 정책에 쓰는 값은 handoff 전에 storage flush까지 끝나야 한다.
save 실패가 caller에 전달되고 이전 copy를 valid 상태로 남기는지 확인한다.
OBJECT LIFETIME
객체와 수명
| 대상 | 만들어지는 시점 | 유효 범위 | 확인할 조건 |
|---|---|---|---|
struct state / state backend buckets | state variables | persistent copy 또는 오류 정리 완료까지 | 진입 전제와 상태 계약 |
| 입력 buffer / metadata | DT state node | parse와 검증이 끝날 때까지 | 길이, 정렬, 소유권, 변조 가능성 |
| 등록된 list / descriptor | pack format | 하위 시스템을 종료하거나 다음 이미지에 제어권을 넘길 때까지 | 중복 등록, 해제된 객체를 가리키는 포인터, 오류 후 자원 정리 |
| hardware 또는 persistent state | 실제 write/probe가 완료된 뒤 | reset 또는 명시적 해제·갱신까지 | 쓰기 완료, 시간 초과, 전원 차단, 이전 상태 복원 |
최종 부트로더 이미지 | link/image 생성 시점 | 다음 stage가 새 image로 교체할 때까지 | 적재 주소, 진입점, 섹션, 헤더의 일치 여부 |
FAILURE PATH
실패 지점과 증상
| # | 조건 | 관찰되는 증상 | 먼저 볼 단계 |
|---|---|---|---|
| 01 | DT type 불일치 | 값 truncation | state variables |
| 02 | bucket 선택 오류 | 오래된 generation load | pack format |
| 03 | write 중 reset | valid marker 손상 | storage buckets |
로그가 끊긴 함수뿐 아니라 그 함수에 주소, 크기, 플래그를 전달한 앞 단계도 조사한다. 오류 처리 후 등록된 객체나 하드웨어 설정이 그대로 남아 있는지도 확인한다.
EVIDENCE
소스 밖에서 확인할 증거
소스에서 파악한 동작을 실제 빌드 결과와 대상 보드의 로그로 확인한다. 아래 명령의 보드 이름과 툴체인 접두사는 사용 중인 빌드 환경에 맞게 바꾼다.
| # | 목적 | 명령 또는 계측 | 판정 기준 |
|---|---|---|---|
| 01 | 빌드 구성 | make <board>_defconfig && make V=1 | Kconfig, linker section과 최종 barebox image 생성 명령을 보관한다. |
| 02 | symbol과 section | ${CROSS_COMPILE}nm -n barebox | grep 'int state_save' | initcall, command, driver descriptor가 image에 남았는지 확인한다. |
| 03 | 주소와 resource | iomem | image, malloc, stack, device resource와 reserved 영역의 겹침을 확인한다. |
| 04 | device 상태 | devinfo; drvinfo; of_dump | DT node 생성, device 등록, driver probe를 서로 구분한다. |
| 05 | boot 정책 | boot -d -v; state -d | entry 탐색 결과와 persistent state가 실제 선택에 미친 영향을 확인한다. |
LAB
직접 확인할 실험
- 01state -d로 variable과 backend 확인
state variables진입 전후에 state object의 주소·크기·반환값과 timestamp를 함께 남긴다. - 02저장 중 reset 주입 후 이전/새 copy 선택 확인
pack format진입 전후에 typed variables의 주소·크기·반환값과 timestamp를 함께 남긴다. - 03DT default와 저장값 우선순위 비교
storage buckets진입 전후에 backend format의 주소·크기·반환값과 timestamp를 함께 남긴다.
PRIMARY REFERENCES