Remove KKASSERT() from the code block where not all callers' CPU own
[dragonfly.git] / sys / kern / usched_bsd4.c
1 /*
2  * Copyright (c) 1999 Peter Wemm <peter@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $DragonFly: src/sys/kern/usched_bsd4.c,v 1.24 2008/06/19 05:34:23 y0netan1 Exp $
27  */
28
29 #include <sys/param.h>
30 #include <sys/systm.h>
31 #include <sys/kernel.h>
32 #include <sys/lock.h>
33 #include <sys/queue.h>
34 #include <sys/proc.h>
35 #include <sys/rtprio.h>
36 #include <sys/uio.h>
37 #include <sys/sysctl.h>
38 #include <sys/resourcevar.h>
39 #include <sys/spinlock.h>
40 #include <machine/cpu.h>
41 #include <machine/smp.h>
42
43 #include <sys/thread2.h>
44 #include <sys/spinlock2.h>
45
46 /*
47  * Priorities.  Note that with 32 run queues per scheduler each queue
48  * represents four priority levels.
49  */
50
51 #define MAXPRI                  128
52 #define PRIMASK                 (MAXPRI - 1)
53 #define PRIBASE_REALTIME        0
54 #define PRIBASE_NORMAL          MAXPRI
55 #define PRIBASE_IDLE            (MAXPRI * 2)
56 #define PRIBASE_THREAD          (MAXPRI * 3)
57 #define PRIBASE_NULL            (MAXPRI * 4)
58
59 #define NQS     32                      /* 32 run queues. */
60 #define PPQ     (MAXPRI / NQS)          /* priorities per queue */
61 #define PPQMASK (PPQ - 1)
62
63 /*
64  * NICEPPQ      - number of nice units per priority queue
65  * ESTCPURAMP   - number of scheduler ticks for estcpu to switch queues
66  *
67  * ESTCPUPPQ    - number of estcpu units per priority queue
68  * ESTCPUMAX    - number of estcpu units
69  * ESTCPUINCR   - amount we have to increment p_estcpu per scheduling tick at
70  *                100% cpu.
71  */
72 #define NICEPPQ         2
73 #define ESTCPURAMP      4
74 #define ESTCPUPPQ       512
75 #define ESTCPUMAX       (ESTCPUPPQ * NQS)
76 #define ESTCPUINCR      (ESTCPUPPQ / ESTCPURAMP)
77 #define PRIO_RANGE      (PRIO_MAX - PRIO_MIN + 1)
78
79 #define ESTCPULIM(v)    min((v), ESTCPUMAX)
80
81 TAILQ_HEAD(rq, lwp);
82
83 #define lwp_priority    lwp_usdata.bsd4.priority
84 #define lwp_rqindex     lwp_usdata.bsd4.rqindex
85 #define lwp_origcpu     lwp_usdata.bsd4.origcpu
86 #define lwp_estcpu      lwp_usdata.bsd4.estcpu
87 #define lwp_rqtype      lwp_usdata.bsd4.rqtype
88
89 static void bsd4_acquire_curproc(struct lwp *lp);
90 static void bsd4_release_curproc(struct lwp *lp);
91 static void bsd4_select_curproc(globaldata_t gd);
92 static void bsd4_setrunqueue(struct lwp *lp);
93 static void bsd4_schedulerclock(struct lwp *lp, sysclock_t period,
94                                 sysclock_t cpstamp);
95 static void bsd4_recalculate_estcpu(struct lwp *lp);
96 static void bsd4_resetpriority(struct lwp *lp);
97 static void bsd4_forking(struct lwp *plp, struct lwp *lp);
98 static void bsd4_exiting(struct lwp *plp, struct lwp *lp);
99 static void bsd4_yield(struct lwp *lp);
100
101 #ifdef SMP
102 static void need_user_resched_remote(void *dummy);
103 #endif
104 static struct lwp *chooseproc_locked(struct lwp *chklp);
105 static void bsd4_remrunqueue_locked(struct lwp *lp);
106 static void bsd4_setrunqueue_locked(struct lwp *lp);
107
108 struct usched usched_bsd4 = {
109         { NULL },
110         "bsd4", "Original DragonFly Scheduler",
111         NULL,                   /* default registration */
112         NULL,                   /* default deregistration */
113         bsd4_acquire_curproc,
114         bsd4_release_curproc,
115         bsd4_setrunqueue,
116         bsd4_schedulerclock,
117         bsd4_recalculate_estcpu,
118         bsd4_resetpriority,
119         bsd4_forking,
120         bsd4_exiting,
121         NULL,                   /* setcpumask not supported */
122         bsd4_yield
123 };
124
125 struct usched_bsd4_pcpu {
126         struct thread helper_thread;
127         short   rrcount;
128         short   upri;
129         struct lwp *uschedcp;
130 };
131
132 typedef struct usched_bsd4_pcpu *bsd4_pcpu_t;
133
134 /*
135  * We have NQS (32) run queues per scheduling class.  For the normal
136  * class, there are 128 priorities scaled onto these 32 queues.  New
137  * processes are added to the last entry in each queue, and processes
138  * are selected for running by taking them from the head and maintaining
139  * a simple FIFO arrangement.  Realtime and Idle priority processes have
140  * and explicit 0-31 priority which maps directly onto their class queue
141  * index.  When a queue has something in it, the corresponding bit is
142  * set in the queuebits variable, allowing a single read to determine
143  * the state of all 32 queues and then a ffs() to find the first busy
144  * queue.
145  */
146 static struct rq bsd4_queues[NQS];
147 static struct rq bsd4_rtqueues[NQS];
148 static struct rq bsd4_idqueues[NQS];
149 static u_int32_t bsd4_queuebits;
150 static u_int32_t bsd4_rtqueuebits;
151 static u_int32_t bsd4_idqueuebits;
152 static cpumask_t bsd4_curprocmask = -1; /* currently running a user process */
153 static cpumask_t bsd4_rdyprocmask;      /* ready to accept a user process */
154 static int       bsd4_runqcount;
155 #ifdef SMP
156 static volatile int bsd4_scancpu;
157 #endif
158 static struct spinlock bsd4_spin;
159 static struct usched_bsd4_pcpu bsd4_pcpu[MAXCPU];
160
161 SYSCTL_INT(_debug, OID_AUTO, bsd4_runqcount, CTLFLAG_RD, &bsd4_runqcount, 0, "");
162 #ifdef INVARIANTS
163 static int usched_nonoptimal;
164 SYSCTL_INT(_debug, OID_AUTO, usched_nonoptimal, CTLFLAG_RW,
165         &usched_nonoptimal, 0, "acquire_curproc() was not optimal");
166 static int usched_optimal;
167 SYSCTL_INT(_debug, OID_AUTO, usched_optimal, CTLFLAG_RW,
168         &usched_optimal, 0, "acquire_curproc() was optimal");
169 #endif
170 static int usched_debug = -1;
171 SYSCTL_INT(_debug, OID_AUTO, scdebug, CTLFLAG_RW, &usched_debug, 0, "");
172 #ifdef SMP
173 static int remote_resched_nonaffinity;
174 static int remote_resched_affinity;
175 static int choose_affinity;
176 SYSCTL_INT(_debug, OID_AUTO, remote_resched_nonaffinity, CTLFLAG_RD,
177         &remote_resched_nonaffinity, 0, "Number of remote rescheds");
178 SYSCTL_INT(_debug, OID_AUTO, remote_resched_affinity, CTLFLAG_RD,
179         &remote_resched_affinity, 0, "Number of remote rescheds");
180 SYSCTL_INT(_debug, OID_AUTO, choose_affinity, CTLFLAG_RD,
181         &choose_affinity, 0, "chooseproc() was smart");
182 #endif
183
184 static int usched_bsd4_rrinterval = (ESTCPUFREQ + 9) / 10;
185 SYSCTL_INT(_kern, OID_AUTO, usched_bsd4_rrinterval, CTLFLAG_RW,
186         &usched_bsd4_rrinterval, 0, "");
187 static int usched_bsd4_decay = ESTCPUINCR / 2;
188 SYSCTL_INT(_kern, OID_AUTO, usched_bsd4_decay, CTLFLAG_RW,
189         &usched_bsd4_decay, 0, "");
190
191 /*
192  * Initialize the run queues at boot time.
193  */
194 static void
195 rqinit(void *dummy)
196 {
197         int i;
198
199         spin_init(&bsd4_spin);
200         for (i = 0; i < NQS; i++) {
201                 TAILQ_INIT(&bsd4_queues[i]);
202                 TAILQ_INIT(&bsd4_rtqueues[i]);
203                 TAILQ_INIT(&bsd4_idqueues[i]);
204         }
205         atomic_clear_int(&bsd4_curprocmask, 1);
206 }
207 SYSINIT(runqueue, SI_BOOT2_USCHED, SI_ORDER_FIRST, rqinit, NULL)
208
209 /*
210  * BSD4_ACQUIRE_CURPROC
211  *
212  * This function is called when the kernel intends to return to userland.
213  * It is responsible for making the thread the current designated userland
214  * thread for this cpu, blocking if necessary.
215  *
216  * We are expected to handle userland reschedule requests here too.
217  *
218  * WARNING! THIS FUNCTION IS ALLOWED TO CAUSE THE CURRENT THREAD TO MIGRATE
219  * TO ANOTHER CPU!  Because most of the kernel assumes that no migration will
220  * occur, this function is called only under very controlled circumstances.
221  *
222  * Basically we recalculate our estcpu to hopefully give us a more
223  * favorable disposition, setrunqueue, then wait for the curlwp
224  * designation to be handed to us (if the setrunqueue didn't do it).
225  *
226  * MPSAFE
227  */
228 static void
229 bsd4_acquire_curproc(struct lwp *lp)
230 {
231         globaldata_t gd = mycpu;
232         bsd4_pcpu_t dd = &bsd4_pcpu[gd->gd_cpuid];
233
234         /*
235          * Possibly select another thread, or keep the current thread.
236          */
237         if (user_resched_wanted())
238                 bsd4_select_curproc(gd);
239
240         /*
241          * If uschedcp is still pointing to us, we're done
242          */
243         if (dd->uschedcp == lp)
244                 return;
245
246         /*
247          * If this cpu has no current thread, and the run queue is
248          * empty, we can safely select ourself.
249          */
250         if (dd->uschedcp == NULL && bsd4_runqcount == 0) {
251                 atomic_set_int(&bsd4_curprocmask, gd->gd_cpumask);
252                 dd->uschedcp = lp;
253                 dd->upri = lp->lwp_priority;
254                 return;
255         }
256
257         /*
258          * Adjust estcpu and recalculate our priority, then put us back on
259          * the user process scheduler's runq.  Only increment the involuntary
260          * context switch count if the setrunqueue call did not immediately
261          * schedule us.
262          *
263          * Loop until we become the currently scheduled process.  Note that
264          * calling setrunqueue can cause us to be migrated to another cpu
265          * after we switch away.
266          */
267         do {
268                 crit_enter();
269                 bsd4_recalculate_estcpu(lp);
270                 lwkt_deschedule_self(gd->gd_curthread);
271                 bsd4_setrunqueue(lp);
272                 if ((gd->gd_curthread->td_flags & TDF_RUNQ) == 0)
273                         ++lp->lwp_ru.ru_nivcsw;
274                 lwkt_switch();
275                 crit_exit();
276                 gd = mycpu;
277                 dd = &bsd4_pcpu[gd->gd_cpuid];
278         } while (dd->uschedcp != lp);
279         KKASSERT((lp->lwp_flag & LWP_ONRUNQ) == 0);
280 }
281
282 /*
283  * BSD4_RELEASE_CURPROC
284  *
285  * This routine detaches the current thread from the userland scheduler,
286  * usually because the thread needs to run in the kernel (at kernel priority)
287  * for a while.
288  *
289  * This routine is also responsible for selecting a new thread to
290  * make the current thread.
291  *
292  * NOTE: This implementation differs from the dummy example in that
293  * bsd4_select_curproc() is able to select the current process, whereas
294  * dummy_select_curproc() is not able to select the current process.
295  * This means we have to NULL out uschedcp.
296  *
297  * Additionally, note that we may already be on a run queue if releasing
298  * via the lwkt_switch() in bsd4_setrunqueue().
299  *
300  * WARNING!  The MP lock may be in an unsynchronized state due to the
301  * way get_mplock() works and the fact that this function may be called
302  * from a passive release during a lwkt_switch().   try_mplock() will deal 
303  * with this for us but you should be aware that td_mpcount may not be
304  * useable.
305  *
306  * MPSAFE
307  */
308 static void
309 bsd4_release_curproc(struct lwp *lp)
310 {
311         globaldata_t gd = mycpu;
312         bsd4_pcpu_t dd = &bsd4_pcpu[gd->gd_cpuid];
313
314         if (dd->uschedcp == lp) {
315                 /*
316                  * Note: we leave ou curprocmask bit set to prevent
317                  * unnecessary scheduler helper wakeups.  
318                  * bsd4_select_curproc() will clean it up.
319                  */
320                 KKASSERT((lp->lwp_flag & LWP_ONRUNQ) == 0);
321                 dd->uschedcp = NULL;    /* don't let lp be selected */
322                 bsd4_select_curproc(gd);
323         }
324 }
325
326 /*
327  * BSD4_SELECT_CURPROC
328  *
329  * Select a new current process for this cpu.  This satisfies a user
330  * scheduler reschedule request so clear that too.
331  *
332  * This routine is also responsible for equal-priority round-robining,
333  * typically triggered from bsd4_schedulerclock().  In our dummy example
334  * all the 'user' threads are LWKT scheduled all at once and we just
335  * call lwkt_switch().
336  *
337  * MPSAFE
338  */
339 static
340 void
341 bsd4_select_curproc(globaldata_t gd)
342 {
343         bsd4_pcpu_t dd = &bsd4_pcpu[gd->gd_cpuid];
344         struct lwp *nlp;
345         int cpuid = gd->gd_cpuid;
346
347         crit_enter_gd(gd);
348         clear_user_resched();   /* This satisfied the reschedule request */
349         dd->rrcount = 0;        /* Reset the round-robin counter */
350
351         spin_lock_wr(&bsd4_spin);
352         if ((nlp = chooseproc_locked(dd->uschedcp)) != NULL) {
353                 atomic_set_int(&bsd4_curprocmask, 1 << cpuid);
354                 dd->upri = nlp->lwp_priority;
355                 dd->uschedcp = nlp;
356                 spin_unlock_wr(&bsd4_spin);
357 #ifdef SMP
358                 lwkt_acquire(nlp->lwp_thread);
359 #endif
360                 lwkt_schedule(nlp->lwp_thread);
361         } else if (dd->uschedcp) {
362                 dd->upri = dd->uschedcp->lwp_priority;
363                 spin_unlock_wr(&bsd4_spin);
364                 KKASSERT(bsd4_curprocmask & (1 << cpuid));
365         } else if (bsd4_runqcount && (bsd4_rdyprocmask & (1 << cpuid))) {
366                 atomic_clear_int(&bsd4_curprocmask, 1 << cpuid);
367                 atomic_clear_int(&bsd4_rdyprocmask, 1 << cpuid);
368                 dd->uschedcp = NULL;
369                 dd->upri = PRIBASE_NULL;
370                 spin_unlock_wr(&bsd4_spin);
371                 lwkt_schedule(&dd->helper_thread);
372         } else {
373                 dd->uschedcp = NULL;
374                 dd->upri = PRIBASE_NULL;
375                 atomic_clear_int(&bsd4_curprocmask, 1 << cpuid);
376                 spin_unlock_wr(&bsd4_spin);
377         }
378         crit_exit_gd(gd);
379 }
380
381 /*
382  * BSD4_SETRUNQUEUE
383  *
384  * This routine is called to schedule a new user process after a fork.
385  *
386  * The caller may set P_PASSIVE_ACQ in p_flag to indicate that we should
387  * attempt to leave the thread on the current cpu.
388  *
389  * If P_PASSIVE_ACQ is set setrunqueue() will not wakeup potential target
390  * cpus in an attempt to keep the process on the current cpu at least for
391  * a little while to take advantage of locality of reference (e.g. fork/exec
392  * or short fork/exit, and uio_yield()).
393  *
394  * CPU AFFINITY: cpu affinity is handled by attempting to either schedule
395  * or (user level) preempt on the same cpu that a process was previously
396  * scheduled to.  If we cannot do this but we are at enough of a higher
397  * priority then the processes running on other cpus, we will allow the
398  * process to be stolen by another cpu.
399  *
400  * WARNING!  This routine cannot block.  bsd4_acquire_curproc() does 
401  * a deschedule/switch interlock and we can be moved to another cpu
402  * the moment we are switched out.  Our LWKT run state is the only
403  * thing preventing the transfer.
404  *
405  * The associated thread must NOT currently be scheduled (but can be the
406  * current process after it has been LWKT descheduled).  It must NOT be on
407  * a bsd4 scheduler queue either.  The purpose of this routine is to put
408  * it on a scheduler queue or make it the current user process and LWKT
409  * schedule it.  It is possible that the thread is in the middle of a LWKT
410  * switchout on another cpu, lwkt_acquire() deals with that case.
411  *
412  * The process must be runnable.
413  *
414  * MPSAFE
415  */
416 static void
417 bsd4_setrunqueue(struct lwp *lp)
418 {
419         globaldata_t gd;
420         bsd4_pcpu_t dd;
421         int cpuid;
422 #ifdef SMP
423         cpumask_t mask;
424         cpumask_t tmpmask;
425 #endif
426
427         /*
428          * First validate the process state relative to the current cpu.
429          * We don't need the spinlock for this, just a critical section.
430          * We are in control of the process.
431          */
432         crit_enter();
433         KASSERT(lp->lwp_stat == LSRUN, ("setrunqueue: lwp not LSRUN"));
434         KASSERT((lp->lwp_flag & LWP_ONRUNQ) == 0,
435             ("lwp %d/%d already on runq! flag %08x/%08x", lp->lwp_proc->p_pid,
436              lp->lwp_tid, lp->lwp_proc->p_flag, lp->lwp_flag));
437         KKASSERT((lp->lwp_thread->td_flags & TDF_RUNQ) == 0);
438
439         /*
440          * Note: gd and dd are relative to the target thread's last cpu,
441          * NOT our current cpu.
442          */
443         gd = lp->lwp_thread->td_gd;
444         dd = &bsd4_pcpu[gd->gd_cpuid];
445
446         /*
447          * This process is not supposed to be scheduled anywhere or assigned
448          * as the current process anywhere.  Assert the condition.
449          */
450         KKASSERT(dd->uschedcp != lp);
451
452         /*
453          * Check local cpu affinity.  The associated thread is stable at 
454          * the moment.  Note that we may be checking another cpu here so we
455          * have to be careful.  We can only assign uschedcp on OUR cpu.
456          *
457          * This allows us to avoid actually queueing the process.  
458          * acquire_curproc() will handle any threads we mistakenly schedule.
459          */
460         cpuid = gd->gd_cpuid;
461         if (gd == mycpu && (bsd4_curprocmask & (1 << cpuid)) == 0) {
462                 atomic_set_int(&bsd4_curprocmask, 1 << cpuid);
463                 dd->uschedcp = lp;
464                 dd->upri = lp->lwp_priority;
465                 lwkt_schedule(lp->lwp_thread);
466                 crit_exit();
467                 return;
468         }
469
470         /*
471          * gd and cpuid may still 'hint' at another cpu.  Even so we have
472          * to place this process on the userland scheduler's run queue for
473          * action by the target cpu.
474          */
475 #ifdef SMP
476         /*
477          * XXX fixme.  Could be part of a remrunqueue/setrunqueue
478          * operation when the priority is recalculated, so TDF_MIGRATING
479          * may already be set.
480          */
481         if ((lp->lwp_thread->td_flags & TDF_MIGRATING) == 0)
482                 lwkt_giveaway(lp->lwp_thread);
483 #endif
484
485         /*
486          * We lose control of lp the moment we release the spinlock after
487          * having placed lp on the queue.  i.e. another cpu could pick it
488          * up and it could exit, or its priority could be further adjusted,
489          * or something like that.
490          */
491         spin_lock_wr(&bsd4_spin);
492         bsd4_setrunqueue_locked(lp);
493
494         /*
495          * gd, dd, and cpuid are still our target cpu 'hint', not our current
496          * cpu info.
497          *
498          * We always try to schedule a LWP to its original cpu first.  It
499          * is possible for the scheduler helper or setrunqueue to assign
500          * the LWP to a different cpu before the one we asked for wakes
501          * up.
502          *
503          * If the LWP has higher priority (lower lwp_priority value) on
504          * its target cpu, reschedule on that cpu.
505          */
506         if ((lp->lwp_thread->td_flags & TDF_NORESCHED) == 0) {
507                 if ((dd->upri & ~PRIMASK) > (lp->lwp_priority & ~PRIMASK)) {
508                         dd->upri = lp->lwp_priority;
509                         spin_unlock_wr(&bsd4_spin);
510 #ifdef SMP
511                         if (gd == mycpu) {
512                                 need_user_resched();
513                         } else {
514                                 lwkt_send_ipiq(gd, need_user_resched_remote,
515                                                NULL);
516                         }
517 #else
518                         need_user_resched();
519 #endif
520                         crit_exit();
521                         return;
522                 }
523         }
524         spin_unlock_wr(&bsd4_spin);
525
526 #ifdef SMP
527         /*
528          * Otherwise the LWP has a lower priority or we were asked not
529          * to reschedule.  Look for an idle cpu whos scheduler helper
530          * is ready to accept more work.
531          *
532          * Look for an idle cpu starting at our rotator (bsd4_scancpu).
533          *
534          * If no cpus are ready to accept work, just return.
535          *
536          * XXX P_PASSIVE_ACQ
537          */
538         mask = ~bsd4_curprocmask & bsd4_rdyprocmask & mycpu->gd_other_cpus &
539             lp->lwp_cpumask;
540         if (mask) {
541                 cpuid = bsd4_scancpu;
542                 if (++cpuid == ncpus)
543                         cpuid = 0;
544                 tmpmask = ~((1 << cpuid) - 1);
545                 if (mask & tmpmask)
546                         cpuid = bsfl(mask & tmpmask);
547                 else
548                         cpuid = bsfl(mask);
549                 atomic_clear_int(&bsd4_rdyprocmask, 1 << cpuid);
550                 bsd4_scancpu = cpuid;
551                 lwkt_schedule(&bsd4_pcpu[cpuid].helper_thread);
552         }
553 #endif
554         crit_exit();
555 }
556
557 /*
558  * This routine is called from a systimer IPI.  It MUST be MP-safe and
559  * the BGL IS NOT HELD ON ENTRY.  This routine is called at ESTCPUFREQ on
560  * each cpu.
561  *
562  * Because this is effectively a 'fast' interrupt, we cannot safely
563  * use spinlocks unless gd_spinlock_rd is NULL and gd_spinlocks_wr is 0,
564  * even if the spinlocks are 'non conflicting'.  This is due to the way
565  * spinlock conflicts against cached read locks are handled.
566  *
567  * MPSAFE
568  */
569 static
570 void
571 bsd4_schedulerclock(struct lwp *lp, sysclock_t period, sysclock_t cpstamp)
572 {
573         globaldata_t gd = mycpu;
574         bsd4_pcpu_t dd = &bsd4_pcpu[gd->gd_cpuid];
575
576         /*
577          * Do we need to round-robin?  We round-robin 10 times a second.
578          * This should only occur for cpu-bound batch processes.
579          */
580         if (++dd->rrcount >= usched_bsd4_rrinterval) {
581                 dd->rrcount = 0;
582                 need_user_resched();
583         }
584
585         /*
586          * As the process accumulates cpu time p_estcpu is bumped and may
587          * push the process into another scheduling queue.  It typically
588          * takes 4 ticks to bump the queue.
589          */
590         lp->lwp_estcpu = ESTCPULIM(lp->lwp_estcpu + ESTCPUINCR);
591
592         /*
593          * Reducing p_origcpu over time causes more of our estcpu to be
594          * returned to the parent when we exit.  This is a small tweak
595          * for the batch detection heuristic.
596          */
597         if (lp->lwp_origcpu)
598                 --lp->lwp_origcpu;
599
600         /*
601          * We can only safely call bsd4_resetpriority(), which uses spinlocks,
602          * if we aren't interrupting a thread that is using spinlocks.
603          * Otherwise we can deadlock with another cpu waiting for our read
604          * spinlocks to clear.
605          */
606         if (gd->gd_spinlock_rd == NULL && gd->gd_spinlocks_wr == 0)
607                 bsd4_resetpriority(lp);
608         else
609                 need_user_resched();
610 }
611
612 /*
613  * Called from acquire and from kern_synch's one-second timer (one of the
614  * callout helper threads) with a critical section held. 
615  *
616  * Decay p_estcpu based on the number of ticks we haven't been running
617  * and our p_nice.  As the load increases each process observes a larger
618  * number of idle ticks (because other processes are running in them).
619  * This observation leads to a larger correction which tends to make the
620  * system more 'batchy'.
621  *
622  * Note that no recalculation occurs for a process which sleeps and wakes
623  * up in the same tick.  That is, a system doing thousands of context
624  * switches per second will still only do serious estcpu calculations
625  * ESTCPUFREQ times per second.
626  *
627  * MPSAFE
628  */
629 static
630 void 
631 bsd4_recalculate_estcpu(struct lwp *lp)
632 {
633         globaldata_t gd = mycpu;
634         sysclock_t cpbase;
635         int loadfac;
636         int ndecay;
637         int nticks;
638         int nleft;
639
640         /*
641          * We have to subtract periodic to get the last schedclock
642          * timeout time, otherwise we would get the upcoming timeout.
643          * Keep in mind that a process can migrate between cpus and
644          * while the scheduler clock should be very close, boundary
645          * conditions could lead to a small negative delta.
646          */
647         cpbase = gd->gd_schedclock.time - gd->gd_schedclock.periodic;
648
649         if (lp->lwp_slptime > 1) {
650                 /*
651                  * Too much time has passed, do a coarse correction.
652                  */
653                 lp->lwp_estcpu = lp->lwp_estcpu >> 1;
654                 bsd4_resetpriority(lp);
655                 lp->lwp_cpbase = cpbase;
656                 lp->lwp_cpticks = 0;
657         } else if (lp->lwp_cpbase != cpbase) {
658                 /*
659                  * Adjust estcpu if we are in a different tick.  Don't waste
660                  * time if we are in the same tick. 
661                  * 
662                  * First calculate the number of ticks in the measurement
663                  * interval.  The nticks calculation can wind up 0 due to
664                  * a bug in the handling of lwp_slptime  (as yet not found),
665                  * so make sure we do not get a divide by 0 panic.
666                  */
667                 nticks = (cpbase - lp->lwp_cpbase) / gd->gd_schedclock.periodic;
668                 if (nticks <= 0)
669                         nticks = 1;
670                 updatepcpu(lp, lp->lwp_cpticks, nticks);
671
672                 if ((nleft = nticks - lp->lwp_cpticks) < 0)
673                         nleft = 0;
674                 if (usched_debug == lp->lwp_proc->p_pid) {
675                         kprintf("pid %d tid %d estcpu %d cpticks %d nticks %d nleft %d",
676                                 lp->lwp_proc->p_pid, lp->lwp_tid, lp->lwp_estcpu,
677                                 lp->lwp_cpticks, nticks, nleft);
678                 }
679
680                 /*
681                  * Calculate a decay value based on ticks remaining scaled
682                  * down by the instantanious load and p_nice.
683                  */
684                 if ((loadfac = bsd4_runqcount) < 2)
685                         loadfac = 2;
686                 ndecay = nleft * usched_bsd4_decay * 2 * 
687                         (PRIO_MAX * 2 - lp->lwp_proc->p_nice) / (loadfac * PRIO_MAX * 2);
688
689                 /*
690                  * Adjust p_estcpu.  Handle a border case where batch jobs
691                  * can get stalled long enough to decay to zero when they
692                  * shouldn't.
693                  */
694                 if (lp->lwp_estcpu > ndecay * 2)
695                         lp->lwp_estcpu -= ndecay;
696                 else
697                         lp->lwp_estcpu >>= 1;
698
699                 if (usched_debug == lp->lwp_proc->p_pid)
700                         kprintf(" ndecay %d estcpu %d\n", ndecay, lp->lwp_estcpu);
701                 bsd4_resetpriority(lp);
702                 lp->lwp_cpbase = cpbase;
703                 lp->lwp_cpticks = 0;
704         }
705 }
706
707 /*
708  * Compute the priority of a process when running in user mode.
709  * Arrange to reschedule if the resulting priority is better
710  * than that of the current process.
711  *
712  * This routine may be called with any process.
713  *
714  * This routine is called by fork1() for initial setup with the process
715  * of the run queue, and also may be called normally with the process on or
716  * off the run queue.
717  *
718  * MPSAFE
719  */
720 static void
721 bsd4_resetpriority(struct lwp *lp)
722 {
723         bsd4_pcpu_t dd;
724         int newpriority;
725         u_short newrqtype;
726         int reschedcpu;
727
728         /*
729          * Calculate the new priority and queue type
730          */
731         crit_enter();
732         spin_lock_wr(&bsd4_spin);
733
734         newrqtype = lp->lwp_rtprio.type;
735
736         switch(newrqtype) {
737         case RTP_PRIO_REALTIME:
738         case RTP_PRIO_FIFO:
739                 newpriority = PRIBASE_REALTIME +
740                              (lp->lwp_rtprio.prio & PRIMASK);
741                 break;
742         case RTP_PRIO_NORMAL:
743                 newpriority = (lp->lwp_proc->p_nice - PRIO_MIN) * PPQ / NICEPPQ;
744                 newpriority += lp->lwp_estcpu * PPQ / ESTCPUPPQ;
745                 newpriority = newpriority * MAXPRI / (PRIO_RANGE * PPQ /
746                               NICEPPQ + ESTCPUMAX * PPQ / ESTCPUPPQ);
747                 newpriority = PRIBASE_NORMAL + (newpriority & PRIMASK);
748                 break;
749         case RTP_PRIO_IDLE:
750                 newpriority = PRIBASE_IDLE + (lp->lwp_rtprio.prio & PRIMASK);
751                 break;
752         case RTP_PRIO_THREAD:
753                 newpriority = PRIBASE_THREAD + (lp->lwp_rtprio.prio & PRIMASK);
754                 break;
755         default:
756                 panic("Bad RTP_PRIO %d", newrqtype);
757                 /* NOT REACHED */
758         }
759
760         /*
761          * The newpriority incorporates the queue type so do a simple masked
762          * check to determine if the process has moved to another queue.  If
763          * it has, and it is currently on a run queue, then move it.
764          */
765         if ((lp->lwp_priority ^ newpriority) & ~PPQMASK) {
766                 lp->lwp_priority = newpriority;
767                 if (lp->lwp_flag & LWP_ONRUNQ) {
768                         bsd4_remrunqueue_locked(lp);
769                         lp->lwp_rqtype = newrqtype;
770                         lp->lwp_rqindex = (newpriority & PRIMASK) / PPQ;
771                         bsd4_setrunqueue_locked(lp);
772                         reschedcpu = lp->lwp_thread->td_gd->gd_cpuid;
773                 } else {
774                         lp->lwp_rqtype = newrqtype;
775                         lp->lwp_rqindex = (newpriority & PRIMASK) / PPQ;
776                         reschedcpu = -1;
777                 }
778         } else {
779                 lp->lwp_priority = newpriority;
780                 reschedcpu = -1;
781         }
782         spin_unlock_wr(&bsd4_spin);
783
784         /*
785          * Determine if we need to reschedule the target cpu.  This only
786          * occurs if the LWP is already on a scheduler queue, which means
787          * that idle cpu notification has already occured.  At most we
788          * need only issue a need_user_resched() on the appropriate cpu.
789          *
790          * The LWP may be owned by a CPU different from the current one,
791          * in which case dd->uschedcp may be modified without an MP lock
792          * or a spinlock held.  The worst that happens is that the code
793          * below causes a spurious need_user_resched() on the target CPU
794          * and dd->pri to be wrong for a short period of time, both of
795          * which are harmless.
796          */
797         if (reschedcpu >= 0) {
798                 dd = &bsd4_pcpu[reschedcpu];
799                 if ((dd->upri & ~PRIMASK) > (lp->lwp_priority & ~PRIMASK)) {
800                         dd->upri = lp->lwp_priority;
801 #ifdef SMP
802                         if (reschedcpu == mycpu->gd_cpuid) {
803                                 need_user_resched();
804                         } else {
805                                 lwkt_send_ipiq(lp->lwp_thread->td_gd,
806                                                need_user_resched_remote, NULL);
807                         }
808 #else
809                         need_user_resched();
810 #endif
811                 }
812         }
813         crit_exit();
814 }
815
816 static
817 void
818 bsd4_yield(struct lwp *lp) 
819 {
820 #if 0
821         /* FUTURE (or something similar) */
822         switch(lp->lwp_rqtype) {
823         case RTP_PRIO_NORMAL:
824                 lp->lwp_estcpu = ESTCPULIM(lp->lwp_estcpu + ESTCPUINCR);
825                 kprintf("Y");
826                 break;
827         default:
828                 break;
829         }
830 #endif
831         need_user_resched();
832 }
833
834 /*
835  * Called from fork1() when a new child process is being created.
836  *
837  * Give the child process an initial estcpu that is more batch then
838  * its parent and dock the parent for the fork (but do not
839  * reschedule the parent).   This comprises the main part of our batch
840  * detection heuristic for both parallel forking and sequential execs.
841  *
842  * Interactive processes will decay the boosted estcpu quickly while batch
843  * processes will tend to compound it.
844  * XXX lwp should be "spawning" instead of "forking"
845  *
846  * MPSAFE
847  */
848 static void
849 bsd4_forking(struct lwp *plp, struct lwp *lp)
850 {
851         lp->lwp_estcpu = ESTCPULIM(plp->lwp_estcpu + ESTCPUPPQ);
852         lp->lwp_origcpu = lp->lwp_estcpu;
853         plp->lwp_estcpu = ESTCPULIM(plp->lwp_estcpu + ESTCPUPPQ);
854 }
855
856 /*
857  * Called when the parent reaps a child.   Propogate cpu use by the child
858  * back to the parent.
859  *
860  * MPSAFE
861  */
862 static void
863 bsd4_exiting(struct lwp *plp, struct lwp *lp)
864 {
865         int delta;
866
867         if (plp->lwp_proc->p_pid != 1) {
868                 delta = lp->lwp_estcpu - lp->lwp_origcpu;
869                 if (delta > 0)
870                         plp->lwp_estcpu = ESTCPULIM(plp->lwp_estcpu + delta);
871         }
872 }
873
874
875 /*
876  * chooseproc() is called when a cpu needs a user process to LWKT schedule,
877  * it selects a user process and returns it.  If chklp is non-NULL and chklp
878  * has a better or equal priority then the process that would otherwise be
879  * chosen, NULL is returned.
880  *
881  * Until we fix the RUNQ code the chklp test has to be strict or we may
882  * bounce between processes trying to acquire the current process designation.
883  *
884  * MPSAFE - must be called with bsd4_spin exclusive held.  The spinlock is
885  *          left intact through the entire routine.
886  */
887 static
888 struct lwp *
889 chooseproc_locked(struct lwp *chklp)
890 {
891         struct lwp *lp;
892         struct rq *q;
893         u_int32_t *which, *which2;
894         u_int32_t pri;
895         u_int32_t rtqbits;
896         u_int32_t tsqbits;
897         u_int32_t idqbits;
898         cpumask_t cpumask;
899
900         rtqbits = bsd4_rtqueuebits;
901         tsqbits = bsd4_queuebits;
902         idqbits = bsd4_idqueuebits;
903         cpumask = mycpu->gd_cpumask;
904
905 #ifdef SMP
906 again:
907 #endif
908         if (rtqbits) {
909                 pri = bsfl(rtqbits);
910                 q = &bsd4_rtqueues[pri];
911                 which = &bsd4_rtqueuebits;
912                 which2 = &rtqbits;
913         } else if (tsqbits) {
914                 pri = bsfl(tsqbits);
915                 q = &bsd4_queues[pri];
916                 which = &bsd4_queuebits;
917                 which2 = &tsqbits;
918         } else if (idqbits) {
919                 pri = bsfl(idqbits);
920                 q = &bsd4_idqueues[pri];
921                 which = &bsd4_idqueuebits;
922                 which2 = &idqbits;
923         } else {
924                 return NULL;
925         }
926         lp = TAILQ_FIRST(q);
927         KASSERT(lp, ("chooseproc: no lwp on busy queue"));
928
929 #ifdef SMP
930         while ((lp->lwp_cpumask & cpumask) == 0) {
931                 lp = TAILQ_NEXT(lp, lwp_procq);
932                 if (lp == NULL) {
933                         *which2 &= ~(1 << pri);
934                         goto again;
935                 }
936         }
937 #endif
938
939         /*
940          * If the passed lwp <chklp> is reasonably close to the selected
941          * lwp <lp>, return NULL (indicating that <chklp> should be kept).
942          * 
943          * Note that we must error on the side of <chklp> to avoid bouncing
944          * between threads in the acquire code.
945          */
946         if (chklp) {
947                 if (chklp->lwp_priority < lp->lwp_priority + PPQ)
948                         return(NULL);
949         }
950
951 #ifdef SMP
952         /*
953          * If the chosen lwp does not reside on this cpu spend a few
954          * cycles looking for a better candidate at the same priority level.
955          * This is a fallback check, setrunqueue() tries to wakeup the
956          * correct cpu and is our front-line affinity.
957          */
958         if (lp->lwp_thread->td_gd != mycpu &&
959             (chklp = TAILQ_NEXT(lp, lwp_procq)) != NULL
960         ) {
961                 if (chklp->lwp_thread->td_gd == mycpu) {
962                         ++choose_affinity;
963                         lp = chklp;
964                 }
965         }
966 #endif
967
968         TAILQ_REMOVE(q, lp, lwp_procq);
969         --bsd4_runqcount;
970         if (TAILQ_EMPTY(q))
971                 *which &= ~(1 << pri);
972         KASSERT((lp->lwp_flag & LWP_ONRUNQ) != 0, ("not on runq6!"));
973         lp->lwp_flag &= ~LWP_ONRUNQ;
974         return lp;
975 }
976
977 #ifdef SMP
978 /*
979  * Called via an ipi message to reschedule on another cpu.
980  *
981  * MPSAFE
982  */
983 static
984 void
985 need_user_resched_remote(void *dummy)
986 {
987         need_user_resched();
988 }
989
990 #endif
991
992
993 /*
994  * bsd4_remrunqueue_locked() removes a given process from the run queue
995  * that it is on, clearing the queue busy bit if it becomes empty.
996  *
997  * Note that user process scheduler is different from the LWKT schedule.
998  * The user process scheduler only manages user processes but it uses LWKT
999  * underneath, and a user process operating in the kernel will often be
1000  * 'released' from our management.
1001  *
1002  * MPSAFE - bsd4_spin must be held exclusively on call
1003  */
1004 static void
1005 bsd4_remrunqueue_locked(struct lwp *lp)
1006 {
1007         struct rq *q;
1008         u_int32_t *which;
1009         u_int8_t pri;
1010
1011         KKASSERT(lp->lwp_flag & LWP_ONRUNQ);
1012         lp->lwp_flag &= ~LWP_ONRUNQ;
1013         --bsd4_runqcount;
1014         KKASSERT(bsd4_runqcount >= 0);
1015
1016         pri = lp->lwp_rqindex;
1017         switch(lp->lwp_rqtype) {
1018         case RTP_PRIO_NORMAL:
1019                 q = &bsd4_queues[pri];
1020                 which = &bsd4_queuebits;
1021                 break;
1022         case RTP_PRIO_REALTIME:
1023         case RTP_PRIO_FIFO:
1024                 q = &bsd4_rtqueues[pri];
1025                 which = &bsd4_rtqueuebits;
1026                 break;
1027         case RTP_PRIO_IDLE:
1028                 q = &bsd4_idqueues[pri];
1029                 which = &bsd4_idqueuebits;
1030                 break;
1031         default:
1032                 panic("remrunqueue: invalid rtprio type");
1033                 /* NOT REACHED */
1034         }
1035         TAILQ_REMOVE(q, lp, lwp_procq);
1036         if (TAILQ_EMPTY(q)) {
1037                 KASSERT((*which & (1 << pri)) != 0,
1038                         ("remrunqueue: remove from empty queue"));
1039                 *which &= ~(1 << pri);
1040         }
1041 }
1042
1043 /*
1044  * bsd4_setrunqueue_locked()
1045  *
1046  * Add a process whos rqtype and rqindex had previously been calculated
1047  * onto the appropriate run queue.   Determine if the addition requires
1048  * a reschedule on a cpu and return the cpuid or -1.
1049  *
1050  * NOTE: Lower priorities are better priorities.
1051  *
1052  * MPSAFE - bsd4_spin must be held exclusively on call
1053  */
1054 static void
1055 bsd4_setrunqueue_locked(struct lwp *lp)
1056 {
1057         struct rq *q;
1058         u_int32_t *which;
1059         int pri;
1060
1061         KKASSERT((lp->lwp_flag & LWP_ONRUNQ) == 0);
1062         lp->lwp_flag |= LWP_ONRUNQ;
1063         ++bsd4_runqcount;
1064
1065         pri = lp->lwp_rqindex;
1066
1067         switch(lp->lwp_rqtype) {
1068         case RTP_PRIO_NORMAL:
1069                 q = &bsd4_queues[pri];
1070                 which = &bsd4_queuebits;
1071                 break;
1072         case RTP_PRIO_REALTIME:
1073         case RTP_PRIO_FIFO:
1074                 q = &bsd4_rtqueues[pri];
1075                 which = &bsd4_rtqueuebits;
1076                 break;
1077         case RTP_PRIO_IDLE:
1078                 q = &bsd4_idqueues[pri];
1079                 which = &bsd4_idqueuebits;
1080                 break;
1081         default:
1082                 panic("remrunqueue: invalid rtprio type");
1083                 /* NOT REACHED */
1084         }
1085
1086         /*
1087          * Add to the correct queue and set the appropriate bit.  If no
1088          * lower priority (i.e. better) processes are in the queue then
1089          * we want a reschedule, calculate the best cpu for the job.
1090          *
1091          * Always run reschedules on the LWPs original cpu.
1092          */
1093         TAILQ_INSERT_TAIL(q, lp, lwp_procq);
1094         *which |= 1 << pri;
1095 }
1096
1097 #ifdef SMP
1098
1099 /*
1100  * For SMP systems a user scheduler helper thread is created for each
1101  * cpu and is used to allow one cpu to wakeup another for the purposes of
1102  * scheduling userland threads from setrunqueue().  UP systems do not
1103  * need the helper since there is only one cpu.  We can't use the idle
1104  * thread for this because we need to hold the MP lock.  Additionally,
1105  * doing things this way allows us to HLT idle cpus on MP systems.
1106  *
1107  * MPSAFE
1108  */
1109 static void
1110 sched_thread(void *dummy)
1111 {
1112     globaldata_t gd;
1113     bsd4_pcpu_t  dd;
1114     struct lwp *nlp;
1115     cpumask_t cpumask;
1116     cpumask_t tmpmask;
1117     int cpuid;
1118     int tmpid;
1119
1120     gd = mycpu;
1121     cpuid = gd->gd_cpuid;       /* doesn't change */
1122     cpumask = 1 << cpuid;       /* doesn't change */
1123     dd = &bsd4_pcpu[cpuid];
1124
1125     /*
1126      * The scheduler thread does not need to hold the MP lock.  Since we
1127      * are woken up only when no user processes are scheduled on a cpu, we
1128      * can run at an ultra low priority.
1129      */
1130     rel_mplock();
1131     lwkt_setpri_self(TDPRI_USER_SCHEDULER);
1132
1133     for (;;) {
1134         /*
1135          * We use the LWKT deschedule-interlock trick to avoid racing
1136          * bsd4_rdyprocmask.  This means we cannot block through to the
1137          * manual lwkt_switch() call we make below.
1138          */
1139         crit_enter_gd(gd);
1140         lwkt_deschedule_self(gd->gd_curthread);
1141         spin_lock_wr(&bsd4_spin);
1142         atomic_set_int(&bsd4_rdyprocmask, cpumask);
1143         if ((bsd4_curprocmask & cpumask) == 0) {
1144                 if ((nlp = chooseproc_locked(NULL)) != NULL) {
1145                         atomic_set_int(&bsd4_curprocmask, cpumask);
1146                         dd->upri = nlp->lwp_priority;
1147                         dd->uschedcp = nlp;
1148                         spin_unlock_wr(&bsd4_spin);
1149                         lwkt_acquire(nlp->lwp_thread);
1150                         lwkt_schedule(nlp->lwp_thread);
1151                 } else {
1152                         spin_unlock_wr(&bsd4_spin);
1153                 }
1154         } else {
1155                 /*
1156                  * Someone scheduled us but raced.  In order to not lose
1157                  * track of the fact that there may be a LWP ready to go,
1158                  * forward the request to another cpu if available.
1159                  *
1160                  * Rotate through cpus starting with cpuid + 1.  Since cpuid
1161                  * is already masked out by gd_other_cpus, just use ~cpumask.
1162                  */
1163                 tmpmask = ~bsd4_curprocmask & bsd4_rdyprocmask &
1164                           mycpu->gd_other_cpus;
1165                 if (tmpmask) {
1166                         if (tmpmask & ~(cpumask - 1))
1167                                 tmpid = bsfl(tmpmask & ~(cpumask - 1));
1168                         else
1169                                 tmpid = bsfl(tmpmask);
1170                         bsd4_scancpu = tmpid;
1171                         atomic_clear_int(&bsd4_rdyprocmask, 1 << tmpid);
1172                         spin_unlock_wr(&bsd4_spin);
1173                         lwkt_schedule(&bsd4_pcpu[tmpid].helper_thread);
1174                 } else {
1175                         spin_unlock_wr(&bsd4_spin);
1176                 }
1177         }
1178         crit_exit_gd(gd);
1179         lwkt_switch();
1180     }
1181 }
1182
1183 /*
1184  * Setup our scheduler helpers.  Note that curprocmask bit 0 has already
1185  * been cleared by rqinit() and we should not mess with it further.
1186  */
1187 static void
1188 sched_thread_cpu_init(void)
1189 {
1190     int i;
1191
1192     if (bootverbose)
1193         kprintf("start scheduler helpers on cpus:");
1194
1195     for (i = 0; i < ncpus; ++i) {
1196         bsd4_pcpu_t dd = &bsd4_pcpu[i];
1197         cpumask_t mask = 1 << i;
1198
1199         if ((mask & smp_active_mask) == 0)
1200             continue;
1201
1202         if (bootverbose)
1203             kprintf(" %d", i);
1204
1205         lwkt_create(sched_thread, NULL, NULL, &dd->helper_thread, 
1206                     TDF_STOPREQ, i, "usched %d", i);
1207
1208         /*
1209          * Allow user scheduling on the target cpu.  cpu #0 has already
1210          * been enabled in rqinit().
1211          */
1212         if (i)
1213             atomic_clear_int(&bsd4_curprocmask, mask);
1214         atomic_set_int(&bsd4_rdyprocmask, mask);
1215     }
1216     if (bootverbose)
1217         kprintf("\n");
1218 }
1219 SYSINIT(uschedtd, SI_BOOT2_USCHED, SI_ORDER_SECOND,
1220         sched_thread_cpu_init, NULL)
1221
1222 #endif
1223