Mneme
Mneme a tool allowing recording the execution of a GPU (CUDA/HIP) kernel and replaying that kernel as an independent executable.
Loading...
Searching...
No Matches
MnemePageManager.hpp
Go to the documentation of this file.
1#pragma once
2#include <algorithm>
3#include <cerrno>
4#include <cstdint>
5#include <cstring>
6#include <iterator>
7#include <map>
8#include <optional>
9#include <set>
10#include <sys/mman.h>
11#include <unistd.h>
12#include <utility>
13
15#include "mneme/MnemeLogger.hpp"
16#include "mneme/MnemeUtils.hpp"
18
19// Free address ranges with best-fit allocation and coalescing release.
21 using AddrMap = std::map<uintptr_t, uint64_t>;
22 // Start -> size.
23 AddrMap ByAddr;
24 // (Size, start) of the same ranges.
25 std::set<std::pair<uint64_t, uintptr_t>> BySize;
26
27 void insert(uintptr_t Start, uint64_t Size) {
28 ByAddr.emplace(Start, Size);
29 BySize.emplace(Size, Start);
30 }
31
32 AddrMap::iterator erase(AddrMap::iterator It) {
33 BySize.erase({It->second, It->first});
34 return ByAddr.erase(It);
35 }
36
37public:
38 std::optional<uintptr_t> allocate(uint64_t Size, uint64_t Align) {
39 for (auto It = BySize.lower_bound({Size, 0}); It != BySize.end(); ++It) {
40 auto [RangeSize, Start] = *It;
41 uintptr_t Addr = mneme::util::roundUp(Start, Align);
42 uintptr_t End = Start + RangeSize;
43 if (Addr + Size > End)
44 continue;
45 BySize.erase(It);
46 ByAddr.erase(Start);
47 if (Addr > Start)
48 insert(Start, Addr - Start);
49 if (Addr + Size < End)
50 insert(Addr + Size, End - Addr - Size);
51 return Addr;
52 }
53 return std::nullopt;
54 }
55
56 // Merges only with free neighbors inside [Lo, Hi).
57 void release(uintptr_t Start, uint64_t Size, uintptr_t Lo = 0,
58 uintptr_t Hi = UINTPTR_MAX) {
59 uintptr_t End = Start + Size;
60 auto Next = ByAddr.lower_bound(Start);
61 if (Next != ByAddr.end() && Next->first == End && End < Hi) {
62 End += Next->second;
63 Next = erase(Next);
64 }
65 if (Next != ByAddr.begin()) {
66 auto Prev = std::prev(Next);
67 if (Prev->first + Prev->second == Start && Prev->first >= Lo) {
68 Start = Prev->first;
69 erase(Prev);
70 }
71 }
72 insert(Start, End - Start);
73 }
74
75 // Drops the free range that starts at Start.
76 void remove(uintptr_t Start) { erase(ByAddr.find(Start)); }
77};
78
79// Picks device addresses for recorded allocations: first fit above one anchor
80// address, using /proc/self/maps as the free list.
81template <mneme::DeviceVendors VendorTypes> class PageManager {
83 static constexpr uintptr_t MaxAddr = 1ULL << 47;
84
85 uintptr_t Anchor = 0;
86
87 void pickAnchor(uint64_t Size) {
89 if (Addrs.empty())
90 LOG_FATAL("No device address range for {} bytes", Size);
91 Anchor = Addrs.front();
92 LOG_INFO("Device address anchor {}", reinterpret_cast<void *>(Anchor));
93 }
94
95public:
96 // Mapping granularity: large pages, and whole driver VA blocks on CUDA.
97 static constexpr uint64_t Align =
98 std::max(mneme::util::LargePageSize, DT::VABlockSize);
99
100 struct AddrRange {
101 void *Addr;
102 uint64_t Size;
103 uint64_t Align;
104 };
105
106 // Maps a range with Map(Range) at the first free address above the anchor.
107 // Ranges are large-page aligned so they can use big GPU fragments, and cover
108 // whole driver VA blocks. Nullopt when the device is out of memory.
109 template <typename MapFn>
110 std::optional<AddrRange> mapAddr(uint64_t Size, MapFn Map) {
111 uint64_t ActualSize = mneme::util::roundUp(Size, Align);
112
113 if (!Anchor)
114 pickAnchor(ActualSize);
115 auto Addr = mneme::util::firstFreeVAddr(Anchor, MaxAddr, ActualSize, Align);
116 if (!Addr)
117 LOG_FATAL("No device address range for {} bytes", Size);
118 AddrRange R{reinterpret_cast<void *>(*Addr), ActualSize, Align};
119 switch (Map(R)) {
121 return R;
123 return std::nullopt;
125 break;
126 }
127 // Blocked by something /proc/self/maps does not show.
128 LOG_FATAL(
129 "Driver placed {} bytes away from {}:\n{}", Size, R.Addr,
130 mneme::util::getMappingsIn(*Addr - ActualSize, *Addr + 2 * ActualSize));
131 }
132};
133
134// Backing memory for the chunks of a ChunkAllocator.
136public:
137 struct Range {
138 uintptr_t Start;
139 uint64_t Size;
140 };
141
142 // Chunk sizes are multiples of this.
143 virtual uint64_t unit() const = 0;
144 // Alignment and size granularity of allocations inside chunks.
145 virtual uint64_t alignment() const = 0;
146 // Maps one chunk of at least Size bytes. Nullopt when out of memory.
147 virtual std::optional<Range> map(uint64_t Size) = 0;
148 virtual void unmap(uintptr_t Start, uint64_t Size) = 0;
149 // Called before a failed map is retried with a smaller chunk.
150 virtual void discardFailure() {}
151
152 virtual ~ChunkSource() = default;
153};
154
155// Chunks of device memory, each one device mapping.
156template <mneme::DeviceVendors VendorTypes>
157class DeviceChunkSource final : public ChunkSource {
159 using Handle_t = typename DT::MemoryAllocationHandle_t;
160
162 int DeviceID;
163 // Chunk start -> its device memory.
164 std::map<uintptr_t, Handle_t> Handles;
165
166public:
168 : PM(PM), DeviceID(DeviceID) {}
169
170 // Chunks are whole multiples of the page manager's mapping unit.
171 uint64_t unit() const override { return PageManager<VendorTypes>::Align; }
172
173 // Matches the device malloc alignment guarantee.
174 uint64_t alignment() const override { return 256; }
175
176 std::optional<Range> map(uint64_t Size) override {
177 Handle_t H{};
178 auto R = PM.mapAddr(Size, [&](const auto &R) {
179 return DT::mapFixed(R.Addr, R.Size, R.Align, DeviceID, H);
180 });
181 if (!R)
182 return std::nullopt;
183 uintptr_t Start = reinterpret_cast<uintptr_t>(R->Addr);
184 Handles[Start] = H;
185 return Range{Start, R->Size};
186 }
187
188 void unmap(uintptr_t Start, uint64_t Size) override {
189 auto It = Handles.find(Start);
190 DT::unmapFixed(reinterpret_cast<void *>(Start), Size, DeviceID, It->second);
191 Handles.erase(It);
192 }
193
194 // The app sees only the final failure.
195 void discardFailure() override { DT::clearLastError(); }
196};
197
198namespace mneme {
199inline constexpr int ReserveFlags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE;
200} // namespace mneme
201
202// Chunks of reserved address space with no memory behind them. The vendor
203// runtime's own mappings are placed inside them.
204template <mneme::DeviceVendors VendorTypes>
205class ReservedChunkSource final : public ChunkSource {
207 uint64_t PageSize = sysconf(_SC_PAGESIZE);
208
209 static mneme::MapStatus reserve(void *Addr, uint64_t Size) {
210 void *Got = mmap(Addr, Size, PROT_NONE,
211 mneme::ReserveFlags | MAP_FIXED_NOREPLACE, -1, 0);
212 if (Got == Addr)
214 // Kernels before 4.17 treat the address as a hint.
215 if (Got != MAP_FAILED) {
216 munmap(Got, Size);
218 }
219 if (errno == EEXIST)
221 if (errno == ENOMEM)
223 LOG_FATAL("Cannot reserve {} bytes at {}: {}", Size, Addr,
224 std::strerror(errno));
225 }
226
227public:
229
230 uint64_t unit() const override { return PageManager<VendorTypes>::Align; }
231
232 uint64_t alignment() const override { return PageSize; }
233
234 std::optional<Range> map(uint64_t Size) override {
235 auto R =
236 PM.mapAddr(Size, [](const auto &R) { return reserve(R.Addr, R.Size); });
237 if (!R)
238 return std::nullopt;
239 return Range{reinterpret_cast<uintptr_t>(R->Addr), R->Size};
240 }
241
242 void unmap(uintptr_t Start, uint64_t Size) override {
243 if (munmap(reinterpret_cast<void *>(Start), Size))
244 LOG_WARN("Could not unmap {}: {}", reinterpret_cast<void *>(Start),
245 std::strerror(errno));
246 }
247};
248
249// Packs allocations into shared ChunkSize-byte chunks mapped by a ChunkSource,
250// since mapping each allocation separately is slow. Chunks shrink when the
251// source is short on memory. An allocation larger than ChunkSize gets a
252// dedicated chunk that nothing else shares and that is unmapped on release.
254 struct Chunk {
255 uint64_t Size = 0;
256 uint64_t Used = 0;
257 };
258 using ChunkMap = std::map<uintptr_t, Chunk>;
259
260 ChunkSource &Source;
261 uint64_t ChunkSize;
262 // Start -> chunk.
263 ChunkMap Chunks;
264 // Chunks may be adjacent but are separate mappings, so ranges never span two.
265 FreeRanges Free;
266
267 ChunkMap::iterator chunkOf(uintptr_t Addr) {
268 return std::prev(Chunks.upper_bound(Addr));
269 }
270
271 // Shared chunks only shrink from ChunkSize, and a dedicated chunk holds more
272 // than ChunkSize bytes.
273 bool isDedicated(const Chunk &C) const { return C.Size > ChunkSize; }
274
275 void *allocateDedicated(uint64_t Size) {
276 auto R = Source.map(Size);
277 if (!R)
278 return nullptr;
279 LOG_DEBUG("New {}-byte dedicated chunk {}", R->Size,
280 reinterpret_cast<void *>(R->Start));
281 Chunks[R->Start] = {R->Size, Size};
282 return reinterpret_cast<void *>(R->Start);
283 }
284
285 bool mapChunk(uint64_t Size) {
286 auto R = Source.map(Size);
287 if (!R)
288 return false;
289 LOG_DEBUG("New {}-byte allocation chunk {}", R->Size,
290 reinterpret_cast<void *>(R->Start));
291 Chunks[R->Start] = {R->Size, 0};
292 Free.release(R->Start, R->Size, R->Start, R->Start + R->Size);
293 return true;
294 }
295
296 // Halves the chunk while the source lacks memory, down to MinSize.
297 bool growFor(uint64_t MinSize) {
298 uint64_t Unit = Source.unit();
299 uint64_t Min = mneme::util::roundUp(MinSize, Unit);
300 for (uint64_t Size = ChunkSize;;
301 Size = std::max(Min, mneme::util::roundUp(Size / 2, Unit))) {
302 if (mapChunk(Size))
303 return true;
304 if (Size == Min)
305 return false;
306 Source.discardFailure();
307 }
308 }
309
310public:
311 ChunkAllocator(ChunkSource &Source, uint64_t ChunkSize)
312 : Source(Source),
313 ChunkSize(mneme::util::roundUp(ChunkSize, Source.unit())) {}
314
315 uint64_t actualSize(uint64_t Size) const {
316 uint64_t Alignment = Source.alignment();
317 return std::max(mneme::util::roundUp(Size, Alignment), Alignment);
318 }
319
320 // Size must come from actualSize().
321 bool packs(uint64_t Size) const { return Size <= ChunkSize; }
322
323 // Size must come from actualSize(). Nullptr when out of memory.
324 void *allocate(uint64_t Size) {
325 if (!packs(Size))
326 return allocateDedicated(Size);
327 auto Addr = Free.allocate(Size, Source.alignment());
328 if (!Addr) {
329 if (!growFor(Size))
330 return nullptr;
331 Addr = Free.allocate(Size, Source.alignment());
332 }
333 chunkOf(*Addr)->second.Used += Size;
334 return reinterpret_cast<void *>(*Addr);
335 }
336
337 void release(void *Addr, uint64_t Size) {
338 uintptr_t A = reinterpret_cast<uintptr_t>(Addr);
339 auto It = chunkOf(A);
340 auto &C = It->second;
341 uintptr_t Start = It->first;
342 if (isDedicated(C)) {
343 Source.unmap(Start, C.Size);
344 Chunks.erase(It);
345 return;
346 }
347 Free.release(A, Size, Start, Start + C.Size);
348 C.Used -= Size;
349 // One empty chunk stays mapped so malloc/free loops don't remap.
350 if (C.Used || std::none_of(Chunks.begin(), Chunks.end(), [&](auto &E) {
351 return E.first != Start && !E.second.Used;
352 }))
353 return;
354 Free.remove(Start);
355 Source.unmap(Start, C.Size);
356 Chunks.erase(It);
357 }
358
360 for (auto &[Start, C] : Chunks)
361 Source.unmap(Start, C.Size);
362 }
363
366};
#define LOG_INFO(...)
Definition MnemeLogger.hpp:110
#define LOG_DEBUG(...)
Definition MnemeLogger.hpp:109
#define LOG_FATAL(...)
Definition MnemeLogger.hpp:113
#define LOG_WARN(...)
Definition MnemeLogger.hpp:111
int munmap(void *Addr, size_t Len) noexcept
Definition MnemeRecordPreloadHIP.cpp:74
void * mmap(void *Addr, size_t Len, int Prot, int Flags, int Fd, off_t Off) noexcept
Definition MnemeRecordPreloadHIP.cpp:60
uint64_t actualSize(uint64_t Size) const
Definition MnemePageManager.hpp:315
void * allocate(uint64_t Size)
Definition MnemePageManager.hpp:324
~ChunkAllocator()
Definition MnemePageManager.hpp:359
ChunkAllocator & operator=(const ChunkAllocator &)=delete
ChunkAllocator(ChunkSource &Source, uint64_t ChunkSize)
Definition MnemePageManager.hpp:311
bool packs(uint64_t Size) const
Definition MnemePageManager.hpp:321
ChunkAllocator(const ChunkAllocator &)=delete
void release(void *Addr, uint64_t Size)
Definition MnemePageManager.hpp:337
Definition MnemePageManager.hpp:135
virtual void discardFailure()
Definition MnemePageManager.hpp:150
virtual std::optional< Range > map(uint64_t Size)=0
virtual uint64_t alignment() const =0
virtual void unmap(uintptr_t Start, uint64_t Size)=0
virtual uint64_t unit() const =0
virtual ~ChunkSource()=default
DeviceChunkSource(PageManager< VendorTypes > &PM, int DeviceID)
Definition MnemePageManager.hpp:167
uint64_t unit() const override
Definition MnemePageManager.hpp:171
std::optional< Range > map(uint64_t Size) override
Definition MnemePageManager.hpp:176
void discardFailure() override
Definition MnemePageManager.hpp:195
uint64_t alignment() const override
Definition MnemePageManager.hpp:174
void unmap(uintptr_t Start, uint64_t Size) override
Definition MnemePageManager.hpp:188
Definition MnemePageManager.hpp:20
void release(uintptr_t Start, uint64_t Size, uintptr_t Lo=0, uintptr_t Hi=UINTPTR_MAX)
Definition MnemePageManager.hpp:57
void remove(uintptr_t Start)
Definition MnemePageManager.hpp:76
std::optional< uintptr_t > allocate(uint64_t Size, uint64_t Align)
Definition MnemePageManager.hpp:38
Definition MnemePageManager.hpp:81
static constexpr uint64_t Align
Definition MnemePageManager.hpp:97
std::optional< AddrRange > mapAddr(uint64_t Size, MapFn Map)
Definition MnemePageManager.hpp:110
uint64_t unit() const override
Definition MnemePageManager.hpp:230
ReservedChunkSource(PageManager< VendorTypes > &PM)
Definition MnemePageManager.hpp:228
std::optional< Range > map(uint64_t Size) override
Definition MnemePageManager.hpp:234
void unmap(uintptr_t Start, uint64_t Size) override
Definition MnemePageManager.hpp:242
uint64_t alignment() const override
Definition MnemePageManager.hpp:232
int64_t u64 Size
Definition cupti_profile.cpp:179
std::optional< uintptr_t > firstFreeVAddr(uintptr_t Lo, uintptr_t Hi, uint64_t Size, uint64_t Align)
Definition MnemeVASpace.hpp:76
std::string getMappingsIn(uintptr_t Lo, uintptr_t Hi)
Definition MnemeVASpace.hpp:43
constexpr uint64_t LargePageSize
Definition MnemeVASpace.hpp:18
std::vector< uintptr_t > suggestVAddrs(uint64_t Size, uint64_t Alignment)
Definition MnemeVASpace.hpp:88
Ty roundUp(Ty Size, Ty Divider)
Definition MnemeUtils.hpp:16
Definition MnemeAnnotation.cpp:3
constexpr int ReserveFlags
Definition MnemePageManager.hpp:199
MapStatus
Definition DeviceTraits.hpp:71
@ Mapped
Definition DeviceTraits.hpp:71
@ OutOfMemory
Definition DeviceTraits.hpp:71
@ Occupied
Definition DeviceTraits.hpp:71
Definition MnemePageManager.hpp:137
uintptr_t Start
Definition MnemePageManager.hpp:138
uint64_t Size
Definition MnemePageManager.hpp:139
Definition MnemePageManager.hpp:100
uint64_t Size
Definition MnemePageManager.hpp:102
uint64_t Align
Definition MnemePageManager.hpp:103
void * Addr
Definition MnemePageManager.hpp:101
Definition DeviceTraits.hpp:73