LK · source analysis

thread_create_etc와 stack 소유권

스레드 제어 블록과 스택을 할당하고 초기 CPU 실행 상태를 구성하는 과정을 살펴봅니다.

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

Series
05 / 20
Baseline
upstream 1eb9917
Commit
1eb99171efae
Source
kernel/thread.c:122-210 (발췌 범위)

thread_create_etc와 stack 소유권 단계에서 실제로 바뀌는 상태는 무엇인가?

thread object와 stack을 누가 할당했는지에 따라 종료 시 free 경로가 달라진다. 초기 상태가 suspended인 이유도 resume과 분리해 본다.

run queue에 들어가기 전 thread의 stack, entry, priority와 architecture context가 모두 유효해야 한다. 이 문장을 기준으로 코드를 위에서 아래로 읽으면, 함수 이름을 외우는 대신 어느 시점에 어떤 상태를 신뢰할 수 있는지 판단할 수 있다.

객체와 주소가 놓이는 구조

그림 1. thread_create_etc와 stack 소유권에서 입력, 내부 상태, 출력의 경계
입력과 전제내부 상태외부로 공개되는 결과
01thread object
02stack allocation
03saved context
04run queue links

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

실행 흐름

그림 2. 정상 경로의 주요 호출과 상태 전달
caller
allocate thread_t
allocate stack
arch_thread_initialize
suspended thread

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

단계별 입력과 출력

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

#단계진입 시 신뢰할 상태성공 뒤 남아야 할 상태다음 소비자
01caller부트 CPU의 동기 실행 문맥thread objectallocate thread_t
02allocate thread_tcaller 완료 상태stack allocationallocate stack
03allocate stackallocate thread_t 완료 상태saved contextarch_thread_initialize
04arch_thread_initializeallocate stack 완료 상태run queue linkssuspended thread
05suspended threadarch_thread_initialize 완료 상태run queue links이 단계의 처리 결과를 사용하는 코드

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

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

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

그림 3. thread_t와 kernel stack의 생성·공개·회수

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

01thread_t 확보
02stack 확보
03초기 register frame 작성
04THREAD_SUSPENDED
05thread_resume
06run queue·실행
07exit·join·free
그림 4. thread 객체와 stack의 소유권

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

동적 생성

01heap thread_t

02heap stack

03free on join/detach

04allocation failure unwind

05stack guard 확인

외부 객체·stack

01caller 소유 thread_t

02static/external stack

03framework free 금지

04owner lifetime 유지

05flags로 소유권 구분

원본 코드

아래 코드는 LK upstream 1eb9917의 kernel/thread.c에서 122-210줄을 그대로 가져온 것이다. 설명을 위해 실제 코드를 가짜 의사 코드로 바꾸지 않았다.

