1 /* 2 * A memory pool allocating a region at a time from the system. 3 * 4 * Copyright (C) 2021 Paul Boddie <paul@boddie.org.uk> 5 * 6 * This program is free software; you can redistribute it and/or 7 * modify it under the terms of the GNU General Public License as 8 * published by the Free Software Foundation; either version 2 of 9 * the License, or (at your option) any later version. 10 * 11 * This program is distributed in the hope that it will be useful, 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 * GNU General Public License for more details. 15 * 16 * You should have received a copy of the GNU General Public License 17 * along with this program; if not, write to the Free Software 18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, 19 * Boston, MA 02110-1301, USA 20 */ 21 22 #include "memory_incremental.h" 23 24 #include <stdlib.h> 25 26 27 28 /* Initialise the memory pool with an optional 'limit' in pages. */ 29 30 MemoryIncremental::MemoryIncremental(unsigned int limit, offset_t region_size) 31 : _limit(limit), _region_size(region_size) 32 { 33 _limited = true; 34 } 35 36 MemoryIncremental::MemoryIncremental() 37 : _region_size(PAGE_SIZE) 38 { 39 _limited = false; 40 } 41 42 /* Allocate a block of the given 'size'. */ 43 44 Region *MemoryIncremental::allocate(offset_t size) 45 { 46 /* Attempt to allocate aligned memory. */ 47 48 void *current; 49 50 /* Make the size appropriate for the invocation. */ 51 52 size = round_multiple(size, PAGE_SIZE); 53 54 if (posix_memalign(¤t, size, size)) 55 return NULL; 56 57 return new Region((offset_t) current, (offset_t) current + size); 58 } 59 60 /* Allocate a new region of the given 'size' rounded to the nearest page. */ 61 62 Region *MemoryIncremental::region(offset_t size) 63 { 64 std::lock_guard<std::mutex> guard(_lock); 65 66 offset_t rounded = round(size, PAGE_SIZE); 67 offset_t pages = rounded / PAGE_SIZE; 68 69 /* Check for sufficient pages. */ 70 71 if (!_limited || (_limit >= pages)) 72 { 73 /* Attempt to allocate aligned memory. */ 74 75 Region *region = allocate(rounded); 76 77 if (region == NULL) 78 return NULL; 79 80 if (_limited) 81 _limit -= pages; 82 83 return region; 84 } 85 86 /* Return no region without sufficient pages. */ 87 88 else 89 return NULL; 90 } 91 92 /* Allocate a new region having the default region size rounded to the nearest 93 page. */ 94 95 Region *MemoryIncremental::region() 96 { 97 return region(_region_size); 98 } 99 100 /* Release the allocated 'region'. */ 101 102 void MemoryIncremental::release(Region *region) 103 { 104 std::lock_guard<std::mutex> guard(_lock); 105 106 offset_t rounded = round(region->size(), PAGE_SIZE); 107 offset_t pages = rounded / PAGE_SIZE; 108 109 if (_limited) 110 _limit += pages; 111 112 delete region; 113 } 114 115 // vim: tabstop=4 expandtab shiftwidth=4