]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/gpu/drm/i915/i915_guc_submission.c
drm/i915: Add a relay backed debugfs interface for capturing GuC logs
[karo-tx-linux.git] / drivers / gpu / drm / i915 / i915_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 #include <linux/firmware.h>
25 #include <linux/circ_buf.h>
26 #include <linux/debugfs.h>
27 #include <linux/relay.h>
28 #include "i915_drv.h"
29 #include "intel_guc.h"
30
31 /**
32  * DOC: GuC-based command submission
33  *
34  * i915_guc_client:
35  * We use the term client to avoid confusion with contexts. A i915_guc_client is
36  * equivalent to GuC object guc_context_desc. This context descriptor is
37  * allocated from a pool of 1024 entries. Kernel driver will allocate doorbell
38  * and workqueue for it. Also the process descriptor (guc_process_desc), which
39  * is mapped to client space. So the client can write Work Item then ring the
40  * doorbell.
41  *
42  * To simplify the implementation, we allocate one gem object that contains all
43  * pages for doorbell, process descriptor and workqueue.
44  *
45  * The Scratch registers:
46  * There are 16 MMIO-based registers start from 0xC180. The kernel driver writes
47  * a value to the action register (SOFT_SCRATCH_0) along with any data. It then
48  * triggers an interrupt on the GuC via another register write (0xC4C8).
49  * Firmware writes a success/fail code back to the action register after
50  * processes the request. The kernel driver polls waiting for this update and
51  * then proceeds.
52  * See host2guc_action()
53  *
54  * Doorbells:
55  * Doorbells are interrupts to uKernel. A doorbell is a single cache line (QW)
56  * mapped into process space.
57  *
58  * Work Items:
59  * There are several types of work items that the host may place into a
60  * workqueue, each with its own requirements and limitations. Currently only
61  * WQ_TYPE_INORDER is needed to support legacy submission via GuC, which
62  * represents in-order queue. The kernel driver packs ring tail pointer and an
63  * ELSP context descriptor dword into Work Item.
64  * See guc_wq_item_append()
65  *
66  */
67
68 /*
69  * Read GuC command/status register (SOFT_SCRATCH_0)
70  * Return true if it contains a response rather than a command
71  */
72 static inline bool host2guc_action_response(struct drm_i915_private *dev_priv,
73                                             u32 *status)
74 {
75         u32 val = I915_READ(SOFT_SCRATCH(0));
76         *status = val;
77         return GUC2HOST_IS_RESPONSE(val);
78 }
79
80 static int host2guc_action(struct intel_guc *guc, u32 *data, u32 len)
81 {
82         struct drm_i915_private *dev_priv = guc_to_i915(guc);
83         u32 status;
84         int i;
85         int ret;
86
87         if (WARN_ON(len < 1 || len > 15))
88                 return -EINVAL;
89
90         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
91
92         dev_priv->guc.action_count += 1;
93         dev_priv->guc.action_cmd = data[0];
94
95         for (i = 0; i < len; i++)
96                 I915_WRITE(SOFT_SCRATCH(i), data[i]);
97
98         POSTING_READ(SOFT_SCRATCH(i - 1));
99
100         I915_WRITE(HOST2GUC_INTERRUPT, HOST2GUC_TRIGGER);
101
102         /*
103          * Fast commands should complete in less than 10us, so sample quickly
104          * up to that length of time, then switch to a slower sleep-wait loop.
105          * No HOST2GUC command should ever take longer than 10ms.
106          */
107         ret = wait_for_us(host2guc_action_response(dev_priv, &status), 10);
108         if (ret)
109                 ret = wait_for(host2guc_action_response(dev_priv, &status), 10);
110         if (status != GUC2HOST_STATUS_SUCCESS) {
111                 /*
112                  * Either the GuC explicitly returned an error (which
113                  * we convert to -EIO here) or no response at all was
114                  * received within the timeout limit (-ETIMEDOUT)
115                  */
116                 if (ret != -ETIMEDOUT)
117                         ret = -EIO;
118
119                 DRM_WARN("Action 0x%X failed; ret=%d status=0x%08X response=0x%08X\n",
120                          data[0], ret, status, I915_READ(SOFT_SCRATCH(15)));
121
122                 dev_priv->guc.action_fail += 1;
123                 dev_priv->guc.action_err = ret;
124         }
125         dev_priv->guc.action_status = status;
126
127         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
128
129         return ret;
130 }
131
132 /*
133  * Tell the GuC to allocate or deallocate a specific doorbell
134  */
135
136 static int host2guc_allocate_doorbell(struct intel_guc *guc,
137                                       struct i915_guc_client *client)
138 {
139         u32 data[2];
140
141         data[0] = HOST2GUC_ACTION_ALLOCATE_DOORBELL;
142         data[1] = client->ctx_index;
143
144         return host2guc_action(guc, data, 2);
145 }
146
147 static int host2guc_release_doorbell(struct intel_guc *guc,
148                                      struct i915_guc_client *client)
149 {
150         u32 data[2];
151
152         data[0] = HOST2GUC_ACTION_DEALLOCATE_DOORBELL;
153         data[1] = client->ctx_index;
154
155         return host2guc_action(guc, data, 2);
156 }
157
158 static int host2guc_sample_forcewake(struct intel_guc *guc,
159                                      struct i915_guc_client *client)
160 {
161         struct drm_i915_private *dev_priv = guc_to_i915(guc);
162         u32 data[2];
163
164         data[0] = HOST2GUC_ACTION_SAMPLE_FORCEWAKE;
165         /* WaRsDisableCoarsePowerGating:skl,bxt */
166         if (!intel_enable_rc6() || NEEDS_WaRsDisableCoarsePowerGating(dev_priv))
167                 data[1] = 0;
168         else
169                 /* bit 0 and 1 are for Render and Media domain separately */
170                 data[1] = GUC_FORCEWAKE_RENDER | GUC_FORCEWAKE_MEDIA;
171
172         return host2guc_action(guc, data, ARRAY_SIZE(data));
173 }
174
175 static int host2guc_logbuffer_flush_complete(struct intel_guc *guc)
176 {
177         u32 data[1];
178
179         data[0] = HOST2GUC_ACTION_LOG_BUFFER_FILE_FLUSH_COMPLETE;
180
181         return host2guc_action(guc, data, 1);
182 }
183
184 /*
185  * Initialise, update, or clear doorbell data shared with the GuC
186  *
187  * These functions modify shared data and so need access to the mapped
188  * client object which contains the page being used for the doorbell
189  */
190
191 static int guc_update_doorbell_id(struct intel_guc *guc,
192                                   struct i915_guc_client *client,
193                                   u16 new_id)
194 {
195         struct sg_table *sg = guc->ctx_pool_vma->pages;
196         void *doorbell_bitmap = guc->doorbell_bitmap;
197         struct guc_doorbell_info *doorbell;
198         struct guc_context_desc desc;
199         size_t len;
200
201         doorbell = client->client_base + client->doorbell_offset;
202
203         if (client->doorbell_id != GUC_INVALID_DOORBELL_ID &&
204             test_bit(client->doorbell_id, doorbell_bitmap)) {
205                 /* Deactivate the old doorbell */
206                 doorbell->db_status = GUC_DOORBELL_DISABLED;
207                 (void)host2guc_release_doorbell(guc, client);
208                 __clear_bit(client->doorbell_id, doorbell_bitmap);
209         }
210
211         /* Update the GuC's idea of the doorbell ID */
212         len = sg_pcopy_to_buffer(sg->sgl, sg->nents, &desc, sizeof(desc),
213                              sizeof(desc) * client->ctx_index);
214         if (len != sizeof(desc))
215                 return -EFAULT;
216         desc.db_id = new_id;
217         len = sg_pcopy_from_buffer(sg->sgl, sg->nents, &desc, sizeof(desc),
218                              sizeof(desc) * client->ctx_index);
219         if (len != sizeof(desc))
220                 return -EFAULT;
221
222         client->doorbell_id = new_id;
223         if (new_id == GUC_INVALID_DOORBELL_ID)
224                 return 0;
225
226         /* Activate the new doorbell */
227         __set_bit(new_id, doorbell_bitmap);
228         doorbell->cookie = 0;
229         doorbell->db_status = GUC_DOORBELL_ENABLED;
230         return host2guc_allocate_doorbell(guc, client);
231 }
232
233 static int guc_init_doorbell(struct intel_guc *guc,
234                               struct i915_guc_client *client,
235                               uint16_t db_id)
236 {
237         return guc_update_doorbell_id(guc, client, db_id);
238 }
239
240 static void guc_disable_doorbell(struct intel_guc *guc,
241                                  struct i915_guc_client *client)
242 {
243         (void)guc_update_doorbell_id(guc, client, GUC_INVALID_DOORBELL_ID);
244
245         /* XXX: wait for any interrupts */
246         /* XXX: wait for workqueue to drain */
247 }
248
249 static uint16_t
250 select_doorbell_register(struct intel_guc *guc, uint32_t priority)
251 {
252         /*
253          * The bitmap tracks which doorbell registers are currently in use.
254          * It is split into two halves; the first half is used for normal
255          * priority contexts, the second half for high-priority ones.
256          * Note that logically higher priorities are numerically less than
257          * normal ones, so the test below means "is it high-priority?"
258          */
259         const bool hi_pri = (priority <= GUC_CTX_PRIORITY_HIGH);
260         const uint16_t half = GUC_MAX_DOORBELLS / 2;
261         const uint16_t start = hi_pri ? half : 0;
262         const uint16_t end = start + half;
263         uint16_t id;
264
265         id = find_next_zero_bit(guc->doorbell_bitmap, end, start);
266         if (id == end)
267                 id = GUC_INVALID_DOORBELL_ID;
268
269         DRM_DEBUG_DRIVER("assigned %s priority doorbell id 0x%x\n",
270                         hi_pri ? "high" : "normal", id);
271
272         return id;
273 }
274
275 /*
276  * Select, assign and relase doorbell cachelines
277  *
278  * These functions track which doorbell cachelines are in use.
279  * The data they manipulate is protected by the host2guc lock.
280  */
281
282 static uint32_t select_doorbell_cacheline(struct intel_guc *guc)
283 {
284         const uint32_t cacheline_size = cache_line_size();
285         uint32_t offset;
286
287         /* Doorbell uses a single cache line within a page */
288         offset = offset_in_page(guc->db_cacheline);
289
290         /* Moving to next cache line to reduce contention */
291         guc->db_cacheline += cacheline_size;
292
293         DRM_DEBUG_DRIVER("selected doorbell cacheline 0x%x, next 0x%x, linesize %u\n",
294                         offset, guc->db_cacheline, cacheline_size);
295
296         return offset;
297 }
298
299 /*
300  * Initialise the process descriptor shared with the GuC firmware.
301  */
302 static void guc_proc_desc_init(struct intel_guc *guc,
303                                struct i915_guc_client *client)
304 {
305         struct guc_process_desc *desc;
306
307         desc = client->client_base + client->proc_desc_offset;
308
309         memset(desc, 0, sizeof(*desc));
310
311         /*
312          * XXX: pDoorbell and WQVBaseAddress are pointers in process address
313          * space for ring3 clients (set them as in mmap_ioctl) or kernel
314          * space for kernel clients (map on demand instead? May make debug
315          * easier to have it mapped).
316          */
317         desc->wq_base_addr = 0;
318         desc->db_base_addr = 0;
319
320         desc->context_id = client->ctx_index;
321         desc->wq_size_bytes = client->wq_size;
322         desc->wq_status = WQ_STATUS_ACTIVE;
323         desc->priority = client->priority;
324 }
325
326 /*
327  * Initialise/clear the context descriptor shared with the GuC firmware.
328  *
329  * This descriptor tells the GuC where (in GGTT space) to find the important
330  * data structures relating to this client (doorbell, process descriptor,
331  * write queue, etc).
332  */
333
334 static void guc_ctx_desc_init(struct intel_guc *guc,
335                               struct i915_guc_client *client)
336 {
337         struct drm_i915_private *dev_priv = guc_to_i915(guc);
338         struct intel_engine_cs *engine;
339         struct i915_gem_context *ctx = client->owner;
340         struct guc_context_desc desc;
341         struct sg_table *sg;
342         unsigned int tmp;
343         u32 gfx_addr;
344
345         memset(&desc, 0, sizeof(desc));
346
347         desc.attribute = GUC_CTX_DESC_ATTR_ACTIVE | GUC_CTX_DESC_ATTR_KERNEL;
348         desc.context_id = client->ctx_index;
349         desc.priority = client->priority;
350         desc.db_id = client->doorbell_id;
351
352         for_each_engine_masked(engine, dev_priv, client->engines, tmp) {
353                 struct intel_context *ce = &ctx->engine[engine->id];
354                 uint32_t guc_engine_id = engine->guc_id;
355                 struct guc_execlist_context *lrc = &desc.lrc[guc_engine_id];
356
357                 /* TODO: We have a design issue to be solved here. Only when we
358                  * receive the first batch, we know which engine is used by the
359                  * user. But here GuC expects the lrc and ring to be pinned. It
360                  * is not an issue for default context, which is the only one
361                  * for now who owns a GuC client. But for future owner of GuC
362                  * client, need to make sure lrc is pinned prior to enter here.
363                  */
364                 if (!ce->state)
365                         break;  /* XXX: continue? */
366
367                 lrc->context_desc = lower_32_bits(ce->lrc_desc);
368
369                 /* The state page is after PPHWSP */
370                 lrc->ring_lcra =
371                         i915_ggtt_offset(ce->state) + LRC_STATE_PN * PAGE_SIZE;
372                 lrc->context_id = (client->ctx_index << GUC_ELC_CTXID_OFFSET) |
373                                 (guc_engine_id << GUC_ELC_ENGINE_OFFSET);
374
375                 lrc->ring_begin = i915_ggtt_offset(ce->ring->vma);
376                 lrc->ring_end = lrc->ring_begin + ce->ring->size - 1;
377                 lrc->ring_next_free_location = lrc->ring_begin;
378                 lrc->ring_current_tail_pointer_value = 0;
379
380                 desc.engines_used |= (1 << guc_engine_id);
381         }
382
383         DRM_DEBUG_DRIVER("Host engines 0x%x => GuC engines used 0x%x\n",
384                         client->engines, desc.engines_used);
385         WARN_ON(desc.engines_used == 0);
386
387         /*
388          * The doorbell, process descriptor, and workqueue are all parts
389          * of the client object, which the GuC will reference via the GGTT
390          */
391         gfx_addr = i915_ggtt_offset(client->vma);
392         desc.db_trigger_phy = sg_dma_address(client->vma->pages->sgl) +
393                                 client->doorbell_offset;
394         desc.db_trigger_cpu = (uintptr_t)client->client_base +
395                                 client->doorbell_offset;
396         desc.db_trigger_uk = gfx_addr + client->doorbell_offset;
397         desc.process_desc = gfx_addr + client->proc_desc_offset;
398         desc.wq_addr = gfx_addr + client->wq_offset;
399         desc.wq_size = client->wq_size;
400
401         /*
402          * XXX: Take LRCs from an existing context if this is not an
403          * IsKMDCreatedContext client
404          */
405         desc.desc_private = (uintptr_t)client;
406
407         /* Pool context is pinned already */
408         sg = guc->ctx_pool_vma->pages;
409         sg_pcopy_from_buffer(sg->sgl, sg->nents, &desc, sizeof(desc),
410                              sizeof(desc) * client->ctx_index);
411 }
412
413 static void guc_ctx_desc_fini(struct intel_guc *guc,
414                               struct i915_guc_client *client)
415 {
416         struct guc_context_desc desc;
417         struct sg_table *sg;
418
419         memset(&desc, 0, sizeof(desc));
420
421         sg = guc->ctx_pool_vma->pages;
422         sg_pcopy_from_buffer(sg->sgl, sg->nents, &desc, sizeof(desc),
423                              sizeof(desc) * client->ctx_index);
424 }
425
426 /**
427  * i915_guc_wq_reserve() - reserve space in the GuC's workqueue
428  * @request:    request associated with the commands
429  *
430  * Return:      0 if space is available
431  *              -EAGAIN if space is not currently available
432  *
433  * This function must be called (and must return 0) before a request
434  * is submitted to the GuC via i915_guc_submit() below. Once a result
435  * of 0 has been returned, it must be balanced by a corresponding
436  * call to submit().
437  *
438  * Reservation allows the caller to determine in advance that space
439  * will be available for the next submission before committing resources
440  * to it, and helps avoid late failures with complicated recovery paths.
441  */
442 int i915_guc_wq_reserve(struct drm_i915_gem_request *request)
443 {
444         const size_t wqi_size = sizeof(struct guc_wq_item);
445         struct i915_guc_client *gc = request->i915->guc.execbuf_client;
446         struct guc_process_desc *desc = gc->client_base + gc->proc_desc_offset;
447         u32 freespace;
448         int ret;
449
450         spin_lock(&gc->wq_lock);
451         freespace = CIRC_SPACE(gc->wq_tail, desc->head, gc->wq_size);
452         freespace -= gc->wq_rsvd;
453         if (likely(freespace >= wqi_size)) {
454                 gc->wq_rsvd += wqi_size;
455                 ret = 0;
456         } else {
457                 gc->no_wq_space++;
458                 ret = -EAGAIN;
459         }
460         spin_unlock(&gc->wq_lock);
461
462         return ret;
463 }
464
465 void i915_guc_wq_unreserve(struct drm_i915_gem_request *request)
466 {
467         const size_t wqi_size = sizeof(struct guc_wq_item);
468         struct i915_guc_client *gc = request->i915->guc.execbuf_client;
469
470         GEM_BUG_ON(READ_ONCE(gc->wq_rsvd) < wqi_size);
471
472         spin_lock(&gc->wq_lock);
473         gc->wq_rsvd -= wqi_size;
474         spin_unlock(&gc->wq_lock);
475 }
476
477 /* Construct a Work Item and append it to the GuC's Work Queue */
478 static void guc_wq_item_append(struct i915_guc_client *gc,
479                                struct drm_i915_gem_request *rq)
480 {
481         /* wqi_len is in DWords, and does not include the one-word header */
482         const size_t wqi_size = sizeof(struct guc_wq_item);
483         const u32 wqi_len = wqi_size/sizeof(u32) - 1;
484         struct intel_engine_cs *engine = rq->engine;
485         struct guc_process_desc *desc;
486         struct guc_wq_item *wqi;
487         void *base;
488         u32 freespace, tail, wq_off, wq_page;
489
490         desc = gc->client_base + gc->proc_desc_offset;
491
492         /* Free space is guaranteed, see i915_guc_wq_reserve() above */
493         freespace = CIRC_SPACE(gc->wq_tail, desc->head, gc->wq_size);
494         GEM_BUG_ON(freespace < wqi_size);
495
496         /* The GuC firmware wants the tail index in QWords, not bytes */
497         tail = rq->tail;
498         GEM_BUG_ON(tail & 7);
499         tail >>= 3;
500         GEM_BUG_ON(tail > WQ_RING_TAIL_MAX);
501
502         /* For now workqueue item is 4 DWs; workqueue buffer is 2 pages. So we
503          * should not have the case where structure wqi is across page, neither
504          * wrapped to the beginning. This simplifies the implementation below.
505          *
506          * XXX: if not the case, we need save data to a temp wqi and copy it to
507          * workqueue buffer dw by dw.
508          */
509         BUILD_BUG_ON(wqi_size != 16);
510         GEM_BUG_ON(gc->wq_rsvd < wqi_size);
511
512         /* postincrement WQ tail for next time */
513         wq_off = gc->wq_tail;
514         GEM_BUG_ON(wq_off & (wqi_size - 1));
515         gc->wq_tail += wqi_size;
516         gc->wq_tail &= gc->wq_size - 1;
517         gc->wq_rsvd -= wqi_size;
518
519         /* WQ starts from the page after doorbell / process_desc */
520         wq_page = (wq_off + GUC_DB_SIZE) >> PAGE_SHIFT;
521         wq_off &= PAGE_SIZE - 1;
522         base = kmap_atomic(i915_gem_object_get_page(gc->vma->obj, wq_page));
523         wqi = (struct guc_wq_item *)((char *)base + wq_off);
524
525         /* Now fill in the 4-word work queue item */
526         wqi->header = WQ_TYPE_INORDER |
527                         (wqi_len << WQ_LEN_SHIFT) |
528                         (engine->guc_id << WQ_TARGET_SHIFT) |
529                         WQ_NO_WCFLUSH_WAIT;
530
531         /* The GuC wants only the low-order word of the context descriptor */
532         wqi->context_desc = (u32)intel_lr_context_descriptor(rq->ctx, engine);
533
534         wqi->ring_tail = tail << WQ_RING_TAIL_SHIFT;
535         wqi->fence_id = rq->fence.seqno;
536
537         kunmap_atomic(base);
538 }
539
540 static int guc_ring_doorbell(struct i915_guc_client *gc)
541 {
542         struct guc_process_desc *desc;
543         union guc_doorbell_qw db_cmp, db_exc, db_ret;
544         union guc_doorbell_qw *db;
545         int attempt = 2, ret = -EAGAIN;
546
547         desc = gc->client_base + gc->proc_desc_offset;
548
549         /* Update the tail so it is visible to GuC */
550         desc->tail = gc->wq_tail;
551
552         /* current cookie */
553         db_cmp.db_status = GUC_DOORBELL_ENABLED;
554         db_cmp.cookie = gc->cookie;
555
556         /* cookie to be updated */
557         db_exc.db_status = GUC_DOORBELL_ENABLED;
558         db_exc.cookie = gc->cookie + 1;
559         if (db_exc.cookie == 0)
560                 db_exc.cookie = 1;
561
562         /* pointer of current doorbell cacheline */
563         db = gc->client_base + gc->doorbell_offset;
564
565         while (attempt--) {
566                 /* lets ring the doorbell */
567                 db_ret.value_qw = atomic64_cmpxchg((atomic64_t *)db,
568                         db_cmp.value_qw, db_exc.value_qw);
569
570                 /* if the exchange was successfully executed */
571                 if (db_ret.value_qw == db_cmp.value_qw) {
572                         /* db was successfully rung */
573                         gc->cookie = db_exc.cookie;
574                         ret = 0;
575                         break;
576                 }
577
578                 /* XXX: doorbell was lost and need to acquire it again */
579                 if (db_ret.db_status == GUC_DOORBELL_DISABLED)
580                         break;
581
582                 DRM_WARN("Cookie mismatch. Expected %d, found %d\n",
583                          db_cmp.cookie, db_ret.cookie);
584
585                 /* update the cookie to newly read cookie from GuC */
586                 db_cmp.cookie = db_ret.cookie;
587                 db_exc.cookie = db_ret.cookie + 1;
588                 if (db_exc.cookie == 0)
589                         db_exc.cookie = 1;
590         }
591
592         return ret;
593 }
594
595 /**
596  * i915_guc_submit() - Submit commands through GuC
597  * @rq:         request associated with the commands
598  *
599  * Return:      0 on success, otherwise an errno.
600  *              (Note: nonzero really shouldn't happen!)
601  *
602  * The caller must have already called i915_guc_wq_reserve() above with
603  * a result of 0 (success), guaranteeing that there is space in the work
604  * queue for the new request, so enqueuing the item cannot fail.
605  *
606  * Bad Things Will Happen if the caller violates this protocol e.g. calls
607  * submit() when _reserve() says there's no space, or calls _submit()
608  * a different number of times from (successful) calls to _reserve().
609  *
610  * The only error here arises if the doorbell hardware isn't functioning
611  * as expected, which really shouln't happen.
612  */
613 static void i915_guc_submit(struct drm_i915_gem_request *rq)
614 {
615         unsigned int engine_id = rq->engine->id;
616         struct intel_guc *guc = &rq->i915->guc;
617         struct i915_guc_client *client = guc->execbuf_client;
618         int b_ret;
619
620         spin_lock(&client->wq_lock);
621         guc_wq_item_append(client, rq);
622         b_ret = guc_ring_doorbell(client);
623
624         client->submissions[engine_id] += 1;
625         client->retcode = b_ret;
626         if (b_ret)
627                 client->b_fail += 1;
628
629         guc->submissions[engine_id] += 1;
630         guc->last_seqno[engine_id] = rq->fence.seqno;
631         spin_unlock(&client->wq_lock);
632 }
633
634 /*
635  * Everything below here is concerned with setup & teardown, and is
636  * therefore not part of the somewhat time-critical batch-submission
637  * path of i915_guc_submit() above.
638  */
639
640 /**
641  * guc_allocate_vma() - Allocate a GGTT VMA for GuC usage
642  * @guc:        the guc
643  * @size:       size of area to allocate (both virtual space and memory)
644  *
645  * This is a wrapper to create an object for use with the GuC. In order to
646  * use it inside the GuC, an object needs to be pinned lifetime, so we allocate
647  * both some backing storage and a range inside the Global GTT. We must pin
648  * it in the GGTT somewhere other than than [0, GUC_WOPCM_TOP) because that
649  * range is reserved inside GuC.
650  *
651  * Return:      A i915_vma if successful, otherwise an ERR_PTR.
652  */
653 static struct i915_vma *guc_allocate_vma(struct intel_guc *guc, u32 size)
654 {
655         struct drm_i915_private *dev_priv = guc_to_i915(guc);
656         struct drm_i915_gem_object *obj;
657         struct i915_vma *vma;
658         int ret;
659
660         obj = i915_gem_object_create(&dev_priv->drm, size);
661         if (IS_ERR(obj))
662                 return ERR_CAST(obj);
663
664         vma = i915_vma_create(obj, &dev_priv->ggtt.base, NULL);
665         if (IS_ERR(vma))
666                 goto err;
667
668         ret = i915_vma_pin(vma, 0, PAGE_SIZE,
669                            PIN_GLOBAL | PIN_OFFSET_BIAS | GUC_WOPCM_TOP);
670         if (ret) {
671                 vma = ERR_PTR(ret);
672                 goto err;
673         }
674
675         /* Invalidate GuC TLB to let GuC take the latest updates to GTT. */
676         I915_WRITE(GEN8_GTCR, GEN8_GTCR_INVALIDATE);
677
678         return vma;
679
680 err:
681         i915_gem_object_put(obj);
682         return vma;
683 }
684
685 static void
686 guc_client_free(struct drm_i915_private *dev_priv,
687                 struct i915_guc_client *client)
688 {
689         struct intel_guc *guc = &dev_priv->guc;
690
691         if (!client)
692                 return;
693
694         /*
695          * XXX: wait for any outstanding submissions before freeing memory.
696          * Be sure to drop any locks
697          */
698
699         if (client->client_base) {
700                 /*
701                  * If we got as far as setting up a doorbell, make sure we
702                  * shut it down before unmapping & deallocating the memory.
703                  */
704                 guc_disable_doorbell(guc, client);
705
706                 kunmap(kmap_to_page(client->client_base));
707         }
708
709         i915_vma_unpin_and_release(&client->vma);
710
711         if (client->ctx_index != GUC_INVALID_CTX_ID) {
712                 guc_ctx_desc_fini(guc, client);
713                 ida_simple_remove(&guc->ctx_ids, client->ctx_index);
714         }
715
716         kfree(client);
717 }
718
719 /* Check that a doorbell register is in the expected state */
720 static bool guc_doorbell_check(struct intel_guc *guc, uint16_t db_id)
721 {
722         struct drm_i915_private *dev_priv = guc_to_i915(guc);
723         i915_reg_t drbreg = GEN8_DRBREGL(db_id);
724         uint32_t value = I915_READ(drbreg);
725         bool enabled = (value & GUC_DOORBELL_ENABLED) != 0;
726         bool expected = test_bit(db_id, guc->doorbell_bitmap);
727
728         if (enabled == expected)
729                 return true;
730
731         DRM_DEBUG_DRIVER("Doorbell %d (reg 0x%x) 0x%x, should be %s\n",
732                          db_id, drbreg.reg, value,
733                          expected ? "active" : "inactive");
734
735         return false;
736 }
737
738 /*
739  * Borrow the first client to set up & tear down each unused doorbell
740  * in turn, to ensure that all doorbell h/w is (re)initialised.
741  */
742 static void guc_init_doorbell_hw(struct intel_guc *guc)
743 {
744         struct i915_guc_client *client = guc->execbuf_client;
745         uint16_t db_id;
746         int i, err;
747
748         /* Save client's original doorbell selection */
749         db_id = client->doorbell_id;
750
751         for (i = 0; i < GUC_MAX_DOORBELLS; ++i) {
752                 /* Skip if doorbell is OK */
753                 if (guc_doorbell_check(guc, i))
754                         continue;
755
756                 err = guc_update_doorbell_id(guc, client, i);
757                 if (err)
758                         DRM_DEBUG_DRIVER("Doorbell %d update failed, err %d\n",
759                                         i, err);
760         }
761
762         /* Restore to original value */
763         err = guc_update_doorbell_id(guc, client, db_id);
764         if (err)
765                 DRM_WARN("Failed to restore doorbell to %d, err %d\n",
766                          db_id, err);
767
768         /* Read back & verify all doorbell registers */
769         for (i = 0; i < GUC_MAX_DOORBELLS; ++i)
770                 (void)guc_doorbell_check(guc, i);
771 }
772
773 /**
774  * guc_client_alloc() - Allocate an i915_guc_client
775  * @dev_priv:   driver private data structure
776  * @engines:    The set of engines to enable for this client
777  * @priority:   four levels priority _CRITICAL, _HIGH, _NORMAL and _LOW
778  *              The kernel client to replace ExecList submission is created with
779  *              NORMAL priority. Priority of a client for scheduler can be HIGH,
780  *              while a preemption context can use CRITICAL.
781  * @ctx:        the context that owns the client (we use the default render
782  *              context)
783  *
784  * Return:      An i915_guc_client object if success, else NULL.
785  */
786 static struct i915_guc_client *
787 guc_client_alloc(struct drm_i915_private *dev_priv,
788                  uint32_t engines,
789                  uint32_t priority,
790                  struct i915_gem_context *ctx)
791 {
792         struct i915_guc_client *client;
793         struct intel_guc *guc = &dev_priv->guc;
794         struct i915_vma *vma;
795         uint16_t db_id;
796
797         client = kzalloc(sizeof(*client), GFP_KERNEL);
798         if (!client)
799                 return NULL;
800
801         client->owner = ctx;
802         client->guc = guc;
803         client->engines = engines;
804         client->priority = priority;
805         client->doorbell_id = GUC_INVALID_DOORBELL_ID;
806
807         client->ctx_index = (uint32_t)ida_simple_get(&guc->ctx_ids, 0,
808                         GUC_MAX_GPU_CONTEXTS, GFP_KERNEL);
809         if (client->ctx_index >= GUC_MAX_GPU_CONTEXTS) {
810                 client->ctx_index = GUC_INVALID_CTX_ID;
811                 goto err;
812         }
813
814         /* The first page is doorbell/proc_desc. Two followed pages are wq. */
815         vma = guc_allocate_vma(guc, GUC_DB_SIZE + GUC_WQ_SIZE);
816         if (IS_ERR(vma))
817                 goto err;
818
819         /* We'll keep just the first (doorbell/proc) page permanently kmap'd. */
820         client->vma = vma;
821         client->client_base = kmap(i915_vma_first_page(vma));
822
823         spin_lock_init(&client->wq_lock);
824         client->wq_offset = GUC_DB_SIZE;
825         client->wq_size = GUC_WQ_SIZE;
826
827         db_id = select_doorbell_register(guc, client->priority);
828         if (db_id == GUC_INVALID_DOORBELL_ID)
829                 /* XXX: evict a doorbell instead? */
830                 goto err;
831
832         client->doorbell_offset = select_doorbell_cacheline(guc);
833
834         /*
835          * Since the doorbell only requires a single cacheline, we can save
836          * space by putting the application process descriptor in the same
837          * page. Use the half of the page that doesn't include the doorbell.
838          */
839         if (client->doorbell_offset >= (GUC_DB_SIZE / 2))
840                 client->proc_desc_offset = 0;
841         else
842                 client->proc_desc_offset = (GUC_DB_SIZE / 2);
843
844         guc_proc_desc_init(guc, client);
845         guc_ctx_desc_init(guc, client);
846         if (guc_init_doorbell(guc, client, db_id))
847                 goto err;
848
849         DRM_DEBUG_DRIVER("new priority %u client %p for engine(s) 0x%x: ctx_index %u\n",
850                 priority, client, client->engines, client->ctx_index);
851         DRM_DEBUG_DRIVER("doorbell id %u, cacheline offset 0x%x\n",
852                 client->doorbell_id, client->doorbell_offset);
853
854         return client;
855
856 err:
857         guc_client_free(dev_priv, client);
858         return NULL;
859 }
860
861 /*
862  * Sub buffer switch callback. Called whenever relay has to switch to a new
863  * sub buffer, relay stays on the same sub buffer if 0 is returned.
864  */
865 static int subbuf_start_callback(struct rchan_buf *buf,
866                                  void *subbuf,
867                                  void *prev_subbuf,
868                                  size_t prev_padding)
869 {
870         /* Use no-overwrite mode by default, where relay will stop accepting
871          * new data if there are no empty sub buffers left.
872          * There is no strict synchronization enforced by relay between Consumer
873          * and Producer. In overwrite mode, there is a possibility of getting
874          * inconsistent/garbled data, the producer could be writing on to the
875          * same sub buffer from which Consumer is reading. This can't be avoided
876          * unless Consumer is fast enough and can always run in tandem with
877          * Producer.
878          */
879         if (relay_buf_full(buf))
880                 return 0;
881
882         return 1;
883 }
884
885 /*
886  * file_create() callback. Creates relay file in debugfs.
887  */
888 static struct dentry *create_buf_file_callback(const char *filename,
889                                                struct dentry *parent,
890                                                umode_t mode,
891                                                struct rchan_buf *buf,
892                                                int *is_global)
893 {
894         struct dentry *buf_file;
895
896         if (!parent)
897                 return NULL;
898
899         /* This to enable the use of a single buffer for the relay channel and
900          * correspondingly have a single file exposed to User, through which
901          * it can collect the logs in order without any post-processing.
902          */
903         *is_global = 1;
904
905         /* Not using the channel filename passed as an argument, since for each
906          * channel relay appends the corresponding CPU number to the filename
907          * passed in relay_open(). This should be fine as relay just needs a
908          * dentry of the file associated with the channel buffer and that file's
909          * name need not be same as the filename passed as an argument.
910          */
911         buf_file = debugfs_create_file("guc_log", mode,
912                                        parent, buf, &relay_file_operations);
913         return buf_file;
914 }
915
916 /*
917  * file_remove() default callback. Removes relay file in debugfs.
918  */
919 static int remove_buf_file_callback(struct dentry *dentry)
920 {
921         debugfs_remove(dentry);
922         return 0;
923 }
924
925 /* relay channel callbacks */
926 static struct rchan_callbacks relay_callbacks = {
927         .subbuf_start = subbuf_start_callback,
928         .create_buf_file = create_buf_file_callback,
929         .remove_buf_file = remove_buf_file_callback,
930 };
931
932 static void guc_log_remove_relay_file(struct intel_guc *guc)
933 {
934         relay_close(guc->log.relay_chan);
935 }
936
937 static int guc_log_create_relay_file(struct intel_guc *guc)
938 {
939         struct drm_i915_private *dev_priv = guc_to_i915(guc);
940         struct rchan *guc_log_relay_chan;
941         struct dentry *log_dir;
942         size_t n_subbufs, subbuf_size;
943
944         /* For now create the log file in /sys/kernel/debug/dri/0 dir */
945         log_dir = dev_priv->drm.primary->debugfs_root;
946
947         /* If /sys/kernel/debug/dri/0 location do not exist, then debugfs is
948          * not mounted and so can't create the relay file.
949          * The relay API seems to fit well with debugfs only, for availing relay
950          * there are 3 requirements which can be met for debugfs file only in a
951          * straightforward/clean manner :-
952          * i)   Need the associated dentry pointer of the file, while opening the
953          *      relay channel.
954          * ii)  Should be able to use 'relay_file_operations' fops for the file.
955          * iii) Set the 'i_private' field of file's inode to the pointer of
956          *      relay channel buffer.
957          */
958         if (!log_dir) {
959                 DRM_ERROR("Debugfs dir not available yet for GuC log file\n");
960                 return -ENODEV;
961         }
962
963         /* Keep the size of sub buffers same as shared log buffer */
964         subbuf_size = guc->log.vma->obj->base.size;
965
966         /* Store up to 8 snapshots, which is large enough to buffer sufficient
967          * boot time logs and provides enough leeway to User, in terms of
968          * latency, for consuming the logs from relay. Also doesn't take
969          * up too much memory.
970          */
971         n_subbufs = 8;
972
973         guc_log_relay_chan = relay_open("guc_log", log_dir, subbuf_size,
974                                         n_subbufs, &relay_callbacks, dev_priv);
975         if (!guc_log_relay_chan) {
976                 DRM_ERROR("Couldn't create relay chan for GuC logging\n");
977                 return -ENOMEM;
978         }
979
980         GEM_BUG_ON(guc_log_relay_chan->subbuf_size < subbuf_size);
981         /* FIXME: Cover the update under a lock ? */
982         guc->log.relay_chan = guc_log_relay_chan;
983         return 0;
984 }
985
986 static void guc_move_to_next_buf(struct intel_guc *guc)
987 {
988         /* Make sure the updates made in the sub buffer are visible when
989          * Consumer sees the following update to offset inside the sub buffer.
990          */
991         smp_wmb();
992
993         /* All data has been written, so now move the offset of sub buffer. */
994         relay_reserve(guc->log.relay_chan, guc->log.vma->obj->base.size);
995
996         /* Switch to the next sub buffer */
997         relay_flush(guc->log.relay_chan);
998 }
999
1000 static void *guc_get_write_buffer(struct intel_guc *guc)
1001 {
1002         /* FIXME: Cover the check under a lock ? */
1003         if (!guc->log.relay_chan)
1004                 return NULL;
1005
1006         /* Just get the base address of a new sub buffer and copy data into it
1007          * ourselves. NULL will be returned in no-overwrite mode, if all sub
1008          * buffers are full. Could have used the relay_write() to indirectly
1009          * copy the data, but that would have been bit convoluted, as we need to
1010          * write to only certain locations inside a sub buffer which cannot be
1011          * done without using relay_reserve() along with relay_write(). So its
1012          * better to use relay_reserve() alone.
1013          */
1014         return relay_reserve(guc->log.relay_chan, 0);
1015 }
1016
1017 static unsigned int guc_get_log_buffer_size(enum guc_log_buffer_type type)
1018 {
1019         switch (type) {
1020         case GUC_ISR_LOG_BUFFER:
1021                 return (GUC_LOG_ISR_PAGES + 1) * PAGE_SIZE;
1022         case GUC_DPC_LOG_BUFFER:
1023                 return (GUC_LOG_DPC_PAGES + 1) * PAGE_SIZE;
1024         case GUC_CRASH_DUMP_LOG_BUFFER:
1025                 return (GUC_LOG_CRASH_PAGES + 1) * PAGE_SIZE;
1026         default:
1027                 MISSING_CASE(type);
1028         }
1029
1030         return 0;
1031 }
1032
1033 static void guc_read_update_log_buffer(struct intel_guc *guc)
1034 {
1035         struct guc_log_buffer_state *log_buf_state, *log_buf_snapshot_state;
1036         struct guc_log_buffer_state log_buf_state_local;
1037         unsigned int buffer_size, write_offset;
1038         enum guc_log_buffer_type type;
1039         void *src_data, *dst_data;
1040
1041         if (WARN_ON(!guc->log.buf_addr))
1042                 return;
1043
1044         /* Get the pointer to shared GuC log buffer */
1045         log_buf_state = src_data = guc->log.buf_addr;
1046
1047         /* Get the pointer to local buffer to store the logs */
1048         log_buf_snapshot_state = dst_data = guc_get_write_buffer(guc);
1049
1050         /* Actual logs are present from the 2nd page */
1051         src_data += PAGE_SIZE;
1052         dst_data += PAGE_SIZE;
1053
1054         for (type = GUC_ISR_LOG_BUFFER; type < GUC_MAX_LOG_BUFFER; type++) {
1055                 /* Make a copy of the state structure, inside GuC log buffer
1056                  * (which is uncached mapped), on the stack to avoid reading
1057                  * from it multiple times.
1058                  */
1059                 memcpy(&log_buf_state_local, log_buf_state,
1060                        sizeof(struct guc_log_buffer_state));
1061                 buffer_size = guc_get_log_buffer_size(type);
1062                 write_offset = log_buf_state_local.sampled_write_ptr;
1063
1064                 /* Update the state of shared log buffer */
1065                 log_buf_state->read_ptr = write_offset;
1066                 log_buf_state->flush_to_file = 0;
1067                 log_buf_state++;
1068
1069                 if (unlikely(!log_buf_snapshot_state))
1070                         continue;
1071
1072                 /* First copy the state structure in snapshot buffer */
1073                 memcpy(log_buf_snapshot_state, &log_buf_state_local,
1074                        sizeof(struct guc_log_buffer_state));
1075
1076                 /* The write pointer could have been updated by GuC firmware,
1077                  * after sending the flush interrupt to Host, for consistency
1078                  * set write pointer value to same value of sampled_write_ptr
1079                  * in the snapshot buffer.
1080                  */
1081                 log_buf_snapshot_state->write_ptr = write_offset;
1082                 log_buf_snapshot_state++;
1083
1084                 /* Now copy the actual logs. */
1085                 memcpy(dst_data, src_data, buffer_size);
1086
1087                 src_data += buffer_size;
1088                 dst_data += buffer_size;
1089
1090                 /* FIXME: invalidate/flush for log buffer needed */
1091         }
1092
1093         if (log_buf_snapshot_state)
1094                 guc_move_to_next_buf(guc);
1095         else {
1096                 /* Used rate limited to avoid deluge of messages, logs might be
1097                  * getting consumed by User at a slow rate.
1098                  */
1099                 DRM_ERROR_RATELIMITED("no sub-buffer to capture logs\n");
1100         }
1101 }
1102
1103 static void guc_capture_logs_work(struct work_struct *work)
1104 {
1105         struct drm_i915_private *dev_priv =
1106                 container_of(work, struct drm_i915_private, guc.log.flush_work);
1107
1108         i915_guc_capture_logs(dev_priv);
1109 }
1110
1111 static void guc_log_cleanup(struct intel_guc *guc)
1112 {
1113         struct drm_i915_private *dev_priv = guc_to_i915(guc);
1114
1115         lockdep_assert_held(&dev_priv->drm.struct_mutex);
1116
1117         /* First disable the flush interrupt */
1118         gen9_disable_guc_interrupts(dev_priv);
1119
1120         if (guc->log.flush_wq)
1121                 destroy_workqueue(guc->log.flush_wq);
1122
1123         guc->log.flush_wq = NULL;
1124
1125         if (guc->log.relay_chan)
1126                 guc_log_remove_relay_file(guc);
1127
1128         guc->log.relay_chan = NULL;
1129
1130         if (guc->log.buf_addr)
1131                 i915_gem_object_unpin_map(guc->log.vma->obj);
1132
1133         guc->log.buf_addr = NULL;
1134 }
1135
1136 static int guc_log_create_extras(struct intel_guc *guc)
1137 {
1138         struct drm_i915_private *dev_priv = guc_to_i915(guc);
1139         void *vaddr;
1140         int ret;
1141
1142         lockdep_assert_held(&dev_priv->drm.struct_mutex);
1143
1144         /* Nothing to do */
1145         if (i915.guc_log_level < 0)
1146                 return 0;
1147
1148         if (!guc->log.buf_addr) {
1149                 /* Create a vmalloc mapping of log buffer pages */
1150                 vaddr = i915_gem_object_pin_map(guc->log.vma->obj, I915_MAP_WB);
1151                 if (IS_ERR(vaddr)) {
1152                         ret = PTR_ERR(vaddr);
1153                         DRM_ERROR("Couldn't map log buffer pages %d\n", ret);
1154                         return ret;
1155                 }
1156
1157                 guc->log.buf_addr = vaddr;
1158         }
1159
1160         if (!guc->log.flush_wq) {
1161                 INIT_WORK(&guc->log.flush_work, guc_capture_logs_work);
1162
1163                 /* Need a dedicated wq to process log buffer flush interrupts
1164                  * from GuC without much delay so as to avoid any loss of logs.
1165                  */
1166                 guc->log.flush_wq = alloc_ordered_workqueue("i915-guc_log", WQ_HIGHPRI);
1167                 if (guc->log.flush_wq == NULL) {
1168                         DRM_ERROR("Couldn't allocate the wq for GuC logging\n");
1169                         return -ENOMEM;
1170                 }
1171         }
1172
1173         return 0;
1174 }
1175
1176 static void guc_log_create(struct intel_guc *guc)
1177 {
1178         struct i915_vma *vma;
1179         unsigned long offset;
1180         uint32_t size, flags;
1181
1182         if (i915.guc_log_level > GUC_LOG_VERBOSITY_MAX)
1183                 i915.guc_log_level = GUC_LOG_VERBOSITY_MAX;
1184
1185         /* The first page is to save log buffer state. Allocate one
1186          * extra page for others in case for overlap */
1187         size = (1 + GUC_LOG_DPC_PAGES + 1 +
1188                 GUC_LOG_ISR_PAGES + 1 +
1189                 GUC_LOG_CRASH_PAGES + 1) << PAGE_SHIFT;
1190
1191         vma = guc->log.vma;
1192         if (!vma) {
1193                 vma = guc_allocate_vma(guc, size);
1194                 if (IS_ERR(vma)) {
1195                         /* logging will be off */
1196                         i915.guc_log_level = -1;
1197                         return;
1198                 }
1199
1200                 guc->log.vma = vma;
1201
1202                 if (guc_log_create_extras(guc)) {
1203                         guc_log_cleanup(guc);
1204                         i915_vma_unpin_and_release(&guc->log.vma);
1205                         i915.guc_log_level = -1;
1206                         return;
1207                 }
1208         }
1209
1210         /* each allocated unit is a page */
1211         flags = GUC_LOG_VALID | GUC_LOG_NOTIFY_ON_HALF_FULL |
1212                 (GUC_LOG_DPC_PAGES << GUC_LOG_DPC_SHIFT) |
1213                 (GUC_LOG_ISR_PAGES << GUC_LOG_ISR_SHIFT) |
1214                 (GUC_LOG_CRASH_PAGES << GUC_LOG_CRASH_SHIFT);
1215
1216         offset = i915_ggtt_offset(vma) >> PAGE_SHIFT; /* in pages */
1217         guc->log.flags = (offset << GUC_LOG_BUF_ADDR_SHIFT) | flags;
1218 }
1219
1220 static int guc_log_late_setup(struct intel_guc *guc)
1221 {
1222         struct drm_i915_private *dev_priv = guc_to_i915(guc);
1223         int ret;
1224
1225         lockdep_assert_held(&dev_priv->drm.struct_mutex);
1226
1227         if (i915.guc_log_level < 0)
1228                 return -EINVAL;
1229
1230         /* If log_level was set as -1 at boot time, then setup needed to
1231          * handle log buffer flush interrupts would not have been done yet,
1232          * so do that now.
1233          */
1234         ret = guc_log_create_extras(guc);
1235         if (ret)
1236                 goto err;
1237
1238         ret = guc_log_create_relay_file(guc);
1239         if (ret)
1240                 goto err;
1241
1242         return 0;
1243 err:
1244         guc_log_cleanup(guc);
1245         /* logging will remain off */
1246         i915.guc_log_level = -1;
1247         return ret;
1248 }
1249
1250 static void guc_policies_init(struct guc_policies *policies)
1251 {
1252         struct guc_policy *policy;
1253         u32 p, i;
1254
1255         policies->dpc_promote_time = 500000;
1256         policies->max_num_work_items = POLICY_MAX_NUM_WI;
1257
1258         for (p = 0; p < GUC_CTX_PRIORITY_NUM; p++) {
1259                 for (i = GUC_RENDER_ENGINE; i < GUC_MAX_ENGINES_NUM; i++) {
1260                         policy = &policies->policy[p][i];
1261
1262                         policy->execution_quantum = 1000000;
1263                         policy->preemption_time = 500000;
1264                         policy->fault_time = 250000;
1265                         policy->policy_flags = 0;
1266                 }
1267         }
1268
1269         policies->is_valid = 1;
1270 }
1271
1272 static void guc_addon_create(struct intel_guc *guc)
1273 {
1274         struct drm_i915_private *dev_priv = guc_to_i915(guc);
1275         struct i915_vma *vma;
1276         struct guc_ads *ads;
1277         struct guc_policies *policies;
1278         struct guc_mmio_reg_state *reg_state;
1279         struct intel_engine_cs *engine;
1280         enum intel_engine_id id;
1281         struct page *page;
1282         u32 size;
1283
1284         /* The ads obj includes the struct itself and buffers passed to GuC */
1285         size = sizeof(struct guc_ads) + sizeof(struct guc_policies) +
1286                         sizeof(struct guc_mmio_reg_state) +
1287                         GUC_S3_SAVE_SPACE_PAGES * PAGE_SIZE;
1288
1289         vma = guc->ads_vma;
1290         if (!vma) {
1291                 vma = guc_allocate_vma(guc, PAGE_ALIGN(size));
1292                 if (IS_ERR(vma))
1293                         return;
1294
1295                 guc->ads_vma = vma;
1296         }
1297
1298         page = i915_vma_first_page(vma);
1299         ads = kmap(page);
1300
1301         /*
1302          * The GuC requires a "Golden Context" when it reinitialises
1303          * engines after a reset. Here we use the Render ring default
1304          * context, which must already exist and be pinned in the GGTT,
1305          * so its address won't change after we've told the GuC where
1306          * to find it.
1307          */
1308         engine = dev_priv->engine[RCS];
1309         ads->golden_context_lrca = engine->status_page.ggtt_offset;
1310
1311         for_each_engine(engine, dev_priv, id)
1312                 ads->eng_state_size[engine->guc_id] = intel_lr_context_size(engine);
1313
1314         /* GuC scheduling policies */
1315         policies = (void *)ads + sizeof(struct guc_ads);
1316         guc_policies_init(policies);
1317
1318         ads->scheduler_policies =
1319                 i915_ggtt_offset(vma) + sizeof(struct guc_ads);
1320
1321         /* MMIO reg state */
1322         reg_state = (void *)policies + sizeof(struct guc_policies);
1323
1324         for_each_engine(engine, dev_priv, id) {
1325                 reg_state->mmio_white_list[engine->guc_id].mmio_start =
1326                         engine->mmio_base + GUC_MMIO_WHITE_LIST_START;
1327
1328                 /* Nothing to be saved or restored for now. */
1329                 reg_state->mmio_white_list[engine->guc_id].count = 0;
1330         }
1331
1332         ads->reg_state_addr = ads->scheduler_policies +
1333                         sizeof(struct guc_policies);
1334
1335         ads->reg_state_buffer = ads->reg_state_addr +
1336                         sizeof(struct guc_mmio_reg_state);
1337
1338         kunmap(page);
1339 }
1340
1341 /*
1342  * Set up the memory resources to be shared with the GuC.  At this point,
1343  * we require just one object that can be mapped through the GGTT.
1344  */
1345 int i915_guc_submission_init(struct drm_i915_private *dev_priv)
1346 {
1347         const size_t ctxsize = sizeof(struct guc_context_desc);
1348         const size_t poolsize = GUC_MAX_GPU_CONTEXTS * ctxsize;
1349         const size_t gemsize = round_up(poolsize, PAGE_SIZE);
1350         struct intel_guc *guc = &dev_priv->guc;
1351         struct i915_vma *vma;
1352
1353         /* Wipe bitmap & delete client in case of reinitialisation */
1354         bitmap_clear(guc->doorbell_bitmap, 0, GUC_MAX_DOORBELLS);
1355         i915_guc_submission_disable(dev_priv);
1356
1357         if (!i915.enable_guc_submission)
1358                 return 0; /* not enabled  */
1359
1360         if (guc->ctx_pool_vma)
1361                 return 0; /* already allocated */
1362
1363         vma = guc_allocate_vma(guc, gemsize);
1364         if (IS_ERR(vma))
1365                 return PTR_ERR(vma);
1366
1367         guc->ctx_pool_vma = vma;
1368         ida_init(&guc->ctx_ids);
1369         guc_log_create(guc);
1370         guc_addon_create(guc);
1371
1372         return 0;
1373 }
1374
1375 int i915_guc_submission_enable(struct drm_i915_private *dev_priv)
1376 {
1377         struct intel_guc *guc = &dev_priv->guc;
1378         struct drm_i915_gem_request *request;
1379         struct i915_guc_client *client;
1380         struct intel_engine_cs *engine;
1381         enum intel_engine_id id;
1382
1383         /* client for execbuf submission */
1384         client = guc_client_alloc(dev_priv,
1385                                   INTEL_INFO(dev_priv)->ring_mask,
1386                                   GUC_CTX_PRIORITY_KMD_NORMAL,
1387                                   dev_priv->kernel_context);
1388         if (!client) {
1389                 DRM_ERROR("Failed to create normal GuC client!\n");
1390                 return -ENOMEM;
1391         }
1392
1393         guc->execbuf_client = client;
1394         host2guc_sample_forcewake(guc, client);
1395         guc_init_doorbell_hw(guc);
1396
1397         /* Take over from manual control of ELSP (execlists) */
1398         for_each_engine(engine, dev_priv, id) {
1399                 engine->submit_request = i915_guc_submit;
1400
1401                 /* Replay the current set of previously submitted requests */
1402                 list_for_each_entry(request, &engine->request_list, link) {
1403                         client->wq_rsvd += sizeof(struct guc_wq_item);
1404                         if (i915_sw_fence_done(&request->submit))
1405                                 i915_guc_submit(request);
1406                 }
1407         }
1408
1409         return 0;
1410 }
1411
1412 void i915_guc_submission_disable(struct drm_i915_private *dev_priv)
1413 {
1414         struct intel_guc *guc = &dev_priv->guc;
1415
1416         if (!guc->execbuf_client)
1417                 return;
1418
1419         /* Revert back to manual ELSP submission */
1420         intel_execlists_enable_submission(dev_priv);
1421
1422         guc_client_free(dev_priv, guc->execbuf_client);
1423         guc->execbuf_client = NULL;
1424 }
1425
1426 void i915_guc_submission_fini(struct drm_i915_private *dev_priv)
1427 {
1428         struct intel_guc *guc = &dev_priv->guc;
1429
1430         i915_vma_unpin_and_release(&guc->ads_vma);
1431         i915_vma_unpin_and_release(&guc->log.vma);
1432
1433         if (guc->ctx_pool_vma)
1434                 ida_destroy(&guc->ctx_ids);
1435         i915_vma_unpin_and_release(&guc->ctx_pool_vma);
1436 }
1437
1438 /**
1439  * intel_guc_suspend() - notify GuC entering suspend state
1440  * @dev:        drm device
1441  */
1442 int intel_guc_suspend(struct drm_device *dev)
1443 {
1444         struct drm_i915_private *dev_priv = to_i915(dev);
1445         struct intel_guc *guc = &dev_priv->guc;
1446         struct i915_gem_context *ctx;
1447         u32 data[3];
1448
1449         if (guc->guc_fw.guc_fw_load_status != GUC_FIRMWARE_SUCCESS)
1450                 return 0;
1451
1452         gen9_disable_guc_interrupts(dev_priv);
1453
1454         ctx = dev_priv->kernel_context;
1455
1456         data[0] = HOST2GUC_ACTION_ENTER_S_STATE;
1457         /* any value greater than GUC_POWER_D0 */
1458         data[1] = GUC_POWER_D1;
1459         /* first page is shared data with GuC */
1460         data[2] = i915_ggtt_offset(ctx->engine[RCS].state);
1461
1462         return host2guc_action(guc, data, ARRAY_SIZE(data));
1463 }
1464
1465
1466 /**
1467  * intel_guc_resume() - notify GuC resuming from suspend state
1468  * @dev:        drm device
1469  */
1470 int intel_guc_resume(struct drm_device *dev)
1471 {
1472         struct drm_i915_private *dev_priv = to_i915(dev);
1473         struct intel_guc *guc = &dev_priv->guc;
1474         struct i915_gem_context *ctx;
1475         u32 data[3];
1476
1477         if (guc->guc_fw.guc_fw_load_status != GUC_FIRMWARE_SUCCESS)
1478                 return 0;
1479
1480         if (i915.guc_log_level >= 0)
1481                 gen9_enable_guc_interrupts(dev_priv);
1482
1483         ctx = dev_priv->kernel_context;
1484
1485         data[0] = HOST2GUC_ACTION_EXIT_S_STATE;
1486         data[1] = GUC_POWER_D0;
1487         /* first page is shared data with GuC */
1488         data[2] = i915_ggtt_offset(ctx->engine[RCS].state);
1489
1490         return host2guc_action(guc, data, ARRAY_SIZE(data));
1491 }
1492
1493 void i915_guc_capture_logs(struct drm_i915_private *dev_priv)
1494 {
1495         guc_read_update_log_buffer(&dev_priv->guc);
1496
1497         /* Generally device is expected to be active only at this
1498          * time, so get/put should be really quick.
1499          */
1500         intel_runtime_pm_get(dev_priv);
1501         host2guc_logbuffer_flush_complete(&dev_priv->guc);
1502         intel_runtime_pm_put(dev_priv);
1503 }
1504
1505 void i915_guc_unregister(struct drm_i915_private *dev_priv)
1506 {
1507         if (!i915.enable_guc_submission)
1508                 return;
1509
1510         mutex_lock(&dev_priv->drm.struct_mutex);
1511         guc_log_cleanup(&dev_priv->guc);
1512         mutex_unlock(&dev_priv->drm.struct_mutex);
1513 }
1514
1515 void i915_guc_register(struct drm_i915_private *dev_priv)
1516 {
1517         if (!i915.enable_guc_submission)
1518                 return;
1519
1520         mutex_lock(&dev_priv->drm.struct_mutex);
1521         guc_log_late_setup(&dev_priv->guc);
1522         mutex_unlock(&dev_priv->drm.struct_mutex);
1523 }