/* * schedule() is the main scheduler function. */ asmlinkage 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();//获取当前CPU的ID rq = cpu_rq(cpu);//获取当前CPU上的rq(run queue)队列 rcu_note_context_switch(cpu);//?????? prev = rq->curr; //当前进程就是需要被切换出去的进程 schedule_debug(prev);//time debugging checks and statistics if (sched_feat(HRTICK)) hrtick_clear(rq); raw_spin_lock_irq(&rq->lock); switch_count = &prev->nivcsw; if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) { //如果当前进程处于stopped状态,并且处于可抢占状态??? if (unlikely(signal_pending_state(prev->state, prev))) {//如果没有待处理的信号??? prev->state = TASK_RUNNING; //则将当前进程的状态设置为RUNNING } else { //如果有待处理的信号 deactivate_task(rq, prev, DEQUEUE_SLEEP); //将当前进程从运行队列中移走 prev->on_rq = 0; //表明当前进程已经不在rq队列中了。 /* * 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); } /* * If we are going to sleep and we have plugged IO * queued, make sure to submit it to avoid deadlocks. */ if (blk_needs_flush_plug(prev)) { //冲刷IO raw_spin_unlock(&rq->lock); blk_schedule_flush_plug(prev); raw_spin_lock(&rq->lock); } } switch_count = &prev->nvcsw; } pre_schedule(rq, prev); //如果非SMP或者非实时任务调度,则为空操作;否则,将当前rt任务放回,并挑选另一个优先级更高的rt任务放到相对空闲的cpu中运行。 if (unlikely(!rq->nr_running))//当然,这个也是针对SMP而言的,因为在上一步过后,可能出现有的cpu空转的现象,所以要在smp间调度 idle_balance(cpu, rq); put_prev_task(rq, prev);//主要是更新待切换进程的运行时间等参数。 next = pick_next_task(rq); //寻找下一个合适的进程以将其调度进来,这是核心函数,我们会在另外一篇博文中详述。 clear_tsk_need_resched(prev);//TIF_NEED_RESCHED indicates that the process should be or would like to be replaced with another process by the scheduler. 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); //和pre_schedule一样,只有在SMP中调度rt任务时才会被实际的执行,否则为空;同时与pre_schedule的作用类似, /*这个函数的作用是: * If the current CPU has more than one RT task, see if the non * running task can migrate over to a CPU that is running a task * of lesser priority. */ preempt_enable_no_resched(); if (need_resched()) //如果被切换进来的进程仍需要被调度,则返回至need_resched,重新调度。 goto need_resched; }