GNU Linux-libre 4.19.286-gnu1
[releases.git] / drivers / gpu / drm / i915 / i915_gem_context.c
1 /*
2  * Copyright © 2011-2012 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  * Authors:
24  *    Ben Widawsky <ben@bwidawsk.net>
25  *
26  */
27
28 /*
29  * This file implements HW context support. On gen5+ a HW context consists of an
30  * opaque GPU object which is referenced at times of context saves and restores.
31  * With RC6 enabled, the context is also referenced as the GPU enters and exists
32  * from RC6 (GPU has it's own internal power context, except on gen5). Though
33  * something like a context does exist for the media ring, the code only
34  * supports contexts for the render ring.
35  *
36  * In software, there is a distinction between contexts created by the user,
37  * and the default HW context. The default HW context is used by GPU clients
38  * that do not request setup of their own hardware context. The default
39  * context's state is never restored to help prevent programming errors. This
40  * would happen if a client ran and piggy-backed off another clients GPU state.
41  * The default context only exists to give the GPU some offset to load as the
42  * current to invoke a save of the context we actually care about. In fact, the
43  * code could likely be constructed, albeit in a more complicated fashion, to
44  * never use the default context, though that limits the driver's ability to
45  * swap out, and/or destroy other contexts.
46  *
47  * All other contexts are created as a request by the GPU client. These contexts
48  * store GPU state, and thus allow GPU clients to not re-emit state (and
49  * potentially query certain state) at any time. The kernel driver makes
50  * certain that the appropriate commands are inserted.
51  *
52  * The context life cycle is semi-complicated in that context BOs may live
53  * longer than the context itself because of the way the hardware, and object
54  * tracking works. Below is a very crude representation of the state machine
55  * describing the context life.
56  *                                         refcount     pincount     active
57  * S0: initial state                          0            0           0
58  * S1: context created                        1            0           0
59  * S2: context is currently running           2            1           X
60  * S3: GPU referenced, but not current        2            0           1
61  * S4: context is current, but destroyed      1            1           0
62  * S5: like S3, but destroyed                 1            0           1
63  *
64  * The most common (but not all) transitions:
65  * S0->S1: client creates a context
66  * S1->S2: client submits execbuf with context
67  * S2->S3: other clients submits execbuf with context
68  * S3->S1: context object was retired
69  * S3->S2: clients submits another execbuf
70  * S2->S4: context destroy called with current context
71  * S3->S5->S0: destroy path
72  * S4->S5->S0: destroy path on current context
73  *
74  * There are two confusing terms used above:
75  *  The "current context" means the context which is currently running on the
76  *  GPU. The GPU has loaded its state already and has stored away the gtt
77  *  offset of the BO. The GPU is not actively referencing the data at this
78  *  offset, but it will on the next context switch. The only way to avoid this
79  *  is to do a GPU reset.
80  *
81  *  An "active context' is one which was previously the "current context" and is
82  *  on the active list waiting for the next context switch to occur. Until this
83  *  happens, the object must remain at the same gtt offset. It is therefore
84  *  possible to destroy a context, but it is still active.
85  *
86  */
87
88 #include <linux/log2.h>
89 #include <drm/drmP.h>
90 #include <drm/i915_drm.h>
91 #include "i915_drv.h"
92 #include "i915_trace.h"
93 #include "intel_workarounds.h"
94
95 #define ALL_L3_SLICES(dev) (1 << NUM_L3_SLICES(dev)) - 1
96
97 static void lut_close(struct i915_gem_context *ctx)
98 {
99         struct i915_lut_handle *lut, *ln;
100         struct radix_tree_iter iter;
101         void __rcu **slot;
102
103         list_for_each_entry_safe(lut, ln, &ctx->handles_list, ctx_link) {
104                 list_del(&lut->obj_link);
105                 kmem_cache_free(ctx->i915->luts, lut);
106         }
107
108         rcu_read_lock();
109         radix_tree_for_each_slot(slot, &ctx->handles_vma, &iter, 0) {
110                 struct i915_vma *vma = rcu_dereference_raw(*slot);
111
112                 radix_tree_iter_delete(&ctx->handles_vma, &iter, slot);
113                 __i915_gem_object_release_unless_active(vma->obj);
114         }
115         rcu_read_unlock();
116 }
117
118 static void i915_gem_context_free(struct i915_gem_context *ctx)
119 {
120         unsigned int n;
121
122         lockdep_assert_held(&ctx->i915->drm.struct_mutex);
123         GEM_BUG_ON(!i915_gem_context_is_closed(ctx));
124
125         i915_ppgtt_put(ctx->ppgtt);
126
127         kfree(ctx->jump_whitelist);
128
129         for (n = 0; n < ARRAY_SIZE(ctx->__engine); n++) {
130                 struct intel_context *ce = &ctx->__engine[n];
131
132                 if (ce->ops)
133                         ce->ops->destroy(ce);
134         }
135
136         kfree(ctx->name);
137         put_pid(ctx->pid);
138
139         list_del(&ctx->link);
140
141         ida_simple_remove(&ctx->i915->contexts.hw_ida, ctx->hw_id);
142         kfree_rcu(ctx, rcu);
143 }
144
145 static void contexts_free(struct drm_i915_private *i915)
146 {
147         struct llist_node *freed = llist_del_all(&i915->contexts.free_list);
148         struct i915_gem_context *ctx, *cn;
149
150         lockdep_assert_held(&i915->drm.struct_mutex);
151
152         llist_for_each_entry_safe(ctx, cn, freed, free_link)
153                 i915_gem_context_free(ctx);
154 }
155
156 static void contexts_free_first(struct drm_i915_private *i915)
157 {
158         struct i915_gem_context *ctx;
159         struct llist_node *freed;
160
161         lockdep_assert_held(&i915->drm.struct_mutex);
162
163         freed = llist_del_first(&i915->contexts.free_list);
164         if (!freed)
165                 return;
166
167         ctx = container_of(freed, typeof(*ctx), free_link);
168         i915_gem_context_free(ctx);
169 }
170
171 static void contexts_free_worker(struct work_struct *work)
172 {
173         struct drm_i915_private *i915 =
174                 container_of(work, typeof(*i915), contexts.free_work);
175
176         mutex_lock(&i915->drm.struct_mutex);
177         contexts_free(i915);
178         mutex_unlock(&i915->drm.struct_mutex);
179 }
180
181 void i915_gem_context_release(struct kref *ref)
182 {
183         struct i915_gem_context *ctx = container_of(ref, typeof(*ctx), ref);
184         struct drm_i915_private *i915 = ctx->i915;
185
186         trace_i915_context_free(ctx);
187         if (llist_add(&ctx->free_link, &i915->contexts.free_list))
188                 queue_work(i915->wq, &i915->contexts.free_work);
189 }
190
191 static void context_close(struct i915_gem_context *ctx)
192 {
193         i915_gem_context_set_closed(ctx);
194
195         /*
196          * The LUT uses the VMA as a backpointer to unref the object,
197          * so we need to clear the LUT before we close all the VMA (inside
198          * the ppgtt).
199          */
200         lut_close(ctx);
201         if (ctx->ppgtt)
202                 i915_ppgtt_close(&ctx->ppgtt->vm);
203
204         ctx->file_priv = ERR_PTR(-EBADF);
205         i915_gem_context_put(ctx);
206 }
207
208 static int assign_hw_id(struct drm_i915_private *dev_priv, unsigned *out)
209 {
210         int ret;
211         unsigned int max;
212
213         if (INTEL_GEN(dev_priv) >= 11) {
214                 max = GEN11_MAX_CONTEXT_HW_ID;
215         } else {
216                 /*
217                  * When using GuC in proxy submission, GuC consumes the
218                  * highest bit in the context id to indicate proxy submission.
219                  */
220                 if (USES_GUC_SUBMISSION(dev_priv))
221                         max = MAX_GUC_CONTEXT_HW_ID;
222                 else
223                         max = MAX_CONTEXT_HW_ID;
224         }
225
226
227         ret = ida_simple_get(&dev_priv->contexts.hw_ida,
228                              0, max, GFP_KERNEL);
229         if (ret < 0) {
230                 /* Contexts are only released when no longer active.
231                  * Flush any pending retires to hopefully release some
232                  * stale contexts and try again.
233                  */
234                 i915_retire_requests(dev_priv);
235                 ret = ida_simple_get(&dev_priv->contexts.hw_ida,
236                                      0, max, GFP_KERNEL);
237                 if (ret < 0)
238                         return ret;
239         }
240
241         *out = ret;
242         return 0;
243 }
244
245 static u32 default_desc_template(const struct drm_i915_private *i915,
246                                  const struct i915_hw_ppgtt *ppgtt)
247 {
248         u32 address_mode;
249         u32 desc;
250
251         desc = GEN8_CTX_VALID | GEN8_CTX_PRIVILEGE;
252
253         address_mode = INTEL_LEGACY_32B_CONTEXT;
254         if (ppgtt && i915_vm_is_48bit(&ppgtt->vm))
255                 address_mode = INTEL_LEGACY_64B_CONTEXT;
256         desc |= address_mode << GEN8_CTX_ADDRESSING_MODE_SHIFT;
257
258         if (IS_GEN8(i915))
259                 desc |= GEN8_CTX_L3LLC_COHERENT;
260
261         /* TODO: WaDisableLiteRestore when we start using semaphore
262          * signalling between Command Streamers
263          * ring->ctx_desc_template |= GEN8_CTX_FORCE_RESTORE;
264          */
265
266         return desc;
267 }
268
269 static struct i915_gem_context *
270 __create_hw_context(struct drm_i915_private *dev_priv,
271                     struct drm_i915_file_private *file_priv)
272 {
273         struct i915_gem_context *ctx;
274         unsigned int n;
275         int ret;
276
277         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
278         if (ctx == NULL)
279                 return ERR_PTR(-ENOMEM);
280
281         ret = assign_hw_id(dev_priv, &ctx->hw_id);
282         if (ret) {
283                 kfree(ctx);
284                 return ERR_PTR(ret);
285         }
286
287         kref_init(&ctx->ref);
288         list_add_tail(&ctx->link, &dev_priv->contexts.list);
289         ctx->i915 = dev_priv;
290         ctx->sched.priority = I915_PRIORITY_NORMAL;
291
292         for (n = 0; n < ARRAY_SIZE(ctx->__engine); n++) {
293                 struct intel_context *ce = &ctx->__engine[n];
294
295                 ce->gem_context = ctx;
296         }
297
298         INIT_RADIX_TREE(&ctx->handles_vma, GFP_KERNEL);
299         INIT_LIST_HEAD(&ctx->handles_list);
300
301         /* Default context will never have a file_priv */
302         ret = DEFAULT_CONTEXT_HANDLE;
303         if (file_priv) {
304                 ret = idr_alloc(&file_priv->context_idr, ctx,
305                                 DEFAULT_CONTEXT_HANDLE, 0, GFP_KERNEL);
306                 if (ret < 0)
307                         goto err_lut;
308         }
309         ctx->user_handle = ret;
310
311         ctx->file_priv = file_priv;
312         if (file_priv) {
313                 ctx->pid = get_task_pid(current, PIDTYPE_PID);
314                 ctx->name = kasprintf(GFP_KERNEL, "%s[%d]/%x",
315                                       current->comm,
316                                       pid_nr(ctx->pid),
317                                       ctx->user_handle);
318                 if (!ctx->name) {
319                         ret = -ENOMEM;
320                         goto err_pid;
321                 }
322         }
323
324         /* NB: Mark all slices as needing a remap so that when the context first
325          * loads it will restore whatever remap state already exists. If there
326          * is no remap info, it will be a NOP. */
327         ctx->remap_slice = ALL_L3_SLICES(dev_priv);
328
329         i915_gem_context_set_bannable(ctx);
330         ctx->ring_size = 4 * PAGE_SIZE;
331         ctx->desc_template =
332                 default_desc_template(dev_priv, dev_priv->mm.aliasing_ppgtt);
333
334         /*
335          * GuC requires the ring to be placed in Non-WOPCM memory. If GuC is not
336          * present or not in use we still need a small bias as ring wraparound
337          * at offset 0 sometimes hangs. No idea why.
338          */
339         if (USES_GUC(dev_priv))
340                 ctx->ggtt_offset_bias = dev_priv->guc.ggtt_pin_bias;
341         else
342                 ctx->ggtt_offset_bias = I915_GTT_PAGE_SIZE;
343
344         ctx->jump_whitelist = NULL;
345         ctx->jump_whitelist_cmds = 0;
346
347         return ctx;
348
349 err_pid:
350         put_pid(ctx->pid);
351         idr_remove(&file_priv->context_idr, ctx->user_handle);
352 err_lut:
353         context_close(ctx);
354         return ERR_PTR(ret);
355 }
356
357 static void __destroy_hw_context(struct i915_gem_context *ctx,
358                                  struct drm_i915_file_private *file_priv)
359 {
360         idr_remove(&file_priv->context_idr, ctx->user_handle);
361         context_close(ctx);
362 }
363
364 static struct i915_gem_context *
365 i915_gem_create_context(struct drm_i915_private *dev_priv,
366                         struct drm_i915_file_private *file_priv)
367 {
368         struct i915_gem_context *ctx;
369
370         lockdep_assert_held(&dev_priv->drm.struct_mutex);
371
372         /* Reap the most stale context */
373         contexts_free_first(dev_priv);
374
375         ctx = __create_hw_context(dev_priv, file_priv);
376         if (IS_ERR(ctx))
377                 return ctx;
378
379         if (USES_FULL_PPGTT(dev_priv)) {
380                 struct i915_hw_ppgtt *ppgtt;
381
382                 ppgtt = i915_ppgtt_create(dev_priv, file_priv);
383                 if (IS_ERR(ppgtt)) {
384                         DRM_DEBUG_DRIVER("PPGTT setup failed (%ld)\n",
385                                          PTR_ERR(ppgtt));
386                         __destroy_hw_context(ctx, file_priv);
387                         return ERR_CAST(ppgtt);
388                 }
389
390                 ctx->ppgtt = ppgtt;
391                 ctx->desc_template = default_desc_template(dev_priv, ppgtt);
392         }
393
394         trace_i915_context_create(ctx);
395
396         return ctx;
397 }
398
399 /**
400  * i915_gem_context_create_gvt - create a GVT GEM context
401  * @dev: drm device *
402  *
403  * This function is used to create a GVT specific GEM context.
404  *
405  * Returns:
406  * pointer to i915_gem_context on success, error pointer if failed
407  *
408  */
409 struct i915_gem_context *
410 i915_gem_context_create_gvt(struct drm_device *dev)
411 {
412         struct i915_gem_context *ctx;
413         int ret;
414
415         if (!IS_ENABLED(CONFIG_DRM_I915_GVT))
416                 return ERR_PTR(-ENODEV);
417
418         ret = i915_mutex_lock_interruptible(dev);
419         if (ret)
420                 return ERR_PTR(ret);
421
422         ctx = __create_hw_context(to_i915(dev), NULL);
423         if (IS_ERR(ctx))
424                 goto out;
425
426         ctx->file_priv = ERR_PTR(-EBADF);
427         i915_gem_context_set_closed(ctx); /* not user accessible */
428         i915_gem_context_clear_bannable(ctx);
429         i915_gem_context_set_force_single_submission(ctx);
430         if (!USES_GUC_SUBMISSION(to_i915(dev)))
431                 ctx->ring_size = 512 * PAGE_SIZE; /* Max ring buffer size */
432
433         GEM_BUG_ON(i915_gem_context_is_kernel(ctx));
434 out:
435         mutex_unlock(&dev->struct_mutex);
436         return ctx;
437 }
438
439 struct i915_gem_context *
440 i915_gem_context_create_kernel(struct drm_i915_private *i915, int prio)
441 {
442         struct i915_gem_context *ctx;
443
444         ctx = i915_gem_create_context(i915, NULL);
445         if (IS_ERR(ctx))
446                 return ctx;
447
448         i915_gem_context_clear_bannable(ctx);
449         ctx->sched.priority = prio;
450         ctx->ring_size = PAGE_SIZE;
451
452         GEM_BUG_ON(!i915_gem_context_is_kernel(ctx));
453
454         return ctx;
455 }
456
457 static void
458 destroy_kernel_context(struct i915_gem_context **ctxp)
459 {
460         struct i915_gem_context *ctx;
461
462         /* Keep the context ref so that we can free it immediately ourselves */
463         ctx = i915_gem_context_get(fetch_and_zero(ctxp));
464         GEM_BUG_ON(!i915_gem_context_is_kernel(ctx));
465
466         context_close(ctx);
467         i915_gem_context_free(ctx);
468 }
469
470 static bool needs_preempt_context(struct drm_i915_private *i915)
471 {
472         return HAS_LOGICAL_RING_PREEMPTION(i915);
473 }
474
475 int i915_gem_contexts_init(struct drm_i915_private *dev_priv)
476 {
477         struct i915_gem_context *ctx;
478         int ret;
479
480         /* Reassure ourselves we are only called once */
481         GEM_BUG_ON(dev_priv->kernel_context);
482         GEM_BUG_ON(dev_priv->preempt_context);
483
484         ret = intel_ctx_workarounds_init(dev_priv);
485         if (ret)
486                 return ret;
487
488         INIT_LIST_HEAD(&dev_priv->contexts.list);
489         INIT_WORK(&dev_priv->contexts.free_work, contexts_free_worker);
490         init_llist_head(&dev_priv->contexts.free_list);
491
492         /* Using the simple ida interface, the max is limited by sizeof(int) */
493         BUILD_BUG_ON(MAX_CONTEXT_HW_ID > INT_MAX);
494         BUILD_BUG_ON(GEN11_MAX_CONTEXT_HW_ID > INT_MAX);
495         ida_init(&dev_priv->contexts.hw_ida);
496
497         /* lowest priority; idle task */
498         ctx = i915_gem_context_create_kernel(dev_priv, I915_PRIORITY_MIN);
499         if (IS_ERR(ctx)) {
500                 DRM_ERROR("Failed to create default global context\n");
501                 return PTR_ERR(ctx);
502         }
503         /*
504          * For easy recognisablity, we want the kernel context to be 0 and then
505          * all user contexts will have non-zero hw_id.
506          */
507         GEM_BUG_ON(ctx->hw_id);
508         dev_priv->kernel_context = ctx;
509
510         /* highest priority; preempting task */
511         if (needs_preempt_context(dev_priv)) {
512                 ctx = i915_gem_context_create_kernel(dev_priv, INT_MAX);
513                 if (!IS_ERR(ctx))
514                         dev_priv->preempt_context = ctx;
515                 else
516                         DRM_ERROR("Failed to create preempt context; disabling preemption\n");
517         }
518
519         DRM_DEBUG_DRIVER("%s context support initialized\n",
520                          DRIVER_CAPS(dev_priv)->has_logical_contexts ?
521                          "logical" : "fake");
522         return 0;
523 }
524
525 void i915_gem_contexts_lost(struct drm_i915_private *dev_priv)
526 {
527         struct intel_engine_cs *engine;
528         enum intel_engine_id id;
529
530         lockdep_assert_held(&dev_priv->drm.struct_mutex);
531
532         for_each_engine(engine, dev_priv, id)
533                 intel_engine_lost_context(engine);
534 }
535
536 void i915_gem_contexts_fini(struct drm_i915_private *i915)
537 {
538         lockdep_assert_held(&i915->drm.struct_mutex);
539
540         if (i915->preempt_context)
541                 destroy_kernel_context(&i915->preempt_context);
542         destroy_kernel_context(&i915->kernel_context);
543
544         /* Must free all deferred contexts (via flush_workqueue) first */
545         ida_destroy(&i915->contexts.hw_ida);
546 }
547
548 static int context_idr_cleanup(int id, void *p, void *data)
549 {
550         struct i915_gem_context *ctx = p;
551
552         context_close(ctx);
553         return 0;
554 }
555
556 int i915_gem_context_open(struct drm_i915_private *i915,
557                           struct drm_file *file)
558 {
559         struct drm_i915_file_private *file_priv = file->driver_priv;
560         struct i915_gem_context *ctx;
561
562         idr_init(&file_priv->context_idr);
563
564         mutex_lock(&i915->drm.struct_mutex);
565         ctx = i915_gem_create_context(i915, file_priv);
566         mutex_unlock(&i915->drm.struct_mutex);
567         if (IS_ERR(ctx)) {
568                 idr_destroy(&file_priv->context_idr);
569                 return PTR_ERR(ctx);
570         }
571
572         GEM_BUG_ON(i915_gem_context_is_kernel(ctx));
573
574         return 0;
575 }
576
577 void i915_gem_context_close(struct drm_file *file)
578 {
579         struct drm_i915_file_private *file_priv = file->driver_priv;
580
581         lockdep_assert_held(&file_priv->dev_priv->drm.struct_mutex);
582
583         idr_for_each(&file_priv->context_idr, context_idr_cleanup, NULL);
584         idr_destroy(&file_priv->context_idr);
585 }
586
587 static struct i915_request *
588 last_request_on_engine(struct i915_timeline *timeline,
589                        struct intel_engine_cs *engine)
590 {
591         struct i915_request *rq;
592
593         GEM_BUG_ON(timeline == &engine->timeline);
594
595         rq = i915_gem_active_raw(&timeline->last_request,
596                                  &engine->i915->drm.struct_mutex);
597         if (rq && rq->engine == engine) {
598                 GEM_TRACE("last request for %s on engine %s: %llx:%d\n",
599                           timeline->name, engine->name,
600                           rq->fence.context, rq->fence.seqno);
601                 GEM_BUG_ON(rq->timeline != timeline);
602                 return rq;
603         }
604
605         return NULL;
606 }
607
608 static bool engine_has_kernel_context_barrier(struct intel_engine_cs *engine)
609 {
610         struct drm_i915_private *i915 = engine->i915;
611         const struct intel_context * const ce =
612                 to_intel_context(i915->kernel_context, engine);
613         struct i915_timeline *barrier = ce->ring->timeline;
614         struct intel_ring *ring;
615         bool any_active = false;
616
617         lockdep_assert_held(&i915->drm.struct_mutex);
618         list_for_each_entry(ring, &i915->gt.active_rings, active_link) {
619                 struct i915_request *rq;
620
621                 rq = last_request_on_engine(ring->timeline, engine);
622                 if (!rq)
623                         continue;
624
625                 any_active = true;
626
627                 if (rq->hw_context == ce)
628                         continue;
629
630                 /*
631                  * Was this request submitted after the previous
632                  * switch-to-kernel-context?
633                  */
634                 if (!i915_timeline_sync_is_later(barrier, &rq->fence)) {
635                         GEM_TRACE("%s needs barrier for %llx:%d\n",
636                                   ring->timeline->name,
637                                   rq->fence.context,
638                                   rq->fence.seqno);
639                         return false;
640                 }
641
642                 GEM_TRACE("%s has barrier after %llx:%d\n",
643                           ring->timeline->name,
644                           rq->fence.context,
645                           rq->fence.seqno);
646         }
647
648         /*
649          * If any other timeline was still active and behind the last barrier,
650          * then our last switch-to-kernel-context must still be queued and
651          * will run last (leaving the engine in the kernel context when it
652          * eventually idles).
653          */
654         if (any_active)
655                 return true;
656
657         /* The engine is idle; check that it is idling in the kernel context. */
658         return engine->last_retired_context == ce;
659 }
660
661 int i915_gem_switch_to_kernel_context(struct drm_i915_private *i915)
662 {
663         struct intel_engine_cs *engine;
664         enum intel_engine_id id;
665
666         GEM_TRACE("awake?=%s\n", yesno(i915->gt.awake));
667
668         lockdep_assert_held(&i915->drm.struct_mutex);
669         GEM_BUG_ON(!i915->kernel_context);
670
671         i915_retire_requests(i915);
672
673         for_each_engine(engine, i915, id) {
674                 struct intel_ring *ring;
675                 struct i915_request *rq;
676
677                 GEM_BUG_ON(!to_intel_context(i915->kernel_context, engine));
678                 if (engine_has_kernel_context_barrier(engine))
679                         continue;
680
681                 GEM_TRACE("emit barrier on %s\n", engine->name);
682
683                 rq = i915_request_alloc(engine, i915->kernel_context);
684                 if (IS_ERR(rq))
685                         return PTR_ERR(rq);
686
687                 /* Queue this switch after all other activity */
688                 list_for_each_entry(ring, &i915->gt.active_rings, active_link) {
689                         struct i915_request *prev;
690
691                         prev = last_request_on_engine(ring->timeline, engine);
692                         if (!prev)
693                                 continue;
694
695                         if (prev->gem_context == i915->kernel_context)
696                                 continue;
697
698                         GEM_TRACE("add barrier on %s for %llx:%d\n",
699                                   engine->name,
700                                   prev->fence.context,
701                                   prev->fence.seqno);
702                         i915_sw_fence_await_sw_fence_gfp(&rq->submit,
703                                                          &prev->submit,
704                                                          I915_FENCE_GFP);
705                         i915_timeline_sync_set(rq->timeline, &prev->fence);
706                 }
707
708                 i915_request_add(rq);
709         }
710
711         return 0;
712 }
713
714 static bool client_is_banned(struct drm_i915_file_private *file_priv)
715 {
716         return atomic_read(&file_priv->ban_score) >= I915_CLIENT_SCORE_BANNED;
717 }
718
719 int i915_gem_context_create_ioctl(struct drm_device *dev, void *data,
720                                   struct drm_file *file)
721 {
722         struct drm_i915_private *dev_priv = to_i915(dev);
723         struct drm_i915_gem_context_create *args = data;
724         struct drm_i915_file_private *file_priv = file->driver_priv;
725         struct i915_gem_context *ctx;
726         int ret;
727
728         if (!DRIVER_CAPS(dev_priv)->has_logical_contexts)
729                 return -ENODEV;
730
731         if (args->pad != 0)
732                 return -EINVAL;
733
734         if (client_is_banned(file_priv)) {
735                 DRM_DEBUG("client %s[%d] banned from creating ctx\n",
736                           current->comm,
737                           pid_nr(get_task_pid(current, PIDTYPE_PID)));
738
739                 return -EIO;
740         }
741
742         ret = i915_mutex_lock_interruptible(dev);
743         if (ret)
744                 return ret;
745
746         ctx = i915_gem_create_context(dev_priv, file_priv);
747         mutex_unlock(&dev->struct_mutex);
748         if (IS_ERR(ctx))
749                 return PTR_ERR(ctx);
750
751         GEM_BUG_ON(i915_gem_context_is_kernel(ctx));
752
753         args->ctx_id = ctx->user_handle;
754         DRM_DEBUG("HW context %d created\n", args->ctx_id);
755
756         return 0;
757 }
758
759 int i915_gem_context_destroy_ioctl(struct drm_device *dev, void *data,
760                                    struct drm_file *file)
761 {
762         struct drm_i915_gem_context_destroy *args = data;
763         struct drm_i915_file_private *file_priv = file->driver_priv;
764         struct i915_gem_context *ctx;
765         int ret;
766
767         if (args->pad != 0)
768                 return -EINVAL;
769
770         if (args->ctx_id == DEFAULT_CONTEXT_HANDLE)
771                 return -ENOENT;
772
773         ret = i915_mutex_lock_interruptible(dev);
774         if (ret)
775                 return ret;
776
777         ctx = i915_gem_context_lookup(file_priv, args->ctx_id);
778         if (!ctx) {
779                 mutex_unlock(&dev->struct_mutex);
780                 return -ENOENT;
781         }
782
783         __destroy_hw_context(ctx, file_priv);
784         mutex_unlock(&dev->struct_mutex);
785
786         i915_gem_context_put(ctx);
787         return 0;
788 }
789
790 int i915_gem_context_getparam_ioctl(struct drm_device *dev, void *data,
791                                     struct drm_file *file)
792 {
793         struct drm_i915_file_private *file_priv = file->driver_priv;
794         struct drm_i915_gem_context_param *args = data;
795         struct i915_gem_context *ctx;
796         int ret = 0;
797
798         ctx = i915_gem_context_lookup(file_priv, args->ctx_id);
799         if (!ctx)
800                 return -ENOENT;
801
802         args->size = 0;
803         switch (args->param) {
804         case I915_CONTEXT_PARAM_BAN_PERIOD:
805                 ret = -EINVAL;
806                 break;
807         case I915_CONTEXT_PARAM_NO_ZEROMAP:
808                 args->value = ctx->flags & CONTEXT_NO_ZEROMAP;
809                 break;
810         case I915_CONTEXT_PARAM_GTT_SIZE:
811                 if (ctx->ppgtt)
812                         args->value = ctx->ppgtt->vm.total;
813                 else if (to_i915(dev)->mm.aliasing_ppgtt)
814                         args->value = to_i915(dev)->mm.aliasing_ppgtt->vm.total;
815                 else
816                         args->value = to_i915(dev)->ggtt.vm.total;
817                 break;
818         case I915_CONTEXT_PARAM_NO_ERROR_CAPTURE:
819                 args->value = i915_gem_context_no_error_capture(ctx);
820                 break;
821         case I915_CONTEXT_PARAM_BANNABLE:
822                 args->value = i915_gem_context_is_bannable(ctx);
823                 break;
824         case I915_CONTEXT_PARAM_PRIORITY:
825                 args->value = ctx->sched.priority;
826                 break;
827         default:
828                 ret = -EINVAL;
829                 break;
830         }
831
832         i915_gem_context_put(ctx);
833         return ret;
834 }
835
836 int i915_gem_context_setparam_ioctl(struct drm_device *dev, void *data,
837                                     struct drm_file *file)
838 {
839         struct drm_i915_file_private *file_priv = file->driver_priv;
840         struct drm_i915_gem_context_param *args = data;
841         struct i915_gem_context *ctx;
842         int ret;
843
844         ctx = i915_gem_context_lookup(file_priv, args->ctx_id);
845         if (!ctx)
846                 return -ENOENT;
847
848         ret = i915_mutex_lock_interruptible(dev);
849         if (ret)
850                 goto out;
851
852         switch (args->param) {
853         case I915_CONTEXT_PARAM_BAN_PERIOD:
854                 ret = -EINVAL;
855                 break;
856         case I915_CONTEXT_PARAM_NO_ZEROMAP:
857                 if (args->size) {
858                         ret = -EINVAL;
859                 } else {
860                         ctx->flags &= ~CONTEXT_NO_ZEROMAP;
861                         ctx->flags |= args->value ? CONTEXT_NO_ZEROMAP : 0;
862                 }
863                 break;
864         case I915_CONTEXT_PARAM_NO_ERROR_CAPTURE:
865                 if (args->size)
866                         ret = -EINVAL;
867                 else if (args->value)
868                         i915_gem_context_set_no_error_capture(ctx);
869                 else
870                         i915_gem_context_clear_no_error_capture(ctx);
871                 break;
872         case I915_CONTEXT_PARAM_BANNABLE:
873                 if (args->size)
874                         ret = -EINVAL;
875                 else if (!capable(CAP_SYS_ADMIN) && !args->value)
876                         ret = -EPERM;
877                 else if (args->value)
878                         i915_gem_context_set_bannable(ctx);
879                 else
880                         i915_gem_context_clear_bannable(ctx);
881                 break;
882
883         case I915_CONTEXT_PARAM_PRIORITY:
884                 {
885                         s64 priority = args->value;
886
887                         if (args->size)
888                                 ret = -EINVAL;
889                         else if (!(to_i915(dev)->caps.scheduler & I915_SCHEDULER_CAP_PRIORITY))
890                                 ret = -ENODEV;
891                         else if (priority > I915_CONTEXT_MAX_USER_PRIORITY ||
892                                  priority < I915_CONTEXT_MIN_USER_PRIORITY)
893                                 ret = -EINVAL;
894                         else if (priority > I915_CONTEXT_DEFAULT_PRIORITY &&
895                                  !capable(CAP_SYS_NICE))
896                                 ret = -EPERM;
897                         else
898                                 ctx->sched.priority = priority;
899                 }
900                 break;
901
902         default:
903                 ret = -EINVAL;
904                 break;
905         }
906         mutex_unlock(&dev->struct_mutex);
907
908 out:
909         i915_gem_context_put(ctx);
910         return ret;
911 }
912
913 int i915_gem_context_reset_stats_ioctl(struct drm_device *dev,
914                                        void *data, struct drm_file *file)
915 {
916         struct drm_i915_private *dev_priv = to_i915(dev);
917         struct drm_i915_reset_stats *args = data;
918         struct i915_gem_context *ctx;
919         int ret;
920
921         if (args->flags || args->pad)
922                 return -EINVAL;
923
924         ret = -ENOENT;
925         rcu_read_lock();
926         ctx = __i915_gem_context_lookup_rcu(file->driver_priv, args->ctx_id);
927         if (!ctx)
928                 goto out;
929
930         /*
931          * We opt for unserialised reads here. This may result in tearing
932          * in the extremely unlikely event of a GPU hang on this context
933          * as we are querying them. If we need that extra layer of protection,
934          * we should wrap the hangstats with a seqlock.
935          */
936
937         if (capable(CAP_SYS_ADMIN))
938                 args->reset_count = i915_reset_count(&dev_priv->gpu_error);
939         else
940                 args->reset_count = 0;
941
942         args->batch_active = atomic_read(&ctx->guilty_count);
943         args->batch_pending = atomic_read(&ctx->active_count);
944
945         ret = 0;
946 out:
947         rcu_read_unlock();
948         return ret;
949 }
950
951 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
952 #include "selftests/mock_context.c"
953 #include "selftests/i915_gem_context.c"
954 #endif