initial commit

4 files changed +687 −0

  • + LICENSE.txt
  • + Makefile
  • + README.md
  • + atomic.c
1commit 2681747f227c6fee6a50a33c72b09b397d2ecefd
2Author: Daniel Kolesa <daniel@octaforge.org>
3Date: Mon Dec 12 16:49:25 2022 +0100
4
5 initial commit
6
7diff --git a/LICENSE.txt b/LICENSE.txt
8new file mode 100644
9index 0000000..d645695
10--- /dev/null
11+++ b/LICENSE.txt
12@@ -0,0 +1,202 @@
13+
14+ Apache License
15+ Version 2.0, January 2004
16+ http://www.apache.org/licenses/
17+
18+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
19+
20+ 1. Definitions.
21+
22+ "License" shall mean the terms and conditions for use, reproduction,
23+ and distribution as defined by Sections 1 through 9 of this document.
24+
25+ "Licensor" shall mean the copyright owner or entity authorized by
26+ the copyright owner that is granting the License.
27+
28+ "Legal Entity" shall mean the union of the acting entity and all
29+ other entities that control, are controlled by, or are under common
30+ control with that entity. For the purposes of this definition,
31+ "control" means (i) the power, direct or indirect, to cause the
32+ direction or management of such entity, whether by contract or
33+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
34+ outstanding shares, or (iii) beneficial ownership of such entity.
35+
36+ "You" (or "Your") shall mean an individual or Legal Entity
37+ exercising permissions granted by this License.
38+
39+ "Source" form shall mean the preferred form for making modifications,
40+ including but not limited to software source code, documentation
41+ source, and configuration files.
42+
43+ "Object" form shall mean any form resulting from mechanical
44+ transformation or translation of a Source form, including but
45+ not limited to compiled object code, generated documentation,
46+ and conversions to other media types.
47+
48+ "Work" shall mean the work of authorship, whether in Source or
49+ Object form, made available under the License, as indicated by a
50+ copyright notice that is included in or attached to the work
51+ (an example is provided in the Appendix below).
52+
53+ "Derivative Works" shall mean any work, whether in Source or Object
54+ form, that is based on (or derived from) the Work and for which the
55+ editorial revisions, annotations, elaborations, or other modifications
56+ represent, as a whole, an original work of authorship. For the purposes
57+ of this License, Derivative Works shall not include works that remain
58+ separable from, or merely link (or bind by name) to the interfaces of,
59+ the Work and Derivative Works thereof.
60+
61+ "Contribution" shall mean any work of authorship, including
62+ the original version of the Work and any modifications or additions
63+ to that Work or Derivative Works thereof, that is intentionally
64+ submitted to Licensor for inclusion in the Work by the copyright owner
65+ or by an individual or Legal Entity authorized to submit on behalf of
66+ the copyright owner. For the purposes of this definition, "submitted"
67+ means any form of electronic, verbal, or written communication sent
68+ to the Licensor or its representatives, including but not limited to
69+ communication on electronic mailing lists, source code control systems,
70+ and issue tracking systems that are managed by, or on behalf of, the
71+ Licensor for the purpose of discussing and improving the Work, but
72+ excluding communication that is conspicuously marked or otherwise
73+ designated in writing by the copyright owner as "Not a Contribution."
74+
75+ "Contributor" shall mean Licensor and any individual or Legal Entity
76+ on behalf of whom a Contribution has been received by Licensor and
77+ subsequently incorporated within the Work.
78+
79+ 2. Grant of Copyright License. Subject to the terms and conditions of
80+ this License, each Contributor hereby grants to You a perpetual,
81+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
82+ copyright license to reproduce, prepare Derivative Works of,
83+ publicly display, publicly perform, sublicense, and distribute the
84+ Work and such Derivative Works in Source or Object form.
85+
86+ 3. Grant of Patent License. Subject to the terms and conditions of
87+ this License, each Contributor hereby grants to You a perpetual,
88+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
89+ (except as stated in this section) patent license to make, have made,
90+ use, offer to sell, sell, import, and otherwise transfer the Work,
91+ where such license applies only to those patent claims licensable
92+ by such Contributor that are necessarily infringed by their
93+ Contribution(s) alone or by combination of their Contribution(s)
94+ with the Work to which such Contribution(s) was submitted. If You
95+ institute patent litigation against any entity (including a
96+ cross-claim or counterclaim in a lawsuit) alleging that the Work
97+ or a Contribution incorporated within the Work constitutes direct
98+ or contributory patent infringement, then any patent licenses
99+ granted to You under this License for that Work shall terminate
100+ as of the date such litigation is filed.
101+
102+ 4. Redistribution. You may reproduce and distribute copies of the
103+ Work or Derivative Works thereof in any medium, with or without
104+ modifications, and in Source or Object form, provided that You
105+ meet the following conditions:
106+
107+ (a) You must give any other recipients of the Work or
108+ Derivative Works a copy of this License; and
109+
110+ (b) You must cause any modified files to carry prominent notices
111+ stating that You changed the files; and
112+
113+ (c) You must retain, in the Source form of any Derivative Works
114+ that You distribute, all copyright, patent, trademark, and
115+ attribution notices from the Source form of the Work,
116+ excluding those notices that do not pertain to any part of
117+ the Derivative Works; and
118+
119+ (d) If the Work includes a "NOTICE" text file as part of its
120+ distribution, then any Derivative Works that You distribute must
121+ include a readable copy of the attribution notices contained
122+ within such NOTICE file, excluding those notices that do not
123+ pertain to any part of the Derivative Works, in at least one
124+ of the following places: within a NOTICE text file distributed
125+ as part of the Derivative Works; within the Source form or
126+ documentation, if provided along with the Derivative Works; or,
127+ within a display generated by the Derivative Works, if and
128+ wherever such third-party notices normally appear. The contents
129+ of the NOTICE file are for informational purposes only and
130+ do not modify the License. You may add Your own attribution
131+ notices within Derivative Works that You distribute, alongside
132+ or as an addendum to the NOTICE text from the Work, provided
133+ that such additional attribution notices cannot be construed
134+ as modifying the License.
135+
136+ You may add Your own copyright statement to Your modifications and
137+ may provide additional or different license terms and conditions
138+ for use, reproduction, or distribution of Your modifications, or
139+ for any such Derivative Works as a whole, provided Your use,
140+ reproduction, and distribution of the Work otherwise complies with
141+ the conditions stated in this License.
142+
143+ 5. Submission of Contributions. Unless You explicitly state otherwise,
144+ any Contribution intentionally submitted for inclusion in the Work
145+ by You to the Licensor shall be under the terms and conditions of
146+ this License, without any additional terms or conditions.
147+ Notwithstanding the above, nothing herein shall supersede or modify
148+ the terms of any separate license agreement you may have executed
149+ with Licensor regarding such Contributions.
150+
151+ 6. Trademarks. This License does not grant permission to use the trade
152+ names, trademarks, service marks, or product names of the Licensor,
153+ except as required for reasonable and customary use in describing the
154+ origin of the Work and reproducing the content of the NOTICE file.
155+
156+ 7. Disclaimer of Warranty. Unless required by applicable law or
157+ agreed to in writing, Licensor provides the Work (and each
158+ Contributor provides its Contributions) on an "AS IS" BASIS,
159+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
160+ implied, including, without limitation, any warranties or conditions
161+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
162+ PARTICULAR PURPOSE. You are solely responsible for determining the
163+ appropriateness of using or redistributing the Work and assume any
164+ risks associated with Your exercise of permissions under this License.
165+
166+ 8. Limitation of Liability. In no event and under no legal theory,
167+ whether in tort (including negligence), contract, or otherwise,
168+ unless required by applicable law (such as deliberate and grossly
169+ negligent acts) or agreed to in writing, shall any Contributor be
170+ liable to You for damages, including any direct, indirect, special,
171+ incidental, or consequential damages of any character arising as a
172+ result of this License or out of the use or inability to use the
173+ Work (including but not limited to damages for loss of goodwill,
174+ work stoppage, computer failure or malfunction, or any and all
175+ other commercial damages or losses), even if such Contributor
176+ has been advised of the possibility of such damages.
177+
178+ 9. Accepting Warranty or Additional Liability. While redistributing
179+ the Work or Derivative Works thereof, You may choose to offer,
180+ and charge a fee for, acceptance of support, warranty, indemnity,
181+ or other liability obligations and/or rights consistent with this
182+ License. However, in accepting such obligations, You may act only
183+ on Your own behalf and on Your sole responsibility, not on behalf
184+ of any other Contributor, and only if You agree to indemnify,
185+ defend, and hold each Contributor harmless for any liability
186+ incurred by, or claims asserted against, such Contributor by reason
187+ of your accepting any such warranty or additional liability.
188+
189+ END OF TERMS AND CONDITIONS
190+
191+ APPENDIX: How to apply the Apache License to your work.
192+
193+ To apply the Apache License to your work, attach the following
194+ boilerplate notice, with the fields enclosed by brackets "[]"
195+ replaced with your own identifying information. (Don't include
196+ the brackets!) The text should be enclosed in the appropriate
197+ comment syntax for the file format. We also recommend that a
198+ file or class name and description of purpose be included on the
199+ same "printed page" as the copyright notice for easier
200+ identification within third-party archives.
201+
202+ Copyright [yyyy] [name of copyright owner]
203+
204+ Licensed under the Apache License, Version 2.0 (the "License");
205+ you may not use this file except in compliance with the License.
206+ You may obtain a copy of the License at
207+
208+ http://www.apache.org/licenses/LICENSE-2.0
209+
210+ Unless required by applicable law or agreed to in writing, software
211+ distributed under the License is distributed on an "AS IS" BASIS,
212+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
213+ See the License for the specific language governing permissions and
214+ limitations under the License.
215diff --git a/Makefile b/Makefile
216new file mode 100644
217index 0000000..6c649f0
218--- /dev/null
219+++ b/Makefile
220@@ -0,0 +1,41 @@
221+CC ?= cc
222+AR ?= ar
223+CFLAGS ?= -O2
224+
225+PREFIX ?= /usr/local
226+LIBDIR ?= $(PREFIX)/lib
227+
228+SOBASE = libatomic.so
229+SONAME = $(SOBASE).1
230+SHAREDLIB = $(SONAME).69.0
231+STATICLIB = libatomic.a
232+
233+EXTRA_CFLAGS = -std=c99 -Wall -Wextra -fPIC
234+
235+OBJS = atomic.o
236+
237+all: $(SHAREDLIB) $(STATICLIB)
238+
239+.c.o:
240+ $(CC) $(EXTRA_CFLAGS) $(CFLAGS) -c -o $@ $<
241+
242+$(SHAREDLIB): $(OBJS)
243+ $(CC) $(OBJS) $(EXTRA_CFLAGS) $(CFLAGS) $(LDFLAGS) \
244+ -nolibc -shared -Wl,-soname,$(SONAME) -o $(SHAREDLIB)
245+
246+$(STATICLIB): $(OBJS)
247+ $(AR) -rcs $(STATICLIB) $(OBJS)
248+
249+# no tests
250+check:
251+ :
252+
253+clean:
254+ rm -f $(OBJS) $(SHAREDLIB) $(STATICLIB)
255+
256+install: $(SHAREDLIB) $(STATICLIB)
257+ install -d $(DESTDIR)$(LIBDIR)
258+ install -m 755 $(SHAREDLIB) $(DESTDIR)$(LIBDIR)
259+ install -m 755 $(STATICLIB) $(DESTDIR)$(LIBDIR)
260+ ln -sf $(SHAREDLIB) $(DESTDIR)$(LIBDIR)/$(SOBASE)
261+ ln -sf $(SHAREDLIB) $(DESTDIR)$(LIBDIR)/$(SONAME)
262diff --git a/README.md b/README.md
263new file mode 100644
264index 0000000..37dfbfa
265--- /dev/null
266+++ b/README.md
267@@ -0,0 +1,16 @@
268+# libatomic-chimera
269+
270+This is a replacement for GCC libatomic. It's ABI-compatible with libatomic
271+and provides the same compiler helpers and other APIs.
272+
273+It does not come with a header file. Its purposes are two:
274+
275+* to provide a compatibility library for existing binaries
276+* to provide emulation symbols for compiler intrinsics
277+
278+To build and install it, just use the supplied Makefile, or compile it by hand.
279+The Clang compiler is needed to build this; it may not compile with GCC.
280+
281+The code is based on `atomic.c` from LLVM's `compiler-rt`, and therefore is
282+available under the same license (Apache-2.0). Extra implementations have been
283+added for completeness/compatibility with GCC libatomic.
284diff --git a/atomic.c b/atomic.c
285new file mode 100644
286index 0000000..343e48b
287--- /dev/null
288+++ b/atomic.c
289@@ -0,0 +1,428 @@
290+// this is an implementation of libatomic created for Chimera Linux
291+//
292+// based on atomic.c from llvm's compiler-rt builtins
293+//
294+// missing implementations were filled in, some parts were rewritten
295+//
296+// changes by q66 <q66@chimera-linux.org>
297+//
298+// provided under the same license as llvm (apache-2.0)
299+//
300+// original header follows:
301+//
302+//===-- atomic.c - Implement support functions for atomic operations.------===//
303+//
304+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
305+// See https://llvm.org/LICENSE.txt for license information.
306+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
307+//
308+//===----------------------------------------------------------------------===//
309+//
310+// atomic.c defines a set of functions for performing atomic accesses on
311+// arbitrary-sized memory locations. This design uses locks that should
312+// be fast in the uncontended case, for two reasons:
313+//
314+// 1) This code must work with C programs that do not link to anything
315+// (including pthreads) and so it should not depend on any pthread
316+// functions.
317+// 2) Atomic operations, rather than explicit mutexes, are most commonly used
318+// on code where contended operations are rate.
319+//
320+// To avoid needing a per-object lock, this code allocates an array of
321+// locks and hashes the object pointers to find the one that it should use.
322+// For operations that must be atomic on two locations, the lower lock is
323+// always acquired first, to avoid deadlock.
324+//
325+//===----------------------------------------------------------------------===//
326+
327+#include <stdbool.h>
328+#include <string.h>
329+#include <stddef.h>
330+#include <stdint.h>
331+#include <fenv.h>
332+
333+#define SPINLOCK_COUNT (1 << 10)
334+
335+static const long SPINLOCK_MASK = SPINLOCK_COUNT - 1;
336+
337+/// lock implementation; clear and tas are guaranteed to be lock free
338+
339+typedef bool lock_t;
340+
341+static inline __attribute__((always_inline)) void unlock(lock_t *l) {
342+ __atomic_clear(l, __ATOMIC_RELEASE);
343+}
344+
345+static inline __attribute__((always_inline)) void lock(lock_t *l) {
346+ while (__atomic_test_and_set(l, __ATOMIC_ACQUIRE));
347+}
348+
349+static lock_t locks[SPINLOCK_COUNT];
350+
351+static inline __attribute__((always_inline)) lock_t *lock_for_pointer(void *ptr) {
352+ intptr_t hash = (intptr_t)ptr;
353+ // Disregard the lowest 4 bits. We want all values that may be part of the
354+ // same memory operation to hash to the same value and therefore use the same
355+ // lock.
356+ hash >>= 4;
357+ // Use the next bits as the basis for the hash
358+ intptr_t low = hash & SPINLOCK_MASK;
359+ // Now use the high(er) set of bits to perturb the hash, so that we don't
360+ // get collisions from atomic fields in a single object
361+ hash >>= 16;
362+ hash ^= low;
363+ // Return a pointer to the word to use
364+ return locks + (hash & SPINLOCK_MASK);
365+}
366+
367+/// Macros for determining whether a size is lock free.
368+#define ATOMIC_ALWAYS_LOCK_FREE_OR_ALIGNED_LOCK_FREE(size, p) \
369+ (__atomic_always_lock_free(size, p) || \
370+ (__atomic_always_lock_free(size, 0) && ((uintptr_t)p % size) == 0))
371+
372+#define IS_LOCK_FREE_1(p) ATOMIC_ALWAYS_LOCK_FREE_OR_ALIGNED_LOCK_FREE(1, p)
373+#define IS_LOCK_FREE_2(p) ATOMIC_ALWAYS_LOCK_FREE_OR_ALIGNED_LOCK_FREE(2, p)
374+#define IS_LOCK_FREE_4(p) ATOMIC_ALWAYS_LOCK_FREE_OR_ALIGNED_LOCK_FREE(4, p)
375+#define IS_LOCK_FREE_8(p) ATOMIC_ALWAYS_LOCK_FREE_OR_ALIGNED_LOCK_FREE(8, p)
376+#define IS_LOCK_FREE_16(p) ATOMIC_ALWAYS_LOCK_FREE_OR_ALIGNED_LOCK_FREE(16, p)
377+
378+/// Macro that calls the compiler-generated lock-free versions of functions
379+/// when they exist.
380+#define TRY_LOCK_FREE_CASE(n, type, ptr) \
381+ case n: \
382+ if (IS_LOCK_FREE_##n(ptr)) { \
383+ LOCK_FREE_ACTION(type); \
384+ } \
385+ break;
386+#ifdef __SIZEOF_INT128__
387+#define TRY_LOCK_FREE_CASE_16(p) TRY_LOCK_FREE_CASE(16, __uint128_t, p)
388+#else
389+#define TRY_LOCK_FREE_CASE_16(p) /* __uint128_t not available */
390+#endif
391+
392+#define LOCK_FREE_CASES(ptr) \
393+ do { \
394+ switch (size) { \
395+ TRY_LOCK_FREE_CASE(1, uint8_t, ptr) \
396+ TRY_LOCK_FREE_CASE(2, uint16_t, ptr) \
397+ TRY_LOCK_FREE_CASE(4, uint32_t, ptr) \
398+ TRY_LOCK_FREE_CASE(8, uint64_t, ptr) \
399+ TRY_LOCK_FREE_CASE_16(ptr) /* __uint128_t may not be supported */ \
400+ default: \
401+ break; \
402+ } \
403+ } while (0)
404+
405+/// Whether atomic operations for the given size (and alignment) are lock-free.
406+#pragma redefine_extname __atomic_is_lock_free_c __atomic_is_lock_free
407+bool __atomic_is_lock_free_c(size_t size, void *ptr) {
408+#define LOCK_FREE_ACTION(type) return true;
409+ LOCK_FREE_CASES(ptr);
410+#undef LOCK_FREE_ACTION
411+ return false;
412+}
413+
414+/// An atomic load operation. This is atomic with respect to the source
415+/// pointer only.
416+#pragma redefine_extname __atomic_load_c __atomic_load
417+void __atomic_load_c(int size, void *src, void *dest, int model) {
418+#define LOCK_FREE_ACTION(type) \
419+ *((type *)dest) = __atomic_load_n((type *)src, model); \
420+ return;
421+ LOCK_FREE_CASES(src);
422+#undef LOCK_FREE_ACTION
423+ lock_t *l = lock_for_pointer(src);
424+ lock(l);
425+ memcpy(dest, src, size);
426+ unlock(l);
427+}
428+
429+/// An atomic store operation. This is atomic with respect to the destination
430+/// pointer only.
431+#pragma redefine_extname __atomic_store_c __atomic_store
432+void __atomic_store_c(int size, void *dest, void *src, int model) {
433+#define LOCK_FREE_ACTION(type) \
434+ __atomic_store_n((type *)dest, *(type *)src, model); \
435+ return;
436+ LOCK_FREE_CASES(dest);
437+#undef LOCK_FREE_ACTION
438+ lock_t *l = lock_for_pointer(dest);
439+ lock(l);
440+ memcpy(dest, src, size);
441+ unlock(l);
442+}
443+
444+/// Atomic compare and exchange operation. If the value at *ptr is identical
445+/// to the value at *expected, then this copies value at *desired to *ptr. If
446+/// they are not, then this stores the current value from *ptr in *expected.
447+///
448+/// This function returns 1 if the exchange takes place or 0 if it fails.
449+#pragma redefine_extname __atomic_compare_exchange_c __atomic_compare_exchange
450+int __atomic_compare_exchange_c(int size, void *ptr, void *expected,
451+ void *desired, int success, int failure) {
452+#define LOCK_FREE_ACTION(type) \
453+ return __atomic_compare_exchange_n( \
454+ (type *)ptr, (type *)expected, *(type *)desired, 0, success, \
455+ failure)
456+ LOCK_FREE_CASES(ptr);
457+#undef LOCK_FREE_ACTION
458+ lock_t *l = lock_for_pointer(ptr);
459+ lock(l);
460+ if (memcmp(ptr, expected, size) == 0) {
461+ memcpy(ptr, desired, size);
462+ unlock(l);
463+ return 1;
464+ }
465+ memcpy(expected, ptr, size);
466+ unlock(l);
467+ return 0;
468+}
469+
470+/// Performs an atomic exchange operation between two pointers. This is atomic
471+/// with respect to the target address.
472+#pragma redefine_extname __atomic_exchange_c __atomic_exchange
473+void __atomic_exchange_c(int size, void *ptr, void *val, void *old, int model) {
474+#define LOCK_FREE_ACTION(type) \
475+ *(type *)old = \
476+ __atomic_exchange_n((type *)ptr, *(type *)val, model); \
477+ return;
478+ LOCK_FREE_CASES(ptr);
479+#undef LOCK_FREE_ACTION
480+ lock_t *l = lock_for_pointer(ptr);
481+ lock(l);
482+ memcpy(old, ptr, size);
483+ memcpy(ptr, val, size);
484+ unlock(l);
485+}
486+
487+////////////////////////////////////////////////////////////////////////////////
488+// Where the size is known at compile time, the compiler may emit calls to
489+// specialised versions of the above functions.
490+////////////////////////////////////////////////////////////////////////////////
491+#ifdef __SIZEOF_INT128__
492+#define OPTIMISED_CASES \
493+ OPTIMISED_CASE(1, IS_LOCK_FREE_1, uint8_t) \
494+ OPTIMISED_CASE(2, IS_LOCK_FREE_2, uint16_t) \
495+ OPTIMISED_CASE(4, IS_LOCK_FREE_4, uint32_t) \
496+ OPTIMISED_CASE(8, IS_LOCK_FREE_8, uint64_t) \
497+ OPTIMISED_CASE(16, IS_LOCK_FREE_16, __uint128_t)
498+#else
499+#define OPTIMISED_CASES \
500+ OPTIMISED_CASE(1, IS_LOCK_FREE_1, uint8_t) \
501+ OPTIMISED_CASE(2, IS_LOCK_FREE_2, uint16_t) \
502+ OPTIMISED_CASE(4, IS_LOCK_FREE_4, uint32_t) \
503+ OPTIMISED_CASE(8, IS_LOCK_FREE_8, uint64_t)
504+#endif
505+
506+#define OPTIMISED_CASE(n, lockfree, type) \
507+ type __atomic_load_##n(type *src, int model) { \
508+ if (lockfree(src)) \
509+ return __atomic_load_n(src, model); \
510+ lock_t *l = lock_for_pointer(src); \
511+ lock(l); \
512+ type val = *src; \
513+ unlock(l); \
514+ return val; \
515+ }
516+OPTIMISED_CASES
517+#undef OPTIMISED_CASE
518+
519+#define OPTIMISED_CASE(n, lockfree, type) \
520+ void __atomic_store_##n(type *dest, type val, int model) { \
521+ if (lockfree(dest)) { \
522+ __atomic_store_n(dest, val, model); \
523+ return; \
524+ } \
525+ lock_t *l = lock_for_pointer(dest); \
526+ lock(l); \
527+ *dest = val; \
528+ unlock(l); \
529+ return; \
530+ }
531+OPTIMISED_CASES
532+#undef OPTIMISED_CASE
533+
534+#define OPTIMISED_CASE(n, lockfree, type) \
535+ type __atomic_exchange_##n(type *dest, type val, int model) { \
536+ if (lockfree(dest)) \
537+ return __atomic_exchange_n(dest, val, model); \
538+ lock_t *l = lock_for_pointer(dest); \
539+ lock(l); \
540+ type tmp = *dest; \
541+ *dest = val; \
542+ unlock(l); \
543+ return tmp; \
544+ }
545+OPTIMISED_CASES
546+#undef OPTIMISED_CASE
547+
548+#define OPTIMISED_CASE(n, lockfree, type) \
549+ bool __atomic_compare_exchange_##n(type *ptr, type *expected, type desired, \
550+ int success, int failure) { \
551+ if (lockfree(ptr)) \
552+ return __atomic_compare_exchange_n( \
553+ ptr, expected, desired, 0, success, failure); \
554+ lock_t *l = lock_for_pointer(ptr); \
555+ lock(l); \
556+ if (*ptr == *expected) { \
557+ *ptr = desired; \
558+ unlock(l); \
559+ return true; \
560+ } \
561+ *expected = *ptr; \
562+ unlock(l); \
563+ return false; \
564+ }
565+OPTIMISED_CASES
566+#undef OPTIMISED_CASE
567+
568+////////////////////////////////////////////////////////////////////////////////
569+// Atomic read-modify-write operations for integers of various sizes.
570+////////////////////////////////////////////////////////////////////////////////
571+#define ATOMIC_RMW(n, lockfree, type, opname, op) \
572+ type __atomic_fetch_##opname##_##n(type *ptr, type val, int model) { \
573+ if (lockfree(ptr)) \
574+ return __atomic_fetch_##opname(ptr, val, model); \
575+ lock_t *l = lock_for_pointer(ptr); \
576+ lock(l); \
577+ type tmp = *ptr; \
578+ *ptr = tmp op val; \
579+ unlock(l); \
580+ return tmp; \
581+ } \
582+ \
583+ type __atomic_##opname##_fetch_##n(type *ptr, type val, int model) { \
584+ if (lockfree(ptr)) \
585+ return __atomic_##opname##_fetch(ptr, val, model); \
586+ lock_t *l = lock_for_pointer(ptr); \
587+ lock(l); \
588+ type tmp = *ptr; \
589+ tmp = tmp op val; \
590+ *ptr = tmp; \
591+ unlock(l); \
592+ return tmp; \
593+ }
594+
595+#define ATOMIC_RMW_NAND(n, lockfree, type) \
596+ type __atomic_fetch_nand_##n(type *ptr, type val, int model) { \
597+ if (lockfree(ptr)) \
598+ return __atomic_fetch_nand(ptr, val, model); \
599+ lock_t *l = lock_for_pointer(ptr); \
600+ lock(l); \
601+ type tmp = *ptr; \
602+ *ptr = ~(tmp & val); \
603+ unlock(l); \
604+ return tmp; \
605+ } \
606+ \
607+ type __atomic_nand_fetch_##n(type *ptr, type val, int model) { \
608+ if (lockfree(ptr)) \
609+ return __atomic_nand_fetch(ptr, val, model); \
610+ lock_t *l = lock_for_pointer(ptr); \
611+ lock(l); \
612+ type tmp = *ptr; \
613+ tmp = ~(tmp & val); \
614+ *ptr = tmp; \
615+ unlock(l); \
616+ return tmp; \
617+ }
618+
619+#define ATOMIC_TAS(n, lockfree, type) \
620+ bool __atomic_test_and_set_##n(type *ptr, int model) { \
621+ if (lockfree(ptr)) \
622+ return __atomic_test_and_set(ptr, model); \
623+ lock_t *l = lock_for_pointer(ptr); \
624+ lock(l); \
625+ type tmp = *ptr; \
626+ *ptr = 1; \
627+ unlock(l); \
628+ return !!tmp; \
629+ }
630+
631+#define OPTIMISED_CASE(n, lockfree, type) ATOMIC_RMW(n, lockfree, type, add, +)
632+OPTIMISED_CASES
633+#undef OPTIMISED_CASE
634+#define OPTIMISED_CASE(n, lockfree, type) ATOMIC_RMW(n, lockfree, type, sub, -)
635+OPTIMISED_CASES
636+#undef OPTIMISED_CASE
637+#define OPTIMISED_CASE(n, lockfree, type) ATOMIC_RMW(n, lockfree, type, and, &)
638+OPTIMISED_CASES
639+#undef OPTIMISED_CASE
640+#define OPTIMISED_CASE(n, lockfree, type) ATOMIC_RMW(n, lockfree, type, or, |)
641+OPTIMISED_CASES
642+#undef OPTIMISED_CASE
643+#define OPTIMISED_CASE(n, lockfree, type) ATOMIC_RMW(n, lockfree, type, xor, ^)
644+OPTIMISED_CASES
645+#undef OPTIMISED_CASE
646+#define OPTIMISED_CASE(n, lockfree, type) ATOMIC_RMW_NAND(n, lockfree, type)
647+OPTIMISED_CASES
648+#undef OPTIMISED_CASE
649+#define OPTIMISED_CASE(n, lockfree, type) ATOMIC_TAS(n, lockfree, type)
650+OPTIMISED_CASES
651+#undef OPTIMISED_CASE
652+
653+/* atomic_flag */
654+
655+typedef struct atomic_flag { bool v; } atomic_flag;
656+
657+void atomic_flag_clear(volatile atomic_flag *o) {
658+ __atomic_clear(&o->v, __ATOMIC_SEQ_CST);
659+}
660+
661+void atomic_flag_clear_explicit(volatile atomic_flag *o, int model) {
662+ __atomic_clear(&o->v, model);
663+}
664+
665+bool atomic_flag_test_and_set(volatile atomic_flag *o) {
666+ return __atomic_test_and_set(&o->v, __ATOMIC_SEQ_CST);
667+}
668+
669+bool atomic_flag_test_and_set_explicit(volatile atomic_flag *o, int model) {
670+ return __atomic_test_and_set(&o->v, model);
671+}
672+
673+/* fence */
674+
675+void atomic_thread_fence(int model) {
676+ __atomic_thread_fence(model);
677+}
678+
679+void atomic_signal_fence(int model) {
680+ __atomic_signal_fence(model);
681+}
682+
683+/* provided by gcc libatomic */
684+
685+void __atomic_feraiseexcept(int e) {
686+ volatile float r __attribute__((unused));
687+#ifdef FE_INVALID
688+ if (e & FE_INVALID) {
689+ volatile float z = 0.0f;
690+ r = z / z;
691+ }
692+#endif
693+#ifdef FE_DIVBYZERO
694+ if (e & FE_DIVBYZERO) {
695+ volatile float z = 0.0f;
696+ r = 1.0f / z;
697+ }
698+#endif
699+#ifdef FE_OVERFLOW
700+ if (e & FE_OVERFLOW) {
701+ volatile float m = __FLT_MAX__;
702+ r = m * m;
703+ }
704+#endif
705+#ifdef FE_UNDERFLOW
706+ if (e & FE_UNDERFLOW) {
707+ volatile float m = __FLT_MIN__;
708+ r = m * m;
709+ }
710+#endif
711+#ifdef FE_INEXACT
712+ if (e & FE_INEXACT) {
713+ volatile float t = 3.0f;
714+ r = 1.0f / t;
715+ }
716+#endif
717+}