commit1eb99171efae98867d4be4a5bd6479ea03f43ac9anchor · L146thread_t *thread_create_etc
122 * This function creates a new thread.  The thread is initially suspended, so you
123 * need to call thread_resume() to execute it.
124 *
125 * @param  name        Name of thread
126 * @param  entry       Entry point of thread
127 * @param  arg         Arbitrary argument passed to entry()
128 * @param  priority    Execution priority for the thread.
129 * @param  stack_size  Stack size for the thread.
130 *
131 * Thread priority is an integer from 0 (lowest) to 31 (highest).  Some standard
132 * prioritys are defined in <kernel/thread.h>:
133 *
134 *  HIGHEST_PRIORITY
135 *  DPC_PRIORITY
136 *  HIGH_PRIORITY
137 *  DEFAULT_PRIORITY
138 *  LOW_PRIORITY
139 *  IDLE_PRIORITY
140 *  LOWEST_PRIORITY
141 *
142 * Stack size is typically set to DEFAULT_STACK_SIZE
143 *
144 * @return  Pointer to thread object, or NULL on failure.
145 */
146thread_t *thread_create_etc(thread_t *t, const char *name, thread_start_routine entry, void *arg, int priority, void *stack, size_t stack_size) {
147    unsigned int flags = 0;
148
149    if (!t) {
150        t = malloc(sizeof(thread_t));
151        if (!t)
152            return NULL;
153        flags |= THREAD_FLAG_FREE_STRUCT;
154    }
155
156    init_thread_struct(t, name);
157
158    t->entry = entry;
159    t->arg = arg;
160    t->priority = priority;
161    t->state = THREAD_SUSPENDED;
162    t->blocking_wait_queue = NULL;
163    t->wait_queue_block_ret = NO_ERROR;
164    thread_set_curr_cpu(t, -1);
165
166    t->retcode = 0;
167    wait_queue_init(&t->retcode_wait_queue);
168
169#if WITH_KERNEL_VM
170    t->aspace = NULL;
171#endif
172
173    /* create the stack */
174    if (!stack) {
175#if THREAD_STACK_BOUNDS_CHECK
176        stack_size += THREAD_STACK_PADDING_SIZE;
177        flags |= THREAD_FLAG_DEBUG_STACK_BOUNDS_CHECK;
178#endif
179        t->stack = malloc(stack_size);
180        if (!t->stack) {
181            if (flags & THREAD_FLAG_FREE_STRUCT)
182                free(t);
183            return NULL;
184        }
185        flags |= THREAD_FLAG_FREE_STACK;
186#if THREAD_STACK_BOUNDS_CHECK
187        memset(t->stack, STACK_DEBUG_BYTE, THREAD_STACK_PADDING_SIZE);
188#endif
189    } else {
190        t->stack = stack;
191    }
192#if THREAD_STACK_HIGHWATER
193    if (flags & THREAD_FLAG_DEBUG_STACK_BOUNDS_CHECK) {
194        memset(t->stack + THREAD_STACK_PADDING_SIZE, STACK_DEBUG_BYTE,
195               stack_size - THREAD_STACK_PADDING_SIZE);
196    } else {
197        memset(t->stack, STACK_DEBUG_BYTE, stack_size);
198    }
199#endif
200
201    t->stack_size = stack_size;
202
203    /* save whether or not we need to free the thread struct and/or stack */
204    t->flags = flags;
205
206    /* inherit thread local storage from the parent */
207    thread_t *current_thread = get_current_thread();
208    int i;
209    for (i=0; i < MAX_TLS_ENTRY; i++)
210        t->tls[i] = current_thread->tls[i];

발췌 범위와 읽기 기준

원문 122-210줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 thread_t *thread_create_etc은 L146에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.

thread object와 stack을 누가 할당했는지에 따라 종료 시 free 경로가 달라진다. 초기 상태가 suspended인 이유도 resume과 분리해 본다.

함께 읽어야 하는 원본 코드

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

01. 생성한 thread를 run queue에 넣는 thread_resume

kernel/thread.c 265-331줄이다.

filekernel/thread.canchor · L275status_t thread_resume(thread_t *t)
265/**
266 * @brief  Make a suspended thread executable.
267 *
268 * This function is typically called to start a thread which has just been
269 * created with thread_create()
270 *
271 * @param t  Thread to resume
272 *
273 * @return NO_ERROR on success, ERR_NOT_SUSPENDED if thread was not suspended.
274 */
275status_t thread_resume(thread_t *t) {
276    DEBUG_ASSERT(t->magic == THREAD_MAGIC);
277    DEBUG_ASSERT(t->state != THREAD_DEATH);
278
279    bool resched = false;
280    bool ints_disabled = arch_ints_disabled();
281    THREAD_LOCK(state);
282    if (t->state == THREAD_SUSPENDED) {
283        t->state = THREAD_READY;
284        insert_in_run_queue_head(t);
285        if (!ints_disabled) /* HACK, don't resced into bootstrap thread before idle thread is set up */
286            resched = true;
287    }
288
289    wakeup_cpu_for_thread(t);
290
291    THREAD_UNLOCK(state);
292
293    if (resched)
294        thread_yield();
295
296    return NO_ERROR;
297}
298
299status_t thread_detach_and_resume(thread_t *t) {
300    status_t err;
301    err = thread_detach(t);
302    if (err < 0)
303        return err;
304    return thread_resume(t);
305}
306
307status_t thread_join(thread_t *t, int *retcode, lk_time_t timeout) {
308    DEBUG_ASSERT(t->magic == THREAD_MAGIC);
309
310    THREAD_LOCK(state);
311
312    if (t->flags & THREAD_FLAG_DETACHED) {
313        /* the thread is detached, go ahead and exit */
314        THREAD_UNLOCK(state);
315        return ERR_THREAD_DETACHED;
316    }
317
318    /* wait for the thread to die */
319    if (t->state != THREAD_DEATH) {
320        status_t err = wait_queue_block(&t->retcode_wait_queue, timeout);
321        if (err < 0) {
322            THREAD_UNLOCK(state);
323            return err;
324        }
325    }
326
327    DEBUG_ASSERT(t->magic == THREAD_MAGIC);
328    DEBUG_ASSERT(t->state == THREAD_DEATH);
329    DEBUG_ASSERT(t->blocking_wait_queue == NULL);
330    DEBUG_ASSERT(!list_in_list(&t->queue_node));
331

내부 동작을 더 깊게 읽기

01

진입 조건을 먼저 고정한다

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

thread object와 stack을 누가 할당했는지에 따라 종료 시 free 경로가 달라진다. 초기 상태가 suspended인 이유도 resume과 분리해 본다.

02

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

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

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

03

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

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

04

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

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

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

05

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

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

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

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

01

thread 객체와 kernel stack은 별도 수명을 가진다

thread control block은 이름, priority, state, wait queue link와 stack 정보를 가진다. allocator가 둘을 따로 확보하는지 embedded stack을 쓰는지에 따라 생성 실패와 destroy 정리 순서가 달라진다.

생성 직후 thread는 runnable이 아닐 수 있으며 resume 전까지 caller가 인자와 entry가 참조하는 객체의 수명을 보장해야 한다.

02

초기 context frame이 첫 return을 가장한다

architecture code는 새 stack에 callee-saved register, entry trampoline과 argument를 배치해 scheduler restore가 함수 호출처럼 보이게 만든다. frame layout과 context switch assembly가 같은 구조 정의를 사용하는지 offset을 대조한다.

stack top alignment와 guard 영역, exception frame이 추가될 최악 깊이를 함께 계산한다.

03

detach, join과 exit는 소유권 정책이다

thread가 종료되어도 누군가 join하거나 reference를 놓을 때까지 object와 stack이 남을 수 있다. detached thread는 누가 최종 free를 수행하는지, exit path가 run queue와 wait queue에서 먼저 제거하는지 확인한다.

반복 생성·종료 실험에서 free heap과 thread list를 비교해 leak와 stale link를 찾는다.

객체와 수명

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

실패 지점과 증상

#조건관찰되는 증상먼저 볼 단계
01stack size 부족context/지역 변수 충돌allocate thread_t
02ownership flag 오류static stack freeallocate stack
03priority 범위 오류run queue 손상arch_thread_initialize

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

소스 밖에서 확인할 증거

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

#목적명령 또는 계측판정 기준
01빌드 구성make <project> -j1platform, target, app 선택과 linker 입력을 로그로 남긴다.
02symbol과 주소nm -n build-*/lk.elf | grep 'thread_t *thread_create_etc'init hook, app descriptor와 함수가 어느 주소에 놓였는지 확인한다.
03어셈블리 대조objdump -drS build-*/lk.elfthread 전환과 interrupt disable 구간의 실제 명령을 확인한다.
04초기화 순서init level 전후에 current_time_hires()와 함수 이름 기록level 내부 순서와 지연을 serial log로 남긴다.
05문맥 확인current_thread, interrupt state, stack pointer 기록함수가 bootstrap thread인지 scheduler 이후 thread인지 구분한다.

직접 확인할 실험

  1. 01
    thread dump에서 stack base/size 확인

    allocate thread_t 진입 전후에 thread object의 주소·크기·반환값과 timestamp를 함께 남긴다.

  2. 02
    작은 stack으로 overflow guard 동작 확인

    allocate stack 진입 전후에 stack allocation의 주소·크기·반환값과 timestamp를 함께 남긴다.

  3. 03
    create와 resume 사이 상태 flag 기록

    arch_thread_initialize 진입 전후에 saved context의 주소·크기·반환값과 timestamp를 함께 남긴다.

원문과 다음 글