LK · source analysis

thread_create_etc와 stack 소유권

thread_t와 stack을 준비해 SUSPENDED로 반환하고, 별도 resume에서 READY가 되는 경계를 읽습니다.

이 글은 LK upstream 고정 commit 1eb9917의 thread 구현을 설명한다. 실제 timer·CPU 동작은 선택한 platform 구성에서 확인한다.

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

생성된 thread는 언제 실행 가능한가?

thread_create()는 thread_create_etc(NULL, …, NULL, stack_size)를 호출한다. 함수는 thread_t와 stack을 확보하고 처음 상태를 THREAD_SUSPENDED로 설정한 뒤 architecture context를 준비해 전역 thread 목록에 등록한다. 생성만으로 run queue나 entry 실행에 도달하지 않는다 (kernel/thread.c:146, kernel/thread.c:223).

별도 thread_resume()에서 SUSPENDED→READY로 전환해 run queue head에 넣는다. 이어지는 로컬 yield, 원격 CPU reschedule, 최종 RUNNING 선택은 각각 조건이 있는 별도 단계다 (kernel/thread.c:275).

thread_t와 stack의 소유권 갈림길

그림 1. NULL 입력에 따라 달라지는 할당·해제 flag
thread_create()t == NULL · stack == NULL둘 다 malloc 대상. 성공하면 FREE_STRUCT / FREE_STACK flag를 기록한다.
thread_create_etc()caller가 t 또는 stack 제공 가능각 입력이 NULL인지에 따라 그 자원만 malloc하고 해당 FREE flag를 설정한다.
thread_t 필드entry, arg, priority, SUSPENDED, TLS 복사
stack + 초기 contextarch_thread_initialize(t)
thread_list 등록포인터 반환; run queue에는 없음
경계: 전역 목록에 보이는 SUSPENDED 객체와 scheduler가 선택할 READY 객체는 다르다.

THREAD_FLAG_FREE_STRUCT와 THREAD_FLAG_FREE_STACK은 동적으로 확보한 자원에만 선다. stack 할당 실패 시에는 자신이 할당한 thread_t만 즉시 해제한다 (kernel/thread.c:149, kernel/thread.c:173).

create, READY, RUNNING은 세 시점

그림 2. 생성과 resume의 조건부 연결
thread_create_etc()SUSPENDED, context 준비, 전역 목록 등록
thread_resume(t)SUSPENDED인 경우 READY + run queue head
scheduler 선택CPU 적합성·우선순위 검사 후 RUNNING
호출 당시 interrupts enabledSUSPENDED를 READY로 바꾼 경우에만 unlock 뒤 thread_yield() 호출. 대상 thread의 즉시 실행은 보장하지 않는다.
호출 당시 interrupts disabledresume가 로컬 yield를 생략한다. wakeup_cpu_for_thread()의 원격 reschedule 요청은 별도다.

wakeup_cpu_for_thread()는 pinning에 맞춰 mp_reschedule()을 요청한다. SMP 구현은 비활성·실시간 실행 중·로컬 CPU를 제외한 대상에 IPI를 보내며, non-SMP stub은 아무 일도 하지 않는다 (kernel/thread.c:101, kernel/mp.c:26, kernel/include/kernel/mp.h:86).

생성·공개·실행 조건

단계입력·조건성공 뒤 상태run queue
thread_create wrappert와 stack을 NULL로 전달두 자원을 동적 확보하려 시도없음
thread_create_etc객체·stack 확보 성공SUSPENDED; entry·arg·priority·TLS·초기 context 설정없음
thread_list 등록arch_thread_initialize 뒤전역 목록에 SUSPENDED 객체 공개없음
thread_resumet가 SUSPENDEDREADY; head 삽입·원격 CPU 요청있음
thread_resched선택 가능한 READY 객체선택된 thread가 RUNNING선택 시 제거

고정 구현의 thread_resume()은 이미 SUSPENDED가 아니면 queue 삽입을 건너뛰지만 NO_ERROR를 반환한다. 함수 주석의 ERR_NOT_SUSPENDED 문구와 구현이 다르므로 반환값만으로 새 실행을 판단하지 않는다 (kernel/thread.c:275).

상태와 자원 수명을 따로 읽기

