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