This source file includes following definitions.
- ALLOC_SIZE
- ALLOC_SIZE
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 #if !defined(_DPS8_MEMALIGN_H)
17 # define _DPS8_MEMALIGN_H
18
19 # include <stdlib.h>
20 # include <stdatomic.h>
21 # include "dps8_sir.h"
22
23 # undef ALLOC_SIZE
24 # if HAS_ATTRIBUTE(alloc_size)
25 # define ALLOC_SIZE(size) __attribute__((alloc_size(size)))
26 # endif
27 # if !defined(ALLOC_SIZE)
28 # define ALLOC_SIZE(size)
29 # endif
30
31 # undef ATTR_MALLOC
32 # if HAS_ATTRIBUTE(malloc)
33 # define ATTR_MALLOC __attribute__((malloc))
34 # endif
35 # if !defined(ATTR_MALLOC)
36 # define ATTR_MALLOC
37 # endif
38
39 # if (!defined(_WIN32) && !defined(__CYGWIN__)) && !defined(__MINGW64__) && !defined(__MINGW32__) && \
40 !defined(CROSS_MINGW64) && !defined(CROSS_MINGW32) && !defined(DUMA)
41 # include <unistd.h>
42
43 # if defined(_SC_PAGESIZE)
44 # define DPS8_MEMALIGN_PAGESIZE _SC_PAGESIZE
45 # elif defined(_SC_PAGE_SIZE)
46 # define DPS8_MEMALIGN_PAGESIZE _SC_PAGE_SIZE
47 # else
48 # error No _SC_PAGESIZE or _SC_PAGE_SIZE defined
49 # endif
50
51 ATTR_MALLOC ALLOC_SIZE(1)
52 static inline void *
53 aligned_malloc(size_t size)
54 {
55 static atomic_size_t page_size = 0;
56 size_t current_page_size = atomic_load(&page_size);
57
58 if (current_page_size == 0) {
59 long sys_page_size = sysconf(DPS8_MEMALIGN_PAGESIZE);
60 size_t temp_ps;
61 size_t expected = 0;
62
63 if (sys_page_size < 1) {
64 temp_ps = 4096UL;
65 } else {
66 temp_ps = (size_t)sys_page_size;
67 }
68
69 if (atomic_compare_exchange_strong(&page_size, &expected, temp_ps)) {
70 current_page_size = temp_ps;
71 } else {
72 current_page_size = atomic_load(&page_size);
73 }
74 }
75
76 void *ptr = NULL;
77 if (posix_memalign(&ptr, current_page_size, size) != 0)
78 return NULL;
79
80 return ptr;
81 }
82
83 # else
84
85 ATTR_MALLOC ALLOC_SIZE(1)
86 static inline void *
87 aligned_malloc(size_t size)
88 {
89 return malloc(size);
90 }
91
92 # endif
93 #endif