21#include <llvm/ADT/DenseMap.h>
22#include <llvm/ADT/DenseSet.h>
26template <DeviceVendors VendorTypes>
35 std::unique_ptr<LaunchTimer<VendorTypes>> Timer;
42 llvm::DenseSet<void *> PassthroughAllocs;
46 llvm::DenseMap<void *, ManagedMapping> ManagedBlobs;
47 std::unique_ptr<PageManager<VendorTypes>> PM;
48 std::unique_ptr<DeviceChunkSource<VendorTypes>> DeviceChunks;
49 std::unique_ptr<ChunkAllocator> DevicePacker;
52 std::unique_ptr<ReservedChunkSource<VendorTypes>> ReservedChunks;
53 std::unique_ptr<ChunkAllocator> ReservedPacker;
54 bool WarnedUnpacked =
false;
72 auto arch = MnemeDeviceRT::GetDeviceArch();
73 LOG_DEBUG(
"Initializing system {}", arch);
75 Runtime.origGetDeviceID(&DeviceID);
76 PM = std::make_unique<PageManager<VendorTypes>>();
78 std::make_unique<DeviceChunkSource<VendorTypes>>(*PM, DeviceID);
79 DevicePacker = std::make_unique<ChunkAllocator>(*DeviceChunks,
81 if (MnemeDeviceRT::PlacesManagedMemory) {
82 ReservedChunks = std::make_unique<ReservedChunkSource<VendorTypes>>(*PM);
83 ReservedPacker = std::make_unique<ChunkAllocator>(
91 void addBlob(
void *Ptr, uint64_t ActualSize, uint64_t
Size,
92 std::optional<ManagedMapping> Managed = std::nullopt) {
95 AllocatedBlobs.insert({Ptr, std::move(Blob)});
97 ManagedBlobs.insert({Ptr, *Managed});
101 DeviceError_t dropBlob(
void *Ptr) {
102 auto It = AllocatedBlobs.find(Ptr);
103 auto ret = It->second.release();
104 AllocatedBlobs.erase(It);
105 ManagedBlobs.erase(Ptr);
115 std::optional<OwningBlob> findOwningBlob(
const void *ptr) {
116 auto It = AllocatedBlobs.upper_bound(
const_cast<void *
>(ptr));
117 if (It == AllocatedBlobs.begin())
121 uint64_t Offset =
reinterpret_cast<std::uintptr_t
>(ptr) -
122 reinterpret_cast<std::uintptr_t
>(It->first);
123 if (Offset >= It->second.getSize())
125 return OwningBlob{It, Offset};
129 DeviceError_t releaseBlob(
void *ptr) {
130 const auto &Blob = AllocatedBlobs.find(ptr)->second;
131 uint64_t ActualSize = Blob.getActualSize();
132 LOG_DEBUG(
"Intercepted device Free PTR:{} SIZE:{} ACTUALSIZE:{}", ptr,
133 Blob.getSize(), ActualSize);
134 auto ret = dropBlob(ptr);
135 DevicePacker->release(ptr, ActualSize);
139 void registerExitDrain() {
145 TimedBackend->drainTimer();
157 DeviceError_t launchKernel(
const void *func, dim3 &GridDim, dim3 &BlockDim,
158 void **Args,
size_t SharedMem,
159 DeviceStream_t Stream) {
160 return Runtime.origLaunchKernel(func, GridDim, BlockDim, Args, SharedMem,
165 DeviceError_t timeLaunchKernel(
const void *func, dim3 &GridDim,
166 dim3 &BlockDim,
void **Args,
size_t SharedMem,
167 DeviceStream_t Stream,
171 std::optional<StartedTiming> Started = Timer->begin(Launch, Stream);
172 auto ret = launchKernel(func, GridDim, BlockDim, Args, SharedMem, Stream);
174 Timer->end(*Started, ret);
181 DeviceError_t captureManagedAlloc(
void **ptr,
size_t size,
182 unsigned int flags) {
183 const char *api = MnemeDeviceRT::getManagedMallocFnName();
184 getOrCreatePageManager();
189 ret = Runtime.origMallocManaged(ptr, size, flags);
190 Placed = Placement.
placed();
192 if (ret != MnemeDeviceRT::DeviceSuccess)
195 LOG_FATAL(
"{} returned PTR:{} SIZE:{} outside the mapping Mneme placed "
196 "at {} SIZE:{}; this runtime does not map the allocation with "
197 "its own anonymous mmap, so Mneme cannot record it",
198 api, *ptr, size,
reinterpret_cast<void *
>(Placed.
Start),
201 addBlob(*ptr, DevicePacker->actualSize(size), size, Placed);
202 LOG_DEBUG(
"Intercepted {} PTR:{} SIZE:{} MAPPING:{} MAPPINGSIZE:{}", api,
203 *ptr, size,
reinterpret_cast<void *
>(Placed.
Start), Placed.
Size);
210 template <
typename FreeFn>
211 DeviceError_t releaseManagedBlob(
void *ptr,
const char *api, FreeFn Free) {
220 if (ret != MnemeDeviceRT::DeviceSuccess) {
222 LOG_FATAL(
"{} failed after unmapping PTR:{} MAPPING:{} SIZE:{}, so "
223 "Mneme can no longer record it",
224 api, ptr,
reinterpret_cast<void *
>(Mapping.
Start),
229 LOG_FATAL(
"{} did not unmap the mapping at {} SIZE:{} of PTR:{} before "
230 "returning, so Mneme cannot keep its addresses reserved and "
231 "cannot record managed memory with this runtime",
232 api,
reinterpret_cast<void *
>(Mapping.
Start), Mapping.
Size,
234 LOG_DEBUG(
"Forwarded free of captured managed allocation PTR:{}", ptr);
236 ReservedPacker->release(
reinterpret_cast<void *
>(Mapping.
Start),
237 ReservedPacker->actualSize(Mapping.
Size));
244 DB(
Config::get().getDataDirectory(),
Config::get().EpilogueType,
245 Config::get().CopySource,
Config::get().KernelTiming) {}
248 auto It = AllocatedBlobs.find(
const_cast<void *
>(ptr));
249 if (It == AllocatedBlobs.end())
250 LOG_FATAL(
"annotation ptr={} tag={} is not the start of a recorded "
251 "allocation; annotate a pointer inside one with its size in "
253 ptr, md.
tag.value_or(
"no_tag"));
255 auto &Blob = It->second;
256 auto Status = Blob.setAnnotation({0, Blob.getSize()}, md);
258 LOG_FATAL(
"annotation {} ptr={} size={} builtin={} tag={}",
260 static_cast<unsigned>(md.
builtin), md.
tag.value_or(
"no_tag"));
266 auto Owner = findOwningBlob(ptr);
268 LOG_FATAL(
"region annotation ptr={} bytes={} tag={} is not inside a "
269 "recorded allocation",
270 ptr, bytes, md.
tag.value_or(
"no_tag"));
272 auto &[BasePtr, Blob] = *Owner->It;
273 auto Status = Blob.setAnnotation({Owner->Offset, bytes}, md);
275 LOG_FATAL(
"region annotation {} ptr={} base_ptr={} offset={} bytes={} "
276 "blob_size={} builtin={} elem_size={} tag={}",
278 bytes, Blob.getSize(),
static_cast<unsigned>(md.
builtin),
287 auto It = AllocatedBlobs.find(
const_cast<void *
>(ptr));
288 if (It == AllocatedBlobs.end())
291 md = It->second.annotationAt(0).MD;
299 auto It = AllocatedBlobs.find(
const_cast<void *
>(ptr));
300 if (It == AllocatedBlobs.end())
303 It->second.resetAnnotations();
307 DeviceError_t
rtMalloc(
void **ptr,
size_t size)
override {
310 auto ret = Runtime.origMallocDevice(ptr, 0);
311 if (ret == MnemeDeviceRT::DeviceSuccess)
316 getOrCreatePageManager();
318 uint64_t ActualSize = DevicePacker->actualSize(size);
319 if (!DevicePacker->packs(ActualSize) && !WarnedUnpacked) {
320 LOG_WARN(
"Mapping {}-byte allocation separately; raise "
321 "MNEME_CHUNK_SIZE to pack it",
323 WarnedUnpacked =
true;
325 *ptr = DevicePacker->allocate(ActualSize);
327 return MnemeDeviceRT::DeviceOutOfMemory;
328 addBlob(*ptr, ActualSize, size);
329 LOG_DEBUG(
"Intercepted Device Malloc PTR:{} SIZE:{} ACTUALSIZE:{}", *ptr,
331 return MnemeDeviceRT::DeviceSuccess;
335 unsigned int flags)
override {
336 if (MnemeDeviceRT::PlacesManagedMemory && size != 0)
337 return captureManagedAlloc(ptr, size, flags);
339 auto ret = Runtime.origMallocManaged(ptr, size, flags);
340 if (ret == MnemeDeviceRT::DeviceSuccess)
342 MnemeDeviceRT::getManagedMallocFnName());
347 unsigned int flags)
override {
348 auto ret = Runtime.origMallocPinned(ptr, size, flags);
349 if (ret == MnemeDeviceRT::DeviceSuccess)
357 PassthroughAllocs.insert(ptr);
358 LOG_DEBUG(
"Intercepted {} PTR:{} SIZE:{}; will not be able to replay "
359 "Kernels accessing it",
363 DeviceError_t
rtFree(
void *ptr)
override {
364 if (ptr ==
nullptr) {
365 LOG_WARN(
"Mneme was instructed to de-allocate nullptr..., skipping");
366 return MnemeDeviceRT::DeviceSuccess;
368 if (ManagedBlobs.contains(ptr))
369 return releaseManagedBlob(ptr, MnemeDeviceRT::getDeviceFreeFnName(),
370 [&] {
return Runtime.origFreeDevice(ptr); });
371 if (!AllocatedBlobs.count(ptr)) {
372 if (PassthroughAllocs.erase(ptr)) {
373 LOG_DEBUG(
"Forwarding free of vendor runtime allocation PTR:{}", ptr);
374 return Runtime.origFreeDevice(ptr);
376 LOG_CRITICAL(
"Free address that is not being allocated through Mneme {}",
378 LOG_FATAL(
"Free address that is not being allocated through Mneme\n");
382 auto ret = MnemeDeviceRT::DeviceSynchronize();
383 if (ret != MnemeDeviceRT::DeviceSuccess) {
384 LOG_WARN(
"Not freeing PTR:{}: device synchronize failed", ptr);
387 return releaseBlob(ptr);
390 DeviceError_t
rtFreeAsync(
void *ptr, DeviceStream_t stream)
override {
391 if (ManagedBlobs.contains(ptr))
392 return releaseManagedBlob(ptr, MnemeDeviceRT::getAsyncFreeFnName(), [&] {
393 return Runtime.origFreeAsync(ptr, stream);
395 if (AllocatedBlobs.count(ptr)) {
399 auto ret = MnemeDeviceRT::DeviceStreamSynchronize(stream);
400 if (ret != MnemeDeviceRT::DeviceSuccess) {
401 LOG_WARN(
"Not freeing PTR:{}: stream synchronize failed", ptr);
404 return releaseBlob(ptr);
406 if (ptr ==
nullptr || PassthroughAllocs.erase(ptr))
407 LOG_DEBUG(
"Forwarding async free of vendor runtime allocation PTR:{}",
411 LOG_WARN(
"Forwarding async free of unknown address PTR:{}", ptr);
412 return Runtime.origFreeAsync(ptr, stream);
416 if (ManagedBlobs.contains(ptr))
417 return releaseManagedBlob(ptr, MnemeDeviceRT::getPinnedFreeFnName(),
418 [&] {
return Runtime.origFreeHost(ptr); });
419 PassthroughAllocs.erase(ptr);
420 auto ret = Runtime.origFreeHost(ptr);
421 LOG_DEBUG(
"Free pinned address:{}", ptr);
426 void **Args,
size_t SharedMem,
427 DeviceStream_t Stream)
override {
428 getOrCreatePageManager();
430 auto Launch = DB.registerLaunch(func, GridDim, BlockDim, SharedMem);
432 LOG_DEBUG(
"Kernel {} has no record", func);
433 return launchKernel(func, GridDim, BlockDim, Args, SharedMem, Stream);
435 const std::string &KernelName = DB.kernelName(Launch->
StaticHash);
437 bool InRecordingScope =
440 auto CaptureEpilogue =
441 InRecordingScope ? DB.takeSnapshot<VendorTypes>(
442 func, *Launch, AllocatedBlobs, Args, Stream)
445 LOG_INFO(
"Successfully Recorded Prologue of Kernel {} NAME:{} GRID:({}, "
449 func, KernelName, GridDim.x, GridDim.y, GridDim.z, BlockDim.x,
450 BlockDim.y, BlockDim.z, SharedMem);
452 Timer ? timeLaunchKernel(func, GridDim, BlockDim, Args, SharedMem,
454 : launchKernel(func, GridDim, BlockDim, Args, SharedMem, Stream);
455 if (CaptureEpilogue) {
456 (*CaptureEpilogue)();
457 LOG_INFO(
"Successfully Recorded Epilogue of Kernel {} NAME:{} GRID:({}, "
461 func, KernelName, GridDim.x, GridDim.y, GridDim.z, BlockDim.x,
462 BlockDim.y, BlockDim.z, SharedMem);
464 DB.writeKernelJSON(Launch->StaticHash);
470 auto ret = Runtime.origSetDeviceID(deviceID);
471 if (DeviceID == -1) {
473 }
else if (PM ==
nullptr) {
475 }
else if (deviceID == DeviceID) {
477 }
else if (DeviceID != -1 && PM !=
nullptr) {
486 return Runtime.origGetDeviceID(deviceID);
490 if (TimedBackend ==
this)
491 TimedBackend =
nullptr;
494 LOG_DEBUG(
"RecordingBackend destructor: releasing {} blobs",
495 AllocatedBlobs.size());
498 for (
auto &Entry : AllocatedBlobs) {
499 auto &Blob = Entry.second;
500 if (Blob.getBlobAddr() !=
nullptr) {
501 LOG_DEBUG(
"Releasing blob at addr={} during recorder cleanup",
507 DevicePacker.reset();
508 DeviceChunks.reset();
511 if (!ManagedBlobs.empty()) {
512 (void)ReservedPacker.release();
513 (void)ReservedChunks.release();
515 ReservedPacker.reset();
516 ReservedChunks.reset();
519 LOG_DEBUG(
"RecordingBackend destructor complete");
#define LOG_INFO(...)
Definition MnemeLogger.hpp:110
#define LOG_CRITICAL(...)
Definition MnemeLogger.hpp:112
#define LOG_DEBUG(...)
Definition MnemeLogger.hpp:109
#define LOG_FATAL(...)
Definition MnemeLogger.hpp:113
#define LOG_WARN(...)
Definition MnemeLogger.hpp:111
Definition MnemePageManager.hpp:81
Definition MnemeConfig.hpp:288
const FilterMode RecordingFilterMode
Definition MnemeConfig.hpp:297
static Config & get()
Definition MnemeConfig.hpp:290
Definition MnemeMemory.hpp:227
void mapInto(void *VA)
Definition MnemeMemory.hpp:415
Definition MnemeManagedPlacement.hpp:55
const ManagedMapping & placed() const
Definition MnemeManagedPlacement.hpp:76
Definition MnemeSnapshot.hpp:479
Definition MnemeRecorderBackend.hpp:48
DeviceTraits< VendorTypes > MnemeDeviceRT
Definition MnemeRecorderBackend.hpp:50
typename MnemeDeviceRT::DeviceError_t DeviceError_t
Definition MnemeRecorderBackend.hpp:51
typename MnemeDeviceRT::DeviceStream_t DeviceStream_t
Definition MnemeRecorderBackend.hpp:52
DeviceError_t rtGetDevice(int *deviceID) override
Definition MnemeRecordingBackend.hpp:485
DeviceError_t rtFree(void *ptr) override
Definition MnemeRecordingBackend.hpp:363
DeviceError_t rtFreeAsync(void *ptr, DeviceStream_t stream) override
Definition MnemeRecordingBackend.hpp:390
DeviceError_t rtLaunchKernel(const void *func, dim3 &GridDim, dim3 &BlockDim, void **Args, size_t SharedMem, DeviceStream_t Stream) override
Definition MnemeRecordingBackend.hpp:425
bool getMetadataForPointer(const void *ptr, Metadata &md) const override
Definition MnemeRecordingBackend.hpp:283
DeviceError_t rtHostMalloc(void **ptr, size_t size, unsigned int flags) override
Definition MnemeRecordingBackend.hpp:346
~RecordingBackend()
Definition MnemeRecordingBackend.hpp:489
DeviceError_t rtHostFree(void *ptr) override
Definition MnemeRecordingBackend.hpp:415
DeviceError_t rtManagedMalloc(void **ptr, size_t size, unsigned int flags) override
Definition MnemeRecordingBackend.hpp:334
bool eraseMetadataForPointer(const void *ptr) override
Definition MnemeRecordingBackend.hpp:295
RecordingBackend()
Definition MnemeRecordingBackend.hpp:242
bool setMetadataForPointer(const void *ptr, Metadata md) override
Definition MnemeRecordingBackend.hpp:247
void trackPassthroughAlloc(void *ptr, size_t size, const char *api) override
Definition MnemeRecordingBackend.hpp:354
bool setMetadataForRegion(const void *ptr, size_t bytes, Metadata md) override
Definition MnemeRecordingBackend.hpp:264
DeviceError_t rtMalloc(void **ptr, size_t size) override
Definition MnemeRecordingBackend.hpp:307
DeviceError_t rtSetDevice(int deviceID) override
Definition MnemeRecordingBackend.hpp:469
Definition MnemeManagedPlacement.hpp:84
bool wasUnmapped() const
Definition MnemeManagedPlacement.hpp:101
int64_t u64 Size
Definition cupti_profile.cpp:179
bool scopeAllowsRecording(const void *Kernel) noexcept
Definition MnemeRecordScope.cpp:28
Definition MnemeAnnotation.cpp:3
const char * describeAnnotationStatus(AnnotationStatus Status)
Definition MnemeMemory.hpp:105
@ Scoped
Definition MnemeConfig.hpp:25
constexpr std::size_t builtinByteWidth(BuiltinDType builtin)
Definition MnemeAnnotation.hpp:54
std::unique_ptr< LaunchTimer< VendorTypes > > createLaunchTimer(KernelTimingType Type)
Definition MnemeLaunchTimer.hpp:100
@ Ok
Definition MnemeMemory.hpp:97
std::map< void *, MnemeMemoryBlob< VendorTypes > > BlobsByAddress
Definition MnemeMemory.hpp:605
Definition MnemeSnapshot.hpp:50
uint64_t StaticHash
Definition MnemeSnapshot.hpp:51
Definition MnemeLaunchTimer.hpp:24
Definition MnemeManagedPlacement.hpp:15
uint64_t Size
Definition MnemeManagedPlacement.hpp:17
bool contains(const void *Ptr, uint64_t Bytes) const
Definition MnemeManagedPlacement.hpp:19
uintptr_t Start
Definition MnemeManagedPlacement.hpp:16
Definition MnemeRecorderBackend.hpp:10