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

对于现代操作系统,多任务是必备的,在linux系统下,进程会不断的被内核调度,从X进程切换为Y进程,以实现用户所见到的多任务状态,下面我们就看一看这样的过程,分析一下内核如何对进程调度,以及进程间如何切换。

内核使用schedule()函数实现进程的调度,而通常的用户进程要无法主动调度这个函数,只能通过中断处理过程(包括时钟中断、I/O中断、系统调用和异常)在某个合适的时机点被动调度;对于现代操作系统,还有内核线程,而内核线程是可以直接调度schedule函数的,只有内核态,当然也可以象用户态进程一样在中断处理过程中被动调度。

为了控制进程的执行,内核必须有能力挂起正在CPU上执行的进程,并恢复以前挂起的某个进程的执行,这叫做进程切换、任务切换、上下文切换;挂起正在CPU上执行的进程,与中断时保存现场不同的,中断前后是在同一个进程上下文中,只是由用户态转向内核态执行;而进程切换是在两个进程之间进行转换,切换前后的上下文是在不同的进程空间。进程上下文包含了进程执行需要的所有信息:用户地址空间:包括程序代码,数据,用户堆栈等;控制信息:进程描述符,内核堆栈等;硬件上下文。

下面将进程切换的关键代码摘录如下:

1、schedule函数

asmlinkage __visible void __sched schedule(void)
{struct task_struct *tsk = current;sched_submit_work(tsk);__schedule();
}

2、__schedule()函数

2770static void __sched __schedule(void)
2771{
2772    struct task_struct *prev, *next;
2773    unsigned long *switch_count;
2774    struct rq *rq;
2775    int cpu;
2776
2777need_resched:
2778    preempt_disable();
2779    cpu = smp_processor_id();
2780    rq = cpu_rq(cpu);
2781    rcu_note_context_switch(cpu);
2782    prev = rq->curr;
2783
2784    schedule_debug(prev);
2785
2786    if (sched_feat(HRTICK))
2787        hrtick_clear(rq);
2788
2789    /*
2790     * Make sure that signal_pending_state()->signal_pending() below
2791     * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
2792     * done by the caller to avoid the race with signal_wake_up().
2793     */
2794    smp_mb__before_spinlock();
2795    raw_spin_lock_irq(&rq->lock);
2796
2797    switch_count = &prev->nivcsw;
2798    if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2799        if (unlikely(signal_pending_state(prev->state, prev))) {
2800            prev->state = TASK_RUNNING;
2801        } else {
2802            deactivate_task(rq, prev, DEQUEUE_SLEEP);
2803            prev->on_rq = 0;
2804
2805            /*
2806             * If a worker went to sleep, notify and ask workqueue
2807             * whether it wants to wake up a task to maintain
2808             * concurrency.
2809             */
2810            if (prev->flags & PF_WQ_WORKER) {
2811                struct task_struct *to_wakeup;
2812
2813                to_wakeup = wq_worker_sleeping(prev, cpu);
2814                if (to_wakeup)
2815                    try_to_wake_up_local(to_wakeup);
2816            }
2817        }
2818        switch_count = &prev->nvcsw;
2819    }
2820
2821    if (task_on_rq_queued(prev) || rq->skip_clock_update < 0)
2822        update_rq_clock(rq);
2823
2824    next = pick_next_task(rq, prev);
2825    clear_tsk_need_resched(prev);
2826    clear_preempt_need_resched();
2827    rq->skip_clock_update = 0;
2828
2829    if (likely(prev != next)) {
2830        rq->nr_switches++;
2831        rq->curr = next;
2832        ++*switch_count;
2833
2834        context_switch(rq, prev, next); /* unlocks the rq */
2835        /*
2836         * The context switch have flipped the stack from under us
2837         * and restored the local variables which were saved when
2838         * this task called schedule() in the past. prev == current
2839         * is still correct, but it can be moved to another cpu/rq.
2840         */
2841        cpu = smp_processor_id();
2842        rq = cpu_rq(cpu);
2843    } else
2844        raw_spin_unlock_irq(&rq->lock);
2845
2846    post_schedule(rq);
2847
2848    sched_preempt_enable_no_resched();
2849    if (need_resched())
2850        goto need_resched;
2851}

其中关键语句:

struct task_struct *prev, *next;
next = pick_next_task(rq, prev);        //进程调度算法
context_switch(rq, prev, next); /* unlocks the rq */ //进程上下文切换

3、context_switch函数

