1 #include <stdlib.h> 2 3 #include "memory_map.h" 4 #include "memory_utils.h" 5 6 7 8 /* Global memory allocator. */ 9 10 Allocator allocator; 11 12 13 14 /* Region management. */ 15 16 void MemoryMap::insert(Region *region) 17 { 18 std::lock_guard<std::mutex> guard(_lock); 19 20 _regions.insert(_MemoryMapEntry(region->start, region)); 21 } 22 23 void MemoryMap::remove(Region *region) 24 { 25 std::lock_guard<std::mutex> guard(_lock); 26 27 _MemoryMap::iterator entry = _regions.find(region->start); 28 29 if (entry != _regions.end()) 30 _regions.erase(entry); 31 } 32 33 /* Show the memory state. */ 34 35 void MemoryMap::show(std::ostringstream &buffer) 36 { 37 std::lock_guard<std::mutex> guard(_lock); 38 39 _MemoryMap::iterator it; 40 41 buffer << "Mem: "; 42 43 for (it = _regions.begin(); it != _regions.end(); it++) 44 { 45 it->second->state.show(buffer); 46 buffer << " "; 47 } 48 49 buffer << std::endl; 50 } 51 52 53 54 /* Allocate a block of the given 'size'. */ 55 56 Region *Allocator::region(offset_t size) 57 { 58 /* Attempt to allocate aligned memory. */ 59 60 void *current; 61 62 /* Make the size appropriate for the invocation. */ 63 64 size = round_multiple(size, PAGE_SIZE); 65 66 if (posix_memalign(¤t, size, size)) 67 return NULL; 68 69 Region *region = new Region((offset_t) current, (offset_t) current + size); 70 71 insert(region); 72 return region; 73 } 74 75 /* Release the allocated 'region'. */ 76 77 void Allocator::release(Region *region) 78 { 79 remove(region); 80 delete region; 81 } 82 83 // vim: tabstop=4 expandtab shiftwidth=4