Files
reims-vgpu/guest/bundle/tests/slab_tests.cpp
T
Anees Iqbal d27ab921c2 🐎 Start a class with no slab again at its first size
A class's next slab doubled with each slab it made, up to kSlabMax, and never
came down once its slabs went. A buffer of a page that came after its class
had grown and let go took a slab of the largest size the class reached: 2 MiB
from the region or the process's pages, and 16 MiB from the Shared pool, which
the host zeroes as it gives it. Keeping empty slabs (the commit before) stops
this for a buffer made and freed again and again, but not for one that comes
more than 2 s after its class's last slab went.

Now a class left with no slab, none holding a buffer and none kept, starts
again from kSlabFirst (128 KiB), over every source. While it keeps an empty
slab it goes on growing as before.

What changes for the guest: after an idle let-go, a class's next slab is 128
KiB, or twice its buffer, rather than the size the class grew to, so its
heap's size and the buffers' GPU addresses in it differ, and the host takes
and zeroes a smaller block. test_slab_class_starts_again_once_empty holds it
over the test's source and the pool's; the pool tests that took the grown size
now read 128 KiB.

The guest sets (guest/prebuilt, guest/prebuilt-arm64e) are rebuilt here from
the bundle of this commit and the one before, which changed it too.
2026-11-26 21:03:22 -08:00

2311 lines
96 KiB
C++

