1 // SPDX-License-Identifier: MIT
2 /*
3 * Copyright © 2014 Intel Corporation
4 */
5
6 /**
7 * DOC: Logical Rings, Logical Ring Contexts and Execlists
8 *
9 * Motivation:
10 * GEN8 brings an expansion of the HW contexts: "Logical Ring Contexts".
11 * These expanded contexts enable a number of new abilities, especially
12 * "Execlists" (also implemented in this file).
13 *
14 * One of the main differences with the legacy HW contexts is that logical
15 * ring contexts incorporate many more things to the context's state, like
16 * PDPs or ringbuffer control registers:
17 *
18 * The reason why PDPs are included in the context is straightforward: as
19 * PPGTTs (per-process GTTs) are actually per-context, having the PDPs
20 * contained there mean you don't need to do a ppgtt->switch_mm yourself,
21 * instead, the GPU will do it for you on the context switch.
22 *
23 * But, what about the ringbuffer control registers (head, tail, etc..)?
24 * shouldn't we just need a set of those per engine command streamer? This is
25 * where the name "Logical Rings" starts to make sense: by virtualizing the
26 * rings, the engine cs shifts to a new "ring buffer" with every context
27 * switch. When you want to submit a workload to the GPU you: A) choose your
28 * context, B) find its appropriate virtualized ring, C) write commands to it
29 * and then, finally, D) tell the GPU to switch to that context.
30 *
31 * Instead of the legacy MI_SET_CONTEXT, the way you tell the GPU to switch
32 * to a contexts is via a context execution list, ergo "Execlists".
33 *
34 * LRC implementation:
35 * Regarding the creation of contexts, we have:
36 *
37 * - One global default context.
38 * - One local default context for each opened fd.
39 * - One local extra context for each context create ioctl call.
40 *
41 * Now that ringbuffers belong per-context (and not per-engine, like before)
42 * and that contexts are uniquely tied to a given engine (and not reusable,
43 * like before) we need:
44 *
45 * - One ringbuffer per-engine inside each context.
46 * - One backing object per-engine inside each context.
47 *
48 * The global default context starts its life with these new objects fully
49 * allocated and populated. The local default context for each opened fd is
50 * more complex, because we don't know at creation time which engine is going
51 * to use them. To handle this, we have implemented a deferred creation of LR
52 * contexts:
53 *
54 * The local context starts its life as a hollow or blank holder, that only
55 * gets populated for a given engine once we receive an execbuffer. If later
56 * on we receive another execbuffer ioctl for the same context but a different
57 * engine, we allocate/populate a new ringbuffer and context backing object and
58 * so on.
59 *
60 * Finally, regarding local contexts created using the ioctl call: as they are
61 * only allowed with the render ring, we can allocate & populate them right
62 * away (no need to defer anything, at least for now).
63 *
64 * Execlists implementation:
65 * Execlists are the new method by which, on gen8+ hardware, workloads are
66 * submitted for execution (as opposed to the legacy, ringbuffer-based, method).
67 * This method works as follows:
68 *
69 * When a request is committed, its commands (the BB start and any leading or
70 * trailing commands, like the seqno breadcrumbs) are placed in the ringbuffer
71 * for the appropriate context. The tail pointer in the hardware context is not
72 * updated at this time, but instead, kept by the driver in the ringbuffer
73 * structure. A structure representing this request is added to a request queue
74 * for the appropriate engine: this structure contains a copy of the context's
75 * tail after the request was written to the ring buffer and a pointer to the
76 * context itself.
77 *
78 * If the engine's request queue was empty before the request was added, the
79 * queue is processed immediately. Otherwise the queue will be processed during
80 * a context switch interrupt. In any case, elements on the queue will get sent
81 * (in pairs) to the GPU's ExecLists Submit Port (ELSP, for short) with a
82 * globally unique 20-bits submission ID.
83 *
84 * When execution of a request completes, the GPU updates the context status
85 * buffer with a context complete event and generates a context switch interrupt.
86 * During the interrupt handling, the driver examines the events in the buffer:
87 * for each context complete event, if the announced ID matches that on the head
88 * of the request queue, then that request is retired and removed from the queue.
89 *
90 * After processing, if any requests were retired and the queue is not empty
91 * then a new execution list can be submitted. The two requests at the front of
92 * the queue are next to be submitted but since a context may not occur twice in
93 * an execution list, if subsequent requests have the same ID as the first then
94 * the two requests must be combined. This is done simply by discarding requests
95 * at the head of the queue until either only one requests is left (in which case
96 * we use a NULL second context) or the first two requests have unique IDs.
97 *
98 * By always executing the first two requests in the queue the driver ensures
99 * that the GPU is kept as busy as possible. In the case where a single context
100 * completes but a second context is still executing, the request for this second
101 * context will be at the head of the queue when we remove the first one. This
102 * request will then be resubmitted along with a new request for a different context,
103 * which will cause the hardware to continue executing the second request and queue
104 * the new request (the GPU detects the condition of a context getting preempted
105 * with the same context and optimizes the context switch flow by not doing
106 * preemption, but just sampling the new tail pointer).
107 *
108 */
109 #include <linux/interrupt.h>
110
111 #include "i915_drv.h"
112 #include "i915_trace.h"
113 #include "i915_vgpu.h"
114 #include "gen8_engine_cs.h"
115 #include "intel_breadcrumbs.h"
116 #include "intel_context.h"
117 #include "intel_engine_heartbeat.h"
118 #include "intel_engine_pm.h"
119 #include "intel_engine_stats.h"
120 #include "intel_execlists_submission.h"
121 #include "intel_gt.h"
122 #include "intel_gt_irq.h"
123 #include "intel_gt_pm.h"
124 #include "intel_gt_requests.h"
125 #include "intel_lrc.h"
126 #include "intel_lrc_reg.h"
127 #include "intel_mocs.h"
128 #include "intel_reset.h"
129 #include "intel_ring.h"
130 #include "intel_workarounds.h"
131 #include "shmem_utils.h"
132
133 #define RING_EXECLIST_QFULL (1 << 0x2)
134 #define RING_EXECLIST1_VALID (1 << 0x3)
135 #define RING_EXECLIST0_VALID (1 << 0x4)
136 #define RING_EXECLIST_ACTIVE_STATUS (3 << 0xE)
137 #define RING_EXECLIST1_ACTIVE (1 << 0x11)
138 #define RING_EXECLIST0_ACTIVE (1 << 0x12)
139
140 #define GEN8_CTX_STATUS_IDLE_ACTIVE (1 << 0)
141 #define GEN8_CTX_STATUS_PREEMPTED (1 << 1)
142 #define GEN8_CTX_STATUS_ELEMENT_SWITCH (1 << 2)
143 #define GEN8_CTX_STATUS_ACTIVE_IDLE (1 << 3)
144 #define GEN8_CTX_STATUS_COMPLETE (1 << 4)
145 #define GEN8_CTX_STATUS_LITE_RESTORE (1 << 15)
146
147 #define GEN8_CTX_STATUS_COMPLETED_MASK \
148 (GEN8_CTX_STATUS_COMPLETE | GEN8_CTX_STATUS_PREEMPTED)
149
150 #define GEN12_CTX_STATUS_SWITCHED_TO_NEW_QUEUE (0x1) /* lower csb dword */
151 #define GEN12_CTX_SWITCH_DETAIL(csb_dw) ((csb_dw) & 0xF) /* upper csb dword */
152 #define GEN12_CSB_SW_CTX_ID_MASK GENMASK(25, 15)
153 #define GEN12_IDLE_CTX_ID 0x7FF
154 #define GEN12_CSB_CTX_VALID(csb_dw) \
155 (FIELD_GET(GEN12_CSB_SW_CTX_ID_MASK, csb_dw) != GEN12_IDLE_CTX_ID)
156
157 #define XEHP_CTX_STATUS_SWITCHED_TO_NEW_QUEUE BIT(1) /* upper csb dword */
158 #define XEHP_CSB_SW_CTX_ID_MASK GENMASK(31, 10)
159 #define XEHP_IDLE_CTX_ID 0xFFFF
160 #define XEHP_CSB_CTX_VALID(csb_dw) \
161 (FIELD_GET(XEHP_CSB_SW_CTX_ID_MASK, csb_dw) != XEHP_IDLE_CTX_ID)
162
163 /* Typical size of the average request (2 pipecontrols and a MI_BB) */
164 #define EXECLISTS_REQUEST_SIZE 64 /* bytes */
165
166 struct virtual_engine {
167 struct intel_engine_cs base;
168 struct intel_context context;
169 struct rcu_work rcu;
170
171 /*
172 * We allow only a single request through the virtual engine at a time
173 * (each request in the timeline waits for the completion fence of
174 * the previous before being submitted). By restricting ourselves to
175 * only submitting a single request, each request is placed on to a
176 * physical to maximise load spreading (by virtue of the late greedy
177 * scheduling -- each real engine takes the next available request
178 * upon idling).
179 */
180 struct i915_request *request;
181
182 /*
183 * We keep a rbtree of available virtual engines inside each physical
184 * engine, sorted by priority. Here we preallocate the nodes we need
185 * for the virtual engine, indexed by physical_engine->id.
186 */
187 struct ve_node {
188 struct rb_node rb;
189 int prio;
190 } nodes[I915_NUM_ENGINES];
191
192 /* And finally, which physical engines this virtual engine maps onto. */
193 unsigned int num_siblings;
194 struct intel_engine_cs *siblings[];
195 };
196
to_virtual_engine(struct intel_engine_cs * engine)197 static struct virtual_engine *to_virtual_engine(struct intel_engine_cs *engine)
198 {
199 GEM_BUG_ON(!intel_engine_is_virtual(engine));
200 return container_of(engine, struct virtual_engine, base);
201 }
202
203 static struct intel_context *
204 execlists_create_virtual(struct intel_engine_cs **siblings, unsigned int count);
205
206 static struct i915_request *
__active_request(const struct intel_timeline * const tl,struct i915_request * rq,int error)207 __active_request(const struct intel_timeline * const tl,
208 struct i915_request *rq,
209 int error)
210 {
211 struct i915_request *active = rq;
212
213 list_for_each_entry_from_reverse(rq, &tl->requests, link) {
214 if (__i915_request_is_complete(rq))
215 break;
216
217 if (error) {
218 i915_request_set_error_once(rq, error);
219 __i915_request_skip(rq);
220 }
221 active = rq;
222 }
223
224 return active;
225 }
226
227 static struct i915_request *
active_request(const struct intel_timeline * const tl,struct i915_request * rq)228 active_request(const struct intel_timeline * const tl, struct i915_request *rq)
229 {
230 return __active_request(tl, rq, 0);
231 }
232
ring_set_paused(const struct intel_engine_cs * engine,int state)233 static void ring_set_paused(const struct intel_engine_cs *engine, int state)
234 {
235 /*
236 * We inspect HWS_PREEMPT with a semaphore inside
237 * engine->emit_fini_breadcrumb. If the dword is true,
238 * the ring is paused as the semaphore will busywait
239 * until the dword is false.
240 */
241 engine->status_page.addr[I915_GEM_HWS_PREEMPT] = state;
242 if (state)
243 wmb();
244 }
245
to_priolist(struct rb_node * rb)246 static struct i915_priolist *to_priolist(struct rb_node *rb)
247 {
248 return rb_entry(rb, struct i915_priolist, node);
249 }
250
rq_prio(const struct i915_request * rq)251 static int rq_prio(const struct i915_request *rq)
252 {
253 return READ_ONCE(rq->sched.attr.priority);
254 }
255
effective_prio(const struct i915_request * rq)256 static int effective_prio(const struct i915_request *rq)
257 {
258 int prio = rq_prio(rq);
259
260 /*
261 * If this request is special and must not be interrupted at any
262 * cost, so be it. Note we are only checking the most recent request
263 * in the context and so may be masking an earlier vip request. It
264 * is hoped that under the conditions where nopreempt is used, this
265 * will not matter (i.e. all requests to that context will be
266 * nopreempt for as long as desired).
267 */
268 if (i915_request_has_nopreempt(rq))
269 prio = I915_PRIORITY_UNPREEMPTABLE;
270
271 return prio;
272 }
273
queue_prio(const struct i915_sched_engine * sched_engine)274 static int queue_prio(const struct i915_sched_engine *sched_engine)
275 {
276 struct rb_node *rb;
277
278 rb = rb_first_cached(&sched_engine->queue);
279 if (!rb)
280 return INT_MIN;
281
282 return to_priolist(rb)->priority;
283 }
284
virtual_prio(const struct intel_engine_execlists * el)285 static int virtual_prio(const struct intel_engine_execlists *el)
286 {
287 struct rb_node *rb = rb_first_cached(&el->virtual);
288
289 return rb ? rb_entry(rb, struct ve_node, rb)->prio : INT_MIN;
290 }
291
need_preempt(const struct intel_engine_cs * engine,const struct i915_request * rq)292 static bool need_preempt(const struct intel_engine_cs *engine,
293 const struct i915_request *rq)
294 {
295 int last_prio;
296
297 if (!intel_engine_has_semaphores(engine))
298 return false;
299
300 /*
301 * Check if the current priority hint merits a preemption attempt.
302 *
303 * We record the highest value priority we saw during rescheduling
304 * prior to this dequeue, therefore we know that if it is strictly
305 * less than the current tail of ESLP[0], we do not need to force
306 * a preempt-to-idle cycle.
307 *
308 * However, the priority hint is a mere hint that we may need to
309 * preempt. If that hint is stale or we may be trying to preempt
310 * ourselves, ignore the request.
311 *
312 * More naturally we would write
313 * prio >= max(0, last);
314 * except that we wish to prevent triggering preemption at the same
315 * priority level: the task that is running should remain running
316 * to preserve FIFO ordering of dependencies.
317 */
318 last_prio = max(effective_prio(rq), I915_PRIORITY_NORMAL - 1);
319 if (engine->sched_engine->queue_priority_hint <= last_prio)
320 return false;
321
322 /*
323 * Check against the first request in ELSP[1], it will, thanks to the
324 * power of PI, be the highest priority of that context.
325 */
326 if (!list_is_last(&rq->sched.link, &engine->sched_engine->requests) &&
327 rq_prio(list_next_entry(rq, sched.link)) > last_prio)
328 return true;
329
330 /*
331 * If the inflight context did not trigger the preemption, then maybe
332 * it was the set of queued requests? Pick the highest priority in
333 * the queue (the first active priolist) and see if it deserves to be
334 * running instead of ELSP[0].
335 *
336 * The highest priority request in the queue can not be either
337 * ELSP[0] or ELSP[1] as, thanks again to PI, if it was the same
338 * context, it's priority would not exceed ELSP[0] aka last_prio.
339 */
340 return max(virtual_prio(&engine->execlists),
341 queue_prio(engine->sched_engine)) > last_prio;
342 }
343
344 __maybe_unused static bool
assert_priority_queue(const struct i915_request * prev,const struct i915_request * next)345 assert_priority_queue(const struct i915_request *prev,
346 const struct i915_request *next)
347 {
348 /*
349 * Without preemption, the prev may refer to the still active element
350 * which we refuse to let go.
351 *
352 * Even with preemption, there are times when we think it is better not
353 * to preempt and leave an ostensibly lower priority request in flight.
354 */
355 if (i915_request_is_active(prev))
356 return true;
357
358 return rq_prio(prev) >= rq_prio(next);
359 }
360
361 static struct i915_request *
__unwind_incomplete_requests(struct intel_engine_cs * engine)362 __unwind_incomplete_requests(struct intel_engine_cs *engine)
363 {
364 struct i915_request *rq, *rn, *active = NULL;
365 struct list_head *pl;
366 int prio = I915_PRIORITY_INVALID;
367
368 lockdep_assert_held(&engine->sched_engine->lock);
369
370 list_for_each_entry_safe_reverse(rq, rn,
371 &engine->sched_engine->requests,
372 sched.link) {
373 if (__i915_request_is_complete(rq)) {
374 list_del_init(&rq->sched.link);
375 continue;
376 }
377
378 __i915_request_unsubmit(rq);
379
380 GEM_BUG_ON(rq_prio(rq) == I915_PRIORITY_INVALID);
381 if (rq_prio(rq) != prio) {
382 prio = rq_prio(rq);
383 pl = i915_sched_lookup_priolist(engine->sched_engine,
384 prio);
385 }
386 GEM_BUG_ON(i915_sched_engine_is_empty(engine->sched_engine));
387
388 list_move(&rq->sched.link, pl);
389 set_bit(I915_FENCE_FLAG_PQUEUE, &rq->fence.flags);
390
391 /* Check in case we rollback so far we wrap [size/2] */
392 if (intel_ring_direction(rq->ring,
393 rq->tail,
394 rq->ring->tail + 8) > 0)
395 rq->context->lrc.desc |= CTX_DESC_FORCE_RESTORE;
396
397 active = rq;
398 }
399
400 return active;
401 }
402
403 struct i915_request *
execlists_unwind_incomplete_requests(struct intel_engine_execlists * execlists)404 execlists_unwind_incomplete_requests(struct intel_engine_execlists *execlists)
405 {
406 struct intel_engine_cs *engine =
407 container_of(execlists, typeof(*engine), execlists);
408
409 return __unwind_incomplete_requests(engine);
410 }
411
412 static void
execlists_context_status_change(struct i915_request * rq,unsigned long status)413 execlists_context_status_change(struct i915_request *rq, unsigned long status)
414 {
415 /*
416 * Only used when GVT-g is enabled now. When GVT-g is disabled,
417 * The compiler should eliminate this function as dead-code.
418 */
419 if (!IS_ENABLED(CONFIG_DRM_I915_GVT))
420 return;
421
422 atomic_notifier_call_chain(&rq->engine->context_status_notifier,
423 status, rq);
424 }
425
reset_active(struct i915_request * rq,struct intel_engine_cs * engine)426 static void reset_active(struct i915_request *rq,
427 struct intel_engine_cs *engine)
428 {
429 struct intel_context * const ce = rq->context;
430 u32 head;
431
432 /*
433 * The executing context has been cancelled. We want to prevent
434 * further execution along this context and propagate the error on
435 * to anything depending on its results.
436 *
437 * In __i915_request_submit(), we apply the -EIO and remove the
438 * requests' payloads for any banned requests. But first, we must
439 * rewind the context back to the start of the incomplete request so
440 * that we do not jump back into the middle of the batch.
441 *
442 * We preserve the breadcrumbs and semaphores of the incomplete
443 * requests so that inter-timeline dependencies (i.e other timelines)
444 * remain correctly ordered. And we defer to __i915_request_submit()
445 * so that all asynchronous waits are correctly handled.
446 */
447 ENGINE_TRACE(engine, "{ reset rq=%llx:%lld }\n",
448 rq->fence.context, rq->fence.seqno);
449
450 /* On resubmission of the active request, payload will be scrubbed */
451 if (__i915_request_is_complete(rq))
452 head = rq->tail;
453 else
454 head = __active_request(ce->timeline, rq, -EIO)->head;
455 head = intel_ring_wrap(ce->ring, head);
456
457 /* Scrub the context image to prevent replaying the previous batch */
458 lrc_init_regs(ce, engine, true);
459
460 /* We've switched away, so this should be a no-op, but intent matters */
461 ce->lrc.lrca = lrc_update_regs(ce, engine, head);
462 }
463
bad_request(const struct i915_request * rq)464 static bool bad_request(const struct i915_request *rq)
465 {
466 return rq->fence.error && i915_request_started(rq);
467 }
468
469 static struct intel_engine_cs *
__execlists_schedule_in(struct i915_request * rq)470 __execlists_schedule_in(struct i915_request *rq)
471 {
472 struct intel_engine_cs * const engine = rq->engine;
473 struct intel_context * const ce = rq->context;
474
475 intel_context_get(ce);
476
477 if (unlikely(intel_context_is_closed(ce) &&
478 !intel_engine_has_heartbeat(engine)))
479 intel_context_set_banned(ce);
480
481 if (unlikely(intel_context_is_banned(ce) || bad_request(rq)))
482 reset_active(rq, engine);
483
484 if (IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM))
485 lrc_check_regs(ce, engine, "before");
486
487 if (ce->tag) {
488 /* Use a fixed tag for OA and friends */
489 GEM_BUG_ON(ce->tag <= BITS_PER_LONG);
490 ce->lrc.ccid = ce->tag;
491 } else if (GRAPHICS_VER_FULL(engine->i915) >= IP_VER(12, 50)) {
492 /* We don't need a strict matching tag, just different values */
493 unsigned int tag = ffs(READ_ONCE(engine->context_tag));
494
495 GEM_BUG_ON(tag == 0 || tag >= BITS_PER_LONG);
496 clear_bit(tag - 1, &engine->context_tag);
497 ce->lrc.ccid = tag << (XEHP_SW_CTX_ID_SHIFT - 32);
498
499 BUILD_BUG_ON(BITS_PER_LONG > GEN12_MAX_CONTEXT_HW_ID);
500
501 } else {
502 /* We don't need a strict matching tag, just different values */
503 unsigned int tag = __ffs(engine->context_tag);
504
505 GEM_BUG_ON(tag >= BITS_PER_LONG);
506 __clear_bit(tag, &engine->context_tag);
507 ce->lrc.ccid = (1 + tag) << (GEN11_SW_CTX_ID_SHIFT - 32);
508
509 BUILD_BUG_ON(BITS_PER_LONG > GEN12_MAX_CONTEXT_HW_ID);
510 }
511
512 ce->lrc.ccid |= engine->execlists.ccid;
513
514 __intel_gt_pm_get(engine->gt);
515 if (engine->fw_domain && !engine->fw_active++)
516 intel_uncore_forcewake_get(engine->uncore, engine->fw_domain);
517 execlists_context_status_change(rq, INTEL_CONTEXT_SCHEDULE_IN);
518 intel_engine_context_in(engine);
519
520 CE_TRACE(ce, "schedule-in, ccid:%x\n", ce->lrc.ccid);
521
522 return engine;
523 }
524
execlists_schedule_in(struct i915_request * rq,int idx)525 static void execlists_schedule_in(struct i915_request *rq, int idx)
526 {
527 struct intel_context * const ce = rq->context;
528 struct intel_engine_cs *old;
529
530 GEM_BUG_ON(!intel_engine_pm_is_awake(rq->engine));
531 trace_i915_request_in(rq, idx);
532
533 old = ce->inflight;
534 if (!old)
535 old = __execlists_schedule_in(rq);
536 WRITE_ONCE(ce->inflight, ptr_inc(old));
537
538 GEM_BUG_ON(intel_context_inflight(ce) != rq->engine);
539 }
540
541 static void
resubmit_virtual_request(struct i915_request * rq,struct virtual_engine * ve)542 resubmit_virtual_request(struct i915_request *rq, struct virtual_engine *ve)
543 {
544 struct intel_engine_cs *engine = rq->engine;
545
546 spin_lock_irq(&engine->sched_engine->lock);
547
548 clear_bit(I915_FENCE_FLAG_PQUEUE, &rq->fence.flags);
549 WRITE_ONCE(rq->engine, &ve->base);
550 ve->base.submit_request(rq);
551
552 spin_unlock_irq(&engine->sched_engine->lock);
553 }
554
kick_siblings(struct i915_request * rq,struct intel_context * ce)555 static void kick_siblings(struct i915_request *rq, struct intel_context *ce)
556 {
557 struct virtual_engine *ve = container_of(ce, typeof(*ve), context);
558 struct intel_engine_cs *engine = rq->engine;
559
560 /*
561 * After this point, the rq may be transferred to a new sibling, so
562 * before we clear ce->inflight make sure that the context has been
563 * removed from the b->signalers and furthermore we need to make sure
564 * that the concurrent iterator in signal_irq_work is no longer
565 * following ce->signal_link.
566 */
567 if (!list_empty(&ce->signals))
568 intel_context_remove_breadcrumbs(ce, engine->breadcrumbs);
569
570 /*
571 * This engine is now too busy to run this virtual request, so
572 * see if we can find an alternative engine for it to execute on.
573 * Once a request has become bonded to this engine, we treat it the
574 * same as other native request.
575 */
576 if (i915_request_in_priority_queue(rq) &&
577 rq->execution_mask != engine->mask)
578 resubmit_virtual_request(rq, ve);
579
580 if (READ_ONCE(ve->request))
581 tasklet_hi_schedule(&ve->base.sched_engine->tasklet);
582 }
583
__execlists_schedule_out(struct i915_request * const rq,struct intel_context * const ce)584 static void __execlists_schedule_out(struct i915_request * const rq,
585 struct intel_context * const ce)
586 {
587 struct intel_engine_cs * const engine = rq->engine;
588 unsigned int ccid;
589
590 /*
591 * NB process_csb() is not under the engine->sched_engine->lock and hence
592 * schedule_out can race with schedule_in meaning that we should
593 * refrain from doing non-trivial work here.
594 */
595
596 CE_TRACE(ce, "schedule-out, ccid:%x\n", ce->lrc.ccid);
597 GEM_BUG_ON(ce->inflight != engine);
598
599 if (IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM))
600 lrc_check_regs(ce, engine, "after");
601
602 /*
603 * If we have just completed this context, the engine may now be
604 * idle and we want to re-enter powersaving.
605 */
606 if (intel_timeline_is_last(ce->timeline, rq) &&
607 __i915_request_is_complete(rq))
608 intel_engine_add_retire(engine, ce->timeline);
609
610 ccid = ce->lrc.ccid;
611 if (GRAPHICS_VER_FULL(engine->i915) >= IP_VER(12, 50)) {
612 ccid >>= XEHP_SW_CTX_ID_SHIFT - 32;
613 ccid &= XEHP_MAX_CONTEXT_HW_ID;
614 } else {
615 ccid >>= GEN11_SW_CTX_ID_SHIFT - 32;
616 ccid &= GEN12_MAX_CONTEXT_HW_ID;
617 }
618
619 if (ccid < BITS_PER_LONG) {
620 GEM_BUG_ON(ccid == 0);
621 GEM_BUG_ON(test_bit(ccid - 1, &engine->context_tag));
622 __set_bit(ccid - 1, &engine->context_tag);
623 }
624
625 lrc_update_runtime(ce);
626 intel_engine_context_out(engine);
627 execlists_context_status_change(rq, INTEL_CONTEXT_SCHEDULE_OUT);
628 if (engine->fw_domain && !--engine->fw_active)
629 intel_uncore_forcewake_put(engine->uncore, engine->fw_domain);
630 intel_gt_pm_put_async(engine->gt);
631
632 /*
633 * If this is part of a virtual engine, its next request may
634 * have been blocked waiting for access to the active context.
635 * We have to kick all the siblings again in case we need to
636 * switch (e.g. the next request is not runnable on this
637 * engine). Hopefully, we will already have submitted the next
638 * request before the tasklet runs and do not need to rebuild
639 * each virtual tree and kick everyone again.
640 */
641 if (ce->engine != engine)
642 kick_siblings(rq, ce);
643
644 WRITE_ONCE(ce->inflight, NULL);
645 intel_context_put(ce);
646 }
647
execlists_schedule_out(struct i915_request * rq)648 static inline void execlists_schedule_out(struct i915_request *rq)
649 {
650 struct intel_context * const ce = rq->context;
651
652 trace_i915_request_out(rq);
653
654 GEM_BUG_ON(!ce->inflight);
655 ce->inflight = ptr_dec(ce->inflight);
656 if (!__intel_context_inflight_count(ce->inflight))
657 __execlists_schedule_out(rq, ce);
658
659 i915_request_put(rq);
660 }
661
execlists_update_context(struct i915_request * rq)662 static u64 execlists_update_context(struct i915_request *rq)
663 {
664 struct intel_context *ce = rq->context;
665 u64 desc = ce->lrc.desc;
666 u32 tail, prev;
667
668 /*
669 * WaIdleLiteRestore:bdw,skl
670 *
671 * We should never submit the context with the same RING_TAIL twice
672 * just in case we submit an empty ring, which confuses the HW.
673 *
674 * We append a couple of NOOPs (gen8_emit_wa_tail) after the end of
675 * the normal request to be able to always advance the RING_TAIL on
676 * subsequent resubmissions (for lite restore). Should that fail us,
677 * and we try and submit the same tail again, force the context
678 * reload.
679 *
680 * If we need to return to a preempted context, we need to skip the
681 * lite-restore and force it to reload the RING_TAIL. Otherwise, the
682 * HW has a tendency to ignore us rewinding the TAIL to the end of
683 * an earlier request.
684 */
685 GEM_BUG_ON(ce->lrc_reg_state[CTX_RING_TAIL] != rq->ring->tail);
686 prev = rq->ring->tail;
687 tail = intel_ring_set_tail(rq->ring, rq->tail);
688 if (unlikely(intel_ring_direction(rq->ring, tail, prev) <= 0))
689 desc |= CTX_DESC_FORCE_RESTORE;
690 ce->lrc_reg_state[CTX_RING_TAIL] = tail;
691 rq->tail = rq->wa_tail;
692
693 /*
694 * Make sure the context image is complete before we submit it to HW.
695 *
696 * Ostensibly, writes (including the WCB) should be flushed prior to
697 * an uncached write such as our mmio register access, the empirical
698 * evidence (esp. on Braswell) suggests that the WC write into memory
699 * may not be visible to the HW prior to the completion of the UC
700 * register write and that we may begin execution from the context
701 * before its image is complete leading to invalid PD chasing.
702 */
703 wmb();
704
705 ce->lrc.desc &= ~CTX_DESC_FORCE_RESTORE;
706 return desc;
707 }
708
write_desc(struct intel_engine_execlists * execlists,u64 desc,u32 port)709 static void write_desc(struct intel_engine_execlists *execlists, u64 desc, u32 port)
710 {
711 if (execlists->ctrl_reg) {
712 writel(lower_32_bits(desc), execlists->submit_reg + port * 2);
713 writel(upper_32_bits(desc), execlists->submit_reg + port * 2 + 1);
714 } else {
715 writel(upper_32_bits(desc), execlists->submit_reg);
716 writel(lower_32_bits(desc), execlists->submit_reg);
717 }
718 }
719
720 static __maybe_unused char *
dump_port(char * buf,int buflen,const char * prefix,struct i915_request * rq)721 dump_port(char *buf, int buflen, const char *prefix, struct i915_request *rq)
722 {
723 if (!rq)
724 return "";
725
726 snprintf(buf, buflen, "%sccid:%x %llx:%lld%s prio %d",
727 prefix,
728 rq->context->lrc.ccid,
729 rq->fence.context, rq->fence.seqno,
730 __i915_request_is_complete(rq) ? "!" :
731 __i915_request_has_started(rq) ? "*" :
732 "",
733 rq_prio(rq));
734
735 return buf;
736 }
737
738 static __maybe_unused noinline void
trace_ports(const struct intel_engine_execlists * execlists,const char * msg,struct i915_request * const * ports)739 trace_ports(const struct intel_engine_execlists *execlists,
740 const char *msg,
741 struct i915_request * const *ports)
742 {
743 const struct intel_engine_cs *engine =
744 container_of(execlists, typeof(*engine), execlists);
745 char __maybe_unused p0[40], p1[40];
746
747 if (!ports[0])
748 return;
749
750 ENGINE_TRACE(engine, "%s { %s%s }\n", msg,
751 dump_port(p0, sizeof(p0), "", ports[0]),
752 dump_port(p1, sizeof(p1), ", ", ports[1]));
753 }
754
755 static bool
reset_in_progress(const struct intel_engine_cs * engine)756 reset_in_progress(const struct intel_engine_cs *engine)
757 {
758 return unlikely(!__tasklet_is_enabled(&engine->sched_engine->tasklet));
759 }
760
761 static __maybe_unused noinline bool
assert_pending_valid(const struct intel_engine_execlists * execlists,const char * msg)762 assert_pending_valid(const struct intel_engine_execlists *execlists,
763 const char *msg)
764 {
765 struct intel_engine_cs *engine =
766 container_of(execlists, typeof(*engine), execlists);
767 struct i915_request * const *port, *rq, *prev = NULL;
768 struct intel_context *ce = NULL;
769 u32 ccid = -1;
770
771 trace_ports(execlists, msg, execlists->pending);
772
773 /* We may be messing around with the lists during reset, lalala */
774 if (reset_in_progress(engine))
775 return true;
776
777 if (!execlists->pending[0]) {
778 GEM_TRACE_ERR("%s: Nothing pending for promotion!\n",
779 engine->name);
780 return false;
781 }
782
783 if (execlists->pending[execlists_num_ports(execlists)]) {
784 GEM_TRACE_ERR("%s: Excess pending[%d] for promotion!\n",
785 engine->name, execlists_num_ports(execlists));
786 return false;
787 }
788
789 for (port = execlists->pending; (rq = *port); port++) {
790 unsigned long flags;
791 bool ok = true;
792
793 GEM_BUG_ON(!kref_read(&rq->fence.refcount));
794 GEM_BUG_ON(!i915_request_is_active(rq));
795
796 if (ce == rq->context) {
797 GEM_TRACE_ERR("%s: Dup context:%llx in pending[%zd]\n",
798 engine->name,
799 ce->timeline->fence_context,
800 port - execlists->pending);
801 return false;
802 }
803 ce = rq->context;
804
805 if (ccid == ce->lrc.ccid) {
806 GEM_TRACE_ERR("%s: Dup ccid:%x context:%llx in pending[%zd]\n",
807 engine->name,
808 ccid, ce->timeline->fence_context,
809 port - execlists->pending);
810 return false;
811 }
812 ccid = ce->lrc.ccid;
813
814 /*
815 * Sentinels are supposed to be the last request so they flush
816 * the current execution off the HW. Check that they are the only
817 * request in the pending submission.
818 *
819 * NB: Due to the async nature of preempt-to-busy and request
820 * cancellation we need to handle the case where request
821 * becomes a sentinel in parallel to CSB processing.
822 */
823 if (prev && i915_request_has_sentinel(prev) &&
824 !READ_ONCE(prev->fence.error)) {
825 GEM_TRACE_ERR("%s: context:%llx after sentinel in pending[%zd]\n",
826 engine->name,
827 ce->timeline->fence_context,
828 port - execlists->pending);
829 return false;
830 }
831 prev = rq;
832
833 /*
834 * We want virtual requests to only be in the first slot so
835 * that they are never stuck behind a hog and can be immediately
836 * transferred onto the next idle engine.
837 */
838 if (rq->execution_mask != engine->mask &&
839 port != execlists->pending) {
840 GEM_TRACE_ERR("%s: virtual engine:%llx not in prime position[%zd]\n",
841 engine->name,
842 ce->timeline->fence_context,
843 port - execlists->pending);
844 return false;
845 }
846
847 /* Hold tightly onto the lock to prevent concurrent retires! */
848 if (!spin_trylock_irqsave(&rq->lock, flags))
849 continue;
850
851 if (__i915_request_is_complete(rq))
852 goto unlock;
853
854 if (i915_active_is_idle(&ce->active) &&
855 !intel_context_is_barrier(ce)) {
856 GEM_TRACE_ERR("%s: Inactive context:%llx in pending[%zd]\n",
857 engine->name,
858 ce->timeline->fence_context,
859 port - execlists->pending);
860 ok = false;
861 goto unlock;
862 }
863
864 if (!i915_vma_is_pinned(ce->state)) {
865 GEM_TRACE_ERR("%s: Unpinned context:%llx in pending[%zd]\n",
866 engine->name,
867 ce->timeline->fence_context,
868 port - execlists->pending);
869 ok = false;
870 goto unlock;
871 }
872
873 if (!i915_vma_is_pinned(ce->ring->vma)) {
874 GEM_TRACE_ERR("%s: Unpinned ring:%llx in pending[%zd]\n",
875 engine->name,
876 ce->timeline->fence_context,
877 port - execlists->pending);
878 ok = false;
879 goto unlock;
880 }
881
882 unlock:
883 spin_unlock_irqrestore(&rq->lock, flags);
884 if (!ok)
885 return false;
886 }
887
888 return ce;
889 }
890
execlists_submit_ports(struct intel_engine_cs * engine)891 static void execlists_submit_ports(struct intel_engine_cs *engine)
892 {
893 struct intel_engine_execlists *execlists = &engine->execlists;
894 unsigned int n;
895
896 GEM_BUG_ON(!assert_pending_valid(execlists, "submit"));
897
898 /*
899 * We can skip acquiring intel_runtime_pm_get() here as it was taken
900 * on our behalf by the request (see i915_gem_mark_busy()) and it will
901 * not be relinquished until the device is idle (see
902 * i915_gem_idle_work_handler()). As a precaution, we make sure
903 * that all ELSP are drained i.e. we have processed the CSB,
904 * before allowing ourselves to idle and calling intel_runtime_pm_put().
905 */
906 GEM_BUG_ON(!intel_engine_pm_is_awake(engine));
907
908 /*
909 * ELSQ note: the submit queue is not cleared after being submitted
910 * to the HW so we need to make sure we always clean it up. This is
911 * currently ensured by the fact that we always write the same number
912 * of elsq entries, keep this in mind before changing the loop below.
913 */
914 for (n = execlists_num_ports(execlists); n--; ) {
915 struct i915_request *rq = execlists->pending[n];
916
917 write_desc(execlists,
918 rq ? execlists_update_context(rq) : 0,
919 n);
920 }
921
922 /* we need to manually load the submit queue */
923 if (execlists->ctrl_reg)
924 writel(EL_CTRL_LOAD, execlists->ctrl_reg);
925 }
926
ctx_single_port_submission(const struct intel_context * ce)927 static bool ctx_single_port_submission(const struct intel_context *ce)
928 {
929 return (IS_ENABLED(CONFIG_DRM_I915_GVT) &&
930 intel_context_force_single_submission(ce));
931 }
932
can_merge_ctx(const struct intel_context * prev,const struct intel_context * next)933 static bool can_merge_ctx(const struct intel_context *prev,
934 const struct intel_context *next)
935 {
936 if (prev != next)
937 return false;
938
939 if (ctx_single_port_submission(prev))
940 return false;
941
942 return true;
943 }
944
i915_request_flags(const struct i915_request * rq)945 static unsigned long i915_request_flags(const struct i915_request *rq)
946 {
947 return READ_ONCE(rq->fence.flags);
948 }
949
can_merge_rq(const struct i915_request * prev,const struct i915_request * next)950 static bool can_merge_rq(const struct i915_request *prev,
951 const struct i915_request *next)
952 {
953 GEM_BUG_ON(prev == next);
954 GEM_BUG_ON(!assert_priority_queue(prev, next));
955
956 /*
957 * We do not submit known completed requests. Therefore if the next
958 * request is already completed, we can pretend to merge it in
959 * with the previous context (and we will skip updating the ELSP
960 * and tracking). Thus hopefully keeping the ELSP full with active
961 * contexts, despite the best efforts of preempt-to-busy to confuse
962 * us.
963 */
964 if (__i915_request_is_complete(next))
965 return true;
966
967 if (unlikely((i915_request_flags(prev) | i915_request_flags(next)) &
968 (BIT(I915_FENCE_FLAG_NOPREEMPT) |
969 BIT(I915_FENCE_FLAG_SENTINEL))))
970 return false;
971
972 if (!can_merge_ctx(prev->context, next->context))
973 return false;
974
975 GEM_BUG_ON(i915_seqno_passed(prev->fence.seqno, next->fence.seqno));
976 return true;
977 }
978
virtual_matches(const struct virtual_engine * ve,const struct i915_request * rq,const struct intel_engine_cs * engine)979 static bool virtual_matches(const struct virtual_engine *ve,
980 const struct i915_request *rq,
981 const struct intel_engine_cs *engine)
982 {
983 const struct intel_engine_cs *inflight;
984
985 if (!rq)
986 return false;
987
988 if (!(rq->execution_mask & engine->mask)) /* We peeked too soon! */
989 return false;
990
991 /*
992 * We track when the HW has completed saving the context image
993 * (i.e. when we have seen the final CS event switching out of
994 * the context) and must not overwrite the context image before
995 * then. This restricts us to only using the active engine
996 * while the previous virtualized request is inflight (so
997 * we reuse the register offsets). This is a very small
998 * hystersis on the greedy seelction algorithm.
999 */
1000 inflight = intel_context_inflight(&ve->context);
1001 if (inflight && inflight != engine)
1002 return false;
1003
1004 return true;
1005 }
1006
1007 static struct virtual_engine *
first_virtual_engine(struct intel_engine_cs * engine)1008 first_virtual_engine(struct intel_engine_cs *engine)
1009 {
1010 struct intel_engine_execlists *el = &engine->execlists;
1011 struct rb_node *rb = rb_first_cached(&el->virtual);
1012
1013 while (rb) {
1014 struct virtual_engine *ve =
1015 rb_entry(rb, typeof(*ve), nodes[engine->id].rb);
1016 struct i915_request *rq = READ_ONCE(ve->request);
1017
1018 /* lazily cleanup after another engine handled rq */
1019 if (!rq || !virtual_matches(ve, rq, engine)) {
1020 rb_erase_cached(rb, &el->virtual);
1021 RB_CLEAR_NODE(rb);
1022 rb = rb_first_cached(&el->virtual);
1023 continue;
1024 }
1025
1026 return ve;
1027 }
1028
1029 return NULL;
1030 }
1031
virtual_xfer_context(struct virtual_engine * ve,struct intel_engine_cs * engine)1032 static void virtual_xfer_context(struct virtual_engine *ve,
1033 struct intel_engine_cs *engine)
1034 {
1035 unsigned int n;
1036
1037 if (likely(engine == ve->siblings[0]))
1038 return;
1039
1040 GEM_BUG_ON(READ_ONCE(ve->context.inflight));
1041 if (!intel_engine_has_relative_mmio(engine))
1042 lrc_update_offsets(&ve->context, engine);
1043
1044 /*
1045 * Move the bound engine to the top of the list for
1046 * future execution. We then kick this tasklet first
1047 * before checking others, so that we preferentially
1048 * reuse this set of bound registers.
1049 */
1050 for (n = 1; n < ve->num_siblings; n++) {
1051 if (ve->siblings[n] == engine) {
1052 swap(ve->siblings[n], ve->siblings[0]);
1053 break;
1054 }
1055 }
1056 }
1057
defer_request(struct i915_request * rq,struct list_head * const pl)1058 static void defer_request(struct i915_request *rq, struct list_head * const pl)
1059 {
1060 LIST_HEAD(list);
1061
1062 /*
1063 * We want to move the interrupted request to the back of
1064 * the round-robin list (i.e. its priority level), but
1065 * in doing so, we must then move all requests that were in
1066 * flight and were waiting for the interrupted request to
1067 * be run after it again.
1068 */
1069 do {
1070 struct i915_dependency *p;
1071
1072 GEM_BUG_ON(i915_request_is_active(rq));
1073 list_move_tail(&rq->sched.link, pl);
1074
1075 for_each_waiter(p, rq) {
1076 struct i915_request *w =
1077 container_of(p->waiter, typeof(*w), sched);
1078
1079 if (p->flags & I915_DEPENDENCY_WEAK)
1080 continue;
1081
1082 /* Leave semaphores spinning on the other engines */
1083 if (w->engine != rq->engine)
1084 continue;
1085
1086 /* No waiter should start before its signaler */
1087 GEM_BUG_ON(i915_request_has_initial_breadcrumb(w) &&
1088 __i915_request_has_started(w) &&
1089 !__i915_request_is_complete(rq));
1090
1091 if (!i915_request_is_ready(w))
1092 continue;
1093
1094 if (rq_prio(w) < rq_prio(rq))
1095 continue;
1096
1097 GEM_BUG_ON(rq_prio(w) > rq_prio(rq));
1098 GEM_BUG_ON(i915_request_is_active(w));
1099 list_move_tail(&w->sched.link, &list);
1100 }
1101
1102 rq = list_first_entry_or_null(&list, typeof(*rq), sched.link);
1103 } while (rq);
1104 }
1105
defer_active(struct intel_engine_cs * engine)1106 static void defer_active(struct intel_engine_cs *engine)
1107 {
1108 struct i915_request *rq;
1109
1110 rq = __unwind_incomplete_requests(engine);
1111 if (!rq)
1112 return;
1113
1114 defer_request(rq, i915_sched_lookup_priolist(engine->sched_engine,
1115 rq_prio(rq)));
1116 }
1117
1118 static bool
timeslice_yield(const struct intel_engine_execlists * el,const struct i915_request * rq)1119 timeslice_yield(const struct intel_engine_execlists *el,
1120 const struct i915_request *rq)
1121 {
1122 /*
1123 * Once bitten, forever smitten!
1124 *
1125 * If the active context ever busy-waited on a semaphore,
1126 * it will be treated as a hog until the end of its timeslice (i.e.
1127 * until it is scheduled out and replaced by a new submission,
1128 * possibly even its own lite-restore). The HW only sends an interrupt
1129 * on the first miss, and we do know if that semaphore has been
1130 * signaled, or even if it is now stuck on another semaphore. Play
1131 * safe, yield if it might be stuck -- it will be given a fresh
1132 * timeslice in the near future.
1133 */
1134 return rq->context->lrc.ccid == READ_ONCE(el->yield);
1135 }
1136
needs_timeslice(const struct intel_engine_cs * engine,const struct i915_request * rq)1137 static bool needs_timeslice(const struct intel_engine_cs *engine,
1138 const struct i915_request *rq)
1139 {
1140 if (!intel_engine_has_timeslices(engine))
1141 return false;
1142
1143 /* If not currently active, or about to switch, wait for next event */
1144 if (!rq || __i915_request_is_complete(rq))
1145 return false;
1146
1147 /* We do not need to start the timeslice until after the ACK */
1148 if (READ_ONCE(engine->execlists.pending[0]))
1149 return false;
1150
1151 /* If ELSP[1] is occupied, always check to see if worth slicing */
1152 if (!list_is_last_rcu(&rq->sched.link,
1153 &engine->sched_engine->requests)) {
1154 ENGINE_TRACE(engine, "timeslice required for second inflight context\n");
1155 return true;
1156 }
1157
1158 /* Otherwise, ELSP[0] is by itself, but may be waiting in the queue */
1159 if (!i915_sched_engine_is_empty(engine->sched_engine)) {
1160 ENGINE_TRACE(engine, "timeslice required for queue\n");
1161 return true;
1162 }
1163
1164 if (!RB_EMPTY_ROOT(&engine->execlists.virtual.rb_root)) {
1165 ENGINE_TRACE(engine, "timeslice required for virtual\n");
1166 return true;
1167 }
1168
1169 return false;
1170 }
1171
1172 static bool
timeslice_expired(struct intel_engine_cs * engine,const struct i915_request * rq)1173 timeslice_expired(struct intel_engine_cs *engine, const struct i915_request *rq)
1174 {
1175 const struct intel_engine_execlists *el = &engine->execlists;
1176
1177 if (i915_request_has_nopreempt(rq) && __i915_request_has_started(rq))
1178 return false;
1179
1180 if (!needs_timeslice(engine, rq))
1181 return false;
1182
1183 return timer_expired(&el->timer) || timeslice_yield(el, rq);
1184 }
1185
timeslice(const struct intel_engine_cs * engine)1186 static unsigned long timeslice(const struct intel_engine_cs *engine)
1187 {
1188 return READ_ONCE(engine->props.timeslice_duration_ms);
1189 }
1190
start_timeslice(struct intel_engine_cs * engine)1191 static void start_timeslice(struct intel_engine_cs *engine)
1192 {
1193 struct intel_engine_execlists *el = &engine->execlists;
1194 unsigned long duration;
1195
1196 /* Disable the timer if there is nothing to switch to */
1197 duration = 0;
1198 if (needs_timeslice(engine, *el->active)) {
1199 /* Avoid continually prolonging an active timeslice */
1200 if (timer_active(&el->timer)) {
1201 /*
1202 * If we just submitted a new ELSP after an old
1203 * context, that context may have already consumed
1204 * its timeslice, so recheck.
1205 */
1206 if (!timer_pending(&el->timer))
1207 tasklet_hi_schedule(&engine->sched_engine->tasklet);
1208 return;
1209 }
1210
1211 duration = timeslice(engine);
1212 }
1213
1214 set_timer_ms(&el->timer, duration);
1215 }
1216
record_preemption(struct intel_engine_execlists * execlists)1217 static void record_preemption(struct intel_engine_execlists *execlists)
1218 {
1219 (void)I915_SELFTEST_ONLY(execlists->preempt_hang.count++);
1220 }
1221
active_preempt_timeout(struct intel_engine_cs * engine,const struct i915_request * rq)1222 static unsigned long active_preempt_timeout(struct intel_engine_cs *engine,
1223 const struct i915_request *rq)
1224 {
1225 if (!rq)
1226 return 0;
1227
1228 /* Only allow ourselves to force reset the currently active context */
1229 engine->execlists.preempt_target = rq;
1230
1231 /* Force a fast reset for terminated contexts (ignoring sysfs!) */
1232 if (unlikely(intel_context_is_banned(rq->context) || bad_request(rq)))
1233 return 1;
1234
1235 return READ_ONCE(engine->props.preempt_timeout_ms);
1236 }
1237
set_preempt_timeout(struct intel_engine_cs * engine,const struct i915_request * rq)1238 static void set_preempt_timeout(struct intel_engine_cs *engine,
1239 const struct i915_request *rq)
1240 {
1241 if (!intel_engine_has_preempt_reset(engine))
1242 return;
1243
1244 set_timer_ms(&engine->execlists.preempt,
1245 active_preempt_timeout(engine, rq));
1246 }
1247
completed(const struct i915_request * rq)1248 static bool completed(const struct i915_request *rq)
1249 {
1250 if (i915_request_has_sentinel(rq))
1251 return false;
1252
1253 return __i915_request_is_complete(rq);
1254 }
1255
execlists_dequeue(struct intel_engine_cs * engine)1256 static void execlists_dequeue(struct intel_engine_cs *engine)
1257 {
1258 struct intel_engine_execlists * const execlists = &engine->execlists;
1259 struct i915_sched_engine * const sched_engine = engine->sched_engine;
1260 struct i915_request **port = execlists->pending;
1261 struct i915_request ** const last_port = port + execlists->port_mask;
1262 struct i915_request *last, * const *active;
1263 struct virtual_engine *ve;
1264 struct rb_node *rb;
1265 bool submit = false;
1266
1267 /*
1268 * Hardware submission is through 2 ports. Conceptually each port
1269 * has a (RING_START, RING_HEAD, RING_TAIL) tuple. RING_START is
1270 * static for a context, and unique to each, so we only execute
1271 * requests belonging to a single context from each ring. RING_HEAD
1272 * is maintained by the CS in the context image, it marks the place
1273 * where it got up to last time, and through RING_TAIL we tell the CS
1274 * where we want to execute up to this time.
1275 *
1276 * In this list the requests are in order of execution. Consecutive
1277 * requests from the same context are adjacent in the ringbuffer. We
1278 * can combine these requests into a single RING_TAIL update:
1279 *
1280 * RING_HEAD...req1...req2
1281 * ^- RING_TAIL
1282 * since to execute req2 the CS must first execute req1.
1283 *
1284 * Our goal then is to point each port to the end of a consecutive
1285 * sequence of requests as being the most optimal (fewest wake ups
1286 * and context switches) submission.
1287 */
1288
1289 spin_lock(&sched_engine->lock);
1290
1291 /*
1292 * If the queue is higher priority than the last
1293 * request in the currently active context, submit afresh.
1294 * We will resubmit again afterwards in case we need to split
1295 * the active context to interject the preemption request,
1296 * i.e. we will retrigger preemption following the ack in case
1297 * of trouble.
1298 *
1299 */
1300 active = execlists->active;
1301 while ((last = *active) && completed(last))
1302 active++;
1303
1304 if (last) {
1305 if (need_preempt(engine, last)) {
1306 ENGINE_TRACE(engine,
1307 "preempting last=%llx:%lld, prio=%d, hint=%d\n",
1308 last->fence.context,
1309 last->fence.seqno,
1310 last->sched.attr.priority,
1311 sched_engine->queue_priority_hint);
1312 record_preemption(execlists);
1313
1314 /*
1315 * Don't let the RING_HEAD advance past the breadcrumb
1316 * as we unwind (and until we resubmit) so that we do
1317 * not accidentally tell it to go backwards.
1318 */
1319 ring_set_paused(engine, 1);
1320
1321 /*
1322 * Note that we have not stopped the GPU at this point,
1323 * so we are unwinding the incomplete requests as they
1324 * remain inflight and so by the time we do complete
1325 * the preemption, some of the unwound requests may
1326 * complete!
1327 */
1328 __unwind_incomplete_requests(engine);
1329
1330 last = NULL;
1331 } else if (timeslice_expired(engine, last)) {
1332 ENGINE_TRACE(engine,
1333 "expired:%s last=%llx:%lld, prio=%d, hint=%d, yield?=%s\n",
1334 yesno(timer_expired(&execlists->timer)),
1335 last->fence.context, last->fence.seqno,
1336 rq_prio(last),
1337 sched_engine->queue_priority_hint,
1338 yesno(timeslice_yield(execlists, last)));
1339
1340 /*
1341 * Consume this timeslice; ensure we start a new one.
1342 *
1343 * The timeslice expired, and we will unwind the
1344 * running contexts and recompute the next ELSP.
1345 * If that submit will be the same pair of contexts
1346 * (due to dependency ordering), we will skip the
1347 * submission. If we don't cancel the timer now,
1348 * we will see that the timer has expired and
1349 * reschedule the tasklet; continually until the
1350 * next context switch or other preeemption event.
1351 *
1352 * Since we have decided to reschedule based on
1353 * consumption of this timeslice, if we submit the
1354 * same context again, grant it a full timeslice.
1355 */
1356 cancel_timer(&execlists->timer);
1357 ring_set_paused(engine, 1);
1358 defer_active(engine);
1359
1360 /*
1361 * Unlike for preemption, if we rewind and continue
1362 * executing the same context as previously active,
1363 * the order of execution will remain the same and
1364 * the tail will only advance. We do not need to
1365 * force a full context restore, as a lite-restore
1366 * is sufficient to resample the monotonic TAIL.
1367 *
1368 * If we switch to any other context, similarly we
1369 * will not rewind TAIL of current context, and
1370 * normal save/restore will preserve state and allow
1371 * us to later continue executing the same request.
1372 */
1373 last = NULL;
1374 } else {
1375 /*
1376 * Otherwise if we already have a request pending
1377 * for execution after the current one, we can
1378 * just wait until the next CS event before
1379 * queuing more. In either case we will force a
1380 * lite-restore preemption event, but if we wait
1381 * we hopefully coalesce several updates into a single
1382 * submission.
1383 */
1384 if (active[1]) {
1385 /*
1386 * Even if ELSP[1] is occupied and not worthy
1387 * of timeslices, our queue might be.
1388 */
1389 spin_unlock(&sched_engine->lock);
1390 return;
1391 }
1392 }
1393 }
1394
1395 /* XXX virtual is always taking precedence */
1396 while ((ve = first_virtual_engine(engine))) {
1397 struct i915_request *rq;
1398
1399 spin_lock(&ve->base.sched_engine->lock);
1400
1401 rq = ve->request;
1402 if (unlikely(!virtual_matches(ve, rq, engine)))
1403 goto unlock; /* lost the race to a sibling */
1404
1405 GEM_BUG_ON(rq->engine != &ve->base);
1406 GEM_BUG_ON(rq->context != &ve->context);
1407
1408 if (unlikely(rq_prio(rq) < queue_prio(sched_engine))) {
1409 spin_unlock(&ve->base.sched_engine->lock);
1410 break;
1411 }
1412
1413 if (last && !can_merge_rq(last, rq)) {
1414 spin_unlock(&ve->base.sched_engine->lock);
1415 spin_unlock(&engine->sched_engine->lock);
1416 return; /* leave this for another sibling */
1417 }
1418
1419 ENGINE_TRACE(engine,
1420 "virtual rq=%llx:%lld%s, new engine? %s\n",
1421 rq->fence.context,
1422 rq->fence.seqno,
1423 __i915_request_is_complete(rq) ? "!" :
1424 __i915_request_has_started(rq) ? "*" :
1425 "",
1426 yesno(engine != ve->siblings[0]));
1427
1428 WRITE_ONCE(ve->request, NULL);
1429 WRITE_ONCE(ve->base.sched_engine->queue_priority_hint, INT_MIN);
1430
1431 rb = &ve->nodes[engine->id].rb;
1432 rb_erase_cached(rb, &execlists->virtual);
1433 RB_CLEAR_NODE(rb);
1434
1435 GEM_BUG_ON(!(rq->execution_mask & engine->mask));
1436 WRITE_ONCE(rq->engine, engine);
1437
1438 if (__i915_request_submit(rq)) {
1439 /*
1440 * Only after we confirm that we will submit
1441 * this request (i.e. it has not already
1442 * completed), do we want to update the context.
1443 *
1444 * This serves two purposes. It avoids
1445 * unnecessary work if we are resubmitting an
1446 * already completed request after timeslicing.
1447 * But more importantly, it prevents us altering
1448 * ve->siblings[] on an idle context, where
1449 * we may be using ve->siblings[] in
1450 * virtual_context_enter / virtual_context_exit.
1451 */
1452 virtual_xfer_context(ve, engine);
1453 GEM_BUG_ON(ve->siblings[0] != engine);
1454
1455 submit = true;
1456 last = rq;
1457 }
1458
1459 i915_request_put(rq);
1460 unlock:
1461 spin_unlock(&ve->base.sched_engine->lock);
1462
1463 /*
1464 * Hmm, we have a bunch of virtual engine requests,
1465 * but the first one was already completed (thanks
1466 * preempt-to-busy!). Keep looking at the veng queue
1467 * until we have no more relevant requests (i.e.
1468 * the normal submit queue has higher priority).
1469 */
1470 if (submit)
1471 break;
1472 }
1473
1474 while ((rb = rb_first_cached(&sched_engine->queue))) {
1475 struct i915_priolist *p = to_priolist(rb);
1476 struct i915_request *rq, *rn;
1477
1478 priolist_for_each_request_consume(rq, rn, p) {
1479 bool merge = true;
1480
1481 /*
1482 * Can we combine this request with the current port?
1483 * It has to be the same context/ringbuffer and not
1484 * have any exceptions (e.g. GVT saying never to
1485 * combine contexts).
1486 *
1487 * If we can combine the requests, we can execute both
1488 * by updating the RING_TAIL to point to the end of the
1489 * second request, and so we never need to tell the
1490 * hardware about the first.
1491 */
1492 if (last && !can_merge_rq(last, rq)) {
1493 /*
1494 * If we are on the second port and cannot
1495 * combine this request with the last, then we
1496 * are done.
1497 */
1498 if (port == last_port)
1499 goto done;
1500
1501 /*
1502 * We must not populate both ELSP[] with the
1503 * same LRCA, i.e. we must submit 2 different
1504 * contexts if we submit 2 ELSP.
1505 */
1506 if (last->context == rq->context)
1507 goto done;
1508
1509 if (i915_request_has_sentinel(last))
1510 goto done;
1511
1512 /*
1513 * We avoid submitting virtual requests into
1514 * the secondary ports so that we can migrate
1515 * the request immediately to another engine
1516 * rather than wait for the primary request.
1517 */
1518 if (rq->execution_mask != engine->mask)
1519 goto done;
1520
1521 /*
1522 * If GVT overrides us we only ever submit
1523 * port[0], leaving port[1] empty. Note that we
1524 * also have to be careful that we don't queue
1525 * the same context (even though a different
1526 * request) to the second port.
1527 */
1528 if (ctx_single_port_submission(last->context) ||
1529 ctx_single_port_submission(rq->context))
1530 goto done;
1531
1532 merge = false;
1533 }
1534
1535 if (__i915_request_submit(rq)) {
1536 if (!merge) {
1537 *port++ = i915_request_get(last);
1538 last = NULL;
1539 }
1540
1541 GEM_BUG_ON(last &&
1542 !can_merge_ctx(last->context,
1543 rq->context));
1544 GEM_BUG_ON(last &&
1545 i915_seqno_passed(last->fence.seqno,
1546 rq->fence.seqno));
1547
1548 submit = true;
1549 last = rq;
1550 }
1551 }
1552
1553 rb_erase_cached(&p->node, &sched_engine->queue);
1554 i915_priolist_free(p);
1555 }
1556 done:
1557 *port++ = i915_request_get(last);
1558
1559 /*
1560 * Here be a bit of magic! Or sleight-of-hand, whichever you prefer.
1561 *
1562 * We choose the priority hint such that if we add a request of greater
1563 * priority than this, we kick the submission tasklet to decide on
1564 * the right order of submitting the requests to hardware. We must
1565 * also be prepared to reorder requests as they are in-flight on the
1566 * HW. We derive the priority hint then as the first "hole" in
1567 * the HW submission ports and if there are no available slots,
1568 * the priority of the lowest executing request, i.e. last.
1569 *
1570 * When we do receive a higher priority request ready to run from the
1571 * user, see queue_request(), the priority hint is bumped to that
1572 * request triggering preemption on the next dequeue (or subsequent
1573 * interrupt for secondary ports).
1574 */
1575 sched_engine->queue_priority_hint = queue_prio(sched_engine);
1576 i915_sched_engine_reset_on_empty(sched_engine);
1577 spin_unlock(&sched_engine->lock);
1578
1579 /*
1580 * We can skip poking the HW if we ended up with exactly the same set
1581 * of requests as currently running, e.g. trying to timeslice a pair
1582 * of ordered contexts.
1583 */
1584 if (submit &&
1585 memcmp(active,
1586 execlists->pending,
1587 (port - execlists->pending) * sizeof(*port))) {
1588 *port = NULL;
1589 while (port-- != execlists->pending)
1590 execlists_schedule_in(*port, port - execlists->pending);
1591
1592 WRITE_ONCE(execlists->yield, -1);
1593 set_preempt_timeout(engine, *active);
1594 execlists_submit_ports(engine);
1595 } else {
1596 ring_set_paused(engine, 0);
1597 while (port-- != execlists->pending)
1598 i915_request_put(*port);
1599 *execlists->pending = NULL;
1600 }
1601 }
1602
execlists_dequeue_irq(struct intel_engine_cs * engine)1603 static void execlists_dequeue_irq(struct intel_engine_cs *engine)
1604 {
1605 local_irq_disable(); /* Suspend interrupts across request submission */
1606 execlists_dequeue(engine);
1607 local_irq_enable(); /* flush irq_work (e.g. breadcrumb enabling) */
1608 }
1609
clear_ports(struct i915_request ** ports,int count)1610 static void clear_ports(struct i915_request **ports, int count)
1611 {
1612 memset_p((void **)ports, NULL, count);
1613 }
1614
1615 static void
copy_ports(struct i915_request ** dst,struct i915_request ** src,int count)1616 copy_ports(struct i915_request **dst, struct i915_request **src, int count)
1617 {
1618 /* A memcpy_p() would be very useful here! */
1619 while (count--)
1620 WRITE_ONCE(*dst++, *src++); /* avoid write tearing */
1621 }
1622
1623 static struct i915_request **
cancel_port_requests(struct intel_engine_execlists * const execlists,struct i915_request ** inactive)1624 cancel_port_requests(struct intel_engine_execlists * const execlists,
1625 struct i915_request **inactive)
1626 {
1627 struct i915_request * const *port;
1628
1629 for (port = execlists->pending; *port; port++)
1630 *inactive++ = *port;
1631 clear_ports(execlists->pending, ARRAY_SIZE(execlists->pending));
1632
1633 /* Mark the end of active before we overwrite *active */
1634 for (port = xchg(&execlists->active, execlists->pending); *port; port++)
1635 *inactive++ = *port;
1636 clear_ports(execlists->inflight, ARRAY_SIZE(execlists->inflight));
1637
1638 smp_wmb(); /* complete the seqlock for execlists_active() */
1639 WRITE_ONCE(execlists->active, execlists->inflight);
1640
1641 /* Having cancelled all outstanding process_csb(), stop their timers */
1642 GEM_BUG_ON(execlists->pending[0]);
1643 cancel_timer(&execlists->timer);
1644 cancel_timer(&execlists->preempt);
1645
1646 return inactive;
1647 }
1648
invalidate_csb_entries(const u64 * first,const u64 * last)1649 static void invalidate_csb_entries(const u64 *first, const u64 *last)
1650 {
1651 clflush((void *)first);
1652 clflush((void *)last);
1653 }
1654
1655 /*
1656 * Starting with Gen12, the status has a new format:
1657 *
1658 * bit 0: switched to new queue
1659 * bit 1: reserved
1660 * bit 2: semaphore wait mode (poll or signal), only valid when
1661 * switch detail is set to "wait on semaphore"
1662 * bits 3-5: engine class
1663 * bits 6-11: engine instance
1664 * bits 12-14: reserved
1665 * bits 15-25: sw context id of the lrc the GT switched to
1666 * bits 26-31: sw counter of the lrc the GT switched to
1667 * bits 32-35: context switch detail
1668 * - 0: ctx complete
1669 * - 1: wait on sync flip
1670 * - 2: wait on vblank
1671 * - 3: wait on scanline
1672 * - 4: wait on semaphore
1673 * - 5: context preempted (not on SEMAPHORE_WAIT or
1674 * WAIT_FOR_EVENT)
1675 * bit 36: reserved
1676 * bits 37-43: wait detail (for switch detail 1 to 4)
1677 * bits 44-46: reserved
1678 * bits 47-57: sw context id of the lrc the GT switched away from
1679 * bits 58-63: sw counter of the lrc the GT switched away from
1680 *
1681 * Xe_HP csb shuffles things around compared to TGL:
1682 *
1683 * bits 0-3: context switch detail (same possible values as TGL)
1684 * bits 4-9: engine instance
1685 * bits 10-25: sw context id of the lrc the GT switched to
1686 * bits 26-31: sw counter of the lrc the GT switched to
1687 * bit 32: semaphore wait mode (poll or signal), Only valid when
1688 * switch detail is set to "wait on semaphore"
1689 * bit 33: switched to new queue
1690 * bits 34-41: wait detail (for switch detail 1 to 4)
1691 * bits 42-57: sw context id of the lrc the GT switched away from
1692 * bits 58-63: sw counter of the lrc the GT switched away from
1693 */
1694 static inline bool
__gen12_csb_parse(bool ctx_to_valid,bool ctx_away_valid,bool new_queue,u8 switch_detail)1695 __gen12_csb_parse(bool ctx_to_valid, bool ctx_away_valid, bool new_queue,
1696 u8 switch_detail)
1697 {
1698 /*
1699 * The context switch detail is not guaranteed to be 5 when a preemption
1700 * occurs, so we can't just check for that. The check below works for
1701 * all the cases we care about, including preemptions of WAIT
1702 * instructions and lite-restore. Preempt-to-idle via the CTRL register
1703 * would require some extra handling, but we don't support that.
1704 */
1705 if (!ctx_away_valid || new_queue) {
1706 GEM_BUG_ON(!ctx_to_valid);
1707 return true;
1708 }
1709
1710 /*
1711 * switch detail = 5 is covered by the case above and we do not expect a
1712 * context switch on an unsuccessful wait instruction since we always
1713 * use polling mode.
1714 */
1715 GEM_BUG_ON(switch_detail);
1716 return false;
1717 }
1718
xehp_csb_parse(const u64 csb)1719 static bool xehp_csb_parse(const u64 csb)
1720 {
1721 return __gen12_csb_parse(XEHP_CSB_CTX_VALID(lower_32_bits(csb)), /* cxt to */
1722 XEHP_CSB_CTX_VALID(upper_32_bits(csb)), /* cxt away */
1723 upper_32_bits(csb) & XEHP_CTX_STATUS_SWITCHED_TO_NEW_QUEUE,
1724 GEN12_CTX_SWITCH_DETAIL(lower_32_bits(csb)));
1725 }
1726
gen12_csb_parse(const u64 csb)1727 static bool gen12_csb_parse(const u64 csb)
1728 {
1729 return __gen12_csb_parse(GEN12_CSB_CTX_VALID(lower_32_bits(csb)), /* cxt to */
1730 GEN12_CSB_CTX_VALID(upper_32_bits(csb)), /* cxt away */
1731 lower_32_bits(csb) & GEN12_CTX_STATUS_SWITCHED_TO_NEW_QUEUE,
1732 GEN12_CTX_SWITCH_DETAIL(upper_32_bits(csb)));
1733 }
1734
gen8_csb_parse(const u64 csb)1735 static bool gen8_csb_parse(const u64 csb)
1736 {
1737 return csb & (GEN8_CTX_STATUS_IDLE_ACTIVE | GEN8_CTX_STATUS_PREEMPTED);
1738 }
1739
1740 static noinline u64
wa_csb_read(const struct intel_engine_cs * engine,u64 * const csb)1741 wa_csb_read(const struct intel_engine_cs *engine, u64 * const csb)
1742 {
1743 u64 entry;
1744
1745 /*
1746 * Reading from the HWSP has one particular advantage: we can detect
1747 * a stale entry. Since the write into HWSP is broken, we have no reason
1748 * to trust the HW at all, the mmio entry may equally be unordered, so
1749 * we prefer the path that is self-checking and as a last resort,
1750 * return the mmio value.
1751 *
1752 * tgl,dg1:HSDES#22011327657
1753 */
1754 preempt_disable();
1755 if (wait_for_atomic_us((entry = READ_ONCE(*csb)) != -1, 10)) {
1756 int idx = csb - engine->execlists.csb_status;
1757 int status;
1758
1759 status = GEN8_EXECLISTS_STATUS_BUF;
1760 if (idx >= 6) {
1761 status = GEN11_EXECLISTS_STATUS_BUF2;
1762 idx -= 6;
1763 }
1764 status += sizeof(u64) * idx;
1765
1766 entry = intel_uncore_read64(engine->uncore,
1767 _MMIO(engine->mmio_base + status));
1768 }
1769 preempt_enable();
1770
1771 return entry;
1772 }
1773
csb_read(const struct intel_engine_cs * engine,u64 * const csb)1774 static u64 csb_read(const struct intel_engine_cs *engine, u64 * const csb)
1775 {
1776 u64 entry = READ_ONCE(*csb);
1777
1778 /*
1779 * Unfortunately, the GPU does not always serialise its write
1780 * of the CSB entries before its write of the CSB pointer, at least
1781 * from the perspective of the CPU, using what is known as a Global
1782 * Observation Point. We may read a new CSB tail pointer, but then
1783 * read the stale CSB entries, causing us to misinterpret the
1784 * context-switch events, and eventually declare the GPU hung.
1785 *
1786 * icl:HSDES#1806554093
1787 * tgl:HSDES#22011248461
1788 */
1789 if (unlikely(entry == -1))
1790 entry = wa_csb_read(engine, csb);
1791
1792 /* Consume this entry so that we can spot its future reuse. */
1793 WRITE_ONCE(*csb, -1);
1794
1795 /* ELSP is an implicit wmb() before the GPU wraps and overwrites csb */
1796 return entry;
1797 }
1798
new_timeslice(struct intel_engine_execlists * el)1799 static void new_timeslice(struct intel_engine_execlists *el)
1800 {
1801 /* By cancelling, we will start afresh in start_timeslice() */
1802 cancel_timer(&el->timer);
1803 }
1804
1805 static struct i915_request **
process_csb(struct intel_engine_cs * engine,struct i915_request ** inactive)1806 process_csb(struct intel_engine_cs *engine, struct i915_request **inactive)
1807 {
1808 struct intel_engine_execlists * const execlists = &engine->execlists;
1809 u64 * const buf = execlists->csb_status;
1810 const u8 num_entries = execlists->csb_size;
1811 struct i915_request **prev;
1812 u8 head, tail;
1813
1814 /*
1815 * As we modify our execlists state tracking we require exclusive
1816 * access. Either we are inside the tasklet, or the tasklet is disabled
1817 * and we assume that is only inside the reset paths and so serialised.
1818 */
1819 GEM_BUG_ON(!tasklet_is_locked(&engine->sched_engine->tasklet) &&
1820 !reset_in_progress(engine));
1821
1822 /*
1823 * Note that csb_write, csb_status may be either in HWSP or mmio.
1824 * When reading from the csb_write mmio register, we have to be
1825 * careful to only use the GEN8_CSB_WRITE_PTR portion, which is
1826 * the low 4bits. As it happens we know the next 4bits are always
1827 * zero and so we can simply masked off the low u8 of the register
1828 * and treat it identically to reading from the HWSP (without having
1829 * to use explicit shifting and masking, and probably bifurcating
1830 * the code to handle the legacy mmio read).
1831 */
1832 head = execlists->csb_head;
1833 tail = READ_ONCE(*execlists->csb_write);
1834 if (unlikely(head == tail))
1835 return inactive;
1836
1837 /*
1838 * We will consume all events from HW, or at least pretend to.
1839 *
1840 * The sequence of events from the HW is deterministic, and derived
1841 * from our writes to the ELSP, with a smidgen of variability for
1842 * the arrival of the asynchronous requests wrt to the inflight
1843 * execution. If the HW sends an event that does not correspond with
1844 * the one we are expecting, we have to abandon all hope as we lose
1845 * all tracking of what the engine is actually executing. We will
1846 * only detect we are out of sequence with the HW when we get an
1847 * 'impossible' event because we have already drained our own
1848 * preemption/promotion queue. If this occurs, we know that we likely
1849 * lost track of execution earlier and must unwind and restart, the
1850 * simplest way is by stop processing the event queue and force the
1851 * engine to reset.
1852 */
1853 execlists->csb_head = tail;
1854 ENGINE_TRACE(engine, "cs-irq head=%d, tail=%d\n", head, tail);
1855
1856 /*
1857 * Hopefully paired with a wmb() in HW!
1858 *
1859 * We must complete the read of the write pointer before any reads
1860 * from the CSB, so that we do not see stale values. Without an rmb
1861 * (lfence) the HW may speculatively perform the CSB[] reads *before*
1862 * we perform the READ_ONCE(*csb_write).
1863 */
1864 rmb();
1865
1866 /* Remember who was last running under the timer */
1867 prev = inactive;
1868 *prev = NULL;
1869
1870 do {
1871 bool promote;
1872 u64 csb;
1873
1874 if (++head == num_entries)
1875 head = 0;
1876
1877 /*
1878 * We are flying near dragons again.
1879 *
1880 * We hold a reference to the request in execlist_port[]
1881 * but no more than that. We are operating in softirq
1882 * context and so cannot hold any mutex or sleep. That
1883 * prevents us stopping the requests we are processing
1884 * in port[] from being retired simultaneously (the
1885 * breadcrumb will be complete before we see the
1886 * context-switch). As we only hold the reference to the
1887 * request, any pointer chasing underneath the request
1888 * is subject to a potential use-after-free. Thus we
1889 * store all of the bookkeeping within port[] as
1890 * required, and avoid using unguarded pointers beneath
1891 * request itself. The same applies to the atomic
1892 * status notifier.
1893 */
1894
1895 csb = csb_read(engine, buf + head);
1896 ENGINE_TRACE(engine, "csb[%d]: status=0x%08x:0x%08x\n",
1897 head, upper_32_bits(csb), lower_32_bits(csb));
1898
1899 if (GRAPHICS_VER_FULL(engine->i915) >= IP_VER(12, 50))
1900 promote = xehp_csb_parse(csb);
1901 else if (GRAPHICS_VER(engine->i915) >= 12)
1902 promote = gen12_csb_parse(csb);
1903 else
1904 promote = gen8_csb_parse(csb);
1905 if (promote) {
1906 struct i915_request * const *old = execlists->active;
1907
1908 if (GEM_WARN_ON(!*execlists->pending)) {
1909 execlists->error_interrupt |= ERROR_CSB;
1910 break;
1911 }
1912
1913 ring_set_paused(engine, 0);
1914
1915 /* Point active to the new ELSP; prevent overwriting */
1916 WRITE_ONCE(execlists->active, execlists->pending);
1917 smp_wmb(); /* notify execlists_active() */
1918
1919 /* cancel old inflight, prepare for switch */
1920 trace_ports(execlists, "preempted", old);
1921 while (*old)
1922 *inactive++ = *old++;
1923
1924 /* switch pending to inflight */
1925 GEM_BUG_ON(!assert_pending_valid(execlists, "promote"));
1926 copy_ports(execlists->inflight,
1927 execlists->pending,
1928 execlists_num_ports(execlists));
1929 smp_wmb(); /* complete the seqlock */
1930 WRITE_ONCE(execlists->active, execlists->inflight);
1931
1932 /* XXX Magic delay for tgl */
1933 ENGINE_POSTING_READ(engine, RING_CONTEXT_STATUS_PTR);
1934
1935 WRITE_ONCE(execlists->pending[0], NULL);
1936 } else {
1937 if (GEM_WARN_ON(!*execlists->active)) {
1938 execlists->error_interrupt |= ERROR_CSB;
1939 break;
1940 }
1941
1942 /* port0 completed, advanced to port1 */
1943 trace_ports(execlists, "completed", execlists->active);
1944
1945 /*
1946 * We rely on the hardware being strongly
1947 * ordered, that the breadcrumb write is
1948 * coherent (visible from the CPU) before the
1949 * user interrupt is processed. One might assume
1950 * that the breadcrumb write being before the
1951 * user interrupt and the CS event for the context
1952 * switch would therefore be before the CS event
1953 * itself...
1954 */
1955 if (GEM_SHOW_DEBUG() &&
1956 !__i915_request_is_complete(*execlists->active)) {
1957 struct i915_request *rq = *execlists->active;
1958 const u32 *regs __maybe_unused =
1959 rq->context->lrc_reg_state;
1960
1961 ENGINE_TRACE(engine,
1962 "context completed before request!\n");
1963 ENGINE_TRACE(engine,
1964 "ring:{start:0x%08x, head:%04x, tail:%04x, ctl:%08x, mode:%08x}\n",
1965 ENGINE_READ(engine, RING_START),
1966 ENGINE_READ(engine, RING_HEAD) & HEAD_ADDR,
1967 ENGINE_READ(engine, RING_TAIL) & TAIL_ADDR,
1968 ENGINE_READ(engine, RING_CTL),
1969 ENGINE_READ(engine, RING_MI_MODE));
1970 ENGINE_TRACE(engine,
1971 "rq:{start:%08x, head:%04x, tail:%04x, seqno:%llx:%d, hwsp:%d}, ",
1972 i915_ggtt_offset(rq->ring->vma),
1973 rq->head, rq->tail,
1974 rq->fence.context,
1975 lower_32_bits(rq->fence.seqno),
1976 hwsp_seqno(rq));
1977 ENGINE_TRACE(engine,
1978 "ctx:{start:%08x, head:%04x, tail:%04x}, ",
1979 regs[CTX_RING_START],
1980 regs[CTX_RING_HEAD],
1981 regs[CTX_RING_TAIL]);
1982 }
1983
1984 *inactive++ = *execlists->active++;
1985
1986 GEM_BUG_ON(execlists->active - execlists->inflight >
1987 execlists_num_ports(execlists));
1988 }
1989 } while (head != tail);
1990
1991 /*
1992 * Gen11 has proven to fail wrt global observation point between
1993 * entry and tail update, failing on the ordering and thus
1994 * we see an old entry in the context status buffer.
1995 *
1996 * Forcibly evict out entries for the next gpu csb update,
1997 * to increase the odds that we get a fresh entries with non
1998 * working hardware. The cost for doing so comes out mostly with
1999 * the wash as hardware, working or not, will need to do the
2000 * invalidation before.
2001 */
2002 invalidate_csb_entries(&buf[0], &buf[num_entries - 1]);
2003
2004 /*
2005 * We assume that any event reflects a change in context flow
2006 * and merits a fresh timeslice. We reinstall the timer after
2007 * inspecting the queue to see if we need to resumbit.
2008 */
2009 if (*prev != *execlists->active) /* elide lite-restores */
2010 new_timeslice(execlists);
2011
2012 return inactive;
2013 }
2014
post_process_csb(struct i915_request ** port,struct i915_request ** last)2015 static void post_process_csb(struct i915_request **port,
2016 struct i915_request **last)
2017 {
2018 while (port != last)
2019 execlists_schedule_out(*port++);
2020 }
2021
__execlists_hold(struct i915_request * rq)2022 static void __execlists_hold(struct i915_request *rq)
2023 {
2024 LIST_HEAD(list);
2025
2026 do {
2027 struct i915_dependency *p;
2028
2029 if (i915_request_is_active(rq))
2030 __i915_request_unsubmit(rq);
2031
2032 clear_bit(I915_FENCE_FLAG_PQUEUE, &rq->fence.flags);
2033 list_move_tail(&rq->sched.link,
2034 &rq->engine->sched_engine->hold);
2035 i915_request_set_hold(rq);
2036 RQ_TRACE(rq, "on hold\n");
2037
2038 for_each_waiter(p, rq) {
2039 struct i915_request *w =
2040 container_of(p->waiter, typeof(*w), sched);
2041
2042 if (p->flags & I915_DEPENDENCY_WEAK)
2043 continue;
2044
2045 /* Leave semaphores spinning on the other engines */
2046 if (w->engine != rq->engine)
2047 continue;
2048
2049 if (!i915_request_is_ready(w))
2050 continue;
2051
2052 if (__i915_request_is_complete(w))
2053 continue;
2054
2055 if (i915_request_on_hold(w))
2056 continue;
2057
2058 list_move_tail(&w->sched.link, &list);
2059 }
2060
2061 rq = list_first_entry_or_null(&list, typeof(*rq), sched.link);
2062 } while (rq);
2063 }
2064
execlists_hold(struct intel_engine_cs * engine,struct i915_request * rq)2065 static bool execlists_hold(struct intel_engine_cs *engine,
2066 struct i915_request *rq)
2067 {
2068 if (i915_request_on_hold(rq))
2069 return false;
2070
2071 spin_lock_irq(&engine->sched_engine->lock);
2072
2073 if (__i915_request_is_complete(rq)) { /* too late! */
2074 rq = NULL;
2075 goto unlock;
2076 }
2077
2078 /*
2079 * Transfer this request onto the hold queue to prevent it
2080 * being resumbitted to HW (and potentially completed) before we have
2081 * released it. Since we may have already submitted following
2082 * requests, we need to remove those as well.
2083 */
2084 GEM_BUG_ON(i915_request_on_hold(rq));
2085 GEM_BUG_ON(rq->engine != engine);
2086 __execlists_hold(rq);
2087 GEM_BUG_ON(list_empty(&engine->sched_engine->hold));
2088
2089 unlock:
2090 spin_unlock_irq(&engine->sched_engine->lock);
2091 return rq;
2092 }
2093
hold_request(const struct i915_request * rq)2094 static bool hold_request(const struct i915_request *rq)
2095 {
2096 struct i915_dependency *p;
2097 bool result = false;
2098
2099 /*
2100 * If one of our ancestors is on hold, we must also be on hold,
2101 * otherwise we will bypass it and execute before it.
2102 */
2103 rcu_read_lock();
2104 for_each_signaler(p, rq) {
2105 const struct i915_request *s =
2106 container_of(p->signaler, typeof(*s), sched);
2107
2108 if (s->engine != rq->engine)
2109 continue;
2110
2111 result = i915_request_on_hold(s);
2112 if (result)
2113 break;
2114 }
2115 rcu_read_unlock();
2116
2117 return result;
2118 }
2119
__execlists_unhold(struct i915_request * rq)2120 static void __execlists_unhold(struct i915_request *rq)
2121 {
2122 LIST_HEAD(list);
2123
2124 do {
2125 struct i915_dependency *p;
2126
2127 RQ_TRACE(rq, "hold release\n");
2128
2129 GEM_BUG_ON(!i915_request_on_hold(rq));
2130 GEM_BUG_ON(!i915_sw_fence_signaled(&rq->submit));
2131
2132 i915_request_clear_hold(rq);
2133 list_move_tail(&rq->sched.link,
2134 i915_sched_lookup_priolist(rq->engine->sched_engine,
2135 rq_prio(rq)));
2136 set_bit(I915_FENCE_FLAG_PQUEUE, &rq->fence.flags);
2137
2138 /* Also release any children on this engine that are ready */
2139 for_each_waiter(p, rq) {
2140 struct i915_request *w =
2141 container_of(p->waiter, typeof(*w), sched);
2142
2143 if (p->flags & I915_DEPENDENCY_WEAK)
2144 continue;
2145
2146 if (w->engine != rq->engine)
2147 continue;
2148
2149 if (!i915_request_on_hold(w))
2150 continue;
2151
2152 /* Check that no other parents are also on hold */
2153 if (hold_request(w))
2154 continue;
2155
2156 list_move_tail(&w->sched.link, &list);
2157 }
2158
2159 rq = list_first_entry_or_null(&list, typeof(*rq), sched.link);
2160 } while (rq);
2161 }
2162
execlists_unhold(struct intel_engine_cs * engine,struct i915_request * rq)2163 static void execlists_unhold(struct intel_engine_cs *engine,
2164 struct i915_request *rq)
2165 {
2166 spin_lock_irq(&engine->sched_engine->lock);
2167
2168 /*
2169 * Move this request back to the priority queue, and all of its
2170 * children and grandchildren that were suspended along with it.
2171 */
2172 __execlists_unhold(rq);
2173
2174 if (rq_prio(rq) > engine->sched_engine->queue_priority_hint) {
2175 engine->sched_engine->queue_priority_hint = rq_prio(rq);
2176 tasklet_hi_schedule(&engine->sched_engine->tasklet);
2177 }
2178
2179 spin_unlock_irq(&engine->sched_engine->lock);
2180 }
2181
2182 struct execlists_capture {
2183 struct work_struct work;
2184 struct i915_request *rq;
2185 struct i915_gpu_coredump *error;
2186 };
2187
execlists_capture_work(struct work_struct * work)2188 static void execlists_capture_work(struct work_struct *work)
2189 {
2190 struct execlists_capture *cap = container_of(work, typeof(*cap), work);
2191 const gfp_t gfp = GFP_KERNEL | __GFP_RETRY_MAYFAIL | __GFP_NOWARN;
2192 struct intel_engine_cs *engine = cap->rq->engine;
2193 struct intel_gt_coredump *gt = cap->error->gt;
2194 struct intel_engine_capture_vma *vma;
2195
2196 /* Compress all the objects attached to the request, slow! */
2197 vma = intel_engine_coredump_add_request(gt->engine, cap->rq, gfp);
2198 if (vma) {
2199 struct i915_vma_compress *compress =
2200 i915_vma_capture_prepare(gt);
2201
2202 intel_engine_coredump_add_vma(gt->engine, vma, compress);
2203 i915_vma_capture_finish(gt, compress);
2204 }
2205
2206 gt->simulated = gt->engine->simulated;
2207 cap->error->simulated = gt->simulated;
2208
2209 /* Publish the error state, and announce it to the world */
2210 i915_error_state_store(cap->error);
2211 i915_gpu_coredump_put(cap->error);
2212
2213 /* Return this request and all that depend upon it for signaling */
2214 execlists_unhold(engine, cap->rq);
2215 i915_request_put(cap->rq);
2216
2217 kfree(cap);
2218 }
2219
capture_regs(struct intel_engine_cs * engine)2220 static struct execlists_capture *capture_regs(struct intel_engine_cs *engine)
2221 {
2222 const gfp_t gfp = GFP_ATOMIC | __GFP_NOWARN;
2223 struct execlists_capture *cap;
2224
2225 cap = kmalloc(sizeof(*cap), gfp);
2226 if (!cap)
2227 return NULL;
2228
2229 cap->error = i915_gpu_coredump_alloc(engine->i915, gfp);
2230 if (!cap->error)
2231 goto err_cap;
2232
2233 cap->error->gt = intel_gt_coredump_alloc(engine->gt, gfp);
2234 if (!cap->error->gt)
2235 goto err_gpu;
2236
2237 cap->error->gt->engine = intel_engine_coredump_alloc(engine, gfp);
2238 if (!cap->error->gt->engine)
2239 goto err_gt;
2240
2241 cap->error->gt->engine->hung = true;
2242
2243 return cap;
2244
2245 err_gt:
2246 kfree(cap->error->gt);
2247 err_gpu:
2248 kfree(cap->error);
2249 err_cap:
2250 kfree(cap);
2251 return NULL;
2252 }
2253
2254 static struct i915_request *
active_context(struct intel_engine_cs * engine,u32 ccid)2255 active_context(struct intel_engine_cs *engine, u32 ccid)
2256 {
2257 const struct intel_engine_execlists * const el = &engine->execlists;
2258 struct i915_request * const *port, *rq;
2259
2260 /*
2261 * Use the most recent result from process_csb(), but just in case
2262 * we trigger an error (via interrupt) before the first CS event has
2263 * been written, peek at the next submission.
2264 */
2265
2266 for (port = el->active; (rq = *port); port++) {
2267 if (rq->context->lrc.ccid == ccid) {
2268 ENGINE_TRACE(engine,
2269 "ccid:%x found at active:%zd\n",
2270 ccid, port - el->active);
2271 return rq;
2272 }
2273 }
2274
2275 for (port = el->pending; (rq = *port); port++) {
2276 if (rq->context->lrc.ccid == ccid) {
2277 ENGINE_TRACE(engine,
2278 "ccid:%x found at pending:%zd\n",
2279 ccid, port - el->pending);
2280 return rq;
2281 }
2282 }
2283
2284 ENGINE_TRACE(engine, "ccid:%x not found\n", ccid);
2285 return NULL;
2286 }
2287
active_ccid(struct intel_engine_cs * engine)2288 static u32 active_ccid(struct intel_engine_cs *engine)
2289 {
2290 return ENGINE_READ_FW(engine, RING_EXECLIST_STATUS_HI);
2291 }
2292
execlists_capture(struct intel_engine_cs * engine)2293 static void execlists_capture(struct intel_engine_cs *engine)
2294 {
2295 struct execlists_capture *cap;
2296
2297 if (!IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR))
2298 return;
2299
2300 /*
2301 * We need to _quickly_ capture the engine state before we reset.
2302 * We are inside an atomic section (softirq) here and we are delaying
2303 * the forced preemption event.
2304 */
2305 cap = capture_regs(engine);
2306 if (!cap)
2307 return;
2308
2309 spin_lock_irq(&engine->sched_engine->lock);
2310 cap->rq = active_context(engine, active_ccid(engine));
2311 if (cap->rq) {
2312 cap->rq = active_request(cap->rq->context->timeline, cap->rq);
2313 cap->rq = i915_request_get_rcu(cap->rq);
2314 }
2315 spin_unlock_irq(&engine->sched_engine->lock);
2316 if (!cap->rq)
2317 goto err_free;
2318
2319 /*
2320 * Remove the request from the execlists queue, and take ownership
2321 * of the request. We pass it to our worker who will _slowly_ compress
2322 * all the pages the _user_ requested for debugging their batch, after
2323 * which we return it to the queue for signaling.
2324 *
2325 * By removing them from the execlists queue, we also remove the
2326 * requests from being processed by __unwind_incomplete_requests()
2327 * during the intel_engine_reset(), and so they will *not* be replayed
2328 * afterwards.
2329 *
2330 * Note that because we have not yet reset the engine at this point,
2331 * it is possible for the request that we have identified as being
2332 * guilty, did in fact complete and we will then hit an arbitration
2333 * point allowing the outstanding preemption to succeed. The likelihood
2334 * of that is very low (as capturing of the engine registers should be
2335 * fast enough to run inside an irq-off atomic section!), so we will
2336 * simply hold that request accountable for being non-preemptible
2337 * long enough to force the reset.
2338 */
2339 if (!execlists_hold(engine, cap->rq))
2340 goto err_rq;
2341
2342 INIT_WORK(&cap->work, execlists_capture_work);
2343 schedule_work(&cap->work);
2344 return;
2345
2346 err_rq:
2347 i915_request_put(cap->rq);
2348 err_free:
2349 i915_gpu_coredump_put(cap->error);
2350 kfree(cap);
2351 }
2352
execlists_reset(struct intel_engine_cs * engine,const char * msg)2353 static void execlists_reset(struct intel_engine_cs *engine, const char *msg)
2354 {
2355 const unsigned int bit = I915_RESET_ENGINE + engine->id;
2356 unsigned long *lock = &engine->gt->reset.flags;
2357
2358 if (!intel_has_reset_engine(engine->gt))
2359 return;
2360
2361 if (test_and_set_bit(bit, lock))
2362 return;
2363
2364 ENGINE_TRACE(engine, "reset for %s\n", msg);
2365
2366 /* Mark this tasklet as disabled to avoid waiting for it to complete */
2367 tasklet_disable_nosync(&engine->sched_engine->tasklet);
2368
2369 ring_set_paused(engine, 1); /* Freeze the current request in place */
2370 execlists_capture(engine);
2371 intel_engine_reset(engine, msg);
2372
2373 tasklet_enable(&engine->sched_engine->tasklet);
2374 clear_and_wake_up_bit(bit, lock);
2375 }
2376
preempt_timeout(const struct intel_engine_cs * const engine)2377 static bool preempt_timeout(const struct intel_engine_cs *const engine)
2378 {
2379 const struct timer_list *t = &engine->execlists.preempt;
2380
2381 if (!CONFIG_DRM_I915_PREEMPT_TIMEOUT)
2382 return false;
2383
2384 if (!timer_expired(t))
2385 return false;
2386
2387 return engine->execlists.pending[0];
2388 }
2389
2390 /*
2391 * Check the unread Context Status Buffers and manage the submission of new
2392 * contexts to the ELSP accordingly.
2393 */
execlists_submission_tasklet(struct tasklet_struct * t)2394 static void execlists_submission_tasklet(struct tasklet_struct *t)
2395 {
2396 struct i915_sched_engine *sched_engine =
2397 from_tasklet(sched_engine, t, tasklet);
2398 struct intel_engine_cs * const engine = sched_engine->private_data;
2399 struct i915_request *post[2 * EXECLIST_MAX_PORTS];
2400 struct i915_request **inactive;
2401
2402 rcu_read_lock();
2403 inactive = process_csb(engine, post);
2404 GEM_BUG_ON(inactive - post > ARRAY_SIZE(post));
2405
2406 if (unlikely(preempt_timeout(engine))) {
2407 const struct i915_request *rq = *engine->execlists.active;
2408
2409 /*
2410 * If after the preempt-timeout expired, we are still on the
2411 * same active request/context as before we initiated the
2412 * preemption, reset the engine.
2413 *
2414 * However, if we have processed a CS event to switch contexts,
2415 * but not yet processed the CS event for the pending
2416 * preemption, reset the timer allowing the new context to
2417 * gracefully exit.
2418 */
2419 cancel_timer(&engine->execlists.preempt);
2420 if (rq == engine->execlists.preempt_target)
2421 engine->execlists.error_interrupt |= ERROR_PREEMPT;
2422 else
2423 set_timer_ms(&engine->execlists.preempt,
2424 active_preempt_timeout(engine, rq));
2425 }
2426
2427 if (unlikely(READ_ONCE(engine->execlists.error_interrupt))) {
2428 const char *msg;
2429
2430 /* Generate the error message in priority wrt to the user! */
2431 if (engine->execlists.error_interrupt & GENMASK(15, 0))
2432 msg = "CS error"; /* thrown by a user payload */
2433 else if (engine->execlists.error_interrupt & ERROR_CSB)
2434 msg = "invalid CSB event";
2435 else if (engine->execlists.error_interrupt & ERROR_PREEMPT)
2436 msg = "preemption time out";
2437 else
2438 msg = "internal error";
2439
2440 engine->execlists.error_interrupt = 0;
2441 execlists_reset(engine, msg);
2442 }
2443
2444 if (!engine->execlists.pending[0]) {
2445 execlists_dequeue_irq(engine);
2446 start_timeslice(engine);
2447 }
2448
2449 post_process_csb(post, inactive);
2450 rcu_read_unlock();
2451 }
2452
execlists_irq_handler(struct intel_engine_cs * engine,u16 iir)2453 static void execlists_irq_handler(struct intel_engine_cs *engine, u16 iir)
2454 {
2455 bool tasklet = false;
2456
2457 if (unlikely(iir & GT_CS_MASTER_ERROR_INTERRUPT)) {
2458 u32 eir;
2459
2460 /* Upper 16b are the enabling mask, rsvd for internal errors */
2461 eir = ENGINE_READ(engine, RING_EIR) & GENMASK(15, 0);
2462 ENGINE_TRACE(engine, "CS error: %x\n", eir);
2463
2464 /* Disable the error interrupt until after the reset */
2465 if (likely(eir)) {
2466 ENGINE_WRITE(engine, RING_EMR, ~0u);
2467 ENGINE_WRITE(engine, RING_EIR, eir);
2468 WRITE_ONCE(engine->execlists.error_interrupt, eir);
2469 tasklet = true;
2470 }
2471 }
2472
2473 if (iir & GT_WAIT_SEMAPHORE_INTERRUPT) {
2474 WRITE_ONCE(engine->execlists.yield,
2475 ENGINE_READ_FW(engine, RING_EXECLIST_STATUS_HI));
2476 ENGINE_TRACE(engine, "semaphore yield: %08x\n",
2477 engine->execlists.yield);
2478 if (del_timer(&engine->execlists.timer))
2479 tasklet = true;
2480 }
2481
2482 if (iir & GT_CONTEXT_SWITCH_INTERRUPT)
2483 tasklet = true;
2484
2485 if (iir & GT_RENDER_USER_INTERRUPT)
2486 intel_engine_signal_breadcrumbs(engine);
2487
2488 if (tasklet)
2489 tasklet_hi_schedule(&engine->sched_engine->tasklet);
2490 }
2491
__execlists_kick(struct intel_engine_execlists * execlists)2492 static void __execlists_kick(struct intel_engine_execlists *execlists)
2493 {
2494 struct intel_engine_cs *engine =
2495 container_of(execlists, typeof(*engine), execlists);
2496
2497 /* Kick the tasklet for some interrupt coalescing and reset handling */
2498 tasklet_hi_schedule(&engine->sched_engine->tasklet);
2499 }
2500
2501 #define execlists_kick(t, member) \
2502 __execlists_kick(container_of(t, struct intel_engine_execlists, member))
2503
execlists_timeslice(struct timer_list * timer)2504 static void execlists_timeslice(struct timer_list *timer)
2505 {
2506 execlists_kick(timer, timer);
2507 }
2508
execlists_preempt(struct timer_list * timer)2509 static void execlists_preempt(struct timer_list *timer)
2510 {
2511 execlists_kick(timer, preempt);
2512 }
2513
queue_request(struct intel_engine_cs * engine,struct i915_request * rq)2514 static void queue_request(struct intel_engine_cs *engine,
2515 struct i915_request *rq)
2516 {
2517 GEM_BUG_ON(!list_empty(&rq->sched.link));
2518 list_add_tail(&rq->sched.link,
2519 i915_sched_lookup_priolist(engine->sched_engine,
2520 rq_prio(rq)));
2521 set_bit(I915_FENCE_FLAG_PQUEUE, &rq->fence.flags);
2522 }
2523
submit_queue(struct intel_engine_cs * engine,const struct i915_request * rq)2524 static bool submit_queue(struct intel_engine_cs *engine,
2525 const struct i915_request *rq)
2526 {
2527 struct i915_sched_engine *sched_engine = engine->sched_engine;
2528
2529 if (rq_prio(rq) <= sched_engine->queue_priority_hint)
2530 return false;
2531
2532 sched_engine->queue_priority_hint = rq_prio(rq);
2533 return true;
2534 }
2535
ancestor_on_hold(const struct intel_engine_cs * engine,const struct i915_request * rq)2536 static bool ancestor_on_hold(const struct intel_engine_cs *engine,
2537 const struct i915_request *rq)
2538 {
2539 GEM_BUG_ON(i915_request_on_hold(rq));
2540 return !list_empty(&engine->sched_engine->hold) && hold_request(rq);
2541 }
2542
execlists_submit_request(struct i915_request * request)2543 static void execlists_submit_request(struct i915_request *request)
2544 {
2545 struct intel_engine_cs *engine = request->engine;
2546 unsigned long flags;
2547
2548 /* Will be called from irq-context when using foreign fences. */
2549 spin_lock_irqsave(&engine->sched_engine->lock, flags);
2550
2551 if (unlikely(ancestor_on_hold(engine, request))) {
2552 RQ_TRACE(request, "ancestor on hold\n");
2553 list_add_tail(&request->sched.link,
2554 &engine->sched_engine->hold);
2555 i915_request_set_hold(request);
2556 } else {
2557 queue_request(engine, request);
2558
2559 GEM_BUG_ON(i915_sched_engine_is_empty(engine->sched_engine));
2560 GEM_BUG_ON(list_empty(&request->sched.link));
2561
2562 if (submit_queue(engine, request))
2563 __execlists_kick(&engine->execlists);
2564 }
2565
2566 spin_unlock_irqrestore(&engine->sched_engine->lock, flags);
2567 }
2568
2569 static int
__execlists_context_pre_pin(struct intel_context * ce,struct intel_engine_cs * engine,struct i915_gem_ww_ctx * ww,void ** vaddr)2570 __execlists_context_pre_pin(struct intel_context *ce,
2571 struct intel_engine_cs *engine,
2572 struct i915_gem_ww_ctx *ww, void **vaddr)
2573 {
2574 int err;
2575
2576 err = lrc_pre_pin(ce, engine, ww, vaddr);
2577 if (err)
2578 return err;
2579
2580 if (!__test_and_set_bit(CONTEXT_INIT_BIT, &ce->flags)) {
2581 lrc_init_state(ce, engine, *vaddr);
2582
2583 __i915_gem_object_flush_map(ce->state->obj, 0, engine->context_size);
2584 }
2585
2586 return 0;
2587 }
2588
execlists_context_pre_pin(struct intel_context * ce,struct i915_gem_ww_ctx * ww,void ** vaddr)2589 static int execlists_context_pre_pin(struct intel_context *ce,
2590 struct i915_gem_ww_ctx *ww,
2591 void **vaddr)
2592 {
2593 return __execlists_context_pre_pin(ce, ce->engine, ww, vaddr);
2594 }
2595
execlists_context_pin(struct intel_context * ce,void * vaddr)2596 static int execlists_context_pin(struct intel_context *ce, void *vaddr)
2597 {
2598 return lrc_pin(ce, ce->engine, vaddr);
2599 }
2600
execlists_context_alloc(struct intel_context * ce)2601 static int execlists_context_alloc(struct intel_context *ce)
2602 {
2603 return lrc_alloc(ce, ce->engine);
2604 }
2605
execlists_context_cancel_request(struct intel_context * ce,struct i915_request * rq)2606 static void execlists_context_cancel_request(struct intel_context *ce,
2607 struct i915_request *rq)
2608 {
2609 struct intel_engine_cs *engine = NULL;
2610
2611 i915_request_active_engine(rq, &engine);
2612
2613 if (engine && intel_engine_pulse(engine))
2614 intel_gt_handle_error(engine->gt, engine->mask, 0,
2615 "request cancellation by %s",
2616 current->comm);
2617 }
2618
2619 static const struct intel_context_ops execlists_context_ops = {
2620 .flags = COPS_HAS_INFLIGHT,
2621
2622 .alloc = execlists_context_alloc,
2623
2624 .cancel_request = execlists_context_cancel_request,
2625
2626 .pre_pin = execlists_context_pre_pin,
2627 .pin = execlists_context_pin,
2628 .unpin = lrc_unpin,
2629 .post_unpin = lrc_post_unpin,
2630
2631 .enter = intel_context_enter_engine,
2632 .exit = intel_context_exit_engine,
2633
2634 .reset = lrc_reset,
2635 .destroy = lrc_destroy,
2636
2637 .create_virtual = execlists_create_virtual,
2638 };
2639
emit_pdps(struct i915_request * rq)2640 static int emit_pdps(struct i915_request *rq)
2641 {
2642 const struct intel_engine_cs * const engine = rq->engine;
2643 struct i915_ppgtt * const ppgtt = i915_vm_to_ppgtt(rq->context->vm);
2644 int err, i;
2645 u32 *cs;
2646
2647 GEM_BUG_ON(intel_vgpu_active(rq->engine->i915));
2648
2649 /*
2650 * Beware ye of the dragons, this sequence is magic!
2651 *
2652 * Small changes to this sequence can cause anything from
2653 * GPU hangs to forcewake errors and machine lockups!
2654 */
2655
2656 cs = intel_ring_begin(rq, 2);
2657 if (IS_ERR(cs))
2658 return PTR_ERR(cs);
2659
2660 *cs++ = MI_ARB_ON_OFF | MI_ARB_DISABLE;
2661 *cs++ = MI_NOOP;
2662 intel_ring_advance(rq, cs);
2663
2664 /* Flush any residual operations from the context load */
2665 err = engine->emit_flush(rq, EMIT_FLUSH);
2666 if (err)
2667 return err;
2668
2669 /* Magic required to prevent forcewake errors! */
2670 err = engine->emit_flush(rq, EMIT_INVALIDATE);
2671 if (err)
2672 return err;
2673
2674 cs = intel_ring_begin(rq, 4 * GEN8_3LVL_PDPES + 2);
2675 if (IS_ERR(cs))
2676 return PTR_ERR(cs);
2677
2678 /* Ensure the LRI have landed before we invalidate & continue */
2679 *cs++ = MI_LOAD_REGISTER_IMM(2 * GEN8_3LVL_PDPES) | MI_LRI_FORCE_POSTED;
2680 for (i = GEN8_3LVL_PDPES; i--; ) {
2681 const dma_addr_t pd_daddr = i915_page_dir_dma_addr(ppgtt, i);
2682 u32 base = engine->mmio_base;
2683
2684 *cs++ = i915_mmio_reg_offset(GEN8_RING_PDP_UDW(base, i));
2685 *cs++ = upper_32_bits(pd_daddr);
2686 *cs++ = i915_mmio_reg_offset(GEN8_RING_PDP_LDW(base, i));
2687 *cs++ = lower_32_bits(pd_daddr);
2688 }
2689 *cs++ = MI_ARB_ON_OFF | MI_ARB_ENABLE;
2690 intel_ring_advance(rq, cs);
2691
2692 intel_ring_advance(rq, cs);
2693
2694 return 0;
2695 }
2696
execlists_request_alloc(struct i915_request * request)2697 static int execlists_request_alloc(struct i915_request *request)
2698 {
2699 int ret;
2700
2701 GEM_BUG_ON(!intel_context_is_pinned(request->context));
2702
2703 /*
2704 * Flush enough space to reduce the likelihood of waiting after
2705 * we start building the request - in which case we will just
2706 * have to repeat work.
2707 */
2708 request->reserved_space += EXECLISTS_REQUEST_SIZE;
2709
2710 /*
2711 * Note that after this point, we have committed to using
2712 * this request as it is being used to both track the
2713 * state of engine initialisation and liveness of the
2714 * golden renderstate above. Think twice before you try
2715 * to cancel/unwind this request now.
2716 */
2717
2718 if (!i915_vm_is_4lvl(request->context->vm)) {
2719 ret = emit_pdps(request);
2720 if (ret)
2721 return ret;
2722 }
2723
2724 /* Unconditionally invalidate GPU caches and TLBs. */
2725 ret = request->engine->emit_flush(request, EMIT_INVALIDATE);
2726 if (ret)
2727 return ret;
2728
2729 request->reserved_space -= EXECLISTS_REQUEST_SIZE;
2730 return 0;
2731 }
2732
reset_csb_pointers(struct intel_engine_cs * engine)2733 static void reset_csb_pointers(struct intel_engine_cs *engine)
2734 {
2735 struct intel_engine_execlists * const execlists = &engine->execlists;
2736 const unsigned int reset_value = execlists->csb_size - 1;
2737
2738 ring_set_paused(engine, 0);
2739
2740 /*
2741 * Sometimes Icelake forgets to reset its pointers on a GPU reset.
2742 * Bludgeon them with a mmio update to be sure.
2743 */
2744 ENGINE_WRITE(engine, RING_CONTEXT_STATUS_PTR,
2745 0xffff << 16 | reset_value << 8 | reset_value);
2746 ENGINE_POSTING_READ(engine, RING_CONTEXT_STATUS_PTR);
2747
2748 /*
2749 * After a reset, the HW starts writing into CSB entry [0]. We
2750 * therefore have to set our HEAD pointer back one entry so that
2751 * the *first* entry we check is entry 0. To complicate this further,
2752 * as we don't wait for the first interrupt after reset, we have to
2753 * fake the HW write to point back to the last entry so that our
2754 * inline comparison of our cached head position against the last HW
2755 * write works even before the first interrupt.
2756 */
2757 execlists->csb_head = reset_value;
2758 WRITE_ONCE(*execlists->csb_write, reset_value);
2759 wmb(); /* Make sure this is visible to HW (paranoia?) */
2760
2761 /* Check that the GPU does indeed update the CSB entries! */
2762 memset(execlists->csb_status, -1, (reset_value + 1) * sizeof(u64));
2763 invalidate_csb_entries(&execlists->csb_status[0],
2764 &execlists->csb_status[reset_value]);
2765
2766 /* Once more for luck and our trusty paranoia */
2767 ENGINE_WRITE(engine, RING_CONTEXT_STATUS_PTR,
2768 0xffff << 16 | reset_value << 8 | reset_value);
2769 ENGINE_POSTING_READ(engine, RING_CONTEXT_STATUS_PTR);
2770
2771 GEM_BUG_ON(READ_ONCE(*execlists->csb_write) != reset_value);
2772 }
2773
sanitize_hwsp(struct intel_engine_cs * engine)2774 static void sanitize_hwsp(struct intel_engine_cs *engine)
2775 {
2776 struct intel_timeline *tl;
2777
2778 list_for_each_entry(tl, &engine->status_page.timelines, engine_link)
2779 intel_timeline_reset_seqno(tl);
2780 }
2781
execlists_sanitize(struct intel_engine_cs * engine)2782 static void execlists_sanitize(struct intel_engine_cs *engine)
2783 {
2784 GEM_BUG_ON(execlists_active(&engine->execlists));
2785
2786 /*
2787 * Poison residual state on resume, in case the suspend didn't!
2788 *
2789 * We have to assume that across suspend/resume (or other loss
2790 * of control) that the contents of our pinned buffers has been
2791 * lost, replaced by garbage. Since this doesn't always happen,
2792 * let's poison such state so that we more quickly spot when
2793 * we falsely assume it has been preserved.
2794 */
2795 if (IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM))
2796 memset(engine->status_page.addr, POISON_INUSE, PAGE_SIZE);
2797
2798 reset_csb_pointers(engine);
2799
2800 /*
2801 * The kernel_context HWSP is stored in the status_page. As above,
2802 * that may be lost on resume/initialisation, and so we need to
2803 * reset the value in the HWSP.
2804 */
2805 sanitize_hwsp(engine);
2806
2807 /* And scrub the dirty cachelines for the HWSP */
2808 clflush_cache_range(engine->status_page.addr, PAGE_SIZE);
2809
2810 intel_engine_reset_pinned_contexts(engine);
2811 }
2812
enable_error_interrupt(struct intel_engine_cs * engine)2813 static void enable_error_interrupt(struct intel_engine_cs *engine)
2814 {
2815 u32 status;
2816
2817 engine->execlists.error_interrupt = 0;
2818 ENGINE_WRITE(engine, RING_EMR, ~0u);
2819 ENGINE_WRITE(engine, RING_EIR, ~0u); /* clear all existing errors */
2820
2821 status = ENGINE_READ(engine, RING_ESR);
2822 if (unlikely(status)) {
2823 drm_err(&engine->i915->drm,
2824 "engine '%s' resumed still in error: %08x\n",
2825 engine->name, status);
2826 __intel_gt_reset(engine->gt, engine->mask);
2827 }
2828
2829 /*
2830 * On current gen8+, we have 2 signals to play with
2831 *
2832 * - I915_ERROR_INSTUCTION (bit 0)
2833 *
2834 * Generate an error if the command parser encounters an invalid
2835 * instruction
2836 *
2837 * This is a fatal error.
2838 *
2839 * - CP_PRIV (bit 2)
2840 *
2841 * Generate an error on privilege violation (where the CP replaces
2842 * the instruction with a no-op). This also fires for writes into
2843 * read-only scratch pages.
2844 *
2845 * This is a non-fatal error, parsing continues.
2846 *
2847 * * there are a few others defined for odd HW that we do not use
2848 *
2849 * Since CP_PRIV fires for cases where we have chosen to ignore the
2850 * error (as the HW is validating and suppressing the mistakes), we
2851 * only unmask the instruction error bit.
2852 */
2853 ENGINE_WRITE(engine, RING_EMR, ~I915_ERROR_INSTRUCTION);
2854 }
2855
enable_execlists(struct intel_engine_cs * engine)2856 static void enable_execlists(struct intel_engine_cs *engine)
2857 {
2858 u32 mode;
2859
2860 assert_forcewakes_active(engine->uncore, FORCEWAKE_ALL);
2861
2862 intel_engine_set_hwsp_writemask(engine, ~0u); /* HWSTAM */
2863
2864 if (GRAPHICS_VER(engine->i915) >= 11)
2865 mode = _MASKED_BIT_ENABLE(GEN11_GFX_DISABLE_LEGACY_MODE);
2866 else
2867 mode = _MASKED_BIT_ENABLE(GFX_RUN_LIST_ENABLE);
2868 ENGINE_WRITE_FW(engine, RING_MODE_GEN7, mode);
2869
2870 ENGINE_WRITE_FW(engine, RING_MI_MODE, _MASKED_BIT_DISABLE(STOP_RING));
2871
2872 ENGINE_WRITE_FW(engine,
2873 RING_HWS_PGA,
2874 i915_ggtt_offset(engine->status_page.vma));
2875 ENGINE_POSTING_READ(engine, RING_HWS_PGA);
2876
2877 enable_error_interrupt(engine);
2878 }
2879
execlists_resume(struct intel_engine_cs * engine)2880 static int execlists_resume(struct intel_engine_cs *engine)
2881 {
2882 intel_mocs_init_engine(engine);
2883 intel_breadcrumbs_reset(engine->breadcrumbs);
2884
2885 enable_execlists(engine);
2886
2887 return 0;
2888 }
2889
execlists_reset_prepare(struct intel_engine_cs * engine)2890 static void execlists_reset_prepare(struct intel_engine_cs *engine)
2891 {
2892 ENGINE_TRACE(engine, "depth<-%d\n",
2893 atomic_read(&engine->sched_engine->tasklet.count));
2894
2895 /*
2896 * Prevent request submission to the hardware until we have
2897 * completed the reset in i915_gem_reset_finish(). If a request
2898 * is completed by one engine, it may then queue a request
2899 * to a second via its execlists->tasklet *just* as we are
2900 * calling engine->resume() and also writing the ELSP.
2901 * Turning off the execlists->tasklet until the reset is over
2902 * prevents the race.
2903 */
2904 __tasklet_disable_sync_once(&engine->sched_engine->tasklet);
2905 GEM_BUG_ON(!reset_in_progress(engine));
2906
2907 /*
2908 * We stop engines, otherwise we might get failed reset and a
2909 * dead gpu (on elk). Also as modern gpu as kbl can suffer
2910 * from system hang if batchbuffer is progressing when
2911 * the reset is issued, regardless of READY_TO_RESET ack.
2912 * Thus assume it is best to stop engines on all gens
2913 * where we have a gpu reset.
2914 *
2915 * WaKBLVECSSemaphoreWaitPoll:kbl (on ALL_ENGINES)
2916 *
2917 * FIXME: Wa for more modern gens needs to be validated
2918 */
2919 ring_set_paused(engine, 1);
2920 intel_engine_stop_cs(engine);
2921
2922 engine->execlists.reset_ccid = active_ccid(engine);
2923 }
2924
2925 static struct i915_request **
reset_csb(struct intel_engine_cs * engine,struct i915_request ** inactive)2926 reset_csb(struct intel_engine_cs *engine, struct i915_request **inactive)
2927 {
2928 struct intel_engine_execlists * const execlists = &engine->execlists;
2929
2930 mb(); /* paranoia: read the CSB pointers from after the reset */
2931 clflush(execlists->csb_write);
2932 mb();
2933
2934 inactive = process_csb(engine, inactive); /* drain preemption events */
2935
2936 /* Following the reset, we need to reload the CSB read/write pointers */
2937 reset_csb_pointers(engine);
2938
2939 return inactive;
2940 }
2941
2942 static void
execlists_reset_active(struct intel_engine_cs * engine,bool stalled)2943 execlists_reset_active(struct intel_engine_cs *engine, bool stalled)
2944 {
2945 struct intel_context *ce;
2946 struct i915_request *rq;
2947 u32 head;
2948
2949 /*
2950 * Save the currently executing context, even if we completed
2951 * its request, it was still running at the time of the
2952 * reset and will have been clobbered.
2953 */
2954 rq = active_context(engine, engine->execlists.reset_ccid);
2955 if (!rq)
2956 return;
2957
2958 ce = rq->context;
2959 GEM_BUG_ON(!i915_vma_is_pinned(ce->state));
2960
2961 if (__i915_request_is_complete(rq)) {
2962 /* Idle context; tidy up the ring so we can restart afresh */
2963 head = intel_ring_wrap(ce->ring, rq->tail);
2964 goto out_replay;
2965 }
2966
2967 /* We still have requests in-flight; the engine should be active */
2968 GEM_BUG_ON(!intel_engine_pm_is_awake(engine));
2969
2970 /* Context has requests still in-flight; it should not be idle! */
2971 GEM_BUG_ON(i915_active_is_idle(&ce->active));
2972
2973 rq = active_request(ce->timeline, rq);
2974 head = intel_ring_wrap(ce->ring, rq->head);
2975 GEM_BUG_ON(head == ce->ring->tail);
2976
2977 /*
2978 * If this request hasn't started yet, e.g. it is waiting on a
2979 * semaphore, we need to avoid skipping the request or else we
2980 * break the signaling chain. However, if the context is corrupt
2981 * the request will not restart and we will be stuck with a wedged
2982 * device. It is quite often the case that if we issue a reset
2983 * while the GPU is loading the context image, that the context
2984 * image becomes corrupt.
2985 *
2986 * Otherwise, if we have not started yet, the request should replay
2987 * perfectly and we do not need to flag the result as being erroneous.
2988 */
2989 if (!__i915_request_has_started(rq))
2990 goto out_replay;
2991
2992 /*
2993 * If the request was innocent, we leave the request in the ELSP
2994 * and will try to replay it on restarting. The context image may
2995 * have been corrupted by the reset, in which case we may have
2996 * to service a new GPU hang, but more likely we can continue on
2997 * without impact.
2998 *
2999 * If the request was guilty, we presume the context is corrupt
3000 * and have to at least restore the RING register in the context
3001 * image back to the expected values to skip over the guilty request.
3002 */
3003 __i915_request_reset(rq, stalled);
3004
3005 /*
3006 * We want a simple context + ring to execute the breadcrumb update.
3007 * We cannot rely on the context being intact across the GPU hang,
3008 * so clear it and rebuild just what we need for the breadcrumb.
3009 * All pending requests for this context will be zapped, and any
3010 * future request will be after userspace has had the opportunity
3011 * to recreate its own state.
3012 */
3013 out_replay:
3014 ENGINE_TRACE(engine, "replay {head:%04x, tail:%04x}\n",
3015 head, ce->ring->tail);
3016 lrc_reset_regs(ce, engine);
3017 ce->lrc.lrca = lrc_update_regs(ce, engine, head);
3018 }
3019
execlists_reset_csb(struct intel_engine_cs * engine,bool stalled)3020 static void execlists_reset_csb(struct intel_engine_cs *engine, bool stalled)
3021 {
3022 struct intel_engine_execlists * const execlists = &engine->execlists;
3023 struct i915_request *post[2 * EXECLIST_MAX_PORTS];
3024 struct i915_request **inactive;
3025
3026 rcu_read_lock();
3027 inactive = reset_csb(engine, post);
3028
3029 execlists_reset_active(engine, true);
3030
3031 inactive = cancel_port_requests(execlists, inactive);
3032 post_process_csb(post, inactive);
3033 rcu_read_unlock();
3034 }
3035
execlists_reset_rewind(struct intel_engine_cs * engine,bool stalled)3036 static void execlists_reset_rewind(struct intel_engine_cs *engine, bool stalled)
3037 {
3038 unsigned long flags;
3039
3040 ENGINE_TRACE(engine, "\n");
3041
3042 /* Process the csb, find the guilty context and throw away */
3043 execlists_reset_csb(engine, stalled);
3044
3045 /* Push back any incomplete requests for replay after the reset. */
3046 rcu_read_lock();
3047 spin_lock_irqsave(&engine->sched_engine->lock, flags);
3048 __unwind_incomplete_requests(engine);
3049 spin_unlock_irqrestore(&engine->sched_engine->lock, flags);
3050 rcu_read_unlock();
3051 }
3052
nop_submission_tasklet(struct tasklet_struct * t)3053 static void nop_submission_tasklet(struct tasklet_struct *t)
3054 {
3055 struct i915_sched_engine *sched_engine =
3056 from_tasklet(sched_engine, t, tasklet);
3057 struct intel_engine_cs * const engine = sched_engine->private_data;
3058
3059 /* The driver is wedged; don't process any more events. */
3060 WRITE_ONCE(engine->sched_engine->queue_priority_hint, INT_MIN);
3061 }
3062
execlists_reset_cancel(struct intel_engine_cs * engine)3063 static void execlists_reset_cancel(struct intel_engine_cs *engine)
3064 {
3065 struct intel_engine_execlists * const execlists = &engine->execlists;
3066 struct i915_sched_engine * const sched_engine = engine->sched_engine;
3067 struct i915_request *rq, *rn;
3068 struct rb_node *rb;
3069 unsigned long flags;
3070
3071 ENGINE_TRACE(engine, "\n");
3072
3073 /*
3074 * Before we call engine->cancel_requests(), we should have exclusive
3075 * access to the submission state. This is arranged for us by the
3076 * caller disabling the interrupt generation, the tasklet and other
3077 * threads that may then access the same state, giving us a free hand
3078 * to reset state. However, we still need to let lockdep be aware that
3079 * we know this state may be accessed in hardirq context, so we
3080 * disable the irq around this manipulation and we want to keep
3081 * the spinlock focused on its duties and not accidentally conflate
3082 * coverage to the submission's irq state. (Similarly, although we
3083 * shouldn't need to disable irq around the manipulation of the
3084 * submission's irq state, we also wish to remind ourselves that
3085 * it is irq state.)
3086 */
3087 execlists_reset_csb(engine, true);
3088
3089 rcu_read_lock();
3090 spin_lock_irqsave(&engine->sched_engine->lock, flags);
3091
3092 /* Mark all executing requests as skipped. */
3093 list_for_each_entry(rq, &engine->sched_engine->requests, sched.link)
3094 i915_request_put(i915_request_mark_eio(rq));
3095 intel_engine_signal_breadcrumbs(engine);
3096
3097 /* Flush the queued requests to the timeline list (for retiring). */
3098 while ((rb = rb_first_cached(&sched_engine->queue))) {
3099 struct i915_priolist *p = to_priolist(rb);
3100
3101 priolist_for_each_request_consume(rq, rn, p) {
3102 if (i915_request_mark_eio(rq)) {
3103 __i915_request_submit(rq);
3104 i915_request_put(rq);
3105 }
3106 }
3107
3108 rb_erase_cached(&p->node, &sched_engine->queue);
3109 i915_priolist_free(p);
3110 }
3111
3112 /* On-hold requests will be flushed to timeline upon their release */
3113 list_for_each_entry(rq, &sched_engine->hold, sched.link)
3114 i915_request_put(i915_request_mark_eio(rq));
3115
3116 /* Cancel all attached virtual engines */
3117 while ((rb = rb_first_cached(&execlists->virtual))) {
3118 struct virtual_engine *ve =
3119 rb_entry(rb, typeof(*ve), nodes[engine->id].rb);
3120
3121 rb_erase_cached(rb, &execlists->virtual);
3122 RB_CLEAR_NODE(rb);
3123
3124 spin_lock(&ve->base.sched_engine->lock);
3125 rq = fetch_and_zero(&ve->request);
3126 if (rq) {
3127 if (i915_request_mark_eio(rq)) {
3128 rq->engine = engine;
3129 __i915_request_submit(rq);
3130 i915_request_put(rq);
3131 }
3132 i915_request_put(rq);
3133
3134 ve->base.sched_engine->queue_priority_hint = INT_MIN;
3135 }
3136 spin_unlock(&ve->base.sched_engine->lock);
3137 }
3138
3139 /* Remaining _unready_ requests will be nop'ed when submitted */
3140
3141 sched_engine->queue_priority_hint = INT_MIN;
3142 sched_engine->queue = RB_ROOT_CACHED;
3143
3144 GEM_BUG_ON(__tasklet_is_enabled(&engine->sched_engine->tasklet));
3145 engine->sched_engine->tasklet.callback = nop_submission_tasklet;
3146
3147 spin_unlock_irqrestore(&engine->sched_engine->lock, flags);
3148 rcu_read_unlock();
3149 }
3150
execlists_reset_finish(struct intel_engine_cs * engine)3151 static void execlists_reset_finish(struct intel_engine_cs *engine)
3152 {
3153 struct intel_engine_execlists * const execlists = &engine->execlists;
3154
3155 /*
3156 * After a GPU reset, we may have requests to replay. Do so now while
3157 * we still have the forcewake to be sure that the GPU is not allowed
3158 * to sleep before we restart and reload a context.
3159 *
3160 * If the GPU reset fails, the engine may still be alive with requests
3161 * inflight. We expect those to complete, or for the device to be
3162 * reset as the next level of recovery, and as a final resort we
3163 * will declare the device wedged.
3164 */
3165 GEM_BUG_ON(!reset_in_progress(engine));
3166
3167 /* And kick in case we missed a new request submission. */
3168 if (__tasklet_enable(&engine->sched_engine->tasklet))
3169 __execlists_kick(execlists);
3170
3171 ENGINE_TRACE(engine, "depth->%d\n",
3172 atomic_read(&engine->sched_engine->tasklet.count));
3173 }
3174
gen8_logical_ring_enable_irq(struct intel_engine_cs * engine)3175 static void gen8_logical_ring_enable_irq(struct intel_engine_cs *engine)
3176 {
3177 ENGINE_WRITE(engine, RING_IMR,
3178 ~(engine->irq_enable_mask | engine->irq_keep_mask));
3179 ENGINE_POSTING_READ(engine, RING_IMR);
3180 }
3181
gen8_logical_ring_disable_irq(struct intel_engine_cs * engine)3182 static void gen8_logical_ring_disable_irq(struct intel_engine_cs *engine)
3183 {
3184 ENGINE_WRITE(engine, RING_IMR, ~engine->irq_keep_mask);
3185 }
3186
execlists_park(struct intel_engine_cs * engine)3187 static void execlists_park(struct intel_engine_cs *engine)
3188 {
3189 cancel_timer(&engine->execlists.timer);
3190 cancel_timer(&engine->execlists.preempt);
3191 }
3192
add_to_engine(struct i915_request * rq)3193 static void add_to_engine(struct i915_request *rq)
3194 {
3195 lockdep_assert_held(&rq->engine->sched_engine->lock);
3196 list_move_tail(&rq->sched.link, &rq->engine->sched_engine->requests);
3197 }
3198
remove_from_engine(struct i915_request * rq)3199 static void remove_from_engine(struct i915_request *rq)
3200 {
3201 struct intel_engine_cs *engine, *locked;
3202
3203 /*
3204 * Virtual engines complicate acquiring the engine timeline lock,
3205 * as their rq->engine pointer is not stable until under that
3206 * engine lock. The simple ploy we use is to take the lock then
3207 * check that the rq still belongs to the newly locked engine.
3208 */
3209 locked = READ_ONCE(rq->engine);
3210 spin_lock_irq(&locked->sched_engine->lock);
3211 while (unlikely(locked != (engine = READ_ONCE(rq->engine)))) {
3212 spin_unlock(&locked->sched_engine->lock);
3213 spin_lock(&engine->sched_engine->lock);
3214 locked = engine;
3215 }
3216 list_del_init(&rq->sched.link);
3217
3218 clear_bit(I915_FENCE_FLAG_PQUEUE, &rq->fence.flags);
3219 clear_bit(I915_FENCE_FLAG_HOLD, &rq->fence.flags);
3220
3221 /* Prevent further __await_execution() registering a cb, then flush */
3222 set_bit(I915_FENCE_FLAG_ACTIVE, &rq->fence.flags);
3223
3224 spin_unlock_irq(&locked->sched_engine->lock);
3225
3226 i915_request_notify_execute_cb_imm(rq);
3227 }
3228
can_preempt(struct intel_engine_cs * engine)3229 static bool can_preempt(struct intel_engine_cs *engine)
3230 {
3231 if (GRAPHICS_VER(engine->i915) > 8)
3232 return true;
3233
3234 /* GPGPU on bdw requires extra w/a; not implemented */
3235 return engine->class != RENDER_CLASS;
3236 }
3237
kick_execlists(const struct i915_request * rq,int prio)3238 static void kick_execlists(const struct i915_request *rq, int prio)
3239 {
3240 struct intel_engine_cs *engine = rq->engine;
3241 struct i915_sched_engine *sched_engine = engine->sched_engine;
3242 const struct i915_request *inflight;
3243
3244 /*
3245 * We only need to kick the tasklet once for the high priority
3246 * new context we add into the queue.
3247 */
3248 if (prio <= sched_engine->queue_priority_hint)
3249 return;
3250
3251 rcu_read_lock();
3252
3253 /* Nothing currently active? We're overdue for a submission! */
3254 inflight = execlists_active(&engine->execlists);
3255 if (!inflight)
3256 goto unlock;
3257
3258 /*
3259 * If we are already the currently executing context, don't
3260 * bother evaluating if we should preempt ourselves.
3261 */
3262 if (inflight->context == rq->context)
3263 goto unlock;
3264
3265 ENGINE_TRACE(engine,
3266 "bumping queue-priority-hint:%d for rq:%llx:%lld, inflight:%llx:%lld prio %d\n",
3267 prio,
3268 rq->fence.context, rq->fence.seqno,
3269 inflight->fence.context, inflight->fence.seqno,
3270 inflight->sched.attr.priority);
3271
3272 sched_engine->queue_priority_hint = prio;
3273
3274 /*
3275 * Allow preemption of low -> normal -> high, but we do
3276 * not allow low priority tasks to preempt other low priority
3277 * tasks under the impression that latency for low priority
3278 * tasks does not matter (as much as background throughput),
3279 * so kiss.
3280 */
3281 if (prio >= max(I915_PRIORITY_NORMAL, rq_prio(inflight)))
3282 tasklet_hi_schedule(&sched_engine->tasklet);
3283
3284 unlock:
3285 rcu_read_unlock();
3286 }
3287
execlists_set_default_submission(struct intel_engine_cs * engine)3288 static void execlists_set_default_submission(struct intel_engine_cs *engine)
3289 {
3290 engine->submit_request = execlists_submit_request;
3291 engine->sched_engine->schedule = i915_schedule;
3292 engine->sched_engine->kick_backend = kick_execlists;
3293 engine->sched_engine->tasklet.callback = execlists_submission_tasklet;
3294 }
3295
execlists_shutdown(struct intel_engine_cs * engine)3296 static void execlists_shutdown(struct intel_engine_cs *engine)
3297 {
3298 /* Synchronise with residual timers and any softirq they raise */
3299 del_timer_sync(&engine->execlists.timer);
3300 del_timer_sync(&engine->execlists.preempt);
3301 tasklet_kill(&engine->sched_engine->tasklet);
3302 }
3303
execlists_release(struct intel_engine_cs * engine)3304 static void execlists_release(struct intel_engine_cs *engine)
3305 {
3306 engine->sanitize = NULL; /* no longer in control, nothing to sanitize */
3307
3308 execlists_shutdown(engine);
3309
3310 intel_engine_cleanup_common(engine);
3311 lrc_fini_wa_ctx(engine);
3312 }
3313
3314 static void
logical_ring_default_vfuncs(struct intel_engine_cs * engine)3315 logical_ring_default_vfuncs(struct intel_engine_cs *engine)
3316 {
3317 /* Default vfuncs which can be overridden by each engine. */
3318
3319 engine->resume = execlists_resume;
3320
3321 engine->cops = &execlists_context_ops;
3322 engine->request_alloc = execlists_request_alloc;
3323 engine->add_active_request = add_to_engine;
3324 engine->remove_active_request = remove_from_engine;
3325
3326 engine->reset.prepare = execlists_reset_prepare;
3327 engine->reset.rewind = execlists_reset_rewind;
3328 engine->reset.cancel = execlists_reset_cancel;
3329 engine->reset.finish = execlists_reset_finish;
3330
3331 engine->park = execlists_park;
3332 engine->unpark = NULL;
3333
3334 engine->emit_flush = gen8_emit_flush_xcs;
3335 engine->emit_init_breadcrumb = gen8_emit_init_breadcrumb;
3336 engine->emit_fini_breadcrumb = gen8_emit_fini_breadcrumb_xcs;
3337 if (GRAPHICS_VER(engine->i915) >= 12) {
3338 engine->emit_fini_breadcrumb = gen12_emit_fini_breadcrumb_xcs;
3339 engine->emit_flush = gen12_emit_flush_xcs;
3340 }
3341 engine->set_default_submission = execlists_set_default_submission;
3342
3343 if (GRAPHICS_VER(engine->i915) < 11) {
3344 engine->irq_enable = gen8_logical_ring_enable_irq;
3345 engine->irq_disable = gen8_logical_ring_disable_irq;
3346 } else {
3347 /*
3348 * TODO: On Gen11 interrupt masks need to be clear
3349 * to allow C6 entry. Keep interrupts enabled at
3350 * and take the hit of generating extra interrupts
3351 * until a more refined solution exists.
3352 */
3353 }
3354 intel_engine_set_irq_handler(engine, execlists_irq_handler);
3355
3356 engine->flags |= I915_ENGINE_SUPPORTS_STATS;
3357 if (!intel_vgpu_active(engine->i915)) {
3358 engine->flags |= I915_ENGINE_HAS_SEMAPHORES;
3359 if (can_preempt(engine)) {
3360 engine->flags |= I915_ENGINE_HAS_PREEMPTION;
3361 if (IS_ACTIVE(CONFIG_DRM_I915_TIMESLICE_DURATION))
3362 engine->flags |= I915_ENGINE_HAS_TIMESLICES;
3363 }
3364 }
3365
3366 if (intel_engine_has_preemption(engine))
3367 engine->emit_bb_start = gen8_emit_bb_start;
3368 else
3369 engine->emit_bb_start = gen8_emit_bb_start_noarb;
3370 }
3371
logical_ring_default_irqs(struct intel_engine_cs * engine)3372 static void logical_ring_default_irqs(struct intel_engine_cs *engine)
3373 {
3374 unsigned int shift = 0;
3375
3376 if (GRAPHICS_VER(engine->i915) < 11) {
3377 const u8 irq_shifts[] = {
3378 [RCS0] = GEN8_RCS_IRQ_SHIFT,
3379 [BCS0] = GEN8_BCS_IRQ_SHIFT,
3380 [VCS0] = GEN8_VCS0_IRQ_SHIFT,
3381 [VCS1] = GEN8_VCS1_IRQ_SHIFT,
3382 [VECS0] = GEN8_VECS_IRQ_SHIFT,
3383 };
3384
3385 shift = irq_shifts[engine->id];
3386 }
3387
3388 engine->irq_enable_mask = GT_RENDER_USER_INTERRUPT << shift;
3389 engine->irq_keep_mask = GT_CONTEXT_SWITCH_INTERRUPT << shift;
3390 engine->irq_keep_mask |= GT_CS_MASTER_ERROR_INTERRUPT << shift;
3391 engine->irq_keep_mask |= GT_WAIT_SEMAPHORE_INTERRUPT << shift;
3392 }
3393
rcs_submission_override(struct intel_engine_cs * engine)3394 static void rcs_submission_override(struct intel_engine_cs *engine)
3395 {
3396 switch (GRAPHICS_VER(engine->i915)) {
3397 case 12:
3398 engine->emit_flush = gen12_emit_flush_rcs;
3399 engine->emit_fini_breadcrumb = gen12_emit_fini_breadcrumb_rcs;
3400 break;
3401 case 11:
3402 engine->emit_flush = gen11_emit_flush_rcs;
3403 engine->emit_fini_breadcrumb = gen11_emit_fini_breadcrumb_rcs;
3404 break;
3405 default:
3406 engine->emit_flush = gen8_emit_flush_rcs;
3407 engine->emit_fini_breadcrumb = gen8_emit_fini_breadcrumb_rcs;
3408 break;
3409 }
3410 }
3411
intel_execlists_submission_setup(struct intel_engine_cs * engine)3412 int intel_execlists_submission_setup(struct intel_engine_cs *engine)
3413 {
3414 struct intel_engine_execlists * const execlists = &engine->execlists;
3415 struct drm_i915_private *i915 = engine->i915;
3416 struct intel_uncore *uncore = engine->uncore;
3417 u32 base = engine->mmio_base;
3418
3419 tasklet_setup(&engine->sched_engine->tasklet, execlists_submission_tasklet);
3420 timer_setup(&engine->execlists.timer, execlists_timeslice, 0);
3421 timer_setup(&engine->execlists.preempt, execlists_preempt, 0);
3422
3423 logical_ring_default_vfuncs(engine);
3424 logical_ring_default_irqs(engine);
3425
3426 if (engine->class == RENDER_CLASS)
3427 rcs_submission_override(engine);
3428
3429 lrc_init_wa_ctx(engine);
3430
3431 if (HAS_LOGICAL_RING_ELSQ(i915)) {
3432 execlists->submit_reg = uncore->regs +
3433 i915_mmio_reg_offset(RING_EXECLIST_SQ_CONTENTS(base));
3434 execlists->ctrl_reg = uncore->regs +
3435 i915_mmio_reg_offset(RING_EXECLIST_CONTROL(base));
3436
3437 engine->fw_domain = intel_uncore_forcewake_for_reg(engine->uncore,
3438 RING_EXECLIST_CONTROL(engine->mmio_base),
3439 FW_REG_WRITE);
3440 } else {
3441 execlists->submit_reg = uncore->regs +
3442 i915_mmio_reg_offset(RING_ELSP(base));
3443 }
3444
3445 execlists->csb_status =
3446 (u64 *)&engine->status_page.addr[I915_HWS_CSB_BUF0_INDEX];
3447
3448 execlists->csb_write =
3449 &engine->status_page.addr[intel_hws_csb_write_index(i915)];
3450
3451 if (GRAPHICS_VER(i915) < 11)
3452 execlists->csb_size = GEN8_CSB_ENTRIES;
3453 else
3454 execlists->csb_size = GEN11_CSB_ENTRIES;
3455
3456 engine->context_tag = GENMASK(BITS_PER_LONG - 2, 0);
3457 if (GRAPHICS_VER(engine->i915) >= 11 &&
3458 GRAPHICS_VER_FULL(engine->i915) < IP_VER(12, 50)) {
3459 execlists->ccid |= engine->instance << (GEN11_ENGINE_INSTANCE_SHIFT - 32);
3460 execlists->ccid |= engine->class << (GEN11_ENGINE_CLASS_SHIFT - 32);
3461 }
3462
3463 /* Finally, take ownership and responsibility for cleanup! */
3464 engine->sanitize = execlists_sanitize;
3465 engine->release = execlists_release;
3466
3467 return 0;
3468 }
3469
virtual_queue(struct virtual_engine * ve)3470 static struct list_head *virtual_queue(struct virtual_engine *ve)
3471 {
3472 return &ve->base.sched_engine->default_priolist.requests;
3473 }
3474
rcu_virtual_context_destroy(struct work_struct * wrk)3475 static void rcu_virtual_context_destroy(struct work_struct *wrk)
3476 {
3477 struct virtual_engine *ve =
3478 container_of(wrk, typeof(*ve), rcu.work);
3479 unsigned int n;
3480
3481 GEM_BUG_ON(ve->context.inflight);
3482
3483 /* Preempt-to-busy may leave a stale request behind. */
3484 if (unlikely(ve->request)) {
3485 struct i915_request *old;
3486
3487 spin_lock_irq(&ve->base.sched_engine->lock);
3488
3489 old = fetch_and_zero(&ve->request);
3490 if (old) {
3491 GEM_BUG_ON(!__i915_request_is_complete(old));
3492 __i915_request_submit(old);
3493 i915_request_put(old);
3494 }
3495
3496 spin_unlock_irq(&ve->base.sched_engine->lock);
3497 }
3498
3499 /*
3500 * Flush the tasklet in case it is still running on another core.
3501 *
3502 * This needs to be done before we remove ourselves from the siblings'
3503 * rbtrees as in the case it is running in parallel, it may reinsert
3504 * the rb_node into a sibling.
3505 */
3506 tasklet_kill(&ve->base.sched_engine->tasklet);
3507
3508 /* Decouple ourselves from the siblings, no more access allowed. */
3509 for (n = 0; n < ve->num_siblings; n++) {
3510 struct intel_engine_cs *sibling = ve->siblings[n];
3511 struct rb_node *node = &ve->nodes[sibling->id].rb;
3512
3513 if (RB_EMPTY_NODE(node))
3514 continue;
3515
3516 spin_lock_irq(&sibling->sched_engine->lock);
3517
3518 /* Detachment is lazily performed in the sched_engine->tasklet */
3519 if (!RB_EMPTY_NODE(node))
3520 rb_erase_cached(node, &sibling->execlists.virtual);
3521
3522 spin_unlock_irq(&sibling->sched_engine->lock);
3523 }
3524 GEM_BUG_ON(__tasklet_is_scheduled(&ve->base.sched_engine->tasklet));
3525 GEM_BUG_ON(!list_empty(virtual_queue(ve)));
3526
3527 lrc_fini(&ve->context);
3528 intel_context_fini(&ve->context);
3529
3530 if (ve->base.breadcrumbs)
3531 intel_breadcrumbs_put(ve->base.breadcrumbs);
3532 if (ve->base.sched_engine)
3533 i915_sched_engine_put(ve->base.sched_engine);
3534 intel_engine_free_request_pool(&ve->base);
3535
3536 kfree(ve);
3537 }
3538
virtual_context_destroy(struct kref * kref)3539 static void virtual_context_destroy(struct kref *kref)
3540 {
3541 struct virtual_engine *ve =
3542 container_of(kref, typeof(*ve), context.ref);
3543
3544 GEM_BUG_ON(!list_empty(&ve->context.signals));
3545
3546 /*
3547 * When destroying the virtual engine, we have to be aware that
3548 * it may still be in use from an hardirq/softirq context causing
3549 * the resubmission of a completed request (background completion
3550 * due to preempt-to-busy). Before we can free the engine, we need
3551 * to flush the submission code and tasklets that are still potentially
3552 * accessing the engine. Flushing the tasklets requires process context,
3553 * and since we can guard the resubmit onto the engine with an RCU read
3554 * lock, we can delegate the free of the engine to an RCU worker.
3555 */
3556 INIT_RCU_WORK(&ve->rcu, rcu_virtual_context_destroy);
3557 queue_rcu_work(system_wq, &ve->rcu);
3558 }
3559
virtual_engine_initial_hint(struct virtual_engine * ve)3560 static void virtual_engine_initial_hint(struct virtual_engine *ve)
3561 {
3562 int swp;
3563
3564 /*
3565 * Pick a random sibling on starting to help spread the load around.
3566 *
3567 * New contexts are typically created with exactly the same order
3568 * of siblings, and often started in batches. Due to the way we iterate
3569 * the array of sibling when submitting requests, sibling[0] is
3570 * prioritised for dequeuing. If we make sure that sibling[0] is fairly
3571 * randomised across the system, we also help spread the load by the
3572 * first engine we inspect being different each time.
3573 *
3574 * NB This does not force us to execute on this engine, it will just
3575 * typically be the first we inspect for submission.
3576 */
3577 swp = prandom_u32_max(ve->num_siblings);
3578 if (swp)
3579 swap(ve->siblings[swp], ve->siblings[0]);
3580 }
3581
virtual_context_alloc(struct intel_context * ce)3582 static int virtual_context_alloc(struct intel_context *ce)
3583 {
3584 struct virtual_engine *ve = container_of(ce, typeof(*ve), context);
3585
3586 return lrc_alloc(ce, ve->siblings[0]);
3587 }
3588
virtual_context_pre_pin(struct intel_context * ce,struct i915_gem_ww_ctx * ww,void ** vaddr)3589 static int virtual_context_pre_pin(struct intel_context *ce,
3590 struct i915_gem_ww_ctx *ww,
3591 void **vaddr)
3592 {
3593 struct virtual_engine *ve = container_of(ce, typeof(*ve), context);
3594
3595 /* Note: we must use a real engine class for setting up reg state */
3596 return __execlists_context_pre_pin(ce, ve->siblings[0], ww, vaddr);
3597 }
3598
virtual_context_pin(struct intel_context * ce,void * vaddr)3599 static int virtual_context_pin(struct intel_context *ce, void *vaddr)
3600 {
3601 struct virtual_engine *ve = container_of(ce, typeof(*ve), context);
3602
3603 return lrc_pin(ce, ve->siblings[0], vaddr);
3604 }
3605
virtual_context_enter(struct intel_context * ce)3606 static void virtual_context_enter(struct intel_context *ce)
3607 {
3608 struct virtual_engine *ve = container_of(ce, typeof(*ve), context);
3609 unsigned int n;
3610
3611 for (n = 0; n < ve->num_siblings; n++)
3612 intel_engine_pm_get(ve->siblings[n]);
3613
3614 intel_timeline_enter(ce->timeline);
3615 }
3616
virtual_context_exit(struct intel_context * ce)3617 static void virtual_context_exit(struct intel_context *ce)
3618 {
3619 struct virtual_engine *ve = container_of(ce, typeof(*ve), context);
3620 unsigned int n;
3621
3622 intel_timeline_exit(ce->timeline);
3623
3624 for (n = 0; n < ve->num_siblings; n++)
3625 intel_engine_pm_put(ve->siblings[n]);
3626 }
3627
3628 static struct intel_engine_cs *
virtual_get_sibling(struct intel_engine_cs * engine,unsigned int sibling)3629 virtual_get_sibling(struct intel_engine_cs *engine, unsigned int sibling)
3630 {
3631 struct virtual_engine *ve = to_virtual_engine(engine);
3632
3633 if (sibling >= ve->num_siblings)
3634 return NULL;
3635
3636 return ve->siblings[sibling];
3637 }
3638
3639 static const struct intel_context_ops virtual_context_ops = {
3640 .flags = COPS_HAS_INFLIGHT,
3641
3642 .alloc = virtual_context_alloc,
3643
3644 .cancel_request = execlists_context_cancel_request,
3645
3646 .pre_pin = virtual_context_pre_pin,
3647 .pin = virtual_context_pin,
3648 .unpin = lrc_unpin,
3649 .post_unpin = lrc_post_unpin,
3650
3651 .enter = virtual_context_enter,
3652 .exit = virtual_context_exit,
3653
3654 .destroy = virtual_context_destroy,
3655
3656 .get_sibling = virtual_get_sibling,
3657 };
3658
virtual_submission_mask(struct virtual_engine * ve)3659 static intel_engine_mask_t virtual_submission_mask(struct virtual_engine *ve)
3660 {
3661 struct i915_request *rq;
3662 intel_engine_mask_t mask;
3663
3664 rq = READ_ONCE(ve->request);
3665 if (!rq)
3666 return 0;
3667
3668 /* The rq is ready for submission; rq->execution_mask is now stable. */
3669 mask = rq->execution_mask;
3670 if (unlikely(!mask)) {
3671 /* Invalid selection, submit to a random engine in error */
3672 i915_request_set_error_once(rq, -ENODEV);
3673 mask = ve->siblings[0]->mask;
3674 }
3675
3676 ENGINE_TRACE(&ve->base, "rq=%llx:%lld, mask=%x, prio=%d\n",
3677 rq->fence.context, rq->fence.seqno,
3678 mask, ve->base.sched_engine->queue_priority_hint);
3679
3680 return mask;
3681 }
3682
virtual_submission_tasklet(struct tasklet_struct * t)3683 static void virtual_submission_tasklet(struct tasklet_struct *t)
3684 {
3685 struct i915_sched_engine *sched_engine =
3686 from_tasklet(sched_engine, t, tasklet);
3687 struct virtual_engine * const ve =
3688 (struct virtual_engine *)sched_engine->private_data;
3689 const int prio = READ_ONCE(sched_engine->queue_priority_hint);
3690 intel_engine_mask_t mask;
3691 unsigned int n;
3692
3693 rcu_read_lock();
3694 mask = virtual_submission_mask(ve);
3695 rcu_read_unlock();
3696 if (unlikely(!mask))
3697 return;
3698
3699 for (n = 0; n < ve->num_siblings; n++) {
3700 struct intel_engine_cs *sibling = READ_ONCE(ve->siblings[n]);
3701 struct ve_node * const node = &ve->nodes[sibling->id];
3702 struct rb_node **parent, *rb;
3703 bool first;
3704
3705 if (!READ_ONCE(ve->request))
3706 break; /* already handled by a sibling's tasklet */
3707
3708 spin_lock_irq(&sibling->sched_engine->lock);
3709
3710 if (unlikely(!(mask & sibling->mask))) {
3711 if (!RB_EMPTY_NODE(&node->rb)) {
3712 rb_erase_cached(&node->rb,
3713 &sibling->execlists.virtual);
3714 RB_CLEAR_NODE(&node->rb);
3715 }
3716
3717 goto unlock_engine;
3718 }
3719
3720 if (unlikely(!RB_EMPTY_NODE(&node->rb))) {
3721 /*
3722 * Cheat and avoid rebalancing the tree if we can
3723 * reuse this node in situ.
3724 */
3725 first = rb_first_cached(&sibling->execlists.virtual) ==
3726 &node->rb;
3727 if (prio == node->prio || (prio > node->prio && first))
3728 goto submit_engine;
3729
3730 rb_erase_cached(&node->rb, &sibling->execlists.virtual);
3731 }
3732
3733 rb = NULL;
3734 first = true;
3735 parent = &sibling->execlists.virtual.rb_root.rb_node;
3736 while (*parent) {
3737 struct ve_node *other;
3738
3739 rb = *parent;
3740 other = rb_entry(rb, typeof(*other), rb);
3741 if (prio > other->prio) {
3742 parent = &rb->rb_left;
3743 } else {
3744 parent = &rb->rb_right;
3745 first = false;
3746 }
3747 }
3748
3749 rb_link_node(&node->rb, rb, parent);
3750 rb_insert_color_cached(&node->rb,
3751 &sibling->execlists.virtual,
3752 first);
3753
3754 submit_engine:
3755 GEM_BUG_ON(RB_EMPTY_NODE(&node->rb));
3756 node->prio = prio;
3757 if (first && prio > sibling->sched_engine->queue_priority_hint)
3758 tasklet_hi_schedule(&sibling->sched_engine->tasklet);
3759
3760 unlock_engine:
3761 spin_unlock_irq(&sibling->sched_engine->lock);
3762
3763 if (intel_context_inflight(&ve->context))
3764 break;
3765 }
3766 }
3767
virtual_submit_request(struct i915_request * rq)3768 static void virtual_submit_request(struct i915_request *rq)
3769 {
3770 struct virtual_engine *ve = to_virtual_engine(rq->engine);
3771 unsigned long flags;
3772
3773 ENGINE_TRACE(&ve->base, "rq=%llx:%lld\n",
3774 rq->fence.context,
3775 rq->fence.seqno);
3776
3777 GEM_BUG_ON(ve->base.submit_request != virtual_submit_request);
3778
3779 spin_lock_irqsave(&ve->base.sched_engine->lock, flags);
3780
3781 /* By the time we resubmit a request, it may be completed */
3782 if (__i915_request_is_complete(rq)) {
3783 __i915_request_submit(rq);
3784 goto unlock;
3785 }
3786
3787 if (ve->request) { /* background completion from preempt-to-busy */
3788 GEM_BUG_ON(!__i915_request_is_complete(ve->request));
3789 __i915_request_submit(ve->request);
3790 i915_request_put(ve->request);
3791 }
3792
3793 ve->base.sched_engine->queue_priority_hint = rq_prio(rq);
3794 ve->request = i915_request_get(rq);
3795
3796 GEM_BUG_ON(!list_empty(virtual_queue(ve)));
3797 list_move_tail(&rq->sched.link, virtual_queue(ve));
3798
3799 tasklet_hi_schedule(&ve->base.sched_engine->tasklet);
3800
3801 unlock:
3802 spin_unlock_irqrestore(&ve->base.sched_engine->lock, flags);
3803 }
3804
3805 static struct intel_context *
execlists_create_virtual(struct intel_engine_cs ** siblings,unsigned int count)3806 execlists_create_virtual(struct intel_engine_cs **siblings, unsigned int count)
3807 {
3808 struct virtual_engine *ve;
3809 unsigned int n;
3810 int err;
3811
3812 ve = kzalloc(struct_size(ve, siblings, count), GFP_KERNEL);
3813 if (!ve)
3814 return ERR_PTR(-ENOMEM);
3815
3816 ve->base.i915 = siblings[0]->i915;
3817 ve->base.gt = siblings[0]->gt;
3818 ve->base.uncore = siblings[0]->uncore;
3819 ve->base.id = -1;
3820
3821 ve->base.class = OTHER_CLASS;
3822 ve->base.uabi_class = I915_ENGINE_CLASS_INVALID;
3823 ve->base.instance = I915_ENGINE_CLASS_INVALID_VIRTUAL;
3824 ve->base.uabi_instance = I915_ENGINE_CLASS_INVALID_VIRTUAL;
3825
3826 /*
3827 * The decision on whether to submit a request using semaphores
3828 * depends on the saturated state of the engine. We only compute
3829 * this during HW submission of the request, and we need for this
3830 * state to be globally applied to all requests being submitted
3831 * to this engine. Virtual engines encompass more than one physical
3832 * engine and so we cannot accurately tell in advance if one of those
3833 * engines is already saturated and so cannot afford to use a semaphore
3834 * and be pessimized in priority for doing so -- if we are the only
3835 * context using semaphores after all other clients have stopped, we
3836 * will be starved on the saturated system. Such a global switch for
3837 * semaphores is less than ideal, but alas is the current compromise.
3838 */
3839 ve->base.saturated = ALL_ENGINES;
3840
3841 snprintf(ve->base.name, sizeof(ve->base.name), "virtual");
3842
3843 intel_engine_init_execlists(&ve->base);
3844
3845 ve->base.sched_engine = i915_sched_engine_create(ENGINE_VIRTUAL);
3846 if (!ve->base.sched_engine) {
3847 err = -ENOMEM;
3848 goto err_put;
3849 }
3850 ve->base.sched_engine->private_data = &ve->base;
3851
3852 ve->base.cops = &virtual_context_ops;
3853 ve->base.request_alloc = execlists_request_alloc;
3854
3855 ve->base.sched_engine->schedule = i915_schedule;
3856 ve->base.sched_engine->kick_backend = kick_execlists;
3857 ve->base.submit_request = virtual_submit_request;
3858
3859 INIT_LIST_HEAD(virtual_queue(ve));
3860 tasklet_setup(&ve->base.sched_engine->tasklet, virtual_submission_tasklet);
3861
3862 intel_context_init(&ve->context, &ve->base);
3863
3864 ve->base.breadcrumbs = intel_breadcrumbs_create(NULL);
3865 if (!ve->base.breadcrumbs) {
3866 err = -ENOMEM;
3867 goto err_put;
3868 }
3869
3870 for (n = 0; n < count; n++) {
3871 struct intel_engine_cs *sibling = siblings[n];
3872
3873 GEM_BUG_ON(!is_power_of_2(sibling->mask));
3874 if (sibling->mask & ve->base.mask) {
3875 DRM_DEBUG("duplicate %s entry in load balancer\n",
3876 sibling->name);
3877 err = -EINVAL;
3878 goto err_put;
3879 }
3880
3881 /*
3882 * The virtual engine implementation is tightly coupled to
3883 * the execlists backend -- we push out request directly
3884 * into a tree inside each physical engine. We could support
3885 * layering if we handle cloning of the requests and
3886 * submitting a copy into each backend.
3887 */
3888 if (sibling->sched_engine->tasklet.callback !=
3889 execlists_submission_tasklet) {
3890 err = -ENODEV;
3891 goto err_put;
3892 }
3893
3894 GEM_BUG_ON(RB_EMPTY_NODE(&ve->nodes[sibling->id].rb));
3895 RB_CLEAR_NODE(&ve->nodes[sibling->id].rb);
3896
3897 ve->siblings[ve->num_siblings++] = sibling;
3898 ve->base.mask |= sibling->mask;
3899
3900 /*
3901 * All physical engines must be compatible for their emission
3902 * functions (as we build the instructions during request
3903 * construction and do not alter them before submission
3904 * on the physical engine). We use the engine class as a guide
3905 * here, although that could be refined.
3906 */
3907 if (ve->base.class != OTHER_CLASS) {
3908 if (ve->base.class != sibling->class) {
3909 DRM_DEBUG("invalid mixing of engine class, sibling %d, already %d\n",
3910 sibling->class, ve->base.class);
3911 err = -EINVAL;
3912 goto err_put;
3913 }
3914 continue;
3915 }
3916
3917 ve->base.class = sibling->class;
3918 ve->base.uabi_class = sibling->uabi_class;
3919 snprintf(ve->base.name, sizeof(ve->base.name),
3920 "v%dx%d", ve->base.class, count);
3921 ve->base.context_size = sibling->context_size;
3922
3923 ve->base.add_active_request = sibling->add_active_request;
3924 ve->base.remove_active_request = sibling->remove_active_request;
3925 ve->base.emit_bb_start = sibling->emit_bb_start;
3926 ve->base.emit_flush = sibling->emit_flush;
3927 ve->base.emit_init_breadcrumb = sibling->emit_init_breadcrumb;
3928 ve->base.emit_fini_breadcrumb = sibling->emit_fini_breadcrumb;
3929 ve->base.emit_fini_breadcrumb_dw =
3930 sibling->emit_fini_breadcrumb_dw;
3931
3932 ve->base.flags = sibling->flags;
3933 }
3934
3935 ve->base.flags |= I915_ENGINE_IS_VIRTUAL;
3936
3937 virtual_engine_initial_hint(ve);
3938 return &ve->context;
3939
3940 err_put:
3941 intel_context_put(&ve->context);
3942 return ERR_PTR(err);
3943 }
3944
intel_execlists_show_requests(struct intel_engine_cs * engine,struct drm_printer * m,void (* show_request)(struct drm_printer * m,const struct i915_request * rq,const char * prefix,int indent),unsigned int max)3945 void intel_execlists_show_requests(struct intel_engine_cs *engine,
3946 struct drm_printer *m,
3947 void (*show_request)(struct drm_printer *m,
3948 const struct i915_request *rq,
3949 const char *prefix,
3950 int indent),
3951 unsigned int max)
3952 {
3953 const struct intel_engine_execlists *execlists = &engine->execlists;
3954 struct i915_sched_engine *sched_engine = engine->sched_engine;
3955 struct i915_request *rq, *last;
3956 unsigned long flags;
3957 unsigned int count;
3958 struct rb_node *rb;
3959
3960 spin_lock_irqsave(&sched_engine->lock, flags);
3961
3962 last = NULL;
3963 count = 0;
3964 list_for_each_entry(rq, &sched_engine->requests, sched.link) {
3965 if (count++ < max - 1)
3966 show_request(m, rq, "\t\t", 0);
3967 else
3968 last = rq;
3969 }
3970 if (last) {
3971 if (count > max) {
3972 drm_printf(m,
3973 "\t\t...skipping %d executing requests...\n",
3974 count - max);
3975 }
3976 show_request(m, last, "\t\t", 0);
3977 }
3978
3979 if (sched_engine->queue_priority_hint != INT_MIN)
3980 drm_printf(m, "\t\tQueue priority hint: %d\n",
3981 READ_ONCE(sched_engine->queue_priority_hint));
3982
3983 last = NULL;
3984 count = 0;
3985 for (rb = rb_first_cached(&sched_engine->queue); rb; rb = rb_next(rb)) {
3986 struct i915_priolist *p = rb_entry(rb, typeof(*p), node);
3987
3988 priolist_for_each_request(rq, p) {
3989 if (count++ < max - 1)
3990 show_request(m, rq, "\t\t", 0);
3991 else
3992 last = rq;
3993 }
3994 }
3995 if (last) {
3996 if (count > max) {
3997 drm_printf(m,
3998 "\t\t...skipping %d queued requests...\n",
3999 count - max);
4000 }
4001 show_request(m, last, "\t\t", 0);
4002 }
4003
4004 last = NULL;
4005 count = 0;
4006 for (rb = rb_first_cached(&execlists->virtual); rb; rb = rb_next(rb)) {
4007 struct virtual_engine *ve =
4008 rb_entry(rb, typeof(*ve), nodes[engine->id].rb);
4009 struct i915_request *rq = READ_ONCE(ve->request);
4010
4011 if (rq) {
4012 if (count++ < max - 1)
4013 show_request(m, rq, "\t\t", 0);
4014 else
4015 last = rq;
4016 }
4017 }
4018 if (last) {
4019 if (count > max) {
4020 drm_printf(m,
4021 "\t\t...skipping %d virtual requests...\n",
4022 count - max);
4023 }
4024 show_request(m, last, "\t\t", 0);
4025 }
4026
4027 spin_unlock_irqrestore(&sched_engine->lock, flags);
4028 }
4029
4030 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
4031 #include "selftest_execlists.c"
4032 #endif
4033