drm/i915: build firmware handling code
[dragonfly.git] / sys / dev / 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 "i915_drv.h"
27 #include "intel_guc.h"
28
29 /**
30  * DOC: GuC Client
31  *
32  * i915_guc_client:
33  * We use the term client to avoid confusion with contexts. A i915_guc_client is
34  * equivalent to GuC object guc_context_desc. This context descriptor is
35  * allocated from a pool of 1024 entries. Kernel driver will allocate doorbell
36  * and workqueue for it. Also the process descriptor (guc_process_desc), which
37  * is mapped to client space. So the client can write Work Item then ring the
38  * doorbell.
39  *
40  * To simplify the implementation, we allocate one gem object that contains all
41  * pages for doorbell, process descriptor and workqueue.
42  *
43  * The Scratch registers:
44  * There are 16 MMIO-based registers start from 0xC180. The kernel driver writes
45  * a value to the action register (SOFT_SCRATCH_0) along with any data. It then
46  * triggers an interrupt on the GuC via another register write (0xC4C8).
47  * Firmware writes a success/fail code back to the action register after
48  * processes the request. The kernel driver polls waiting for this update and
49  * then proceeds.
50  * See host2guc_action()
51  *
52  * Doorbells:
53  * Doorbells are interrupts to uKernel. A doorbell is a single cache line (QW)
54  * mapped into process space.
55  *
56  * Work Items:
57  * There are several types of work items that the host may place into a
58  * workqueue, each with its own requirements and limitations. Currently only
59  * WQ_TYPE_INORDER is needed to support legacy submission via GuC, which
60  * represents in-order queue. The kernel driver packs ring tail pointer and an
61  * ELSP context descriptor dword into Work Item.
62  * See guc_add_workqueue_item()
63  *
64  */
65
66 /*
67  * Read GuC command/status register (SOFT_SCRATCH_0)
68  * Return true if it contains a response rather than a command
69  */
70 static inline bool host2guc_action_response(struct drm_i915_private *dev_priv,
71                                             u32 *status)
72 {
73         u32 val = I915_READ(SOFT_SCRATCH(0));
74         *status = val;
75         return GUC2HOST_IS_RESPONSE(val);
76 }
77
78 static int host2guc_action(struct intel_guc *guc, u32 *data, u32 len)
79 {
80         struct drm_i915_private *dev_priv = guc_to_i915(guc);
81         u32 status;
82         int i;
83         int ret;
84
85         if (WARN_ON(len < 1 || len > 15))
86                 return -EINVAL;
87
88         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
89         lockmgr(&dev_priv->guc.host2guc_lock, LK_EXCLUSIVE);
90
91         dev_priv->guc.action_count += 1;
92         dev_priv->guc.action_cmd = data[0];
93
94         for (i = 0; i < len; i++)
95                 I915_WRITE(SOFT_SCRATCH(i), data[i]);
96
97         POSTING_READ(SOFT_SCRATCH(i - 1));
98
99         I915_WRITE(HOST2GUC_INTERRUPT, HOST2GUC_TRIGGER);
100
101         /* No HOST2GUC command should take longer than 10ms */
102         ret = wait_for_atomic(host2guc_action_response(dev_priv, &status), 10);
103         if (status != GUC2HOST_STATUS_SUCCESS) {
104                 /*
105                  * Either the GuC explicitly returned an error (which
106                  * we convert to -EIO here) or no response at all was
107                  * received within the timeout limit (-ETIMEDOUT)
108                  */
109                 if (ret != -ETIMEDOUT)
110                         ret = -EIO;
111
112                 DRM_ERROR("GUC: host2guc action 0x%X failed. ret=%d "
113                                 "status=0x%08X response=0x%08X\n",
114                                 data[0], ret, status,
115                                 I915_READ(SOFT_SCRATCH(15)));
116
117                 dev_priv->guc.action_fail += 1;
118                 dev_priv->guc.action_err = ret;
119         }
120         dev_priv->guc.action_status = status;
121
122         lockmgr(&dev_priv->guc.host2guc_lock, LK_RELEASE);
123         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
124
125         return ret;
126 }
127
128 /*
129  * Tell the GuC to allocate or deallocate a specific doorbell
130  */
131
132 static int host2guc_allocate_doorbell(struct intel_guc *guc,
133                                       struct i915_guc_client *client)
134 {
135         u32 data[2];
136
137         data[0] = HOST2GUC_ACTION_ALLOCATE_DOORBELL;
138         data[1] = client->ctx_index;
139
140         return host2guc_action(guc, data, 2);
141 }
142
143 static int host2guc_release_doorbell(struct intel_guc *guc,
144                                      struct i915_guc_client *client)
145 {
146         u32 data[2];
147
148         data[0] = HOST2GUC_ACTION_DEALLOCATE_DOORBELL;
149         data[1] = client->ctx_index;
150
151         return host2guc_action(guc, data, 2);
152 }
153
154 static int host2guc_sample_forcewake(struct intel_guc *guc,
155                                      struct i915_guc_client *client)
156 {
157         struct drm_i915_private *dev_priv = guc_to_i915(guc);
158         struct drm_device *dev = dev_priv->dev;
159         u32 data[2];
160
161         data[0] = HOST2GUC_ACTION_SAMPLE_FORCEWAKE;
162         /* WaRsDisableCoarsePowerGating:skl,bxt */
163         if (!intel_enable_rc6(dev_priv->dev) ||
164             (IS_BROXTON(dev) && (INTEL_REVID(dev) < BXT_REVID_B0)) ||
165             (IS_SKL_GT3(dev) && (INTEL_REVID(dev) <= SKL_REVID_E0)) ||
166             (IS_SKL_GT4(dev) && (INTEL_REVID(dev) <= SKL_REVID_E0)))
167                 data[1] = 0;
168         else
169                 /* bit 0 and 1 are for Render and Media domain separately */
170                 data[1] = GUC_FORCEWAKE_RENDER | GUC_FORCEWAKE_MEDIA;
171
172         return host2guc_action(guc, data, ARRAY_SIZE(data));
173 }
174
175 /*
176  * Initialise, update, or clear doorbell data shared with the GuC
177  *
178  * These functions modify shared data and so need access to the mapped
179  * client object which contains the page being used for the doorbell
180  */
181
182 static void guc_init_doorbell(struct intel_guc *guc,
183                               struct i915_guc_client *client)
184 {
185         struct guc_doorbell_info *doorbell;
186         void *base;
187
188         base = kmap_atomic(i915_gem_object_get_page(client->client_obj, 0));
189         doorbell = (struct guc_doorbell_info *)((char *)base + client->doorbell_offset);
190
191         doorbell->db_status = 1;
192         doorbell->cookie = 0;
193
194         kunmap_atomic(base);
195 }
196
197 static int guc_ring_doorbell(struct i915_guc_client *gc)
198 {
199         struct guc_process_desc *desc;
200         union guc_doorbell_qw db_cmp, db_exc, db_ret;
201         union guc_doorbell_qw *db;
202         void *base;
203         int attempt = 2, ret = -EAGAIN;
204
205         base = kmap_atomic(i915_gem_object_get_page(gc->client_obj, 0));
206         desc = (struct guc_process_desc *)((char *)base + gc->proc_desc_offset);
207
208         /* Update the tail so it is visible to GuC */
209         desc->tail = gc->wq_tail;
210
211         /* current cookie */
212         db_cmp.db_status = GUC_DOORBELL_ENABLED;
213         db_cmp.cookie = gc->cookie;
214
215         /* cookie to be updated */
216         db_exc.db_status = GUC_DOORBELL_ENABLED;
217         db_exc.cookie = gc->cookie + 1;
218         if (db_exc.cookie == 0)
219                 db_exc.cookie = 1;
220
221         /* pointer of current doorbell cacheline */
222         db = (union guc_doorbell_qw *)((char *)base + gc->doorbell_offset);
223
224         while (attempt--) {
225                 /* lets ring the doorbell */
226                 db_ret.value_qw = atomic64_cmpxchg((atomic64_t *)db,
227                         db_cmp.value_qw, db_exc.value_qw);
228
229                 /* if the exchange was successfully executed */
230                 if (db_ret.value_qw == db_cmp.value_qw) {
231                         /* db was successfully rung */
232                         gc->cookie = db_exc.cookie;
233                         ret = 0;
234                         break;
235                 }
236
237                 /* XXX: doorbell was lost and need to acquire it again */
238                 if (db_ret.db_status == GUC_DOORBELL_DISABLED)
239                         break;
240
241                 DRM_ERROR("Cookie mismatch. Expected %d, returned %d\n",
242                           db_cmp.cookie, db_ret.cookie);
243
244                 /* update the cookie to newly read cookie from GuC */
245                 db_cmp.cookie = db_ret.cookie;
246                 db_exc.cookie = db_ret.cookie + 1;
247                 if (db_exc.cookie == 0)
248                         db_exc.cookie = 1;
249         }
250
251         kunmap_atomic(base);
252         return ret;
253 }
254
255 static void guc_disable_doorbell(struct intel_guc *guc,
256                                  struct i915_guc_client *client)
257 {
258         struct drm_i915_private *dev_priv = guc_to_i915(guc);
259         struct guc_doorbell_info *doorbell;
260         void *base;
261         int drbreg = GEN8_DRBREGL(client->doorbell_id);
262         int value;
263
264         base = kmap_atomic(i915_gem_object_get_page(client->client_obj, 0));
265         doorbell = (struct guc_doorbell_info*)((char *)base + client->doorbell_offset);
266
267         doorbell->db_status = 0;
268
269         kunmap_atomic(base);
270
271         I915_WRITE(drbreg, I915_READ(drbreg) & ~GEN8_DRB_VALID);
272
273         value = I915_READ(drbreg);
274         WARN_ON((value & GEN8_DRB_VALID) != 0);
275
276         I915_WRITE(GEN8_DRBREGU(client->doorbell_id), 0);
277         I915_WRITE(drbreg, 0);
278
279         /* XXX: wait for any interrupts */
280         /* XXX: wait for workqueue to drain */
281 }
282
283 /*
284  * Select, assign and relase doorbell cachelines
285  *
286  * These functions track which doorbell cachelines are in use.
287  * The data they manipulate is protected by the host2guc lock.
288  */
289
290 static uint32_t select_doorbell_cacheline(struct intel_guc *guc)
291 {
292         const uint32_t cacheline_size = cache_line_size();
293         uint32_t offset;
294
295         lockmgr(&guc->host2guc_lock, LK_EXCLUSIVE);
296
297         /* Doorbell uses a single cache line within a page */
298         offset = offset_in_page(guc->db_cacheline);
299
300         /* Moving to next cache line to reduce contention */
301         guc->db_cacheline += cacheline_size;
302
303         lockmgr(&guc->host2guc_lock, LK_RELEASE);
304
305         DRM_DEBUG_DRIVER("selected doorbell cacheline 0x%x, next 0x%x, linesize %u\n",
306                         offset, guc->db_cacheline, cacheline_size);
307
308         return offset;
309 }
310
311 static uint16_t assign_doorbell(struct intel_guc *guc, uint32_t priority)
312 {
313         /*
314          * The bitmap is split into two halves; the first half is used for
315          * normal priority contexts, the second half for high-priority ones.
316          * Note that logically higher priorities are numerically less than
317          * normal ones, so the test below means "is it high-priority?"
318          */
319         const bool hi_pri = (priority <= GUC_CTX_PRIORITY_HIGH);
320         const uint16_t half = GUC_MAX_DOORBELLS / 2;
321         const uint16_t start = hi_pri ? half : 0;
322         const uint16_t end = start + half;
323         uint16_t id;
324
325         lockmgr(&guc->host2guc_lock, LK_EXCLUSIVE);
326         id = find_next_zero_bit(guc->doorbell_bitmap, end, start);
327         if (id == end)
328                 id = GUC_INVALID_DOORBELL_ID;
329         else
330                 bitmap_set(guc->doorbell_bitmap, id, 1);
331         lockmgr(&guc->host2guc_lock, LK_RELEASE);
332
333         DRM_DEBUG_DRIVER("assigned %s priority doorbell id 0x%x\n",
334                         hi_pri ? "high" : "normal", id);
335
336         return id;
337 }
338
339 static void release_doorbell(struct intel_guc *guc, uint16_t id)
340 {
341         lockmgr(&guc->host2guc_lock, LK_EXCLUSIVE);
342         bitmap_clear(guc->doorbell_bitmap, id, 1);
343         lockmgr(&guc->host2guc_lock, LK_RELEASE);
344 }
345
346 /*
347  * Initialise the process descriptor shared with the GuC firmware.
348  */
349 static void guc_init_proc_desc(struct intel_guc *guc,
350                                struct i915_guc_client *client)
351 {
352         struct guc_process_desc *desc;
353         void *base;
354
355         base = kmap_atomic(i915_gem_object_get_page(client->client_obj, 0));
356         desc = (struct guc_process_desc *)((char *)base + client->proc_desc_offset);
357
358         memset(desc, 0, sizeof(*desc));
359
360         /*
361          * XXX: pDoorbell and WQVBaseAddress are pointers in process address
362          * space for ring3 clients (set them as in mmap_ioctl) or kernel
363          * space for kernel clients (map on demand instead? May make debug
364          * easier to have it mapped).
365          */
366         desc->wq_base_addr = 0;
367         desc->db_base_addr = 0;
368
369         desc->context_id = client->ctx_index;
370         desc->wq_size_bytes = client->wq_size;
371         desc->wq_status = WQ_STATUS_ACTIVE;
372         desc->priority = client->priority;
373
374         kunmap_atomic(base);
375 }
376
377 /*
378  * Initialise/clear the context descriptor shared with the GuC firmware.
379  *
380  * This descriptor tells the GuC where (in GGTT space) to find the important
381  * data structures relating to this client (doorbell, process descriptor,
382  * write queue, etc).
383  */
384
385 static void guc_init_ctx_desc(struct intel_guc *guc,
386                               struct i915_guc_client *client)
387 {
388         struct intel_context *ctx = client->owner;
389         struct guc_context_desc desc;
390         struct sg_table *sg;
391         int i;
392
393         memset(&desc, 0, sizeof(desc));
394
395         desc.attribute = GUC_CTX_DESC_ATTR_ACTIVE | GUC_CTX_DESC_ATTR_KERNEL;
396         desc.context_id = client->ctx_index;
397         desc.priority = client->priority;
398         desc.db_id = client->doorbell_id;
399
400         for (i = 0; i < I915_NUM_RINGS; i++) {
401                 struct guc_execlist_context *lrc = &desc.lrc[i];
402                 struct intel_ringbuffer *ringbuf = ctx->engine[i].ringbuf;
403                 struct intel_engine_cs *ring;
404                 struct drm_i915_gem_object *obj;
405                 uint64_t ctx_desc;
406
407                 /* TODO: We have a design issue to be solved here. Only when we
408                  * receive the first batch, we know which engine is used by the
409                  * user. But here GuC expects the lrc and ring to be pinned. It
410                  * is not an issue for default context, which is the only one
411                  * for now who owns a GuC client. But for future owner of GuC
412                  * client, need to make sure lrc is pinned prior to enter here.
413                  */
414                 obj = ctx->engine[i].state;
415                 if (!obj)
416                         break;  /* XXX: continue? */
417
418                 ring = ringbuf->ring;
419                 ctx_desc = intel_lr_context_descriptor(ctx, ring);
420                 lrc->context_desc = (u32)ctx_desc;
421
422                 /* The state page is after PPHWSP */
423                 lrc->ring_lcra = i915_gem_obj_ggtt_offset(obj) +
424                                 LRC_STATE_PN * PAGE_SIZE;
425                 lrc->context_id = (client->ctx_index << GUC_ELC_CTXID_OFFSET) |
426                                 (ring->id << GUC_ELC_ENGINE_OFFSET);
427
428                 obj = ringbuf->obj;
429
430                 lrc->ring_begin = i915_gem_obj_ggtt_offset(obj);
431                 lrc->ring_end = lrc->ring_begin + obj->base.size - 1;
432                 lrc->ring_next_free_location = lrc->ring_begin;
433                 lrc->ring_current_tail_pointer_value = 0;
434
435                 desc.engines_used |= (1 << ring->id);
436         }
437
438         WARN_ON(desc.engines_used == 0);
439
440         /*
441          * The CPU address is only needed at certain points, so kmap_atomic on
442          * demand instead of storing it in the ctx descriptor.
443          * XXX: May make debug easier to have it mapped
444          */
445         desc.db_trigger_cpu = 0;
446         desc.db_trigger_uk = client->doorbell_offset +
447                 i915_gem_obj_ggtt_offset(client->client_obj);
448         desc.db_trigger_phy = client->doorbell_offset +
449                 sg_dma_address(client->client_obj->pages->sgl);
450
451         desc.process_desc = client->proc_desc_offset +
452                 i915_gem_obj_ggtt_offset(client->client_obj);
453
454         desc.wq_addr = client->wq_offset +
455                 i915_gem_obj_ggtt_offset(client->client_obj);
456
457         desc.wq_size = client->wq_size;
458
459         /*
460          * XXX: Take LRCs from an existing intel_context if this is not an
461          * IsKMDCreatedContext client
462          */
463         desc.desc_private = (uintptr_t)client;
464
465         /* Pool context is pinned already */
466         sg = guc->ctx_pool_obj->pages;
467         sg_pcopy_from_buffer(sg->sgl, sg->nents, &desc, sizeof(desc),
468                              sizeof(desc) * client->ctx_index);
469 }
470
471 static void guc_fini_ctx_desc(struct intel_guc *guc,
472                               struct i915_guc_client *client)
473 {
474         struct guc_context_desc desc;
475         struct sg_table *sg;
476
477         memset(&desc, 0, sizeof(desc));
478
479         sg = guc->ctx_pool_obj->pages;
480         sg_pcopy_from_buffer(sg->sgl, sg->nents, &desc, sizeof(desc),
481                              sizeof(desc) * client->ctx_index);
482 }
483
484 /* Get valid workqueue item and return it back to offset */
485 static int guc_get_workqueue_space(struct i915_guc_client *gc, u32 *offset)
486 {
487         struct guc_process_desc *desc;
488         void *base;
489         u32 size = sizeof(struct guc_wq_item);
490         int ret = 0, timeout_counter = 200;
491
492         base = kmap_atomic(i915_gem_object_get_page(gc->client_obj, 0));
493         desc = (struct guc_process_desc *)((char *)base + gc->proc_desc_offset);
494
495         while (timeout_counter-- > 0) {
496                 ret = wait_for_atomic(CIRC_SPACE(gc->wq_tail, desc->head,
497                                 gc->wq_size) >= size, 1);
498
499                 if (!ret) {
500                         *offset = gc->wq_tail;
501
502                         /* advance the tail for next workqueue item */
503                         gc->wq_tail += size;
504                         gc->wq_tail &= gc->wq_size - 1;
505
506                         /* this will break the loop */
507                         timeout_counter = 0;
508                 }
509         };
510
511         kunmap_atomic(base);
512
513         return ret;
514 }
515
516 static int guc_add_workqueue_item(struct i915_guc_client *gc,
517                                   struct drm_i915_gem_request *rq)
518 {
519         enum intel_ring_id ring_id = rq->ring->id;
520         struct guc_wq_item *wqi;
521         void *base;
522         u32 tail, wq_len, wq_off = 0;
523         int ret;
524
525         ret = guc_get_workqueue_space(gc, &wq_off);
526         if (ret)
527                 return ret;
528
529         /* For now workqueue item is 4 DWs; workqueue buffer is 2 pages. So we
530          * should not have the case where structure wqi is across page, neither
531          * wrapped to the beginning. This simplifies the implementation below.
532          *
533          * XXX: if not the case, we need save data to a temp wqi and copy it to
534          * workqueue buffer dw by dw.
535          */
536         WARN_ON(sizeof(struct guc_wq_item) != 16);
537         WARN_ON(wq_off & 3);
538
539         /* wq starts from the page after doorbell / process_desc */
540         base = kmap_atomic(i915_gem_object_get_page(gc->client_obj,
541                         (wq_off + GUC_DB_SIZE) >> PAGE_SHIFT));
542         wq_off &= PAGE_SIZE - 1;
543         wqi = (struct guc_wq_item *)((char *)base + wq_off);
544
545         /* len does not include the header */
546         wq_len = sizeof(struct guc_wq_item) / sizeof(u32) - 1;
547         wqi->header = WQ_TYPE_INORDER |
548                         (wq_len << WQ_LEN_SHIFT) |
549                         (ring_id << WQ_TARGET_SHIFT) |
550                         WQ_NO_WCFLUSH_WAIT;
551
552         /* The GuC wants only the low-order word of the context descriptor */
553         wqi->context_desc = (u32)intel_lr_context_descriptor(rq->ctx, rq->ring);
554
555         /* The GuC firmware wants the tail index in QWords, not bytes */
556         tail = rq->ringbuf->tail >> 3;
557         wqi->ring_tail = tail << WQ_RING_TAIL_SHIFT;
558         wqi->fence_id = 0; /*XXX: what fence to be here */
559
560         kunmap_atomic(base);
561
562         return 0;
563 }
564
565 #define CTX_RING_BUFFER_START           0x08
566
567 /* Update the ringbuffer pointer in a saved context image */
568 static void lr_context_update(struct drm_i915_gem_request *rq)
569 {
570         enum intel_ring_id ring_id = rq->ring->id;
571         struct drm_i915_gem_object *ctx_obj = rq->ctx->engine[ring_id].state;
572         struct drm_i915_gem_object *rb_obj = rq->ringbuf->obj;
573         struct vm_page *page;
574         uint32_t *reg_state;
575
576         BUG_ON(!ctx_obj);
577         WARN_ON(!i915_gem_obj_is_pinned(ctx_obj));
578         WARN_ON(!i915_gem_obj_is_pinned(rb_obj));
579
580         page = i915_gem_object_get_page(ctx_obj, LRC_STATE_PN);
581         reg_state = kmap_atomic(page);
582
583         reg_state[CTX_RING_BUFFER_START+1] = i915_gem_obj_ggtt_offset(rb_obj);
584
585         kunmap_atomic(reg_state);
586 }
587
588 /**
589  * i915_guc_submit() - Submit commands through GuC
590  * @client:     the guc client where commands will go through
591  * @ctx:        LRC where commands come from
592  * @ring:       HW engine that will excute the commands
593  *
594  * Return:      0 if succeed
595  */
596 int i915_guc_submit(struct i915_guc_client *client,
597                     struct drm_i915_gem_request *rq)
598 {
599         struct intel_guc *guc = client->guc;
600         enum intel_ring_id ring_id = rq->ring->id;
601         unsigned long flags;
602         int q_ret, b_ret;
603
604         /* Need this because of the deferred pin ctx and ring */
605         /* Shall we move this right after ring is pinned? */
606         lr_context_update(rq);
607
608         spin_lock_irqsave(&client->wq_lock, flags);
609
610         q_ret = guc_add_workqueue_item(client, rq);
611         if (q_ret == 0)
612                 b_ret = guc_ring_doorbell(client);
613
614         client->submissions[ring_id] += 1;
615         if (q_ret) {
616                 client->q_fail += 1;
617                 client->retcode = q_ret;
618         } else if (b_ret) {
619                 client->b_fail += 1;
620                 client->retcode = q_ret = b_ret;
621         } else {
622                 client->retcode = 0;
623         }
624         spin_unlock_irqrestore(&client->wq_lock, flags);
625
626         lockmgr(&guc->host2guc_lock, LK_EXCLUSIVE);
627         guc->submissions[ring_id] += 1;
628         guc->last_seqno[ring_id] = rq->seqno;
629         lockmgr(&guc->host2guc_lock, LK_RELEASE);
630
631         return q_ret;
632 }
633
634 /*
635  * Everything below here is concerned with setup & teardown, and is
636  * therefore not part of the somewhat time-critical batch-submission
637  * path of i915_guc_submit() above.
638  */
639
640 /**
641  * gem_allocate_guc_obj() - Allocate gem object for GuC usage
642  * @dev:        drm device
643  * @size:       size of object
644  *
645  * This is a wrapper to create a gem obj. In order to use it inside GuC, the
646  * object needs to be pinned lifetime. Also we must pin it to gtt space other
647  * than [0, GUC_WOPCM_TOP) because this range is reserved inside GuC.
648  *
649  * Return:      A drm_i915_gem_object if successful, otherwise NULL.
650  */
651 static struct drm_i915_gem_object *gem_allocate_guc_obj(struct drm_device *dev,
652                                                         u32 size)
653 {
654         struct drm_i915_private *dev_priv = dev->dev_private;
655         struct drm_i915_gem_object *obj;
656
657         obj = i915_gem_alloc_object(dev, size);
658         if (!obj)
659                 return NULL;
660
661         if (i915_gem_object_get_pages(obj)) {
662                 drm_gem_object_unreference(&obj->base);
663                 return NULL;
664         }
665
666         if (i915_gem_obj_ggtt_pin(obj, PAGE_SIZE,
667                         PIN_OFFSET_BIAS | GUC_WOPCM_TOP)) {
668                 drm_gem_object_unreference(&obj->base);
669                 return NULL;
670         }
671
672         /* Invalidate GuC TLB to let GuC take the latest updates to GTT. */
673         I915_WRITE(GEN8_GTCR, GEN8_GTCR_INVALIDATE);
674
675         return obj;
676 }
677
678 /**
679  * gem_release_guc_obj() - Release gem object allocated for GuC usage
680  * @obj:        gem obj to be released
681   */
682 static void gem_release_guc_obj(struct drm_i915_gem_object *obj)
683 {
684         if (!obj)
685                 return;
686
687         if (i915_gem_obj_is_pinned(obj))
688                 i915_gem_object_ggtt_unpin(obj);
689
690         drm_gem_object_unreference(&obj->base);
691 }
692
693 static void guc_client_free(struct drm_device *dev,
694                             struct i915_guc_client *client)
695 {
696         struct drm_i915_private *dev_priv = dev->dev_private;
697         struct intel_guc *guc = &dev_priv->guc;
698
699         if (!client)
700                 return;
701
702         if (client->doorbell_id != GUC_INVALID_DOORBELL_ID) {
703                 /*
704                  * First disable the doorbell, then tell the GuC we've
705                  * finished with it, finally deallocate it in our bitmap
706                  */
707                 guc_disable_doorbell(guc, client);
708                 host2guc_release_doorbell(guc, client);
709                 release_doorbell(guc, client->doorbell_id);
710         }
711
712         /*
713          * XXX: wait for any outstanding submissions before freeing memory.
714          * Be sure to drop any locks
715          */
716
717         gem_release_guc_obj(client->client_obj);
718
719         if (client->ctx_index != GUC_INVALID_CTX_ID) {
720                 guc_fini_ctx_desc(guc, client);
721                 ida_simple_remove(&guc->ctx_ids, client->ctx_index);
722         }
723
724         kfree(client);
725 }
726
727 /**
728  * guc_client_alloc() - Allocate an i915_guc_client
729  * @dev:        drm device
730  * @priority:   four levels priority _CRITICAL, _HIGH, _NORMAL and _LOW
731  *              The kernel client to replace ExecList submission is created with
732  *              NORMAL priority. Priority of a client for scheduler can be HIGH,
733  *              while a preemption context can use CRITICAL.
734  * @ctx         the context to own the client (we use the default render context)
735  *
736  * Return:      An i915_guc_client object if success.
737  */
738 static struct i915_guc_client *guc_client_alloc(struct drm_device *dev,
739                                                 uint32_t priority,
740                                                 struct intel_context *ctx)
741 {
742         struct i915_guc_client *client;
743         struct drm_i915_private *dev_priv = dev->dev_private;
744         struct intel_guc *guc = &dev_priv->guc;
745         struct drm_i915_gem_object *obj;
746
747         client = kzalloc(sizeof(*client), GFP_KERNEL);
748         if (!client)
749                 return NULL;
750
751         client->doorbell_id = GUC_INVALID_DOORBELL_ID;
752         client->priority = priority;
753         client->owner = ctx;
754         client->guc = guc;
755
756         client->ctx_index = (uint32_t)ida_simple_get(&guc->ctx_ids, 0,
757                         GUC_MAX_GPU_CONTEXTS, GFP_KERNEL);
758         if (client->ctx_index >= GUC_MAX_GPU_CONTEXTS) {
759                 client->ctx_index = GUC_INVALID_CTX_ID;
760                 goto err;
761         }
762
763         /* The first page is doorbell/proc_desc. Two followed pages are wq. */
764         obj = gem_allocate_guc_obj(dev, GUC_DB_SIZE + GUC_WQ_SIZE);
765         if (!obj)
766                 goto err;
767
768         client->client_obj = obj;
769         client->wq_offset = GUC_DB_SIZE;
770         client->wq_size = GUC_WQ_SIZE;
771         lockinit(&client->wq_lock, "i915cwql", 0, LK_CANRECURSE);
772
773         client->doorbell_offset = select_doorbell_cacheline(guc);
774
775         /*
776          * Since the doorbell only requires a single cacheline, we can save
777          * space by putting the application process descriptor in the same
778          * page. Use the half of the page that doesn't include the doorbell.
779          */
780         if (client->doorbell_offset >= (GUC_DB_SIZE / 2))
781                 client->proc_desc_offset = 0;
782         else
783                 client->proc_desc_offset = (GUC_DB_SIZE / 2);
784
785         client->doorbell_id = assign_doorbell(guc, client->priority);
786         if (client->doorbell_id == GUC_INVALID_DOORBELL_ID)
787                 /* XXX: evict a doorbell instead */
788                 goto err;
789
790         guc_init_proc_desc(guc, client);
791         guc_init_ctx_desc(guc, client);
792         guc_init_doorbell(guc, client);
793
794         /* XXX: Any cache flushes needed? General domain mgmt calls? */
795
796         if (host2guc_allocate_doorbell(guc, client))
797                 goto err;
798
799         DRM_DEBUG_DRIVER("new priority %u client %p: ctx_index %u db_id %u\n",
800                 priority, client, client->ctx_index, client->doorbell_id);
801
802         return client;
803
804 err:
805         DRM_ERROR("FAILED to create priority %u GuC client!\n", priority);
806
807         guc_client_free(dev, client);
808         return NULL;
809 }
810
811 static void guc_create_log(struct intel_guc *guc)
812 {
813         struct drm_i915_private *dev_priv = guc_to_i915(guc);
814         struct drm_i915_gem_object *obj;
815         unsigned long offset;
816         uint32_t size, flags;
817
818         if (i915.guc_log_level < GUC_LOG_VERBOSITY_MIN)
819                 return;
820
821         if (i915.guc_log_level > GUC_LOG_VERBOSITY_MAX)
822                 i915.guc_log_level = GUC_LOG_VERBOSITY_MAX;
823
824         /* The first page is to save log buffer state. Allocate one
825          * extra page for others in case for overlap */
826         size = (1 + GUC_LOG_DPC_PAGES + 1 +
827                 GUC_LOG_ISR_PAGES + 1 +
828                 GUC_LOG_CRASH_PAGES + 1) << PAGE_SHIFT;
829
830         obj = guc->log_obj;
831         if (!obj) {
832                 obj = gem_allocate_guc_obj(dev_priv->dev, size);
833                 if (!obj) {
834                         /* logging will be off */
835                         i915.guc_log_level = -1;
836                         return;
837                 }
838
839                 guc->log_obj = obj;
840         }
841
842         /* each allocated unit is a page */
843         flags = GUC_LOG_VALID | GUC_LOG_NOTIFY_ON_HALF_FULL |
844                 (GUC_LOG_DPC_PAGES << GUC_LOG_DPC_SHIFT) |
845                 (GUC_LOG_ISR_PAGES << GUC_LOG_ISR_SHIFT) |
846                 (GUC_LOG_CRASH_PAGES << GUC_LOG_CRASH_SHIFT);
847
848         offset = i915_gem_obj_ggtt_offset(obj) >> PAGE_SHIFT; /* in pages */
849         guc->log_flags = (offset << GUC_LOG_BUF_ADDR_SHIFT) | flags;
850 }
851
852 /*
853  * Set up the memory resources to be shared with the GuC.  At this point,
854  * we require just one object that can be mapped through the GGTT.
855  */
856 int i915_guc_submission_init(struct drm_device *dev)
857 {
858         struct drm_i915_private *dev_priv = dev->dev_private;
859         const size_t ctxsize = sizeof(struct guc_context_desc);
860         const size_t poolsize = GUC_MAX_GPU_CONTEXTS * ctxsize;
861         const size_t gemsize = round_up(poolsize, PAGE_SIZE);
862         struct intel_guc *guc = &dev_priv->guc;
863
864         if (!i915.enable_guc_submission)
865                 return 0; /* not enabled  */
866
867         if (guc->ctx_pool_obj)
868                 return 0; /* already allocated */
869
870         guc->ctx_pool_obj = gem_allocate_guc_obj(dev_priv->dev, gemsize);
871         if (!guc->ctx_pool_obj)
872                 return -ENOMEM;
873
874         lockinit(&dev_priv->guc.host2guc_lock, "i915gh2g", 0, LK_CANRECURSE);
875
876         ida_init(&guc->ctx_ids);
877
878         guc_create_log(guc);
879
880         return 0;
881 }
882
883 int i915_guc_submission_enable(struct drm_device *dev)
884 {
885         struct drm_i915_private *dev_priv = dev->dev_private;
886         struct intel_guc *guc = &dev_priv->guc;
887         struct intel_context *ctx = dev_priv->ring[RCS].default_context;
888         struct i915_guc_client *client;
889
890         /* client for execbuf submission */
891         client = guc_client_alloc(dev, GUC_CTX_PRIORITY_KMD_NORMAL, ctx);
892         if (!client) {
893                 DRM_ERROR("Failed to create execbuf guc_client\n");
894                 return -ENOMEM;
895         }
896
897         guc->execbuf_client = client;
898
899         host2guc_sample_forcewake(guc, client);
900
901         return 0;
902 }
903
904 void i915_guc_submission_disable(struct drm_device *dev)
905 {
906         struct drm_i915_private *dev_priv = dev->dev_private;
907         struct intel_guc *guc = &dev_priv->guc;
908
909         guc_client_free(dev, guc->execbuf_client);
910         guc->execbuf_client = NULL;
911 }
912
913 void i915_guc_submission_fini(struct drm_device *dev)
914 {
915         struct drm_i915_private *dev_priv = dev->dev_private;
916         struct intel_guc *guc = &dev_priv->guc;
917
918         gem_release_guc_obj(dev_priv->guc.log_obj);
919         guc->log_obj = NULL;
920
921         if (guc->ctx_pool_obj)
922                 ida_destroy(&guc->ctx_ids);
923         gem_release_guc_obj(guc->ctx_pool_obj);
924         guc->ctx_pool_obj = NULL;
925 }
926
927 /**
928  * intel_guc_suspend() - notify GuC entering suspend state
929  * @dev:        drm device
930  */
931 int intel_guc_suspend(struct drm_device *dev)
932 {
933         struct drm_i915_private *dev_priv = dev->dev_private;
934         struct intel_guc *guc = &dev_priv->guc;
935         struct intel_context *ctx;
936         u32 data[3];
937
938         if (!i915.enable_guc_submission)
939                 return 0;
940
941         ctx = dev_priv->ring[RCS].default_context;
942
943         data[0] = HOST2GUC_ACTION_ENTER_S_STATE;
944         /* any value greater than GUC_POWER_D0 */
945         data[1] = GUC_POWER_D1;
946         /* first page is shared data with GuC */
947         data[2] = i915_gem_obj_ggtt_offset(ctx->engine[RCS].state);
948
949         return host2guc_action(guc, data, ARRAY_SIZE(data));
950         return -EIO;
951 }
952
953
954 /**
955  * intel_guc_resume() - notify GuC resuming from suspend state
956  * @dev:        drm device
957  */
958 int intel_guc_resume(struct drm_device *dev)
959 {
960         struct drm_i915_private *dev_priv = dev->dev_private;
961         struct intel_guc *guc = &dev_priv->guc;
962         struct intel_context *ctx;
963         u32 data[3];
964
965         if (!i915.enable_guc_submission)
966                 return 0;
967
968         ctx = dev_priv->ring[RCS].default_context;
969
970         data[0] = HOST2GUC_ACTION_EXIT_S_STATE;
971         data[1] = GUC_POWER_D0;
972         /* first page is shared data with GuC */
973         data[2] = i915_gem_obj_ggtt_offset(ctx->engine[RCS].state);
974
975         return host2guc_action(guc, data, ARRAY_SIZE(data));
976         return -EIO;
977 }