cpu_startup_entry() – cpuidle

 

Idle-task

Idle 태스크는 코어 별로 존재하는데 별도로 생성하지 않고 각 코어의 커널 부트업 프로세스 과정이 끝난 후 이 프로세스를 이용하여 Idle 태스크로 활용하도록 Idle-task 스케줄러에 연결한다.

  • init_task가 부트업 과정을 마친 boot cpu에서 idle 태스크로 변경하여 사용하고, 나머지 cpu들은 init_task를 idle 태스크로 복사하여 사용한다.
    • 이 idle 태스크는 pid 0번을 가지며, hidden task 형태로 존재하여 ps 명령 또는 top 명령에 의해 보여지지 않는다.
    • 각 cpu의 rq->idle에 idle 태스크가  cpu별로 지정되어 사용되며, “swapper/<cpu>”라는 이름을 사용한다..
  • idle 진입 시 폴링 커널 옵션을 사용하는 경우 cpu 절전 기능을 사용하지 않고 busy-wait을 한다.
    • CONFIG_GENERIC_IDLE_POLL_SETUP 커널 옵션 사용시 폴링한다.
  • idle 진입 시 폴링 커널 옵션을 사용하지 않는 경우 아키텍처의 idle 방법을 사용한다.
    • cpu idle 드라이버를 사용하는 경우 아래와 같이 동작하고 그렇지 않은 경우 해당 아키텍처의 기본 동작을 사용한다. armv7의 기본 동작은 wfi 이다.

 

 

cpu idle 드라이버

cpu idle 드라이버는 멀티 사용을 지원한다. cpu ilde을 사용하지 않는 경우 armv7 아키텍처는 wfi 기반을 사용한다.

  • arm 기본 드라이버
    • ARMv7에서 cpu 개별 idle 진입 시 wfi 기반을 사용한다.
    • “arm,idle-state” – drivers/cpuidle/cpuidle-arm.c
  • arm 빅 & 리틀 드라이버
    • ARMv7에서 cpu 개별 idle 진입 시 wfi 기반을 사용한다.
    • 빅/리틀 클러스터 idle 진입 시 deep-state는 “C1″으로 클러스터 단위로 전원을 내리기 위해 PM(suspend/resume) 기능을 동작시키고 timer도 stop 된다.
    • “arm,idle-state” – drivers/cpuidle/cpuidle-big_little.c
    • 머신 compatible 명이 “samsung,exynos4210″인 경우 – drivers/cpuidle/cpuidle-exynos.c
  • arm64 PSCI 드라이버
    • ARMv8은 항상 PSCI 드라이버를 사용한다. (arm32에서는 optional)
    • cpu 개별 idle 진입 시 wfi 기반을 사용한다.
    • cpu 개별 idle 진입 시 deep sleep 기반으로 core 전원을 내리기 위해 PM(suspend/resume) 기능을 동작시키고 timer도 stop 된다.
    • 클러스터 idle 진입 시 클러스터 단위로 전원을 내리기 위해 PM(suspend/resume) 기능을 동작시키고 timer도 stop 된다.
    • “arm,idle-state” – drivers/cpuidle/cpuidle-psci.c
  • mips 및 ppc도 드라이버가 있지만 생략한다.

 

Intel의 C State

Intel에서 제조한 프로세서는 절전 모드에서 세 가지 C-state (C1, C2, C3)를 지원한다.

  • C1 상태는 “Auto Halt” 또는 “MWAIT”라고도 불리며, 프로세서가 대기하면서 최소한의 전력을 소비하도록 하는 가장 간단한 절전 모드이다. 프로세서는 일시 중지되어 있지만, 빠른 복귀를 위해 기다리고 있는 시스템 이벤트를 감지한다.
  • C2 상태는 “Stop-Clock” 또는 “HALT”라고도 불리며, 프로세서의 클럭을 중지하고 캐시를 비우는 것을 포함하여 C1보다 더 많은 전력을 절약한다. 프로세서는 일시 중지 상태이지만, C1보다 더 많은 시간을 소비하므로 기다리고 있는 이벤트를 탐지하기 위해 더 많은 시간이 걸린다.
  • C3 상태는 “Deep Sleep” 또는 “Sleep”라고도 불리며, 프로세서의 코어 전압과 클럭을 낮추어서 더 많은 전력을 절약한다. C3 상태는 대개 C2보다 더 깊은 수면 상태이며, 프로세서는 기다리고 있는 이벤트를 탐지하기 위해 C2보다 더 많은 시간이 걸린다.
  • 이 세 가지 C-state는 프로세서가 실행되는 로드와 같은 여러 가지 요소에 따라 다르다. 예를 들어, 높은 로드를 처리하는 경우 C1 상태가 더 많이 사용된다. 그러나 낮은 로드를 처리하는 경우에는 C3 상태가 더 많이 사용된다.

 

리눅스 시스템 절전 상태 변경

s2idle, standby, s2ram, s2disk 순으로 빠른 순서이며 각각 다음의 특징을 갖는다.

  • s2idle : 프로세서를 일시 중지시켜 전력 소비를 최소화하는 상태이다. 프로세서는 코어 클럭을 중지하고 캐시를 비우지 않는다. 메모리는 활성화되어 있으며, 시스템은 빠르게 복원될 수 있다.
  • standby : 메모리의 내용을 메모리에 유지하면서, 프로세서와 메모리를 비활성화하는 상태이다. 모든 하드웨어 장치는 꺼지고, 전원 소비가 크게 감소한다. 시스템은 빠르게 복원될 수 있다.
  • s2ram : 메모리의 내용을 메모리에 유지하면서, 프로세서와 메모리를 비활성화하는 상태이다. 모든 하드웨어 장치는 꺼지고, 전원 소비가 크게 감소한다. 시스템은 복원될 때 메모리의 내용을 읽어들여 복구한다.
  • s2disk : 메모리의 내용을 하드 디스크에 저장하고, 프로세서와 메모리를 비활성화하는 상태이다. 모든 하드웨어 장치는 꺼지고, 전원 소비가 크게 감소한다. 시스템은 전원을 다시 켤 때 하드 디스크에서 저장된 메모리의 내용을 읽어들여 복구한다. 이는 가장 느린 종류의 절전 모드이다.

 

절전 상태 명령을 바꾸는 명령

  • /sys/power/stat 파일을 통해 시스템에서 지원하는 절전상태를 알아보고, 지정할 수 있다.
  • /sys/power/mem_sleep을 통해 시스템에서 지원하는 memeory를 사용하는 suspend 지원방법을 알아보고 지정할 수 있다.

 

cpuidle governor

