OLD | NEW |
| (Empty) |
1 // Copyright (c) 2016, the Dartino project authors. Please see the AUTHORS file | |
2 // for details. All rights reserved. Use of this source code is governed by a | |
3 // BSD-style license that can be found in the LICENSE.md file. | |
4 | |
5 #ifndef PLATFORMS_STM_DISCO_FLETCH_SRC_PAGE_ALLOCATOR_H_ | |
6 #define PLATFORMS_STM_DISCO_FLETCH_SRC_PAGE_ALLOCATOR_H_ | |
7 | |
8 #include <cinttypes> | |
9 #include <cstdlib> | |
10 #include <cstring> | |
11 | |
12 #include "platforms/stm/disco_fletch/src/globals.h" | |
13 | |
14 class PageAllocator { | |
15 public: | |
16 PageAllocator() { Initialize(); } | |
17 | |
18 void Initialize() { | |
19 // The initialization must be simple, as it can be called early | |
20 // during startup before the C++-runtime is fully initialized. | |
21 memset(&arenas_, 0, kMaxArenas * sizeof(Arena)); | |
22 } | |
23 | |
24 // Add a section of memory to the allocator. | |
25 // | |
26 // The arguments map and map_size can be used to pass a memory area | |
27 // for the map of allocated/un-allocated pages. This memory area | |
28 // uses one byte per page. If this memory area is not passed or is | |
29 // to small for the number of pages in the area this map will be | |
30 // allocated in the first page in the area. | |
31 // | |
32 // Returns the bit in the arenas bitmap representing this | |
33 // arena. This bit can be used in the call to AllocatePages. | |
34 uint32_t AddArena(const char* name, uintptr_t start, size_t size, | |
35 uint8_t* map = NULL, size_t map_size = 0); | |
36 | |
37 // Allocate pages from an arena. The arenas_bitmap specifies the | |
38 // arenas to try. The default is to only allocate in the initial | |
39 // arena added. | |
40 void* AllocatePages(size_t pages, uint32_t arenas_bitmap = 0x1); | |
41 void FreePages(void* start, size_t pages); | |
42 | |
43 static size_t PagesForBytes(size_t bytes) { | |
44 return ROUNDUP(bytes, PAGE_SIZE) / PAGE_SIZE; | |
45 } | |
46 | |
47 private: | |
48 class Arena { | |
49 public: | |
50 void Initialize(const char* name, uintptr_t start, size_t size, | |
51 uint8_t* map, size_t map_size); | |
52 void* AllocatePages(size_t pages); | |
53 void FreePages(void* start, size_t pages); | |
54 | |
55 bool IsFree() { return pages_ == 0; } | |
56 bool ContainsPageAt(void* start) { | |
57 return base_ <= start && start < base_ + (pages_ << PAGE_SIZE_SHIFT); | |
58 } | |
59 | |
60 private: | |
61 const char* name_; | |
62 size_t pages_; | |
63 uint8_t* base_; | |
64 uint8_t* map_; | |
65 }; | |
66 | |
67 static const int kMaxArenas = 3; | |
68 Arena arenas_[kMaxArenas]; | |
69 }; | |
70 | |
71 #endif // PLATFORMS_STM_DISCO_FLETCH_SRC_PAGE_ALLOCATOR_H_ | |
OLD | NEW |