main
 1#ifndef KC_HEADER_PLATFORM_MEMORY_INCLUDED
 2#define KC_HEADER_PLATFORM_MEMORY_INCLUDED
 3
 4#include "./info.h"
 5#include "../types/types.h"
 6#include "../memory/units.h"
 7
 8#if KC_PLATFORM_LINUX
 9	#define KC_PLATFORM_MEM_PAGESIZE KiB(4)
10#elif KC_PLATFORM_WINDOWS
11	#define KC_PLATFORM_MEM_PAGESIZE KiB(4)
12#else
13	#error Unknown platform. Page size can not be known.
14#endif
15
16/* This aligns a number to a power of 2. 'p' must be a power of 2. */
17#define ROUND_UP_TO_A_POW2(n, p) (((u64)(n) + ((u64)(p) - 1)) & (~((u64)(p) - 1)))
18
19status kc_platform_mem_va_reserve( void** outptr, u64 amount );
20status kc_platform_mem_va_release( void* start, u64 amount );
21
22status kc_platform_mem_va_commit( void* start, u64 amount );
23status kc_platform_mem_va_uncommit( void* start, u64 amount );
24
25
26#ifdef KC_IMPLEMENT
27
28	#if defined(KC_USE_PLATFORM_LIBC)
29		#if defined(KC_PLATFORM_LINUX)
30			#include <sys/mman.h>
31
32			status kc_platform_mem_va_reserve( void** outptr, u64 amount ) {
33				void* res = mmap( 0, amount, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0 );
34				if( res == MAP_FAILED ) {
35					return ERROR_PLATFORM_MAPPING_FAILED;
36				}
37				*outptr = res;
38				return STATUS_SUCCESS;
39			}
40
41			status kc_platform_mem_va_release( void* start, u64 amount ) {
42				i32 res = munmap( start, amount );
43
44				if( res != 0 ) { return ERROR_PLATFORM_MAPPING_FAILED; }
45
46				return STATUS_SUCCESS;
47			}
48
49			status kc_platform_mem_va_commit( void* start, u64 amount ) {
50				i32 res = mprotect( start, amount, PROT_READ | PROT_WRITE );
51
52				if( res != 0 ) { return ERROR_PLATFORM_MEMORY_PERMISSION_CHANGE_FAILED; };
53
54				return STATUS_SUCCESS;
55			}
56
57			status kc_platform_mem_va_uncommit( void* start, u64 amount ) {
58				i32 res = mprotect( start, amount, PROT_NONE );
59				if( res != 0 ) { return ERROR_PLATFORM_MEMORY_PERMISSION_CHANGE_FAILED; };
60
61				res = madvise( start, amount, MADV_DONTNEED);
62
63				if( res != 0 ) { return ERROR_PLATFORM_MEMORY_HINT_CHANGE_FAILED; };
64
65				return STATUS_SUCCESS;
66			}
67
68
69		#elif KC_PLATFORM_WINDOWS
70			#error Windows is not yet supported for memory arenas.
71		#elif KC_USE_PLATFORM_LIBC
72			#error Using libc for memory arenas is currently unsupported.
73			#warning Make sure malloc does not commit all the allocated memory immediately or else code may use unexpected amounts of memory (or just crash).
74		#else
75			#error Current platform does not have a memory arena implementation.
76		#endif
77	#else
78		#error No platform currently implements memory management without libc.
79	#endif
80
81#endif
82
83#endif