리눅스 시스템이 지원하는 7가지의 cpuidle governor는 다음과 같다.

  • menu governor : 최소한의 전력 소비를 위해 가능한한 적은 C-state으로 CPU를 유지하고, 사용자 요청이 있을 때 빠르게 복귀한다. (default)
  • ladder governor : 시스템 부하에 따라서 다른 C-state으로 이동한다. 부하가 낮을 때는 더 깊은 C-state으로 이동하여 전력 소비를 최소화하고, 부하가 높을 때는 더 얕은 C-state으로 이동하여 빠른 응답성을 유지한다.
  • menu-ladder governor : menu와 ladder governor의 조합이다. 일반적으로 ladder보다 더 나은 전력 절약을 제공한다.
  • power aware governor : Intel의 P-state 기능을 활용하여 CPU의 주파수와 전압을 동적으로 조절하면서, 전력 소비를 최소화한다.
  • conservative governor : CPU 사용률이 낮을 때는 더 깊은 C-state으로 이동하여 전력 소비를 최소화하고, 사용률이 높을 때는 더 얕은 C-state으로 이동하여 빠른 응답성을 유지한다.
  • performance governor : CPU를 항상 최대 주파수에서 동작하도록 유지한다. 이 governor는 전력 소비를 최소화하지 않으며, CPU 성능을 우선시하는 경우에 사용된다.
  • ondemand governor : CPU 사용률에 따라 C-state을 선택한다. 사용률이 높을 때는 더 얕은 C-state으로 이동하여 빠른 응답성을 유지하고, 사용률이 낮을 때는 더 깊은 C-state으로 이동하여 전력 소비를 최소화한다.

 

지원 가능 cpuidle governor 및 설정

  • /sys/devices/system/cpu/cpuidle/available_governors 에서 사용가능한 cpuidle governor를 보여준다.
  • /sys/devices/system/cpu/cpuidle/current_governors에서 현재 지정된 cpuilde governor를 보여주고, 지정할 수 있다.

 


cpu_startup_entry()

kernel/sched/idle.c

void cpu_startup_entry(enum cpuhp_state state) 
{
        /*
         * This #ifdef needs to die, but it's too late in the cycle to
         * make this generic (arm and sh have never invoked the canary
         * init for the non boot cpus!). Will be fixed in 3.11
         */
#ifdef CONFIG_X86
        /*
         * If we're the non-boot CPU, nothing set the stack canary up
         * for us. The boot CPU already has it initialized but no harm
         * in doing it again. This is a good place for updating it, as
         * we wont ever return from this function (so the invalid
         * canaries already on the stack wont ever trigger).
         */
        boot_init_stack_canary();
#endif
        arch_cpu_idle_prepare();
        cpu_idle_loop();
}

각 코어의 커널 부트업 프로세스 과정이 끝난 후 진입되어 첫 태스크인 idle-task가 동작하고 idle 루프를 수행한다.

  • 코드 라인 18에서 idle 태스크를 처음 수행할 때 아키텍처 관련 준비할 루틴을 수행한다.
    • arm 아키텍처에서는 현재 cpu의 fiq를 enable한다.
  • 코드 라인 19에서 idle 루프를 수행한다.

 

arch_cpu_idle_prepare()

arch/arm/kernel/process.c

void arch_cpu_idle_prepare(void)
{
        local_fiq_enable();
}

현재 cpu의 fiq를 enable한다.

 

IDLE 루프

cpu_idle_loop()

idle 루프를 수행하며 규칙적으로 깨어나거나 다른 프로세서에 의해 깨어날 때 마다 preemption 여부를 체크하여 필요 시 다른 태스크로의 수행을 넘겨주기 위해 preemption 된다.

kernel/sched/idle.c

/*
 * Generic idle loop implementation
 *
 * Called with polling cleared.
 */
static void cpu_idle_loop(void)
{
        while (1) {
                /*
                 * If the arch has a polling bit, we maintain an invariant:
                 *
                 * Our polling bit is clear if we're not scheduled (i.e. if
                 * rq->curr != rq->idle).  This means that, if rq->idle has
                 * the polling bit set, then setting need_resched is
                 * guaranteed to cause the cpu to reschedule.
                 */

                __current_set_polling();
                tick_nohz_idle_enter();

                while (!need_resched()) {
                        check_pgt_cache();
                        rmb();

                        if (cpu_is_offline(smp_processor_id()))
                                arch_cpu_idle_dead();

                        local_irq_disable();
                        arch_cpu_idle_enter();

                        /*
                         * In poll mode we reenable interrupts and spin.
                         *
                         * Also if we detected in the wakeup from idle
                         * path that the tick broadcast device expired
                         * for us, we don't want to go deep idle as we
                         * know that the IPI is going to arrive right
                         * away
                         */
                        if (cpu_idle_force_poll || tick_check_broadcast_expired())
                                cpu_idle_poll();
                        else
                                cpuidle_idle_call();

                        arch_cpu_idle_exit();
                }
  • 코드 라인 18에서 무한 루프를 돌며 polling 중으로 설정한다.
  • 코드 라인 19에서 nohz idle을 지원하는 경우 tick을 발생하지 못하게 nohz idle 모드로 진입한다.
  • 코드 라인 21에서 리스케줄 요청이 없는 경우 루프를 돈다.
  • 코드 라인 25~26에서 cpu가 offline 상태인 경우 die 상태로 진입한다.
  • 코드 라인 28~29에서 현재 cpu의 irq를 disable하고 idle 시작에 대한 아키텍처 관련 처리를 수행한다.
    • arm 아키텍처에서는 idle 시작에 대한 led 밝기 처리를 변경한다.
  • 코드 라인 40~41에서 idle 상태에서 폴링이 필요하거나 현재 cpu에 대해 tick 브로드캐스트 체크가 필요한 경우 idle 폴링을 한다.
    • idle 폴링은 인터럽트를 enable하고 cpu의 전원을 끄지 않은 상태에서 리스케줄링 요청 플래그만 계속 감시한다.
  • 코드 라인 42~43에서 그렇지 않은 경우 절전 기능을 위해 deep state idle 진입을 위해 cpuidle 드라이버에 요청한다.
  • 코드 라인 45에서 idle 종료에 대한 아키텍처 관련 처리를 수행한다.
    • arm 아키텍처에서는 idle 종료에 대한 led 밝기 처리를 변경한다.

 

                /*
                 * Since we fell out of the loop above, we know
                 * TIF_NEED_RESCHED must be set, propagate it into
                 * PREEMPT_NEED_RESCHED.
                 *
                 * This is required because for polling idle loops we will
                 * not have had an IPI to fold the state for us.
                 */
                preempt_set_need_resched();
                tick_nohz_idle_exit();
                __current_clr_polling();

                /*
                 * We promise to call sched_ttwu_pending and reschedule
                 * if need_resched is set while polling is set.  That
                 * means that clearing polling needs to be visible
                 * before doing these things.
                 */
                smp_mb__after_atomic();

                sched_ttwu_pending();
                schedule_preempt_disabled();
        }
}
  • 코드 라인 9에서 리스케줄 요청이 있는 경우 이 루틴에 도착하게 된다. preemption 설정을 하는데 arm 아키텍처는 아무 일도 수행하지 않는다.
  • 코드 라인 10에서 nohz idle 모드를 벗어난다.
  • 코드 라인 11에서 폴링 플래그를 제거한다.
  • 코드 라인 21에서 대기중인 태스크를 깨운다.
  • 코드 라인 22에서 리스케줄한다.

 

 

 

