gavanwanggw

导航

Linux内核分析:实验八--Linux进程调度与切换

刘畅 原创作品转载请注明出处 《Linux内核分析》MOOC课程http://mooc.study.163.com/course/USTC-1000029000

概述

这篇文章主要分析Linux中,进程调度和上下文切换的过程,会涉及到进度调度的时机和进程的切换运行过程,并通过GDB跟踪Linux的schedule()函数来比較深入的理解一下这个过程。

进程调度策略与调度时机

调度策略

操作系统中包括有非常多进程调度的算法,内核会根据进程的属性来选择不同的调度策略。进程能够比較粗略的分为:IO密集型的和CPU计算密集型的,为了让计算机的资源有非常高的利用率。内核会根据进程的基本属性来选择不同的调度策略。

调度类型又可分为分时调度和优先级调度,分时调度就是为每一个进程分配不同的时间片。而优先级调度会从优先队列中选取优先级最高的那个进程调度。须要注意的是,在运行的过程中,进程的优先级会发生变化的。一般来说,运行越长时间的进程,优先级会减少。而等待时间越久进程的优先级会逐渐添加。

调度时机

在前面一篇博文分析Linux系统调用的过程中。我们知道在系统调用运行完毕之前会调用一次work_pending,也就是说在系统调用运行完毕之前可能会发生进程的切换,非常显然系统调度是Linux内核进程调度的一个时机。

进程的调度通过schedule()函数实现的。它是个内核函数,不是用户态函数。所以用户态的进程不能直接调用,仅仅能间接调用。内核线程是仅仅有内核态没实用户态的特殊进程。

进程调度发生在以下几种情况下:

1.中断处理过程(包括时钟中断、I/O中断、系统调用和异常)中。直接调用schedule()。或者返回用户态时根据need_resched标记调用schedule();

2.内核线程能够直接调用schedule()进行进程切换,也能够在中断处理过程中进行调度,也就是说内核线程作为一类的特殊的进程能够主动调度。也能够被动调度。

3.用户态进程无法实现主动调度。仅能通过陷入内核态后的某个时机点进行调度。即在中断处理过程中进行调度。

schedule函数概述

schedule函数位于/kernel/sched/core.c文件里,其内核代码描写叙述例如以下:

static void __sched __schedule(void)
{
    struct task_struct *prev, *next;
    unsigned long *switch_count;
    struct rq *rq;
    int cpu;

need_resched:
    preempt_disable();
    cpu = smp_processor_id();
    rq = cpu_rq(cpu);
    rcu_note_context_switch(cpu);
    prev = rq->curr;

    schedule_debug(prev);

    if (sched_feat(HRTICK))
        hrtick_clear(rq);

    /*
     * Make sure that signal_pending_state()->signal_pending() below
     * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
     * done by the caller to avoid the race with signal_wake_up().
     */
    smp_mb__before_spinlock();
    raw_spin_lock_irq(&rq->lock);

    switch_count = &prev->nivcsw;
    if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
        if (unlikely(signal_pending_state(prev->state, prev))) {
            prev->state = TASK_RUNNING;
        } else {
            deactivate_task(rq, prev, DEQUEUE_SLEEP);
            prev->on_rq = 0;

            /*
             * If a worker went to sleep, notify and ask workqueue
             * whether it wants to wake up a task to maintain
             * concurrency.
             */
            if (prev->flags & PF_WQ_WORKER) {
                struct task_struct *to_wakeup;

                to_wakeup = wq_worker_sleeping(prev, cpu);
                if (to_wakeup)
                    try_to_wake_up_local(to_wakeup);
            }
        }
        switch_count = &prev->nvcsw;
    }

    if (task_on_rq_queued(prev) || rq->skip_clock_update < 0)
        update_rq_clock(rq);

    next = pick_next_task(rq, prev);
    clear_tsk_need_resched(prev);
    clear_preempt_need_resched();
    rq->skip_clock_update = 0;

    if (likely(prev != next)) {
        rq->nr_switches++;
        rq->curr = next;
        ++*switch_count;

        context_switch(rq, prev, next); /* unlocks the rq */
        /*
         * The context switch have flipped the stack from under us
         * and restored the local variables which were saved when
         * this task called schedule() in the past. prev == current
         * is still correct, but it can be moved to another cpu/rq.
         */
        cpu = smp_processor_id();
        rq = cpu_rq(cpu);
    } else
        raw_spin_unlock_irq(&rq->lock);

    post_schedule(rq);

    sched_preempt_enable_no_resched();
    if (need_resched())
        goto need_resched;
}

schedule()函数主要工作是通过pick_next_task选择一个新的进程来运行,并调用context_switch进行上下文的切换,这个宏调用switch_to来进行上下文切换。

pick_next_task函数中就是Linux内核中的进度调度策略了,这里没有深入进去,这篇文章目的在于理清Linux中进程的调度流程。

