1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/memory_incremental.cc Sat Mar 20 01:41:43 2021 +0100
1.3 @@ -0,0 +1,71 @@
1.4 +#include "memory_incremental.h"
1.5 +
1.6 +/* Initialise the memory pool with an optional 'limit' in pages. */
1.7 +
1.8 +MemoryIncremental::MemoryIncremental(unsigned int limit, offset_t region_size)
1.9 +: Memory(region_size), _limit(limit)
1.10 +{
1.11 + _limited = true;
1.12 +}
1.13 +
1.14 +MemoryIncremental::MemoryIncremental()
1.15 +: Memory()
1.16 +{
1.17 + _limited = false;
1.18 +}
1.19 +
1.20 +/* Allocate a new region of the configured size rounded to the nearest page. */
1.21 +
1.22 +Region *MemoryIncremental::region()
1.23 +{
1.24 + return region(_region_size);
1.25 +}
1.26 +
1.27 +/* Allocate a new region of the given 'size' rounded to the nearest page. */
1.28 +
1.29 +Region *MemoryIncremental::region(offset_t size)
1.30 +{
1.31 + std::lock_guard<std::mutex> guard(_lock);
1.32 +
1.33 + offset_t rounded = round(size, PAGE_SIZE);
1.34 + offset_t pages = rounded / PAGE_SIZE;
1.35 +
1.36 + /* Check for sufficient pages. */
1.37 +
1.38 + if (!_limited || (_limit >= pages))
1.39 + {
1.40 + /* Attempt to allocate aligned memory. */
1.41 +
1.42 + Region *region = allocate(rounded);
1.43 +
1.44 + if (region == NULL)
1.45 + return NULL;
1.46 +
1.47 + if (_limited)
1.48 + _limit -= pages;
1.49 +
1.50 + return region;
1.51 + }
1.52 +
1.53 + /* Return no region without sufficient pages. */
1.54 +
1.55 + else
1.56 + return NULL;
1.57 +}
1.58 +
1.59 +/* Release the allocated 'region'. */
1.60 +
1.61 +void MemoryIncremental::release(Region *region)
1.62 +{
1.63 + std::lock_guard<std::mutex> guard(_lock);
1.64 +
1.65 + offset_t rounded = round(region->size(), PAGE_SIZE);
1.66 + offset_t pages = rounded / PAGE_SIZE;
1.67 +
1.68 + if (_limited)
1.69 + _limit += pages;
1.70 +
1.71 + delete region;
1.72 +}
1.73 +
1.74 +// vim: tabstop=4 expandtab shiftwidth=4