paul@1 | 1 | #include "memory.h" |
paul@1 | 2 | #include "memory_map.h" |
paul@1 | 3 | |
paul@1 | 4 | |
paul@1 | 5 | |
paul@1 | 6 | /* Global memory allocator. */ |
paul@1 | 7 | |
paul@1 | 8 | extern Allocator allocator; |
paul@1 | 9 | |
paul@1 | 10 | |
paul@1 | 11 | |
paul@1 | 12 | /* Initialise the memory pool with an optional 'limit' in pages. */ |
paul@1 | 13 | |
paul@1 | 14 | Memory::Memory(unsigned int limit, offset_t region_size) |
paul@1 | 15 | : _limit(limit), _region_size(region_size) |
paul@1 | 16 | { |
paul@1 | 17 | _limited = true; |
paul@1 | 18 | } |
paul@1 | 19 | |
paul@1 | 20 | Memory::Memory() |
paul@1 | 21 | : _region_size(PAGE_SIZE) |
paul@1 | 22 | { |
paul@1 | 23 | _limited = false; |
paul@1 | 24 | } |
paul@1 | 25 | |
paul@1 | 26 | /* Allocate a new region of the given 'size' rounded to the nearest page. */ |
paul@1 | 27 | |
paul@1 | 28 | Region *Memory::region(offset_t size) |
paul@1 | 29 | { |
paul@1 | 30 | std::lock_guard<std::mutex> guard(_lock); |
paul@1 | 31 | |
paul@1 | 32 | offset_t rounded = round(size, PAGE_SIZE); |
paul@1 | 33 | offset_t pages = rounded / PAGE_SIZE; |
paul@1 | 34 | |
paul@1 | 35 | /* Check for sufficient pages. */ |
paul@1 | 36 | |
paul@1 | 37 | if (!_limited || (_limit >= pages)) |
paul@1 | 38 | { |
paul@1 | 39 | /* Attempt to allocate aligned memory. */ |
paul@1 | 40 | |
paul@1 | 41 | Region *region = allocator.region(rounded); |
paul@1 | 42 | |
paul@1 | 43 | if (region == NULL) |
paul@1 | 44 | return NULL; |
paul@1 | 45 | |
paul@1 | 46 | if (_limited) |
paul@1 | 47 | _limit -= pages; |
paul@1 | 48 | |
paul@1 | 49 | return region; |
paul@1 | 50 | } |
paul@1 | 51 | |
paul@1 | 52 | /* Return no region without sufficient pages. */ |
paul@1 | 53 | |
paul@1 | 54 | else |
paul@1 | 55 | return NULL; |
paul@1 | 56 | } |
paul@1 | 57 | |
paul@1 | 58 | Region *Memory::region() |
paul@1 | 59 | { |
paul@1 | 60 | return region(_region_size); |
paul@1 | 61 | } |
paul@1 | 62 | |
paul@1 | 63 | /* Release the allocated 'region'. */ |
paul@1 | 64 | |
paul@1 | 65 | void Memory::release(Region *region) |
paul@1 | 66 | { |
paul@1 | 67 | std::lock_guard<std::mutex> guard(_lock); |
paul@1 | 68 | |
paul@1 | 69 | offset_t rounded = round(region->size(), PAGE_SIZE); |
paul@1 | 70 | offset_t pages = rounded / PAGE_SIZE; |
paul@1 | 71 | |
paul@1 | 72 | if (_limited) |
paul@1 | 73 | _limit += pages; |
paul@1 | 74 | |
paul@1 | 75 | allocator.remove(region); |
paul@1 | 76 | |
paul@1 | 77 | delete region; |
paul@1 | 78 | } |
paul@1 | 79 | |
paul@1 | 80 | // vim: tabstop=4 expandtab shiftwidth=4 |