diff --git a/guest/kext/src/RgfxAccelerator.hpp b/guest/kext/src/RgfxAccelerator.hpp index d62abfdcf..37dd7822e 100644 --- a/guest/kext/src/RgfxAccelerator.hpp +++ b/guest/kext/src/RgfxAccelerator.hpp @@ -105,21 +105,23 @@ class RgfxSurfaceUserClient; class ReimsGraphics; // A surface's shared block goes (RgfxAcceleratorContexts.cpp): its device cache's pending writes -// go, waking the locks waiting on them, and its device cache and IOSurface are released -// (RgfxAcceleratorLocks.cpp), the cache's first. Either may be null. A cached block's surface -// stays cached until its BLOCK_RELEASE is answered where `releasing` (rgfxSurfaceCacheReleased), -// its locks waiting for the answer and its cache, its surface and its memory's wiring held until -// then; else it goes, or, where a lock is naming a deferred block's pages, goes once that attach -// is answered, which lets it go: the call waits for no host. A surface that goes takes the wiring -// of its memory with it, unless `wire` is given: that wiring is then the caller's (`*wire`, null -// where the surface was not cached, or its memory was never wired), to hand to a block the device -// may still map in place, or to unwire. The block is the one at `offset`: the surface's cached -// state is its cached block's alone, which another block of the surface leaves as it is -// (rgfxCacheBlockLetGo). `blockWired`: the block keeps a wire of the surface's pages of its own -// while it is in the table; decided in the same hold of the locks' state as the attach in flight, -// a block kept for good without one has that attach keep its pages' wiring for good -// (rgfxCacheLetGo). -void rgfxSurfaceLocksForget(void *cache, void *surface, UInt64 offset, bool releasing, +// go, waking the locks waiting on them. Either of the cache and the IOSurface may be null. A +// cached block's surface stays cached until its BLOCK_RELEASE is answered where `releasing` +// (rgfxSurfaceCacheReleased), its locks waiting for the answer and its cache, its surface and its +// memory's wiring held until then; else it goes, or, where a lock is naming a deferred block's +// pages, goes once that attach is answered, which lets it go: the call waits for no host. True +// where the block's references of its device cache and IOSurface are the caller's to release, +// out of every lock of the kext's, the cache's first (the contexts' lock order, +// RgfxAcceleratorContexts.cpp); false where the cached state keeps them. A surface that goes +// takes the wiring of its memory with it, unless `wire` is given: that wiring is then the +// caller's (`*wire`, null where the surface was not cached, or its memory was never wired), to +// hand to a block the device may still map in place, or to unwire. The block is the one at +// `offset`: the surface's cached state is its cached block's alone, which another block of the +// surface leaves as it is (rgfxCacheBlockLetGo). `blockWired`: the block keeps a wire of the +// surface's pages of its own while it is in the table; decided in the same hold of the locks' +// state as the attach in flight, a block kept for good without one has that attach keep its +// pages' wiring for good (rgfxCacheLetGo). +bool rgfxSurfaceLocksForget(void *cache, void *surface, UInt64 offset, bool releasing, bool blockWired, void **wire = nullptr); // The surface `surface` of device cache `cache` (rgfxSurfaceLocksAttach), IOSurfaceID // `surfaceId`, has its block at `offset` cached (RgfxSurfaceCaches.hpp), the block's first page @@ -198,14 +200,15 @@ void rgfxSurfaceCacheLetGo(const RgfxReleasedSurface &gone); bool rgfxSurfaceCacheGeneration(uint32_t surfaceId, uint64_t *gen); // Makes the device cache of the surface of ID `surfaceId` that `task` may see, whose memory holds // the physical byte `phys` (a shared block's first), with the kext's control function: its -// IOSurface and its cache, each retained, or false. Under the contexts' lock. +// IOSurface and its cache, each retained, or false. Under no lock of the kext's: it calls into +// IOSurface (the contexts' lock order, RgfxAcceleratorContexts.cpp). bool rgfxSurfaceLocksAttach(RgfxAccelerator *accel, task_t task, uint32_t surfaceId, UInt64 phys, void **surface, void **cache); // 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. +// The IOSurface of ID `surfaceId` that `task` may see, retained, or null. Under no lock of the +// kext's: it calls into IOSurface (the contexts' lock order, RgfxAcceleratorContexts.cpp). OSObject *rgfxSurfaceLocksLookup(RgfxAccelerator *accel, task_t task, uint32_t surfaceId); // Whether `task` maps `surface`'s memory from its first byte at `address`, `length` bytes of it // or more: IOSurface's own mapping of it for the task's client, found, never made, and not wired. @@ -457,7 +460,9 @@ public: const RgfxSurfacePagesLayout *layout, const RgfxSurfaceResident *resident, SurfaceBlock *block); // A dormant block's surface asked it to go (RgfxAcceleratorLocks.cpp): the release thread - // lets it go (RgfxAcceleratorContexts.cpp). From any thread, under no lock of the kext's. + // lets it go (RgfxAcceleratorContexts.cpp). From any thread holding no lock of the kext's, the + // device caches' control function among them, under IOSurface's lock: it takes no lock (the + // contexts' lock order, RgfxAcceleratorContexts.cpp). void wakeReleases(); // Posts again the release of every block the device refused (an object of some context lay in // it): a context close may have dropped that object. Called after a context closes, from the @@ -649,10 +654,11 @@ private: // block in place of entry `e` at `offset`, still pending, and records the block cached // (rgfxSurfaceCacheAdd): false, nothing made, where it cannot be. bool cacheSurface(RgfxSurfaceEntry &e, task_t task, uint32_t surfaceId, UInt64 offset); - // Holds the dormant block of entry `e` again for the ask of the surface of IOSurfaceID - // `surfaceId` in `task`, where it is that block's surface (RgfxSurfaceBlocks.hpp): false, - // nothing changed, where it is not. Under the contexts' lock. - bool reviveSurfaceBlock(RgfxSurfaceEntry &e, task_t task, uint32_t surfaceId); + // Holds the dormant block of entry `e`, found by the asker's pages, again for the ask of + // `surface`, of IOSurfaceID `surfaceId`, the asker's lookup of it (null where none), where it + // is that block's surface (RgfxSurfaceBlocks.hpp): false, nothing changed, where it is not. + // Under the contexts' lock, calling nothing of IOSurface's. + bool reviveSurfaceBlock(RgfxSurfaceEntry &e, OSObject *surface, uint32_t surfaceId); IOPCIDevice *pci; IOMemoryMap *registerMap; diff --git a/guest/kext/src/RgfxAcceleratorContexts.cpp b/guest/kext/src/RgfxAcceleratorContexts.cpp index f5f7bce3c..eb7c2b22c 100644 --- a/guest/kext/src/RgfxAcceleratorContexts.cpp +++ b/guest/kext/src/RgfxAcceleratorContexts.cpp @@ -121,6 +121,21 @@ struct ContextState { // Under contextLock: the units of GPU addresses held, the units a context holds (set at the // state's start, from the device's maxBufferLength), the next context number, and the // blocks handed out, sorted by offset. + // + // The lock order: IOSurface's own locks come before every lock of the kext's. IOSurface calls + // the device caches' control function (RgfxAcceleratorLocks.cpp) holding locks of its own: + // op 5 from a client's release (IOSurfaceRootUserClient::release_surface), under the lock + // IOSurfaceRoot's lookupSurface takes; ops 6 and 7 from a purgeable change; ops 0 to 3 from a + // CPU lock. The control function takes the locks' state.lock, which is taken after + // contextLock where both are held, and never contextLock. So no thread holding contextLock or + // state.lock calls into IOSurface: no lookup, no device cache made or its control function + // set, no setCurrent, no CPU lock, and no release of a surface or a device cache, which may + // free it inside IOSurface (letGo hands those to the release worker). The getters read under + // them, IOSurface's getClientRetainCount, getLockSeed and getMemoryDescriptor, each load a + // field and take no lock (read from IOSurface's x86_64 code in macOS 26.6's KDK). Seen on a + // 12.7.6 boot, in a spindump: an ask holding contextLock in a lookup, and a client's release + // holding the lock it waited for, its op 5 waiting for contextLock in wakeReleases, held + // WindowServer for good. IOLock *contextLock; RgfxContextSlots slots; UInt32 contextUnits; @@ -258,12 +273,67 @@ struct ReleaseStats { // on with it still pending. UInt64 writeBackWaits; UInt64 writeBackLate; + // Atomic, under no lock: when the first dormant block asked to go since the worker's last + // run, set from the control function (wakeReleases), which takes no contextLock. UInt64 reapAskedAt; UInt64 loggedCount; UInt64 loggedAt; }; ReleaseStats releaseStats = {}; +// Under contextLock: the references of device caches and surfaces let go of under it (letGo), +// which the release worker releases out of every lock of the kext's (releaseLetGo), in the order +// let go. The list holds them as they were given, retaining none; null and empty while none waits. +struct LetGoList { + OSObject **refs; + UInt32 count; + UInt32 capacity; +}; +LetGoList letGoList = {nullptr, 0, 0}; +constexpr UInt32 kLetGoFirst = 16; + +// Hands the caller's reference of `object`, a device cache or a surface, to the release worker, +// which releases it out of every lock of the kext's: a release here may free it inside IOSurface, +// which may wait for IOSurface's lock (ContextState's lock order). Under contextLock. One the list +// has no room for is kept for good, logged. +void letGo(OSObject *object) +{ + if (!object) + return; + if (letGoList.count == letGoList.capacity) { + const UInt32 grown = letGoList.capacity ? 2 * letGoList.capacity : kLetGoFirst; + auto *refs = static_cast(IOMalloc(sizeof(OSObject *) * grown)); + if (!refs) { + IOLog("RgfxAccelerator: no memory to let go of a %s out of the contexts' lock: it is " + "kept for good\n", + object->getMetaClass()->getClassName()); + return; + } + if (letGoList.count) + bcopy(letGoList.refs, refs, sizeof(OSObject *) * letGoList.count); + if (letGoList.refs) + IOFree(letGoList.refs, sizeof(OSObject *) * letGoList.capacity); + letGoList.refs = refs; + letGoList.capacity = grown; + } + letGoList.refs[letGoList.count++] = object; + thread_call_enter(releaseCall); +} + +// Releases the references letGo was given, in its order, out of every lock of the kext's. On the +// release worker. +void releaseLetGo() +{ + IOLockLock(contextLock); + const LetGoList list = letGoList; + letGoList = {nullptr, 0, 0}; + IOLockUnlock(contextLock); + for (UInt32 i = 0; i < list.count; i++) + list.refs[i]->release(); + if (list.refs) + IOFree(list.refs, sizeof(OSObject *) * list.capacity); +} + UInt64 nanosSince(UInt64 then, UInt64 now) { UInt64 ns = 0; @@ -499,13 +569,11 @@ void releaseFreedBlocks(thread_call_param_t accelerator, thread_call_param_t) { RgfxAccelerator *accel = static_cast(accelerator); IOLockLock(contextLock); - if (releaseStats.reapAskedAt) { - rgfxLatencyAdd(releaseStats.reapWait, - nanosSince(releaseStats.reapAskedAt, mach_absolute_time())); - releaseStats.reapAskedAt = 0; - } + if (const UInt64 asked = __atomic_exchange_n(&releaseStats.reapAskedAt, 0, __ATOMIC_RELAXED)) + rgfxLatencyAdd(releaseStats.reapWait, nanosSince(asked, mach_absolute_time())); reapDormant(); IOLockUnlock(contextLock); + releaseLetGo(); noteDormant(); // The answers come through the framebuffer's work loop: name this worker's hook there // before the first release is posted. @@ -1299,8 +1367,13 @@ bool letGoBlock(RgfxSurfaceEntry &e, UInt32 context, bool keep, void *wired = nu // flight names it), the cache's, so they never go back to macOS while it is in the table. void *cacheWire = nullptr; const bool blockWired = ownedWire || hostPages != nullptr; - rgfxSurfaceLocksForget(e.cache, e.surface, e.offset, e.cached && release, blockWired, - &cacheWire); + // The entry's references of the device cache and the surface go out of this lock, the + // cache's first, where the locks' state no longer holds them. + if (rgfxSurfaceLocksForget(e.cache, e.surface, e.offset, e.cached && release, blockWired, + &cacheWire)) { + letGo(static_cast(e.cache)); + letGo(static_cast(e.surface)); + } if (cacheWire && !rgfxBlockHoldWire(blockTable, e.offset, cacheWire)) unwire(cacheWire); rgfxSurfaceClear(surfaceTable, e); @@ -1559,6 +1632,22 @@ IOReturn RgfxAccelerator::acquireSurfaceBlock(RgfxAcceleratorUserClient *client, if (inPlace ? address % kPage || length % kPage : size < length) return kIOReturnBadArgument; RgfxSurfaceTable &table = surfaceTable; + // The asker's IOSurface, where the device caches surfaces: a new block of it waits for its + // pages' write-back (rgfxSurfaceCacheWritingBack), and a cached block in place of it, held or + // dormant, is the ask's, found by it (rgfxSurfaceFindCached), and so is a dormant block found + // by the asker's pages that is its block (reviveSurfaceBlock). 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. None wires the asker's pages: the kext wires them only where none holds. + // Looked up before the contexts' lock, under which nothing calls into IOSurface + // (ContextState), and released once the ask is done, out of it, but a new deferred entry's, + // which keeps it. + struct SurfaceRef { + OSObject *object = nullptr; + ~SurfaceRef() { OSSafeReleaseNULL(object); } + } asker; + if (inPlace && surfaceId && (surfaceCache || deferredBudget)) + asker.object = rgfxSurfaceLocksLookup(this, task, surfaceId); IOLockLock(contextLock); if (!table.entries) { auto *made = static_cast( @@ -1568,17 +1657,6 @@ IOReturn RgfxAccelerator::acquireSurfaceBlock(RgfxAcceleratorUserClient *client, table = {made, kMaxSurfaceBlocks}; } } - // The asker's IOSurface, where the device caches surfaces: a new block of it waits for its - // pages' write-back (rgfxSurfaceCacheWritingBack), and a cached block in place of it, held or - // dormant, is the ask's, found by it (rgfxSurfaceFindCached). 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. None wires the asker's pages: the kext wires them only where none 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, cachedFound = false; // The surface's resident pages the ask listed, where the host lets a deferral carry them // (RgfxDeferCarry.hpp): a surface fresh but for those may be deferred too. @@ -1586,11 +1664,9 @@ IOReturn RgfxAccelerator::acquireSurfaceBlock(RgfxAcceleratorUserClient *client, resident && deferCarries ? rgfxResidentPages(*resident, length, PAGE_SIZE) : 0; if (!listed) resident = nullptr; - if (inPlace && surfaceId && (surfaceCache || deferredBudget) && table.entries) - asker.object = rgfxSurfaceLocksLookup(this, task, surfaceId); - if (asker.object && surfaceCache) + if (asker.object && table.entries && surfaceCache) cachedFound = rgfxSurfaceFindCached(table, asker.object, length, size, true) >= 0; - if (asker.object && deferredBudget && !cachedFound) { + if (asker.object && table.entries && deferredBudget && !cachedFound) { int32_t d = -1; while (asker.object && (d = rgfxSurfaceFindDeferred(table, asker.object)) >= 0 && table.entries[d].pending) @@ -1696,7 +1772,7 @@ IOReturn RgfxAccelerator::acquireSurfaceBlock(RgfxAcceleratorUserClient *client, ? rgfxSurfaceFind(table, runs, count, length, size, inPlace, &differs) : -1; if (at >= 0 && table.entries[at].dormant) { - revived = reviveSurfaceBlock(table.entries[at], task, surfaceId); + revived = reviveSurfaceBlock(table.entries[at], asker.object, surfaceId); if (revived) break; release |= letGoDormant(static_cast(at), kRgfxDormantStale); @@ -2001,11 +2077,11 @@ void RgfxAccelerator::wakeReleases() { if (!__atomic_load_n(&contextLock, __ATOMIC_ACQUIRE)) return; - // When the first dormant block asked to go, for the worker's reap of it (ReleaseStats). - IOLockLock(contextLock); - if (!releaseStats.reapAskedAt) - releaseStats.reapAskedAt = mach_absolute_time(); - IOLockUnlock(contextLock); + // When the first dormant block asked to go, for the worker's reap of it (ReleaseStats), set + // with no lock: the control function calls this holding IOSurface's lock (ContextState). + UInt64 none = 0; + __atomic_compare_exchange_n(&releaseStats.reapAskedAt, &none, mach_absolute_time(), false, + __ATOMIC_RELAXED, __ATOMIC_RELAXED); thread_call_enter(releaseCall); } @@ -2024,21 +2100,15 @@ void RgfxAccelerator::retryRefusedBlocks() } } -bool RgfxAccelerator::reviveSurfaceBlock(RgfxSurfaceEntry &e, task_t task, uint32_t surfaceId) +bool RgfxAccelerator::reviveSurfaceBlock(RgfxSurfaceEntry &e, OSObject *surface, + uint32_t surfaceId) { - void *surface = nullptr, *cache = nullptr; - if (!surfaceCache || !surfaceId || !e.runCount || - !rgfxSurfaceLocksAttach(this, task, surfaceId, e.runs[0].address, &surface, &cache)) - return false; - // The asker's surface is the dormant block's only where IOSurface gives it the same device - // cache, which the block holds: no other surface has it, and no new cache takes its address - // while it is held. - const bool same = cache == e.cache && surface == e.surface && - rgfxSurfaceRevives(e, cache, rgfxSurfaceCacheWake(cache)); - // The attach's references go: the entry holds its own of both. - static_cast(cache)->release(); - static_cast(surface)->release(); - if (!same) + // The asker's surface is the dormant block's only where it is the surface the block holds, + // with the block's device cache, the one IOSurface gives that surface for this accelerator: + // the block's pages, which the ask found it by, are that surface's (rgfxSurfaceLocksAttach + // checked them at the block's caching), and no other surface has the cache. + if (!surfaceCache || !surfaceId || !e.runCount || !surface || surface != e.surface || + !e.cache || !rgfxSurfaceRevives(e, e.cache, rgfxSurfaceCacheWake(e.cache))) return false; rgfxSurfaceWake(surfaceTable, e); e.surfaceId = surfaceId; @@ -2545,32 +2615,66 @@ RgfxAccelerator::surfaceDeviceCache(RgfxAcceleratorUserClient *client, task_t ta if (!contextLock) return kSurfaceCacheNotHeld; RgfxSurfaceTable &table = surfaceTable; - IOLockLock(contextLock); - int32_t at = table.entries ? rgfxSurfaceAt(table, offset) : -1; - RgfxSurfaceEntry *e = at >= 0 ? &table.entries[at] : nullptr; + // A held block with no device cache yet has its surface's made out of the contexts' lock + // (ContextState's lock order), for the block of that serial and first page, and the entry is + // read again under the lock: the block that takes the attach is the one it was made for, and + // an attach no block takes is released out of the lock, the cache's first. + void *madeCache = nullptr, *madeSurface = nullptr; + bool attached = false, tried = false; + UInt64 madeSerial = 0, madeAt = 0; SurfaceCacheAnswer answer = kSurfaceCacheMade; - if (!e || (!e->runCount && !e->deferred) || !rgfxSurfaceHeldBy(table, client, offset, 1)) - answer = kSurfaceCacheNotHeld; - else if (e->pending) - answer = kSurfaceCachePending; - if (answer == kSurfaceCacheMade && !e->cache && !e->noCache) { - e->noCache = !rgfxSurfaceLocksAttach(this, task, surfaceId, e->runs[0].address, - &e->surface, &e->cache); - if (!e->noCache) - e->surfaceId = surfaceId; - } - if (answer == kSurfaceCacheMade && !e->cache) - answer = kSurfaceCacheNone; - else if (answer == kSurfaceCacheMade && e->surfaceId != surfaceId) - answer = kSurfaceCacheOtherSurface; - if (answer == kSurfaceCacheMade) { - *cache = e->cache; - static_cast(e->cache)->retain(); - *surface = static_cast(e->surface); - (*surface)->retain(); - *inPlace = e->inPlace; + IOLockLock(contextLock); + for (;;) { + const int32_t at = table.entries ? rgfxSurfaceAt(table, offset) : -1; + RgfxSurfaceEntry *e = at >= 0 ? &table.entries[at] : nullptr; + answer = kSurfaceCacheMade; + if (!e || (!e->runCount && !e->deferred) || !rgfxSurfaceHeldBy(table, client, offset, 1)) + answer = kSurfaceCacheNotHeld; + else if (e->pending) + answer = kSurfaceCachePending; + const bool needed = answer == kSurfaceCacheMade && !e->cache && !e->noCache; + if (needed && (!tried || e->serial != madeSerial || e->runs[0].address != madeAt)) { + madeSerial = e->serial; + madeAt = e->runs[0].address; + IOLockUnlock(contextLock); + if (madeCache) + static_cast(madeCache)->release(); + if (madeSurface) + static_cast(madeSurface)->release(); + madeCache = madeSurface = nullptr; + attached = rgfxSurfaceLocksAttach(this, task, surfaceId, madeAt, &madeSurface, + &madeCache); + tried = true; + IOLockLock(contextLock); + continue; + } + if (needed) { + e->noCache = !attached; + if (attached) { + e->surface = madeSurface; + e->cache = madeCache; + e->surfaceId = surfaceId; + madeCache = madeSurface = nullptr; + } + } + if (answer == kSurfaceCacheMade && !e->cache) + answer = kSurfaceCacheNone; + else if (answer == kSurfaceCacheMade && e->surfaceId != surfaceId) + answer = kSurfaceCacheOtherSurface; + if (answer == kSurfaceCacheMade) { + *cache = e->cache; + static_cast(e->cache)->retain(); + *surface = static_cast(e->surface); + (*surface)->retain(); + *inPlace = e->inPlace; + } + break; } IOLockUnlock(contextLock); + if (madeCache) + static_cast(madeCache)->release(); + if (madeSurface) + static_cast(madeSurface)->release(); return answer; } diff --git a/guest/kext/src/RgfxAcceleratorLocks.cpp b/guest/kext/src/RgfxAcceleratorLocks.cpp index 633ef64a0..337697b59 100644 --- a/guest/kext/src/RgfxAcceleratorLocks.cpp +++ b/guest/kext/src/RgfxAcceleratorLocks.cpp @@ -109,11 +109,15 @@ constexpr UInt32 kNoRoomLogged = 4; // One initialised object (it lands in __DATA,__data, as the contexts' state does), made at the // first write named and kept for the kernel's life. struct LockState { - // Under `lock`: the pending writes. The waiting locks sleep on `table`. + // Under `lock`: the pending writes. The waiting locks sleep on `table`. The control function + // takes `lock` holding IOSurface's own locks, and a thread holding the contexts' lock may take + // it: so nothing calls into IOSurface under it but IOSurface's getters, which take no lock, + // and nothing takes the contexts' lock under it (the lock order, ContextState in + // RgfxAcceleratorContexts.cpp). IOLock *lock; RgfxLockTable table; - // Under the contexts' lock (RgfxAccelerator::surfaceDeviceCache): IOSurfaceRoot, retained, - // and the accelerator ID it gave this accelerator. + // Set once (startRoot), under no lock: IOSurfaceRoot, retained, and the accelerator ID it + // gave this accelerator. Atomic: the device caches made, the first kCachesLogged logged. OSObject *root; uint32_t acceleratorId; uint32_t cachesMade; @@ -218,21 +222,35 @@ bool isSurface(const OSObject *surface) 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. +// Whether a caller of startRoot is finding IOSurfaceRoot, or found it. +bool rootStarting = false; + +// IOSurfaceRoot, retained, and the accelerator ID it gives `accel`, found at the first call and +// kept. Under no lock of the kext's, as the ID is IOSurface's to give (the lock order, +// ContextState in RgfxAcceleratorContexts.cpp): one caller finds them, and the others wait for +// it to publish them, or to find no root, which the next call looks for again. bool startRoot(RgfxAccelerator *accel) { - if (state.root) + if (__atomic_load_n(&state.root, __ATOMIC_ACQUIRE)) return true; + bool expected = false; + if (!__atomic_compare_exchange_n(&rootStarting, &expected, true, false, __ATOMIC_ACQ_REL, + __ATOMIC_ACQUIRE)) { + while (!__atomic_load_n(&state.root, __ATOMIC_ACQUIRE) && + __atomic_load_n(&rootStarting, __ATOMIC_ACQUIRE)) + IOSleep(1); + return __atomic_load_n(&state.root, __ATOMIC_ACQUIRE) != nullptr; + } 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"); + __atomic_store_n(&rootStarting, false, __ATOMIC_RELEASE); return false; } - state.root = root; state.acceleratorId = rgfxIOSurfaceRootAcceleratorID(root, accel); + __atomic_store_n(&state.root, root, __ATOMIC_RELEASE); IOLog("RgfxAccelerator: IOSurface accelerator ID %u\n", state.acceleratorId); return true; } @@ -363,6 +381,11 @@ void surfaceControl(void *accelerator, RgfxDeviceCache *cache, uint32_t op, uint const RgfxCachedSurface *c = rgfxCacheFind(state.caches, key); if (c != nullptr && c->object != nullptr) { const auto *surface = static_cast(c->object); + // IOSurface's getter under state.lock, kept there on purpose: it loads a field and + // takes no lock (read from IOSurface's x86_64 code in macOS 26.6's KDK), and op 5 + // calls it holding IOSurface's own lock at each client's release, which a getter + // taking that lock could not do (the lock order, ContextState in + // RgfxAcceleratorContexts.cpp). clients = rgfxIOSurfaceClientCount(surface); rgfxCacheNoteClients(state.caches, key, clients); } @@ -532,7 +555,7 @@ bool rgfxSurfaceLocksAttach(RgfxAccelerator *accel, task_t task, uint32_t surfac return false; } rgfxDeviceCacheSetControl(cache, accel, &surfaceControl); - if (state.cachesMade++ < kCachesLogged) + if (__atomic_fetch_add(&state.cachesMade, 1, __ATOMIC_RELAXED) < kCachesLogged) IOLog("RgfxAccelerator: IOSurface %u's device cache %p, retain count %d\n", surfaceId, cache, reinterpret_cast(cache)->getRetainCount()); *surfaceOut = surface; @@ -756,6 +779,11 @@ RgfxSurfacePageCounts rgfxSurfaceLocksPageCounts(OSObject *surface) bool rgfxSurfaceLocksFresh(OSObject *surface, UInt64 length, uint64_t listed) { + // Called under the contexts' lock, kept there on purpose: IOSurface's getters here load a + // field and take no lock (read from IOSurface's x86_64 code in macOS 26.6's KDK; op 5 calls + // getClientRetainCount holding IOSurface's own lock at each client's release), and the count + // maps and walks the surface's memory through IOKit and the VM, never IOSurface (the lock + // order, ContextState in RgfxAcceleratorContexts.cpp). const uint32_t seed = rgfxIOSurfaceLockSeed(surface); IOMemoryDescriptor *md = OSDynamicCast(IOMemoryDescriptor, rgfxIOSurfaceMemory(surface)); return md && length <= md->getLength() && @@ -842,6 +870,10 @@ RgfxDeferAnswer rgfxSurfaceLocksDefer(RgfxAccelerator *accel, OSObject *surface, c->context = context; c->size = size; c->length = length; + // IOSurface's getter, as in op 5, under state.lock, kept there on purpose: it loads a field + // and takes no lock (read from IOSurface's x86_64 code in macOS 26.6's KDK), and op 5 calls + // it holding IOSurface's own lock at each client's release, which a getter taking that lock + // could not do (the lock order, ContextState in RgfxAcceleratorContexts.cpp). rgfxCacheNoteClients(state.caches, key, rgfxIOSurfaceClientCount(surface)); } else if (!previous) { state.noRoom++; @@ -1045,7 +1077,7 @@ void unwireSurface(void *wire) } } // namespace -void rgfxSurfaceLocksForget(void *cache, void *surface, UInt64 offset, bool releasing, +bool rgfxSurfaceLocksForget(void *cache, void *surface, UInt64 offset, bool releasing, bool blockWired, void **wireOut) { if (wireOut) @@ -1076,20 +1108,18 @@ void rgfxSurfaceLocksForget(void *cache, void *surface, UInt64 offset, bool rele static_cast(map)->release(); letGoMemory(carried, true); if (kept) - return; - // 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. 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(); + return false; + // The references rgfxSurfaceLocksAttach took are the caller's to release, out of every lock, + // the cache's first: IOSurface frees a cache released to none (RgfxIOSurfaceKPI.hpp), while + // its surface lives. 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. A deferred block's memory never wired, whose pages the device never had, is + // only released. if (wireOut && wired) *wireOut = wire; else letGoMemory(wire, wired); + return true; } bool rgfxSurfaceCacheAdd(void *cache, void *surface, UInt64 offset, uint32_t surfaceId, @@ -1138,6 +1168,10 @@ bool rgfxSurfaceCacheAdd(void *cache, void *surface, UInt64 offset, uint32_t sur c->clientsAt = reinterpret_cast(header->getVirtualAddress() + kRgfxSurfaceClientsOffset); c->object = surface; + // IOSurface's getter, as in op 5, under state.lock, kept there on purpose: it loads a field + // and takes no lock (read from IOSurface's x86_64 code in macOS 26.6's KDK), and op 5 calls + // it holding IOSurface's own lock at each client's release, which a getter taking that lock + // could not do (the lock order, ContextState in RgfxAcceleratorContexts.cpp). rgfxCacheNoteClients(state.caches, key, rgfxIOSurfaceClientCount(static_cast(surface))); } @@ -1178,6 +1212,10 @@ void rgfxSurfaceCacheNoteClients(UInt64 offset) return; IOLockLock(state.lock); RgfxCachedSurface *c = rgfxCacheAtBlock(state.caches, offset); + // IOSurface's getter, as in op 5, under state.lock, kept there on purpose: it loads a field and + // takes no lock (read from IOSurface's x86_64 code in macOS 26.6's KDK), and op 5 calls it + // holding IOSurface's own lock at each client's release, which a getter taking that lock could + // not do (the lock order, ContextState in RgfxAcceleratorContexts.cpp). if (c != nullptr && c->object != nullptr) rgfxCacheNoteClients(state.caches, c->key, rgfxIOSurfaceClientCount(static_cast(c->object)));