1/*
2 * Copyright © 2017 Gražvydas Ignotas
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24/* #if defined(MISSING_64BIT_ATOMICS) && defined(HAVE_PTHREAD) */
25#include <sys/types.h>
26#ifndef __HAVE_ATOMIC64_OPS
27
28#include <stdint.h>
29#include <pthread.h>
30
31#if defined(HAVE_FUNC_ATTRIBUTE_WEAK) && !defined(__CYGWIN__)
32#define WEAK __attribute__((weak))
33#else
34#define WEAK
35#endif
36
37static pthread_mutex_t sync_mutex = PTHREAD_MUTEX_INITIALIZER;
38
39WEAK long long
40__atomic_fetch_add_8(volatile long long *ptr, long long val, int memorder)
41{
42   long long r;
43
44   pthread_mutex_lock(&sync_mutex);
45   *ptr += val;
46   r = *ptr;
47   pthread_mutex_unlock(&sync_mutex);
48
49   return r;
50}
51
52WEAK long long
53__atomic_fetch_sub_8(volatile long long *ptr, long long val, int memorder)
54{
55   long long r;
56
57   pthread_mutex_lock(&sync_mutex);
58   *ptr -= val;
59   r = *ptr;
60   pthread_mutex_unlock(&sync_mutex);
61
62   return r;
63}
64
65#ifndef __clang__
66WEAK long long
67__sync_val_compare_and_swap_8(volatile long long *ptr, long long oldval, long long newval)
68{
69   long long r;
70
71   pthread_mutex_lock(&sync_mutex);
72   r = *ptr;
73   if (*ptr == oldval)
74      *ptr = newval;
75   pthread_mutex_unlock(&sync_mutex);
76
77   return r;
78}
79#endif
80
81#endif
82