进程上下文的切换

上面一节说道进程通过switch_to来进行上下文的切换,switch_to是一个宏定义。其描写叙述例如以下:

#define switch_to(prev, next, last)                 \
do {                                    \
    /*                              \
     * Context-switching clobbers all registers, so we clobber  \
     * them explicitly, via unused output variables.        \
     * (EAX and EBP is not listed because EBP is saved/restored \
     * explicitly for wchan access and EAX is the return value of   \
     * __switch_to())                       \
     */                             \
    unsigned long ebx, ecx, edx, esi, edi;              \
                                    \
    asm volatile("pushfl\n\t"       /* save    flags */ \
             "pushl %%ebp\n\t"      /* save    EBP   */ \
             "movl %%esp,%[prev_sp]\n\t"    /* save    ESP   */ \
             "movl %[next_sp],%%esp\n\t"    /* restore ESP   */ \
             "movl $1f,%[prev_ip]\n\t" /* save    EIP   */ \
             "pushl %[next_ip]\n\t" /* restore EIP   */ \
             __switch_canary                    \
             "jmp __switch_to\n"    /* regparm call  */ \
             "1:\t"                     \
             "popl %%ebp\n\t"       /* restore EBP   */ \
             "popfl\n"          /* restore flags */ \
                                    \
             /* output parameters */                \
             : [prev_sp] "=m" (prev->thread.sp),        \
               [prev_ip] "=m" (prev->thread.ip),        \
               "=a" (last),                 \
                                    \
               /* clobbered output registers: */        \
               "=b" (ebx), "=c" (ecx), "=d" (edx),      \
               "=S" (esi), "=D" (edi)               \
                                        \
               __switch_canary_oparam               \
                                    \
               /* input parameters: */              \
             : [next_sp]  "m" (next->thread.sp),        \
               [next_ip]  "m" (next->thread.ip),        \
                                        \
               /* regparm parameters for __switch_to(): */  \
               [prev]     "a" (prev),               \
               [next]     "d" (next)                \
                                    \
               __switch_canary_iparam               \
                                    \
             : /* reloaded segment registers */         \
            "memory");                  \
} while (0)

之前MenuOS中的Mykernel中进程的上下文切换就是一根据这个宏定编写的。它保存前一个进程的esp、ebp、eip的值。并把下一个进程的esp、eip、ebp的值放到CPU对应的寄存器中,这样实现了进程的切换。这段代码是用宏汇编的形式,不熟悉的汇编的情况下看起来非常吃力,但要表达的目的非常清晰。就是把保存上一个进程的esp、ebp、eip,而且把下一个待调度的进程的上下文置入CPU对应的寄存器中。

GDB跟踪schedule函数运行过程

GDB跟踪过程跟前几篇文章中叙述的相似。在schedule处设下断点,内核进程切换运行的流程下图所看到的:

这里写图片描写叙述

这里写图片描写叙述

这里写图片描写叙述

这里写图片描写叙述

Linux系统运行总览

最普通情况:正在运行的用户态进程X切换到运行用户态进程Y的过程

1.正在运行的用户态进程X

2.发生中断——save cs:eip/esp/eflags(current) to kernel stack,then load cs:eip(entry of a specific ISR) and ss:esp(point to kernel stack).

  1. SAVE_ALL //保存现场

  2. 中断处理过程中或中断返回前调用了schedule()。当中的switch_to做了关键的进程上下文切换

  3. 标号1之后開始运行用户态进程Y(这里Y以前通过以上步骤被切换出去过因此能够从标号1继续运行)

  4. restore_all //恢复现场

  5. iret - pop cs:eip/ss:esp/eflags from kernel stack

  6. 继续运行用户态进程Y

几种特殊的情况:

  1. 通过中断处理过程中的调度时机,用户态进程与内核线程之间互相切换和内核线程之间互相切换。与最一般的情况非常相似,仅仅是内核线程运行过程中发生中断没有进程用户态和内核态的转换。

  2. 内核线程主动调用schedule()。仅仅有进程上下文的切换,没有发生中断上下文的切换,与最一般的情况略简略;

  3. 创建子进程的系统调用在子进程中的运行起点及返回用户态,如fork;

  4. 载入一个新的可运行程序后返回到用户态的情况,如execve;

总结

Linux进程的调度和切换是通过schedule函数来实现的,进程的调度和切换是须要时机的。并非不论什么时刻都能发生进程的调度、切换的。普通情况下在中断或者异常发生的情况下,Linux会发生进程的切换。

内核线程能够通过调用schedule完毕进程调度,而用户进程仅仅能通过系统调用或者发生异常时,才干进入内核态来进行schedule调度的。

posted on 2017-08-07 13:21  gavanwanggw  阅读(645)  评论(0编辑  收藏  举报