Linux内核分析:实验八

Linux进程调度与切换

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

实验概述

进程调度和上下文切换的过程,会涉及到进度调度的时机和进程的切换执行过程,并通过GDB跟踪Linux的schedule()函数来比较深入的理解。

调度策略和时机

调度策略

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

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

调度时机

进程的调度通过schedule()函数实现的,它是个内核函数,不是用户态函数。所以用户态的进程不能直接调用,只能间接调用,内核线程是只有内核态没有用户态的特殊进程。进程调度发生在下面几种情况下:

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

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

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

关于shedule()函数

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来进行上下文切换。

 

进程上下文切换

宏定义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中进程的上下文切换就是根据switch_to来编写的,它保存前一个进程的espebpeip的值,并把下一个进程的espeipebp的值放到CPU相应的寄存器中,从而实现进程的切换。这段代码是用宏汇编的形式,需要有相当的汇编水平才能看懂,但要表达的目的很清晰,就是把保存上一个进程的espebpeip,并且把下一个待调度的进程的上下文置入CPU相应的寄存器中。

 

使用GDB跟踪schedule函数:

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

进程切换总述

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

2. 发生中断——savecs:eip/esp/eflags(current) to kernel stack,then load cs:eip(entry of a specificISR) 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. 继续运行用户态进程B

总结

Linux进程的调度和切换是通过schedule函数来实现的,进程的调度和切换是需要时机的,并不是任何时刻都能发生进程的调度、切换的。一般情况下在中断或者异常发生的情况下,Linux会发生进程的切换。

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值