2 * Copyright (c) 2008-2011 Apple Inc. All rights reserved.
4 * @APPLE_APACHE_LICENSE_HEADER_START@
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 * @APPLE_APACHE_LICENSE_HEADER_END@
23 // semaphores are too fundamental to use the dispatch_assume*() macros
25 #define DISPATCH_SEMAPHORE_VERIFY_KR(x) do { \
27 DISPATCH_CRASH("flawed group/semaphore logic"); \
31 #define DISPATCH_SEMAPHORE_VERIFY_RET(x) do { \
32 if (slowpath((x) == -1)) { \
33 DISPATCH_CRASH("flawed group/semaphore logic"); \
38 DISPATCH_WEAK
// rdar://problem/8503746
39 long _dispatch_semaphore_signal_slow(dispatch_semaphore_t dsema
);
41 static long _dispatch_group_wake(dispatch_semaphore_t dsema
);
44 #pragma mark dispatch_semaphore_t
47 _dispatch_semaphore_init(long value
, dispatch_object_t dou
)
49 dispatch_semaphore_t dsema
= dou
._dsema
;
51 dsema
->do_next
= DISPATCH_OBJECT_LISTLESS
;
52 dsema
->do_targetq
= dispatch_get_global_queue(
53 DISPATCH_QUEUE_PRIORITY_DEFAULT
, 0);
54 dsema
->dsema_value
= value
;
55 dsema
->dsema_orig
= value
;
57 int ret
= sem_init(&dsema
->dsema_sem
, 0, 0);
58 DISPATCH_SEMAPHORE_VERIFY_RET(ret
);
63 dispatch_semaphore_create(long value
)
65 dispatch_semaphore_t dsema
;
67 // If the internal value is negative, then the absolute of the value is
68 // equal to the number of waiting threads. Therefore it is bogus to
69 // initialize the semaphore with a negative value.
74 dsema
= _dispatch_alloc(DISPATCH_VTABLE(semaphore
),
75 sizeof(struct dispatch_semaphore_s
));
76 _dispatch_semaphore_init(value
, dsema
);
82 _dispatch_semaphore_create_port(semaphore_t
*s4
)
90 _dispatch_safe_fork
= false;
92 // lazily allocate the semaphore port
95 // 1) Switch to a doubly-linked FIFO in user-space.
96 // 2) User-space timers for the timeout.
97 // 3) Use the per-thread semaphore port.
99 while ((kr
= semaphore_create(mach_task_self(), &tmp
,
100 SYNC_POLICY_FIFO
, 0))) {
101 DISPATCH_VERIFY_MIG(kr
);
105 if (!dispatch_atomic_cmpxchg(s4
, 0, tmp
)) {
106 kr
= semaphore_destroy(mach_task_self(), tmp
);
107 DISPATCH_SEMAPHORE_VERIFY_KR(kr
);
113 _dispatch_semaphore_dispose(dispatch_object_t dou
)
115 dispatch_semaphore_t dsema
= dou
._dsema
;
117 if (dsema
->dsema_value
< dsema
->dsema_orig
) {
118 DISPATCH_CLIENT_CRASH(
119 "Semaphore/group object deallocated while in use");
124 if (dsema
->dsema_port
) {
125 kr
= semaphore_destroy(mach_task_self(), dsema
->dsema_port
);
126 DISPATCH_SEMAPHORE_VERIFY_KR(kr
);
128 if (dsema
->dsema_waiter_port
) {
129 kr
= semaphore_destroy(mach_task_self(), dsema
->dsema_waiter_port
);
130 DISPATCH_SEMAPHORE_VERIFY_KR(kr
);
133 int ret
= sem_destroy(&dsema
->dsema_sem
);
134 DISPATCH_SEMAPHORE_VERIFY_RET(ret
);
139 _dispatch_semaphore_debug(dispatch_object_t dou
, char *buf
, size_t bufsiz
)
141 dispatch_semaphore_t dsema
= dou
._dsema
;
144 offset
+= snprintf(&buf
[offset
], bufsiz
- offset
, "%s[%p] = { ",
145 dx_kind(dsema
), dsema
);
146 offset
+= _dispatch_object_debug_attr(dsema
, &buf
[offset
], bufsiz
- offset
);
148 offset
+= snprintf(&buf
[offset
], bufsiz
- offset
, "port = 0x%u, ",
151 offset
+= snprintf(&buf
[offset
], bufsiz
- offset
,
152 "value = %ld, orig = %ld }", dsema
->dsema_value
, dsema
->dsema_orig
);
158 _dispatch_semaphore_signal_slow(dispatch_semaphore_t dsema
)
160 // Before dsema_sent_ksignals is incremented we can rely on the reference
161 // held by the waiter. However, once this value is incremented the waiter
162 // may return between the atomic increment and the semaphore_signal(),
163 // therefore an explicit reference must be held in order to safely access
164 // dsema after the atomic increment.
165 _dispatch_retain(dsema
);
167 (void)dispatch_atomic_inc2o(dsema
, dsema_sent_ksignals
);
170 _dispatch_semaphore_create_port(&dsema
->dsema_port
);
171 kern_return_t kr
= semaphore_signal(dsema
->dsema_port
);
172 DISPATCH_SEMAPHORE_VERIFY_KR(kr
);
174 int ret
= sem_post(&dsema
->dsema_sem
);
175 DISPATCH_SEMAPHORE_VERIFY_RET(ret
);
178 _dispatch_release(dsema
);
183 dispatch_semaphore_signal(dispatch_semaphore_t dsema
)
185 dispatch_atomic_release_barrier();
186 long value
= dispatch_atomic_inc2o(dsema
, dsema_value
);
187 if (fastpath(value
> 0)) {
190 if (slowpath(value
== LONG_MIN
)) {
191 DISPATCH_CLIENT_CRASH("Unbalanced call to dispatch_group_leave() or "
192 "dispatch_semaphore_signal()");
194 return _dispatch_semaphore_signal_slow(dsema
);
199 _dispatch_semaphore_wait_slow(dispatch_semaphore_t dsema
,
200 dispatch_time_t timeout
)
205 // Mach semaphores appear to sometimes spuriously wake up. Therefore,
206 // we keep a parallel count of the number of times a Mach semaphore is
207 // signaled (6880961).
208 while ((orig
= dsema
->dsema_sent_ksignals
)) {
209 if (dispatch_atomic_cmpxchg2o(dsema
, dsema_sent_ksignals
, orig
,
216 mach_timespec_t _timeout
;
219 _dispatch_semaphore_create_port(&dsema
->dsema_port
);
221 // From xnu/osfmk/kern/sync_sema.c:
222 // wait_semaphore->count = -1; /* we don't keep an actual count */
224 // The code above does not match the documentation, and that fact is
225 // not surprising. The documented semantics are clumsy to use in any
226 // practical way. The above hack effectively tricks the rest of the
227 // Mach semaphore logic to behave like the libdispatch algorithm.
232 uint64_t nsec
= _dispatch_timeout(timeout
);
233 _timeout
.tv_sec
= (typeof(_timeout
.tv_sec
))(nsec
/ NSEC_PER_SEC
);
234 _timeout
.tv_nsec
= (typeof(_timeout
.tv_nsec
))(nsec
% NSEC_PER_SEC
);
235 kr
= slowpath(semaphore_timedwait(dsema
->dsema_port
, _timeout
));
236 } while (kr
== KERN_ABORTED
);
238 if (kr
!= KERN_OPERATION_TIMED_OUT
) {
239 DISPATCH_SEMAPHORE_VERIFY_KR(kr
);
242 // Fall through and try to undo what the fast path did to
243 // dsema->dsema_value
244 case DISPATCH_TIME_NOW
:
245 while ((orig
= dsema
->dsema_value
) < 0) {
246 if (dispatch_atomic_cmpxchg2o(dsema
, dsema_value
, orig
, orig
+ 1)) {
247 return KERN_OPERATION_TIMED_OUT
;
250 // Another thread called semaphore_signal().
251 // Fall through and drain the wakeup.
252 case DISPATCH_TIME_FOREVER
:
254 kr
= semaphore_wait(dsema
->dsema_port
);
255 } while (kr
== KERN_ABORTED
);
256 DISPATCH_SEMAPHORE_VERIFY_KR(kr
);
260 struct timespec _timeout
;
266 uint64_t nsec
= _dispatch_timeout(timeout
);
267 _timeout
.tv_sec
= (typeof(_timeout
.tv_sec
))(nsec
/ NSEC_PER_SEC
);
268 _timeout
.tv_nsec
= (typeof(_timeout
.tv_nsec
))(nsec
% NSEC_PER_SEC
);
269 ret
= slowpath(sem_timedwait(&dsema
->dsema_sem
, &_timeout
));
270 } while (ret
== -1 && errno
== EINTR
);
272 if (ret
== -1 && errno
!= ETIMEDOUT
) {
273 DISPATCH_SEMAPHORE_VERIFY_RET(ret
);
276 // Fall through and try to undo what the fast path did to
277 // dsema->dsema_value
278 case DISPATCH_TIME_NOW
:
279 while ((orig
= dsema
->dsema_value
) < 0) {
280 if (dispatch_atomic_cmpxchg2o(dsema
, dsema_value
, orig
, orig
+ 1)) {
285 // Another thread called semaphore_signal().
286 // Fall through and drain the wakeup.
287 case DISPATCH_TIME_FOREVER
:
289 ret
= sem_wait(&dsema
->dsema_sem
);
291 DISPATCH_SEMAPHORE_VERIFY_RET(ret
);
300 dispatch_semaphore_wait(dispatch_semaphore_t dsema
, dispatch_time_t timeout
)
302 long value
= dispatch_atomic_dec2o(dsema
, dsema_value
);
303 dispatch_atomic_acquire_barrier();
304 if (fastpath(value
>= 0)) {
307 return _dispatch_semaphore_wait_slow(dsema
, timeout
);
311 #pragma mark dispatch_group_t
314 dispatch_group_create(void)
316 dispatch_group_t dg
= _dispatch_alloc(DISPATCH_VTABLE(group
),
317 sizeof(struct dispatch_semaphore_s
));
318 _dispatch_semaphore_init(LONG_MAX
, dg
);
323 dispatch_group_enter(dispatch_group_t dg
)
325 dispatch_semaphore_t dsema
= (dispatch_semaphore_t
)dg
;
327 (void)dispatch_semaphore_wait(dsema
, DISPATCH_TIME_FOREVER
);
332 _dispatch_group_wake(dispatch_semaphore_t dsema
)
334 struct dispatch_sema_notify_s
*next
, *head
, *tail
= NULL
;
337 head
= dispatch_atomic_xchg2o(dsema
, dsema_notify_head
, NULL
);
339 // snapshot before anything is notified/woken <rdar://problem/8554546>
340 tail
= dispatch_atomic_xchg2o(dsema
, dsema_notify_tail
, NULL
);
342 rval
= dispatch_atomic_xchg2o(dsema
, dsema_group_waiters
, 0);
344 // wake group waiters
346 _dispatch_semaphore_create_port(&dsema
->dsema_waiter_port
);
348 kern_return_t kr
= semaphore_signal(dsema
->dsema_waiter_port
);
349 DISPATCH_SEMAPHORE_VERIFY_KR(kr
);
353 int ret
= sem_post(&dsema
->dsema_sem
);
354 DISPATCH_SEMAPHORE_VERIFY_RET(ret
);
359 // async group notify blocks
361 dispatch_async_f(head
->dsn_queue
, head
->dsn_ctxt
, head
->dsn_func
);
362 _dispatch_release(head
->dsn_queue
);
363 next
= fastpath(head
->dsn_next
);
364 if (!next
&& head
!= tail
) {
365 while (!(next
= fastpath(head
->dsn_next
))) {
366 _dispatch_hardware_pause();
370 } while ((head
= next
));
371 _dispatch_release(dsema
);
377 dispatch_group_leave(dispatch_group_t dg
)
379 dispatch_semaphore_t dsema
= (dispatch_semaphore_t
)dg
;
381 dispatch_semaphore_signal(dsema
);
382 if (dsema
->dsema_value
== dsema
->dsema_orig
) {
383 (void)_dispatch_group_wake(dsema
);
389 _dispatch_group_wait_slow(dispatch_semaphore_t dsema
, dispatch_time_t timeout
)
394 // check before we cause another signal to be sent by incrementing
395 // dsema->dsema_group_waiters
396 if (dsema
->dsema_value
== dsema
->dsema_orig
) {
397 return _dispatch_group_wake(dsema
);
399 // Mach semaphores appear to sometimes spuriously wake up. Therefore,
400 // we keep a parallel count of the number of times a Mach semaphore is
401 // signaled (6880961).
402 (void)dispatch_atomic_inc2o(dsema
, dsema_group_waiters
);
403 // check the values again in case we need to wake any threads
404 if (dsema
->dsema_value
== dsema
->dsema_orig
) {
405 return _dispatch_group_wake(dsema
);
409 mach_timespec_t _timeout
;
412 _dispatch_semaphore_create_port(&dsema
->dsema_waiter_port
);
414 // From xnu/osfmk/kern/sync_sema.c:
415 // wait_semaphore->count = -1; /* we don't keep an actual count */
417 // The code above does not match the documentation, and that fact is
418 // not surprising. The documented semantics are clumsy to use in any
419 // practical way. The above hack effectively tricks the rest of the
420 // Mach semaphore logic to behave like the libdispatch algorithm.
425 uint64_t nsec
= _dispatch_timeout(timeout
);
426 _timeout
.tv_sec
= (typeof(_timeout
.tv_sec
))(nsec
/ NSEC_PER_SEC
);
427 _timeout
.tv_nsec
= (typeof(_timeout
.tv_nsec
))(nsec
% NSEC_PER_SEC
);
428 kr
= slowpath(semaphore_timedwait(dsema
->dsema_waiter_port
,
430 } while (kr
== KERN_ABORTED
);
432 if (kr
!= KERN_OPERATION_TIMED_OUT
) {
433 DISPATCH_SEMAPHORE_VERIFY_KR(kr
);
436 // Fall through and try to undo the earlier change to
437 // dsema->dsema_group_waiters
438 case DISPATCH_TIME_NOW
:
439 while ((orig
= dsema
->dsema_group_waiters
)) {
440 if (dispatch_atomic_cmpxchg2o(dsema
, dsema_group_waiters
, orig
,
442 return KERN_OPERATION_TIMED_OUT
;
445 // Another thread called semaphore_signal().
446 // Fall through and drain the wakeup.
447 case DISPATCH_TIME_FOREVER
:
449 kr
= semaphore_wait(dsema
->dsema_waiter_port
);
450 } while (kr
== KERN_ABORTED
);
451 DISPATCH_SEMAPHORE_VERIFY_KR(kr
);
455 struct timespec _timeout
;
461 uint64_t nsec
= _dispatch_timeout(timeout
);
462 _timeout
.tv_sec
= (typeof(_timeout
.tv_sec
))(nsec
/ NSEC_PER_SEC
);
463 _timeout
.tv_nsec
= (typeof(_timeout
.tv_nsec
))(nsec
% NSEC_PER_SEC
);
464 ret
= slowpath(sem_timedwait(&dsema
->dsema_sem
, &_timeout
));
465 } while (ret
== -1 && errno
== EINTR
);
467 if (!(ret
== -1 && errno
== ETIMEDOUT
)) {
468 DISPATCH_SEMAPHORE_VERIFY_RET(ret
);
471 // Fall through and try to undo the earlier change to
472 // dsema->dsema_group_waiters
473 case DISPATCH_TIME_NOW
:
474 while ((orig
= dsema
->dsema_group_waiters
)) {
475 if (dispatch_atomic_cmpxchg2o(dsema
, dsema_group_waiters
, orig
,
481 // Another thread called semaphore_signal().
482 // Fall through and drain the wakeup.
483 case DISPATCH_TIME_FOREVER
:
485 ret
= sem_wait(&dsema
->dsema_sem
);
486 } while (ret
== -1 && errno
== EINTR
);
487 DISPATCH_SEMAPHORE_VERIFY_RET(ret
);
496 dispatch_group_wait(dispatch_group_t dg
, dispatch_time_t timeout
)
498 dispatch_semaphore_t dsema
= (dispatch_semaphore_t
)dg
;
500 if (dsema
->dsema_value
== dsema
->dsema_orig
) {
505 return KERN_OPERATION_TIMED_OUT
;
511 return _dispatch_group_wait_slow(dsema
, timeout
);
516 dispatch_group_notify_f(dispatch_group_t dg
, dispatch_queue_t dq
, void *ctxt
,
517 void (*func
)(void *))
519 dispatch_semaphore_t dsema
= (dispatch_semaphore_t
)dg
;
520 struct dispatch_sema_notify_s
*dsn
, *prev
;
522 // FIXME -- this should be updated to use the continuation cache
523 while (!(dsn
= calloc(1, sizeof(*dsn
)))) {
528 dsn
->dsn_ctxt
= ctxt
;
529 dsn
->dsn_func
= func
;
530 _dispatch_retain(dq
);
531 dispatch_atomic_store_barrier();
532 prev
= dispatch_atomic_xchg2o(dsema
, dsema_notify_tail
, dsn
);
533 if (fastpath(prev
)) {
534 prev
->dsn_next
= dsn
;
536 _dispatch_retain(dg
);
537 dsema
->dsema_notify_head
= dsn
;
538 if (dsema
->dsema_value
== dsema
->dsema_orig
) {
539 _dispatch_group_wake(dsema
);
546 dispatch_group_notify(dispatch_group_t dg
, dispatch_queue_t dq
,
549 dispatch_group_notify_f(dg
, dq
, _dispatch_Block_copy(db
),
550 _dispatch_call_block_and_release
);
555 #pragma mark _dispatch_thread_semaphore_t
558 static _dispatch_thread_semaphore_t
559 _dispatch_thread_semaphore_create(void)
561 _dispatch_safe_fork
= false;
565 while (slowpath(kr
= semaphore_create(mach_task_self(), &s4
,
566 SYNC_POLICY_FIFO
, 0))) {
567 DISPATCH_VERIFY_MIG(kr
);
573 int ret
= sem_init(&s4
, 0, 0);
574 DISPATCH_SEMAPHORE_VERIFY_RET(ret
);
581 _dispatch_thread_semaphore_dispose(_dispatch_thread_semaphore_t sema
)
584 semaphore_t s4
= (semaphore_t
)sema
;
585 kern_return_t kr
= semaphore_destroy(mach_task_self(), s4
);
586 DISPATCH_SEMAPHORE_VERIFY_KR(kr
);
588 sem_t s4
= (sem_t
)sema
;
589 int ret
= sem_destroy(&s4
);
590 DISPATCH_SEMAPHORE_VERIFY_RET(ret
);
595 _dispatch_thread_semaphore_signal(_dispatch_thread_semaphore_t sema
)
598 semaphore_t s4
= (semaphore_t
)sema
;
599 kern_return_t kr
= semaphore_signal(s4
);
600 DISPATCH_SEMAPHORE_VERIFY_KR(kr
);
602 sem_t s4
= (sem_t
)sema
;
603 int ret
= sem_post(&s4
);
604 DISPATCH_SEMAPHORE_VERIFY_RET(ret
);
609 _dispatch_thread_semaphore_wait(_dispatch_thread_semaphore_t sema
)
612 semaphore_t s4
= (semaphore_t
)sema
;
615 kr
= semaphore_wait(s4
);
616 } while (slowpath(kr
== KERN_ABORTED
));
617 DISPATCH_SEMAPHORE_VERIFY_KR(kr
);
619 sem_t s4
= (sem_t
)sema
;
623 } while (slowpath(ret
!= 0));
624 DISPATCH_SEMAPHORE_VERIFY_RET(ret
);
628 _dispatch_thread_semaphore_t
629 _dispatch_get_thread_semaphore(void)
631 _dispatch_thread_semaphore_t sema
= (_dispatch_thread_semaphore_t
)
632 _dispatch_thread_getspecific(dispatch_sema4_key
);
633 if (slowpath(!sema
)) {
634 return _dispatch_thread_semaphore_create();
636 _dispatch_thread_setspecific(dispatch_sema4_key
, NULL
);
641 _dispatch_put_thread_semaphore(_dispatch_thread_semaphore_t sema
)
643 _dispatch_thread_semaphore_t old_sema
= (_dispatch_thread_semaphore_t
)
644 _dispatch_thread_getspecific(dispatch_sema4_key
);
645 _dispatch_thread_setspecific(dispatch_sema4_key
, (void*)sema
);
646 if (slowpath(old_sema
)) {
647 return _dispatch_thread_semaphore_dispose(old_sema
);