Semantics and Behavior of Atomic and Bitmask Operations David S. Miller This document is intended to serve as a guide to Linux port maintainers on how to implement atomic counter, bitops, and spinlock interfaces properly. The atomic_t type should be defined as a signed integer and the atomic_long_t type as a signed long integer. Also, they should be made opaque such that any kind of cast to a normal C integer type will fail. Something like the following should suffice: typedef struct { int counter; } atomic_t; typedef struct { long counter; } atomic_long_t; Historically, counter has been declared volatile. This is now discouraged. See Documentation/volatile-considered-harmful.txt for the complete rationale. local_t is very similar to atomic_t. If the counter is per CPU and only updated by one CPU, local_t is probably more appropriate. Please see Documentation/local_ops.txt for the semantics of local_t. The first operations to implement for atomic_t's are the initializers and plain reads. #define ATOMIC_INIT(i) { (i) } #define atomic_set(v, i) ((v)->counter = (i)) The first macro is used in definitions, such as: static atomic_t my_counter = ATOMIC_INIT(1); The initializer is atomic in that the return values of the atomic operations are guaranteed to be correct reflecting the initialized value if the initializer is used before runtime. If the initializer is used at runtime, a proper implicit or explicit read memory barrier is needed before reading the value with atomic_read from another thread. As with all of the atomic_ interfaces, replace the leading "atomic_" with "atomic_long_" to operate on atomic_long_t. The second interface can be used at runtime, as in: struct foo { atomic_t counter; }; ... struct foo *k; k = kmalloc(sizeof(*k), GFP_KERNEL); if (!k) return -ENOMEM; atomic_set(&k->counter, 0); The setting is atomic in that the return values of the atomic operations by all threads are guaranteed to be correct reflecting either the value that has been set with this operation or set with another operation. A proper implicit or explicit memory barrier is needed before the value set with the operation is guaranteed to be readable with atomic_read from another thread. Next, we have: #define atomic_read(v) ((v)->counter) which simply reads the counter value currently visible to the calling thread. The read is atomic in that the return value is guaranteed to be one of the values initialized or modified with the interface operations if a proper implicit or explicit memory barrier is used after possible runtime initialization by any other thread and the value is modified only with the interface operations. atomic_read does not guarantee that the runtime initialization by any other thread is visible yet, so the user of the interface must take care of that with a proper implicit or explicit memory barrier. *** WARNING: atomic_read() and atomic_set() DO NOT IMPLY BARRIERS! *** Some architectures may choose to use the volatile keyword, barriers, or inline assembly to guarantee some degree of immediacy for atomic_read() and atomic_set(). This is not uniformly guaranteed, and may change in the future, so all users of atomic_t should treat atomic_read() and atomic_set() as simple C statements that may be reordered or optimized away entirely by the compiler or processor, and explicitly invoke the appropriate compiler and/or memory barrier for each use case. Failure to do so will result in code that may suddenly break when used with different architectures or compiler optimizations, or even changes in unrelated code which changes how the compiler optimizes the section accessing atomic_t variables. *** YOU HAVE BEEN WARNED! *** Properly aligned pointers, longs, ints, and chars (and unsigned equivalents) may be atomically loaded from and stored to in the same sense as described for atomic
# A Heat environment file which can be used to enable config
# management (e.g. Puppet) debugging.

parameter_defaults:
  ConfigDebug: true
