Linux内核的进程负载均衡机制

系统 Linux
在多核系统中,为了更好的利用多CPU并行能力,进程调度器可以将进程负载尽可能的平均到各个CPU上。再具体实现中,如何选择将进程迁移到的目标CPU,除了考虑各个CPU的负载平衡,还需要将Cache利用纳入权衡因素。同时,对于进程A唤醒进程B这个模型,还做了特殊的处理。

概述

在多核系统中,为了更好的利用多CPU并行能力,进程调度器可以将进程负载尽可能的平均到各个CPU上。再具体实现中,如何选择将进程迁移到的目标CPU,除了考虑各个CPU的负载平衡,还需要将Cache利用纳入权衡因素。同时,对于进程A唤醒进程B这个模型,还做了特殊的处理。本文分析以Centos kernel 3.10.0-975源码为蓝本。

SMP负载均衡模型

问题

如果只是将CPU负载平均的分布在各个CPU上,那么就无所谓需要调度域。但是由于Cache以及内存Numa的存在,使得进程最好能迁移到与之前运行所在CPU更'近'的CPU上。

以我们常用的Intel X86为例。Cache基本视图如下图:

[[261979]]

从Cache和内存访问的视角,如果进程负载均衡需要把进程A迁移到另一个CPU上,

  • 如果目标CPU和进程A之前所在CPU正好是同一个物理CPU同一个核心上(超线程),那么Cache利用率最好,毕竟L1,L2和L3中还是'热'的。
  • 如果目标CPU和进程A之前所在CPU正好是同一个物理CPU但不同核心上(多核),那么Cache利用率次之,L3中还有'热'数据。
  • 如果目标CPU和进程A之前所在CPU正好是同一个NUMA但是不同物理CPU上(多NUMA结构),虽然Cache已经是'冷'了,但至少内存访问还是在本NUMA中。
  • 如果目标CPU和进程A之前所在CPU在不同NUMA中,不但Cache是'冷'的,跨NUMA内存还有惩罚,此时内存访问速度最差。

SMP组织

为了更好地利用Cache,内核将CPU(如果开启了超线程,那么以逻辑CPU为单位,否则以物理CPU核心为单位)组织成了调度域。

逻辑视角

假设某机器为2路4核8核心CPU,它的CPU调度域逻辑上如下图:

 

2路NUMA最为简单,如果是4路NUMA,那么这个视图在NUMA层级将会复杂很多,因为跨NUMA访问根据访问距离导致访问延时还不相同,这部分最后讨论。

分层视角

所有CPU一共分为三个层次:SMT,MC,NUMA,每层都包含了所有CPU,但是划分粒度不同。根据Cache和内存的相关性划分调度域,调度域内的CPU又划分一次调度组。越往下层调度域越小,越往上层调度域越大。进程负载均衡会尽可能的在底层调度域内部解决,这样Cache利用率最优。

从分层的视角分析,下图是调度域实际组织方式,每层都有per-cpu数组保存每个CPU对应的调度域和调度组,它们是在初始化时已经提前分配的内存。值得注意的是

  • 每个CPU对应的调度域数据结构都包含了有效的内容,比如说SMT层中,CPU0和CPU1对应的不同调度域数据结构,内容是一模一样的。
  • 每个CPU对应的调度组数据结构不一定包含了有效内容,比如说MC层中,CPU0和CPU1指向不同的struct sched_domain,但是sched_domain->groups指向的调度组确是同样的数据结构,这些调度组组成了环。
 

单CPU视角

从单个CPU的视角分析,下图是调度域实际组织方式。

 

[[261980]]

 

每个CPU的进程运行队列有一个成员指向其所在调度域。从最低层到最高层。

我们可以在/proc/sys/kernel/sched_domain/cpuX/ 中看到CPU实际使用的调度域个数以及每个调度域的名字和配置参数。

负载均衡时机

  • 周期性调用进程调度程序scheduler_tick()->trigger_load_balance()中,通过软中断触发负载均衡。
  • 某个CPU上无可运行进程,__schedule()准备调度idle进程前,会尝试从其它CPU上pull一批进程过来。

周期性负载均衡

