sched_m2.c revision 1.10.2.2 1 /* $NetBSD: sched_m2.c,v 1.10.2.2 2007/11/06 23:32:09 matt Exp $ */
2
3 /*
4 * Copyright (c) 2007, Mindaugas Rasiukevicius
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
17 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
19 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25 * POSSIBILITY OF SUCH DAMAGE.
26 */
27
28 /*
29 * TODO:
30 * - Implementation of fair share queue;
31 * - Support for NUMA;
32 */
33
34 #include <sys/cdefs.h>
35 __KERNEL_RCSID(0, "$NetBSD: sched_m2.c,v 1.10.2.2 2007/11/06 23:32:09 matt Exp $");
36
37 #include <sys/param.h>
38
39 #include <sys/bitops.h>
40 #include <sys/cpu.h>
41 #include <sys/callout.h>
42 #include <sys/errno.h>
43 #include <sys/kernel.h>
44 #include <sys/kmem.h>
45 #include <sys/lwp.h>
46 #include <sys/mutex.h>
47 #include <sys/pool.h>
48 #include <sys/proc.h>
49 #include <sys/resource.h>
50 #include <sys/resourcevar.h>
51 #include <sys/sched.h>
52 #include <sys/syscallargs.h>
53 #include <sys/sysctl.h>
54 #include <sys/types.h>
55
56 /*
57 * Priority related defintions.
58 */
59 #define PRI_TS_COUNT (NPRI_USER)
60 #define PRI_RT_COUNT (PRI_COUNT - PRI_TS_COUNT)
61 #define PRI_HTS_RANGE (PRI_TS_COUNT / 10)
62
63 #define PRI_HIGHEST_TS (PRI_KERNEL - 1)
64 #define PRI_DEFAULT (NPRI_USER >> 1)
65
66 const int schedppq = 1;
67
68 /*
69 * Bits per map.
70 */
71 #define BITMAP_BITS (32)
72 #define BITMAP_SHIFT (5)
73 #define BITMAP_MSB (0x80000000)
74 #define BITMAP_MASK (BITMAP_BITS - 1)
75
76 /*
77 * Time-slices and priorities.
78 */
79 static u_int min_ts; /* Minimal time-slice */
80 static u_int max_ts; /* Maximal time-slice */
81 static u_int rt_ts; /* Real-time time-slice */
82 static u_int ts_map[PRI_COUNT]; /* Map of time-slices */
83 static pri_t high_pri[PRI_COUNT]; /* Map for priority increase */
84
85 /*
86 * Migration and balancing.
87 */
88 #ifdef MULTIPROCESSOR
89 static u_int cacheht_time; /* Cache hotness time */
90 static u_int min_catch; /* Minimal LWP count for catching */
91
92 static u_int balance_period; /* Balance period */
93 static struct callout balance_ch; /* Callout of balancer */
94
95 static struct cpu_info * volatile worker_ci;
96
97 #define CACHE_HOT(sil) (sil->sl_lrtime && \
98 (hardclock_ticks - sil->sl_lrtime < cacheht_time))
99
100 #endif
101
102 /*
103 * Structures, runqueue.
104 */
105
106 typedef struct {
107 TAILQ_HEAD(, lwp) q_head;
108 } queue_t;
109
110 typedef struct {
111 /* Lock and bitmap */
112 kmutex_t r_rq_mutex;
113 uint32_t r_bitmap[PRI_COUNT >> BITMAP_SHIFT];
114 /* Counters */
115 u_int r_count; /* Count of the threads */
116 pri_t r_highest_pri; /* Highest priority */
117 u_int r_avgcount; /* Average count of threads */
118 u_int r_mcount; /* Count of migratable threads */
119 /* Runqueues */
120 queue_t r_rt_queue[PRI_RT_COUNT];
121 queue_t r_ts_queue[PRI_TS_COUNT];
122 } runqueue_t;
123
124 typedef struct {
125 u_int sl_flags;
126 u_int sl_timeslice; /* Time-slice of thread */
127 u_int sl_slept; /* Saved sleep time for sleep sum */
128 u_int sl_slpsum; /* Sum of sleep time */
129 u_int sl_rtime; /* Saved start time of run */
130 u_int sl_rtsum; /* Sum of the run time */
131 u_int sl_lrtime; /* Last run time */
132 } sched_info_lwp_t;
133
134 /* Flags */
135 #define SL_BATCH 0x01
136
137 /* Pool of the scheduler-specific structures for threads */
138 static struct pool sil_pool;
139
140 /*
141 * Prototypes.
142 */
143
144 static inline void * sched_getrq(runqueue_t *, const pri_t);
145 static inline void sched_newts(struct lwp *);
146 static void sched_precalcts(void);
147
148 #ifdef MULTIPROCESSOR
149 static struct lwp * sched_catchlwp(void);
150 static void sched_balance(void *);
151 #endif
152
153 /*
154 * Initialization and setup.
155 */
156
157 void
158 sched_rqinit(void)
159 {
160 struct cpu_info *ci = curcpu();
161
162 if (hz < 100) {
163 panic("sched_rqinit: value of HZ is too low\n");
164 }
165
166 /* Default timing ranges */
167 min_ts = mstohz(50); /* ~50ms */
168 max_ts = mstohz(150); /* ~150ms */
169 rt_ts = mstohz(100); /* ~100ms */
170 sched_precalcts();
171
172 #ifdef MULTIPROCESSOR
173 /* Balancing */
174 worker_ci = ci;
175 cacheht_time = mstohz(5); /* ~5 ms */
176 balance_period = mstohz(300); /* ~300ms */
177 min_catch = ~0;
178 #endif
179
180 /* Pool of the scheduler-specific structures */
181 pool_init(&sil_pool, sizeof(sched_info_lwp_t), 0, 0, 0,
182 "lwpsd", &pool_allocator_nointr, IPL_NONE);
183
184 /* Attach the primary CPU here */
185 sched_cpuattach(ci);
186
187 /* Initialize the scheduler structure of the primary LWP */
188 lwp0.l_mutex = &ci->ci_schedstate.spc_lwplock;
189 sched_lwp_fork(NULL, &lwp0);
190 sched_newts(&lwp0);
191 }
192
193 void
194 sched_setup(void)
195 {
196
197 #ifdef MULTIPROCESSOR
198 /* Minimal count of LWPs for catching: log2(count of CPUs) */
199 min_catch = min(ilog2(ncpu), 4);
200
201 /* Initialize balancing callout and run it */
202 callout_init(&balance_ch, CALLOUT_MPSAFE);
203 callout_setfunc(&balance_ch, sched_balance, NULL);
204 callout_schedule(&balance_ch, balance_period);
205 #endif
206 }
207
208 void
209 sched_cpuattach(struct cpu_info *ci)
210 {
211 runqueue_t *ci_rq;
212 void *rq_ptr;
213 u_int i, size;
214
215 /*
216 * Allocate the run queue.
217 * XXX: Estimate cache behaviour more..
218 */
219 size = roundup(sizeof(runqueue_t), CACHE_LINE_SIZE) + CACHE_LINE_SIZE;
220 rq_ptr = kmem_zalloc(size, KM_NOSLEEP);
221 if (rq_ptr == NULL) {
222 panic("scheduler: could not allocate the runqueue");
223 }
224 /* XXX: Save the original pointer for future.. */
225 ci_rq = (void *)(roundup((intptr_t)(rq_ptr), CACHE_LINE_SIZE));
226
227 /* Initialize run queues */
228 mutex_init(&ci_rq->r_rq_mutex, MUTEX_SPIN, IPL_SCHED);
229 for (i = 0; i < PRI_RT_COUNT; i++)
230 TAILQ_INIT(&ci_rq->r_rt_queue[i].q_head);
231 for (i = 0; i < PRI_TS_COUNT; i++)
232 TAILQ_INIT(&ci_rq->r_ts_queue[i].q_head);
233 ci_rq->r_highest_pri = 0;
234
235 ci->ci_schedstate.spc_sched_info = ci_rq;
236 ci->ci_schedstate.spc_mutex = &ci_rq->r_rq_mutex;
237 }
238
239 /* Pre-calculate the time-slices for the priorities */
240 static void
241 sched_precalcts(void)
242 {
243 pri_t p;
244
245 /* Time-sharing range */
246 for (p = 0; p <= PRI_HIGHEST_TS; p++) {
247 ts_map[p] = max_ts -
248 (p * 100 / (PRI_TS_COUNT - 1) * (max_ts - min_ts) / 100);
249 high_pri[p] = (PRI_HIGHEST_TS - PRI_HTS_RANGE) +
250 ((p * PRI_HTS_RANGE) / (PRI_TS_COUNT - 1));
251 }
252
253 /* Real-time range */
254 for (p = (PRI_HIGHEST_TS + 1); p < PRI_COUNT; p++) {
255 ts_map[p] = rt_ts;
256 high_pri[p] = p;
257 }
258 }
259
260 /*
261 * Hooks.
262 */
263
264 void
265 sched_proc_fork(struct proc *parent, struct proc *child)
266 {
267 struct lwp *l;
268
269 LIST_FOREACH(l, &child->p_lwps, l_sibling) {
270 lwp_lock(l);
271 sched_newts(l);
272 lwp_unlock(l);
273 }
274 }
275
276 void
277 sched_proc_exit(struct proc *child, struct proc *parent)
278 {
279
280 /* Dummy */
281 }
282
283 void
284 sched_lwp_fork(struct lwp *l1, struct lwp *l2)
285 {
286
287 KASSERT(l2->l_sched_info == NULL);
288 l2->l_sched_info = pool_get(&sil_pool, PR_WAITOK);
289 memset(l2->l_sched_info, 0, sizeof(sched_info_lwp_t));
290 if (l2->l_priority <= PRI_HIGHEST_TS) /* XXX: For now only.. */
291 l2->l_priority = PRI_DEFAULT;
292 }
293
294 void
295 sched_lwp_exit(struct lwp *l)
296 {
297
298 KASSERT(l->l_sched_info != NULL);
299 pool_put(&sil_pool, l->l_sched_info);
300 l->l_sched_info = NULL;
301 }
302
303 void
304 sched_lwp_collect(struct lwp *l)
305 {
306
307 }
308
309 void
310 sched_setrunnable(struct lwp *l)
311 {
312
313 /* Dummy */
314 }
315
316 void
317 sched_schedclock(struct lwp *l)
318 {
319
320 /* Dummy */
321 }
322
323 /*
324 * Priorities and time-slice.
325 */
326
327 void
328 sched_nice(struct proc *p, int prio)
329 {
330 int nprio;
331 struct lwp *l;
332
333 KASSERT(mutex_owned(&p->p_smutex));
334
335 p->p_nice = prio;
336 nprio = max(min(PRI_DEFAULT + p->p_nice, PRI_HIGHEST_TS), 0);
337
338 LIST_FOREACH(l, &p->p_lwps, l_sibling) {
339 lwp_lock(l);
340 lwp_changepri(l, nprio);
341 lwp_unlock(l);
342 }
343 }
344
345 /* Recalculate the time-slice */
346 static inline void
347 sched_newts(struct lwp *l)
348 {
349 sched_info_lwp_t *sil = l->l_sched_info;
350
351 sil->sl_timeslice = ts_map[lwp_eprio(l)];
352 }
353
354 /*
355 * Control of the runqueue.
356 */
357
358 static inline void *
359 sched_getrq(runqueue_t *ci_rq, const pri_t prio)
360 {
361
362 KASSERT(prio < PRI_COUNT);
363 return (prio <= PRI_HIGHEST_TS) ?
364 &ci_rq->r_ts_queue[prio].q_head :
365 &ci_rq->r_rt_queue[prio - PRI_HIGHEST_TS - 1].q_head;
366 }
367
368 void
369 sched_enqueue(struct lwp *l, bool swtch)
370 {
371 runqueue_t *ci_rq;
372 sched_info_lwp_t *sil = l->l_sched_info;
373 TAILQ_HEAD(, lwp) *q_head;
374 const pri_t eprio = lwp_eprio(l);
375
376 ci_rq = l->l_cpu->ci_schedstate.spc_sched_info;
377 KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
378
379 /* Update the last run time on switch */
380 if (swtch == true) {
381 sil->sl_lrtime = hardclock_ticks;
382 sil->sl_rtsum += (hardclock_ticks - sil->sl_rtime);
383 } else if (sil->sl_lrtime == 0)
384 sil->sl_lrtime = hardclock_ticks;
385
386 /* Enqueue the thread */
387 q_head = sched_getrq(ci_rq, eprio);
388 if (TAILQ_EMPTY(q_head)) {
389 u_int i;
390 uint32_t q;
391
392 /* Mark bit */
393 i = eprio >> BITMAP_SHIFT;
394 q = BITMAP_MSB >> (eprio & BITMAP_MASK);
395 KASSERT((ci_rq->r_bitmap[i] & q) == 0);
396 ci_rq->r_bitmap[i] |= q;
397 }
398 TAILQ_INSERT_TAIL(q_head, l, l_runq);
399 ci_rq->r_count++;
400 if ((l->l_flag & LW_BOUND) == 0)
401 ci_rq->r_mcount++;
402
403 /*
404 * Update the value of highest priority in the runqueue,
405 * if priority of this thread is higher.
406 */
407 if (eprio > ci_rq->r_highest_pri)
408 ci_rq->r_highest_pri = eprio;
409
410 sched_newts(l);
411 }
412
413 void
414 sched_dequeue(struct lwp *l)
415 {
416 runqueue_t *ci_rq;
417 TAILQ_HEAD(, lwp) *q_head;
418 const pri_t eprio = lwp_eprio(l);
419
420 ci_rq = l->l_cpu->ci_schedstate.spc_sched_info;
421 KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
422 KASSERT(eprio <= ci_rq->r_highest_pri);
423 KASSERT(ci_rq->r_bitmap[eprio >> BITMAP_SHIFT] != 0);
424 KASSERT(ci_rq->r_count > 0);
425
426 ci_rq->r_count--;
427 if ((l->l_flag & LW_BOUND) == 0)
428 ci_rq->r_mcount--;
429
430 q_head = sched_getrq(ci_rq, eprio);
431 TAILQ_REMOVE(q_head, l, l_runq);
432 if (TAILQ_EMPTY(q_head)) {
433 u_int i;
434 uint32_t q;
435
436 /* Unmark bit */
437 i = eprio >> BITMAP_SHIFT;
438 q = BITMAP_MSB >> (eprio & BITMAP_MASK);
439 KASSERT((ci_rq->r_bitmap[i] & q) != 0);
440 ci_rq->r_bitmap[i] &= ~q;
441
442 /*
443 * Update the value of highest priority in the runqueue, in a
444 * case it was a last thread in the queue of highest priority.
445 */
446 if (eprio != ci_rq->r_highest_pri)
447 return;
448
449 do {
450 q = ffs(ci_rq->r_bitmap[i]);
451 if (q) {
452 ci_rq->r_highest_pri =
453 (i << BITMAP_SHIFT) + (BITMAP_BITS - q);
454 return;
455 }
456 } while (i--);
457
458 /* If not found - set the lowest value */
459 ci_rq->r_highest_pri = 0;
460 }
461 }
462
463 void
464 sched_slept(struct lwp *l)
465 {
466 sched_info_lwp_t *sil = l->l_sched_info;
467
468 /* Save the time when thread has slept */
469 sil->sl_slept = hardclock_ticks;
470
471 /*
472 * If thread is in time-sharing queue and batch flag is not marked,
473 * increase the the priority, and run with the lower time-quantum.
474 */
475 if (l->l_priority < PRI_HIGHEST_TS && (sil->sl_flags & SL_BATCH) == 0) {
476 KASSERT(l->l_class == SCHED_OTHER);
477 l->l_priority++;
478 }
479 }
480
481 void
482 sched_wakeup(struct lwp *l)
483 {
484 sched_info_lwp_t *sil = l->l_sched_info;
485
486 /* Update sleep time delta */
487 sil->sl_slpsum += (l->l_slptime == 0) ?
488 (hardclock_ticks - sil->sl_slept) : hz;
489
490 /* If thread was sleeping a second or more - set a high priority */
491 if (l->l_slptime > 1 || (hardclock_ticks - sil->sl_slept) >= hz)
492 l->l_priority = high_pri[l->l_priority];
493
494 /* Also, consider looking for a better CPU to wake up */
495 if ((l->l_flag & (LW_BOUND | LW_SYSTEM)) == 0)
496 l->l_cpu = sched_takecpu(l);
497 }
498
499 void
500 sched_pstats_hook(struct lwp *l)
501 {
502 sched_info_lwp_t *sil = l->l_sched_info;
503 bool batch;
504
505 if (l->l_stat == LSSLEEP || l->l_stat == LSSTOP ||
506 l->l_stat == LSSUSPENDED)
507 l->l_slptime++;
508
509 /*
510 * Set that thread is more CPU-bound, if sum of run time exceeds the
511 * sum of sleep time. Check if thread is CPU-bound a first time.
512 */
513 batch = (sil->sl_rtsum > sil->sl_slpsum);
514 if (batch) {
515 if ((sil->sl_flags & SL_BATCH) == 0)
516 batch = false;
517 sil->sl_flags |= SL_BATCH;
518 } else
519 sil->sl_flags &= ~SL_BATCH;
520
521 /* Reset the time sums */
522 sil->sl_slpsum = 0;
523 sil->sl_rtsum = 0;
524
525 /* Estimate threads on time-sharing queue only */
526 if (l->l_priority >= PRI_HIGHEST_TS)
527 return;
528
529 /* If it is CPU-bound not a first time - decrease the priority */
530 if (batch && l->l_priority != 0)
531 l->l_priority--;
532
533 /* If thread was not ran a second or more - set a high priority */
534 if (l->l_stat == LSRUN && sil->sl_lrtime &&
535 (hardclock_ticks - sil->sl_lrtime >= hz))
536 lwp_changepri(l, high_pri[l->l_priority]);
537 }
538
539 /*
540 * Migration and balancing.
541 */
542
543 #ifdef MULTIPROCESSOR
544
545 /* Check if LWP can migrate to the chosen CPU */
546 static inline bool
547 sched_migratable(const struct lwp *l, const struct cpu_info *ci)
548 {
549
550 if (ci->ci_schedstate.spc_flags & SPCF_OFFLINE)
551 return false;
552
553 if ((l->l_flag & LW_BOUND) == 0)
554 return true;
555 #if 0
556 return cpu_in_pset(ci, l->l_psid);
557 #else
558 return false;
559 #endif
560 }
561
562 /*
563 * Estimate the migration of LWP to the other CPU.
564 * Take and return the CPU, if migration is needed.
565 */
566 struct cpu_info *
567 sched_takecpu(struct lwp *l)
568 {
569 struct cpu_info *ci, *tci = NULL;
570 struct schedstate_percpu *spc;
571 runqueue_t *ci_rq;
572 sched_info_lwp_t *sil;
573 CPU_INFO_ITERATOR cii;
574 pri_t eprio, lpri;
575
576 ci = l->l_cpu;
577 spc = &ci->ci_schedstate;
578 ci_rq = spc->spc_sched_info;
579
580 /* CPU of this thread is idling - run there */
581 if (ci_rq->r_count == 0)
582 return ci;
583
584 eprio = lwp_eprio(l);
585 sil = l->l_sched_info;
586
587 /* Stay if thread is cache-hot */
588 if (l->l_stat == LSSLEEP && l->l_slptime <= 1 &&
589 CACHE_HOT(sil) && eprio >= spc->spc_curpriority)
590 return ci;
591
592 /* Run on current CPU if priority of thread is higher */
593 ci = curcpu();
594 spc = &ci->ci_schedstate;
595 if (eprio > spc->spc_curpriority && sched_migratable(l, ci))
596 return ci;
597
598 /*
599 * Look for the CPU with the lowest priority thread. In case of
600 * equal the priority - check the lower count of the threads.
601 */
602 lpri = PRI_COUNT;
603 for (CPU_INFO_FOREACH(cii, ci)) {
604 runqueue_t *ici_rq;
605 pri_t pri;
606
607 spc = &ci->ci_schedstate;
608 ici_rq = spc->spc_sched_info;
609 pri = max(spc->spc_curpriority, ici_rq->r_highest_pri);
610 if (pri > lpri)
611 continue;
612
613 if (pri == lpri && tci && ci_rq->r_count < ici_rq->r_count)
614 continue;
615
616 if (sched_migratable(l, ci) == false)
617 continue;
618
619 lpri = pri;
620 tci = ci;
621 ci_rq = ici_rq;
622 }
623
624 KASSERT(tci != NULL);
625 return tci;
626 }
627
628 /*
629 * Tries to catch an LWP from the runqueue of other CPU.
630 */
631 static struct lwp *
632 sched_catchlwp(void)
633 {
634 struct cpu_info *curci = curcpu(), *ci = worker_ci;
635 TAILQ_HEAD(, lwp) *q_head;
636 runqueue_t *ci_rq;
637 struct lwp *l;
638
639 if (curci == ci)
640 return NULL;
641
642 /* Lockless check */
643 ci_rq = ci->ci_schedstate.spc_sched_info;
644 if (ci_rq->r_count < min_catch)
645 return NULL;
646
647 /*
648 * Double-lock the runqueues.
649 */
650 if (curci < ci) {
651 spc_lock(ci);
652 } else if (!mutex_tryenter(ci->ci_schedstate.spc_mutex)) {
653 const runqueue_t *cur_rq = curci->ci_schedstate.spc_sched_info;
654
655 spc_unlock(curci);
656 spc_lock(ci);
657 spc_lock(curci);
658
659 if (cur_rq->r_count) {
660 spc_unlock(ci);
661 return NULL;
662 }
663 }
664
665 if (ci_rq->r_count < min_catch) {
666 spc_unlock(ci);
667 return NULL;
668 }
669
670 /* Take the highest priority thread */
671 q_head = sched_getrq(ci_rq, ci_rq->r_highest_pri);
672 l = TAILQ_FIRST(q_head);
673
674 for (;;) {
675 sched_info_lwp_t *sil;
676
677 /* Check the first and next result from the queue */
678 if (l == NULL)
679 break;
680
681 /* Look for threads, whose are allowed to migrate */
682 sil = l->l_sched_info;
683 if ((l->l_flag & LW_SYSTEM) || CACHE_HOT(sil) ||
684 sched_migratable(l, curci) == false) {
685 l = TAILQ_NEXT(l, l_runq);
686 continue;
687 }
688 /* Recheck if chosen thread is still on the runqueue */
689 if (l->l_stat == LSRUN && (l->l_flag & LW_INMEM)) {
690 sched_dequeue(l);
691 l->l_cpu = curci;
692 lwp_setlock(l, curci->ci_schedstate.spc_mutex);
693 sched_enqueue(l, false);
694 break;
695 }
696 l = TAILQ_NEXT(l, l_runq);
697 }
698 spc_unlock(ci);
699
700 return l;
701 }
702
703 /*
704 * Periodical calculations for balancing.
705 */
706 static void
707 sched_balance(void *nocallout)
708 {
709 struct cpu_info *ci, *hci;
710 runqueue_t *ci_rq;
711 CPU_INFO_ITERATOR cii;
712 u_int highest;
713
714 hci = curcpu();
715 highest = 0;
716
717 /* Make lockless countings */
718 for (CPU_INFO_FOREACH(cii, ci)) {
719 ci_rq = ci->ci_schedstate.spc_sched_info;
720
721 /* Average count of the threads */
722 ci_rq->r_avgcount = (ci_rq->r_avgcount + ci_rq->r_mcount) >> 1;
723
724 /* Look for CPU with the highest average */
725 if (ci_rq->r_avgcount > highest) {
726 hci = ci;
727 highest = ci_rq->r_avgcount;
728 }
729 }
730
731 /* Update the worker */
732 worker_ci = hci;
733
734 if (nocallout == NULL)
735 callout_schedule(&balance_ch, balance_period);
736 }
737
738 #else
739
740 struct cpu_info *
741 sched_takecpu(struct lwp *l)
742 {
743
744 return l->l_cpu;
745 }
746
747 #endif /* MULTIPROCESSOR */
748
749 /*
750 * Scheduler mill.
751 */
752 struct lwp *
753 sched_nextlwp(void)
754 {
755 struct cpu_info *ci = curcpu();
756 struct schedstate_percpu *spc;
757 TAILQ_HEAD(, lwp) *q_head;
758 sched_info_lwp_t *sil;
759 runqueue_t *ci_rq;
760 struct lwp *l;
761
762 spc = &ci->ci_schedstate;
763 ci_rq = ci->ci_schedstate.spc_sched_info;
764
765 #ifdef MULTIPROCESSOR
766 /* If runqueue is empty, try to catch some thread from other CPU */
767 if (spc->spc_flags & SPCF_OFFLINE) {
768 if ((ci_rq->r_count - ci_rq->r_mcount) == 0)
769 return NULL;
770 } else if (ci_rq->r_count == 0) {
771 /* Reset the counter, and call the balancer */
772 ci_rq->r_avgcount = 0;
773 sched_balance(ci);
774
775 /* The re-locking will be done inside */
776 return sched_catchlwp();
777 }
778 #else
779 if (ci_rq->r_count == 0)
780 return NULL;
781 #endif
782
783 /* Take the highest priority thread */
784 KASSERT(ci_rq->r_bitmap[ci_rq->r_highest_pri >> BITMAP_SHIFT]);
785 q_head = sched_getrq(ci_rq, ci_rq->r_highest_pri);
786 l = TAILQ_FIRST(q_head);
787 KASSERT(l != NULL);
788
789 /* Update the counters */
790 sil = l->l_sched_info;
791 KASSERT(sil->sl_timeslice >= min_ts);
792 KASSERT(sil->sl_timeslice <= max_ts);
793 spc->spc_ticks = sil->sl_timeslice;
794 sil->sl_rtime = hardclock_ticks;
795
796 return l;
797 }
798
799 bool
800 sched_curcpu_runnable_p(void)
801 {
802 const struct cpu_info *ci = curcpu();
803 const runqueue_t *ci_rq = ci->ci_schedstate.spc_sched_info;
804
805 if (ci->ci_schedstate.spc_flags & SPCF_OFFLINE)
806 return (ci_rq->r_count - ci_rq->r_mcount);
807
808 return ci_rq->r_count;
809 }
810
811 /*
812 * Time-driven events.
813 */
814
815 /*
816 * Called once per time-quantum. This routine is CPU-local and runs at
817 * IPL_SCHED, thus the locking is not needed.
818 */
819 void
820 sched_tick(struct cpu_info *ci)
821 {
822 const runqueue_t *ci_rq = ci->ci_schedstate.spc_sched_info;
823 struct schedstate_percpu *spc = &ci->ci_schedstate;
824 struct lwp *l = curlwp;
825 sched_info_lwp_t *sil = l->l_sched_info;
826
827 if (CURCPU_IDLE_P())
828 return;
829
830 switch (l->l_class) {
831 case SCHED_FIFO:
832 /*
833 * Update the time-quantum, and continue running,
834 * if thread runs on FIFO real-time policy.
835 */
836 spc->spc_ticks = sil->sl_timeslice;
837 return;
838 case SCHED_OTHER:
839 /*
840 * If thread is in time-sharing queue, decrease the priority,
841 * and run with a higher time-quantum.
842 */
843 if (l->l_priority > PRI_HIGHEST_TS)
844 break;
845 if (l->l_priority != 0)
846 l->l_priority--;
847 break;
848 }
849
850 /*
851 * If there are higher priority threads or threads in the same queue,
852 * mark that thread should yield, otherwise, continue running.
853 */
854 if (lwp_eprio(l) <= ci_rq->r_highest_pri) {
855 spc->spc_flags |= SPCF_SHOULDYIELD;
856 cpu_need_resched(ci, 0);
857 } else
858 spc->spc_ticks = sil->sl_timeslice;
859 }
860
861 /*
862 * Sysctl nodes and initialization.
863 */
864
865 static int
866 sysctl_sched_mints(SYSCTLFN_ARGS)
867 {
868 struct sysctlnode node;
869 struct cpu_info *ci;
870 int error, newsize;
871 CPU_INFO_ITERATOR cii;
872
873 node = *rnode;
874 node.sysctl_data = &newsize;
875
876 newsize = hztoms(min_ts);
877 error = sysctl_lookup(SYSCTLFN_CALL(&node));
878 if (error || newp == NULL)
879 return error;
880
881 newsize = mstohz(newsize);
882 if (newsize < 1 || newsize > hz || newsize >= max_ts)
883 return EINVAL;
884
885 /* It is safe to do this in such order */
886 for (CPU_INFO_FOREACH(cii, ci))
887 spc_lock(ci);
888
889 min_ts = newsize;
890 sched_precalcts();
891
892 for (CPU_INFO_FOREACH(cii, ci))
893 spc_unlock(ci);
894
895 return 0;
896 }
897
898 static int
899 sysctl_sched_maxts(SYSCTLFN_ARGS)
900 {
901 struct sysctlnode node;
902 struct cpu_info *ci;
903 int error, newsize;
904 CPU_INFO_ITERATOR cii;
905
906 node = *rnode;
907 node.sysctl_data = &newsize;
908
909 newsize = hztoms(max_ts);
910 error = sysctl_lookup(SYSCTLFN_CALL(&node));
911 if (error || newp == NULL)
912 return error;
913
914 newsize = mstohz(newsize);
915 if (newsize < 10 || newsize > hz || newsize <= min_ts)
916 return EINVAL;
917
918 /* It is safe to do this in such order */
919 for (CPU_INFO_FOREACH(cii, ci))
920 spc_lock(ci);
921
922 max_ts = newsize;
923 sched_precalcts();
924
925 for (CPU_INFO_FOREACH(cii, ci))
926 spc_unlock(ci);
927
928 return 0;
929 }
930
931 SYSCTL_SETUP(sysctl_sched_setup, "sysctl kern.sched subtree setup")
932 {
933 const struct sysctlnode *node = NULL;
934
935 sysctl_createv(clog, 0, NULL, NULL,
936 CTLFLAG_PERMANENT,
937 CTLTYPE_NODE, "kern", NULL,
938 NULL, 0, NULL, 0,
939 CTL_KERN, CTL_EOL);
940 sysctl_createv(clog, 0, NULL, &node,
941 CTLFLAG_PERMANENT,
942 CTLTYPE_NODE, "sched",
943 SYSCTL_DESCR("Scheduler options"),
944 NULL, 0, NULL, 0,
945 CTL_KERN, CTL_CREATE, CTL_EOL);
946
947 if (node == NULL)
948 return;
949
950 sysctl_createv(clog, 0, &node, NULL,
951 CTLFLAG_PERMANENT,
952 CTLTYPE_STRING, "name", NULL,
953 NULL, 0, __UNCONST("M2"), 0,
954 CTL_CREATE, CTL_EOL);
955 sysctl_createv(clog, 0, &node, NULL,
956 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
957 CTLTYPE_INT, "maxts",
958 SYSCTL_DESCR("Maximal time quantum (in miliseconds)"),
959 sysctl_sched_maxts, 0, &max_ts, 0,
960 CTL_CREATE, CTL_EOL);
961 sysctl_createv(clog, 0, &node, NULL,
962 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
963 CTLTYPE_INT, "mints",
964 SYSCTL_DESCR("Minimal time quantum (in miliseconds)"),
965 sysctl_sched_mints, 0, &min_ts, 0,
966 CTL_CREATE, CTL_EOL);
967
968 #ifdef MULTIPROCESSOR
969 sysctl_createv(clog, 0, &node, NULL,
970 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
971 CTLTYPE_INT, "cacheht_time",
972 SYSCTL_DESCR("Cache hotness time (in ticks)"),
973 NULL, 0, &cacheht_time, 0,
974 CTL_CREATE, CTL_EOL);
975 sysctl_createv(clog, 0, &node, NULL,
976 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
977 CTLTYPE_INT, "balance_period",
978 SYSCTL_DESCR("Balance period (in ticks)"),
979 NULL, 0, &balance_period, 0,
980 CTL_CREATE, CTL_EOL);
981 sysctl_createv(clog, 0, &node, NULL,
982 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
983 CTLTYPE_INT, "min_catch",
984 SYSCTL_DESCR("Minimal count of the threads for catching"),
985 NULL, 0, &min_catch, 0,
986 CTL_CREATE, CTL_EOL);
987 #endif
988 }
989
990 /*
991 * Debugging.
992 */
993
994 #ifdef DDB
995
996 void
997 sched_print_runqueue(void (*pr)(const char *, ...))
998 {
999 runqueue_t *ci_rq;
1000 sched_info_lwp_t *sil;
1001 struct lwp *l;
1002 struct proc *p;
1003 int i;
1004
1005 struct cpu_info *ci;
1006 CPU_INFO_ITERATOR cii;
1007
1008 for (CPU_INFO_FOREACH(cii, ci)) {
1009 ci_rq = ci->ci_schedstate.spc_sched_info;
1010
1011 (*pr)("Run-queue (CPU = %d):\n", ci->ci_cpuid);
1012 (*pr)(" pid.lid = %d.%d, threads count = %u, "
1013 "avgcount = %u, highest pri = %d\n",
1014 ci->ci_curlwp->l_proc->p_pid, ci->ci_curlwp->l_lid,
1015 ci_rq->r_count, ci_rq->r_avgcount, ci_rq->r_highest_pri);
1016 i = (PRI_COUNT >> BITMAP_SHIFT) - 1;
1017 do {
1018 uint32_t q;
1019 q = ci_rq->r_bitmap[i];
1020 (*pr)(" bitmap[%d] => [ %d (0x%x) ]\n", i, ffs(q), q);
1021 } while (i--);
1022 }
1023
1024 (*pr)(" %5s %4s %4s %10s %3s %4s %11s %3s %s\n",
1025 "LID", "PRI", "EPRI", "FL", "ST", "TS", "LWP", "CPU", "LRTIME");
1026
1027 PROCLIST_FOREACH(p, &allproc) {
1028 (*pr)(" /- %d (%s)\n", (int)p->p_pid, p->p_comm);
1029 LIST_FOREACH(l, &p->p_lwps, l_sibling) {
1030 sil = l->l_sched_info;
1031 ci = l->l_cpu;
1032 (*pr)(" | %5d %4u %4u 0x%8.8x %3s %4u %11p %3d "
1033 "%u ST=%d RT=%d %d\n",
1034 (int)l->l_lid, l->l_priority, lwp_eprio(l),
1035 l->l_flag, l->l_stat == LSRUN ? "RQ" :
1036 (l->l_stat == LSSLEEP ? "SQ" : "-"),
1037 sil->sl_timeslice, l, ci->ci_cpuid,
1038 (u_int)(hardclock_ticks - sil->sl_lrtime),
1039 sil->sl_slpsum, sil->sl_rtsum, sil->sl_flags);
1040 }
1041 }
1042 }
1043
1044 #endif /* defined(DDB) */
1045