Parisc uses the same scheme. Another note is that the atomic_t operations returning values are extremely slow on an old 386. We will now cover the atomic bitmask operations. You will find that their SMP and memory barrier semantics are similar in shape and scope to the atomic_t ops above. Native atomic bit operations are defined to operate on objects aligned to the size of an "unsigned long" C data type, and are least of that size. The endianness of the bits within each "unsigned long" are the native endianness of the cpu. void set_bit(unsigned long nr, volatile unsigned long *addr); void clear_bit(unsigned long nr, volatile unsigned long *addr); void change_bit(unsigned long nr, volatile unsigned long *addr); These routines set, clear, and change, respectively, the bit number indicated by "nr" on the bit mask pointed to by "ADDR". They must execute atomically, yet there are no implicit memory barrier semantics required of these interfaces. int test_and_set_bit(unsigned long nr, volatile unsigned long *addr); int test_and_clear_bit(unsigned long nr, volatile unsigned long *addr); int test_and_change_bit(unsigned long nr, volatile unsigned long *addr); Like the above, except that these routines return a boolean which indicates whether the changed bit was set _BEFORE_ the atomic bit operation. WARNING! It is incredibly important that the value be a boolean, ie. "0" or "1". Do not try to be fancy and save a few instructions by declaring the above to return "long" and just returning something like "old_val & mask" because that will not work. For one thing, this return value gets truncated to int in many code paths using these interfaces, so on 64-bit if the bit is set in the upper 32-bits then testers will never see that. One great example of where this problem crops up are the thread_info flag operations. Routines such as test_and_set_ti_thread_flag() chop the return value into an int. There are other places where things like this occur as well. These routines, like the atomic_t counter operations returning values, must provide explicit memory barrier semantics around their execution. All memory operations before the atomic bit operation call must be made visible globally before the atomic bit operation is made visible. Likewise, the atomic bit operation must be visible globally before any subsequent memory operation is made visible. For example: obj->dead = 1; if (test_and_set_bit(0, &obj->flags)) /* ... */; obj->killed = 1; The implementation of test_and_set_bit() must guarantee that "obj->dead = 1;" is visible to cpus before the atomic memory operation done by test_and_set_bit() becomes visible. Likewise, the atomic memory operation done by test_and_set_bit() must become visible before "obj->killed = 1;" is visible. Finally there is the basic operation: int test_bit(unsigned long nr, __const__ volatile unsigned long *addr); Which returns a boolean indicating if bit "nr" is set in the bitmask pointed to by "addr". If explicit memory barriers are required around {set,clear}_bit() (which do not return a value, and thus does not need to provide memory barrier semantics), two interfaces are provided: void smp_mb__before_atomic(void); void smp_mb__after_atomic(void); They are used as follows, and are akin to their atomic_t operation brothers: /* All memory operations before this call will * be globally visible before the clear_bit(). */ smp_mb__before_atomic(); clear_bit( ... ); /* The clear_bit() will be visible before all * subsequent memory operations. */ smp_mb__after_atomic(); There are two special bitops with lock barrier semantics (acquire/release, same as spinlocks). These operate in the same way as their non-_lock/unlock postfixed variants, except that they are to provide acquire/release semantics, respectively. This means they can be used for bit_spin_trylock and bit_spin_unlock type operations without specifying any more barriers. int test_and_set_bit_lock(unsigned long nr, unsigned long *addr); void clear_bit_unlock(unsigned long nr, unsigned long *addr); void __clear_bit_unlock(unsigned long nr, unsigned long *addr); The __clear_bit_unlock version is non-atomic, however it still implements unlock barrier semantics. This can be useful if the lock itself is protecting the other bits in the word. Finally, there are non-atomic versions of the bitmask operations provided. They are used in contexts where some other higher-level SMP locking scheme is being used to protect the bitmask, and thus less expensive non-atomic operations may be used in the implementation. They have names similar to the above bitmask operation interfaces, except that two underscores are prefixed to the interface name. void __set_bit(unsigned long nr, volatile unsigned long *addr); void __clear_bit(unsigned long nr, volatile unsigned long *addr); void __change_bit(unsigned long nr, volatile unsigned long *addr); int __test_and_set_bit(unsigned long nr, volatile unsigned long *addr); int __test_and_clear_bit(unsigned long nr, volatile unsigned long *addr); int __test_and_change_bit(unsigned long nr, volatile unsigned long *addr); These non-atomic variants also do not require any special memory barrier semantics. The routines xchg() and cmpxchg() must provide the same exact memory-barrier semantics as the atomic and bit operations returning values. Note: If someone wants to use xchg(), cmpxchg() and their variants, linux/atomic.h should be included rather than asm/cmpxchg.h, unless the code is in arch/* and can take care of itself. Spinlocks and rwlocks have memory barrier expectations as well. The rule to follow is simple: 1) When acquiring a lock, the implementation must make it globally visible before any subsequent memory operation. 2) When releasing a lock, the implementation must make it such that all previous memory operations are globally visible before the lock release. Which finally brings us to _atomic_dec_and_lock(). There is an architecture-neutral version implemented in lib/dec_and_lock.c, but most platforms will wish to optimize this in assembler. int _atomic_dec_and_lock(atomic_t *atomic, spinlock_t *lock); Atomically decrement the given counter, and if will drop to zero atomically acquire the given spinlock and perform the decrement of the counter to zero. If it does not drop to zero, do nothing with the spinlock. It is actually pretty simple to get the memory barrier correct. Simply satisfy the spinlock grab requirements, which is make sure the spinlock operation is globally visible before any subsequent memory operation. We can demonstrate this operation more clearly if we define an abstract atomic operation: long cas(long *mem, long old, long new); "cas" stands for "compare and swap". It atomically: 1) Compares "old" with the value currently at "mem". 2) If they are equal, "new" is written to "mem". 3) Regardless, the current value at "mem" is returned. As an example usage, here is what an atomic counter update might look like: void example_atomic_inc(long *counter) { long old, new, ret; while (1) { old = *counter; new = old + 1; ret = cas(counter, old, new); if (ret == old) break; } } Let's use cas() in order to build a pseudo-C atomic_dec_and_lock(): int _atomic_dec_and_lock(atomic_t *atomic, spinlock_t *lock) { long old, new, ret; int went_to_zero; went_to_zero = 0; while (1) { old = atomic_read(atomic); new = old - 1; if (new == 0) { went_to_zero = 1; spin_lock(lock); } ret = cas(atomic, old, new); if (ret == old) break; if (went_to_zero) { spin_unlock(lock); went_to_zero = 0; } } return went_to_zero; } Now, as far as memory barriers go, as long as spin_lock() strictly orders all subsequent memory operations (including the cas()) with respect to itself, things will be fine. Said another way, _atomic_dec_and_lock() must guarantee that a counter dropping to zero is never made visible before the spinlock being acquired. Note that this also means that for the case where the counter is not dropping to zero, there are no memory ordering requirements.