IDLE 폴링

“nohlt”, “hlt” 커널 파라메터 설정

“nohlt”, “hlt” 설정 시 다음 정수 변수에 설정이 반영된다.

kernel/sched/idle.c

static int __read_mostly cpu_idle_force_poll;

 

cpu_idle_poll_setup() & cpu_idle_nopoll_setup()

kernel/sched/idle.c

#ifdef CONFIG_GENERIC_IDLE_POLL_SETUP
static int __init cpu_idle_poll_setup(char *__unused)
{
        cpu_idle_force_poll = 1;
        return 1;
}
__setup("nohlt", cpu_idle_poll_setup);

static int __init cpu_idle_nopoll_setup(char *__unused)
{
        cpu_idle_force_poll = 0;
        return 1;
}
__setup("hlt", cpu_idle_nopoll_setup);
#endif

“hlt” 커널 파라메터를 사용하는 경우 cpu_idle_force_poll=1로 설정하여 폴링을 하게한다.

“nohlt” 커널 파라메터를 사용하는 경우 cpu_idle_force_poll=0로 설정하여 폴링을 하지 못하게한다. (기본값)

 

Idle 폴링 수행

cpu_idle_poll()

kernel/sched/idle.c

static inline int cpu_idle_poll(void)
{
        rcu_idle_enter();
        trace_cpu_idle_rcuidle(0, smp_processor_id());
        local_irq_enable();
        while (!tif_need_resched() &&
                (cpu_idle_force_poll || tick_check_broadcast_expired()))
                cpu_relax();
        trace_cpu_idle_rcuidle(PWR_EVENT_EXIT, smp_processor_id());
        rcu_idle_exit();
        return 1;
}

idle 상태에 진입해 있는 중이며, 리스케줄 요청이 있을 때까지 계속 루프를 돌며 조사한다.

 

__current_set_polling()

include/linux/sched.h

static inline void __current_set_polling(void)
{
        set_thread_flag(TIF_POLLING_NRFLAG);
}

현재 스레드에 폴링 플래그를 설정한다.

 

__current_clr_polling()

include/linux/sched.h

static inline void __current_clr_polling(void)
{         
        clear_thread_flag(TIF_POLLING_NRFLAG);
}

현재 스레드에서 폴링 플래그를 클리어한다.

 

절전용 Idle 콜 호출

cpuidle_idle_call()

kernel/sched/idle.c -1/3-

/**
 * cpuidle_idle_call - the main idle function
 *
 * NOTE: no locks or semaphores should be used here
 *
 * On archs that support TIF_POLLING_NRFLAG, is called with polling
 * set, and it returns with polling set.  If it ever stops polling, it
 * must clear the polling bit.
 */
static void cpuidle_idle_call(void)
{
        struct cpuidle_device *dev = __this_cpu_read(cpuidle_devices);
        struct cpuidle_driver *drv = cpuidle_get_cpu_driver(dev);
        int next_state, entered_state;
        unsigned int broadcast;
        bool reflect;

        /*
         * Check if the idle task must be rescheduled. If it is the
         * case, exit the function after re-enabling the local irq.
         */
        if (need_resched()) {
                local_irq_enable();
                return;
        }

        /*
         * During the idle period, stop measuring the disabled irqs
         * critical sections latencies
         */
        stop_critical_timings();

        /*
         * Tell the RCU framework we are entering an idle section,
         * so no more rcu read side critical sections and one more
         * step to the grace period
         */
        rcu_idle_enter();

        if (cpuidle_not_available(drv, dev))
                goto use_default;
  • 코드 라인 22~25에서 리스케줄 요청이 있는 경우 현재 cpu의 irq를 enable하고 함수를 빠져나간다.
  • 코드 라인 31에서 irq 및 preempt 트레이싱을 위한 타이밍 측정을 잠시 멈춘다.
  • 코드 라인 38에서 idle 진입 전에 rcu를 위해 수행할 일들을 처리한다.
  • 코드 라인 40~41에서 cpu idle 드라이버가 없는 경우 아키텍처 기본 처리 루틴을 호출한다.
    • armv7에서는 특정 머신 코드를 호출하거나 특정 머신 코드가 없는 대부분의 경우 cpu_do_idle() 함수에서 wfi 동작을 수행한다.

 

kernel/sched/idle.c -2/3-

        /*
         * Suspend-to-idle ("freeze") is a system state in which all user space
         * has been frozen, all I/O devices have been suspended and the only
         * activity happens here and in iterrupts (if any).  In that case bypass
         * the cpuidle governor and go stratight for the deepest idle state
         * available.  Possibly also suspend the local tick and the entire
         * timekeeping to prevent timer interrupts from kicking us out of idle
         * until a proper wakeup interrupt happens.
         */
        if (idle_should_freeze()) {
                entered_state = cpuidle_enter_freeze(drv, dev);
                if (entered_state >= 0) {
                        local_irq_enable();
                        goto exit_idle;
                }

                reflect = false;
                next_state = cpuidle_find_deepest_state(drv, dev);
        } else {
                reflect = true;
                /*
                 * Ask the cpuidle framework to choose a convenient idle state.
                 */
                next_state = cpuidle_select(drv, dev);
        }
        /* Fall back to the default arch idle method on errors. */
        if (next_state < 0)
                goto use_default;

        /*
         * The idle task must be scheduled, it is pointless to
         * go to idle, just update no idle residency and get
         * out of this function
         */
        if (current_clr_polling_and_test()) {
                dev->last_residency = 0;
                entered_state = next_state;
                local_irq_enable();
                goto exit_idle;
        }
  • 코드 라인 10~11에서 suspend로 인한 idle로 진입하는 경우 freeze 한다.
  • 코드 라인 12~15에서 resume에 의해 깨어난 후에 cpu idle 드라이버를 사용하여 suspend 한 경우 현재 cpu의 irq를 enable 시킨 후  exit_idle 레이블로 이동한다.
  • 코드 라인 17~18에서 cpu idle 드라이버를 사용하여 진입하지 못한 경우 reflect에 false를 대입한 후 다음 이용할 적절한 0 이상의 state 인덱스를 알아온다.
  • 코드 라인 19~25에서 reflect에 false를 대입한 후 cpu idle 프레임워크가 적절한 state 인덱스를 결정한다.
  • 코드 라인 27~28에서 만일 결정된 state가 없으면 use_default 레이블로 이동하여 아키텍처 자체 idle 처리를 수행하게 한다.
  • 코드 라인 35~40에서 폴링 플래그를 클리어한 후 리스케줄 요청이 있는 경우 현재 cpu의 irq를 enable하고 exit_idle 레이블로 이동한다.

 

kernel/sched/idle.c -3/3-

        broadcast = drv->states[next_state].flags & CPUIDLE_FLAG_TIMER_STOP;

        /*
         * Tell the time framework to switch to a broadcast timer
         * because our local timer will be shutdown. If a local timer
         * is used from another cpu as a broadcast timer, this call may
         * fail if it is not available
         */
        if (broadcast &&
            clockevents_notify(CLOCK_EVT_NOTIFY_BROADCAST_ENTER, &dev->cpu))
                goto use_default;

        /* Take note of the planned idle state. */
        idle_set_state(this_rq(), &drv->states[next_state]);

        /*
         * Enter the idle state previously returned by the governor decision.
         * This function will block until an interrupt occurs and will take
         * care of re-enabling the local interrupts
         */
        entered_state = cpuidle_enter(drv, dev, next_state);

        /* The cpu is no longer idle or about to enter idle. */
        idle_set_state(this_rq(), NULL);

        if (broadcast)
                clockevents_notify(CLOCK_EVT_NOTIFY_BROADCAST_EXIT, &dev->cpu);

        /*
         * Give the governor an opportunity to reflect on the outcome
         */
        if (reflect)
                cpuidle_reflect(dev, entered_state);

exit_idle:
        __current_set_polling();

        /*
         * It is up to the idle functions to reenable local interrupts
         */
        if (WARN_ON_ONCE(irqs_disabled()))
                local_irq_enable();

        rcu_idle_exit();
        start_critical_timings();
        return;

use_default:
        /*
         * We can't use the cpuidle framework, let's use the default
         * idle routine.
         */
        if (current_clr_polling_and_test())
                local_irq_enable();
        else
                arch_cpu_idle();

        goto exit_idle;
}
  • 코드 라인 1에서 cpu idle 드라이버에서 동작시킬 state 인덱스의 플래그레 timer-stop 플래그가 있는지 여부를 알아온다.
    • timer를 사용할 수 없는 경우 deep-idle 상태에서 빠져나오려면 브로드캐스팅을 해서 알려야 한다.
  • 코드 라인 9~11에서 브로드캐스트가 필요한 상태에서 클럭이벤트 드라이버를 통해 broadcast enter에 대한 통지가 성공한 경우 use_default 레이블로 이동하여 아키텍처 기본 idle 루틴을 사용하게 한다.
    • 로컬 타이머가 셧다운되어 사용하지 못하는 상황에서는 브로드 캐스트 타이머를 사용해야 한다.
  • 코드 라인 14에서 런큐의 idle_state에 동작 시킬 cpu idle driver의 state를 대입한다.
  • 코드 라인 21에서 cpu idle 드라이버를 통해 idle에 진입한다.
  • 코드 라인 24에서런큐의 idle_state에 다시 null을 대입한다.
  • 코드 라인 26에서 브로드캐스트가 필요한 상태였었던 경우 클럭이벤트 드라이버를 통해 broadcast exit에 대한 통지를 수행한다.
  • 코드 라인 31~32에서 cpu idle 드라이버 진입 시 프레임웍이 골라준 state 인덱스를 reflect에 반영한다.
  • 코드 라인 35에서 폴링 플래그를 클리어한다.
  • 코드 라인 43에서 idle에서 빠져나온 후 rcu를 위해 수행할 일들을 처리한다.
  • 코드 라인 44에서 irq 및 preempt 트레이싱을 위해 타이밍 측정을 다시 재계한다.

 

