LK · source analysis

run queue와 thread_resched

현재 스레드를 상태에 맞는 큐로 되돌린 뒤, 다음에 실행할 스레드를 선택하고 문맥을 전환하는 과정을 살펴봅니다.

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

Series
06 / 20
Baseline
upstream 1eb9917
Commit
1eb99171efae
Source
kernel/thread.c:46-134 (발췌 범위)

run queue와 thread_resched 단계에서 실제로 바뀌는 상태는 무엇인가?

호출 이유가 yield인지 block인지 preemption인지에 따라 현재 thread를 다시 enqueue하는 조건이 달라진다. interrupt disable 구간도 함께 본다.

같은 순간에 하나의 thread만 RUNNING이며 runnable thread는 정확히 하나의 run queue에 존재해야 한다. 이 문장을 기준으로 코드를 위에서 아래로 읽으면, 함수 이름을 외우는 대신 어느 시점에 어떤 상태를 신뢰할 수 있는지 판단할 수 있다.

객체와 주소가 놓이는 구조

그림 1. run queue와 thread_resched에서 입력, 내부 상태, 출력의 경계
입력과 전제내부 상태외부로 공개되는 결과
01priority queues
02current_thread
03saved registers
04scheduler lock

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

실행 흐름

그림 2. 정상 경로의 주요 호출과 상태 전달
timer/wakeup/yield
scheduler lock
run queue pick
arch context switch
next thread

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

단계별 입력과 출력

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

#단계진입 시 신뢰할 상태성공 뒤 남아야 할 상태다음 소비자
01timer/wakeup/yieldinterrupt를 막은 scheduler 임계 구역priority queuesscheduler lock
02scheduler locktimer/wakeup/yield 완료 상태current_threadrun queue pick
03run queue pickscheduler lock 완료 상태saved registersarch context switch
04arch context switchrun queue pick 완료 상태scheduler locknext thread
05next threadarch context switch 완료 상태scheduler lock이 단계의 처리 결과를 사용하는 코드

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

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

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

그림 3. thread_resched의 run queue 갱신과 context switch

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

01interrupt·scheduler lock 확인
02current 상태 판정
03필요 시 current 재삽입
04priority bitmap 탐색
05next를 RUNNING으로 전환
06arch_context_switch
그림 4. 스케줄러가 읽는 상태와 갱신 지점

왼쪽 생산자가 가운데 상태를 완성하고, 오른쪽 소비자가 그 상태를 처음 사용하는 관계다.

01thread_resumeREADY + run queue linkget_top_thread
02timer tickpreempt requestthread_resched
03thread_blockBLOCKEDwakeup path
04priority bitmap최상위 queuenext selection
05arch switchsaved SP/registersold thread 재개

원본 코드

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

