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