aral.c 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  1. #include "../libnetdata.h"
  2. #include "aral.h"
  3. #ifdef NETDATA_TRACE_ALLOCATIONS
  4. #define TRACE_ALLOCATIONS_FUNCTION_DEFINITION_PARAMS , const char *file, const char *function, size_t line
  5. #define TRACE_ALLOCATIONS_FUNCTION_CALL_PARAMS , file, function, line
  6. #else
  7. #define TRACE_ALLOCATIONS_FUNCTION_DEFINITION_PARAMS
  8. #define TRACE_ALLOCATIONS_FUNCTION_CALL_PARAMS
  9. #endif
  10. #define ARAL_FREE_PAGES_DELTA_TO_REARRANGE_LIST 5
  11. // max file size
  12. #define ARAL_MAX_PAGE_SIZE_MMAP (1*1024*1024*1024)
  13. // max malloc size
  14. // optimal at current versions of libc is up to 256k
  15. // ideal to have the same overhead as libc is 4k
  16. #define ARAL_MAX_PAGE_SIZE_MALLOC (65*1024)
  17. typedef struct aral_free {
  18. size_t size;
  19. struct aral_free *next;
  20. } ARAL_FREE;
  21. typedef struct aral_page {
  22. size_t size; // the allocation size of the page
  23. const char *filename;
  24. uint8_t *data;
  25. uint32_t free_elements_to_move_first;
  26. uint32_t max_elements; // the number of elements that can fit on this page
  27. struct {
  28. uint32_t used_elements; // the number of used elements on this page
  29. uint32_t free_elements; // the number of free elements on this page
  30. struct aral_page *prev; // the prev page on the list
  31. struct aral_page *next; // the next page on the list
  32. } aral_lock;
  33. struct {
  34. SPINLOCK spinlock;
  35. ARAL_FREE *list;
  36. } free;
  37. } ARAL_PAGE;
  38. typedef enum {
  39. ARAL_LOCKLESS = (1 << 0),
  40. ARAL_DEFRAGMENT = (1 << 1),
  41. ARAL_ALLOCATED_STATS = (1 << 2),
  42. } ARAL_OPTIONS;
  43. struct aral {
  44. struct {
  45. char name[ARAL_MAX_NAME + 1];
  46. ARAL_OPTIONS options;
  47. size_t element_size; // calculated to take into account ARAL overheads
  48. size_t max_allocation_size; // calculated in bytes
  49. size_t max_page_elements; // calculated
  50. size_t page_ptr_offset; // calculated
  51. size_t natural_page_size; // calculated
  52. size_t initial_page_elements;
  53. size_t requested_element_size;
  54. size_t requested_max_page_size;
  55. struct {
  56. bool enabled;
  57. const char *filename;
  58. char **cache_dir;
  59. } mmap;
  60. } config;
  61. struct {
  62. SPINLOCK spinlock;
  63. size_t file_number; // for mmap
  64. struct aral_page *pages; // linked list of pages
  65. size_t user_malloc_operations;
  66. size_t user_free_operations;
  67. size_t defragment_operations;
  68. size_t defragment_linked_list_traversals;
  69. } aral_lock;
  70. struct {
  71. SPINLOCK spinlock;
  72. size_t allocating_elements; // currently allocating elements
  73. size_t allocation_size; // current / next allocation size
  74. } adders;
  75. struct {
  76. size_t allocators; // the number of threads currently trying to allocate memory
  77. } atomic;
  78. struct aral_statistics *stats;
  79. };
  80. size_t aral_structures_from_stats(struct aral_statistics *stats) {
  81. return __atomic_load_n(&stats->structures.allocated_bytes, __ATOMIC_RELAXED);
  82. }
  83. size_t aral_overhead_from_stats(struct aral_statistics *stats) {
  84. return __atomic_load_n(&stats->malloc.allocated_bytes, __ATOMIC_RELAXED) -
  85. __atomic_load_n(&stats->malloc.used_bytes, __ATOMIC_RELAXED);
  86. }
  87. size_t aral_overhead(ARAL *ar) {
  88. return aral_overhead_from_stats(ar->stats);
  89. }
  90. size_t aral_structures(ARAL *ar) {
  91. return aral_structures_from_stats(ar->stats);
  92. }
  93. struct aral_statistics *aral_statistics(ARAL *ar) {
  94. return ar->stats;
  95. }
  96. #define ARAL_NATURAL_ALIGNMENT (sizeof(uintptr_t) * 2)
  97. static inline size_t natural_alignment(size_t size, size_t alignment) {
  98. if(unlikely(size % alignment))
  99. size = size + alignment - (size % alignment);
  100. return size;
  101. }
  102. static size_t aral_align_alloc_size(ARAL *ar, uint64_t size) {
  103. if(size % ar->config.natural_page_size)
  104. size += ar->config.natural_page_size - (size % ar->config.natural_page_size) ;
  105. if(size % ar->config.element_size)
  106. size -= size % ar->config.element_size;
  107. return size;
  108. }
  109. static inline void aral_lock(ARAL *ar) {
  110. if(likely(!(ar->config.options & ARAL_LOCKLESS)))
  111. netdata_spinlock_lock(&ar->aral_lock.spinlock);
  112. }
  113. static inline void aral_unlock(ARAL *ar) {
  114. if(likely(!(ar->config.options & ARAL_LOCKLESS)))
  115. netdata_spinlock_unlock(&ar->aral_lock.spinlock);
  116. }
  117. static inline void aral_page_free_lock(ARAL *ar, ARAL_PAGE *page) {
  118. if(likely(!(ar->config.options & ARAL_LOCKLESS)))
  119. netdata_spinlock_lock(&page->free.spinlock);
  120. }
  121. static inline void aral_page_free_unlock(ARAL *ar, ARAL_PAGE *page) {
  122. if(likely(!(ar->config.options & ARAL_LOCKLESS)))
  123. netdata_spinlock_unlock(&page->free.spinlock);
  124. }
  125. static inline bool aral_adders_trylock(ARAL *ar) {
  126. if(likely(!(ar->config.options & ARAL_LOCKLESS)))
  127. return netdata_spinlock_trylock(&ar->adders.spinlock);
  128. return true;
  129. }
  130. static inline void aral_adders_lock(ARAL *ar) {
  131. if(likely(!(ar->config.options & ARAL_LOCKLESS)))
  132. netdata_spinlock_lock(&ar->adders.spinlock);
  133. }
  134. static inline void aral_adders_unlock(ARAL *ar) {
  135. if(likely(!(ar->config.options & ARAL_LOCKLESS)))
  136. netdata_spinlock_unlock(&ar->adders.spinlock);
  137. }
  138. static void aral_delete_leftover_files(const char *name, const char *path, const char *required_prefix) {
  139. DIR *dir = opendir(path);
  140. if(!dir) return;
  141. char full_path[FILENAME_MAX + 1];
  142. size_t len = strlen(required_prefix);
  143. struct dirent *de = NULL;
  144. while((de = readdir(dir))) {
  145. if(de->d_type == DT_DIR)
  146. continue;
  147. if(strncmp(de->d_name, required_prefix, len) != 0)
  148. continue;
  149. snprintfz(full_path, FILENAME_MAX, "%s/%s", path, de->d_name);
  150. info("ARAL: '%s' removing left-over file '%s'", name, full_path);
  151. if(unlikely(unlink(full_path) == -1))
  152. error("ARAL: '%s' cannot delete file '%s'", name, full_path);
  153. }
  154. closedir(dir);
  155. }
  156. // ----------------------------------------------------------------------------
  157. // check a free slot
  158. #ifdef NETDATA_INTERNAL_CHECKS
  159. static inline void aral_free_validate_internal_check(ARAL *ar, ARAL_FREE *fr) {
  160. if(unlikely(fr->size < ar->config.element_size))
  161. fatal("ARAL: '%s' free item of size %zu, less than the expected element size %zu",
  162. ar->config.name, fr->size, ar->config.element_size);
  163. if(unlikely(fr->size % ar->config.element_size))
  164. fatal("ARAL: '%s' free item of size %zu is not multiple to element size %zu",
  165. ar->config.name, fr->size, ar->config.element_size);
  166. }
  167. #else
  168. #define aral_free_validate_internal_check(ar, fr) debug_dummy()
  169. #endif
  170. // ----------------------------------------------------------------------------
  171. // find the page a pointer belongs to
  172. #ifdef NETDATA_INTERNAL_CHECKS
  173. static inline ARAL_PAGE *find_page_with_allocation_internal_check(ARAL *ar, void *ptr) {
  174. aral_lock(ar);
  175. uintptr_t seeking = (uintptr_t)ptr;
  176. ARAL_PAGE *page;
  177. for(page = ar->aral_lock.pages; page ; page = page->aral_lock.next) {
  178. if(unlikely(seeking >= (uintptr_t)page->data && seeking < (uintptr_t)page->data + page->size))
  179. break;
  180. }
  181. aral_unlock(ar);
  182. return page;
  183. }
  184. #endif
  185. // ----------------------------------------------------------------------------
  186. // find a page with a free slot (there shouldn't be any)
  187. #ifdef NETDATA_ARAL_INTERNAL_CHECKS
  188. static inline ARAL_PAGE *find_page_with_free_slots_internal_check___with_aral_lock(ARAL *ar) {
  189. ARAL_PAGE *page;
  190. for(page = ar->aral_lock.pages; page ; page = page->next) {
  191. if(page->aral_lock.free_elements)
  192. break;
  193. internal_fatal(page->size - page->aral_lock.used_elements * ar->config.element_size >= ar->config.element_size,
  194. "ARAL: '%s' a page is marked full, but it is not!", ar->config.name);
  195. internal_fatal(page->size < page->aral_lock.used_elements * ar->config.element_size,
  196. "ARAL: '%s' a page has been overflown!", ar->config.name);
  197. }
  198. return page;
  199. }
  200. #endif
  201. size_t aral_next_allocation_size___adders_lock_needed(ARAL *ar) {
  202. size_t size = ar->adders.allocation_size;
  203. if(size > ar->config.max_allocation_size)
  204. size = ar->config.max_allocation_size;
  205. else
  206. ar->adders.allocation_size = aral_align_alloc_size(ar, (uint64_t)ar->adders.allocation_size * 2);
  207. return size;
  208. }
  209. static ARAL_PAGE *aral_create_page___no_lock_needed(ARAL *ar, size_t size TRACE_ALLOCATIONS_FUNCTION_DEFINITION_PARAMS) {
  210. ARAL_PAGE *page = callocz(1, sizeof(ARAL_PAGE));
  211. netdata_spinlock_init(&page->free.spinlock);
  212. page->size = size;
  213. page->max_elements = page->size / ar->config.element_size;
  214. page->aral_lock.free_elements = page->max_elements;
  215. page->free_elements_to_move_first = page->max_elements / 4;
  216. if(unlikely(page->free_elements_to_move_first < 1))
  217. page->free_elements_to_move_first = 1;
  218. __atomic_add_fetch(&ar->stats->structures.allocations, 1, __ATOMIC_RELAXED);
  219. __atomic_add_fetch(&ar->stats->structures.allocated_bytes, sizeof(ARAL_PAGE), __ATOMIC_RELAXED);
  220. if(unlikely(ar->config.mmap.enabled)) {
  221. ar->aral_lock.file_number++;
  222. char filename[FILENAME_MAX + 1];
  223. snprintfz(filename, FILENAME_MAX, "%s/array_alloc.mmap/%s.%zu", *ar->config.mmap.cache_dir, ar->config.mmap.filename, ar->aral_lock.file_number);
  224. page->filename = strdupz(filename);
  225. page->data = netdata_mmap(page->filename, page->size, MAP_SHARED, 0, false, NULL);
  226. if (unlikely(!page->data))
  227. fatal("ARAL: '%s' cannot allocate aral buffer of size %zu on filename '%s'",
  228. ar->config.name, page->size, page->filename);
  229. __atomic_add_fetch(&ar->stats->mmap.allocations, 1, __ATOMIC_RELAXED);
  230. __atomic_add_fetch(&ar->stats->mmap.allocated_bytes, page->size, __ATOMIC_RELAXED);
  231. }
  232. else {
  233. #ifdef NETDATA_TRACE_ALLOCATIONS
  234. page->data = mallocz_int(page->size TRACE_ALLOCATIONS_FUNCTION_CALL_PARAMS);
  235. #else
  236. page->data = mallocz(page->size);
  237. #endif
  238. __atomic_add_fetch(&ar->stats->malloc.allocations, 1, __ATOMIC_RELAXED);
  239. __atomic_add_fetch(&ar->stats->malloc.allocated_bytes, page->size, __ATOMIC_RELAXED);
  240. }
  241. // link the free space to its page
  242. ARAL_FREE *fr = (ARAL_FREE *)page->data;
  243. fr->size = page->size;
  244. fr->next = NULL;
  245. page->free.list = fr;
  246. aral_free_validate_internal_check(ar, fr);
  247. return page;
  248. }
  249. void aral_del_page___no_lock_needed(ARAL *ar, ARAL_PAGE *page TRACE_ALLOCATIONS_FUNCTION_DEFINITION_PARAMS) {
  250. // free it
  251. if (ar->config.mmap.enabled) {
  252. netdata_munmap(page->data, page->size);
  253. if (unlikely(unlink(page->filename) == 1))
  254. error("Cannot delete file '%s'", page->filename);
  255. freez((void *)page->filename);
  256. __atomic_sub_fetch(&ar->stats->mmap.allocations, 1, __ATOMIC_RELAXED);
  257. __atomic_sub_fetch(&ar->stats->mmap.allocated_bytes, page->size, __ATOMIC_RELAXED);
  258. }
  259. else {
  260. #ifdef NETDATA_TRACE_ALLOCATIONS
  261. freez_int(page->data TRACE_ALLOCATIONS_FUNCTION_CALL_PARAMS);
  262. #else
  263. freez(page->data);
  264. #endif
  265. __atomic_sub_fetch(&ar->stats->malloc.allocations, 1, __ATOMIC_RELAXED);
  266. __atomic_sub_fetch(&ar->stats->malloc.allocated_bytes, page->size, __ATOMIC_RELAXED);
  267. }
  268. freez(page);
  269. __atomic_sub_fetch(&ar->stats->structures.allocations, 1, __ATOMIC_RELAXED);
  270. __atomic_sub_fetch(&ar->stats->structures.allocated_bytes, sizeof(ARAL_PAGE), __ATOMIC_RELAXED);
  271. }
  272. static inline void aral_insert_not_linked_page_with_free_items_to_proper_position___aral_lock_needed(ARAL *ar, ARAL_PAGE *page) {
  273. ARAL_PAGE *first = ar->aral_lock.pages;
  274. if (page->aral_lock.free_elements <= page->free_elements_to_move_first ||
  275. !first ||
  276. !first->aral_lock.free_elements ||
  277. page->aral_lock.free_elements <= first->aral_lock.free_elements + ARAL_FREE_PAGES_DELTA_TO_REARRANGE_LIST) {
  278. // first position
  279. DOUBLE_LINKED_LIST_PREPEND_ITEM_UNSAFE(ar->aral_lock.pages, page, aral_lock.prev, aral_lock.next);
  280. }
  281. else {
  282. ARAL_PAGE *second = first->aral_lock.next;
  283. if (!second ||
  284. !second->aral_lock.free_elements ||
  285. page->aral_lock.free_elements <= second->aral_lock.free_elements)
  286. // second position
  287. DOUBLE_LINKED_LIST_INSERT_ITEM_AFTER_UNSAFE(ar->aral_lock.pages, first, page, aral_lock.prev, aral_lock.next);
  288. else
  289. // third position
  290. DOUBLE_LINKED_LIST_INSERT_ITEM_AFTER_UNSAFE(ar->aral_lock.pages, second, page, aral_lock.prev, aral_lock.next);
  291. }
  292. }
  293. static inline ARAL_PAGE *aral_acquire_a_free_slot(ARAL *ar TRACE_ALLOCATIONS_FUNCTION_DEFINITION_PARAMS) {
  294. __atomic_add_fetch(&ar->atomic.allocators, 1, __ATOMIC_RELAXED);
  295. aral_lock(ar);
  296. ARAL_PAGE *page = ar->aral_lock.pages;
  297. while(!page || !page->aral_lock.free_elements) {
  298. #ifdef NETDATA_ARAL_INTERNAL_CHECKS
  299. internal_fatal(find_page_with_free_slots_internal_check___with_aral_lock(ar), "ARAL: '%s' found page with free slot!", ar->config.name);
  300. #endif
  301. aral_unlock(ar);
  302. if(aral_adders_trylock(ar)) {
  303. if(ar->adders.allocating_elements < __atomic_load_n(&ar->atomic.allocators, __ATOMIC_RELAXED)) {
  304. size_t size = aral_next_allocation_size___adders_lock_needed(ar);
  305. ar->adders.allocating_elements += size / ar->config.element_size;
  306. aral_adders_unlock(ar);
  307. page = aral_create_page___no_lock_needed(ar, size TRACE_ALLOCATIONS_FUNCTION_CALL_PARAMS);
  308. aral_lock(ar);
  309. aral_insert_not_linked_page_with_free_items_to_proper_position___aral_lock_needed(ar, page);
  310. aral_adders_lock(ar);
  311. ar->adders.allocating_elements -= size / ar->config.element_size;
  312. aral_adders_unlock(ar);
  313. // we have a page that is all empty
  314. // and only aral_lock() is held, so
  315. // break the loop
  316. break;
  317. }
  318. aral_adders_unlock(ar);
  319. }
  320. aral_lock(ar);
  321. page = ar->aral_lock.pages;
  322. }
  323. __atomic_sub_fetch(&ar->atomic.allocators, 1, __ATOMIC_RELAXED);
  324. // we have a page
  325. // and aral locked
  326. {
  327. ARAL_PAGE *first = ar->aral_lock.pages;
  328. ARAL_PAGE *second = first->aral_lock.next;
  329. if (!second ||
  330. !second->aral_lock.free_elements ||
  331. first->aral_lock.free_elements <= second->aral_lock.free_elements + ARAL_FREE_PAGES_DELTA_TO_REARRANGE_LIST)
  332. page = first;
  333. else {
  334. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(ar->aral_lock.pages, second, aral_lock.prev, aral_lock.next);
  335. DOUBLE_LINKED_LIST_PREPEND_ITEM_UNSAFE(ar->aral_lock.pages, second, aral_lock.prev, aral_lock.next);
  336. page = second;
  337. }
  338. }
  339. internal_fatal(!page || !page->aral_lock.free_elements,
  340. "ARAL: '%s' selected page does not have a free slot in it",
  341. ar->config.name);
  342. internal_fatal(page->max_elements != page->aral_lock.used_elements + page->aral_lock.free_elements,
  343. "ARAL: '%s' page element counters do not match, "
  344. "page says it can handle %zu elements, "
  345. "but there are %zu used and %zu free items, "
  346. "total %zu items",
  347. ar->config.name,
  348. (size_t)page->max_elements,
  349. (size_t)page->aral_lock.used_elements, (size_t)page->aral_lock.free_elements,
  350. (size_t)page->aral_lock.used_elements + (size_t)page->aral_lock.free_elements
  351. );
  352. ar->aral_lock.user_malloc_operations++;
  353. // acquire a slot for the caller
  354. page->aral_lock.used_elements++;
  355. if(--page->aral_lock.free_elements == 0) {
  356. // we are done with this page
  357. // move the full page last
  358. // so that pages with free items remain first in the list
  359. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(ar->aral_lock.pages, page, aral_lock.prev, aral_lock.next);
  360. DOUBLE_LINKED_LIST_APPEND_ITEM_UNSAFE(ar->aral_lock.pages, page, aral_lock.prev, aral_lock.next);
  361. }
  362. aral_unlock(ar);
  363. return page;
  364. }
  365. void *aral_mallocz_internal(ARAL *ar TRACE_ALLOCATIONS_FUNCTION_DEFINITION_PARAMS) {
  366. ARAL_PAGE *page = aral_acquire_a_free_slot(ar TRACE_ALLOCATIONS_FUNCTION_CALL_PARAMS);
  367. aral_page_free_lock(ar, page);
  368. internal_fatal(!page->free.list,
  369. "ARAL: '%s' free item to use, cannot be NULL.", ar->config.name);
  370. internal_fatal(page->free.list->size < ar->config.element_size,
  371. "ARAL: '%s' free item size %zu, cannot be smaller than %zu",
  372. ar->config.name, page->free.list->size, ar->config.element_size);
  373. ARAL_FREE *found_fr = page->free.list;
  374. // check if the remaining size (after we use this slot) is not enough for another element
  375. if(unlikely(found_fr->size - ar->config.element_size < ar->config.element_size)) {
  376. // we can use the entire free space entry
  377. page->free.list = found_fr->next;
  378. }
  379. else {
  380. // we can split the free space entry
  381. uint8_t *data = (uint8_t *)found_fr;
  382. ARAL_FREE *fr = (ARAL_FREE *)&data[ar->config.element_size];
  383. fr->size = found_fr->size - ar->config.element_size;
  384. // link the free slot first in the page
  385. fr->next = found_fr->next;
  386. page->free.list = fr;
  387. aral_free_validate_internal_check(ar, fr);
  388. }
  389. aral_page_free_unlock(ar, page);
  390. // put the page pointer after the element
  391. uint8_t *data = (uint8_t *)found_fr;
  392. ARAL_PAGE **page_ptr = (ARAL_PAGE **)&data[ar->config.page_ptr_offset];
  393. *page_ptr = page;
  394. if(unlikely(ar->config.mmap.enabled))
  395. __atomic_add_fetch(&ar->stats->mmap.used_bytes, ar->config.element_size, __ATOMIC_RELAXED);
  396. else
  397. __atomic_add_fetch(&ar->stats->malloc.used_bytes, ar->config.element_size, __ATOMIC_RELAXED);
  398. return (void *)found_fr;
  399. }
  400. static inline ARAL_PAGE *aral_ptr_to_page___must_NOT_have_aral_lock(ARAL *ar, void *ptr) {
  401. // given a data pointer we returned before,
  402. // find the ARAL_PAGE it belongs to
  403. uint8_t *data = (uint8_t *)ptr;
  404. ARAL_PAGE **page_ptr = (ARAL_PAGE **)&data[ar->config.page_ptr_offset];
  405. ARAL_PAGE *page = *page_ptr;
  406. #ifdef NETDATA_INTERNAL_CHECKS
  407. // make it NULL so that we will fail on double free
  408. // do not enable this on production, because the MMAP file
  409. // will need to be saved again!
  410. *page_ptr = NULL;
  411. #endif
  412. #ifdef NETDATA_ARAL_INTERNAL_CHECKS
  413. {
  414. // find the page ptr belongs
  415. ARAL_PAGE *page2 = find_page_with_allocation_internal_check(ar, ptr);
  416. internal_fatal(page != page2,
  417. "ARAL: '%s' page pointers do not match!",
  418. ar->name);
  419. internal_fatal(!page2,
  420. "ARAL: '%s' free of pointer %p is not in ARAL address space.",
  421. ar->name, ptr);
  422. }
  423. #endif
  424. internal_fatal(!page,
  425. "ARAL: '%s' possible corruption or double free of pointer %p",
  426. ar->config.name, ptr);
  427. return page;
  428. }
  429. static void aral_defrag_sorted_page_position___aral_lock_needed(ARAL *ar, ARAL_PAGE *page) {
  430. ARAL_PAGE *tmp;
  431. int action = 0; (void)action;
  432. size_t move_later = 0, move_earlier = 0;
  433. for(tmp = page->aral_lock.next ;
  434. tmp && tmp->aral_lock.free_elements && tmp->aral_lock.free_elements < page->aral_lock.free_elements ;
  435. tmp = tmp->aral_lock.next)
  436. move_later++;
  437. if(!tmp && page->aral_lock.next) {
  438. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(ar->aral_lock.pages, page, aral_lock.prev, aral_lock.next);
  439. DOUBLE_LINKED_LIST_APPEND_ITEM_UNSAFE(ar->aral_lock.pages, page, aral_lock.prev, aral_lock.next);
  440. action = 1;
  441. }
  442. else if(tmp != page->aral_lock.next) {
  443. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(ar->aral_lock.pages, page, aral_lock.prev, aral_lock.next);
  444. DOUBLE_LINKED_LIST_INSERT_ITEM_BEFORE_UNSAFE(ar->aral_lock.pages, tmp, page, aral_lock.prev, aral_lock.next);
  445. action = 2;
  446. }
  447. else {
  448. for(tmp = (page == ar->aral_lock.pages) ? NULL : page->aral_lock.prev ;
  449. tmp && (!tmp->aral_lock.free_elements || tmp->aral_lock.free_elements > page->aral_lock.free_elements);
  450. tmp = (tmp == ar->aral_lock.pages) ? NULL : tmp->aral_lock.prev)
  451. move_earlier++;
  452. if(!tmp) {
  453. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(ar->aral_lock.pages, page, aral_lock.prev, aral_lock.next);
  454. DOUBLE_LINKED_LIST_PREPEND_ITEM_UNSAFE(ar->aral_lock.pages, page, aral_lock.prev, aral_lock.next);
  455. action = 3;
  456. }
  457. else if(tmp != page->aral_lock.prev){
  458. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(ar->aral_lock.pages, page, aral_lock.prev, aral_lock.next);
  459. DOUBLE_LINKED_LIST_INSERT_ITEM_AFTER_UNSAFE(ar->aral_lock.pages, tmp, page, aral_lock.prev, aral_lock.next);
  460. action = 4;
  461. }
  462. }
  463. ar->aral_lock.defragment_operations++;
  464. ar->aral_lock.defragment_linked_list_traversals += move_earlier + move_later;
  465. internal_fatal(page->aral_lock.next && page->aral_lock.next->aral_lock.free_elements && page->aral_lock.next->aral_lock.free_elements < page->aral_lock.free_elements,
  466. "ARAL: '%s' item should be later in the list", ar->config.name);
  467. internal_fatal(page != ar->aral_lock.pages && (!page->aral_lock.prev->aral_lock.free_elements || page->aral_lock.prev->aral_lock.free_elements > page->aral_lock.free_elements),
  468. "ARAL: '%s' item should be earlier in the list", ar->config.name);
  469. }
  470. static inline void aral_move_page_with_free_list___aral_lock_needed(ARAL *ar, ARAL_PAGE *page) {
  471. if(unlikely(page == ar->aral_lock.pages))
  472. // we are the first already
  473. return;
  474. if(likely(!(ar->config.options & ARAL_DEFRAGMENT))) {
  475. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(ar->aral_lock.pages, page, aral_lock.prev, aral_lock.next);
  476. aral_insert_not_linked_page_with_free_items_to_proper_position___aral_lock_needed(ar, page);
  477. }
  478. else
  479. aral_defrag_sorted_page_position___aral_lock_needed(ar, page);
  480. }
  481. void aral_freez_internal(ARAL *ar, void *ptr TRACE_ALLOCATIONS_FUNCTION_DEFINITION_PARAMS) {
  482. if(unlikely(!ptr)) return;
  483. // get the page pointer
  484. ARAL_PAGE *page = aral_ptr_to_page___must_NOT_have_aral_lock(ar, ptr);
  485. if(unlikely(ar->config.mmap.enabled))
  486. __atomic_sub_fetch(&ar->stats->mmap.used_bytes, ar->config.element_size, __ATOMIC_RELAXED);
  487. else
  488. __atomic_sub_fetch(&ar->stats->malloc.used_bytes, ar->config.element_size, __ATOMIC_RELAXED);
  489. // make this element available
  490. ARAL_FREE *fr = (ARAL_FREE *)ptr;
  491. fr->size = ar->config.element_size;
  492. aral_page_free_lock(ar, page);
  493. fr->next = page->free.list;
  494. page->free.list = fr;
  495. aral_page_free_unlock(ar, page);
  496. aral_lock(ar);
  497. internal_fatal(!page->aral_lock.used_elements,
  498. "ARAL: '%s' pointer %p is inside a page without any active allocations.",
  499. ar->config.name, ptr);
  500. internal_fatal(page->max_elements != page->aral_lock.used_elements + page->aral_lock.free_elements,
  501. "ARAL: '%s' page element counters do not match, "
  502. "page says it can handle %zu elements, "
  503. "but there are %zu used and %zu free items, "
  504. "total %zu items",
  505. ar->config.name,
  506. (size_t)page->max_elements,
  507. (size_t)page->aral_lock.used_elements, (size_t)page->aral_lock.free_elements,
  508. (size_t)page->aral_lock.used_elements + (size_t)page->aral_lock.free_elements
  509. );
  510. page->aral_lock.used_elements--;
  511. page->aral_lock.free_elements++;
  512. ar->aral_lock.user_free_operations++;
  513. // if the page is empty, release it
  514. if(unlikely(!page->aral_lock.used_elements)) {
  515. bool is_this_page_the_last_one = ar->aral_lock.pages == page && !page->aral_lock.next;
  516. if(!is_this_page_the_last_one)
  517. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(ar->aral_lock.pages, page, aral_lock.prev, aral_lock.next);
  518. aral_unlock(ar);
  519. if(!is_this_page_the_last_one)
  520. aral_del_page___no_lock_needed(ar, page TRACE_ALLOCATIONS_FUNCTION_CALL_PARAMS);
  521. }
  522. else {
  523. aral_move_page_with_free_list___aral_lock_needed(ar, page);
  524. aral_unlock(ar);
  525. }
  526. }
  527. void aral_destroy_internal(ARAL *ar TRACE_ALLOCATIONS_FUNCTION_DEFINITION_PARAMS) {
  528. aral_lock(ar);
  529. ARAL_PAGE *page;
  530. while((page = ar->aral_lock.pages)) {
  531. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(ar->aral_lock.pages, page, aral_lock.prev, aral_lock.next);
  532. aral_del_page___no_lock_needed(ar, page TRACE_ALLOCATIONS_FUNCTION_CALL_PARAMS);
  533. }
  534. aral_unlock(ar);
  535. if(ar->config.options & ARAL_ALLOCATED_STATS)
  536. freez(ar->stats);
  537. freez(ar);
  538. }
  539. size_t aral_element_size(ARAL *ar) {
  540. return ar->config.requested_element_size;
  541. }
  542. ARAL *aral_create(const char *name, size_t element_size, size_t initial_page_elements, size_t max_page_size,
  543. struct aral_statistics *stats, const char *filename, char **cache_dir, bool mmap, bool lockless) {
  544. ARAL *ar = callocz(1, sizeof(ARAL));
  545. ar->config.options = (lockless) ? ARAL_LOCKLESS : 0;
  546. ar->config.requested_element_size = element_size;
  547. ar->config.initial_page_elements = initial_page_elements;
  548. ar->config.requested_max_page_size = max_page_size;
  549. ar->config.mmap.filename = filename;
  550. ar->config.mmap.cache_dir = cache_dir;
  551. ar->config.mmap.enabled = mmap;
  552. strncpyz(ar->config.name, name, ARAL_MAX_NAME);
  553. netdata_spinlock_init(&ar->aral_lock.spinlock);
  554. if(stats) {
  555. ar->stats = stats;
  556. ar->config.options &= ~ARAL_ALLOCATED_STATS;
  557. }
  558. else {
  559. ar->stats = callocz(1, sizeof(struct aral_statistics));
  560. ar->config.options |= ARAL_ALLOCATED_STATS;
  561. }
  562. long int page_size = sysconf(_SC_PAGE_SIZE);
  563. if (unlikely(page_size == -1))
  564. ar->config.natural_page_size = 4096;
  565. else
  566. ar->config.natural_page_size = page_size;
  567. // we need to add a page pointer after the element
  568. // so, first align the element size to the pointer size
  569. ar->config.element_size = natural_alignment(ar->config.requested_element_size, sizeof(uintptr_t));
  570. // then add the size of a pointer to it
  571. ar->config.element_size += sizeof(uintptr_t);
  572. // make sure it is at least what we need for an ARAL_FREE slot
  573. if (ar->config.element_size < sizeof(ARAL_FREE))
  574. ar->config.element_size = sizeof(ARAL_FREE);
  575. // and finally align it to the natural alignment
  576. ar->config.element_size = natural_alignment(ar->config.element_size, ARAL_NATURAL_ALIGNMENT);
  577. ar->config.max_page_elements = ar->config.requested_max_page_size / ar->config.element_size;
  578. // we write the page pointer just after each element
  579. ar->config.page_ptr_offset = ar->config.element_size - sizeof(uintptr_t);
  580. if(ar->config.requested_element_size + sizeof(uintptr_t) > ar->config.element_size)
  581. fatal("ARAL: '%s' failed to calculate properly page_ptr_offset: "
  582. "element size %zu, sizeof(uintptr_t) %zu, natural alignment %zu, "
  583. "final element size %zu, page_ptr_offset %zu",
  584. ar->config.name, ar->config.requested_element_size, sizeof(uintptr_t), ARAL_NATURAL_ALIGNMENT,
  585. ar->config.element_size, ar->config.page_ptr_offset);
  586. //info("ARAL: element size %zu, sizeof(uintptr_t) %zu, natural alignment %zu, final element size %zu, page_ptr_offset %zu",
  587. // ar->element_size, sizeof(uintptr_t), ARAL_NATURAL_ALIGNMENT, ar->internal.element_size, ar->internal.page_ptr_offset);
  588. if (ar->config.initial_page_elements < 2)
  589. ar->config.initial_page_elements = 2;
  590. if(ar->config.mmap.enabled && (!ar->config.mmap.cache_dir || !*ar->config.mmap.cache_dir)) {
  591. error("ARAL: '%s' mmap cache directory is not configured properly, disabling mmap.", ar->config.name);
  592. ar->config.mmap.enabled = false;
  593. internal_fatal(true, "ARAL: '%s' mmap cache directory is not configured properly", ar->config.name);
  594. }
  595. uint64_t max_alloc_size;
  596. if(!ar->config.max_page_elements)
  597. max_alloc_size = ar->config.mmap.enabled ? ARAL_MAX_PAGE_SIZE_MMAP : ARAL_MAX_PAGE_SIZE_MALLOC;
  598. else
  599. max_alloc_size = ar->config.max_page_elements * ar->config.element_size;
  600. ar->config.max_allocation_size = aral_align_alloc_size(ar, max_alloc_size);
  601. ar->adders.allocation_size = aral_align_alloc_size(ar, (uint64_t)ar->config.element_size * ar->config.initial_page_elements);
  602. ar->aral_lock.pages = NULL;
  603. ar->aral_lock.file_number = 0;
  604. if(ar->config.mmap.enabled) {
  605. char directory_name[FILENAME_MAX + 1];
  606. snprintfz(directory_name, FILENAME_MAX, "%s/array_alloc.mmap", *ar->config.mmap.cache_dir);
  607. int r = mkdir(directory_name, 0775);
  608. if (r != 0 && errno != EEXIST)
  609. fatal("Cannot create directory '%s'", directory_name);
  610. char file[FILENAME_MAX + 1];
  611. snprintfz(file, FILENAME_MAX, "%s.", ar->config.mmap.filename);
  612. aral_delete_leftover_files(ar->config.name, directory_name, file);
  613. }
  614. internal_error(true,
  615. "ARAL: '%s' "
  616. "element size %zu (requested %zu bytes), "
  617. "min elements per page %zu (requested %zu), "
  618. "max elements per page %zu, "
  619. "max page size %zu bytes (requested %zu) "
  620. , ar->config.name
  621. , ar->config.element_size, ar->config.requested_element_size
  622. , ar->adders.allocation_size / ar->config.element_size, ar->config.initial_page_elements
  623. , ar->config.max_allocation_size / ar->config.element_size
  624. , ar->config.max_allocation_size, ar->config.requested_max_page_size
  625. );
  626. __atomic_add_fetch(&ar->stats->structures.allocations, 1, __ATOMIC_RELAXED);
  627. __atomic_add_fetch(&ar->stats->structures.allocated_bytes, sizeof(ARAL), __ATOMIC_RELAXED);
  628. return ar;
  629. }
  630. // ----------------------------------------------------------------------------
  631. // global aral caching
  632. #define ARAL_BY_SIZE_MAX_SIZE 1024
  633. struct aral_by_size {
  634. ARAL *ar;
  635. int32_t refcount;
  636. };
  637. struct {
  638. struct aral_statistics shared_statistics;
  639. SPINLOCK spinlock;
  640. struct aral_by_size array[ARAL_BY_SIZE_MAX_SIZE + 1];
  641. } aral_by_size_globals = {};
  642. struct aral_statistics *aral_by_size_statistics(void) {
  643. return &aral_by_size_globals.shared_statistics;
  644. }
  645. size_t aral_by_size_structures(void) {
  646. return aral_structures_from_stats(&aral_by_size_globals.shared_statistics);
  647. }
  648. size_t aral_by_size_overhead(void) {
  649. return aral_overhead_from_stats(&aral_by_size_globals.shared_statistics);
  650. }
  651. ARAL *aral_by_size_acquire(size_t size) {
  652. netdata_spinlock_lock(&aral_by_size_globals.spinlock);
  653. ARAL *ar = NULL;
  654. if(size <= ARAL_BY_SIZE_MAX_SIZE && aral_by_size_globals.array[size].ar) {
  655. ar = aral_by_size_globals.array[size].ar;
  656. aral_by_size_globals.array[size].refcount++;
  657. internal_fatal(aral_element_size(ar) != size, "DICTIONARY: aral has size %zu but we want %zu",
  658. aral_element_size(ar), size);
  659. }
  660. if(!ar) {
  661. char buf[30 + 1];
  662. snprintf(buf, 30, "size-%zu", size);
  663. ar = aral_create(buf,
  664. size,
  665. 0,
  666. 65536 * ((size / 150) + 1),
  667. &aral_by_size_globals.shared_statistics,
  668. NULL, NULL, false, false);
  669. if(size <= ARAL_BY_SIZE_MAX_SIZE) {
  670. aral_by_size_globals.array[size].ar = ar;
  671. aral_by_size_globals.array[size].refcount = 1;
  672. }
  673. }
  674. netdata_spinlock_unlock(&aral_by_size_globals.spinlock);
  675. return ar;
  676. }
  677. void aral_by_size_release(ARAL *ar) {
  678. size_t size = aral_element_size(ar);
  679. if(size <= ARAL_BY_SIZE_MAX_SIZE) {
  680. netdata_spinlock_lock(&aral_by_size_globals.spinlock);
  681. internal_fatal(aral_by_size_globals.array[size].ar != ar,
  682. "ARAL BY SIZE: aral pointers do not match");
  683. if(aral_by_size_globals.array[size].refcount <= 0)
  684. fatal("ARAL BY SIZE: double release detected");
  685. aral_by_size_globals.array[size].refcount--;
  686. if(!aral_by_size_globals.array[size].refcount) {
  687. aral_destroy(aral_by_size_globals.array[size].ar);
  688. aral_by_size_globals.array[size].ar = NULL;
  689. }
  690. netdata_spinlock_unlock(&aral_by_size_globals.spinlock);
  691. }
  692. else
  693. aral_destroy(ar);
  694. }
  695. // ----------------------------------------------------------------------------
  696. // unittest
  697. struct aral_unittest_config {
  698. bool single_threaded;
  699. bool stop;
  700. ARAL *ar;
  701. size_t elements;
  702. size_t threads;
  703. int errors;
  704. };
  705. static void *aral_test_thread(void *ptr) {
  706. struct aral_unittest_config *auc = ptr;
  707. ARAL *ar = auc->ar;
  708. size_t elements = auc->elements;
  709. void **pointers = callocz(elements, sizeof(void *));
  710. do {
  711. for (size_t i = 0; i < elements; i++) {
  712. pointers[i] = aral_mallocz(ar);
  713. }
  714. for (size_t div = 5; div >= 2; div--) {
  715. for (size_t i = 0; i < elements / div; i++) {
  716. aral_freez(ar, pointers[i]);
  717. pointers[i] = NULL;
  718. }
  719. for (size_t i = 0; i < elements / div; i++) {
  720. pointers[i] = aral_mallocz(ar);
  721. }
  722. }
  723. for (size_t step = 50; step >= 10; step -= 10) {
  724. for (size_t i = 0; i < elements; i += step) {
  725. aral_freez(ar, pointers[i]);
  726. pointers[i] = NULL;
  727. }
  728. for (size_t i = 0; i < elements; i += step) {
  729. pointers[i] = aral_mallocz(ar);
  730. }
  731. }
  732. for (size_t i = 0; i < elements; i++) {
  733. aral_freez(ar, pointers[i]);
  734. pointers[i] = NULL;
  735. }
  736. if (auc->single_threaded && ar->aral_lock.pages && ar->aral_lock.pages->aral_lock.used_elements) {
  737. fprintf(stderr, "\n\nARAL leftovers detected (1)\n\n");
  738. __atomic_add_fetch(&auc->errors, 1, __ATOMIC_RELAXED);
  739. }
  740. if(!auc->single_threaded && __atomic_load_n(&auc->stop, __ATOMIC_RELAXED))
  741. break;
  742. for (size_t i = 0; i < elements; i++) {
  743. pointers[i] = aral_mallocz(ar);
  744. }
  745. size_t increment = elements / ar->config.max_page_elements;
  746. for (size_t all = increment; all <= elements / 2; all += increment) {
  747. size_t to_free = (all % ar->config.max_page_elements) + 1;
  748. size_t step = elements / to_free;
  749. if(!step) step = 1;
  750. // fprintf(stderr, "all %zu, to free %zu, step %zu\n", all, to_free, step);
  751. size_t free_list[to_free];
  752. for (size_t i = 0; i < to_free; i++) {
  753. size_t pos = step * i;
  754. aral_freez(ar, pointers[pos]);
  755. pointers[pos] = NULL;
  756. free_list[i] = pos;
  757. }
  758. for (size_t i = 0; i < to_free; i++) {
  759. size_t pos = free_list[i];
  760. pointers[pos] = aral_mallocz(ar);
  761. }
  762. }
  763. for (size_t i = 0; i < elements; i++) {
  764. aral_freez(ar, pointers[i]);
  765. pointers[i] = NULL;
  766. }
  767. if (auc->single_threaded && ar->aral_lock.pages && ar->aral_lock.pages->aral_lock.used_elements) {
  768. fprintf(stderr, "\n\nARAL leftovers detected (2)\n\n");
  769. __atomic_add_fetch(&auc->errors, 1, __ATOMIC_RELAXED);
  770. }
  771. } while(!auc->single_threaded && !__atomic_load_n(&auc->stop, __ATOMIC_RELAXED));
  772. freez(pointers);
  773. return ptr;
  774. }
  775. int aral_stress_test(size_t threads, size_t elements, size_t seconds) {
  776. fprintf(stderr, "Running stress test of %zu threads, with %zu elements each, for %zu seconds...\n",
  777. threads, elements, seconds);
  778. struct aral_unittest_config auc = {
  779. .single_threaded = false,
  780. .threads = threads,
  781. .ar = aral_create("aral-stress-test", 20, 0, 8192, NULL, "aral-stress-test", NULL, false, false),
  782. .elements = elements,
  783. .errors = 0,
  784. };
  785. usec_t started_ut = now_monotonic_usec();
  786. netdata_thread_t thread_ptrs[threads];
  787. for(size_t i = 0; i < threads ; i++) {
  788. char tag[NETDATA_THREAD_NAME_MAX + 1];
  789. snprintfz(tag, NETDATA_THREAD_NAME_MAX, "TH[%zu]", i);
  790. netdata_thread_create(&thread_ptrs[i], tag,
  791. NETDATA_THREAD_OPTION_JOINABLE | NETDATA_THREAD_OPTION_DONT_LOG,
  792. aral_test_thread, &auc);
  793. }
  794. size_t malloc_done = 0;
  795. size_t free_done = 0;
  796. size_t countdown = seconds;
  797. while(countdown-- > 0) {
  798. sleep_usec(1 * USEC_PER_SEC);
  799. aral_lock(auc.ar);
  800. size_t m = auc.ar->aral_lock.user_malloc_operations;
  801. size_t f = auc.ar->aral_lock.user_free_operations;
  802. aral_unlock(auc.ar);
  803. fprintf(stderr, "ARAL executes %0.2f M malloc and %0.2f M free operations/s\n",
  804. (double)(m - malloc_done) / 1000000.0, (double)(f - free_done) / 1000000.0);
  805. malloc_done = m;
  806. free_done = f;
  807. }
  808. __atomic_store_n(&auc.stop, true, __ATOMIC_RELAXED);
  809. // fprintf(stderr, "Cancelling the threads...\n");
  810. // for(size_t i = 0; i < threads ; i++) {
  811. // netdata_thread_cancel(thread_ptrs[i]);
  812. // }
  813. fprintf(stderr, "Waiting the threads to finish...\n");
  814. for(size_t i = 0; i < threads ; i++) {
  815. netdata_thread_join(thread_ptrs[i], NULL);
  816. }
  817. usec_t ended_ut = now_monotonic_usec();
  818. if (auc.ar->aral_lock.pages && auc.ar->aral_lock.pages->aral_lock.used_elements) {
  819. fprintf(stderr, "\n\nARAL leftovers detected (3)\n\n");
  820. __atomic_add_fetch(&auc.errors, 1, __ATOMIC_RELAXED);
  821. }
  822. info("ARAL: did %zu malloc, %zu free, "
  823. "using %zu threads, in %llu usecs",
  824. auc.ar->aral_lock.user_malloc_operations,
  825. auc.ar->aral_lock.user_free_operations,
  826. threads,
  827. ended_ut - started_ut);
  828. aral_destroy(auc.ar);
  829. return auc.errors;
  830. }
  831. int aral_unittest(size_t elements) {
  832. char *cache_dir = "/tmp/";
  833. struct aral_unittest_config auc = {
  834. .single_threaded = true,
  835. .threads = 1,
  836. .ar = aral_create("aral-test", 20, 0, 8192, NULL, "aral-test", &cache_dir, false, false),
  837. .elements = elements,
  838. .errors = 0,
  839. };
  840. aral_test_thread(&auc);
  841. aral_destroy(auc.ar);
  842. int errors = aral_stress_test(2, elements, 5);
  843. return auc.errors + errors;
  844. }