ARM 아키텍처 관련

arch_cpu_idle_prepare()

arch/arm/kernel/process.c

void arch_cpu_idle_prepare(void)
{
        local_fiq_enable();
}

현재 cpu의 fiq를 enable 한다.

 

arch_cpu_idle_dead()

arch/arm/kernel/process.c

#ifdef CONFIG_HOTPLUG_CPU
void arch_cpu_idle_dead(void)
{
        cpu_die();
}
#endif

hotplug cpu 커널 옵션을 사용하는 경우 die 처리를 한다.

 

arch_cpu_idle_enter()

arch/arm/kernel/process.c

void arch_cpu_idle_enter(void)
{
        ledtrig_cpu(CPU_LED_IDLE_START);
#ifdef CONFIG_PL310_ERRATA_769419
        wmb(); 
#endif
}

arm 아키텍처에서 cpu idle 진입 시 led 장치의 트리거 on을 위해 호출한다.

 

arch_cpu_idle_exit()

arch/arm/kernel/process.c

void arch_cpu_idle_exit(void)
{
        ledtrig_cpu(CPU_LED_IDLE_END);
}

arm 아키텍처에서 cpu idle 처리 완료 후 led 장치의 트리거 off를 위해 호출한다.

 

arch_cpu_idle()

arch/arm/kernel/process.c

/*      
 * Called from the core idle loop.
 */
void arch_cpu_idle(void)
{
        if (arm_pm_idle)
                arm_pm_idle();
        else
                cpu_do_idle();
        local_irq_enable(); 
}

arm cpu가 idle 대기 모드로 진입하도록 한다.

  • 코드 6~7에서 (*arm_pm_idle) 후크 함수에 연결된 함수가 있으면 호출한다.
  • 코드 8~9에서 없으면 cpu_do_idle() 함수를 호출한다.
    • armv7 아키텍처에서는 cpu_v7_do_idle() 함수를 호출하여  인터럽트가 발생하기 전까지 저전력 상태에서 대기한다.

 

cpu_v7_do_idle()

arch/arm/mm/proc-v7.S

/*
 *      cpu_v7_do_idle()
 *
 *      Idle the processor (eg, wait for interrupt).
 *
 *      IRQs are already disabled.
 */
ENTRY(cpu_v7_do_idle)
        dsb                                     @ WFI may enter a low-power mode
        wfi
        ret     lr
ENDPROC(cpu_v7_do_idle)

인터럽트가 발생하기 전까지 저전력 상태에서 대기한다. 인터럽트에 의해 다시 재개된다.

 

Tick nohz idle

nohz idle로 진입할 때

tick_nohz_idle_enter()

kernel/time/tick-sched.c

/**
 * tick_nohz_idle_enter - stop the idle tick from the idle task
 *
 * When the next event is more than a tick into the future, stop the idle tick
 * Called when we start the idle loop.
 *
 * The arch is responsible of calling:
 *
 * - rcu_idle_enter() after its last use of RCU before the CPU is put
 *  to sleep.
 * - rcu_idle_exit() before the first use of RCU after the CPU is woken up.
 */
void tick_nohz_idle_enter(void)
{
        struct tick_sched *ts;

        WARN_ON_ONCE(irqs_disabled());

        /*
         * Update the idle state in the scheduler domain hierarchy
         * when tick_nohz_stop_sched_tick() is called from the idle loop.
         * State will be updated to busy during the first busy tick after
         * exiting idle.
         */             
        set_cpu_sd_state_idle();

        local_irq_disable();

        ts = this_cpu_ptr(&tick_cpu_sched);
        ts->inidle = 1;
        __tick_nohz_idle_enter(ts);

        local_irq_enable();
}

