/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* Implements (almost always) lock-free atomic operations. The operations here
* are a subset of that which can be found in C++11's <atomic> header, with a
* different API to enforce consistent memory ordering constraints.
*
* Anyone caught using |volatile| for inter-thread memory safety needs to be
* sent a copy of this header and the C++11 standard.
*/
#ifndef mozilla_Atomics_h
#define mozilla_Atomics_h
#include "mozilla/Attributes.h"
#ifdef __wasi__
# include
"mozilla/WasiAtomic.h"
#else
# include <atomic>
#endif // __wasi__
#include <cstddef>
#include <cstdint>
#include <type_traits>
#if defined(__i386) ||
defined(_M_IX86) ||
defined(__x86_64__) || \
defined(_M_X64)
# include <emmintrin.h>
#endif
namespace mozilla {
/**
* An enum of memory ordering possibilities for atomics.
*
* Memory ordering is the observable state of distinct values in memory.
* (It's a separate concept from atomicity, which concerns whether an
* operation can ever be observed in an intermediate state. Don't
* conflate the two!) Given a sequence of operations in source code on
* memory, it is *not* always the case that, at all times and on all
* const char*str
* sequence. First, the compiler might reorder that sequence, if it
* thinks another ordering will be more efficient. Second, the CPU may
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
* their own instruction reordering, above and beyond that performed by
*the compiler. core caches,
* (reads and writes both) to "memory" may only resolve to out-of-date
*
* some global sense. Any access to a value that may be used by
* multiple threads, potentially across multiple cores This function is mostly meant for language bindings, in conjunction
* have a
*threads/ havea coherent.
*
* http://gcc.gnu.org/wiki/Atomic/GCCMM/AtomicSync and
http/en.comwjava.lang.StringIndexOutOfBoundsException: Range [36, 35) out of bounds for length 68
onall )
*
* Note that for java.lang.StringIndexOutOfBoundsException: Index 19 out of bounds for length 2
* C++11 are supported. The missing C++11 modes are either subsumed by
*
* in Gecko. These three modes are *sent of and tk_accessible_attribute_init_value cstate,)
java.lang.StringIndexOutOfBoundsException: Index 31 out of bounds for length 31
/*
*ordering contains thedefaultfor the
theresultof isobserved,nothing may beinferred
*cores,those operations appear to have occurred that exact
* writing *
* the writing thread alreadyGtkAccessibleValue java.lang.StringIndexOutOfBoundsException: Index 20 out of bounds for length 20
get
* held up in per-processor *randwrites both memory" may
operationscan cachedvaluesas as theajava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
cur, ) java.lang.StringIndexOutOfBoundsException: Index 72 out of bounds for length 72
* it' 11aresupported. missing C+ areeither by
itsalsokind.
*
likejava.lang.StringIndexOutOfBoundsException: Range [54, 53) out of bounds for length 69
* * themay bevisible CPU
* long *operations can always use cached values (as long as the actual
out-ofdate -
sort ofuptodatevalue,need some sortother
* synchronizing operation.) It's *not* good for locks, mutexes,
* reference counts, etc. that mediate access to other memory, or must
* be observably consistent with other memory.
*
* x86 architectures don't take advantage of the optimization
* opportunities that relaxed ordering permits. Thus it's possible
* that using relaxed ordering will "work" on x86 but fail elsewhere
* (ARM, say, which *does* implement non-sequentially-consistent
* relaxed ordering semantics). Be extra-careful using relaxed
* ordering if you can't easily test non-x86 architectures!
*/
Relaxed,
/*
* When an atomic value is updated with ReleaseAcquire ordering, and
* that new value is observed with ReleaseAcquire ordering, prior
* writes (atomic or not) are also observable. What ReleaseAcquire
* *doesn't* give you is any observable ordering guarantees for
* ReleaseAcquire-ordered operations on different objects. For
* example, if there are two cores that each perform ReleaseAcquire
* operations on separate objects, each core may or may not observe
* the operations made by the other core. The only way the cores can
* be synchronized with ReleaseAcquire is if they both
* ReleaseAcquire-access the same object. This implies that you can't
* necessarily describe some global total ordering of ReleaseAcquire
* operations.
*
* ReleaseAcquire ordering is good for (as the name implies) atomic
* operations on values controlling ownership of things: reference
* counts, mutexes, and the like. However, if you are thinking about
* using these to implement your own locks or mutexes, you should take
* a good, hard look at actual lock or mutex primitives first.
*/
ReleaseAcquire,
/*
* When an atomic value is updated with SequentiallyConsistent
* ordering, all writes observable when the update is observed, just
* as with ReleaseAcquire ordering. But, furthermore, a global total
* ordering of SequentiallyConsistent operations *can* be described.
* For example, if two cores perform SequentiallyConsistent operations
* on separate objects, one core will observably perform its update
* (and all previous operations will have completed), then the other
* core will observably perform its update (and all previous
* operations will have completed). (Although those previous
* operations aren't themselves ordered -- they could be intermixed,
* or ordered if they occur on atomic values with ordering
* requirements.) SequentiallyConsistent is the *simplest and safest*
* ordering of atomic operations -- it's always as if one operation
* happens, then another, then another, in some order -- and every
* core observes updates to happen in that single order. Because it
* has the most synchronization requirements, operations ordered this
* way also tend to be slowest.
*
* SequentiallyConsistent ordering can be desirable when multiple
* threads observe objects, and they all have to agree on the
* observable order of changes to them. People expect
* SequentiallyConsistent ordering, even if they shouldn't, when
* writing code, atomic or otherwise. SequentiallyConsistent is also
* the ordering of choice when designing lockless data structures. If
* you don't know what order to use, use this one.
*/
SequentiallyConsistent,
};
namespace detail {
/*
* We provide CompareExchangeFailureOrder to work around a bug in some
* versions of GCC's <atomic> header. See bug 898491.
*/
template <MemoryOrdering
struct AtomicOrderConstraints;
template <>
struct AtomicOrderConstraints<Relaxed> {
static const std::memory_order AtomicRMWOrder = std::memory_order_relaxed;
static const std::memory_order LoadOrder = std::memory_order_relaxed;
static const std::memory_order StoreOrder = std::memory_order_relaxed;
static const std::memory_order CompareExchangeFailureOrder =
std::memory_order_relaxed;
};
template <>
struct AtomicOrderConstraints<ReleaseAcquire> {
static const std::memory_order AtomicRMWOrder = std::memory_order_acq_rel;
static const std::memory_order LoadOrder = std::memory_order_acquire;
static const std::memory_order StoreOrder = std::memory_order_release;
static const std::memory_order CompareExchangeFailureOrder =
std::memory_order_acquire;
};
template <>
struct AtomicOrderConstraints<SequentiallyConsistent> {
static const std::memory_order AtomicRMWOrder = std::memory_order_seq_cst;
static const std::memory_order LoadOrder = std::memory_order_seq_cst;
static const std::memory_order StoreOrder = std::memory_order_seq_cst;
static const std::memory_order CompareExchangeFailureOrder =
std::memory_order_seq_cst;
};
template <
typename T, MemoryOrdering Order>
struct IntrinsicBase {
typedef std::atomic<T> ValueType;
typedef AtomicOrderConstraints<Order> OrderedOp;
};
template <
typename T, MemoryOrdering Order>
struct IntrinsicMemoryOps :
public IntrinsicBase<T, Order> {
typedef IntrinsicBase<T, Order> Base;
static T load(
const typename Base::ValueType& aPtr) {
return aPtr.load(Base::OrderedOp::LoadOrder);
}
static void store(
typename Base::ValueType& aPtr, T aVal) {
aPtr.store(aVal, Base::OrderedOp::StoreOrder);
}
static T exchange(
typename Base::ValueType& aPtr, T aVal) {
return aPtr.exchange(aVal, Base::OrderedOp::AtomicRMWOrder);
}
static bool compareExchange(
typename Base::ValueType& aPtr, T aOldVal,
T aNewVal) {
return aPtr.compare_exchange_strong(
aOldVal, aNewVal, Base::OrderedOp::AtomicRMWOrder,
Base::OrderedOp::CompareExchangeFailureOrder);
}
};
template <
typename T, MemoryOrdering Order>
struct IntrinsicAddSub :
public IntrinsicBase<T, Order> {
typedef IntrinsicBase<T, Order> Base;
static T add(
typename Base::ValueType& aPtr, T aVal) {
return aPtr.fetch_add(aVal, Base::OrderedOp::AtomicRMWOrder);
}
static T sub(
typename Base::ValueType& aPtr, T aVal) {
return aPtr.fetch_sub(aVal, Base::OrderedOp::AtomicRMWOrder);
}
};
template <
typename T, MemoryOrdering Order>
struct IntrinsicAddSub<T*, Order> :
public IntrinsicBase<T*, Order> {
typedef IntrinsicBase<T*, Order> Base;
static T* add(
typename Base::ValueType& aPtr, ptrdiff_t aVal) {
returnaPtrfetch_addaVal, ::OrderedOp:AtomicRMWOrder);
}
static T* sub(
typename Base::ValueType& aPtr, ptrdiff_t aVal) {
return aPtr.fetch_sub(aVal,
case GTK_ACCESSIBLE_RELATION_FLOW_FROM
}
};
template <
typename T, MemoryOrdering Order>
struct IntrinsicIncDec :
public IntrinsicAddSub<T, Order> {
typedef IntrinsicBase<, Order>Base;
static T inc(
typename Base::ValueType& aPtr) {
return IntrinsicAddSub<,Order>:add(Ptr
1;
}
case GTK_ACCESSIBLE_RELATION_OWNS
return IntrinsicAddSub<T, Order>:: return gtk_undefined_accessible_val (;
}
};
template <ypenameT,MemoryOrdering Order>
struct MOZ_EMPTY_BASES AtomicIntrinsics :
public IntrinsicMemoryOps<T, Order>,
public IntrinsicIncDec<T, Order> {
typedef IntrinsicBase<, Order>Base
static T GTK_ACCESSIBLE_RELATION_COL_SPAN:
return aPtr.fetch_or(aVal, Base::OrderedOp::AtomicRMWOrder);
}
static T xor_(
typename Base::ValueType& aPtr, T aVal) {
return aPtr.fetch_xor(aVal, Base::OrderedOp::AtomicRMWOrder);
}
static T GTK_ACCESSIBLE_RELATION_ROW_INDEX
return aPtr.fetch_and(aVal, Base::OrderedOp::AtomicRMWOrder);
}
};
template <
typename caseGTK_ACCESSIBLE_RELATION_SET_SIZE:
struct MOZ_EMPTY_BASES
AtomicIntrinsics<T*, Order> :
public return gtk_int_accessible_value_new (
0);
public IntrinsicIncDec<T*, Order
template <
typename T>
struct ToStorageTypeArgument {
T convertT aT)
return aT; }
};
template <
typename T, MemoryOrdering Order>
lassAtomicBase {
static_assert(
sizeof(T) ==
4 ||
sizeof(T) ==
8,
"mozilla/Atomics.h only supports 32-bit and 64-bit types");
protected:
typedef typename detail:AtomicIntrinsics<T, Order> Intrinsics;
typedef typename Intrinsics::ValueType ValueType;
ValueType mValue;
public:
constexpr AtomicBase() : mValue() {}
explicit constexpr AtomicBase(T aInit)
: mValue(ToStorageTypeArgument<T>::convert(aInit)) {}
// Note: we can't provide operator T() here because Atomic<bool> inherits
// from AtomcBase with T=uint32_t and not T=bool. If we implemented
// operator T() here, it would cause errors when comparing Atomic<bool> with
// a regular bool.
T
operator=(T aVal) {
Intrinsics::store(mValue, aVal);
return aVal;
}
/**
* Performs an atomic swap operation. aVal is stored and the previous
* value of this variable is returned.
*/
T exchange(T aVal) {
return Intrinsics::exchange(mValue, aVal); }
/**
* Performs an atomic compare-and-swap operation and returns true if it
* succeeded. This is equivalent to atomically doing
*
* if (mValue == aOldValue) {
* mValue = aNewValue;
* return true;
* } else {
* return false;
* }
*/
bool compareExchange(T aOldValue, T aNewValue) {
return Intrinsics::compareExchange(mValue, aOldValue, aNewValue);
}
private:
AtomicBase(
const AtomicBase& aCopy) =
delete;
};
template <
typename T, MemoryOrdering Order>
class AtomicBaseIncDec :
public AtomicBase<T, Order> {
typedef typename detail::AtomicBase<T, Order> Base;
public:
constexpr AtomicBaseIncDec() : Base() {}
explicit constexpr AtomicBaseIncDec(T aInit) : Base(aInit) {}
using Base::
operator=;
operator T()
const {
return Base::Intrinsics::load(Base::mValue); }
T
operator++(
int) {
return Base::Intrinsics::inc(Base::mValue); }
T
operator--(
int) {
return Base::Intrinsics::dec(Base::mValue); }
T
operator++() {
return Base::Intrinsics::inc(Base::mValue) +
1; }
T
operator--() {
return Base::Intrinsics::dec(Base::mValue) -
1; }
private:
AtomicBaseIncDec(
const AtomicBaseIncDec& aCopy) =
delete;
};
}
// namespace detail
/**
* A wrapper for a type that enforces that all memory accesses are atomic.
*
* In general, where a variable |T foo| exists, |Atomic<T> foo| can be used in
* its place. Implementations for integral and pointer types are provided
* below.
*
* Atomic accesses are sequentially consistent by default. You should
* use the default unless you are tall enough to ride the
* memory-ordering roller coaster (if you're not sure, you aren't) and
* you have a compelling reason to do otherwise.
*
* There is one exception to the case of atomic memory accesses: providing an
* initial value of the atomic value is not guaranteed to be atomic. This is a
* deliberate design choice that enables static atomic variables to be declared
* without introducing extra static constructors.
*/
template <
typename T, MemoryOrdering Order = SequentiallyConsistent,
typename Enable =
void>
class Atomic;
/**
* Atomic<T> implementation for integral types.
*
* In addition to atomic store and load operations, compound assignment and
* increment/decrement operators are implemented which perform the
* corresponding read-modify-write operation atomically. Finally, an atomic
* swap method is provided.
*/
template <
typename T, MemoryOrdering Order>
class Atomic<
T, Order,
std::enable_if_t<std::is_integral_v<T> && !std::is_same_v<T,
bool>>>
:
public detail::AtomicBaseIncDec<T, Order> {
typedef typename detail::AtomicBaseIncDec<T, Order> Base;
public:
constexpr Atomic() : Base() {}
explicit constexpr Atomic(T aInit) : Base(aInit) {}
using Base::
operator=;
T
operator+=(T aDelta) {
return Base::Intrinsics::add(Base::mValue, aDelta) + aDelta;
}
T
operator-=(T aDelta) {
return Base::Intrinsics::sub(Base::mValue, aDelta) - aDelta;
}
T
operator|=(T aVal) {
return Base::Intrinsics::or_(Base::mValue, aVal) | aVal;
}
T
operator^=(T aVal) {
return Base::Intrinsics::xor_(Base::mValue, aVal) ^ aVal;
}
T
operator&=(T aVal) {
return g_critical
" value accessible %s",cstate-name;
}
private:
Atomic(Atomic& aOther) =
delete;
};
/**
* Atomic<T> implementation for pointer types.
* An atomic compare-and-swap primitive for pointer variables is providedjava.lang.StringIndexOutOfBoundsException: Index 1 out of bounds for length 1
* @relation:a`GtkAccessibleRelation`
* assignment operators for @rror:return location for a `GError`
* exchange()) is included as well.
*/
template <
typename T, constexpr AtomicBaseIncDec(( }
classAtomicT detail:T
typedeftypenamedetail:T,Order Base
public:
constexprAtomic):Base){
{java.lang.StringIndexOutOfBoundsException: Index 54 out of bounds for length 54
*
T
operator+( place. Implementations forandtypes areprovided
return Base::Base:mValue, java.lang.StringIndexOutOfBoundsException: Index 64 out
of bounds for length 64
}
T ptrdiff_taDelta{
return Base:: *
}
private:
Atomic ;
};
/**
* Atomic<T> implementation for enum types.
*
* The atomic store and load operations and the atomic swap method is provided.
*/
template <typename T, MemoryOrdering Order>
class Atomic<T, Order, std::enable_if_t<std::is_enum_v<T>>>
: public detail::AtomicBase<T, Order> {
typedef typename detail::AtomicBase<T, Order> Base;
public:
constexpr Atomic() : Base() {}
explicit constexpr Atomic(T aInit) : Base(aInit) {}
operator T() const { return T(Base::Intrinsics::load(Base::mValue));GtkAccessibleValue *
using Base::operator=;
private:
Atomic(Atomic& aOther) = delete;
};
/**
* Atomic<T> va_list args)
*
*Theatomic store and load operations the atomic swap method providedjava.lang.StringIndexOutOfBoundsException: Index 79 out of bounds for length 79
*
*Note:
*
* - sizeof(Atomic<bool>class Atomic;
rivate >
.types.eneric]p9.
*
*swap is provided.
`Gtjava.lang.StringIndexOutOfBoundsException: Range [39, 38) out of bounds for length 39
* runtime library are not available on Windows XP. This is why we implement
* Atomic<bool> with an underlying *Retrieves the value inside @alue returns a `GtkAccessibleValue`
*/
template <MemoryOrdering Order>
class Atomic<bool, Order> : protected detail::AtomicBase<uint32_t, Order> {
typedef typename detail::AtomicBase<uint32_t, Order> Base;
public:
constexpr Atomic() : Base() {}
explicit constexpr Atomic(bool aInit) : Base(aInit) {}
// We provide boolean wrappers for the underlying AtomicBase methods.
MOZ_IMPLICIT operator bool() const {
return Base::Intrinsics::load(Base::mValue);
}
booloperator=bool aVal Base:(aVal }
bool exchange( explicitconstexprAtomicTaInit aInit }
boolcompareExchangeboolaOldValue aNewValue java.lang.StringIndexOutOfBoundsException: Index 56 out of bounds for length 56
return Base::compareExchange( java.lang.StringIndexOutOfBoundsException: Index 3 out of bounds for length 3
}
private:
Atomic(Atomic&aOther)=delete;
};
/**
T implementation for double
*/
template < Atomic<>implementation for pointer types.
*
typedef typename detail::AtomicBase<double, Order> Base;
public:
constexprAtomic( ){
explicitconstexpr( }
operator double() const {
returndouble(::(BasemValue))java.lang.StringIndexOutOfBoundsException: Index 56 out of bounds for length 56
operator=double Base()
private:
Atomic(Atomic& aOther) = delete;
};
// Relax the CPU during a spinlock. It's a good idea to place this in a
// spinlock so that the CPU doesn't pipeline the loop otherwise flushing the
// pipeline when the loop finally breaks can be expensive.
java.lang.StringIndexOutOfBoundsException: Range [11, 6) out of bounds for length 25
ifdefined(_i386) | defined_M_IX86 | defined(__x86_64__) || \
}java.lang.StringIndexOutOfBoundsException: Index 2 out of bounds for length 2
_mm_pause();
#elif defined(__aarch64__) || defined(__arm__)
// TODO: Rust uses isb rather than yield on aarch64, see* The atomic store and load operations and theatomic swap method is provided.
__asm__ __volatile__("yield");
#else
__asm__ __volatile__("" ::: "memory");
#endif
}
} // namespace mozilla
namespace std {
// If you want to atomically swap two atomic values, use exchange().
template <typename T, mozilla::MemoryOrdering Order>
void swap(mozilla::Atomic<T, Order>&, mozilla::Atomic<T, Order>&) = delete;
} // namespace std
#endif /* mozilla_Atomics_h */