1 /* 2 * A memory pool providing regions from a preallocated amount of memory. 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_preallocated.h" 23 24 #include <l4/cxx/exceptions> 25 26 27 28 /* Initialise the memory pool with the given amount in bytes. */ 29 30 MemoryPreallocated::MemoryPreallocated(Memory *memory, offset_t amount) 31 : _memory(memory), _amount(amount) 32 { 33 offset_t remaining = amount; 34 35 while (remaining) 36 { 37 Region *region = memory->region(); 38 39 if (region == NULL) 40 throw L4::Out_of_memory(); 41 42 _regions.push_back(region); 43 44 remaining -= memory->region_size(); 45 } 46 } 47 48 /* Discard all unused regions. */ 49 50 MemoryPreallocated::~MemoryPreallocated() 51 { 52 while (!_regions.empty()) 53 { 54 Region *region = _regions.front(); 55 56 _regions.pop_front(); 57 _memory->release(region); 58 } 59 } 60 61 /* Obtain an allocated region. */ 62 63 Region *MemoryPreallocated::region() 64 { 65 std::lock_guard<std::mutex> guard(_lock); 66 67 if (_regions.empty()) 68 return NULL; 69 70 Region *region = _regions.front(); 71 72 _regions.pop_front(); 73 return region; 74 } 75 76 /* Release the allocated 'region'. */ 77 78 void MemoryPreallocated::release(Region *region) 79 { 80 std::lock_guard<std::mutex> guard(_lock); 81 82 _regions.push_back(region); 83 } 84 85 // vim: tabstop=4 expandtab shiftwidth=4