CPU对应的运行队列数据结构中记录了下一次周期性负载均衡的时间,当超过这个时间点后,将触发SCHED_SOFTIRQ软中断来进行负载均衡。

  1. void trigger_load_balance(struct rq *rq, int cpu) 
  2.         /* Don't need to rebalance while attached to NULL domain */ 
  3.         if (time_after_eq(jiffies, rq->next_balance) && 
  4.             likely(!on_null_domain(cpu))) 
  5.                 raise_softirq(SCHED_SOFTIRQ); 
  6. #ifdef CONFIG_NO_HZ_COMMON 
  7.         if (nohz_kick_needed(rq) && likely(!on_null_domain(cpu))) 
  8.                 nohz_balancer_kick(cpu); 
  9. #endif 

以下是rebalance_domains()函数核心流程,值得注意的是,每个层级的调度间隔不是固定的,而是临时计算出来,他在一个可通过proc接口配置的最小值和最大值之间。

 

[[261981]]

 

以下是对CPU的每个层级调度域调用load_balance()函数核心流程,目的是把一些进程迁移到指定的CPU(该场景就是当前CPU)。

 

[[261982]]

 

以我的服务器为例,观察不同层级调度域的调度间隔范围,时间单位为jiffies。

Level

min_interval

max_interval

SMT

2

4

MC

40

80

NUMA

80

160

可见,SMT负载均衡频率最高,越往上层越低。这也符合体系结构特点,在越低层次迁移进程代价越小(Cache利用率高),所以可以更加频繁一点。

CPU进入idle前负载均衡

当进程调度函数__schedule()把即将切换到idle进程前,会发生一次负载均衡来避免当前CPU空闲。

  1. static void __sched __schedule(void) 
  2.         ... 
  3.         if (unlikely(!rq->nr_running)) 
  4.                 idle_balance(cpu, rq); 
  5.  
  6.         ... 

核心函数idle_balance()。基本上也是尽可能在低层调度域中负载均衡。

  1. /*  * idle_balance is called by schedule() if this_cpu is about to become  * idle. Attempts to pull tasks from other CPUs.  */ 
  2. void idle_balance(int this_cpu, struct rq *this_rq) 
  3.     unsigned long next_balance = jiffies + HZ; 
  4.     struct sched_domain *sd; 
  5.     int pulled_task = 0; 
  6.     u64 curr_cost = 0; 
  7.  
  8.     this_rq->idle_stamp = rq_clock(this_rq); 
  9.  
  10.     /* 如果该CPU平均空闲时间小于/proc中的配置值或者该cpu调度域中所有cpu都是idle状态,那么不需要负载均衡了*/ 
  11.     if (this_rq->avg_idle < sysctl_sched_migration_cost || 
  12.         !this_rq->rd->overload) { 
  13.         rcu_read_lock(); 
  14.         sd = rcu_dereference_check_sched_domain(this_rq->sd); 
  15.         if (sd) 
  16.             update_next_balance(sd, 0, &next_balance); 
  17.         rcu_read_unlock(); 
  18.  
  19.         goto out
  20.     } 
  21.  
  22.     /*   * Drop the rq->lock, but keep IRQ/preempt disabled.     */ 
  23.     raw_spin_unlock(&this_rq->lock); 
  24.  
  25.     update_blocked_averages(this_cpu); 
  26.     rcu_read_lock(); 
  27.     /* 从底向上遍历调度域,只要迁移成功一个进程就跳出循环*/ 
  28.     for_each_domain(this_cpu, sd) { 
  29.         int should_balance; 
  30.         u64 t0, domain_cost; 
  31.  
  32.         if (!(sd->flags & SD_LOAD_BALANCE)) 
  33.             continue
  34.  
  35.         /*           * 如果(当前累积的负载均衡开销时间 + 历史上该层级负载均衡开销最大值)已经大于CPU平均空闲时间了,          * 那么就没有必要负载均衡了。注意,sd->max_newidle_lb_cost会在load_balance()函数中缓慢减少。          */ 
  36.         if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost) { 
  37.             update_next_balance(sd, 0, &next_balance); 
  38.             break; 
  39.         } 
  40.  
  41.         /* 我的机器上该标记总是设置了SD_BALANCE_NEWIDLE */ 
  42.         if (sd->flags & SD_BALANCE_NEWIDLE) { 
  43.             t0 = sched_clock_cpu(this_cpu); 
  44.  
  45.             pulled_task = load_balance(this_cpu, this_rq, 
  46.                            sd, CPU_NEWLY_IDLE, 
  47.                            &should_balance); 
  48.             
  49.             domain_cost = sched_clock_cpu(this_cpu) - t0; 
  50.             if (domain_cost > sd->max_newidle_lb_cost) 
  51.                 sd->max_newidle_lb_cost = domain_cost; 
  52.  
  53.            /* 记录了当前负载均衡开销累计值 */ 
  54.             curr_cost += domain_cost; 
  55.         } 
  56.  
  57.         update_next_balance(sd, 0, &next_balance); 
  58.  
  59.         /*       * Stop searching for tasks to pull if there are         * now runnable tasks on this rq.        */         
  60.         if (pulled_task || this_rq->nr_running > 0) { 
  61.             this_rq->idle_stamp = 0; 
  62.             break; 
  63.         } 
  64.     } 
  65.     rcu_read_unlock(); 
  66.  
  67.     raw_spin_lock(&this_rq->lock); 
  68.  
  69. out
  70.     /* Move the next balance forward */ 
  71.     if (time_after(this_rq->next_balance, next_balance)) 
  72.         this_rq->next_balance = next_balance; 
  73.  
  74.     if (curr_cost > this_rq->max_idle_balance_cost) 
  75.         this_rq->max_idle_balance_cost = curr_cost; 

