xref: /xnu-12377.41.6/osfmk/kern/sched_prim.h (revision bbb1b6f9e71b8cdde6e5cd6f4841f207dee3d828)
1 /*
2  * Copyright (c) 2000-2012 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
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.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
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.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /*
29  * @OSF_COPYRIGHT@
30  */
31 /*
32  * Mach Operating System
33  * Copyright (c) 1991,1990,1989,1988,1987 Carnegie Mellon University
34  * All Rights Reserved.
35  *
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.
41  *
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.
45  *
46  * Carnegie Mellon requests users of this software to return to
47  *
48  *  Software Distribution Coordinator  or  [email protected]
49  *  School of Computer Science
50  *  Carnegie Mellon University
51  *  Pittsburgh PA 15213-3890
52  *
53  * any improvements or extensions that they make and grant Carnegie Mellon
54  * the rights to redistribute these changes.
55  */
56 /*
57  */
58 /*
59  *	File:	sched_prim.h
60  *	Author:	David Golub
61  *
62  *	Scheduling primitive definitions file
63  *
64  */
65 
66 #ifndef _KERN_SCHED_PRIM_H_
67 #define _KERN_SCHED_PRIM_H_
68 
69 #include <sys/cdefs.h>
70 #include <mach/boolean.h>
71 #include <mach/machine/vm_types.h>
72 #include <mach/kern_return.h>
73 #include <kern/clock.h>
74 #include <kern/kern_types.h>
75 #include <kern/percpu.h>
76 #include <kern/thread.h>
77 #include <kern/block_hint.h>
78 
79 extern int              thread_get_current_cpuid(void);
80 
81 #if XNU_KERNEL_PRIVATE
82 
83 /*
84  * The quantum length used for Fixed and RT sched modes. In general the quantum
85  * can vary - for example for background or QOS.
86  */
87 uint64_t sched_get_quantum_us(void);
88 
89 #endif /* XNU_KERNEL_PRIVATE */
90 
91 #if defined(MACH_KERNEL_PRIVATE) || SCHED_TEST_HARNESS
92 
93 #include <kern/sched_urgency.h>
94 #include <kern/thread_group.h>
95 #include <kern/waitq.h>
96 
97 /* Initialization */
98 extern void             sched_init(void);
99 
100 extern void             sched_startup(void);
101 
102 extern void             sched_timebase_init(void);
103 
104 extern bool             processor_is_fast_track_candidate_for_realtime_thread(processor_set_t pset, processor_t processor);
105 
106 extern void             sched_check_spill(processor_set_t pset, thread_t thread);
107 
108 extern bool             sched_thread_should_yield(processor_t processor, thread_t thread);
109 
110 extern bool             sched_steal_thread_DISABLED(processor_set_t pset);
111 extern bool             sched_steal_thread_enabled(processor_set_t pset);
112 
113 /* Force a preemption point for a thread and wait for it to stop running */
114 extern boolean_t        thread_stop(
115 	thread_t        thread,
116 	boolean_t       until_not_runnable);
117 
118 /* Release a previous stop request */
119 extern void                     thread_unstop(
120 	thread_t        thread);
121 
122 /* Wait for a thread to stop running */
123 extern void                     thread_wait(
124 	thread_t        thread,
125 	boolean_t       until_not_runnable);
126 
127 /* Unblock thread on wake up */
128 extern boolean_t        thread_unblock(
129 	thread_t                thread,
130 	wait_result_t   wresult);
131 
132 /* Unblock and dispatch thread */
133 extern void thread_go(
134 	thread_t                thread,
135 	wait_result_t           wresult,
136 	bool                    try_handoff);
137 
138 /* Check if direct handoff is allowed */
139 extern boolean_t
140 thread_allowed_for_handoff(
141 	thread_t         thread);
142 
143 /* Handle threads at context switch */
144 extern void                     thread_dispatch(
145 	thread_t                old_thread,
146 	thread_t                new_thread);
147 
148 /* Switch directly to a particular thread */
149 extern int                      thread_run(
150 	thread_t                        self,
151 	thread_continue_t       continuation,
152 	void                            *parameter,
153 	thread_t                        new_thread);
154 
155 /* Resume thread with new stack */
156 extern __dead2 void     thread_continue(thread_t old_thread);
157 
158 /* Invoke continuation */
159 extern __dead2 void     call_continuation(
160 	thread_continue_t       continuation,
161 	void                    *parameter,
162 	wait_result_t           wresult,
163 	boolean_t               enable_interrupts);
164 
165 /*
166  * Flags that can be passed to set_sched_pri
167  * to skip side effects
168  */
169 __options_decl(set_sched_pri_options_t, uint32_t, {
170 	SETPRI_DEFAULT  = 0x0,
171 	SETPRI_LAZY     = 0x1,  /* Avoid setting AST flags or sending IPIs */
172 });
173 
174 /* Set the current scheduled priority */
175 extern void set_sched_pri(
176 	thread_t      thread,
177 	int16_t       priority,
178 	set_sched_pri_options_t options);
179 
180 /* Set base priority of the specified thread */
181 extern void             sched_set_thread_base_priority(
182 	thread_t                thread,
183 	int                             priority);
184 
185 /* Set absolute base priority of the specified thread */
186 extern void             sched_set_kernel_thread_priority(
187 	thread_t                thread,
188 	int                             priority);
189 
190 
191 /* Set the thread's true scheduling mode */
192 extern void             sched_set_thread_mode(thread_t thread,
193     sched_mode_t mode);
194 
195 /*
196  * Set the thread's scheduling mode taking into account that the thread may have
197  * been demoted.
198  * */
199 extern void             sched_set_thread_mode_user(thread_t thread,
200     sched_mode_t mode);
201 
202 /*
203  * Get the thread's scheduling mode taking into account that the thread may have
204  * been demoted.
205  * */
206 extern sched_mode_t     sched_get_thread_mode_user(thread_t thread);
207 
208 
209 /* Demote the true scheduler mode */
210 extern void             sched_thread_mode_demote(thread_t thread,
211     uint32_t reason);
212 /* Un-demote the true scheduler mode */
213 extern void             sched_thread_mode_undemote(thread_t thread,
214     uint32_t reason);
215 /* Check for a specific demotion */
216 extern bool             sched_thread_mode_has_demotion(thread_t thread,
217     uint32_t reason);
218 
219 extern void sched_thread_promote_reason(thread_t thread, uint32_t reason, uintptr_t trace_obj);
220 extern void sched_thread_unpromote_reason(thread_t thread, uint32_t reason, uintptr_t trace_obj);
221 
222 /* Re-evaluate base priority of thread (thread locked) */
223 void thread_recompute_priority(thread_t thread);
224 
225 /* Re-evaluate scheduled priority of thread (thread locked) */
226 extern void thread_recompute_sched_pri(
227 	thread_t thread,
228 	set_sched_pri_options_t options);
229 
230 /* Periodic scheduler activity */
231 extern void             sched_init_thread(void);
232 
233 /* Perform sched_tick housekeeping activities */
234 extern boolean_t                can_update_priority(
235 	thread_t                thread);
236 
237 extern void             update_priority(
238 	thread_t                thread);
239 
240 extern void             lightweight_update_priority(
241 	thread_t                thread);
242 
243 extern void             sched_default_quantum_expire(thread_t thread);
244 
245 /* Idle processor thread continuation */
246 extern void             idle_thread(
247 	void*           parameter,
248 	wait_result_t   result);
249 
250 extern void idle_thread_create(
251 	processor_t             processor,
252 	thread_continue_t       continuation);
253 
254 /* Continuation return from syscall */
255 extern void     thread_syscall_return(
256 	kern_return_t   ret);
257 
258 /* Context switch */
259 extern wait_result_t    thread_block_reason(
260 	thread_continue_t       continuation,
261 	void                            *parameter,
262 	ast_t                           reason);
263 
264 __options_decl(sched_options_t, uint32_t, {
265 	SCHED_NONE      = 0x0,
266 	SCHED_TAILQ     = 0x1,
267 	SCHED_HEADQ     = 0x2,
268 	SCHED_PREEMPT   = 0x4,
269 	SCHED_REBALANCE = 0x8,
270 	SCHED_STIR_POT  = 0x10,
271 });
272 
273 /* Reschedule thread for execution */
274 extern void             thread_setrun(
275 	thread_t        thread,
276 	sched_options_t options);
277 
278 extern processor_set_t  task_choose_pset(
279 	task_t                  task);
280 
281 /* Bind the current thread to a particular processor */
282 extern processor_t      thread_bind(
283 	processor_t             processor);
284 
285 extern void             thread_bind_during_wakeup(
286 	thread_t                thread,
287 	processor_t             processor);
288 
289 extern void             thread_unbind_after_queue_shutdown(
290 	thread_t                thread,
291 	processor_t             processor);
292 
293 extern bool pset_has_stealable_threads(
294 	processor_set_t         pset);
295 
296 extern processor_set_t choose_starting_pset(
297 	pset_node_t  node,
298 	thread_t     thread,
299 	processor_t *processor_hint);
300 
301 extern int pset_available_cpu_count(
302 	processor_set_t pset);
303 
304 extern bool pset_is_recommended(
305 	processor_set_t pset);
306 
307 extern bool pset_type_is_recommended(
308 	processor_set_t pset);
309 
310 extern pset_node_t sched_choose_node(
311 	thread_t     thread);
312 
313 #if CONFIG_SCHED_SMT
314 extern processor_t      choose_processor_smt(
315 	processor_set_t                pset,
316 	processor_t                    processor,
317 	thread_t                       thread,
318 	sched_options_t               *options);
319 #else /* !CONFIG_SCHED_SMT */
320 /* Choose the best processor to run a thread */
321 extern processor_t      choose_processor(
322 	processor_set_t                pset,
323 	processor_t                    processor,
324 	thread_t                       thread,
325 	sched_options_t               *options);
326 #endif /* !CONFIG_SCHED_SMT */
327 
328 extern bool sched_SMT_balance(
329 	processor_t processor,
330 	processor_set_t pset);
331 
332 extern void thread_quantum_init(
333 	thread_t thread,
334 	uint64_t now);
335 
336 
337 extern void             run_queue_init(
338 	run_queue_t             runq);
339 
340 extern thread_t run_queue_dequeue(
341 	run_queue_t           runq,
342 	sched_options_t       options);
343 
344 extern boolean_t        run_queue_enqueue(
345 	run_queue_t           runq,
346 	thread_t              thread,
347 	sched_options_t       options);
348 
349 extern void     run_queue_remove(
350 	run_queue_t            runq,
351 	thread_t                       thread);
352 
353 extern thread_t run_queue_peek(
354 	run_queue_t            runq);
355 
356 struct sched_update_scan_context {
357 	uint64_t        earliest_bg_make_runnable_time;
358 	uint64_t        earliest_normal_make_runnable_time;
359 	uint64_t        earliest_rt_make_runnable_time;
360 	uint64_t        sched_tick_last_abstime;
361 };
362 typedef struct sched_update_scan_context *sched_update_scan_context_t;
363 
364 
365 extern void sched_pset_made_schedulable(
366 	processor_t processor,
367 	processor_set_t pset,
368 	boolean_t drop_lock);
369 
370 extern void sched_cpu_init_completed(void);
371 
372 /*
373  * Enum to define various events which need IPIs. The IPI policy
374  * engine decides what kind of IPI to use based on destination
375  * processor state, thread and one of the following scheduling events.
376  */
377 typedef enum {
378 	SCHED_IPI_EVENT_BOUND_THR   = 0x1,
379 	SCHED_IPI_EVENT_PREEMPT     = 0x2,
380 	SCHED_IPI_EVENT_SMT_REBAL   = 0x3,
381 	SCHED_IPI_EVENT_SPILL       = 0x4,
382 	SCHED_IPI_EVENT_REBALANCE   = 0x5,
383 	SCHED_IPI_EVENT_RT_PREEMPT  = 0x6,
384 } sched_ipi_event_t;
385 
386 
387 /* Enum to define various IPI types used by the scheduler */
388 typedef enum {
389 	SCHED_IPI_NONE              = 0x0,
390 	SCHED_IPI_IMMEDIATE         = 0x1,
391 	SCHED_IPI_IDLE              = 0x2,
392 	SCHED_IPI_DEFERRED          = 0x3,
393 } sched_ipi_type_t;
394 
395 /* The IPI policy engine behaves in the following manner:
396  * - All scheduler events which need an IPI invoke sched_ipi_action() with
397  *   the appropriate destination processor, thread and event.
398  * - sched_ipi_action() performs basic checks, invokes the scheduler specific
399  *   ipi_policy routine and sets pending_AST bits based on the result.
400  * - Once the pset lock is dropped, the scheduler invokes sched_ipi_perform()
401  *   routine which actually sends the appropriate IPI to the destination core.
402  */
403 extern sched_ipi_type_t sched_ipi_action(processor_t dst, thread_t thread, sched_ipi_event_t event);
404 extern void sched_ipi_perform(processor_t dst, sched_ipi_type_t ipi);
405 
406 /* sched_ipi_policy() is the global default IPI policy for all schedulers */
407 extern sched_ipi_type_t sched_ipi_policy(processor_t dst, thread_t thread,
408     boolean_t dst_idle, sched_ipi_event_t event);
409 
410 /* sched_ipi_deferred_policy() is the global default deferred IPI policy for all schedulers */
411 extern sched_ipi_type_t sched_ipi_deferred_policy(processor_set_t pset,
412     processor_t dst, thread_t thread, sched_ipi_event_t event);
413 
414 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
415 
416 extern boolean_t        thread_update_add_thread(thread_t thread);
417 extern void             thread_update_process_threads(void);
418 extern boolean_t        runq_scan(run_queue_t runq, sched_update_scan_context_t scan_context);
419 
420 #if CONFIG_SCHED_CLUTCH
421 extern boolean_t        sched_clutch_timeshare_scan(queue_t thread_queue, uint16_t count, sched_update_scan_context_t scan_context);
422 #endif /* CONFIG_SCHED_CLUTCH */
423 
424 extern void sched_timeshare_init(void);
425 extern void sched_timeshare_timebase_init(void);
426 extern void sched_timeshare_maintenance_continue(void);
427 
428 
429 
430 extern boolean_t priority_is_urgent(int priority);
431 extern uint32_t sched_timeshare_initial_quantum_size(thread_t thread);
432 
433 extern int sched_compute_timeshare_priority(thread_t thread);
434 
435 #endif /* CONFIG_SCHED_TIMESHARE_CORE */
436 
437 /* Remove thread from its run queue */
438 extern boolean_t        thread_run_queue_remove(thread_t thread);
439 thread_t thread_run_queue_remove_for_handoff(thread_t thread);
440 
441 /* Put a thread back in the run queue after being yanked */
442 extern void thread_run_queue_reinsert(thread_t thread, sched_options_t options);
443 
444 extern void             thread_timer_expire(
445 	void                    *thread,
446 	void                    *p1);
447 
448 extern bool thread_is_eager_preempt(thread_t thread);
449 
450 extern boolean_t sched_generic_direct_dispatch_to_idle_processors;
451 
452 /* Set the maximum interrupt level for the thread */
453 __private_extern__ wait_interrupt_t thread_interrupt_level(
454 	wait_interrupt_t interruptible);
455 
456 __private_extern__ wait_result_t thread_mark_wait_locked(
457 	thread_t                 thread,
458 	wait_interrupt_t interruptible);
459 
460 /* Wake up locked thread directly, passing result */
461 __private_extern__ kern_return_t clear_wait_internal(
462 	thread_t                thread,
463 	wait_result_t   result);
464 
465 struct sched_statistics {
466 	uint32_t        csw_count;
467 	uint32_t        preempt_count;
468 	uint32_t        preempted_rt_count;
469 	uint32_t        preempted_by_rt_count;
470 	uint32_t        rt_sched_count;
471 	uint32_t        interrupt_count;
472 	uint32_t        ipi_count;
473 	uint32_t        timer_pop_count;
474 	uint32_t        idle_transitions;
475 	uint32_t        quantum_timer_expirations;
476 };
477 PERCPU_DECL(struct sched_statistics, sched_stats);
478 extern bool             sched_stats_active;
479 
480 extern void sched_stats_handle_csw(
481 	processor_t processor,
482 	int reasons,
483 	int selfpri,
484 	int otherpri);
485 
486 extern void sched_stats_handle_runq_change(
487 	struct runq_stats *stats,
488 	int old_count);
489 
490 #define SCHED_STATS_INC(field)                                                  \
491 MACRO_BEGIN                                                                     \
492 	if (__improbable(sched_stats_active)) {                                 \
493 	        PERCPU_GET(sched_stats)->field++;                               \
494 	}                                                                       \
495 MACRO_END
496 
497 #if DEBUG
498 
499 #define SCHED_STATS_CSW(processor, reasons, selfpri, otherpri)                  \
500 MACRO_BEGIN                                                                     \
501 	if (__improbable(sched_stats_active)) {                                 \
502 	        sched_stats_handle_csw((processor),                             \
503 	            (reasons), (selfpri), (otherpri));                          \
504 	}                                                                       \
505 MACRO_END
506 
507 
508 #define SCHED_STATS_RUNQ_CHANGE(stats, old_count)                               \
509 MACRO_BEGIN                                                                     \
510 	if (__improbable(sched_stats_active)) {                                 \
511 	        sched_stats_handle_runq_change((stats), (old_count));           \
512 	}                                                                       \
513 MACRO_END
514 
515 #else /* DEBUG */
516 
517 #define SCHED_STATS_CSW(processor, reasons, selfpri, otherpri) do { }while(0)
518 #define SCHED_STATS_RUNQ_CHANGE(stats, old_count) do { }while(0)
519 
520 #endif /* DEBUG */
521 
522 extern uint32_t sched_debug_flags;
523 #define SCHED_DEBUG_FLAG_PLATFORM_TRACEPOINTS           0x00000001
524 #define SCHED_DEBUG_FLAG_CHOOSE_PROCESSOR_TRACEPOINTS   0x00000002
525 #define SCHED_DEBUG_FLAG_AST_CHECK_TRACEPOINTS   0x00000004
526 
527 #define SCHED_DEBUG_PLATFORM_KERNEL_DEBUG_CONSTANT(...)                         \
528 MACRO_BEGIN                                                                     \
529 	if (__improbable(sched_debug_flags &                                    \
530 	    SCHED_DEBUG_FLAG_PLATFORM_TRACEPOINTS)) {                           \
531 	        KERNEL_DEBUG_CONSTANT(__VA_ARGS__);                             \
532 	}                                                                       \
533 MACRO_END
534 
535 #define SCHED_DEBUG_CHOOSE_PROCESSOR_KERNEL_DEBUG_CONSTANT_IST(...)             \
536 MACRO_BEGIN                                                                     \
537 	if (__improbable(sched_debug_flags &                                    \
538 	    SCHED_DEBUG_FLAG_CHOOSE_PROCESSOR_TRACEPOINTS)) {                   \
539 	        KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE, __VA_ARGS__);           \
540 	}                                                                       \
541 MACRO_END
542 
543 #define SCHED_DEBUG_AST_CHECK_KDBG_RELEASE(...)                                 \
544 MACRO_BEGIN                                                                     \
545 	if (__improbable(sched_debug_flags &                                    \
546 	    SCHED_DEBUG_FLAG_AST_CHECK_TRACEPOINTS)) {                          \
547 	        KDBG_RELEASE(__VA_ARGS__);                                      \
548 	}                                                                       \
549 MACRO_END
550 
551 
552 /* Tells if there are "active" RT threads in the system (provided by CPU PM) */
553 extern void     active_rt_threads(
554 	boolean_t       active);
555 
556 /* Returns the perfcontrol attribute for the thread */
557 extern perfcontrol_class_t thread_get_perfcontrol_class(
558 	thread_t        thread);
559 
560 /* Generic routine for Non-AMP schedulers to calculate parallelism */
561 extern uint32_t sched_qos_max_parallelism(int qos, uint64_t options);
562 
563 extern void check_monotonic_time(uint64_t ctime);
564 
565 #endif /* defined(MACH_KERNEL_PRIVATE) || SCHED_TEST_HARNESS */
566 
567 __BEGIN_DECLS
568 
569 #ifdef  XNU_KERNEL_PRIVATE
570 
571 extern kern_return_t thread_soft_bind_cluster_type(thread_t, char cluster_type);
572 
573 __options_decl(thread_bind_option_t, uint64_t, {
574 	/* Unbind a previously cluster bound thread */
575 	THREAD_UNBIND                   = 0x1,
576 	/*
577 	 * Bind thread to the cluster only if it is eligible to run on that cluster. If
578 	 * the thread is not eligible to run on the cluster, thread_soft_bind_cluster_id()
579 	 * returns KERN_INVALID_POLICY.
580 	 */
581 	THREAD_BIND_ELIGIBLE_ONLY       = 0x2,
582 });
583 extern kern_return_t thread_soft_bind_cluster_id(thread_t thread, uint32_t cluster_id, thread_bind_option_t options);
584 
585 extern int sched_get_rt_n_backup_processors(void);
586 extern void sched_set_rt_n_backup_processors(int n);
587 
588 extern int sched_get_rt_deadline_epsilon(void);
589 extern void sched_set_rt_deadline_epsilon(int new_epsilon_us);
590 
591 /* Toggles a global override to turn off CPU Throttling */
592 extern void     sys_override_cpu_throttle(boolean_t enable_override);
593 
594 extern int sched_get_powered_cores(void);
595 extern void sched_set_powered_cores(int n);
596 
597 uint64_t sched_sysctl_get_recommended_cores(void);
598 
599 /*
600  ****************** Only exported until BSD stops using ********************
601  */
602 
603 extern void                     thread_vm_bind_group_add(void);
604 
605 /* Wake up thread directly, passing result */
606 extern kern_return_t clear_wait(
607 	thread_t                thread,
608 	wait_result_t   result);
609 
610 /* Start thread running */
611 extern void             thread_bootstrap_return(void) __attribute__((noreturn));
612 
613 /* Return from exception (BSD-visible interface) */
614 extern void             thread_exception_return(void) __dead2;
615 
616 #define SCHED_STRING_MAX_LENGTH (48)
617 /* String declaring the name of the current scheduler */
618 extern char sched_string[SCHED_STRING_MAX_LENGTH];
619 
620 __options_decl(thread_handoff_option_t, uint32_t, {
621 	THREAD_HANDOFF_NONE          = 0,
622 	THREAD_HANDOFF_SETRUN_NEEDED = 0x1,
623 });
624 
625 /* Remove thread from its run queue */
626 thread_t thread_prepare_for_handoff(thread_t thread, thread_handoff_option_t option);
627 
628 /* Attempt to context switch to a specific runnable thread */
629 extern wait_result_t thread_handoff_deallocate(thread_t thread, thread_handoff_option_t option);
630 
631 __attribute__((nonnull(2)))
632 extern void thread_handoff_parameter(thread_t thread,
633     thread_continue_t continuation, void *parameter, thread_handoff_option_t) __dead2;
634 
635 extern struct waitq     *assert_wait_queue(event_t event);
636 
637 /*
638  * sched_cond_t:
639  *
640  * A atomic condition variable used to synchronize wake/block operations on threads.
641  * Bits defined below are reserved for use by sched_prim. Remaining
642  * bits may be used by caller for additional synchronization semantics.
643  */
644 __options_decl(sched_cond_t, uint32_t, {
645 	SCHED_COND_INIT = 0x0000,    /* initialize all bits to zero (inactive and not awoken) */
646 	SCHED_COND_ACTIVE = 0x0001,  /* target thread is active */
647 	SCHED_COND_WAKEUP = 0x0002   /* wakeup has been issued for target thread */
648 });
649 typedef _Atomic sched_cond_t sched_cond_atomic_t;
650 
651 /*
652  * sched_cond_init:
653  *
654  * Initialize an atomic condition variable. Note that this does not occur atomically and should be
655  * performed during thread initialization, before the condition is observable by other threads.
656  */
657 extern void sched_cond_init(
658 	sched_cond_atomic_t *cond);
659 
660 /*
661  * sched_cond_signal:
662  *
663  * Wakeup the specified thread if it is waiting on this event and it has not already been issued a wakeup.
664  *
665  * parameters:
666  *      thread    thread to awaken
667  *      cond      atomic condition variable
668  */
669 extern kern_return_t sched_cond_signal(
670 	sched_cond_atomic_t *cond,
671 	thread_t thread);
672 
673 /*
674  * sched_cond_wait_parameter:
675  *
676  * Assert wait and block on cond if no wakeup has been issued.
677  * If a wakeup has been issued on cond since the last `sched_cond_ack`, clear_wait and
678  * return `THREAD_AWAKENED`.
679  *
680  * `sched_cond_wait_parameter` must be paired with `sched_cond_ack`.
681  *
682  * NOTE: `continuation` will only be jumped to if a wakeup has not been issued
683  *
684  * parameters:
685  *      cond             atomic condition variable to synchronize on
686  *      interruptible    interruptible value to pass to assert_wait
687  *      continuation     continuation if block succeeds
688  *      parameter
689  */
690 extern wait_result_t sched_cond_wait_parameter(
691 	sched_cond_atomic_t *cond,
692 	wait_interrupt_t interruptible,
693 	thread_continue_t continuation,
694 	void *parameter);
695 
696 /*
697  * sched_cond_wait:
698  *
699  * Assert wait and block on cond if no wakeup has been issued.
700  * If a wakeup has been issued on cond since the last `sched_cond_ack`, clear_wait and
701  * return `THREAD_AWAKENED`.
702  *
703  * `sched_cond_wait` must be paired with `sched_cond_ack`.
704  *
705  * NOTE: `continuation` will only be jumped to if a wakeup has not been issued
706  *
707  * parameters:
708  *      cond             atomic condition variable to synchronize on
709  *      interruptible    interruptible value to pass to assert_wait
710  *      continuation     continuation if block succeeds
711  */
712 extern wait_result_t sched_cond_wait(
713 	sched_cond_atomic_t *cond,
714 	wait_interrupt_t interruptible,
715 	thread_continue_t continuation);
716 
717 /*
718  * sched_cond_ack:
719  *
720  * Acknowledge an issued wakeup by clearing WAKEUP and setting ACTIVE (via XOR).
721  * It is the callers responsibility to ensure that the ACTIVE bit is always low prior to calling
722  * (i.e. by calling `sched_cond_wait` prior to any rerun or block).
723  * Synchronization schemes that allow for WAKEUP bit to be reset prior to wakeup
724  * (e.g. a cancellation mechanism) should check that WAKEUP was indeed cleared.
725  *
726  * e.g.
727  * ```
728  * if (sched_cond_ack(&my_state) & SCHED_THREAD_WAKEUP) {
729  *     // WAKEUP bit was no longer set by the time this thread woke up
730  *     do_cancellation_policy();
731  * }
732  * ```
733  *
734  * parameters:
735  *      cond:    atomic condition variable
736  */
737 extern sched_cond_t sched_cond_ack(
738 	sched_cond_atomic_t *cond);
739 
740 #endif  /* XNU_KERNEL_PRIVATE */
741 
742 #if defined(KERNEL_PRIVATE) || SCHED_TEST_HARNESS
743 /* Set pending block hint for a particular object before we go into a wait state */
744 extern void             thread_set_pending_block_hint(
745 	thread_t                        thread,
746 	block_hint_t                    block_hint);
747 
748 #define QOS_PARALLELISM_COUNT_LOGICAL   0x1
749 #define QOS_PARALLELISM_REALTIME        0x2
750 #define QOS_PARALLELISM_CLUSTER_SHARED_RESOURCE              0x4
751 
752 extern uint32_t qos_max_parallelism(int qos, uint64_t options);
753 #endif /* defined(KERNEL_PRIVATE) || SCHED_TEST_HARNESS */
754 
755 #if XNU_KERNEL_PRIVATE
756 extern void             thread_yield_with_continuation(
757 	thread_continue_t       continuation,
758 	void                            *parameter) __dead2;
759 #endif /* XNU_KERNEL_PRIVATE */
760 
761 /* Context switch */
762 extern wait_result_t    thread_block(
763 	thread_continue_t       continuation);
764 
765 extern wait_result_t    thread_block_parameter(
766 	thread_continue_t       continuation,
767 	void                            *parameter);
768 
769 /* Declare thread will wait on a particular event */
770 extern wait_result_t    assert_wait(
771 	event_t                         event,
772 	wait_interrupt_t        interruptible);
773 
774 /* Assert that the thread intends to wait with a timeout */
775 extern wait_result_t    assert_wait_timeout(
776 	event_t                         event,
777 	wait_interrupt_t        interruptible,
778 	uint32_t                        interval,
779 	uint32_t                        scale_factor);
780 
781 /* Assert that the thread intends to wait with an urgency, timeout and leeway */
782 extern wait_result_t    assert_wait_timeout_with_leeway(
783 	event_t                         event,
784 	wait_interrupt_t        interruptible,
785 	wait_timeout_urgency_t  urgency,
786 	uint32_t                        interval,
787 	uint32_t                        leeway,
788 	uint32_t                        scale_factor);
789 
790 extern wait_result_t    assert_wait_deadline(
791 	event_t                         event,
792 	wait_interrupt_t        interruptible,
793 	uint64_t                        deadline);
794 
795 /* Assert that the thread intends to wait with an urgency, deadline, and leeway */
796 extern wait_result_t    assert_wait_deadline_with_leeway(
797 	event_t                         event,
798 	wait_interrupt_t        interruptible,
799 	wait_timeout_urgency_t  urgency,
800 	uint64_t                        deadline,
801 	uint64_t                        leeway);
802 
803 
804 /* Wake up thread (or threads) waiting on a particular event */
805 extern kern_return_t    thread_wakeup_prim(
806 	event_t                         event,
807 	boolean_t                       one_thread,
808 	wait_result_t                   result);
809 
810 /* Wake up up to given number of threads waiting on a particular event */
811 extern kern_return_t    thread_wakeup_nthreads_prim(
812 	event_t                         event,
813 	uint32_t                        nthreads,
814 	wait_result_t                   result);
815 
816 #define thread_wakeup(x) \
817 	thread_wakeup_prim((x), FALSE, THREAD_AWAKENED)
818 #define thread_wakeup_with_result(x, z) \
819 	thread_wakeup_prim((x), FALSE, (z))
820 #define thread_wakeup_one(x) \
821 	thread_wakeup_prim((x), TRUE, THREAD_AWAKENED)
822 
823 #define thread_wakeup_nthreads(x, nthreads) \
824 	thread_wakeup_nthreads_prim((x), (nthreads), THREAD_AWAKENED)
825 #define thread_wakeup_nthreads_with_result(x, nthreads, z) \
826 	thread_wakeup_nthreads_prim((x), (nthreads), (z))
827 
828 /* Wakeup the specified thread if it is waiting on this event */
829 extern kern_return_t thread_wakeup_thread(event_t event, thread_t thread);
830 
831 extern boolean_t preemption_enabled(void);
832 
833 #if defined(MACH_KERNEL_PRIVATE) || SCHED_TEST_HARNESS
834 
835 
836 #if   !CONFIG_SCHED_TIMESHARE_CORE && !CONFIG_SCHED_CLUTCH && !CONFIG_SCHED_EDGE
837 #error Enable at least one scheduler algorithm in osfmk/conf/MASTER.XXX
838 #endif
839 
840 /*
841  * The scheduling policy is fixed at compile-time, in order to save the performance
842  * cost of function pointer indirection that we would otherwise pay each time when
843  * making a policy-specific callout.
844  */
845 #if __AMP__
846 
847 #if CONFIG_SCHED_EDGE
848 extern const struct sched_dispatch_table sched_edge_dispatch;
849 #define SCHED(f) (sched_edge_dispatch.f)
850 #else /* CONFIG_SCHED_EDGE */
851 extern const struct sched_dispatch_table sched_amp_dispatch;
852 #define SCHED(f) (sched_amp_dispatch.f)
853 #endif /* CONFIG_SCHED_EDGE */
854 
855 #else /* __AMP__ */
856 
857 #if CONFIG_SCHED_CLUTCH
858 extern const struct sched_dispatch_table sched_clutch_dispatch;
859 #define SCHED(f) (sched_clutch_dispatch.f)
860 #else /* CONFIG_SCHED_CLUTCH */
861 extern const struct sched_dispatch_table sched_dualq_dispatch;
862 #define SCHED(f) (sched_dualq_dispatch.f)
863 #endif /* CONFIG_SCHED_CLUTCH */
864 
865 #endif /* __AMP__ */
866 
867 struct sched_dispatch_table {
868 	const char *sched_name;
869 	void    (*init)(void);                          /* Init global state */
870 	void    (*timebase_init)(void);         /* Timebase-dependent initialization */
871 	void    (*processor_init)(processor_t processor);       /* Per-processor scheduler init */
872 	void    (*pset_init)(processor_set_t pset);     /* Per-processor set scheduler init */
873 
874 	void    (*maintenance_continuation)(void);      /* Function called regularly */
875 
876 	/*
877 	 * Choose a thread of greater or equal priority from the per-processor
878 	 * runqueue for timeshare/fixed threads
879 	 */
880 	thread_t        (*choose_thread)(
881 		processor_t           processor,
882 		int                           priority,
883 		thread_t              prev_thread,
884 		ast_t reason);
885 
886 	/* True if scheduler supports stealing threads for this pset */
887 	bool    (*steal_thread_enabled)(processor_set_t pset);
888 
889 	/*
890 	 * Steal a thread from another processor in the pset so that it can run
891 	 * immediately
892 	 */
893 	thread_t        (*steal_thread)(
894 		processor_set_t         pset);
895 
896 	/*
897 	 * Compute priority for a timeshare thread based on base priority.
898 	 */
899 	int (*compute_timeshare_priority)(thread_t thread);
900 
901 	/*
902 	 * Pick the best node for a thread to run on.
903 	 */
904 	pset_node_t (*choose_node)(
905 		thread_t                      thread);
906 
907 	/*
908 	 * Pick the best processor for a thread (any kind of thread) to run on.
909 	 */
910 	processor_t     (*choose_processor)(
911 		processor_set_t                pset,
912 		processor_t                    processor,
913 		thread_t                       thread,
914 		sched_options_t               *options);
915 
916 	/*
917 	 * Enqueue a timeshare or fixed priority thread onto the per-processor
918 	 * runqueue
919 	 */
920 	boolean_t (*processor_enqueue)(
921 		processor_t                    processor,
922 		thread_t                       thread,
923 		sched_options_t                options);
924 
925 	/* Migrate threads away in preparation for processor shutdown */
926 	void (*processor_queue_shutdown)(
927 		processor_t                    processor);
928 
929 	/* Remove the specific thread from the per-processor runqueue */
930 	boolean_t       (*processor_queue_remove)(
931 		processor_t             processor,
932 		thread_t                thread);
933 
934 	/*
935 	 * Does the per-processor runqueue have any timeshare or fixed priority
936 	 * threads on it? Called without pset lock held, so should
937 	 * not assume immutability while executing.
938 	 */
939 	boolean_t       (*processor_queue_empty)(processor_t            processor);
940 
941 	/*
942 	 * Would this priority trigger an urgent preemption if it's sitting
943 	 * on the per-processor runqueue?
944 	 */
945 	boolean_t       (*priority_is_urgent)(int priority);
946 
947 	/*
948 	 * Does the per-processor runqueue contain runnable threads that
949 	 * should cause the currently-running thread to be preempted?
950 	 */
951 	ast_t           (*processor_csw_check)(processor_t processor);
952 
953 	/*
954 	 * Does the per-processor runqueue contain a runnable thread
955 	 * of > or >= priority, as a preflight for choose_thread() or other
956 	 * thread selection
957 	 */
958 	boolean_t       (*processor_queue_has_priority)(processor_t             processor,
959 	    int                             priority,
960 	    boolean_t               gte);
961 
962 	/* Quantum size for the specified non-realtime thread. */
963 	uint32_t        (*initial_quantum_size)(thread_t thread);
964 
965 	/* Scheduler mode for a new thread */
966 	sched_mode_t    (*initial_thread_sched_mode)(task_t parent_task);
967 
968 	/*
969 	 * Is it safe to call update_priority, which may change a thread's
970 	 * runqueue or other state. This can be used to throttle changes
971 	 * to dynamic priority.
972 	 */
973 	boolean_t       (*can_update_priority)(thread_t thread);
974 
975 	/*
976 	 * Update both scheduled priority and other persistent state.
977 	 * Side effects may including migration to another processor's runqueue.
978 	 */
979 	void            (*update_priority)(thread_t thread);
980 
981 	/* Lower overhead update to scheduled priority and state. */
982 	void            (*lightweight_update_priority)(thread_t thread);
983 
984 	/* Callback for non-realtime threads when the quantum timer fires */
985 	void            (*quantum_expire)(thread_t thread);
986 
987 	/*
988 	 * Runnable threads on per-processor runqueue. Should only
989 	 * be used for relative comparisons of load between processors.
990 	 */
991 	int                     (*processor_runq_count)(processor_t     processor);
992 
993 	/* Aggregate runcount statistics for per-processor runqueue */
994 	uint64_t    (*processor_runq_stats_count_sum)(processor_t   processor);
995 
996 	boolean_t       (*processor_bound_count)(processor_t processor);
997 
998 	void            (*thread_update_scan)(sched_update_scan_context_t scan_context);
999 
1000 	/* Supports more than one pset */
1001 	boolean_t   multiple_psets_enabled;
1002 
1003 	/* Supports avoid-processor */
1004 	boolean_t   avoid_processor_enabled;
1005 
1006 	/* Returns true if this processor should avoid running this thread. */
1007 	bool    (*thread_avoid_processor)(processor_t processor, thread_t thread, ast_t reason);
1008 
1009 	/*
1010 	 * Invoked when a processor is about to choose the idle thread
1011 	 * Used to send IPIs to a processor which would be preferred to be idle instead.
1012 	 * Returns true if the current processor should anticipate a quick IPI reply back
1013 	 * from another core.
1014 	 * Called with pset lock held, returns with pset lock unlocked.
1015 	 */
1016 	bool    (*processor_balance)(processor_t processor, processor_set_t pset);
1017 
1018 	processor_t (*rt_choose_processor)(processor_set_t starting_pset, processor_t starting_processor, thread_t thread);
1019 	thread_t    (*rt_steal_thread)(processor_set_t stealing_pset);
1020 	void    (*rt_init_pset)(processor_set_t pset);
1021 	void    (*rt_init_completed)(void);
1022 	void    (*rt_queue_shutdown)(processor_t processor);
1023 	void    (*rt_runq_scan)(sched_update_scan_context_t scan_context);
1024 	int64_t (*rt_runq_count_sum)(void);
1025 
1026 	uint32_t (*qos_max_parallelism)(int qos, uint64_t options);
1027 	void    (*check_spill)(processor_set_t pset, thread_t thread);
1028 	sched_ipi_type_t (*ipi_policy)(processor_t dst, thread_t thread, boolean_t dst_idle, sched_ipi_event_t event);
1029 	bool    (*thread_should_yield)(processor_t processor, thread_t thread);
1030 
1031 	/* Routine to update run counts */
1032 	uint32_t (*run_count_incr)(thread_t thread);
1033 	uint32_t (*run_count_decr)(thread_t thread);
1034 
1035 	/* Routine to update scheduling bucket for a thread */
1036 	void (*update_thread_bucket)(thread_t thread);
1037 
1038 	/* Routine to inform the scheduler when a new pset becomes schedulable */
1039 	void (*pset_made_schedulable)(processor_t processor, processor_set_t pset, boolean_t drop_lock);
1040 #if CONFIG_THREAD_GROUPS
1041 	/* Routine to inform the scheduler when CLPC changes a thread group recommendation */
1042 	void (*thread_group_recommendation_change)(struct thread_group *tg, cluster_type_t new_recommendation);
1043 #endif
1044 	/* Routine to inform the scheduler when all CPUs have finished initializing */
1045 	void (*cpu_init_completed)(void);
1046 	/* Routine to check if a thread is eligible to execute on a specific pset */
1047 	bool (*thread_eligible_for_pset)(thread_t thread, processor_set_t pset);
1048 };
1049 
1050 extern const struct sched_dispatch_table sched_dualq_dispatch;
1051 #if __AMP__
1052 extern const struct sched_dispatch_table sched_amp_dispatch;
1053 #endif
1054 
1055 #if defined(CONFIG_SCHED_CLUTCH)
1056 extern const struct sched_dispatch_table sched_clutch_dispatch;
1057 #endif
1058 
1059 #if defined(CONFIG_SCHED_EDGE)
1060 extern const struct sched_dispatch_table sched_edge_dispatch;
1061 #endif
1062 
1063 extern void sched_set_max_unsafe_rt_quanta(int max);
1064 extern void sched_set_max_unsafe_fixed_quanta(int max);
1065 
1066 #endif  /* defined(MACH_KERNEL_PRIVATE) || SCHED_TEST_HARNESS */
1067 
1068 __END_DECLS
1069 
1070 #endif  /* _KERN_SCHED_PRIM_H_ */
1071