nohz idle에 진입함을 설정한다.

  • 코드 라인 25에서 스케줄 도메인에 현재 cpu가 idle 상태로 진입했음을 설정한다.
  • 코드 라인 29~30에서 tick_sched에 idle로 진입했음을 설정한다.
  • 코드 라인 31에서 nohz idle 상태로 진입한다.

 

set_cpu_sd_state_idle()

kernel/sched/fair.c

void set_cpu_sd_state_idle(void)
{
        struct sched_domain *sd;
        int cpu = smp_processor_id();

        rcu_read_lock();
        sd = rcu_dereference(per_cpu(sd_busy, cpu));
        
        if (!sd || sd->nohz_idle)
                goto unlock;
        sd->nohz_idle = 1;

        atomic_dec(&sd->groups->sgc->nr_busy_cpus);
unlock:
        rcu_read_unlock();
}

busy 스케줄 도메인에 nohz idle 상태를 설정한다.

  • 코드 라인 9~10에서 현재 cpu에 대한 busy 스케줄링 도메인이 없거나 nohz_idle 설정이 없으면 함수를 빠져나온다.
  • 코드 라인 11에서 현재 cpu에 대한 busy 스케줄링 도메인의 nohz_idle에 1을 설정하여 현재 cpu가 nohz idle 상태에 진입했음을 알린다.
  • 코드 라인 13에서 역시 스케줄링 도메인의 그룹 캐파에 busy cpu 수를 감소시킨다.

 

__tick_nohz_idle_enter()

kernel/time/tick-sched.c

static void __tick_nohz_idle_enter(struct tick_sched *ts)
{
        ktime_t now, expires;
        int cpu = smp_processor_id();

        now = tick_nohz_start_idle(ts);

        if (can_stop_idle_tick(cpu, ts)) {
                int was_stopped = ts->tick_stopped;

                ts->idle_calls++;

                expires = tick_nohz_stop_sched_tick(ts, now, cpu);
                if (expires.tv64 > 0LL) {
                        ts->idle_sleeps++;
                        ts->idle_expires = expires;
                }
                        
                if (!was_stopped && ts->tick_stopped)
                        ts->idle_jiffies = ts->last_jiffies;
        }       
}

nohz idle 상태로 진입한다.

  • 코드 라인 6에서 현재 시각으로 idle 시작 시간을 설정하고 알아온다.
  • 코드 라인 8에서 정상적으로 idle 처리를 위해 tick을 정지시켜야하는 경우
  • 코드 라인 9~11에서 기존 틱 정지 상태를 알아와서 was_stopped에 담고 idle 처리 카운터를 1 증가시킨다.
  • 코드 라인 13에서 정규 스케줄 틱을 정지 시키고 nohz 모드로 진입한다.  여러 이유로 타이머 프로그램을 한 경우 만료 시각을 반환한다.
  • 코드 라인 14~17에서 만료 시각이 설정된 경우 idle 슬립 카운터를 1 증가킨다.
  • 코드 라인 19~20에서 틱 운용 중에 정지 요청이 발생한 경우 idle_jiffies에 last_jiffies를 대입한다.

 

can_stop_idle_tick()

kernel/time/tick-sched.c

static bool can_stop_idle_tick(int cpu, struct tick_sched *ts)
{
        /*
         * If this cpu is offline and it is the one which updates
         * jiffies, then give up the assignment and let it be taken by
         * the cpu which runs the tick timer next. If we don't drop
         * this here the jiffies might be stale and do_timer() never
         * invoked.
         */
        if (unlikely(!cpu_online(cpu))) {
                if (cpu == tick_do_timer_cpu)
                        tick_do_timer_cpu = TICK_DO_TIMER_NONE;
                return false;
        }

        if (unlikely(ts->nohz_mode == NOHZ_MODE_INACTIVE)) {
                ts->sleep_length = (ktime_t) { .tv64 = NSEC_PER_SEC/HZ };
                return false;
        }

        if (need_resched())
                return false;

        if (unlikely(local_softirq_pending() && cpu_online(cpu))) {
                static int ratelimit;

                if (ratelimit < 10 &&
                    (local_softirq_pending() & SOFTIRQ_STOP_IDLE_MASK)) {
                        pr_warn("NOHZ: local_softirq_pending %02x\n",
                                (unsigned int) local_softirq_pending());
                        ratelimit++;
                }
                return false;
        }

        if (tick_nohz_full_enabled()) {
                /*
                 * Keep the tick alive to guarantee timekeeping progression
                 * if there are full dynticks CPUs around
                 */
                if (tick_do_timer_cpu == cpu)
                        return false;
                /*
                 * Boot safety: make sure the timekeeping duty has been
                 * assigned before entering dyntick-idle mode,
                 */
                if (tick_do_timer_cpu == TICK_DO_TIMER_NONE)
                        return false;
        }

        return true;
}

idle 처리를 위해 tick을 정지시켜야하는지 여부를 반환한다.

  • 코드 라인 10~14에서 낮은 확률로 요청한 cpu가 online이 아니면 false를 반환한다. 요청하는 cpu가 틱을 발생하는 cpu인 경우 tick_do_timer_cpu에 TICK_DO_TIMER_NONE(-1)을 대입하여 틱을 발생하는 cpu가 없다는 것을 설정하게 한다.
  • 코드 라인 16~19에서 앚은 확률로 nohz 모드가 설정되지 않은 상태인 경우 sleep_length에 1초에 해당하는 jiffies 값을 대입하고 false를 반환한다.
  • 코드 라인 21~22에서 리스케줄 요청이 있는 경우 false를 반환한다.
  • 코드 라인 24~34에서 낮은 확률로 현재 cpu에서 softirq 펜딩중인 경우 경고 메시지를 출력하고 false를 반환한다. 경고 메시지는 10회 미만일때 까지만 출력한다.
  • 코드 라인 36~49에서 nohz full이 enable된 경우이고 틱 타이머가 현재 cpu이거나 설정되지 않은 경우 false를 반환한다.
  • 코드 라인 51에서 그외의 경우 true를 반환한다.

 

tick_nohz_start_idle()

kernel/time/tick-sched.c

static ktime_t tick_nohz_start_idle(struct tick_sched *ts)
{
        ktime_t now = ktime_get();

        ts->idle_entrytime = now;
        ts->idle_active = 1;
        sched_clock_idle_sleep_event();
        return now;
}

틱 스케줄에게 nohz idle 진입함을 설정하고 현재 시각을 반환한다.

 

tick_nohz_stop_sched_tick()

정규 스케줄 틱을 정지 시키고 nohz 모드로 진입한다. lazy된 rcu 처리나 다른 타이머 요청이 있는 경우의 타이머에 대해서는 동작시킨다.(nohz full인 경우 1초 단위) 타이머를 동작시키는 경우 만료 시각을 반환한다.

