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