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