heap_linux.odin 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. //+private
  2. package os2
  3. import "base:runtime"
  4. import "core:sys/linux"
  5. import "core:sync"
  6. import "core:mem"
  7. // Use the experimental custom heap allocator (over calling `malloc` etc.).
  8. // This is a switch because there are thread-safety problems that need to be fixed.
  9. // See: https://github.com/odin-lang/Odin/issues/4161
  10. USE_EXPERIMENTAL_ALLOCATOR :: #config(OS2_LINUX_USE_EXPERIMENTAL_ALLOCATOR, false)
  11. // NOTEs
  12. //
  13. // All allocations below DIRECT_MMAP_THRESHOLD exist inside of memory "Regions." A region
  14. // consists of a Region_Header and the memory that will be divided into allocations to
  15. // send to the user. The memory is an array of "Allocation_Headers" which are 8 bytes.
  16. // Allocation_Headers are used to navigate the memory in the region. The "next" member of
  17. // the Allocation_Header points to the next header, and the space between the headers
  18. // can be used to send to the user. This space between is referred to as "blocks" in the
  19. // code. The indexes in the header refer to these blocks instead of bytes. This allows us
  20. // to index all the memory in the region with a u16.
  21. //
  22. // When an allocation request is made, it will use the first free block that can contain
  23. // the entire block. If there is an excess number of blocks (as specified by the constant
  24. // BLOCK_SEGMENT_THRESHOLD), this extra space will be segmented and left in the free_list.
  25. //
  26. // To keep the implementation simple, there can never exist 2 free blocks adjacent to each
  27. // other. Any freeing will result in attempting to merge the blocks before and after the
  28. // newly free'd blocks.
  29. //
  30. // Any request for size above the DIRECT_MMAP_THRESHOLD will result in the allocation
  31. // getting its own individual mmap. Individual mmaps will still get an Allocation_Header
  32. // that contains the size with the last bit set to 1 to indicate it is indeed a direct
  33. // mmap allocation.
  34. // Why not brk?
  35. // glibc's malloc utilizes a mix of the brk and mmap system calls. This implementation
  36. // does *not* utilize the brk system call to avoid possible conflicts with foreign C
  37. // code. Just because we aren't directly using libc, there is nothing stopping the user
  38. // from doing it.
  39. // What's with all the #no_bounds_check?
  40. // When memory is returned from mmap, it technically doesn't get written ... well ... anywhere
  41. // until that region is written to by *you*. So, when a new region is created, we call mmap
  42. // to get a pointer to some memory, and we claim that memory is a ^Region. Therefor, the
  43. // region itself is never formally initialized by the compiler as this would result in writing
  44. // zeros to memory that we can already assume are 0. This would also have the effect of
  45. // actually commiting this data to memory whether it gets used or not.
  46. //
  47. // Some variables to play with
  48. //
  49. // Minimum blocks used for any one allocation
  50. MINIMUM_BLOCK_COUNT :: 2
  51. // Number of extra blocks beyond the requested amount where we would segment.
  52. // E.g. (blocks) |H0123456| 7 available
  53. // |H01H0123| Ask for 2, now 4 available
  54. BLOCK_SEGMENT_THRESHOLD :: 4
  55. // Anything above this threshold will get its own memory map. Since regions
  56. // are indexed by 16 bit integers, this value should not surpass max(u16) * 6
  57. DIRECT_MMAP_THRESHOLD_USER :: int(max(u16))
  58. // The point at which we convert direct mmap to region. This should be a decent
  59. // amount less than DIRECT_MMAP_THRESHOLD to avoid jumping in and out of regions.
  60. MMAP_TO_REGION_SHRINK_THRESHOLD :: DIRECT_MMAP_THRESHOLD - PAGE_SIZE * 4
  61. // free_list is dynamic and is initialized in the begining of the region memory
  62. // when the region is initialized. Once resized, it can be moved anywhere.
  63. FREE_LIST_DEFAULT_CAP :: 32
  64. //
  65. // Other constants that should not be touched
  66. //
  67. // This universally seems to be 4096 outside of uncommon archs.
  68. PAGE_SIZE :: 4096
  69. // just rounding up to nearest PAGE_SIZE
  70. DIRECT_MMAP_THRESHOLD :: (DIRECT_MMAP_THRESHOLD_USER-1) + PAGE_SIZE - (DIRECT_MMAP_THRESHOLD_USER-1) % PAGE_SIZE
  71. // Regions must be big enough to hold DIRECT_MMAP_THRESHOLD - 1 as well
  72. // as end right on a page boundary as to not waste space.
  73. SIZE_OF_REGION :: DIRECT_MMAP_THRESHOLD + 4 * int(PAGE_SIZE)
  74. // size of user memory blocks
  75. BLOCK_SIZE :: size_of(Allocation_Header)
  76. // number of allocation sections (call them blocks) of the region used for allocations
  77. BLOCKS_PER_REGION :: u16((SIZE_OF_REGION - size_of(Region_Header)) / BLOCK_SIZE)
  78. // minimum amount of space that can used by any individual allocation (includes header)
  79. MINIMUM_ALLOCATION :: (MINIMUM_BLOCK_COUNT * BLOCK_SIZE) + BLOCK_SIZE
  80. // This is used as a boolean value for Region_Header.local_addr.
  81. CURRENTLY_ACTIVE :: (^^Region)(~uintptr(0))
  82. FREE_LIST_ENTRIES_PER_BLOCK :: BLOCK_SIZE / size_of(u16)
  83. MMAP_FLAGS : linux.Map_Flags : {.ANONYMOUS, .PRIVATE}
  84. MMAP_PROT : linux.Mem_Protection : {.READ, .WRITE}
  85. @thread_local _local_region: ^Region
  86. global_regions: ^Region
  87. // There is no way of correctly setting the last bit of free_idx or
  88. // the last bit of requested, so we can safely use it as a flag to
  89. // determine if we are interacting with a direct mmap.
  90. REQUESTED_MASK :: 0x7FFFFFFFFFFFFFFF
  91. IS_DIRECT_MMAP :: 0x8000000000000000
  92. // Special free_idx value that does not index the free_list.
  93. NOT_FREE :: 0x7FFF
  94. Allocation_Header :: struct #raw_union {
  95. using _: struct {
  96. // Block indicies
  97. idx: u16,
  98. prev: u16,
  99. next: u16,
  100. free_idx: u16,
  101. },
  102. requested: u64,
  103. }
  104. Region_Header :: struct #align(16) {
  105. next_region: ^Region, // points to next region in global_heap (linked list)
  106. local_addr: ^^Region, // tracks region ownership via address of _local_region
  107. reset_addr: ^^Region, // tracks old local addr for reset
  108. free_list: []u16,
  109. free_list_len: u16,
  110. free_blocks: u16, // number of free blocks in region (includes headers)
  111. last_used: u16, // farthest back block that has been used (need zeroing?)
  112. _reserved: u16,
  113. }
  114. Region :: struct {
  115. hdr: Region_Header,
  116. memory: [BLOCKS_PER_REGION]Allocation_Header,
  117. }
  118. when USE_EXPERIMENTAL_ALLOCATOR {
  119. _heap_allocator_proc :: proc(allocator_data: rawptr, mode: mem.Allocator_Mode,
  120. size, alignment: int,
  121. old_memory: rawptr, old_size: int, loc := #caller_location) -> ([]byte, mem.Allocator_Error) {
  122. //
  123. // NOTE(tetra, 2020-01-14): The heap doesn't respect alignment.
  124. // Instead, we overallocate by `alignment + size_of(rawptr) - 1`, and insert
  125. // padding. We also store the original pointer returned by heap_alloc right before
  126. // the pointer we return to the user.
  127. //
  128. aligned_alloc :: proc(size, alignment: int, old_ptr: rawptr = nil) -> ([]byte, mem.Allocator_Error) {
  129. a := max(alignment, align_of(rawptr))
  130. space := size + a - 1
  131. allocated_mem: rawptr
  132. if old_ptr != nil {
  133. original_old_ptr := mem.ptr_offset((^rawptr)(old_ptr), -1)^
  134. allocated_mem = heap_resize(original_old_ptr, space+size_of(rawptr))
  135. } else {
  136. allocated_mem = heap_alloc(space+size_of(rawptr))
  137. }
  138. aligned_mem := rawptr(mem.ptr_offset((^u8)(allocated_mem), size_of(rawptr)))
  139. ptr := uintptr(aligned_mem)
  140. aligned_ptr := (ptr - 1 + uintptr(a)) & -uintptr(a)
  141. diff := int(aligned_ptr - ptr)
  142. if (size + diff) > space || allocated_mem == nil {
  143. return nil, .Out_Of_Memory
  144. }
  145. aligned_mem = rawptr(aligned_ptr)
  146. mem.ptr_offset((^rawptr)(aligned_mem), -1)^ = allocated_mem
  147. return mem.byte_slice(aligned_mem, size), nil
  148. }
  149. aligned_free :: proc(p: rawptr) {
  150. if p != nil {
  151. heap_free(mem.ptr_offset((^rawptr)(p), -1)^)
  152. }
  153. }
  154. aligned_resize :: proc(p: rawptr, old_size: int, new_size: int, new_alignment: int) -> (new_memory: []byte, err: mem.Allocator_Error) {
  155. if p == nil {
  156. return nil, nil
  157. }
  158. return aligned_alloc(new_size, new_alignment, p)
  159. }
  160. switch mode {
  161. case .Alloc, .Alloc_Non_Zeroed:
  162. return aligned_alloc(size, alignment)
  163. case .Free:
  164. aligned_free(old_memory)
  165. case .Free_All:
  166. return nil, .Mode_Not_Implemented
  167. case .Resize, .Resize_Non_Zeroed:
  168. if old_memory == nil {
  169. return aligned_alloc(size, alignment)
  170. }
  171. return aligned_resize(old_memory, old_size, size, alignment)
  172. case .Query_Features:
  173. set := (^mem.Allocator_Mode_Set)(old_memory)
  174. if set != nil {
  175. set^ = {.Alloc, .Free, .Resize, .Query_Features}
  176. }
  177. return nil, nil
  178. case .Query_Info:
  179. return nil, .Mode_Not_Implemented
  180. }
  181. return nil, nil
  182. }
  183. } else {
  184. _heap_allocator_proc :: runtime.heap_allocator_proc
  185. }
  186. heap_alloc :: proc(size: int) -> rawptr {
  187. if size >= DIRECT_MMAP_THRESHOLD {
  188. return _direct_mmap_alloc(size)
  189. }
  190. // atomically check if the local region has been stolen
  191. if _local_region != nil {
  192. res := sync.atomic_compare_exchange_strong_explicit(
  193. &_local_region.hdr.local_addr,
  194. &_local_region,
  195. CURRENTLY_ACTIVE,
  196. .Acquire,
  197. .Relaxed,
  198. )
  199. if res != &_local_region {
  200. // At this point, the region has been stolen and res contains the unexpected value
  201. expected := res
  202. if res != CURRENTLY_ACTIVE {
  203. expected = res
  204. res = sync.atomic_compare_exchange_strong_explicit(
  205. &_local_region.hdr.local_addr,
  206. expected,
  207. CURRENTLY_ACTIVE,
  208. .Acquire,
  209. .Relaxed,
  210. )
  211. }
  212. if res != expected {
  213. _local_region = nil
  214. }
  215. }
  216. }
  217. size := size
  218. size = _round_up_to_nearest(size, BLOCK_SIZE)
  219. blocks_needed := u16(max(MINIMUM_BLOCK_COUNT, size / BLOCK_SIZE))
  220. // retrieve a region if new thread or stolen
  221. if _local_region == nil {
  222. _local_region, _ = _region_retrieve_with_space(blocks_needed)
  223. if _local_region == nil {
  224. return nil
  225. }
  226. }
  227. defer sync.atomic_store_explicit(&_local_region.hdr.local_addr, &_local_region, .Release)
  228. // At this point we have a usable region. Let's find the user some memory
  229. idx: u16
  230. local_region_idx := _region_get_local_idx()
  231. back_idx := -1
  232. infinite: for {
  233. for i := 0; i < int(_local_region.hdr.free_list_len); i += 1 {
  234. idx = _local_region.hdr.free_list[i]
  235. #no_bounds_check if _get_block_count(_local_region.memory[idx]) >= blocks_needed {
  236. break infinite
  237. }
  238. }
  239. sync.atomic_store_explicit(&_local_region.hdr.local_addr, &_local_region, .Release)
  240. _local_region, back_idx = _region_retrieve_with_space(blocks_needed, local_region_idx, back_idx)
  241. }
  242. user_ptr, used := _region_get_block(_local_region, idx, blocks_needed)
  243. _local_region.hdr.free_blocks -= (used + 1)
  244. // If this memory was ever used before, it now needs to be zero'd.
  245. if idx < _local_region.hdr.last_used {
  246. mem.zero(user_ptr, int(used) * BLOCK_SIZE)
  247. } else {
  248. _local_region.hdr.last_used = idx + used
  249. }
  250. return user_ptr
  251. }
  252. heap_resize :: proc(old_memory: rawptr, new_size: int) -> rawptr #no_bounds_check {
  253. alloc := _get_allocation_header(old_memory)
  254. if alloc.requested & IS_DIRECT_MMAP > 0 {
  255. return _direct_mmap_resize(alloc, new_size)
  256. }
  257. if new_size > DIRECT_MMAP_THRESHOLD {
  258. return _direct_mmap_from_region(alloc, new_size)
  259. }
  260. return _region_resize(alloc, new_size)
  261. }
  262. heap_free :: proc(memory: rawptr) {
  263. alloc := _get_allocation_header(memory)
  264. if alloc.requested & IS_DIRECT_MMAP == IS_DIRECT_MMAP {
  265. _direct_mmap_free(alloc)
  266. return
  267. }
  268. assert(alloc.free_idx == NOT_FREE)
  269. _region_find_and_assign_local(alloc)
  270. _region_local_free(alloc)
  271. sync.atomic_store_explicit(&_local_region.hdr.local_addr, &_local_region, .Release)
  272. }
  273. //
  274. // Regions
  275. //
  276. _new_region :: proc() -> ^Region #no_bounds_check {
  277. ptr, errno := linux.mmap(0, uint(SIZE_OF_REGION), MMAP_PROT, MMAP_FLAGS, -1, 0)
  278. if errno != .NONE {
  279. return nil
  280. }
  281. new_region := (^Region)(ptr)
  282. new_region.hdr.local_addr = CURRENTLY_ACTIVE
  283. new_region.hdr.reset_addr = &_local_region
  284. free_list_blocks := _round_up_to_nearest(FREE_LIST_DEFAULT_CAP, FREE_LIST_ENTRIES_PER_BLOCK)
  285. _region_assign_free_list(new_region, &new_region.memory[1], u16(free_list_blocks) * FREE_LIST_ENTRIES_PER_BLOCK)
  286. // + 2 to account for free_list's allocation header
  287. first_user_block := len(new_region.hdr.free_list) / FREE_LIST_ENTRIES_PER_BLOCK + 2
  288. // first allocation header (this is a free list)
  289. new_region.memory[0].next = u16(first_user_block)
  290. new_region.memory[0].free_idx = NOT_FREE
  291. new_region.memory[first_user_block].idx = u16(first_user_block)
  292. new_region.memory[first_user_block].next = BLOCKS_PER_REGION - 1
  293. // add the first user block to the free list
  294. new_region.hdr.free_list[0] = u16(first_user_block)
  295. new_region.hdr.free_list_len = 1
  296. new_region.hdr.free_blocks = _get_block_count(new_region.memory[first_user_block]) + 1
  297. for r := sync.atomic_compare_exchange_strong(&global_regions, nil, new_region);
  298. r != nil;
  299. r = sync.atomic_compare_exchange_strong(&r.hdr.next_region, nil, new_region) {}
  300. return new_region
  301. }
  302. _region_resize :: proc(alloc: ^Allocation_Header, new_size: int, alloc_is_free_list: bool = false) -> rawptr #no_bounds_check {
  303. assert(alloc.free_idx == NOT_FREE)
  304. old_memory := mem.ptr_offset(alloc, 1)
  305. old_block_count := _get_block_count(alloc^)
  306. new_block_count := u16(
  307. max(MINIMUM_BLOCK_COUNT, _round_up_to_nearest(new_size, BLOCK_SIZE) / BLOCK_SIZE),
  308. )
  309. if new_block_count < old_block_count {
  310. if new_block_count - old_block_count >= MINIMUM_BLOCK_COUNT {
  311. _region_find_and_assign_local(alloc)
  312. _region_segment(_local_region, alloc, new_block_count, alloc.free_idx)
  313. new_block_count = _get_block_count(alloc^)
  314. sync.atomic_store_explicit(&_local_region.hdr.local_addr, &_local_region, .Release)
  315. }
  316. // need to zero anything within the new block that that lies beyond new_size
  317. extra_bytes := int(new_block_count * BLOCK_SIZE) - new_size
  318. extra_bytes_ptr := mem.ptr_offset((^u8)(alloc), new_size + BLOCK_SIZE)
  319. mem.zero(extra_bytes_ptr, extra_bytes)
  320. return old_memory
  321. }
  322. if !alloc_is_free_list {
  323. _region_find_and_assign_local(alloc)
  324. }
  325. defer if !alloc_is_free_list {
  326. sync.atomic_store_explicit(&_local_region.hdr.local_addr, &_local_region, .Release)
  327. }
  328. // First, let's see if we can grow in place.
  329. if alloc.next != BLOCKS_PER_REGION - 1 && _local_region.memory[alloc.next].free_idx != NOT_FREE {
  330. next_alloc := _local_region.memory[alloc.next]
  331. total_available := old_block_count + _get_block_count(next_alloc) + 1
  332. if total_available >= new_block_count {
  333. alloc.next = next_alloc.next
  334. _local_region.memory[alloc.next].prev = alloc.idx
  335. if total_available - new_block_count > BLOCK_SEGMENT_THRESHOLD {
  336. _region_segment(_local_region, alloc, new_block_count, next_alloc.free_idx)
  337. } else {
  338. _region_free_list_remove(_local_region, next_alloc.free_idx)
  339. }
  340. mem.zero(&_local_region.memory[next_alloc.idx], int(alloc.next - next_alloc.idx) * BLOCK_SIZE)
  341. _local_region.hdr.last_used = max(alloc.next, _local_region.hdr.last_used)
  342. _local_region.hdr.free_blocks -= (_get_block_count(alloc^) - old_block_count)
  343. if alloc_is_free_list {
  344. _region_assign_free_list(_local_region, old_memory, _get_block_count(alloc^))
  345. }
  346. return old_memory
  347. }
  348. }
  349. // If we made it this far, we need to resize, copy, zero and free.
  350. region_iter := _local_region
  351. local_region_idx := _region_get_local_idx()
  352. back_idx := -1
  353. idx: u16
  354. infinite: for {
  355. for i := 0; i < len(region_iter.hdr.free_list); i += 1 {
  356. idx = region_iter.hdr.free_list[i]
  357. if _get_block_count(region_iter.memory[idx]) >= new_block_count {
  358. break infinite
  359. }
  360. }
  361. if region_iter != _local_region {
  362. sync.atomic_store_explicit(
  363. &region_iter.hdr.local_addr,
  364. region_iter.hdr.reset_addr,
  365. .Release,
  366. )
  367. }
  368. region_iter, back_idx = _region_retrieve_with_space(new_block_count, local_region_idx, back_idx)
  369. }
  370. if region_iter != _local_region {
  371. sync.atomic_store_explicit(
  372. &region_iter.hdr.local_addr,
  373. region_iter.hdr.reset_addr,
  374. .Release,
  375. )
  376. }
  377. // copy from old memory
  378. new_memory, used_blocks := _region_get_block(region_iter, idx, new_block_count)
  379. mem.copy(new_memory, old_memory, int(old_block_count * BLOCK_SIZE))
  380. // zero any new memory
  381. addon_section := mem.ptr_offset((^Allocation_Header)(new_memory), old_block_count)
  382. new_blocks := used_blocks - old_block_count
  383. mem.zero(addon_section, int(new_blocks) * BLOCK_SIZE)
  384. region_iter.hdr.free_blocks -= (used_blocks + 1)
  385. // Set free_list before freeing.
  386. if alloc_is_free_list {
  387. _region_assign_free_list(_local_region, new_memory, used_blocks)
  388. }
  389. // free old memory
  390. _region_local_free(alloc)
  391. return new_memory
  392. }
  393. _region_local_free :: proc(alloc: ^Allocation_Header) #no_bounds_check {
  394. alloc := alloc
  395. add_to_free_list := true
  396. _local_region.hdr.free_blocks += _get_block_count(alloc^) + 1
  397. // try to merge with prev
  398. if alloc.idx > 0 && _local_region.memory[alloc.prev].free_idx != NOT_FREE {
  399. _local_region.memory[alloc.prev].next = alloc.next
  400. _local_region.memory[alloc.next].prev = alloc.prev
  401. alloc = &_local_region.memory[alloc.prev]
  402. add_to_free_list = false
  403. }
  404. // try to merge with next
  405. if alloc.next < BLOCKS_PER_REGION - 1 && _local_region.memory[alloc.next].free_idx != NOT_FREE {
  406. old_next := alloc.next
  407. alloc.next = _local_region.memory[old_next].next
  408. _local_region.memory[alloc.next].prev = alloc.idx
  409. if add_to_free_list {
  410. _local_region.hdr.free_list[_local_region.memory[old_next].free_idx] = alloc.idx
  411. alloc.free_idx = _local_region.memory[old_next].free_idx
  412. } else {
  413. // NOTE: We have aleady merged with prev, and now merged with next.
  414. // Now, we are actually going to remove from the free_list.
  415. _region_free_list_remove(_local_region, _local_region.memory[old_next].free_idx)
  416. }
  417. add_to_free_list = false
  418. }
  419. // This is the only place where anything is appended to the free list.
  420. if add_to_free_list {
  421. fl := _local_region.hdr.free_list
  422. alloc.free_idx = _local_region.hdr.free_list_len
  423. fl[alloc.free_idx] = alloc.idx
  424. _local_region.hdr.free_list_len += 1
  425. if int(_local_region.hdr.free_list_len) == len(fl) {
  426. free_alloc := _get_allocation_header(mem.raw_data(_local_region.hdr.free_list))
  427. _region_resize(free_alloc, len(fl) * 2 * size_of(fl[0]), true)
  428. }
  429. }
  430. }
  431. _region_assign_free_list :: proc(region: ^Region, memory: rawptr, blocks: u16) {
  432. raw_free_list := transmute(mem.Raw_Slice)region.hdr.free_list
  433. raw_free_list.len = int(blocks) * FREE_LIST_ENTRIES_PER_BLOCK
  434. raw_free_list.data = memory
  435. region.hdr.free_list = transmute([]u16)(raw_free_list)
  436. }
  437. _region_retrieve_with_space :: proc(blocks: u16, local_idx: int = -1, back_idx: int = -1) -> (^Region, int) {
  438. r: ^Region
  439. idx: int
  440. for r = global_regions; r != nil; r = r.hdr.next_region {
  441. if idx == local_idx || idx < back_idx || r.hdr.free_blocks < blocks {
  442. idx += 1
  443. continue
  444. }
  445. idx += 1
  446. local_addr: ^^Region = sync.atomic_load(&r.hdr.local_addr)
  447. if local_addr != CURRENTLY_ACTIVE {
  448. res := sync.atomic_compare_exchange_strong_explicit(
  449. &r.hdr.local_addr,
  450. local_addr,
  451. CURRENTLY_ACTIVE,
  452. .Acquire,
  453. .Relaxed,
  454. )
  455. if res == local_addr {
  456. r.hdr.reset_addr = local_addr
  457. return r, idx
  458. }
  459. }
  460. }
  461. return _new_region(), idx
  462. }
  463. _region_retrieve_from_addr :: proc(addr: rawptr) -> ^Region {
  464. r: ^Region
  465. for r = global_regions; r != nil; r = r.hdr.next_region {
  466. if _region_contains_mem(r, addr) {
  467. return r
  468. }
  469. }
  470. unreachable()
  471. }
  472. _region_get_block :: proc(region: ^Region, idx, blocks_needed: u16) -> (rawptr, u16) #no_bounds_check {
  473. alloc := &region.memory[idx]
  474. assert(alloc.free_idx != NOT_FREE)
  475. assert(alloc.next > 0)
  476. block_count := _get_block_count(alloc^)
  477. if block_count - blocks_needed > BLOCK_SEGMENT_THRESHOLD {
  478. _region_segment(region, alloc, blocks_needed, alloc.free_idx)
  479. } else {
  480. _region_free_list_remove(region, alloc.free_idx)
  481. }
  482. alloc.free_idx = NOT_FREE
  483. return mem.ptr_offset(alloc, 1), _get_block_count(alloc^)
  484. }
  485. _region_segment :: proc(region: ^Region, alloc: ^Allocation_Header, blocks, new_free_idx: u16) #no_bounds_check {
  486. old_next := alloc.next
  487. alloc.next = alloc.idx + blocks + 1
  488. region.memory[old_next].prev = alloc.next
  489. // Initialize alloc.next allocation header here.
  490. region.memory[alloc.next].prev = alloc.idx
  491. region.memory[alloc.next].next = old_next
  492. region.memory[alloc.next].idx = alloc.next
  493. region.memory[alloc.next].free_idx = new_free_idx
  494. // Replace our original spot in the free_list with new segment.
  495. region.hdr.free_list[new_free_idx] = alloc.next
  496. }
  497. _region_get_local_idx :: proc() -> int {
  498. idx: int
  499. for r := global_regions; r != nil; r = r.hdr.next_region {
  500. if r == _local_region {
  501. return idx
  502. }
  503. idx += 1
  504. }
  505. return -1
  506. }
  507. _region_find_and_assign_local :: proc(alloc: ^Allocation_Header) {
  508. // Find the region that contains this memory
  509. if !_region_contains_mem(_local_region, alloc) {
  510. _local_region = _region_retrieve_from_addr(alloc)
  511. }
  512. // At this point, _local_region is set correctly. Spin until acquired
  513. res: ^^Region
  514. for res != &_local_region {
  515. res = sync.atomic_compare_exchange_strong_explicit(
  516. &_local_region.hdr.local_addr,
  517. &_local_region,
  518. CURRENTLY_ACTIVE,
  519. .Acquire,
  520. .Relaxed,
  521. )
  522. }
  523. }
  524. _region_contains_mem :: proc(r: ^Region, memory: rawptr) -> bool #no_bounds_check {
  525. if r == nil {
  526. return false
  527. }
  528. mem_int := uintptr(memory)
  529. return mem_int >= uintptr(&r.memory[0]) && mem_int <= uintptr(&r.memory[BLOCKS_PER_REGION - 1])
  530. }
  531. _region_free_list_remove :: proc(region: ^Region, free_idx: u16) #no_bounds_check {
  532. // pop, swap and update allocation hdr
  533. if n := region.hdr.free_list_len - 1; free_idx != n {
  534. region.hdr.free_list[free_idx] = region.hdr.free_list[n]
  535. alloc_idx := region.hdr.free_list[free_idx]
  536. region.memory[alloc_idx].free_idx = free_idx
  537. }
  538. region.hdr.free_list_len -= 1
  539. }
  540. //
  541. // Direct mmap
  542. //
  543. _direct_mmap_alloc :: proc(size: int) -> rawptr {
  544. mmap_size := _round_up_to_nearest(size + BLOCK_SIZE, PAGE_SIZE)
  545. new_allocation, errno := linux.mmap(0, uint(mmap_size), MMAP_PROT, MMAP_FLAGS, -1, 0)
  546. if errno != .NONE {
  547. return nil
  548. }
  549. alloc := (^Allocation_Header)(uintptr(new_allocation))
  550. alloc.requested = u64(size) // NOTE: requested = requested size
  551. alloc.requested += IS_DIRECT_MMAP
  552. return rawptr(mem.ptr_offset(alloc, 1))
  553. }
  554. _direct_mmap_resize :: proc(alloc: ^Allocation_Header, new_size: int) -> rawptr {
  555. old_requested := int(alloc.requested & REQUESTED_MASK)
  556. old_mmap_size := _round_up_to_nearest(old_requested + BLOCK_SIZE, PAGE_SIZE)
  557. new_mmap_size := _round_up_to_nearest(new_size + BLOCK_SIZE, PAGE_SIZE)
  558. if int(new_mmap_size) < MMAP_TO_REGION_SHRINK_THRESHOLD {
  559. return _direct_mmap_to_region(alloc, new_size)
  560. } else if old_requested == new_size {
  561. return mem.ptr_offset(alloc, 1)
  562. }
  563. new_allocation, errno := linux.mremap(alloc, uint(old_mmap_size), uint(new_mmap_size), {.MAYMOVE})
  564. if errno != .NONE {
  565. return nil
  566. }
  567. new_header := (^Allocation_Header)(uintptr(new_allocation))
  568. new_header.requested = u64(new_size)
  569. new_header.requested += IS_DIRECT_MMAP
  570. if new_mmap_size > old_mmap_size {
  571. // new section may not be pointer aligned, so cast to ^u8
  572. new_section := mem.ptr_offset((^u8)(new_header), old_requested + BLOCK_SIZE)
  573. mem.zero(new_section, new_mmap_size - old_mmap_size)
  574. }
  575. return mem.ptr_offset(new_header, 1)
  576. }
  577. _direct_mmap_from_region :: proc(alloc: ^Allocation_Header, new_size: int) -> rawptr {
  578. new_memory := _direct_mmap_alloc(new_size)
  579. if new_memory != nil {
  580. old_memory := mem.ptr_offset(alloc, 1)
  581. mem.copy(new_memory, old_memory, int(_get_block_count(alloc^)) * BLOCK_SIZE)
  582. }
  583. _region_find_and_assign_local(alloc)
  584. _region_local_free(alloc)
  585. sync.atomic_store_explicit(&_local_region.hdr.local_addr, &_local_region, .Release)
  586. return new_memory
  587. }
  588. _direct_mmap_to_region :: proc(alloc: ^Allocation_Header, new_size: int) -> rawptr {
  589. new_memory := heap_alloc(new_size)
  590. if new_memory != nil {
  591. mem.copy(new_memory, mem.ptr_offset(alloc, -1), new_size)
  592. _direct_mmap_free(alloc)
  593. }
  594. return new_memory
  595. }
  596. _direct_mmap_free :: proc(alloc: ^Allocation_Header) {
  597. requested := int(alloc.requested & REQUESTED_MASK)
  598. mmap_size := _round_up_to_nearest(requested + BLOCK_SIZE, PAGE_SIZE)
  599. linux.munmap(alloc, uint(mmap_size))
  600. }
  601. //
  602. // Util
  603. //
  604. _get_block_count :: #force_inline proc(alloc: Allocation_Header) -> u16 {
  605. return alloc.next - alloc.idx - 1
  606. }
  607. _get_allocation_header :: #force_inline proc(raw_mem: rawptr) -> ^Allocation_Header {
  608. return mem.ptr_offset((^Allocation_Header)(raw_mem), -1)
  609. }
  610. _round_up_to_nearest :: #force_inline proc(size, round: int) -> int {
  611. return (size-1) + round - (size-1) % round
  612. }