2 * Copyright (c) 1993-1995, 1999-2008 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@
29 #include <mach/mach_types.h>
30 #include <mach/thread_act.h>
32 #include <kern/kern_types.h>
33 #include <kern/zalloc.h>
34 #include <kern/sched_prim.h>
35 #include <kern/clock.h>
36 #include <kern/task.h>
37 #include <kern/thread.h>
38 #include <kern/waitq.h>
39 #include <kern/ledger.h>
40 #include <kern/policy_internal.h>
42 #include <vm/vm_pageout.h>
44 #include <kern/thread_call.h>
45 #include <kern/call_entry.h>
46 #include <kern/timer_call.h>
48 #include <libkern/OSAtomic.h>
49 #include <kern/timer_queue.h>
51 #include <sys/kdebug.h>
55 #include <machine/machine_routines.h>
57 static zone_t thread_call_zone
;
58 static struct waitq daemon_waitq
;
64 } thread_call_flavor_t
;
69 TCG_DEALLOC_ACTIVE
= 0x2,
70 } thread_call_group_flags_t
;
72 static struct thread_call_group
{
73 const char * tcg_name
;
75 queue_head_t pending_queue
;
76 uint32_t pending_count
;
78 queue_head_t delayed_queues
[TCF_COUNT
];
79 timer_call_data_t delayed_timers
[TCF_COUNT
];
81 timer_call_data_t dealloc_timer
;
83 struct waitq idle_waitq
;
84 uint32_t idle_count
, active_count
, blocked_count
;
86 uint32_t tcg_thread_pri
;
87 uint32_t target_thread_count
;
88 uint64_t idle_timestamp
;
90 thread_call_group_flags_t flags
;
92 } thread_call_groups
[THREAD_CALL_INDEX_MAX
] = {
93 [THREAD_CALL_INDEX_HIGH
] = {
95 .tcg_thread_pri
= BASEPRI_PREEMPT_HIGH
,
96 .target_thread_count
= 4,
99 [THREAD_CALL_INDEX_KERNEL
] = {
100 .tcg_name
= "kernel",
101 .tcg_thread_pri
= BASEPRI_KERNEL
,
102 .target_thread_count
= 1,
103 .flags
= TCG_PARALLEL
,
105 [THREAD_CALL_INDEX_USER
] = {
107 .tcg_thread_pri
= BASEPRI_DEFAULT
,
108 .target_thread_count
= 1,
109 .flags
= TCG_PARALLEL
,
111 [THREAD_CALL_INDEX_LOW
] = {
113 .tcg_thread_pri
= MAXPRI_THROTTLE
,
114 .target_thread_count
= 1,
115 .flags
= TCG_PARALLEL
,
117 [THREAD_CALL_INDEX_KERNEL_HIGH
] = {
118 .tcg_name
= "kernel-high",
119 .tcg_thread_pri
= BASEPRI_PREEMPT
,
120 .target_thread_count
= 2,
123 [THREAD_CALL_INDEX_QOS_UI
] = {
124 .tcg_name
= "qos-ui",
125 .tcg_thread_pri
= BASEPRI_FOREGROUND
,
126 .target_thread_count
= 1,
129 [THREAD_CALL_INDEX_QOS_IN
] = {
130 .tcg_name
= "qos-in",
131 .tcg_thread_pri
= BASEPRI_USER_INITIATED
,
132 .target_thread_count
= 1,
135 [THREAD_CALL_INDEX_QOS_UT
] = {
136 .tcg_name
= "qos-ut",
137 .tcg_thread_pri
= BASEPRI_UTILITY
,
138 .target_thread_count
= 1,
143 typedef struct thread_call_group
*thread_call_group_t
;
145 #define INTERNAL_CALL_COUNT 768
146 #define THREAD_CALL_DEALLOC_INTERVAL_NS (5 * NSEC_PER_MSEC) /* 5 ms */
147 #define THREAD_CALL_ADD_RATIO 4
148 #define THREAD_CALL_MACH_FACTOR_CAP 3
149 #define THREAD_CALL_GROUP_MAX_THREADS 500
151 static boolean_t thread_call_daemon_awake
;
152 static thread_call_data_t internal_call_storage
[INTERNAL_CALL_COUNT
];
153 static queue_head_t thread_call_internal_queue
;
154 int thread_call_internal_queue_count
= 0;
155 static uint64_t thread_call_dealloc_interval_abs
;
157 static __inline__ thread_call_t
_internal_call_allocate(thread_call_func_t func
, thread_call_param_t param0
);
158 static __inline__
void _internal_call_release(thread_call_t call
);
159 static __inline__ boolean_t
_pending_call_enqueue(thread_call_t call
, thread_call_group_t group
);
160 static boolean_t
_delayed_call_enqueue(thread_call_t call
, thread_call_group_t group
,
161 uint64_t deadline
, thread_call_flavor_t flavor
);
162 static __inline__ boolean_t
_call_dequeue(thread_call_t call
, thread_call_group_t group
);
163 static __inline__
void thread_call_wake(thread_call_group_t group
);
164 static void thread_call_daemon(void *arg
);
165 static void thread_call_thread(thread_call_group_t group
, wait_result_t wres
);
166 static void thread_call_dealloc_timer(timer_call_param_t p0
, timer_call_param_t p1
);
167 static void thread_call_group_setup(thread_call_group_t group
);
168 static void sched_call_thread(int type
, thread_t thread
);
169 static void thread_call_start_deallocate_timer(thread_call_group_t group
);
170 static void thread_call_wait_locked(thread_call_t call
, spl_t s
);
171 static boolean_t
thread_call_wait_once_locked(thread_call_t call
, spl_t s
);
173 static boolean_t
thread_call_enter_delayed_internal(thread_call_t call
,
174 thread_call_func_t alt_func
, thread_call_param_t alt_param0
,
175 thread_call_param_t param1
, uint64_t deadline
,
176 uint64_t leeway
, unsigned int flags
);
178 /* non-static so dtrace can find it rdar://problem/31156135&31379348 */
179 extern void thread_call_delayed_timer(timer_call_param_t p0
, timer_call_param_t p1
);
181 lck_grp_t thread_call_lck_grp
;
182 lck_mtx_t thread_call_lock_data
;
184 #define thread_call_lock_spin() \
185 lck_mtx_lock_spin_always(&thread_call_lock_data)
187 #define thread_call_unlock() \
188 lck_mtx_unlock_always(&thread_call_lock_data)
190 #define tc_deadline tc_call.deadline
192 extern boolean_t mach_timer_coalescing_enabled
;
195 disable_ints_and_lock(void)
197 spl_t s
= splsched();
198 thread_call_lock_spin();
204 enable_ints_and_unlock(spl_t s
)
206 thread_call_unlock();
210 static inline boolean_t
211 group_isparallel(thread_call_group_t group
)
213 return ((group
->flags
& TCG_PARALLEL
) != 0);
217 thread_call_group_should_add_thread(thread_call_group_t group
)
219 if ((group
->active_count
+ group
->blocked_count
+ group
->idle_count
) >= THREAD_CALL_GROUP_MAX_THREADS
) {
220 panic("thread_call group '%s' reached max thread cap (%d): active: %d, blocked: %d, idle: %d",
221 group
->tcg_name
, THREAD_CALL_GROUP_MAX_THREADS
,
222 group
->active_count
, group
->blocked_count
, group
->idle_count
);
225 if (group_isparallel(group
) == FALSE
) {
226 if (group
->pending_count
> 0 && group
->active_count
== 0) {
233 if (group
->pending_count
> 0) {
234 if (group
->idle_count
> 0) {
238 uint32_t thread_count
= group
->active_count
;
241 * Add a thread if either there are no threads,
242 * the group has fewer than its target number of
243 * threads, or the amount of work is large relative
244 * to the number of threads. In the last case, pay attention
245 * to the total load on the system, and back off if
248 if ((thread_count
== 0) ||
249 (thread_count
< group
->target_thread_count
) ||
250 ((group
->pending_count
> THREAD_CALL_ADD_RATIO
* thread_count
) &&
251 (sched_mach_factor
< THREAD_CALL_MACH_FACTOR_CAP
))) {
260 static inline thread_call_group_t
261 thread_call_get_group(thread_call_t call
)
263 thread_call_index_t index
= call
->tc_index
;
265 assert(index
>= 0 && index
< THREAD_CALL_INDEX_MAX
);
267 return &thread_call_groups
[index
];
271 static inline thread_call_flavor_t
272 thread_call_get_flavor(thread_call_t call
)
274 return (call
->tc_flags
& THREAD_CALL_CONTINUOUS
) ? TCF_CONTINUOUS
: TCF_ABSOLUTE
;
278 thread_call_group_setup(thread_call_group_t group
)
280 queue_init(&group
->pending_queue
);
281 queue_init(&group
->delayed_queues
[TCF_ABSOLUTE
]);
282 queue_init(&group
->delayed_queues
[TCF_CONTINUOUS
]);
284 /* TODO: Consolidate to one hard timer for each group */
285 timer_call_setup(&group
->delayed_timers
[TCF_ABSOLUTE
], thread_call_delayed_timer
, group
);
286 timer_call_setup(&group
->delayed_timers
[TCF_CONTINUOUS
], thread_call_delayed_timer
, group
);
287 timer_call_setup(&group
->dealloc_timer
, thread_call_dealloc_timer
, group
);
289 /* Reverse the wait order so we re-use the most recently parked thread from the pool */
290 waitq_init(&group
->idle_waitq
, SYNC_POLICY_REVERSED
|SYNC_POLICY_DISABLE_IRQ
);
294 * Simple wrapper for creating threads bound to
295 * thread call groups.
298 thread_call_thread_create(
299 thread_call_group_t group
)
302 kern_return_t result
;
304 int thread_pri
= group
->tcg_thread_pri
;
306 result
= kernel_thread_start_priority((thread_continue_t
)thread_call_thread
,
307 group
, thread_pri
, &thread
);
308 if (result
!= KERN_SUCCESS
) {
312 if (thread_pri
<= BASEPRI_KERNEL
) {
314 * THREAD_CALL_PRIORITY_KERNEL and lower don't get to run to completion
315 * in kernel if there are higher priority threads available.
317 thread_set_eager_preempt(thread
);
320 char name
[MAXTHREADNAMESIZE
] = "";
322 int group_thread_count
= group
->idle_count
+ group
->active_count
+ group
->blocked_count
;
324 snprintf(name
, sizeof(name
), "thread call %s #%d", group
->tcg_name
, group_thread_count
);
325 thread_set_thread_name(thread
, name
);
327 thread_deallocate(thread
);
332 * thread_call_initialize:
334 * Initialize this module, called
335 * early during system initialization.
338 thread_call_initialize(void)
340 int tc_size
= sizeof (thread_call_data_t
);
341 thread_call_zone
= zinit(tc_size
, 4096 * tc_size
, 16 * tc_size
, "thread_call");
342 zone_change(thread_call_zone
, Z_CALLERACCT
, FALSE
);
343 zone_change(thread_call_zone
, Z_NOENCRYPT
, TRUE
);
345 lck_grp_init(&thread_call_lck_grp
, "thread_call", LCK_GRP_ATTR_NULL
);
346 lck_mtx_init(&thread_call_lock_data
, &thread_call_lck_grp
, LCK_ATTR_NULL
);
348 nanotime_to_absolutetime(0, THREAD_CALL_DEALLOC_INTERVAL_NS
, &thread_call_dealloc_interval_abs
);
349 waitq_init(&daemon_waitq
, SYNC_POLICY_DISABLE_IRQ
| SYNC_POLICY_FIFO
);
351 for (uint32_t i
= 0; i
< THREAD_CALL_INDEX_MAX
; i
++)
352 thread_call_group_setup(&thread_call_groups
[i
]);
354 spl_t s
= disable_ints_and_lock();
356 queue_init(&thread_call_internal_queue
);
358 thread_call_t call
= internal_call_storage
;
359 call
< &internal_call_storage
[INTERNAL_CALL_COUNT
];
362 enqueue_tail(&thread_call_internal_queue
, &call
->tc_call
.q_link
);
363 thread_call_internal_queue_count
++;
366 thread_call_daemon_awake
= TRUE
;
368 enable_ints_and_unlock(s
);
371 kern_return_t result
;
373 result
= kernel_thread_start_priority((thread_continue_t
)thread_call_daemon
,
374 NULL
, BASEPRI_PREEMPT_HIGH
+ 1, &thread
);
375 if (result
!= KERN_SUCCESS
)
376 panic("thread_call_initialize");
378 thread_deallocate(thread
);
384 thread_call_func_t func
,
385 thread_call_param_t param0
)
387 bzero(call
, sizeof(*call
));
388 call_entry_setup((call_entry_t
)call
, func
, param0
);
390 /* Thread calls default to the HIGH group unless otherwise specified */
391 call
->tc_index
= THREAD_CALL_INDEX_HIGH
;
393 /* THREAD_CALL_ALLOC not set, memory owned by caller */
397 * _internal_call_allocate:
399 * Allocate an internal callout entry.
401 * Called with thread_call_lock held.
403 static __inline__ thread_call_t
404 _internal_call_allocate(thread_call_func_t func
, thread_call_param_t param0
)
408 if (queue_empty(&thread_call_internal_queue
))
409 panic("_internal_call_allocate");
411 call
= qe_dequeue_head(&thread_call_internal_queue
, struct thread_call
, tc_call
.q_link
);
413 thread_call_internal_queue_count
--;
415 thread_call_setup(call
, func
, param0
);
417 call
->tc_flags
= 0; /* THREAD_CALL_ALLOC not set, do not free back to zone */
423 * _internal_call_release:
425 * Release an internal callout entry which
426 * is no longer pending (or delayed). This is
427 * safe to call on a non-internal entry, in which
428 * case nothing happens.
430 * Called with thread_call_lock held.
432 static __inline__
void
433 _internal_call_release(thread_call_t call
)
435 if (call
>= internal_call_storage
&&
436 call
< &internal_call_storage
[INTERNAL_CALL_COUNT
]) {
437 assert((call
->tc_flags
& THREAD_CALL_ALLOC
) == 0);
438 enqueue_head(&thread_call_internal_queue
, &call
->tc_call
.q_link
);
439 thread_call_internal_queue_count
++;
444 * _pending_call_enqueue:
446 * Place an entry at the end of the
447 * pending queue, to be executed soon.
449 * Returns TRUE if the entry was already
452 * Called with thread_call_lock held.
454 static __inline__ boolean_t
455 _pending_call_enqueue(thread_call_t call
,
456 thread_call_group_t group
)
458 if ((THREAD_CALL_ONCE
| THREAD_CALL_RUNNING
)
459 == (call
->tc_flags
& (THREAD_CALL_ONCE
| THREAD_CALL_RUNNING
))) {
460 call
->tc_deadline
= 0;
462 uint32_t flags
= call
->tc_flags
;
463 call
->tc_flags
|= THREAD_CALL_RESCHEDULE
;
465 if ((flags
& THREAD_CALL_RESCHEDULE
) != 0)
471 queue_head_t
*old_queue
= call_entry_enqueue_tail(CE(call
), &group
->pending_queue
);
473 if (old_queue
== NULL
) {
474 call
->tc_submit_count
++;
475 } else if (old_queue
!= &group
->pending_queue
&&
476 old_queue
!= &group
->delayed_queues
[TCF_ABSOLUTE
] &&
477 old_queue
!= &group
->delayed_queues
[TCF_CONTINUOUS
]) {
478 panic("tried to move a thread call (%p) between groups (old_queue: %p)", call
, old_queue
);
481 group
->pending_count
++;
483 thread_call_wake(group
);
485 return (old_queue
!= NULL
);
489 * _delayed_call_enqueue:
491 * Place an entry on the delayed queue,
492 * after existing entries with an earlier
493 * (or identical) deadline.
495 * Returns TRUE if the entry was already
498 * Called with thread_call_lock held.
501 _delayed_call_enqueue(
503 thread_call_group_t group
,
505 thread_call_flavor_t flavor
)
507 if ((THREAD_CALL_ONCE
| THREAD_CALL_RUNNING
)
508 == (call
->tc_flags
& (THREAD_CALL_ONCE
| THREAD_CALL_RUNNING
))) {
509 call
->tc_deadline
= deadline
;
511 uint32_t flags
= call
->tc_flags
;
512 call
->tc_flags
|= THREAD_CALL_RESCHEDULE
;
514 if ((flags
& THREAD_CALL_RESCHEDULE
) != 0)
520 queue_head_t
*old_queue
= call_entry_enqueue_deadline(CE(call
),
521 &group
->delayed_queues
[flavor
],
524 if (old_queue
== &group
->pending_queue
) {
525 group
->pending_count
--;
526 } else if (old_queue
== NULL
) {
527 call
->tc_submit_count
++;
528 } else if (old_queue
== &group
->delayed_queues
[TCF_ABSOLUTE
] ||
529 old_queue
== &group
->delayed_queues
[TCF_CONTINUOUS
]) {
530 /* TODO: if it's in the other delayed queue, that might not be OK */
531 // we did nothing, and that's fine
533 panic("tried to move a thread call (%p) between groups (old_queue: %p)", call
, old_queue
);
536 return (old_queue
!= NULL
);
542 * Remove an entry from a queue.
544 * Returns TRUE if the entry was on a queue.
546 * Called with thread_call_lock held.
548 static __inline__ boolean_t
551 thread_call_group_t group
)
553 queue_head_t
*old_queue
;
555 old_queue
= call_entry_dequeue(CE(call
));
557 if (old_queue
!= NULL
) {
558 assert(old_queue
== &group
->pending_queue
||
559 old_queue
== &group
->delayed_queues
[TCF_ABSOLUTE
] ||
560 old_queue
== &group
->delayed_queues
[TCF_CONTINUOUS
]);
562 call
->tc_finish_count
++;
563 if (old_queue
== &group
->pending_queue
)
564 group
->pending_count
--;
567 return (old_queue
!= NULL
);
571 * _arm_delayed_call_timer:
573 * Check if the timer needs to be armed for this flavor,
576 * If call is non-NULL, only re-arm the timer if the specified call
577 * is the first in the queue.
579 * Returns true if the timer was armed/re-armed, false if it was left unset
580 * Caller should cancel the timer if need be.
582 * Called with thread_call_lock held.
585 _arm_delayed_call_timer(thread_call_t new_call
,
586 thread_call_group_t group
,
587 thread_call_flavor_t flavor
)
589 /* No calls implies no timer needed */
590 if (queue_empty(&group
->delayed_queues
[flavor
]))
593 thread_call_t call
= qe_queue_first(&group
->delayed_queues
[flavor
], struct thread_call
, tc_call
.q_link
);
595 /* We only need to change the hard timer if this new call is the first in the list */
596 if (new_call
!= NULL
&& new_call
!= call
)
599 assert((call
->tc_soft_deadline
!= 0) && ((call
->tc_soft_deadline
<= call
->tc_call
.deadline
)));
601 uint64_t fire_at
= call
->tc_soft_deadline
;
603 if (flavor
== TCF_CONTINUOUS
) {
604 assert((call
->tc_flags
& THREAD_CALL_CONTINUOUS
) == THREAD_CALL_CONTINUOUS
);
605 fire_at
= continuoustime_to_absolutetime(fire_at
);
607 assert((call
->tc_flags
& THREAD_CALL_CONTINUOUS
) == 0);
611 * Note: This picks the soonest-deadline call's leeway as the hard timer's leeway,
612 * which does not take into account later-deadline timers with a larger leeway.
613 * This is a valid coalescing behavior, but masks a possible window to
614 * fire a timer instead of going idle.
616 uint64_t leeway
= call
->tc_call
.deadline
- call
->tc_soft_deadline
;
618 timer_call_enter_with_leeway(&group
->delayed_timers
[flavor
], (timer_call_param_t
)flavor
,
620 TIMER_CALL_SYS_CRITICAL
|TIMER_CALL_LEEWAY
,
621 ((call
->tc_flags
& THREAD_CALL_RATELIMITED
) == THREAD_CALL_RATELIMITED
));
627 * _cancel_func_from_queue:
629 * Remove the first (or all) matching
630 * entries from the specified queue.
632 * Returns TRUE if any matching entries
635 * Called with thread_call_lock held.
638 _cancel_func_from_queue(thread_call_func_t func
,
639 thread_call_param_t param0
,
640 thread_call_group_t group
,
641 boolean_t remove_all
,
644 boolean_t call_removed
= FALSE
;
647 qe_foreach_element_safe(call
, queue
, tc_call
.q_link
) {
648 if (call
->tc_call
.func
!= func
||
649 call
->tc_call
.param0
!= param0
) {
653 _call_dequeue(call
, group
);
655 _internal_call_release(call
);
662 return (call_removed
);
666 * thread_call_func_delayed:
668 * Enqueue a function callout to
669 * occur at the stated time.
672 thread_call_func_delayed(
673 thread_call_func_t func
,
674 thread_call_param_t param
,
677 (void)thread_call_enter_delayed_internal(NULL
, func
, param
, 0, deadline
, 0, 0);
681 * thread_call_func_delayed_with_leeway:
683 * Same as thread_call_func_delayed(), but with
684 * leeway/flags threaded through.
688 thread_call_func_delayed_with_leeway(
689 thread_call_func_t func
,
690 thread_call_param_t param
,
695 (void)thread_call_enter_delayed_internal(NULL
, func
, param
, 0, deadline
, leeway
, flags
);
699 * thread_call_func_cancel:
701 * Dequeue a function callout.
703 * Removes one (or all) { function, argument }
704 * instance(s) from either (or both)
705 * the pending and the delayed queue,
708 * Returns TRUE if any calls were cancelled.
710 * This iterates all of the pending or delayed thread calls in the group,
711 * which is really inefficient. Switch to an allocated thread call instead.
714 thread_call_func_cancel(
715 thread_call_func_t func
,
716 thread_call_param_t param
,
717 boolean_t cancel_all
)
721 assert(func
!= NULL
);
723 spl_t s
= disable_ints_and_lock();
725 /* Function-only thread calls are only kept in the default HIGH group */
726 thread_call_group_t group
= &thread_call_groups
[THREAD_CALL_INDEX_HIGH
];
729 /* exhaustively search every queue, and return true if any search found something */
730 result
= _cancel_func_from_queue(func
, param
, group
, cancel_all
, &group
->pending_queue
) |
731 _cancel_func_from_queue(func
, param
, group
, cancel_all
, &group
->delayed_queues
[TCF_ABSOLUTE
]) |
732 _cancel_func_from_queue(func
, param
, group
, cancel_all
, &group
->delayed_queues
[TCF_CONTINUOUS
]);
734 /* early-exit as soon as we find something, don't search other queues */
735 result
= _cancel_func_from_queue(func
, param
, group
, cancel_all
, &group
->pending_queue
) ||
736 _cancel_func_from_queue(func
, param
, group
, cancel_all
, &group
->delayed_queues
[TCF_ABSOLUTE
]) ||
737 _cancel_func_from_queue(func
, param
, group
, cancel_all
, &group
->delayed_queues
[TCF_CONTINUOUS
]);
740 enable_ints_and_unlock(s
);
746 * Allocate a thread call with a given priority. Importances other than
747 * THREAD_CALL_PRIORITY_HIGH or THREAD_CALL_PRIORITY_KERNEL_HIGH will be run in threads
748 * with eager preemption enabled (i.e. may be aggressively preempted by higher-priority
749 * threads which are not in the normal "urgent" bands).
752 thread_call_allocate_with_priority(
753 thread_call_func_t func
,
754 thread_call_param_t param0
,
755 thread_call_priority_t pri
)
757 return thread_call_allocate_with_options(func
, param0
, pri
, 0);
761 thread_call_allocate_with_options(
762 thread_call_func_t func
,
763 thread_call_param_t param0
,
764 thread_call_priority_t pri
,
765 thread_call_options_t options
)
767 thread_call_t call
= thread_call_allocate(func
, param0
);
770 case THREAD_CALL_PRIORITY_HIGH
:
771 call
->tc_index
= THREAD_CALL_INDEX_HIGH
;
773 case THREAD_CALL_PRIORITY_KERNEL
:
774 call
->tc_index
= THREAD_CALL_INDEX_KERNEL
;
776 case THREAD_CALL_PRIORITY_USER
:
777 call
->tc_index
= THREAD_CALL_INDEX_USER
;
779 case THREAD_CALL_PRIORITY_LOW
:
780 call
->tc_index
= THREAD_CALL_INDEX_LOW
;
782 case THREAD_CALL_PRIORITY_KERNEL_HIGH
:
783 call
->tc_index
= THREAD_CALL_INDEX_KERNEL_HIGH
;
786 panic("Invalid thread call pri value: %d", pri
);
790 if (options
& THREAD_CALL_OPTIONS_ONCE
) {
791 call
->tc_flags
|= THREAD_CALL_ONCE
;
793 if (options
& THREAD_CALL_OPTIONS_SIGNAL
) {
794 call
->tc_flags
|= THREAD_CALL_SIGNAL
| THREAD_CALL_ONCE
;
801 thread_call_allocate_with_qos(thread_call_func_t func
,
802 thread_call_param_t param0
,
804 thread_call_options_t options
)
806 thread_call_t call
= thread_call_allocate(func
, param0
);
809 case THREAD_QOS_UNSPECIFIED
:
810 call
->tc_index
= THREAD_CALL_INDEX_HIGH
;
812 case THREAD_QOS_LEGACY
:
813 call
->tc_index
= THREAD_CALL_INDEX_USER
;
815 case THREAD_QOS_MAINTENANCE
:
816 case THREAD_QOS_BACKGROUND
:
817 call
->tc_index
= THREAD_CALL_INDEX_LOW
;
819 case THREAD_QOS_UTILITY
:
820 call
->tc_index
= THREAD_CALL_INDEX_QOS_UT
;
822 case THREAD_QOS_USER_INITIATED
:
823 call
->tc_index
= THREAD_CALL_INDEX_QOS_IN
;
825 case THREAD_QOS_USER_INTERACTIVE
:
826 call
->tc_index
= THREAD_CALL_INDEX_QOS_UI
;
829 panic("Invalid thread call qos value: %d", qos_tier
);
833 if (options
& THREAD_CALL_OPTIONS_ONCE
)
834 call
->tc_flags
|= THREAD_CALL_ONCE
;
836 /* does not support THREAD_CALL_OPTIONS_SIGNAL */
843 * thread_call_allocate:
845 * Allocate a callout entry.
848 thread_call_allocate(
849 thread_call_func_t func
,
850 thread_call_param_t param0
)
852 thread_call_t call
= zalloc(thread_call_zone
);
854 thread_call_setup(call
, func
, param0
);
856 call
->tc_flags
= THREAD_CALL_ALLOC
;
864 * Release a callout. If the callout is currently
865 * executing, it will be freed when all invocations
868 * If the callout is currently armed to fire again, then
869 * freeing is not allowed and returns FALSE. The
870 * client must have canceled the pending invocation before freeing.
876 spl_t s
= disable_ints_and_lock();
878 if (call
->tc_call
.queue
!= NULL
||
879 ((call
->tc_flags
& THREAD_CALL_RESCHEDULE
) != 0)) {
880 thread_call_unlock();
886 int32_t refs
= --call
->tc_refs
;
888 panic("Refcount negative: %d\n", refs
);
891 if ((THREAD_CALL_SIGNAL
| THREAD_CALL_RUNNING
)
892 == ((THREAD_CALL_SIGNAL
| THREAD_CALL_RUNNING
) & call
->tc_flags
)) {
893 thread_call_wait_once_locked(call
, s
);
894 /* thread call lock has been unlocked */
896 enable_ints_and_unlock(s
);
900 assert(call
->tc_finish_count
== call
->tc_submit_count
);
901 zfree(thread_call_zone
, call
);
910 * Enqueue a callout entry to occur "soon".
912 * Returns TRUE if the call was
913 * already on a queue.
919 return thread_call_enter1(call
, 0);
925 thread_call_param_t param1
)
927 boolean_t result
= TRUE
;
928 thread_call_group_t group
;
930 assert(call
->tc_call
.func
!= NULL
);
932 assert((call
->tc_flags
& THREAD_CALL_SIGNAL
) == 0);
934 group
= thread_call_get_group(call
);
936 spl_t s
= disable_ints_and_lock();
938 if (call
->tc_call
.queue
!= &group
->pending_queue
) {
939 result
= _pending_call_enqueue(call
, group
);
942 call
->tc_call
.param1
= param1
;
944 enable_ints_and_unlock(s
);
950 * thread_call_enter_delayed:
952 * Enqueue a callout entry to occur
953 * at the stated time.
955 * Returns TRUE if the call was
956 * already on a queue.
959 thread_call_enter_delayed(
963 assert(call
!= NULL
);
964 return thread_call_enter_delayed_internal(call
, NULL
, 0, 0, deadline
, 0, 0);
968 thread_call_enter1_delayed(
970 thread_call_param_t param1
,
973 assert(call
!= NULL
);
974 return thread_call_enter_delayed_internal(call
, NULL
, 0, param1
, deadline
, 0, 0);
978 thread_call_enter_delayed_with_leeway(
980 thread_call_param_t param1
,
985 assert(call
!= NULL
);
986 return thread_call_enter_delayed_internal(call
, NULL
, 0, param1
, deadline
, leeway
, flags
);
991 * thread_call_enter_delayed_internal:
992 * enqueue a callout entry to occur at the stated time
994 * Returns True if the call was already on a queue
996 * call - structure encapsulating state of the callout
997 * alt_func/alt_param0 - if call is NULL, allocate temporary storage using these parameters
998 * deadline - time deadline in nanoseconds
999 * leeway - timer slack represented as delta of deadline.
1000 * flags - THREAD_CALL_DELAY_XXX : classification of caller's desires wrt timer coalescing.
1001 * THREAD_CALL_DELAY_LEEWAY : value in leeway is used for timer coalescing.
1002 * THREAD_CALL_CONTINUOUS: thread call will be called according to mach_continuous_time rather
1003 * than mach_absolute_time
1006 thread_call_enter_delayed_internal(
1008 thread_call_func_t alt_func
,
1009 thread_call_param_t alt_param0
,
1010 thread_call_param_t param1
,
1015 boolean_t result
= TRUE
;
1016 thread_call_group_t group
;
1017 uint64_t now
, sdeadline
, slop
;
1020 thread_call_flavor_t flavor
= (flags
& THREAD_CALL_CONTINUOUS
) ? TCF_CONTINUOUS
: TCF_ABSOLUTE
;
1022 /* direct mapping between thread_call, timer_call, and timeout_urgency values */
1023 urgency
= (flags
& TIMEOUT_URGENCY_MASK
);
1025 spl_t s
= disable_ints_and_lock();
1028 /* allocate a structure out of internal storage, as a convenience for BSD callers */
1029 call
= _internal_call_allocate(alt_func
, alt_param0
);
1032 assert(call
->tc_call
.func
!= NULL
);
1033 group
= thread_call_get_group(call
);
1035 /* TODO: assert that call is not enqueued before flipping the flag */
1036 if (flavor
== TCF_CONTINUOUS
) {
1037 now
= mach_continuous_time();
1038 call
->tc_flags
|= THREAD_CALL_CONTINUOUS
;
1040 now
= mach_absolute_time();
1041 call
->tc_flags
&= ~THREAD_CALL_CONTINUOUS
;
1044 call
->tc_flags
|= THREAD_CALL_DELAYED
;
1046 call
->tc_soft_deadline
= sdeadline
= deadline
;
1048 boolean_t ratelimited
= FALSE
;
1049 slop
= timer_call_slop(deadline
, now
, urgency
, current_thread(), &ratelimited
);
1051 if ((flags
& THREAD_CALL_DELAY_LEEWAY
) != 0 && leeway
> slop
)
1054 if (UINT64_MAX
- deadline
<= slop
)
1055 deadline
= UINT64_MAX
;
1060 call
->tc_flags
|= TIMER_CALL_RATELIMITED
;
1062 call
->tc_flags
&= ~TIMER_CALL_RATELIMITED
;
1065 call
->tc_call
.param1
= param1
;
1067 call
->tc_ttd
= (sdeadline
> now
) ? (sdeadline
- now
) : 0;
1069 result
= _delayed_call_enqueue(call
, group
, deadline
, flavor
);
1071 _arm_delayed_call_timer(call
, group
, flavor
);
1074 DTRACE_TMR5(thread_callout__create
, thread_call_func_t
, call
->tc_call
.func
,
1075 uint64_t, (deadline
- sdeadline
), uint64_t, (call
->tc_ttd
>> 32),
1076 (unsigned) (call
->tc_ttd
& 0xFFFFFFFF), call
);
1079 enable_ints_and_unlock(s
);
1085 * Remove a callout entry from the queue
1086 * Called with thread_call_lock held
1089 thread_call_cancel_locked(thread_call_t call
)
1091 boolean_t canceled
= (0 != (THREAD_CALL_RESCHEDULE
& call
->tc_flags
));
1092 call
->tc_flags
&= ~THREAD_CALL_RESCHEDULE
;
1095 /* if reschedule was set, it must not have been queued */
1096 assert(call
->tc_call
.queue
== NULL
);
1098 boolean_t do_cancel_callout
= FALSE
;
1100 thread_call_flavor_t flavor
= thread_call_get_flavor(call
);
1101 thread_call_group_t group
= thread_call_get_group(call
);
1103 if ((call
->tc_call
.deadline
!= 0) &&
1104 (call
== qe_queue_first(&group
->delayed_queues
[flavor
], struct thread_call
, tc_call
.q_link
))) {
1105 assert(call
->tc_call
.queue
== &group
->delayed_queues
[flavor
]);
1106 do_cancel_callout
= TRUE
;
1109 canceled
= _call_dequeue(call
, group
);
1111 if (do_cancel_callout
) {
1112 if (_arm_delayed_call_timer(NULL
, group
, flavor
) == false)
1113 timer_call_cancel(&group
->delayed_timers
[flavor
]);
1118 DTRACE_TMR4(thread_callout__cancel
, thread_call_func_t
, call
->tc_call
.func
,
1119 0, (call
->tc_ttd
>> 32), (unsigned) (call
->tc_ttd
& 0xFFFFFFFF));
1126 * thread_call_cancel:
1128 * Dequeue a callout entry.
1130 * Returns TRUE if the call was
1134 thread_call_cancel(thread_call_t call
)
1136 spl_t s
= disable_ints_and_lock();
1138 boolean_t result
= thread_call_cancel_locked(call
);
1140 enable_ints_and_unlock(s
);
1146 * Cancel a thread call. If it cannot be cancelled (i.e.
1147 * is already in flight), waits for the most recent invocation
1148 * to finish. Note that if clients re-submit this thread call,
1149 * it may still be pending or in flight when thread_call_cancel_wait
1150 * returns, but all requests to execute this work item prior
1151 * to the call to thread_call_cancel_wait will have finished.
1154 thread_call_cancel_wait(thread_call_t call
)
1156 if ((call
->tc_flags
& THREAD_CALL_ALLOC
) == 0)
1157 panic("thread_call_cancel_wait: can't wait on thread call whose storage I don't own");
1159 if (!ml_get_interrupts_enabled())
1160 panic("unsafe thread_call_cancel_wait");
1162 if (current_thread()->thc_state
.thc_call
== call
)
1163 panic("thread_call_cancel_wait: deadlock waiting on self from inside call: %p to function %p",
1164 call
, call
->tc_call
.func
);
1166 spl_t s
= disable_ints_and_lock();
1168 boolean_t canceled
= thread_call_cancel_locked(call
);
1170 if ((call
->tc_flags
& THREAD_CALL_ONCE
) == THREAD_CALL_ONCE
) {
1172 * A cancel-wait on a 'once' call will both cancel
1173 * the pending call and wait for the in-flight call
1176 thread_call_wait_once_locked(call
, s
);
1177 /* thread call lock unlocked */
1180 * A cancel-wait on a normal call will only wait for the in-flight calls
1181 * if it did not cancel the pending call.
1183 * TODO: This seems less than useful - shouldn't it do the wait as well?
1186 if (canceled
== FALSE
) {
1187 thread_call_wait_locked(call
, s
);
1188 /* thread call lock unlocked */
1190 enable_ints_and_unlock(s
);
1201 * Wake a call thread to service
1202 * pending call entries. May wake
1203 * the daemon thread in order to
1204 * create additional call threads.
1206 * Called with thread_call_lock held.
1208 * For high-priority group, only does wakeup/creation if there are no threads
1211 static __inline__
void
1213 thread_call_group_t group
)
1216 * New behavior: use threads if you've got 'em.
1217 * Traditional behavior: wake only if no threads running.
1219 if (group_isparallel(group
) || group
->active_count
== 0) {
1220 if (waitq_wakeup64_one(&group
->idle_waitq
, NO_EVENT64
,
1221 THREAD_AWAKENED
, WAITQ_ALL_PRIORITIES
) == KERN_SUCCESS
) {
1222 group
->idle_count
--; group
->active_count
++;
1224 if (group
->idle_count
== 0) {
1225 timer_call_cancel(&group
->dealloc_timer
);
1226 group
->flags
&= ~TCG_DEALLOC_ACTIVE
;
1229 if (!thread_call_daemon_awake
&& thread_call_group_should_add_thread(group
)) {
1230 thread_call_daemon_awake
= TRUE
;
1231 waitq_wakeup64_one(&daemon_waitq
, NO_EVENT64
,
1232 THREAD_AWAKENED
, WAITQ_ALL_PRIORITIES
);
1239 * sched_call_thread:
1241 * Call out invoked by the scheduler.
1248 thread_call_group_t group
;
1250 group
= thread
->thc_state
.thc_group
;
1251 assert((group
- &thread_call_groups
[0]) < THREAD_CALL_INDEX_MAX
);
1253 thread_call_lock_spin();
1257 case SCHED_CALL_BLOCK
:
1258 assert(group
->active_count
);
1259 --group
->active_count
;
1260 group
->blocked_count
++;
1261 if (group
->pending_count
> 0)
1262 thread_call_wake(group
);
1265 case SCHED_CALL_UNBLOCK
:
1266 assert(group
->blocked_count
);
1267 --group
->blocked_count
;
1268 group
->active_count
++;
1272 thread_call_unlock();
1276 * Interrupts disabled, lock held; returns the same way.
1277 * Only called on thread calls whose storage we own. Wakes up
1278 * anyone who might be waiting on this work item and frees it
1279 * if the client has so requested.
1282 thread_call_finish(thread_call_t call
, thread_call_group_t group
, spl_t
*s
)
1287 boolean_t dowake
= FALSE
;
1288 boolean_t repend
= FALSE
;
1290 call
->tc_finish_count
++;
1291 flags
= call
->tc_flags
;
1292 signal
= ((THREAD_CALL_SIGNAL
& flags
) != 0);
1295 /* The thread call thread owns a ref until the call is finished */
1296 if (call
->tc_refs
<= 0)
1297 panic("thread_call_finish: detected over-released thread call: %p", call
);
1301 call
->tc_flags
&= ~(THREAD_CALL_RESCHEDULE
| THREAD_CALL_RUNNING
| THREAD_CALL_WAIT
);
1303 if ((call
->tc_refs
!= 0) && ((flags
& THREAD_CALL_RESCHEDULE
) != 0)) {
1304 assert(flags
& THREAD_CALL_ONCE
);
1305 thread_call_flavor_t flavor
= thread_call_get_flavor(call
);
1307 if (THREAD_CALL_DELAYED
& flags
) {
1308 time
= mach_absolute_time();
1309 if (flavor
== TCF_CONTINUOUS
) {
1310 time
= absolutetime_to_continuoustime(time
);
1312 if (call
->tc_soft_deadline
<= time
) {
1313 call
->tc_flags
&= ~(THREAD_CALL_DELAYED
| TIMER_CALL_RATELIMITED
);
1314 call
->tc_deadline
= 0;
1317 if (call
->tc_deadline
) {
1318 _delayed_call_enqueue(call
, group
, call
->tc_deadline
, flavor
);
1320 _arm_delayed_call_timer(call
, group
, flavor
);
1322 } else if (signal
) {
1323 call
->tc_submit_count
++;
1326 _pending_call_enqueue(call
, group
);
1330 if ((flags
& THREAD_CALL_WAIT
) != 0) {
1334 * Dropping lock here because the sched call for the
1335 * high-pri group can take the big lock from under
1338 thread_call_unlock();
1339 thread_wakeup((event_t
)call
);
1340 thread_call_lock_spin();
1341 /* THREAD_CALL_SIGNAL call may have been freed */
1344 if (!signal
&& (call
->tc_refs
== 0)) {
1346 panic("Someone waiting on a thread call that is scheduled for free: %p\n", call
->tc_call
.func
);
1349 assert(call
->tc_finish_count
== call
->tc_submit_count
);
1351 enable_ints_and_unlock(*s
);
1353 zfree(thread_call_zone
, call
);
1355 *s
= disable_ints_and_lock();
1362 * thread_call_invoke
1364 * Invoke the function provided for this thread call
1366 * Note that the thread call object can be deallocated by the function if we do not control its storage.
1368 static void __attribute__((noinline
))
1369 thread_call_invoke(thread_call_func_t func
, thread_call_param_t param0
, thread_call_param_t param1
, thread_call_t call
)
1371 current_thread()->thc_state
.thc_call
= call
;
1373 #if DEVELOPMENT || DEBUG
1374 KERNEL_DEBUG_CONSTANT(
1375 MACHDBG_CODE(DBG_MACH_SCHED
,MACH_CALLOUT
) | DBG_FUNC_START
,
1376 VM_KERNEL_UNSLIDE(func
), VM_KERNEL_ADDRHIDE(param0
), VM_KERNEL_ADDRHIDE(param1
), 0, 0);
1377 #endif /* DEVELOPMENT || DEBUG */
1380 uint64_t tc_ttd
= call
->tc_ttd
;
1381 boolean_t is_delayed
= call
->tc_flags
& THREAD_CALL_DELAYED
;
1382 DTRACE_TMR6(thread_callout__start
, thread_call_func_t
, func
, int, 0, int, (tc_ttd
>> 32),
1383 (unsigned) (tc_ttd
& 0xFFFFFFFF), is_delayed
, call
);
1386 (*func
)(param0
, param1
);
1389 DTRACE_TMR6(thread_callout__end
, thread_call_func_t
, func
, int, 0, int, (tc_ttd
>> 32),
1390 (unsigned) (tc_ttd
& 0xFFFFFFFF), is_delayed
, call
);
1393 #if DEVELOPMENT || DEBUG
1394 KERNEL_DEBUG_CONSTANT(
1395 MACHDBG_CODE(DBG_MACH_SCHED
,MACH_CALLOUT
) | DBG_FUNC_END
,
1396 VM_KERNEL_UNSLIDE(func
), 0, 0, 0, 0);
1397 #endif /* DEVELOPMENT || DEBUG */
1399 current_thread()->thc_state
.thc_call
= NULL
;
1403 * thread_call_thread:
1407 thread_call_group_t group
,
1410 thread_t self
= current_thread();
1413 if ((thread_get_tag_internal(self
) & THREAD_TAG_CALLOUT
) == 0)
1414 (void)thread_set_tag_internal(self
, THREAD_TAG_CALLOUT
);
1417 * A wakeup with THREAD_INTERRUPTED indicates that
1418 * we should terminate.
1420 if (wres
== THREAD_INTERRUPTED
) {
1421 thread_terminate(self
);
1424 panic("thread_terminate() returned?");
1427 spl_t s
= disable_ints_and_lock();
1429 self
->thc_state
.thc_group
= group
;
1430 thread_sched_call(self
, sched_call_thread
);
1432 while (group
->pending_count
> 0) {
1434 thread_call_func_t func
;
1435 thread_call_param_t param0
, param1
;
1437 call
= qe_dequeue_head(&group
->pending_queue
, struct thread_call
, tc_call
.q_link
);
1438 assert(call
!= NULL
);
1439 group
->pending_count
--;
1441 func
= call
->tc_call
.func
;
1442 param0
= call
->tc_call
.param0
;
1443 param1
= call
->tc_call
.param1
;
1445 call
->tc_call
.queue
= NULL
;
1447 _internal_call_release(call
);
1450 * Can only do wakeups for thread calls whose storage
1453 if ((call
->tc_flags
& THREAD_CALL_ALLOC
) != 0) {
1455 call
->tc_flags
|= THREAD_CALL_RUNNING
;
1456 call
->tc_refs
++; /* Delay free until we're done */
1460 enable_ints_and_unlock(s
);
1462 thread_call_invoke(func
, param0
, param1
, call
);
1464 if (get_preemption_level() != 0) {
1465 int pl
= get_preemption_level();
1466 panic("thread_call_thread: preemption_level %d, last callout %p(%p, %p)",
1467 pl
, (void *)VM_KERNEL_UNSLIDE(func
), param0
, param1
);
1470 s
= disable_ints_and_lock();
1473 /* Frees if so desired */
1474 thread_call_finish(call
, group
, &s
);
1478 thread_sched_call(self
, NULL
);
1479 group
->active_count
--;
1481 if (self
->callout_woken_from_icontext
&& !self
->callout_woke_thread
) {
1482 ledger_credit(self
->t_ledger
, task_ledgers
.interrupt_wakeups
, 1);
1483 if (self
->callout_woken_from_platform_idle
)
1484 ledger_credit(self
->t_ledger
, task_ledgers
.platform_idle_wakeups
, 1);
1487 self
->callout_woken_from_icontext
= FALSE
;
1488 self
->callout_woken_from_platform_idle
= FALSE
;
1489 self
->callout_woke_thread
= FALSE
;
1491 if (group_isparallel(group
)) {
1493 * For new style of thread group, thread always blocks.
1494 * If we have more than the target number of threads,
1495 * and this is the first to block, and it isn't active
1496 * already, set a timer for deallocating a thread if we
1497 * continue to have a surplus.
1499 group
->idle_count
++;
1501 if (group
->idle_count
== 1) {
1502 group
->idle_timestamp
= mach_absolute_time();
1505 if (((group
->flags
& TCG_DEALLOC_ACTIVE
) == 0) &&
1506 ((group
->active_count
+ group
->idle_count
) > group
->target_thread_count
)) {
1507 group
->flags
|= TCG_DEALLOC_ACTIVE
;
1508 thread_call_start_deallocate_timer(group
);
1511 /* Wait for more work (or termination) */
1512 wres
= waitq_assert_wait64(&group
->idle_waitq
, NO_EVENT64
, THREAD_INTERRUPTIBLE
, 0);
1513 if (wres
!= THREAD_WAITING
) {
1514 panic("kcall worker unable to assert wait?");
1517 enable_ints_and_unlock(s
);
1519 thread_block_parameter((thread_continue_t
)thread_call_thread
, group
);
1521 if (group
->idle_count
< group
->target_thread_count
) {
1522 group
->idle_count
++;
1524 waitq_assert_wait64(&group
->idle_waitq
, NO_EVENT64
, THREAD_UNINT
, 0); /* Interrupted means to exit */
1526 enable_ints_and_unlock(s
);
1528 thread_block_parameter((thread_continue_t
)thread_call_thread
, group
);
1533 enable_ints_and_unlock(s
);
1535 thread_terminate(self
);
1540 * thread_call_daemon: walk list of groups, allocating
1541 * threads if appropriate (as determined by
1542 * thread_call_group_should_add_thread()).
1545 thread_call_daemon_continue(__unused
void *arg
)
1547 spl_t s
= disable_ints_and_lock();
1549 /* Starting at zero happens to be high-priority first. */
1550 for (int i
= 0; i
< THREAD_CALL_INDEX_MAX
; i
++) {
1551 thread_call_group_t group
= &thread_call_groups
[i
];
1552 while (thread_call_group_should_add_thread(group
)) {
1553 group
->active_count
++;
1555 enable_ints_and_unlock(s
);
1557 kern_return_t kr
= thread_call_thread_create(group
);
1558 if (kr
!= KERN_SUCCESS
) {
1560 * On failure, just pause for a moment and give up.
1561 * We can try again later.
1563 delay(10000); /* 10 ms */
1564 s
= disable_ints_and_lock();
1568 s
= disable_ints_and_lock();
1573 thread_call_daemon_awake
= FALSE
;
1574 waitq_assert_wait64(&daemon_waitq
, NO_EVENT64
, THREAD_UNINT
, 0);
1576 enable_ints_and_unlock(s
);
1578 thread_block_parameter((thread_continue_t
)thread_call_daemon_continue
, NULL
);
1586 thread_t self
= current_thread();
1588 self
->options
|= TH_OPT_VMPRIV
;
1589 vm_page_free_reserve(2); /* XXX */
1591 thread_set_thread_name(self
, "thread_call_daemon");
1593 thread_call_daemon_continue(NULL
);
1598 * Schedule timer to deallocate a worker thread if we have a surplus
1599 * of threads (in excess of the group's target) and at least one thread
1600 * is idle the whole time.
1603 thread_call_start_deallocate_timer(
1604 thread_call_group_t group
)
1609 assert(group
->idle_count
> 0);
1611 group
->flags
|= TCG_DEALLOC_ACTIVE
;
1612 deadline
= group
->idle_timestamp
+ thread_call_dealloc_interval_abs
;
1613 onqueue
= timer_call_enter(&group
->dealloc_timer
, deadline
, 0);
1616 panic("Deallocate timer already active?");
1620 /* non-static so dtrace can find it rdar://problem/31156135&31379348 */
1622 thread_call_delayed_timer(timer_call_param_t p0
, timer_call_param_t p1
)
1624 thread_call_group_t group
= (thread_call_group_t
) p0
;
1625 thread_call_flavor_t flavor
= (thread_call_flavor_t
) p1
;
1632 thread_call_lock_spin();
1634 if (flavor
== TCF_CONTINUOUS
)
1635 now
= mach_continuous_time();
1636 else if (flavor
== TCF_ABSOLUTE
)
1637 now
= mach_absolute_time();
1639 panic("invalid timer flavor: %d", flavor
);
1643 qe_foreach_element_safe(call
, &group
->delayed_queues
[flavor
], tc_call
.q_link
) {
1644 if (flavor
== TCF_CONTINUOUS
)
1645 assert((call
->tc_flags
& THREAD_CALL_CONTINUOUS
) == THREAD_CALL_CONTINUOUS
);
1647 assert((call
->tc_flags
& THREAD_CALL_CONTINUOUS
) == 0);
1650 * if we hit a call that isn't yet ready to expire,
1651 * then we're done for now
1652 * TODO: The next timer in the list could have a larger leeway
1653 * and therefore be ready to expire.
1654 * Sort by deadline then by soft deadline to avoid this
1656 if (call
->tc_soft_deadline
> now
)
1660 * If we hit a rate-limited timer, don't eagerly wake it up.
1661 * Wait until it reaches the end of the leeway window.
1663 * TODO: What if the next timer is not rate-limited?
1664 * Have a separate rate-limited queue to avoid this
1666 if ((call
->tc_flags
& THREAD_CALL_RATELIMITED
) &&
1667 (call
->tc_call
.deadline
> now
) &&
1668 (ml_timer_forced_evaluation() == FALSE
)) {
1672 if (THREAD_CALL_SIGNAL
& call
->tc_flags
) {
1673 __assert_only queue_head_t
*old_queue
;
1674 old_queue
= call_entry_dequeue(&call
->tc_call
);
1675 assert(old_queue
== &group
->delayed_queues
[flavor
]);
1678 thread_call_func_t func
= call
->tc_call
.func
;
1679 thread_call_param_t param0
= call
->tc_call
.param0
;
1680 thread_call_param_t param1
= call
->tc_call
.param1
;
1682 call
->tc_flags
|= THREAD_CALL_RUNNING
;
1683 thread_call_unlock();
1684 thread_call_invoke(func
, param0
, param1
, call
);
1685 thread_call_lock_spin();
1687 repend
= thread_call_finish(call
, group
, NULL
);
1690 /* call may have been freed */
1694 _pending_call_enqueue(call
, group
);
1699 _arm_delayed_call_timer(call
, group
, flavor
);
1701 thread_call_unlock();
1705 thread_call_delayed_timer_rescan(thread_call_group_t group
,
1706 thread_call_flavor_t flavor
)
1711 spl_t s
= disable_ints_and_lock();
1713 assert(ml_timer_forced_evaluation() == TRUE
);
1715 if (flavor
== TCF_CONTINUOUS
) {
1716 now
= mach_continuous_time();
1718 now
= mach_absolute_time();
1721 qe_foreach_element_safe(call
, &group
->delayed_queues
[flavor
], tc_call
.q_link
) {
1722 if (call
->tc_soft_deadline
<= now
) {
1723 _pending_call_enqueue(call
, group
);
1725 uint64_t skew
= call
->tc_call
.deadline
- call
->tc_soft_deadline
;
1726 assert (call
->tc_call
.deadline
>= call
->tc_soft_deadline
);
1728 * On a latency quality-of-service level change,
1729 * re-sort potentially rate-limited callout. The platform
1730 * layer determines which timers require this.
1732 if (timer_resort_threshold(skew
)) {
1733 _call_dequeue(call
, group
);
1734 _delayed_call_enqueue(call
, group
, call
->tc_soft_deadline
, flavor
);
1739 _arm_delayed_call_timer(NULL
, group
, flavor
);
1741 enable_ints_and_unlock(s
);
1745 thread_call_delayed_timer_rescan_all(void) {
1746 for (int i
= 0; i
< THREAD_CALL_INDEX_MAX
; i
++) {
1747 thread_call_delayed_timer_rescan(&thread_call_groups
[i
], TCF_ABSOLUTE
);
1748 thread_call_delayed_timer_rescan(&thread_call_groups
[i
], TCF_CONTINUOUS
);
1753 * Timer callback to tell a thread to terminate if
1754 * we have an excess of threads and at least one has been
1755 * idle for a long time.
1758 thread_call_dealloc_timer(
1759 timer_call_param_t p0
,
1760 __unused timer_call_param_t p1
)
1762 thread_call_group_t group
= (thread_call_group_t
)p0
;
1765 boolean_t terminated
= FALSE
;
1767 thread_call_lock_spin();
1769 now
= mach_absolute_time();
1770 if (group
->idle_count
> 0) {
1771 if (now
> group
->idle_timestamp
+ thread_call_dealloc_interval_abs
) {
1773 group
->idle_count
--;
1774 res
= waitq_wakeup64_one(&group
->idle_waitq
, NO_EVENT64
,
1775 THREAD_INTERRUPTED
, WAITQ_ALL_PRIORITIES
);
1776 if (res
!= KERN_SUCCESS
) {
1777 panic("Unable to wake up idle thread for termination?");
1784 * If we still have an excess of threads, schedule another
1785 * invocation of this function.
1787 if (group
->idle_count
> 0 && (group
->idle_count
+ group
->active_count
> group
->target_thread_count
)) {
1789 * If we killed someone just now, push out the
1793 group
->idle_timestamp
= now
;
1796 thread_call_start_deallocate_timer(group
);
1798 group
->flags
&= ~TCG_DEALLOC_ACTIVE
;
1801 thread_call_unlock();
1805 * Wait for the invocation of the thread call to complete
1806 * We know there's only one in flight because of the 'once' flag.
1808 * If a subsequent invocation comes in before we wake up, that's OK
1810 * TODO: Here is where we will add priority inheritance to the thread executing
1811 * the thread call in case it's lower priority than the current thread
1812 * <rdar://problem/30321792> Priority inheritance for thread_call_wait_once
1814 * Takes the thread call lock locked, returns unlocked
1815 * This lets us avoid a spurious take/drop after waking up from thread_block
1818 thread_call_wait_once_locked(thread_call_t call
, spl_t s
)
1820 assert(call
->tc_flags
& THREAD_CALL_ALLOC
);
1821 assert(call
->tc_flags
& THREAD_CALL_ONCE
);
1823 if ((call
->tc_flags
& THREAD_CALL_RUNNING
) == 0) {
1824 enable_ints_and_unlock(s
);
1828 /* call is running, so we have to wait for it */
1829 call
->tc_flags
|= THREAD_CALL_WAIT
;
1831 wait_result_t res
= assert_wait(call
, THREAD_UNINT
);
1832 if (res
!= THREAD_WAITING
)
1833 panic("Unable to assert wait: %d", res
);
1835 enable_ints_and_unlock(s
);
1837 res
= thread_block(THREAD_CONTINUE_NULL
);
1838 if (res
!= THREAD_AWAKENED
)
1839 panic("Awoken with %d?", res
);
1841 /* returns unlocked */
1846 * Wait for an in-flight invocation to complete
1847 * Does NOT try to cancel, so the client doesn't need to hold their
1848 * lock while calling this function.
1850 * Returns whether or not it had to wait.
1852 * Only works for THREAD_CALL_ONCE calls.
1855 thread_call_wait_once(thread_call_t call
)
1857 if ((call
->tc_flags
& THREAD_CALL_ALLOC
) == 0)
1858 panic("thread_call_wait_once: can't wait on thread call whose storage I don't own");
1860 if ((call
->tc_flags
& THREAD_CALL_ONCE
) == 0)
1861 panic("thread_call_wait_once: can't wait_once on a non-once call");
1863 if (!ml_get_interrupts_enabled())
1864 panic("unsafe thread_call_wait_once");
1866 if (current_thread()->thc_state
.thc_call
== call
)
1867 panic("thread_call_wait_once: deadlock waiting on self from inside call: %p to function %p",
1868 call
, call
->tc_call
.func
);
1870 spl_t s
= disable_ints_and_lock();
1872 boolean_t waited
= thread_call_wait_once_locked(call
, s
);
1873 /* thread call lock unlocked */
1880 * Wait for all requested invocations of a thread call prior to now
1881 * to finish. Can only be invoked on thread calls whose storage we manage.
1882 * Just waits for the finish count to catch up to the submit count we find
1883 * at the beginning of our wait.
1885 * Called with thread_call_lock held. Returns with lock released.
1888 thread_call_wait_locked(thread_call_t call
, spl_t s
)
1890 uint64_t submit_count
;
1893 assert(call
->tc_flags
& THREAD_CALL_ALLOC
);
1895 submit_count
= call
->tc_submit_count
;
1897 while (call
->tc_finish_count
< submit_count
) {
1898 call
->tc_flags
|= THREAD_CALL_WAIT
;
1900 res
= assert_wait(call
, THREAD_UNINT
);
1901 if (res
!= THREAD_WAITING
)
1902 panic("Unable to assert wait: %d", res
);
1904 enable_ints_and_unlock(s
);
1906 res
= thread_block(THREAD_CONTINUE_NULL
);
1907 if (res
!= THREAD_AWAKENED
)
1908 panic("Awoken with %d?", res
);
1910 s
= disable_ints_and_lock();
1913 enable_ints_and_unlock(s
);
1917 * Determine whether a thread call is either on a queue or
1918 * currently being executed.
1921 thread_call_isactive(thread_call_t call
)
1925 spl_t s
= disable_ints_and_lock();
1926 active
= (call
->tc_submit_count
> call
->tc_finish_count
);
1927 enable_ints_and_unlock(s
);
1933 * adjust_cont_time_thread_calls
1934 * on wake, reenqueue delayed call timer for continuous time thread call groups
1937 adjust_cont_time_thread_calls(void)
1939 spl_t s
= disable_ints_and_lock();
1941 for (int i
= 0; i
< THREAD_CALL_INDEX_MAX
; i
++) {
1942 thread_call_group_t group
= &thread_call_groups
[i
];
1944 /* only the continuous timers need to be re-armed */
1946 _arm_delayed_call_timer(NULL
, group
, TCF_CONTINUOUS
);
1949 enable_ints_and_unlock(s
);