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