2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2005, David Xu <davidxu@freebsd.org>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice unmodified, this list of conditions, and the following
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include "namespace.h"
34 #include "un-namespace.h"
36 #include "thr_private.h"
38 __weak_reference(_pthread_once, pthread_once);
40 #define ONCE_NEVER_DONE PTHREAD_NEEDS_INIT
41 #define ONCE_DONE PTHREAD_DONE_INIT
42 #define ONCE_IN_PROGRESS 0x02
43 #define ONCE_WAIT 0x03
47 * The pthread_once() function is not a cancellation point. However,
48 * if init_routine is a cancellation point and is canceled, the effect
49 * on once_control shall be as if pthread_once() was never called.
53 once_cancel_handler(void *arg)
55 pthread_once_t *once_control;
58 if (atomic_cmpset_rel_int(&once_control->state, ONCE_IN_PROGRESS,
61 atomic_store_rel_int(&once_control->state, ONCE_NEVER_DONE);
62 _thr_umtx_wake(&once_control->state, INT_MAX, 0);
66 _pthread_once(pthread_once_t *once_control, void (*init_routine) (void))
68 struct pthread *curthread;
74 state = once_control->state;
75 if (state == ONCE_DONE) {
76 atomic_thread_fence_acq();
79 if (state == ONCE_NEVER_DONE) {
80 if (atomic_cmpset_int(&once_control->state, state,
83 } else if (state == ONCE_IN_PROGRESS) {
84 if (atomic_cmpset_int(&once_control->state, state,
86 _thr_umtx_wait_uint(&once_control->state,
88 } else if (state == ONCE_WAIT) {
89 _thr_umtx_wait_uint(&once_control->state, state,
95 curthread = _get_curthread();
96 THR_CLEANUP_PUSH(curthread, once_cancel_handler, once_control);
98 THR_CLEANUP_POP(curthread, 0);
99 if (atomic_cmpset_rel_int(&once_control->state, ONCE_IN_PROGRESS,
102 atomic_store_rel_int(&once_control->state, ONCE_DONE);
103 _thr_umtx_wake(&once_control->state, INT_MAX, 0);