kernel/time/tick-sched.c

static ktime_t tick_nohz_stop_sched_tick(struct tick_sched *ts,
                                         ktime_t now, int cpu)
{
        unsigned long seq, last_jiffies, next_jiffies, delta_jiffies;
        ktime_t last_update, expires, ret = { .tv64 = 0 };
        unsigned long rcu_delta_jiffies;
        struct clock_event_device *dev = __this_cpu_read(tick_cpu_device.evtdev);
        u64 time_delta;

        time_delta = timekeeping_max_deferment();

        /* Read jiffies and the time when jiffies were updated last */
        do {
                seq = read_seqbegin(&jiffies_lock);
                last_update = last_jiffies_update;
                last_jiffies = jiffies;
        } while (read_seqretry(&jiffies_lock, seq));

        if (rcu_needs_cpu(&rcu_delta_jiffies) ||
            arch_needs_cpu() || irq_work_needs_cpu()) {
                next_jiffies = last_jiffies + 1;
                delta_jiffies = 1;
        } else {
                /* Get the next timer wheel timer */
                next_jiffies = get_next_timer_interrupt(last_jiffies);
                delta_jiffies = next_jiffies - last_jiffies;
                if (rcu_delta_jiffies < delta_jiffies) {
                        next_jiffies = last_jiffies + rcu_delta_jiffies;
                        delta_jiffies = rcu_delta_jiffies;
                }
        }
  • 코드 라인 10에서 타임 키핑 클럭에서 유예된 최대 시간을 알아온다.
  • 코드 라인 13~17에서 jiffies를 읽어와서 last_jiffies에 대입한다.
  • 코드 라인 19~22에서 idle 모드에 진입하기 전에 현재 cpu에서 처리할 rcu 콜백들을 처리하거나 지연처리하고 0을 반환하거나 lazy rcu 용 지연된 jiffies 틱을 알아왔거나 irq work가 아직 처리되지 않은 것이 남아있는 경우 다음 jiffies에 last_jiffies+1을 한다.
    • arch_needs_cpu() 함수는 대부분의 아키텍처에서는 0을 반환하고 s390 아키텍처만 CIF_NOHZ_DELAY 플래그가 설정된 경우만 1이된다.
  • 코드 라인 23~31에서 지연되어 처리할 시간이 필요 없는 경우 다음 lowres 및 hrtimer에서 jiffies 단위의 가장 빠른 만료시각을 알아와서 next_jiffies에 대입한다. delta_jiffies에는 마지막 last_jiffies와의 차이 시간을 구한다. 만일 delta 기간이 rcu 처리에 필요한 틱보다 더 큰 경우 rcu에 필요한 기간도 더한다.

 

        /*
         * Do not stop the tick, if we are only one off (or less)
         * or if the cpu is required for RCU:
         */
        if (!ts->tick_stopped && delta_jiffies <= 1)
                goto out;

        /* Schedule the tick, if we are at least one jiffie off */
        if ((long)delta_jiffies >= 1) {

                /*
                 * If this cpu is the one which updates jiffies, then
                 * give up the assignment and let it be taken by the
                 * cpu which runs the tick timer next, which might be
                 * this cpu as well. If we don't drop this here the
                 * jiffies might be stale and do_timer() never
                 * invoked. Keep track of the fact that it was the one
                 * which had the do_timer() duty last. If this cpu is
                 * the one which had the do_timer() duty last, we
                 * limit the sleep time to the timekeeping
                 * max_deferement value which we retrieved
                 * above. Otherwise we can sleep as long as we want.
                 */
                if (cpu == tick_do_timer_cpu) {
                        tick_do_timer_cpu = TICK_DO_TIMER_NONE;
                        ts->do_timer_last = 1;
                } else if (tick_do_timer_cpu != TICK_DO_TIMER_NONE) {
                        time_delta = KTIME_MAX;
                        ts->do_timer_last = 0;
                } else if (!ts->do_timer_last) {
                        time_delta = KTIME_MAX;
                }

#ifdef CONFIG_NO_HZ_FULL
                if (!ts->inidle) {
                        time_delta = min(time_delta,
                                         scheduler_tick_max_deferment());
                }
#endif
  • 코드 라인 5~6에서 이미 틱이 스탑되었었던 경우이면서 delta 틱이 1이하인 경우 처리를 중단하고 함수를 빠져나간다.
  • 코드 라인 9에서 delta 틱이 1 이상인 경우
  • 코드 라인 24~26에서 요청한 cpu가 현재 틱을 생성하는 cpu인 경우 tick_do_timer_cpu에 none을 대입하고 do_timer_last에 1을 대입한다.
  • 코드 라인 27~29에서 그렇지 않고 현재 틱을 생성하는 cpu가 지정된 경우 time_delta에 KTIME_MAX를 대입하고 do_timer_last에 0을 대입한다.
  • 코드 라인 30~32에서 그렇지 않고 do_timer_last가 0인 경우 time_delta에 KTIME_MAX를 대입한다.
  • 코드 라인 35~38에서 nohz full을 지원하는 시스템에서 inidle이 0인 경우 time_delta와 nohz full이 필요한 시간에서 작은 시간으로 time_delta를 구한다.
    • nohz full은 완벽하게 nohz로 아직 동작하지 않는다. uptime, CFS vruntime, 로드 밸런싱, … 등 아직 이전이 완료되지 않아서 다음 스케줄링에 필요한 틱에 1초를 더해 나노단위로 반환한다.

 

                /*
                 * calculate the expiry time for the next timer wheel
                 * timer. delta_jiffies >= NEXT_TIMER_MAX_DELTA signals
                 * that there is no timer pending or at least extremely
                 * far into the future (12 days for HZ=1000). In this
                 * case we set the expiry to the end of time.
                 */
                if (likely(delta_jiffies < NEXT_TIMER_MAX_DELTA)) {
                        /*
                         * Calculate the time delta for the next timer event.
                         * If the time delta exceeds the maximum time delta
                         * permitted by the current clocksource then adjust
                         * the time delta accordingly to ensure the
                         * clocksource does not wrap.
                         */
                        time_delta = min_t(u64, time_delta,
                                           tick_period.tv64 * delta_jiffies);
                }

                if (time_delta < KTIME_MAX)
                        expires = ktime_add_ns(last_update, time_delta);
                else
                        expires.tv64 = KTIME_MAX;

                /* Skip reprogram of event if its not changed */
                if (ts->tick_stopped && ktime_equal(expires, dev->next_event))
                        goto out;

                ret = expires;

                /*
                 * nohz_stop_sched_tick can be called several times before
                 * the nohz_restart_sched_tick is called. This happens when
                 * interrupts arrive which do not cause a reschedule. In the
                 * first call we save the current tick time, so we can restart
                 * the scheduler tick in nohz_restart_sched_tick.
                 */
                if (!ts->tick_stopped) {
                        nohz_balance_enter_idle(cpu);
                        calc_load_enter_idle();

                        ts->last_tick = hrtimer_get_expires(&ts->sched_timer);
                        ts->tick_stopped = 1;
                        trace_tick_stop(1, " ");
                }
  • 코드 라인 8~18에서 delta_jiffies가 1G-1 틱 미만인 경우 time_delta와 delta_jiffies를 나노초로 변환한 시간 중 작은 기간을 time_delta로 한다.
  • 코드 라인 20~23에서 time_delta가 KTIME_MAX보다 작은 경우 만료시각으로 last_update에 time_delta를 추가한다. 그렇지 않은 경우 최대 만료 시각을 담는다.
  • 코드 라인 26~27에서 틱이 이미 정지된 상태이고 이미 동일한 만료 시각으로 설정된 경우는 변경 사항이 없는 경우이므로 함수를 빠져나간다.
  • 코드 라인 29에서 반환 값으로 만료 시각을 대입한다.
  • 코드 라인 38~45에서 요청 cpu의 틱이 동작 중인 경우 로드밸런스를 위해 틱이 정지되어 idle 상태로 진입할 것이라 설정하고,  nohz 모드 진입으로 calc_load_idle도 갱신한다. 또한 last_tick을 스케줄 타이머의 만료시각으로 갱신하고 tick_stopped에 1을 대입하여 틱이 정지된 상태임을 알린다.

 

                /*
                 * If the expiration time == KTIME_MAX, then
                 * in this case we simply stop the tick timer.
                 */
                 if (unlikely(expires.tv64 == KTIME_MAX)) {
                        if (ts->nohz_mode == NOHZ_MODE_HIGHRES)
                                hrtimer_cancel(&ts->sched_timer);
                        goto out;
                }

                if (ts->nohz_mode == NOHZ_MODE_HIGHRES) {
                        hrtimer_start(&ts->sched_timer, expires,
                                      HRTIMER_MODE_ABS_PINNED);
                        /* Check, if the timer was already in the past */
                        if (hrtimer_active(&ts->sched_timer))
                                goto out;
                } else if (!tick_program_event(expires, 0))
                                goto out;
                /*
                 * We are past the event already. So we crossed a
                 * jiffie boundary. Update jiffies and raise the
                 * softirq.
                 */
                tick_do_update_jiffies64(ktime_get());
        }
        raise_softirq_irqoff(TIMER_SOFTIRQ);
out:
        ts->next_jiffies = next_jiffies;
        ts->last_jiffies = last_jiffies;
        ts->sleep_length = ktime_sub(dev->next_event, now);

        return ret;
}
  • 코드 라인 5~9에서 만료 시각이 최대치로 설정된 경우 nohz 모드가 high-resolution을 사용하는 타이머인 경우 스케줄 타이머를 정지하고 함수를 빠져나간다.
  • 코드 라인 11~16에서 nohz 모드가 high-resolution을 사용하는 타이머인 경우 만료 시각으로 틱 스케줄 타이머를 가동시킨다. 만일 잘 가동된 경우 함수를 빠져나간다.
  • 코드 라인 17~18에서 만료 시각으로 틱 프로그램을 하고 성공(0)한 경우 함수를 빠져나간다.
  • 코드 라인 24에서 jiffies 값을 갱신한다.
  • 코드 라인 26에서 lowres 타이머용 softirq를 트리거한다.
  • 코드 라인 28~32에서 틱의 next_jiffies, last_jiffies, sleep_length를 갱신하고 ret를 반환한다.

 