其它需要用到SMP负载均衡模型的时机

内核运行中,还有部分情况中需要用掉SMP负载均衡模型来确定最佳运行CPU:

  • 进程A唤醒进程B时,try_to_wake_up()中会考虑进程B将在哪个CPU上运行。
  • 进程调用execve()系统调用时。
  • fork出子进程,子进程第一次被调度运

唤醒进程时

当A进程唤醒B进程时,假设都是普通进程,那么将会调用try_to_wake_up()->select_task_rq()->select_task_rq_fair()

  1. /*  * sched_balance_self: balance the current task (running on cpu) in domains  * that have the 'flag' flag setIn practice, this is SD_BALANCE_FORK and  * SD_BALANCE_EXEC.  *  * Balance, ie. select the least loaded group.  *  * Returns the target CPU number, or the same CPU if no balancing is needed.  *  * preempt must be disabled.  */ 
  2. /* A进程给自己或者B进程选择一个CPU运行,  * 1: A唤醒B  * 2: A fork()出B后让B运行  * 3: A execute()后重新选择自己将要运行的CPU  */  
  3. static int 
  4. select_task_rq_fair(struct task_struct *p, int prev_cpu, int sd_flag, int wake_flags) 
  5.     struct sched_domain *tmp, *affine_sd = NULL, *sd = NULL
  6.     int cpu = smp_processor_id(); 
  7.     int new_cpu = cpu; 
  8.     int want_affine = 0; 
  9.     int sync = wake_flags & WF_SYNC; 
  10.  
  11.     /* 当A进程唤醒B进程时,从try_to_wake_up()进入本函数,这里会置位SD_BALANCE_WAKE。 */ 
  12.     if (sd_flag & SD_BALANCE_WAKE) { 
  13.         /* B进程被唤醒时希望运行的CPU尽可能离A进程所在CPU近一点 */ 
  14.         if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p))) 
  15.             want_affine = 1; 
  16.         new_cpu = prev_cpu; 
  17.         record_wakee(p); 
  18.     } 
  19.  
  20.     rcu_read_lock(); 
  21.     /*       * 如果是A唤醒B模式,则查找同时包含A所在cpu和B睡眠前所在prev_cpu的最低级别的调度域。因为A进程      * 和B进程大概率会有某种数据交换关系,唤醒B时让它们所在的CPU离的近一点会性能最优。      * 否则,查找包含了sd_flag的最高调度域。      */ 
  22.     for_each_domain(cpu, tmp) { 
  23.         if (!(tmp->flags & SD_LOAD_BALANCE)) 
  24.             continue
  25.  
  26.         /*       * If both cpu and prev_cpu are part of this domain,         * cpu is a valid SD_WAKE_AFFINE target.         */         
  27.         if (want_affine && (tmp->flags & SD_WAKE_AFFINE) && 
  28.             cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) { 
  29.             affine_sd = tmp; 
  30.             break; 
  31.         } 
  32.  
  33.         if (tmp->flags & sd_flag) 
  34.             sd = tmp; 
  35.     } 
  36.  
  37.     /* 如果是A唤醒B模式,则在同时包含A所在cpu和B睡眠前所在prev_cpu的最低级别的调度域中寻找合适的CPU */ 
  38.     if (affine_sd) { 
  39.        /*          * wake_affine()计算A所在CPU和B睡眠前所在CPU的负载值,判断出B进程唤醒时是否         * 需要离A近一点。         */ 
  40.         if (cpu != prev_cpu && wake_affine(affine_sd, p, sync)) 
  41.             prev_cpu = cpu; 
  42.  
  43.        /* 在与prev_cpu共享LLC的CPU中寻找空闲CPU,如果没有找到,则返回prev_cpu。这里将确定         * B进程唤醒后在哪个CPU运行。         */ 
  44.         new_cpu = select_idle_sibling(p, prev_cpu); 
  45.         goto unlock; 
  46.     } 
  47.  
  48.     /* 到这里,A进程和B进程基本是没有啥亲缘关系的。不用考虑两个进程的Cache亲缘性 */ 
  49.     while (sd) { 
  50.         int load_idx = sd->forkexec_idx; 
  51.         struct sched_group *group
  52.         int weight; 
  53.  
  54.         if (!(sd->flags & sd_flag)) { 
  55.             sd = sd->child; 
  56.             continue
  57.         } 
  58.  
  59.         if (sd_flag & SD_BALANCE_WAKE) 
  60.             load_idx = sd->wake_idx; 
  61.  
  62.         group = find_idlest_group(sd, p, cpu, load_idx); 
  63.         if (!group) { 
  64.             sd = sd->child; 
  65.             continue
  66.         } 
  67.  
  68.         new_cpu = find_idlest_cpu(group, p, cpu); 
  69.         if (new_cpu == -1 || new_cpu == cpu) { 
  70.             /* Now try balancing at a lower domain level of cpu */ 
  71.             sd = sd->child; 
  72.             continue
  73.         } 
  74.  
  75.         /* Now try balancing at a lower domain level of new_cpu */ 
  76.         cpu = new_cpu; 
  77.         weight = sd->span_weight; 
  78.         sd = NULL
  79.         for_each_domain(cpu, tmp) { 
  80.             if (weight <= tmp->span_weight) 
  81.                 break; 
  82.             if (tmp->flags & sd_flag) 
  83.                 sd = tmp; 
  84.         } 
  85.         /* while loop will break here if sd == NULL */ 
  86.     } 
  87. unlock: 
  88.     rcu_read_unlock(); 
  89.  
  90.     return new_cpu; 
  91. }  
  1. /*  * Try and locate an idle CPU in the sched_domain.  */ 
  2.  /* 寻找离target CPU最近的空闲CPU(Cache或者内存距离最近)*/ 
  3. static int select_idle_sibling(struct task_struct *p, int target) 
  4.     struct sched_domain *sd; 
  5.     struct sched_group *sg; 
  6.     int i = task_cpu(p); 
  7.      
  8.     /* target CPU正好空闲,自己跟自己当然最近*/ 
  9.     if (idle_cpu(target)) 
  10.         return target; 
  11.  
  12.     /*   * If the prevous cpu is cache affine and idle, don't be stupid.     */ 
  13.     /*       * p进程所在的CPU跟target CPU有Cache共享关系(SMT,或者MC层才有这个关系),并且是空闲的,那就用它了。      * Cache共享说明距离很近了       */ 
  14.     if (i != target && cpus_share_cache(i, target) && idle_cpu(i)) 
  15.         return i; 
  16.  
  17.     /*   * Otherwise, iterate the domains and find an elegible idle cpu.     */ 
  18.     /*      * 在与target CPU有LLC Cache共享关系的调度域中寻找空闲CPU。注意,在X86体系中只有SMT和MC层的调度域才有Cache共享。      */ 
  19.     sd = rcu_dereference(per_cpu(sd_llc, target));     
  20.     /* 在我的机器上是按MC,SMT调度域顺序遍历 */ 
  21.     for_each_lower_domain(sd) { 
  22.         sg = sd->groups; 
  23.         do { 
  24.             if (!cpumask_intersects(sched_group_cpus(sg), 
  25.                         tsk_cpus_allowed(p))) 
  26.                 goto next
  27.  
  28.            /* 调度组内所有CPU都是空闲状态,才能选定 */ 
  29.             for_each_cpu(i, sched_group_cpus(sg)) { 
  30.                 if (i == target || !idle_cpu(i)) 
  31.                     goto next
  32.             } 
  33.  
  34.            /* 选择全部CPU都空闲的调度组中第一个CPU*/ 
  35.             target = cpumask_first_and(sched_group_cpus(sg), 
  36.                     tsk_cpus_allowed(p)); 
  37.             goto done; 
  38. next
  39.             sg = sg->next
  40.         } while (sg != sd->groups); 
  41.     } 
  42. done: 
  43.     return target; 

