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