2 * Copyright (c) 2000-2010 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
32 * Mach Operating System
33 * Copyright (c) 1991,1990,1989,1988,1987 Carnegie Mellon University
34 * All Rights Reserved.
36 * Permission to use, copy, modify and distribute this software and its
37 * documentation is hereby granted, provided that both the copyright
38 * notice and this permission notice appear in all copies of the
39 * software, derivative works or modified versions, and any portions
40 * thereof, and that both notices appear in supporting documentation.
42 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
43 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
44 * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
46 * Carnegie Mellon requests users of this software to return to
48 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
49 * School of Computer Science
50 * Carnegie Mellon University
51 * Pittsburgh PA 15213-3890
53 * any improvements or extensions that they make and grant Carnegie Mellon
54 * the rights to redistribute these changes.
60 * Author: Avadis Tevanian, Jr.
63 * Priority related scheduler bits.
66 #include <mach/boolean.h>
67 #include <mach/kern_return.h>
68 #include <mach/machine.h>
69 #include <kern/host.h>
70 #include <kern/mach_param.h>
71 #include <kern/sched.h>
72 #include <sys/kdebug.h>
74 #include <kern/thread.h>
75 #include <kern/processor.h>
76 #include <kern/ledger.h>
77 #include <machine/machparam.h>
78 #include <kern/machine.h>
80 #ifdef CONFIG_MACH_APPROXIMATE_TIME
81 #include <machine/commpage.h> /* for commpage_update_mach_approximate_time */
84 static void sched_update_thread_bucket(thread_t thread
);
87 * thread_quantum_expire:
89 * Recalculate the quantum and priority for a thread.
95 thread_quantum_expire(
96 timer_call_param_t p0
,
97 timer_call_param_t p1
)
99 processor_t processor
= p0
;
100 thread_t thread
= p1
;
104 uint64_t ignore1
, ignore2
;
106 assert(processor
== current_processor());
107 assert(thread
== current_thread());
109 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED
, MACH_SCHED_QUANTUM_EXPIRED
) | DBG_FUNC_START
, 0, 0, 0, 0, 0);
111 SCHED_STATS_QUANTUM_TIMER_EXPIRATION(processor
);
114 * We bill CPU time to both the individual thread and its task.
116 * Because this balance adjustment could potentially attempt to wake this very
117 * thread, we must credit the ledger before taking the thread lock. The ledger
118 * pointers are only manipulated by the thread itself at the ast boundary.
120 * TODO: This fails to account for the time between when the timer was armed and when it fired.
121 * It should be based on the system_timer and running a thread_timer_event operation here.
123 ledger_credit(thread
->t_ledger
, task_ledgers
.cpu_time
, thread
->quantum_remaining
);
124 ledger_credit(thread
->t_threadledger
, thread_ledgers
.cpu_time
, thread
->quantum_remaining
);
126 if (thread
->t_bankledger
) {
127 ledger_credit(thread
->t_bankledger
, bank_ledgers
.cpu_time
,
128 (thread
->quantum_remaining
- thread
->t_deduct_bank_ledger_time
));
130 thread
->t_deduct_bank_ledger_time
= 0;
133 ctime
= mach_absolute_time();
135 #ifdef CONFIG_MACH_APPROXIMATE_TIME
136 commpage_update_mach_approximate_time(ctime
);
142 * We've run up until our quantum expiration, and will (potentially)
143 * continue without re-entering the scheduler, so update this now.
145 processor
->last_dispatch
= ctime
;
146 thread
->last_run_time
= ctime
;
149 * Check for fail-safe trip.
151 if ((thread
->sched_mode
== TH_MODE_REALTIME
|| thread
->sched_mode
== TH_MODE_FIXED
) &&
152 !(thread
->sched_flags
& TH_SFLAG_PROMOTED_MASK
) &&
153 !(thread
->options
& TH_OPT_SYSTEM_CRITICAL
)) {
154 uint64_t new_computation
;
156 new_computation
= ctime
- thread
->computation_epoch
;
157 new_computation
+= thread
->computation_metered
;
158 if (new_computation
> max_unsafe_computation
) {
159 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED
, MACH_FAILSAFE
)|DBG_FUNC_NONE
,
160 (uintptr_t)thread
->sched_pri
, (uintptr_t)thread
->sched_mode
, 0, 0, 0);
162 thread
->safe_release
= ctime
+ sched_safe_duration
;
164 sched_thread_mode_demote(thread
, TH_SFLAG_FAILSAFE
);
169 * Recompute scheduled priority if appropriate.
171 if (SCHED(can_update_priority
)(thread
))
172 SCHED(update_priority
)(thread
);
174 SCHED(lightweight_update_priority
)(thread
);
176 if (thread
->sched_mode
!= TH_MODE_REALTIME
)
177 SCHED(quantum_expire
)(thread
);
179 processor
->current_pri
= thread
->sched_pri
;
180 processor
->current_thmode
= thread
->sched_mode
;
182 /* Tell platform layer that we are still running this thread */
183 urgency
= thread_get_urgency(thread
, &ignore1
, &ignore2
);
184 machine_thread_going_on_core(thread
, urgency
, 0);
187 * This quantum is up, give this thread another.
189 processor
->first_timeslice
= FALSE
;
191 thread_quantum_init(thread
);
193 /* Reload precise timing global policy to thread-local policy */
194 thread
->precise_user_kernel_time
= use_precise_user_kernel_time(thread
);
197 * Since non-precise user/kernel time doesn't update the state/thread timer
198 * during privilege transitions, synthesize an event now.
200 if (!thread
->precise_user_kernel_time
) {
201 timer_switch(PROCESSOR_DATA(processor
, current_state
),
203 PROCESSOR_DATA(processor
, current_state
));
204 timer_switch(PROCESSOR_DATA(processor
, thread_timer
),
206 PROCESSOR_DATA(processor
, thread_timer
));
209 processor
->quantum_end
= ctime
+ thread
->quantum_remaining
;
212 * Context switch check.
214 if ((preempt
= csw_check(processor
, AST_QUANTUM
)) != AST_NONE
)
217 thread_unlock(thread
);
219 timer_call_enter1(&processor
->quantum_timer
, thread
,
220 processor
->quantum_end
, TIMER_CALL_SYS_CRITICAL
| TIMER_CALL_LOCAL
);
222 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
223 sched_timeshare_consider_maintenance(ctime
);
224 #endif /* CONFIG_SCHED_TIMESHARE_CORE */
227 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED
, MACH_SCHED_QUANTUM_EXPIRED
) | DBG_FUNC_END
, preempt
, 0, 0, 0, 0);
231 * sched_set_thread_base_priority:
233 * Set the base priority of the thread
234 * and reset its scheduled priority.
236 * This is the only path to change base_pri.
238 * Called with the thread locked.
241 sched_set_thread_base_priority(thread_t thread
, int priority
)
243 assert(priority
>= MINPRI
);
245 if (thread
->sched_mode
== TH_MODE_REALTIME
)
246 assert(priority
<= BASEPRI_RTQUEUES
);
248 assert(priority
< BASEPRI_RTQUEUES
);
250 thread
->base_pri
= priority
;
252 sched_update_thread_bucket(thread
);
254 thread_recompute_sched_pri(thread
, FALSE
);
258 * thread_recompute_sched_pri:
260 * Reset the scheduled priority of the thread
261 * according to its base priority if the
262 * thread has not been promoted or depressed.
264 * This is the standard way to push base_pri changes into sched_pri,
265 * or to recalculate the appropriate sched_pri after clearing
266 * a promotion or depression.
268 * Called at splsched with the thread locked.
271 thread_recompute_sched_pri(
273 boolean_t override_depress
)
277 if (thread
->sched_mode
== TH_MODE_TIMESHARE
)
278 priority
= SCHED(compute_timeshare_priority
)(thread
);
280 priority
= thread
->base_pri
;
282 if ((!(thread
->sched_flags
& TH_SFLAG_PROMOTED_MASK
) || (priority
> thread
->sched_pri
)) &&
283 (!(thread
->sched_flags
& TH_SFLAG_DEPRESSED_MASK
) || override_depress
)) {
284 set_sched_pri(thread
, priority
);
289 sched_default_quantum_expire(thread_t thread __unused
)
292 * No special behavior when a timeshare, fixed, or realtime thread
293 * uses up its entire quantum
297 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
300 * lightweight_update_priority:
302 * Update the scheduled priority for
303 * a timesharing thread.
305 * Only for use on the current thread.
307 * Called with the thread locked.
310 lightweight_update_priority(thread_t thread
)
312 assert(thread
->runq
== PROCESSOR_NULL
);
313 assert(thread
== current_thread());
315 if (thread
->sched_mode
== TH_MODE_TIMESHARE
) {
319 thread_timer_delta(thread
, delta
);
322 * Accumulate timesharing usage only
323 * during contention for processor
326 if (thread
->pri_shift
< INT8_MAX
)
327 thread
->sched_usage
+= delta
;
329 thread
->cpu_delta
+= delta
;
331 priority
= sched_compute_timeshare_priority(thread
);
334 * Adjust the scheduled priority like thread_recompute_sched_pri,
335 * except with the benefit of knowing the thread is on this core.
337 if ((!(thread
->sched_flags
& TH_SFLAG_PROMOTED_MASK
) || (priority
> thread
->sched_pri
)) &&
338 (!(thread
->sched_flags
& TH_SFLAG_DEPRESSED_MASK
)) &&
339 priority
!= thread
->sched_pri
) {
341 thread
->sched_pri
= priority
;
343 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED
, MACH_SCHED_CHANGE_PRIORITY
),
344 (uintptr_t)thread_tid(thread
),
347 0, /* eventually, 'reason' */
354 * Define shifts for simulating (5/8) ** n
356 * Shift structures for holding update shifts. Actual computation
357 * is usage = (usage >> shift1) +/- (usage >> abs(shift2)) where the
358 * +/- is determined by the sign of shift 2.
365 #define SCHED_DECAY_TICKS 32
366 static struct shift_data sched_decay_shifts
[SCHED_DECAY_TICKS
] = {
367 {1,1},{1,3},{1,-3},{2,-7},{3,5},{3,-5},{4,-8},{5,7},
368 {5,-7},{6,-10},{7,10},{7,-9},{8,-11},{9,12},{9,-11},{10,-13},
369 {11,14},{11,-13},{12,-15},{13,17},{13,-15},{14,-17},{15,19},{16,18},
370 {16,-19},{17,22},{18,20},{18,-20},{19,26},{20,22},{20,-22},{21,-27}
374 * sched_compute_timeshare_priority:
376 * Calculate the timesharing priority based upon usage and load.
378 extern int sched_pri_decay_band_limit
;
382 sched_compute_timeshare_priority(thread_t thread
)
384 /* start with base priority */
385 int priority
= thread
->base_pri
- (thread
->sched_usage
>> thread
->pri_shift
);
387 if (priority
< MINPRI_USER
)
388 priority
= MINPRI_USER
;
389 else if (priority
> MAXPRI_KERNEL
)
390 priority
= MAXPRI_KERNEL
;
397 * can_update_priority
399 * Make sure we don't do re-dispatches more frequently than a scheduler tick.
401 * Called with the thread locked.
407 if (sched_tick
== thread
->sched_stamp
)
416 * Perform housekeeping operations driven by scheduler tick.
418 * Called with the thread locked.
424 uint32_t ticks
, delta
;
426 ticks
= sched_tick
- thread
->sched_stamp
;
429 thread
->sched_stamp
+= ticks
;
431 thread
->pri_shift
= sched_pri_shifts
[thread
->th_sched_bucket
];
433 /* If requested, accelerate aging of sched_usage */
434 if (sched_decay_usage_age_factor
> 1)
435 ticks
*= sched_decay_usage_age_factor
;
438 * Gather cpu usage data.
440 thread_timer_delta(thread
, delta
);
441 if (ticks
< SCHED_DECAY_TICKS
) {
443 * Accumulate timesharing usage only
444 * during contention for processor
447 if (thread
->pri_shift
< INT8_MAX
)
448 thread
->sched_usage
+= delta
;
450 thread
->cpu_usage
+= delta
+ thread
->cpu_delta
;
451 thread
->cpu_delta
= 0;
453 struct shift_data
*shiftp
= &sched_decay_shifts
[ticks
];
455 if (shiftp
->shift2
> 0) {
456 thread
->cpu_usage
= (thread
->cpu_usage
>> shiftp
->shift1
) +
457 (thread
->cpu_usage
>> shiftp
->shift2
);
458 thread
->sched_usage
= (thread
->sched_usage
>> shiftp
->shift1
) +
459 (thread
->sched_usage
>> shiftp
->shift2
);
461 thread
->cpu_usage
= (thread
->cpu_usage
>> shiftp
->shift1
) -
462 (thread
->cpu_usage
>> -(shiftp
->shift2
));
463 thread
->sched_usage
= (thread
->sched_usage
>> shiftp
->shift1
) -
464 (thread
->sched_usage
>> -(shiftp
->shift2
));
467 thread
->cpu_usage
= thread
->cpu_delta
= 0;
468 thread
->sched_usage
= 0;
472 * Check for fail-safe release.
474 if ((thread
->sched_flags
& TH_SFLAG_FAILSAFE
) &&
475 mach_absolute_time() >= thread
->safe_release
) {
476 sched_thread_mode_undemote(thread
, TH_SFLAG_FAILSAFE
);
480 * Recompute scheduled priority if appropriate.
482 if (thread
->sched_mode
== TH_MODE_TIMESHARE
) {
483 int priority
= sched_compute_timeshare_priority(thread
);
486 * Adjust the scheduled priority like thread_recompute_sched_pri,
487 * except without setting an AST.
489 if ((!(thread
->sched_flags
& TH_SFLAG_PROMOTED_MASK
) || (priority
> thread
->sched_pri
)) &&
490 (!(thread
->sched_flags
& TH_SFLAG_DEPRESSED_MASK
)) &&
491 priority
!= thread
->sched_pri
) {
493 boolean_t removed
= thread_run_queue_remove(thread
);
495 thread
->sched_pri
= priority
;
497 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED
, MACH_SCHED_CHANGE_PRIORITY
),
498 (uintptr_t)thread_tid(thread
),
501 0, /* eventually, 'reason' */
505 thread_run_queue_reinsert(thread
, SCHED_TAILQ
);
512 #endif /* CONFIG_SCHED_TIMESHARE_CORE */
516 * TH_BUCKET_RUN is a count of *all* runnable non-idle threads.
517 * Each other bucket is a count of the runnable non-idle threads
518 * with that property.
520 volatile uint32_t sched_run_buckets
[TH_BUCKET_MAX
];
523 sched_incr_bucket(sched_bucket_t bucket
)
525 assert(bucket
>= TH_BUCKET_FIXPRI
&&
526 bucket
<= TH_BUCKET_SHARE_BG
);
528 hw_atomic_add(&sched_run_buckets
[bucket
], 1);
532 sched_decr_bucket(sched_bucket_t bucket
)
534 assert(bucket
>= TH_BUCKET_FIXPRI
&&
535 bucket
<= TH_BUCKET_SHARE_BG
);
537 assert(sched_run_buckets
[bucket
] > 0);
539 hw_atomic_sub(&sched_run_buckets
[bucket
], 1);
542 /* TH_RUN & !TH_IDLE controls whether a thread has a run count */
545 sched_run_incr(thread_t thread
)
547 assert((thread
->state
& (TH_RUN
|TH_IDLE
)) == TH_RUN
);
549 uint32_t new_count
= hw_atomic_add(&sched_run_buckets
[TH_BUCKET_RUN
], 1);
551 sched_incr_bucket(thread
->th_sched_bucket
);
557 sched_run_decr(thread_t thread
)
559 assert((thread
->state
& (TH_RUN
|TH_IDLE
)) != TH_RUN
);
561 sched_decr_bucket(thread
->th_sched_bucket
);
563 uint32_t new_count
= hw_atomic_sub(&sched_run_buckets
[TH_BUCKET_RUN
], 1);
569 sched_update_thread_bucket(thread_t thread
)
571 sched_bucket_t old_bucket
= thread
->th_sched_bucket
;
572 sched_bucket_t new_bucket
= TH_BUCKET_RUN
;
574 switch (thread
->sched_mode
) {
576 case TH_MODE_REALTIME
:
577 new_bucket
= TH_BUCKET_FIXPRI
;
580 case TH_MODE_TIMESHARE
:
581 if (thread
->base_pri
> BASEPRI_UTILITY
)
582 new_bucket
= TH_BUCKET_SHARE_FG
;
583 else if (thread
->base_pri
> MAXPRI_THROTTLE
)
584 new_bucket
= TH_BUCKET_SHARE_UT
;
586 new_bucket
= TH_BUCKET_SHARE_BG
;
590 panic("unexpected mode: %d", thread
->sched_mode
);
594 if (old_bucket
!= new_bucket
) {
595 thread
->th_sched_bucket
= new_bucket
;
596 thread
->pri_shift
= sched_pri_shifts
[new_bucket
];
598 if ((thread
->state
& (TH_RUN
|TH_IDLE
)) == TH_RUN
) {
599 sched_decr_bucket(old_bucket
);
600 sched_incr_bucket(new_bucket
);
606 * Set the thread's true scheduling mode
607 * Called with thread mutex and thread locked
608 * The thread has already been removed from the runqueue.
610 * (saved_mode is handled before this point)
613 sched_set_thread_mode(thread_t thread
, sched_mode_t new_mode
)
615 assert(thread
->runq
== PROCESSOR_NULL
);
619 case TH_MODE_REALTIME
:
620 case TH_MODE_TIMESHARE
:
624 panic("unexpected mode: %d", new_mode
);
628 thread
->sched_mode
= new_mode
;
630 sched_update_thread_bucket(thread
);
634 * Demote the true scheduler mode to timeshare (called with the thread locked)
637 sched_thread_mode_demote(thread_t thread
, uint32_t reason
)
639 assert(reason
& TH_SFLAG_DEMOTED_MASK
);
640 assert((thread
->sched_flags
& reason
) != reason
);
642 if (thread
->policy_reset
)
645 if (thread
->sched_flags
& TH_SFLAG_DEMOTED_MASK
) {
646 /* Another demotion reason is already active */
647 thread
->sched_flags
|= reason
;
651 assert(thread
->saved_mode
== TH_MODE_NONE
);
653 boolean_t removed
= thread_run_queue_remove(thread
);
655 thread
->sched_flags
|= reason
;
657 thread
->saved_mode
= thread
->sched_mode
;
659 sched_set_thread_mode(thread
, TH_MODE_TIMESHARE
);
661 thread_recompute_priority(thread
);
664 thread_run_queue_reinsert(thread
, SCHED_TAILQ
);
668 * Un-demote the true scheduler mode back to the saved mode (called with the thread locked)
671 sched_thread_mode_undemote(thread_t thread
, uint32_t reason
)
673 assert(reason
& TH_SFLAG_DEMOTED_MASK
);
674 assert((thread
->sched_flags
& reason
) == reason
);
675 assert(thread
->saved_mode
!= TH_MODE_NONE
);
676 assert(thread
->sched_mode
== TH_MODE_TIMESHARE
);
677 assert(thread
->policy_reset
== 0);
679 thread
->sched_flags
&= ~reason
;
681 if (thread
->sched_flags
& TH_SFLAG_DEMOTED_MASK
) {
682 /* Another demotion reason is still active */
686 boolean_t removed
= thread_run_queue_remove(thread
);
688 sched_set_thread_mode(thread
, thread
->saved_mode
);
690 thread
->saved_mode
= TH_MODE_NONE
;
692 thread_recompute_priority(thread
);
695 thread_run_queue_reinsert(thread
, SCHED_TAILQ
);