QUESTION
생성된 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).
STRUCTURE
thread_t와 stack의 소유권 갈림길
THREAD_FLAG_FREE_STRUCT와 THREAD_FLAG_FREE_STACK은 동적으로 확보한 자원에만 선다. stack 할당 실패 시에는 자신이 할당한 thread_t만 즉시 해제한다 (kernel/thread.c:149, kernel/thread.c:173).
CALL PATH
create, READY, RUNNING은 세 시점
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).
STATE LEDGER
생성·공개·실행 조건
| 단계 | 입력·조건 | 성공 뒤 상태 | run queue |
|---|---|---|---|
| thread_create wrapper | t와 stack을 NULL로 전달 | 두 자원을 동적 확보하려 시도 | 없음 |
| thread_create_etc | 객체·stack 확보 성공 | SUSPENDED; entry·arg·priority·TLS·초기 context 설정 | 없음 |
| thread_list 등록 | arch_thread_initialize 뒤 | 전역 목록에 SUSPENDED 객체 공개 | 없음 |
| thread_resume | t가 SUSPENDED | READY; head 삽입·원격 CPU 요청 | 있음 |
| thread_resched | 선택 가능한 READY 객체 | 선택된 thread가 RUNNING | 선택 시 제거 |
고정 구현의 thread_resume()은 이미 SUSPENDED가 아니면 queue 삽입을 건너뛰지만 NO_ERROR를 반환한다. 함수 주석의 ERR_NOT_SUSPENDED 문구와 구현이 다르므로 반환값만으로 새 실행을 판단하지 않는다 (kernel/thread.c:275).
VISUAL WALKTHROUGH
상태와 자원 수명을 따로 읽기
두 그림은 객체의 소유권과 scheduler 공개 시점을 연결한다. runtime에서는 state, queue link, FREE flag를 함께 기록한다.
생성은 SUSPENDED 객체를 등록하고, resume와 scheduler 선택이 뒤따라야 entry가 실행된다.
동적 자원에는 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 여부를 확인
UPSTREAM SOURCE
원본 코드
아래 코드는 LK upstream 1eb9917의 kernel/thread.c에서 122-210줄을 그대로 가져온 것이다.
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];
READING CONTRACT
원본 발췌와 상태 전이 경계
기존 kernel/thread.c 122–210행과 보충 265–331행은 고정 원문과 일치해 그대로 보존했다. 첫 발췌의 함수 시작은 L146이고, L210은 TLS 복사 중간이다. 이어지는 초기 context·목록 등록·wrapper는 아래 원문이 결정한다.
생성 반환 직전과 thread_create wrapper
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).
RELATED SOURCE
함께 읽어야 하는 원본 코드
첫 코드 조각만으로 동작이 완성되지 않는 경우 호출 매크로, 객체 정의와 실제 실행 목록을 같은 페이지에 묶었다. 각 조각은 같은 기준 commit에서 가져왔다.
01. 생성한 thread를 run queue에 넣는 thread_resume
kernel/thread.c 265-331줄이다.
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
DETAILS
thread_create_etc의 실제 작업
두 자원을 독립적으로 확보한다
t == NULL이면 thread_t를 malloc하고 FREE_STRUCT를 기록한다. stack == NULL이면 stack을 malloc하고 FREE_STACK을 기록한다. caller 제공 자원에는 해당 FREE flag를 세우지 않는다 (kernel/thread.c:149, kernel/thread.c:173).
스케줄 대상이 되기 전에 필드를 채운다
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).
전역 목록과 run queue를 구분한다
생성 함수는 thread_lock 아래 thread_list에 등록하고 포인터를 반환한다. READY queue 삽입은 thread_resume()에 있다 (kernel/thread.c:215, kernel/thread.c:282).
실패 정리는 stack 할당 실패에서 본다
malloc한 stack을 얻지 못하면 자신이 malloc한 thread_t만 free하고 NULL을 반환한다. caller 제공 thread_t는 이 경로에서 해제하지 않는다. 목록 등록은 아직 일어나지 않았다 (kernel/thread.c:179).
resume 뒤에도 선택은 별도다
호출 때 interrupt가 enabled였고 SUSPENDED에서 READY로 바뀌었으면 unlock 후 thread_yield()를 호출한다. disabled였다면 로컬 yield가 없다. 우선순위와 CPU pinning에 맞는 후보를 scheduler가 선택해야 entry가 실행된다 (kernel/thread.c:279, kernel/thread.c:431).
IMPLEMENTATION NOTES
소유권과 반환값에서 놓치기 쉬운 점
FREE flag는 두 자원에 각각 적용된다
join은 DEATH를 기다린 뒤 목록에서 제거하고 FREE_STACK·FREE_STRUCT에 따라 해제한다. detached thread는 exit 경로에서 소유 자원을 heap_delayed_free()로 넘긴다 (kernel/thread.c:307, kernel/thread.c:382).
stack option을 무조건적인 guard로 쓰지 않는다
THREAD_STACK_BOUNDS_CHECK일 때 padding을 더하고 패턴을 채운다. THREAD_STACK_HIGHWATER도 별도 compile-time option이다. 보드의 실제 설정과 architecture stack 초기화를 확인한다 (kernel/thread.c:173).
resume 주석과 반환 구현이 다르다
주석은 비정상 상태에서 ERR_NOT_SUSPENDED를 말하지만, 이 commit의 코드는 그 상태에서도 NO_ERROR를 반환한다. 재호출의 성공 여부를 반환값만으로 해석하지 않는다 (kernel/thread.c:265).
OBJECT LIFETIME
누가 보유하고 언제 회수하는가
| 대상 | 생성 때 | 회수 조건 | 근거 |
|---|---|---|---|
| thread_t | NULL이면 malloc + FREE_STRUCT | join 또는 detached exit의 flag 검사 | kernel/thread.c:149 |
| stack | NULL이면 malloc + FREE_STACK | join의 free 또는 detached exit의 delayed_free | kernel/thread.c:173 |
| thread_list link | 초기 context 뒤 등록 | join 또는 detached exit에서 제거 | kernel/thread.c:215 |
| run queue link | resume에서 READY가 될 때 삽입 | 선택되면 get_top_thread에서 제거 | kernel/thread.c:282 |
FAILURE PATH
상태 경계에서 확인할 증상
| 조건 | 이 commit의 결과 | 확인 지점 |
|---|---|---|
| thread_t malloc 실패 | NULL 반환; stack 작업 전 | kernel/thread.c:149 |
| stack malloc 실패 | 자체 할당 thread_t만 free 뒤 NULL | kernel/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별 전제는 해당 구현에서 확인한다.
EVIDENCE
실제 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 반환 전에 종료·회수될 수 있으므로 반환 뒤 포인터를 무조건 읽지 않음 |
| 소유 flag | t->flags·stack 주소 기록 | NULL 제공 여부와 FREE_STRUCT/FREE_STACK 일치 |
| 첫 실행 | entry 시작 로그에 CPU·thread 이름·시간 기록 | resume 호출 시각과 첫 실행 시각을 분리 |
LAB
세 가지 재현 질문
- 01create 직후와 resume 직후를 비교
state, thread_list link, run queue link를 두 시점에 기록해 생성과 runnable 전이를 분리한다.
- 02제공 자원과 동적 자원을 분리
thread_create_etc에 외부 t·stack을 전달한 경우와 NULL 입력을 비교해 FREE flag와 종료 후 owner의 해제 책임을 검증한다.
- 03interrupt 상태별 resume 관찰
interrupt enabled/disabled 진입에서 로컬 yield 유무와 첫 entry 로그를 비교한다. 다른 CPU 요청은 별도 추적한다.
PRIMARY REFERENCES