commit1eb99171efae98867d4be4a5bd6479ea03f43ac9anchor · L70void thread_resched(void)
46
47/* global thread list */
48static struct list_node thread_list;
49
50/* master thread spinlock */
51spin_lock_t thread_lock = SPIN_LOCK_INITIAL_VALUE;
52
53/* the run queue */
54static struct list_node run_queue[NUM_PRIORITIES];
55static uint32_t run_queue_bitmap;
56
57/* make sure the bitmap is large enough to cover our number of priorities */
58STATIC_ASSERT(NUM_PRIORITIES <= sizeof(run_queue_bitmap) * 8);
59
60/* the idle thread(s) (statically allocated) */
61#if WITH_SMP
62static thread_t _idle_threads[SMP_MAX_CPUS];
63#define idle_thread(cpu) (&_idle_threads[cpu])
64#else
65static thread_t _idle_thread;
66#define idle_thread(cpu) (&_idle_thread)
67#endif
68
69/* local routines */
70static void thread_resched(void);
71static void idle_thread_routine(void) __NO_RETURN;
72
73#if PLATFORM_HAS_DYNAMIC_TIMER
74/* preemption timer */
75static timer_t preempt_timer[SMP_MAX_CPUS];
76#endif
77
78/* run queue manipulation */
79static void insert_in_run_queue_head(thread_t *t) {
80    DEBUG_ASSERT(t->magic == THREAD_MAGIC);
81    DEBUG_ASSERT(t->state == THREAD_READY);
82    DEBUG_ASSERT(!list_in_list(&t->queue_node));
83    DEBUG_ASSERT(arch_ints_disabled());
84    DEBUG_ASSERT(spin_lock_held(&thread_lock));
85
86    list_add_head(&run_queue[t->priority], &t->queue_node);
87    run_queue_bitmap |= (1<<t->priority);
88}
89
90static void insert_in_run_queue_tail(thread_t *t) {
91    DEBUG_ASSERT(t->magic == THREAD_MAGIC);
92    DEBUG_ASSERT(t->state == THREAD_READY);
93    DEBUG_ASSERT(!list_in_list(&t->queue_node));
94    DEBUG_ASSERT(arch_ints_disabled());
95    DEBUG_ASSERT(spin_lock_held(&thread_lock));
96
97    list_add_tail(&run_queue[t->priority], &t->queue_node);
98    run_queue_bitmap |= (1<<t->priority);
99}
100
101static void wakeup_cpu_for_thread(thread_t *t)
102{
103    /* Wake up the core to which this thread is pinned
104     * or wake up all if thread is unpinned */
105    int pinned_cpu = thread_pinned_cpu(t);
106    if (pinned_cpu < 0)
107        mp_reschedule(MP_CPU_ALL_BUT_LOCAL, 0);
108    else
109        mp_reschedule(1U << pinned_cpu, 0);
110}
111
112static void init_thread_struct(thread_t *t, const char *name) {
113    memset(t, 0, sizeof(thread_t));
114    t->magic = THREAD_MAGIC;
115    thread_set_pinned_cpu(t, -1);
116    strlcpy(t->name, name, sizeof(t->name));
117}
118
119/**
120 * @brief  Create a new thread
121 *
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

발췌 범위와 읽기 기준

원문 46-134줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 void thread_resched(void)은 L70에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.

호출 이유가 yield인지 block인지 preemption인지에 따라 현재 thread를 다시 enqueue하는 조건이 달라진다. interrupt disable 구간도 함께 본다.

함께 읽어야 하는 원본 코드

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

01. 현재 CPU에서 우선순위가 가장 높은 thread 선택

kernel/thread.c 421-479줄이다.

filekernel/thread.canchor · L431static thread_t *get_top_thread(int cpu)
421    thread_resched();
422
423    panic("somehow fell through thread_exit()\n");
424}
425
426static void idle_thread_routine(void) {
427    for (;;)
428        arch_idle();
429}
430
431static thread_t *get_top_thread(int cpu) {
432    thread_t *newthread;
433    uint32_t local_run_queue_bitmap = run_queue_bitmap;
434
435    while (local_run_queue_bitmap) {
436        /* find the first (remaining) queue with a thread in it */
437        uint next_queue = sizeof(run_queue_bitmap) * 8 - 1 - __builtin_clz(local_run_queue_bitmap);
438
439        list_for_every_entry(&run_queue[next_queue], newthread, thread_t, queue_node) {
440#if WITH_SMP
441            if (newthread->pinned_cpu < 0 || newthread->pinned_cpu == cpu)
442#endif
443            {
444                list_delete(&newthread->queue_node);
445
446                if (list_is_empty(&run_queue[next_queue]))
447                    run_queue_bitmap &= ~(1<<next_queue);
448
449                return newthread;
450            }
451        }
452
453        local_run_queue_bitmap &= ~(1<<next_queue);
454    }
455    /* no threads to run, select the idle thread for this cpu */
456    return idle_thread(cpu);
457}
458
459/**
460 * @brief  Cause another thread to be executed.
461 *
462 * Internal reschedule routine. The current thread needs to already be in whatever
463 * state and queues it needs to be in. This routine simply picks the next thread and
464 * switches to it.
465 *
466 * This is probably not the function you're looking for. See
467 * thread_yield() instead.
468 */
469void thread_resched(void) {
470    thread_t *oldthread;
471    thread_t *newthread;
472
473    thread_t *current_thread = get_current_thread();
474    uint cpu = arch_curr_cpu_num();
475
476    DEBUG_ASSERT(arch_ints_disabled());
477    DEBUG_ASSERT(spin_lock_held(&thread_lock));
478    DEBUG_ASSERT(current_thread->state != THREAD_RUNNING);
479

내부 동작을 더 깊게 읽기

01

진입 조건을 먼저 고정한다

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

호출 이유가 yield인지 block인지 preemption인지에 따라 현재 thread를 다시 enqueue하는 조건이 달라진다. interrupt disable 구간도 함께 본다.

02

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

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

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

03

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

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

04

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

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

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

05

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

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

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

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

01

run queue 조작은 interrupt-disabled lock 범위에서 읽는다

현재 thread를 queue에 다시 넣고 다음 runnable thread를 고르는 동안 timer interrupt나 다른 CPU가 같은 queue를 만질 수 있다. spinlock만 볼 것이 아니라 local interrupt state와 scheduler disable count를 함께 확인한다.

priority별 queue와 bitmap이 있다면 두 표현이 항상 일치해야 한다. dequeue 뒤 bitmap bit를 지우는 조건을 빈 queue 경계에서 검증한다.

02

reschedule 요청과 실제 context switch는 같은 시점이 아니다

interrupt handler는 reschedule flag만 세우고 exception return에서 switch할 수 있으며 thread 문맥은 즉시 thread_resched()를 호출할 수 있다. latency는 요청 timestamp부터 새 thread가 실행한 첫 instruction까지 측정한다.

preemption disable 구간이 길면 높은 priority thread가 runnable이어도 상한이 깨진다.

03

SMP에서는 current thread와 CPU affinity를 함께 본다

thread가 다른 CPU run queue로 이동할 수 있으면 per-CPU current pointer, affinity mask와 IPI가 일관되어야 한다. lock 획득 순서가 CPU 번호에 따라 달라지면 migration과 wakeup이 교차할 때 deadlock이 생긴다.

두 CPU에서 같은 thread가 동시에 RUNNING으로 보이지 않는다는 불변 조건을 trace로 검증한다.

객체와 수명

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

실패 지점과 증상

#조건관찰되는 증상먼저 볼 단계
01이중 enqueue같은 thread 두 번 선택scheduler lock
02lock count 불일치영구 preemption disablerun queue pick
03ISR 반환 flag 누락높은 우선순위 thread 지연arch context switch

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

소스 밖에서 확인할 증거

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

#목적명령 또는 계측판정 기준
01빌드 구성make <project> -j1platform, target, app 선택과 linker 입력을 로그로 남긴다.
02symbol과 주소nm -n build-*/lk.elf | grep 'void thread_resched'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
    context switch마다 old/new priority 기록

    scheduler lock 진입 전후에 priority queues의 주소·크기·반환값과 timestamp를 함께 남긴다.

  2. 02
    run queue bitmap과 list 일관성 검사

    run queue pick 진입 전후에 current_thread의 주소·크기·반환값과 timestamp를 함께 남긴다.

  3. 03
    timer tick과 explicit yield의 call stack 비교

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

원문과 다음 글