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