mirror of
https://github.com/lemonade-sdk/mac_linuxgpu.git
synced 2026-11-22 23:57:31 -10:00
Session calls never run on the driver's incoming-call thread
DriverKit delivers every client's calls, and the driver's own Stop, on one thread, and runs each under its target queue with a synchronous dispatch. Session clients shared the owner's queue, and observers and Linux-file clients hopped to it synchronously, so a session call that slept there (a probe, an allocation that evicts, a fence wait, a session close), or anything queued behind one, held every client; on a GPU that stopped, forever (build 241). Every client now has a queue of its own, and nothing on the delivery thread waits for the owner's queue: - Selectors that never sleep answer there: Ping, RuntimeBuild (from flags the session queue publishes; the context is never touched), the cached QueryInfo tags, the power query and the power wait's registration, and OWNER_RESULT (88). - Every other selector must be called with IOConnectCallAsync*: the call returns at once with a token and runs on the owner's queue, in arrival order, exactly as it ran there before; it completes with its IOReturn, scalar outputs and structure output length, and OWNER_RESULT fetches the structure output once. EVENT_WAIT keeps its own completion; a wait that does not start completes at once with the reason. A synchronous call of such a selector is refused (kIOReturnNotPermitted, logged once per client). - SysfsRead and DrmInfo stay synchronous but bounded: the read runs on a wait-pool thread (rt_bounded_run, new) and the call waits at most 250 ms (kIOReturnTimeout; while one overruns, the next is kIOReturnBusy). The observer's self-test, Retire and ReleaseQuarantine are async calls. - A session client's Stop, and an observer's FinishStop, run on the owner's queue after the client's queued calls. Linux-file clients join the session on the owner's queue with their first open (LX_CALL_ASYNC), and the first open's InitDevice and HostWindow are async calls. - CopyClientMemoryForType no longer touches the session: BOMap makes the BO's descriptor on the owner's queue and the mapping looks it up; the raw BAR lease takes its own spinlock. Clients: host/owner_call.h and host/selector_call.h (header-only) call a selector as the driver serves it, synchronously or as an awaited async call; the HSA runtime, the host app (callScalar, callStruct, callMethod) and libmlg_drm use them, and scripts/mlg_owner_call.py does the same for drm-selftest.py and display-test.py's initialization. A client older than this driver fails at its first session call that can sleep, with the reason in the driver log. Tests: test-owner-call runs the production owner_call machinery (extracted, DriverKit mocked) against a session call that sleeps: calls return at once, cached queries and the power wait answer while it sleeps, later calls queue in order, completions carry the right layout, OWNER_RESULT once, BO memory is found without the session, and a hung bounded read times out within its bound. test-bounded covers rt_bounded_run on the real wait pool; test-session-shutdown checks the selector rules and runs the Stop paths through the owner's queue.
This commit is contained in:
1 parent
0c8ffc27d5
commit
9d10aa0e33
27 files changed
+1910
-176
No files matched your search
@@ -874,6 +874,22 @@ test-display-async:
|
||||
test: test-display-async
|
||||
.PHONY: test-display-async
|
||||
|
||||
# Session calls off the delivery thread (dext/sources/MacLinuxGPUXcode.mm
|
||||
# owner_call), and the bounded reads' runtime (rt/bounded.h).
|
||||
test-owner-call:
|
||||
bash scripts/test-owner-call.sh
|
||||
|
||||
test-bounded:
|
||||
@mkdir -p $(BUILD)/tests
|
||||
$(CC) -std=gnu11 -g -O1 -w -fsanitize=address,undefined -D__KERNEL__ -include linux/autoconf.h \
|
||||
-Ilinuxu/headers linuxu/tests/test_bounded.c linuxu/src/amdgpu-rt/bounded.c \
|
||||
linuxu/src/amdgpu-rt/wait_pool.c linuxu/src/shims/timekeeping.c -Wl,-dead_strip -lpthread \
|
||||
-o $(BUILD)/tests/test_bounded
|
||||
$(BUILD)/tests/test_bounded
|
||||
|
||||
test: test-owner-call test-bounded
|
||||
.PHONY: test-owner-call test-bounded
|
||||
|
||||
test-session-shutdown:
|
||||
bash scripts/test-session-shutdown.sh
|
||||
|
||||
@@ -1118,7 +1134,7 @@ MLG_DRM_BUILD := $(BUILD)/libmlg_drm
|
||||
MLG_DRM_SRCS := libmlg_drm/src/mlg_drm.c libmlg_drm/src/mlg_transport_iokit.c libmlg_drm/src/mlg_init.c \
|
||||
linuxu/src/amdgpu-rt/lx_frame.c linuxu/src/amdgpu-rt/lx_describe.c
|
||||
MLG_DRM_OBJS := $(addprefix $(MLG_DRM_BUILD)/,$(notdir $(MLG_DRM_SRCS:.c=.o)))
|
||||
MLG_DRM_CFLAGS := -std=c11 -Wall -Wextra -Werror -O2 -fPIC -MMD -MP -DMLG_LX_CLIENT_BUILD \
|
||||
MLG_DRM_CFLAGS := -std=c11 -Wall -Wextra -Werror -O2 -fPIC -MMD -MP -DMLG_LX_CLIENT_BUILD -Ihost \
|
||||
-Ilibmlg_drm/include -Ilibmlg_drm/compat -Ilibmlg_drm/src \
|
||||
-I$(LINUX)/include/uapi -idirafter linuxu/headers
|
||||
|
||||
|
||||
+628
-105
@@ -82,6 +82,7 @@
|
||||
#include <rt/lx_timing.h>
|
||||
#include <rt/kfd_session.h>
|
||||
#include <rt/wait_pool.h>
|
||||
#include <rt/bounded.h>
|
||||
#include <rt/sysfs.h>
|
||||
#include <rt/dext_pci.h>
|
||||
#include <rt/dext_dma.h>
|
||||
@@ -357,10 +358,20 @@ struct MacLinuxGPUUserClient_IVars {
|
||||
bool stopping;
|
||||
bool observer; // read-only: never joins, opens or closes a session
|
||||
bool identityRecorded; // pid/name handed to the compute backend
|
||||
// Observers and Linux-file clients run on their own queue and hop to
|
||||
// the owner's queue for everything but their own calls.
|
||||
// Every client's calls arrive on a queue of its own; whatever touches
|
||||
// the session runs on the owner's (session) queue, as an async call
|
||||
// (owner_call) that never holds the delivery thread.
|
||||
IODispatchQueue *ownerQueue;
|
||||
bool onOwnerQueue;
|
||||
// Structure outputs of the client's async session calls, until
|
||||
// OWNER_RESULT fetches them (owner_call_store, owner_result).
|
||||
IOLock *ownerLock;
|
||||
struct OwnerResult *ownerResults;
|
||||
uint64_t ownerToken;
|
||||
// The memory of its mapped BOs (BOMap), made on the owner's queue, so a
|
||||
// mapping (CopyClientMemoryForType, on the delivery thread) only looks
|
||||
// one up. Under ownerLock.
|
||||
struct ClientMemory *memories;
|
||||
bool syncRefusalLogged;
|
||||
bool linuxFile; // type 2: a Linux process of its own (lx_files)
|
||||
struct rt_lx_client *lx; // created on the first Linux-file call
|
||||
MacLinuxGPUUserClient *nextLinuxFile; // s_linuxFiles registry
|
||||
@@ -2060,26 +2071,22 @@ IMPL(MacLinuxGPUUserClient, Start)
|
||||
ret = driver->CopyDispatchQueue(kIOServiceDefaultQueueName, &ownerQueue);
|
||||
if (ret != kIOReturnSuccess || ownerQueue == nullptr)
|
||||
return ret != kIOReturnSuccess ? ret : kIOReturnNoResources;
|
||||
// A session client shares the owner's serial queue with every session
|
||||
// transition and LSE ioctl. An observer gets its own: SysfsRead and
|
||||
// DrmInfo run upstream callbacks that take upstream locks and may sleep
|
||||
// on an SMU round trip, so they must neither wait behind an in-flight
|
||||
// ioctl nor stall one. Its other selectors hop to the owner's queue.
|
||||
// A Linux-file client gets its own for the same reason: its process's
|
||||
// system calls (lx_files) may sleep in upstream locks, and none of them
|
||||
// may wait behind another client's.
|
||||
IODispatchQueue *clientQueue = ownerQueue;
|
||||
if (observer || linuxFile) {
|
||||
clientQueue = nullptr;
|
||||
ret = IODispatchQueue::Create(observer ? "MacLinuxGPUObserver" : "MacLinuxGPULinuxFile",
|
||||
0, 0, &clientQueue);
|
||||
if (ret != kIOReturnSuccess || clientQueue == nullptr) {
|
||||
ownerQueue->release();
|
||||
return ret != kIOReturnSuccess ? ret : kIOReturnNoMemory;
|
||||
}
|
||||
// Every client gets a queue of its own for its calls. DriverKit runs a
|
||||
// call on its one delivery thread, under the target queue: a call that
|
||||
// waited for the owner's queue (busy with a probe, a session close, or
|
||||
// a client's session call that sleeps) would hold every client and the
|
||||
// driver's Stop with it. Session work runs on the owner's queue as
|
||||
// async calls (owner_call), in arrival order.
|
||||
IODispatchQueue *clientQueue = nullptr;
|
||||
ret = IODispatchQueue::Create(observer ? "MacLinuxGPUObserver" :
|
||||
linuxFile ? "MacLinuxGPULinuxFile" : "MacLinuxGPUSession",
|
||||
0, 0, &clientQueue);
|
||||
if (ret != kIOReturnSuccess || clientQueue == nullptr) {
|
||||
ownerQueue->release();
|
||||
return ret != kIOReturnSuccess ? ret : kIOReturnNoMemory;
|
||||
}
|
||||
ret = SetDispatchQueue(kIOServiceDefaultQueueName, clientQueue);
|
||||
if (clientQueue != ownerQueue) clientQueue->release();
|
||||
clientQueue->release();
|
||||
if (ret != kIOReturnSuccess || s_nextClientID == UINT64_MAX) {
|
||||
ownerQueue->release();
|
||||
return ret != kIOReturnSuccess ? ret : kIOReturnNoResources;
|
||||
@@ -2087,7 +2094,10 @@ IMPL(MacLinuxGPUUserClient, Start)
|
||||
ivars = IONewZero(MacLinuxGPUUserClient_IVars, 1);
|
||||
if (!ivars) { ownerQueue->release(); return kIOReturnNoMemory; }
|
||||
ivars->displayResults = display_slot_new();
|
||||
if (!ivars->displayResults) {
|
||||
ivars->ownerLock = IOLockAlloc();
|
||||
if (!ivars->displayResults || !ivars->ownerLock) {
|
||||
display_slot_put(ivars->displayResults);
|
||||
if (ivars->ownerLock) IOLockFree(ivars->ownerLock);
|
||||
IOSafeDeleteNULL(ivars, MacLinuxGPUUserClient_IVars, 1);
|
||||
ownerQueue->release();
|
||||
return kIOReturnNoMemory;
|
||||
@@ -2109,6 +2119,10 @@ IMPL(MacLinuxGPUUserClient, Start)
|
||||
static void lx_finish_stop(MacLinuxGPUUserClient *client, IOService *provider)
|
||||
{
|
||||
auto *iv = client->ivars;
|
||||
// A first call that joined on this queue after the Stop took the
|
||||
// client's process (lx_join_main ran in between): that process exits
|
||||
// too, on a thread of its own.
|
||||
if (struct rt_lx_client *late = lx_take(client)) (void)rt_lx_client_retire(late, nullptr, nullptr);
|
||||
const bool participant = iv->sessionGeneration == s_sessionGeneration;
|
||||
if (participant) {
|
||||
iv->sessionGeneration = 0;
|
||||
@@ -2172,6 +2186,10 @@ static void lx_client_stop(MacLinuxGPUUserClient *client, IOService *provider)
|
||||
client->ivars->ownerQueue->DispatchAsync(^{ lx_finish_stop(client, provider); });
|
||||
}
|
||||
|
||||
static void session_client_stop(MacLinuxGPUUserClient *client, IOService *provider);
|
||||
static void owner_results_free(MacLinuxGPUUserClient *client);
|
||||
static IOMemoryDescriptor *client_memory_find(MacLinuxGPUUserClient *client, uint64_t type);
|
||||
|
||||
kern_return_t
|
||||
IMPL(MacLinuxGPUUserClient, Stop)
|
||||
{
|
||||
@@ -2185,8 +2203,9 @@ IMPL(MacLinuxGPUUserClient, Stop)
|
||||
// No session membership or mappings. A display agent's imports and
|
||||
// the output it started end with it (on its own queue, so none of
|
||||
// its calls is in flight); a closing session has released them.
|
||||
// It finishes on the owner's queue, after its session calls.
|
||||
observer_display_client_stop(ivars->clientID);
|
||||
FinishStop(provider);
|
||||
ivars->ownerQueue->DispatchAsync(^{ FinishStop(provider); });
|
||||
return kIOReturnSuccess;
|
||||
}
|
||||
// An unplug terminates the clients before the provider: see whether the
|
||||
@@ -2196,6 +2215,15 @@ IMPL(MacLinuxGPUUserClient, Stop)
|
||||
lx_client_stop(this, provider);
|
||||
return kIOReturnSuccess;
|
||||
}
|
||||
// The rest is session work: on the owner's queue, after the client's
|
||||
// session calls, never on the delivery thread.
|
||||
ivars->ownerQueue->DispatchAsync(^{ session_client_stop(this, provider); });
|
||||
return kIOReturnSuccess;
|
||||
}
|
||||
|
||||
static void session_client_stop(MacLinuxGPUUserClient *client, IOService *provider)
|
||||
{
|
||||
auto *ivars = client->ivars;
|
||||
const bool participant = ivars->sessionGeneration == s_sessionGeneration;
|
||||
if (participant && s_participants > 1 && !s_sessionClosing) {
|
||||
// IRQ delivery stays active while this client's queues are removed.
|
||||
@@ -2214,12 +2242,11 @@ IMPL(MacLinuxGPUUserClient, Stop)
|
||||
}
|
||||
if (s_sessionClosing || (participant && (!s_participants || s_dmaQuarantined))) {
|
||||
ivars->nextStopping = s_stoppingClients;
|
||||
s_stoppingClients = this;
|
||||
s_stoppingClients = client;
|
||||
close_session(ivars->ownerDriver);
|
||||
} else {
|
||||
FinishStop(provider);
|
||||
client->FinishStop(provider);
|
||||
}
|
||||
return kIOReturnSuccess;
|
||||
}
|
||||
|
||||
void
|
||||
@@ -2241,6 +2268,7 @@ MacLinuxGPUUserClient::FinishStop(IOService *provider)
|
||||
if (!ivars->observer) s_rawBARLease.release(ivars->clientID);
|
||||
if (ivars->ownerQueue) ivars->ownerQueue->release();
|
||||
display_slot_put(ivars->displayResults);
|
||||
owner_results_free(this);
|
||||
IOSafeDeleteNULL(ivars, MacLinuxGPUUserClient_IVars, 1);
|
||||
Stop(provider, SUPERDISPATCH);
|
||||
provider->release();
|
||||
@@ -2281,31 +2309,36 @@ IMPL(MacLinuxGPUUserClient, InterruptOccurred)
|
||||
// Linux-file calls (rt/lx_abi.h selectors), on the client's own queue.
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
// The client's process, created on its first call: the client joins the
|
||||
// session as a session client does (on the owner's queue, outside the
|
||||
// call admission, which a closing session drains while holding that
|
||||
// queue), then gets a Linux process with its creator's pid and name.
|
||||
static kern_return_t lx_state(MacLinuxGPUUserClient *client, struct rt_lx_client **out)
|
||||
// The client's process, created by its first call, on the owner's queue
|
||||
// (lx_join): the client joins the session as a session client does, then
|
||||
// gets a Linux process with its creator's pid and name. The delivery
|
||||
// thread only reads whether it exists (lx_ready).
|
||||
static struct rt_lx_client *lx_ready(MacLinuxGPUUserClient *client)
|
||||
{
|
||||
auto *iv = client->ivars;
|
||||
if (iv->lx && iv->sessionGeneration == __atomic_load_n(&s_sessionGeneration, __ATOMIC_ACQUIRE)) {
|
||||
*out = iv->lx;
|
||||
return kIOReturnSuccess;
|
||||
}
|
||||
if (iv->lx) {
|
||||
// From a session that has closed: never used since its admission
|
||||
// closed, so it holds no files of the driver that is gone.
|
||||
if (struct rt_lx_client *stale = lx_take(client)) rt_lx_client_destroy(stale);
|
||||
}
|
||||
__block kern_return_t ret = kIOReturnNotReady;
|
||||
__block void *pdev = nullptr;
|
||||
iv->ownerQueue->DispatchSync(^{
|
||||
if (s_stopping || s_sessionClosing || s_dmaQuarantined || !s_modulesRunning || !s_rtDevice)
|
||||
return;
|
||||
ret = ensure_open(client);
|
||||
if (ret == kIOReturnSuccess) pdev = rt_device_get_pdev(s_rtDevice);
|
||||
});
|
||||
lx_registry_acquire();
|
||||
struct rt_lx_client *lx = iv->lx &&
|
||||
iv->sessionGeneration == __atomic_load_n(&s_sessionGeneration, __ATOMIC_ACQUIRE) ?
|
||||
iv->lx : nullptr;
|
||||
lx_registry_release();
|
||||
return lx;
|
||||
}
|
||||
|
||||
// On the owner's queue.
|
||||
static kern_return_t lx_join(MacLinuxGPUUserClient *client, struct rt_lx_client **out)
|
||||
{
|
||||
auto *iv = client->ivars;
|
||||
if (iv->stopping) return kIOReturnNotAttached;
|
||||
if ((*out = lx_ready(client))) return kIOReturnSuccess;
|
||||
// A process from a session that has closed: never used since its
|
||||
// admission closed, so it holds no files of the driver that is gone;
|
||||
// it exits on a thread of its own all the same.
|
||||
if (struct rt_lx_client *stale = lx_take(client)) (void)rt_lx_client_retire(stale, nullptr, nullptr);
|
||||
if (s_stopping || s_sessionClosing || s_dmaQuarantined || !s_modulesRunning || !s_rtDevice)
|
||||
return kIOReturnNotReady;
|
||||
kern_return_t ret = ensure_open(client);
|
||||
if (ret != kIOReturnSuccess) return ret;
|
||||
void *pdev = rt_device_get_pdev(s_rtDevice);
|
||||
int pid = 0;
|
||||
char name[32];
|
||||
client_creator(client, &pid, name, sizeof(name));
|
||||
@@ -2596,13 +2629,70 @@ static kern_return_t lx_scanout_call(struct rt_lx_client *lx, IOUserClientMethod
|
||||
return a->structureOutput ? kIOReturnSuccess : kIOReturnNoMemory;
|
||||
}
|
||||
|
||||
// A client's first LX_CALL_ASYNC: the join (lx_join) and the operation on
|
||||
// the owner's queue; the delivery thread returns at once (token 0: the
|
||||
// completion carries the operation's own).
|
||||
struct LxJoin {
|
||||
MacLinuxGPUUserClient *client;
|
||||
LxAsync *ctx;
|
||||
uint64_t in[MLG_LX_OP_MMAP_ARGS];
|
||||
uint32_t nin;
|
||||
};
|
||||
static void lx_join_main(LxJoin *job)
|
||||
{
|
||||
struct rt_lx_client *lx = nullptr;
|
||||
const kern_return_t kr = lx_join(job->client, &lx);
|
||||
int r = kr == kIOReturnSuccess ? 0 :
|
||||
kr == kIOReturnNoMemory ? -MLG_LX_ENOMEM : -MLG_LX_ENODEV;
|
||||
if (!r) {
|
||||
uint64_t token = 0;
|
||||
if (!s_lxCalls.enter()) {
|
||||
r = -MLG_LX_ENODEV;
|
||||
} else {
|
||||
r = rt_lx_op_async(lx, job->in, job->nin, lx_async_done, job->ctx, &token);
|
||||
s_lxCalls.leave();
|
||||
}
|
||||
}
|
||||
// Not started: complete it here (the worker completes the others).
|
||||
if (r) lx_async_done(job->ctx, 0, r, nullptr, 0);
|
||||
IOFree(job, sizeof(*job));
|
||||
}
|
||||
|
||||
static kern_return_t lx_join_call(MacLinuxGPUUserClient *client, IOUserClientMethodArguments *a)
|
||||
{
|
||||
const uint32_t nin = a->scalarInputCount;
|
||||
if (!a->completion || !a->scalarInput || nin < 1 || nin > MLG_LX_OP_MMAP_ARGS ||
|
||||
!a->scalarOutput || a->scalarOutputCount < 2)
|
||||
return kIOReturnBadArgument;
|
||||
auto *job = static_cast<LxJoin *>(IOMallocZero(sizeof(LxJoin)));
|
||||
if (!job) return kIOReturnNoMemory;
|
||||
job->ctx = lx_async_begin(client, a->completion);
|
||||
if (!job->ctx) {
|
||||
IOFree(job, sizeof(*job));
|
||||
return kIOReturnNoMemory;
|
||||
}
|
||||
job->client = client;
|
||||
job->nin = nin;
|
||||
memcpy(job->in, a->scalarInput, nin * sizeof(uint64_t));
|
||||
client->ivars->ownerQueue->DispatchAsync(^{ lx_join_main(job); });
|
||||
a->scalarOutput[0] = 0;
|
||||
a->scalarOutput[1] = 0;
|
||||
a->scalarOutputCount = 2;
|
||||
return kIOReturnSuccess;
|
||||
}
|
||||
|
||||
static kern_return_t lx_external_method(MacLinuxGPUUserClient *client, uint64_t selector,
|
||||
IOUserClientMethodArguments *arguments)
|
||||
{
|
||||
const uint64_t entered_ns = rt_lx_time_ns();
|
||||
struct rt_lx_client *lx = nullptr;
|
||||
kern_return_t ret = lx_state(client, &lx);
|
||||
if (ret != kIOReturnSuccess) return ret;
|
||||
struct rt_lx_client *lx = lx_ready(client);
|
||||
if (!lx) {
|
||||
// No process yet (or one from a closed session): its first call is
|
||||
// an open (LX_CALL_ASYNC), which joins on the owner's queue.
|
||||
return selector == MLG_SELECTOR_LX_CALL_ASYNC ? lx_join_call(client, arguments)
|
||||
: kIOReturnNotReady;
|
||||
}
|
||||
kern_return_t ret;
|
||||
if (!s_lxCalls.enter()) return kIOReturnNotReady;
|
||||
ret = selector == MLG_SELECTOR_LX_SCANOUT ? lx_scanout_call(lx, arguments) :
|
||||
lx_call(client, lx, selector, arguments, entered_ns,
|
||||
@@ -2732,35 +2822,26 @@ static kern_return_t lx_copy_memory(MacLinuxGPUUserClient *client, uint64_t type
|
||||
kern_return_t
|
||||
IMPL(MacLinuxGPUUserClient, CopyClientMemoryForType)
|
||||
{
|
||||
// On the delivery thread: a lookup or a provider call, never the
|
||||
// session's state (the owner's queue made the BO descriptors at BOMap).
|
||||
if (!ivars || ivars->stopping) return kIOReturnNotAttached;
|
||||
if (ivars->observer) return kIOReturnNotPermitted;
|
||||
if (ivars->linuxFile) return lx_copy_memory(this, type, options, memory);
|
||||
ComputeClientScope clientScope(ivars->clientID);
|
||||
if (memory == nullptr || options == nullptr) {
|
||||
return kIOReturnBadArgument;
|
||||
}
|
||||
if (s_retainedPCI == nullptr) {
|
||||
return kIOReturnNotReady;
|
||||
}
|
||||
kern_return_t opened = ensure_open(this);
|
||||
if (opened != kIOReturnSuccess) return opened;
|
||||
if (type == MLG_FW_MAILBOX_MEMORY_TYPE) {
|
||||
*options = 0;
|
||||
return copy_firmware_mailbox(memory);
|
||||
}
|
||||
if (ivars->sessionGeneration != __atomic_load_n(&s_sessionGeneration, __ATOMIC_ACQUIRE))
|
||||
return kIOReturnNotOpen;
|
||||
if (type >= 0x10000) {
|
||||
void *cpu = nullptr;
|
||||
uint64_t size = 0;
|
||||
const int located = dext_compute_bo_memory(type, &cpu, &size);
|
||||
IOMemoryDescriptor *descriptor = nullptr;
|
||||
if (located == -EAGAIN_L && size) {
|
||||
// A KFD process's GTT BO: its TTM pages, at the BO's GPU VA.
|
||||
descriptor = copy_bo_ranges_descriptor((uint32_t)type, size);
|
||||
} else {
|
||||
if (located != 0 || !cpu || !size) return kIOReturnBadArgument;
|
||||
descriptor = static_cast<IOMemoryDescriptor *>(dext_dma_copy_descriptor(cpu));
|
||||
}
|
||||
if (!descriptor) return kIOReturnNotReady;
|
||||
IOMemoryDescriptor *descriptor = client_memory_find(this, type);
|
||||
if (!descriptor) return kIOReturnBadArgument;
|
||||
*options = 0;
|
||||
*memory = descriptor;
|
||||
return kIOReturnSuccess;
|
||||
@@ -3147,6 +3228,449 @@ static kern_return_t display_frames(uint64_t clientID, IOUserClientMethodArgumen
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// Session calls off the delivery thread (session_state.h, "Calls that
|
||||
// never sleep, and every other call").
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
// ExternalMethod's reference when a session call runs on the owner's queue
|
||||
// (owner_job_main) rather than arriving from a client.
|
||||
static const uint8_t kOwnerJob = 0;
|
||||
|
||||
struct OwnerResult {
|
||||
OwnerResult *next;
|
||||
uint64_t token;
|
||||
OSData *data;
|
||||
};
|
||||
|
||||
struct ClientMemory {
|
||||
ClientMemory *next;
|
||||
uint64_t handle, type;
|
||||
IOMemoryDescriptor *memory;
|
||||
};
|
||||
|
||||
static void owner_results_free(MacLinuxGPUUserClient *client)
|
||||
{
|
||||
auto *iv = client->ivars;
|
||||
if (!iv->ownerLock) return;
|
||||
IOLockLock(iv->ownerLock);
|
||||
OwnerResult *list = iv->ownerResults;
|
||||
iv->ownerResults = nullptr;
|
||||
ClientMemory *memories = iv->memories;
|
||||
iv->memories = nullptr;
|
||||
IOLockUnlock(iv->ownerLock);
|
||||
while (memories) {
|
||||
ClientMemory *next = memories->next;
|
||||
memories->memory->release();
|
||||
IOFree(memories, sizeof(*memories));
|
||||
memories = next;
|
||||
}
|
||||
while (list) {
|
||||
OwnerResult *next = list->next;
|
||||
if (list->data) list->data->release();
|
||||
IOFree(list, sizeof(*list));
|
||||
list = next;
|
||||
}
|
||||
IOLockFree(iv->ownerLock);
|
||||
iv->ownerLock = nullptr;
|
||||
}
|
||||
|
||||
// Keep a call's structure output for OWNER_RESULT (@data's reference
|
||||
// passes to the list). Results nobody fetches go with the client.
|
||||
static void owner_result_store(MacLinuxGPUUserClient *client, uint64_t token, OSData *data)
|
||||
{
|
||||
auto *entry = static_cast<OwnerResult *>(IOMallocZero(sizeof(OwnerResult)));
|
||||
if (!entry) {
|
||||
data->release();
|
||||
return;
|
||||
}
|
||||
entry->token = token;
|
||||
entry->data = data;
|
||||
IOLockLock(client->ivars->ownerLock);
|
||||
entry->next = client->ivars->ownerResults;
|
||||
client->ivars->ownerResults = entry;
|
||||
IOLockUnlock(client->ivars->ownerLock);
|
||||
}
|
||||
|
||||
// On the owner's queue, after BOMap: the descriptor a mapping of @type
|
||||
// hands out (the BO's DMA buffer, or a KFD GTT BO's page ranges).
|
||||
static void client_memory_stash(MacLinuxGPUUserClient *client, uint64_t handle, uint64_t type)
|
||||
{
|
||||
void *cpu = nullptr;
|
||||
uint64_t size = 0;
|
||||
const int located = dext_compute_bo_memory((uint32_t)type, &cpu, &size);
|
||||
IOMemoryDescriptor *descriptor = nullptr;
|
||||
if (located == -EAGAIN_L && size)
|
||||
descriptor = copy_bo_ranges_descriptor((uint32_t)type, size);
|
||||
else if (located == 0 && cpu && size)
|
||||
descriptor = static_cast<IOMemoryDescriptor *>(dext_dma_copy_descriptor(cpu));
|
||||
if (!descriptor) return; // the mapping then fails (kIOReturnBadArgument)
|
||||
auto *entry = static_cast<ClientMemory *>(IOMallocZero(sizeof(ClientMemory)));
|
||||
if (!entry) { descriptor->release(); return; }
|
||||
entry->handle = handle;
|
||||
entry->type = type;
|
||||
entry->memory = descriptor;
|
||||
IOLockLock(client->ivars->ownerLock);
|
||||
for (ClientMemory **link = &client->ivars->memories; *link; link = &(*link)->next) {
|
||||
if ((*link)->type != type) continue;
|
||||
ClientMemory *old = *link; // mapped again: the newer descriptor
|
||||
*link = old->next;
|
||||
old->memory->release();
|
||||
IOFree(old, sizeof(*old));
|
||||
break;
|
||||
}
|
||||
entry->next = client->ivars->memories;
|
||||
client->ivars->memories = entry;
|
||||
IOLockUnlock(client->ivars->ownerLock);
|
||||
}
|
||||
|
||||
// On the owner's queue, after BOFree.
|
||||
static void client_memory_drop(MacLinuxGPUUserClient *client, uint64_t handle)
|
||||
{
|
||||
ClientMemory *found = nullptr;
|
||||
IOLockLock(client->ivars->ownerLock);
|
||||
for (ClientMemory **link = &client->ivars->memories; *link; link = &(*link)->next) {
|
||||
if ((*link)->handle != handle) continue;
|
||||
found = *link;
|
||||
*link = found->next;
|
||||
break;
|
||||
}
|
||||
IOLockUnlock(client->ivars->ownerLock);
|
||||
if (found) {
|
||||
found->memory->release();
|
||||
IOFree(found, sizeof(*found));
|
||||
}
|
||||
}
|
||||
|
||||
// On the delivery thread: the descriptor, retained, or nullptr.
|
||||
static IOMemoryDescriptor *client_memory_find(MacLinuxGPUUserClient *client, uint64_t type)
|
||||
{
|
||||
IOMemoryDescriptor *memory = nullptr;
|
||||
IOLockLock(client->ivars->ownerLock);
|
||||
for (ClientMemory *entry = client->ivars->memories; entry; entry = entry->next) {
|
||||
if (entry->type != type) continue;
|
||||
memory = entry->memory;
|
||||
memory->retain();
|
||||
break;
|
||||
}
|
||||
IOLockUnlock(client->ivars->ownerLock);
|
||||
return memory;
|
||||
}
|
||||
|
||||
// OWNER_RESULT, on the delivery thread: a lookup under the client's lock.
|
||||
static kern_return_t owner_result(MacLinuxGPUUserClient *client, IOUserClientMethodArguments *a)
|
||||
{
|
||||
const uint64_t token = a->scalarInput[0];
|
||||
OSData *data = nullptr;
|
||||
bool fits = true;
|
||||
IOLockLock(client->ivars->ownerLock);
|
||||
for (OwnerResult **link = &client->ivars->ownerResults; *link; link = &(*link)->next) {
|
||||
if ((*link)->token != token) continue;
|
||||
if ((*link)->data->getLength() > a->structureOutputMaximumSize) {
|
||||
fits = false; // kept: the caller asks again with room
|
||||
break;
|
||||
}
|
||||
OwnerResult *entry = *link;
|
||||
*link = entry->next;
|
||||
data = entry->data;
|
||||
IOFree(entry, sizeof(*entry));
|
||||
break;
|
||||
}
|
||||
IOLockUnlock(client->ivars->ownerLock);
|
||||
if (!fits) return kIOReturnNoSpace;
|
||||
if (!data) return kIOReturnNotFound;
|
||||
a->structureOutput = data; // its reference passes to the reply
|
||||
a->scalarOutputCount = 0;
|
||||
return kIOReturnSuccess;
|
||||
}
|
||||
|
||||
struct OwnerJob {
|
||||
MacLinuxGPUUserClient *client;
|
||||
OSAction *action;
|
||||
uint64_t selector;
|
||||
uint64_t token;
|
||||
uint64_t in[16];
|
||||
uint32_t nin, nout;
|
||||
uint64_t outputMax;
|
||||
OSData *input; // a copy of the structure input
|
||||
IOMemoryDescriptor *inputDescriptor; // a large structure input, retained
|
||||
};
|
||||
|
||||
static void owner_job_free(OwnerJob *job)
|
||||
{
|
||||
if (job->input) job->input->release();
|
||||
if (job->inputDescriptor) job->inputDescriptor->release();
|
||||
job->action->release();
|
||||
job->client->release();
|
||||
IOFree(job, sizeof(*job));
|
||||
}
|
||||
|
||||
// On the owner's queue: the selector as it always ran there, then the
|
||||
// completion (session_state.h's layout).
|
||||
static void owner_job_main(OwnerJob *job)
|
||||
{
|
||||
IOUserClientMethodArguments a{};
|
||||
uint64_t out[MLG_OWNER_ASYNC_WORDS] = {};
|
||||
a.version = kIOUserClientMethodArgumentsCurrentVersion;
|
||||
a.selector = job->selector;
|
||||
a.scalarInput = job->in;
|
||||
a.scalarInputCount = job->nin;
|
||||
a.structureInput = job->input;
|
||||
a.structureInputDescriptor = job->inputDescriptor;
|
||||
a.scalarOutput = out;
|
||||
a.scalarOutputCount = job->nout;
|
||||
a.structureOutputMaximumSize = job->outputMax;
|
||||
a.completion = job->action;
|
||||
const kern_return_t kr = job->client->ExternalMethod(job->selector, &a, nullptr, nullptr,
|
||||
const_cast<uint8_t *>(&kOwnerJob));
|
||||
IOUserClientAsyncArgumentsArray data = {};
|
||||
if (job->selector == MLG_SELECTOR_EVENT_WAIT) {
|
||||
// Started: event_wait_main completes it. Not started: completed
|
||||
// here, in EVENT_WAIT's own layout, with the reason.
|
||||
const bool started = kr == kIOReturnSuccess && a.scalarOutputCount >= 1 &&
|
||||
(int64_t)out[0] >= 0;
|
||||
if (!started) {
|
||||
data[0] = job->in[0];
|
||||
data[1] = kr == kIOReturnSuccess ? out[0] : (uint64_t)(int64_t)-22; /* EINVAL */
|
||||
data[2] = 2; // the KFD wait failed
|
||||
job->client->AsyncCompletion(job->action, kIOReturnSuccess, data, MLG_EVENT_WAIT_WORDS);
|
||||
}
|
||||
if (a.structureOutput) a.structureOutput->release();
|
||||
owner_job_free(job);
|
||||
return;
|
||||
}
|
||||
const uint32_t n = kr == kIOReturnSuccess ?
|
||||
(a.scalarOutputCount < MLG_OWNER_ASYNC_SCALARS ? a.scalarOutputCount : MLG_OWNER_ASYNC_SCALARS) : 0;
|
||||
OSData *output = a.structureOutput;
|
||||
data[0] = job->token;
|
||||
data[1] = (uint64_t)(int64_t)kr;
|
||||
data[2] = n;
|
||||
data[3] = output ? output->getLength() : 0;
|
||||
for (uint32_t i = 0; i < n; ++i) data[MLG_OWNER_ASYNC_HEADER + i] = out[i];
|
||||
// In place before the completion, so a fetch that follows finds it.
|
||||
if (output) owner_result_store(job->client, job->token, output);
|
||||
job->client->AsyncCompletion(job->action, kIOReturnSuccess, data, MLG_OWNER_ASYNC_HEADER + n);
|
||||
owner_job_free(job);
|
||||
}
|
||||
|
||||
// The delivery thread's part of a session call: copy the arguments, queue
|
||||
// the call on the owner's queue, return.
|
||||
static kern_return_t owner_call(MacLinuxGPUUserClient *client, uint64_t selector,
|
||||
IOUserClientMethodArguments *a)
|
||||
{
|
||||
if (a->scalarInputCount > 16 || (a->scalarInputCount && !a->scalarInput))
|
||||
return kIOReturnBadArgument;
|
||||
auto *job = static_cast<OwnerJob *>(IOMallocZero(sizeof(OwnerJob)));
|
||||
if (!job) return kIOReturnNoMemory;
|
||||
if (a->structureInput && a->structureInput->getLength()) {
|
||||
job->input = OSData::withBytes(a->structureInput->getBytesNoCopy(),
|
||||
a->structureInput->getLength());
|
||||
if (!job->input) { IOFree(job, sizeof(*job)); return kIOReturnNoMemory; }
|
||||
}
|
||||
job->client = client;
|
||||
job->action = a->completion;
|
||||
job->selector = selector;
|
||||
job->token = __atomic_add_fetch(&client->ivars->ownerToken, 1, __ATOMIC_ACQ_REL);
|
||||
job->nin = a->scalarInputCount;
|
||||
if (job->nin) memcpy(job->in, a->scalarInput, job->nin * sizeof(uint64_t));
|
||||
// As many scalar outputs as the caller asked for, up to what the
|
||||
// completion carries (EVENT_WAIT: its one status word).
|
||||
job->nout = a->scalarOutputCount < MLG_OWNER_ASYNC_SCALARS ? a->scalarOutputCount
|
||||
: MLG_OWNER_ASYNC_SCALARS;
|
||||
if (selector == MLG_SELECTOR_EVENT_WAIT && job->nout < 1) job->nout = 1;
|
||||
// The caller's structure output room (a descriptor above 4096 bytes):
|
||||
// the output itself comes back through OWNER_RESULT.
|
||||
uint64_t room = a->structureOutputMaximumSize;
|
||||
if (a->structureOutputDescriptor) {
|
||||
uint64_t length = 0;
|
||||
if (a->structureOutputDescriptor->GetLength(&length) == kIOReturnSuccess) room = length;
|
||||
}
|
||||
job->outputMax = room;
|
||||
job->inputDescriptor = a->structureInputDescriptor;
|
||||
client->retain();
|
||||
job->action->retain();
|
||||
if (job->inputDescriptor) job->inputDescriptor->retain();
|
||||
client->ivars->ownerQueue->DispatchAsync(^{ owner_job_main(job); });
|
||||
if (a->scalarOutput && a->scalarOutputCount) {
|
||||
a->scalarOutput[0] = selector == MLG_SELECTOR_EVENT_WAIT ? 0 : job->token;
|
||||
a->scalarOutputCount = 1;
|
||||
}
|
||||
return kIOReturnSuccess;
|
||||
}
|
||||
|
||||
// The calls that run on the delivery thread (mlg_call_runs_on_delivery):
|
||||
// published state, a spinlock, or a client's own result list.
|
||||
static kern_return_t direct_call(MacLinuxGPUUserClient *client, uint64_t selector,
|
||||
IOUserClientMethodArguments *a)
|
||||
{
|
||||
const uint64_t *in = a->scalarInput;
|
||||
uint64_t *out = a->scalarOutput;
|
||||
switch (selector) {
|
||||
case MLG_SELECTOR_PING:
|
||||
if (a->scalarInputCount || !out || a->scalarOutputCount < 1) return kIOReturnBadArgument;
|
||||
out[0] = 0xA117AB1Eu;
|
||||
a->scalarOutputCount = 1;
|
||||
return kIOReturnSuccess;
|
||||
case MLG_SELECTOR_RUNTIME_BUILD: {
|
||||
// out[0]=magic, out[1]=ABI, out[2]=build when the session serves
|
||||
// compute, out[3] (when asked) the compiled build. Flags only.
|
||||
if (a->scalarInputCount || !out || a->scalarOutputCount < 3) return kIOReturnBadArgument;
|
||||
uint64_t build[4] = {0, 0, 0, 0};
|
||||
if (dext_compute_runtime_build_cached(build) != 0) return kIOReturnError;
|
||||
if (s_sessionClosing) build[2] = 0;
|
||||
const uint32_t words = a->scalarOutputCount >= 4 ? 4 : 3;
|
||||
for (uint32_t i = 0; i < words; ++i) out[i] = build[i];
|
||||
a->scalarOutputCount = words;
|
||||
return kIOReturnSuccess;
|
||||
}
|
||||
case MLG_SELECTOR_OWNER_RESULT:
|
||||
return owner_result(client, a);
|
||||
case MLG_SELECTOR_POWER:
|
||||
if (in[0] == MLG_POWER_OP_WAIT) {
|
||||
if (a->scalarInputCount != 2 || !a->completion) return kIOReturnBadArgument;
|
||||
return power_wait(client, a->completion, in[1]);
|
||||
}
|
||||
if (a->scalarInputCount != 1 || !out || a->scalarOutputCount < MLG_POWER_STATE_WORDS)
|
||||
return kIOReturnBadArgument;
|
||||
power_snapshot(out);
|
||||
a->scalarOutputCount = MLG_POWER_STATE_WORDS;
|
||||
return kIOReturnSuccess;
|
||||
case MLG_SELECTOR_QUERY_INFO:
|
||||
if (in[0] == DEXT_COMPUTE_QUERY_KERNEL_LOG) {
|
||||
if (!out || a->scalarOutputCount < 4) return kIOReturnBadArgument;
|
||||
uint64_t cursor = in[1], end = 0;
|
||||
uint8_t text[104] = {};
|
||||
const uint32_t words = a->scalarOutputCount < 16 ? a->scalarOutputCount : 16;
|
||||
const size_t copied = klog_read(&cursor, (char *)text,
|
||||
(words - 3) * sizeof(uint64_t), &end);
|
||||
memset(out, 0, words * sizeof(uint64_t));
|
||||
out[0] = end; out[1] = cursor; out[2] = copied;
|
||||
memcpy(out + 3, text, copied);
|
||||
a->scalarOutputCount = 3 + (uint32_t)((copied + 7) / 8);
|
||||
return kIOReturnSuccess;
|
||||
}
|
||||
if (in[0] == MLG_QUERY_POWER_STATE) {
|
||||
if (!out || a->scalarOutputCount < MLG_POWER_STATE_WORDS) return kIOReturnBadArgument;
|
||||
power_snapshot(out);
|
||||
a->scalarOutputCount = MLG_POWER_STATE_WORDS;
|
||||
return kIOReturnSuccess;
|
||||
}
|
||||
if (in[0] == DEXT_COMPUTE_QUERY_SESSION_STATE) {
|
||||
if (!out || a->scalarOutputCount < MLG_SESSION_STATE_WORDS) return kIOReturnBadArgument;
|
||||
session_state(out);
|
||||
a->scalarOutputCount = MLG_SESSION_STATE_WORDS;
|
||||
return kIOReturnSuccess;
|
||||
}
|
||||
// DEXT_COMPUTE_QUERY_PROBE_STATUS: probe progress, no MMIO.
|
||||
if (!out || a->scalarOutputCount < 5) return kIOReturnBadArgument;
|
||||
out[0] = s_probeAttempted;
|
||||
out[1] = s_modulesRunning;
|
||||
out[2] = (uint64_t)(int64_t)s_probeResult;
|
||||
out[3] = (uint64_t)dext_pci_transport_fault();
|
||||
out[4] = dext_pci_transport_fault_offset();
|
||||
a->scalarOutputCount = 5;
|
||||
return kIOReturnSuccess;
|
||||
default:
|
||||
return kIOReturnUnsupported;
|
||||
}
|
||||
}
|
||||
|
||||
// SysfsRead and DrmInfo, bounded (session_state.h): the read on a pool
|
||||
// thread, the call waiting at most MLG_BOUNDED_READ_MS for it.
|
||||
struct BoundedRead {
|
||||
uint64_t selector;
|
||||
uint64_t in[2];
|
||||
OSData *input;
|
||||
uint64_t outputMax;
|
||||
uint64_t out[MLG_SYSFS_READ_WORDS];
|
||||
uint32_t outCount;
|
||||
kern_return_t result;
|
||||
OSData *output;
|
||||
};
|
||||
static uint32_t s_boundedReadRunning;
|
||||
|
||||
static void bounded_read_free(void *arg)
|
||||
{
|
||||
auto *r = static_cast<BoundedRead *>(arg);
|
||||
if (r->input) r->input->release();
|
||||
if (r->output) r->output->release();
|
||||
IOFree(r, sizeof(*r));
|
||||
__atomic_store_n(&s_boundedReadRunning, 0u, __ATOMIC_RELEASE);
|
||||
}
|
||||
|
||||
static void bounded_read_main(void *arg)
|
||||
{
|
||||
auto *r = static_cast<BoundedRead *>(arg);
|
||||
IOUserClientMethodArguments a{};
|
||||
a.version = kIOUserClientMethodArgumentsCurrentVersion;
|
||||
a.selector = r->selector;
|
||||
a.scalarInput = r->in;
|
||||
a.scalarInputCount = 2;
|
||||
a.structureInput = r->input;
|
||||
a.scalarOutput = r->out;
|
||||
a.scalarOutputCount = MLG_SYSFS_READ_WORDS;
|
||||
a.structureOutputMaximumSize = r->outputMax;
|
||||
r->result = r->selector == MLG_SELECTOR_SYSFS_READ ? observer_sysfs_read(&a)
|
||||
: observer_drm_info(&a);
|
||||
r->outCount = a.scalarOutputCount;
|
||||
r->output = a.structureOutput;
|
||||
}
|
||||
|
||||
static kern_return_t bounded_read(uint64_t selector, IOUserClientMethodArguments *a)
|
||||
{
|
||||
if (!a->scalarInput || a->scalarInputCount != 2 || !a->scalarOutput ||
|
||||
a->structureInputDescriptor || a->structureOutputDescriptor)
|
||||
return kIOReturnBadArgument;
|
||||
// One at a time: a read still running past its bound makes the next
|
||||
// one busy rather than piling up threads.
|
||||
if (__atomic_exchange_n(&s_boundedReadRunning, 1u, __ATOMIC_ACQ_REL)) return kIOReturnBusy;
|
||||
auto *r = static_cast<BoundedRead *>(IOMallocZero(sizeof(BoundedRead)));
|
||||
if (!r) {
|
||||
__atomic_store_n(&s_boundedReadRunning, 0u, __ATOMIC_RELEASE);
|
||||
return kIOReturnNoMemory;
|
||||
}
|
||||
r->selector = selector;
|
||||
r->in[0] = a->scalarInput[0];
|
||||
r->in[1] = a->scalarInput[1];
|
||||
r->outputMax = a->structureOutputMaximumSize;
|
||||
if (a->structureInput && a->structureInput->getLength()) {
|
||||
r->input = OSData::withBytes(a->structureInput->getBytesNoCopy(),
|
||||
a->structureInput->getLength());
|
||||
if (!r->input) { bounded_read_free(r); return kIOReturnNoMemory; }
|
||||
}
|
||||
const int ran = rt_bounded_run(bounded_read_main, r, bounded_read_free, MLG_BOUNDED_READ_MS);
|
||||
if (ran == -110 /* Linux ETIMEDOUT (rt/bounded.h) */) {
|
||||
MACLINUXGPU_LOG("observer read (selector %llu) still running after %u ms; answered with a timeout",
|
||||
(unsigned long long)selector, MLG_BOUNDED_READ_MS);
|
||||
return kIOReturnTimeout;
|
||||
}
|
||||
if (ran) {
|
||||
bounded_read_free(r);
|
||||
return kIOReturnNoResources;
|
||||
}
|
||||
const kern_return_t kr = r->result;
|
||||
const uint32_t words = r->outCount < a->scalarOutputCount ? r->outCount : a->scalarOutputCount;
|
||||
for (uint32_t i = 0; i < words; ++i) a->scalarOutput[i] = r->out[i];
|
||||
a->scalarOutputCount = words;
|
||||
a->structureOutput = r->output; // its reference passes to the reply
|
||||
r->output = nullptr;
|
||||
bounded_read_free(r);
|
||||
return kr;
|
||||
}
|
||||
|
||||
// A synchronous call of a selector that must be called async: refused,
|
||||
// and logged once per client (an old client library or runtime).
|
||||
static kern_return_t refuse_sync(MacLinuxGPUUserClient *client, uint64_t selector)
|
||||
{
|
||||
if (!client->ivars->syncRefusalLogged) {
|
||||
client->ivars->syncRefusalLogged = true;
|
||||
MACLINUXGPU_EVENT("client %llu: selector %llu called synchronously; it can sleep and must be "
|
||||
"called async (a client library or runtime older than this driver: "
|
||||
"rebuild it)", client->ivars->clientID, (unsigned long long)selector);
|
||||
}
|
||||
return kIOReturnNotPermitted;
|
||||
}
|
||||
|
||||
// A client's last display op result (MacLinuxGPUUserClient_IVars::displayResults).
|
||||
struct DisplayResultSlot {
|
||||
uint32_t refs;
|
||||
@@ -3430,6 +3954,7 @@ static kern_return_t display_call(MacLinuxGPUUserClient *client, uint64_t client
|
||||
return kIOReturnSuccess;
|
||||
}
|
||||
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// ExternalMethod — the selector-RPC dispatch.
|
||||
//
|
||||
@@ -3447,47 +3972,37 @@ MacLinuxGPUUserClient::ExternalMethod(uint64_t selector,
|
||||
void *reference)
|
||||
{
|
||||
(void)target;
|
||||
(void)reference;
|
||||
(void)dispatch;
|
||||
if (!arguments) return kIOReturnBadArgument;
|
||||
if (ivars && ivars->observer && !ivars->onOwnerQueue) {
|
||||
// On the observer's own queue. Only the Linux reads run here; the
|
||||
// rest reads session state, which lives on the owner's queue.
|
||||
if (ivars->stopping) return kIOReturnNotAttached;
|
||||
if (!mlg_observer_selector_allowed(selector, arguments->scalarInput,
|
||||
arguments->scalarInputCount))
|
||||
return kIOReturnNotPermitted;
|
||||
if (selector == MLG_SELECTOR_SYSFS_READ) return observer_sysfs_read(arguments);
|
||||
if (selector == MLG_SELECTOR_DRM_INFO) return observer_drm_info(arguments);
|
||||
if (selector == MLG_SELECTOR_DRM_SELFTEST) return observer_drm_selftest(arguments);
|
||||
if (selector == MLG_SELECTOR_DISPLAY) return display_call(this, ivars->clientID, arguments);
|
||||
__block kern_return_t result = kIOReturnNotAttached;
|
||||
ivars->onOwnerQueue = true;
|
||||
ivars->ownerQueue->DispatchSync(^{
|
||||
result = ExternalMethod(selector, arguments, dispatch, target, reference);
|
||||
});
|
||||
ivars->onOwnerQueue = false;
|
||||
return result;
|
||||
}
|
||||
if (ivars && ivars->linuxFile && !ivars->onOwnerQueue) {
|
||||
// On the client's own queue: its process's system calls run here;
|
||||
// device initialization and cached queries on the owner's queue.
|
||||
// HostWindow comes with InitDevice: the probe maps the GART at the
|
||||
// host window the client placed (libmlg_drm/src/mlg_init.c).
|
||||
if (ivars->stopping) return kIOReturnNotAttached;
|
||||
if (selector >= MLG_SELECTOR_LX_FIRST && selector <= MLG_SELECTOR_LX_LAST)
|
||||
return lx_external_method(this, selector, arguments);
|
||||
if (selector != kMacAMDGPUMethodPing && selector != kMacAMDGPUMethodRuntimeBuild &&
|
||||
selector != kMacAMDGPUMethodQueryInfo && selector != kMacAMDGPUMethodInitDevice &&
|
||||
selector != kMacAMDGPUMethodHostWindow)
|
||||
return kIOReturnUnsupported;
|
||||
__block kern_return_t result = kIOReturnNotAttached;
|
||||
ivars->onOwnerQueue = true;
|
||||
ivars->ownerQueue->DispatchSync(^{
|
||||
result = ExternalMethod(selector, arguments, dispatch, target, reference);
|
||||
});
|
||||
ivars->onOwnerQueue = false;
|
||||
return result;
|
||||
if (reference != &kOwnerJob) {
|
||||
// From a client, on the delivery thread every client's calls share:
|
||||
// nothing here may sleep or wait for the owner's queue.
|
||||
if (!ivars || ivars->stopping) return kIOReturnNotAttached;
|
||||
const uint64_t *in = arguments->scalarInput;
|
||||
const uint32_t nin = arguments->scalarInputCount;
|
||||
if (ivars->observer) {
|
||||
if (!mlg_observer_selector_allowed(selector, in, nin))
|
||||
return kIOReturnNotPermitted;
|
||||
if (selector == MLG_SELECTOR_SYSFS_READ || selector == MLG_SELECTOR_DRM_INFO)
|
||||
return bounded_read(selector, arguments);
|
||||
if (selector == MLG_SELECTOR_DISPLAY) return display_call(this, ivars->clientID, arguments);
|
||||
} else if (ivars->linuxFile) {
|
||||
// Its process's system calls, the GPU's initialization (with the
|
||||
// host window it needs) and the cached queries.
|
||||
if (selector >= MLG_SELECTOR_LX_FIRST && selector <= MLG_SELECTOR_LX_LAST)
|
||||
return lx_external_method(this, selector, arguments);
|
||||
if (selector != kMacAMDGPUMethodPing && selector != kMacAMDGPUMethodRuntimeBuild &&
|
||||
selector != kMacAMDGPUMethodQueryInfo && selector != kMacAMDGPUMethodInitDevice &&
|
||||
selector != kMacAMDGPUMethodHostWindow && selector != MLG_SELECTOR_OWNER_RESULT)
|
||||
return kIOReturnUnsupported;
|
||||
}
|
||||
if (mlg_call_runs_on_delivery(selector, in, nin))
|
||||
return direct_call(this, selector, arguments);
|
||||
if (selector == MLG_SELECTOR_OWNER_RESULT) return kIOReturnBadArgument;
|
||||
if (!arguments->completion) return refuse_sync(this, selector);
|
||||
return owner_call(this, selector, arguments);
|
||||
}
|
||||
// On the owner's queue (owner_job_main): the session call itself.
|
||||
if (!ivars || ivars->stopping || ivars->ownerDriver != s_driver ||
|
||||
(s_stopping && !ivars->observer))
|
||||
return kIOReturnNotAttached;
|
||||
@@ -3895,6 +4410,7 @@ MacLinuxGPUUserClient::ExternalMethod(uint64_t selector,
|
||||
if (arguments->scalarInput == nullptr || arguments->scalarInputCount < 1)
|
||||
return kIOReturnBadArgument;
|
||||
int r = dext_compute_bo_free(arguments->scalarInput[0]);
|
||||
if (r == 0) client_memory_drop(this, arguments->scalarInput[0]);
|
||||
if (r == -ENOENT_L) return kIOReturnBadArgument;
|
||||
if (r == -EAGAIN_L || r == -EBUSY_L) return kIOReturnBusy;
|
||||
if (r != 0) return kIOReturnError;
|
||||
@@ -3928,6 +4444,7 @@ MacLinuxGPUUserClient::ExternalMethod(uint64_t selector,
|
||||
arguments->scalarOutput[0] = out[0];
|
||||
if (arguments->scalarOutputCount >= 2) arguments->scalarOutput[1] = out[1];
|
||||
if (arguments->scalarOutputCount > 2) arguments->scalarOutputCount = 2;
|
||||
client_memory_stash(this, arguments->scalarInput[0], out[0]);
|
||||
return kIOReturnSuccess;
|
||||
}
|
||||
|
||||
@@ -4348,6 +4865,12 @@ MacLinuxGPUUserClient::ExternalMethod(uint64_t selector,
|
||||
return kIOReturnSuccess;
|
||||
}
|
||||
|
||||
case MLG_SELECTOR_DRM_SELFTEST:
|
||||
// The observer's self-test: GPU work for seconds, so an async call
|
||||
// on this (the owner's) queue.
|
||||
if (!ivars->observer) return kIOReturnUnsupported;
|
||||
return observer_drm_selftest(arguments);
|
||||
|
||||
case MLG_SELECTOR_RETIRE: {
|
||||
// Hand the GPU to a replacement driver (session_state.h). Entitled:
|
||||
// it ends every client's session.
|
||||
|
||||
@@ -84,6 +84,10 @@ static struct {
|
||||
bool removed;
|
||||
bool legacy_queues; /* the queue partition left a legacy HQD */
|
||||
bool kfd_disabled; /* policy: never open KFD sessions */
|
||||
/* Whether the context serves AQL or KFD queues, set on the session
|
||||
* queue when it opens, so RuntimeBuild answers on any thread without
|
||||
* touching the context (dext_compute_runtime_build_cached). */
|
||||
bool runtime_available;
|
||||
} production;
|
||||
|
||||
uint64_t dext_compute_select_client(uint64_t client)
|
||||
@@ -134,9 +138,18 @@ static struct production_client *client_record(uint64_t client, bool create)
|
||||
return empty;
|
||||
}
|
||||
|
||||
static void runtime_available_update(void)
|
||||
{
|
||||
__atomic_store_n(&production.runtime_available, production.ctx &&
|
||||
(dext_aql_available(production.ctx) == 0 ||
|
||||
(!production.kfd_disabled && dext_kfd_supported(production.ctx) == 0)),
|
||||
__ATOMIC_RELEASE);
|
||||
}
|
||||
|
||||
void dext_compute_set_kfd_policy(bool enabled)
|
||||
{
|
||||
production.kfd_disabled = !enabled;
|
||||
runtime_available_update();
|
||||
}
|
||||
|
||||
int dext_compute_client_identity(uint64_t client, int pid, const char *comm)
|
||||
@@ -445,6 +458,7 @@ int dext_compute_start(struct pci_dev *pdev)
|
||||
production.properties = properties;
|
||||
production.ready = true;
|
||||
production.uncertain = false;
|
||||
runtime_available_update();
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -458,6 +472,7 @@ int dext_compute_stop(void)
|
||||
if (production.uncertain && !production.uncertain_kfd_only && !production.removed)
|
||||
return -EBUSY_L;
|
||||
production.ready = false;
|
||||
__atomic_store_n(&production.runtime_available, false, __ATOMIC_RELEASE);
|
||||
/* KFD processes first: their queues leave MES and their memory is
|
||||
* freed before the kernel BOs and the context go. */
|
||||
{
|
||||
@@ -544,7 +559,11 @@ int dext_compute_runtime_build_cached(uint64_t *out)
|
||||
return -EINVAL_L;
|
||||
out[0] = DEXT_RUNTIME_MAGIC;
|
||||
out[1] = DEXT_RUNTIME_ABI;
|
||||
out[2] = production.ready && !production.uncertain && production.ctx ?
|
||||
/* Flags the session queue publishes: never the context itself, which
|
||||
* may be closing on that queue. */
|
||||
out[2] = __atomic_load_n(&production.ready, __ATOMIC_ACQUIRE) &&
|
||||
!__atomic_load_n(&production.uncertain, __ATOMIC_ACQUIRE) &&
|
||||
__atomic_load_n(&production.runtime_available, __ATOMIC_ACQUIRE) ?
|
||||
DEXT_RUNTIME_BUILD : 0;
|
||||
out[3] = DEXT_RUNTIME_BUILD;
|
||||
return 0;
|
||||
|
||||
@@ -2,28 +2,49 @@
|
||||
#include <stdint.h>
|
||||
|
||||
namespace maclinuxgpu {
|
||||
/* Serialized by the driver's lifecycle queue. Raw mappings permit writes
|
||||
* outside RPC serialization, so their lease lasts until client retirement. */
|
||||
/* Raw mappings permit writes outside RPC serialization, so their lease
|
||||
* lasts until client retirement. Claimed on the delivery thread (a client's
|
||||
* memory mapping) and checked and released on the session queue, so every
|
||||
* operation takes the lease's own spinlock (held for a few loads and
|
||||
* stores). */
|
||||
class RawBARLease {
|
||||
uint64_t owner = 0;
|
||||
bool mapped = false;
|
||||
uint32_t lock = 0;
|
||||
void acquire() { while (__atomic_exchange_n(&lock, 1u, __ATOMIC_ACQUIRE)) {} }
|
||||
void release_lock() { __atomic_store_n(&lock, 0u, __ATOMIC_RELEASE); }
|
||||
bool allowsJoinLocked(uint64_t client) const { return client && (!owner || owner == client); }
|
||||
public:
|
||||
bool allowsJoin(uint64_t client) const {
|
||||
return client && (!owner || owner == client);
|
||||
bool allowsJoin(uint64_t client) {
|
||||
acquire();
|
||||
const bool allowed = allowsJoinLocked(client);
|
||||
release_lock();
|
||||
return allowed;
|
||||
}
|
||||
bool claim(uint64_t client, bool attached, uint32_t participants) {
|
||||
if (!attached || participants != 1 || !allowsJoin(client)) return false;
|
||||
owner = client;
|
||||
return true;
|
||||
acquire();
|
||||
const bool claimed = attached && participants == 1 && allowsJoinLocked(client);
|
||||
if (claimed) owner = client;
|
||||
release_lock();
|
||||
return claimed;
|
||||
}
|
||||
bool markMapped(uint64_t client) {
|
||||
if (!client || owner != client) return false;
|
||||
mapped = true;
|
||||
return true;
|
||||
acquire();
|
||||
const bool marked = client && owner == client;
|
||||
if (marked) mapped = true;
|
||||
release_lock();
|
||||
return marked;
|
||||
}
|
||||
bool hasMappings() {
|
||||
acquire();
|
||||
const bool has = mapped;
|
||||
release_lock();
|
||||
return has;
|
||||
}
|
||||
bool hasMappings() const { return mapped; }
|
||||
void release(uint64_t client) {
|
||||
acquire();
|
||||
if (owner == client) { owner = 0; mapped = false; }
|
||||
release_lock();
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -119,6 +119,39 @@ static inline bool mlg_release_blocker_permanent(uint32_t blocker)
|
||||
#define MLG_SELECTOR_RETIRE 85u
|
||||
#define MLG_SELECTOR_EVENT 86u
|
||||
#define MLG_SELECTOR_EVENT_WAIT 87u
|
||||
#define MLG_SELECTOR_OWNER_RESULT 88u
|
||||
|
||||
/* Calls that never sleep, and every other call.
|
||||
*
|
||||
* DriverKit delivers every client's calls, and the driver's own Stop, on
|
||||
* one thread. A call that sleeps there (an upstream lock, an allocation
|
||||
* that evicts, a fence, a probe) holds them all; on a GPU that stopped it
|
||||
* holds them forever (build 241). So only the calls
|
||||
* mlg_call_runs_on_delivery() names (cached state, the power wait's
|
||||
* registration) run on that thread, synchronously as always. Every other
|
||||
* selector (the session client's whole MacAMDGPU set, InitDevice and
|
||||
* HostWindow from any client, the observer's self-test, Retire and
|
||||
* ReleaseQuarantine, EVENT) must be called with IOConnectCallAsync*: the
|
||||
* call returns at once (out[0] = its token when the caller asked for any
|
||||
* scalar output), the selector runs on the driver's session queue, in the
|
||||
* order the calls arrived, with the same arguments, and the call completes
|
||||
* with async data
|
||||
* [0] token, [1] the selector's IOReturn, [2] n, its scalar output count
|
||||
* (at most MLG_OWNER_ASYNC_SCALARS), [3] bytes of its structure output,
|
||||
* [4 .. 4+n) its scalar outputs.
|
||||
* OWNER_RESULT, in [0] = token, returns that structure output once (struct
|
||||
* out, sized by the caller), or kIOReturnNotFound. A synchronous call of
|
||||
* such a selector is refused with kIOReturnNotPermitted (and logged).
|
||||
* EVENT_WAIT keeps its own completion (above): its registration runs on
|
||||
* the session queue, then the wait on a driver thread; a wait that does
|
||||
* not start completes at once with [1] = -errno. SysfsRead and DrmInfo
|
||||
* stay synchronous, bounded: the read runs on a driver thread, and the
|
||||
* call waits at most MLG_BOUNDED_READ_MS for it (kIOReturnTimeout; while
|
||||
* it is still running another is kIOReturnBusy). */
|
||||
#define MLG_OWNER_ASYNC_HEADER 4u
|
||||
#define MLG_OWNER_ASYNC_SCALARS 12u
|
||||
#define MLG_OWNER_ASYNC_WORDS (MLG_OWNER_ASYNC_HEADER + MLG_OWNER_ASYNC_SCALARS)
|
||||
#define MLG_BOUNDED_READ_MS 250u
|
||||
|
||||
/* Interrupt-driven waits on KFD signal events (a session client on the KFD
|
||||
* path; rt/kfd_session.h has the semantics).
|
||||
@@ -418,6 +451,8 @@ static inline bool mlg_observer_selector_allowed(uint64_t selector,
|
||||
case MLG_SELECTOR_RUNTIME_BUILD:
|
||||
case MLG_SELECTOR_RELEASE_QUARANTINE:
|
||||
return true;
|
||||
case MLG_SELECTOR_OWNER_RESULT:
|
||||
return input && input_count == 1 && input[0];
|
||||
case MLG_SELECTOR_RETIRE: /* entitlement-checked in the handler */
|
||||
return mlg_retire_args_valid(input, input_count);
|
||||
case MLG_SELECTOR_QUERY_INFO:
|
||||
@@ -470,4 +505,47 @@ static inline bool mlg_observer_selector_allowed(uint64_t selector,
|
||||
}
|
||||
}
|
||||
|
||||
/* Whether a call of @selector with @input runs on the delivery thread
|
||||
* itself (above): Ping, RuntimeBuild (its cached answer), the cached
|
||||
* QueryInfo tags, the power query and the power wait's registration, and
|
||||
* OWNER_RESULT. They read state the session queue publishes, or take only
|
||||
* a spinlock. */
|
||||
static inline bool mlg_call_runs_on_delivery(uint64_t selector, const uint64_t *input,
|
||||
uint32_t input_count)
|
||||
{
|
||||
switch (selector) {
|
||||
case MLG_SELECTOR_PING:
|
||||
case MLG_SELECTOR_RUNTIME_BUILD:
|
||||
return true;
|
||||
case MLG_SELECTOR_OWNER_RESULT:
|
||||
return input && input_count == 1 && input[0];
|
||||
case MLG_SELECTOR_QUERY_INFO:
|
||||
if (!input || !input_count)
|
||||
return false;
|
||||
return (input[0] == MLG_QUERY_PROBE_STATUS && input_count == 1) ||
|
||||
(input[0] == MLG_QUERY_SESSION_STATE && input_count == 1) ||
|
||||
(input[0] == MLG_QUERY_POWER_STATE && input_count == 1) ||
|
||||
(input[0] == MLG_QUERY_KERNEL_LOG && input_count == 2);
|
||||
case MLG_SELECTOR_POWER:
|
||||
return input && input_count >= 1 &&
|
||||
(input[0] == MLG_POWER_OP_QUERY || input[0] == MLG_POWER_OP_WAIT);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/* Whether a client calls @selector with @input synchronously: those that
|
||||
* run on the delivery thread, the bounded reads (SysfsRead, DrmInfo), and
|
||||
* the display's PRESENT and RESULT. Every other call is async. */
|
||||
static inline bool mlg_call_is_synchronous(uint64_t selector, const uint64_t *input,
|
||||
uint32_t input_count)
|
||||
{
|
||||
if (mlg_call_runs_on_delivery(selector, input, input_count))
|
||||
return true;
|
||||
if (selector == MLG_SELECTOR_SYSFS_READ || selector == MLG_SELECTOR_DRM_INFO)
|
||||
return true;
|
||||
return selector == MLG_SELECTOR_DISPLAY && input && input_count >= 1 &&
|
||||
(input[0] == MLG_DISPLAY_OP_PRESENT || input[0] == MLG_DISPLAY_OP_RESULT);
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -5,3 +5,6 @@
|
||||
#include "CGVirtualDisplayPrivate.h"
|
||||
/* Darwin notifications between the display daemon and the menu bar. */
|
||||
#include <notify.h>
|
||||
/* Selectors as the driver serves them: synchronous when they never sleep,
|
||||
* else async session calls awaited on the calling thread. */
|
||||
#include "selector_call.h"
|
||||
@@ -971,13 +971,12 @@ final class MacLinuxGPUHost {
|
||||
let inCount = UInt32(inScalars.count)
|
||||
var outBuf = [UInt64](repeating: 0, count: max(1, outScalars))
|
||||
var outN = UInt32(outBuf.count)
|
||||
// As the driver serves it: synchronous when it never sleeps, else an
|
||||
// async session call awaited here (host/selector_call.h).
|
||||
let kr: kern_return_t = inScalars.withUnsafeBufferPointer { ibuf in
|
||||
outBuf.withUnsafeMutableBufferPointer { obuf in
|
||||
IOConnectCallScalarMethod(ucConn, selector,
|
||||
ibuf.baseAddress,
|
||||
inCount,
|
||||
obuf.baseAddress,
|
||||
&outN)
|
||||
mlg_selector_call(ucConn, selector, ibuf.baseAddress, inCount, nil, 0,
|
||||
obuf.baseAddress, &outN, nil, nil)
|
||||
}
|
||||
}
|
||||
return (kr, Array(outBuf.prefix(Int(outN))))
|
||||
@@ -995,14 +994,12 @@ final class MacLinuxGPUHost {
|
||||
let kr: kern_return_t = outData.withUnsafeMutableBytes { outPtr -> kern_return_t in
|
||||
if let inData = inData {
|
||||
return inData.withUnsafeBytes { inPtr in
|
||||
IOConnectCallStructMethod(ucConn, selector,
|
||||
inPtr.baseAddress, inSize,
|
||||
outPtr.baseAddress, &outCnt)
|
||||
mlg_selector_call(ucConn, selector, nil, 0, inPtr.baseAddress, inSize,
|
||||
nil, nil, outPtr.baseAddress, &outCnt)
|
||||
}
|
||||
} else {
|
||||
return IOConnectCallStructMethod(ucConn, selector,
|
||||
nil, 0,
|
||||
outPtr.baseAddress, &outCnt)
|
||||
return mlg_selector_call(ucConn, selector, nil, 0, nil, 0,
|
||||
nil, nil, outPtr.baseAddress, &outCnt)
|
||||
}
|
||||
}
|
||||
return (kr, outData.prefix(Int(min(outCnt, size_t(max(0, outSize))))))
|
||||
@@ -1366,9 +1363,9 @@ extension MacLinuxGPUHost {
|
||||
outBuf.withUnsafeMutableBufferPointer { obuf in
|
||||
outData.withUnsafeMutableBytes { optr in
|
||||
inData.withUnsafeBytes { iptr in
|
||||
IOConnectCallMethod(ucConn, selector, ibuf.baseAddress, UInt32(inScalars.count),
|
||||
inData.isEmpty ? nil : iptr.baseAddress, inData.count,
|
||||
obuf.baseAddress, &outN, optr.baseAddress, &outCnt)
|
||||
mlg_selector_call(ucConn, selector, ibuf.baseAddress, UInt32(inScalars.count),
|
||||
inData.isEmpty ? nil : iptr.baseAddress, inData.count,
|
||||
obuf.baseAddress, &outN, optr.baseAddress, &outCnt)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
/* A MacLinuxGPU selector called the way the driver runs every call that can
|
||||
* sleep (dext/sources/session_state.h, "Calls that never sleep, and every
|
||||
* other call"): with IOConnectCallAsyncMethod, the completion awaited on the
|
||||
* calling thread, and the structure output, if any, fetched with
|
||||
* OWNER_RESULT. To its caller it behaves as IOConnectCallMethod does: the
|
||||
* selector's IOReturn, its scalar outputs and its structure output.
|
||||
*
|
||||
* Header only (static inline), for the host app (through its bridging
|
||||
* header), the HSA runtime and libmlg_drm. Each call has a notification
|
||||
* port of its own (header-only code keeps no state: Swift imports these
|
||||
* functions, not static variables). */
|
||||
#ifndef MLG_OWNER_CALL_H
|
||||
#define MLG_OWNER_CALL_H
|
||||
|
||||
#include <pthread.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <IOKit/IOKitLib.h>
|
||||
#include <mach/mach.h>
|
||||
|
||||
/* session_state.h's numbers (scripts/test-owner-call.sh checks they match). */
|
||||
#define MLG_OWNER_CALL_SELECTOR_PING 0u
|
||||
#define MLG_OWNER_CALL_SELECTOR_RESULT 88u
|
||||
#define MLG_OWNER_CALL_HEADER 4u
|
||||
#define MLG_OWNER_CALL_SCALARS 12u
|
||||
#define MLG_OWNER_CALL_WORDS (MLG_OWNER_CALL_HEADER + MLG_OWNER_CALL_SCALARS)
|
||||
|
||||
struct mlg_owner_call_waiter {
|
||||
bool done;
|
||||
kern_return_t status;
|
||||
uint64_t args[MLG_OWNER_CALL_WORDS];
|
||||
uint32_t nargs;
|
||||
};
|
||||
|
||||
static inline void mlg_owner_call_completed(void *refcon, IOReturn result, void **args,
|
||||
uint32_t nargs)
|
||||
{
|
||||
struct mlg_owner_call_waiter *w = (struct mlg_owner_call_waiter *)refcon;
|
||||
|
||||
w->status = result;
|
||||
w->nargs = nargs < MLG_OWNER_CALL_WORDS ? nargs : MLG_OWNER_CALL_WORDS;
|
||||
for (uint32_t i = 0; i < w->nargs; ++i)
|
||||
w->args[i] = (uint64_t)(uintptr_t)args[i];
|
||||
w->done = true;
|
||||
}
|
||||
|
||||
/* Wait for @w's completion on @port. The driver ends every call itself (a
|
||||
* session call's own bounds, the session's close); each second without
|
||||
* one, a Ping notices a driver that went away (kIOReturnNotAttached). */
|
||||
static inline kern_return_t mlg_owner_call_wait(io_connect_t connection, IONotificationPortRef port,
|
||||
struct mlg_owner_call_waiter *w)
|
||||
{
|
||||
union {
|
||||
mach_msg_header_t header;
|
||||
uint8_t bytes[4096];
|
||||
} msg;
|
||||
|
||||
while (!w->done) {
|
||||
kern_return_t kr;
|
||||
|
||||
memset(&msg.header, 0, sizeof(msg.header));
|
||||
kr = mach_msg(&msg.header, MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0, sizeof(msg),
|
||||
IONotificationPortGetMachPort(port), 1000, MACH_PORT_NULL);
|
||||
if (kr == MACH_RCV_TIMED_OUT) {
|
||||
uint64_t pong = 0;
|
||||
uint32_t n = 1;
|
||||
|
||||
if (IOConnectCallScalarMethod(connection, MLG_OWNER_CALL_SELECTOR_PING, NULL, 0,
|
||||
&pong, &n) != kIOReturnSuccess)
|
||||
return kIOReturnNotAttached;
|
||||
continue;
|
||||
}
|
||||
if (kr != MACH_MSG_SUCCESS)
|
||||
return kIOReturnIPCError;
|
||||
IODispatchCalloutFromMessage(NULL, &msg.header, port);
|
||||
}
|
||||
return kIOReturnSuccess;
|
||||
}
|
||||
|
||||
/* @selector with @input and @input_struct, as IOConnectCallMethod would
|
||||
* call it: on return *@output_count scalars are in @output and
|
||||
* *@output_struct_size bytes in @output_struct (pass NULLs for none). The
|
||||
* result is the selector's IOReturn, or a transport failure (the call did
|
||||
* not start, or the driver went away). */
|
||||
static inline kern_return_t mlg_owner_call_on(IONotificationPortRef port, io_connect_t connection,
|
||||
uint32_t selector,
|
||||
const uint64_t *input, uint32_t input_count,
|
||||
const void *input_struct, size_t input_struct_size,
|
||||
uint64_t *output, uint32_t *output_count,
|
||||
void *output_struct, size_t *output_struct_size)
|
||||
{
|
||||
struct mlg_owner_call_waiter w;
|
||||
io_user_reference_t ref[kIOAsyncCalloutCount];
|
||||
uint64_t immediate[MLG_OWNER_CALL_SCALARS];
|
||||
uint32_t want = output_count ? *output_count : 0, n;
|
||||
size_t struct_cap = output_struct_size ? *output_struct_size : 0;
|
||||
uint8_t struct_probe = 0;
|
||||
kern_return_t kr;
|
||||
|
||||
if (want > MLG_OWNER_CALL_SCALARS)
|
||||
want = MLG_OWNER_CALL_SCALARS;
|
||||
memset(&w, 0, sizeof(w));
|
||||
memset(ref, 0, sizeof(ref));
|
||||
ref[kIOAsyncCalloutFuncIndex] = (io_user_reference_t)(uintptr_t)mlg_owner_call_completed;
|
||||
ref[kIOAsyncCalloutRefconIndex] = (io_user_reference_t)(uintptr_t)&w;
|
||||
/* The immediate reply carries only the token; the scalar and structure
|
||||
* capacities tell the driver what the caller asked of the selector. */
|
||||
n = want;
|
||||
{
|
||||
size_t probe_size = struct_cap;
|
||||
|
||||
kr = IOConnectCallAsyncMethod(connection, selector, IONotificationPortGetMachPort(port),
|
||||
ref, kIOAsyncCalloutCount, input, input_count,
|
||||
input_struct, input_struct_size, immediate, &n,
|
||||
struct_cap ? output_struct : (void *)&struct_probe,
|
||||
struct_cap ? &probe_size : NULL);
|
||||
}
|
||||
if (kr != kIOReturnSuccess)
|
||||
return kr;
|
||||
kr = mlg_owner_call_wait(connection, port, &w);
|
||||
if (kr != kIOReturnSuccess)
|
||||
return kr;
|
||||
if (w.status != kIOReturnSuccess)
|
||||
return w.status;
|
||||
if (w.nargs < MLG_OWNER_CALL_HEADER || w.args[2] > MLG_OWNER_CALL_SCALARS ||
|
||||
w.nargs < MLG_OWNER_CALL_HEADER + w.args[2])
|
||||
return kIOReturnIPCError;
|
||||
if ((kern_return_t)w.args[1] != kIOReturnSuccess)
|
||||
return (kern_return_t)w.args[1];
|
||||
n = (uint32_t)w.args[2];
|
||||
if (output_count) {
|
||||
if (n > *output_count)
|
||||
n = *output_count;
|
||||
for (uint32_t i = 0; i < n; ++i)
|
||||
output[i] = w.args[MLG_OWNER_CALL_HEADER + i];
|
||||
*output_count = n;
|
||||
}
|
||||
if (w.args[3]) {
|
||||
/* The structure output, kept by the driver until fetched. */
|
||||
uint64_t token = w.args[0];
|
||||
size_t size = struct_cap;
|
||||
uint32_t none = 0;
|
||||
|
||||
if (!output_struct || w.args[3] > struct_cap)
|
||||
return kIOReturnNoSpace;
|
||||
kr = IOConnectCallMethod(connection, MLG_OWNER_CALL_SELECTOR_RESULT, &token, 1, NULL, 0,
|
||||
NULL, &none, output_struct, &size);
|
||||
if (kr != kIOReturnSuccess)
|
||||
return kr;
|
||||
*output_struct_size = size;
|
||||
} else if (output_struct_size) {
|
||||
*output_struct_size = 0;
|
||||
}
|
||||
return kIOReturnSuccess;
|
||||
}
|
||||
|
||||
static inline kern_return_t mlg_owner_call(io_connect_t connection, uint32_t selector,
|
||||
const uint64_t *input, uint32_t input_count,
|
||||
const void *input_struct, size_t input_struct_size,
|
||||
uint64_t *output, uint32_t *output_count,
|
||||
void *output_struct, size_t *output_struct_size)
|
||||
{
|
||||
IONotificationPortRef port = IONotificationPortCreate(kIOMainPortDefault);
|
||||
kern_return_t kr;
|
||||
|
||||
if (!port)
|
||||
return kIOReturnNoMemory;
|
||||
kr = mlg_owner_call_on(port, connection, selector, input, input_count, input_struct,
|
||||
input_struct_size, output, output_count, output_struct,
|
||||
output_struct_size);
|
||||
IONotificationPortDestroy(port);
|
||||
return kr;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,38 @@
|
||||
/* A MacLinuxGPU selector called as the driver serves it
|
||||
* (dext/sources/session_state.h): synchronously when it never sleeps (or is
|
||||
* a bounded read), else as an async session call awaited on this thread
|
||||
* (owner_call.h). Either way the caller sees what IOConnectCallMethod
|
||||
* returns: the selector's IOReturn, its scalars and its structure output.
|
||||
* Header only, for the host app (bridging header), the HSA runtime and
|
||||
* libmlg_drm. */
|
||||
#ifndef MLG_SELECTOR_CALL_H
|
||||
#define MLG_SELECTOR_CALL_H
|
||||
|
||||
#include "owner_call.h"
|
||||
#include "../dext/sources/session_state.h"
|
||||
|
||||
static inline kern_return_t mlg_selector_call(io_connect_t connection, uint32_t selector,
|
||||
const uint64_t *input, uint32_t input_count,
|
||||
const void *input_struct, size_t input_struct_size,
|
||||
uint64_t *output, uint32_t *output_count,
|
||||
void *output_struct, size_t *output_struct_size)
|
||||
{
|
||||
#ifndef MLG_SELECTOR_CALL_TEST_SYNC
|
||||
if (mlg_call_is_synchronous(selector, input, input_count))
|
||||
#endif
|
||||
{
|
||||
/* (Tests that replace the IOKit calls define
|
||||
* MLG_SELECTOR_CALL_TEST_SYNC to see every selector here.) */
|
||||
if (!input_struct && !output_struct)
|
||||
return IOConnectCallScalarMethod(connection, selector, input, input_count,
|
||||
output, output_count);
|
||||
return IOConnectCallMethod(connection, selector, input, input_count, input_struct,
|
||||
input_struct_size, output, output_count, output_struct,
|
||||
output_struct_size);
|
||||
}
|
||||
return mlg_owner_call(connection, selector, input, input_count, input_struct,
|
||||
input_struct_size, output, output_count, output_struct,
|
||||
output_struct_size);
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -58,6 +58,8 @@ endif()
|
||||
add_library(hsa-runtime64 ${HSA_RUNTIME_LIBRARY_TYPE} ${HSA_RUNTIME_SOURCES} ${FW_SERVICER_SOURCES})
|
||||
target_compile_definitions(hsa-runtime64 PRIVATE HSA_EXPORT)
|
||||
target_include_directories(hsa-runtime64 PUBLIC include third_party/hsa/include)
|
||||
# host/selector_call.h (async session calls, with the driver's selector
|
||||
# rules from dext/sources/session_state.h) is shared with the host app.
|
||||
target_include_directories(hsa-runtime64 PRIVATE ${FW_SERVICER_DIR})
|
||||
target_compile_options(hsa-runtime64 PRIVATE -Wall -Wextra -Werror)
|
||||
target_link_libraries(hsa-runtime64 PRIVATE "-framework IOKit" "-framework CoreFoundation")
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "transport_fake.h"
|
||||
#include "../abi/amdgpu_vram_accounting.h"
|
||||
#include "fw_mailbox_service.h"
|
||||
#include "selector_call.h"
|
||||
#include <IOKit/IOKitLib.h>
|
||||
#include <CoreFoundation/CoreFoundation.h>
|
||||
#include <mach/mach.h>
|
||||
@@ -26,6 +27,15 @@
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
// A selector as the driver serves it (host/selector_call.h).
|
||||
static kern_return_t rpcMethod(io_connect_t port, uint32_t selector, const uint64_t *input,
|
||||
uint32_t inputs, const void *inputStruct, size_t inputStructSize,
|
||||
uint64_t *output, uint32_t *outputs, void *outputStruct,
|
||||
size_t *outputStructSize) {
|
||||
return mlg_selector_call(port, selector, input, inputs, inputStruct, inputStructSize,
|
||||
output, outputs, outputStruct, outputStructSize);
|
||||
}
|
||||
|
||||
namespace mac_hsa {
|
||||
namespace {
|
||||
class IOObject {
|
||||
@@ -180,8 +190,8 @@ public:
|
||||
uint64_t *output, uint32_t outputs, uint32_t *rawResult = nullptr,
|
||||
uint32_t *actualCount = nullptr) {
|
||||
uint32_t count = outputs;
|
||||
const auto result = IOConnectCallScalarMethod(port, selector, input, inputs,
|
||||
output, &count);
|
||||
const auto result = rpcMethod(port, selector, input, inputs, nullptr, 0,
|
||||
output, &count, nullptr, nullptr);
|
||||
if (rawResult) *rawResult = uint32_t(result);
|
||||
if (actualCount) *actualCount = count;
|
||||
if (selector == 60 && (result != KERN_SUCCESS || count != outputs))
|
||||
@@ -466,7 +476,7 @@ public:
|
||||
std::array<uint64_t,5> output{};
|
||||
uint32_t count=output.size();
|
||||
std::atomic_thread_fence(std::memory_order_seq_cst);
|
||||
const auto status=IOConnectCallMethod(ownerPort,55,nullptr,0,&request,sizeof(request),
|
||||
const auto status=rpcMethod(ownerPort,55,nullptr,0,&request,sizeof(request),
|
||||
output.data(),&count,nullptr,nullptr);
|
||||
// Linux-shim contract: kIOReturnNoResources means every queue slot is
|
||||
// held (possibly by another client) and the driver refused before
|
||||
@@ -498,7 +508,7 @@ public:
|
||||
std::array<uint64_t, 3> output{};
|
||||
uint32_t count = output.size();
|
||||
std::atomic_thread_fence(std::memory_order_seq_cst);
|
||||
const auto status = IOConnectCallMethod(ownerPort, 51, nullptr, 0, &request,
|
||||
const auto status = rpcMethod(ownerPort, 51, nullptr, 0, &request,
|
||||
request.version == 1 ? amdgpu::kComputeDispatchV1Bytes : sizeof(request),
|
||||
output.data(), &count, nullptr, nullptr);
|
||||
// Linux-shim contract (as for 55): kIOReturnNoResources means every
|
||||
@@ -893,7 +903,7 @@ private:
|
||||
const uint64_t input[] = {kCachedKernelLog, cursor};
|
||||
std::array<uint64_t, 16> output{};
|
||||
uint32_t count = output.size();
|
||||
if (IOConnectCallScalarMethod(ownerPort, 21, input, 2, output.data(), &count) != KERN_SUCCESS ||
|
||||
if (rpcMethod(ownerPort, 21, input, 2, nullptr, 0, output.data(), &count, nullptr, nullptr) != KERN_SUCCESS ||
|
||||
count < 3 || output[2] > (count - 3) * sizeof(uint64_t))
|
||||
return;
|
||||
if (chunk == 0) {
|
||||
@@ -1112,7 +1122,8 @@ private:
|
||||
// Close can finish teardown. No diagnostic claims PCI or retries init.
|
||||
if (ownerPort) dumpCachedShimDiagnostics(
|
||||
[this](const uint64_t *input, uint32_t inputs, uint64_t *output, uint32_t *outputs) {
|
||||
return uint32_t(IOConnectCallScalarMethod(ownerPort, 21, input, inputs, output, outputs));
|
||||
return uint32_t(rpcMethod(ownerPort, 21, input, inputs, nullptr, 0, output, outputs,
|
||||
nullptr, nullptr));
|
||||
}, emit);
|
||||
(void)std::fflush(stderr);
|
||||
const auto closed=IOServiceClose(ownerPort);
|
||||
@@ -1302,7 +1313,7 @@ private:
|
||||
std::atomic_thread_fence(std::memory_order_seq_cst);
|
||||
} else {
|
||||
size_t returned = span;
|
||||
const auto result = IOConnectCallMethod(ownerPort, 50, io.data(), 3, nullptr, 0,
|
||||
const auto result = rpcMethod(ownerPort, 50, io.data(), 3, nullptr, 0,
|
||||
nullptr, nullptr, chunk, &returned);
|
||||
if (result == kIOReturnOffline) return kDeviceSuspendedStatus;
|
||||
if (result != KERN_SUCCESS || returned != span) { state = State::Faulted; return HSA_STATUS_ERROR; }
|
||||
@@ -1313,7 +1324,7 @@ private:
|
||||
if (mapped) {
|
||||
std::atomic_thread_fence(std::memory_order_seq_cst);
|
||||
} else {
|
||||
const auto result = IOConnectCallMethod(ownerPort, 49, io.data(), 3, chunk, span,
|
||||
const auto result = rpcMethod(ownerPort, 49, io.data(), 3, chunk, span,
|
||||
nullptr, nullptr, nullptr, nullptr);
|
||||
if (result == kIOReturnOffline) return kDeviceSuspendedStatus;
|
||||
if (result != KERN_SUCCESS) { state = State::Faulted; return HSA_STATUS_ERROR; }
|
||||
|
||||
@@ -17,6 +17,8 @@
|
||||
#define IOConnectUnmapMemory64 test_unmap_memory
|
||||
#define mach_vm_map test_vm_map
|
||||
#define mach_vm_deallocate test_vm_deallocate
|
||||
/* The IOKit calls are replaced: every selector reaches them synchronously. */
|
||||
#define MLG_SELECTOR_CALL_TEST_SYNC
|
||||
#include "../src/transport_iokit.cpp"
|
||||
#include "fw/fw_mailbox.h"
|
||||
#include "../../linuxu/headers/rt/fw_mailbox.h"
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
#define mach_vm_deallocate test_vm_deallocate
|
||||
#define mlg_fw_service_start_connection test_fw_start
|
||||
#define mlg_fw_service_stop test_fw_stop
|
||||
/* The IOKit calls are replaced: every selector reaches them synchronously. */
|
||||
#define MLG_SELECTOR_CALL_TEST_SYNC
|
||||
#include "../src/transport_iokit.cpp"
|
||||
#include <cassert>
|
||||
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
#define IOConnectCallMethod test_method
|
||||
#define mlg_fw_service_start_connection test_fw_start
|
||||
#define mlg_fw_service_stop test_fw_stop
|
||||
/* The IOKit calls are replaced: every selector reaches them synchronously. */
|
||||
#define MLG_SELECTOR_CALL_TEST_SYNC
|
||||
#include "../src/transport_iokit.cpp"
|
||||
#include <cassert>
|
||||
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
#define IOConnectCallMethod test_method
|
||||
#define mlg_fw_service_start_connection test_fw_start
|
||||
#define mlg_fw_service_stop test_fw_stop
|
||||
/* The IOKit calls are replaced: every selector reaches them synchronously. */
|
||||
#define MLG_SELECTOR_CALL_TEST_SYNC
|
||||
#include "../src/transport_iokit.cpp"
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
#include <mach/mach.h>
|
||||
|
||||
#include "mlg_transport.h"
|
||||
#include "selector_call.h"
|
||||
#include <rt/lx_abi.h>
|
||||
|
||||
/* MacAMDGPU selector numbers the Linux-file client also takes (and
|
||||
@@ -105,7 +106,9 @@ static int scalar(uint32_t selector, const uint64_t *in, uint32_t nin, uint64_t
|
||||
|
||||
if (r)
|
||||
return r;
|
||||
return from_ioreturn(IOConnectCallScalarMethod(c, selector, in, nin, out, out ? &n : NULL));
|
||||
/* HostWindow and InitDevice can sleep: async session calls. */
|
||||
return from_ioreturn(mlg_selector_call(c, selector, in, nin, NULL, 0, out,
|
||||
out ? &n : NULL, NULL, NULL));
|
||||
}
|
||||
|
||||
static int scalar_call(void *ctx, uint32_t selector, const uint64_t *in, uint32_t nin,
|
||||
@@ -248,7 +251,9 @@ static int call_async(io_connect_t c, uint32_t selector, const uint64_t *in, uin
|
||||
return r;
|
||||
if (w->status != kIOReturnSuccess)
|
||||
return w->status == kIOReturnAborted ? -MLG_LX_EINTR : from_ioreturn(w->status);
|
||||
if (w->nargs < 3 || w->args[0] != *token)
|
||||
/* Token 0: a client's first call, which joins the session before its
|
||||
* operation gets a token of its own. */
|
||||
if (w->nargs < 3 || (*token && w->args[0] != *token))
|
||||
return -5; /* EIO */
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/* A call bounded in time for a caller that must not sleep long (the
|
||||
* driver's incoming-call thread): the work runs on a wait-pool thread
|
||||
* (rt/wait_pool.h), and the caller waits for it at most a bounded time.
|
||||
* Work that overruns keeps running; it then owns its argument and frees it
|
||||
* when it ends. Runtime: linuxu/src/amdgpu-rt/bounded.c. */
|
||||
#ifndef LINUXU_RT_BOUNDED_H
|
||||
#define LINUXU_RT_BOUNDED_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Run @fn(@arg) on a pool thread and wait up to @ms for it. 0: it ran to
|
||||
* the end, the caller owns @arg (and frees it). -ETIMEDOUT: it is still
|
||||
* running, and @release(@arg) runs on its thread when it ends. -EAGAIN or
|
||||
* -ENOMEM: it did not start; the caller owns @arg. Linux errno values. */
|
||||
int rt_bounded_run(void (*fn)(void *arg), void *arg, void (*release)(void *arg),
|
||||
unsigned int ms);
|
||||
/* Bounded calls whose work overran and still runs. */
|
||||
unsigned int rt_bounded_overrunning(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,101 @@
|
||||
/* Calls bounded in time (rt/bounded.h). */
|
||||
#include <pthread.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#include <linux/errno.h> /* Linux values, as every rt caller compares */
|
||||
#include <linux/ktime.h>
|
||||
|
||||
#include <rt/bounded.h>
|
||||
#include <rt/wait_pool.h>
|
||||
|
||||
/* DriverKit's libsystem_pthread exports only the relative timed wait. */
|
||||
extern int pthread_cond_timedwait_relative_np(pthread_cond_t *cond, pthread_mutex_t *mutex,
|
||||
const struct timespec *relative);
|
||||
|
||||
struct bounded {
|
||||
pthread_mutex_t lock;
|
||||
pthread_cond_t done_cv;
|
||||
void (*fn)(void *arg);
|
||||
void *arg;
|
||||
void (*release)(void *arg);
|
||||
bool done;
|
||||
bool abandoned; /* the caller stopped waiting: the thread frees */
|
||||
};
|
||||
|
||||
static unsigned int overrunning;
|
||||
|
||||
static void bounded_free(struct bounded *b)
|
||||
{
|
||||
pthread_cond_destroy(&b->done_cv);
|
||||
pthread_mutex_destroy(&b->lock);
|
||||
free(b);
|
||||
}
|
||||
|
||||
static void bounded_main(void *p)
|
||||
{
|
||||
struct bounded *b = p;
|
||||
bool abandoned;
|
||||
|
||||
b->fn(b->arg);
|
||||
pthread_mutex_lock(&b->lock);
|
||||
b->done = true;
|
||||
abandoned = b->abandoned;
|
||||
pthread_cond_signal(&b->done_cv);
|
||||
pthread_mutex_unlock(&b->lock);
|
||||
if (abandoned) {
|
||||
if (b->release)
|
||||
b->release(b->arg);
|
||||
__atomic_sub_fetch(&overrunning, 1, __ATOMIC_ACQ_REL);
|
||||
bounded_free(b);
|
||||
}
|
||||
}
|
||||
|
||||
int rt_bounded_run(void (*fn)(void *arg), void *arg, void (*release)(void *arg),
|
||||
unsigned int ms)
|
||||
{
|
||||
struct bounded *b;
|
||||
uint64_t deadline;
|
||||
int r;
|
||||
|
||||
if (!fn)
|
||||
return -EINVAL;
|
||||
b = calloc(1, sizeof(*b));
|
||||
if (!b)
|
||||
return -ENOMEM;
|
||||
pthread_mutex_init(&b->lock, NULL);
|
||||
pthread_cond_init(&b->done_cv, NULL);
|
||||
b->fn = fn;
|
||||
b->arg = arg;
|
||||
b->release = release;
|
||||
r = rt_wait_pool_run(bounded_main, b);
|
||||
if (r) {
|
||||
bounded_free(b);
|
||||
return r;
|
||||
}
|
||||
deadline = ktime_get_ns() + (uint64_t)ms * 1000000ull;
|
||||
pthread_mutex_lock(&b->lock);
|
||||
while (!b->done) {
|
||||
uint64_t now = ktime_get_ns();
|
||||
struct timespec rel;
|
||||
|
||||
if (now >= deadline) {
|
||||
b->abandoned = true;
|
||||
__atomic_add_fetch(&overrunning, 1, __ATOMIC_ACQ_REL);
|
||||
pthread_mutex_unlock(&b->lock);
|
||||
return -ETIMEDOUT;
|
||||
}
|
||||
rel.tv_sec = (time_t)((deadline - now) / 1000000000ull);
|
||||
rel.tv_nsec = (long)((deadline - now) % 1000000000ull);
|
||||
pthread_cond_timedwait_relative_np(&b->done_cv, &b->lock, &rel);
|
||||
}
|
||||
pthread_mutex_unlock(&b->lock);
|
||||
bounded_free(b);
|
||||
return 0;
|
||||
}
|
||||
|
||||
unsigned int rt_bounded_overrunning(void)
|
||||
{
|
||||
return __atomic_load_n(&overrunning, __ATOMIC_ACQUIRE);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/* Calls bounded in time (rt/bounded.h, linuxu/src/amdgpu-rt/bounded.c) on
|
||||
* the real wait pool: work that finishes in time hands its argument back;
|
||||
* work that overruns returns -ETIMEDOUT at the bound and frees its argument
|
||||
* itself when it ends. */
|
||||
#include <assert.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <rt/bounded.h>
|
||||
|
||||
#define LINUX_ETIMEDOUT 110
|
||||
|
||||
struct work {
|
||||
unsigned int sleep_ms;
|
||||
int ran;
|
||||
int *freed;
|
||||
};
|
||||
|
||||
static void work_main(void *arg)
|
||||
{
|
||||
struct work *w = arg;
|
||||
|
||||
usleep(w->sleep_ms * 1000);
|
||||
w->ran = 1;
|
||||
}
|
||||
|
||||
static void work_release(void *arg)
|
||||
{
|
||||
struct work *w = arg;
|
||||
|
||||
__atomic_store_n(w->freed, 1, __ATOMIC_RELEASE);
|
||||
free(w);
|
||||
}
|
||||
|
||||
static double ms_now(void)
|
||||
{
|
||||
struct timespec ts;
|
||||
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return ts.tv_sec * 1e3 + ts.tv_nsec / 1e6;
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
int freed = 0;
|
||||
struct work *w = calloc(1, sizeof(*w));
|
||||
double start;
|
||||
|
||||
/* In time: the caller owns the argument, release is not called. */
|
||||
w->sleep_ms = 5;
|
||||
w->freed = &freed;
|
||||
assert(rt_bounded_run(work_main, w, work_release, 500) == 0);
|
||||
assert(w->ran && !freed && rt_bounded_overrunning() == 0);
|
||||
free(w);
|
||||
|
||||
/* Overrun: -ETIMEDOUT at the bound; the work frees its argument. */
|
||||
w = calloc(1, sizeof(*w));
|
||||
w->sleep_ms = 300;
|
||||
w->freed = &freed;
|
||||
start = ms_now();
|
||||
assert(rt_bounded_run(work_main, w, work_release, 50) == -LINUX_ETIMEDOUT);
|
||||
assert(ms_now() - start >= 45 && ms_now() - start < 250);
|
||||
assert(rt_bounded_overrunning() == 1 && !__atomic_load_n(&freed, __ATOMIC_ACQUIRE));
|
||||
for (int i = 0; i < 200 && !__atomic_load_n(&freed, __ATOMIC_ACQUIRE); ++i)
|
||||
usleep(5000);
|
||||
assert(__atomic_load_n(&freed, __ATOMIC_ACQUIRE) && rt_bounded_overrunning() == 0);
|
||||
printf("PASS bounded calls: in-time work returns its argument, overrunning work times out "
|
||||
"at the bound and frees its argument when it ends\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
/* The dext's session calls with DriverKit mocked: the production owner_call
|
||||
* machinery (extracted from dext/sources/MacLinuxGPUXcode.mm by
|
||||
* scripts/test-owner-call.sh) against session selectors that sleep, as an
|
||||
* eviction or a probe waiting on a hung GPU ring did on build 241 and
|
||||
* froze every client of the driver. The delivery thread (the test's main
|
||||
* thread) must never wait: a call is queued for the owner's queue (a
|
||||
* thread of its own here) and answered through its completion; calls that
|
||||
* never sleep are answered at once; a synchronous call of one that can is
|
||||
* refused; a bounded read returns within its bound while its read hangs;
|
||||
* results come once through OWNER_RESULT; BO memory is found without the
|
||||
* session's state. */
|
||||
#include "session_state.h"
|
||||
#include "dext_compute.h"
|
||||
#include <Block.h>
|
||||
#include <atomic>
|
||||
#include <cassert>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
using kern_return_t = int;
|
||||
enum : int {
|
||||
kIOReturnSuccess = 0, kIOReturnBadArgument = 1, kIOReturnBusy = 2, kIOReturnNotReady = 3,
|
||||
kIOReturnNoResources = 4, kIOReturnNoMemory = 5, kIOReturnNotFound = 6, kIOReturnNoSpace = 7,
|
||||
kIOReturnTimeout = 8, kIOReturnNotPermitted = 9, kIOReturnError = 10, kIOReturnUnsupported = 11,
|
||||
};
|
||||
static std::atomic<int> eventsLogged;
|
||||
#define MACLINUXGPU_LOG(...) (std::printf("log: " __VA_ARGS__), std::printf("\n"))
|
||||
#define MACLINUXGPU_EVENT(...) (++eventsLogged, std::printf("event: " __VA_ARGS__), std::printf("\n"))
|
||||
|
||||
// ---- DriverKit mocks ----
|
||||
struct OSObjectMock {
|
||||
std::atomic<int> refs{1};
|
||||
virtual ~OSObjectMock() = default;
|
||||
void retain() { ++refs; }
|
||||
void release() { if (--refs == 0) delete this; }
|
||||
};
|
||||
struct OSData : OSObjectMock {
|
||||
std::vector<uint8_t> bytes;
|
||||
static OSData *withBytes(const void *p, size_t n) {
|
||||
auto *d = new OSData;
|
||||
d->bytes.assign(static_cast<const uint8_t *>(p), static_cast<const uint8_t *>(p) + n);
|
||||
return d;
|
||||
}
|
||||
size_t getLength() const { return bytes.size(); }
|
||||
const void *getBytesNoCopy() const { return bytes.data(); }
|
||||
};
|
||||
struct IOMemoryDescriptor : OSObjectMock {
|
||||
uint64_t length = 0;
|
||||
kern_return_t GetLength(uint64_t *out) { *out = length; return kIOReturnSuccess; }
|
||||
};
|
||||
struct OSAction : OSObjectMock {};
|
||||
using IOUserClientAsyncArgumentsArray = uint64_t[16];
|
||||
static constexpr uint64_t kIOUserClientMethodArgumentsCurrentVersion = 2;
|
||||
struct IOUserClientMethodArguments {
|
||||
uint64_t version;
|
||||
uint64_t selector;
|
||||
OSAction *completion;
|
||||
const uint64_t *scalarInput;
|
||||
uint32_t scalarInputCount;
|
||||
OSData *structureInput;
|
||||
IOMemoryDescriptor *structureInputDescriptor;
|
||||
uint64_t *scalarOutput;
|
||||
uint32_t scalarOutputCount;
|
||||
OSData *structureOutput;
|
||||
IOMemoryDescriptor *structureOutputDescriptor;
|
||||
uint64_t structureOutputMaximumSize;
|
||||
};
|
||||
struct IOLock { std::mutex m; };
|
||||
static IOLock *IOLockAlloc() { return new IOLock; }
|
||||
static void IOLockFree(IOLock *l) { delete l; }
|
||||
static void IOLockLock(IOLock *l) { l->m.lock(); }
|
||||
static void IOLockUnlock(IOLock *l) { l->m.unlock(); }
|
||||
static void *IOMallocZero(size_t n) { return calloc(1, n); }
|
||||
static void IOFree(void *p, size_t) { free(p); }
|
||||
|
||||
// The owner's queue: a thread of its own that runs what is queued, in order.
|
||||
struct IODispatchQueue {
|
||||
using Block = void (^)(void);
|
||||
std::mutex lock;
|
||||
std::condition_variable kick;
|
||||
std::deque<Block> pending;
|
||||
bool stop = false;
|
||||
std::thread thread;
|
||||
std::thread::id id;
|
||||
void start() {
|
||||
thread = std::thread([this] {
|
||||
id = std::this_thread::get_id();
|
||||
std::unique_lock guard(lock);
|
||||
for (;;) {
|
||||
kick.wait(guard, [this] { return stop || !pending.empty(); });
|
||||
if (pending.empty()) return;
|
||||
Block block = pending.front();
|
||||
pending.pop_front();
|
||||
guard.unlock();
|
||||
block();
|
||||
Block_release(block);
|
||||
guard.lock();
|
||||
}
|
||||
});
|
||||
}
|
||||
void DispatchAsync(Block block) {
|
||||
std::lock_guard guard(lock);
|
||||
pending.push_back(Block_copy(block));
|
||||
kick.notify_one();
|
||||
}
|
||||
void finish() {
|
||||
{ std::lock_guard guard(lock); stop = true; kick.notify_one(); }
|
||||
thread.join();
|
||||
}
|
||||
};
|
||||
|
||||
struct OwnerResult;
|
||||
struct ClientMemory;
|
||||
struct MacLinuxGPUUserClient_IVars {
|
||||
uint64_t clientID;
|
||||
IODispatchQueue *ownerQueue;
|
||||
IOLock *ownerLock;
|
||||
OwnerResult *ownerResults;
|
||||
uint64_t ownerToken;
|
||||
ClientMemory *memories;
|
||||
bool syncRefusalLogged;
|
||||
};
|
||||
struct Completion { uint64_t args[16]; uint32_t count; std::thread::id thread; };
|
||||
static std::mutex completionsLock;
|
||||
static std::condition_variable completionsChanged;
|
||||
static std::vector<Completion> completions;
|
||||
static std::thread::id deliveryThread;
|
||||
|
||||
// The session selectors as they run on the owner's queue: 16 (BOAlloc)
|
||||
// answers three scalars, 50 (BORead) a structure, 9 (InitDevice) sleeps
|
||||
// until the GPU answers, 87 (EVENT_WAIT) does not start.
|
||||
static std::mutex gpuLock;
|
||||
static std::condition_variable gpuAnswer;
|
||||
static bool gpuAnswers;
|
||||
static std::atomic<int> sessionCallsOnDelivery, sessionCallsRun;
|
||||
struct MacLinuxGPUUserClient : OSObjectMock {
|
||||
MacLinuxGPUUserClient_IVars *ivars;
|
||||
void AsyncCompletion(OSAction *, kern_return_t, const IOUserClientAsyncArgumentsArray data, uint32_t count) {
|
||||
Completion c{};
|
||||
memcpy(c.args, data, count * sizeof(uint64_t));
|
||||
c.count = count;
|
||||
c.thread = std::this_thread::get_id();
|
||||
std::lock_guard lock(completionsLock);
|
||||
completions.push_back(c);
|
||||
completionsChanged.notify_all();
|
||||
}
|
||||
kern_return_t ExternalMethod(uint64_t selector, IOUserClientMethodArguments *a, const void *,
|
||||
void *, void *reference);
|
||||
};
|
||||
|
||||
// ---- the state the direct calls read ----
|
||||
static bool s_sessionClosing;
|
||||
static bool s_probeAttempted = true, s_modulesRunning = true;
|
||||
static int s_probeResult;
|
||||
static int dext_pci_transport_fault() { return 0; }
|
||||
static uint64_t dext_pci_transport_fault_offset() { return 0; }
|
||||
static std::atomic<int> powerWaits;
|
||||
static kern_return_t power_wait(MacLinuxGPUUserClient *, OSAction *, uint64_t) { ++powerWaits; return kIOReturnSuccess; }
|
||||
static void power_snapshot(uint64_t *out) { memset(out, 0, MLG_POWER_STATE_WORDS * 8); out[0] = MLG_POWER_STATE_VERSION; }
|
||||
static void session_state(uint64_t *out) { memset(out, 0, MLG_SESSION_STATE_WORDS * 8); out[0] = MLG_SESSION_STATE_VERSION; }
|
||||
static size_t klog_read(uint64_t *cursor, char *out, size_t capacity, uint64_t *end)
|
||||
{
|
||||
static const char text[] = "probe completed";
|
||||
size_t n = sizeof(text) - 1 < capacity ? sizeof(text) - 1 : capacity;
|
||||
memcpy(out, text, n);
|
||||
*cursor += n;
|
||||
*end = n;
|
||||
return n;
|
||||
}
|
||||
int dext_compute_runtime_build_cached(uint64_t *out) { out[0] = 1; out[1] = 1; out[2] = 243; out[3] = 243; return 0; }
|
||||
|
||||
// SysfsRead hangs until the GPU answers (an SMU message that never returns).
|
||||
static std::mutex smuLock;
|
||||
static std::condition_variable smuAnswer;
|
||||
static bool smuAnswers;
|
||||
static std::atomic<int> readsRun;
|
||||
static kern_return_t observer_sysfs_read(IOUserClientMethodArguments *a)
|
||||
{
|
||||
++readsRun;
|
||||
std::unique_lock lock(smuLock);
|
||||
smuAnswer.wait(lock, [] { return smuAnswers; });
|
||||
a->scalarOutput[0] = 0; a->scalarOutput[1] = 3; a->scalarOutput[2] = 3;
|
||||
a->scalarOutputCount = MLG_SYSFS_READ_WORDS;
|
||||
a->structureOutput = OSData::withBytes("42\n", 3);
|
||||
return kIOReturnSuccess;
|
||||
}
|
||||
static kern_return_t observer_drm_info(IOUserClientMethodArguments *a) { return observer_sysfs_read(a); }
|
||||
|
||||
// BO memory for the mapping table.
|
||||
static IOMemoryDescriptor *lastDescriptor;
|
||||
int dext_compute_bo_memory(uint32_t type, void **cpu, uint64_t *size)
|
||||
{
|
||||
if (type != 0x10001) return -ENOENT_L;
|
||||
*cpu = (void *)0x1000; *size = 4096;
|
||||
return 0;
|
||||
}
|
||||
static IOMemoryDescriptor *copy_bo_ranges_descriptor(uint32_t, uint64_t) { return nullptr; }
|
||||
static void *dext_dma_copy_descriptor(void *) { lastDescriptor = new IOMemoryDescriptor; return lastDescriptor; }
|
||||
|
||||
// rt/bounded.h, as linuxu/src/amdgpu-rt/bounded.c behaves (its own test
|
||||
// covers it): run on a thread, wait up to @ms.
|
||||
struct BoundedRun {
|
||||
std::mutex lock;
|
||||
std::condition_variable done;
|
||||
bool finished = false, abandoned = false;
|
||||
};
|
||||
static std::vector<std::thread> boundedThreads;
|
||||
extern "C" int rt_bounded_run(void (*fn)(void *), void *arg, void (*release)(void *), unsigned int ms)
|
||||
{
|
||||
auto *run = new BoundedRun;
|
||||
boundedThreads.emplace_back([=] {
|
||||
fn(arg);
|
||||
bool abandoned;
|
||||
{ std::lock_guard guard(run->lock); run->finished = true; abandoned = run->abandoned; run->done.notify_all(); }
|
||||
if (abandoned) { release(arg); delete run; }
|
||||
});
|
||||
std::unique_lock guard(run->lock);
|
||||
if (!run->done.wait_for(guard, std::chrono::milliseconds(ms), [&] { return run->finished; })) {
|
||||
run->abandoned = true;
|
||||
return -110;
|
||||
}
|
||||
guard.unlock();
|
||||
delete run;
|
||||
return 0;
|
||||
}
|
||||
|
||||
#include "owner_call_production.inc"
|
||||
|
||||
kern_return_t MacLinuxGPUUserClient::ExternalMethod(uint64_t selector, IOUserClientMethodArguments *a,
|
||||
const void *, void *, void *reference)
|
||||
{
|
||||
assert(reference == &kOwnerJob);
|
||||
++sessionCallsRun;
|
||||
if (std::this_thread::get_id() == deliveryThread) ++sessionCallsOnDelivery;
|
||||
switch (selector) {
|
||||
case 16:
|
||||
assert(a->scalarInputCount == 4 && a->scalarInput[0] == 4096 && a->scalarOutputCount >= 3);
|
||||
a->scalarOutput[0] = 0x10001; a->scalarOutput[1] = 0x400000; a->scalarOutput[2] = 0;
|
||||
a->scalarOutputCount = 3;
|
||||
return kIOReturnSuccess;
|
||||
case 50: {
|
||||
uint8_t bytes[64];
|
||||
for (unsigned i = 0; i < sizeof(bytes); ++i) bytes[i] = (uint8_t)i;
|
||||
assert(a->structureOutputMaximumSize >= sizeof(bytes));
|
||||
a->structureOutput = OSData::withBytes(bytes, sizeof(bytes));
|
||||
a->scalarOutputCount = 0;
|
||||
return kIOReturnSuccess;
|
||||
}
|
||||
case 9: {
|
||||
std::unique_lock lock(gpuLock);
|
||||
gpuAnswer.wait(lock, [] { return gpuAnswers; });
|
||||
a->scalarOutputCount = 0;
|
||||
return kIOReturnSuccess;
|
||||
}
|
||||
case MLG_SELECTOR_EVENT_WAIT:
|
||||
assert(a->completion);
|
||||
a->scalarOutput[0] = (uint64_t)(int64_t)-11; // every waiting thread busy
|
||||
a->scalarOutputCount = 1;
|
||||
return kIOReturnSuccess;
|
||||
default:
|
||||
return kIOReturnUnsupported;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ---- the checks ----
|
||||
static Completion waitCompletion(size_t index)
|
||||
{
|
||||
std::unique_lock lock(completionsLock);
|
||||
assert(completionsChanged.wait_for(lock, std::chrono::seconds(5), [&] { return completions.size() > index; }));
|
||||
return completions[index];
|
||||
}
|
||||
|
||||
static double msSince(std::chrono::steady_clock::time_point start)
|
||||
{
|
||||
return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
deliveryThread = std::this_thread::get_id();
|
||||
IODispatchQueue owner;
|
||||
owner.start();
|
||||
MacLinuxGPUUserClient client;
|
||||
MacLinuxGPUUserClient_IVars ivars{};
|
||||
ivars.clientID = 1;
|
||||
ivars.ownerQueue = &owner;
|
||||
ivars.ownerLock = IOLockAlloc();
|
||||
client.ivars = &ivars;
|
||||
|
||||
// A session call that sleeps (a probe waiting on a hung GPU): the
|
||||
// delivery thread queues it and returns at once.
|
||||
OSAction *action = new OSAction;
|
||||
uint64_t out[16] = {};
|
||||
IOUserClientMethodArguments a{};
|
||||
a.completion = action;
|
||||
a.scalarOutput = out;
|
||||
a.scalarOutputCount = 1;
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
assert(owner_call(&client, 9, &a) == kIOReturnSuccess);
|
||||
assert(msSince(start) < 50 && a.scalarOutputCount == 1 && out[0] == 1); // its token
|
||||
|
||||
// Everything else on the delivery thread still answers while it sleeps:
|
||||
// the cached queries at once, more session calls queued behind it.
|
||||
uint64_t ping[1] = {};
|
||||
IOUserClientMethodArguments p{};
|
||||
p.scalarOutput = ping; p.scalarOutputCount = 1;
|
||||
assert(mlg_call_runs_on_delivery(MLG_SELECTOR_PING, nullptr, 0));
|
||||
assert(direct_call(&client, MLG_SELECTOR_PING, &p) == kIOReturnSuccess && ping[0] == 0xA117AB1Eu);
|
||||
uint64_t build[4] = {};
|
||||
IOUserClientMethodArguments b{};
|
||||
b.scalarOutput = build; b.scalarOutputCount = 4;
|
||||
assert(direct_call(&client, MLG_SELECTOR_RUNTIME_BUILD, &b) == kIOReturnSuccess && build[2] == 243);
|
||||
const uint64_t klogTag[2] = {DEXT_COMPUTE_QUERY_KERNEL_LOG, 0};
|
||||
uint64_t klog[16] = {};
|
||||
IOUserClientMethodArguments k{};
|
||||
k.scalarInput = klogTag; k.scalarInputCount = 2; k.scalarOutput = klog; k.scalarOutputCount = 16;
|
||||
assert(mlg_call_runs_on_delivery(MLG_SELECTOR_QUERY_INFO, klogTag, 2));
|
||||
assert(direct_call(&client, MLG_SELECTOR_QUERY_INFO, &k) == kIOReturnSuccess && klog[2] == 15);
|
||||
const uint64_t waitIn[2] = {MLG_POWER_OP_WAIT, 3};
|
||||
IOUserClientMethodArguments w{};
|
||||
w.scalarInput = waitIn; w.scalarInputCount = 2; w.completion = action;
|
||||
assert(direct_call(&client, MLG_SELECTOR_POWER, &w) == kIOReturnSuccess && powerWaits == 1);
|
||||
|
||||
const uint64_t allocIn[4] = {4096, 2, 4096, 0};
|
||||
uint64_t allocOut[3] = {};
|
||||
IOUserClientMethodArguments alloc{};
|
||||
alloc.completion = action; alloc.scalarInput = allocIn; alloc.scalarInputCount = 4;
|
||||
alloc.scalarOutput = allocOut; alloc.scalarOutputCount = 3;
|
||||
start = std::chrono::steady_clock::now();
|
||||
assert(owner_call(&client, 16, &alloc) == kIOReturnSuccess && allocOut[0] == 2);
|
||||
const uint64_t readIn[3] = {0x10001, 0, 64};
|
||||
IOUserClientMethodArguments read{};
|
||||
read.completion = action; read.scalarInput = readIn; read.scalarInputCount = 3;
|
||||
read.structureOutputMaximumSize = 64;
|
||||
assert(owner_call(&client, 50, &read) == kIOReturnSuccess);
|
||||
const uint64_t waitArgs[4] = {77, 1, 0, 100};
|
||||
uint32_t ids[1] = {5};
|
||||
OSData *idData = OSData::withBytes(ids, sizeof(ids));
|
||||
uint64_t waitOut[1] = {99};
|
||||
IOUserClientMethodArguments ev{};
|
||||
ev.completion = action; ev.scalarInput = waitArgs; ev.scalarInputCount = 4;
|
||||
ev.structureInput = idData; ev.scalarOutput = waitOut; ev.scalarOutputCount = 1;
|
||||
assert(owner_call(&client, MLG_SELECTOR_EVENT_WAIT, &ev) == kIOReturnSuccess && waitOut[0] == 0);
|
||||
idData->release();
|
||||
assert(msSince(start) < 50);
|
||||
{
|
||||
std::lock_guard lock(completionsLock);
|
||||
assert(completions.empty()); // all behind the sleeping probe, in order
|
||||
}
|
||||
|
||||
// A synchronous call of a session selector: refused, logged once.
|
||||
assert(refuse_sync(&client, 16) == kIOReturnNotPermitted);
|
||||
assert(refuse_sync(&client, 17) == kIOReturnNotPermitted && eventsLogged == 1);
|
||||
|
||||
// The GPU answers: the calls complete in order, on the owner's queue.
|
||||
{ std::lock_guard lock(gpuLock); gpuAnswers = true; gpuAnswer.notify_all(); }
|
||||
Completion init = waitCompletion(0), allocated = waitCompletion(1), readDone = waitCompletion(2),
|
||||
eventDone = waitCompletion(3);
|
||||
assert(init.thread == owner.id && init.args[0] == 1 && init.args[1] == kIOReturnSuccess &&
|
||||
init.args[2] == 0 && init.args[3] == 0 && init.count == MLG_OWNER_ASYNC_HEADER);
|
||||
assert(allocated.args[0] == 2 && allocated.args[1] == kIOReturnSuccess && allocated.args[2] == 3 &&
|
||||
allocated.args[4] == 0x10001 && allocated.args[5] == 0x400000 &&
|
||||
allocated.count == MLG_OWNER_ASYNC_HEADER + 3);
|
||||
assert(readDone.args[0] == 3 && readDone.args[3] == 64);
|
||||
// EVENT_WAIT that did not start: its own layout, with the reason.
|
||||
assert(eventDone.count == MLG_EVENT_WAIT_WORDS && eventDone.args[0] == 77 &&
|
||||
(int64_t)eventDone.args[1] == -11 && eventDone.args[2] == 2);
|
||||
assert(sessionCallsRun == 4 && sessionCallsOnDelivery == 0);
|
||||
|
||||
// The structure output, once, with room; short room keeps it.
|
||||
const uint64_t token[1] = {3};
|
||||
IOUserClientMethodArguments fetch{};
|
||||
fetch.scalarInput = token; fetch.scalarInputCount = 1; fetch.structureOutputMaximumSize = 8;
|
||||
assert(owner_result(&client, &fetch) == kIOReturnNoSpace);
|
||||
fetch.structureOutputMaximumSize = 64;
|
||||
assert(owner_result(&client, &fetch) == kIOReturnSuccess && fetch.structureOutput &&
|
||||
fetch.structureOutput->getLength() == 64 &&
|
||||
static_cast<const uint8_t *>(fetch.structureOutput->getBytesNoCopy())[63] == 63);
|
||||
fetch.structureOutput->release();
|
||||
fetch.structureOutput = nullptr;
|
||||
assert(owner_result(&client, &fetch) == kIOReturnNotFound);
|
||||
|
||||
// BO memory: made on the owner's queue at BOMap, found on the delivery
|
||||
// thread without the session's state, gone at BOFree.
|
||||
client_memory_stash(&client, 0x77, 0x10001);
|
||||
IOMemoryDescriptor *found = client_memory_find(&client, 0x10001);
|
||||
assert(found && found == lastDescriptor && found->refs == 2);
|
||||
found->release();
|
||||
assert(!client_memory_find(&client, 0x10002));
|
||||
client_memory_drop(&client, 0x77);
|
||||
assert(!client_memory_find(&client, 0x10001));
|
||||
|
||||
// A bounded read whose SMU message never returns: answered with a
|
||||
// timeout within its bound; the next is busy until it ends.
|
||||
const uint64_t sysfsIn[2] = {MLG_SYSFS_OP_READ, 0};
|
||||
OSData *path = OSData::withBytes("gpu_busy_percent", 16);
|
||||
uint64_t sysfsOut[3] = {};
|
||||
IOUserClientMethodArguments sysfs{};
|
||||
sysfs.scalarInput = sysfsIn; sysfs.scalarInputCount = 2; sysfs.structureInput = path;
|
||||
sysfs.scalarOutput = sysfsOut; sysfs.scalarOutputCount = 3; sysfs.structureOutputMaximumSize = 4096;
|
||||
start = std::chrono::steady_clock::now();
|
||||
assert(bounded_read(MLG_SELECTOR_SYSFS_READ, &sysfs) == kIOReturnTimeout);
|
||||
const double waited = msSince(start);
|
||||
assert(waited >= MLG_BOUNDED_READ_MS - 5 && waited < MLG_BOUNDED_READ_MS + 200);
|
||||
assert(bounded_read(MLG_SELECTOR_SYSFS_READ, &sysfs) == kIOReturnBusy && readsRun == 1);
|
||||
{ std::lock_guard lock(smuLock); smuAnswers = true; smuAnswer.notify_all(); }
|
||||
for (auto &thread : boundedThreads) thread.join();
|
||||
boundedThreads.clear();
|
||||
// Answered now: within the bound, with its output.
|
||||
sysfs.scalarOutputCount = 3;
|
||||
assert(bounded_read(MLG_SELECTOR_SYSFS_READ, &sysfs) == kIOReturnSuccess &&
|
||||
sysfs.structureOutput && sysfs.structureOutput->getLength() == 3 && sysfsOut[1] == 3);
|
||||
sysfs.structureOutput->release();
|
||||
for (auto &thread : boundedThreads) thread.join();
|
||||
path->release();
|
||||
|
||||
owner_results_free(&client);
|
||||
owner.finish();
|
||||
action->release();
|
||||
std::printf("PASS session calls: a session call that sleeps never holds the delivery thread; "
|
||||
"cached queries and the power wait answer at once, later calls queue in order, a "
|
||||
"synchronous call of one is refused, completions carry scalars and EVENT_WAIT's own "
|
||||
"layout, RESULT once, BO memory found without the session, a hung bounded read "
|
||||
"times out within %u ms and makes the next busy\n", MLG_BOUNDED_READ_MS);
|
||||
return 0;
|
||||
}
|
||||
@@ -82,7 +82,11 @@ struct IOPCIDevice : IOService {};
|
||||
struct IODispatchQueue {
|
||||
using Block = void (^)(void);
|
||||
std::deque<Block> pending;
|
||||
// The owner's queue as a client's Stop sees it: nothing else is queued
|
||||
// there in these scenarios, so its block runs at once.
|
||||
bool runsAtOnce = false;
|
||||
void DispatchAsync(Block block) {
|
||||
if (runsAtOnce) { block(); return; }
|
||||
assert(irqDrained);
|
||||
events.push_back("enqueue_finish");
|
||||
pending.push_back(Block_copy(block));
|
||||
@@ -100,6 +104,8 @@ struct IOUserClientMethodArguments {
|
||||
uint32_t scalarOutputCount = 2;
|
||||
};
|
||||
struct MacLinuxGPUUserClient_IVars;
|
||||
struct IOLock;
|
||||
static IODispatchQueue s_ownerQueueAtOnce{{}, true};
|
||||
struct MacLinuxGPU : IOService {
|
||||
void FinishSession();
|
||||
void FinishStop(IOService *provider);
|
||||
@@ -197,6 +203,7 @@ static void power_before_removal() { ++powerRemovalHooks; }
|
||||
static unsigned displayUnpublishes;
|
||||
static void displays_unpublish(MacLinuxGPU *) { ++displayUnpublishes; }
|
||||
|
||||
static void session_client_stop(MacLinuxGPUUserClient *client, IOService *provider);
|
||||
#include "session_shutdown_production.inc"
|
||||
|
||||
// An observer read in flight when the session closes: the close waits, and
|
||||
@@ -403,12 +410,14 @@ struct Fixture {
|
||||
clients[i].ivars = &ivars[i];
|
||||
ivars[i].ownerDriver = &driver; ivars[i].stopProvider = &driver;
|
||||
ivars[i].clientID = i + 1; ivars[i].stopping = true;
|
||||
ivars[i].ownerQueue = &s_ownerQueueAtOnce;
|
||||
ivars[i].nextStopping = i ? nullptr : &clients[1];
|
||||
driver.retain(); driver.retain(); clients[i].retain();
|
||||
}
|
||||
s_stoppingClients = &clients[0];
|
||||
observer.ivars = &ivars[2];
|
||||
ivars[2].ownerDriver = &driver; ivars[2].clientID = 3;
|
||||
ivars[2].ownerQueue = &s_ownerQueueAtOnce;
|
||||
retainedDriver = driver.references; retainedProvider = provider.references;
|
||||
}
|
||||
void deliverIRQDrain() {
|
||||
@@ -583,9 +592,48 @@ static void checkObserverPolicy() {
|
||||
assert(!mlg_sysfs_path_copy(path, tooLong.c_str(), tooLong.size(), false));
|
||||
for (uint64_t selector = 1; selector < 128; ++selector) {
|
||||
if (selector == MLG_SELECTOR_QUERY_INFO || selector == MLG_SELECTOR_RUNTIME_BUILD ||
|
||||
selector == MLG_SELECTOR_RELEASE_QUARANTINE) continue;
|
||||
selector == MLG_SELECTOR_RELEASE_QUARANTINE || selector == MLG_SELECTOR_OWNER_RESULT)
|
||||
continue;
|
||||
assert(!mlg_observer_selector_allowed(selector, probe, 1));
|
||||
}
|
||||
// OWNER_RESULT names the call's token, never 0.
|
||||
const uint64_t token[] = {5}, noToken[] = {0};
|
||||
assert(mlg_observer_selector_allowed(MLG_SELECTOR_OWNER_RESULT, token, 1));
|
||||
assert(!mlg_observer_selector_allowed(MLG_SELECTOR_OWNER_RESULT, noToken, 1));
|
||||
|
||||
// What runs on the delivery thread (session_state.h): cached state,
|
||||
// the power query and wait, the result fetch; nothing else.
|
||||
const uint64_t klog[] = {MLG_QUERY_KERNEL_LOG, 0}, qSession[] = {MLG_QUERY_SESSION_STATE},
|
||||
qPower[] = {MLG_QUERY_POWER_STATE}, probeStatus[] = {MLG_QUERY_PROBE_STATUS},
|
||||
computeTag[] = {10}, powerQuery[] = {MLG_POWER_OP_QUERY},
|
||||
powerWait[] = {MLG_POWER_OP_WAIT, 1}, powerPrepare[] = {MLG_POWER_OP_PREPARE};
|
||||
assert(mlg_call_runs_on_delivery(MLG_SELECTOR_PING, nullptr, 0));
|
||||
assert(mlg_call_runs_on_delivery(MLG_SELECTOR_RUNTIME_BUILD, nullptr, 0));
|
||||
assert(mlg_call_runs_on_delivery(MLG_SELECTOR_QUERY_INFO, klog, 2));
|
||||
assert(mlg_call_runs_on_delivery(MLG_SELECTOR_QUERY_INFO, qSession, 1));
|
||||
assert(mlg_call_runs_on_delivery(MLG_SELECTOR_QUERY_INFO, qPower, 1));
|
||||
assert(mlg_call_runs_on_delivery(MLG_SELECTOR_QUERY_INFO, probeStatus, 1));
|
||||
assert(!mlg_call_runs_on_delivery(MLG_SELECTOR_QUERY_INFO, computeTag, 1));
|
||||
assert(!mlg_call_runs_on_delivery(MLG_SELECTOR_QUERY_INFO, klog, 1));
|
||||
assert(mlg_call_runs_on_delivery(MLG_SELECTOR_POWER, powerQuery, 1));
|
||||
assert(mlg_call_runs_on_delivery(MLG_SELECTOR_POWER, powerWait, 2));
|
||||
assert(!mlg_call_runs_on_delivery(MLG_SELECTOR_POWER, powerPrepare, 1));
|
||||
assert(mlg_call_runs_on_delivery(MLG_SELECTOR_OWNER_RESULT, token, 1));
|
||||
assert(!mlg_call_runs_on_delivery(MLG_SELECTOR_OWNER_RESULT, noToken, 1));
|
||||
for (uint64_t selector : {1ull, 2ull, 6ull, 9ull, 16ull, 17ull, 36ull, 49ull, 50ull, 51ull, 54ull,
|
||||
55ull, 56ull, 57ull, 58ull, 59ull, 61ull, 82ull, 85ull, 86ull, 87ull})
|
||||
assert(!mlg_call_runs_on_delivery(selector, probe, 1) &&
|
||||
!mlg_call_is_synchronous(selector, probe, 1));
|
||||
// The bounded reads and the display's PRESENT and RESULT stay
|
||||
// synchronous; its other ops are async.
|
||||
const uint64_t present[] = {MLG_DISPLAY_OP_PRESENT, 0, MLG_DISPLAY_CONFIRM},
|
||||
result[] = {MLG_DISPLAY_OP_RESULT, 1, MLG_DISPLAY_CONFIRM},
|
||||
output[] = {MLG_DISPLAY_OP_OUTPUT, 1, MLG_DISPLAY_CONFIRM};
|
||||
assert(mlg_call_is_synchronous(MLG_SELECTOR_SYSFS_READ, probe, 1));
|
||||
assert(mlg_call_is_synchronous(MLG_SELECTOR_DRM_INFO, probe, 1));
|
||||
assert(mlg_call_is_synchronous(MLG_SELECTOR_DISPLAY, present, 3));
|
||||
assert(mlg_call_is_synchronous(MLG_SELECTOR_DISPLAY, result, 3));
|
||||
assert(!mlg_call_is_synchronous(MLG_SELECTOR_DISPLAY, output, 3));
|
||||
}
|
||||
|
||||
// Successful probe and compute start, then the only client exits without
|
||||
@@ -602,8 +650,8 @@ static void clientExitReopen(bool queueExhausted) {
|
||||
s_irqReady = s_irqDeliver = s_pciOpen = true; s_token = 7;
|
||||
bar0Aliases = 1;
|
||||
client.ivars = &clientIvars;
|
||||
clientIvars = {&driver, nullptr, nullptr, s_sessionGeneration, 1, false, false, false, nullptr, false,
|
||||
false, nullptr, nullptr, 0, nullptr};
|
||||
clientIvars = {&driver, nullptr, nullptr, s_sessionGeneration, 1, false, false, false, &s_ownerQueueAtOnce, nullptr,
|
||||
nullptr, 0, nullptr, false, false, nullptr, nullptr, 0, nullptr};
|
||||
driver.retain(); s_participants = 1;
|
||||
// A second queue found every slot held. The runtime refused it before
|
||||
// any allocation (or the driver did, with -ENOSPC before reserving), so
|
||||
@@ -638,8 +686,8 @@ static void clientExitReopen(bool queueExhausted) {
|
||||
expectLog("session closed after upstream removal, interrupt drain and endpoint isolation");
|
||||
// The dext is reusable: a new client opens a new PCI session.
|
||||
next.ivars = &nextIvars;
|
||||
nextIvars = {&driver, nullptr, nullptr, 0, 2, false, false, false, nullptr, false,
|
||||
false, nullptr, nullptr, 0, nullptr};
|
||||
nextIvars = {&driver, nullptr, nullptr, 0, 2, false, false, false, &s_ownerQueueAtOnce, nullptr,
|
||||
nullptr, 0, nullptr, false, false, nullptr, nullptr, 0, nullptr};
|
||||
pciOpenExpected = true;
|
||||
assert(ensure_open(&next) == kIOReturnSuccess);
|
||||
assert(s_pciOpen && s_participants == 1 && pciOpens == 1 && saw("pci_open"));
|
||||
@@ -667,8 +715,8 @@ static void surpriseRemoval(bool quarantined, bool held = false) {
|
||||
s_irqReady = s_irqDeliver = s_pciOpen = true; s_token = 7;
|
||||
bar0Aliases = 1;
|
||||
client.ivars = &clientIvars;
|
||||
clientIvars = {&driver, nullptr, nullptr, s_sessionGeneration, 1, false, false, false, nullptr, false,
|
||||
false, nullptr, nullptr, 0, nullptr};
|
||||
clientIvars = {&driver, nullptr, nullptr, s_sessionGeneration, 1, false, false, false, &s_ownerQueueAtOnce, nullptr,
|
||||
nullptr, 0, nullptr, false, false, nullptr, nullptr, 0, nullptr};
|
||||
driver.retain(); s_participants = 1;
|
||||
// The KFD close cannot confirm anything once MES is gone.
|
||||
computeError = -11006;
|
||||
@@ -757,8 +805,8 @@ static void surpriseRemoval(bool quarantined, bool held = false) {
|
||||
// The replugged device: a new client opens a new session.
|
||||
devicePresent = true;
|
||||
next.ivars = &nextIvars;
|
||||
nextIvars = {&driver, nullptr, nullptr, 0, 2, false, false, false, nullptr, false,
|
||||
false, nullptr, nullptr, 0, nullptr};
|
||||
nextIvars = {&driver, nullptr, nullptr, 0, 2, false, false, false, &s_ownerQueueAtOnce, nullptr,
|
||||
nullptr, 0, nullptr, false, false, nullptr, nullptr, 0, nullptr};
|
||||
pciOpenExpected = true;
|
||||
assert(ensure_open(&next) == kIOReturnSuccess);
|
||||
assert(s_pciOpen && s_participants == 1 && saw("pci_open"));
|
||||
@@ -798,6 +846,7 @@ struct UpgradeRig {
|
||||
// An idle observer (a monitor, the installer): never a participant.
|
||||
observer.ivars = &observerIvars;
|
||||
observerIvars.ownerDriver = &driver; observerIvars.clientID = 3; observerIvars.observer = true;
|
||||
observerIvars.ownerQueue = &s_ownerQueueAtOnce;
|
||||
driver.retain();
|
||||
if (session) {
|
||||
s_rtDevice = &device; s_modulesRunning = true; s_probeAttempted = true;
|
||||
@@ -805,6 +854,7 @@ struct UpgradeRig {
|
||||
bar0Aliases = 1;
|
||||
client.ivars = &clientIvars;
|
||||
clientIvars.ownerDriver = &driver; clientIvars.clientID = 1;
|
||||
clientIvars.ownerQueue = &s_ownerQueueAtOnce;
|
||||
clientIvars.sessionGeneration = s_sessionGeneration;
|
||||
driver.retain(); s_participants = 1;
|
||||
} else {
|
||||
@@ -813,6 +863,7 @@ struct UpgradeRig {
|
||||
}
|
||||
next.ivars = &nextIvars;
|
||||
nextIvars.ownerDriver = &driver; nextIvars.clientID = 2;
|
||||
nextIvars.ownerQueue = &s_ownerQueueAtOnce;
|
||||
}
|
||||
void deliverIRQDrain() {
|
||||
assert(irqCompletion);
|
||||
|
||||
@@ -34,6 +34,9 @@ import struct
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from mlg_owner_call import OwnerCall # noqa: E402
|
||||
|
||||
SESSION_CLIENT, OBSERVER_CLIENT = 0, 1
|
||||
RUNTIME_BUILD, INIT_DEVICE = 43, 9
|
||||
SYSFS_READ = 80 # MLG_SELECTOR_SYSFS_READ
|
||||
@@ -287,8 +290,8 @@ def connect(init=False):
|
||||
count = c.c_uint(3)
|
||||
result = io.IOConnectCallScalarMethod(session, RUNTIME_BUILD, None, 0, build, c.byref(count))
|
||||
if not result:
|
||||
count = c.c_uint(0)
|
||||
result = io.IOConnectCallScalarMethod(session, INIT_DEVICE, None, 0, None, c.byref(count))
|
||||
# InitDevice can sleep: an async session call (session_state.h).
|
||||
result, _, _ = OwnerCall(session.value)(INIT_DEVICE, [])
|
||||
if result:
|
||||
io.IOServiceClose(session)
|
||||
io.IOServiceClose(port)
|
||||
|
||||
+14
-20
@@ -31,6 +31,9 @@ import os
|
||||
import struct
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from mlg_owner_call import OwnerCall # noqa: E402
|
||||
|
||||
SESSION_CLIENT, OBSERVER_CLIENT = 0, 1
|
||||
RUNTIME_BUILD, INIT_DEVICE, HOST_WINDOW = 43, 9, 54
|
||||
DRM_SELFTEST = 82 # dext/sources/session_state.h MLG_SELECTOR_DRM_SELFTEST
|
||||
@@ -160,6 +163,9 @@ def connect(init=False):
|
||||
io.IOObjectRelease(service)
|
||||
if result:
|
||||
raise DriverError(f"observer open failed: {result & 0xffffffff:#x}")
|
||||
# Every selector that can sleep is an async session call (session_state.h).
|
||||
owner = OwnerCall(session.value) if init else None
|
||||
observer = OwnerCall(port.value)
|
||||
if init:
|
||||
build = (c.c_uint64 * 3)()
|
||||
count = c.c_uint(3)
|
||||
@@ -169,11 +175,8 @@ def connect(init=False):
|
||||
# Place the host window before the probe, as the HSA runtime does:
|
||||
# query the GART aperture size, reserve that much address space
|
||||
# aligned to its size, and hand the base to the driver.
|
||||
window = (c.c_uint64 * 3)()
|
||||
count = c.c_uint(3)
|
||||
query = (c.c_uint64 * 1)(0)
|
||||
result = io.IOConnectCallScalarMethod(session, HOST_WINDOW, query, 1, window, c.byref(count))
|
||||
size = window[1]
|
||||
result, window, _ = owner(HOST_WINDOW, [0], outputs=3)
|
||||
size = window[1] if len(window) > 1 else 0
|
||||
if not result and size and not size & (size - 1):
|
||||
system.mmap.argtypes = [c.c_void_p, c.c_size_t, c.c_int, c.c_int, c.c_int, c.c_long]
|
||||
system.mmap.restype = c.c_void_p
|
||||
@@ -182,12 +185,9 @@ def connect(init=False):
|
||||
if raw and raw != c.c_void_p(-1).value:
|
||||
reservation = (raw, size * 2)
|
||||
base = (raw + size - 1) & ~(size - 1)
|
||||
count = c.c_uint(3)
|
||||
request = (c.c_uint64 * 1)(base)
|
||||
result = io.IOConnectCallScalarMethod(session, HOST_WINDOW, request, 1, window, c.byref(count))
|
||||
result, window, _ = owner(HOST_WINDOW, [base], outputs=3)
|
||||
if not result:
|
||||
count = c.c_uint(0)
|
||||
result = io.IOConnectCallScalarMethod(session, INIT_DEVICE, None, 0, None, c.byref(count))
|
||||
result, _, _ = owner(INIT_DEVICE, [])
|
||||
if reservation:
|
||||
system.munmap(reservation[0], reservation[1])
|
||||
if result:
|
||||
@@ -197,23 +197,17 @@ def connect(init=False):
|
||||
"(scripts/read-driver-log.py shows why)")
|
||||
|
||||
def call(selector, scalars, capacity):
|
||||
inputs = (c.c_uint64 * len(scalars))(*scalars)
|
||||
outputs = (c.c_uint64 * 2)()
|
||||
count = c.c_uint(2)
|
||||
out = c.create_string_buffer(capacity)
|
||||
size = c.c_size_t(capacity)
|
||||
result = io.IOConnectCallMethod(port, selector, inputs, len(scalars), None, 0,
|
||||
outputs, c.byref(count), out, c.byref(size))
|
||||
code = result & 0xffffffff
|
||||
# The self-test runs for seconds: an async session call.
|
||||
code, values, blob = observer(selector, scalars, outputs=2, capacity=capacity)
|
||||
if code == NOT_READY:
|
||||
raise DriverError("not ready: the upstream driver is not running in an open session")
|
||||
if code == NOT_PERMITTED:
|
||||
raise DriverError("not permitted: this driver predates the CS self-test")
|
||||
if code == BUSY:
|
||||
raise DriverError("busy: another self-test is running")
|
||||
if result:
|
||||
if code:
|
||||
raise DriverError(f"self-test call failed: {code:#x}")
|
||||
return list(outputs[:count.value]), out.raw[:size.value]
|
||||
return values, blob
|
||||
|
||||
def close():
|
||||
result = io.IOServiceClose(port)
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
"""A MacLinuxGPU selector called the way the driver runs every call that can
|
||||
sleep (dext/sources/session_state.h, "Calls that never sleep, and every other
|
||||
call"): IOConnectCallAsyncMethod, the completion awaited on this thread, and
|
||||
the structure output fetched with OWNER_RESULT. The Python twin of
|
||||
host/owner_call.h, for the scripts.
|
||||
|
||||
call = OwnerCall(connection)
|
||||
result, scalars, data = call(selector, scalars, data=b"", outputs=0, capacity=0)
|
||||
|
||||
result is the selector's IOReturn (0 on success)."""
|
||||
import ctypes as c
|
||||
|
||||
OWNER_RESULT = 88 # session_state.h MLG_SELECTOR_OWNER_RESULT
|
||||
OWNER_HEADER = 4 # MLG_OWNER_ASYNC_HEADER
|
||||
OWNER_SCALARS = 12 # MLG_OWNER_ASYNC_SCALARS
|
||||
PING = 0
|
||||
CALLOUT_FUNC, CALLOUT_REFCON, CALLOUT_COUNT = 1, 2, 3 # IOKit's kIOAsyncCallout* indices
|
||||
MACH_RCV_MSG, MACH_RCV_TIMEOUT, MACH_RCV_TIMED_OUT = 0x2, 0x100, 0x10004003
|
||||
NOT_ATTACHED, IPC_ERROR = 0xe00002d8, 0xe00002c3
|
||||
|
||||
_CALLBACK = c.CFUNCTYPE(None, c.c_void_p, c.c_int, c.POINTER(c.c_void_p), c.c_uint32)
|
||||
|
||||
|
||||
class OwnerCall:
|
||||
def __init__(self, connection):
|
||||
self.connection = connection
|
||||
io = self.io = c.CDLL("/System/Library/Frameworks/IOKit.framework/IOKit")
|
||||
system = self.system = c.CDLL("/usr/lib/libSystem.B.dylib")
|
||||
io.IONotificationPortCreate.argtypes = [c.c_uint]
|
||||
io.IONotificationPortCreate.restype = c.c_void_p
|
||||
io.IONotificationPortDestroy.argtypes = [c.c_void_p]
|
||||
io.IONotificationPortGetMachPort.argtypes = [c.c_void_p]
|
||||
io.IONotificationPortGetMachPort.restype = c.c_uint
|
||||
io.IODispatchCalloutFromMessage.argtypes = [c.c_void_p, c.c_void_p, c.c_void_p]
|
||||
io.IOConnectCallAsyncMethod.argtypes = [
|
||||
c.c_uint, c.c_uint, c.c_uint, c.POINTER(c.c_uint64), c.c_uint,
|
||||
c.POINTER(c.c_uint64), c.c_uint, c.c_void_p, c.c_size_t,
|
||||
c.POINTER(c.c_uint64), c.POINTER(c.c_uint), c.c_void_p, c.POINTER(c.c_size_t)]
|
||||
io.IOConnectCallAsyncMethod.restype = c.c_int
|
||||
io.IOConnectCallMethod.argtypes = [
|
||||
c.c_uint, c.c_uint, c.POINTER(c.c_uint64), c.c_uint, c.c_void_p, c.c_size_t,
|
||||
c.POINTER(c.c_uint64), c.POINTER(c.c_uint), c.c_void_p, c.POINTER(c.c_size_t)]
|
||||
io.IOConnectCallMethod.restype = c.c_int
|
||||
system.mach_msg.argtypes = [c.c_void_p, c.c_int, c.c_uint, c.c_uint, c.c_uint,
|
||||
c.c_uint, c.c_uint]
|
||||
system.mach_msg.restype = c.c_int
|
||||
|
||||
def __call__(self, selector, scalars, data=b"", outputs=0, capacity=0):
|
||||
io, system = self.io, self.system
|
||||
port = io.IONotificationPortCreate(0)
|
||||
if not port:
|
||||
raise MemoryError("no notification port")
|
||||
try:
|
||||
done = {}
|
||||
|
||||
def completed(refcon, status, args, count):
|
||||
done["status"] = status
|
||||
done["args"] = [(args[i] or 0) for i in range(min(count, OWNER_HEADER + OWNER_SCALARS))]
|
||||
|
||||
callback = _CALLBACK(completed)
|
||||
reference = (c.c_uint64 * 8)()
|
||||
reference[CALLOUT_FUNC] = c.cast(callback, c.c_void_p).value
|
||||
inputs = (c.c_uint64 * max(1, len(scalars)))(*scalars)
|
||||
immediate = (c.c_uint64 * OWNER_SCALARS)()
|
||||
count = c.c_uint(min(outputs, OWNER_SCALARS))
|
||||
room = c.c_size_t(capacity)
|
||||
probe = c.create_string_buffer(max(1, capacity))
|
||||
source = c.create_string_buffer(data, len(data)) if data else None
|
||||
result = io.IOConnectCallAsyncMethod(
|
||||
self.connection, selector, io.IONotificationPortGetMachPort(port), reference,
|
||||
CALLOUT_COUNT, inputs, len(scalars), source, len(data), immediate,
|
||||
c.byref(count), probe if capacity else None, c.byref(room) if capacity else None)
|
||||
if result:
|
||||
return result & 0xffffffff, [], b""
|
||||
message = c.create_string_buffer(4096)
|
||||
while "status" not in done:
|
||||
received = system.mach_msg(message, MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0, 4096,
|
||||
io.IONotificationPortGetMachPort(port), 1000, 0)
|
||||
if received & 0xffffffff == MACH_RCV_TIMED_OUT:
|
||||
pong = (c.c_uint64 * 1)()
|
||||
n = c.c_uint(1)
|
||||
if io.IOConnectCallMethod(self.connection, PING, None, 0, None, 0, pong,
|
||||
c.byref(n), None, None):
|
||||
return NOT_ATTACHED, [], b""
|
||||
continue
|
||||
if received:
|
||||
return IPC_ERROR, [], b""
|
||||
io.IODispatchCalloutFromMessage(None, message, port)
|
||||
args = done["args"]
|
||||
if done["status"]:
|
||||
return done["status"] & 0xffffffff, [], b""
|
||||
if len(args) < OWNER_HEADER:
|
||||
return IPC_ERROR, [], b""
|
||||
code = args[1] & 0xffffffff
|
||||
values = args[OWNER_HEADER:OWNER_HEADER + args[2]][:outputs]
|
||||
blob = b""
|
||||
if code == 0 and args[3]:
|
||||
token = (c.c_uint64 * 1)(args[0])
|
||||
out = c.create_string_buffer(max(1, capacity))
|
||||
size = c.c_size_t(capacity)
|
||||
none = c.c_uint(0)
|
||||
fetched = io.IOConnectCallMethod(self.connection, OWNER_RESULT, token, 1, None, 0,
|
||||
None, c.byref(none), out, c.byref(size))
|
||||
if fetched:
|
||||
return fetched & 0xffffffff, [], b""
|
||||
blob = out.raw[:size.value]
|
||||
return code, values, blob
|
||||
finally:
|
||||
io.IONotificationPortDestroy(port)
|
||||
@@ -8,7 +8,7 @@ make -s lib >/dev/null
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
client=(-std=c11 -Wall -Wextra -Werror -Wno-missing-field-initializers -g -O1
|
||||
-DMLG_LX_CLIENT_BUILD -Ilibmlg_drm/include -Ilibmlg_drm/compat -Ilibmlg_drm/src
|
||||
-DMLG_LX_CLIENT_BUILD -Ihost -Ilibmlg_drm/include -Ilibmlg_drm/compat -Ilibmlg_drm/src
|
||||
-Ithird_party/linux/include/uapi -idirafter linuxu/headers)
|
||||
client_srcs=(libmlg_drm/src/mlg_drm.c libmlg_drm/src/mlg_transport_iokit.c libmlg_drm/src/mlg_init.c
|
||||
linuxu/src/amdgpu-rt/lx_frame.c linuxu/src/amdgpu-rt/lx_describe.c)
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env bash
|
||||
# The dext's session calls (dext/sources/MacLinuxGPUXcode.mm owner_call):
|
||||
# a call that can sleep never runs on the delivery thread, with the
|
||||
# production functions extracted and DriverKit mocked
|
||||
# (linuxu/tests/test_owner_call.cpp). Also checks that host/owner_call.h
|
||||
# carries session_state.h's numbers.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
test_dir=$(mktemp -d)
|
||||
trap 'rm -rf "$test_dir"' EXIT
|
||||
python3 - "$test_dir" <<'PY'
|
||||
import pathlib, re, sys
|
||||
source = pathlib.Path("dext/sources/MacLinuxGPUXcode.mm").read_text()
|
||||
start = "// ----------------------------------------------------------------\n// Session calls off the delivery thread"
|
||||
end = "// A client's last display op result (MacLinuxGPUUserClient_IVars::displayResults)."
|
||||
if source.count(start) != 1 or source.count(end) != 1:
|
||||
raise SystemExit("owner call extraction markers changed")
|
||||
text = source[source.index(start):source.index(end)]
|
||||
if len(text.splitlines()) > 480:
|
||||
raise SystemExit("owner call extraction exceeded its bounded section")
|
||||
pathlib.Path(sys.argv[1], "owner_call_production.inc").write_text(text)
|
||||
state = pathlib.Path("dext/sources/session_state.h").read_text()
|
||||
client = pathlib.Path("host/owner_call.h").read_text()
|
||||
def number(text, name):
|
||||
found = re.search(r"#define\s+" + name + r"\s+\(?(\w+)", text)
|
||||
if not found:
|
||||
raise SystemExit(f"{name} not found")
|
||||
return found.group(1).rstrip("u")
|
||||
for driver, mirror in (("MLG_SELECTOR_OWNER_RESULT", "MLG_OWNER_CALL_SELECTOR_RESULT"),
|
||||
("MLG_OWNER_ASYNC_HEADER", "MLG_OWNER_CALL_HEADER"),
|
||||
("MLG_OWNER_ASYNC_SCALARS", "MLG_OWNER_CALL_SCALARS")):
|
||||
if number(state, driver) != number(client, mirror):
|
||||
raise SystemExit(f"host/owner_call.h {mirror} differs from session_state.h {driver}")
|
||||
python = pathlib.Path("scripts/mlg_owner_call.py").read_text()
|
||||
for driver, mirror in (("MLG_SELECTOR_OWNER_RESULT", "OWNER_RESULT"),
|
||||
("MLG_OWNER_ASYNC_HEADER", "OWNER_HEADER"),
|
||||
("MLG_OWNER_ASYNC_SCALARS", "OWNER_SCALARS")):
|
||||
found = re.search(r"^" + mirror + r"\s*=\s*(\d+)", python, re.M)
|
||||
if not found or found.group(1) != number(state, driver):
|
||||
raise SystemExit(f"scripts/mlg_owner_call.py {mirror} differs from session_state.h {driver}")
|
||||
PY
|
||||
clang++ -std=c++20 -fblocks -Wall -Wextra -Werror -Wno-unused-function -Wno-unused-parameter \
|
||||
-g -O1 -fsanitize=address,undefined -fno-sanitize-recover=all \
|
||||
-I"$test_dir" -Idext/sources -idirafter linuxu/headers \
|
||||
linuxu/tests/test_owner_call.cpp -lpthread -o "$test_dir/test_owner_call"
|
||||
"$test_dir/test_owner_call"
|
||||
@@ -15,12 +15,12 @@ def section(start, end, limit):
|
||||
if len(text.splitlines()) > limit:
|
||||
raise SystemExit("shutdown fixture extraction exceeded its bounded section")
|
||||
return text
|
||||
state = section("static IODispatchQueue *s_bringupQueue", "class ComputeClientScope", 110)
|
||||
state = section("static IODispatchQueue *s_bringupQueue", "class ComputeClientScope", 130)
|
||||
close = section("static void session_irq_drained(void *context)", "static kern_return_t ensure_open", 520)
|
||||
opening = section("static kern_return_t ensure_open(MacLinuxGPUUserClient *client)", "static kern_return_t prepare_interrupts", 50)
|
||||
driver_stop = section("kern_return_t\nIMPL(MacLinuxGPU, Stop)", "void\nMacLinuxGPU::FinishSession()", 50)
|
||||
finish = section("void\nMacLinuxGPU::FinishSession()", "void\nMacLinuxGPU::FinishStop(IOService *provider)", 100)
|
||||
client_stop = section("kern_return_t\nIMPL(MacLinuxGPUUserClient, Stop)", "void\nMacLinuxGPUUserClient::FinishStop(IOService *provider)", 50)
|
||||
client_stop = section("kern_return_t\nIMPL(MacLinuxGPUUserClient, Stop)", "void\nMacLinuxGPUUserClient::FinishStop(IOService *provider)", 70)
|
||||
shutdown = section(" case kMacAMDGPUMethodShutdownGPU: {", " case kMacAMDGPUMethodGetReBARInfo: {", 40)
|
||||
probe_failure = section(" if (s_probeResult != 0) {", ' MACLINUXGPU_EVENT("upstream AMDGPU PCI probe completed");', 20)
|
||||
wrapper = """
|
||||
|
||||
Reference in new issue
Block a user