2332 * context_switch - switch to the new MM and the new
2333 * thread's register state.
2334 */
2335static inline void
2336context_switch(struct rq *rq, struct task_struct *prev,
2337           struct task_struct *next)
2338{
2339    struct mm_struct *mm, *oldmm;
2340
2341    prepare_task_switch(rq, prev, next);
2342
2343    mm = next->mm;
2344    oldmm = prev->active_mm;
2345    /*
2346     * For paravirt, this is coupled with an exit in switch_to to
2347     * combine the page table reload and the switch backend into
2348     * one hypercall.
2349     */
2350    arch_start_context_switch(prev);
2351
2352    if (!mm) {
2353        next->active_mm = oldmm;
2354        atomic_inc(&oldmm->mm_count);
2355        enter_lazy_tlb(oldmm, next);
2356    } else
2357        switch_mm(oldmm, mm, next);
2358
2359    if (!prev->mm) {
2360        prev->active_mm = NULL;
2361        rq->prev_mm = oldmm;
2362    }
2363    /*
2364     * Since the runqueue lock will be released by the next
2365     * task (which is an invalid locking op but in the case
2366     * of the scheduler it's an obvious special-case), so we
2367     * do an early lockdep release here:
2368     */
2369    spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2370
2371    context_tracking_task_switch(prev, next);
2372    /* Here we just switch the register state and the stack. */
2373    switch_to(prev, next, prev);
2374
2375    barrier();
2376    /*
2377     * this_rq must be evaluated again because prev may have moved
2378     * CPUs since it called schedule(), thus the 'rq' on its stack
2379     * frame will be invalid.
2380     */
2381    finish_task_switch(this_rq(), prev);
2382}

4、switch_to宏定义了一段内联汇编代码

31#define switch_to(prev, next, last)                   \
32do {                                  \
33  /*                              \
34   * Context-switching clobbers all registers, so we clobber  \
35   * them explicitly, via unused output variables.        \
36   * (EAX and EBP is not listed because EBP is saved/restored \
37   * explicitly for wchan access and EAX is the return value of   \
38   * __switch_to())                       \
39   */                             \
40  unsigned long ebx, ecx, edx, esi, edi;              \
41                                  \
42  asm volatile("pushfl\n\t"     /* save    flags */ \
43           "pushl %%ebp\n\t"        /* save    EBP   */ \
44           "movl %%esp,%[prev_sp]\n\t"  /* save    ESP   */ \
45           "movl %[next_sp],%%esp\n\t"  /* restore ESP   */ \
46           "movl $1f,%[prev_ip]\n\t"    /* save    EIP   */ \
47           "pushl %[next_ip]\n\t"   /* restore EIP   */ \
48           __switch_canary                    \
49           "jmp __switch_to\n"  /* regparm call  */ \
50           "1:\t"                       \
51           "popl %%ebp\n\t"     /* restore EBP   */ \
52           "popfl\n"            /* restore flags */ \
53                                  \
54           /* output parameters */                \
55           : [prev_sp] "=m" (prev->thread.sp),      \
56             [prev_ip] "=m" (prev->thread.ip),      \
57             "=a" (last),                  \
58                                  \
59             /* clobbered output registers: */        \
60             "=b" (ebx), "=c" (ecx), "=d" (edx),     \
61             "=S" (esi), "=D" (edi)             \
62                                      \
63             __switch_canary_oparam               \
64                                  \
65             /* input parameters: */              \
66           : [next_sp]  "m" (next->thread.sp),       \
67             [next_ip]  "m" (next->thread.ip),       \
68                                      \
69             /* regparm parameters for __switch_to(): */  \
70             [prev]     "a" (prev),             \
71             [next]     "d" (next)              \
72                                  \
73             __switch_canary_iparam               \
74                                  \
75           : /* reloaded segment registers */         \
76          "memory");                    \
77} while (0)

通过以上代码,我们可以看到,当cpu由正在运行的X进程切换到Y进程的大致步骤,其中X,Y是哪一个进程是由调度算法决定的。

进程X正在中运行->发生中断->进行中断处理(保存当前的eflag,eip,esp;加载内核中特定的eflag,eip,esp)->执行SAVE ALL->中断处理过程中或中断返回前调用了schedule(),switch_to实现关键的进程上下文切换->开始从标号1之后运行用户态进程Y->restore all->iret从内核堆栈中返回eflag,eip,esp->继续执行Y进程。对于前面提到的内核线程,以及系统中的特殊调用fork和execve会有些特殊,但大致原则是相同的。

转载于:https://blog.51cto.com/swordautumn/1636335