nohz_balance_enter_idle()

kernel/sched/fair.c

/*
 * This routine will record that the cpu is going idle with tick stopped.
 * This info will be used in performing idle load balancing in the future.
 */
void nohz_balance_enter_idle(int cpu)
{
        /* 
         * If this cpu is going down, then nothing needs to be done.
         */
        if (!cpu_active(cpu))
                return;

        if (test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))
                return;

        /*
         * If we're a completely isolated CPU, we don't play.
         */
        if (on_null_domain(cpu_rq(cpu)))
                return;

        cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
        atomic_inc(&nohz.nr_cpus);
        set_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
}

로드밸런스를 위해 틱이 정지되어 idle 상태로 진입할 것이라 설정한다.

 

  • 코드 라인 10~11에서 요청한 cpu가 active cpu가 아닌 경우 함수를 빠져나간다.
  • 코드 라인 13~14에서 런큐 nohz_flags에 이미 NOHZ_TICK_STOPPED 플래그가 설정된 경우 함수를 빠져나간다.
    • 이미 nohz idle 진입했음을 알아낸다.
  • 코드 라인 19~20에서 요청한 cpu의 런큐에 스케줄 도메인이 없는 경우 함수를 빠져나간다.
  • 코드 라인 22에서 nohz.idle_cpus_mask 비트맵에 요청한 cpu에 해당하는 비트를 설정하여 idle 상태임을 알린다.
  • 코드 라인 23에서 nohz.nr_cpus를 1 증가시켜 nohz idle 상태로 진입한 cpu의 수를 나타내게한다.
  • 코드 라인 24에서 런큐 nohz_flags에 NOHZ_TICK_STOPPED 플래그를 설정한다.

 

calc_load_enter_idle()

kernel/sched/proc.c

void calc_load_enter_idle(void)
{
        struct rq *this_rq = this_rq();
        long delta;     

        /*
         * We're going into NOHZ mode, if there's any pending delta, fold it
         * into the pending idle delta.
         */     
        delta = calc_load_fold_active(this_rq);
        if (delta) {
                int idx = calc_load_write_idx();
                atomic_long_add(delta, &calc_load_idle[idx]);
        }               
}

nohz idle 진입 시 로드값을 갱신한다.

  • 코드 라인 10에서 요청한 런큐의 기존 active 태스크 수와 현재 산출한 active 태스크 수의 차이를 산출한다.
  • 코드 라인 11~14에서 그 차이가 발생하는 경우 로드 계산에 사용할 인덱스를 알아와서 그 인덱스로 calc_load_idle[]에 delta를 추가한다.

 

nohz idle에서 벗어날 때

tick_nohz_idle_exit()

kernel/time/tick-sched.c

/**
 * tick_nohz_idle_exit - restart the idle tick from the idle task
 *
 * Restart the idle tick when the CPU is woken up from idle
 * This also exit the RCU extended quiescent state. The CPU
 * can use RCU again after this function is called.
 */
void tick_nohz_idle_exit(void)
{
        struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
        ktime_t now;

        local_irq_disable();

        WARN_ON_ONCE(!ts->inidle);

        ts->inidle = 0;

        if (ts->idle_active || ts->tick_stopped)
                now = ktime_get();

        if (ts->idle_active)
                tick_nohz_stop_idle(ts, now);

        if (ts->tick_stopped) { 
                tick_nohz_restart_sched_tick(ts, now);
                tick_nohz_account_idle_ticks(ts);
        }

        local_irq_enable();
}

