Skip to content

Commit

Permalink
[VM][PooledAllocator] try reallocation once when OOM (apache#8285)
Browse files Browse the repository at this point in the history
  • Loading branch information
ganler authored and ylc committed Sep 29, 2021
1 parent 42ac8c0 commit b20cd57
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions src/runtime/vm/pooled_allocator.h
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class PooledAllocator final : public Allocator {
~PooledAllocator() { ReleaseAll(); }

Buffer Alloc(size_t nbytes, size_t alignment, DLDataType type_hint) override {
std::lock_guard<std::mutex> lock(mu_);
std::lock_guard<std::recursive_mutex> lock(mu_);
size_t size = ((nbytes + page_size_ - 1) / page_size_) * page_size_;
auto&& it = memory_pool_.find(size);
if (it != memory_pool_.end() && !it->second.empty()) {
Expand All @@ -57,14 +57,22 @@ class PooledAllocator final : public Allocator {
Buffer buf;
buf.device = device_;
buf.size = size;
buf.data = DeviceAPI::Get(device_)->AllocDataSpace(device_, size, alignment, type_hint);
try {
buf.data = DeviceAPI::Get(device_)->AllocDataSpace(device_, size, alignment, type_hint);
} catch (InternalError& err) {
LOG(WARNING) << "PooledAllocator got InternalError during allocation: " << err.message();
LOG(WARNING) << "Trying to release all unused memory and reallocate...";
ReleaseAll();
buf.data = DeviceAPI::Get(device_)->AllocDataSpace(device_, size, alignment, type_hint);
}

used_memory_.fetch_add(size, std::memory_order_relaxed);
DLOG(INFO) << "allocate " << size << " B, used memory " << used_memory_ << " B";
return buf;
}

void Free(const Buffer& buffer) override {
std::lock_guard<std::mutex> lock(mu_);
std::lock_guard<std::recursive_mutex> lock(mu_);
if (memory_pool_.find(buffer.size) == memory_pool_.end()) {
memory_pool_.emplace(buffer.size, std::vector<Buffer>{});
}
Expand All @@ -76,7 +84,7 @@ class PooledAllocator final : public Allocator {

private:
void ReleaseAll() {
std::lock_guard<std::mutex> lock(mu_);
std::lock_guard<std::recursive_mutex> lock(mu_);
for (auto const& it : memory_pool_) {
auto const& pool = it.second;
for (auto const& buf : pool) {
Expand All @@ -92,7 +100,7 @@ class PooledAllocator final : public Allocator {
size_t page_size_;
std::atomic<size_t> used_memory_;
std::unordered_map<size_t, std::vector<Buffer> > memory_pool_;
std::mutex mu_;
std::recursive_mutex mu_;
Device device_;
};

Expand Down

0 comments on commit b20cd57

Please sign in to comment.