Linux内核进程调度的时机和进程切换相关推荐

  1. 《Linux内核分析》 第八节 进程的切换和一般的执行过程

    张嘉琪 原创作品转载请注明出处 <Linux内核分析>MOOC课程http://mooc.study.163.com/course/USTC-1000029000 Linux内核分析 第八 ...

  2. Linux内核源码分析《进程管理》

    Linux内核源码分析<进程管理> 前言 1. Linux 内核源码分析架构 2. 进程原理分析 2.1 进程基础知识 2.2 Linux进程四要素 2.3 进程描述符 task_stru ...

  3. 通过fork来剖析Linux内核的内存管理和进程管理(上)

    1.开场白 本文主要从内存管理和进程管理两个维度来窥探一下fork背后隐藏的技术细节,希望能够通过本文让大家站在一个高度去看进程创建. 全文分为两部分讲解:fork的内存管理部分和进程管理部分,内存管 ...

  4. Linux内核进程调度时机和过程

    深度详解Linux内核网络结构及分布 linux内核,进程调度器的实现,完全公平调度器 CFS 1.调度类型和时机 调度触发有两种类型,进程主动触发的主动调度和被动调度,被动调度又叫抢占式调度. 主动 ...

  5. 通过fork来剖析Linux内核的内存管理和进程管理(下)

    上一篇文章我们讲到fork的时候内存管理相关的内容,时间大概隔了快一周了,发布下篇文章,写文章确实费时费力,需要仔细推敲,原创不易,希望大家多多支持吧.本文讲解fork的时候进程管理相关的内容,主要讲 ...

  6. linux 4.1.16 ftrace 进程调度,Linux内核进程调度overview(1)

    一.概述 决定何时.如何选择一个新进程运行的这组规则叫做:调度策略(scheduling policy). Linux的调度是基于分时技术(time sharing):多个进程以"时间多路复 ...

  7. Linux内核设计与实现:进程管理

    1. 关于进程 在linux操作系统中,进程通过fork()函数调用,通过复制一个现有的进程来创建一个新的进程: 调用fork()的叫做父进程,而创建的进程叫子进程,fork()调用从内核返回两次,一 ...

  8. 【Linux 内核】实时调度类 ① ( 进程分类 | 实时进程、普通进程 | Linux 内核 SCHED_FIFO、SCHED_RR 调度策略 | 实时调度实体 sched_rt_entity )

    文章目录 一.进程分类 ( 实时进程 | 普通进程 ) 二.Linux 内核调度策略 1.SCHED_FIFO 调度策略 2.SCHED_RR 调度策略 三.实时调度实体 sched_rt_entit ...

  9. Linux内核学习之2号进程kthreadd

    Author       : Toney Email         : vip_13031075266@163.com Date          : 2020.12.04 Copyright : ...

最新文章

  1. windows下安装ElasticSearch的Head插件
  2. 苹果的 Metal 工程
  3. android指定sqlite路径_Android:自定义Sqlite数据库路径
  4. 绝对路径VS相对路径
  5. Apache Camel 2.12 –支持后退,以减少较积极的轮询路线
  6. [react] React为什么要搞一个Hooks?
  7. 金和oa:自定义表单函数计算一段时期内的工作日
  8. zabbix报错cannot set resource limit: [13] Permission denied解决方法
  9. LintCode: Combination Sum
  10. VS C# string 字符查找 寻找指定字符
  11. 网上书店软件测试,网上书店测试用例.doc
  12. Qt6 tesseract-ocr 截图识字
  13. 【错误记录】编译 Linux 内核报错 ( Unable to find the ncurses package. )
  14. 3D打印切片软件Cura入门
  15. oracle的gc告警,防患未然:Oracle gc等待事件的发现、处理与预防
  16. matlab带下标的字母,matlab的特殊字符(上下标和希腊字母等)
  17. 个人日记开发最终实现
  18. java docker 部署_使用docker部署java项目
  19. 软件工程导论(张海藩第六版)期末考试、考研复试重点
  20. C语言学习记录——辗转相除法

热门文章

  1. 关于自定义控件设计时如何把属性写入aspx中的研究(上)
  2. gitlab更改默认Nginx
  3. Android性能优化之运算篇
  4. 基于纯 CSS3 技术实现美观的标签云效果
  5. 给Jquery添加alert,prompt方法,类似系统的Alert,Prompt,可以响应键盘,支持拖动...
  6. ubuntu 客户端ssh连接服务器速度缓慢
  7. sql loader 导入数据时的问题
  8. WorldWind Java 版学习:10、服务器响应
  9. HDOJ_ACM_折线分割平面
  10. (转载)(c#)数据结构与算法分析 --数组、向量和表