1 // Copyright 2019 The Dawn Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #ifndef DAWNNATIVE_BUDDYMEMORYALLOCATOR_H_ 16 #define DAWNNATIVE_BUDDYMEMORYALLOCATOR_H_ 17 18 #include "dawn_native/BuddyAllocator.h" 19 #include "dawn_native/Error.h" 20 #include "dawn_native/ResourceMemoryAllocation.h" 21 22 #include <memory> 23 #include <vector> 24 25 namespace dawn_native { 26 27 class ResourceHeapAllocator; 28 29 // BuddyMemoryAllocator uses the buddy allocator to sub-allocate blocks of device 30 // memory created by MemoryAllocator clients. It creates a very large buddy system 31 // where backing device memory blocks equal a specified level in the system. 32 // 33 // Upon sub-allocating, the offset gets mapped to device memory by computing the corresponding 34 // memory index and should the memory not exist, it is created. If two sub-allocations share the 35 // same memory index, the memory refcount is incremented to ensure de-allocating one doesn't 36 // release the other prematurely. 37 // 38 // The MemoryAllocator should return ResourceHeaps that are all compatible with each other. 39 // It should also outlive all the resources that are in the buddy allocator. 40 class BuddyMemoryAllocator { 41 public: 42 BuddyMemoryAllocator(uint64_t maxSystemSize, 43 uint64_t memoryBlockSize, 44 ResourceHeapAllocator* heapAllocator); 45 ~BuddyMemoryAllocator() = default; 46 47 ResultOrError<ResourceMemoryAllocation> Allocate(uint64_t allocationSize, 48 uint64_t alignment); 49 void Deallocate(const ResourceMemoryAllocation& allocation); 50 51 uint64_t GetMemoryBlockSize() const; 52 53 // For testing purposes. 54 uint64_t ComputeTotalNumOfHeapsForTesting() const; 55 56 private: 57 uint64_t GetMemoryIndex(uint64_t offset) const; 58 59 uint64_t mMemoryBlockSize = 0; 60 61 BuddyAllocator mBuddyBlockAllocator; 62 ResourceHeapAllocator* mHeapAllocator; 63 64 struct TrackedSubAllocations { 65 size_t refcount = 0; 66 std::unique_ptr<ResourceHeapBase> mMemoryAllocation; 67 }; 68 69 std::vector<TrackedSubAllocations> mTrackedSubAllocations; 70 }; 71 72 } // namespace dawn_native 73 74 #endif // DAWNNATIVE_BUDDYMEMORYALLOCATOR_H_ 75