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