두 그림은 객체의 소유권과 scheduler 공개 시점을 연결한다. runtime에서는 state, queue link, FREE flag를 함께 기록한다.

그림 3. 생성부터 종료까지의 상태 경계

생성은 SUSPENDED 객체를 등록하고, resume와 scheduler 선택이 뒤따라야 entry가 실행된다.

01객체·stack 확보
02초기 context 작성
03SUSPENDED + thread_list
04resume → READY
05선택 → RUNNING
06exit → DEATH
그림 4. 동적 자원과 외부 제공 자원의 회수

동적 자원에는 FREE flag가 있으며, 외부 제공 자원의 수명 책임은 호출자에게 남는다.

thread_create의 동적 자원

01thread_t malloc → FREE_STRUCT

02stack malloc → FREE_STACK

03join: DEATH 뒤 free

04detached exit: delayed_free

thread_create_etc의 외부 자원

01제공한 t에는 FREE_STRUCT 없음

02제공한 stack에는 FREE_STACK 없음

03호출자가 수명 책임을 유지

04각 자원별 NULL 여부를 확인

원본 코드

아래 코드는 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];

원본 발췌와 상태 전이 경계

기존 kernel/thread.c 122–210행과 보충 265–331행은 고정 원문과 일치해 그대로 보존했다. 첫 발췌의 함수 시작은 L146이고, L210은 TLS 복사 중간이다. 이어지는 초기 context·목록 등록·wrapper는 아래 원문이 결정한다.

생성 반환 직전과 thread_create wrapper

kernel/thread.c L206–225

 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];
 211
 212      /* set up the initial stack frame */
 213      arch_thread_initialize(t);
 214
 215      /* add it to the global thread list */
 216      THREAD_LOCK(state);
 217      list_add_head(&thread_list, &t->thread_list_node);
 218      THREAD_UNLOCK(state);
 219
 220      return t;
 221  }
 222
 223  thread_t *thread_create(const char *name, thread_start_routine entry, void *arg, int priority, size_t stack_size) {
 224      return thread_create_etc(NULL, name, entry, arg, priority, NULL, stack_size);
 225  }

thread_resume()는 SUSPENDED 상태에 한해 READY로 바꾸지만, wakeup_cpu_for_thread()와 NO_ERROR 반환은 조건문 바깥에 있다 (kernel/thread.c:275).

함께 읽어야 하는 원본 코드

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

thread_create_etc의 실제 작업

01

두 자원을 독립적으로 확보한다

t == NULL이면 thread_t를 malloc하고 FREE_STRUCT를 기록한다. stack == NULL이면 stack을 malloc하고 FREE_STACK을 기록한다. caller 제공 자원에는 해당 FREE flag를 세우지 않는다 (kernel/thread.c:149, kernel/thread.c:173).

02

스케줄 대상이 되기 전에 필드를 채운다

entry·arg·priority를 저장하고 SUSPENDED로 둔다. current thread의 TLS를 복사한 뒤 arch_thread_initialize(t)를 호출한다. 초기 frame의 정확한 layout은 선택한 architecture의 arch_thread_initialize 구현에 달려 있다 (kernel/thread.c:156, kernel/thread.c:206).

03

전역 목록과 run queue를 구분한다

생성 함수는 thread_lock 아래 thread_list에 등록하고 포인터를 반환한다. READY queue 삽입은 thread_resume()에 있다 (kernel/thread.c:215, kernel/thread.c:282).

04

실패 정리는 stack 할당 실패에서 본다

malloc한 stack을 얻지 못하면 자신이 malloc한 thread_t만 free하고 NULL을 반환한다. caller 제공 thread_t는 이 경로에서 해제하지 않는다. 목록 등록은 아직 일어나지 않았다 (kernel/thread.c:179).

05

resume 뒤에도 선택은 별도다

호출 때 interrupt가 enabled였고 SUSPENDED에서 READY로 바뀌었으면 unlock 후 thread_yield()를 호출한다. disabled였다면 로컬 yield가 없다. 우선순위와 CPU pinning에 맞는 후보를 scheduler가 선택해야 entry가 실행된다 (kernel/thread.c:279, kernel/thread.c:431).

소유권과 반환값에서 놓치기 쉬운 점

01

