OVR_Atomic.h 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  1. /************************************************************************************
  2. PublicHeader: OVR_Kernel.h
  3. Filename : OVR_Atomic.h
  4. Content : Contains atomic operations and inline fastest locking
  5. functionality. Will contain #ifdefs for OS efficiency.
  6. Have non-thread-safe implementaion if not available.
  7. Created : September 19, 2012
  8. Notes :
  9. Copyright : Copyright 2014 Oculus VR, LLC All Rights reserved.
  10. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
  11. you may not use the Oculus VR Rift SDK except in compliance with the License,
  12. which is provided at the time of installation or download, or which
  13. otherwise accompanies this software in either electronic or hard copy form.
  14. You may obtain a copy of the License at
  15. http://www.oculusvr.com/licenses/LICENSE-3.2
  16. Unless required by applicable law or agreed to in writing, the Oculus VR SDK
  17. distributed under the License is distributed on an "AS IS" BASIS,
  18. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. See the License for the specific language governing permissions and
  20. limitations under the License.
  21. ************************************************************************************/
  22. #ifndef OVR_Atomic_h
  23. #define OVR_Atomic_h
  24. #include "OVR_Types.h"
  25. // Include System thread functionality.
  26. #if defined(OVR_OS_MS) && !defined(OVR_OS_MS_MOBILE)
  27. #include "OVR_Win32_IncludeWindows.h"
  28. #else
  29. #include <pthread.h>
  30. #endif
  31. #ifdef OVR_CC_MSVC
  32. #include <intrin.h>
  33. #pragma intrinsic(_ReadBarrier, _WriteBarrier, _ReadWriteBarrier)
  34. #endif
  35. #ifdef OVR_OS_LINUX
  36. #include <atomic>
  37. namespace OVR {
  38. template<class T>
  39. class AtomicTranslator : public std::atomic<T>
  40. {
  41. public:
  42. AtomicTranslator() :
  43. std::atomic<T>(T())
  44. {
  45. }
  46. AtomicTranslator(const T &from) :
  47. std::atomic<T>(from)
  48. {
  49. }
  50. AtomicTranslator(const AtomicTranslator<T> &from) :
  51. std::atomic<T>(from.Load_Acquire())
  52. {
  53. }
  54. T operator = (const T &from)
  55. {
  56. Store_Release(from);
  57. return from;
  58. }
  59. operator T() const
  60. {
  61. return Load_Acquire();
  62. }
  63. T Exchange_Sync(T& other)
  64. {
  65. return std::atomic<T>::exchange(other);
  66. }
  67. T Exchange_Sync(const T& other)
  68. {
  69. T tmp_val = other;
  70. return std::atomic<T>::exchange(tmp_val);
  71. }
  72. T ExchangeAdd_Sync(const T &val)
  73. {
  74. return std::atomic<T>::fetch_add(val);
  75. }
  76. T ExchangeAdd_NoSync(const T &val)
  77. {
  78. return std::atomic<T>::fetch_add(val, std::memory_order_relaxed);
  79. }
  80. bool CompareAndSet_Sync(const T &other, const T &val)
  81. {
  82. T tmp_val = other;
  83. return std::atomic<T>::compare_exchange_strong(tmp_val, val);
  84. }
  85. bool CompareAndSet_NoSync(const T &other, const T &val)
  86. {
  87. T tmp_val = other;
  88. return std::atomic<T>::compare_exchange_weak(tmp_val, val);
  89. }
  90. T Load_Acquire() const
  91. {
  92. return std::atomic<T>::load(std::memory_order_acquire);
  93. }
  94. void Store_Release(const T &val)
  95. {
  96. std::atomic<T>::store(val, std::memory_order_release);
  97. }
  98. };
  99. template<class T> using AtomicOps = AtomicTranslator<T>;
  100. template<class T> using AtomicInt = AtomicTranslator<T>;
  101. template<class T> using AtomicPtr = AtomicTranslator<T*>;
  102. #else // OVR_OS_LINUX
  103. namespace OVR {
  104. // ****** Declared classes
  105. // If there is NO thread support we implement AtomicOps and
  106. // Lock objects as no-ops. The other classes are not defined.
  107. template<class C> class AtomicOps;
  108. template<class T> class AtomicInt;
  109. template<class T> class AtomicPtr;
  110. class Lock;
  111. //-----------------------------------------------------------------------------------
  112. // ***** AtomicOps
  113. // Atomic operations are provided by the AtomicOps templates class,
  114. // implemented through system-specific AtomicOpsRaw specializations.
  115. // It provides several fundamental operations such as Exchange, ExchangeAdd
  116. // CompareAndSet, and Store_Release. Each function includes several memory
  117. // synchronization versions, important for multiprocessing CPUs with weak
  118. // memory consistency. The following memory fencing strategies are supported:
  119. //
  120. // - NoSync. No memory synchronization is done for atomic op.
  121. // - Release. All other memory writes are completed before atomic op
  122. // writes its results.
  123. // - Acquire. Further memory reads are forced to wait until atomic op
  124. // executes, guaranteeing that the right values will be seen.
  125. // - Sync. A combination of Release and Acquire.
  126. // *** AtomicOpsRaw
  127. // AtomicOpsRaw is a specialized template that provides atomic operations
  128. // used by AtomicOps. This class has two fundamental qualities: (1) it
  129. // defines a type T of correct size, and (2) provides operations that work
  130. // atomically, such as Exchange_Sync and CompareAndSet_Release.
  131. // AtomicOpsRawBase class contains shared constants/classes for AtomicOpsRaw.
  132. // The primary thing is does is define sync class objects, whose destructor and
  133. // constructor provide places to insert appropriate synchronization calls, on
  134. // systems where such calls are necessary. So far, the breakdown is as follows:
  135. //
  136. // - X86 systems don't need custom syncs, since their exchange/atomic
  137. // instructions are implicitly synchronized.
  138. // - PowerPC requires lwsync/isync instructions that can use this mechanism.
  139. // - If some other systems require a mechanism where syncing type is associated
  140. // with a particular instruction, the default implementation (which implements
  141. // all Sync, Acquire, and Release modes in terms of NoSync and fence) may not
  142. // work. Ii that case it will need to be #ifdef-ed conditionally.
  143. struct AtomicOpsRawBase
  144. {
  145. #if !defined(OVR_ENABLE_THREADS) || defined(OVR_CPU_X86) || defined(OVR_CPU_X86_64)
  146. // Need to have empty constructor to avoid class 'unused' variable warning.
  147. struct FullSync { inline FullSync() { } };
  148. struct AcquireSync { inline AcquireSync() { } };
  149. struct ReleaseSync { inline ReleaseSync() { } };
  150. #elif defined(OVR_CPU_PPC64) || defined(OVR_CPU_PPC)
  151. struct FullSync { inline FullSync() { asm volatile("sync\n"); } ~FullSync() { asm volatile("isync\n"); } };
  152. struct AcquireSync { inline AcquireSync() { } ~AcquireSync() { asm volatile("isync\n"); } };
  153. struct ReleaseSync { inline ReleaseSync() { asm volatile("sync\n"); } };
  154. #elif defined(OVR_CPU_MIPS)
  155. struct FullSync { inline FullSync() { asm volatile("sync\n"); } ~FullSync() { asm volatile("sync\n"); } };
  156. struct AcquireSync { inline AcquireSync() { } ~AcquireSync() { asm volatile("sync\n"); } };
  157. struct ReleaseSync { inline ReleaseSync() { asm volatile("sync\n"); } };
  158. #elif defined(OVR_CPU_ARM) // Includes Android and iOS.
  159. struct FullSync { inline FullSync() { asm volatile("dmb\n"); } ~FullSync() { asm volatile("dmb\n"); } };
  160. struct AcquireSync { inline AcquireSync() { } ~AcquireSync() { asm volatile("dmb\n"); } };
  161. struct ReleaseSync { inline ReleaseSync() { asm volatile("dmb\n"); } };
  162. #elif defined(OVR_CC_GNU) && (__GNUC__ >= 4)
  163. // __sync functions are already full sync
  164. struct FullSync { inline FullSync() { } };
  165. struct AcquireSync { inline AcquireSync() { } };
  166. struct ReleaseSync { inline ReleaseSync() { } };
  167. #endif
  168. };
  169. // 4-Byte raw data atomic op implementation class.
  170. struct AtomicOpsRaw_4ByteImpl : public AtomicOpsRawBase
  171. {
  172. #if !defined(OVR_ENABLE_THREADS)
  173. // Provide a type for no-thread-support cases. Used by AtomicOpsRaw_DefImpl.
  174. typedef uint32_t T;
  175. // *** Thread - Safe Atomic Versions.
  176. #elif defined(OVR_OS_MS)
  177. // Use special defined for VC6, where volatile is not used and
  178. // InterlockedCompareExchange is declared incorrectly.
  179. typedef LONG T;
  180. #if defined(OVR_CC_MSVC) && (OVR_CC_MSVC < 1300)
  181. typedef T* InterlockTPtr;
  182. typedef LPVOID ET;
  183. typedef ET* InterlockETPtr;
  184. #else
  185. typedef volatile T* InterlockTPtr;
  186. typedef T ET;
  187. typedef InterlockTPtr InterlockETPtr;
  188. #endif
  189. inline static T Exchange_NoSync(volatile T* p, T val) { return InterlockedExchange((InterlockTPtr)p, val); }
  190. inline static T ExchangeAdd_NoSync(volatile T* p, T val) { return InterlockedExchangeAdd((InterlockTPtr)p, val); }
  191. inline static bool CompareAndSet_NoSync(volatile T* p, T c, T val) { return InterlockedCompareExchange((InterlockETPtr)p, (ET)val, (ET)c) == (ET)c; }
  192. #elif defined(OVR_CPU_PPC64) || defined(OVR_CPU_PPC)
  193. typedef uint32_t T;
  194. static inline uint32_t Exchange_NoSync(volatile uint32_t *i, uint32_t j)
  195. {
  196. uint32_t ret;
  197. asm volatile("1:\n\t"
  198. "lwarx %[r],0,%[i]\n\t"
  199. "stwcx. %[j],0,%[i]\n\t"
  200. "bne- 1b\n"
  201. : "+m" (*i), [r] "=&b" (ret) : [i] "b" (i), [j] "b" (j) : "cc", "memory");
  202. return ret;
  203. }
  204. static inline uint32_t ExchangeAdd_NoSync(volatile uint32_t *i, uint32_t j)
  205. {
  206. uint32_t dummy, ret;
  207. asm volatile("1:\n\t"
  208. "lwarx %[r],0,%[i]\n\t"
  209. "add %[o],%[r],%[j]\n\t"
  210. "stwcx. %[o],0,%[i]\n\t"
  211. "bne- 1b\n"
  212. : "+m" (*i), [r] "=&b" (ret), [o] "=&r" (dummy) : [i] "b" (i), [j] "b" (j) : "cc", "memory");
  213. return ret;
  214. }
  215. static inline bool CompareAndSet_NoSync(volatile uint32_t *i, uint32_t c, uint32_t value)
  216. {
  217. uint32_t ret;
  218. asm volatile("1:\n\t"
  219. "lwarx %[r],0,%[i]\n\t"
  220. "cmpw 0,%[r],%[cmp]\n\t"
  221. "mfcr %[r]\n\t"
  222. "bne- 2f\n\t"
  223. "stwcx. %[val],0,%[i]\n\t"
  224. "bne- 1b\n\t"
  225. "2:\n"
  226. : "+m" (*i), [r] "=&b" (ret) : [i] "b" (i), [cmp] "b" (c), [val] "b" (value) : "cc", "memory");
  227. return (ret & 0x20000000) ? 1 : 0;
  228. }
  229. #elif defined(OVR_CPU_MIPS)
  230. typedef uint32_t T;
  231. static inline uint32_t Exchange_NoSync(volatile uint32_t *i, uint32_t j)
  232. {
  233. uint32_t ret;
  234. asm volatile("1:\n\t"
  235. "ll %[r],0(%[i])\n\t"
  236. "sc %[j],0(%[i])\n\t"
  237. "beq %[j],$0,1b\n\t"
  238. "nop \n"
  239. : "+m" (*i), [r] "=&d" (ret) : [i] "d" (i), [j] "d" (j) : "cc", "memory");
  240. return ret;
  241. }
  242. static inline uint32_t ExchangeAdd_NoSync(volatile uint32_t *i, uint32_t j)
  243. {
  244. uint32_t ret;
  245. asm volatile("1:\n\t"
  246. "ll %[r],0(%[i])\n\t"
  247. "addu %[j],%[r],%[j]\n\t"
  248. "sc %[j],0(%[i])\n\t"
  249. "beq %[j],$0,1b\n\t"
  250. "nop \n"
  251. : "+m" (*i), [r] "=&d" (ret) : [i] "d" (i), [j] "d" (j) : "cc", "memory");
  252. return ret;
  253. }
  254. static inline bool CompareAndSet_NoSync(volatile uint32_t *i, uint32_t c, uint32_t value)
  255. {
  256. uint32_t ret, dummy;
  257. asm volatile("1:\n\t"
  258. "move %[r],$0\n\t"
  259. "ll %[o],0(%[i])\n\t"
  260. "bne %[o],%[c],2f\n\t"
  261. "move %[r],%[v]\n\t"
  262. "sc %[r],0(%[i])\n\t"
  263. "beq %[r],$0,1b\n\t"
  264. "nop \n\t"
  265. "2:\n"
  266. : "+m" (*i),[r] "=&d" (ret), [o] "=&d" (dummy) : [i] "d" (i), [c] "d" (c), [v] "d" (value)
  267. : "cc", "memory");
  268. return ret;
  269. }
  270. #elif defined(OVR_CPU_ARM) && defined(OVR_CC_ARM)
  271. typedef uint32_t T;
  272. static inline uint32_t Exchange_NoSync(volatile uint32_t *i, uint32_t j)
  273. {
  274. for(;;)
  275. {
  276. T r = __ldrex(i);
  277. if (__strex(j, i) == 0)
  278. return r;
  279. }
  280. }
  281. static inline uint32_t ExchangeAdd_NoSync(volatile uint32_t *i, uint32_t j)
  282. {
  283. for(;;)
  284. {
  285. T r = __ldrex(i);
  286. if (__strex(r + j, i) == 0)
  287. return r;
  288. }
  289. }
  290. static inline bool CompareAndSet_NoSync(volatile uint32_t *i, uint32_t c, uint32_t value)
  291. {
  292. for(;;)
  293. {
  294. T r = __ldrex(i);
  295. if (r != c)
  296. return 0;
  297. if (__strex(value, i) == 0)
  298. return 1;
  299. }
  300. }
  301. #elif defined(OVR_CPU_ARM)
  302. typedef uint32_t T;
  303. static inline uint32_t Exchange_NoSync(volatile uint32_t *i, uint32_t j)
  304. {
  305. uint32_t ret, dummy;
  306. asm volatile("1:\n\t"
  307. "ldrex %[r],[%[i]]\n\t"
  308. "strex %[t],%[j],[%[i]]\n\t"
  309. "cmp %[t],#0\n\t"
  310. "bne 1b\n\t"
  311. : "+m" (*i), [r] "=&r" (ret), [t] "=&r" (dummy) : [i] "r" (i), [j] "r" (j) : "cc", "memory");
  312. return ret;
  313. }
  314. static inline uint32_t ExchangeAdd_NoSync(volatile uint32_t *i, uint32_t j)
  315. {
  316. uint32_t ret, dummy, test;
  317. asm volatile("1:\n\t"
  318. "ldrex %[r],[%[i]]\n\t"
  319. "add %[o],%[r],%[j]\n\t"
  320. "strex %[t],%[o],[%[i]]\n\t"
  321. "cmp %[t],#0\n\t"
  322. "bne 1b\n\t"
  323. : "+m" (*i), [r] "=&r" (ret), [o] "=&r" (dummy), [t] "=&r" (test) : [i] "r" (i), [j] "r" (j) : "cc", "memory");
  324. return ret;
  325. }
  326. static inline bool CompareAndSet_NoSync(volatile uint32_t *i, uint32_t c, uint32_t value)
  327. {
  328. uint32_t ret = 1, dummy, test;
  329. asm volatile("1:\n\t"
  330. "ldrex %[o],[%[i]]\n\t"
  331. "cmp %[o],%[c]\n\t"
  332. "bne 2f\n\t"
  333. "strex %[r],%[v],[%[i]]\n\t"
  334. "cmp %[r],#0\n\t"
  335. "bne 1b\n\t"
  336. "2:\n"
  337. : "+m" (*i),[r] "=&r" (ret), [o] "=&r" (dummy), [t] "=&r" (test) : [i] "r" (i), [c] "r" (c), [v] "r" (value)
  338. : "cc", "memory");
  339. return !ret;
  340. }
  341. #elif defined(OVR_CPU_X86)
  342. typedef uint32_t T;
  343. static inline uint32_t Exchange_NoSync(volatile uint32_t *i, uint32_t j)
  344. {
  345. asm volatile("xchgl %1,%[i]\n"
  346. : "+m" (*i), "=q" (j) : [i] "m" (*i), "1" (j) : "cc", "memory");
  347. return j;
  348. }
  349. static inline uint32_t ExchangeAdd_NoSync(volatile uint32_t *i, uint32_t j)
  350. {
  351. asm volatile("lock; xaddl %1,%[i]\n"
  352. : "+m" (*i), "+q" (j) : [i] "m" (*i) : "cc", "memory");
  353. return j;
  354. }
  355. static inline bool CompareAndSet_NoSync(volatile uint32_t *i, uint32_t c, uint32_t value)
  356. {
  357. uint32_t ret;
  358. asm volatile("lock; cmpxchgl %[v],%[i]\n"
  359. : "+m" (*i), "=a" (ret) : [i] "m" (*i), "1" (c), [v] "q" (value) : "cc", "memory");
  360. return (ret == c);
  361. }
  362. #elif defined(OVR_CC_GNU) && (__GNUC__ >= 4 && __GNUC_MINOR__ >= 1)
  363. typedef uint32_t T;
  364. static inline T Exchange_NoSync(volatile T *i, T j)
  365. {
  366. T v;
  367. do {
  368. v = *i;
  369. } while (!__sync_bool_compare_and_swap(i, v, j));
  370. return v;
  371. }
  372. static inline T ExchangeAdd_NoSync(volatile T *i, T j)
  373. {
  374. return __sync_fetch_and_add(i, j);
  375. }
  376. static inline bool CompareAndSet_NoSync(volatile T *i, T c, T value)
  377. {
  378. return __sync_bool_compare_and_swap(i, c, value);
  379. }
  380. #endif // OS
  381. };
  382. // 8-Byte raw data data atomic op implementation class.
  383. // Currently implementation is provided only on systems with 64-bit pointers.
  384. struct AtomicOpsRaw_8ByteImpl : public AtomicOpsRawBase
  385. {
  386. #if !defined(OVR_64BIT_POINTERS) || !defined(OVR_ENABLE_THREADS)
  387. // Provide a type for no-thread-support cases. Used by AtomicOpsRaw_DefImpl.
  388. typedef uint64_t T;
  389. // *** Thread - Safe OS specific versions.
  390. #elif defined(OVR_OS_MS)
  391. // This is only for 64-bit systems.
  392. typedef LONG64 T;
  393. typedef volatile T* InterlockTPtr;
  394. inline static T Exchange_NoSync(volatile T* p, T val) { return InterlockedExchange64((InterlockTPtr)p, val); }
  395. inline static T ExchangeAdd_NoSync(volatile T* p, T val) { return InterlockedExchangeAdd64((InterlockTPtr)p, val); }
  396. inline static bool CompareAndSet_NoSync(volatile T* p, T c, T val) { return InterlockedCompareExchange64((InterlockTPtr)p, val, c) == c; }
  397. #elif defined(OVR_CPU_PPC64)
  398. typedef uint64_t T;
  399. static inline uint64_t Exchange_NoSync(volatile uint64_t *i, uint64_t j)
  400. {
  401. uint64_t dummy, ret;
  402. asm volatile("1:\n\t"
  403. "ldarx %[r],0,%[i]\n\t"
  404. "mr %[o],%[j]\n\t"
  405. "stdcx. %[o],0,%[i]\n\t"
  406. "bne- 1b\n"
  407. : "+m" (*i), [r] "=&b" (ret), [o] "=&r" (dummy) : [i] "b" (i), [j] "b" (j) : "cc");
  408. return ret;
  409. }
  410. static inline uint64_t ExchangeAdd_NoSync(volatile uint64_t *i, uint64_t j)
  411. {
  412. uint64_t dummy, ret;
  413. asm volatile("1:\n\t"
  414. "ldarx %[r],0,%[i]\n\t"
  415. "add %[o],%[r],%[j]\n\t"
  416. "stdcx. %[o],0,%[i]\n\t"
  417. "bne- 1b\n"
  418. : "+m" (*i), [r] "=&b" (ret), [o] "=&r" (dummy) : [i] "b" (i), [j] "b" (j) : "cc");
  419. return ret;
  420. }
  421. static inline bool CompareAndSet_NoSync(volatile uint64_t *i, uint64_t c, uint64_t value)
  422. {
  423. uint64_t ret, dummy;
  424. asm volatile("1:\n\t"
  425. "ldarx %[r],0,%[i]\n\t"
  426. "cmpw 0,%[r],%[cmp]\n\t"
  427. "mfcr %[r]\n\t"
  428. "bne- 2f\n\t"
  429. "stdcx. %[val],0,%[i]\n\t"
  430. "bne- 1b\n\t"
  431. "2:\n"
  432. : "+m" (*i), [r] "=&b" (ret), [o] "=&r" (dummy) : [i] "b" (i), [cmp] "b" (c), [val] "b" (value) : "cc");
  433. return (ret & 0x20000000) ? 1 : 0;
  434. }
  435. #elif defined(OVR_CC_GNU) && (__GNUC__ >= 4 && __GNUC_MINOR__ >= 1)
  436. typedef uint64_t T;
  437. static inline T Exchange_NoSync(volatile T *i, T j)
  438. {
  439. T v;
  440. do {
  441. v = *i;
  442. } while (!__sync_bool_compare_and_swap(i, v, j));
  443. return v;
  444. }
  445. static inline T ExchangeAdd_NoSync(volatile T *i, T j)
  446. {
  447. return __sync_fetch_and_add(i, j);
  448. }
  449. static inline bool CompareAndSet_NoSync(volatile T *i, T c, T value)
  450. {
  451. return __sync_bool_compare_and_swap(i, c, value);
  452. }
  453. #endif // OS
  454. };
  455. // Default implementation for AtomicOpsRaw; provides implementation of mem-fenced
  456. // atomic operations where fencing is done with a sync object wrapped around a NoSync
  457. // operation implemented in the base class. If such implementation is not possible
  458. // on a given platform, #ifdefs can be used to disable it and then op functions can be
  459. // implemented individually in the appropriate AtomicOpsRaw<size> class.
  460. template<class O>
  461. struct AtomicOpsRaw_DefImpl : public O
  462. {
  463. typedef typename O::T O_T;
  464. typedef typename O::FullSync O_FullSync;
  465. typedef typename O::AcquireSync O_AcquireSync;
  466. typedef typename O::ReleaseSync O_ReleaseSync;
  467. // If there is no thread support, provide the default implementation. In this case,
  468. // the base class (0) must still provide the T declaration.
  469. #ifndef OVR_ENABLE_THREADS
  470. // Atomic exchange of val with argument. Returns old val.
  471. inline static O_T Exchange_NoSync(volatile O_T* p, O_T val) { O_T old = *p; *p = val; return old; }
  472. // Adds a new val to argument; returns its old val.
  473. inline static O_T ExchangeAdd_NoSync(volatile O_T* p, O_T val) { O_T old = *p; *p += val; return old; }
  474. // Compares the argument data with 'c' val.
  475. // If succeeded, stores val int '*p' and returns true; otherwise returns false.
  476. inline static bool CompareAndSet_NoSync(volatile O_T* p, O_T c, O_T val) { if (*p==c) { *p = val; return 1; } return 0; }
  477. #endif
  478. // If NoSync wrapped implementation may not be possible, it this block should be
  479. // replaced with per-function implementation in O.
  480. // "AtomicOpsRaw_DefImpl<O>::" prefix in calls below.
  481. inline static O_T Exchange_Sync(volatile O_T* p, O_T val) { O_FullSync sync; OVR_UNUSED(sync); return AtomicOpsRaw_DefImpl<O>::Exchange_NoSync(p, val); }
  482. inline static O_T Exchange_Release(volatile O_T* p, O_T val) { O_ReleaseSync sync; OVR_UNUSED(sync); return AtomicOpsRaw_DefImpl<O>::Exchange_NoSync(p, val); }
  483. inline static O_T Exchange_Acquire(volatile O_T* p, O_T val) { O_AcquireSync sync; OVR_UNUSED(sync); return AtomicOpsRaw_DefImpl<O>::Exchange_NoSync(p, val); }
  484. inline static O_T ExchangeAdd_Sync(volatile O_T* p, O_T val) { O_FullSync sync; OVR_UNUSED(sync); return AtomicOpsRaw_DefImpl<O>::ExchangeAdd_NoSync(p, val); }
  485. inline static O_T ExchangeAdd_Release(volatile O_T* p, O_T val) { O_ReleaseSync sync; OVR_UNUSED(sync); return AtomicOpsRaw_DefImpl<O>::ExchangeAdd_NoSync(p, val); }
  486. inline static O_T ExchangeAdd_Acquire(volatile O_T* p, O_T val) { O_AcquireSync sync; OVR_UNUSED(sync); return AtomicOpsRaw_DefImpl<O>::ExchangeAdd_NoSync(p, val); }
  487. inline static bool CompareAndSet_Sync(volatile O_T* p, O_T c, O_T val) { O_FullSync sync; OVR_UNUSED(sync); return AtomicOpsRaw_DefImpl<O>::CompareAndSet_NoSync(p,c,val); }
  488. inline static bool CompareAndSet_Release(volatile O_T* p, O_T c, O_T val) { O_ReleaseSync sync; OVR_UNUSED(sync); return AtomicOpsRaw_DefImpl<O>::CompareAndSet_NoSync(p,c,val); }
  489. inline static bool CompareAndSet_Acquire(volatile O_T* p, O_T c, O_T val) { O_AcquireSync sync; OVR_UNUSED(sync); return AtomicOpsRaw_DefImpl<O>::CompareAndSet_NoSync(p,c,val); }
  490. // Loads and stores with memory fence. These have only the relevant versions.
  491. #ifdef OVR_CPU_X86
  492. // On X86, Store_Release is implemented as exchange. Note that we can also
  493. // consider 'sfence' in the future, although it is not as compatible with older CPUs.
  494. inline static void Store_Release(volatile O_T* p, O_T val) { Exchange_Release(p, val); }
  495. #else
  496. inline static void Store_Release(volatile O_T* p, O_T val) { O_ReleaseSync sync; OVR_UNUSED(sync); *p = val; }
  497. #endif
  498. inline static O_T Load_Acquire(const volatile O_T* p)
  499. {
  500. O_AcquireSync sync;
  501. OVR_UNUSED(sync);
  502. #if defined(OVR_CC_MSVC)
  503. _ReadBarrier(); // Compiler fence and load barrier
  504. #elif defined(OVR_CC_INTEL)
  505. __memory_barrier(); // Compiler fence
  506. #else
  507. // GCC-compatible:
  508. asm volatile ("" : : : "memory"); // Compiler fence
  509. #endif
  510. return *p;
  511. }
  512. };
  513. template<int size>
  514. struct AtomicOpsRaw : public AtomicOpsRawBase { };
  515. template<>
  516. struct AtomicOpsRaw<4> : public AtomicOpsRaw_DefImpl<AtomicOpsRaw_4ByteImpl>
  517. {
  518. // Ensure that assigned type size is correct.
  519. AtomicOpsRaw()
  520. { OVR_COMPILER_ASSERT(sizeof(AtomicOpsRaw_DefImpl<AtomicOpsRaw_4ByteImpl>::T) == 4); }
  521. };
  522. template<>
  523. struct AtomicOpsRaw<8> : public AtomicOpsRaw_DefImpl<AtomicOpsRaw_8ByteImpl>
  524. {
  525. AtomicOpsRaw()
  526. { OVR_COMPILER_ASSERT(sizeof(AtomicOpsRaw_DefImpl<AtomicOpsRaw_8ByteImpl>::T) == 8); }
  527. };
  528. // *** AtomicOps - implementation of atomic Ops for specified class
  529. // Implements atomic ops on a class, provided that the object is either
  530. // 4 or 8 bytes in size (depending on the AtomicOpsRaw specializations
  531. // available). Relies on AtomicOpsRaw for much of implementation.
  532. template<class C>
  533. class AtomicOps
  534. {
  535. typedef AtomicOpsRaw<sizeof(C)> Ops;
  536. typedef typename Ops::T T;
  537. typedef volatile typename Ops::T* PT;
  538. // We cast through unions to (1) avoid pointer size compiler warnings
  539. // and (2) ensure that there are no problems with strict pointer aliasing.
  540. union C2T_union { C c; T t; };
  541. public:
  542. // General purpose implementation for standard syncs.
  543. inline static C Exchange_Sync(volatile C* p, C val) { C2T_union u; u.c = val; u.t = Ops::Exchange_Sync((PT)p, u.t); return u.c; }
  544. inline static C Exchange_Release(volatile C* p, C val) { C2T_union u; u.c = val; u.t = Ops::Exchange_Release((PT)p, u.t); return u.c; }
  545. inline static C Exchange_Acquire(volatile C* p, C val) { C2T_union u; u.c = val; u.t = Ops::Exchange_Acquire((PT)p, u.t); return u.c; }
  546. inline static C Exchange_NoSync(volatile C* p, C val) { C2T_union u; u.c = val; u.t = Ops::Exchange_NoSync((PT)p, u.t); return u.c; }
  547. inline static C ExchangeAdd_Sync(volatile C* p, C val) { C2T_union u; u.c = val; u.t = Ops::ExchangeAdd_Sync((PT)p, u.t); return u.c; }
  548. inline static C ExchangeAdd_Release(volatile C* p, C val) { C2T_union u; u.c = val; u.t = Ops::ExchangeAdd_Release((PT)p, u.t); return u.c; }
  549. inline static C ExchangeAdd_Acquire(volatile C* p, C val) { C2T_union u; u.c = val; u.t = Ops::ExchangeAdd_Acquire((PT)p, u.t); return u.c; }
  550. inline static C ExchangeAdd_NoSync(volatile C* p, C val) { C2T_union u; u.c = val; u.t = Ops::ExchangeAdd_NoSync((PT)p, u.t); return u.c; }
  551. inline static bool CompareAndSet_Sync(volatile C* p, C c, C val) { C2T_union u,cu; u.c = val; cu.c = c; return Ops::CompareAndSet_Sync((PT)p, cu.t, u.t); }
  552. inline static bool CompareAndSet_Release(volatile C* p, C c, C val){ C2T_union u,cu; u.c = val; cu.c = c; return Ops::CompareAndSet_Release((PT)p, cu.t, u.t); }
  553. inline static bool CompareAndSet_Acquire(volatile C* p, C c, C val){ C2T_union u,cu; u.c = val; cu.c = c; return Ops::CompareAndSet_Acquire((PT)p, cu.t, u.t); }
  554. inline static bool CompareAndSet_NoSync(volatile C* p, C c, C val) { C2T_union u,cu; u.c = val; cu.c = c; return Ops::CompareAndSet_NoSync((PT)p, cu.t, u.t); }
  555. // Loads and stores with memory fence. These have only the relevant versions.
  556. inline static void Store_Release(volatile C* p, C val) { C2T_union u; u.c = val; Ops::Store_Release((PT)p, u.t); }
  557. inline static C Load_Acquire(const volatile C* p) { C2T_union u; u.t = Ops::Load_Acquire((PT)p); return u.c; }
  558. // Deprecated typo error:
  559. inline static bool CompareAndSet_Relse(volatile C* p, C c, C val){ C2T_union u,cu; u.c = val; cu.c = c; return Ops::CompareAndSet_Acquire((PT)p, cu.t, u.t); }
  560. };
  561. // Atomic value base class - implements operations shared for integers and pointers.
  562. template<class T>
  563. class AtomicValueBase
  564. {
  565. protected:
  566. typedef AtomicOps<T> Ops;
  567. public:
  568. volatile T Value;
  569. inline AtomicValueBase() { }
  570. explicit inline AtomicValueBase(T val) { Ops::Store_Release(&Value, val); }
  571. // Most libraries (TBB and Joshua Scholar's) library do not do Load_Acquire
  572. // here, since most algorithms do not require atomic loads. Needs some research.
  573. inline operator T() const { return Value; }
  574. // *** Standard Atomic inlines
  575. inline T Exchange_Sync(T val) { return Ops::Exchange_Sync(&Value, val); }
  576. inline T Exchange_Release(T val) { return Ops::Exchange_Release(&Value, val); }
  577. inline T Exchange_Acquire(T val) { return Ops::Exchange_Acquire(&Value, val); }
  578. inline T Exchange_NoSync(T val) { return Ops::Exchange_NoSync(&Value, val); }
  579. inline bool CompareAndSet_Sync(T c, T val) { return Ops::CompareAndSet_Sync(&Value, c, val); }
  580. inline bool CompareAndSet_Release(T c, T val) { return Ops::CompareAndSet_Release(&Value, c, val); }
  581. inline bool CompareAndSet_Acquire(T c, T val) { return Ops::CompareAndSet_Acquire(&Value, c, val); }
  582. inline bool CompareAndSet_NoSync(T c, T val) { return Ops::CompareAndSet_NoSync(&Value, c, val); }
  583. // Load & Store.
  584. inline void Store_Release(T val) { Ops::Store_Release(&Value, val); }
  585. inline T Load_Acquire() const { return Ops::Load_Acquire(&Value); }
  586. };
  587. // ***** AtomicPtr - Atomic pointer template
  588. // This pointer class supports atomic assignments with release,
  589. // increment / decrement operations, and conditional compare + set.
  590. template<class T>
  591. class AtomicPtr : public AtomicValueBase<T*>
  592. {
  593. typedef typename AtomicValueBase<T*>::Ops Ops;
  594. public:
  595. // Initialize pointer value to 0 by default; use Store_Release only with explicit constructor.
  596. inline AtomicPtr() : AtomicValueBase<T*>() { this->Value = 0; }
  597. explicit inline AtomicPtr(T* val) : AtomicValueBase<T*>(val) { }
  598. // Pointer access.
  599. inline T* operator -> () const { return this->Load_Acquire(); }
  600. // It looks like it is convenient to have Load_Acquire characteristics
  601. // for this, since that is convenient for algorithms such as linked
  602. // list traversals that can be added to bu another thread.
  603. inline operator T* () const { return this->Load_Acquire(); }
  604. // *** Standard Atomic inlines (applicable to pointers)
  605. // ExhangeAdd considers pointer size for pointers.
  606. template<class I>
  607. inline T* ExchangeAdd_Sync(I incr) { return Ops::ExchangeAdd_Sync(&this->Value, ((T*)0) + incr); }
  608. template<class I>
  609. inline T* ExchangeAdd_Release(I incr) { return Ops::ExchangeAdd_Release(&this->Value, ((T*)0) + incr); }
  610. template<class I>
  611. inline T* ExchangeAdd_Acquire(I incr) { return Ops::ExchangeAdd_Acquire(&this->Value, ((T*)0) + incr); }
  612. template<class I>
  613. inline T* ExchangeAdd_NoSync(I incr) { return Ops::ExchangeAdd_NoSync(&this->Value, ((T*)0) + incr); }
  614. // *** Atomic Operators
  615. inline T* operator = (T* val) { this->Store_Release(val); return val; }
  616. template<class I>
  617. inline T* operator += (I val) { return ExchangeAdd_Sync(val) + val; }
  618. template<class I>
  619. inline T* operator -= (I val) { return operator += (-val); }
  620. inline T* operator ++ () { return ExchangeAdd_Sync(1) + 1; }
  621. inline T* operator -- () { return ExchangeAdd_Sync(-1) - 1; }
  622. inline T* operator ++ (int) { return ExchangeAdd_Sync(1); }
  623. inline T* operator -- (int) { return ExchangeAdd_Sync(-1); }
  624. };
  625. // ***** AtomicInt - Atomic integer template
  626. // Implements an atomic integer type; the exact type to use is provided
  627. // as an argument. Supports atomic Acquire / Release semantics, atomic
  628. // arithmetic operations, and atomic conditional compare + set.
  629. template<class T>
  630. class AtomicInt : public AtomicValueBase<T>
  631. {
  632. typedef typename AtomicValueBase<T>::Ops Ops;
  633. public:
  634. inline AtomicInt() : AtomicValueBase<T>() { }
  635. explicit inline AtomicInt(T val) : AtomicValueBase<T>(val) { }
  636. // *** Standard Atomic inlines (applicable to int)
  637. inline T ExchangeAdd_Sync(T val) { return Ops::ExchangeAdd_Sync(&this->Value, val); }
  638. inline T ExchangeAdd_Release(T val) { return Ops::ExchangeAdd_Release(&this->Value, val); }
  639. inline T ExchangeAdd_Acquire(T val) { return Ops::ExchangeAdd_Acquire(&this->Value, val); }
  640. inline T ExchangeAdd_NoSync(T val) { return Ops::ExchangeAdd_NoSync(&this->Value, val); }
  641. // These increments could be more efficient because they don't return a value.
  642. inline void Increment_Sync() { ExchangeAdd_Sync((T)1); }
  643. inline void Increment_Release() { ExchangeAdd_Release((T)1); }
  644. inline void Increment_Acquire() { ExchangeAdd_Acquire((T)1); }
  645. inline void Increment_NoSync() { ExchangeAdd_NoSync((T)1); }
  646. // *** Atomic Operators
  647. inline T operator = (T val) { this->Store_Release(val); return val; }
  648. inline T operator += (T val) { return ExchangeAdd_Sync(val) + val; }
  649. inline T operator -= (T val) { return ExchangeAdd_Sync(0 - val) - val; }
  650. inline T operator ++ () { return ExchangeAdd_Sync((T)1) + 1; }
  651. inline T operator -- () { return ExchangeAdd_Sync(((T)0)-1) - 1; }
  652. inline T operator ++ (int) { return ExchangeAdd_Sync((T)1); }
  653. inline T operator -- (int) { return ExchangeAdd_Sync(((T)0)-1); }
  654. // More complex atomic operations. Leave it to compiler whether to optimize them or not.
  655. T operator &= (T arg)
  656. {
  657. T comp, newVal;
  658. do {
  659. comp = this->Value;
  660. newVal = comp & arg;
  661. } while(!this->CompareAndSet_Sync(comp, newVal));
  662. return newVal;
  663. }
  664. T operator |= (T arg)
  665. {
  666. T comp, newVal;
  667. do {
  668. comp = this->Value;
  669. newVal = comp | arg;
  670. } while(!this->CompareAndSet_Sync(comp, newVal));
  671. return newVal;
  672. }
  673. T operator ^= (T arg)
  674. {
  675. T comp, newVal;
  676. do {
  677. comp = this->Value;
  678. newVal = comp ^ arg;
  679. } while(!this->CompareAndSet_Sync(comp, newVal));
  680. return newVal;
  681. }
  682. T operator *= (T arg)
  683. {
  684. T comp, newVal;
  685. do {
  686. comp = this->Value;
  687. newVal = comp * arg;
  688. } while(!this->CompareAndSet_Sync(comp, newVal));
  689. return newVal;
  690. }
  691. T operator /= (T arg)
  692. {
  693. T comp, newVal;
  694. do {
  695. comp = this->Value;
  696. newVal = comp / arg;
  697. } while(!CompareAndSet_Sync(comp, newVal));
  698. return newVal;
  699. }
  700. T operator >>= (unsigned bits)
  701. {
  702. T comp, newVal;
  703. do {
  704. comp = this->Value;
  705. newVal = comp >> bits;
  706. } while(!CompareAndSet_Sync(comp, newVal));
  707. return newVal;
  708. }
  709. T operator <<= (unsigned bits)
  710. {
  711. T comp, newVal;
  712. do {
  713. comp = this->Value;
  714. newVal = comp << bits;
  715. } while(!this->CompareAndSet_Sync(comp, newVal));
  716. return newVal;
  717. }
  718. };
  719. #endif // OVR_OS_LINUX
  720. //-----------------------------------------------------------------------------------
  721. // ***** Lock
  722. // Lock is a simplest and most efficient mutual-exclusion lock class.
  723. // Unlike Mutex, it cannot be waited on.
  724. class Lock
  725. {
  726. #if !defined(OVR_ENABLE_THREADS)
  727. public:
  728. // With no thread support, lock does nothing.
  729. inline Lock() { }
  730. inline Lock(unsigned) { }
  731. inline ~Lock() { }
  732. inline void DoLock() { }
  733. inline void Unlock() { }
  734. // Windows.
  735. #elif defined(OVR_OS_MS)
  736. CRITICAL_SECTION cs;
  737. public:
  738. Lock(unsigned spinCount = 10000); // Mutexes with non-zero spin counts usually result in better performance.
  739. ~Lock();
  740. // Locking functions.
  741. inline void DoLock() { ::EnterCriticalSection(&cs); }
  742. inline void Unlock() { ::LeaveCriticalSection(&cs); }
  743. #else
  744. pthread_mutex_t mutex;
  745. public:
  746. static pthread_mutexattr_t RecursiveAttr;
  747. static bool RecursiveAttrInit;
  748. Lock (unsigned spinCount = 0) // To do: Support spin count, probably via a custom lock implementation.
  749. {
  750. OVR_UNUSED(spinCount);
  751. if (!RecursiveAttrInit)
  752. {
  753. pthread_mutexattr_init(&RecursiveAttr);
  754. pthread_mutexattr_settype(&RecursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  755. RecursiveAttrInit = 1;
  756. }
  757. pthread_mutex_init(&mutex,&RecursiveAttr);
  758. }
  759. ~Lock () { pthread_mutex_destroy(&mutex); }
  760. inline void DoLock() { pthread_mutex_lock(&mutex); }
  761. inline void Unlock() { pthread_mutex_unlock(&mutex); }
  762. #endif // OVR_ENABLE_THREDS
  763. public:
  764. // Locker class, used for automatic locking
  765. class Locker
  766. {
  767. Lock *pLock;
  768. public:
  769. Locker(Lock *plock)
  770. {
  771. pLock = plock;
  772. if (plock)
  773. pLock->DoLock();
  774. }
  775. ~Locker()
  776. {
  777. Release();
  778. }
  779. void Release()
  780. {
  781. if (pLock)
  782. pLock->Unlock();
  783. pLock = nullptr;
  784. }
  785. };
  786. };
  787. //-------------------------------------------------------------------------------------
  788. // Globally shared Lock implementation used for MessageHandlers, etc.
  789. class SharedLock
  790. {
  791. public:
  792. SharedLock() : UseCount(0) {}
  793. Lock* GetLockAddRef();
  794. void ReleaseLock(Lock* plock);
  795. private:
  796. Lock* toLock() { return (Lock*)Buffer; }
  797. // UseCount and max alignment.
  798. AtomicInt<int> UseCount;
  799. uint64_t Buffer[(sizeof(Lock)+sizeof(uint64_t)-1)/sizeof(uint64_t)];
  800. };
  801. //-------------------------------------------------------------------------------------
  802. // Thin locking wrapper around data
  803. template<class T> class LockedData
  804. {
  805. public:
  806. LockedData(Lock& lock) :
  807. TheLock(lock)
  808. {
  809. }
  810. LockedData& operator=(const LockedData& rhs)
  811. {
  812. OVR_ASSERT(false);
  813. return *this;
  814. }
  815. T Get()
  816. {
  817. Lock::Locker locker(&TheLock);
  818. return Instance;
  819. }
  820. void Set(const T& value)
  821. {
  822. Lock::Locker locker(&TheLock);
  823. Instance = value;
  824. }
  825. // Returns true if the value has changed.
  826. // Returns false if the value has not changed.
  827. bool GetIfChanged(T& value)
  828. {
  829. Lock::Locker locker(&TheLock);
  830. if (value != Instance)
  831. {
  832. value = Instance;
  833. return true;
  834. }
  835. return false;
  836. }
  837. protected:
  838. T Instance;
  839. Lock& TheLock;
  840. };
  841. } // namespace OVR
  842. #endif