Merge tag 'tegra-for-5.2-bus-fixes' of git://git.kernel.org/pub/scm/linux/kernel...
[sfrench/cifs-2.6.git] / drivers / gpu / drm / i915 / intel_guc_submission.c
1 /*
2  * Copyright © 2014 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  */
24
25 #include <linux/circ_buf.h>
26
27 #include "intel_guc_submission.h"
28 #include "intel_lrc_reg.h"
29 #include "i915_drv.h"
30
31 #define GUC_PREEMPT_FINISHED            0x1
32 #define GUC_PREEMPT_BREADCRUMB_DWORDS   0x8
33 #define GUC_PREEMPT_BREADCRUMB_BYTES    \
34         (sizeof(u32) * GUC_PREEMPT_BREADCRUMB_DWORDS)
35
36 /**
37  * DOC: GuC-based command submission
38  *
39  * GuC client:
40  * A intel_guc_client refers to a submission path through GuC. Currently, there
41  * are two clients. One of them (the execbuf_client) is charged with all
42  * submissions to the GuC, the other one (preempt_client) is responsible for
43  * preempting the execbuf_client. This struct is the owner of a doorbell, a
44  * process descriptor and a workqueue (all of them inside a single gem object
45  * that contains all required pages for these elements).
46  *
47  * GuC stage descriptor:
48  * During initialization, the driver allocates a static pool of 1024 such
49  * descriptors, and shares them with the GuC.
50  * Currently, there exists a 1:1 mapping between a intel_guc_client and a
51  * guc_stage_desc (via the client's stage_id), so effectively only one
52  * gets used. This stage descriptor lets the GuC know about the doorbell,
53  * workqueue and process descriptor. Theoretically, it also lets the GuC
54  * know about our HW contexts (context ID, etc...), but we actually
55  * employ a kind of submission where the GuC uses the LRCA sent via the work
56  * item instead (the single guc_stage_desc associated to execbuf client
57  * contains information about the default kernel context only, but this is
58  * essentially unused). This is called a "proxy" submission.
59  *
60  * The Scratch registers:
61  * There are 16 MMIO-based registers start from 0xC180. The kernel driver writes
62  * a value to the action register (SOFT_SCRATCH_0) along with any data. It then
63  * triggers an interrupt on the GuC via another register write (0xC4C8).
64  * Firmware writes a success/fail code back to the action register after
65  * processes the request. The kernel driver polls waiting for this update and
66  * then proceeds.
67  * See intel_guc_send()
68  *
69  * Doorbells:
70  * Doorbells are interrupts to uKernel. A doorbell is a single cache line (QW)
71  * mapped into process space.
72  *
73  * Work Items:
74  * There are several types of work items that the host may place into a
75  * workqueue, each with its own requirements and limitations. Currently only
76  * WQ_TYPE_INORDER is needed to support legacy submission via GuC, which
77  * represents in-order queue. The kernel driver packs ring tail pointer and an
78  * ELSP context descriptor dword into Work Item.
79  * See guc_add_request()
80  *
81  */
82
83 static inline u32 intel_hws_preempt_done_address(struct intel_engine_cs *engine)
84 {
85         return (i915_ggtt_offset(engine->status_page.vma) +
86                 I915_GEM_HWS_PREEMPT_ADDR);
87 }
88
89 static inline struct i915_priolist *to_priolist(struct rb_node *rb)
90 {
91         return rb_entry(rb, struct i915_priolist, node);
92 }
93
94 static inline bool is_high_priority(struct intel_guc_client *client)
95 {
96         return (client->priority == GUC_CLIENT_PRIORITY_KMD_HIGH ||
97                 client->priority == GUC_CLIENT_PRIORITY_HIGH);
98 }
99
100 static int reserve_doorbell(struct intel_guc_client *client)
101 {
102         unsigned long offset;
103         unsigned long end;
104         u16 id;
105
106         GEM_BUG_ON(client->doorbell_id != GUC_DOORBELL_INVALID);
107
108         /*
109          * The bitmap tracks which doorbell registers are currently in use.
110          * It is split into two halves; the first half is used for normal
111          * priority contexts, the second half for high-priority ones.
112          */
113         offset = 0;
114         end = GUC_NUM_DOORBELLS / 2;
115         if (is_high_priority(client)) {
116                 offset = end;
117                 end += offset;
118         }
119
120         id = find_next_zero_bit(client->guc->doorbell_bitmap, end, offset);
121         if (id == end)
122                 return -ENOSPC;
123
124         __set_bit(id, client->guc->doorbell_bitmap);
125         client->doorbell_id = id;
126         DRM_DEBUG_DRIVER("client %u (high prio=%s) reserved doorbell: %d\n",
127                          client->stage_id, yesno(is_high_priority(client)),
128                          id);
129         return 0;
130 }
131
132 static bool has_doorbell(struct intel_guc_client *client)
133 {
134         if (client->doorbell_id == GUC_DOORBELL_INVALID)
135                 return false;
136
137         return test_bit(client->doorbell_id, client->guc->doorbell_bitmap);
138 }
139
140 static void unreserve_doorbell(struct intel_guc_client *client)
141 {
142         GEM_BUG_ON(!has_doorbell(client));
143
144         __clear_bit(client->doorbell_id, client->guc->doorbell_bitmap);
145         client->doorbell_id = GUC_DOORBELL_INVALID;
146 }
147
148 /*
149  * Tell the GuC to allocate or deallocate a specific doorbell
150  */
151
152 static int __guc_allocate_doorbell(struct intel_guc *guc, u32 stage_id)
153 {
154         u32 action[] = {
155                 INTEL_GUC_ACTION_ALLOCATE_DOORBELL,
156                 stage_id
157         };
158
159         return intel_guc_send(guc, action, ARRAY_SIZE(action));
160 }
161
162 static int __guc_deallocate_doorbell(struct intel_guc *guc, u32 stage_id)
163 {
164         u32 action[] = {
165                 INTEL_GUC_ACTION_DEALLOCATE_DOORBELL,
166                 stage_id
167         };
168
169         return intel_guc_send(guc, action, ARRAY_SIZE(action));
170 }
171
172 static struct guc_stage_desc *__get_stage_desc(struct intel_guc_client *client)
173 {
174         struct guc_stage_desc *base = client->guc->stage_desc_pool_vaddr;
175
176         return &base[client->stage_id];
177 }
178
179 /*
180  * Initialise, update, or clear doorbell data shared with the GuC
181  *
182  * These functions modify shared data and so need access to the mapped
183  * client object which contains the page being used for the doorbell
184  */
185
186 static void __update_doorbell_desc(struct intel_guc_client *client, u16 new_id)
187 {
188         struct guc_stage_desc *desc;
189
190         /* Update the GuC's idea of the doorbell ID */
191         desc = __get_stage_desc(client);
192         desc->db_id = new_id;
193 }
194
195 static struct guc_doorbell_info *__get_doorbell(struct intel_guc_client *client)
196 {
197         return client->vaddr + client->doorbell_offset;
198 }
199
200 static bool __doorbell_valid(struct intel_guc *guc, u16 db_id)
201 {
202         struct drm_i915_private *dev_priv = guc_to_i915(guc);
203
204         GEM_BUG_ON(db_id >= GUC_NUM_DOORBELLS);
205         return I915_READ(GEN8_DRBREGL(db_id)) & GEN8_DRB_VALID;
206 }
207
208 static void __init_doorbell(struct intel_guc_client *client)
209 {
210         struct guc_doorbell_info *doorbell;
211
212         doorbell = __get_doorbell(client);
213         doorbell->db_status = GUC_DOORBELL_ENABLED;
214         doorbell->cookie = 0;
215 }
216
217 static void __fini_doorbell(struct intel_guc_client *client)
218 {
219         struct guc_doorbell_info *doorbell;
220         u16 db_id = client->doorbell_id;
221
222         doorbell = __get_doorbell(client);
223         doorbell->db_status = GUC_DOORBELL_DISABLED;
224
225         /* Doorbell release flow requires that we wait for GEN8_DRB_VALID bit
226          * to go to zero after updating db_status before we call the GuC to
227          * release the doorbell
228          */
229         if (wait_for_us(!__doorbell_valid(client->guc, db_id), 10))
230                 WARN_ONCE(true, "Doorbell never became invalid after disable\n");
231 }
232
233 static int create_doorbell(struct intel_guc_client *client)
234 {
235         int ret;
236
237         if (WARN_ON(!has_doorbell(client)))
238                 return -ENODEV; /* internal setup error, should never happen */
239
240         __update_doorbell_desc(client, client->doorbell_id);
241         __init_doorbell(client);
242
243         ret = __guc_allocate_doorbell(client->guc, client->stage_id);
244         if (ret) {
245                 __fini_doorbell(client);
246                 __update_doorbell_desc(client, GUC_DOORBELL_INVALID);
247                 DRM_DEBUG_DRIVER("Couldn't create client %u doorbell: %d\n",
248                                  client->stage_id, ret);
249                 return ret;
250         }
251
252         return 0;
253 }
254
255 static int destroy_doorbell(struct intel_guc_client *client)
256 {
257         int ret;
258
259         GEM_BUG_ON(!has_doorbell(client));
260
261         __fini_doorbell(client);
262         ret = __guc_deallocate_doorbell(client->guc, client->stage_id);
263         if (ret)
264                 DRM_ERROR("Couldn't destroy client %u doorbell: %d\n",
265                           client->stage_id, ret);
266
267         __update_doorbell_desc(client, GUC_DOORBELL_INVALID);
268
269         return ret;
270 }
271
272 static unsigned long __select_cacheline(struct intel_guc *guc)
273 {
274         unsigned long offset;
275
276         /* Doorbell uses a single cache line within a page */
277         offset = offset_in_page(guc->db_cacheline);
278
279         /* Moving to next cache line to reduce contention */
280         guc->db_cacheline += cache_line_size();
281
282         DRM_DEBUG_DRIVER("reserved cacheline 0x%lx, next 0x%x, linesize %u\n",
283                          offset, guc->db_cacheline, cache_line_size());
284         return offset;
285 }
286
287 static inline struct guc_process_desc *
288 __get_process_desc(struct intel_guc_client *client)
289 {
290         return client->vaddr + client->proc_desc_offset;
291 }
292
293 /*
294  * Initialise the process descriptor shared with the GuC firmware.
295  */
296 static void guc_proc_desc_init(struct intel_guc_client *client)
297 {
298         struct guc_process_desc *desc;
299
300         desc = memset(__get_process_desc(client), 0, sizeof(*desc));
301
302         /*
303          * XXX: pDoorbell and WQVBaseAddress are pointers in process address
304          * space for ring3 clients (set them as in mmap_ioctl) or kernel
305          * space for kernel clients (map on demand instead? May make debug
306          * easier to have it mapped).
307          */
308         desc->wq_base_addr = 0;
309         desc->db_base_addr = 0;
310
311         desc->stage_id = client->stage_id;
312         desc->wq_size_bytes = GUC_WQ_SIZE;
313         desc->wq_status = WQ_STATUS_ACTIVE;
314         desc->priority = client->priority;
315 }
316
317 static void guc_proc_desc_fini(struct intel_guc_client *client)
318 {
319         struct guc_process_desc *desc;
320
321         desc = __get_process_desc(client);
322         memset(desc, 0, sizeof(*desc));
323 }
324
325 static int guc_stage_desc_pool_create(struct intel_guc *guc)
326 {
327         struct i915_vma *vma;
328         void *vaddr;
329
330         vma = intel_guc_allocate_vma(guc,
331                                      PAGE_ALIGN(sizeof(struct guc_stage_desc) *
332                                      GUC_MAX_STAGE_DESCRIPTORS));
333         if (IS_ERR(vma))
334                 return PTR_ERR(vma);
335
336         vaddr = i915_gem_object_pin_map(vma->obj, I915_MAP_WB);
337         if (IS_ERR(vaddr)) {
338                 i915_vma_unpin_and_release(&vma, 0);
339                 return PTR_ERR(vaddr);
340         }
341
342         guc->stage_desc_pool = vma;
343         guc->stage_desc_pool_vaddr = vaddr;
344         ida_init(&guc->stage_ids);
345
346         return 0;
347 }
348
349 static void guc_stage_desc_pool_destroy(struct intel_guc *guc)
350 {
351         ida_destroy(&guc->stage_ids);
352         i915_vma_unpin_and_release(&guc->stage_desc_pool, I915_VMA_RELEASE_MAP);
353 }
354
355 /*
356  * Initialise/clear the stage descriptor shared with the GuC firmware.
357  *
358  * This descriptor tells the GuC where (in GGTT space) to find the important
359  * data structures relating to this client (doorbell, process descriptor,
360  * write queue, etc).
361  */
362 static void guc_stage_desc_init(struct intel_guc_client *client)
363 {
364         struct intel_guc *guc = client->guc;
365         struct drm_i915_private *dev_priv = guc_to_i915(guc);
366         struct intel_engine_cs *engine;
367         struct i915_gem_context *ctx = client->owner;
368         struct guc_stage_desc *desc;
369         unsigned int tmp;
370         u32 gfx_addr;
371
372         desc = __get_stage_desc(client);
373         memset(desc, 0, sizeof(*desc));
374
375         desc->attribute = GUC_STAGE_DESC_ATTR_ACTIVE |
376                           GUC_STAGE_DESC_ATTR_KERNEL;
377         if (is_high_priority(client))
378                 desc->attribute |= GUC_STAGE_DESC_ATTR_PREEMPT;
379         desc->stage_id = client->stage_id;
380         desc->priority = client->priority;
381         desc->db_id = client->doorbell_id;
382
383         for_each_engine_masked(engine, dev_priv, client->engines, tmp) {
384                 struct intel_context *ce = intel_context_lookup(ctx, engine);
385                 u32 guc_engine_id = engine->guc_id;
386                 struct guc_execlist_context *lrc = &desc->lrc[guc_engine_id];
387
388                 /* TODO: We have a design issue to be solved here. Only when we
389                  * receive the first batch, we know which engine is used by the
390                  * user. But here GuC expects the lrc and ring to be pinned. It
391                  * is not an issue for default context, which is the only one
392                  * for now who owns a GuC client. But for future owner of GuC
393                  * client, need to make sure lrc is pinned prior to enter here.
394                  */
395                 if (!ce || !ce->state)
396                         break;  /* XXX: continue? */
397
398                 /*
399                  * XXX: When this is a GUC_STAGE_DESC_ATTR_KERNEL client (proxy
400                  * submission or, in other words, not using a direct submission
401                  * model) the KMD's LRCA is not used for any work submission.
402                  * Instead, the GuC uses the LRCA of the user mode context (see
403                  * guc_add_request below).
404                  */
405                 lrc->context_desc = lower_32_bits(ce->lrc_desc);
406
407                 /* The state page is after PPHWSP */
408                 lrc->ring_lrca = intel_guc_ggtt_offset(guc, ce->state) +
409                                  LRC_STATE_PN * PAGE_SIZE;
410
411                 /* XXX: In direct submission, the GuC wants the HW context id
412                  * here. In proxy submission, it wants the stage id
413                  */
414                 lrc->context_id = (client->stage_id << GUC_ELC_CTXID_OFFSET) |
415                                 (guc_engine_id << GUC_ELC_ENGINE_OFFSET);
416
417                 lrc->ring_begin = intel_guc_ggtt_offset(guc, ce->ring->vma);
418                 lrc->ring_end = lrc->ring_begin + ce->ring->size - 1;
419                 lrc->ring_next_free_location = lrc->ring_begin;
420                 lrc->ring_current_tail_pointer_value = 0;
421
422                 desc->engines_used |= (1 << guc_engine_id);
423         }
424
425         DRM_DEBUG_DRIVER("Host engines 0x%x => GuC engines used 0x%x\n",
426                          client->engines, desc->engines_used);
427         WARN_ON(desc->engines_used == 0);
428
429         /*
430          * The doorbell, process descriptor, and workqueue are all parts
431          * of the client object, which the GuC will reference via the GGTT
432          */
433         gfx_addr = intel_guc_ggtt_offset(guc, client->vma);
434         desc->db_trigger_phy = sg_dma_address(client->vma->pages->sgl) +
435                                 client->doorbell_offset;
436         desc->db_trigger_cpu = ptr_to_u64(__get_doorbell(client));
437         desc->db_trigger_uk = gfx_addr + client->doorbell_offset;
438         desc->process_desc = gfx_addr + client->proc_desc_offset;
439         desc->wq_addr = gfx_addr + GUC_DB_SIZE;
440         desc->wq_size = GUC_WQ_SIZE;
441
442         desc->desc_private = ptr_to_u64(client);
443 }
444
445 static void guc_stage_desc_fini(struct intel_guc_client *client)
446 {
447         struct guc_stage_desc *desc;
448
449         desc = __get_stage_desc(client);
450         memset(desc, 0, sizeof(*desc));
451 }
452
453 /* Construct a Work Item and append it to the GuC's Work Queue */
454 static void guc_wq_item_append(struct intel_guc_client *client,
455                                u32 target_engine, u32 context_desc,
456                                u32 ring_tail, u32 fence_id)
457 {
458         /* wqi_len is in DWords, and does not include the one-word header */
459         const size_t wqi_size = sizeof(struct guc_wq_item);
460         const u32 wqi_len = wqi_size / sizeof(u32) - 1;
461         struct guc_process_desc *desc = __get_process_desc(client);
462         struct guc_wq_item *wqi;
463         u32 wq_off;
464
465         lockdep_assert_held(&client->wq_lock);
466
467         /* For now workqueue item is 4 DWs; workqueue buffer is 2 pages. So we
468          * should not have the case where structure wqi is across page, neither
469          * wrapped to the beginning. This simplifies the implementation below.
470          *
471          * XXX: if not the case, we need save data to a temp wqi and copy it to
472          * workqueue buffer dw by dw.
473          */
474         BUILD_BUG_ON(wqi_size != 16);
475
476         /* We expect the WQ to be active if we're appending items to it */
477         GEM_BUG_ON(desc->wq_status != WQ_STATUS_ACTIVE);
478
479         /* Free space is guaranteed. */
480         wq_off = READ_ONCE(desc->tail);
481         GEM_BUG_ON(CIRC_SPACE(wq_off, READ_ONCE(desc->head),
482                               GUC_WQ_SIZE) < wqi_size);
483         GEM_BUG_ON(wq_off & (wqi_size - 1));
484
485         /* WQ starts from the page after doorbell / process_desc */
486         wqi = client->vaddr + wq_off + GUC_DB_SIZE;
487
488         if (I915_SELFTEST_ONLY(client->use_nop_wqi)) {
489                 wqi->header = WQ_TYPE_NOOP | (wqi_len << WQ_LEN_SHIFT);
490         } else {
491                 /* Now fill in the 4-word work queue item */
492                 wqi->header = WQ_TYPE_INORDER |
493                               (wqi_len << WQ_LEN_SHIFT) |
494                               (target_engine << WQ_TARGET_SHIFT) |
495                               WQ_NO_WCFLUSH_WAIT;
496                 wqi->context_desc = context_desc;
497                 wqi->submit_element_info = ring_tail << WQ_RING_TAIL_SHIFT;
498                 GEM_BUG_ON(ring_tail > WQ_RING_TAIL_MAX);
499                 wqi->fence_id = fence_id;
500         }
501
502         /* Make the update visible to GuC */
503         WRITE_ONCE(desc->tail, (wq_off + wqi_size) & (GUC_WQ_SIZE - 1));
504 }
505
506 static void guc_ring_doorbell(struct intel_guc_client *client)
507 {
508         struct guc_doorbell_info *db;
509         u32 cookie;
510
511         lockdep_assert_held(&client->wq_lock);
512
513         /* pointer of current doorbell cacheline */
514         db = __get_doorbell(client);
515
516         /*
517          * We're not expecting the doorbell cookie to change behind our back,
518          * we also need to treat 0 as a reserved value.
519          */
520         cookie = READ_ONCE(db->cookie);
521         WARN_ON_ONCE(xchg(&db->cookie, cookie + 1 ?: cookie + 2) != cookie);
522
523         /* XXX: doorbell was lost and need to acquire it again */
524         GEM_BUG_ON(db->db_status != GUC_DOORBELL_ENABLED);
525 }
526
527 static void guc_add_request(struct intel_guc *guc, struct i915_request *rq)
528 {
529         struct intel_guc_client *client = guc->execbuf_client;
530         struct intel_engine_cs *engine = rq->engine;
531         u32 ctx_desc = lower_32_bits(rq->hw_context->lrc_desc);
532         u32 ring_tail = intel_ring_set_tail(rq->ring, rq->tail) / sizeof(u64);
533
534         spin_lock(&client->wq_lock);
535
536         guc_wq_item_append(client, engine->guc_id, ctx_desc,
537                            ring_tail, rq->fence.seqno);
538         guc_ring_doorbell(client);
539
540         client->submissions[engine->id] += 1;
541
542         spin_unlock(&client->wq_lock);
543 }
544
545 /*
546  * When we're doing submissions using regular execlists backend, writing to
547  * ELSP from CPU side is enough to make sure that writes to ringbuffer pages
548  * pinned in mappable aperture portion of GGTT are visible to command streamer.
549  * Writes done by GuC on our behalf are not guaranteeing such ordering,
550  * therefore, to ensure the flush, we're issuing a POSTING READ.
551  */
552 static void flush_ggtt_writes(struct i915_vma *vma)
553 {
554         struct drm_i915_private *dev_priv = vma->vm->i915;
555
556         if (i915_vma_is_map_and_fenceable(vma))
557                 POSTING_READ_FW(GUC_STATUS);
558 }
559
560 static void inject_preempt_context(struct work_struct *work)
561 {
562         struct guc_preempt_work *preempt_work =
563                 container_of(work, typeof(*preempt_work), work);
564         struct intel_engine_cs *engine = preempt_work->engine;
565         struct intel_guc *guc = container_of(preempt_work, typeof(*guc),
566                                              preempt_work[engine->id]);
567         struct intel_guc_client *client = guc->preempt_client;
568         struct guc_stage_desc *stage_desc = __get_stage_desc(client);
569         struct intel_context *ce = engine->preempt_context;
570         u32 data[7];
571
572         if (!ce->ring->emit) { /* recreate upon load/resume */
573                 u32 addr = intel_hws_preempt_done_address(engine);
574                 u32 *cs;
575
576                 cs = ce->ring->vaddr;
577                 if (engine->class == RENDER_CLASS) {
578                         cs = gen8_emit_ggtt_write_rcs(cs,
579                                                       GUC_PREEMPT_FINISHED,
580                                                       addr,
581                                                       PIPE_CONTROL_CS_STALL);
582                 } else {
583                         cs = gen8_emit_ggtt_write(cs,
584                                                   GUC_PREEMPT_FINISHED,
585                                                   addr,
586                                                   0);
587                         *cs++ = MI_NOOP;
588                         *cs++ = MI_NOOP;
589                 }
590                 *cs++ = MI_USER_INTERRUPT;
591                 *cs++ = MI_NOOP;
592
593                 ce->ring->emit = GUC_PREEMPT_BREADCRUMB_BYTES;
594                 GEM_BUG_ON((void *)cs - ce->ring->vaddr != ce->ring->emit);
595
596                 flush_ggtt_writes(ce->ring->vma);
597         }
598
599         spin_lock_irq(&client->wq_lock);
600         guc_wq_item_append(client, engine->guc_id, lower_32_bits(ce->lrc_desc),
601                            GUC_PREEMPT_BREADCRUMB_BYTES / sizeof(u64), 0);
602         spin_unlock_irq(&client->wq_lock);
603
604         /*
605          * If GuC firmware performs an engine reset while that engine had
606          * a preemption pending, it will set the terminated attribute bit
607          * on our preemption stage descriptor. GuC firmware retains all
608          * pending work items for a high-priority GuC client, unlike the
609          * normal-priority GuC client where work items are dropped. It
610          * wants to make sure the preempt-to-idle work doesn't run when
611          * scheduling resumes, and uses this bit to inform its scheduler
612          * and presumably us as well. Our job is to clear it for the next
613          * preemption after reset, otherwise that and future preemptions
614          * will never complete. We'll just clear it every time.
615          */
616         stage_desc->attribute &= ~GUC_STAGE_DESC_ATTR_TERMINATED;
617
618         data[0] = INTEL_GUC_ACTION_REQUEST_PREEMPTION;
619         data[1] = client->stage_id;
620         data[2] = INTEL_GUC_PREEMPT_OPTION_DROP_WORK_Q |
621                   INTEL_GUC_PREEMPT_OPTION_DROP_SUBMIT_Q;
622         data[3] = engine->guc_id;
623         data[4] = guc->execbuf_client->priority;
624         data[5] = guc->execbuf_client->stage_id;
625         data[6] = intel_guc_ggtt_offset(guc, guc->shared_data);
626
627         if (WARN_ON(intel_guc_send(guc, data, ARRAY_SIZE(data)))) {
628                 execlists_clear_active(&engine->execlists,
629                                        EXECLISTS_ACTIVE_PREEMPT);
630                 tasklet_schedule(&engine->execlists.tasklet);
631         }
632
633         (void)I915_SELFTEST_ONLY(engine->execlists.preempt_hang.count++);
634 }
635
636 /*
637  * We're using user interrupt and HWSP value to mark that preemption has
638  * finished and GPU is idle. Normally, we could unwind and continue similar to
639  * execlists submission path. Unfortunately, with GuC we also need to wait for
640  * it to finish its own postprocessing, before attempting to submit. Otherwise
641  * GuC may silently ignore our submissions, and thus we risk losing request at
642  * best, executing out-of-order and causing kernel panic at worst.
643  */
644 #define GUC_PREEMPT_POSTPROCESS_DELAY_MS 10
645 static void wait_for_guc_preempt_report(struct intel_engine_cs *engine)
646 {
647         struct intel_guc *guc = &engine->i915->guc;
648         struct guc_shared_ctx_data *data = guc->shared_data_vaddr;
649         struct guc_ctx_report *report =
650                 &data->preempt_ctx_report[engine->guc_id];
651
652         if (wait_for_atomic(report->report_return_status ==
653                             INTEL_GUC_REPORT_STATUS_COMPLETE,
654                             GUC_PREEMPT_POSTPROCESS_DELAY_MS))
655                 DRM_ERROR("Timed out waiting for GuC preemption report\n");
656         /*
657          * GuC is expecting that we're also going to clear the affected context
658          * counter, let's also reset the return status to not depend on GuC
659          * resetting it after recieving another preempt action
660          */
661         report->affected_count = 0;
662         report->report_return_status = INTEL_GUC_REPORT_STATUS_UNKNOWN;
663 }
664
665 static void complete_preempt_context(struct intel_engine_cs *engine)
666 {
667         struct intel_engine_execlists *execlists = &engine->execlists;
668
669         GEM_BUG_ON(!execlists_is_active(execlists, EXECLISTS_ACTIVE_PREEMPT));
670
671         if (inject_preempt_hang(execlists))
672                 return;
673
674         execlists_cancel_port_requests(execlists);
675         execlists_unwind_incomplete_requests(execlists);
676
677         wait_for_guc_preempt_report(engine);
678         intel_write_status_page(engine, I915_GEM_HWS_PREEMPT, 0);
679 }
680
681 /**
682  * guc_submit() - Submit commands through GuC
683  * @engine: engine associated with the commands
684  *
685  * The only error here arises if the doorbell hardware isn't functioning
686  * as expected, which really shouln't happen.
687  */
688 static void guc_submit(struct intel_engine_cs *engine)
689 {
690         struct intel_guc *guc = &engine->i915->guc;
691         struct intel_engine_execlists * const execlists = &engine->execlists;
692         struct execlist_port *port = execlists->port;
693         unsigned int n;
694
695         for (n = 0; n < execlists_num_ports(execlists); n++) {
696                 struct i915_request *rq;
697                 unsigned int count;
698
699                 rq = port_unpack(&port[n], &count);
700                 if (rq && count == 0) {
701                         port_set(&port[n], port_pack(rq, ++count));
702
703                         flush_ggtt_writes(rq->ring->vma);
704
705                         guc_add_request(guc, rq);
706                 }
707         }
708 }
709
710 static void port_assign(struct execlist_port *port, struct i915_request *rq)
711 {
712         GEM_BUG_ON(port_isset(port));
713
714         port_set(port, i915_request_get(rq));
715 }
716
717 static inline int rq_prio(const struct i915_request *rq)
718 {
719         return rq->sched.attr.priority;
720 }
721
722 static inline int port_prio(const struct execlist_port *port)
723 {
724         return rq_prio(port_request(port)) | __NO_PREEMPTION;
725 }
726
727 static bool __guc_dequeue(struct intel_engine_cs *engine)
728 {
729         struct intel_engine_execlists * const execlists = &engine->execlists;
730         struct execlist_port *port = execlists->port;
731         struct i915_request *last = NULL;
732         const struct execlist_port * const last_port =
733                 &execlists->port[execlists->port_mask];
734         bool submit = false;
735         struct rb_node *rb;
736
737         lockdep_assert_held(&engine->timeline.lock);
738
739         if (port_isset(port)) {
740                 if (intel_engine_has_preemption(engine)) {
741                         struct guc_preempt_work *preempt_work =
742                                 &engine->i915->guc.preempt_work[engine->id];
743                         int prio = execlists->queue_priority_hint;
744
745                         if (__execlists_need_preempt(prio, port_prio(port))) {
746                                 execlists_set_active(execlists,
747                                                      EXECLISTS_ACTIVE_PREEMPT);
748                                 queue_work(engine->i915->guc.preempt_wq,
749                                            &preempt_work->work);
750                                 return false;
751                         }
752                 }
753
754                 port++;
755                 if (port_isset(port))
756                         return false;
757         }
758         GEM_BUG_ON(port_isset(port));
759
760         while ((rb = rb_first_cached(&execlists->queue))) {
761                 struct i915_priolist *p = to_priolist(rb);
762                 struct i915_request *rq, *rn;
763                 int i;
764
765                 priolist_for_each_request_consume(rq, rn, p, i) {
766                         if (last && rq->hw_context != last->hw_context) {
767                                 if (port == last_port)
768                                         goto done;
769
770                                 if (submit)
771                                         port_assign(port, last);
772                                 port++;
773                         }
774
775                         list_del_init(&rq->sched.link);
776
777                         __i915_request_submit(rq);
778                         trace_i915_request_in(rq, port_index(port, execlists));
779
780                         last = rq;
781                         submit = true;
782                 }
783
784                 rb_erase_cached(&p->node, &execlists->queue);
785                 i915_priolist_free(p);
786         }
787 done:
788         execlists->queue_priority_hint =
789                 rb ? to_priolist(rb)->priority : INT_MIN;
790         if (submit)
791                 port_assign(port, last);
792         if (last)
793                 execlists_user_begin(execlists, execlists->port);
794
795         /* We must always keep the beast fed if we have work piled up */
796         GEM_BUG_ON(port_isset(execlists->port) &&
797                    !execlists_is_active(execlists, EXECLISTS_ACTIVE_USER));
798         GEM_BUG_ON(rb_first_cached(&execlists->queue) &&
799                    !port_isset(execlists->port));
800
801         return submit;
802 }
803
804 static void guc_dequeue(struct intel_engine_cs *engine)
805 {
806         if (__guc_dequeue(engine))
807                 guc_submit(engine);
808 }
809
810 static void guc_submission_tasklet(unsigned long data)
811 {
812         struct intel_engine_cs * const engine = (struct intel_engine_cs *)data;
813         struct intel_engine_execlists * const execlists = &engine->execlists;
814         struct execlist_port *port = execlists->port;
815         struct i915_request *rq;
816         unsigned long flags;
817
818         spin_lock_irqsave(&engine->timeline.lock, flags);
819
820         rq = port_request(port);
821         while (rq && i915_request_completed(rq)) {
822                 trace_i915_request_out(rq);
823                 i915_request_put(rq);
824
825                 port = execlists_port_complete(execlists, port);
826                 if (port_isset(port)) {
827                         execlists_user_begin(execlists, port);
828                         rq = port_request(port);
829                 } else {
830                         execlists_user_end(execlists);
831                         rq = NULL;
832                 }
833         }
834
835         if (execlists_is_active(execlists, EXECLISTS_ACTIVE_PREEMPT) &&
836             intel_read_status_page(engine, I915_GEM_HWS_PREEMPT) ==
837             GUC_PREEMPT_FINISHED)
838                 complete_preempt_context(engine);
839
840         if (!execlists_is_active(execlists, EXECLISTS_ACTIVE_PREEMPT))
841                 guc_dequeue(engine);
842
843         spin_unlock_irqrestore(&engine->timeline.lock, flags);
844 }
845
846 static void guc_reset_prepare(struct intel_engine_cs *engine)
847 {
848         struct intel_engine_execlists * const execlists = &engine->execlists;
849
850         GEM_TRACE("%s\n", engine->name);
851
852         /*
853          * Prevent request submission to the hardware until we have
854          * completed the reset in i915_gem_reset_finish(). If a request
855          * is completed by one engine, it may then queue a request
856          * to a second via its execlists->tasklet *just* as we are
857          * calling engine->init_hw() and also writing the ELSP.
858          * Turning off the execlists->tasklet until the reset is over
859          * prevents the race.
860          */
861         __tasklet_disable_sync_once(&execlists->tasklet);
862
863         /*
864          * We're using worker to queue preemption requests from the tasklet in
865          * GuC submission mode.
866          * Even though tasklet was disabled, we may still have a worker queued.
867          * Let's make sure that all workers scheduled before disabling the
868          * tasklet are completed before continuing with the reset.
869          */
870         if (engine->i915->guc.preempt_wq)
871                 flush_workqueue(engine->i915->guc.preempt_wq);
872 }
873
874 static void guc_reset(struct intel_engine_cs *engine, bool stalled)
875 {
876         struct intel_engine_execlists * const execlists = &engine->execlists;
877         struct i915_request *rq;
878         unsigned long flags;
879
880         spin_lock_irqsave(&engine->timeline.lock, flags);
881
882         execlists_cancel_port_requests(execlists);
883
884         /* Push back any incomplete requests for replay after the reset. */
885         rq = execlists_unwind_incomplete_requests(execlists);
886         if (!rq)
887                 goto out_unlock;
888
889         if (!i915_request_started(rq))
890                 stalled = false;
891
892         i915_reset_request(rq, stalled);
893         intel_lr_context_reset(engine, rq->hw_context, rq->head, stalled);
894
895 out_unlock:
896         spin_unlock_irqrestore(&engine->timeline.lock, flags);
897 }
898
899 static void guc_cancel_requests(struct intel_engine_cs *engine)
900 {
901         struct intel_engine_execlists * const execlists = &engine->execlists;
902         struct i915_request *rq, *rn;
903         struct rb_node *rb;
904         unsigned long flags;
905
906         GEM_TRACE("%s\n", engine->name);
907
908         /*
909          * Before we call engine->cancel_requests(), we should have exclusive
910          * access to the submission state. This is arranged for us by the
911          * caller disabling the interrupt generation, the tasklet and other
912          * threads that may then access the same state, giving us a free hand
913          * to reset state. However, we still need to let lockdep be aware that
914          * we know this state may be accessed in hardirq context, so we
915          * disable the irq around this manipulation and we want to keep
916          * the spinlock focused on its duties and not accidentally conflate
917          * coverage to the submission's irq state. (Similarly, although we
918          * shouldn't need to disable irq around the manipulation of the
919          * submission's irq state, we also wish to remind ourselves that
920          * it is irq state.)
921          */
922         spin_lock_irqsave(&engine->timeline.lock, flags);
923
924         /* Cancel the requests on the HW and clear the ELSP tracker. */
925         execlists_cancel_port_requests(execlists);
926
927         /* Mark all executing requests as skipped. */
928         list_for_each_entry(rq, &engine->timeline.requests, link) {
929                 if (!i915_request_signaled(rq))
930                         dma_fence_set_error(&rq->fence, -EIO);
931
932                 i915_request_mark_complete(rq);
933         }
934
935         /* Flush the queued requests to the timeline list (for retiring). */
936         while ((rb = rb_first_cached(&execlists->queue))) {
937                 struct i915_priolist *p = to_priolist(rb);
938                 int i;
939
940                 priolist_for_each_request_consume(rq, rn, p, i) {
941                         list_del_init(&rq->sched.link);
942                         __i915_request_submit(rq);
943                         dma_fence_set_error(&rq->fence, -EIO);
944                         i915_request_mark_complete(rq);
945                 }
946
947                 rb_erase_cached(&p->node, &execlists->queue);
948                 i915_priolist_free(p);
949         }
950
951         /* Remaining _unready_ requests will be nop'ed when submitted */
952
953         execlists->queue_priority_hint = INT_MIN;
954         execlists->queue = RB_ROOT_CACHED;
955         GEM_BUG_ON(port_isset(execlists->port));
956
957         spin_unlock_irqrestore(&engine->timeline.lock, flags);
958 }
959
960 static void guc_reset_finish(struct intel_engine_cs *engine)
961 {
962         struct intel_engine_execlists * const execlists = &engine->execlists;
963
964         if (__tasklet_enable(&execlists->tasklet))
965                 /* And kick in case we missed a new request submission. */
966                 tasklet_hi_schedule(&execlists->tasklet);
967
968         GEM_TRACE("%s: depth->%d\n", engine->name,
969                   atomic_read(&execlists->tasklet.count));
970 }
971
972 /*
973  * Everything below here is concerned with setup & teardown, and is
974  * therefore not part of the somewhat time-critical batch-submission
975  * path of guc_submit() above.
976  */
977
978 /* Check that a doorbell register is in the expected state */
979 static bool doorbell_ok(struct intel_guc *guc, u16 db_id)
980 {
981         bool valid;
982
983         GEM_BUG_ON(db_id >= GUC_NUM_DOORBELLS);
984
985         valid = __doorbell_valid(guc, db_id);
986
987         if (test_bit(db_id, guc->doorbell_bitmap) == valid)
988                 return true;
989
990         DRM_DEBUG_DRIVER("Doorbell %u has unexpected state: valid=%s\n",
991                          db_id, yesno(valid));
992
993         return false;
994 }
995
996 static bool guc_verify_doorbells(struct intel_guc *guc)
997 {
998         bool doorbells_ok = true;
999         u16 db_id;
1000
1001         for (db_id = 0; db_id < GUC_NUM_DOORBELLS; ++db_id)
1002                 if (!doorbell_ok(guc, db_id))
1003                         doorbells_ok = false;
1004
1005         return doorbells_ok;
1006 }
1007
1008 /**
1009  * guc_client_alloc() - Allocate an intel_guc_client
1010  * @dev_priv:   driver private data structure
1011  * @engines:    The set of engines to enable for this client
1012  * @priority:   four levels priority _CRITICAL, _HIGH, _NORMAL and _LOW
1013  *              The kernel client to replace ExecList submission is created with
1014  *              NORMAL priority. Priority of a client for scheduler can be HIGH,
1015  *              while a preemption context can use CRITICAL.
1016  * @ctx:        the context that owns the client (we use the default render
1017  *              context)
1018  *
1019  * Return:      An intel_guc_client object if success, else NULL.
1020  */
1021 static struct intel_guc_client *
1022 guc_client_alloc(struct drm_i915_private *dev_priv,
1023                  u32 engines,
1024                  u32 priority,
1025                  struct i915_gem_context *ctx)
1026 {
1027         struct intel_guc_client *client;
1028         struct intel_guc *guc = &dev_priv->guc;
1029         struct i915_vma *vma;
1030         void *vaddr;
1031         int ret;
1032
1033         client = kzalloc(sizeof(*client), GFP_KERNEL);
1034         if (!client)
1035                 return ERR_PTR(-ENOMEM);
1036
1037         client->guc = guc;
1038         client->owner = ctx;
1039         client->engines = engines;
1040         client->priority = priority;
1041         client->doorbell_id = GUC_DOORBELL_INVALID;
1042         spin_lock_init(&client->wq_lock);
1043
1044         ret = ida_simple_get(&guc->stage_ids, 0, GUC_MAX_STAGE_DESCRIPTORS,
1045                              GFP_KERNEL);
1046         if (ret < 0)
1047                 goto err_client;
1048
1049         client->stage_id = ret;
1050
1051         /* The first page is doorbell/proc_desc. Two followed pages are wq. */
1052         vma = intel_guc_allocate_vma(guc, GUC_DB_SIZE + GUC_WQ_SIZE);
1053         if (IS_ERR(vma)) {
1054                 ret = PTR_ERR(vma);
1055                 goto err_id;
1056         }
1057
1058         /* We'll keep just the first (doorbell/proc) page permanently kmap'd. */
1059         client->vma = vma;
1060
1061         vaddr = i915_gem_object_pin_map(vma->obj, I915_MAP_WB);
1062         if (IS_ERR(vaddr)) {
1063                 ret = PTR_ERR(vaddr);
1064                 goto err_vma;
1065         }
1066         client->vaddr = vaddr;
1067
1068         ret = reserve_doorbell(client);
1069         if (ret)
1070                 goto err_vaddr;
1071
1072         client->doorbell_offset = __select_cacheline(guc);
1073
1074         /*
1075          * Since the doorbell only requires a single cacheline, we can save
1076          * space by putting the application process descriptor in the same
1077          * page. Use the half of the page that doesn't include the doorbell.
1078          */
1079         if (client->doorbell_offset >= (GUC_DB_SIZE / 2))
1080                 client->proc_desc_offset = 0;
1081         else
1082                 client->proc_desc_offset = (GUC_DB_SIZE / 2);
1083
1084         DRM_DEBUG_DRIVER("new priority %u client %p for engine(s) 0x%x: stage_id %u\n",
1085                          priority, client, client->engines, client->stage_id);
1086         DRM_DEBUG_DRIVER("doorbell id %u, cacheline offset 0x%lx\n",
1087                          client->doorbell_id, client->doorbell_offset);
1088
1089         return client;
1090
1091 err_vaddr:
1092         i915_gem_object_unpin_map(client->vma->obj);
1093 err_vma:
1094         i915_vma_unpin_and_release(&client->vma, 0);
1095 err_id:
1096         ida_simple_remove(&guc->stage_ids, client->stage_id);
1097 err_client:
1098         kfree(client);
1099         return ERR_PTR(ret);
1100 }
1101
1102 static void guc_client_free(struct intel_guc_client *client)
1103 {
1104         unreserve_doorbell(client);
1105         i915_vma_unpin_and_release(&client->vma, I915_VMA_RELEASE_MAP);
1106         ida_simple_remove(&client->guc->stage_ids, client->stage_id);
1107         kfree(client);
1108 }
1109
1110 static inline bool ctx_save_restore_disabled(struct intel_context *ce)
1111 {
1112         u32 sr = ce->lrc_reg_state[CTX_CONTEXT_CONTROL + 1];
1113
1114 #define SR_DISABLED \
1115         _MASKED_BIT_ENABLE(CTX_CTRL_ENGINE_CTX_RESTORE_INHIBIT | \
1116                            CTX_CTRL_ENGINE_CTX_SAVE_INHIBIT)
1117
1118         return (sr & SR_DISABLED) == SR_DISABLED;
1119
1120 #undef SR_DISABLED
1121 }
1122
1123 static int guc_clients_create(struct intel_guc *guc)
1124 {
1125         struct drm_i915_private *dev_priv = guc_to_i915(guc);
1126         struct intel_guc_client *client;
1127
1128         GEM_BUG_ON(guc->execbuf_client);
1129         GEM_BUG_ON(guc->preempt_client);
1130
1131         client = guc_client_alloc(dev_priv,
1132                                   INTEL_INFO(dev_priv)->engine_mask,
1133                                   GUC_CLIENT_PRIORITY_KMD_NORMAL,
1134                                   dev_priv->kernel_context);
1135         if (IS_ERR(client)) {
1136                 DRM_ERROR("Failed to create GuC client for submission!\n");
1137                 return PTR_ERR(client);
1138         }
1139         guc->execbuf_client = client;
1140
1141         if (dev_priv->preempt_context) {
1142                 client = guc_client_alloc(dev_priv,
1143                                           INTEL_INFO(dev_priv)->engine_mask,
1144                                           GUC_CLIENT_PRIORITY_KMD_HIGH,
1145                                           dev_priv->preempt_context);
1146                 if (IS_ERR(client)) {
1147                         DRM_ERROR("Failed to create GuC client for preemption!\n");
1148                         guc_client_free(guc->execbuf_client);
1149                         guc->execbuf_client = NULL;
1150                         return PTR_ERR(client);
1151                 }
1152                 guc->preempt_client = client;
1153         }
1154
1155         return 0;
1156 }
1157
1158 static void guc_clients_destroy(struct intel_guc *guc)
1159 {
1160         struct intel_guc_client *client;
1161
1162         client = fetch_and_zero(&guc->preempt_client);
1163         if (client)
1164                 guc_client_free(client);
1165
1166         client = fetch_and_zero(&guc->execbuf_client);
1167         if (client)
1168                 guc_client_free(client);
1169 }
1170
1171 static int __guc_client_enable(struct intel_guc_client *client)
1172 {
1173         int ret;
1174
1175         guc_proc_desc_init(client);
1176         guc_stage_desc_init(client);
1177
1178         ret = create_doorbell(client);
1179         if (ret)
1180                 goto fail;
1181
1182         return 0;
1183
1184 fail:
1185         guc_stage_desc_fini(client);
1186         guc_proc_desc_fini(client);
1187         return ret;
1188 }
1189
1190 static void __guc_client_disable(struct intel_guc_client *client)
1191 {
1192         /*
1193          * By the time we're here, GuC may have already been reset. if that is
1194          * the case, instead of trying (in vain) to communicate with it, let's
1195          * just cleanup the doorbell HW and our internal state.
1196          */
1197         if (intel_guc_is_alive(client->guc))
1198                 destroy_doorbell(client);
1199         else
1200                 __fini_doorbell(client);
1201
1202         guc_stage_desc_fini(client);
1203         guc_proc_desc_fini(client);
1204 }
1205
1206 static int guc_clients_enable(struct intel_guc *guc)
1207 {
1208         int ret;
1209
1210         ret = __guc_client_enable(guc->execbuf_client);
1211         if (ret)
1212                 return ret;
1213
1214         if (guc->preempt_client) {
1215                 ret = __guc_client_enable(guc->preempt_client);
1216                 if (ret) {
1217                         __guc_client_disable(guc->execbuf_client);
1218                         return ret;
1219                 }
1220         }
1221
1222         return 0;
1223 }
1224
1225 static void guc_clients_disable(struct intel_guc *guc)
1226 {
1227         if (guc->preempt_client)
1228                 __guc_client_disable(guc->preempt_client);
1229
1230         if (guc->execbuf_client)
1231                 __guc_client_disable(guc->execbuf_client);
1232 }
1233
1234 /*
1235  * Set up the memory resources to be shared with the GuC (via the GGTT)
1236  * at firmware loading time.
1237  */
1238 int intel_guc_submission_init(struct intel_guc *guc)
1239 {
1240         struct drm_i915_private *dev_priv = guc_to_i915(guc);
1241         struct intel_engine_cs *engine;
1242         enum intel_engine_id id;
1243         int ret;
1244
1245         if (guc->stage_desc_pool)
1246                 return 0;
1247
1248         ret = guc_stage_desc_pool_create(guc);
1249         if (ret)
1250                 return ret;
1251         /*
1252          * Keep static analysers happy, let them know that we allocated the
1253          * vma after testing that it didn't exist earlier.
1254          */
1255         GEM_BUG_ON(!guc->stage_desc_pool);
1256
1257         WARN_ON(!guc_verify_doorbells(guc));
1258         ret = guc_clients_create(guc);
1259         if (ret)
1260                 goto err_pool;
1261
1262         for_each_engine(engine, dev_priv, id) {
1263                 guc->preempt_work[id].engine = engine;
1264                 INIT_WORK(&guc->preempt_work[id].work, inject_preempt_context);
1265         }
1266
1267         return 0;
1268
1269 err_pool:
1270         guc_stage_desc_pool_destroy(guc);
1271         return ret;
1272 }
1273
1274 void intel_guc_submission_fini(struct intel_guc *guc)
1275 {
1276         struct drm_i915_private *dev_priv = guc_to_i915(guc);
1277         struct intel_engine_cs *engine;
1278         enum intel_engine_id id;
1279
1280         for_each_engine(engine, dev_priv, id)
1281                 cancel_work_sync(&guc->preempt_work[id].work);
1282
1283         guc_clients_destroy(guc);
1284         WARN_ON(!guc_verify_doorbells(guc));
1285
1286         if (guc->stage_desc_pool)
1287                 guc_stage_desc_pool_destroy(guc);
1288 }
1289
1290 static void guc_interrupts_capture(struct drm_i915_private *dev_priv)
1291 {
1292         struct intel_rps *rps = &dev_priv->gt_pm.rps;
1293         struct intel_engine_cs *engine;
1294         enum intel_engine_id id;
1295         int irqs;
1296
1297         /* tell all command streamers to forward interrupts (but not vblank)
1298          * to GuC
1299          */
1300         irqs = _MASKED_BIT_ENABLE(GFX_INTERRUPT_STEERING);
1301         for_each_engine(engine, dev_priv, id)
1302                 I915_WRITE(RING_MODE_GEN7(engine), irqs);
1303
1304         /* route USER_INTERRUPT to Host, all others are sent to GuC. */
1305         irqs = GT_RENDER_USER_INTERRUPT << GEN8_RCS_IRQ_SHIFT |
1306                GT_RENDER_USER_INTERRUPT << GEN8_BCS_IRQ_SHIFT;
1307         /* These three registers have the same bit definitions */
1308         I915_WRITE(GUC_BCS_RCS_IER, ~irqs);
1309         I915_WRITE(GUC_VCS2_VCS1_IER, ~irqs);
1310         I915_WRITE(GUC_WD_VECS_IER, ~irqs);
1311
1312         /*
1313          * The REDIRECT_TO_GUC bit of the PMINTRMSK register directs all
1314          * (unmasked) PM interrupts to the GuC. All other bits of this
1315          * register *disable* generation of a specific interrupt.
1316          *
1317          * 'pm_intrmsk_mbz' indicates bits that are NOT to be set when
1318          * writing to the PM interrupt mask register, i.e. interrupts
1319          * that must not be disabled.
1320          *
1321          * If the GuC is handling these interrupts, then we must not let
1322          * the PM code disable ANY interrupt that the GuC is expecting.
1323          * So for each ENABLED (0) bit in this register, we must SET the
1324          * bit in pm_intrmsk_mbz so that it's left enabled for the GuC.
1325          * GuC needs ARAT expired interrupt unmasked hence it is set in
1326          * pm_intrmsk_mbz.
1327          *
1328          * Here we CLEAR REDIRECT_TO_GUC bit in pm_intrmsk_mbz, which will
1329          * result in the register bit being left SET!
1330          */
1331         rps->pm_intrmsk_mbz |= ARAT_EXPIRED_INTRMSK;
1332         rps->pm_intrmsk_mbz &= ~GEN8_PMINTR_DISABLE_REDIRECT_TO_GUC;
1333 }
1334
1335 static void guc_interrupts_release(struct drm_i915_private *dev_priv)
1336 {
1337         struct intel_rps *rps = &dev_priv->gt_pm.rps;
1338         struct intel_engine_cs *engine;
1339         enum intel_engine_id id;
1340         int irqs;
1341
1342         /*
1343          * tell all command streamers NOT to forward interrupts or vblank
1344          * to GuC.
1345          */
1346         irqs = _MASKED_FIELD(GFX_FORWARD_VBLANK_MASK, GFX_FORWARD_VBLANK_NEVER);
1347         irqs |= _MASKED_BIT_DISABLE(GFX_INTERRUPT_STEERING);
1348         for_each_engine(engine, dev_priv, id)
1349                 I915_WRITE(RING_MODE_GEN7(engine), irqs);
1350
1351         /* route all GT interrupts to the host */
1352         I915_WRITE(GUC_BCS_RCS_IER, 0);
1353         I915_WRITE(GUC_VCS2_VCS1_IER, 0);
1354         I915_WRITE(GUC_WD_VECS_IER, 0);
1355
1356         rps->pm_intrmsk_mbz |= GEN8_PMINTR_DISABLE_REDIRECT_TO_GUC;
1357         rps->pm_intrmsk_mbz &= ~ARAT_EXPIRED_INTRMSK;
1358 }
1359
1360 static void guc_submission_park(struct intel_engine_cs *engine)
1361 {
1362         intel_engine_unpin_breadcrumbs_irq(engine);
1363         engine->flags &= ~I915_ENGINE_NEEDS_BREADCRUMB_TASKLET;
1364 }
1365
1366 static void guc_submission_unpark(struct intel_engine_cs *engine)
1367 {
1368         engine->flags |= I915_ENGINE_NEEDS_BREADCRUMB_TASKLET;
1369         intel_engine_pin_breadcrumbs_irq(engine);
1370 }
1371
1372 static void guc_set_default_submission(struct intel_engine_cs *engine)
1373 {
1374         /*
1375          * We inherit a bunch of functions from execlists that we'd like
1376          * to keep using:
1377          *
1378          *    engine->submit_request = execlists_submit_request;
1379          *    engine->cancel_requests = execlists_cancel_requests;
1380          *    engine->schedule = execlists_schedule;
1381          *
1382          * But we need to override the actual submission backend in order
1383          * to talk to the GuC.
1384          */
1385         intel_execlists_set_default_submission(engine);
1386
1387         engine->execlists.tasklet.func = guc_submission_tasklet;
1388
1389         engine->park = guc_submission_park;
1390         engine->unpark = guc_submission_unpark;
1391
1392         engine->reset.prepare = guc_reset_prepare;
1393         engine->reset.reset = guc_reset;
1394         engine->reset.finish = guc_reset_finish;
1395
1396         engine->cancel_requests = guc_cancel_requests;
1397
1398         engine->flags &= ~I915_ENGINE_SUPPORTS_STATS;
1399 }
1400
1401 int intel_guc_submission_enable(struct intel_guc *guc)
1402 {
1403         struct drm_i915_private *dev_priv = guc_to_i915(guc);
1404         struct intel_engine_cs *engine;
1405         enum intel_engine_id id;
1406         int err;
1407
1408         /*
1409          * We're using GuC work items for submitting work through GuC. Since
1410          * we're coalescing multiple requests from a single context into a
1411          * single work item prior to assigning it to execlist_port, we can
1412          * never have more work items than the total number of ports (for all
1413          * engines). The GuC firmware is controlling the HEAD of work queue,
1414          * and it is guaranteed that it will remove the work item from the
1415          * queue before our request is completed.
1416          */
1417         BUILD_BUG_ON(ARRAY_SIZE(engine->execlists.port) *
1418                      sizeof(struct guc_wq_item) *
1419                      I915_NUM_ENGINES > GUC_WQ_SIZE);
1420
1421         GEM_BUG_ON(!guc->execbuf_client);
1422
1423         err = intel_guc_sample_forcewake(guc);
1424         if (err)
1425                 return err;
1426
1427         err = guc_clients_enable(guc);
1428         if (err)
1429                 return err;
1430
1431         /* Take over from manual control of ELSP (execlists) */
1432         guc_interrupts_capture(dev_priv);
1433
1434         for_each_engine(engine, dev_priv, id) {
1435                 engine->set_default_submission = guc_set_default_submission;
1436                 engine->set_default_submission(engine);
1437         }
1438
1439         return 0;
1440 }
1441
1442 void intel_guc_submission_disable(struct intel_guc *guc)
1443 {
1444         struct drm_i915_private *dev_priv = guc_to_i915(guc);
1445
1446         GEM_BUG_ON(dev_priv->gt.awake); /* GT should be parked first */
1447
1448         guc_interrupts_release(dev_priv);
1449         guc_clients_disable(guc);
1450 }
1451
1452 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
1453 #include "selftests/intel_guc.c"
1454 #endif