FREE flag는 두 자원에 각각 적용된다

join은 DEATH를 기다린 뒤 목록에서 제거하고 FREE_STACK·FREE_STRUCT에 따라 해제한다. detached thread는 exit 경로에서 소유 자원을 heap_delayed_free()로 넘긴다 (kernel/thread.c:307, kernel/thread.c:382).

02

stack option을 무조건적인 guard로 쓰지 않는다

THREAD_STACK_BOUNDS_CHECK일 때 padding을 더하고 패턴을 채운다. THREAD_STACK_HIGHWATER도 별도 compile-time option이다. 보드의 실제 설정과 architecture stack 초기화를 확인한다 (kernel/thread.c:173).

03

resume 주석과 반환 구현이 다르다

주석은 비정상 상태에서 ERR_NOT_SUSPENDED를 말하지만, 이 commit의 코드는 그 상태에서도 NO_ERROR를 반환한다. 재호출의 성공 여부를 반환값만으로 해석하지 않는다 (kernel/thread.c:265).

누가 보유하고 언제 회수하는가

대상생성 때회수 조건근거
thread_tNULL이면 malloc + FREE_STRUCTjoin 또는 detached exit의 flag 검사kernel/thread.c:149
stackNULL이면 malloc + FREE_STACKjoin의 free 또는 detached exit의 delayed_freekernel/thread.c:173
thread_list link초기 context 뒤 등록join 또는 detached exit에서 제거kernel/thread.c:215
run queue linkresume에서 READY가 될 때 삽입선택되면 get_top_thread에서 제거kernel/thread.c:282

상태 경계에서 확인할 증상

조건이 commit의 결과확인 지점
thread_t malloc 실패NULL 반환; stack 작업 전kernel/thread.c:149
stack malloc 실패자체 할당 thread_t만 free 뒤 NULLkernel/thread.c:179
resume 없이 생성만 함SUSPENDED·thread_list 등록 상태; entry 미실행kernel/thread.c:161
외부 stack 수명 종료LK가 그 stack을 소유·해제하지 않음; caller 수명 점검kernel/thread.c:189
priority 범위 부적합run_queue index 사용 전에 caller의 값 검증 필요kernel/thread.c:86

arch_thread_initialize()은 void 호출이며 이 함수 뒤 생성 경로에 별도 오류 반환 분기가 없다. architecture별 전제는 해당 구현에서 확인한다.

실제 LK 빌드에서 확인하기

ELF 경로는 선택한 project의 심볼이 남아 있는 산출물로 대체한다. nm 출력은 C 함수 선언문이 아니라 symbol 이름과 주소다.

목적명령 또는 계측판정 기준
symbol 위치nm -an <ELF> | grep -E '[[:space:]](thread_create_etc|thread_resume)$'선택한 빌드에 symbol이 남아 있을 때 주소 확인
상태 변화t->state와 list_in_list(&t->queue_node) 기록create 뒤 SUSPENDED. resume 내부의 잠금 구간에서 READY 전이를 기록하며, 반환 뒤 상태는 실행·대기·종료로 바뀔 수 있음
종료 후 관찰join 가능한 시험 thread 또는 수명을 보장한 trace 사용detached thread는 resume 반환 전에 종료·회수될 수 있으므로 반환 뒤 포인터를 무조건 읽지 않음
소유 flagt->flags·stack 주소 기록NULL 제공 여부와 FREE_STRUCT/FREE_STACK 일치
첫 실행entry 시작 로그에 CPU·thread 이름·시간 기록resume 호출 시각과 첫 실행 시각을 분리

세 가지 재현 질문

  1. 01
    create 직후와 resume 직후를 비교

    state, thread_list link, run queue link를 두 시점에 기록해 생성과 runnable 전이를 분리한다.

  2. 02
    제공 자원과 동적 자원을 분리

    thread_create_etc에 외부 t·stack을 전달한 경우와 NULL 입력을 비교해 FREE flag와 종료 후 owner의 해제 책임을 검증한다.

  3. 03
    interrupt 상태별 resume 관찰

    interrupt enabled/disabled 진입에서 로컬 yield 유무와 첫 entry 로그를 비교한다. 다른 CPU 요청은 별도 추적한다.

원문과 다음 글