diff --git a/docs/graphics-kext/design.md b/docs/graphics-kext/design.md index 957945134..f89405d73 100644 --- a/docs/graphics-kext/design.md +++ b/docs/graphics-kext/design.md @@ -469,6 +469,35 @@ Stages: and a texture's own CPU access (`getBytes`, `replaceRegion`) locks the surface as a CPU access does (`guest/kext/src/RgfxSurfaceCaches.hpp`, `guest/bundle/src/RgfxIOSurface.h`). + - *Deferred pages:* a fresh surface only the GPU touches has no guest + pages until a CPU lock needs them, as on a GPU of its own memory (the + AMD 5300M's footprint grew 0 KiB from a 3840x2054 surface's first GPU + use). Where the kext took `RGFX_FEATURE_SURFACE_DEFERRED`, and no + IOSurface mapper device (`IOSurfaceParavirtMapperService`) is matched, + a cacheable ask in place of a surface that reads fresh (its seed 0, + none of its pages resident) defers its block: the kext makes the + device cache and sets its control function first, then reads the seed + and the resident pages under a read-only `lockSurface`, which waits + out any lock calling the control functions, so a read-write lock + either moved the seed before the read or calls the control function + after it (`RgfxIOSurfaceKPI.hpp`). Found fresh, its `SURFACE_PAGES` + carries `DEFERRED` and no runs, the block keeping room for one run a + page of the whole allocation, every plane's; the host makes the cache + as zeros. Not fresh, or refused, the kext names the pages at once, as + for any block. A deferred block is found by its surface, never by + pages, and its holders wire none. Its first read-write lock, or a + read-only one after a GPU write, wires the pages and names them + (`ATTACH`) before it goes on, one lock at a time, under no lock of the + contexts'; a read-only lock of a surface the GPU never wrote names + none, a fresh page reading as the zeros the cache holds. A dormant + deferred block stays at a client's going (op 5) while others are + left. Its release names its pages first where the GPU wrote it and + the surface is retained past the kext's own three references (the + table's, the device cache's, and the release thread's), so the + release copies the cache into them; else nothing reads them. Deferred + blocks fit the host's budget (`DEFERRED_BUDGET_LO` and `_HI`), held + and dormant, and dormant ones are let go past half of it, the oldest + first (`guest/kext/src/RgfxSurfaceBlocks.hpp`). 15. **The stage 3 stack is IOGPUFamily.** x86-64 macOS 26 carries IOGPUFamily and IOGPU.framework, and the x86-64 port runs Metal compositing on them: diff --git a/guest/kext/src/RgfxAccelerator.hpp b/guest/kext/src/RgfxAccelerator.hpp index 7c42d932a..94e99371d 100644 --- a/guest/kext/src/RgfxAccelerator.hpp +++ b/guest/kext/src/RgfxAccelerator.hpp @@ -137,12 +137,14 @@ UInt64 rgfxSurfaceCacheNoRoom(); // its cache since its last copy. Null where no cached surface is releasing the block. OSObject *rgfxSurfaceCacheReleasingSurface(UInt64 offset, bool *written); // What a cached surface held for its block's release, taken out by rgfxSurfaceCacheReleased: its -// header's mapping, its device cache's reference, the surface's and its memory's wiring. +// header's mapping, its device cache's reference, the surface's and its memory, and whether that +// memory is wired (a deferred block's whose pages were never named is not). struct RgfxReleasedSurface { void *map; void *cache; void *surface; void *wire; + bool wired; }; // The BLOCK_RELEASE of the block at `offset` was answered: a cached surface releasing it is // cached no more and its locks go on, what it held in `*gone`, for the caller to let go with @@ -164,6 +166,42 @@ bool rgfxSurfaceLocksAttach(RgfxAccelerator *accel, task_t task, uint32_t surfac // The device raised its vector: the locks waiting for a surface look at the queues' completions // again. void rgfxSurfaceLocksWake(); +// The IOSurface of ID `surfaceId` that `task` may see, retained, or null. Under the contexts' +// lock. +OSObject *rgfxSurfaceLocksLookup(RgfxAccelerator *accel, task_t task, uint32_t surfaceId); +// Whether `surface` reads fresh, to look at: its seed 0, none of its pages resident and its +// memory holding `length` bytes. Racy: the deferral's own read is rgfxSurfaceLocksDefer's. +bool rgfxSurfaceLocksFresh(OSObject *surface, UInt64 length); +// What rgfxSurfaceLocksDefer found. +enum RgfxDeferAnswer { + // No device cache, or no state for it: the block is neither deferred nor cached. + kRgfxDeferNoCache, + // The cache made, the surface not fresh: the block's pages are named now, as any cached + // block's, and rgfxSurfaceCacheSettle says so. + kRgfxDeferStale, + // The cache made, the surface fresh: the host is asked to defer the block, and + // rgfxSurfaceCacheSettle gives its answer, locks waiting for it meanwhile. + kRgfxDeferFresh, +}; +// For the new deferred block at `offset` of surface `surface` (retained by its entry), IOSurfaceID +// `surfaceId`, made by context `context`, its holders mapping `size` bytes and the plane `length`: +// makes the surface's device cache with the kext's control function, and records the block +// cached and gating (RgfxSurfaceCaches.hpp), the block's first page mapped at `header`, which the +// table keeps, its memory retained but not wired; then reads whether the surface is fresh, under +// a read-only lock of it. `*cache` is the cache, retained, for the entry, where it answers other +// than kRgfxDeferNoCache, which leaves `header` the caller's. Under no lock of the kext's. +RgfxDeferAnswer rgfxSurfaceLocksDefer(RgfxAccelerator *accel, OSObject *surface, + uint32_t surfaceId, UInt64 offset, UInt64 size, + UInt64 length, UInt32 context, IOMemoryMap *header, + void **cache); +// The host answered the ask of the block of device cache `cache`: deferred where `deferred`, +// else its pages are named, its surface's memory wired. Locks waiting for the answer go on. +void rgfxSurfaceCacheSettle(void *cache, bool deferred); +// The release thread is to post the BLOCK_RELEASE of the cached block at `offset`, of surface +// `surface` (retained by the caller): a deferred block's pages are named first where the GPU +// wrote it and the surface lives past the kext's own references (rgfxCacheReleaseNext). True +// where the block goes with its pages never named. Under no lock of the kext's. +bool rgfxSurfaceCacheReleaseAttach(RgfxAccelerator *accel, UInt64 offset, OSObject *surface); // A command queue's completion ring the accelerator watches for its client // (RgfxAcceleratorContexts.cpp): the ring's header, mapped into the kernel, and the producer @@ -308,6 +346,16 @@ public: // copies its device cache into its pages (SURFACE_DOWNLOAD). True once answered OK, waiting // up to `timeoutMs` (RgfxAcceleratorContexts.cpp). bool downloadSurfaceCache(UInt64 offset, UInt32 timeoutMs); + // Names the pages of the in-place block at `offset` made by context `context`: wires the + // first `length` bytes of the surface's memory `memory`, writes their runs past the `size` + // bytes its holders map, and posts its SURFACE_PAGES with `flags` (RGFX_SURFACE_PAGES_*): a + // deferred block's attach, or the pages of a block its ask meant to defer. True where the + // device answered OK, `memory` then wired and the runs in `*runs` (IOMalloc'd, `*count` + // of them, the caller's) where asked for; false, `memory` as it was. Under no lock of the + // kext's. + bool attachSurfacePages(UInt32 context, UInt64 offset, UInt64 size, UInt64 length, + IOMemoryDescriptor *memory, UInt32 flags, RgfxPageRun **runs, + UInt32 *count); IOReturn releaseSurfaceBlock(RgfxAcceleratorUserClient *client, UInt64 offset); void dropSurfaceBlocks(const void *client, bool closed); // The processes' object lifecycle, on the framebuffer's control ring @@ -435,9 +483,21 @@ private: // SURFACE_PAGES of the block of `total` bytes at `offset` made for context `context`: its // `count` runs of `length` bytes at region offset `runsOffset`, already written, with // `flags` (RGFX_SURFACE_PAGES_*, none sent where 0). kIOReturnSuccess where the device - // answered OK, kIOReturnUnsupported where it answered otherwise, else why it did not answer. + // answered OK, kIOReturnUnsupported where it answered otherwise, its status in `*status` + // where asked for, else why it did not answer. IOReturn postPages(UInt32 context, UInt64 offset, UInt64 total, UInt64 runsOffset, - UInt64 length, UInt32 count, UInt32 flags); + UInt64 length, UInt32 count, UInt32 flags, UInt32 *status = nullptr); + // The new deferred block of entry `e`, pending, held by its asker of context `context` alone, + // `total` bytes with its runs' room: makes its surface's device cache and reads the surface + // (rgfxSurfaceLocksDefer); fresh, asks the host to defer it; not fresh, refused or with no + // cache, names its pages now, the entry keyed by them from then on. Whether the device took + // the block, and `*cached` where it is cached. Not under the contexts' lock. + bool deferSurfaceBlock(RgfxSurfaceEntry &e, UInt32 context, uint32_t surfaceId, UInt64 total, + bool *cached); + // Holds the dormant deferred block of entry `e` again for the ask of IOSurfaceID + // `surfaceId`, its own surface: false, nothing changed, where its cache asked it to go. + // Under the contexts' lock. + bool reviveDeferredBlock(RgfxSurfaceEntry &e, uint32_t surfaceId); // Makes the device cache of the surface of IOSurfaceID `surfaceId` in `task` for the fresh // block in place of entry `e` at `offset`, still pending, and records the block cached // (rgfxSurfaceCacheAdd): false, nothing made, where it cannot be. diff --git a/guest/kext/src/RgfxAcceleratorContexts.cpp b/guest/kext/src/RgfxAcceleratorContexts.cpp index ae97d58fb..cff303bf3 100644 --- a/guest/kext/src/RgfxAcceleratorContexts.cpp +++ b/guest/kext/src/RgfxAcceleratorContexts.cpp @@ -173,6 +173,14 @@ bool surfacePages = false; // Whether the device keeps cached surfaces' GPU copies in its own memory // (RGFX_FEATURE_SURFACE_CACHE), read with it. bool surfaceCache = false; +// The bytes of the host GPU's memory deferred blocks' device caches may hold +// (RGFX_FEATURE_SURFACE_DEFERRED, its DEFERRED_BUDGET registers), read at the first context's +// open: 0, deferring none, where the device or the kext does not take the feature, or where the +// guest's IOSurfaces have a mapper device of their own (kSurfaceMapperService), which maps their +// pages for the host. +UInt64 deferredBudget = 0; +// The service of that mapper device, the paravirtualized GPU's. +const char *const kSurfaceMapperService = "IOSurfaceParavirtMapperService"; // Under contextLock: the shared blocks of surface planes, made at the first ask. RgfxSurfaceTable surfaceTable = {nullptr, 0}; // The bytes of surface pages the dormant blocks hold at most (RgfxSurfaceBlocks.hpp): an eighth @@ -195,6 +203,11 @@ struct DormantStats { // last copy, which the host copies into the pages all the same. UInt64 unread; UInt64 unreadWritten; + // Blocks deferred (RgfxSurfaceBlocks.hpp), deferrals the host refused, and deferred blocks + // released with their pages never named. + UInt64 deferred; + UInt64 deferredRefused; + UInt64 deferredUnattached; UInt64 changes; UInt64 loggedChanges; // The surfaces left uncached for want of room (rgfxSurfaceCacheNoRoom) at the last line. @@ -473,8 +486,16 @@ void releaseFreedBlocks(thread_call_param_t accelerator, thread_call_param_t) // mach port or an XPC object holds a surface with no client, and the process that // looks it up from one reads its pages. Its clients are read here, out of every // lock, as at a block's sleep. + // A deferred block's pages are named first, where the GPU wrote it and its surface + // lives on, so the release copies the cache into them (rgfxCacheReleaseNext). bool written = false; if (OSObject *surface = rgfxSurfaceCacheReleasingSurface(block.offset, &written)) { + if (rgfxSurfaceCacheReleaseAttach(accel, block.offset, surface)) { + IOLockLock(contextLock); + dormantStats.deferredUnattached++; + dormantStats.changes++; + IOLockUnlock(contextLock); + } release.flags = rgfxCacheReleaseFlags(rgfxIOSurfaceClientCount(surface)); surface->release(); } @@ -581,6 +602,22 @@ bool RgfxAccelerator::startContexts() const UInt32 features = readRegister(RGFX_REG_FEATURES_LO); surfacePages = (features & RGFX_FEATURE_SURFACE_PAGES) != 0; surfaceCache = surfacePages && (features & RGFX_FEATURE_SURFACE_CACHE) != 0; + // Deferred blocks where the kext took the feature, and no mapper device maps the + // surfaces' pages. + if (surfaceCache && (featureWord() & RGFX_FEATURE_SURFACE_DEFERRED)) { + OSDictionary *matching = IOService::serviceMatching(kSurfaceMapperService); + IOService *mapper = matching ? IOService::copyMatchingService(matching) : nullptr; + OSSafeReleaseNULL(matching); + if (!mapper) + deferredBudget = + (static_cast(readRegister(RGFX_REG_DEFERRED_BUDGET_HI)) << 32) | + readRegister(RGFX_REG_DEFERRED_BUDGET_LO); + else + IOLog("RgfxAccelerator: the guest's IOSurfaces have a mapper device (%s): no " + "block is deferred\n", + kSurfaceMapperService); + OSSafeReleaseNULL(mapper); + } blocksStart = RGFX_CONTEXT_ALLOCATIONS_OFFSET; blocksEnd = (regionSize - RGFX_CURSOR_SPAN) & ~(kPage - 1); // A reserve of no more than a quarter of the blocks' room, on a region too small for it. @@ -605,11 +642,11 @@ bool RgfxAccelerator::startContexts() contextUnits = rgfxContextUnitsFor(maxBufferLength); __atomic_store_n(&contextLock, lock, __ATOMIC_RELEASE); IOLog("RgfxAccelerator: blocks 0x%llx-0x%llx, %u contexts of %u GiB of GPU addresses " - "(maxBufferLength %llu MiB), surfaces %s; WindowServer's reserve: %u of %u " - "entries, %llu MiB\n", + "(maxBufferLength %llu MiB), surfaces %s, deferred blocks' budget %llu MiB; " + "WindowServer's reserve: %u of %u entries, %llu MiB\n", blocksStart, blocksEnd, kRgfxContextUnits / contextUnits, static_cast((contextUnits * RGFX_CONTEXT_VA_UNIT) >> 30), - maxBufferLength >> 20, surfacePages ? "in place" : "copied", + maxBufferLength >> 20, surfacePages ? "in place" : "copied", deferredBudget >> 20, blockTable.reserveEntries, kMaxBlocks, blockTable.reserveBytes >> 20); return true; } @@ -970,20 +1007,11 @@ namespace { constexpr UInt32 kMaxSurfaceBlocks = kRgfxSurfaceMaxBlocks; constexpr UInt64 kMaxPlaneBytes = 256ull << 20; -// The plane of `length` bytes at `address` in `task`, wired: its descriptor, prepared, and its -// pages' runs (`*runs`, IOMalloc'd, `*count` of them, the caller's to free with freeRuns), or -// null where the range is not mapped there or its runs do not fit. -IOMemoryDescriptor *wirePlane(task_t task, UInt64 address, UInt64 length, RgfxPageRun **runs, - UInt32 *count) +// The runs of the first `length` bytes of the prepared `md`, whose first byte lies `address` +// bytes into a page (IOMalloc'd, `*count` of them, the caller's to free with freeRuns), or null +// where they do not fit one run a page. +RgfxPageRun *walkRuns(IOMemoryDescriptor *md, UInt64 address, UInt64 length, UInt32 *count) { - IOMemoryDescriptor *md = - IOMemoryDescriptor::withAddressRange(address, length, kIODirectionOutIn, task); - if (!md) - return nullptr; - if (md->prepare(kIODirectionOutIn) != kIOReturnSuccess) { - md->release(); - return nullptr; - } // One run a page at most. UInt32 capacity = static_cast(((address & (kPage - 1)) + length + kPage - 1) / kPage); RgfxPageRun *all = static_cast(IOMalloc(sizeof(RgfxPageRun) * capacity)); @@ -1007,13 +1035,31 @@ IOMemoryDescriptor *wirePlane(task_t task, UInt64 address, UInt64 length, RgfxPa bcopy(all, kept, sizeof(RgfxPageRun) * n); if (all) IOFree(all, sizeof(RgfxPageRun) * capacity); + *count = kept ? n : 0; + return kept; +} + +// The plane of `length` bytes at `address` in `task`, wired: its descriptor, prepared, and its +// pages' runs (`*runs`, IOMalloc'd, `*count` of them, the caller's to free with freeRuns), or +// null where the range is not mapped there or its runs do not fit. +IOMemoryDescriptor *wirePlane(task_t task, UInt64 address, UInt64 length, RgfxPageRun **runs, + UInt32 *count) +{ + IOMemoryDescriptor *md = + IOMemoryDescriptor::withAddressRange(address, length, kIODirectionOutIn, task); + if (!md) + return nullptr; + if (md->prepare(kIODirectionOutIn) != kIOReturnSuccess) { + md->release(); + return nullptr; + } + RgfxPageRun *kept = walkRuns(md, address, length, count); if (!kept) { md->complete(kIODirectionOutIn); md->release(); return nullptr; } *runs = kept; - *count = n; return md; } @@ -1092,7 +1138,8 @@ bool letGoDormant(UInt32 i, RgfxDormantCause why, bool written = false) dormantStats.letGo[why]++; if (why == kRgfxDormantPurged && written) dormantStats.purgedWritten++; - if (why >= kRgfxDormantCount && why <= kRgfxDormantNoSpace && + if (((why >= kRgfxDormantCount && why <= kRgfxDormantNoSpace) || + why == kRgfxDormantDeferredBytes) && surfaceTable.entries[i].purgeable) dormantStats.volatileFirst++; dormantStats.changes++; @@ -1107,6 +1154,9 @@ bool trimDormant() RgfxDormantCause why = kRgfxDormantCauses; for (int32_t i; (i = rgfxSurfaceOverCaps(surfaceTable, dormantMaxBytes, &why)) >= 0;) release |= letGoDormant(static_cast(i), why); + // The deferred ones past half the device's budget for them. + for (int32_t i; (i = rgfxSurfaceOverDeferredCap(surfaceTable, deferredBudget / 2, &why)) >= 0;) + release |= letGoDormant(static_cast(i), why); return release; } @@ -1238,14 +1288,16 @@ void noteDormant() "%llu revived; let go: %llu purged (%llu with a cache written), %llu made " "empty, %llu with no client at sleep, %llu past the count, %llu past the " "bytes, %llu for a table entry, %llu for the region's room (%llu of these " - "volatile), %llu asked otherwise; %llu released with no client left (%llu of them " - "written, not copied); %llu not cached: no room\n", + "volatile), %llu asked otherwise, %llu past the deferred bytes; %llu released with " + "no client left (%llu of them written, not copied); %llu not cached: no room; " + "%llu deferred (%llu refused), %llu released with no pages named\n", count, bytes >> 20, dormantMaxBytes >> 20, d.slept, d.revived, d.letGo[kRgfxDormantPurged], d.purgedWritten, d.letGo[kRgfxDormantEmptied], d.letGo[kRgfxDormantNoClients], d.letGo[kRgfxDormantCount], d.letGo[kRgfxDormantBytes], d.letGo[kRgfxDormantTableFull], d.letGo[kRgfxDormantNoSpace], d.volatileFirst, - d.letGo[kRgfxDormantStale], d.unread, d.unreadWritten, noRoom); + d.letGo[kRgfxDormantStale], d.letGo[kRgfxDormantDeferredBytes], d.unread, + d.unreadWritten, noRoom, d.deferred, d.deferredRefused, d.deferredUnattached); } // The last holder, of context `context`, of the cached entry `e` let it go: the block sleeps @@ -1309,11 +1361,6 @@ IOReturn RgfxAccelerator::acquireSurfaceBlock(RgfxAcceleratorUserClient *client, // pages, which the device maps as they are. if (inPlace ? address % kPage || length % kPage : size < length) return kIOReturnBadArgument; - RgfxPageRun *runs = nullptr; - UInt32 count = 0; - IOMemoryDescriptor *pages = wirePlane(task, address, length, &runs, &count); - if (!pages) - return kIOReturnBadArgument; RgfxSurfaceTable &table = surfaceTable; IOLockLock(contextLock); if (!table.entries) { @@ -1324,6 +1371,31 @@ IOReturn RgfxAccelerator::acquireSurfaceBlock(RgfxAcceleratorUserClient *client, table = {made, kMaxSurfaceBlocks}; } } + // The asker's IOSurface, where a block of it may be deferred (RgfxSurfaceBlocks.hpp): a + // deferred block of it is the ask's, found by it whatever the asker's pages, and a fresh one + // may be deferred, where cacheable and within the device's budget. Neither wires the asker's + // pages: the kext wires them only where neither holds. Released once the ask is done, but a + // new deferred entry's, which keeps it. + struct SurfaceRef { + OSObject *object = nullptr; + ~SurfaceRef() { OSSafeReleaseNULL(object); } + } asker; + bool defer = false, deferredFound = false; + if (inPlace && surfaceId && deferredBudget && table.entries) { + asker.object = rgfxSurfaceLocksLookup(this, task, surfaceId); + int32_t d = -1; + while (asker.object && (d = rgfxSurfaceFindDeferred(table, asker.object)) >= 0 && + table.entries[d].pending) + IOLockSleep(contextLock, &surfaceTable, THREAD_UNINT); + deferredFound = d >= 0; + defer = asker.object && !deferredFound && cacheable && + rgfxSurfaceDeferFits(table, length, deferredBudget) && + rgfxSurfaceLocksFresh(asker.object, length); + } + IOLockUnlock(contextLock); + RgfxPageRun *runs = nullptr; + UInt32 count = 0; + IOMemoryDescriptor *pages = nullptr; // A block in place is no other ask's until the device has answered for its pages: the ask // waits for the answer, which keeps the block or lets it go. A dormant block of the plane is // held again by an ask of the same surface (reviveSurfaceBlock), and goes where the ask is @@ -1333,68 +1405,117 @@ IOReturn RgfxAccelerator::acquireSurfaceBlock(RgfxAcceleratorUserClient *client, uint64_t roomDeadline = 0; int32_t at = -1, slot = -1; RgfxBlockPin pin = {}; - UInt64 offset = 0; - // A block in place holds the runs past the part the processes map, whole pages of them. - UInt64 runBytes = sizeof(RgfxPageRun) * static_cast(count); - UInt64 total = inPlace ? size + alignUp(runBytes, kPage) : size; + UInt64 offset = 0, total = 0; RgfxBlockResult made = kRgfxBlockTableFull; - for (;;) { - while (table.entries && rgfxSurfacePending(table, runs, count)) - IOLockSleep(contextLock, &surfaceTable, THREAD_UNINT); - differs = false; - at = table.entries ? rgfxSurfaceFind(table, runs, count, length, size, inPlace, &differs) - : -1; - if (at >= 0 && table.entries[at].dormant) { - revived = reviveSurfaceBlock(table.entries[at], task, surfaceId); - if (revived) - break; - release |= letGoDormant(static_cast(at), kRgfxDormantStale); - continue; + for (bool wire = !defer && !deferredFound;;) { + if (wire) { + pages = wirePlane(task, address, length, &runs, &count); + if (!pages) + return kIOReturnBadArgument; } - const int32_t meeting = - at < 0 && differs ? rgfxSurfaceDormantMeeting(table, runs, count) : -1; - if (meeting >= 0) { - release |= letGoDormant(static_cast(meeting), kRgfxDormantStale); - continue; - } - if (at >= 0 || differs || !table.entries) - break; - // A new block: a dormant one gives its entry where the table is full, and the region's - // room where it has none, its release waited for a while, once. - slot = rgfxSurfaceFreeEntry(table); - if (slot < 0) { - const int32_t oldest = rgfxSurfaceOldestDormant(table); - if (oldest >= 0) { - release |= letGoDormant(static_cast(oldest), kRgfxDormantTableFull); - slot = rgfxSurfaceFreeEntry(table); - } - } - made = slot < 0 ? kRgfxBlockTableFull - : rgfxBlockAlloc(blockTable, &table.entries[slot], context, total, kPage, - &offset, &pin, client->isWindowServer()); - if (made != kRgfxBlockNoSpace) - break; - // No room: dormant blocks go once, and the ask waits for room until its deadline, - // whatever else wakes it meanwhile (rgfxSurfaceRoomStep). - const RgfxSurfaceRoomStep step = - rgfxSurfaceRoomStep(roomDeadline, table.dormantCount, mach_absolute_time()); - if (step == kRgfxSurfaceRoomGiveUp) - break; - if (step == kRgfxSurfaceRoomLetGoAndWait) { - waitedForRoom = true; - releaseStats.roomWaits++; - for (UInt32 n = 0; n < kDormantRoomBlocks; n++) { - const int32_t oldest = rgfxSurfaceOldestDormant(table); - if (oldest < 0) + IOLockLock(contextLock); + // The ask finds no deferred block and has no pages: it wires them, and looks again. + bool needPages = false; + for (;;) { + int32_t d = -1; + while (table.entries && + (rgfxSurfacePending(table, runs, count) || + ((d = rgfxSurfaceFindDeferred(table, asker.object)) >= 0 && + table.entries[d].pending))) + IOLockSleep(contextLock, &surfaceTable, THREAD_UNINT); + differs = false; + at = -1; + // A deferred block of the asker's surface is its block, held again where dormant. + d = table.entries ? rgfxSurfaceFindDeferred(table, asker.object) : -1; + if (d >= 0) { + RgfxSurfaceEntry &de = table.entries[d]; + if (de.size != size || de.length != length) { + differs = true; break; - release |= letGoDormant(static_cast(oldest), kRgfxDormantNoSpace); + } + if (de.dormant) { + revived = reviveDeferredBlock(de, surfaceId); + if (!revived) { + release |= letGoDormant(static_cast(d), kRgfxDormantStale); + continue; + } + } + at = d; + break; } - if (release) - thread_call_enter(releaseCall); - release = false; - clock_interval_to_deadline(kDormantRoomMs, kMillisecondScale, &roomDeadline); + // No pages, no deferred block: a new one is deferred where its surface is fresh + // still, and fits the budget. + if (!count && (!defer || !rgfxSurfaceDeferFits(table, length, deferredBudget) || + !rgfxSurfaceLocksFresh(asker.object, length))) { + needPages = true; + break; + } + at = table.entries && count + ? rgfxSurfaceFind(table, runs, count, length, size, inPlace, &differs) + : -1; + if (at >= 0 && table.entries[at].dormant) { + revived = reviveSurfaceBlock(table.entries[at], task, surfaceId); + if (revived) + break; + release |= letGoDormant(static_cast(at), kRgfxDormantStale); + continue; + } + const int32_t meeting = + at < 0 && differs ? rgfxSurfaceDormantMeeting(table, runs, count) : -1; + if (meeting >= 0) { + release |= letGoDormant(static_cast(meeting), kRgfxDormantStale); + continue; + } + if (at >= 0 || differs || !table.entries) + break; + // A new block in place holds the runs past the part the processes map, whole pages + // of them; a deferred one room for one run a page of the plane. + const UInt64 runBytes = sizeof(RgfxPageRun) * static_cast(count); + total = !inPlace ? size + : count ? size + alignUp(runBytes, kPage) + : size + rgfxSurfaceRunRoom(length); + // A new block: a dormant one gives its entry where the table is full, and the + // region's room where it has none, its release waited for a while, once. + slot = rgfxSurfaceFreeEntry(table); + if (slot < 0) { + const int32_t oldest = rgfxSurfaceOldestDormant(table); + if (oldest >= 0) { + release |= letGoDormant(static_cast(oldest), kRgfxDormantTableFull); + slot = rgfxSurfaceFreeEntry(table); + } + } + made = slot < 0 ? kRgfxBlockTableFull + : rgfxBlockAlloc(blockTable, &table.entries[slot], context, total, + kPage, &offset, &pin, client->isWindowServer()); + if (made != kRgfxBlockNoSpace) + break; + // No room: dormant blocks go once, and the ask waits for room until its deadline, + // whatever else wakes it meanwhile (rgfxSurfaceRoomStep). + const RgfxSurfaceRoomStep step = + rgfxSurfaceRoomStep(roomDeadline, table.dormantCount, mach_absolute_time()); + if (step == kRgfxSurfaceRoomGiveUp) + break; + if (step == kRgfxSurfaceRoomLetGoAndWait) { + waitedForRoom = true; + releaseStats.roomWaits++; + for (UInt32 n = 0; n < kDormantRoomBlocks; n++) { + const int32_t oldest = rgfxSurfaceOldestDormant(table); + if (oldest < 0) + break; + release |= letGoDormant(static_cast(oldest), kRgfxDormantNoSpace); + } + if (release) + thread_call_enter(releaseCall); + release = false; + clock_interval_to_deadline(kDormantRoomMs, kMillisecondScale, &roomDeadline); + } + IOLockSleepDeadline(contextLock, &surfaceTable, roomDeadline, THREAD_UNINT); } - IOLockSleepDeadline(contextLock, &surfaceTable, roomDeadline, THREAD_UNINT); + if (!needPages) + break; + IOLockUnlock(contextLock); + defer = false; + wire = true; } if (waitedForRoom && made == kRgfxBlockNoSpace) releaseStats.roomWaitsFailed++; @@ -1403,8 +1524,12 @@ IOReturn RgfxAccelerator::acquireSurfaceBlock(RgfxAcceleratorUserClient *client, if (at >= 0) { // Another process's plane, or a dormant one held again: this client holds its block // too, in its window from its first hold, mapped under the lock so no let-go of the - // hold comes between. A block held again is fresh to its holders. + // hold comes between. A block held again is fresh to its holders. A deferred block's + // holders hold no pages: the asker's, where it wired them, go. RgfxSurfaceEntry &e = table.entries[at]; + IOMemoryDescriptor *own = e.deferred ? pages : nullptr; + if (own) + pages = nullptr; RgfxSurfaceHoldResult held = rgfxSurfaceHold(e, client, context, pages); *block = {e.offset, e.size, e.serial, revived, e.cached}; IOReturn mapped = kIOReturnSuccess; @@ -1425,6 +1550,7 @@ IOReturn RgfxAccelerator::acquireSurfaceBlock(RgfxAcceleratorUserClient *client, } IOLockUnlock(contextLock); freeRuns(runs, count); + unwire(own); if (held != kRgfxSurfaceHoldNew) { if (!keptWire) unwire(pages); @@ -1484,6 +1610,14 @@ IOReturn RgfxAccelerator::acquireSurfaceBlock(RgfxAcceleratorUserClient *client, e.length = length; e.runs = runs; e.runCount = count; + // A block in place with no pages is deferred, its surface its key from here on. + const bool deferring = inPlace && !count; + if (deferring) { + e.surface = asker.object; + asker.object = nullptr; + e.surfaceId = surfaceId; + rgfxSurfaceDefer(table, e); + } rgfxSurfaceHold(e, client, context, pages); *block = {offset, size, pin.serial, true, false}; // In the client's window, under the lock, so no let-go of the hold comes between: the part @@ -1491,6 +1625,7 @@ IOReturn RgfxAccelerator::acquireSurfaceBlock(RgfxAcceleratorUserClient *client, // device was not told of it. IOReturn mapped = client->mapSpan(offset, size); if (mapped != kIOReturnSuccess) { + OSObject *deferredSurface = deferring ? static_cast(e.surface) : nullptr; client->unmapSpan(offset, size); rgfxBlockDrop(blockTable, pin); rgfxSurfaceClear(table, e); @@ -1499,6 +1634,7 @@ IOReturn RgfxAccelerator::acquireSurfaceBlock(RgfxAcceleratorUserClient *client, IOLockUnlock(contextLock); freeRuns(runs, count); unwire(pages); + OSSafeReleaseNULL(deferredSurface); return mapped; } IOLockUnlock(contextLock); @@ -1507,13 +1643,21 @@ IOReturn RgfxAccelerator::acquireSurfaceBlock(RgfxAcceleratorUserClient *client, // and goes as a share not posted goes where the device maps none of them: the process makes // a copy instead. // A block in place may be cached: its surface's device cache is made before the device - // learns of the block, so its CPU generation counts from the start. - bool cached = inPlace && surfaceCache && cacheable && surfaceId && - cacheSurface(e, task, surfaceId, offset); - block->cached = cached; + // learns of the block, so its CPU generation counts from the start. A deferred one is cached + // with no pages, or has them named now (deferSurfaceBlock). + bool cached = false; IOReturn posted = kIOReturnSuccess; - if (inPlace && !postSurfacePages(context, offset, total, size, length, runs, count, cached)) - posted = kIOReturnUnsupported; + if (deferring) { + if (!deferSurfaceBlock(e, context, surfaceId, total, &cached)) + posted = kIOReturnUnsupported; + } else { + cached = inPlace && surfaceCache && cacheable && surfaceId && + cacheSurface(e, task, surfaceId, offset); + if (inPlace && + !postSurfacePages(context, offset, total, size, length, runs, count, cached)) + posted = kIOReturnUnsupported; + } + block->cached = cached; if (posted == kIOReturnSuccess) { RgfxBlockGrant share = {}; share.context = context; @@ -1629,6 +1773,130 @@ bool RgfxAccelerator::cacheSurface(RgfxSurfaceEntry &e, task_t task, uint32_t su return true; } +bool RgfxAccelerator::reviveDeferredBlock(RgfxSurfaceEntry &e, uint32_t surfaceId) +{ + // The surface is the block's own, found by it: its device cache is the block's, held. + if (!rgfxSurfaceRevives(e, e.cache, rgfxSurfaceCacheWake(e.cache))) + return false; + rgfxSurfaceWake(surfaceTable, e); + e.surfaceId = surfaceId; + dormantStats.revived++; + dormantStats.changes++; + return true; +} + +bool RgfxAccelerator::deferSurfaceBlock(RgfxSurfaceEntry &e, UInt32 context, uint32_t surfaceId, + UInt64 total, bool *cached) +{ + // The entry is pending until the device answers its pages, so no other asker reads it. + OSObject *surface = static_cast(e.surface); + const UInt64 offset = e.offset, size = e.size, length = e.length; + // The header's page, where the kext writes the surface's CPU generation for the processes. + IOMemoryMap *header = region->createMappingInTask( + kernel_task, 0, kIOMapAnywhere | kIOMapCopybackCache, offset, kPage); + void *cache = nullptr; + const RgfxDeferAnswer answer = + header ? rgfxSurfaceLocksDefer(this, surface, surfaceId, offset, size, length, context, + header, &cache) + : kRgfxDeferNoCache; + // Not cached: its surface is looked up anew at its first write named, as any block's, and the + // entry's reference goes once its pages are named. + OSObject *uncached = answer == kRgfxDeferNoCache ? surface : nullptr; + IOLockLock(contextLock); + if (uncached) { + e.surface = nullptr; + } else { + e.cache = cache; + e.cached = true; + } + IOLockUnlock(contextLock); + if (uncached) + OSSafeReleaseNULL(header); + *cached = !uncached; + if (answer == kRgfxDeferFresh) { + UInt32 status = RGFX_STATUS_OK; + const IOReturn r = postPages(context, offset, total, offset + size, length, 0, + RGFX_SURFACE_PAGES_CACHED | RGFX_SURFACE_PAGES_DEFERRED, + &status); + if (r == kIOReturnSuccess || r != kIOReturnUnsupported || status != RGFX_STATUS_REFUSED) { + // Deferred, or not answered: a block whose answer did not come goes, its pages + // never named. + rgfxSurfaceCacheSettle(cache, true); + IOLockLock(contextLock); + dormantStats.deferred += r == kIOReturnSuccess; + dormantStats.changes++; + IOLockUnlock(contextLock); + if (r != kIOReturnSuccess) + IOLog("RgfxAccelerator: the deferred block 0x%llx was not answered (0x%x, status " + "%u): it goes\n", + offset, r, status); + return r == kIOReturnSuccess; + } + IOLockLock(contextLock); + dormantStats.deferredRefused++; + dormantStats.changes++; + IOLockUnlock(contextLock); + } + // Not fresh, refused, or with no cache: the block's pages are named now, as any block's in + // place, and its asker's hold wires them as any holder's. + IOMemoryDescriptor *memory = OSDynamicCast(IOMemoryDescriptor, rgfxIOSurfaceMemory(surface)); + RgfxPageRun *runs = nullptr; + UInt32 count = 0; + const bool named = + memory && attachSurfacePages(context, offset, size, length, memory, + *cached ? RGFX_SURFACE_PAGES_CACHED : 0, &runs, &count); + if (*cached) + rgfxSurfaceCacheSettle(cache, !named); + if (!named) { + OSSafeReleaseNULL(uncached); + return false; + } + IOMemoryDescriptor *held = memory; + held->retain(); + if (held->prepare(kIODirectionOutIn) != kIOReturnSuccess) + OSSafeReleaseNULL(held); + IOLockLock(contextLock); + rgfxSurfaceUndefer(surfaceTable, e, runs, count); + if (e.holdCount) + e.holds[0].pages = held; + IOLockUnlock(contextLock); + OSSafeReleaseNULL(uncached); + return true; +} + +bool RgfxAccelerator::attachSurfacePages(UInt32 context, UInt64 offset, UInt64 size, + UInt64 length, IOMemoryDescriptor *memory, UInt32 flags, + RgfxPageRun **runsOut, UInt32 *countOut) +{ + if (length > memory->getLength() || memory->prepare(kIODirectionOutIn) != kIOReturnSuccess) + return false; + UInt32 count = 0; + RgfxPageRun *runs = walkRuns(memory, 0, length, &count); + const char *why = nullptr; + if (!runs) + why = "its runs do not fit"; + else if (!writeRuns(region, offset + size, runs, count)) + why = "its runs could not be written"; + else if (IOReturn r = postPages(context, offset, size + rgfxSurfaceRunRoom(length), + offset + size, length, count, flags); + r != kIOReturnSuccess) + why = r == kIOReturnUnsupported ? "the device refused them" : "they were not answered"; + if (why) { + IOLog("RgfxAccelerator: the block 0x%llx's pages (flags 0x%x) were not named: %s\n", + offset, flags, why); + freeRuns(runs, count); + memory->complete(kIODirectionOutIn); + return false; + } + if (runsOut) { + *runsOut = runs; + *countOut = count; + } else { + freeRuns(runs, count); + } + return true; +} + bool RgfxAccelerator::downloadSurfaceCache(UInt64 offset, UInt32 timeoutMs) { RgfxSurfaceDownload message = {}; @@ -1661,7 +1929,8 @@ bool RgfxAccelerator::postSurfacePages(UInt32 context, UInt64 offset, UInt64 tot } IOReturn RgfxAccelerator::postPages(UInt32 context, UInt64 offset, UInt64 total, - UInt64 runsOffset, UInt64 length, UInt32 count, UInt32 flags) + UInt64 runsOffset, UInt64 length, UInt32 count, UInt32 flags, + UInt32 *status) { // The message, then where it has flags, the part that holds them. struct { @@ -1686,6 +1955,8 @@ IOReturn RgfxAccelerator::postPages(UInt32 context, UInt64 offset, UInt64 total, r = kIOReturnTimeout; if (r != kIOReturnSuccess) return r; + if (status) + *status = answer.status; return answer.status == RGFX_STATUS_OK ? kIOReturnSuccess : kIOReturnUnsupported; } @@ -1863,7 +2134,7 @@ RgfxAccelerator::surfaceDeviceCache(RgfxAcceleratorUserClient *client, task_t ta int32_t at = table.entries ? rgfxSurfaceAt(table, offset) : -1; RgfxSurfaceEntry *e = at >= 0 ? &table.entries[at] : nullptr; SurfaceCacheAnswer answer = kSurfaceCacheMade; - if (!e || !e->runCount || !rgfxSurfaceHeldBy(table, client, offset, 1)) + if (!e || (!e->runCount && !e->deferred) || !rgfxSurfaceHeldBy(table, client, offset, 1)) answer = kSurfaceCacheNotHeld; else if (e->pending) answer = kSurfaceCachePending; diff --git a/guest/kext/src/RgfxAcceleratorLocks.cpp b/guest/kext/src/RgfxAcceleratorLocks.cpp index ee102440a..13ff79be2 100644 --- a/guest/kext/src/RgfxAcceleratorLocks.cpp +++ b/guest/kext/src/RgfxAcceleratorLocks.cpp @@ -34,6 +34,15 @@ * The kext holds such a cache until that answer, so the surface's locks go on calling the * control function until then. * + * A deferred block's surface (RgfxSurfaceBlocks.hpp) has its cache made at its ask, before the + * block is posted, and the ask reads the surface's seed and its resident pages only once the + * control function is set, under a read-only lockSurface, which waits out any lock calling the + * control functions (RgfxIOSurfaceKPI.hpp): a read-write lock begun before it has moved the seed, + * and one after it calls the control function, which waits for the host's answer to the + * deferral, then names the block's pages before it goes on (SURFACE_PAGES with ATTACH), one lock + * at a time and under no lock of the contexts'. Its release names them first where the GPU wrote + * it and its surface lives on (rgfxSurfaceCacheReleaseAttach). + * * Our own code; it names SDK-public IOKit calls and IOSurface's interface (RgfxIOSurfaceKPI.hpp). */ @@ -156,6 +165,71 @@ bool surfaceHolds(OSObject *surface, UInt64 phys) void wakeLocked(); +// Whether `surface` is an IOSurface, as IOSurfaceRoot hands out. +bool isSurface(const OSObject *surface) +{ + const OSMetaClass *meta = surface->getMetaClass(); + return meta && strcmp(meta->getClassName(), "IOSurface") == 0; +} + +// IOSurfaceRoot, retained, and the accelerator ID it gives `accel`, found at the first call. +// Under the contexts' lock. +bool startRoot(RgfxAccelerator *accel) +{ + if (state.root) + return true; + OSDictionary *matching = IOService::serviceMatching("IOSurfaceRoot"); + IOService *root = matching ? IOService::copyMatchingService(matching) : nullptr; + OSSafeReleaseNULL(matching); + if (!root) { + IOLog("RgfxAccelerator: no IOSurfaceRoot: CPU locks of surfaces wait for no GPU write\n"); + return false; + } + state.root = root; + state.acceleratorId = rgfxIOSurfaceRootAcceleratorID(root, accel); + IOLog("RgfxAccelerator: IOSurface accelerator ID %u\n", state.acceleratorId); + return true; +} + +// Lets go of a cached surface's memory: unwired where it was wired (rgfxCacheWired), else only +// released. +void letGoMemory(void *memory, bool wired) +{ + IOMemoryDescriptor *md = static_cast(memory); + if (!md) + return; + if (wired) + md->complete(kIODirectionOutIn); + md->release(); +} + +// Names the pages of surface `key`'s deferred block, whose attach rgfxCacheNext or +// rgfxCacheReleaseNext asked (kRgfxCacheAttaching): under state.lock, which it lets go around +// the SURFACE_PAGES, and takes again. Whether the host took them. +bool attachLocked(RgfxAccelerator *accel, uint64_t key) +{ + const RgfxCachedSurface *c = rgfxCacheFind(state.caches, key); + if (c == nullptr) + return false; + const UInt32 context = c->context; + const UInt64 offset = c->offset, size = c->size, length = c->length; + IOMemoryDescriptor *memory = static_cast(c->wire); + const uint32_t surfaceId = c->surfaceId; + IOLockUnlock(state.lock); + const bool ok = + memory && accel->attachSurfacePages(context, offset, size, length, memory, + RGFX_SURFACE_PAGES_CACHED | RGFX_SURFACE_PAGES_ATTACH, + nullptr, nullptr); + IOLockLock(state.lock); + rgfxCacheAttached(state.caches, key, ok); + wakeLocked(); + if (!ok) + IOLog("RgfxAccelerator: IOSurface %u's deferred block 0x%llx: its pages were not " + "named\n", + surfaceId, offset); + return ok; +} + static_assert(kRgfxPurgeableNonVolatile == kIOMemoryPurgeableNonVolatile, "op 7's nonvolatile"); static_assert(kRgfxPurgeableVolatile == kIOMemoryPurgeableVolatile, "op 7's volatile"); static_assert(kRgfxPurgeableEmpty == kIOMemoryPurgeableEmpty, "op 7's empty"); @@ -186,14 +260,17 @@ void surfaceControl(void *accelerator, RgfxDeviceCache *cache, uint32_t op, uint // the surface's clients left (the bundle's keep): IOSurface counts the client out before // it calls op 5 (RgfxIOSurfaceKPI.hpp). IOLockLock(state.lock); + // A dormant deferred block stays while clients are left (rgfxCachePurged). + int32_t clients = 0; if (op == 5) { const RgfxCachedSurface *c = rgfxCacheFind(state.caches, key); if (c != nullptr && c->object != nullptr) { const auto *surface = static_cast(c->object); - rgfxCacheNoteClients(state.caches, key, rgfxIOSurfaceClientCount(surface)); + clients = rgfxIOSurfaceClientCount(surface); + rgfxCacheNoteClients(state.caches, key, clients); } } - const bool look = op == 5 ? rgfxCachePurged(state.caches, key) + const bool look = op == 5 ? rgfxCachePurged(state.caches, key, clients) : op == 6 ? rgfxCacheUnpurged(state.caches, key) : rgfxCachePurgeable(state.caches, key, a); IOLockUnlock(state.lock); @@ -248,9 +325,17 @@ void surfaceControl(void *accelerator, RgfxDeviceCache *cache, uint32_t op, uint } while (!gaveUp) { uint64_t offset = 0, mark = 0; - RgfxCacheStep step = rgfxCacheNext(state.caches, key, &offset, &mark); + RgfxCacheStep step = rgfxCacheNext(state.caches, key, &offset, &mark, a == 0); if (step == kRgfxCacheGoOn) break; + if (step == kRgfxCacheAttach) { + // A deferred block's pages, named first: then a download, where the GPU wrote it. + if (!attachLocked(accel, key)) { + waitedFor = "its deferred block's pages not named"; + break; + } + continue; + } if (step == kRgfxCacheDownload) { IOLockUnlock(state.lock); bool ok = accel->downloadSurfaceCache(offset, kDownloadAnswerMs); @@ -297,19 +382,8 @@ void wakeLocked() bool rgfxSurfaceLocksAttach(RgfxAccelerator *accel, task_t task, uint32_t surfaceId, UInt64 phys, void **surfaceOut, void **cacheOut) { - if (!state.root) { - OSDictionary *matching = IOService::serviceMatching("IOSurfaceRoot"); - IOService *root = matching ? IOService::copyMatchingService(matching) : nullptr; - OSSafeReleaseNULL(matching); - if (!root) { - IOLog("RgfxAccelerator: no IOSurfaceRoot: CPU locks of surfaces wait for no GPU " - "write\n"); - return false; - } - state.root = root; - state.acceleratorId = rgfxIOSurfaceRootAcceleratorID(root, accel); - IOLog("RgfxAccelerator: IOSurface accelerator ID %u\n", state.acceleratorId); - } + if (!startRoot(accel)) + return false; OSObject *surface = rgfxIOSurfaceRootLookupSurface(state.root, surfaceId, task); if (!surface) { IOLog("RgfxAccelerator: IOSurface %u is not the naming process's: its locks wait for no " @@ -317,8 +391,7 @@ bool rgfxSurfaceLocksAttach(RgfxAccelerator *accel, task_t task, uint32_t surfac surfaceId); return false; } - const OSMetaClass *meta = surface->getMetaClass(); - if (!meta || strcmp(meta->getClassName(), "IOSurface") != 0 || !surfaceHolds(surface, phys)) { + if (!isSurface(surface) || !surfaceHolds(surface, phys)) { IOLog("RgfxAccelerator: IOSurface %u is not its shared block's surface: its locks wait " "for no GPU write\n", surfaceId); @@ -342,14 +415,148 @@ bool rgfxSurfaceLocksAttach(RgfxAccelerator *accel, task_t task, uint32_t surfac return true; } +OSObject *rgfxSurfaceLocksLookup(RgfxAccelerator *accel, task_t task, uint32_t surfaceId) +{ + if (!startRoot(accel)) + return nullptr; + OSObject *surface = rgfxIOSurfaceRootLookupSurface(state.root, surfaceId, task); + if (surface && !isSurface(surface)) + OSSafeReleaseNULL(surface); + return surface; +} + +bool rgfxSurfaceLocksFresh(OSObject *surface, UInt64 length) +{ + if (rgfxIOSurfaceLockSeed(surface) != 0) + return false; + IOMemoryDescriptor *md = OSDynamicCast(IOMemoryDescriptor, rgfxIOSurfaceMemory(surface)); + IOByteCount resident = 0, dirty = 0; + return md && length <= md->getLength() && + md->getPageCounts(&resident, &dirty) == kIOReturnSuccess && resident == 0; +} + +RgfxDeferAnswer rgfxSurfaceLocksDefer(RgfxAccelerator *accel, OSObject *surface, + uint32_t surfaceId, UInt64 offset, UInt64 size, + UInt64 length, UInt32 context, IOMemoryMap *header, + void **cacheOut) +{ + *cacheOut = nullptr; + IOMemoryDescriptor *memory = + OSDynamicCast(IOMemoryDescriptor, rgfxIOSurfaceMemory(surface)); + if (!memory || !startLocks()) + return kRgfxDeferNoCache; + RgfxDeviceCache *cache = rgfxIOSurfaceDeviceCache(surface, accel, state.acceleratorId, 0); + if (!cache) { + IOLog("RgfxAccelerator: IOSurface %u gave no device cache: its block is not deferred, " + "nor cached\n", + surfaceId); + return kRgfxDeferNoCache; + } + // The surface's memory, retained, not wired: its pages are named only where a lock needs them. + memory->retain(); + const uint64_t key = reinterpret_cast(cache); + uint64_t deadline = 0; + clock_interval_to_deadline(state.waitMs, kMillisecondScale, &deadline); + IOLockLock(state.lock); + // As rgfxSurfaceCacheAdd: the surface's previous block's release is answered first. + while (rgfxCacheFind(state.caches, key) && mach_absolute_time() < deadline) + IOLockSleepDeadline(state.lock, &state.table, deadline, THREAD_UNINT); + const bool previous = rgfxCacheFind(state.caches, key) != nullptr; + RgfxCachedSurface *c = previous ? nullptr : rgfxCacheAdd(state.caches, key, offset, surfaceId); + if (c) { + c->genAt = reinterpret_cast(header->getVirtualAddress() + + kRgfxSurfaceCpuGenOffset); + __atomic_store_n(c->genAt, 0, __ATOMIC_RELEASE); + c->map = header; + c->wire = memory; + c->clientsAt = reinterpret_cast(header->getVirtualAddress() + + kRgfxSurfaceClientsOffset); + c->object = surface; + c->deferral = kRgfxCacheGating; + c->context = context; + c->size = size; + c->length = length; + rgfxCacheNoteClients(state.caches, key, rgfxIOSurfaceClientCount(surface)); + } else if (!previous) { + state.noRoom++; + } + IOLockUnlock(state.lock); + if (!c) { + IOLog("RgfxAccelerator: IOSurface %u: %s: its block is not deferred, nor cached\n", + surfaceId, + previous ? "its previous block is cached still, its release unanswered" + : "no room for its device cache's state"); + memory->release(); + reinterpret_cast(cache)->release(); + return kRgfxDeferNoCache; + } + // The control function first, then the read: a read-write lock either moved the seed before + // the read-only lock below returned, or calls the control function. + rgfxDeviceCacheSetControl(cache, accel, &surfaceControl); + uint32_t seed = ~0u; + IOByteCount resident = ~0ull, dirty = 0; + const IOReturn locked = rgfxIOSurfaceLock(surface, kRgfxIOSurfaceLockReadOnly, &seed); + if (locked == kIOReturnSuccess) { + if (memory->getPageCounts(&resident, &dirty) != kIOReturnSuccess) + resident = ~0ull; + rgfxIOSurfaceUnlock(surface, kRgfxIOSurfaceLockReadOnly, nullptr); + } + const bool fresh = locked == kIOReturnSuccess && seed == 0 && resident == 0; + if (fresh) { + IOLockLock(state.lock); + rgfxCacheGated(state.caches, key); + IOLockUnlock(state.lock); + } + *cacheOut = cache; + return fresh ? kRgfxDeferFresh : kRgfxDeferStale; +} + +void rgfxSurfaceCacheSettle(void *cache, bool deferred) +{ + if (!cache || !__atomic_load_n(&state.lock, __ATOMIC_ACQUIRE)) + return; + IOLockLock(state.lock); + rgfxCacheSettled(state.caches, reinterpret_cast(cache), deferred); + wakeLocked(); + IOLockUnlock(state.lock); +} + +bool rgfxSurfaceCacheReleaseAttach(RgfxAccelerator *accel, UInt64 offset, OSObject *surface) +{ + if (!__atomic_load_n(&state.lock, __ATOMIC_ACQUIRE)) + return false; + // Read out of every lock, as at a block's sleep. + const int32_t clients = rgfxIOSurfaceClientCount(surface); + const int32_t retains = surface->getRetainCount(); + uint64_t deadline = 0; + clock_interval_to_deadline(state.waitMs, kMillisecondScale, &deadline); + bool unattached = false; + IOLockLock(state.lock); + for (;;) { + const RgfxCacheReleaseStep step = + rgfxCacheReleaseNext(state.caches, offset, clients, retains); + if (step == kRgfxCacheReleaseAttach) { + const RgfxCachedSurface *c = rgfxCacheAtBlock(state.caches, offset); + unattached = !attachLocked(accel, c->key); + break; + } + if (step == kRgfxCacheReleaseWait && mach_absolute_time() < deadline) { + IOLockSleepDeadline(state.lock, &state.table, deadline, THREAD_UNINT); + continue; + } + const RgfxCachedSurface *c = rgfxCacheAtBlock(state.caches, offset); + unattached = c != nullptr && c->deferral == kRgfxCacheDeferred; + break; + } + IOLockUnlock(state.lock); + return unattached; +} + namespace { // Lets go of a cached surface's memory, wired while its block lived (rgfxSurfaceCacheAdd). void unwireSurface(void *wire) { - if (IOMemoryDescriptor *md = static_cast(wire)) { - md->complete(kIODirectionOutIn); - md->release(); - } + letGoMemory(wire, true); } } // namespace @@ -358,14 +565,21 @@ void rgfxSurfaceLocksForget(void *cache, void *surface, bool releasing, void **w if (wireOut) *wireOut = nullptr; void *map = nullptr, *wire = nullptr; - bool kept = false; + bool kept = false, wired = true; if (cache && __atomic_load_n(&state.lock, __ATOMIC_ACQUIRE)) { IOLockLock(state.lock); const uint64_t key = reinterpret_cast(cache); bool wake = rgfxLockForgetKey(state.table, key); // A cached surface's locks wait for its block's release, the cache and the surface held - // until the answer (rgfxSurfaceCacheReleased), or it is cached no more. - wake |= rgfxCacheFind(state.caches, key) != nullptr; + // until the answer (rgfxSurfaceCacheReleased), or it is cached no more. A lock naming a + // deferred block's pages uses its memory: one not released waits for it. + const RgfxCachedSurface *c = rgfxCacheFind(state.caches, key); + while (!releasing && c != nullptr && c->deferral == kRgfxCacheAttaching) { + IOLockSleep(state.lock, &state.table, THREAD_UNINT); + c = rgfxCacheFind(state.caches, key); + } + wake |= c != nullptr; + wired = c == nullptr || rgfxCacheWired(*c); kept = !rgfxCacheLetGo(state.caches, key, releasing, surface, &map, &wire); if (wake) wakeLocked(); @@ -378,15 +592,16 @@ void rgfxSurfaceLocksForget(void *cache, void *surface, bool releasing, void **w // The references rgfxSurfaceLocksAttach took, out of every lock, the cache's first: IOSurface // frees a cache released to none (RgfxIOSurfaceKPI.hpp), while its surface lives. Then the // surface's memory is unwired, or its wiring handed to the caller, who keeps it while the - // device may map the memory: the wiring holds the memory, whatever becomes of the surface. + // device may map the memory: the wiring holds the memory, whatever becomes of the surface. A + // deferred block's memory never wired, whose pages the device never had, is only released. if (cache) reinterpret_cast(cache)->release(); if (surface) static_cast(surface)->release(); - if (wireOut) + if (wireOut && wired) *wireOut = wire; else - unwireSurface(wire); + letGoMemory(wire, wired); } bool rgfxSurfaceCacheAdd(void *cache, void *surface, UInt64 offset, uint32_t surfaceId, @@ -472,6 +687,8 @@ void rgfxSurfaceCacheReleased(UInt64 offset, RgfxReleasedSurface *gone) if (!__atomic_load_n(&state.lock, __ATOMIC_ACQUIRE)) return; IOLockLock(state.lock); + const RgfxCachedSurface *c = rgfxCacheAtBlock(state.caches, offset); + gone->wired = c == nullptr || rgfxCacheWired(*c); // One cached surface at most has the block: its offset is reused only past this release. gone->cache = reinterpret_cast(static_cast( rgfxCacheReleased(state.caches, offset, &gone->map, &gone->wire, &gone->surface))); @@ -485,12 +702,12 @@ void rgfxSurfaceCacheLetGo(const RgfxReleasedSurface &gone) if (gone.map) static_cast(gone.map)->release(); // The cache's reference and the surface's, held for the answer (rgfxSurfaceLocksForget), in - // that order; then the surface's memory is unwired. + // that order; then the surface's memory is unwired, or only released where it was never wired. if (gone.cache) static_cast(gone.cache)->release(); if (gone.surface) static_cast(gone.surface)->release(); - unwireSurface(gone.wire); + letGoMemory(gone.wire, gone.wired); } OSObject *rgfxSurfaceCacheReleasingSurface(UInt64 offset, bool *written) diff --git a/guest/kext/src/RgfxFeatures.hpp b/guest/kext/src/RgfxFeatures.hpp index b687fc4a8..503eb466c 100644 --- a/guest/kext/src/RgfxFeatures.hpp +++ b/guest/kext/src/RgfxFeatures.hpp @@ -36,7 +36,11 @@ // buffer; // - COMMIT_ORDER (bit 18): the bundle names, as it posts a command buffer, the latest buffer each // other queue of its process posted since (design.md, "Commit order"), which needs nothing of -// the kext. +// the kext; +// - SURFACE_DEFERRED (bit 19), meaningful only with SURFACE_CACHE: the kext defers a fresh +// cached surface's block in place, naming its pages at the first CPU lock that needs them +// (RgfxSurfaceBlocks.hpp), within the budget the host gives in DEFERRED_BUDGET_LO and _HI, +// which needs nothing of the bundle. // // The accelerator answers the bundle's Features call with the feature word (rgfxFeatureWord), and // grants a queue's flags (kRgfxAccelMethodQueueCreate's seventh input) only where their feature @@ -62,7 +66,7 @@ constexpr uint64_t kRgfxCarriedFeatures = RGFX_FEATURE_PAGES_BUFFERS | RGFX_FEATURE_SURFACE_ORDER | RGFX_FEATURE_INDIRECT_COMMAND_BUFFERS | RGFX_FEATURE_UNSHARED_QUEUES | RGFX_FEATURE_MANAGED_AT_OFFSET | RGFX_FEATURE_HEAP_OVER_PAGES | RGFX_FEATURE_SUBMIT_ROOM | - RGFX_FEATURE_ICB_SLOTS | RGFX_FEATURE_COMMIT_ORDER; + RGFX_FEATURE_ICB_SLOTS | RGFX_FEATURE_COMMIT_ORDER | RGFX_FEATURE_SURFACE_DEFERRED; // What the framebuffer writes to DRIVER_FEATURES, given the host's offer. inline uint64_t rgfxDriverFeatures(uint64_t offered) diff --git a/guest/kext/src/RgfxIOSurfaceKPI.hpp b/guest/kext/src/RgfxIOSurfaceKPI.hpp index 85c71a525..99f6b1d7f 100644 --- a/guest/kext/src/RgfxIOSurfaceKPI.hpp +++ b/guest/kext/src/RgfxIOSurfaceKPI.hpp @@ -47,6 +47,21 @@ // The accelerator ID came from IOSurfaceRoot::generateUniqueAcceleratorID(the accelerator) on // both, 1 for IOGPU and 2 for the AMD's (taken before the trace began). // +// A surface's seed, and its CPU locks, read from IOSurface 393.5.8's code (the guest's macOS +// 26.6.1, 25G76) and measured in the guest with IOSurfaceGetSeed: +// - getLockSeed is the seed IOSurfaceGetSeed reads: 0 for a fresh surface, 4K ones included; +// a read-only lock leaves it, a read-write lock moves it as it locks, and a command buffer +// that writes the surface moves it at its commit (the kext's setCurrent); a texture made +// over the surface leaves it (measured); +// - lockSurface holds the surface's mutex throughout but while synchronize_device_caches calls +// the device caches' control functions, during which other syncs wait for it to end; a +// read-write lock moves the seed after those calls, under the mutex again. A lock of a +// surface with no device cache never lets the mutex go. So a read-only lockSurface returns a +// seed that counts every read-write lock begun before it, and with no device cache current, +// calls no control function (read from code); +// - IOSurfaceDeviceCache::init retains its surface, which the cache holds until it is freed +// (read from code). +// // Our own code. #ifndef RGFX_IOSURFACE_KPI_HPP_ #define RGFX_IOSURFACE_KPI_HPP_ @@ -96,6 +111,18 @@ void rgfxDeviceCacheSetControl(RgfxDeviceCache *cache, void *context, RgfxDevice // IOSurfaceDeviceCache::setCurrent(): the GPU holds the surface's newest contents. void rgfxDeviceCacheSetCurrent(RgfxDeviceCache *cache) __asm__("__ZN20IOSurfaceDeviceCache10setCurrentEv"); +// IOSurface::getLockSeed() const: the surface's seed, as IOSurfaceGetSeed reads it. +uint32_t rgfxIOSurfaceLockSeed(const OSObject *surface) __asm__("__ZNK9IOSurface11getLockSeedEv"); +// IOSurface::lockSurface(unsigned int, unsigned int*) and unlockSurface(unsigned int, unsigned +// int*): a CPU lock of the surface, as a process's, with IOSurface's lock options +// (kRgfxIOSurfaceLockReadOnly), the seed after it in `*seed` where not null. +IOReturn rgfxIOSurfaceLock(OSObject *surface, uint32_t options, uint32_t *seed) + __asm__("__ZN9IOSurface11lockSurfaceEjPj"); +IOReturn rgfxIOSurfaceUnlock(OSObject *surface, uint32_t options, uint32_t *seed) + __asm__("__ZN9IOSurface13unlockSurfaceEjPj"); } +// IOSurface's kIOSurfaceLockReadOnly. +constexpr uint32_t kRgfxIOSurfaceLockReadOnly = 1; + #endif // RGFX_IOSURFACE_KPI_HPP_ diff --git a/guest/kext/tests/features_test.cpp b/guest/kext/tests/features_test.cpp index b5e129bfb..7e07aab88 100644 --- a/guest/kext/tests/features_test.cpp +++ b/guest/kext/tests/features_test.cpp @@ -11,6 +11,10 @@ static_assert(RGFX_REG_DRIVER_FEATURES_LO == 0x024, "DRIVER_FEATURES_LO"); static_assert(RGFX_REG_DRIVER_FEATURES_HI == 0x028, "DRIVER_FEATURES_HI"); static_assert(RGFX_REG_CONSUMED == 0x02c, "CONSUMED"); +static_assert(RGFX_REG_DEFERRED_BUDGET_LO == 0x030, "DEFERRED_BUDGET_LO"); +static_assert(RGFX_REG_DEFERRED_BUDGET_HI == 0x034, "DEFERRED_BUDGET_HI"); +static_assert(RGFX_SURFACE_PAGES_DEFERRED == (1u << 2), "SURFACE_PAGES_DEFERRED"); +static_assert(RGFX_SURFACE_PAGES_ATTACH == (1u << 3), "SURFACE_PAGES_ATTACH"); static_assert(offsetof(RgfxRingHeader, producer_waiting) == 0x10, "producer_waiting"); static_assert(offsetof(RgfxRingHeader, raise_all) == 0xc4, "raise_all"); static_assert(RGFX_QUEUE_CREATE_FLAGS_OFFSET == sizeof(RgfxQueueCreate), "the tail's offset"); @@ -44,7 +48,8 @@ constexpr uint64_t kNotCarried = RGFX_FEATURE_QUIET_SCHEDULED | RGFX_FEATURE_CON // as records or as slots, the kext admits, makes its slabs' heaps over pages blocks, whose blocks // the kext checks, a full submission ring's post waits for the host's room record, and each post // names the buffers of the process's other queues posted before it, which needs nothing of the -// kext; the kext makes WindowServer's queues unshared, which needs nothing of the bundle. +// kext; the kext makes WindowServer's queues unshared, which needs nothing of the bundle, and +// defers fresh cached surfaces' blocks. constexpr uint64_t kPages = RGFX_FEATURE_PAGES_BUFFERS; constexpr uint64_t kOrder = RGFX_FEATURE_SURFACE_ORDER; constexpr uint64_t kIcb = RGFX_FEATURE_INDIRECT_COMMAND_BUFFERS; @@ -54,8 +59,9 @@ constexpr uint64_t kHeaps = RGFX_FEATURE_HEAP_OVER_PAGES; constexpr uint64_t kRoom = RGFX_FEATURE_SUBMIT_ROOM; constexpr uint64_t kSlots = RGFX_FEATURE_ICB_SLOTS; constexpr uint64_t kCommits = RGFX_FEATURE_COMMIT_ORDER; +constexpr uint64_t kDeferred = RGFX_FEATURE_SURFACE_DEFERRED; constexpr uint64_t kCarried = - kPages | kOrder | kIcb | kUnshared | kManaged | kHeaps | kRoom | kSlots | kCommits; + kPages | kOrder | kIcb | kUnshared | kManaged | kHeaps | kRoom | kSlots | kCommits | kDeferred; // Every bit the wire names from bit 3. constexpr uint64_t kNew = kNotCarried | kCarried; } // namespace @@ -64,10 +70,10 @@ int main() { // Of the bits from 3 the kext carries out PAGES_BUFFERS, SURFACE_ORDER, // INDIRECT_COMMAND_BUFFERS, UNSHARED_QUEUES, MANAGED_AT_OFFSET, HEAP_OVER_PAGES, SUBMIT_ROOM, - // ICB_SLOTS and COMMIT_ORDER, and writes each only where offered. + // ICB_SLOTS, COMMIT_ORDER and SURFACE_DEFERRED, and writes each only where offered. check(kRgfxCarriedFeatures == kCarried, "the kext takes PAGES_BUFFERS, SURFACE_ORDER, ICBs, UNSHARED_QUEUES, MANAGED_AT_OFFSET, " - "HEAP_OVER_PAGES, SUBMIT_ROOM, ICB slots and COMMIT_ORDER from bit 3"); + "HEAP_OVER_PAGES, SUBMIT_ROOM, ICB slots, COMMIT_ORDER and SURFACE_DEFERRED from bit 3"); check(RGFX_FEATURE_PAGES_BUFFERS == (1u << 7), "PAGES_BUFFERS is bit 7"); check(RGFX_FEATURE_SURFACE_ORDER == (1u << 11), "SURFACE_ORDER is bit 11"); check(RGFX_FEATURE_INDIRECT_COMMAND_BUFFERS == (1u << 12), "INDIRECT_COMMAND_BUFFERS is bit 12"); @@ -84,6 +90,11 @@ int main() check(rgfxFeatureWord(kRgfxOfferedFeatures | kCommits, kCommits) == (kRgfxOfferedFeatures | kCommits), "COMMIT_ORDER taken is in the word"); + check(RGFX_FEATURE_SURFACE_DEFERRED == (1u << 19), "SURFACE_DEFERRED is bit 19"); + check(rgfxDriverFeatures(kRgfxOfferedFeatures | kNotCarried | kDeferred) == kDeferred, + "SURFACE_DEFERRED offered, written"); + check(rgfxFeatureWord(kRgfxOfferedFeatures | kDeferred, 0) == kRgfxOfferedFeatures, + "SURFACE_DEFERRED offered but not taken is not in the word"); check(rgfxDriverFeatures(0) == 0, "nothing offered, nothing written"); check(rgfxDriverFeatures(kRgfxOfferedFeatures | kNotCarried | (1ull << 40)) == 0, "every other bit offered, none written");