调用execve()系统调用时

  1. /*  * sched_exec - execve() is a valuable balancing opportunity, because at  * this point the task has the smallest effective memory and cache footprint.  */ 
  2. void sched_exec(void) 
  3.     struct task_struct *p = current
  4.     unsigned long flags; 
  5.     int dest_cpu; 
  6.  
  7.     raw_spin_lock_irqsave(&p->pi_lock, flags); 
  8.     /* 选择最合适的CPU,这里由于进程execve()后,之前的Cache就无意义了,因此选择目标CPU不用考虑Cache距离 */ 
  9.     dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0); 
  10.     if (dest_cpu == smp_processor_id()) 
  11.         goto unlock; 
  12.  
  13.     if (likely(cpu_active(dest_cpu))) { 
  14.         struct migration_arg arg = { p, dest_cpu }; 
  15.  
  16.         raw_spin_unlock_irqrestore(&p->pi_lock, flags); 
  17.         stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg); 
  18.         return
  19.     } 
  20. unlock: 
  21.     raw_spin_unlock_irqrestore(&p->pi_lock, flags); 

fork的子进程第一次被调度运行时

  1. do_fork()->wake_up_new_task() 
  2.  
  3. /*  * wake_up_new_task - wake up a newly created task for the first time.  *  * This function will do some initial scheduler statistics housekeeping  * that must be done for every newly created context, then puts the task  * on the runqueue and wakes it.  */ 
  4. void wake_up_new_task(struct task_struct *p) 
  5.     unsigned long flags; 
  6.     struct rq *rq; 
  7.  
  8.     raw_spin_lock_irqsave(&p->pi_lock, flags); 
  9. #ifdef CONFIG_SMP 
  10.     /*   * Fork balancing, do it here and not earlier because:   *  - cpus_allowed can change in the fork path   *  - any previously selected cpu might disappear through hotplug    */ 
  11.     /* 选择最合适的CPU,这里由于进程execve()后,之前的Cache就无意义了,因此选择目标CPU不用考虑Cache距离 */ 
  12.     set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0)); 
  13. #endif 
  14.  
  15.     /* Initialize new task's runnable average */ 
  16.     init_task_runnable_average(p); 
  17.     rq = __task_rq_lock(p); 
  18.     activate_task(rq, p, 0); 
  19.     p->on_rq = TASK_ON_RQ_QUEUED; 
  20.     trace_sched_wakeup_new(p, true); 
  21.     check_preempt_curr(rq, p, WF_FORK); 
  22. #ifdef CONFIG_SMP 
  23.     if (p->sched_class->task_woken) 
  24.         p->sched_class->task_woken(rq, p); 
  25. #endif 
  26.     task_rq_unlock(rq, p, &flags); 
  27. }  

