Skip to content

Commit c8986d1

Browse files
authored
[Offload] Guard olMemAlloc/Free with a mutex (#153786)
Both these functions update an `AllocInfoMap` structure in the context, however they did not use any locks, causing random failures in threaded code. Now they use a mutex.
1 parent 4c29521 commit c8986d1

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

offload/liboffload/src/OffloadImpl.cpp

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@ struct OffloadContext {
125125
bool TracingEnabled = false;
126126
bool ValidationEnabled = true;
127127
DenseMap<void *, AllocInfo> AllocInfoMap{};
128+
std::mutex AllocInfoMapMutex{};
128129
SmallVector<ol_platform_impl_t, 4> Platforms{};
129130
size_t RefCount;
130131

@@ -534,26 +535,33 @@ Error olMemAlloc_impl(ol_device_handle_t Device, ol_alloc_type_t Type,
534535
return Alloc.takeError();
535536

536537
*AllocationOut = *Alloc;
537-
OffloadContext::get().AllocInfoMap.insert_or_assign(*Alloc,
538-
AllocInfo{Device, Type});
538+
{
539+
std::lock_guard<std::mutex> Lock(OffloadContext::get().AllocInfoMapMutex);
540+
OffloadContext::get().AllocInfoMap.insert_or_assign(
541+
*Alloc, AllocInfo{Device, Type});
542+
}
539543
return Error::success();
540544
}
541545

542546
Error olMemFree_impl(void *Address) {
543-
if (!OffloadContext::get().AllocInfoMap.contains(Address))
544-
return createOffloadError(ErrorCode::INVALID_ARGUMENT,
545-
"address is not a known allocation");
547+
ol_device_handle_t Device;
548+
ol_alloc_type_t Type;
549+
{
550+
std::lock_guard<std::mutex> Lock(OffloadContext::get().AllocInfoMapMutex);
551+
if (!OffloadContext::get().AllocInfoMap.contains(Address))
552+
return createOffloadError(ErrorCode::INVALID_ARGUMENT,
553+
"address is not a known allocation");
546554

547-
auto AllocInfo = OffloadContext::get().AllocInfoMap.at(Address);
548-
auto Device = AllocInfo.Device;
549-
auto Type = AllocInfo.Type;
555+
auto AllocInfo = OffloadContext::get().AllocInfoMap.at(Address);
556+
Device = AllocInfo.Device;
557+
Type = AllocInfo.Type;
558+
OffloadContext::get().AllocInfoMap.erase(Address);
559+
}
550560

551561
if (auto Res =
552562
Device->Device->dataDelete(Address, convertOlToPluginAllocTy(Type)))
553563
return Res;
554564

555-
OffloadContext::get().AllocInfoMap.erase(Address);
556-
557565
return Error::success();
558566
}
559567

0 commit comments

Comments
 (0)