1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/memory_map.cc Wed Jan 20 01:37:12 2021 +0100
1.3 @@ -0,0 +1,83 @@
1.4 +#include <stdlib.h>
1.5 +
1.6 +#include "memory_map.h"
1.7 +#include "memory_utils.h"
1.8 +
1.9 +
1.10 +
1.11 +/* Global memory allocator. */
1.12 +
1.13 +Allocator allocator;
1.14 +
1.15 +
1.16 +
1.17 +/* Region management. */
1.18 +
1.19 +void MemoryMap::insert(Region *region)
1.20 +{
1.21 + std::lock_guard<std::mutex> guard(_lock);
1.22 +
1.23 + _regions.insert(_MemoryMapEntry(region->start, region));
1.24 +}
1.25 +
1.26 +void MemoryMap::remove(Region *region)
1.27 +{
1.28 + std::lock_guard<std::mutex> guard(_lock);
1.29 +
1.30 + _MemoryMap::iterator entry = _regions.find(region->start);
1.31 +
1.32 + if (entry != _regions.end())
1.33 + _regions.erase(entry);
1.34 +}
1.35 +
1.36 +/* Show the memory state. */
1.37 +
1.38 +void MemoryMap::show(std::ostringstream &buffer)
1.39 +{
1.40 + std::lock_guard<std::mutex> guard(_lock);
1.41 +
1.42 + _MemoryMap::iterator it;
1.43 +
1.44 + buffer << "Mem: ";
1.45 +
1.46 + for (it = _regions.begin(); it != _regions.end(); it++)
1.47 + {
1.48 + it->second->state.show(buffer);
1.49 + buffer << " ";
1.50 + }
1.51 +
1.52 + buffer << std::endl;
1.53 +}
1.54 +
1.55 +
1.56 +
1.57 +/* Allocate a block of the given 'size'. */
1.58 +
1.59 +Region *Allocator::region(offset_t size)
1.60 +{
1.61 + /* Attempt to allocate aligned memory. */
1.62 +
1.63 + void *current;
1.64 +
1.65 + /* Make the size appropriate for the invocation. */
1.66 +
1.67 + size = round_multiple(size, PAGE_SIZE);
1.68 +
1.69 + if (posix_memalign(¤t, size, size))
1.70 + return NULL;
1.71 +
1.72 + Region *region = new Region((offset_t) current, (offset_t) current + size);
1.73 +
1.74 + insert(region);
1.75 + return region;
1.76 +}
1.77 +
1.78 +/* Release the allocated 'region'. */
1.79 +
1.80 +void Allocator::release(Region *region)
1.81 +{
1.82 + remove(region);
1.83 + delete region;
1.84 +}
1.85 +
1.86 +// vim: tabstop=4 expandtab shiftwidth=4