rollback_stack_allocator.odin 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. package mem
  2. import "base:runtime"
  3. /*
  4. Rollback stack default block size.
  5. */
  6. ROLLBACK_STACK_DEFAULT_BLOCK_SIZE :: 4 * Megabyte
  7. /*
  8. Rollback stack max head block size.
  9. This limitation is due to the size of `prev_ptr`, but it is only for the
  10. head block; any allocation in excess of the allocator's `block_size` is
  11. valid, so long as the block allocator can handle it.
  12. This is because allocations over the block size are not split up if the item
  13. within is freed; they are immediately returned to the block allocator.
  14. */
  15. ROLLBACK_STACK_MAX_HEAD_BLOCK_SIZE :: 2 * Gigabyte
  16. /*
  17. Allocation header of the rollback stack allocator.
  18. */
  19. Rollback_Stack_Header :: bit_field u64 {
  20. prev_offset: uintptr | 32,
  21. is_free: bool | 1,
  22. prev_ptr: uintptr | 31,
  23. }
  24. /*
  25. Block header of the rollback stack allocator.
  26. */
  27. Rollback_Stack_Block :: struct {
  28. next_block: ^Rollback_Stack_Block,
  29. last_alloc: rawptr,
  30. offset: uintptr,
  31. buffer: []byte,
  32. }
  33. /*
  34. Rollback stack allocator data.
  35. */
  36. Rollback_Stack :: struct {
  37. head: ^Rollback_Stack_Block,
  38. block_size: int,
  39. block_allocator: Allocator,
  40. }
  41. @(private="file", require_results)
  42. rb_ptr_in_bounds :: proc(block: ^Rollback_Stack_Block, ptr: rawptr) -> bool {
  43. start := raw_data(block.buffer)
  44. end := start[block.offset:]
  45. return start < ptr && ptr <= end
  46. }
  47. @(private="file", require_results)
  48. rb_find_ptr :: proc(stack: ^Rollback_Stack, ptr: rawptr) -> (
  49. parent: ^Rollback_Stack_Block,
  50. block: ^Rollback_Stack_Block,
  51. header: ^Rollback_Stack_Header,
  52. err: Allocator_Error,
  53. ) {
  54. for block = stack.head; block != nil; block = block.next_block {
  55. if rb_ptr_in_bounds(block, ptr) {
  56. header = cast(^Rollback_Stack_Header)(cast(uintptr)ptr - size_of(Rollback_Stack_Header))
  57. return
  58. }
  59. parent = block
  60. }
  61. return nil, nil, nil, .Invalid_Pointer
  62. }
  63. @(private="file", require_results)
  64. rb_find_last_alloc :: proc(stack: ^Rollback_Stack, ptr: rawptr) -> (
  65. block: ^Rollback_Stack_Block,
  66. header: ^Rollback_Stack_Header,
  67. ok: bool,
  68. ) {
  69. for block = stack.head; block != nil; block = block.next_block {
  70. if block.last_alloc == ptr {
  71. header = cast(^Rollback_Stack_Header)(cast(uintptr)ptr - size_of(Rollback_Stack_Header))
  72. return block, header, true
  73. }
  74. }
  75. return nil, nil, false
  76. }
  77. @(private="file")
  78. rb_rollback_block :: proc(block: ^Rollback_Stack_Block, header: ^Rollback_Stack_Header) {
  79. header := header
  80. for block.offset > 0 && header.is_free {
  81. block.offset = header.prev_offset
  82. block.last_alloc = raw_data(block.buffer)[header.prev_ptr:]
  83. header = cast(^Rollback_Stack_Header)(raw_data(block.buffer)[header.prev_ptr - size_of(Rollback_Stack_Header):])
  84. }
  85. }
  86. /*
  87. Free memory to a rollback stack allocator.
  88. */
  89. @(private="file", require_results)
  90. rb_free :: proc(stack: ^Rollback_Stack, ptr: rawptr) -> Allocator_Error {
  91. parent, block, header := rb_find_ptr(stack, ptr) or_return
  92. if header.is_free {
  93. return .Invalid_Pointer
  94. }
  95. header.is_free = true
  96. if block.last_alloc == ptr {
  97. block.offset = header.prev_offset
  98. rb_rollback_block(block, header)
  99. }
  100. if parent != nil && block.offset == 0 {
  101. parent.next_block = block.next_block
  102. runtime.mem_free_with_size(block, size_of(Rollback_Stack_Block) + len(block.buffer), stack.block_allocator)
  103. }
  104. return nil
  105. }
  106. /*
  107. Free all memory owned by the rollback stack allocator.
  108. */
  109. @(private="file")
  110. rb_free_all :: proc(stack: ^Rollback_Stack) {
  111. for block := stack.head.next_block; block != nil; /**/ {
  112. next_block := block.next_block
  113. runtime.mem_free_with_size(block, size_of(Rollback_Stack_Block) + len(block.buffer), stack.block_allocator)
  114. block = next_block
  115. }
  116. stack.head.next_block = nil
  117. stack.head.last_alloc = nil
  118. stack.head.offset = 0
  119. }
  120. /*
  121. Allocate memory using the rollback stack allocator.
  122. */
  123. @(require_results)
  124. rb_alloc :: proc(
  125. stack: ^Rollback_Stack,
  126. size: int,
  127. alignment := DEFAULT_ALIGNMENT,
  128. loc := #caller_location,
  129. ) -> (rawptr, Allocator_Error) {
  130. bytes, err := rb_alloc_bytes_non_zeroed(stack, size, alignment, loc)
  131. if bytes != nil {
  132. zero_slice(bytes)
  133. }
  134. return raw_data(bytes), err
  135. }
  136. /*
  137. Allocate memory using the rollback stack allocator.
  138. */
  139. @(require_results)
  140. rb_alloc_bytes :: proc(
  141. stack: ^Rollback_Stack,
  142. size: int,
  143. alignment := DEFAULT_ALIGNMENT,
  144. loc := #caller_location,
  145. ) -> ([]byte, Allocator_Error) {
  146. bytes, err := rb_alloc_bytes_non_zeroed(stack, size, alignment, loc)
  147. if bytes != nil {
  148. zero_slice(bytes)
  149. }
  150. return bytes, err
  151. }
  152. /*
  153. Allocate non-initialized memory using the rollback stack allocator.
  154. */
  155. @(require_results)
  156. rb_alloc_non_zeroed :: proc(
  157. stack: ^Rollback_Stack,
  158. size: int,
  159. alignment := DEFAULT_ALIGNMENT,
  160. loc := #caller_location,
  161. ) -> (rawptr, Allocator_Error) {
  162. bytes, err := rb_alloc_bytes_non_zeroed(stack, size, alignment, loc)
  163. return raw_data(bytes), err
  164. }
  165. /*
  166. Allocate non-initialized memory using the rollback stack allocator.
  167. */
  168. @(require_results)
  169. rb_alloc_bytes_non_zeroed :: proc(
  170. stack: ^Rollback_Stack,
  171. size: int,
  172. alignment := DEFAULT_ALIGNMENT,
  173. loc := #caller_location,
  174. ) -> (result: []byte, err: Allocator_Error) {
  175. assert(size >= 0, "Size must be positive or zero.", loc)
  176. assert(is_power_of_two(cast(uintptr)alignment), "Alignment must be a power of two.", loc)
  177. parent: ^Rollback_Stack_Block
  178. for block := stack.head; /**/; block = block.next_block {
  179. when !ODIN_DISABLE_ASSERT {
  180. allocated_new_block: bool
  181. }
  182. if block == nil {
  183. if stack.block_allocator.procedure == nil {
  184. return nil, .Out_Of_Memory
  185. }
  186. minimum_size_required := size_of(Rollback_Stack_Header) + size + alignment - 1
  187. new_block_size := max(minimum_size_required, stack.block_size)
  188. block = rb_make_block(new_block_size, stack.block_allocator) or_return
  189. parent.next_block = block
  190. when !ODIN_DISABLE_ASSERT {
  191. allocated_new_block = true
  192. }
  193. }
  194. start := raw_data(block.buffer)[block.offset:]
  195. padding := cast(uintptr)calc_padding_with_header(cast(uintptr)start, cast(uintptr)alignment, size_of(Rollback_Stack_Header))
  196. if block.offset + padding + cast(uintptr)size > cast(uintptr)len(block.buffer) {
  197. when !ODIN_DISABLE_ASSERT {
  198. if allocated_new_block {
  199. panic("Rollback Stack Allocator allocated a new block but did not use it.")
  200. }
  201. }
  202. parent = block
  203. continue
  204. }
  205. header := cast(^Rollback_Stack_Header)(start[padding - size_of(Rollback_Stack_Header):])
  206. ptr := start[padding:]
  207. header^ = {
  208. prev_offset = block.offset,
  209. prev_ptr = uintptr(0) if block.last_alloc == nil else cast(uintptr)block.last_alloc - cast(uintptr)raw_data(block.buffer),
  210. is_free = false,
  211. }
  212. block.last_alloc = ptr
  213. block.offset += padding + cast(uintptr)size
  214. if len(block.buffer) > stack.block_size {
  215. // This block exceeds the allocator's standard block size and is considered a singleton.
  216. // Prevent any further allocations on it.
  217. block.offset = cast(uintptr)len(block.buffer)
  218. }
  219. #no_bounds_check return ptr[:size], nil
  220. }
  221. return nil, .Out_Of_Memory
  222. }
  223. /*
  224. Resize an allocation owned by rollback stack allocator.
  225. */
  226. @(require_results)
  227. rb_resize :: proc(
  228. stack: ^Rollback_Stack,
  229. old_ptr: rawptr,
  230. old_size: int,
  231. size: int,
  232. alignment := DEFAULT_ALIGNMENT,
  233. loc := #caller_location,
  234. ) -> (rawptr, Allocator_Error) {
  235. bytes, err := rb_resize_bytes_non_zeroed(stack, byte_slice(old_ptr, old_size), size, alignment, loc)
  236. if bytes != nil {
  237. if old_ptr == nil {
  238. zero_slice(bytes)
  239. } else if size > old_size {
  240. zero_slice(bytes[old_size:])
  241. }
  242. }
  243. return raw_data(bytes), err
  244. }
  245. /*
  246. Resize an allocation owned by rollback stack allocator.
  247. */
  248. @(require_results)
  249. rb_resize_bytes :: proc(
  250. stack: ^Rollback_Stack,
  251. old_memory: []byte,
  252. size: int,
  253. alignment := DEFAULT_ALIGNMENT,
  254. loc := #caller_location,
  255. ) -> ([]u8, Allocator_Error) {
  256. bytes, err := rb_resize_bytes_non_zeroed(stack, old_memory, size, alignment, loc)
  257. if bytes != nil {
  258. if old_memory == nil {
  259. zero_slice(bytes)
  260. } else if size > len(old_memory) {
  261. zero_slice(bytes[len(old_memory):])
  262. }
  263. }
  264. return bytes, err
  265. }
  266. /*
  267. Resize an allocation owned by rollback stack allocator without explicit
  268. zero-initialization.
  269. */
  270. @(require_results)
  271. rb_resize_non_zeroed :: proc(
  272. stack: ^Rollback_Stack,
  273. old_ptr: rawptr,
  274. old_size: int,
  275. size: int,
  276. alignment := DEFAULT_ALIGNMENT,
  277. loc := #caller_location,
  278. ) -> (rawptr, Allocator_Error) {
  279. bytes, err := rb_resize_bytes_non_zeroed(stack, byte_slice(old_ptr, old_size), size, alignment, loc)
  280. return raw_data(bytes), err
  281. }
  282. /*
  283. Resize an allocation owned by rollback stack allocator without explicit
  284. zero-initialization.
  285. */
  286. @(require_results)
  287. rb_resize_bytes_non_zeroed :: proc(
  288. stack: ^Rollback_Stack,
  289. old_memory: []byte,
  290. size: int,
  291. alignment := DEFAULT_ALIGNMENT,
  292. loc := #caller_location,
  293. ) -> (result: []byte, err: Allocator_Error) {
  294. old_size := len(old_memory)
  295. ptr := raw_data(old_memory)
  296. assert(size >= 0, "Size must be positive or zero.", loc)
  297. assert(old_size >= 0, "Old size must be positive or zero.", loc)
  298. assert(is_power_of_two(cast(uintptr)alignment), "Alignment must be a power of two.", loc)
  299. if ptr != nil {
  300. if block, _, ok := rb_find_last_alloc(stack, ptr); ok {
  301. // `block.offset` should never underflow because it is contingent
  302. // on `old_size` in the first place, assuming sane arguments.
  303. assert(block.offset >= cast(uintptr)old_size, "Rollback Stack Allocator received invalid `old_size`.")
  304. if block.offset + cast(uintptr)size - cast(uintptr)old_size < cast(uintptr)len(block.buffer) {
  305. // Prevent singleton allocations from fragmenting by forbidding
  306. // them to shrink, removing the possibility of overflow bugs.
  307. if len(block.buffer) <= stack.block_size {
  308. block.offset += cast(uintptr)size - cast(uintptr)old_size
  309. }
  310. #no_bounds_check return (ptr)[:size], nil
  311. }
  312. }
  313. }
  314. result = rb_alloc_bytes_non_zeroed(stack, size, alignment) or_return
  315. runtime.mem_copy_non_overlapping(raw_data(result), ptr, old_size)
  316. err = rb_free(stack, ptr)
  317. return
  318. }
  319. @(private="file", require_results)
  320. rb_make_block :: proc(size: int, allocator: Allocator) -> (block: ^Rollback_Stack_Block, err: Allocator_Error) {
  321. buffer := runtime.mem_alloc(size_of(Rollback_Stack_Block) + size, align_of(Rollback_Stack_Block), allocator) or_return
  322. block = cast(^Rollback_Stack_Block)raw_data(buffer)
  323. #no_bounds_check block.buffer = buffer[size_of(Rollback_Stack_Block):]
  324. return
  325. }
  326. /*
  327. Initialize the rollback stack allocator using a fixed backing buffer.
  328. */
  329. rollback_stack_init_buffered :: proc(stack: ^Rollback_Stack, buffer: []byte, location := #caller_location) {
  330. MIN_SIZE :: size_of(Rollback_Stack_Block) + size_of(Rollback_Stack_Header) + size_of(rawptr)
  331. assert(len(buffer) >= MIN_SIZE, "User-provided buffer to Rollback Stack Allocator is too small.", location)
  332. block := cast(^Rollback_Stack_Block)raw_data(buffer)
  333. block^ = {}
  334. #no_bounds_check block.buffer = buffer[size_of(Rollback_Stack_Block):]
  335. stack^ = {}
  336. stack.head = block
  337. stack.block_size = len(block.buffer)
  338. }
  339. /*
  340. Initialize the rollback stack alocator using a backing block allocator.
  341. */
  342. rollback_stack_init_dynamic :: proc(
  343. stack: ^Rollback_Stack,
  344. block_size : int = ROLLBACK_STACK_DEFAULT_BLOCK_SIZE,
  345. block_allocator := context.allocator,
  346. location := #caller_location,
  347. ) -> Allocator_Error {
  348. assert(block_size >= size_of(Rollback_Stack_Header) + size_of(rawptr), "Rollback Stack Allocator block size is too small.", location)
  349. when size_of(int) > 4 {
  350. // It's impossible to specify an argument in excess when your integer
  351. // size is insufficient; check only on platforms with big enough ints.
  352. assert(block_size <= ROLLBACK_STACK_MAX_HEAD_BLOCK_SIZE, "Rollback Stack Allocators cannot support head blocks larger than 2 gigabytes.", location)
  353. }
  354. block := rb_make_block(block_size, block_allocator) or_return
  355. stack^ = {}
  356. stack.head = block
  357. stack.block_size = block_size
  358. stack.block_allocator = block_allocator
  359. return nil
  360. }
  361. /*
  362. Initialize the rollback stack.
  363. */
  364. rollback_stack_init :: proc {
  365. rollback_stack_init_buffered,
  366. rollback_stack_init_dynamic,
  367. }
  368. /*
  369. Destroy a rollback stack.
  370. */
  371. rollback_stack_destroy :: proc(stack: ^Rollback_Stack) {
  372. if stack.block_allocator.procedure != nil {
  373. rb_free_all(stack)
  374. free(stack.head, stack.block_allocator)
  375. }
  376. stack^ = {}
  377. }
  378. /*
  379. Rollback stack allocator.
  380. The Rollback Stack Allocator was designed for the test runner to be fast,
  381. able to grow, and respect the Tracking Allocator's requirement for
  382. individual frees. It is not overly concerned with fragmentation, however.
  383. It has support for expansion when configured with a block allocator and
  384. limited support for out-of-order frees.
  385. Allocation has constant-time best and usual case performance.
  386. At worst, it is linear according to the number of memory blocks.
  387. Allocation follows a first-fit strategy when there are multiple memory
  388. blocks.
  389. Freeing has constant-time best and usual case performance.
  390. At worst, it is linear according to the number of memory blocks and number
  391. of freed items preceding the last item in a block.
  392. Resizing has constant-time performance, if it's the last item in a block, or
  393. the new size is smaller. Naturally, this becomes linear-time if there are
  394. multiple blocks to search for the pointer's owning block. Otherwise, the
  395. allocator defaults to a combined alloc & free operation internally.
  396. Out-of-order freeing is accomplished by collapsing a run of freed items
  397. from the last allocation backwards.
  398. Each allocation has an overhead of 8 bytes and any extra bytes to satisfy
  399. the requested alignment.
  400. */
  401. @(require_results)
  402. rollback_stack_allocator :: proc(stack: ^Rollback_Stack) -> Allocator {
  403. return Allocator {
  404. data = stack,
  405. procedure = rollback_stack_allocator_proc,
  406. }
  407. }
  408. @(require_results)
  409. rollback_stack_allocator_proc :: proc(
  410. allocator_data: rawptr,
  411. mode: Allocator_Mode,
  412. size, alignment: int,
  413. old_memory: rawptr,
  414. old_size: int,
  415. loc := #caller_location,
  416. ) -> (result: []byte, err: Allocator_Error) {
  417. stack := cast(^Rollback_Stack)allocator_data
  418. switch mode {
  419. case .Alloc:
  420. return rb_alloc_bytes(stack, size, alignment, loc)
  421. case .Alloc_Non_Zeroed:
  422. return rb_alloc_bytes_non_zeroed(stack, size, alignment, loc)
  423. case .Free:
  424. return nil, rb_free(stack, old_memory)
  425. case .Free_All:
  426. rb_free_all(stack)
  427. return nil, nil
  428. case .Resize:
  429. return rb_resize_bytes(stack, byte_slice(old_memory, old_size), size, alignment, loc)
  430. case .Resize_Non_Zeroed:
  431. return rb_resize_bytes_non_zeroed(stack, byte_slice(old_memory, old_size), size, alignment, loc)
  432. case .Query_Features:
  433. set := (^Allocator_Mode_Set)(old_memory)
  434. if set != nil {
  435. set^ = {.Alloc, .Alloc_Non_Zeroed, .Free, .Free_All, .Resize, .Resize_Non_Zeroed}
  436. }
  437. return nil, nil
  438. case .Query_Info:
  439. return nil, .Mode_Not_Implemented
  440. }
  441. return
  442. }