Skip to content

Commit

Permalink
Add free region manager
Browse files Browse the repository at this point in the history
  • Loading branch information
wheremyfoodat committed Nov 30, 2024
1 parent f4d6299 commit e593fb6
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
2 changes: 1 addition & 1 deletion third_party/host_memory/host_memory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@

#include "align.hpp"
#include <host_memory/host_memory.h>
// #include "common/free_region_manager.h"
#include <host_memory/free_region_manager.h>

namespace Common {

Expand Down
55 changes: 55 additions & 0 deletions third_party/host_memory/include/host_memory/free_region_manager.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <mutex>
#include <boost/icl/interval_set.hpp>

namespace Common {

class FreeRegionManager {
public:
explicit FreeRegionManager() = default;
~FreeRegionManager() = default;

void SetAddressSpace(void* start, size_t size) {
this->FreeBlock(start, size);
}

std::pair<void*, size_t> FreeBlock(void* block_ptr, size_t size) {
std::scoped_lock lk(m_mutex);

// Check to see if we are adjacent to any regions.
auto start_address = reinterpret_cast<uintptr_t>(block_ptr);
auto end_address = start_address + size;
auto it = m_free_regions.find({start_address - 1, end_address + 1});

// If we are, join with them, ensuring we stay in bounds.
if (it != m_free_regions.end()) {
start_address = std::min(start_address, it->lower());
end_address = std::max(end_address, it->upper());
}

// Free the relevant region.
m_free_regions.insert({start_address, end_address});

// Return the adjusted pointers.
block_ptr = reinterpret_cast<void*>(start_address);
size = end_address - start_address;
return {block_ptr, size};
}

void AllocateBlock(void* block_ptr, size_t size) {
std::scoped_lock lk(m_mutex);

auto address = reinterpret_cast<uintptr_t>(block_ptr);
m_free_regions.subtract({address, address + size});
}

private:
std::mutex m_mutex;
boost::icl::interval_set<uintptr_t> m_free_regions;
};

} // namespace Common

0 comments on commit e593fb6

Please sign in to comment.