您的位置:首页 > 运维架构 > Linux

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

2016-04-16 14:39 691 查看
刘畅 原创作品转载请注明出处 《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).

SAVE_ALL //保存现场

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

标号1之后开始运行用户态进程Y(这里Y曾经通过以上步骤被切换出去过因此可以从标号1继续执行)

restore_all //恢复现场

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

继续运行用户态进程Y

几种特殊的情况:

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

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

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

加载一个新的可执行程序后返回到用户态的情况,如execve;

总结

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

内核线程可以通过调用schedule完成进程调度,而用户进程只能通过系统调用或者发生异常时,才能进入内核态来进行schedule调度的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息