nohz idle이 종료되었음을 설정하고 틱을 리스타트한다.

  • 코드 라인 17에서  tick_sched에 idle에서 벗어났음을 설정한다.
  • 코드 라인 19~20에서 idle_active 또는 tick_stopped가 설정된 경우 현재 시각을 알아온다.
  • 코드 라인 22~23에서 idle_active가 설정된 경우 현재 시각으로 nohz가 stop 되었음을 알린다.
  • 코드 라인 25에서 tick_stopped가 설정된 경우 현재 시각을 기준으로 nohz 틱을 리스타트하고 측정과 관련하여 갱신한다.

 

tick_nohz_stop_idle()

kernel/time/tick-sched.c

static void tick_nohz_stop_idle(struct tick_sched *ts, ktime_t now)
{
        update_ts_time_stats(smp_processor_id(), ts, now, NULL);
        ts->idle_active = 0;

        sched_clock_idle_wakeup_event(0);
}

 

요청한 틱 스케줄러의 idle_active에 0을 대입하여 nohz가 stop 되었음을 나타낸다.

  • sched_clock_idle_wakeup_event()는 unstable 클럭을 사용하는 경우에 수행되며 arm 아키텍처에서는 아무것도 수행하지 않는다.

 

tick_nohz_restart_sched_tick()

kernel/time/tick-sched.c

static void tick_nohz_restart_sched_tick(struct tick_sched *ts, ktime_t now)
{
        /* Update jiffies first */
        tick_do_update_jiffies64(now);
        update_cpu_load_nohz();

        calc_load_exit_idle();
        touch_softlockup_watchdog();
        /*
         * Cancel the scheduled timer and restore the tick
         */
        ts->tick_stopped  = 0;
        ts->idle_exittime = now;

        tick_nohz_restart(ts, now);
}

 

nohz 틱을 다시 리스타트 한다.

  • 코드 라인 4에서 jiffes를 갱신한다.
  • 코드 라인 5에서 cpu load를 갱신한다.
  • 코드 라인 7에서 idle을 빠져나가는 것에 대해 로드 밸런스 체크 주기를 갱신한다.
  • 코드 라인 12~15에서 tick_stopped에 0을 대입하고 idle 끝시각을 현재 시각으로 갱신하고 틱 nohz를 다시 시작한다.

 

tick_nohz_restart()

kernel/time/tick-sched.c

static void tick_nohz_restart(struct tick_sched *ts, ktime_t now)
{
        hrtimer_cancel(&ts->sched_timer);
        hrtimer_set_expires(&ts->sched_timer, ts->last_tick);

        while (1) {
                /* Forward the time to expire in the future */
                hrtimer_forward(&ts->sched_timer, now, tick_period);

                if (ts->nohz_mode == NOHZ_MODE_HIGHRES) {
                        hrtimer_start_expires(&ts->sched_timer,
                                              HRTIMER_MODE_ABS_PINNED);
                        /* Check, if the timer was already in the past */
                        if (hrtimer_active(&ts->sched_timer))
                                break;
                } else {
                        if (!tick_program_event(
                                hrtimer_get_expires(&ts->sched_timer), 0))
                                break;
                }
                /* Reread time and update jiffies */
                now = ktime_get();
                tick_do_update_jiffies64(now);
        }
}

nohz 틱을 다시 리프로그램한다.

  • 코드 라인 3에서 기존 스케줄 틱을 정지시킨다.
  • 코드 라인 4에서 last_tick으로 스케줄 타이머의 만료 시각을 다시 설정한다.
  • 코드 라인 6에서 루프를 돌며 tick_period 기간으로 스케줄 타이머를 동작 시킨다.
  • 코드 라인 8~13에서 nohz_mode가 NOHZ_MODE_HIGHRES로 설정된 경우 스케줄 타이머를 동작시킨다. 만일 정상적으로 가동된 경우 함수를 빠져나간다.
  • 코드 라인 14~18에서 다른 모드로 설정된 경우 틱 이벤트를 다시 프로그램하고 함수를 빠져나간다.
  • 코드 라인 20~21에서 리프로그램이 실패한 경우 jiffies를 갱신하고 루프를 다시 돈다.

 

 

nohz full 킥

kernel/time/tick-sched.c

static DEFINE_PER_CPU(struct irq_work, nohz_full_kick_work) = {
        .func = nohz_full_kick_work_func,
};

nohz_full_kick_work_func() 함수를 호출하는 per-cpu nohz_full_kick_work라는 이름의 irq 워크큐를 선언한다.

 

tick_nohz_full_kick()

kernel/time/tick-sched.c

/*
 * Kick this CPU if it's full dynticks in order to force it to
 * re-evaluate its dependency on the tick and restart it if necessary.
 * This kick, unlike tick_nohz_full_kick_cpu() and tick_nohz_full_kick_all(),
 * is NMI safe.
 */
void tick_nohz_full_kick(void)
{
        if (!tick_nohz_full_cpu(smp_processor_id()))
                return;

        irq_work_queue(this_cpu_ptr(&nohz_full_kick_work));
}

현재 cpu가 nohz full 모드로 동작하는 경우 nohz_full_kick_work를 irq 워크큐에 추가한 후 ipi call을 호출한다.

 

tick_nohz_full_kick_cpu()

kernel/time/tick-sched.c

/*
 * Kick the CPU if it's full dynticks in order to force it to
 * re-evaluate its dependency on the tick and restart it if necessary.
 */
void tick_nohz_full_kick_cpu(int cpu)
{
        if (!tick_nohz_full_cpu(cpu))
                return;

        irq_work_queue_on(&per_cpu(nohz_full_kick_work, cpu), cpu);
}

요청한 cpu가 nohz full 모드로 동작하는 경우 nohz_full_kick_work를 irq 워크큐에 추가한 후 ipi call을 호출한다.

 

nohz_full_kick_work_func()

kernel/time/tick-sched.c

static void nohz_full_kick_work_func(struct irq_work *work)
{
        __tick_nohz_full_check();
}

ipi 호출되었다. nohz full 상태를 체크하여 필요한 경우 틱을 재개시킨다.

 

__tick_nohz_full_check()

kernel/time/tick-sched.c

/*
 * Re-evaluate the need for the tick on the current CPU
 * and restart it if necessary.
 */
void __tick_nohz_full_check(void)
{
        struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);

        if (tick_nohz_full_cpu(smp_processor_id())) {
                if (ts->tick_stopped && !is_idle_task(current)) {
                        if (!can_stop_full_tick())
                                tick_nohz_restart_sched_tick(ts, ktime_get());
                }
        }
}

nohz full 상태를 체크하여 필요한 경우 틱을 재개시킨다.

  • 코드 라인 9~에서 현재 cpu가 nohz full 상태, tick 정지, 현재 태스크가 idle 상태가 아니고 nohz full을 멈출 수 없는 경우 틱을 정지시킨 후 다시 재개시킨다.

 

참고

 

 

댓글 남기기