SMP负载均衡模型的配置

可以在/proc/sys/kernel/sched_domain/cpuX/中可以对指定CPU所在不同层的调度域进行设置

主要分两类:

  • 调度层名字:name
  • 调度域支持的特性:设置flags文件值,比如SD_LOAD_BALANCE,SD_BALANCE_NEWIDLE,SD_BALANCE_EXEC等,它将决定上文函数遍历调度域时是否忽略本域。
  • 调度域计算参数:其它所有文件。 

 

责任编辑:庞桂玉 来源: 腾讯云-云+社区
相关推荐

2021-04-22 07:47:46

Linux进程管理

2021-08-30 07:49:31

Linux内核负载均衡

2021-05-17 18:28:36

Linux CFS负载均衡

2009-10-29 09:41:01

Linux内核DeviceMappe

2010-05-05 21:39:29

linux负载均衡

2017-07-03 08:08:25

负载均衡分类

2010-04-27 12:56:35

lvs负载均衡

2010-04-27 12:29:08

Linux负载均衡

2009-10-23 19:11:32

linux集群

2010-05-06 12:18:34

IP负载均衡

2010-04-27 12:42:45

LVS负载均衡

2017-08-16 16:20:01

Linux内核态抢占用户态抢占

2021-04-21 14:56:28

负载均衡高并发优化技术架构

2021-04-15 05:51:25

Linux

2012-05-14 14:09:53

Linux内核调度系统

2018-11-07 10:12:37

2011-12-02 22:51:46

Nginx负载均衡

2010-04-21 11:08:57

MySQL负载均衡

2010-05-10 15:58:14

porxy负载均衡

2010-04-20 12:07:17

DNS负载均衡
点赞
收藏

51CTO技术栈公众号