The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/kern/sched_4bsd.c

Version: -  FREEBSD  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-2  -  FREEBSD-11-1  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-4  -  FREEBSD-10-3  -  FREEBSD-10-2  -  FREEBSD-10-1  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-3  -  FREEBSD-9-2  -  FREEBSD-9-1  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-4  -  FREEBSD-8-3  -  FREEBSD-8-2  -  FREEBSD-8-1  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-4  -  FREEBSD-7-3  -  FREEBSD-7-2  -  FREEBSD-7-1  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-4  -  FREEBSD-6-3  -  FREEBSD-6-2  -  FREEBSD-6-1  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-5  -  FREEBSD-5-4  -  FREEBSD-5-3  -  FREEBSD-5-2  -  FREEBSD-5-1  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  linux-2.6  -  linux-2.4.22  -  MK83  -  MK84  -  PLAN9  -  DFBSD  -  NETBSD  -  NETBSD5  -  NETBSD4  -  NETBSD3  -  NETBSD20  -  OPENBSD  -  xnu-517  -  xnu-792  -  xnu-792.6.70  -  xnu-1228  -  xnu-1456.1.26  -  xnu-1699.24.8  -  xnu-2050.18.24  -  OPENSOLARIS  -  minix-3-1-1 
SearchContext: -  none  -  3  -  10 

    1 /*-
    2  * Copyright (c) 1982, 1986, 1990, 1991, 1993
    3  *      The Regents of the University of California.  All rights reserved.
    4  * (c) UNIX System Laboratories, Inc.
    5  * All or some portions of this file are derived from material licensed
    6  * to the University of California by American Telephone and Telegraph
    7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
    8  * the permission of UNIX System Laboratories, Inc.
    9  *
   10  * Redistribution and use in source and binary forms, with or without
   11  * modification, are permitted provided that the following conditions
   12  * are met:
   13  * 1. Redistributions of source code must retain the above copyright
   14  *    notice, this list of conditions and the following disclaimer.
   15  * 2. Redistributions in binary form must reproduce the above copyright
   16  *    notice, this list of conditions and the following disclaimer in the
   17  *    documentation and/or other materials provided with the distribution.
   18  * 4. Neither the name of the University nor the names of its contributors
   19  *    may be used to endorse or promote products derived from this software
   20  *    without specific prior written permission.
   21  *
   22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
   23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   32  * SUCH DAMAGE.
   33  */
   34 
   35 #include <sys/cdefs.h>
   36 __FBSDID("$FreeBSD$");
   37 
   38 #include "opt_hwpmc_hooks.h"
   39 
   40 #define kse td_sched
   41 
   42 #include <sys/param.h>
   43 #include <sys/systm.h>
   44 #include <sys/kernel.h>
   45 #include <sys/ktr.h>
   46 #include <sys/lock.h>
   47 #include <sys/kthread.h>
   48 #include <sys/mutex.h>
   49 #include <sys/proc.h>
   50 #include <sys/resourcevar.h>
   51 #include <sys/sched.h>
   52 #include <sys/smp.h>
   53 #include <sys/sysctl.h>
   54 #include <sys/sx.h>
   55 #include <sys/turnstile.h>
   56 #include <machine/smp.h>
   57 
   58 #ifdef HWPMC_HOOKS
   59 #include <sys/pmckern.h>
   60 #endif
   61 
   62 /*
   63  * INVERSE_ESTCPU_WEIGHT is only suitable for statclock() frequencies in
   64  * the range 100-256 Hz (approximately).
   65  */
   66 #define ESTCPULIM(e) \
   67     min((e), INVERSE_ESTCPU_WEIGHT * (NICE_WEIGHT * (PRIO_MAX - PRIO_MIN) - \
   68     RQ_PPQ) + INVERSE_ESTCPU_WEIGHT - 1)
   69 #ifdef SMP
   70 #define INVERSE_ESTCPU_WEIGHT   (8 * smp_cpus)
   71 #else
   72 #define INVERSE_ESTCPU_WEIGHT   8       /* 1 / (priorities per estcpu level). */
   73 #endif
   74 #define NICE_WEIGHT             1       /* Priorities per nice level. */
   75 
   76 /*
   77  * The schedulable entity that can be given a context to run.
   78  * A process may have several of these. Probably one per processor
   79  * but posibly a few more. In this universe they are grouped
   80  * with a KSEG that contains the priority and niceness
   81  * for the group.
   82  */
   83 struct kse {
   84         TAILQ_ENTRY(kse) ke_procq;      /* (j/z) Run queue. */
   85         struct thread   *ke_thread;     /* (*) Active associated thread. */
   86         fixpt_t         ke_pctcpu;      /* (j) %cpu during p_swtime. */
   87         char            ke_rqindex;     /* (j) Run queue index. */
   88         enum {
   89                 KES_THREAD = 0x0,       /* slaved to thread state */
   90                 KES_ONRUNQ
   91         } ke_state;                     /* (j) KSE status. */
   92         int             ke_cpticks;     /* (j) Ticks of cpu time. */
   93         struct runq     *ke_runq;       /* runq the kse is currently on */
   94 };
   95 
   96 #define ke_proc         ke_thread->td_proc
   97 #define ke_ksegrp       ke_thread->td_ksegrp
   98 
   99 #define td_kse td_sched
  100 
  101 /* flags kept in td_flags */
  102 #define TDF_DIDRUN      TDF_SCHED0      /* KSE actually ran. */
  103 #define TDF_EXIT        TDF_SCHED1      /* KSE is being killed. */
  104 #define TDF_BOUND       TDF_SCHED2
  105 
  106 #define ke_flags        ke_thread->td_flags
  107 #define KEF_DIDRUN      TDF_DIDRUN /* KSE actually ran. */
  108 #define KEF_EXIT        TDF_EXIT /* KSE is being killed. */
  109 #define KEF_BOUND       TDF_BOUND /* stuck to one CPU */
  110 
  111 #define SKE_RUNQ_PCPU(ke)                                               \
  112     ((ke)->ke_runq != 0 && (ke)->ke_runq != &runq)
  113 
  114 struct kg_sched {
  115         struct thread   *skg_last_assigned; /* (j) Last thread assigned to */
  116                                            /* the system scheduler. */
  117         int     skg_avail_opennings;    /* (j) Num KSEs requested in group. */
  118         int     skg_concurrency;        /* (j) Num KSEs requested in group. */
  119 };
  120 #define kg_last_assigned        kg_sched->skg_last_assigned
  121 #define kg_avail_opennings      kg_sched->skg_avail_opennings
  122 #define kg_concurrency          kg_sched->skg_concurrency
  123 
  124 #define SLOT_RELEASE(kg)                                                \
  125 do {                                                                    \
  126         kg->kg_avail_opennings++;                                       \
  127         CTR3(KTR_RUNQ, "kg %p(%d) Slot released (->%d)",                \
  128         kg,                                                             \
  129         kg->kg_concurrency,                                             \
  130          kg->kg_avail_opennings);                                       \
  131 /*      KASSERT((kg->kg_avail_opennings <= kg->kg_concurrency),         \
  132             ("slots out of whack"));*/                                  \
  133 } while (0)
  134 
  135 #define SLOT_USE(kg)                                                    \
  136 do {                                                                    \
  137         kg->kg_avail_opennings--;                                       \
  138         CTR3(KTR_RUNQ, "kg %p(%d) Slot used (->%d)",                    \
  139         kg,                                                             \
  140         kg->kg_concurrency,                                             \
  141          kg->kg_avail_opennings);                                       \
  142 /*      KASSERT((kg->kg_avail_opennings >= 0),                          \
  143             ("slots out of whack"));*/                                  \
  144 } while (0)
  145 
  146 /*
  147  * KSE_CAN_MIGRATE macro returns true if the kse can migrate between
  148  * cpus.
  149  */
  150 #define KSE_CAN_MIGRATE(ke)                                             \
  151     ((ke)->ke_thread->td_pinned == 0 && ((ke)->ke_flags & KEF_BOUND) == 0)
  152 
  153 static struct kse kse0;
  154 static struct kg_sched kg_sched0;
  155 
  156 static int      sched_tdcnt;    /* Total runnable threads in the system. */
  157 static int      sched_quantum;  /* Roundrobin scheduling quantum in ticks. */
  158 #define SCHED_QUANTUM   (hz / 10)       /* Default sched quantum */
  159 
  160 static void     slot_fill(struct ksegrp *kg);
  161 static struct kse *sched_choose(void);          /* XXX Should be thread * */
  162 
  163 static void     setup_runqs(void);
  164 static void     schedcpu(void);
  165 static void     schedcpu_thread(void);
  166 static void     sched_priority(struct thread *td, u_char prio);
  167 static void     sched_setup(void *dummy);
  168 static void     maybe_resched(struct thread *td);
  169 static void     updatepri(struct ksegrp *kg);
  170 static void     resetpriority(struct ksegrp *kg);
  171 static void     resetpriority_thread(struct thread *td, struct ksegrp *kg);
  172 #ifdef SMP
  173 static int      forward_wakeup(int  cpunum);
  174 #endif
  175 
  176 static struct kproc_desc sched_kp = {
  177         "schedcpu",
  178         schedcpu_thread,
  179         NULL
  180 };
  181 SYSINIT(schedcpu, SI_SUB_RUN_SCHEDULER, SI_ORDER_FIRST, kproc_start, &sched_kp)
  182 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL)
  183 
  184 /*
  185  * Global run queue.
  186  */
  187 static struct runq runq;
  188 
  189 #ifdef SMP
  190 /*
  191  * Per-CPU run queues
  192  */
  193 static struct runq runq_pcpu[MAXCPU];
  194 #endif
  195 
  196 static void
  197 setup_runqs(void)
  198 {
  199 #ifdef SMP
  200         int i;
  201 
  202         for (i = 0; i < MAXCPU; ++i)
  203                 runq_init(&runq_pcpu[i]);
  204 #endif
  205 
  206         runq_init(&runq);
  207 }
  208 
  209 static int
  210 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
  211 {
  212         int error, new_val;
  213 
  214         new_val = sched_quantum * tick;
  215         error = sysctl_handle_int(oidp, &new_val, 0, req);
  216         if (error != 0 || req->newptr == NULL)
  217                 return (error);
  218         if (new_val < tick)
  219                 return (EINVAL);
  220         sched_quantum = new_val / tick;
  221         hogticks = 2 * sched_quantum;
  222         return (0);
  223 }
  224 
  225 SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RD, 0, "Scheduler");
  226 
  227 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "4BSD", 0,
  228     "Scheduler name");
  229 
  230 SYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
  231     0, sizeof sched_quantum, sysctl_kern_quantum, "I",
  232     "Roundrobin scheduling quantum in microseconds");
  233 
  234 #ifdef SMP
  235 /* Enable forwarding of wakeups to all other cpus */
  236 SYSCTL_NODE(_kern_sched, OID_AUTO, ipiwakeup, CTLFLAG_RD, NULL, "Kernel SMP");
  237 
  238 static int forward_wakeup_enabled = 1;
  239 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, enabled, CTLFLAG_RW,
  240            &forward_wakeup_enabled, 0,
  241            "Forwarding of wakeup to idle CPUs");
  242 
  243 static int forward_wakeups_requested = 0;
  244 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, requested, CTLFLAG_RD,
  245            &forward_wakeups_requested, 0,
  246            "Requests for Forwarding of wakeup to idle CPUs");
  247 
  248 static int forward_wakeups_delivered = 0;
  249 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, delivered, CTLFLAG_RD,
  250            &forward_wakeups_delivered, 0,
  251            "Completed Forwarding of wakeup to idle CPUs");
  252 
  253 static int forward_wakeup_use_mask = 1;
  254 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, usemask, CTLFLAG_RW,
  255            &forward_wakeup_use_mask, 0,
  256            "Use the mask of idle cpus");
  257 
  258 static int forward_wakeup_use_loop = 0;
  259 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, useloop, CTLFLAG_RW,
  260            &forward_wakeup_use_loop, 0,
  261            "Use a loop to find idle cpus");
  262 
  263 static int forward_wakeup_use_single = 0;
  264 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, onecpu, CTLFLAG_RW,
  265            &forward_wakeup_use_single, 0,
  266            "Only signal one idle cpu");
  267 
  268 static int forward_wakeup_use_htt = 0;
  269 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, htt2, CTLFLAG_RW,
  270            &forward_wakeup_use_htt, 0,
  271            "account for htt");
  272 
  273 #endif
  274 static int sched_followon = 0;
  275 SYSCTL_INT(_kern_sched, OID_AUTO, followon, CTLFLAG_RW,
  276            &sched_followon, 0,
  277            "allow threads to share a quantum");
  278 
  279 static int sched_pfollowons = 0;
  280 SYSCTL_INT(_kern_sched, OID_AUTO, pfollowons, CTLFLAG_RD,
  281            &sched_pfollowons, 0,
  282            "number of followons done to a different ksegrp");
  283 
  284 static int sched_kgfollowons = 0;
  285 SYSCTL_INT(_kern_sched, OID_AUTO, kgfollowons, CTLFLAG_RD,
  286            &sched_kgfollowons, 0,
  287            "number of followons done in a ksegrp");
  288 
  289 static __inline void
  290 sched_load_add(void)
  291 {
  292         sched_tdcnt++;
  293         CTR1(KTR_SCHED, "global load: %d", sched_tdcnt);
  294 }
  295 
  296 static __inline void
  297 sched_load_rem(void)
  298 {
  299         sched_tdcnt--;
  300         CTR1(KTR_SCHED, "global load: %d", sched_tdcnt);
  301 }
  302 /*
  303  * Arrange to reschedule if necessary, taking the priorities and
  304  * schedulers into account.
  305  */
  306 static void
  307 maybe_resched(struct thread *td)
  308 {
  309 
  310         mtx_assert(&sched_lock, MA_OWNED);
  311         if (td->td_priority < curthread->td_priority)
  312                 curthread->td_flags |= TDF_NEEDRESCHED;
  313 }
  314 
  315 /*
  316  * Constants for digital decay and forget:
  317  *      90% of (kg_estcpu) usage in 5 * loadav time
  318  *      95% of (ke_pctcpu) usage in 60 seconds (load insensitive)
  319  *          Note that, as ps(1) mentions, this can let percentages
  320  *          total over 100% (I've seen 137.9% for 3 processes).
  321  *
  322  * Note that schedclock() updates kg_estcpu and p_cpticks asynchronously.
  323  *
  324  * We wish to decay away 90% of kg_estcpu in (5 * loadavg) seconds.
  325  * That is, the system wants to compute a value of decay such
  326  * that the following for loop:
  327  *      for (i = 0; i < (5 * loadavg); i++)
  328  *              kg_estcpu *= decay;
  329  * will compute
  330  *      kg_estcpu *= 0.1;
  331  * for all values of loadavg:
  332  *
  333  * Mathematically this loop can be expressed by saying:
  334  *      decay ** (5 * loadavg) ~= .1
  335  *
  336  * The system computes decay as:
  337  *      decay = (2 * loadavg) / (2 * loadavg + 1)
  338  *
  339  * We wish to prove that the system's computation of decay
  340  * will always fulfill the equation:
  341  *      decay ** (5 * loadavg) ~= .1
  342  *
  343  * If we compute b as:
  344  *      b = 2 * loadavg
  345  * then
  346  *      decay = b / (b + 1)
  347  *
  348  * We now need to prove two things:
  349  *      1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
  350  *      2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
  351  *
  352  * Facts:
  353  *         For x close to zero, exp(x) =~ 1 + x, since
  354  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
  355  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
  356  *         For x close to zero, ln(1+x) =~ x, since
  357  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
  358  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
  359  *         ln(.1) =~ -2.30
  360  *
  361  * Proof of (1):
  362  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
  363  *      solving for factor,
  364  *      ln(factor) =~ (-2.30/5*loadav), or
  365  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
  366  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
  367  *
  368  * Proof of (2):
  369  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
  370  *      solving for power,
  371  *      power*ln(b/(b+1)) =~ -2.30, or
  372  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
  373  *
  374  * Actual power values for the implemented algorithm are as follows:
  375  *      loadav: 1       2       3       4
  376  *      power:  5.68    10.32   14.94   19.55
  377  */
  378 
  379 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
  380 #define loadfactor(loadav)      (2 * (loadav))
  381 #define decay_cpu(loadfac, cpu) (((loadfac) * (cpu)) / ((loadfac) + FSCALE))
  382 
  383 /* decay 95% of `ke_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
  384 static fixpt_t  ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
  385 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
  386 
  387 /*
  388  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
  389  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
  390  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
  391  *
  392  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
  393  *      1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
  394  *
  395  * If you don't want to bother with the faster/more-accurate formula, you
  396  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
  397  * (more general) method of calculating the %age of CPU used by a process.
  398  */
  399 #define CCPU_SHIFT      11
  400 
  401 /*
  402  * Recompute process priorities, every hz ticks.
  403  * MP-safe, called without the Giant mutex.
  404  */
  405 /* ARGSUSED */
  406 static void
  407 schedcpu(void)
  408 {
  409         register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
  410         struct thread *td;
  411         struct proc *p;
  412         struct kse *ke;
  413         struct ksegrp *kg;
  414         int awake, realstathz;
  415 
  416         realstathz = stathz ? stathz : hz;
  417         sx_slock(&allproc_lock);
  418         FOREACH_PROC_IN_SYSTEM(p) {
  419                 /*
  420                  * Prevent state changes and protect run queue.
  421                  */
  422                 mtx_lock_spin(&sched_lock);
  423                 /*
  424                  * Increment time in/out of memory.  We ignore overflow; with
  425                  * 16-bit int's (remember them?) overflow takes 45 days.
  426                  */
  427                 p->p_swtime++;
  428                 FOREACH_KSEGRP_IN_PROC(p, kg) { 
  429                         awake = 0;
  430                         FOREACH_THREAD_IN_GROUP(kg, td) {
  431                                 ke = td->td_kse;
  432                                 /*
  433                                  * Increment sleep time (if sleeping).  We
  434                                  * ignore overflow, as above.
  435                                  */
  436                                 /*
  437                                  * The kse slptimes are not touched in wakeup
  438                                  * because the thread may not HAVE a KSE.
  439                                  */
  440                                 if (ke->ke_state == KES_ONRUNQ) {
  441                                         awake = 1;
  442                                         ke->ke_flags &= ~KEF_DIDRUN;
  443                                 } else if ((ke->ke_state == KES_THREAD) &&
  444                                     (TD_IS_RUNNING(td))) {
  445                                         awake = 1;
  446                                         /* Do not clear KEF_DIDRUN */
  447                                 } else if (ke->ke_flags & KEF_DIDRUN) {
  448                                         awake = 1;
  449                                         ke->ke_flags &= ~KEF_DIDRUN;
  450                                 }
  451 
  452                                 /*
  453                                  * ke_pctcpu is only for ps and ttyinfo().
  454                                  * Do it per kse, and add them up at the end?
  455                                  * XXXKSE
  456                                  */
  457                                 ke->ke_pctcpu = (ke->ke_pctcpu * ccpu) >>
  458                                     FSHIFT;
  459                                 /*
  460                                  * If the kse has been idle the entire second,
  461                                  * stop recalculating its priority until
  462                                  * it wakes up.
  463                                  */
  464                                 if (ke->ke_cpticks == 0)
  465                                         continue;
  466 #if     (FSHIFT >= CCPU_SHIFT)
  467                                 ke->ke_pctcpu += (realstathz == 100)
  468                                     ? ((fixpt_t) ke->ke_cpticks) <<
  469                                     (FSHIFT - CCPU_SHIFT) :
  470                                     100 * (((fixpt_t) ke->ke_cpticks)
  471                                     << (FSHIFT - CCPU_SHIFT)) / realstathz;
  472 #else
  473                                 ke->ke_pctcpu += ((FSCALE - ccpu) *
  474                                     (ke->ke_cpticks *
  475                                     FSCALE / realstathz)) >> FSHIFT;
  476 #endif
  477                                 ke->ke_cpticks = 0;
  478                         } /* end of kse loop */
  479                         /* 
  480                          * If there are ANY running threads in this KSEGRP,
  481                          * then don't count it as sleeping.
  482                          */
  483                         if (awake) {
  484                                 if (kg->kg_slptime > 1) {
  485                                         /*
  486                                          * In an ideal world, this should not
  487                                          * happen, because whoever woke us
  488                                          * up from the long sleep should have
  489                                          * unwound the slptime and reset our
  490                                          * priority before we run at the stale
  491                                          * priority.  Should KASSERT at some
  492                                          * point when all the cases are fixed.
  493                                          */
  494                                         updatepri(kg);
  495                                 }
  496                                 kg->kg_slptime = 0;
  497                         } else
  498                                 kg->kg_slptime++;
  499                         if (kg->kg_slptime > 1)
  500                                 continue;
  501                         kg->kg_estcpu = decay_cpu(loadfac, kg->kg_estcpu);
  502                         resetpriority(kg);
  503                         FOREACH_THREAD_IN_GROUP(kg, td) {
  504                                 resetpriority_thread(td, kg);
  505                         }
  506                 } /* end of ksegrp loop */
  507                 mtx_unlock_spin(&sched_lock);
  508         } /* end of process loop */
  509         sx_sunlock(&allproc_lock);
  510 }
  511 
  512 /*
  513  * Main loop for a kthread that executes schedcpu once a second.
  514  */
  515 static void
  516 schedcpu_thread(void)
  517 {
  518         int nowake;
  519 
  520         for (;;) {
  521                 schedcpu();
  522                 tsleep(&nowake, 0, "-", hz);
  523         }
  524 }
  525 
  526 /*
  527  * Recalculate the priority of a process after it has slept for a while.
  528  * For all load averages >= 1 and max kg_estcpu of 255, sleeping for at
  529  * least six times the loadfactor will decay kg_estcpu to zero.
  530  */
  531 static void
  532 updatepri(struct ksegrp *kg)
  533 {
  534         register fixpt_t loadfac;
  535         register unsigned int newcpu;
  536 
  537         loadfac = loadfactor(averunnable.ldavg[0]);
  538         if (kg->kg_slptime > 5 * loadfac)
  539                 kg->kg_estcpu = 0;
  540         else {
  541                 newcpu = kg->kg_estcpu;
  542                 kg->kg_slptime--;       /* was incremented in schedcpu() */
  543                 while (newcpu && --kg->kg_slptime)
  544                         newcpu = decay_cpu(loadfac, newcpu);
  545                 kg->kg_estcpu = newcpu;
  546         }
  547 }
  548 
  549 /*
  550  * Compute the priority of a process when running in user mode.
  551  * Arrange to reschedule if the resulting priority is better
  552  * than that of the current process.
  553  */
  554 static void
  555 resetpriority(struct ksegrp *kg)
  556 {
  557         register unsigned int newpriority;
  558 
  559         if (kg->kg_pri_class == PRI_TIMESHARE) {
  560                 newpriority = PUSER + kg->kg_estcpu / INVERSE_ESTCPU_WEIGHT +
  561                     NICE_WEIGHT * (kg->kg_proc->p_nice - PRIO_MIN);
  562                 newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
  563                     PRI_MAX_TIMESHARE);
  564                 kg->kg_user_pri = newpriority;
  565         }
  566 }
  567 
  568 /*
  569  * Update the thread's priority when the associated ksegroup's user
  570  * priority changes.
  571  */
  572 static void
  573 resetpriority_thread(struct thread *td, struct ksegrp *kg)
  574 {
  575 
  576         /* Only change threads with a time sharing user priority. */
  577         if (td->td_priority < PRI_MIN_TIMESHARE ||
  578             td->td_priority > PRI_MAX_TIMESHARE)
  579                 return;
  580 
  581         /* XXX the whole needresched thing is broken, but not silly. */
  582         maybe_resched(td);
  583 
  584         sched_prio(td, kg->kg_user_pri);
  585 }
  586 
  587 /* ARGSUSED */
  588 static void
  589 sched_setup(void *dummy)
  590 {
  591         setup_runqs();
  592 
  593         if (sched_quantum == 0)
  594                 sched_quantum = SCHED_QUANTUM;
  595         hogticks = 2 * sched_quantum;
  596 
  597         /* Account for thread0. */
  598         sched_load_add();
  599 }
  600 
  601 /* External interfaces start here */
  602 /*
  603  * Very early in the boot some setup of scheduler-specific
  604  * parts of proc0 and of some scheduler resources needs to be done.
  605  * Called from:
  606  *  proc0_init()
  607  */
  608 void
  609 schedinit(void)
  610 {
  611         /*
  612          * Set up the scheduler specific parts of proc0.
  613          */
  614         proc0.p_sched = NULL; /* XXX */
  615         ksegrp0.kg_sched = &kg_sched0;
  616         thread0.td_sched = &kse0;
  617         kse0.ke_thread = &thread0;
  618         kse0.ke_state = KES_THREAD;
  619         kg_sched0.skg_concurrency = 1;
  620         kg_sched0.skg_avail_opennings = 0; /* we are already running */
  621 }
  622 
  623 int
  624 sched_runnable(void)
  625 {
  626 #ifdef SMP
  627         return runq_check(&runq) + runq_check(&runq_pcpu[PCPU_GET(cpuid)]);
  628 #else
  629         return runq_check(&runq);
  630 #endif
  631 }
  632 
  633 int 
  634 sched_rr_interval(void)
  635 {
  636         if (sched_quantum == 0)
  637                 sched_quantum = SCHED_QUANTUM;
  638         return (sched_quantum);
  639 }
  640 
  641 /*
  642  * We adjust the priority of the current process.  The priority of
  643  * a process gets worse as it accumulates CPU time.  The cpu usage
  644  * estimator (kg_estcpu) is increased here.  resetpriority() will
  645  * compute a different priority each time kg_estcpu increases by
  646  * INVERSE_ESTCPU_WEIGHT
  647  * (until MAXPRI is reached).  The cpu usage estimator ramps up
  648  * quite quickly when the process is running (linearly), and decays
  649  * away exponentially, at a rate which is proportionally slower when
  650  * the system is busy.  The basic principle is that the system will
  651  * 90% forget that the process used a lot of CPU time in 5 * loadav
  652  * seconds.  This causes the system to favor processes which haven't
  653  * run much recently, and to round-robin among other processes.
  654  */
  655 void
  656 sched_clock(struct thread *td)
  657 {
  658         struct ksegrp *kg;
  659         struct kse *ke;
  660 
  661         mtx_assert(&sched_lock, MA_OWNED);
  662         kg = td->td_ksegrp;
  663         ke = td->td_kse;
  664 
  665         ke->ke_cpticks++;
  666         kg->kg_estcpu = ESTCPULIM(kg->kg_estcpu + 1);
  667         if ((kg->kg_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
  668                 resetpriority(kg);
  669                 resetpriority_thread(td, kg);
  670         }
  671 
  672         /*
  673          * Force a context switch if the current thread has used up a full
  674          * quantum (default quantum is 100ms).
  675          */
  676         if (td != PCPU_GET(idlethread) &&
  677             ticks - PCPU_GET(switchticks) >= sched_quantum)
  678                 td->td_flags |= TDF_NEEDRESCHED;
  679 }
  680 
  681 /*
  682  * charge childs scheduling cpu usage to parent.
  683  *
  684  * XXXKSE assume only one thread & kse & ksegrp keep estcpu in each ksegrp.
  685  * Charge it to the ksegrp that did the wait since process estcpu is sum of
  686  * all ksegrps, this is strictly as expected.  Assume that the child process
  687  * aggregated all the estcpu into the 'built-in' ksegrp.
  688  */
  689 void
  690 sched_exit(struct proc *p, struct thread *td)
  691 {
  692         sched_exit_ksegrp(FIRST_KSEGRP_IN_PROC(p), td);
  693         sched_exit_thread(FIRST_THREAD_IN_PROC(p), td);
  694 }
  695 
  696 void
  697 sched_exit_ksegrp(struct ksegrp *kg, struct thread *childtd)
  698 {
  699 
  700         mtx_assert(&sched_lock, MA_OWNED);
  701         kg->kg_estcpu = ESTCPULIM(kg->kg_estcpu + childtd->td_ksegrp->kg_estcpu);
  702 }
  703 
  704 void
  705 sched_exit_thread(struct thread *td, struct thread *child)
  706 {
  707         CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
  708             child, child->td_proc->p_comm, child->td_priority);
  709         if ((child->td_proc->p_flag & P_NOLOAD) == 0)
  710                 sched_load_rem();
  711 }
  712 
  713 void
  714 sched_fork(struct thread *td, struct thread *childtd)
  715 {
  716         sched_fork_ksegrp(td, childtd->td_ksegrp);
  717         sched_fork_thread(td, childtd);
  718 }
  719 
  720 void
  721 sched_fork_ksegrp(struct thread *td, struct ksegrp *child)
  722 {
  723         mtx_assert(&sched_lock, MA_OWNED);
  724         child->kg_estcpu = td->td_ksegrp->kg_estcpu;
  725 }
  726 
  727 void
  728 sched_fork_thread(struct thread *td, struct thread *childtd)
  729 {
  730         sched_newthread(childtd);
  731 }
  732 
  733 void
  734 sched_nice(struct proc *p, int nice)
  735 {
  736         struct ksegrp *kg;
  737         struct thread *td;
  738 
  739         PROC_LOCK_ASSERT(p, MA_OWNED);
  740         mtx_assert(&sched_lock, MA_OWNED);
  741         p->p_nice = nice;
  742         FOREACH_KSEGRP_IN_PROC(p, kg) {
  743                 resetpriority(kg);
  744                 FOREACH_THREAD_IN_GROUP(kg, td) {
  745                         resetpriority_thread(td, kg);
  746                 }
  747         }
  748 }
  749 
  750 void
  751 sched_class(struct ksegrp *kg, int class)
  752 {
  753         mtx_assert(&sched_lock, MA_OWNED);
  754         kg->kg_pri_class = class;
  755 }
  756 
  757 /*
  758  * Adjust the priority of a thread.
  759  * This may include moving the thread within the KSEGRP,
  760  * changing the assignment of a kse to the thread,
  761  * and moving a KSE in the system run queue.
  762  */
  763 static void
  764 sched_priority(struct thread *td, u_char prio)
  765 {
  766         CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
  767             td, td->td_proc->p_comm, td->td_priority, prio, curthread, 
  768             curthread->td_proc->p_comm);
  769 
  770         mtx_assert(&sched_lock, MA_OWNED);
  771         if (td->td_priority == prio)
  772                 return;
  773         if (TD_ON_RUNQ(td)) {
  774                 adjustrunqueue(td, prio);
  775         } else {
  776                 td->td_priority = prio;
  777         }
  778 }
  779 
  780 /*
  781  * Update a thread's priority when it is lent another thread's
  782  * priority.
  783  */
  784 void
  785 sched_lend_prio(struct thread *td, u_char prio)
  786 {
  787 
  788         td->td_flags |= TDF_BORROWING;
  789         sched_priority(td, prio);
  790 }
  791 
  792 /*
  793  * Restore a thread's priority when priority propagation is
  794  * over.  The prio argument is the minimum priority the thread
  795  * needs to have to satisfy other possible priority lending
  796  * requests.  If the thread's regulary priority is less
  797  * important than prio the thread will keep a priority boost
  798  * of prio.
  799  */
  800 void
  801 sched_unlend_prio(struct thread *td, u_char prio)
  802 {
  803         u_char base_pri;
  804 
  805         if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
  806             td->td_base_pri <= PRI_MAX_TIMESHARE)
  807                 base_pri = td->td_ksegrp->kg_user_pri;
  808         else
  809                 base_pri = td->td_base_pri;
  810         if (prio >= base_pri) {
  811                 td->td_flags &= ~TDF_BORROWING;
  812                 sched_prio(td, base_pri);
  813         } else
  814                 sched_lend_prio(td, prio);
  815 }
  816 
  817 void
  818 sched_prio(struct thread *td, u_char prio)
  819 {
  820         u_char oldprio;
  821 
  822         /* First, update the base priority. */
  823         td->td_base_pri = prio;
  824 
  825         /*
  826          * If the thread is borrowing another thread's priority, don't ever
  827          * lower the priority.
  828          */
  829         if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
  830                 return;
  831 
  832         /* Change the real priority. */
  833         oldprio = td->td_priority;
  834         sched_priority(td, prio);
  835 
  836         /*
  837          * If the thread is on a turnstile, then let the turnstile update
  838          * its state.
  839          */
  840         if (TD_ON_LOCK(td) && oldprio != prio)
  841                 turnstile_adjust(td, oldprio);
  842 }
  843 
  844 void
  845 sched_sleep(struct thread *td)
  846 {
  847 
  848         mtx_assert(&sched_lock, MA_OWNED);
  849         td->td_ksegrp->kg_slptime = 0;
  850 }
  851 
  852 static void remrunqueue(struct thread *td);
  853 
  854 void
  855 sched_switch(struct thread *td, struct thread *newtd, int flags)
  856 {
  857         struct kse *ke;
  858         struct ksegrp *kg;
  859         struct proc *p;
  860 
  861         ke = td->td_kse;
  862         p = td->td_proc;
  863 
  864         mtx_assert(&sched_lock, MA_OWNED);
  865 
  866         if ((p->p_flag & P_NOLOAD) == 0)
  867                 sched_load_rem();
  868         /* 
  869          * We are volunteering to switch out so we get to nominate
  870          * a successor for the rest of our quantum
  871          * First try another thread in our ksegrp, and then look for 
  872          * other ksegrps in our process.
  873          */
  874         if (sched_followon &&
  875             (p->p_flag & P_HADTHREADS) &&
  876             (flags & SW_VOL) &&
  877             newtd == NULL) {
  878                 /* lets schedule another thread from this process */
  879                  kg = td->td_ksegrp;
  880                  if ((newtd = TAILQ_FIRST(&kg->kg_runq))) {
  881                         remrunqueue(newtd);
  882                         sched_kgfollowons++;
  883                  } else {
  884                         FOREACH_KSEGRP_IN_PROC(p, kg) {
  885                                 if ((newtd = TAILQ_FIRST(&kg->kg_runq))) {
  886                                         sched_pfollowons++;
  887                                         remrunqueue(newtd);
  888                                         break;
  889                                 }
  890                         }
  891                 }
  892         }
  893 
  894         if (newtd) 
  895                 newtd->td_flags |= (td->td_flags & TDF_NEEDRESCHED);
  896 
  897         td->td_lastcpu = td->td_oncpu;
  898         td->td_flags &= ~TDF_NEEDRESCHED;
  899         td->td_owepreempt = 0;
  900         td->td_oncpu = NOCPU;
  901         /*
  902          * At the last moment, if this thread is still marked RUNNING,
  903          * then put it back on the run queue as it has not been suspended
  904          * or stopped or any thing else similar.  We never put the idle
  905          * threads on the run queue, however.
  906          */
  907         if (td == PCPU_GET(idlethread))
  908                 TD_SET_CAN_RUN(td);
  909         else {
  910                 SLOT_RELEASE(td->td_ksegrp);
  911                 if (TD_IS_RUNNING(td)) {
  912                         /* Put us back on the run queue (kse and all). */
  913                         setrunqueue(td, (flags & SW_PREEMPT) ?
  914                             SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
  915                             SRQ_OURSELF|SRQ_YIELDING);
  916                 } else if (p->p_flag & P_HADTHREADS) {
  917                         /*
  918                          * We will not be on the run queue. So we must be
  919                          * sleeping or similar. As it's available,
  920                          * someone else can use the KSE if they need it.
  921                          * It's NOT available if we are about to need it
  922                          */
  923                         if (newtd == NULL || newtd->td_ksegrp != td->td_ksegrp)
  924                                 slot_fill(td->td_ksegrp);
  925                 }
  926         }
  927         if (newtd) {
  928                 /* 
  929                  * The thread we are about to run needs to be counted
  930                  * as if it had been added to the run queue and selected.
  931                  * It came from:
  932                  * * A preemption
  933                  * * An upcall 
  934                  * * A followon
  935                  */
  936                 KASSERT((newtd->td_inhibitors == 0),
  937                         ("trying to run inhibitted thread"));
  938                 SLOT_USE(newtd->td_ksegrp);
  939                 newtd->td_kse->ke_flags |= KEF_DIDRUN;
  940                 TD_SET_RUNNING(newtd);
  941                 if ((newtd->td_proc->p_flag & P_NOLOAD) == 0)
  942                         sched_load_add();
  943         } else {
  944                 newtd = choosethread();
  945         }
  946 
  947         if (td != newtd) {
  948 #ifdef  HWPMC_HOOKS
  949                 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
  950                         PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
  951 #endif
  952                 cpu_switch(td, newtd);
  953 #ifdef  HWPMC_HOOKS
  954                 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
  955                         PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
  956 #endif
  957         }
  958 
  959         sched_lock.mtx_lock = (uintptr_t)td;
  960         td->td_oncpu = PCPU_GET(cpuid);
  961 }
  962 
  963 void
  964 sched_wakeup(struct thread *td)
  965 {
  966         struct ksegrp *kg;
  967 
  968         mtx_assert(&sched_lock, MA_OWNED);
  969         kg = td->td_ksegrp;
  970         if (kg->kg_slptime > 1) {
  971                 updatepri(kg);
  972                 resetpriority(kg);
  973         }
  974         kg->kg_slptime = 0;
  975         setrunqueue(td, SRQ_BORING);
  976 }
  977 
  978 #ifdef SMP
  979 /* enable HTT_2 if you have a 2-way HTT cpu.*/
  980 static int
  981 forward_wakeup(int  cpunum)
  982 {
  983         cpumask_t map, me, dontuse;
  984         cpumask_t map2;
  985         struct pcpu *pc;
  986         cpumask_t id, map3;
  987 
  988         mtx_assert(&sched_lock, MA_OWNED);
  989 
  990         CTR0(KTR_RUNQ, "forward_wakeup()");
  991 
  992         if ((!forward_wakeup_enabled) ||
  993              (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
  994                 return (0);
  995         if (!smp_started || cold || panicstr)
  996                 return (0);
  997 
  998         forward_wakeups_requested++;
  999 
 1000 /*
 1001  * check the idle mask we received against what we calculated before
 1002  * in the old version.
 1003  */
 1004         me = PCPU_GET(cpumask);
 1005         /* 
 1006          * don't bother if we should be doing it ourself..
 1007          */
 1008         if ((me & idle_cpus_mask) && (cpunum == NOCPU || me == (1 << cpunum)))
 1009                 return (0);
 1010 
 1011         dontuse = me | stopped_cpus | hlt_cpus_mask;
 1012         map3 = 0;
 1013         if (forward_wakeup_use_loop) {
 1014                 SLIST_FOREACH(pc, &cpuhead, pc_allcpu) {
 1015                         id = pc->pc_cpumask;
 1016                         if ( (id & dontuse) == 0 &&
 1017                             pc->pc_curthread == pc->pc_idlethread) {
 1018                                 map3 |= id;
 1019                         }
 1020                 }
 1021         }
 1022 
 1023         if (forward_wakeup_use_mask) {
 1024                 map = 0;
 1025                 map = idle_cpus_mask & ~dontuse;
 1026 
 1027                 /* If they are both on, compare and use loop if different */
 1028                 if (forward_wakeup_use_loop) {
 1029                         if (map != map3) {
 1030                                 printf("map (%02X) != map3 (%02X)\n",
 1031                                                 map, map3);
 1032                                 map = map3;
 1033                         }
 1034                 }
 1035         } else {
 1036                 map = map3;
 1037         }
 1038         /* If we only allow a specific CPU, then mask off all the others */
 1039         if (cpunum != NOCPU) {
 1040                 KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
 1041                 map &= (1 << cpunum);
 1042         } else {
 1043                 /* Try choose an idle die. */
 1044                 if (forward_wakeup_use_htt) {
 1045                         map2 =  (map & (map >> 1)) & 0x5555;
 1046                         if (map2) {
 1047                                 map = map2;
 1048                         }
 1049                 }
 1050 
 1051                 /* set only one bit */ 
 1052                 if (forward_wakeup_use_single) {
 1053                         map = map & ((~map) + 1);
 1054                 }
 1055         }
 1056         if (map) {
 1057                 forward_wakeups_delivered++;
 1058                 ipi_selected(map, IPI_AST);
 1059                 return (1);
 1060         }
 1061         if (cpunum == NOCPU)
 1062                 printf("forward_wakeup: Idle processor not found\n");
 1063         return (0);
 1064 }
 1065 #endif
 1066 
 1067 #ifdef SMP
 1068 static void kick_other_cpu(int pri,int cpuid);
 1069 
 1070 static void
 1071 kick_other_cpu(int pri,int cpuid)
 1072 {       
 1073         struct pcpu * pcpu = pcpu_find(cpuid);
 1074         int cpri = pcpu->pc_curthread->td_priority;
 1075 
 1076         if (idle_cpus_mask & pcpu->pc_cpumask) {
 1077                 forward_wakeups_delivered++;
 1078                 ipi_selected(pcpu->pc_cpumask, IPI_AST);
 1079                 return;
 1080         }
 1081 
 1082         if (pri >= cpri)
 1083                 return;
 1084 
 1085 #if defined(IPI_PREEMPTION) && defined(PREEMPTION)
 1086 #if !defined(FULL_PREEMPTION)
 1087         if (pri <= PRI_MAX_ITHD)
 1088 #endif /* ! FULL_PREEMPTION */
 1089         {
 1090                 ipi_selected(pcpu->pc_cpumask, IPI_PREEMPT);
 1091                 return;
 1092         }
 1093 #endif /* defined(IPI_PREEMPTION) && defined(PREEMPTION) */
 1094 
 1095         pcpu->pc_curthread->td_flags |= TDF_NEEDRESCHED;
 1096         ipi_selected( pcpu->pc_cpumask , IPI_AST);
 1097         return;
 1098 }
 1099 #endif /* SMP */
 1100 
 1101 void
 1102 sched_add(struct thread *td, int flags)
 1103 #ifdef SMP
 1104 {
 1105         struct kse *ke;
 1106         int forwarded = 0;
 1107         int cpu;
 1108         int single_cpu = 0;
 1109 
 1110         ke = td->td_kse;
 1111         mtx_assert(&sched_lock, MA_OWNED);
 1112         KASSERT(ke->ke_state != KES_ONRUNQ,
 1113             ("sched_add: kse %p (%s) already in run queue", ke,
 1114             ke->ke_proc->p_comm));
 1115         KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
 1116             ("sched_add: process swapped out"));
 1117         CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
 1118             td, td->td_proc->p_comm, td->td_priority, curthread,
 1119             curthread->td_proc->p_comm);
 1120 
 1121 
 1122         if (td->td_pinned != 0) {
 1123                 cpu = td->td_lastcpu;
 1124                 ke->ke_runq = &runq_pcpu[cpu];
 1125                 single_cpu = 1;
 1126                 CTR3(KTR_RUNQ,
 1127                     "sched_add: Put kse:%p(td:%p) on cpu%d runq", ke, td, cpu);
 1128         } else if ((ke)->ke_flags & KEF_BOUND) {
 1129                 /* Find CPU from bound runq */
 1130                 KASSERT(SKE_RUNQ_PCPU(ke),("sched_add: bound kse not on cpu runq"));
 1131                 cpu = ke->ke_runq - &runq_pcpu[0];
 1132                 single_cpu = 1;
 1133                 CTR3(KTR_RUNQ,
 1134                     "sched_add: Put kse:%p(td:%p) on cpu%d runq", ke, td, cpu);
 1135         } else {        
 1136                 CTR2(KTR_RUNQ,
 1137                     "sched_add: adding kse:%p (td:%p) to gbl runq", ke, td);
 1138                 cpu = NOCPU;
 1139                 ke->ke_runq = &runq;
 1140         }
 1141         
 1142         if (single_cpu && (cpu != PCPU_GET(cpuid))) {
 1143                 kick_other_cpu(td->td_priority,cpu);
 1144         } else {
 1145                 
 1146                 if (!single_cpu) {
 1147                         cpumask_t me = PCPU_GET(cpumask);
 1148                         int idle = idle_cpus_mask & me; 
 1149 
 1150                         if (!idle && ((flags & SRQ_INTR) == 0) &&
 1151                             (idle_cpus_mask & ~(hlt_cpus_mask | me)))
 1152                                 forwarded = forward_wakeup(cpu);
 1153                 }
 1154 
 1155                 if (!forwarded) {
 1156                         if ((flags & SRQ_YIELDING) == 0 && maybe_preempt(td))
 1157                                 return;
 1158                         else
 1159                                 maybe_resched(td);
 1160                 }
 1161         }
 1162         
 1163         if ((td->td_proc->p_flag & P_NOLOAD) == 0)
 1164                 sched_load_add();
 1165         SLOT_USE(td->td_ksegrp);
 1166         runq_add(ke->ke_runq, ke, flags);
 1167         ke->ke_state = KES_ONRUNQ;
 1168 }
 1169 #else /* SMP */
 1170 {
 1171         struct kse *ke;
 1172         ke = td->td_kse;
 1173         mtx_assert(&sched_lock, MA_OWNED);
 1174         KASSERT(ke->ke_state != KES_ONRUNQ,
 1175             ("sched_add: kse %p (%s) already in run queue", ke,
 1176             ke->ke_proc->p_comm));
 1177         KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
 1178             ("sched_add: process swapped out"));
 1179         CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
 1180             td, td->td_proc->p_comm, td->td_priority, curthread,
 1181             curthread->td_proc->p_comm);
 1182         CTR2(KTR_RUNQ, "sched_add: adding kse:%p (td:%p) to runq", ke, td);
 1183         ke->ke_runq = &runq;
 1184 
 1185         /* 
 1186          * If we are yielding (on the way out anyhow) 
 1187          * or the thread being saved is US,
 1188          * then don't try be smart about preemption
 1189          * or kicking off another CPU
 1190          * as it won't help and may hinder.
 1191          * In the YIEDLING case, we are about to run whoever is 
 1192          * being put in the queue anyhow, and in the 
 1193          * OURSELF case, we are puting ourself on the run queue
 1194          * which also only happens when we are about to yield.
 1195          */
 1196         if((flags & SRQ_YIELDING) == 0) {
 1197                 if (maybe_preempt(td))
 1198                         return;
 1199         }       
 1200         if ((td->td_proc->p_flag & P_NOLOAD) == 0)
 1201                 sched_load_add();
 1202         SLOT_USE(td->td_ksegrp);
 1203         runq_add(ke->ke_runq, ke, flags);
 1204         ke->ke_state = KES_ONRUNQ;
 1205         maybe_resched(td);
 1206 }
 1207 #endif /* SMP */
 1208 
 1209 void
 1210 sched_rem(struct thread *td)
 1211 {
 1212         struct kse *ke;
 1213 
 1214         ke = td->td_kse;
 1215         KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
 1216             ("sched_rem: process swapped out"));
 1217         KASSERT((ke->ke_state == KES_ONRUNQ),
 1218             ("sched_rem: KSE not on run queue"));
 1219         mtx_assert(&sched_lock, MA_OWNED);
 1220         CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
 1221             td, td->td_proc->p_comm, td->td_priority, curthread,
 1222             curthread->td_proc->p_comm);
 1223 
 1224         if ((td->td_proc->p_flag & P_NOLOAD) == 0)
 1225                 sched_load_rem();
 1226         SLOT_RELEASE(td->td_ksegrp);
 1227         runq_remove(ke->ke_runq, ke);
 1228 
 1229         ke->ke_state = KES_THREAD;
 1230 }
 1231 
 1232 /*
 1233  * Select threads to run.
 1234  * Notice that the running threads still consume a slot.
 1235  */
 1236 struct kse *
 1237 sched_choose(void)
 1238 {
 1239         struct kse *ke;
 1240         struct runq *rq;
 1241 
 1242 #ifdef SMP
 1243         struct kse *kecpu;
 1244 
 1245         rq = &runq;
 1246         ke = runq_choose(&runq);
 1247         kecpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
 1248 
 1249         if (ke == NULL || 
 1250             (kecpu != NULL && 
 1251              kecpu->ke_thread->td_priority < ke->ke_thread->td_priority)) {
 1252                 CTR2(KTR_RUNQ, "choosing kse %p from pcpu runq %d", kecpu,
 1253                      PCPU_GET(cpuid));
 1254                 ke = kecpu;
 1255                 rq = &runq_pcpu[PCPU_GET(cpuid)];
 1256         } else { 
 1257                 CTR1(KTR_RUNQ, "choosing kse %p from main runq", ke);
 1258         }
 1259 
 1260 #else
 1261         rq = &runq;
 1262         ke = runq_choose(&runq);
 1263 #endif
 1264 
 1265         if (ke != NULL) {
 1266                 runq_remove(rq, ke);
 1267                 ke->ke_state = KES_THREAD;
 1268 
 1269                 KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
 1270                     ("sched_choose: process swapped out"));
 1271         }
 1272         return (ke);
 1273 }
 1274 
 1275 void
 1276 sched_userret(struct thread *td)
 1277 {
 1278         struct ksegrp *kg;
 1279         /*
 1280          * XXX we cheat slightly on the locking here to avoid locking in
 1281          * the usual case.  Setting td_priority here is essentially an
 1282          * incomplete workaround for not setting it properly elsewhere.
 1283          * Now that some interrupt handlers are threads, not setting it
 1284          * properly elsewhere can clobber it in the window between setting
 1285          * it here and returning to user mode, so don't waste time setting
 1286          * it perfectly here.
 1287          */
 1288         KASSERT((td->td_flags & TDF_BORROWING) == 0,
 1289             ("thread with borrowed priority returning to userland"));
 1290         kg = td->td_ksegrp;
 1291         if (td->td_priority != kg->kg_user_pri) {
 1292                 mtx_lock_spin(&sched_lock);
 1293                 td->td_priority = kg->kg_user_pri;
 1294                 td->td_base_pri = kg->kg_user_pri;
 1295                 mtx_unlock_spin(&sched_lock);
 1296         }
 1297 }
 1298 
 1299 void
 1300 sched_bind(struct thread *td, int cpu)
 1301 {
 1302         struct kse *ke;
 1303 
 1304         mtx_assert(&sched_lock, MA_OWNED);
 1305         KASSERT(TD_IS_RUNNING(td),
 1306             ("sched_bind: cannot bind non-running thread"));
 1307 
 1308         ke = td->td_kse;
 1309 
 1310         ke->ke_flags |= KEF_BOUND;
 1311 #ifdef SMP
 1312         ke->ke_runq = &runq_pcpu[cpu];
 1313         if (PCPU_GET(cpuid) == cpu)
 1314                 return;
 1315 
 1316         ke->ke_state = KES_THREAD;
 1317 
 1318         mi_switch(SW_VOL, NULL);
 1319 #endif
 1320 }
 1321 
 1322 void
 1323 sched_unbind(struct thread* td)
 1324 {
 1325         mtx_assert(&sched_lock, MA_OWNED);
 1326         td->td_kse->ke_flags &= ~KEF_BOUND;
 1327 }
 1328 
 1329 int
 1330 sched_is_bound(struct thread *td)
 1331 {
 1332         mtx_assert(&sched_lock, MA_OWNED);
 1333         return (td->td_kse->ke_flags & KEF_BOUND);
 1334 }
 1335 
 1336 int
 1337 sched_load(void)
 1338 {
 1339         return (sched_tdcnt);
 1340 }
 1341 
 1342 int
 1343 sched_sizeof_ksegrp(void)
 1344 {
 1345         return (sizeof(struct ksegrp) + sizeof(struct kg_sched));
 1346 }
 1347 int
 1348 sched_sizeof_proc(void)
 1349 {
 1350         return (sizeof(struct proc));
 1351 }
 1352 int
 1353 sched_sizeof_thread(void)
 1354 {
 1355         return (sizeof(struct thread) + sizeof(struct kse));
 1356 }
 1357 
 1358 fixpt_t
 1359 sched_pctcpu(struct thread *td)
 1360 {
 1361         struct kse *ke;
 1362 
 1363         ke = td->td_kse;
 1364         return (ke->ke_pctcpu);
 1365 
 1366         return (0);
 1367 }
 1368 #define KERN_SWITCH_INCLUDE 1
 1369 #include "kern/kern_switch.c"

Cache object: 1a3b956b86af864070190ff3840c75c3


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.