1*9356374aSAndroid Build Coastguard Worker // Copyright 2017 The Abseil Authors.
2*9356374aSAndroid Build Coastguard Worker //
3*9356374aSAndroid Build Coastguard Worker // Licensed under the Apache License, Version 2.0 (the "License");
4*9356374aSAndroid Build Coastguard Worker // you may not use this file except in compliance with the License.
5*9356374aSAndroid Build Coastguard Worker // You may obtain a copy of the License at
6*9356374aSAndroid Build Coastguard Worker //
7*9356374aSAndroid Build Coastguard Worker // https://www.apache.org/licenses/LICENSE-2.0
8*9356374aSAndroid Build Coastguard Worker //
9*9356374aSAndroid Build Coastguard Worker // Unless required by applicable law or agreed to in writing, software
10*9356374aSAndroid Build Coastguard Worker // distributed under the License is distributed on an "AS IS" BASIS,
11*9356374aSAndroid Build Coastguard Worker // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12*9356374aSAndroid Build Coastguard Worker // See the License for the specific language governing permissions and
13*9356374aSAndroid Build Coastguard Worker // limitations under the License.
14*9356374aSAndroid Build Coastguard Worker //
15*9356374aSAndroid Build Coastguard Worker // -----------------------------------------------------------------------------
16*9356374aSAndroid Build Coastguard Worker // File: call_once.h
17*9356374aSAndroid Build Coastguard Worker // -----------------------------------------------------------------------------
18*9356374aSAndroid Build Coastguard Worker //
19*9356374aSAndroid Build Coastguard Worker // This header file provides an Abseil version of `std::call_once` for invoking
20*9356374aSAndroid Build Coastguard Worker // a given function at most once, across all threads. This Abseil version is
21*9356374aSAndroid Build Coastguard Worker // faster than the C++11 version and incorporates the C++17 argument-passing
22*9356374aSAndroid Build Coastguard Worker // fix, so that (for example) non-const references may be passed to the invoked
23*9356374aSAndroid Build Coastguard Worker // function.
24*9356374aSAndroid Build Coastguard Worker
25*9356374aSAndroid Build Coastguard Worker #ifndef ABSL_BASE_CALL_ONCE_H_
26*9356374aSAndroid Build Coastguard Worker #define ABSL_BASE_CALL_ONCE_H_
27*9356374aSAndroid Build Coastguard Worker
28*9356374aSAndroid Build Coastguard Worker #include <algorithm>
29*9356374aSAndroid Build Coastguard Worker #include <atomic>
30*9356374aSAndroid Build Coastguard Worker #include <cstdint>
31*9356374aSAndroid Build Coastguard Worker #include <type_traits>
32*9356374aSAndroid Build Coastguard Worker #include <utility>
33*9356374aSAndroid Build Coastguard Worker
34*9356374aSAndroid Build Coastguard Worker #include "absl/base/internal/invoke.h"
35*9356374aSAndroid Build Coastguard Worker #include "absl/base/internal/low_level_scheduling.h"
36*9356374aSAndroid Build Coastguard Worker #include "absl/base/internal/raw_logging.h"
37*9356374aSAndroid Build Coastguard Worker #include "absl/base/internal/scheduling_mode.h"
38*9356374aSAndroid Build Coastguard Worker #include "absl/base/internal/spinlock_wait.h"
39*9356374aSAndroid Build Coastguard Worker #include "absl/base/macros.h"
40*9356374aSAndroid Build Coastguard Worker #include "absl/base/nullability.h"
41*9356374aSAndroid Build Coastguard Worker #include "absl/base/optimization.h"
42*9356374aSAndroid Build Coastguard Worker #include "absl/base/port.h"
43*9356374aSAndroid Build Coastguard Worker
44*9356374aSAndroid Build Coastguard Worker namespace absl {
45*9356374aSAndroid Build Coastguard Worker ABSL_NAMESPACE_BEGIN
46*9356374aSAndroid Build Coastguard Worker
47*9356374aSAndroid Build Coastguard Worker class once_flag;
48*9356374aSAndroid Build Coastguard Worker
49*9356374aSAndroid Build Coastguard Worker namespace base_internal {
50*9356374aSAndroid Build Coastguard Worker absl::Nonnull<std::atomic<uint32_t>*> ControlWord(
51*9356374aSAndroid Build Coastguard Worker absl::Nonnull<absl::once_flag*> flag);
52*9356374aSAndroid Build Coastguard Worker } // namespace base_internal
53*9356374aSAndroid Build Coastguard Worker
54*9356374aSAndroid Build Coastguard Worker // call_once()
55*9356374aSAndroid Build Coastguard Worker //
56*9356374aSAndroid Build Coastguard Worker // For all invocations using a given `once_flag`, invokes a given `fn` exactly
57*9356374aSAndroid Build Coastguard Worker // once across all threads. The first call to `call_once()` with a particular
58*9356374aSAndroid Build Coastguard Worker // `once_flag` argument (that does not throw an exception) will run the
59*9356374aSAndroid Build Coastguard Worker // specified function with the provided `args`; other calls with the same
60*9356374aSAndroid Build Coastguard Worker // `once_flag` argument will not run the function, but will wait
61*9356374aSAndroid Build Coastguard Worker // for the provided function to finish running (if it is still running).
62*9356374aSAndroid Build Coastguard Worker //
63*9356374aSAndroid Build Coastguard Worker // This mechanism provides a safe, simple, and fast mechanism for one-time
64*9356374aSAndroid Build Coastguard Worker // initialization in a multi-threaded process.
65*9356374aSAndroid Build Coastguard Worker //
66*9356374aSAndroid Build Coastguard Worker // Example:
67*9356374aSAndroid Build Coastguard Worker //
68*9356374aSAndroid Build Coastguard Worker // class MyInitClass {
69*9356374aSAndroid Build Coastguard Worker // public:
70*9356374aSAndroid Build Coastguard Worker // ...
71*9356374aSAndroid Build Coastguard Worker // mutable absl::once_flag once_;
72*9356374aSAndroid Build Coastguard Worker //
73*9356374aSAndroid Build Coastguard Worker // MyInitClass* init() const {
74*9356374aSAndroid Build Coastguard Worker // absl::call_once(once_, &MyInitClass::Init, this);
75*9356374aSAndroid Build Coastguard Worker // return ptr_;
76*9356374aSAndroid Build Coastguard Worker // }
77*9356374aSAndroid Build Coastguard Worker //
78*9356374aSAndroid Build Coastguard Worker template <typename Callable, typename... Args>
79*9356374aSAndroid Build Coastguard Worker void call_once(absl::once_flag& flag, Callable&& fn, Args&&... args);
80*9356374aSAndroid Build Coastguard Worker
81*9356374aSAndroid Build Coastguard Worker // once_flag
82*9356374aSAndroid Build Coastguard Worker //
83*9356374aSAndroid Build Coastguard Worker // Objects of this type are used to distinguish calls to `call_once()` and
84*9356374aSAndroid Build Coastguard Worker // ensure the provided function is only invoked once across all threads. This
85*9356374aSAndroid Build Coastguard Worker // type is not copyable or movable. However, it has a `constexpr`
86*9356374aSAndroid Build Coastguard Worker // constructor, and is safe to use as a namespace-scoped global variable.
87*9356374aSAndroid Build Coastguard Worker class once_flag {
88*9356374aSAndroid Build Coastguard Worker public:
once_flag()89*9356374aSAndroid Build Coastguard Worker constexpr once_flag() : control_(0) {}
90*9356374aSAndroid Build Coastguard Worker once_flag(const once_flag&) = delete;
91*9356374aSAndroid Build Coastguard Worker once_flag& operator=(const once_flag&) = delete;
92*9356374aSAndroid Build Coastguard Worker
93*9356374aSAndroid Build Coastguard Worker private:
94*9356374aSAndroid Build Coastguard Worker friend absl::Nonnull<std::atomic<uint32_t>*> base_internal::ControlWord(
95*9356374aSAndroid Build Coastguard Worker absl::Nonnull<once_flag*> flag);
96*9356374aSAndroid Build Coastguard Worker std::atomic<uint32_t> control_;
97*9356374aSAndroid Build Coastguard Worker };
98*9356374aSAndroid Build Coastguard Worker
99*9356374aSAndroid Build Coastguard Worker //------------------------------------------------------------------------------
100*9356374aSAndroid Build Coastguard Worker // End of public interfaces.
101*9356374aSAndroid Build Coastguard Worker // Implementation details follow.
102*9356374aSAndroid Build Coastguard Worker //------------------------------------------------------------------------------
103*9356374aSAndroid Build Coastguard Worker
104*9356374aSAndroid Build Coastguard Worker namespace base_internal {
105*9356374aSAndroid Build Coastguard Worker
106*9356374aSAndroid Build Coastguard Worker // Like call_once, but uses KERNEL_ONLY scheduling. Intended to be used to
107*9356374aSAndroid Build Coastguard Worker // initialize entities used by the scheduler implementation.
108*9356374aSAndroid Build Coastguard Worker template <typename Callable, typename... Args>
109*9356374aSAndroid Build Coastguard Worker void LowLevelCallOnce(absl::Nonnull<absl::once_flag*> flag, Callable&& fn,
110*9356374aSAndroid Build Coastguard Worker Args&&... args);
111*9356374aSAndroid Build Coastguard Worker
112*9356374aSAndroid Build Coastguard Worker // Disables scheduling while on stack when scheduling mode is non-cooperative.
113*9356374aSAndroid Build Coastguard Worker // No effect for cooperative scheduling modes.
114*9356374aSAndroid Build Coastguard Worker class SchedulingHelper {
115*9356374aSAndroid Build Coastguard Worker public:
SchedulingHelper(base_internal::SchedulingMode mode)116*9356374aSAndroid Build Coastguard Worker explicit SchedulingHelper(base_internal::SchedulingMode mode) : mode_(mode) {
117*9356374aSAndroid Build Coastguard Worker if (mode_ == base_internal::SCHEDULE_KERNEL_ONLY) {
118*9356374aSAndroid Build Coastguard Worker guard_result_ = base_internal::SchedulingGuard::DisableRescheduling();
119*9356374aSAndroid Build Coastguard Worker }
120*9356374aSAndroid Build Coastguard Worker }
121*9356374aSAndroid Build Coastguard Worker
~SchedulingHelper()122*9356374aSAndroid Build Coastguard Worker ~SchedulingHelper() {
123*9356374aSAndroid Build Coastguard Worker if (mode_ == base_internal::SCHEDULE_KERNEL_ONLY) {
124*9356374aSAndroid Build Coastguard Worker base_internal::SchedulingGuard::EnableRescheduling(guard_result_);
125*9356374aSAndroid Build Coastguard Worker }
126*9356374aSAndroid Build Coastguard Worker }
127*9356374aSAndroid Build Coastguard Worker
128*9356374aSAndroid Build Coastguard Worker private:
129*9356374aSAndroid Build Coastguard Worker base_internal::SchedulingMode mode_;
130*9356374aSAndroid Build Coastguard Worker bool guard_result_ = false;
131*9356374aSAndroid Build Coastguard Worker };
132*9356374aSAndroid Build Coastguard Worker
133*9356374aSAndroid Build Coastguard Worker // Bit patterns for call_once state machine values. Internal implementation
134*9356374aSAndroid Build Coastguard Worker // detail, not for use by clients.
135*9356374aSAndroid Build Coastguard Worker //
136*9356374aSAndroid Build Coastguard Worker // The bit patterns are arbitrarily chosen from unlikely values, to aid in
137*9356374aSAndroid Build Coastguard Worker // debugging. However, kOnceInit must be 0, so that a zero-initialized
138*9356374aSAndroid Build Coastguard Worker // once_flag will be valid for immediate use.
139*9356374aSAndroid Build Coastguard Worker enum {
140*9356374aSAndroid Build Coastguard Worker kOnceInit = 0,
141*9356374aSAndroid Build Coastguard Worker kOnceRunning = 0x65C2937B,
142*9356374aSAndroid Build Coastguard Worker kOnceWaiter = 0x05A308D2,
143*9356374aSAndroid Build Coastguard Worker // A very small constant is chosen for kOnceDone so that it fit in a single
144*9356374aSAndroid Build Coastguard Worker // compare with immediate instruction for most common ISAs. This is verified
145*9356374aSAndroid Build Coastguard Worker // for x86, POWER and ARM.
146*9356374aSAndroid Build Coastguard Worker kOnceDone = 221, // Random Number
147*9356374aSAndroid Build Coastguard Worker };
148*9356374aSAndroid Build Coastguard Worker
149*9356374aSAndroid Build Coastguard Worker template <typename Callable, typename... Args>
CallOnceImpl(absl::Nonnull<std::atomic<uint32_t> * > control,base_internal::SchedulingMode scheduling_mode,Callable && fn,Args &&...args)150*9356374aSAndroid Build Coastguard Worker ABSL_ATTRIBUTE_NOINLINE void CallOnceImpl(
151*9356374aSAndroid Build Coastguard Worker absl::Nonnull<std::atomic<uint32_t>*> control,
152*9356374aSAndroid Build Coastguard Worker base_internal::SchedulingMode scheduling_mode, Callable&& fn,
153*9356374aSAndroid Build Coastguard Worker Args&&... args) {
154*9356374aSAndroid Build Coastguard Worker #ifndef NDEBUG
155*9356374aSAndroid Build Coastguard Worker {
156*9356374aSAndroid Build Coastguard Worker uint32_t old_control = control->load(std::memory_order_relaxed);
157*9356374aSAndroid Build Coastguard Worker if (old_control != kOnceInit &&
158*9356374aSAndroid Build Coastguard Worker old_control != kOnceRunning &&
159*9356374aSAndroid Build Coastguard Worker old_control != kOnceWaiter &&
160*9356374aSAndroid Build Coastguard Worker old_control != kOnceDone) {
161*9356374aSAndroid Build Coastguard Worker ABSL_RAW_LOG(FATAL, "Unexpected value for control word: 0x%lx",
162*9356374aSAndroid Build Coastguard Worker static_cast<unsigned long>(old_control)); // NOLINT
163*9356374aSAndroid Build Coastguard Worker }
164*9356374aSAndroid Build Coastguard Worker }
165*9356374aSAndroid Build Coastguard Worker #endif // NDEBUG
166*9356374aSAndroid Build Coastguard Worker static const base_internal::SpinLockWaitTransition trans[] = {
167*9356374aSAndroid Build Coastguard Worker {kOnceInit, kOnceRunning, true},
168*9356374aSAndroid Build Coastguard Worker {kOnceRunning, kOnceWaiter, false},
169*9356374aSAndroid Build Coastguard Worker {kOnceDone, kOnceDone, true}};
170*9356374aSAndroid Build Coastguard Worker
171*9356374aSAndroid Build Coastguard Worker // Must do this before potentially modifying control word's state.
172*9356374aSAndroid Build Coastguard Worker base_internal::SchedulingHelper maybe_disable_scheduling(scheduling_mode);
173*9356374aSAndroid Build Coastguard Worker // Short circuit the simplest case to avoid procedure call overhead.
174*9356374aSAndroid Build Coastguard Worker // The base_internal::SpinLockWait() call returns either kOnceInit or
175*9356374aSAndroid Build Coastguard Worker // kOnceDone. If it returns kOnceDone, it must have loaded the control word
176*9356374aSAndroid Build Coastguard Worker // with std::memory_order_acquire and seen a value of kOnceDone.
177*9356374aSAndroid Build Coastguard Worker uint32_t old_control = kOnceInit;
178*9356374aSAndroid Build Coastguard Worker if (control->compare_exchange_strong(old_control, kOnceRunning,
179*9356374aSAndroid Build Coastguard Worker std::memory_order_relaxed) ||
180*9356374aSAndroid Build Coastguard Worker base_internal::SpinLockWait(control, ABSL_ARRAYSIZE(trans), trans,
181*9356374aSAndroid Build Coastguard Worker scheduling_mode) == kOnceInit) {
182*9356374aSAndroid Build Coastguard Worker base_internal::invoke(std::forward<Callable>(fn),
183*9356374aSAndroid Build Coastguard Worker std::forward<Args>(args)...);
184*9356374aSAndroid Build Coastguard Worker old_control =
185*9356374aSAndroid Build Coastguard Worker control->exchange(base_internal::kOnceDone, std::memory_order_release);
186*9356374aSAndroid Build Coastguard Worker if (old_control == base_internal::kOnceWaiter) {
187*9356374aSAndroid Build Coastguard Worker base_internal::SpinLockWake(control, true);
188*9356374aSAndroid Build Coastguard Worker }
189*9356374aSAndroid Build Coastguard Worker } // else *control is already kOnceDone
190*9356374aSAndroid Build Coastguard Worker }
191*9356374aSAndroid Build Coastguard Worker
ControlWord(absl::Nonnull<once_flag * > flag)192*9356374aSAndroid Build Coastguard Worker inline absl::Nonnull<std::atomic<uint32_t>*> ControlWord(
193*9356374aSAndroid Build Coastguard Worker absl::Nonnull<once_flag*> flag) {
194*9356374aSAndroid Build Coastguard Worker return &flag->control_;
195*9356374aSAndroid Build Coastguard Worker }
196*9356374aSAndroid Build Coastguard Worker
197*9356374aSAndroid Build Coastguard Worker template <typename Callable, typename... Args>
LowLevelCallOnce(absl::Nonnull<absl::once_flag * > flag,Callable && fn,Args &&...args)198*9356374aSAndroid Build Coastguard Worker void LowLevelCallOnce(absl::Nonnull<absl::once_flag*> flag, Callable&& fn,
199*9356374aSAndroid Build Coastguard Worker Args&&... args) {
200*9356374aSAndroid Build Coastguard Worker std::atomic<uint32_t>* once = base_internal::ControlWord(flag);
201*9356374aSAndroid Build Coastguard Worker uint32_t s = once->load(std::memory_order_acquire);
202*9356374aSAndroid Build Coastguard Worker if (ABSL_PREDICT_FALSE(s != base_internal::kOnceDone)) {
203*9356374aSAndroid Build Coastguard Worker base_internal::CallOnceImpl(once, base_internal::SCHEDULE_KERNEL_ONLY,
204*9356374aSAndroid Build Coastguard Worker std::forward<Callable>(fn),
205*9356374aSAndroid Build Coastguard Worker std::forward<Args>(args)...);
206*9356374aSAndroid Build Coastguard Worker }
207*9356374aSAndroid Build Coastguard Worker }
208*9356374aSAndroid Build Coastguard Worker
209*9356374aSAndroid Build Coastguard Worker } // namespace base_internal
210*9356374aSAndroid Build Coastguard Worker
211*9356374aSAndroid Build Coastguard Worker template <typename Callable, typename... Args>
call_once(absl::once_flag & flag,Callable && fn,Args &&...args)212*9356374aSAndroid Build Coastguard Worker void call_once(absl::once_flag& flag, Callable&& fn, Args&&... args) {
213*9356374aSAndroid Build Coastguard Worker std::atomic<uint32_t>* once = base_internal::ControlWord(&flag);
214*9356374aSAndroid Build Coastguard Worker uint32_t s = once->load(std::memory_order_acquire);
215*9356374aSAndroid Build Coastguard Worker if (ABSL_PREDICT_FALSE(s != base_internal::kOnceDone)) {
216*9356374aSAndroid Build Coastguard Worker base_internal::CallOnceImpl(
217*9356374aSAndroid Build Coastguard Worker once, base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL,
218*9356374aSAndroid Build Coastguard Worker std::forward<Callable>(fn), std::forward<Args>(args)...);
219*9356374aSAndroid Build Coastguard Worker }
220*9356374aSAndroid Build Coastguard Worker }
221*9356374aSAndroid Build Coastguard Worker
222*9356374aSAndroid Build Coastguard Worker ABSL_NAMESPACE_END
223*9356374aSAndroid Build Coastguard Worker } // namespace absl
224*9356374aSAndroid Build Coastguard Worker
225*9356374aSAndroid Build Coastguard Worker #endif // ABSL_BASE_CALL_ONCE_H_
226