/*
* slab_tests: the slab allocator of the device's Shared and Managed buffers (RgfxSlabs.hpp), over
* a source of memory of the test's own and over the region's source, part of the serialiser check
* (serializer_tests.cpp calls rgfxSlabTests; guest/bundle/Makefile `test`). No Metal.
*/
#include <mach/kern_return.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <cstring>
#include <map>
#include <mutex>
#include <set>
#include <string>
#include <thread>
#include <vector>
#include "RgfxHeapRanges.hpp"
#include "RgfxObjectModel.hpp"
#include "RgfxRegion.hpp"
#include "RgfxRingWriter.hpp"
#include "RgfxSerializer.hpp"
#include "RgfxSlabs.hpp"
#include "reims_graphics_wire.h"
#include "rgfx_test_ring.hpp" // CHECK, g_checks, TestRing, expectMessage
void rgfxSlabTests();
namespace {
constexpr uint32_t kShared = 0x200; // Shared, default cache, Tracked
constexpr uint32_t kSharedUntracked = 0x100; // Shared, default cache, Untracked
constexpr uint32_t kManaged = 0x210; // Managed, Tracked
constexpr uint64_t kMiB = 1ull << 20;
// Memory of the test's own, handed out first fit in units of `unitBytes` (16 KiB, as the region's),
// every byte 0xee as it first comes, with a log of what the allocator asked of it, in order. Its
// Shared classes are heaped where `heapedClasses`, as the region's are. A give waits while the
// gate is shut (shut()), as a block's release waits for the host, but for one let through
// (letOneThrough()) and those of the thread passThread() names; `held` counts the gives that
// waited at it, and `passed` that thread's.
struct Source : RgfxSlabSource {
std::vector<uint8_t> raw;
uint8_t *base; // raw's first byte at a 16 KiB boundary
uint64_t bytes;
RgfxHeapRanges free;
uint64_t gpu = 0x100000000ull;
uint64_t nextObj = 1;
uint64_t unitBytes;
bool refuseHeaps = false;
bool zeroed = false;
bool heapedClasses = true;
std::mutex lock;
std::vector<std::string> log;
uint64_t takes = 0, refusedTakes = 0, gives = 0, heaps = 0, heapDrops = 0;
std::mutex gateLock;
std::condition_variable gateMoved;
bool gateShut = false;
int held = 0;
std::thread::id passer; // whose gives the shut gate lets through
int letThrough = 0; // other gives the shut gate lets through
int passed = 0; // the passer's gives
explicit Source(uint64_t size, uint64_t unit = 0x4000)
: raw(size + 0x4000, 0xee), bytes(size), free(size), unitBytes(unit)
{
base = raw.data() + (0x4000 - reinterpret_cast<uintptr_t>(raw.data()) % 0x4000) % 0x4000;
}
uint64_t unit() const override { return unitBytes; }
uint64_t capacity() const override { return bytes; }
bool heaped(uint32_t options) const override
{
return heapedClasses && ((options >> 4) & 0xf) == 0;
}
bool take(uint64_t size, bool heap, Memory *out) override
{
std::lock_guard<std::mutex> hold(lock);
uint64_t at = 0;
if (!free.take(size, unit(), &at)) {
refusedTakes++;
log.push_back("refuse " + std::to_string(size));
return false;
}
takes++;
log.push_back("take " + std::to_string(size));
out->bytes = base + at;
out->size = size;
out->regionOffset = at;
out->zeroed = zeroed;
if (zeroed)
std::memset(out->bytes, 0, size);
return true;
}
void give(const Memory &memory) override
{
{
std::unique_lock<std::mutex> gate(gateLock);
if (gateShut && std::this_thread::get_id() == passer) {
passed++;
} else {
held++;
gateMoved.notify_all();
gateMoved.wait(gate, [this] { return !gateShut || letThrough > 0; });
if (gateShut)
letThrough--;
}
}
std::lock_guard<std::mutex> hold(lock);
gives++;
log.push_back("give " + std::to_string(memory.size));
free.give(memory.regionOffset, memory.size);
}
bool makeHeap(const Memory &memory, uint32_t options, Heap *out) override
{
std::lock_guard<std::mutex> hold(lock);
if (refuseHeaps)
return false;
heaps++;
out->objId = nextObj++;
out->gpuAddress = gpu;
gpu += memory.size + 0x8000;
log.push_back("heap");
return true;
}
void dropHeap(const Heap &heap) override
{
std::lock_guard<std::mutex> hold(lock);
heapDrops++;
log.push_back("drop heap");
}
bool makeBuffer(const Memory &memory, const Heap &heap, uint64_t offset, uint64_t length,
uint32_t options, Made *out) override
{
std::lock_guard<std::mutex> hold(lock);
out->objId = nextObj++;
out->gpuAddress = heap.objId != 0 ? heap.gpuAddress + offset : (gpu += 0x10000);
out->ownsAddress = heap.objId == 0;
return true;
}
void shut()
{
std::lock_guard<std::mutex> gate(gateLock);
gateShut = true;
}
void open()
{
{
std::lock_guard<std::mutex> gate(gateLock);
gateShut = false;
}
gateMoved.notify_all();
}
// Lets one give the shut gate holds, or the next to come, through.
void letOneThrough()
{
{
std::lock_guard<std::mutex> gate(gateLock);
letThrough++;
}
gateMoved.notify_all();
}
// The shut gate lets `thread`'s gives through.
void passThread(std::thread::id thread)
{
std::lock_guard<std::mutex> gate(gateLock);
passer = thread;
}
int passes()
{
std::lock_guard<std::mutex> gate(gateLock);
return passed;
}
// Waits until `n` gives came to the gate.
void waitHeld(int n)
{
std::unique_lock<std::mutex> gate(gateLock);
gateMoved.wait(gate, [&] { return held >= n; });
}
uint64_t refusals()
{
std::lock_guard<std::mutex> hold(lock);
return refusedTakes;
}
uint64_t used()
{
std::lock_guard<std::mutex> hold(lock);
return free.used();
}
// Whether the last `n` entries of the log are `want`.
bool logEnds(const std::vector<std::string> &want)
{
std::lock_guard<std::mutex> hold(lock);
return log.size() >= want.size() &&
std::equal(want.begin(), want.end(), log.end() - want.size());
}
};
bool allBytes(const uint8_t *p, uint64_t n, uint8_t v)
{
for (uint64_t i = 0; i < n; i++) {
if (p[i] != v)
return false;
}
return true;
}
// A buffer takes whole 4 KiB pages of a slab, page aligned, and buffers of one class share a slab
// (the first 128 KiB), first fit; other options take a slab of their own.
void test_slab_granule_and_classes()
{
Source source(64 * kMiB);
RgfxSlabs slabs(source);
std::vector<RgfxSlabs::Range> held;
for (int i = 0; i < 32; i++) {
RgfxSlabs::Range r;
CHECK(slabs.take(256, kShared, 0, &r));
CHECK(r.size == 0x1000 && r.offset == 0x1000ull * i);
CHECK(reinterpret_cast<uintptr_t>(r.contents) % 0x1000 == 0);
CHECK(r.slab == (held.empty() ? r.slab : held[0].slab));
held.push_back(r);
}
CHECK(source.takes == 1 && source.log[0] == "take 131072" && source.heaps == 1);
// One more takes the class's next slab, twice as large.
RgfxSlabs::Range next;
CHECK(slabs.take(1, kShared, 0, &next) && next.slab != held[0].slab && next.offset == 0);
CHECK(source.log.back() == "heap" && source.takes == 2 && source.log[2] == "take 262144");
// The buffer's GPU address is its heap's plus its offset.
RgfxSlabSource::Made a, b;
CHECK(slabs.makeBuffer(held[0], 256, kShared, &a) && slabs.makeBuffer(held[3], 256, kShared, &b));
CHECK(b.gpuAddress == a.gpuAddress + 0x3000 && !a.ownsAddress);
// Untracked and Managed buffers lie in slabs of their own; a Managed one in no heap.
RgfxSlabs::Range untracked, managed;
CHECK(slabs.take(0x1000, kSharedUntracked, 0, &untracked) && untracked.slab != held[0].slab &&
untracked.slab != next.slab);
CHECK(slabs.take(0x1000, kManaged, 0, &managed) && managed.slab != untracked.slab);
CHECK(source.heaps == 3 && source.takes == 4);
RgfxSlabSource::Made m;
CHECK(slabs.makeBuffer(managed, 0x1000, kManaged, &m) && m.ownsAddress);
// A buffer of 1 MiB still lies in a class's slab; one a byte past it takes its own.
RgfxSlabs::Range mib, big;
CHECK(slabs.take(kMiB, kShared, 0, &mib) && mib.size == kMiB);
CHECK(slabs.take(kMiB + 1, kShared, 0, &big) && big.size == kMiB + 0x1000 && big.offset == 0);
CHECK(source.log.back() == "heap" && source.log[source.log.size() - 2] == "take 1064960");
for (auto &r : held)
slabs.give(r);
slabs.give(next);
slabs.give(untracked);
slabs.give(managed);
slabs.give(mib);
slabs.give(big);
CHECK(slabs.stats().usedBytes == 0);
}
// A class's slabs grow 128 KiB, 256, 512, 1 MiB, then 2 MiB each, and a buffer never makes one
// smaller than twice itself.
void test_slab_growth()
{
Source source(64 * kMiB);
RgfxSlabs slabs(source);
std::vector<RgfxSlabs::Range> held;
while (source.takes < 7) {
RgfxSlabs::Range r;
CHECK(slabs.take(0x10000, kShared, 0, &r));
held.push_back(r);
}
std::vector<std::string> sizes;
for (const auto &e : source.log) {
if (e.rfind("take ", 0) == 0)
sizes.push_back(e.substr(5));
}
CHECK(sizes == std::vector<std::string>({"131072", "262144", "524288", "1048576", "2097152",
"2097152", "2097152"}));
Source other(64 * kMiB);
RgfxSlabs first(other);
RgfxSlabs::Range r;
CHECK(first.take(600 << 10, kShared, 0, &r) && other.log[0] == "take 2097152");
first.give(r);
for (auto &h : held)
slabs.give(h);
}
// A range freed is free again, first fit: freed pages beside each other join, and a buffer takes
// the lowest hole that holds it, never one too small; another slab only where none does.
void test_slab_reuse_and_fragmentation()
{
Source source(64 * kMiB);
RgfxSlabs slabs(source);
std::vector<RgfxSlabs::Range> held(32);
for (auto &r : held)
CHECK(slabs.take(0x1000, kShared, 0, &r));
for (int i = 0; i < 32; i += 2)
slabs.give(held[i]);
// Every hole is one page: two pages go to the next slab.
RgfxSlabs::Range two;
CHECK(slabs.take(0x2000, kShared, 0, &two) && two.slab != held[0].slab);
// A page goes in the lowest hole.
RgfxSlabs::Range one;
CHECK(slabs.take(0x1000, kShared, 0, &one) && one.slab == held[0].slab && one.offset == 0);
// Pages 4, 5 and 6 free make a hole of three, which a buffer of three pages takes.
slabs.give(held[5]);
RgfxSlabs::Range three;
CHECK(slabs.take(0x3000, kShared, 0, &three) && three.slab == held[0].slab &&
three.offset == 0x4000);
// The slab's pages past the 32 taken are free too: 0x20000 - 0x20000 = none; a fourth page
// lies in hole 2.
RgfxSlabs::Range again;
CHECK(slabs.take(0x1000, kShared, 0, &again) && again.slab == held[0].slab &&
again.offset == 0x2000);
CHECK(source.takes == 2);
slabs.give(two);
slabs.give(one);
slabs.give(three);
slabs.give(again);
for (int i = 1; i < 32; i += 2) {
if (i != 5)
slabs.give(held[i]);
}
CHECK(slabs.stats().usedBytes == 0 && slabs.stats().emptySlabs == 2);
}
// Every range reads zero as it is taken, whatever its memory held: the source's bytes, a freed
// buffer's. A create zeroes only past the bytes its caller writes; the background zeroes freed
// bytes, after which a create finds them clean.
void test_slab_zeroing()
{
Source source(64 * kMiB);
RgfxSlabs slabs(source);
RgfxSlabs::Range r;
CHECK(slabs.take(0x3000, kShared, 0, &r) && allBytes(r.contents, 0x3000, 0));
CHECK(r.zeroFrom == 0); // a range reads zero from its caller's bytes on
// The rest of the slab is still the source's bytes until the background zeroes it.
CHECK(r.contents[0x3000] == 0xee && slabs.stats().dirtyBytes == 0x20000 - 0x3000);
std::memset(r.contents, 0xa5, 0x3000);
slabs.give(r);
CHECK(slabs.stats().dirtyBytes == 0x20000);
RgfxSlabs::Range again;
CHECK(slabs.take(0x2000, kShared, 0x100, &again) && again.offset == 0);
// The caller writes its first 256 bytes: the rest reads zero.
CHECK(again.contents[0] == 0xa5 && again.contents[0xff] == 0xa5 &&
allBytes(again.contents + 0x100, 0x1f00, 0));
CHECK(again.zeroFrom == 0x100);
slabs.give(again);
while (slabs.step()) {
}
CHECK(slabs.stats().dirtyBytes == 0);
const RgfxSlabs::Range *any = &again;
CHECK(allBytes(any->contents, 0x20000, 0));
// Clean memory is taken as it is: a byte the background zeroed and nothing wrote since.
RgfxSlabs::Range clean;
CHECK(slabs.take(0x20000, kShared, 0, &clean) && allBytes(clean.contents, 0x20000, 0));
CHECK(clean.zeroFrom == 0);
slabs.give(clean);
// Bytes of the caller's past the range: none of it reads zero for sure.
RgfxSlabs::Range past;
CHECK(slabs.take(0x800, kShared, 0x5000, &past) && past.size == 0x1000 &&
past.zeroFrom == 0x1000);
slabs.give(past);
// A source's zeroed slabs are clean from the start.
Source zeroed(64 * kMiB);
zeroed.zeroed = true;
RgfxSlabs z(zeroed);
RgfxSlabs::Range zr;
CHECK(z.take(0x1000, kShared, 0, &zr) && z.stats().dirtyBytes == 0);
z.give(zr);
}
// A class keeps two empty slabs; a third empty one goes: its heap dropped, then its memory given
// back. Without the background thread it goes at once.
void test_slab_empty_slabs_go()
{
Source source(64 * kMiB);
RgfxSlabs slabs(source);
std::vector<RgfxSlabs::Range> held;
while (source.takes < 4) {
RgfxSlabs::Range r;
CHECK(slabs.take(0x20000, kShared, 0, &r));
held.push_back(r);
}
CHECK(held.size() >= 4);
for (auto &r : held)
slabs.give(r);
CHECK(slabs.stats().emptySlabs == 2 && source.heapDrops == 2 && source.gives == 2);
// Slabs of 256 KiB, 512 KiB, 1 and 2 MiB emptied in turn: the last two go.
CHECK(source.logEnds({"drop heap", "give 1048576", "drop heap", "give 2097152"}));
// The kept ones serve the class again, with no new slab.
RgfxSlabs::Range r;
CHECK(slabs.take(0x1000, kShared, 0, &r) && source.takes == 4);
slabs.give(r);
}
// The kept empty slabs go once they sat empty kCacheIdleMs, as a cached slab does, so a process
// at rest holds only the slabs its buffers lie in; one a buffer took from meanwhile stays. The
// background's step lets them go, its heap destroyed and its memory given back.
uint64_t g_testNowMs = 0;
uint64_t testClock(void *) { return g_testNowMs; }
void test_slab_idle_empty_slabs_go()
{
Source source(64 * kMiB);
RgfxSlabs slabs(source);
g_testNowMs = 1000;
slabs.setClock(&testClock, nullptr);
auto drain = [&]() {
while (slabs.step()) {
}
};
// Two slabs of the class, both emptied at 1000 ms; a third holds a buffer.
std::vector<RgfxSlabs::Range> held;
while (source.takes < 3) {
RgfxSlabs::Range r;
CHECK(slabs.take(0x20000, kShared, 0, &r));
held.push_back(r);
}
RgfxSlabs::Range last = held.back();
held.pop_back();
for (auto &r : held)
slabs.give(r);
drain();
CHECK(slabs.stats().emptySlabs == 2 && slabs.stats().slabs == 3 && source.heapDrops == 0);
// Not yet at 2999 ms.
g_testNowMs = 1000 + RgfxSlabs::kCacheIdleMs - 1;
drain();
CHECK(slabs.stats().emptySlabs == 2 && source.heapDrops == 0);
// At 3000 ms both go, their heaps destroyed and their memory given back; the slab with a
// buffer stays.
g_testNowMs = 1000 + RgfxSlabs::kCacheIdleMs;
drain();
CHECK(slabs.stats().emptySlabs == 0 && slabs.stats().slabs == 1);
CHECK(source.heapDrops == 2 && source.gives == 2 && slabs.stats().usedBytes == last.size);
// One emptied, then taken from again before its time: it stays, and goes once emptied
// for its own kCacheIdleMs.
slabs.give(last);
g_testNowMs += 1000;
RgfxSlabs::Range again;
CHECK(slabs.take(0x1000, kShared, 0, &again) && again.slab == last.slab);
g_testNowMs += RgfxSlabs::kCacheIdleMs;
drain();
CHECK(slabs.stats().slabs == 1 && source.heapDrops == 2);
slabs.give(again);
g_testNowMs += RgfxSlabs::kCacheIdleMs - 1;
drain();
CHECK(slabs.stats().slabs == 1);
g_testNowMs += 1;
drain();
CHECK(slabs.stats().slabs == 0 && source.heapDrops == 3 && source.gives == 3);
// A cached dedicated slab goes on the same clock.
RgfxSlabs::Range big;
CHECK(slabs.take(3 * kMiB, kShared, 0, &big));
slabs.give(big);
drain();
CHECK(slabs.stats().cachedSlabs == 1);
g_testNowMs += RgfxSlabs::kCacheIdleMs;
drain();
CHECK(slabs.stats().cachedSlabs == 0 && slabs.stats().slabs == 0);
}
// CHURN: the slabs made, the small buffers' slabs emptied, the empty ones kept that a buffer took
// from again and those let go, and the cached slabs large buffers took, counted; the background's
// step calls the churn log with them once they changed, kChurnLogMs after its last call at the
// soonest.
std::vector<RgfxSlabs::Churn> g_churnLines;
void testChurnLog(void *, const RgfxSlabs::Churn &churn) { g_churnLines.push_back(churn); }
void test_slab_churn_counts()
{
Source source(64 * kMiB);
RgfxSlabs slabs(source);
g_testNowMs = 1000;
g_churnLines.clear();
slabs.setClock(&testClock, nullptr);
slabs.setChurnLog(&testChurnLog, nullptr);
auto drain = [&]() {
while (slabs.step()) {
}
};
drain();
CHECK(g_churnLines.empty()); // nothing counted yet
// Slabs of 256 KiB, 512 KiB, 1 and 2 MiB, each emptied: the last two let go.
std::vector<RgfxSlabs::Range> held;
while (source.takes < 4) {
RgfxSlabs::Range r;
CHECK(slabs.take(0x20000, kShared, 0, &r));
held.push_back(r);
}
for (auto &r : held)
slabs.give(r);
RgfxSlabs::Churn c = slabs.churn();
CHECK(c.classMade == 4 && c.classMadeBytes == 3840 * 1024 && c.emptied == 4);
CHECK(c.emptyLetGo == 2 && c.refilled == 0 && c.dedicatedMade == 0);
// A kept empty slab taken from again, the oldest: 256 KiB.
RgfxSlabs::Range r;
CHECK(slabs.take(0x1000, kShared, 0, &r) && source.takes == 4);
c = slabs.churn();
CHECK(c.refilled == 1 && c.refilledBytes == 256 * 1024 && c.classMade == 4);
// The first log line at the first step with the counts changed.
drain();
CHECK(g_churnLines.size() == 1 && g_churnLines[0].refilled == 1 &&
g_churnLines[0].emptyLetGo == 2);
// A large buffer's slab made, cached at its free, taken again: counted, logged no sooner
// than kChurnLogMs after the last line.
RgfxSlabs::Range big, again;
CHECK(slabs.take(3 * kMiB, kShared, 0, &big));
slabs.give(big);
CHECK(slabs.take(2 * kMiB, kShared, 0, &again) && again.slab == big.slab);
c = slabs.churn();
CHECK(c.dedicatedMade == 1 && c.dedicatedReused == 1 && c.dedicatedReusedBytes == 3 * kMiB);
g_testNowMs += RgfxSlabs::kChurnLogMs - 1;
drain();
CHECK(g_churnLines.size() == 1);
g_testNowMs += 1;
drain();
CHECK(g_churnLines.size() == 2 && g_churnLines[1].dedicatedReused == 1);
// No line where nothing changed.
g_testNowMs += 2 * RgfxSlabs::kChurnLogMs;
drain();
CHECK(g_churnLines.size() == 2);
slabs.give(again);
slabs.give(r);
}
// A buffer past 1 MiB takes a slab of its own; once freed the slab is cached, and a later buffer
// of its class that needs at least half of it lies there at offset 0, its bytes zeroed. The cache
// holds a sixteenth of the source, the oldest let go first.
void test_slab_dedicated_cache()
{
Source source(256 * kMiB); // a cache of 16 MiB
RgfxSlabs slabs(source);
RgfxSlabs::Range big;
CHECK(slabs.take(3 * kMiB, kShared, 0, &big) && big.offset == 0 && big.size == 3 * kMiB);
std::memset(big.contents, 0xa5, big.size);
const void *slab = big.slab;
slabs.give(big);
CHECK(slabs.stats().cachedSlabs == 1 && source.gives == 0);
// Too small for it (under half) and of another class: slabs of their own.
RgfxSlabs::Range small, other;
CHECK(slabs.take(kMiB + 0x1000, kShared, 0, &small) && small.slab != slab);
CHECK(slabs.take(3 * kMiB, kSharedUntracked, 0, &other) && other.slab != slab);
RgfxSlabs::Range reuse;
CHECK(slabs.take(2 * kMiB, kShared, 0, &reuse) && reuse.slab == slab && reuse.offset == 0);
CHECK(allBytes(reuse.contents, 2 * kMiB, 0) && slabs.stats().cachedSlabs == 0);
const uint64_t takes = source.takes;
slabs.give(reuse);
slabs.give(small);
slabs.give(other);
// 3 + 1.0039 + 3 MiB cached; four 4 MiB slabs more pass 16 MiB: the oldest go.
std::vector<RgfxSlabs::Range> four(4);
for (auto &r : four)
CHECK(slabs.take(4 * kMiB, kSharedUntracked, 0, &r));
CHECK(source.takes == takes + 4); // the cached Untracked one of 3 MiB holds no 4 MiB
for (auto &r : four)
slabs.give(r);
CHECK(slabs.stats().cachedBytes <= 16 * kMiB && source.gives >= 3);
// The background zeroes the cached slabs.
while (slabs.step()) {
}
CHECK(slabs.stats().dirtyBytes == 0);
}
// Where the source has no room for a new slab: the process's own empty and cached slabs go and
// the slab is asked again; then a small buffer takes slabs half as large down to its own size.
// Nil only where the source has no room even for that, and a buffer is made again once one goes.
// A slab whose heap the device never got is nil at once, its memory given back.
void test_slab_fallbacks()
{
{
Source source(0x40000); // 256 KiB
RgfxSlabs slabs(source);
RgfxSlabs::Range a, b;
CHECK(slabs.take(0x1000, kShared, 0, &a)); // 128 KiB slab
CHECK(slabs.take(0x1000, kManaged, 0, &b)); // 128 KiB slab: the source is full
std::vector<RgfxSlabs::Range> more;
RgfxSlabs::Range r;
for (int i = 0; i < 31; i++) {
CHECK(slabs.take(0x1000, kShared, 0, &r));
more.push_back(r);
}
// The Shared slab is full and the source too: nil.
CHECK(!slabs.take(0x1000, kShared, 0, &r));
CHECK(source.refusedTakes >= 2);
// The Managed slab emptied gives the source room again.
slabs.give(b);
CHECK(slabs.take(0x1000, kShared, 0, &r) && r.slab != a.slab);
CHECK(slabs.stats().slabs == 2 && source.gives == 1);
slabs.give(r);
for (auto &m : more)
slabs.give(m);
slabs.give(a);
}
{
// Room for a 16 KiB slab only: a page takes it, after 256, 128, 64 and 32 KiB were refused.
Source source(0x24000);
RgfxSlabs slabs(source);
RgfxSlabs::Range a, b;
CHECK(slabs.take(0x20000, kShared, 0, &a) && a.size == 0x20000); // 256 KiB refused, 128 taken
source.log.clear();
CHECK(slabs.take(0x1000, kManaged, 0, &b));
CHECK(source.log == std::vector<std::string>({"refuse 131072", "refuse 131072",
"refuse 65536", "refuse 32768",
"take 16384"}));
// A cached slab goes before a create is refused.
slabs.give(a);
slabs.give(b);
RgfxSlabs::Range big;
CHECK(slabs.take(0x20000, kSharedUntracked, 0, &big) && slabs.stats().emptySlabs == 0);
slabs.give(big);
}
{
Source source(64 * kMiB);
source.refuseHeaps = true;
RgfxSlabs slabs(source);
RgfxSlabs::Range r;
CHECK(!slabs.take(0x1000, kShared, 0, &r));
CHECK(source.takes == 1 && source.gives == 1 && slabs.stats().slabs == 0);
// A Managed class makes no heap.
CHECK(slabs.take(0x1000, kManaged, 0, &r));
slabs.give(r);
}
}
// With a first source (the process's own guest RAM: 2 MiB units, no heaps, zeroed pages), a new
// slab comes from it at its unit while it has memory, small and dedicated ones alike, and its
// buffers are its own; once it has none, the region's source makes the slab, heaped as its classes
// are. A slab goes back to the source it came from, and a cached one past a sixteenth of its own
// source's capacity goes at once. Where both refuse, the process's empty slabs go and the first
// source is asked again first.
void test_slab_first_source()
{
{
Source region(64 * kMiB);
Source pages(8 * kMiB, 2 * kMiB);
pages.heapedClasses = false;
pages.zeroed = true;
RgfxSlabs slabs(region);
slabs.setFirst(&pages);
RgfxSlabs::Range a, b, big, c;
CHECK(slabs.take(0x1000, kShared, 0, &a) && pages.takes == 1 && region.takes == 0);
CHECK(pages.logEnds({"take 2097152"})); // the unit, though a class's first slab is 128 KiB
RgfxSlabSource::Made made;
CHECK(slabs.makeBuffer(a, 0x1000, kShared, &made) && made.ownsAddress && pages.heaps == 0);
std::vector<RgfxSlabs::Range> fill(511);
for (auto &r : fill)
CHECK(slabs.take(0x1000, kShared, 0, &r) && r.slab == a.slab);
CHECK(slabs.take(0x1000, kShared, 0, &b) && b.slab != a.slab && pages.takes == 2);
CHECK(allBytes(b.contents, b.size, 0) && slabs.stats().dirtyBytes == 0);
// A dedicated 3 MiB buffer takes two units, the source's last.
CHECK(slabs.take(3 * kMiB, kShared, 0, &big) && big.size == 3 * kMiB);
CHECK(pages.takes == 3 && pages.logEnds({"take 4194304"}));
// The pages are full: the region's source makes the next slab, with its heap.
CHECK(slabs.take(0x1000, kSharedUntracked, 0, &c));
CHECK(pages.logEnds({"refuse 2097152"}) && region.takes == 1 && region.heaps == 1);
CHECK(slabs.makeBuffer(c, 0x1000, kSharedUntracked, &made) && !made.ownsAddress);
RgfxSlabs::Stats st = slabs.stats();
CHECK(st.slabs == 4 && st.firstSlabs == 3);
// The dedicated slab is past a sixteenth of the pages (512 KiB): it goes back to them at
// once, and the region's source gives nothing.
slabs.give(big);
CHECK(pages.gives == 1 && pages.logEnds({"give 4194304"}) && region.gives == 0);
CHECK(slabs.stats().cachedSlabs == 0);
slabs.give(c);
slabs.give(b);
for (auto &r : fill)
slabs.give(r);
slabs.give(a);
CHECK(region.gives == 0 && slabs.stats().emptySlabs == 3);
}
{
Source region(0x20000); // one 128 KiB slab
Source pages(4 * kMiB, 2 * kMiB);
pages.heapedClasses = false;
RgfxSlabs slabs(region);
slabs.setFirst(&pages);
RgfxSlabs::Range a, b, c, d;
CHECK(slabs.take(0x1000, kShared, 0, &a));
CHECK(slabs.take(0x1000, kSharedUntracked, 0, &b) && pages.takes == 2);
CHECK(slabs.take(0x1000, kManaged, 0, &c) && region.takes == 1);
slabs.give(a); // kept, empty
// A fourth class (Shared, write-combined): both refuse, the empty slab goes, and the pages
// make the slab.
pages.log.clear();
CHECK(slabs.take(0x1000, kShared | 0x1, 0, &d));
CHECK(pages.gives == 1 && pages.takes == 3 && region.refusedTakes >= 1);
CHECK(pages.log == std::vector<std::string>({"refuse 2097152", "give 2097152",
"take 2097152"}));
slabs.give(d);
slabs.give(c);
slabs.give(b);
}
}
// With the background thread, a freed slab goes and freed bytes are zeroed on it, and buffers
// made and freed on several threads at once never share a byte.
void test_slab_thread()
{
Source source(256 * kMiB);
RgfxSlabs slabs(source);
CHECK(slabs.start());
std::vector<uint8_t> owner(source.bytes / 0x1000, 0);
std::mutex ownerLock;
std::atomic<int> overlaps{0}, bad{0};
auto worker = [&](uint8_t id) {
uint32_t seed = id * 2654435761u;
std::vector<RgfxSlabs::Range> mine;
for (int i = 0; i < 3000; i++) {
seed = seed * 1664525u + 1013904223u;
if (mine.size() > 40 || (!mine.empty() && (seed >> 28) < 6)) {
size_t k = (seed >> 8) % mine.size();
RgfxSlabs::Range r = mine[k];
mine.erase(mine.begin() + k);
if (r.contents[0] != id || r.contents[r.size - 1] != id)
bad++;
{
std::lock_guard<std::mutex> hold(ownerLock);
const uint64_t first = (r.contents - source.base) / 0x1000;
for (uint64_t p = first; p < first + r.size / 0x1000; p++)
owner[p] = 0;
}
slabs.give(r);
continue;
}
const uint64_t sizes[] = {256, 0x1000, 0x3000, 0x10000, 0x80000, 3 * kMiB};
const uint64_t length = sizes[(seed >> 12) % 6];
const uint32_t options = (seed >> 20) & 1 ? kShared : kManaged;
RgfxSlabs::Range r;
if (!slabs.take(length, options, 0, &r)) {
bad++;
continue;
}
if (r.contents[0] != 0 || r.contents[r.size - 1] != 0)
bad++;
{
std::lock_guard<std::mutex> hold(ownerLock);
const uint64_t first = (r.contents - source.base) / 0x1000;
for (uint64_t p = first; p < first + r.size / 0x1000; p++) {
if (owner[p] != 0)
overlaps++;
owner[p] = id;
}
}
r.contents[0] = id;
r.contents[r.size - 1] = id;
mine.push_back(r);
}
for (auto &r : mine) {
std::lock_guard<std::mutex> hold(ownerLock);
const uint64_t first = (r.contents - source.base) / 0x1000;
for (uint64_t p = first; p < first + r.size / 0x1000; p++)
owner[p] = 0;
slabs.give(r);
}
};
std::vector<std::thread> threads;
for (uint8_t id = 1; id <= 4; id++)
threads.emplace_back(worker, id);
for (auto &t : threads)
t.join();
CHECK(overlaps == 0 && bad == 0);
// The thread zeroes what was freed and lets the extra slabs go.
bool settled = false;
for (int i = 0; i < 2000 && !settled; i++) {
RgfxSlabs::Stats s = slabs.stats();
settled = s.dirtyBytes == 0 && s.dooming == 0;
if (!settled)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
CHECK(settled && slabs.stats().usedBytes == 0);
// Every byte the source gave is a slab's.
CHECK(source.used() == slabs.stats().slabBytes);
}
// A create that finds no room waits for the slabs another thread is giving back as it asks, and
// takes their memory once it is back, as long as its block's release takes (THE FALLBACKS): a
// 3 MiB slab let go on one thread, its release held at the source, while another asks for 3 MiB
// of a 4 MiB source. No background thread: the thread that lets a slab go drops it.
void test_slab_take_waits_for_slabs_given_back()
{
Source source(4 * kMiB);
RgfxSlabs slabs(source);
RgfxSlabs::Range first;
CHECK(slabs.take(3 * kMiB, kShared, 0, &first));
// Past the cache's cap (a sixteenth of the source), the slab goes as its buffer does.
source.shut();
std::thread giver([&] { slabs.give(first); });
source.waitHeld(1);
std::atomic<int> answer{-1};
RgfxSlabs::Range second;
std::thread taker([&] { answer = slabs.take(3 * kMiB, kShared, 0, &second) ? 1 : 0; });
// It found no room, and waits for the slab on its way back: no answer while it is held.
while (source.refusals() == 0)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
for (int i = 0; i < 200 && answer == -1; i++)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
CHECK(answer == -1);
// The slab on its way back is out of the slabs and counted as going.
CHECK(slabs.stats().slabs == 0 && slabs.stats().dooming == 1);
source.open();
taker.join();
giver.join();
CHECK(answer == 1 && second.size == 3 * kMiB && slabs.stats().dooming == 0);
CHECK(source.gives == 1 && source.used() == 3 * kMiB);
slabs.give(second);
CHECK(source.used() == 0 && slabs.stats().slabs == 0);
}
// A create that waited for a slab on its way back gives back, before it asks again, the slabs let
// go while it waited (THE FALLBACKS), which the background thread, behind on its drops as under
// CPU load, leaves doomed with their memory out of the source: a 1.25 MiB slab and two of 3 MiB
// fill the source, and the first is let go, its release on the background held at the source,
// while another thread asks for 3 MiB; the two others are let go as it waits, and once the first
// is back, 1.25 MiB short of the create's 3, the background's release of the next is held too.
void test_slab_take_gives_back_slabs_let_go_while_it_waited()
{
Source source(7 * kMiB + (256 << 10));
RgfxSlabs slabs(source);
CHECK(slabs.start());
RgfxSlabs::Range first, second, third;
CHECK(slabs.take(kMiB + (256 << 10), kShared, 0, &first));
CHECK(slabs.take(3 * kMiB, kShared, 0, &second) && slabs.take(3 * kMiB, kShared, 0, &third));
CHECK(source.used() == source.bytes);
// Past the cache's cap (a sixteenth of the source), each slab goes as its buffer does.
source.shut();
slabs.give(first);
source.waitHeld(1);
std::atomic<int> answer{-1};
RgfxSlabs::Range got;
std::thread taker([&] { answer = slabs.take(3 * kMiB, kShared, 0, &got) ? 1 : 0; });
source.passThread(taker.get_id()); // the create's own releases go through
// It found no room, and waits for the slab on its way back.
while (source.refusals() == 0)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
std::this_thread::sleep_for(std::chrono::milliseconds(50));
CHECK(answer == -1);
slabs.give(second);
slabs.give(third);
source.letOneThrough();
// It gives back what is still let go itself, waits for the one the background holds, and
// takes the room: without that, it is nil here. (Should it have come to wait for all three,
// the gate opens after 2 s.)
for (int i = 0; i < 2000 && answer == -1 && source.passes() == 0; i++)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
source.open();
taker.join();
CHECK(answer == 1 && got.size == 3 * kMiB);
slabs.give(got);
bool settled = false;
for (int i = 0; i < 2000 && !settled; i++) {
settled = slabs.stats().slabs == 0 && slabs.stats().dooming == 0;
if (!settled)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
CHECK(settled && source.used() == 0);
}
// Over the region: a Shared slab is a Placement heap over host memory at its block, each buffer a
// BUFFER_AT_OFFSET there; a Managed one is the block, each buffer a BUFFER_OVER_HOST_MEMORY over
// its own range of it. A slab let go destroys its heap.
void test_region_slab_source()
{
std::vector<uint8_t> mem(RGFX_ALLOCATIONS_OFFSET + 0x800000, 0xee);
TestRing ring(0x8000);
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell,
nullptr);
RgfxIdSpace ids;
RgfxSerializer ser(writer, ids);
RgfxRegion region(mem.data(), mem.size());
RgfxRegionSlabSource source(region, ser);
CHECK(source.unit() == 0x4000 && source.heaped(kShared) && !source.heaped(kManaged));
RgfxSlabs slabs(source);
RgfxSlabs::Range r;
CHECK(slabs.take(256, kShared, 0, &r));
auto heap = expectMessage<RgfxHeapOverHostMemory>(ring, RGFX_CMD_HEAP_OVER_HOST_MEMORY);
CHECK(heap.region_offset == static_cast<uint64_t>(r.contents - mem.data()) &&
heap.size_bytes == 0x20000 && heap.options == kShared && heap.heap_type == 1);
RgfxSlabSource::Made made;
CHECK(slabs.makeBuffer(r, 256, 0, &made));
auto at = expectMessage<RgfxBufferAtOffset>(ring, RGFX_CMD_BUFFER_AT_OFFSET);
CHECK(at.heap_obj_id == heap.obj_id && at.offset == 0 && at.length == 256 && at.options == 0);
CHECK(made.objId == at.obj_id && made.gpuAddress == heap.gpu_address && !made.ownsAddress);
RgfxSlabs::Range m;
CHECK(slabs.take(0x2000, kManaged, 0, &m) && slabs.makeBuffer(m, 0x2000, kManaged, &made));
auto over = expectMessage<RgfxBufferOverHostMemory>(ring, RGFX_CMD_BUFFER_OVER_HOST_MEMORY);
CHECK(over.region_offset == static_cast<uint64_t>(m.contents - mem.data()) &&
over.length == 0x2000 && made.ownsAddress && made.gpuAddress == over.gpu_address);
slabs.give(r);
slabs.give(m);
// Three slabs of another class, two 1 MiB buffers each, emptied: the third goes, its heap
// destroyed.
std::vector<RgfxSlabs::Range> held;
for (int i = 0; i < 6; i++) {
RgfxSlabs::Range h;
CHECK(slabs.take(kMiB, kSharedUntracked, 0, &h));
held.push_back(h);
}
CHECK(slabs.stats().slabs == 5);
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
while (ring.next(&h, &bytes)) {
}
for (auto &r : held)
slabs.give(r);
CHECK(ring.next(&h, &bytes) && h.type == RGFX_CMD_OBJECT_DESTROY);
CHECK(!ring.next(&h, &bytes));
}
// A kext of the test's own: blocks first fit past the floor. A release waits while the gate is
// shut (shut()), as the kext's waits for the device's answer, and `held` counts the releases that
// came to it.
struct Kext {
RgfxHeapRanges free;
std::map<uint64_t, uint64_t> sizes; // each block's, by region offset
std::atomic<int> reclaims{0}, reclaimed{0};
RgfxSlabs *slabs = nullptr;
std::mutex lock;
std::mutex gateLock;
std::condition_variable gateMoved;
bool gateShut = false;
int held = 0;
explicit Kext(uint64_t size) : free(size) {}
static bool alloc(void *context, uint64_t size, uint64_t align, uint64_t *offset)
{
Kext *k = static_cast<Kext *>(context);
std::lock_guard<std::mutex> hold(k->lock);
if (!k->free.take(size, align, offset))
return false;
*offset += RGFX_ALLOCATIONS_OFFSET;
k->sizes[*offset] = size;
return true;
}
static void release(void *context, uint64_t offset)
{
Kext *k = static_cast<Kext *>(context);
{
std::unique_lock<std::mutex> gate(k->gateLock);
k->held++;
k->gateMoved.notify_all();
k->gateMoved.wait(gate, [k] { return !k->gateShut; });
}
std::lock_guard<std::mutex> hold(k->lock);
auto it = k->sizes.find(offset);
if (it == k->sizes.end())
return;
k->free.give(offset - RGFX_ALLOCATIONS_OFFSET, it->second);
k->sizes.erase(it);
}
static bool reclaim(void *context)
{
Kext *k = static_cast<Kext *>(context);
k->reclaims++;
const bool went = k->slabs != nullptr ? k->slabs->reclaim() : false;
k->reclaimed += went;
return went;
}
void shut()
{
std::lock_guard<std::mutex> gate(gateLock);
gateShut = true;
}
void open()
{
{
std::lock_guard<std::mutex> gate(gateLock);
gateShut = false;
}
gateMoved.notify_all();
}
// Waits until `n` releases came to the gate.
void waitHeld(int n)
{
std::unique_lock<std::mutex> gate(gateLock);
gateMoved.wait(gate, [&] { return held >= n; });
}
};
// Where the kext has no room for a block, the region lets the slabs the process keeps go (the
// cached and the empty ones) and asks once more: a block is refused only where nothing the
// process holds could make room.
// A region slab source over a kext that zeroes the blocks it gives (kRgfxKextFeatureZeroedBlocks):
// its slabs come clean and are not zeroed again, so a buffer reads what the block held as the
// kext gave it (the test region's 0xee standing for the kext's zeros). Without the kext's word,
// the bytes a buffer takes are zeroed here.
void test_region_slab_source_zeroed_blocks()
{
for (int kextZeroes = 0; kextZeroes < 2; kextZeroes++) {
std::vector<uint8_t> mem(RGFX_ALLOCATIONS_OFFSET + 0x800000, 0xee);
TestRing ring(0x8000);
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell,
nullptr);
RgfxIdSpace ids;
RgfxSerializer ser(writer, ids);
RgfxRegion region(mem.data(), mem.size());
RgfxRegionSlabSource source(region, ser);
source.setZeroedBlocks(kextZeroes != 0);
RgfxSlabs slabs(source);
RgfxSlabs::Range r;
CHECK(slabs.take(0x3000, kShared, 0, &r));
CHECK(allBytes(r.contents, 0x3000, kextZeroes ? 0xee : 0));
CHECK(slabs.stats().dirtyBytes == (kextZeroes ? 0 : 0x20000 - 0x3000));
slabs.give(r);
}
}
void test_region_reclaims_slabs()
{
constexpr uint64_t kRoom = 80 * kMiB; // a cache of 5 MiB
std::vector<uint8_t> mem(RGFX_ALLOCATIONS_OFFSET + kRoom, 0xee);
TestRing ring(0x8000);
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell,
nullptr);
RgfxIdSpace ids;
RgfxSerializer ser(writer, ids);
RgfxRegion region(mem.data(), mem.size());
Kext kext(kRoom);
region.setBlockSource(&Kext::alloc, &Kext::release, &kext);
region.setReclaim(&Kext::reclaim, &kext);
RgfxRegionSlabSource source(region, ser);
RgfxSlabs slabs(source);
kext.slabs = &slabs;
// A 4 MiB buffer freed stays cached, a 256 KiB one's slab stays empty: 4.5 MiB kept.
RgfxSlabs::Range big, small;
CHECK(slabs.take(4 * kMiB, kShared, 0, &big) && slabs.take(256 << 10, kShared, 0, &small));
slabs.give(big);
slabs.give(small);
CHECK(slabs.stats().cachedSlabs == 1 && slabs.stats().emptySlabs == 1);
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
while (ring.next(&h, &bytes)) {
}
// Room for 3.5 MiB past the rest: a 4.5 MiB block is placed where both slabs lay, once they
// went, their heaps destroyed.
RgfxRegion::Block filler = region.allocate(72 * kMiB);
CHECK(filler.ok && kext.reclaims == 0);
RgfxRegion::Block block = region.allocate(4 * kMiB + (512 << 10));
CHECK(block.ok && kext.reclaims == 1 && kext.reclaimed == 1);
CHECK(slabs.stats().slabs == 0 && slabs.stats().cachedSlabs == 0);
int destroys = 0;
while (ring.next(&h, &bytes))
destroys += h.type == RGFX_CMD_OBJECT_DESTROY;
CHECK(destroys == 2);
// Nothing left to give back: refused after one reclaim that let nothing go.
CHECK(!region.allocate(4 * kMiB).ok && kext.reclaims == 2 && kext.reclaimed == 1);
region.release(block.offset);
// The slabs' own blocks ask through the region too: a buffer past the room is nil.
RgfxSlabs::Range none;
CHECK(!slabs.take(16 * kMiB, kShared, 0, &none));
}
// A block the kext has no room for waits, in the region's reclaim, for the slab another thread is
// giving back as it asks, and is placed in its room once its release is answered: a 3 MiB slab
// let go on one thread, its block's release held at the kext, while another asks the region for
// 2 MiB with 3 MiB of 8 MiB free only once that release is done. No background thread.
void test_region_reclaim_waits_for_slabs_given_back()
{
constexpr uint64_t kRoom = 8 * kMiB; // a cache of 512 KiB
std::vector<uint8_t> mem(RGFX_ALLOCATIONS_OFFSET + kRoom, 0xee);
TestRing ring(0x8000);
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell,
nullptr);
RgfxIdSpace ids;
RgfxSerializer ser(writer, ids);
RgfxRegion region(mem.data(), mem.size());
Kext kext(kRoom);
region.setBlockSource(&Kext::alloc, &Kext::release, &kext);
region.setReclaim(&Kext::reclaim, &kext);
RgfxRegionSlabSource source(region, ser);
RgfxSlabs slabs(source);
kext.slabs = &slabs;
RgfxSlabs::Range big;
CHECK(slabs.take(3 * kMiB, kShared, 0, &big));
RgfxRegion::Block filler = region.allocate(5 * kMiB);
CHECK(filler.ok);
// Past the cache's cap, the slab goes as its buffer does, its release held.
kext.shut();
std::thread giver([&] { slabs.give(big); });
kext.waitHeld(1);
std::atomic<int> answer{-1};
RgfxRegion::Block block = {};
std::thread asker([&] {
block = region.allocate(2 * kMiB);
answer = block.ok ? 1 : 0;
});
while (kext.reclaims == 0)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
for (int i = 0; i < 200 && answer == -1; i++)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
CHECK(answer == -1);
kext.open();
asker.join();
giver.join();
CHECK(answer == 1 && kext.reclaims == 1 && kext.reclaimed == 1);
CHECK(slabs.stats().slabs == 0 && slabs.stats().dooming == 0);
region.release(block.offset);
region.release(filler.offset);
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
while (ring.next(&h, &bytes)) {
}
}
// A kext of the test's own for the pages source: region blocks and pages blocks (16 KiB, which
// hold the runs) first fit from one room past the floor, each release logged.
struct PagesKext {
RgfxHeapRanges free;
std::map<uint64_t, uint64_t> blocks; // region blocks, by offset
std::set<uint64_t> pages; // pages blocks, by offset
std::map<uint64_t, std::vector<uint8_t>> chunks; // chunked pages blocks' memory, by offset
std::vector<std::string> *log;
bool refusePages = false;
bool refuseChunks = false;
const void *lastAddress = nullptr;
uint64_t lastLength = 0;
bool lastWritable = false;
PagesKext(uint64_t size, std::vector<std::string> *events) : free(size), log(events) {}
static bool alloc(void *context, uint64_t size, uint64_t align, uint64_t *offset)
{
PagesKext *k = static_cast<PagesKext *>(context);
if (!k->free.take(size, align, offset))
return false;
*offset += RGFX_ALLOCATIONS_OFFSET;
k->blocks[*offset] = size;
return true;
}
static bool pagesBlock(void *context, const void *address, uint64_t length, uint32_t how,
uint64_t *offset, uint64_t *size, uint64_t *gpuAddress)
{
const bool writable = (how & RgfxRegion::kPagesWritable) != 0;
PagesKext *k = static_cast<PagesKext *>(context);
*gpuAddress = 0;
k->lastAddress = address;
k->lastLength = length;
k->lastWritable = writable;
if (k->refusePages || !k->free.take(0x4000, 0x4000, offset))
return false;
*offset += RGFX_ALLOCATIONS_OFFSET;
*size = 0x4000;
k->pages.insert(*offset);
return true;
}
// The kext's chunks and their pages block (PagesChunked): memory of its own, zero-filled,
// which goes with the block's release.
static bool chunked(void *context, uint64_t length, uint8_t **bytes, uint64_t *offset,
uint64_t *size)
{
PagesKext *k = static_cast<PagesKext *>(context);
const std::string what = "chunked " + std::to_string(length);
if (k->refuseChunks || !k->free.take(0x4000, 0x4000, offset)) {
k->log->push_back(what + " refused");
return false;
}
k->log->push_back(what);
*offset += RGFX_ALLOCATIONS_OFFSET;
*size = 0x4000;
std::vector<uint8_t> memory(length, 0);
*bytes = memory.data();
k->chunks[*offset] = std::move(memory);
return true;
}
static void release(void *context, uint64_t offset)
{
PagesKext *k = static_cast<PagesKext *>(context);
if (k->chunks.erase(offset) != 0) {
k->free.give(offset - RGFX_ALLOCATIONS_OFFSET, 0x4000);
k->log->push_back("release chunked");
return;
}
if (k->pages.erase(offset) != 0) {
k->free.give(offset - RGFX_ALLOCATIONS_OFFSET, 0x4000);
k->log->push_back("release pages");
return;
}
auto it = k->blocks.find(offset);
if (it == k->blocks.end())
return;
k->free.give(offset - RGFX_ALLOCATIONS_OFFSET, it->second);
k->blocks.erase(it);
}
};
// The kernel's memory for the pages source: plain pages (`pages`) where `refusePlain` is false,
// else KERN_NO_SPACE.
struct PagesVm {
std::map<uint8_t *, std::vector<uint8_t>> held;
bool refusePlain = false;
std::vector<std::string> *log;
explicit PagesVm(std::vector<std::string> *events) : log(events) {}
static int pages(void *context, uint64_t size, uint8_t **bytes)
{
PagesVm *vm = static_cast<PagesVm *>(context);
const std::string what = "pages " + std::to_string(size);
if (vm->refusePlain) {
vm->log->push_back(what + " refused");
return KERN_NO_SPACE;
}
vm->log->push_back(what);
std::vector<uint8_t> memory(size, 0);
*bytes = memory.data();
vm->held[*bytes] = std::move(memory);
return KERN_SUCCESS;
}
static void unmap(void *context, uint8_t *bytes, uint64_t size)
{
PagesVm *vm = static_cast<PagesVm *>(context);
vm->held.erase(bytes);
vm->log->push_back("unmap " + std::to_string(size));
}
};
bool endsWith(const std::vector<std::string> &log, const std::vector<std::string> &want)
{
return log.size() >= want.size() && std::equal(want.begin(), want.end(), log.end() - want.size());
}
// The process's own pages as the first source: a heaped class's slab is 2 MiB of plain pages the
// take asks the kernel for, wired into a pages block of the kext's, made one HEAP_OVER_PAGES its
// buffers are placed in (BUFFER_AT_OFFSET, and BUFFER_MANAGED_AT_OFFSET where the device took
// MANAGED_AT_OFFSET), the host's heap over the block's view. A dedicated Shared slab larger than
// 2 MiB is plain pages with no heap, its buffer a BUFFER_OVER_PAGES over the view. A larger
// Managed one, a take the kernel gives no pages, and a kext that gives no block (the pages given
// back) are the region's slabs, as are Managed buffers without MANAGED_AT_OFFSET. The slabs'
// thread asks the kernel for nothing. A slab's heap is destroyed, then its block released, then
// its pages go.
void test_pages_slab_source()
{
std::vector<uint8_t> mem(RGFX_ALLOCATIONS_OFFSET + 16 * kMiB, 0xee);
TestRing ring(0x10000);
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell,
nullptr);
RgfxIdSpace ids;
RgfxSerializer ser(writer, ids);
RgfxRegion region(mem.data(), mem.size());
std::vector<std::string> log;
PagesKext kext(16 * kMiB, &log);
region.setBlockSource(&PagesKext::alloc, &PagesKext::release, &kext);
region.setPagesBlockSource(&PagesKext::pagesBlock, &kext);
PagesVm vm(&log);
RgfxPagesMemory calls;
calls.context = &vm;
calls.pages = &PagesVm::pages;
calls.unmap = &PagesVm::unmap;
RgfxRegionSlabSource regionSource(region, ser);
RgfxPagesSlabSource pages(region, ser, calls, 16ull << 30);
CHECK(pages.unit() == 2 * kMiB && pages.heaped(kShared) && !pages.heaped(kManaged));
CHECK(pages.serves(kShared, 2 * kMiB, false) && pages.serves(kSharedUntracked, 2 * kMiB, false));
CHECK(pages.serves(kShared, 4 * kMiB, true) && !pages.serves(kManaged, 2 * kMiB, false));
// Without the kext's chunks a class's slab is 2 MiB, and a buffer past 1 MiB has its own.
CHECK(!pages.serves(kShared, 4 * kMiB, false) && pages.slabMax() == 2 * kMiB);
CHECK(pages.smallMax() == kMiB);
RgfxSlabs slabs(regionSource);
slabs.setFirst(&pages);
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
// The thread has no work, and asks the kernel for nothing; the first take asks for the slab.
CHECK(!slabs.step() && log.empty());
RgfxSlabs::Range a, b;
CHECK(slabs.take(256, kShared, 0, &a) && a.offset == 0 && a.size == 0x1000);
CHECK(log == std::vector<std::string>({"pages 2097152"}) && kext.pages.size() == 1);
CHECK(kext.lastAddress == a.contents && kext.lastLength == 2 * kMiB && kext.lastWritable);
const uint64_t block = *kext.pages.begin();
auto heap = expectMessage<RgfxHeapOverPages>(ring, RGFX_CMD_HEAP_OVER_PAGES);
CHECK(heap.block_offset == block && heap.block_size == 0x4000);
CHECK(heap.size_bytes == 2 * kMiB && heap.options == kShared && heap.heap_type == 1);
CHECK(heap.gpu_address != 0);
CHECK(slabs.take(0x3000, kShared, 0, &b) && b.slab == a.slab && b.offset == 0x1000);
CHECK(allBytes(b.contents, b.size, 0));
RgfxSlabSource::Made made;
CHECK(slabs.makeBuffer(b, 0x2800, kShared, &made));
auto at = expectMessage<RgfxBufferAtOffset>(ring, RGFX_CMD_BUFFER_AT_OFFSET);
CHECK(at.heap_obj_id == heap.obj_id && at.offset == 0x1000 && at.length == 0x2800);
CHECK(made.objId == at.obj_id && made.gpuAddress == heap.gpu_address + 0x1000);
CHECK(!made.ownsAddress);
CHECK(!slabs.step() && log.size() == 1);
// A dedicated buffer of up to 2 MiB: a slab with its heap; a larger one plain pages with no
// heap, its buffer over the block's view.
RgfxSlabs::Range one, big;
CHECK(slabs.take(3 * kMiB / 2, kShared, 0, &one) && one.size == 3 * kMiB / 2);
CHECK(log.size() == 2 && endsWith(log, {"pages 2097152"}) && kext.pages.size() == 2);
CHECK(expectMessage<RgfxHeapOverPages>(ring, RGFX_CMD_HEAP_OVER_PAGES).size_bytes == 2 * kMiB);
CHECK(slabs.take(3 * kMiB, kShared, 0, &big) && big.size == 3 * kMiB && big.offset == 0);
CHECK(log.size() == 3 && endsWith(log, {"pages 4194304"}) && kext.pages.size() == 3);
CHECK(kext.lastAddress == big.contents && kext.lastLength == 4 * kMiB);
CHECK(!ring.next(&h, &bytes));
CHECK(slabs.makeBuffer(big, 3 * kMiB, kShared, &made));
auto bigOver = expectMessage<RgfxBufferOverPages>(ring, RGFX_CMD_BUFFER_OVER_PAGES);
CHECK(bigOver.block_offset == *kext.pages.rbegin() && bigOver.block_size == 0x4000);
CHECK(bigOver.offset == 0 && bigOver.length == 3 * kMiB && bigOver.options == kShared);
CHECK(made.objId == bigOver.obj_id && made.gpuAddress == bigOver.gpu_address);
CHECK(made.ownsAddress && made.gpuAddress != 0);
const size_t asked = log.size();
// Managed, with no MANAGED_AT_OFFSET: the region's slab, unasked.
RgfxSlabs::Range m;
CHECK(slabs.take(0x1000, kManaged, 0, &m) && slabs.makeBuffer(m, 0x1000, kManaged, &made));
CHECK(log.size() == asked);
CHECK(expectMessage<RgfxBufferOverHostMemory>(ring, RGFX_CMD_BUFFER_OVER_HOST_MEMORY).length ==
0x1000);
// Another class's slab, plain pages; with none from the kernel, the region's heaped slab.
RgfxSlabs::Range c, d;
CHECK(slabs.take(0x1000, kSharedUntracked, 0, &c) && log.size() == asked + 1);
CHECK(endsWith(log, {"pages 2097152"}));
vm.refusePlain = true;
CHECK(slabs.take(0x1000, kShared | 0x2, 0, &d) && endsWith(log, {"pages 2097152 refused"}));
vm.refusePlain = false;
while (ring.next(&h, &bytes)) {
}
CHECK(h.type == RGFX_CMD_HEAP_OVER_HOST_MEMORY);
CHECK(slabs.stats().slabs == 6 && slabs.stats().firstSlabs == 4);
// No block from the kext: the pages go back, and the region's slab.
kext.refusePages = true;
log.clear();
RgfxSlabs::Range f;
CHECK(slabs.take(0x1000, kSharedUntracked | 0x2, 0, &f));
CHECK(log == std::vector<std::string>({"pages 2097152", "unmap 2097152"}));
CHECK(vm.held.size() == 4 && slabs.stats().firstSlabs == 4);
kext.refusePages = false;
while (ring.next(&h, &bytes)) {
}
// Every slab let go: each heap destroyed, its pages block released, then its pages.
for (RgfxSlabs::Range *r : {&a, &b, &one, &big, &m, &c, &d, &f})
slabs.give(*r);
log.clear();
CHECK(slabs.reclaim() && slabs.stats().slabs == 0 && kext.pages.empty() && vm.held.empty());
CHECK(log.size() == 8 && std::count(log.begin(), log.end(), "unmap 4194304") == 1);
for (size_t i = 0; i < log.size(); i += 2)
CHECK(log[i] == "release pages" && log[i + 1].rfind("unmap ", 0) == 0);
int destroys = 0;
while (ring.next(&h, &bytes))
destroys += h.type == RGFX_CMD_OBJECT_DESTROY;
CHECK(destroys == 5); // every slab's heap: none for the Managed plain block or the large one
// With MANAGED_AT_OFFSET, a Managed slab is the process's pages too, its buffers' CPU copies
// placed in its heap.
RgfxPagesSlabSource managed(region, ser, calls, 16ull << 30, true);
CHECK(managed.serves(kManaged, 2 * kMiB, true) && !managed.serves(kManaged, 4 * kMiB, true));
CHECK(managed.heaped(kManaged));
RgfxRegionSlabSource managedRegion(region, ser, true);
RgfxSlabs both(managedRegion);
both.setFirst(&managed);
RgfxSlabs::Range g;
CHECK(both.take(0x1000, kManaged, 0, &g) && endsWith(log, {"pages 2097152"}));
auto mheap = expectMessage<RgfxHeapOverPages>(ring, RGFX_CMD_HEAP_OVER_PAGES);
CHECK(mheap.options == kShared && mheap.size_bytes == 2 * kMiB);
CHECK(both.makeBuffer(g, 0x800, kManaged, &made));
auto mat = expectMessage<RgfxBufferManagedAtOffset>(ring, RGFX_CMD_BUFFER_MANAGED_AT_OFFSET);
CHECK(mat.heap_obj_id == mheap.obj_id && mat.offset == 0 && mat.length == 0x800);
CHECK(made.ownsAddress && made.gpuAddress == mat.gpu_address);
// A Managed buffer past 2 MiB: the region's heaped slab, the kernel never asked.
const size_t before = log.size();
RgfxSlabs::Range bigManaged;
CHECK(both.take(3 * kMiB, kManaged, 0, &bigManaged) && log.size() == before);
CHECK(expectMessage<RgfxHeapOverHostMemory>(ring, RGFX_CMD_HEAP_OVER_HOST_MEMORY).size_bytes >=
3 * kMiB);
both.give(g);
both.give(bigManaged);
CHECK(both.reclaim() && kext.pages.empty() && vm.held.empty());
}
// Where the kext makes chunked pages blocks, a slab of the process's own pages is the kext's
// chunks first: a heaped slab's heap and a large Shared slab's buffer are over the chunks' block
// as over plain pages', and the kernel is asked for no pages. A slab the kext gives no chunks for
// is plain pages. A chunked slab goes with its block's release alone, the process unmapping
// nothing; a plain one's pages go after its release.
void test_pages_slab_source_chunks()
{
std::vector<uint8_t> mem(RGFX_ALLOCATIONS_OFFSET + 16 * kMiB, 0xee);
TestRing ring(0x10000);
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell,
nullptr);
RgfxIdSpace ids;
RgfxSerializer ser(writer, ids);
RgfxRegion region(mem.data(), mem.size());
std::vector<std::string> log;
PagesKext kext(16 * kMiB, &log);
region.setBlockSource(&PagesKext::alloc, &PagesKext::release, &kext);
region.setPagesBlockSource(&PagesKext::pagesBlock, &kext);
CHECK(!region.hasChunkedPages());
region.setChunkedPagesSource(&PagesKext::chunked, &kext);
CHECK(region.hasChunkedPages());
PagesVm vm(&log);
RgfxPagesMemory calls;
calls.context = &vm;
calls.pages = &PagesVm::pages;
calls.unmap = &PagesVm::unmap;
RgfxRegionSlabSource regionSource(region, ser);
RgfxPagesSlabSource pages(region, ser, calls, 16ull << 30);
RgfxSlabs slabs(regionSource);
slabs.setFirst(&pages);
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
// A heaped slab: the kext's chunks, the heap over their block, the kernel unasked.
RgfxSlabs::Range a;
CHECK(slabs.take(256, kShared, 0, &a) && a.offset == 0);
CHECK(log == std::vector<std::string>({"chunked 2097152"}) && kext.chunks.size() == 1);
const uint64_t block = kext.chunks.begin()->first;
CHECK(a.contents == kext.chunks.begin()->second.data() && allBytes(a.contents, a.size, 0));
auto heap = expectMessage<RgfxHeapOverPages>(ring, RGFX_CMD_HEAP_OVER_PAGES);
CHECK(heap.block_offset == block && heap.block_size == 0x4000);
CHECK(heap.size_bytes == 2 * kMiB && heap.options == kShared);
RgfxSlabSource::Made made;
CHECK(slabs.makeBuffer(a, 0x100, kShared, &made));
auto at = expectMessage<RgfxBufferAtOffset>(ring, RGFX_CMD_BUFFER_AT_OFFSET);
CHECK(at.heap_obj_id == heap.obj_id && at.offset == 0);
// A large Shared slab, of a buffer past 4 MiB (CHUNKED SLABS GROW): chunks too, its buffer over
// their block's view.
RgfxSlabs::Range big;
CHECK(slabs.take(5 * kMiB, kShared, 0, &big) && big.offset == 0);
CHECK(endsWith(log, {"chunked 6291456"}) && kext.chunks.size() == 2 && vm.held.empty());
CHECK(slabs.makeBuffer(big, 5 * kMiB, kShared, &made));
auto over = expectMessage<RgfxBufferOverPages>(ring, RGFX_CMD_BUFFER_OVER_PAGES);
CHECK(over.block_offset == kext.chunks.rbegin()->first && over.length == 5 * kMiB);
CHECK(made.ownsAddress && made.objId == over.obj_id);
// No chunks from the kext: plain pages, wired into a pages block.
kext.refuseChunks = true;
RgfxSlabs::Range plain;
CHECK(slabs.take(0x1000, kSharedUntracked, 0, &plain));
CHECK(endsWith(log, {"chunked 2097152 refused", "pages 2097152"}) && kext.pages.size() == 1);
CHECK(vm.held.size() == 1);
kext.refuseChunks = false;
while (ring.next(&h, &bytes)) {
}
// Each slab let go: the chunked ones with their release alone, the plain one's pages after
// its release.
for (RgfxSlabs::Range *r : {&a, &big, &plain})
slabs.give(*r);
log.clear();
CHECK(slabs.reclaim() && slabs.stats().slabs == 0);
CHECK(kext.chunks.empty() && kext.pages.empty() && vm.held.empty());
CHECK(log.size() == 4 && std::count(log.begin(), log.end(), "release chunked") == 2);
const auto released = std::find(log.begin(), log.end(), "release pages");
CHECK(released != log.end() && released + 1 != log.end() && released[1] == "unmap 2097152");
}
// Where the kext gives chunks, a class's slabs of the process's pages grow from 2 MiB, doubling, to
// 16 MiB, each one heap over its block, and a buffer of up to 4 MiB lies in them (CHUNKED SLABS
// GROW): the host imports one view a slab, whatever the buffers in it. A buffer past 4 MiB takes a
// slab of its own, as past 1 MiB without chunks; a class's slab past 2 MiB that the kext gives no
// chunks for is no plain pages, but the region's slab of at most 2 MiB that holds the buffer.
void test_chunked_slabs_grow()
{
std::vector<uint8_t> mem(RGFX_ALLOCATIONS_OFFSET + 16 * kMiB, 0xee);
TestRing ring(0x10000);
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell,
nullptr);
RgfxIdSpace ids;
RgfxSerializer ser(writer, ids);
RgfxRegion region(mem.data(), mem.size());
std::vector<std::string> log;
PagesKext kext(16 * kMiB, &log);
region.setBlockSource(&PagesKext::alloc, &PagesKext::release, &kext);
region.setPagesBlockSource(&PagesKext::pagesBlock, &kext);
region.setChunkedPagesSource(&PagesKext::chunked, &kext);
PagesVm vm(&log);
RgfxPagesMemory calls;
calls.context = &vm;
calls.pages = &PagesVm::pages;
calls.unmap = &PagesVm::unmap;
RgfxRegionSlabSource regionSource(region, ser);
RgfxPagesSlabSource pages(region, ser, calls, 16ull << 30);
CHECK(pages.smallMax() == 4 * kMiB && pages.slabMax() == 16 * kMiB);
CHECK(pages.serves(kShared, 16 * kMiB, false) && !pages.serves(kShared, 18 * kMiB, false));
CHECK(!pages.serves(kManaged, 2 * kMiB, false));
RgfxSlabs slabs(regionSource);
slabs.setFirst(&pages);
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
// Buffers of 1 MiB: each new slab of the class twice the last, up to 16 MiB, each a heap.
std::vector<RgfxSlabs::Range> held;
std::vector<uint64_t> heaps;
while (heaps.size() < 6) {
RgfxSlabs::Range r;
CHECK(slabs.take(kMiB, kShared, 0, &r));
held.push_back(r);
while (ring.next(&h, &bytes)) {
if (h.type == RGFX_CMD_HEAP_OVER_PAGES) {
RgfxHeapOverPages m;
std::memcpy(&m, bytes.data(), sizeof(m));
heaps.push_back(m.size_bytes);
}
}
}
CHECK(heaps == std::vector<uint64_t>({2 * kMiB, 4 * kMiB, 8 * kMiB, 16 * kMiB, 16 * kMiB,
16 * kMiB}));
CHECK(std::count(log.begin(), log.end(), "chunked 16777216") == 3 && vm.held.empty());
// A buffer of 4 MiB lies in its class's slab, placed in its heap; one past it has a slab of
// its own, its buffer over the block's view.
RgfxSlabs::Range four, five;
CHECK(slabs.take(4 * kMiB, kShared, 0, &four) && four.slab == held.back().slab);
RgfxSlabSource::Made made;
CHECK(slabs.makeBuffer(four, 4 * kMiB, kShared, &made));
CHECK(expectMessage<RgfxBufferAtOffset>(ring, RGFX_CMD_BUFFER_AT_OFFSET).length == 4 * kMiB);
CHECK(slabs.take(5 * kMiB, kShared, 0, &five) && five.offset == 0 && five.slab != four.slab);
CHECK(endsWith(log, {"chunked 6291456"}));
CHECK(slabs.makeBuffer(five, 5 * kMiB, kShared, &made));
CHECK(expectMessage<RgfxBufferOverPages>(ring, RGFX_CMD_BUFFER_OVER_PAGES).length == 5 * kMiB);
// No chunks for another class's slab of 4 MiB: no plain pages, but the region's heaped slab,
// of 2 MiB at most and at least the buffer.
kext.refuseChunks = true;
RgfxSlabs::Range c1, c2;
CHECK(slabs.take(kMiB, kSharedUntracked, 0, &c1));
CHECK(endsWith(log, {"chunked 2097152 refused", "pages 2097152"}));
CHECK(slabs.take(3 * kMiB / 2, kSharedUntracked, 0, &c2) && c2.slab != c1.slab);
CHECK(endsWith(log, {"chunked 4194304 refused"}) && vm.held.size() == 1);
RgfxHeapOverHostMemory region2 = {};
while (ring.next(&h, &bytes)) {
if (h.type == RGFX_CMD_HEAP_OVER_HOST_MEMORY)
std::memcpy(&region2, bytes.data(), sizeof(region2));
}
CHECK(region2.size_bytes == 2 * kMiB);
kext.refuseChunks = false;
for (auto &r : held)
slabs.give(r);
for (RgfxSlabs::Range *r : {&four, &five, &c1, &c2})
slabs.give(*r);
CHECK(slabs.reclaim() && slabs.stats().slabs == 0);
CHECK(kext.chunks.empty() && kext.pages.empty() && vm.held.empty());
}
// Where the device took MANAGED_BUFFER_SLABS, a Managed buffer lies in its Shared class: a range
// of the Shared buffers' slabs, the process's own pages first, at any size, its CPU copy a Shared
// buffer there (BUFFER_AT_OFFSET in a 2 MiB slab's heap, BUFFER_OVER_PAGES over a larger slab's
// view, BUFFER_AT_OFFSET in a region slab's heap where the kernel gives no pages),
// and the Managed buffer a MANAGED_BUFFER_CREATE over it at an address of its own. Its range goes
// back once the copy's destroy follows the buffer's, the copy's address given back where its
// create picked it.
void test_managed_buffers_over_shared_copies()
{
std::vector<uint8_t> mem(RGFX_ALLOCATIONS_OFFSET + 16 * kMiB, 0xee);
TestRing ring(0x10000);
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell,
nullptr);
RgfxIdSpace ids;
RgfxSerializer ser(writer, ids);
RgfxRegion region(mem.data(), mem.size());
std::vector<std::string> log;
PagesKext kext(16 * kMiB, &log);
region.setBlockSource(&PagesKext::alloc, &PagesKext::release, &kext);
region.setPagesBlockSource(&PagesKext::pagesBlock, &kext);
PagesVm vm(&log);
RgfxPagesMemory calls;
calls.context = &vm;
calls.pages = &PagesVm::pages;
calls.unmap = &PagesVm::unmap;
RgfxRegionSlabSource regionSource(region, ser, false, true);
RgfxPagesSlabSource pages(region, ser, calls, 16ull << 30, false, true);
CHECK(regionSource.overCopy(kManaged) && !regionSource.overCopy(kShared));
CHECK(regionSource.classOptions(kManaged) == kShared && pages.classOptions(kShared) == kShared);
RgfxSlabs slabs(regionSource);
slabs.setFirst(&pages);
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
// A small one: a 2 MiB slab, a heap of the Shared class, shared with a Shared buffer.
RgfxSlabs::Range m, s;
CHECK(slabs.take(0x1000, kManaged, 0, &m) && m.offset == 0 && m.size == 0x1000);
CHECK(log == std::vector<std::string>({"pages 2097152"}));
auto heap = expectMessage<RgfxHeapOverPages>(ring, RGFX_CMD_HEAP_OVER_PAGES);
CHECK(heap.options == kShared && heap.size_bytes == 2 * kMiB);
RgfxSlabSource::Made made;
CHECK(slabs.makeBuffer(m, 0x800, kManaged, &made));
auto copy = expectMessage<RgfxBufferAtOffset>(ring, RGFX_CMD_BUFFER_AT_OFFSET);
CHECK(copy.heap_obj_id == heap.obj_id && copy.offset == 0 && copy.length == 0x800 &&
copy.options == kShared);
auto overWhole = expectMessage<RgfxManagedBufferCreateWhole>(ring, RGFX_CMD_MANAGED_BUFFER_CREATE);
const RgfxManagedBufferCreate &over = overWhole.create;
CHECK(over.cpu_buffer_obj_id == copy.obj_id && over.length == 0x800 &&
over.options == kManaged && over.gpu_address != 0);
CHECK(overWhole.zero.zero_from == 0); // taken with no bytes of the caller's
CHECK(made.objId == over.obj_id && made.gpuAddress == over.gpu_address && made.ownsAddress);
CHECK(slabs.take(0x1000, kShared, 0, &s) && s.slab == m.slab && s.offset == 0x1000);
// A large one: plain pages with no heap, its copy over the block's view.
RgfxSlabs::Range big;
CHECK(slabs.take(3 * kMiB, kManaged, 0, &big) && big.size == 3 * kMiB && big.offset == 0);
CHECK(endsWith(log, {"pages 4194304"}) && kext.pages.size() == 2);
CHECK(!ring.next(&h, &bytes));
CHECK(slabs.makeBuffer(big, 3 * kMiB, kManaged, &made));
auto bigCopy = expectMessage<RgfxBufferOverPages>(ring, RGFX_CMD_BUFFER_OVER_PAGES);
CHECK(bigCopy.offset == 0 && bigCopy.length == 3 * kMiB && bigCopy.options == kShared);
auto bigWhole = expectMessage<RgfxManagedBufferCreateWhole>(ring, RGFX_CMD_MANAGED_BUFFER_CREATE);
const RgfxManagedBufferCreate &bigOver = bigWhole.create;
CHECK(bigOver.cpu_buffer_obj_id == bigCopy.obj_id && bigOver.length == 3 * kMiB);
CHECK(bigWhole.zero.zero_from == 0);
CHECK(made.objId == bigOver.obj_id && bigOver.gpu_address != bigCopy.gpu_address);
CHECK(slabs.stats().slabs == 2 && slabs.stats().firstSlabs == 2);
// No pages from the kernel: a region slab's heap of the Shared class, nothing of the region's
// own.
RgfxSlabs::Range r;
vm.refusePlain = true;
CHECK(slabs.take(0x1000, kManaged | 0x1, 0, &r));
CHECK(endsWith(log, {"pages 2097152 refused"}));
vm.refusePlain = false;
auto regionHeap = expectMessage<RgfxHeapOverHostMemory>(ring, RGFX_CMD_HEAP_OVER_HOST_MEMORY);
CHECK(regionHeap.options == (kShared | 0x1));
CHECK(slabs.makeBuffer(r, 0x1000, kManaged | 0x1, &made));
auto regionCopy = expectMessage<RgfxBufferAtOffset>(ring, RGFX_CMD_BUFFER_AT_OFFSET);
CHECK(regionCopy.heap_obj_id == regionHeap.obj_id && regionCopy.options == (kShared | 0x1));
auto regionWhole =
expectMessage<RgfxManagedBufferCreateWhole>(ring, RGFX_CMD_MANAGED_BUFFER_CREATE);
const RgfxManagedBufferCreate &regionOver = regionWhole.create;
CHECK(regionOver.cpu_buffer_obj_id == regionCopy.obj_id && regionOver.options == (kManaged | 0x1));
CHECK(regionWhole.zero.zero_from == 0);
// Each give destroys its copy, and only then is the range free again: the small Managed
// buffer's range is taken again by the next buffer of the class.
CHECK(!ring.next(&h, &bytes));
slabs.give(m);
auto destroyed = expectMessage<RgfxObjectDestroy>(ring, RGFX_CMD_OBJECT_DESTROY);
CHECK(destroyed.obj_id == copy.obj_id && !ring.next(&h, &bytes));
RgfxSlabs::Range again;
CHECK(slabs.take(0x1000, kManaged, 0, &again) && again.slab == m.slab && again.offset == 0);
// A Shared buffer's give destroys nothing of its own.
slabs.give(s);
CHECK(!ring.next(&h, &bytes));
slabs.give(big);
CHECK(expectMessage<RgfxObjectDestroy>(ring, RGFX_CMD_OBJECT_DESTROY).obj_id == bigCopy.obj_id);
slabs.give(r);
CHECK(expectMessage<RgfxObjectDestroy>(ring, RGFX_CMD_OBJECT_DESTROY).obj_id ==
regionCopy.obj_id);
slabs.give(again);
// One whose caller writes its first bytes: its create says its bytes read zero from there,
// as they do; and nothing of one whose caller writes all of it.
auto nextCreate = [&]() {
RgfxManagedBufferCreateWhole whole = {};
while (ring.next(&h, &bytes)) {
if (h.type != RGFX_CMD_MANAGED_BUFFER_CREATE)
continue;
CHECK(bytes.size() == sizeof(whole));
std::memcpy(&whole, bytes.data(), sizeof(whole));
return whole;
}
CHECK(false);
return whole;
};
RgfxSlabs::Range kept, full;
CHECK(slabs.take(0x1000, kManaged, 0x300, &kept) && kept.zeroFrom == 0x300);
CHECK(allBytes(kept.contents + 0x300, 0xd00, 0));
CHECK(slabs.makeBuffer(kept, 0x800, kManaged, &made));
auto keptCreate = nextCreate();
CHECK(keptCreate.create.obj_id == made.objId && keptCreate.create.length == 0x800 &&
keptCreate.zero.zero_from == 0x300);
CHECK(slabs.take(0x800, kManaged, 0x800, &full) && full.zeroFrom == 0x800);
CHECK(slabs.makeBuffer(full, 0x800, kManaged, &made));
auto fullCreate = nextCreate();
CHECK(fullCreate.create.obj_id == made.objId && fullCreate.zero.zero_from == 0x800);
slabs.give(kept);
slabs.give(full);
while (ring.next(&h, &bytes)) {
}
CHECK(slabs.reclaim() && slabs.stats().slabs == 0 && kext.pages.empty() && vm.held.empty());
while (ring.next(&h, &bytes)) {
}
}
// The kext's blocks of the device's Shared pool for the pool source: first fit in 64 KiB blocks
// of a pool of `size` bytes whose first block another process holds, each block `fill` (0, as the
// host zeroes it) as it comes. Each take and give is logged, and a give first logs the destroys
// on the ring then, which the slab's let-go posted before it.
struct PoolKext {
RgfxHeapRanges free;
std::map<uint64_t, std::vector<uint8_t>> blocks; // by offset in the pool
std::vector<std::string> *log;
TestRing *ring;
bool refuse = false;
uint8_t fill = 0;
// The GPU address of the pool's start where the host gives blocks theirs
// (RGFX_FEATURE_POOL_ADDRESSES): a block's is it plus the block's offset; 0 for none.
uint64_t gpuBase = 0;
PoolKext(uint64_t size, std::vector<std::string> *events, TestRing *posted)
: free(size), log(events), ring(posted)
{
uint64_t held = 0;
free.take(RgfxPoolSlabSource::kUnit, RgfxPoolSlabSource::kUnit, &held);
}
static int take(void *context, uint64_t size, uint8_t **bytes, uint64_t *offset,
uint64_t *gpu_address)
{
PoolKext *k = static_cast<PoolKext *>(context);
const std::string what = "take " + std::to_string(size);
if (k->refuse || !k->free.take(size, RgfxPoolSlabSource::kUnit, offset)) {
k->log->push_back(what + " refused");
return KERN_NO_SPACE;
}
k->log->push_back(what);
std::vector<uint8_t> memory(size, k->fill);
*bytes = memory.data();
*gpu_address = k->gpuBase != 0 ? k->gpuBase + *offset : 0;
k->blocks[*offset] = std::move(memory);
return KERN_SUCCESS;
}
static void give(void *context, uint64_t offset)
{
PoolKext *k = static_cast<PoolKext *>(context);
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
while (k->ring->next(&h, &bytes)) {
if (h.type != RGFX_CMD_OBJECT_DESTROY || bytes.size() != sizeof(RgfxObjectDestroy)) {
k->log->push_back("message " + std::to_string(h.type));
continue;
}
RgfxObjectDestroy destroy;
std::memcpy(&destroy, bytes.data(), sizeof(destroy));
k->log->push_back("destroy " + std::to_string(destroy.obj_id));
}
auto it = k->blocks.find(offset);
if (it == k->blocks.end()) {
k->log->push_back("give of no block");
return;
}
k->free.give(offset, it->second.size());
k->log->push_back("give " + std::to_string(it->second.size()));
k->blocks.erase(it);
}
};
// What the tests' pool sources answer as their capacity, which sizes the cache of their slabs: a
// guest's RAM of 1 GiB, as the device gives its own (a sixteenth, 64 MiB, cached at most).
constexpr uint64_t kPoolCapacity = 1024 * kMiB;
// The device's Shared pool as the slabs' one source: a heaped class's slab is a block of the pool
// the kext maps, zero as the host gives it, made one HEAP_OVER_POOL whose region_offset is the
// block's offset in the pool, its buffers placed in it (BUFFER_AT_OFFSET, and
// BUFFER_MANAGED_AT_OFFSET where the device took MANAGED_AT_OFFSET, or a Managed buffer over a
// Shared copy where it took MANAGED_BUFFER_SLABS). A class holds buffers of up to 4 MiB in slabs
// of up to 16 MiB, and a larger buffer has a block and a heap of its own. No region is behind the
// pool: a Managed class with no heap, a buffer past the longest block and a buffer the kext takes
// no block for, after slabs half as large down to its size, are nil, and the region gives no
// block. The pool's slabs are kept once empty as the region's are (LETTING GO): an emptied class
// slab, and a large buffer's own in the cache, serve a later buffer, and each goes kCacheIdleMs
// after its last buffer, its heap's destroy posted, then its block given back.
void test_pool_slab_source()
{
using Pool = RgfxPoolSlabSource;
std::vector<uint8_t> mem(RGFX_ALLOCATIONS_OFFSET + 16 * kMiB, 0xee);
TestRing ring(0x10000);
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell,
nullptr);
RgfxIdSpace ids;
RgfxSerializer ser(writer, ids);
RgfxRegion region(mem.data(), mem.size());
std::vector<std::string> log;
PagesKext regionKext(16 * kMiB, &log);
region.setBlockSource(&PagesKext::alloc, &PagesKext::release, &regionKext);
PoolKext kext(64 * kMiB, &log, &ring);
RgfxPoolMemory calls;
calls.context = &kext;
calls.take = &PoolKext::take;
calls.give = &PoolKext::give;
Pool pool(region, ser, calls, kPoolCapacity);
CHECK(pool.unit() == 64 * 1024 && pool.smallMax() == 4 * kMiB && pool.slabMax() == 16 * kMiB);
CHECK(pool.capacity() == kPoolCapacity && pool.heaped(kShared) && !pool.heaped(kManaged));
CHECK(pool.serves(kShared, Pool::kUnit, false) && pool.serves(kSharedUntracked, 16 * kMiB, false));
CHECK(!pool.serves(kShared, 32 * kMiB, false) && pool.serves(kShared, 32 * kMiB, true));
CHECK(!pool.serves(kShared, 0x4000, false) && !pool.serves(kShared, 0, true));
CHECK(pool.serves(kShared, Pool::kTakeMax, true));
CHECK(!pool.serves(kShared, Pool::kTakeMax + Pool::kUnit, true));
CHECK(!pool.serves(kManaged, Pool::kUnit, false) && !pool.serves(kManaged, 8 * kMiB, true));
CHECK(pool.heapedSlab(32 * kMiB, kShared, true));
RgfxSlabs slabs(pool);
g_testNowMs = 1000;
slabs.setClock(&testClock, nullptr);
auto settle = [&] {
while (slabs.step()) {
}
};
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
auto drain = [&] {
while (ring.next(&h, &bytes)) {
}
};
// The thread has no work and takes nothing; the first take takes the class's slab, past the
// block another process holds. The host zeroed it, and the allocator writes none of it: a
// block the test fills with 0xee reads 0xee.
CHECK(!slabs.step() && log.empty());
RgfxSlabs::Range a, b;
kext.fill = 0xee;
CHECK(slabs.take(256, kShared, 0, &a) && a.offset == 0 && a.size == 0x1000);
kext.fill = 0;
CHECK(log == std::vector<std::string>({"take 131072"}) && kext.blocks.size() == 1);
CHECK(a.contents == kext.blocks.at(Pool::kUnit).data() && allBytes(a.contents, a.size, 0xee));
CHECK(slabs.stats().dirtyBytes == 0 && slabs.stats().slabs == 1);
auto heap = expectMessage<RgfxHeapOverHostMemory>(ring, RGFX_CMD_HEAP_OVER_POOL);
CHECK(heap.region_offset == Pool::kUnit && heap.size_bytes == 128 * 1024);
CHECK(heap.options == kShared && heap.heap_type == 1 && heap.gpu_address != 0);
CHECK(slabs.take(0x3000, kShared, 0, &b) && b.slab == a.slab && b.offset == 0x1000);
RgfxSlabSource::Made made;
CHECK(slabs.makeBuffer(b, 0x2800, kShared, &made));
auto at = expectMessage<RgfxBufferAtOffset>(ring, RGFX_CMD_BUFFER_AT_OFFSET);
CHECK(at.heap_obj_id == heap.obj_id && at.offset == 0x1000 && at.length == 0x2800);
CHECK(made.objId == at.obj_id && made.gpuAddress == heap.gpu_address + 0x1000);
CHECK(!made.ownsAddress && !slabs.step() && log.size() == 1);
// A 3 MiB buffer shares its class's slab, 8 MiB from the pool; a buffer past 4 MiB has a block
// of its own, whole blocks, with its heap, its buffer at the heap's start.
RgfxSlabs::Range c, d;
CHECK(slabs.take(3 * kMiB, kShared, 0, &c) && c.offset == 0 && c.slab != a.slab);
CHECK(endsWith(log, {"take 8388608"}));
auto cheap = expectMessage<RgfxHeapOverHostMemory>(ring, RGFX_CMD_HEAP_OVER_POOL);
CHECK(cheap.region_offset == 3 * Pool::kUnit && cheap.size_bytes == 8 * kMiB);
CHECK(slabs.take(5 * kMiB + 0x1000, kShared, 0, &d) && d.offset == 0);
CHECK(d.size == 5 * kMiB + 0x1000 && endsWith(log, {"take 5308416"}));
auto dheap = expectMessage<RgfxHeapOverHostMemory>(ring, RGFX_CMD_HEAP_OVER_POOL);
CHECK(dheap.region_offset == 3 * Pool::kUnit + 8 * kMiB && dheap.size_bytes == 5308416);
CHECK(slabs.makeBuffer(d, 5 * kMiB + 0x1000, kShared, &made));
auto dat = expectMessage<RgfxBufferAtOffset>(ring, RGFX_CMD_BUFFER_AT_OFFSET);
CHECK(dat.heap_obj_id == dheap.obj_id && dat.offset == 0 && dat.length == 5 * kMiB + 0x1000);
CHECK(made.gpuAddress == dheap.gpu_address && !made.ownsAddress);
drain();
// Managed, with no MANAGED_AT_OFFSET: a class the pool has no heap for, so nil, nothing taken
// and nothing sent.
const size_t asked = log.size();
RgfxSlabs::Range m;
CHECK(!slabs.take(0x1000, kManaged, 0, &m) && log.size() == asked && !ring.next(&h, &bytes));
// A buffer past the longest block: nil, nothing taken.
CHECK(!slabs.take(Pool::kTakeMax + 1, kShared, 0, &m) && log.size() == asked);
CHECK(!ring.next(&h, &bytes));
// A take the kext refuses: asked again once the process's slabs went, then half as large down
// to the buffer's size, and nil, with no slab of the region's.
RgfxSlabs::Range f;
kext.refuse = true;
CHECK(!slabs.take(0x1000, kSharedUntracked, 0, &f));
CHECK(endsWith(log, {"take 131072 refused", "take 131072 refused", "take 65536 refused"}));
kext.refuse = false;
CHECK(!ring.next(&h, &bytes) && regionKext.blocks.empty());
CHECK(slabs.stats().slabs == 3);
Pool::Takes t = pool.takes();
CHECK(t.taken == 3 && t.takenBytes == 131072 + 8388608 + 5308416 && t.refused == 3);
CHECK(t.given == 0 && t.longestUs <= t.waitUs && t.addressed == 0);
// The slabs are kept once their buffers go: the class's two, emptied, and the large buffer's
// own, cached. Nothing is destroyed or given back.
drain();
log.clear();
slabs.give(c);
slabs.give(d);
slabs.give(a);
slabs.give(b);
CHECK(log.empty() && kext.blocks.size() == 3 && slabs.stats().slabs == 3);
CHECK(slabs.stats().emptySlabs == 2 && slabs.stats().cachedSlabs == 1);
// A later buffer of the class lies in the oldest kept slab, and a large one in the cached
// slab, with no block taken.
RgfxSlabs::Range again, large;
CHECK(slabs.take(0x1000, kShared, 0, &again) && again.slab == a.slab && again.offset == 0);
CHECK(slabs.take(5 * kMiB, kShared, 0, &large) && large.slab == d.slab && large.offset == 0);
CHECK(log.empty() && slabs.churn().refilled == 1 && slabs.churn().dedicatedReused == 1);
slabs.give(again);
slabs.give(large);
// Not yet a millisecond before kCacheIdleMs; then each goes, its heap destroyed before its
// block is given back: the cached slab first, then the class's in the order they were made.
g_testNowMs += RgfxSlabs::kCacheIdleMs - 1;
settle();
CHECK(log.empty() && slabs.stats().slabs == 3);
g_testNowMs += 1;
settle();
CHECK(log == std::vector<std::string>({"destroy " + std::to_string(dheap.obj_id), "give 5308416",
"destroy " + std::to_string(heap.obj_id), "give 131072",
"destroy " + std::to_string(cheap.obj_id),
"give 8388608"}));
CHECK(kext.blocks.empty() && slabs.stats().slabs == 0);
CHECK(slabs.churn().emptyLetGo == 2 && slabs.churn().refilled == 1);
CHECK(pool.takes().given == 3 && pool.takes().taken == 3);
// A later buffer of the class takes a block again, of the class's first size, as the class
// holds no slab (THE SIZES), kept once it goes.
RgfxSlabs::Range later;
CHECK(slabs.take(0x1000, kShared, 0, &later) && log.size() == 7);
CHECK(log.back() == "take 131072" && kext.blocks.size() == 1);
drain();
slabs.give(later);
CHECK(log.size() == 7 && slabs.stats().emptySlabs == 1);
g_testNowMs += RgfxSlabs::kCacheIdleMs;
settle();
CHECK(log.size() == 9 && endsWith(log, {"give " + log[6].substr(5)}) && kext.blocks.empty());
drain();
CHECK(slabs.stats().slabs == 0 && regionKext.blocks.empty());
CHECK(pool.takes().taken == 4 && pool.takes().given == 4 && pool.takes().refused == 3);
// A pool with room for a block of 64 KiB alone: the class's slab of 128 KiB is refused, and
// one half as large, the buffer's size, taken.
{
PoolKext tight(2 * Pool::kUnit, &log, &ring);
RgfxPoolMemory tightCalls = calls;
tightCalls.context = &tight;
Pool small(region, ser, tightCalls, kPoolCapacity);
RgfxSlabs halved(small);
log.clear();
RgfxSlabs::Range e;
CHECK(halved.take(0x1000, kShared, 0, &e) && e.offset == 0);
CHECK(log == std::vector<std::string>(
{"take 131072 refused", "take 131072 refused", "take 65536"}));
auto eheap = expectMessage<RgfxHeapOverHostMemory>(ring, RGFX_CMD_HEAP_OVER_POOL);
CHECK(eheap.region_offset == Pool::kUnit && eheap.size_bytes == Pool::kUnit);
halved.give(e);
CHECK(halved.reclaim()); // the kept slab let go now, as where a take found no room
CHECK(endsWith(log, {"destroy " + std::to_string(eheap.obj_id), "give 65536"}));
CHECK(tight.blocks.empty() && regionKext.blocks.empty());
drain();
}
// With MANAGED_AT_OFFSET, a Managed class's slab is a block of the pool too, its buffers' CPU
// copies placed in its Shared heap.
Pool managed(region, ser, calls, kPoolCapacity, true);
CHECK(managed.heaped(kManaged) && managed.serves(kManaged, Pool::kUnit, false));
RgfxSlabs both(managed);
log.clear();
RgfxSlabs::Range g;
CHECK(both.take(0x1000, kManaged, 0, &g) && log == std::vector<std::string>({"take 131072"}));
auto mheap = expectMessage<RgfxHeapOverHostMemory>(ring, RGFX_CMD_HEAP_OVER_POOL);
CHECK(mheap.options == kShared && mheap.size_bytes == 128 * 1024);
CHECK(mheap.region_offset == kext.blocks.begin()->first);
CHECK(both.makeBuffer(g, 0x800, kManaged, &made));
auto mat = expectMessage<RgfxBufferManagedAtOffset>(ring, RGFX_CMD_BUFFER_MANAGED_AT_OFFSET);
CHECK(mat.heap_obj_id == mheap.obj_id && mat.offset == 0 && mat.length == 0x800);
CHECK(made.ownsAddress && made.gpuAddress == mat.gpu_address);
drain();
both.give(g);
CHECK(both.reclaim());
CHECK(endsWith(log, {"destroy " + std::to_string(mheap.obj_id), "give 131072"}));
CHECK(kext.blocks.empty() && managed.takes().given == 1);
drain();
// With MANAGED_BUFFER_SLABS, as the device takes the pool, a Managed buffer lies over a Shared
// copy in its Shared class's block.
Pool copies(region, ser, calls, kPoolCapacity, false, true);
RgfxSlabs over(copies);
log.clear();
RgfxSlabs::Range o;
CHECK(over.take(0x1000, kManaged, 0, &o) && log == std::vector<std::string>({"take 131072"}));
auto oheap = expectMessage<RgfxHeapOverHostMemory>(ring, RGFX_CMD_HEAP_OVER_POOL);
CHECK(oheap.options == kShared && oheap.size_bytes == 128 * 1024);
CHECK(over.makeBuffer(o, 0x800, kManaged, &made));
auto copy = expectMessage<RgfxBufferAtOffset>(ring, RGFX_CMD_BUFFER_AT_OFFSET);
CHECK(copy.heap_obj_id == oheap.obj_id && copy.offset == 0 && copy.options == kShared);
auto overWhole =
expectMessage<RgfxManagedBufferCreateWhole>(ring, RGFX_CMD_MANAGED_BUFFER_CREATE);
CHECK(overWhole.create.cpu_buffer_obj_id == copy.obj_id && overWhole.create.length == 0x800);
CHECK(made.objId == overWhole.create.obj_id && made.ownsAddress);
drain();
over.give(o);
CHECK(over.reclaim());
// The Managed buffer's own destroy is its RgfxBuffer's: the slabs post its copy's.
CHECK(endsWith(log, {"destroy " + std::to_string(copy.obj_id),
"destroy " + std::to_string(oheap.obj_id), "give 131072"}));
CHECK(kext.blocks.empty() && copies.takes().given == 1 && regionKext.blocks.empty());
drain();
}
// Where the host gives a block of the pool its GPU address (RGFX_FEATURE_POOL_ADDRESSES), the
// block's heap lies there, picked by no one in the process's range of addresses, its buffers at
// their offsets from it; the heap's drop gives no address of the process's back, though one of
// its picks starts there. A Managed buffer's own address is still the process's pick.
void test_pool_slab_source_at_host_addresses()
{
using Pool = RgfxPoolSlabSource;
std::vector<uint8_t> mem(RGFX_ALLOCATIONS_OFFSET + 16 * kMiB, 0xee);
TestRing ring(0x10000);
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell,
nullptr);
// Room for one pick of a page, which the process holds: the slabs pick nothing more.
RgfxIdSpace ids(RGFX_CONTEXT_VA_BASE, RgfxIdSpace::addressSpan(0x1000));
const uint64_t picked = ids.allocAddress(0x1000, 1);
CHECK(picked == RGFX_CONTEXT_VA_BASE && ids.allocAddress(0x1000, 1) == 0);
RgfxSerializer ser(writer, ids);
RgfxRegion region(mem.data(), mem.size());
std::vector<std::string> log;
PoolKext kext(64 * kMiB, &log, &ring);
RgfxPoolMemory calls;
calls.context = &kext;
calls.take = &PoolKext::take;
calls.give = &PoolKext::give;
Pool pool(region, ser, calls, kPoolCapacity);
RgfxSlabs slabs(pool);
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
auto drain = [&] {
while (ring.next(&h, &bytes)) {
}
};
// A block at the host's address 2^45 plus its offset in the pool. (Each slab, kept once
// empty, is let go with reclaim, as where a take found no room.)
kext.gpuBase = 1ull << 45;
RgfxSlabs::Range a, b;
CHECK(slabs.take(256, kShared, 0, &a) && log == std::vector<std::string>({"take 131072"}));
auto heap = expectMessage<RgfxHeapOverHostMemory>(ring, RGFX_CMD_HEAP_OVER_POOL);
CHECK(heap.region_offset == Pool::kUnit && heap.size_bytes == 128 * 1024);
CHECK(heap.gpu_address == (1ull << 45) + Pool::kUnit);
CHECK(slabs.take(0x3000, kShared, 0, &b) && b.slab == a.slab && b.offset == 0x1000);
RgfxSlabSource::Made made;
CHECK(slabs.makeBuffer(b, 0x2800, kShared, &made));
auto at = expectMessage<RgfxBufferAtOffset>(ring, RGFX_CMD_BUFFER_AT_OFFSET);
CHECK(at.heap_obj_id == heap.obj_id && at.offset == 0x1000);
CHECK(made.gpuAddress == heap.gpu_address + 0x1000 && !made.ownsAddress);
CHECK(pool.takes().taken == 1 && pool.takes().addressed == 1);
drain();
log.clear();
slabs.give(a);
slabs.give(b);
CHECK(log.empty() && slabs.reclaim());
CHECK(log == std::vector<std::string>(
{"destroy " + std::to_string(heap.obj_id), "give 131072"}));
// A host address where a pick of the process's starts: the heap's drop leaves the pick held.
// (The class holds no slab, so its next is of its first size again: THE SIZES.)
kext.gpuBase = picked - Pool::kUnit;
RgfxSlabs::Range c;
CHECK(slabs.take(0x1000, kShared, 0, &c) && log.back() == "take 131072");
const std::string took = log.back().substr(5);
auto cheap = expectMessage<RgfxHeapOverHostMemory>(ring, RGFX_CMD_HEAP_OVER_POOL);
CHECK(cheap.region_offset == Pool::kUnit && cheap.gpu_address == picked);
drain();
slabs.give(c);
CHECK(slabs.reclaim());
CHECK(endsWith(log, {"destroy " + std::to_string(cheap.obj_id), "give " + took}));
CHECK(ids.allocAddress(0x1000, 1) == 0);
ids.freeAddress(picked);
CHECK(ids.allocAddress(0x1000, 1) == picked);
CHECK(pool.takes().addressed == 2 && pool.takes().given == 2 && kext.blocks.empty());
drain();
}
// Where the host makes Managed buffers at their copies (RGFX_FEATURE_MANAGED_AT_COPY, a GPU that
// shares the CPU's memory), a Managed buffer over a Shared copy in a pool block at the host's
// address lies at the copy's address, with no pick of the process's: one is made with no room
// left for a pick, where without the feature none is. Its address goes back with its copy, so
// its give leaves the process's own pick held.
void test_pool_managed_buffers_at_their_copies()
{
using Pool = RgfxPoolSlabSource;
std::vector<uint8_t> mem(RGFX_ALLOCATIONS_OFFSET + 16 * kMiB, 0xee);
TestRing ring(0x10000);
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell,
nullptr);
// Room for one pick of a page, which the process holds: no pick is left for anything else.
RgfxIdSpace ids(RGFX_CONTEXT_VA_BASE, RgfxIdSpace::addressSpan(0x1000));
const uint64_t picked = ids.allocAddress(0x1000, 1);
CHECK(picked == RGFX_CONTEXT_VA_BASE && ids.allocAddress(0x1000, 1) == 0);
RgfxSerializer ser(writer, ids);
RgfxRegion region(mem.data(), mem.size());
std::vector<std::string> log;
PoolKext kext(64 * kMiB, &log, &ring);
kext.gpuBase = 1ull << 45;
RgfxPoolMemory calls;
calls.context = &kext;
calls.take = &PoolKext::take;
calls.give = &PoolKext::give;
Pool pool(region, ser, calls, kPoolCapacity, false, true);
RgfxSlabs slabs(pool);
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
auto drain = [&] {
while (ring.next(&h, &bytes)) {
}
};
// Without the feature: the Managed buffer's address is a pick, and none is left.
RgfxSlabs::Range m;
RgfxSlabSource::Made made;
CHECK(!ser.managedAtCopy());
CHECK(slabs.take(0x1000, kManaged, 0, &m));
CHECK(!slabs.makeBuffer(m, 0x800, kManaged, &made));
drain();
slabs.give(m);
CHECK(slabs.reclaim()); // its slab, kept once empty, let go
drain();
// With it: at the copy's address, the heap's at the host's address plus its offset.
ser.setManagedAtCopy(true);
log.clear();
RgfxSlabs::Range a, b;
CHECK(slabs.take(0x1000, kShared, 0, &a) && slabs.take(0x1000, kManaged, 0, &b));
CHECK(b.slab == a.slab && b.offset == 0x1000);
CHECK(log.size() == 1 && log[0].rfind("take ", 0) == 0);
const std::string took = log[0].substr(5);
auto heap = expectMessage<RgfxHeapOverHostMemory>(ring, RGFX_CMD_HEAP_OVER_POOL);
CHECK(heap.gpu_address >= (1ull << 45) && heap.options == kShared);
CHECK(slabs.makeBuffer(b, 0x800, kManaged, &made));
auto copy = expectMessage<RgfxBufferAtOffset>(ring, RGFX_CMD_BUFFER_AT_OFFSET);
CHECK(copy.heap_obj_id == heap.obj_id && copy.offset == 0x1000 && copy.options == kShared);
auto overWhole =
expectMessage<RgfxManagedBufferCreateWhole>(ring, RGFX_CMD_MANAGED_BUFFER_CREATE);
CHECK(overWhole.create.cpu_buffer_obj_id == copy.obj_id && overWhole.create.length == 0x800 &&
overWhole.create.options == kManaged);
CHECK(overWhole.create.gpu_address == heap.gpu_address + 0x1000);
CHECK(made.objId == overWhole.create.obj_id && made.gpuAddress == heap.gpu_address + 0x1000 &&
!made.ownsAddress);
CHECK(ids.privatePicksLive() == 0 && ids.privateBlocksHeld() == 0);
drain();
slabs.give(b);
slabs.give(a);
CHECK(slabs.reclaim());
CHECK(endsWith(log, {"destroy " + std::to_string(copy.obj_id),
"destroy " + std::to_string(heap.obj_id), "give " + took}));
// Nothing of the process's went back: its own pick is still held.
CHECK(ids.allocAddress(0x1000, 1) == 0);
ids.freeAddress(picked);
CHECK(ids.allocAddress(0x1000, 1) == picked);
CHECK(kext.blocks.empty());
drain();
}
// One buffer made and freed again and again in an otherwise empty class of the pool, 60 ms apart
// (about 17 a second), then one large buffer the same way: the class keeps its emptied slab and
// the cache the large buffer's own, so the 100 buffers of each take one block of the pool between
// them, not one a buffer, and the class's slab stays its first, 128 KiB, rather than growing to
// 16 MiB a new slab at a time. Each buffer reads zeros as it comes, though the one before it in
// the same range wrote 0xa5 over its bytes: zeroed by the background between them, or by the take
// itself where the background had not run. Each slab goes kCacheIdleMs after the last free.
void test_pool_slab_churn_is_bounded()
{
using Pool = RgfxPoolSlabSource;
std::vector<uint8_t> mem(RGFX_ALLOCATIONS_OFFSET + 16 * kMiB, 0xee);
TestRing ring(0x10000);
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell,
nullptr);
RgfxIdSpace ids;
RgfxSerializer ser(writer, ids);
RgfxRegion region(mem.data(), mem.size());
std::vector<std::string> log;
PoolKext kext(256 * kMiB, &log, &ring);
RgfxPoolMemory calls;
calls.context = &kext;
calls.take = &PoolKext::take;
calls.give = &PoolKext::give;
Pool pool(region, ser, calls, kPoolCapacity);
RgfxSlabs slabs(pool);
g_testNowMs = 1000;
slabs.setClock(&testClock, nullptr);
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
auto drain = [&] {
while (ring.next(&h, &bytes)) {
}
};
auto settle = [&] {
while (slabs.step()) {
}
};
constexpr int kRounds = 100;
const void *small = nullptr;
for (int i = 0; i < kRounds; i++) {
RgfxSlabs::Range r;
RgfxSlabSource::Made made;
CHECK(slabs.take(0x1000, kShared, 0, &r) && slabs.makeBuffer(r, 0x1000, kShared, &made));
CHECK(allBytes(r.contents, r.size, 0) && (small == nullptr || r.slab == small));
small = r.slab;
std::memset(r.contents, 0xa5, r.size);
drain();
slabs.give(r);
if (i % 2 == 0)
settle();
g_testNowMs += 60;
}
settle();
RgfxSlabs::Churn c = slabs.churn();
CHECK(c.classMade == 1 && c.classMadeBytes == 128 * 1024 && c.emptied == kRounds);
CHECK(c.refilled == kRounds - 1 && c.emptyLetGo == 0);
CHECK(pool.takes().taken == 1 && pool.takes().given == 0 && log.size() == 1);
// kCacheIdleMs after the last free, the slab goes: its heap destroyed, its block given back.
g_testNowMs += RgfxSlabs::kCacheIdleMs;
settle();
CHECK(slabs.churn().emptyLetGo == 1 && slabs.stats().slabs == 0 && kext.blocks.empty());
CHECK(log.size() == 3 && log[2] == "give 131072" && pool.takes().given == 1);
constexpr int kLargeRounds = 20;
const void *large = nullptr;
for (int i = 0; i < kLargeRounds; i++) {
RgfxSlabs::Range r;
RgfxSlabSource::Made made;
CHECK(slabs.take(5 * kMiB, kShared, 0, &r) && slabs.makeBuffer(r, 5 * kMiB, kShared, &made));
CHECK(allBytes(r.contents, r.size, 0) && (large == nullptr || r.slab == large));
large = r.slab;
std::memset(r.contents, 0xa5, r.size);
drain();
slabs.give(r);
if (i % 2 == 0)
settle();
g_testNowMs += 60;
}
settle();
c = slabs.churn();
CHECK(c.dedicatedMade == 1 && c.dedicatedReused == kLargeRounds - 1);
CHECK(c.dedicatedReusedBytes == (kLargeRounds - 1) * 5 * kMiB);
CHECK(pool.takes().taken == 2 && pool.takes().given == 1);
CHECK(log.size() == 4 && log[3] == "take 5242880" && slabs.stats().cachedSlabs == 1);
g_testNowMs += RgfxSlabs::kCacheIdleMs;
settle();
CHECK(slabs.stats().slabs == 0 && kext.blocks.empty());
CHECK(log.size() == 6 && log[5] == "give 5242880");
CHECK(pool.takes().taken == 2 && pool.takes().given == 2 && pool.takes().refused == 0);
drain();
}
// A class left with no slab, none holding a buffer and none kept, grows from its first size again
// (THE SIZES): a buffer that comes once its class's slabs went takes a slab of 128 KiB, not of the
// largest size the class grew to. While the class keeps an empty slab, a new one goes on at the
// size it grew to. Over the test's own source, and over the Shared pool's.
void test_slab_class_starts_again_once_empty()
{
Source source(64 * kMiB);
RgfxSlabs slabs(source);
auto lastTake = [&]() -> std::string {
for (auto it = source.log.rbegin(); it != source.log.rend(); ++it) {
if (it->rfind("take ", 0) == 0)
return *it;
}
return "";
};
// Slabs of 128 KiB, 256, 512, 1 MiB, then 2 MiB; all emptied, the first two kept.
std::vector<RgfxSlabs::Range> held;
while (source.takes < 7) {
RgfxSlabs::Range r;
CHECK(slabs.take(0x10000, kShared, 0, &r));
held.push_back(r);
}
CHECK(lastTake() == "take 2097152");
for (auto &r : held)
slabs.give(r);
CHECK(slabs.stats().emptySlabs == 2 && slabs.stats().slabs == 2);
// A buffer neither kept slab holds takes a new slab of 2 MiB, the size the class grew to; a
// third empty slab, it goes with its buffer.
RgfxSlabs::Range wide;
CHECK(slabs.take(0x60000, kShared, 0, &wide) && lastTake() == "take 2097152");
CHECK(source.takes == 8);
slabs.give(wide);
CHECK(slabs.stats().slabs == 2);
// Once the kept slabs go too, the class starts again at 128 KiB, and grows from there.
CHECK(slabs.reclaim() && slabs.stats().slabs == 0);
RgfxSlabs::Range again, more;
CHECK(slabs.take(0x1000, kShared, 0, &again) && lastTake() == "take 131072");
CHECK(slabs.take(0x20000, kShared, 0, &more) && lastTake() == "take 262144");
CHECK(source.takes == 10);
slabs.give(again);
slabs.give(more);
// The pool's: a 4 MiB buffer's slab of 8 MiB, kept once empty and taken from again; once it
// went, a buffer of a page takes a block of 128 KiB, not of 16 MiB.
using Pool = RgfxPoolSlabSource;
std::vector<uint8_t> mem(RGFX_ALLOCATIONS_OFFSET + 16 * kMiB, 0xee);
TestRing ring(0x10000);
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell,
nullptr);
RgfxIdSpace ids;
RgfxSerializer ser(writer, ids);
RgfxRegion region(mem.data(), mem.size());
std::vector<std::string> log;
PoolKext kext(64 * kMiB, &log, &ring);
RgfxPoolMemory calls;
calls.context = &kext;
calls.take = &PoolKext::take;
calls.give = &PoolKext::give;
Pool pool(region, ser, calls, kPoolCapacity);
RgfxSlabs poolSlabs(pool);
RgfxSlabs::Range big, after, small;
CHECK(poolSlabs.take(4 * kMiB, kShared, 0, &big) && log.back() == "take 8388608");
poolSlabs.give(big);
CHECK(poolSlabs.take(0x1000, kShared, 0, &after) && after.slab == big.slab && log.size() == 1);
poolSlabs.give(after);
CHECK(poolSlabs.reclaim() && kext.blocks.empty() && log.back() == "give 8388608");
CHECK(poolSlabs.take(0x1000, kShared, 0, &small) && log.back() == "take 131072");
poolSlabs.give(small);
CHECK(poolSlabs.reclaim() && kext.blocks.empty());
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
while (ring.next(&h, &bytes)) {
}
}
} // namespace
void rgfxSlabTests()
{
test_slab_granule_and_classes();
test_slab_growth();
test_slab_reuse_and_fragmentation();
test_slab_zeroing();
test_slab_empty_slabs_go();
test_slab_idle_empty_slabs_go();
test_slab_churn_counts();
test_slab_dedicated_cache();
test_slab_fallbacks();
test_slab_first_source();
test_slab_thread();
test_slab_take_waits_for_slabs_given_back();
test_slab_take_gives_back_slabs_let_go_while_it_waited();
test_region_slab_source();
test_region_slab_source_zeroed_blocks();
test_region_reclaims_slabs();
test_region_reclaim_waits_for_slabs_given_back();
test_pages_slab_source();
test_pages_slab_source_chunks();
test_chunked_slabs_grow();
test_managed_buffers_over_shared_copies();
test_pool_slab_source();
test_pool_slab_source_at_host_addresses();
test_pool_managed_buffers_at_their_copies();
test_pool_slab_churn_is_bounded();
test_slab_class_starts_again_once_empty();
}