diff --git a/Makefile b/Makefile index cf06c6b..e483108 100644 --- a/Makefile +++ b/Makefile @@ -1216,6 +1216,12 @@ test-surface-import: test: test-surface-import .PHONY: test-surface-import +test-display-pipeline: + bash scripts/test-display-pipeline.sh + +test: test-display-pipeline +.PHONY: test-display-pipeline + # The display agent's model (host/DisplayAgent.swift): decoding, the # virtual-display plan for a monitor, and the changes a probe makes. test-display-agent: diff --git a/dext/sources/MacLinuxGPUXcode.mm b/dext/sources/MacLinuxGPUXcode.mm index 1f75dcc..e05a9ca 100644 --- a/dext/sources/MacLinuxGPUXcode.mm +++ b/dext/sources/MacLinuxGPUXcode.mm @@ -176,6 +176,8 @@ static_assert(MLG_DISPLAY_PATTERNS == RT_DISPLAY_PATTERNS && sizeof(struct rt_surface_verify_result) <= MLG_DISPLAY_REPORT_MAX && sizeof(struct rt_display_present_stats) <= MLG_DISPLAY_REPORT_MAX && sizeof(struct mlg_display_rect) == sizeof(struct rt_surface_rect) && + sizeof(struct rt_display_present_stats) == 120 && + offsetof(struct mlg_display_present, rect) == 16 && sizeof(struct mlg_display_present) + MLG_DISPLAY_PRESENT_RECTS_MAX * sizeof(struct mlg_display_rect) <= 4096, "display ABI"); static_assert(DEXT_COMPUTE_QUERY_SESSION_STATE == MLG_QUERY_SESSION_STATE && @@ -2607,16 +2609,23 @@ static kern_return_t display_frames(uint64_t clientID, IOUserClientMethodArgumen if (request->count > MLG_DISPLAY_PRESENT_RECTS_MAX || data->getLength() != sizeof(*request) + request->count * sizeof(struct mlg_display_rect)) return kIOReturnBadArgument; - struct rt_surface *surface = rt_surface_get(clientID, (uint32_t)in[1]); struct rt_display_present_stats stats{}; int r = -kLinuxENOENT; - if (surface && __atomic_load_n(&s_displayOwner, __ATOMIC_ACQUIRE) == clientID) - r = rt_display_present(pdev, surface, - reinterpret_cast(request->rect), - request->count, &stats); + if (__atomic_load_n(&s_displayOwner, __ATOMIC_ACQUIRE) != clientID) { + /* Only the client that lit the output presents or reads it. */ + } else if (!request->count) { + r = rt_display_stats(pdev, &stats); + } else { + /* The hold goes to the output's worker, which releases it once + * the frame is copied (or replaced by a newer one). */ + struct rt_surface *surface = rt_surface_get_hold(clientID, (uint32_t)in[1]); + if (surface) + r = rt_display_present(pdev, surface, + reinterpret_cast(request->rect), + request->count, request->capture_ns, &stats); + } if (r && r != -kLinuxENOENT) - MACLINUXGPU_LOG("display: PRESENT failed %d (copy %d, flip %d)", r, stats.copy_status, - stats.flip_status); + MACLINUXGPU_LOG("display: PRESENT failed %d (worker error %d)", r, stats.error); a->structureOutput = OSData::withBytes(&stats, sizeof(stats)); if (!a->structureOutput) return kIOReturnNoMemory; out[0] = (uint64_t)(int64_t)r; diff --git a/dext/sources/session_state.h b/dext/sources/session_state.h index 738e5d6..b548db9 100644 --- a/dext/sources/session_state.h +++ b/dext/sources/session_state.h @@ -202,11 +202,14 @@ static inline bool mlg_release_blocker_permanent(uint32_t blocker) * struct out: struct rt_surface_verify_result * RELEASE [1] handle * OUTPUT [1] refresh in mHz; struct in: struct mlg_display_output; the - * connector at that mode with two framebuffers (rt_display_output) + * connector at that mode with three framebuffers and a worker + * that copies and flips (rt_display_output) * struct out: struct rt_display_report - * PRESENT [1] handle; struct in: struct mlg_display_present; the dirty - * rectangles copied and flipped (rt_display_present) - * struct out: struct rt_display_present_stats */ + * PRESENT [1] handle; struct in: struct mlg_display_present; queues the + * frame (its dirty rectangles and capture time) for the worker + * and returns without waiting for the copy or the flip + * (rt_display_present); no rectangle only reads the statistics + * struct out: struct rt_display_present_stats (version 2) */ #define MLG_DISPLAY_OP_IMPORT 5u #define MLG_DISPLAY_OP_VERIFY 6u #define MLG_DISPLAY_OP_RELEASE 7u @@ -226,6 +229,7 @@ struct mlg_display_rect { struct mlg_display_present { uint32_t count; uint32_t reserved; + uint64_t capture_ns; /* when the frame was captured, mach_absolute_time in ns */ struct mlg_display_rect rect[]; /* count, at most MLG_DISPLAY_PRESENT_RECTS_MAX */ }; #define MLG_DISPLAY_PATTERN_BARS 0u diff --git a/linuxu/headers/rt/display.h b/linuxu/headers/rt/display.h index ced2f90..d77d0d4 100644 --- a/linuxu/headers/rt/display.h +++ b/linuxu/headers/rt/display.h @@ -152,35 +152,47 @@ int rt_display_modes(struct pci_dev *pdev, const char *connector, struct rt_disp * rt_display_stop() restore it. While it runs, report->pattern is * RT_DISPLAY_PATTERN_OUTPUT. * - * rt_display_present() copies the dirty rectangles of an imported surface - * (rt/surface.h, the output's size) into the framebuffer not on screen, - * with SDMA, together with the rectangles of the frame before (that - * buffer is one frame behind), then flips to it with an atomic commit - * (drm_client_modeset_commit: a plane update that completes on vblank). - * No rectangle means nothing changed: nothing is copied or flipped. */ + * rt_display_present() hands a frame to the output's worker and returns: + * it takes over one hold on @surface (rt_surface_get_hold; released even + * on failure), the dirty rectangles and the capture time (CLOCK_UPTIME_RAW + * ns, the clock ktime_get_ns() reads, for the latency statistics), and + * replaces a frame the worker has not taken yet (their damage adds up). + * The worker copies into one of three framebuffers with SDMA and flips to + * it with a nonblocking commit (display.c describes the pipeline). No + * rectangle means nothing changed: only the statistics come back. A + * worker error is returned by every later call. */ #define RT_DISPLAY_PATTERN_OUTPUT 0xffu -#define RT_DISPLAY_PRESENT_RECTS_MAX 64u struct rt_surface; struct rt_surface_rect; struct rt_display_present_stats { - uint32_t version; /* 1 */ - uint32_t rects; /* rectangles copied */ - uint32_t jobs; /* SDMA jobs */ - uint32_t full; /* the whole frame was copied */ - uint64_t bytes; - uint64_t copy_ns, flip_ns; - int32_t copy_status, flip_status; - uint64_t frames; /* frames presented since the output started */ + uint32_t version; /* 2 */ + uint32_t engines; /* SDMA engines the output copies with */ + uint64_t frames_received; /* presents with damage */ + uint64_t frames_flipped; /* frames that reached the screen */ + uint64_t frames_replaced; /* replaced in the mailbox by a newer frame */ + uint64_t copy_jobs; + uint64_t bytes; /* copied */ + uint64_t copy_submit_ns; /* the worker's CPU time building and submitting copies */ + uint64_t copy_gpu_ns; /* submit to the copies' fences, summed over flipped frames */ + uint64_t latency_ns; /* capture to flip (vblank timestamp), summed */ + uint64_t latency_max_ns; + uint64_t last_bytes, last_copy_gpu_ns, last_latency_ns; /* the last flipped frame */ + int32_t error; /* the worker's first error, 0 */ + uint32_t full_frames; /* frames copied whole */ + uint64_t reserved; }; int rt_display_output(struct pci_dev *pdev, const char *connector, uint32_t width, uint32_t height, uint32_t refresh_mhz, struct rt_display_report *report); int rt_display_present(struct pci_dev *pdev, struct rt_surface *surface, - const struct rt_surface_rect *rects, uint32_t count, + const struct rt_surface_rect *rects, uint32_t count, uint64_t capture_ns, struct rt_display_present_stats *stats); +/* The output's statistics; -ENOENT without an output. */ +int rt_display_stats(struct pci_dev *pdev, struct rt_display_present_stats *stats); + /* Whether a pattern is showing (cached; takes no lock). */ int rt_display_showing(void); diff --git a/linuxu/headers/rt/surface.h b/linuxu/headers/rt/surface.h index 7cd6a65..e57af61 100644 --- a/linuxu/headers/rt/surface.h +++ b/linuxu/headers/rt/surface.h @@ -62,8 +62,9 @@ int rt_surface_import(struct pci_dev *pdev, const struct rt_surface_segment *seg uint32_t pitch, const struct rt_surface_provider *provider, struct rt_surface **out); -/* Drop the surface: unpin, drop the BO. The provider's release follows - * once the BO is destroyed (possibly later, on a TTM worker). */ +/* Drop a reference; the last one unpins and drops the BO. The provider's + * release follows once the BO is destroyed (possibly later, on a TTM + * worker). */ void rt_surface_release(struct rt_surface *surface); /* The surface's geometry. */ @@ -127,6 +128,12 @@ uint32_t rt_surface_add(uint64_t owner, struct rt_surface *surface); struct rt_surface *rt_surface_get(uint64_t owner, uint32_t handle); /* The provider context the surface was imported with. */ void *rt_surface_provider_context(const struct rt_surface *surface); +/* The surface of @owner's @handle with a hold the caller drops with + * rt_surface_release(), or NULL. */ +struct rt_surface *rt_surface_get_hold(uint64_t owner, uint32_t handle); +/* Another reference; rt_surface_release() drops one, the last releases. */ +void rt_surface_hold(struct rt_surface *surface); + /* Remove and release: one handle (0 or -ENOENT), all of an owner's, or all * (both return how many). */ int rt_surface_remove(uint64_t owner, uint32_t handle); @@ -136,6 +143,33 @@ unsigned int rt_surface_count(void); #ifdef __KERNEL__ struct drm_gem_object; +struct drm_sched_entity; +struct amdgpu_ring; +struct amdgpu_device; +struct dma_fence; + +/* SDMA engines a caller owns for asynchronous copies: one scheduler + * entity per ready SDMA ring, at most two. */ +#define RT_SURFACE_ENGINES_MAX 2u +struct rt_surface_engines { + unsigned int count; + struct drm_sched_entity *entity[RT_SURFACE_ENGINES_MAX]; + struct amdgpu_ring *ring[RT_SURFACE_ENGINES_MAX]; +}; +int rt_surface_engines_init(struct amdgpu_device *adev, struct rt_surface_engines *engines); +void rt_surface_engines_fini(struct rt_surface_engines *engines); + +/* Submit the copies of @count rectangles into @dst (an amdgpu BO the + * caller keeps pinned in VRAM at @dst_address) and return without waiting. + * Damage of 1 MiB or more is split between the engines. Each engine's last + * fence is added to both buffers (a commit of @dst waits for it) and + * returned in @fences (NULL for an engine left unused; the caller puts + * them). Returns 0 or the failing step's errno (nothing submitted then). */ +int rt_surface_copy_submit(struct rt_surface *src, struct drm_gem_object *dst, uint64_t dst_address, + uint32_t dst_pitch, const struct rt_surface_rect *rects, uint32_t count, + struct rt_surface_engines *engines, + struct dma_fence *fences[RT_SURFACE_ENGINES_MAX], + struct rt_surface_copy_stats *stats); /* Copy @count rectangles of @src into @dst (an amdgpu BO, linear, @dst_pitch * bytes per row, at least the surface's size) at the same coordinates, on diff --git a/linuxu/src/amdgpu-rt/display.c b/linuxu/src/amdgpu-rt/display.c index 2d0669c..8f29dae 100644 --- a/linuxu/src/amdgpu-rt/display.c +++ b/linuxu/src/amdgpu-rt/display.c @@ -6,6 +6,11 @@ #include #include #include +#include +#include +#include +#include +#include #include #include #include @@ -39,7 +44,7 @@ _Static_assert(sizeof(struct rt_display_mode) == 16 && sizeof(struct rt_display_ "rt_display_modes layout"); /* host/DisplayAgent.swift decodes these. */ -_Static_assert(sizeof(struct rt_display_present_stats) == 56, "rt_display_present_stats layout"); +_Static_assert(sizeof(struct rt_display_present_stats) == 120, "rt_display_present_stats layout"); _Static_assert(sizeof(struct rt_surface_verify_result) == 64, "rt_surface_verify_result layout"); static DEFINE_MUTEX(rt_display_lock); @@ -68,6 +73,53 @@ struct display_snapshot { } *connector; }; +#define OUTPUT_BUFFERS 3 +#define OUTPUT_DAMAGE_MAX 128u +#define OUTPUT_FLIP_TIMEOUT_MS 200u + +extern struct dma_fence *drm_crtc_create_fence(struct drm_crtc *crtc); + +struct output_damage { + struct rt_surface_rect rect[OUTPUT_DAMAGE_MAX]; + uint32_t count; + bool full; +}; + +struct output_frame { + uint64_t capture_ns, received_ns, submitted_ns, bytes; + struct dma_fence *copy[RT_SURFACE_ENGINES_MAX]; +}; + +struct display_output { + struct drm_device *dev; + struct amdgpu_device *adev; + struct drm_crtc *crtc; + struct drm_plane *plane; + uint32_t width, height; + struct drm_client_buffer *fb[OUTPUT_BUFFERS]; + uint64_t fb_address[OUTPUT_BUFFERS]; + bool pinned[OUTPUT_BUFFERS]; + struct output_damage missed[OUTPUT_BUFFERS]; + struct rt_surface_engines engines; + /* The worker's own state. */ + int front, pending; + struct dma_fence *pending_flip; + struct dma_fence_cb flip_cb; + struct output_frame pending_frame; + struct task_struct *worker; + wait_queue_head_t wake; + /* Under lock: the mailbox, the stats, the flip's signal. */ + spinlock_t lock; + struct rt_surface *next; + struct output_damage next_damage; + uint64_t next_capture_ns, next_received_ns; + bool flip_done; + struct rt_display_present_stats stats; +}; + +static void output_stop(struct display_output *o); +static void output_free(struct display_output *o); + /* Guarded by rt_display_lock. */ static struct { struct drm_device *dev; @@ -77,15 +129,8 @@ static struct { uint32_t pattern; uint64_t fill_ns, commit_ns; int restore_status; - /* An output (rt_display_output): the second framebuffer, which one is - * on screen, which needs a whole frame, and the last frame's damage. */ - bool output; - struct drm_client_buffer *back; - bool stale[2]; /* [0] buffer, [1] back */ - struct rt_surface_rect last[RT_DISPLAY_PRESENT_RECTS_MAX]; - uint32_t last_count; - bool last_overflow; - uint64_t frames; + /* An output a display agent feeds (rt_display_output). */ + struct display_output *output; } rt_display; static int rt_display_on; /* atomic copy of "a pattern is showing" */ @@ -476,6 +521,9 @@ static int display_off_locked(void) if (!dev) return 0; + /* An output's worker stops first: no flip of its may follow. */ + if (rt_display.output) + output_stop(rt_display.output); if (rt_display.saved && rt_removal_active(drm_to_adev(dev))) { /* The device left the bus: there is no screen to restore. The * buffers and the client go as on a Linux unplug, where the @@ -502,12 +550,10 @@ static int display_off_locked(void) drm_client_buffer_delete(rt_display.buffer); rt_display.buffer = NULL; } - if (rt_display.back) { - drm_client_buffer_delete(rt_display.back); - rt_display.back = NULL; + if (rt_display.output) { + output_free(rt_display.output); + rt_display.output = NULL; } - rt_display.output = false; - rt_display.frames = 0; drm_client_release(&rt_display.client); memset(&rt_display.client, 0, sizeof(rt_display.client)); rt_display.dev = NULL; @@ -576,11 +622,22 @@ static void report_state(struct drm_device *dev, struct rt_display_report *repor report->showing = rt_display.dev == dev && rt_display.saved; report->restore_status = rt_display.restore_status; report->commit_ns = rt_display.commit_ns; - if (report->showing && rt_display.buffer) { + if (report->showing) + report->pattern = rt_display.pattern; + if (report->showing && rt_display.output) { + struct display_output *o = rt_display.output; + /* The buffer the output started on (the worker owns which is + * on screen now; their geometry is the same). */ + struct drm_framebuffer *fb = o->fb[0]->fb; + + report->fb_width = fb->width; + report->fb_height = fb->height; + report->fb_pitch = fb->pitches[0]; + report->fb_gpu_addr = o->fb_address[0]; + } else if (report->showing && rt_display.buffer) { struct drm_framebuffer *fb = rt_display.buffer->fb; struct amdgpu_bo *bo = gem_to_amdgpu_bo(fb->obj[0]); - report->pattern = rt_display.pattern; report->fb_width = fb->width; report->fb_height = fb->height; report->fb_pitch = fb->pitches[0]; @@ -937,11 +994,372 @@ static int modeset_use_mode(struct drm_client_dev *client, uint32_t width, uint3 return ret; } +/* ---- the output pipeline ---- + * + * PRESENT is a mailbox: it queues the newest frame (its surface, damage and + * capture time), merging a frame the worker has not taken yet, wakes the + * worker and returns. The worker copies into a framebuffer that is neither + * on screen nor waiting for its flip (three of them), with SDMA and no CPU + * wait, and flips to it with a nonblocking atomic commit: the copy's fence + * is on the buffer, so the commit waits for it (an implicit in-fence), and + * the commit's out-fence (a CRTC fence on a kernel flip event) signals at + * the flip with its vblank timestamp. The worker sleeps on interrupts (the + * flip's fence callback, a new frame) and never polls; its waits are + * bounded as a backstop. Each buffer remembers the damage it missed while + * others were drawn, so a copy is that plus the frame's own. */ +static void damage_add(struct output_damage *d, const struct rt_surface_rect *rects, uint32_t count) +{ + if (d->full) + return; + if (count > OUTPUT_DAMAGE_MAX - d->count) { + d->full = true; + d->count = 0; + return; + } + memcpy(&d->rect[d->count], rects, count * sizeof(*rects)); + d->count += count; +} + +static void damage_merge(struct output_damage *d, const struct output_damage *add) +{ + if (add->full) { + d->full = true; + d->count = 0; + } else { + damage_add(d, add->rect, add->count); + } +} + +static void output_flip_signaled(struct dma_fence *fence, struct dma_fence_cb *cb) +{ + struct display_output *o = container_of(cb, struct display_output, flip_cb); + unsigned long flags; + + (void)fence; + spin_lock_irqsave(&o->lock, flags); + o->flip_done = true; + spin_unlock_irqrestore(&o->lock, flags); + wake_up(&o->wake); +} + +static void output_error(struct display_output *o, int error) +{ + unsigned long flags; + + spin_lock_irqsave(&o->lock, flags); + if (!o->stats.error) + o->stats.error = error; + spin_unlock_irqrestore(&o->lock, flags); + drm_err(o->dev, "display output: worker stopped by error %d\n", error); +} + +/* The pending flip happened: account it, its buffer is on screen. */ +static void output_flip_account(struct display_output *o) +{ + struct output_frame *f = &o->pending_frame; + uint64_t flip_ns = ktime_to_ns(o->pending_flip->timestamp); + uint64_t gpu_ns = 0, latency = 0; + unsigned long flags; + + for (unsigned int i = 0; i < RT_SURFACE_ENGINES_MAX; i++) { + if (!f->copy[i]) + continue; + if (dma_fence_is_signaled(f->copy[i]) && + test_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &f->copy[i]->flags)) { + uint64_t done = ktime_to_ns(f->copy[i]->timestamp); + + if (done > f->submitted_ns && done - f->submitted_ns > gpu_ns) + gpu_ns = done - f->submitted_ns; + } + dma_fence_put(f->copy[i]); + f->copy[i] = NULL; + } + if (f->capture_ns && flip_ns > f->capture_ns) + latency = flip_ns - f->capture_ns; + spin_lock_irqsave(&o->lock, flags); + o->stats.frames_flipped++; + o->stats.copy_gpu_ns += gpu_ns; + o->stats.last_copy_gpu_ns = gpu_ns; + o->stats.last_bytes = f->bytes; + o->stats.latency_ns += latency; + o->stats.last_latency_ns = latency; + if (latency > o->stats.latency_max_ns) + o->stats.latency_max_ns = latency; + o->flip_done = false; + spin_unlock_irqrestore(&o->lock, flags); + dma_fence_put(o->pending_flip); + o->pending_flip = NULL; + o->front = o->pending; + o->pending = -1; +} + +/* Wait (bounded) for the pending flip; 0 when it happened. */ +static int output_flip_wait(struct display_output *o) +{ + long left; + + if (!o->pending_flip) + return 0; + left = dma_fence_wait_timeout(o->pending_flip, false, msecs_to_jiffies(OUTPUT_FLIP_TIMEOUT_MS)); + if (left <= 0) + return left < 0 ? (int)left : -ETIME; + output_flip_account(o); + return 0; +} + +/* A nonblocking commit of buffer @b on the primary plane, with a CRTC + * fence that signals at the flip. */ +static int output_commit(struct display_output *o, int b, struct dma_fence **out) +{ + struct drm_modeset_acquire_ctx ctx; + struct drm_atomic_state *state; + struct dma_fence *fence = NULL; + int ret; + + *out = NULL; + drm_modeset_acquire_init(&ctx, 0); + state = drm_atomic_state_alloc(o->dev); + if (!state) { + ret = -ENOMEM; + goto fini; + } + state->acquire_ctx = &ctx; +retry: + { + struct drm_plane_state *ps = drm_atomic_get_plane_state(state, o->plane); + struct drm_crtc_state *cs; + struct drm_pending_vblank_event *e; + + ret = PTR_ERR_OR_ZERO(ps); + if (ret) + goto backoff; + drm_atomic_set_fb_for_plane(ps, o->fb[b]->fb); + cs = drm_atomic_get_crtc_state(state, o->crtc); + ret = PTR_ERR_OR_ZERO(cs); + if (ret) + goto backoff; + e = kzalloc(sizeof(*e), GFP_KERNEL); + fence = drm_crtc_create_fence(o->crtc); + if (!e || !fence) { + kfree(e); + if (fence) + dma_fence_put(fence); + fence = NULL; + ret = -ENOMEM; + goto put; + } + e->pipe = drm_crtc_index(o->crtc); + e->event.base.type = DRM_EVENT_FLIP_COMPLETE; + e->event.base.length = sizeof(e->event); + e->event.vbl.crtc_id = o->crtc->base.id; + e->base.event = &e->event.base; + e->base.fence = dma_fence_get(fence); /* signalled and put at the flip */ + cs->event = e; + ret = drm_atomic_nonblocking_commit(state); + if (ret) { + /* As the atomic ioctl's failure path does. */ + cs->event = NULL; + drm_event_cancel_free(o->dev, &e->base); + dma_fence_put(fence); + fence = NULL; + } + } +backoff: + if (ret == -EDEADLK) { + drm_atomic_state_clear(state); + drm_modeset_backoff(&ctx); + goto retry; + } +put: + drm_atomic_state_put(state); +fini: + drm_modeset_drop_locks(&ctx); + drm_modeset_acquire_fini(&ctx); + *out = fence; + return ret; +} + +/* One frame: copy into a free buffer, wait for the previous flip, flip. */ +static int output_frame(struct display_output *o, struct rt_surface *surface, + struct output_damage *damage, uint64_t capture_ns, uint64_t received_ns) +{ + struct rt_surface_rect full = { 0, 0, o->width, o->height }; + struct output_damage copy; + struct rt_surface_copy_stats cs; + struct output_frame frame = { .capture_ns = capture_ns, .received_ns = received_ns }; + struct dma_fence *flip; + unsigned long flags; + int b = 0, r; + u64 start = ktime_get_ns(); + + while (b == o->front || b == o->pending) + b++; + copy = o->missed[b]; + damage_merge(©, damage); + r = rt_surface_copy_submit(surface, o->fb[b]->fb->obj[0], o->fb_address[b], o->fb[b]->fb->pitches[0], + copy.full ? &full : copy.rect, copy.full ? 1 : copy.count, &o->engines, + frame.copy, &cs); + rt_surface_release(surface); + if (r) + return r; + frame.submitted_ns = ktime_get_ns(); + frame.bytes = cs.bytes; + memset(&o->missed[b], 0, sizeof(o->missed[b])); + for (int i = 0; i < OUTPUT_BUFFERS; i++) + if (i != b) + damage_merge(&o->missed[i], damage); + spin_lock_irqsave(&o->lock, flags); + o->stats.copy_jobs += cs.jobs; + o->stats.bytes += cs.bytes; + o->stats.copy_submit_ns += frame.submitted_ns - start; + o->stats.full_frames += copy.full; + spin_unlock_irqrestore(&o->lock, flags); + + /* One flip in flight per CRTC: the previous one first. */ + r = output_flip_wait(o); + if (!r) + r = output_commit(o, b, &flip); + if (r) { + for (unsigned int i = 0; i < RT_SURFACE_ENGINES_MAX; i++) + if (frame.copy[i]) + dma_fence_put(frame.copy[i]); + return r; + } + o->pending = b; + o->pending_flip = flip; + o->pending_frame = frame; + spin_lock_irqsave(&o->lock, flags); + o->flip_done = false; + spin_unlock_irqrestore(&o->lock, flags); + if (dma_fence_add_callback(flip, &o->flip_cb, output_flip_signaled)) + output_flip_signaled(flip, &o->flip_cb); /* already signalled */ + return 0; +} + +static bool output_has_work(struct display_output *o) +{ + unsigned long flags; + bool work; + + spin_lock_irqsave(&o->lock, flags); + work = o->next || o->flip_done; + spin_unlock_irqrestore(&o->lock, flags); + return work || kthread_should_stop(); +} + +static int output_worker(void *arg) +{ + struct display_output *o = arg; + + while (!kthread_should_stop()) { + struct output_damage damage; + struct rt_surface *surface; + uint64_t capture_ns, received_ns; + unsigned long flags; + bool done; + int r; + + /* Nothing outstanding: sleep until a frame or a flip arrives. + * A pending flip is also checked after a bounded wait, the + * backstop for a lost flip interrupt. */ + if (o->pending_flip) + wait_event_timeout(o->wake, output_has_work(o), msecs_to_jiffies(OUTPUT_FLIP_TIMEOUT_MS)); + else + wait_event(o->wake, output_has_work(o)); + if (kthread_should_stop()) + break; + spin_lock_irqsave(&o->lock, flags); + done = o->flip_done; + surface = o->next; + o->next = NULL; + damage = o->next_damage; + memset(&o->next_damage, 0, sizeof(o->next_damage)); + capture_ns = o->next_capture_ns; + received_ns = o->next_received_ns; + spin_unlock_irqrestore(&o->lock, flags); + if ((done || (o->pending_flip && dma_fence_is_signaled(o->pending_flip))) && o->pending_flip) + output_flip_account(o); + if (!surface) + continue; + if (rt_removal_active(o->adev)) { + rt_surface_release(surface); + output_error(o, -ENODEV); + break; + } + r = output_frame(o, surface, &damage, capture_ns, received_ns); + if (r) { + output_error(o, r); + break; + } + } + /* Whatever is left in the mailbox is not shown. */ + { + unsigned long flags; + struct rt_surface *left; + + spin_lock_irqsave(&o->lock, flags); + left = o->next; + o->next = NULL; + spin_unlock_irqrestore(&o->lock, flags); + rt_surface_release(left); + } + while (!kthread_should_stop()) + wait_event_timeout(o->wake, kthread_should_stop(), msecs_to_jiffies(1000)); + return 0; +} + +static void output_stop(struct display_output *o) +{ + if (o->worker) { + kthread_stop(o->worker); + o->worker = NULL; + } + /* The last flip lands before the screen is restored, unless the + * device is gone (nothing will flip). */ + if (o->pending_flip) { + if (!rt_removal_active(o->adev)) + (void)output_flip_wait(o); + if (o->pending_flip) { + dma_fence_remove_callback(o->pending_flip, &o->flip_cb); + dma_fence_put(o->pending_flip); + o->pending_flip = NULL; + for (unsigned int i = 0; i < RT_SURFACE_ENGINES_MAX; i++) + if (o->pending_frame.copy[i]) { + dma_fence_put(o->pending_frame.copy[i]); + o->pending_frame.copy[i] = NULL; + } + } + } +} + +/* After the screen was restored: the engines, the pins, the buffers. */ +static void output_free(struct display_output *o) +{ + output_stop(o); + if (o->engines.count) + rt_surface_engines_fini(&o->engines); + for (int i = 0; i < OUTPUT_BUFFERS; i++) { + if (!o->fb[i]) + continue; + if (o->pinned[i]) { + struct amdgpu_bo *bo = gem_to_amdgpu_bo(o->fb[i]->fb->obj[0]); + + if (!amdgpu_bo_reserve(bo, true)) { + amdgpu_bo_unpin(bo); + amdgpu_bo_unreserve(bo); + } + } + drm_client_buffer_delete(o->fb[i]); + } + kfree(o); +} + int rt_display_output(struct pci_dev *pdev, const char *connector, uint32_t width, uint32_t height, uint32_t refresh_mhz, struct rt_display_report *report) { struct drm_device *dev = display_device(pdev); - struct drm_client_buffer *buffers[2] = { NULL, NULL }; + struct display_output *o; + struct drm_mode_set *modeset; unsigned int lit; u64 start; int ret; @@ -965,6 +1383,20 @@ int rt_display_output(struct pci_dev *pdev, const char *connector, uint32_t widt } rt_display.dev = dev; rt_display.pattern = RT_DISPLAY_PATTERN_OUTPUT; + o = kzalloc(sizeof(*o), GFP_KERNEL); + if (!o) { + ret = -ENOMEM; + goto fail; + } + rt_display.output = o; + o->dev = dev; + o->adev = drm_to_adev(dev); + o->width = width; + o->height = height; + o->front = o->pending = -1; + spin_lock_init(&o->lock); + init_waitqueue_head(&o->wake); + o->stats.version = 2; ret = drm_client_modeset_probe(&rt_display.client, 0, 0); if (report) report->probe_status = ret; @@ -981,21 +1413,49 @@ int rt_display_output(struct pci_dev *pdev, const char *connector, uint32_t widt height, refresh_mhz); goto fail; } - /* amdgpu clears new dumb buffers with SDMA: both start black. */ - for (int i = 0; i < 2; i++) { - buffers[i] = drm_client_buffer_create_dumb(&rt_display.client, width, height, - DRM_FORMAT_XRGB8888); - if (IS_ERR(buffers[i])) { - ret = PTR_ERR(buffers[i]); - buffers[i] = NULL; + mutex_lock(&rt_display.client.modeset_mutex); + drm_client_for_each_modeset(modeset, &rt_display.client) + if (modeset->mode && modeset->num_connectors) + o->crtc = modeset->crtc; + mutex_unlock(&rt_display.client.modeset_mutex); + o->plane = o->crtc ? o->crtc->primary : NULL; + if (!o->plane) { + ret = -ENOENT; + goto fail; + } + /* Three buffers, pinned in VRAM for the output's life (amdgpu clears + * new dumb buffers with SDMA: they start black). */ + for (int i = 0; i < OUTPUT_BUFFERS; i++) { + struct amdgpu_bo *bo; + + o->fb[i] = drm_client_buffer_create_dumb(&rt_display.client, width, height, + DRM_FORMAT_XRGB8888); + if (IS_ERR(o->fb[i])) { + ret = PTR_ERR(o->fb[i]); + o->fb[i] = NULL; goto fail; } - if (!i) - rt_display.buffer = buffers[0]; - else - rt_display.back = buffers[1]; + bo = gem_to_amdgpu_bo(o->fb[i]->fb->obj[0]); + ret = amdgpu_bo_reserve(bo, false); + if (!ret) { + ret = amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_VRAM); + if (!ret) { + o->pinned[i] = true; + o->fb_address[i] = amdgpu_bo_gpu_offset(bo); + } + amdgpu_bo_unreserve(bo); + } + if (ret) + goto fail; + o->missed[i].full = true; } - modesets_attach(&rt_display.client, rt_display.buffer->fb); + ret = rt_surface_engines_init(o->adev, &o->engines); + if (ret) { + drm_err(dev, "display output: no SDMA engine to copy with (%d)\n", ret); + goto fail; + } + o->stats.engines = o->engines.count; + modesets_attach(&rt_display.client, o->fb[0]->fb); ret = state_save(dev, &rt_display.saved); if (ret) goto fail; @@ -1008,14 +1468,19 @@ int rt_display_output(struct pci_dev *pdev, const char *connector, uint32_t widt drm_err(dev, "display output: commit failed (%d)\n", ret); goto fail; } - rt_display.output = true; - rt_display.stale[0] = rt_display.stale[1] = true; - rt_display.last_count = 0; - rt_display.last_overflow = false; - rt_display.frames = 0; + o->front = 0; + o->worker = kthread_run(output_worker, o, "display-output"); + if (IS_ERR_OR_NULL(o->worker)) { + ret = o->worker ? PTR_ERR(o->worker) : -ENOMEM; + o->worker = NULL; + goto fail; + } + /* Its buffer is drawn by the first frame: the black one stays until then. */ + rt_display.buffer = NULL; __atomic_store_n(&rt_display_on, 1, __ATOMIC_RELEASE); - drm_info(dev, "display output: %s at %ux%u (%u mHz), two framebuffers (commit %llu ms)\n", - connector, width, height, refresh_mhz, rt_display.commit_ns / 1000000); + drm_info(dev, "display output: %s at %ux%u (%u mHz), %d framebuffers, %u SDMA engine(s) (commit %llu ms)\n", + connector, width, height, refresh_mhz, OUTPUT_BUFFERS, o->engines.count, + rt_display.commit_ns / 1000000); report_state(dev, report); mutex_unlock(&rt_display_lock); return 0; @@ -1035,87 +1500,83 @@ out: } int rt_display_present(struct pci_dev *pdev, struct rt_surface *surface, - const struct rt_surface_rect *rects, uint32_t count, + const struct rt_surface_rect *rects, uint32_t count, uint64_t capture_ns, struct rt_display_present_stats *stats) { struct drm_device *dev = display_device(pdev); - struct rt_surface_rect list[2 * RT_DISPLAY_PRESENT_RECTS_MAX]; - struct rt_display_present_stats local = { 0 }; - struct rt_surface_copy_stats copied = { 0 }; - struct drm_client_buffer *back; - uint32_t width, height, pitch, n = 0; - bool full; - u64 start; - int ret; + struct display_output *o; + struct rt_surface *replaced = NULL; + uint32_t width, height, pitch; + unsigned long flags; + int ret = 0; - if (!stats) - stats = &local; - memset(stats, 0, sizeof(*stats)); - stats->version = 1; - if (!dev) + if (stats) + memset(stats, 0, sizeof(*stats)); + if (!dev) { + rt_surface_release(surface); return -ENODEV; - if (!surface || (count && !rects)) + } + if (!surface || (count && !rects)) { + rt_surface_release(surface); return -EINVAL; + } mutex_lock(&rt_display_lock); - if (!rt_display.output || rt_display.dev != dev) { + o = rt_display.dev == dev ? rt_display.output : NULL; + if (!o) { mutex_unlock(&rt_display_lock); + rt_surface_release(surface); return -ENOENT; } rt_surface_geometry(surface, &width, &height, &pitch); - back = rt_display.back; - if (width != back->fb->width || height != back->fb->height) { - mutex_unlock(&rt_display_lock); + spin_lock_irqsave(&o->lock, flags); + if (o->stats.error) { + ret = o->stats.error; + } else if (width != o->width || height != o->height) { + ret = -EINVAL; + } else if (count) { + struct output_damage add = { .count = 0 }; + + /* The newest frame replaces one not yet taken; damage adds up. */ + replaced = o->next; + if (replaced) + o->stats.frames_replaced++; + damage_add(&add, rects, count); + damage_merge(&o->next_damage, &add); + o->next = surface; + surface = NULL; + o->next_capture_ns = capture_ns; + o->next_received_ns = ktime_get_ns(); + o->stats.frames_received++; + } + if (stats) + *stats = o->stats; + spin_unlock_irqrestore(&o->lock, flags); + mutex_unlock(&rt_display_lock); + if (!surface) + wake_up(&o->wake); + rt_surface_release(surface); + rt_surface_release(replaced); + return ret; +} + +int rt_display_stats(struct pci_dev *pdev, struct rt_display_present_stats *stats) +{ + struct drm_device *dev = pdev ? pci_get_drvdata(pdev) : NULL; + struct display_output *o; + unsigned long flags; + int ret = -ENOENT; + + if (!stats) return -EINVAL; + memset(stats, 0, sizeof(*stats)); + mutex_lock(&rt_display_lock); + o = dev && rt_display.dev == dev ? rt_display.output : NULL; + if (o) { + spin_lock_irqsave(&o->lock, flags); + *stats = o->stats; + spin_unlock_irqrestore(&o->lock, flags); + ret = 0; } - stats->frames = rt_display.frames; - if (!count) { - mutex_unlock(&rt_display_lock); - return 0; - } - /* The back buffer holds the frame before the one on screen: it needs - * this frame's damage and the last one's, or a whole frame. */ - full = rt_display.stale[1] || rt_display.last_overflow || count > RT_DISPLAY_PRESENT_RECTS_MAX; - if (full) { - list[n++] = (struct rt_surface_rect){ 0, 0, width, height }; - } else { - memcpy(list, rects, count * sizeof(*rects)); - memcpy(list + count, rt_display.last, rt_display.last_count * sizeof(*rects)); - n = count + rt_display.last_count; - } - stats->full = full; - stats->rects = n; - start = ktime_get_ns(); - ret = rt_surface_copy(surface, back->fb->obj[0], back->fb->pitches[0], list, n, 1000, &copied); - stats->copy_ns = ktime_get_ns() - start; - stats->copy_status = ret; - stats->jobs = copied.jobs; - stats->bytes = copied.bytes; - if (ret) - goto out; - modesets_attach(&rt_display.client, back->fb); - start = ktime_get_ns(); - ret = drm_client_modeset_commit(&rt_display.client); - stats->flip_ns = ktime_get_ns() - start; - stats->flip_status = ret; - if (ret) { - /* The screen still shows the front buffer. */ - modesets_attach(&rt_display.client, rt_display.buffer->fb); - goto out; - } - rt_display.back = rt_display.buffer; - rt_display.buffer = back; - rt_display.stale[1] = rt_display.stale[0]; - rt_display.stale[0] = false; - if (count > RT_DISPLAY_PRESENT_RECTS_MAX) { - rt_display.last_overflow = true; - rt_display.last_count = 0; - } else { - rt_display.last_overflow = false; - memcpy(rt_display.last, rects, count * sizeof(*rects)); - rt_display.last_count = count; - } - stats->frames = ++rt_display.frames; -out: mutex_unlock(&rt_display_lock); return ret; } diff --git a/linuxu/src/amdgpu-rt/surface.c b/linuxu/src/amdgpu-rt/surface.c index 73736fe..af4889b 100644 --- a/linuxu/src/amdgpu-rt/surface.c +++ b/linuxu/src/amdgpu-rt/surface.c @@ -27,6 +27,7 @@ struct surface_buffer { }; struct rt_surface { + int refs; /* the import's, plus each hold (rt_surface_hold) */ struct drm_gem_object *obj; uint64_t gpu_address; uint64_t size; @@ -198,6 +199,7 @@ int rt_surface_import(struct pci_dev *pdev, const struct rt_surface_segment *seg surface->height = height; surface->pitch = pitch; surface->provider_context = provider->context; + surface->refs = 1; /* Success: the provider is released with the dma-buf. */ buffer->armed = true; *out = surface; @@ -218,11 +220,17 @@ uncharge: return r; } +void rt_surface_hold(struct rt_surface *surface) +{ + if (surface) + __atomic_add_fetch(&surface->refs, 1, __ATOMIC_RELAXED); +} + void rt_surface_release(struct rt_surface *surface) { struct amdgpu_bo *bo; - if (!surface) + if (!surface || __atomic_sub_fetch(&surface->refs, 1, __ATOMIC_ACQ_REL)) return; bo = gem_to_amdgpu_bo(surface->obj); if (!amdgpu_bo_reserve(bo, true)) { @@ -255,6 +263,8 @@ uint64_t rt_surface_gpu_address(const struct rt_surface *surface) struct copy_batch { struct amdgpu_device *adev; + struct drm_sched_entity *entity; /* NULL: the TTM buffer-function entity */ + struct amdgpu_ring *ring; /* the entity's ring (for IB padding) */ struct amdgpu_job *job; uint32_t packets; struct dma_fence *last; @@ -263,7 +273,7 @@ struct copy_batch { static int batch_submit(struct copy_batch *b) { - struct amdgpu_ring *ring = b->adev->mman.buffer_funcs_ring; + struct amdgpu_ring *ring = b->ring ? b->ring : b->adev->mman.buffer_funcs_ring; struct dma_fence *fence; if (!b->job) @@ -287,7 +297,8 @@ static int batch_copy(struct copy_batch *b, uint64_t src, uint64_t dst, uint64_t uint32_t chunk = bytes > funcs->copy_max_bytes ? funcs->copy_max_bytes : (uint32_t)bytes; if (!b->job) { - r = amdgpu_job_alloc_with_ib(b->adev, &b->adev->mman.default_entity.base, + r = amdgpu_job_alloc_with_ib(b->adev, b->entity ? b->entity : + &b->adev->mman.default_entity.base, AMDGPU_FENCE_OWNER_UNDEFINED, ALIGN(COPY_PACKETS_PER_JOB * funcs->copy_num_dw, 8) * 4, AMDGPU_IB_POOL_DELAYED, &b->job, @@ -566,6 +577,20 @@ struct rt_surface *rt_surface_get(uint64_t owner, uint32_t handle) return found; } +struct rt_surface *rt_surface_get_hold(uint64_t owner, uint32_t handle) +{ + struct rt_surface *found = NULL; + + mutex_lock(&surface_table_lock); + for (uint32_t i = 0; handle && i < RT_SURFACE_IMPORTS_MAX; i++) + if (surface_table[i].surface && surface_table[i].owner == owner && + surface_table[i].handle == handle) + found = surface_table[i].surface; + rt_surface_hold(found); + mutex_unlock(&surface_table_lock); + return found; +} + void *rt_surface_provider_context(const struct rt_surface *surface) { return surface ? surface->provider_context : NULL; @@ -621,3 +646,155 @@ unsigned int rt_surface_count(void) mutex_unlock(&surface_table_lock); return n; } + +/* ---- asynchronous copies on engines the caller owns ---- */ + +int rt_surface_engines_init(struct amdgpu_device *adev, struct rt_surface_engines *e) +{ + memset(e, 0, sizeof(*e)); + for (int i = 0; i < adev->sdma.num_instances && e->count < RT_SURFACE_ENGINES_MAX; i++) { + struct amdgpu_ring *ring = &adev->sdma.instance[i].ring; + struct drm_gpu_scheduler *sched = &ring->sched; + struct drm_sched_entity *entity; + + if (!ring->sched.ready || !adev->mman.buffer_funcs) + continue; + entity = kzalloc(sizeof(*entity), GFP_KERNEL); + if (!entity) + break; + if (drm_sched_entity_init(entity, DRM_SCHED_PRIORITY_NORMAL, &sched, 1, NULL)) { + kfree(entity); + continue; + } + e->entity[e->count] = entity; + e->ring[e->count] = ring; + e->count++; + } + return e->count ? 0 : -ENODEV; +} + +void rt_surface_engines_fini(struct rt_surface_engines *e) +{ + for (unsigned int i = 0; i < e->count; i++) { + drm_sched_entity_destroy(e->entity[i]); + kfree(e->entity[i]); + } + memset(e, 0, sizeof(*e)); +} + +/* Rows of one rectangle as copy ranges: whole rows with equal pitches in + * bands of up to 64 rows, else one range per row. */ +#define COPY_BAND_ROWS 64u + +static uint64_t rect_bytes(const struct rt_surface *src, uint32_t dst_pitch, + const struct rt_surface_rect *r, uint32_t *x, uint32_t *y, + uint32_t *w, uint32_t *h) +{ + if (r->x >= src->width || r->y >= src->height || !r->width || !r->height) + return 0; + *x = r->x; + *y = r->y; + *w = min_t(u32, r->width, src->width - r->x); + *h = min_t(u32, r->height, src->height - r->y); + (void)dst_pitch; + return (uint64_t)*w * 4 * *h; +} + +int rt_surface_copy_submit(struct rt_surface *src, struct drm_gem_object *dst, uint64_t dst_address, + uint32_t dst_pitch, const struct rt_surface_rect *rects, uint32_t count, + struct rt_surface_engines *engines, + struct dma_fence *fences[RT_SURFACE_ENGINES_MAX], + struct rt_surface_copy_stats *stats) +{ + struct copy_batch batch[RT_SURFACE_ENGINES_MAX] = { 0 }; + struct rt_surface_copy_stats local[RT_SURFACE_ENGINES_MAX] = { 0 }; + struct amdgpu_device *adev; + struct amdgpu_bo *dst_bo, *src_bo; + uint64_t total = 0, half; + unsigned int use, e = 0; + u64 start = ktime_get_ns(); + int r = 0; + + for (unsigned int i = 0; i < RT_SURFACE_ENGINES_MAX; i++) + fences[i] = NULL; + if (stats) + memset(stats, 0, sizeof(*stats)); + if (!src || !dst || !rects || !count || !engines || !engines->count || + dst_pitch < (uint64_t)src->width * 4 || dst->size < (uint64_t)dst_pitch * src->height) + return -EINVAL; + dst_bo = gem_to_amdgpu_bo(dst); + src_bo = gem_to_amdgpu_bo(src->obj); + adev = amdgpu_ttm_adev(dst_bo->tbo.bdev); + if (rt_removal_active(adev)) + return -ENODEV; + for (uint32_t i = 0; i < count; i++) { + uint32_t x, y, w, h; + + total += rect_bytes(src, dst_pitch, &rects[i], &x, &y, &w, &h); + } + if (!total) + return 0; + /* Large damage goes to both engines, about half each. */ + use = total >= (1u << 20) ? engines->count : 1; + half = (total + use - 1) / use; + for (unsigned int i = 0; i < use; i++) { + batch[i].adev = adev; + batch[i].entity = engines->entity[i]; + batch[i].ring = engines->ring[i]; + batch[i].stats = &local[i]; + } + for (uint32_t i = 0; !r && i < count; i++) { + uint32_t x, y, w, h; + + if (!rect_bytes(src, dst_pitch, &rects[i], &x, &y, &w, &h)) + continue; + if (stats) + stats->rows += h; + for (uint32_t row = y; !r && row < y + h;) { + uint32_t rows = 1; + uint64_t bytes = (uint64_t)w * 4; + + if (!x && w == src->width && src->pitch == dst_pitch) { + rows = min_t(u32, COPY_BAND_ROWS, y + h - row); + bytes = (uint64_t)(rows - 1) * src->pitch + (uint64_t)w * 4; + } + if (e + 1 < use && local[e].bytes >= half) + e++; + r = batch_copy(&batch[e], src->gpu_address + (u64)row * src->pitch + (u64)x * 4, + dst_address + (u64)row * dst_pitch + (u64)x * 4, bytes); + row += rows; + } + } + for (unsigned int i = 0; i < use; i++) { + if (r && batch[i].job) { + amdgpu_job_free(batch[i].job); + batch[i].job = NULL; + } else if (!r) { + batch_submit(&batch[i]); + } + if (batch[i].last) { + /* Neither buffer moves or goes before the copy finished, and + * a commit of @dst waits for it (an implicit in-fence). */ + if (!amdgpu_bo_reserve(src_bo, true)) { + amdgpu_bo_fence(src_bo, batch[i].last, true); + amdgpu_bo_unreserve(src_bo); + } else { + dma_fence_wait(batch[i].last, false); + } + if (!amdgpu_bo_reserve(dst_bo, true)) { + amdgpu_bo_fence(dst_bo, batch[i].last, false); + amdgpu_bo_unreserve(dst_bo); + } else { + dma_fence_wait(batch[i].last, false); + } + fences[i] = batch[i].last; + } + if (stats) { + stats->jobs += local[i].jobs; + stats->bytes += local[i].bytes; + } + } + if (stats) + stats->ns = ktime_get_ns() - start; + return r; +} diff --git a/linuxu/tests/cs_fixture.c b/linuxu/tests/cs_fixture.c index 59f1268..007fc03 100644 --- a/linuxu/tests/cs_fixture.c +++ b/linuxu/tests/cs_fixture.c @@ -88,6 +88,8 @@ enum { static struct pci_dev *pdev; static struct amdgpu_device *adev; uint64_t cs_fixture_visible_vram; +unsigned int cs_fixture_sdma_instances; +void (*cs_fixture_display)(struct amdgpu_device *adev); static uint8_t *vram; /* the VRAM behind the aperture */ static uint64_t *doorbells; static struct amdgpu_irq_src fence_irq; @@ -252,7 +254,7 @@ static void hub_set_pd(struct engine *e, uint32_t vmid, uint64_t pd) hub_pd[e->ring->vm_hub][vmid] = pd; pthread_mutex_unlock(&hub_lock); } -static struct engine compute_engine, sdma_engine; +static struct engine compute_engine, sdma_engine, sdma1_engine; static uint8_t *gpu_to_host(struct engine *e, uint32_t vmid, uint64_t addr) { @@ -270,7 +272,9 @@ static uint8_t *gpu_to_host(struct engine *e, uint32_t vmid, uint64_t addr) static struct engine *engine_of(struct amdgpu_ring *ring) { - return ring == &adev->gfx.compute_ring[0] ? &compute_engine : &sdma_engine; + if (ring == &adev->gfx.compute_ring[0]) + return &compute_engine; + return ring == &adev->sdma.instance[1].ring ? &sdma1_engine : &sdma_engine; } static uint64_t fx_get_rptr(struct amdgpu_ring *ring) @@ -1047,6 +1051,11 @@ struct pci_dev *cs_fixture_init(void) /* Host test DMA addresses are user pointers: no narrower mask (as * rt_device_alloc does for the host backend). */ + /* A display (cs_fixture.h): modesetting and dumb buffers. */ + if (cs_fixture_display) { + fx_driver.driver_features |= DRIVER_MODESET | DRIVER_ATOMIC; + fx_driver.dumb_create = amdgpu_mode_dumb_create; + } adev = devm_drm_dev_alloc(&pdev->dev, &fx_driver, typeof(*adev), ddev); if (IS_ERR(adev)) FX_ABORT("devm_drm_dev_alloc = %ld", PTR_ERR(adev)); @@ -1187,11 +1196,14 @@ struct pci_dev *cs_fixture_init(void) fence_irq.funcs = &fx_irq_funcs; fence_irq.enabled_types = kcalloc(1, sizeof(atomic_t), GFP_KERNEL); adev->gfx.num_compute_rings = 1; - adev->sdma.num_instances = 1; + adev->sdma.num_instances = cs_fixture_sdma_instances == 2 ? 2 : 1; ring_setup(&adev->gfx.compute_ring[0], &fx_compute_funcs, "comp_1.0.0", AMDGPU_GFXHUB(0), &compute_engine); ring_setup(&adev->sdma.instance[0].ring, &fx_sdma_funcs, "sdma0", AMDGPU_GFXHUB(0), &sdma_engine); + if (adev->sdma.num_instances == 2) + ring_setup(&adev->sdma.instance[1].ring, &fx_sdma_funcs, "sdma1", AMDGPU_GFXHUB(0), + &sdma1_engine); adev->mman.buffer_funcs = &fx_buffer_funcs; adev->mman.buffer_funcs_ring = &adev->sdma.instance[0].ring; adev->vm_manager.vm_pte_funcs = &fx_pte_funcs; @@ -1204,6 +1216,10 @@ struct pci_dev *cs_fixture_init(void) if (!getenv("CS_FIXTURE_NO_DMA_HOLD")) /* the negative control */ rt_dma_hold_attach(adev); + /* The display IP's init runs before registration, as in + * amdgpu_device_ip_init. */ + if (cs_fixture_display) + cs_fixture_display(adev); r = drm_dev_register(adev_to_drm(adev), 0); if (r) FX_ABORT("drm_dev_register = %d", r); @@ -1212,9 +1228,11 @@ struct pci_dev *cs_fixture_init(void) void cs_fixture_stop(void) { - struct engine *engines[] = { &compute_engine, &sdma_engine }; + struct engine *engines[] = { &compute_engine, &sdma_engine, &sdma1_engine }; - for (unsigned int i = 0; i < 2; ++i) { + for (unsigned int i = 0; i < 3; ++i) { + if (!engines[i]->ring) + continue; pthread_mutex_lock(&engines[i]->lock); engines[i]->stop = true; pthread_cond_signal(&engines[i]->kick); @@ -1230,6 +1248,12 @@ void cs_fixture_stats(struct cs_fixture_stats *out) pthread_mutex_unlock(&stats_lock); } +uint8_t *cs_fixture_vram_host(uint64_t mc) +{ + return mc >= adev->gmc.vram_start && mc <= adev->gmc.vram_end ? + vram + (mc - adev->gmc.vram_start) : NULL; +} + struct amdgpu_device *cs_fixture_adev(void) { return adev; diff --git a/linuxu/tests/cs_fixture.h b/linuxu/tests/cs_fixture.h index eef624b..d1487b4 100644 --- a/linuxu/tests/cs_fixture.h +++ b/linuxu/tests/cs_fixture.h @@ -23,6 +23,14 @@ struct cs_fixture_stats { unsigned long skipped; /* packets skipped (state, caches) */ }; +/* Before cs_fixture_init: two SDMA instances (each its own engine), and a + * display: the driver gets modesetting and dumb buffers, mode config is + * initialized and this function runs the display IP's init (after TTM, + * GART, VM and the rings, before drm_dev_register). */ +struct amdgpu_device; +extern unsigned int cs_fixture_sdma_instances; +extern void (*cs_fixture_display)(struct amdgpu_device *adev); + /* Bring up the linked DRM/amdgpu modules and the fixture device, and * register its DRM device (render node minor 128). Aborts on failure. */ struct pci_dev *cs_fixture_init(void); @@ -37,6 +45,8 @@ void cs_fixture_hold_sdma(int hold); extern uint64_t cs_fixture_visible_vram; struct amdgpu_device; struct amdgpu_device *cs_fixture_adev(void); +/* The host memory behind VRAM MC address @mc, or NULL. */ +uint8_t *cs_fixture_vram_host(uint64_t mc); /* TTM moves VRAM <-> GTT through the upstream code on this device * (ttm_evict_check.c). */ void ttm_evict_check(void); diff --git a/linuxu/tests/test_display_pipeline.c b/linuxu/tests/test_display_pipeline.c new file mode 100644 index 0000000..cc38a62 --- /dev/null +++ b/linuxu/tests/test_display_pipeline.c @@ -0,0 +1,332 @@ +/* The display output pipeline offline (rt/display.h, rt/surface.h): the CS + * fixture device (GART, VM, rings, two software SDMA engines that execute + * what upstream submits) with the fixture DCN 4.0.1 display of + * test-dm-offline on it, the unmodified amdgpu_dm and Display Core. + * + * A client surface (three host allocations as DMA segments) is imported, + * an output is lit on a sink, and frames are presented: each PRESENT only + * queues; the output's worker copies with SDMA into one of three + * framebuffers and flips with a nonblocking commit whose out-fence the + * fixture's "vblank" signals: a thread that raises the HUBP flip + * interrupts through amdgpu's interrupt source, as the IH would, every + * 16 ms. Checked: the scanned-out buffer holds the frame; damage-only + * copies; frames replaced in the mailbox while no flip can happen; a whole + * frame split over both SDMA engines; latency and counters; the output + * stopped and the screen restored. */ +#include +#include +#include +#include +#include +extern int usleep(unsigned int usec); + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "amdgpu.h" +#include "amdgpu_dm.h" +#include "dcn/dcn_4_1_0_offset.h" +#include "ivsrcid/dcn/irqsrcs_dcn_1_0.h" +#include "soc15_ih_clientid.h" +#include "cs_fixture.h" +#include "dcn401_fixture.h" + +#define CHECK(c) do { if (!(c)) { fprintf(stderr, "%s:%d: CHECK failed: %s\n", \ + __FILE__, __LINE__, #c); abort(); } } while (0) + +extern const struct amdgpu_ip_block_version dm_ip_block; +extern int fw_table_register_embedded(void); +extern int drm_edid_override_set(struct drm_connector *connector, const void *edid, size_t size); +extern u64 ktime_get_ns(void); + +#define W 1920u +#define H 1080u +#define PITCH (W * 4) +#define PAGE (16u * 1024u) + +static struct amdgpu_device *adev; + +static void display_init(struct amdgpu_device *a) +{ + struct amdgpu_ip_block block = { .adev = a, .version = &dm_ip_block }; + + drm_mode_config_init(adev_to_drm(a)); + a->firmware.load_type = AMDGPU_FW_LOAD_PSP; + a->ip_versions[MMHUB_HWIP][0] = IP_VERSION(4, 1, 0); + dcn401_fixture_attach(a); + dcn401_fixture_vbios(a); + CHECK(block.version->funcs->early_init(&block) == 0); + CHECK(block.version->funcs->sw_init(&block) == 0); + CHECK(block.version->funcs->hw_init(&block) == 0); +} + +/* ---- the fixture's vblank: flip interrupts and frame counters ---- */ +static volatile int vblank_run = 1, vblank_hold; +static unsigned long vblanks; + +static void raise_irq(unsigned int src_id) +{ + struct amdgpu_irq_src *src = adev->irq.client[SOC15_IH_CLIENTID_DCE].sources ? + adev->irq.client[SOC15_IH_CLIENTID_DCE].sources[src_id] : NULL; + struct amdgpu_iv_entry entry = { .client_id = SOC15_IH_CLIENTID_DCE, .src_id = src_id }; + + if (src && src->funcs && src->funcs->process) + src->funcs->process(adev, src, &entry); +} + +static void *vblank_main(void *arg) +{ + (void)arg; + while (vblank_run) { + usleep(16000); + if (vblank_hold) + continue; + for (int i = 0; i < 4; i++) { + uint32_t reg = dcn401_dce_base[regOTG0_OTG_STATUS_FRAME_COUNT_BASE_IDX] + + regOTG0_OTG_STATUS_FRAME_COUNT + i * (regOTG1_OTG_H_TOTAL - regOTG0_OTG_H_TOTAL); + + WREG32(reg, RREG32(reg) + 1); + } + for (int i = 0; i < 4; i++) + raise_irq(DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + i); + __atomic_add_fetch(&vblanks, 1, __ATOMIC_RELAXED); + } + return NULL; +} + +/* ---- a client surface in three DMA segments ---- */ +struct fake_surface { + uint8_t *run[3]; + uint64_t run_bytes[3], size; + struct rt_surface_segment segment[3]; + int releases; +}; + +static uint32_t *pixel(struct fake_surface *s, uint32_t x, uint32_t y) +{ + uint64_t offset = (uint64_t)y * PITCH + x * 4; + + for (int i = 0; i < 3; i++) { + if (offset < s->run_bytes[i]) + return (uint32_t *)(s->run[i] + offset); + offset -= s->run_bytes[i]; + } + return NULL; +} + +static void fake_init(struct fake_surface *s) +{ + uint64_t pages = ((uint64_t)PITCH * H + PAGE - 1) / PAGE; + const uint64_t split[3] = { pages / 3, pages / 3, pages - 2 * (pages / 3) }; + + memset(s, 0, sizeof(*s)); + s->size = pages * PAGE; + for (int i = 0; i < 3; i++) { + s->run_bytes[i] = split[i] * PAGE; + s->run[i] = aligned_alloc(PAGE, s->run_bytes[i]); + CHECK(s->run[i]); + s->segment[i] = (struct rt_surface_segment){ (uint64_t)(uintptr_t)s->run[i], s->run_bytes[i] }; + } +} + +static void fake_fill(struct fake_surface *s, uint32_t value, const struct rt_surface_rect *r) +{ + struct rt_surface_rect all = { 0, 0, W, H }; + + if (!r) + r = &all; + for (uint32_t y = r->y; y < r->y + r->height; y++) + for (uint32_t x = r->x; x < r->x + r->width; x++) + *pixel(s, x, y) = value ^ (x << 12) ^ y; +} + +static void provider_release(void *context) +{ + ((struct fake_surface *)context)->releases++; +} + +/* The buffer HUBP0 scans out, as the CPU sees it. */ +static uint32_t screen_pixel(uint32_t x, uint32_t y) +{ + uint32_t lo = RREG32(dcn401_dce_base[regHUBPREQ0_DCSURF_PRIMARY_SURFACE_ADDRESS_BASE_IDX] + + regHUBPREQ0_DCSURF_PRIMARY_SURFACE_ADDRESS); + uint32_t hi = RREG32(dcn401_dce_base[regHUBPREQ0_DCSURF_PRIMARY_SURFACE_ADDRESS_HIGH_BASE_IDX] + + regHUBPREQ0_DCSURF_PRIMARY_SURFACE_ADDRESS_HIGH); + uint8_t *fb = cs_fixture_vram_host(((uint64_t)hi << 32) | lo); + + CHECK(fb); + return *(uint32_t *)(fb + (size_t)y * PITCH + x * 4); +} + +static struct rt_display_present_stats wait_flipped(struct pci_dev *pdev, uint64_t flipped) +{ + struct rt_display_present_stats st; + + for (int i = 0; i < 400; i++) { + usleep(5000); + CHECK(rt_display_stats(pdev, &st) == 0); + if (st.frames_flipped >= flipped || st.error) + break; + } + return st; +} + +int main(void) +{ + struct fake_surface surf; + struct rt_surface_provider provider = { provider_release, &surf }; + struct rt_display_report report; + struct rt_display_present_stats st; + struct cs_fixture_stats before, after; + struct drm_connector_list_iter iter; + struct drm_connector *connector, *hdmi = NULL; + struct rt_surface *surface; + struct pci_dev *pdev; + pthread_t vblank; + uint32_t handle; + int r; + + CHECK(fw_table_register_embedded() == 0); + cs_fixture_sdma_instances = 2; + cs_fixture_display = display_init; + pdev = cs_fixture_init(); + adev = cs_fixture_adev(); + + /* A sink on HDMI-A-1 (forced on with a synthetic EDID). */ + dcn401_fixture_build_edid(); + drm_connector_list_iter_begin(adev_to_drm(adev), &iter); + drm_for_each_connector_iter(connector, &iter) + if (!strcmp(connector->name, "HDMI-A-1")) + hdmi = connector; + drm_connector_list_iter_end(&iter); + CHECK(hdmi); + hdmi->force = DRM_FORCE_ON; + CHECK(drm_edid_override_set(hdmi, dcn401_fixture_edid, sizeof(dcn401_fixture_edid)) == 0); + CHECK(rt_display_probe(pdev, &report) == 0); + + CHECK(pthread_create(&vblank, NULL, vblank_main, NULL) == 0); + r = rt_display_output(pdev, "HDMI-A-1", W, H, 60000, &report); + printf("pipeline: output -> %d (commit %d)\n", r, report.commit_status); + CHECK(r == 0 && report.showing && report.pattern == RT_DISPLAY_PATTERN_OUTPUT); + + fake_init(&surf); + fake_fill(&surf, 0x00a00000u, NULL); + CHECK(rt_surface_import(pdev, surf.segment, 3, surf.size, W, H, PITCH, &provider, &surface) == 0); + handle = rt_surface_add(1, surface); + CHECK(handle); + + /* Frame 1: the whole frame (every buffer starts stale), on both + * engines. PRESENT returns before anything ran. */ + { + const struct rt_surface_rect all = { 0, 0, W, H }; + u64 t0 = ktime_get_ns(), dt; + + cs_fixture_stats(&before); + r = rt_display_present(pdev, rt_surface_get_hold(1, handle), &all, 1, ktime_get_ns(), &st); + dt = ktime_get_ns() - t0; + printf("pipeline: present 1 -> %d in %llu us (queued: received %llu, flipped %llu)\n", r, + (unsigned long long)dt / 1000, (unsigned long long)st.frames_received, + (unsigned long long)st.frames_flipped); + CHECK(r == 0 && st.version == 2 && st.engines == 2 && st.frames_received == 1); + st = wait_flipped(pdev, 1); + cs_fixture_stats(&after); + printf("pipeline: frame 1 flipped: %llu bytes in %llu job(s), copy %llu us, latency %llu us, " + "%lu SDMA copy packets\n", (unsigned long long)st.bytes, (unsigned long long)st.copy_jobs, + (unsigned long long)st.last_copy_gpu_ns / 1000, + (unsigned long long)st.last_latency_ns / 1000, after.copies - before.copies); + CHECK(!st.error && st.frames_flipped == 1 && st.full_frames == 1); + CHECK(st.bytes == (uint64_t)PITCH * H && st.copy_jobs == 2); + CHECK(st.last_latency_ns > 0 && after.faults == 0 && after.dart_faults == 0); + CHECK(screen_pixel(0, 0) == (0x00a00000u ^ 0) && screen_pixel(W - 1, H - 1) == + (0x00a00000u ^ ((W - 1) << 12) ^ (H - 1))); + } + + /* Frames 2-4, one at a time (each flips before the next): the worker + * alternates between the two buffers not on screen. Frame 2 lands in + * the buffer the output started on, stale, so it is copied whole; + * frame 3 in frame 1's buffer: frame 2's damage and its own; frame 4 + * in frame 2's: frame 3's damage and its own. */ + { + const struct rt_surface_rect box[3] = { { 100, 100, 200, 50 }, { 400, 300, 64, 64 }, + { 0, 1000, W, 80 } }; + + for (int f = 0; f < 3; f++) { + fake_fill(&surf, 0x00b00000u + (uint32_t)f, &box[f]); + r = rt_display_present(pdev, rt_surface_get_hold(1, handle), &box[f], 1, ktime_get_ns(), &st); + CHECK(r == 0); + st = wait_flipped(pdev, 2 + (uint64_t)f); + printf("pipeline: frame %d flipped: %llu bytes total, last %llu, full frames %u\n", 2 + f, + (unsigned long long)st.bytes, (unsigned long long)st.last_bytes, st.full_frames); + CHECK(!st.error && st.frames_flipped == 2 + (uint64_t)f); + if (f == 1) + CHECK(st.last_bytes == 200 * 4 * 50 + 64 * 4 * 64); + } + CHECK(st.full_frames == 2); + CHECK(st.last_bytes == (uint64_t)W * 4 * 80 + 64 * 4 * 64); + CHECK(screen_pixel(150, 120) == ((0x00b00000u) ^ (150u << 12) ^ 120u)); + CHECK(screen_pixel(410, 310) == ((0x00b00001u) ^ (410u << 12) ^ 310u)); + CHECK(screen_pixel(5, 1010) == ((0x00b00002u) ^ (5u << 12) ^ 1010u)); + CHECK(screen_pixel(1000, 500) == ((0x00a00000u) ^ (1000u << 12) ^ 500u)); + } + + /* No vblank: frames pile up in the mailbox, the newest wins, the + * damage of the replaced ones is kept. */ + { + const struct rt_surface_rect a = { 10, 10, 10, 10 }, b = { 50, 50, 10, 10 }; + uint64_t flipped; + + st = wait_flipped(pdev, 4); + flipped = st.frames_flipped; + vblank_hold = 1; + usleep(40000); + for (int f = 0; f < 4; f++) { + fake_fill(&surf, 0x00c00000u + (uint32_t)f, (f & 1) ? &b : &a); + CHECK(rt_display_present(pdev, rt_surface_get_hold(1, handle), (f & 1) ? &b : &a, 1, + ktime_get_ns(), &st) == 0); + usleep(5000); + } + CHECK(st.frames_replaced >= 1); + vblank_hold = 0; + st = wait_flipped(pdev, flipped + 2); + usleep(100000); + CHECK(rt_display_stats(pdev, &st) == 0); + printf("pipeline: 4 frames while no flip: received %llu, replaced %llu, flipped %llu\n", + (unsigned long long)st.frames_received, (unsigned long long)st.frames_replaced, + (unsigned long long)st.frames_flipped); + CHECK(!st.error && st.frames_flipped < flipped + 4); + CHECK(screen_pixel(15, 15) == ((0x00c00002u) ^ (15u << 12) ^ 15u)); + CHECK(screen_pixel(55, 55) == ((0x00c00003u) ^ (55u << 12) ^ 55u)); + } + + /* A frame of another size is refused; nothing breaks. */ + CHECK(rt_display_stats(pdev, &st) == 0 && !st.error); + printf("pipeline: average copy %llu us, latency %llu us (max %llu), worker submit %llu us per frame\n", + (unsigned long long)(st.copy_gpu_ns / st.frames_flipped / 1000), + (unsigned long long)(st.latency_ns / st.frames_flipped / 1000), + (unsigned long long)st.latency_max_ns / 1000, + (unsigned long long)(st.copy_submit_ns / st.frames_flipped / 1000)); + + /* Off: the worker stops, the screen is restored, no frame is lost + * in flight. */ + CHECK(rt_display_off(pdev, &report) == 0 && !report.showing && !rt_display_showing()); + CHECK(rt_display_present(pdev, rt_surface_get_hold(1, handle), NULL, 0, 0, &st) == -ENOENT); + CHECK(rt_surface_remove(1, handle) == 0); + for (int i = 0; i < 5000 && !surf.releases; i++) + usleep(1000); + CHECK(surf.releases == 1); + vblank_run = 0; + pthread_join(vblank, NULL); + cs_fixture_stats(&after); + CHECK(after.faults == 0 && after.dart_faults == 0); + printf("PASS display pipeline: queued presents, SDMA copies on two engines into three buffers, " + "nonblocking flips on the flip interrupt, damage tracking, mailbox, stop (%lu vblanks)\n", + vblanks); + cs_fixture_stop(); + return 0; +} diff --git a/scripts/test-display-pipeline.sh b/scripts/test-display-pipeline.sh new file mode 100755 index 0000000..1d657b8 --- /dev/null +++ b/scripts/test-display-pipeline.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# The display output pipeline offline: queued presents, SDMA copies on two +# engines, nonblocking flips on the flip interrupt, on the CS fixture with +# the fixture DCN 4.0.1 display (linuxu/tests/test_display_pipeline.c). +set -euo pipefail +cd "$(dirname "$0")/.." +make -s lib >/dev/null +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +cat > "$work/flags.mk" <<'MAKE' +.PHONY: print-includes +print-includes: + @printf '%s\n' $(INCPATHS) +.PHONY: print-hostcflags +print-hostcflags: + @printf '%s\n' $(filter-out -MMD -MP -DLINUXU_RT_HOST_SHADOW=1,$(HOSTCFLAGS)) +MAKE +include_string=$(make -s -f Makefile -f "$work/flags.mk" print-includes | tr '\n' ' ') +read -r -a includes <<< "$include_string" +host_string=$(make -s -f Makefile -f "$work/flags.mk" print-hostcflags | tr '\n' ' ') +read -r -a hostcflags <<< "$host_string" +cflags=("${hostcflags[@]}" -g -O1 "${includes[@]}") +# The fixture's GART table and VRAM are host memory. The library's host +# build routes readX/writeX through synthetic MMIO tokens, which would drop +# the GART PTE writes (amdgpu_gmc_set_pte_pde uses writeq); these two +# upstream files are rebuilt with plain-memory accessors, as the KFD session +# test builds its doorbell code, and take the archive members' place. +plain=() +for source in third_party/linux/drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c \ + third_party/linux/drivers/gpu/drm/amd/amdgpu/amdgpu_gart.c; do + object="$work/$(basename "$source" .c).o" + clang "${cflags[@]}" -c "$source" -o "$object" + plain+=("$object") +done +clang "${cflags[@]}" -fsanitize=address \ + linuxu/tests/test_display_pipeline.c linuxu/tests/cs_fixture.c linuxu/tests/dcn401_fixture.c \ + "${plain[@]}" build/libmacamgdu.a \ + -lpthread -o "$work/test_display_pipeline" +# DISPLAY_PIPELINE_KEEP= keeps the binary for a debugger; CS_FIXTURE_TRACE=1 +# traces what the software engines execute. +if [ -n "${DISPLAY_PIPELINE_KEEP:-}" ]; then cp "$work/test_display_pipeline" "$DISPLAY_PIPELINE_KEEP"; fi +"$work/test_display_pipeline"