2 * SPDX-License-Identifier: MIT
4 * Copyright © 2008,2010 Intel Corporation
7 #include <linux/intel-iommu.h>
8 #include <linux/dma-resv.h>
9 #include <linux/sync_file.h>
10 #include <linux/uaccess.h>
12 #include <drm/drm_syncobj.h>
14 #include "display/intel_frontbuffer.h"
16 #include "gem/i915_gem_ioctls.h"
17 #include "gt/intel_context.h"
18 #include "gt/intel_gt.h"
19 #include "gt/intel_gt_buffer_pool.h"
20 #include "gt/intel_gt_pm.h"
21 #include "gt/intel_ring.h"
24 #include "i915_gem_clflush.h"
25 #include "i915_gem_context.h"
26 #include "i915_gem_ioctls.h"
27 #include "i915_sw_fence_work.h"
28 #include "i915_trace.h"
29 #include "i915_user_extensions.h"
35 /** This vma's place in the execbuf reservation list */
36 struct drm_i915_gem_exec_object2 *exec;
37 struct list_head bind_link;
38 struct list_head reloc_link;
40 struct hlist_node node;
49 #define __EXEC_OBJECT_HAS_PIN BIT(31)
50 #define __EXEC_OBJECT_HAS_FENCE BIT(30)
51 #define __EXEC_OBJECT_NEEDS_MAP BIT(29)
52 #define __EXEC_OBJECT_NEEDS_BIAS BIT(28)
53 #define __EXEC_OBJECT_INTERNAL_FLAGS (~0u << 28) /* all of the above */
55 #define __EXEC_HAS_RELOC BIT(31)
56 #define __EXEC_INTERNAL_FLAGS (~0u << 31)
57 #define UPDATE PIN_OFFSET_FIXED
59 #define BATCH_OFFSET_BIAS (256*1024)
61 #define __I915_EXEC_ILLEGAL_FLAGS \
62 (__I915_EXEC_UNKNOWN_FLAGS | \
63 I915_EXEC_CONSTANTS_MASK | \
64 I915_EXEC_RESOURCE_STREAMER)
66 /* Catch emission of unexpected errors for CI! */
67 #if IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM)
70 DRM_DEBUG_DRIVER("EINVAL at %s:%d\n", __func__, __LINE__); \
76 * DOC: User command execution
78 * Userspace submits commands to be executed on the GPU as an instruction
79 * stream within a GEM object we call a batchbuffer. This instructions may
80 * refer to other GEM objects containing auxiliary state such as kernels,
81 * samplers, render targets and even secondary batchbuffers. Userspace does
82 * not know where in the GPU memory these objects reside and so before the
83 * batchbuffer is passed to the GPU for execution, those addresses in the
84 * batchbuffer and auxiliary objects are updated. This is known as relocation,
85 * or patching. To try and avoid having to relocate each object on the next
86 * execution, userspace is told the location of those objects in this pass,
87 * but this remains just a hint as the kernel may choose a new location for
88 * any object in the future.
90 * At the level of talking to the hardware, submitting a batchbuffer for the
91 * GPU to execute is to add content to a buffer from which the HW
92 * command streamer is reading.
94 * 1. Add a command to load the HW context. For Logical Ring Contexts, i.e.
95 * Execlists, this command is not placed on the same buffer as the
98 * 2. Add a command to invalidate caches to the buffer.
100 * 3. Add a batchbuffer start command to the buffer; the start command is
101 * essentially a token together with the GPU address of the batchbuffer
104 * 4. Add a pipeline flush to the buffer.
106 * 5. Add a memory write command to the buffer to record when the GPU
107 * is done executing the batchbuffer. The memory write writes the
108 * global sequence number of the request, ``i915_request::global_seqno``;
109 * the i915 driver uses the current value in the register to determine
110 * if the GPU has completed the batchbuffer.
112 * 6. Add a user interrupt command to the buffer. This command instructs
113 * the GPU to issue an interrupt when the command, pipeline flush and
114 * memory write are completed.
116 * 7. Inform the hardware of the additional commands added to the buffer
117 * (by updating the tail pointer).
119 * Processing an execbuf ioctl is conceptually split up into a few phases.
121 * 1. Validation - Ensure all the pointers, handles and flags are valid.
122 * 2. Reservation - Assign GPU address space for every object
123 * 3. Relocation - Update any addresses to point to the final locations
124 * 4. Serialisation - Order the request with respect to its dependencies
125 * 5. Construction - Construct a request to execute the batchbuffer
126 * 6. Submission (at some point in the future execution)
128 * Reserving resources for the execbuf is the most complicated phase. We
129 * neither want to have to migrate the object in the address space, nor do
130 * we want to have to update any relocations pointing to this object. Ideally,
131 * we want to leave the object where it is and for all the existing relocations
132 * to match. If the object is given a new address, or if userspace thinks the
133 * object is elsewhere, we have to parse all the relocation entries and update
134 * the addresses. Userspace can set the I915_EXEC_NORELOC flag to hint that
135 * all the target addresses in all of its objects match the value in the
136 * relocation entries and that they all match the presumed offsets given by the
137 * list of execbuffer objects. Using this knowledge, we know that if we haven't
138 * moved any buffers, all the relocation entries are valid and we can skip
139 * the update. (If userspace is wrong, the likely outcome is an impromptu GPU
140 * hang.) The requirement for using I915_EXEC_NO_RELOC are:
142 * The addresses written in the objects must match the corresponding
143 * reloc.presumed_offset which in turn must match the corresponding
146 * Any render targets written to in the batch must be flagged with
149 * To avoid stalling, execobject.offset should match the current
150 * address of that object within the active context.
152 * The reservation is done is multiple phases. First we try and keep any
153 * object already bound in its current location - so as long as meets the
154 * constraints imposed by the new execbuffer. Any object left unbound after the
155 * first pass is then fitted into any available idle space. If an object does
156 * not fit, all objects are removed from the reservation and the process rerun
157 * after sorting the objects into a priority order (more difficult to fit
158 * objects are tried first). Failing that, the entire VM is cleared and we try
159 * to fit the execbuf once last time before concluding that it simply will not
162 * A small complication to all of this is that we allow userspace not only to
163 * specify an alignment and a size for the object in the address space, but
164 * we also allow userspace to specify the exact offset. This objects are
165 * simpler to place (the location is known a priori) all we have to do is make
166 * sure the space is available.
168 * Once all the objects are in place, patching up the buried pointers to point
169 * to the final locations is a fairly simple job of walking over the relocation
170 * entry arrays, looking up the right address and rewriting the value into
171 * the object. Simple! ... The relocation entries are stored in user memory
172 * and so to access them we have to copy them into a local buffer. That copy
173 * has to avoid taking any pagefaults as they may lead back to a GEM object
174 * requiring the struct_mutex (i.e. recursive deadlock). So once again we split
175 * the relocation into multiple passes. First we try to do everything within an
176 * atomic context (avoid the pagefaults) which requires that we never wait. If
177 * we detect that we may wait, or if we need to fault, then we have to fallback
178 * to a slower path. The slowpath has to drop the mutex. (Can you hear alarm
179 * bells yet?) Dropping the mutex means that we lose all the state we have
180 * built up so far for the execbuf and we must reset any global data. However,
181 * we do leave the objects pinned in their final locations - which is a
182 * potential issue for concurrent execbufs. Once we have left the mutex, we can
183 * allocate and copy all the relocation entries into a large array at our
184 * leisure, reacquire the mutex, reclaim all the objects and other state and
185 * then proceed to update any incorrect addresses with the objects.
187 * As we process the relocation entries, we maintain a record of whether the
188 * object is being written to. Using NORELOC, we expect userspace to provide
189 * this information instead. We also check whether we can skip the relocation
190 * by comparing the expected value inside the relocation entry with the target's
191 * final address. If they differ, we have to map the current object and rewrite
192 * the 4 or 8 byte pointer within.
194 * Serialising an execbuf is quite simple according to the rules of the GEM
195 * ABI. Execution within each context is ordered by the order of submission.
196 * Writes to any GEM object are in order of submission and are exclusive. Reads
197 * from a GEM object are unordered with respect to other reads, but ordered by
198 * writes. A write submitted after a read cannot occur before the read, and
199 * similarly any read submitted after a write cannot occur before the write.
200 * Writes are ordered between engines such that only one write occurs at any
201 * time (completing any reads beforehand) - using semaphores where available
202 * and CPU serialisation otherwise. Other GEM access obey the same rules, any
203 * write (either via mmaps using set-domain, or via pwrite) must flush all GPU
204 * reads before starting, and any read (either using set-domain or pread) must
205 * flush all GPU writes before starting. (Note we only employ a barrier before,
206 * we currently rely on userspace not concurrently starting a new execution
207 * whilst reading or writing to an object. This may be an advantage or not
208 * depending on how much you trust userspace not to shoot themselves in the
209 * foot.) Serialisation may just result in the request being inserted into
210 * a DAG awaiting its turn, but most simple is to wait on the CPU until
211 * all dependencies are resolved.
213 * After all of that, is just a matter of closing the request and handing it to
214 * the hardware (well, leaving it in a queue to be executed). However, we also
215 * offer the ability for batchbuffers to be run with elevated privileges so
216 * that they access otherwise hidden registers. (Used to adjust L3 cache etc.)
217 * Before any batch is given extra privileges we first must check that it
218 * contains no nefarious instructions, we check that each instruction is from
219 * our whitelist and all registers are also from an allowed list. We first
220 * copy the user's batchbuffer to a shadow (so that the user doesn't have
221 * access to it, either by the CPU or GPU as we scan it) and then parse each
222 * instruction. If everything is ok, we set a flag telling the hardware to run
223 * the batchbuffer in trusted mode, otherwise the ioctl is rejected.
227 struct drm_syncobj *syncobj; /* Use with ptr_mask_bits() */
228 struct dma_fence *dma_fence;
230 struct dma_fence_chain *chain_fence;
233 struct i915_execbuffer {
234 struct drm_i915_private *i915; /** i915 backpointer */
235 struct drm_file *file; /** per-file lookup tables and limits */
236 struct drm_i915_gem_execbuffer2 *args; /** ioctl parameters */
237 struct drm_i915_gem_exec_object2 *exec; /** ioctl execobj[] */
240 struct intel_engine_cs *engine; /** engine to queue the request to */
241 struct intel_context *context; /* logical state for the request */
242 struct i915_gem_context *gem_context; /** caller's context */
244 struct i915_request *request; /** our request to build */
245 struct eb_vma *batch; /** identity of the batch obj/vma */
246 struct i915_vma *trampoline; /** trampoline used for chaining */
248 /** actual size of execobj[] as we may extend it for the cmdparser */
249 unsigned int buffer_count;
251 /** list of vma not yet bound during reservation phase */
252 struct list_head unbound;
254 /** list of vma that have execobj.relocation_count */
255 struct list_head relocs;
258 * Track the most recently used object for relocations, as we
259 * frequently have to perform multiple relocations within the same
263 struct drm_mm_node node; /** temporary GTT binding */
264 unsigned int gen; /** Cached value of INTEL_GEN */
265 bool use_64bit_reloc : 1;
268 bool needs_unfenced : 1;
270 struct i915_vma *target;
271 struct i915_request *rq;
272 struct i915_vma *rq_vma;
274 unsigned int rq_size;
277 u64 invalid_flags; /** Set of execobj.flags that are invalid */
278 u32 context_flags; /** Set of execobj.flags to insert from the ctx */
280 u32 batch_start_offset; /** Location within object of batch */
281 u32 batch_len; /** Length of batch within object */
282 u32 batch_flags; /** Flags composed for emit_bb_start() */
285 * Indicate either the size of the hastable used to resolve
286 * relocation handles, or if negative that we are using a direct
287 * index into the execobj[].
290 struct hlist_head *buckets; /** ht for relocation handles */
291 struct eb_vma_array *array;
293 struct eb_fence *fences;
294 unsigned long num_fences;
297 static inline bool eb_use_cmdparser(const struct i915_execbuffer *eb)
299 return intel_engine_requires_cmd_parser(eb->engine) ||
300 (intel_engine_using_cmd_parser(eb->engine) &&
301 eb->args->batch_len);
304 static struct eb_vma_array *eb_vma_array_create(unsigned int count)
306 struct eb_vma_array *arr;
308 arr = kvmalloc(struct_size(arr, vma, count), GFP_KERNEL | __GFP_NOWARN);
312 kref_init(&arr->kref);
313 arr->vma[0].vma = NULL;
318 static inline void eb_unreserve_vma(struct eb_vma *ev)
320 struct i915_vma *vma = ev->vma;
322 if (unlikely(ev->flags & __EXEC_OBJECT_HAS_FENCE))
323 __i915_vma_unpin_fence(vma);
325 if (ev->flags & __EXEC_OBJECT_HAS_PIN)
326 __i915_vma_unpin(vma);
328 ev->flags &= ~(__EXEC_OBJECT_HAS_PIN |
329 __EXEC_OBJECT_HAS_FENCE);
332 static void eb_vma_array_destroy(struct kref *kref)
334 struct eb_vma_array *arr = container_of(kref, typeof(*arr), kref);
335 struct eb_vma *ev = arr->vma;
338 eb_unreserve_vma(ev);
339 i915_vma_put(ev->vma);
346 static void eb_vma_array_put(struct eb_vma_array *arr)
348 kref_put(&arr->kref, eb_vma_array_destroy);
351 static int eb_create(struct i915_execbuffer *eb)
353 /* Allocate an extra slot for use by the command parser + sentinel */
354 eb->array = eb_vma_array_create(eb->buffer_count + 2);
358 eb->vma = eb->array->vma;
360 if (!(eb->args->flags & I915_EXEC_HANDLE_LUT)) {
361 unsigned int size = 1 + ilog2(eb->buffer_count);
364 * Without a 1:1 association between relocation handles and
365 * the execobject[] index, we instead create a hashtable.
366 * We size it dynamically based on available memory, starting
367 * first with 1:1 assocative hash and scaling back until
368 * the allocation succeeds.
370 * Later on we use a positive lut_size to indicate we are
371 * using this hashtable, and a negative value to indicate a
377 /* While we can still reduce the allocation size, don't
378 * raise a warning and allow the allocation to fail.
379 * On the last pass though, we want to try as hard
380 * as possible to perform the allocation and warn
385 flags |= __GFP_NORETRY | __GFP_NOWARN;
387 eb->buckets = kzalloc(sizeof(struct hlist_head) << size,
393 if (unlikely(!size)) {
394 eb_vma_array_put(eb->array);
400 eb->lut_size = -eb->buffer_count;
407 eb_vma_misplaced(const struct drm_i915_gem_exec_object2 *entry,
408 const struct i915_vma *vma,
411 if (vma->node.size < entry->pad_to_size)
414 if (entry->alignment && !IS_ALIGNED(vma->node.start, entry->alignment))
417 if (flags & EXEC_OBJECT_PINNED &&
418 vma->node.start != entry->offset)
421 if (flags & __EXEC_OBJECT_NEEDS_BIAS &&
422 vma->node.start < BATCH_OFFSET_BIAS)
425 if (!(flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS) &&
426 (vma->node.start + vma->node.size - 1) >> 32)
429 if (flags & __EXEC_OBJECT_NEEDS_MAP &&
430 !i915_vma_is_map_and_fenceable(vma))
436 static u64 eb_pin_flags(const struct drm_i915_gem_exec_object2 *entry,
437 unsigned int exec_flags)
441 if (exec_flags & EXEC_OBJECT_NEEDS_GTT)
442 pin_flags |= PIN_GLOBAL;
445 * Wa32bitGeneralStateOffset & Wa32bitInstructionBaseOffset,
446 * limit address to the first 4GBs for unflagged objects.
448 if (!(exec_flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS))
449 pin_flags |= PIN_ZONE_4G;
451 if (exec_flags & __EXEC_OBJECT_NEEDS_MAP)
452 pin_flags |= PIN_MAPPABLE;
454 if (exec_flags & EXEC_OBJECT_PINNED)
455 pin_flags |= entry->offset | PIN_OFFSET_FIXED;
456 else if (exec_flags & __EXEC_OBJECT_NEEDS_BIAS)
457 pin_flags |= BATCH_OFFSET_BIAS | PIN_OFFSET_BIAS;
463 eb_pin_vma(struct i915_execbuffer *eb,
464 const struct drm_i915_gem_exec_object2 *entry,
467 struct i915_vma *vma = ev->vma;
471 pin_flags = vma->node.start;
473 pin_flags = entry->offset & PIN_OFFSET_MASK;
475 pin_flags |= PIN_USER | PIN_NOEVICT | PIN_OFFSET_FIXED;
476 if (unlikely(ev->flags & EXEC_OBJECT_NEEDS_GTT))
477 pin_flags |= PIN_GLOBAL;
479 /* Attempt to reuse the current location if available */
480 if (unlikely(i915_vma_pin(vma, 0, 0, pin_flags))) {
481 if (entry->flags & EXEC_OBJECT_PINNED)
484 /* Failing that pick any _free_ space if suitable */
485 if (unlikely(i915_vma_pin(vma,
488 eb_pin_flags(entry, ev->flags) |
489 PIN_USER | PIN_NOEVICT)))
493 if (unlikely(ev->flags & EXEC_OBJECT_NEEDS_FENCE)) {
494 if (unlikely(i915_vma_pin_fence(vma))) {
500 ev->flags |= __EXEC_OBJECT_HAS_FENCE;
503 ev->flags |= __EXEC_OBJECT_HAS_PIN;
504 return !eb_vma_misplaced(entry, vma, ev->flags);
508 eb_validate_vma(struct i915_execbuffer *eb,
509 struct drm_i915_gem_exec_object2 *entry,
510 struct i915_vma *vma)
512 if (unlikely(entry->flags & eb->invalid_flags))
515 if (unlikely(entry->alignment &&
516 !is_power_of_2_u64(entry->alignment)))
520 * Offset can be used as input (EXEC_OBJECT_PINNED), reject
521 * any non-page-aligned or non-canonical addresses.
523 if (unlikely(entry->flags & EXEC_OBJECT_PINNED &&
524 entry->offset != gen8_canonical_addr(entry->offset & I915_GTT_PAGE_MASK)))
527 /* pad_to_size was once a reserved field, so sanitize it */
528 if (entry->flags & EXEC_OBJECT_PAD_TO_SIZE) {
529 if (unlikely(offset_in_page(entry->pad_to_size)))
532 entry->pad_to_size = 0;
535 * From drm_mm perspective address space is continuous,
536 * so from this point we're always using non-canonical
539 entry->offset = gen8_noncanonical_addr(entry->offset);
541 if (!eb->reloc_cache.has_fence) {
542 entry->flags &= ~EXEC_OBJECT_NEEDS_FENCE;
544 if ((entry->flags & EXEC_OBJECT_NEEDS_FENCE ||
545 eb->reloc_cache.needs_unfenced) &&
546 i915_gem_object_is_tiled(vma->obj))
547 entry->flags |= EXEC_OBJECT_NEEDS_GTT | __EXEC_OBJECT_NEEDS_MAP;
550 if (!(entry->flags & EXEC_OBJECT_PINNED))
551 entry->flags |= eb->context_flags;
557 eb_add_vma(struct i915_execbuffer *eb,
558 unsigned int i, unsigned batch_idx,
559 struct i915_vma *vma)
561 struct drm_i915_gem_exec_object2 *entry = &eb->exec[i];
562 struct eb_vma *ev = &eb->vma[i];
564 GEM_BUG_ON(i915_vma_is_closed(vma));
568 ev->flags = entry->flags;
570 if (eb->lut_size > 0) {
571 ev->handle = entry->handle;
572 hlist_add_head(&ev->node,
573 &eb->buckets[hash_32(entry->handle,
577 if (entry->relocation_count)
578 list_add_tail(&ev->reloc_link, &eb->relocs);
581 * SNA is doing fancy tricks with compressing batch buffers, which leads
582 * to negative relocation deltas. Usually that works out ok since the
583 * relocate address is still positive, except when the batch is placed
584 * very low in the GTT. Ensure this doesn't happen.
586 * Note that actual hangs have only been observed on gen7, but for
587 * paranoia do it everywhere.
589 if (i == batch_idx) {
590 if (entry->relocation_count &&
591 !(ev->flags & EXEC_OBJECT_PINNED))
592 ev->flags |= __EXEC_OBJECT_NEEDS_BIAS;
593 if (eb->reloc_cache.has_fence)
594 ev->flags |= EXEC_OBJECT_NEEDS_FENCE;
599 if (eb_pin_vma(eb, entry, ev)) {
600 if (entry->offset != vma->node.start) {
601 entry->offset = vma->node.start | UPDATE;
602 eb->args->flags |= __EXEC_HAS_RELOC;
605 eb_unreserve_vma(ev);
606 list_add_tail(&ev->bind_link, &eb->unbound);
610 static int eb_reserve_vma(const struct i915_execbuffer *eb,
614 struct drm_i915_gem_exec_object2 *entry = ev->exec;
615 struct i915_vma *vma = ev->vma;
618 if (drm_mm_node_allocated(&vma->node) &&
619 eb_vma_misplaced(entry, vma, ev->flags)) {
620 err = i915_vma_unbind(vma);
625 err = i915_vma_pin(vma,
626 entry->pad_to_size, entry->alignment,
627 eb_pin_flags(entry, ev->flags) | pin_flags);
631 if (entry->offset != vma->node.start) {
632 entry->offset = vma->node.start | UPDATE;
633 eb->args->flags |= __EXEC_HAS_RELOC;
636 if (unlikely(ev->flags & EXEC_OBJECT_NEEDS_FENCE)) {
637 err = i915_vma_pin_fence(vma);
644 ev->flags |= __EXEC_OBJECT_HAS_FENCE;
647 ev->flags |= __EXEC_OBJECT_HAS_PIN;
648 GEM_BUG_ON(eb_vma_misplaced(entry, vma, ev->flags));
653 static int eb_reserve(struct i915_execbuffer *eb)
655 const unsigned int count = eb->buffer_count;
656 unsigned int pin_flags = PIN_USER | PIN_NONBLOCK;
657 struct list_head last;
659 unsigned int i, pass;
663 * Attempt to pin all of the buffers into the GTT.
664 * This is done in 3 phases:
666 * 1a. Unbind all objects that do not match the GTT constraints for
667 * the execbuffer (fenceable, mappable, alignment etc).
668 * 1b. Increment pin count for already bound objects.
669 * 2. Bind new objects.
670 * 3. Decrement pin count.
672 * This avoid unnecessary unbinding of later objects in order to make
673 * room for the earlier objects *unless* we need to defragment.
676 if (mutex_lock_interruptible(&eb->i915->drm.struct_mutex))
681 list_for_each_entry(ev, &eb->unbound, bind_link) {
682 err = eb_reserve_vma(eb, ev, pin_flags);
686 if (!(err == -ENOSPC || err == -EAGAIN))
689 /* Resort *all* the objects into priority order */
690 INIT_LIST_HEAD(&eb->unbound);
691 INIT_LIST_HEAD(&last);
692 for (i = 0; i < count; i++) {
697 if (flags & EXEC_OBJECT_PINNED &&
698 flags & __EXEC_OBJECT_HAS_PIN)
701 eb_unreserve_vma(ev);
703 if (flags & EXEC_OBJECT_PINNED)
704 /* Pinned must have their slot */
705 list_add(&ev->bind_link, &eb->unbound);
706 else if (flags & __EXEC_OBJECT_NEEDS_MAP)
707 /* Map require the lowest 256MiB (aperture) */
708 list_add_tail(&ev->bind_link, &eb->unbound);
709 else if (!(flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS))
710 /* Prioritise 4GiB region for restricted bo */
711 list_add(&ev->bind_link, &last);
713 list_add_tail(&ev->bind_link, &last);
715 list_splice_tail(&last, &eb->unbound);
717 if (err == -EAGAIN) {
718 mutex_unlock(&eb->i915->drm.struct_mutex);
719 flush_workqueue(eb->i915->mm.userptr_wq);
720 mutex_lock(&eb->i915->drm.struct_mutex);
729 /* Too fragmented, unbind everything and retry */
730 mutex_lock(&eb->context->vm->mutex);
731 err = i915_gem_evict_vm(eb->context->vm);
732 mutex_unlock(&eb->context->vm->mutex);
742 pin_flags = PIN_USER;
746 mutex_unlock(&eb->i915->drm.struct_mutex);
750 static unsigned int eb_batch_index(const struct i915_execbuffer *eb)
752 if (eb->args->flags & I915_EXEC_BATCH_FIRST)
755 return eb->buffer_count - 1;
758 static int eb_select_context(struct i915_execbuffer *eb)
760 struct i915_gem_context *ctx;
762 ctx = i915_gem_context_lookup(eb->file->driver_priv, eb->args->rsvd1);
766 eb->gem_context = ctx;
767 if (rcu_access_pointer(ctx->vm))
768 eb->invalid_flags |= EXEC_OBJECT_NEEDS_GTT;
770 eb->context_flags = 0;
771 if (test_bit(UCONTEXT_NO_ZEROMAP, &ctx->user_flags))
772 eb->context_flags |= __EXEC_OBJECT_NEEDS_BIAS;
777 static int __eb_add_lut(struct i915_execbuffer *eb,
778 u32 handle, struct i915_vma *vma)
780 struct i915_gem_context *ctx = eb->gem_context;
781 struct i915_lut_handle *lut;
784 lut = i915_lut_handle_alloc();
789 if (!atomic_fetch_inc(&vma->open_count))
790 i915_vma_reopen(vma);
791 lut->handle = handle;
794 /* Check that the context hasn't been closed in the meantime */
796 if (!mutex_lock_interruptible(&ctx->lut_mutex)) {
797 struct i915_address_space *vm = rcu_access_pointer(ctx->vm);
799 if (unlikely(vm && vma->vm != vm))
800 err = -EAGAIN; /* user racing with ctx set-vm */
801 else if (likely(!i915_gem_context_is_closed(ctx)))
802 err = radix_tree_insert(&ctx->handles_vma, handle, vma);
805 if (err == 0) { /* And nor has this handle */
806 struct drm_i915_gem_object *obj = vma->obj;
808 spin_lock(&obj->lut_lock);
809 if (idr_find(&eb->file->object_idr, handle) == obj) {
810 list_add(&lut->obj_link, &obj->lut_list);
812 radix_tree_delete(&ctx->handles_vma, handle);
815 spin_unlock(&obj->lut_lock);
817 mutex_unlock(&ctx->lut_mutex);
827 i915_lut_handle_free(lut);
831 static struct i915_vma *eb_lookup_vma(struct i915_execbuffer *eb, u32 handle)
833 struct i915_address_space *vm = eb->context->vm;
836 struct drm_i915_gem_object *obj;
837 struct i915_vma *vma;
841 vma = radix_tree_lookup(&eb->gem_context->handles_vma, handle);
842 if (likely(vma && vma->vm == vm))
843 vma = i915_vma_tryget(vma);
848 obj = i915_gem_object_lookup(eb->file, handle);
850 return ERR_PTR(-ENOENT);
852 vma = i915_vma_instance(obj, vm, NULL);
854 i915_gem_object_put(obj);
858 err = __eb_add_lut(eb, handle, vma);
862 i915_gem_object_put(obj);
868 static int eb_lookup_vmas(struct i915_execbuffer *eb)
870 unsigned int batch = eb_batch_index(eb);
874 INIT_LIST_HEAD(&eb->relocs);
875 INIT_LIST_HEAD(&eb->unbound);
877 for (i = 0; i < eb->buffer_count; i++) {
878 struct i915_vma *vma;
880 vma = eb_lookup_vma(eb, eb->exec[i].handle);
886 err = eb_validate_vma(eb, &eb->exec[i], vma);
892 eb_add_vma(eb, i, batch, vma);
895 eb->vma[i].vma = NULL;
899 static struct eb_vma *
900 eb_get_vma(const struct i915_execbuffer *eb, unsigned long handle)
902 if (eb->lut_size < 0) {
903 if (handle >= -eb->lut_size)
905 return &eb->vma[handle];
907 struct hlist_head *head;
910 head = &eb->buckets[hash_32(handle, eb->lut_size)];
911 hlist_for_each_entry(ev, head, node) {
912 if (ev->handle == handle)
919 static void eb_destroy(const struct i915_execbuffer *eb)
921 GEM_BUG_ON(eb->reloc_cache.rq);
924 eb_vma_array_put(eb->array);
926 if (eb->lut_size > 0)
931 relocation_target(const struct drm_i915_gem_relocation_entry *reloc,
932 const struct i915_vma *target)
934 return gen8_canonical_addr((int)reloc->delta + target->node.start);
937 static void reloc_cache_init(struct reloc_cache *cache,
938 struct drm_i915_private *i915)
940 /* Must be a variable in the struct to allow GCC to unroll. */
941 cache->gen = INTEL_GEN(i915);
942 cache->has_llc = HAS_LLC(i915);
943 cache->use_64bit_reloc = HAS_64BIT_RELOC(i915);
944 cache->has_fence = cache->gen < 4;
945 cache->needs_unfenced = INTEL_INFO(i915)->unfenced_needs_alignment;
946 cache->node.flags = 0;
948 cache->target = NULL;
953 static int reloc_gpu_chain(struct reloc_cache *cache)
955 struct intel_gt_buffer_pool_node *pool;
956 struct i915_request *rq = cache->rq;
957 struct i915_vma *batch;
961 pool = intel_gt_get_buffer_pool(rq->engine->gt, PAGE_SIZE);
963 return PTR_ERR(pool);
965 batch = i915_vma_instance(pool->obj, rq->context->vm, NULL);
967 err = PTR_ERR(batch);
971 err = i915_vma_pin(batch, 0, 0, PIN_USER | PIN_NONBLOCK);
975 GEM_BUG_ON(cache->rq_size + RELOC_TAIL > PAGE_SIZE / sizeof(u32));
976 cmd = cache->rq_cmd + cache->rq_size;
977 *cmd++ = MI_ARB_CHECK;
979 *cmd++ = MI_BATCH_BUFFER_START_GEN8;
980 else if (cache->gen >= 6)
981 *cmd++ = MI_BATCH_BUFFER_START;
983 *cmd++ = MI_BATCH_BUFFER_START | MI_BATCH_GTT;
984 *cmd++ = lower_32_bits(batch->node.start);
985 *cmd++ = upper_32_bits(batch->node.start); /* Always 0 for gen<8 */
986 i915_gem_object_flush_map(cache->rq_vma->obj);
987 i915_gem_object_unpin_map(cache->rq_vma->obj);
988 cache->rq_vma = NULL;
990 err = intel_gt_buffer_pool_mark_active(pool, rq);
992 i915_vma_lock(batch);
993 err = i915_request_await_object(rq, batch->obj, false);
995 err = i915_vma_move_to_active(batch, rq, 0);
996 i915_vma_unlock(batch);
998 i915_vma_unpin(batch);
1002 cmd = i915_gem_object_pin_map(batch->obj,
1011 /* Return with batch mapping (cmd) still pinned */
1012 cache->rq_cmd = cmd;
1014 cache->rq_vma = batch;
1017 intel_gt_buffer_pool_put(pool);
1021 static unsigned int reloc_bb_flags(const struct reloc_cache *cache)
1023 return cache->gen > 5 ? 0 : I915_DISPATCH_SECURE;
1026 static int reloc_gpu_flush(struct reloc_cache *cache)
1028 struct i915_request *rq;
1031 rq = fetch_and_zero(&cache->rq);
1035 if (cache->rq_vma) {
1036 struct drm_i915_gem_object *obj = cache->rq_vma->obj;
1038 GEM_BUG_ON(cache->rq_size >= obj->base.size / sizeof(u32));
1039 cache->rq_cmd[cache->rq_size++] = MI_BATCH_BUFFER_END;
1041 __i915_gem_object_flush_map(obj,
1042 0, sizeof(u32) * cache->rq_size);
1043 i915_gem_object_unpin_map(obj);
1047 if (rq->engine->emit_init_breadcrumb)
1048 err = rq->engine->emit_init_breadcrumb(rq);
1050 err = rq->engine->emit_bb_start(rq,
1051 rq->batch->node.start,
1053 reloc_bb_flags(cache));
1055 i915_request_set_error_once(rq, err);
1057 intel_gt_chipset_flush(rq->engine->gt);
1058 i915_request_add(rq);
1063 static int reloc_move_to_gpu(struct i915_request *rq, struct i915_vma *vma)
1065 struct drm_i915_gem_object *obj = vma->obj;
1070 if (obj->cache_dirty & ~obj->cache_coherent)
1071 i915_gem_clflush_object(obj, 0);
1072 obj->write_domain = 0;
1074 err = i915_request_await_object(rq, vma->obj, true);
1076 err = i915_vma_move_to_active(vma, rq, EXEC_OBJECT_WRITE);
1078 i915_vma_unlock(vma);
1083 static int __reloc_gpu_alloc(struct i915_execbuffer *eb,
1084 struct intel_engine_cs *engine,
1087 struct reloc_cache *cache = &eb->reloc_cache;
1088 struct intel_gt_buffer_pool_node *pool;
1089 struct i915_request *rq;
1090 struct i915_vma *batch;
1094 pool = intel_gt_get_buffer_pool(engine->gt, PAGE_SIZE);
1096 return PTR_ERR(pool);
1098 cmd = i915_gem_object_pin_map(pool->obj,
1107 batch = i915_vma_instance(pool->obj, eb->context->vm, NULL);
1108 if (IS_ERR(batch)) {
1109 err = PTR_ERR(batch);
1113 err = i915_vma_pin(batch, 0, 0, PIN_USER | PIN_NONBLOCK);
1117 if (engine == eb->context->engine) {
1118 rq = i915_request_create(eb->context);
1120 struct intel_context *ce;
1122 ce = intel_context_create(engine);
1128 i915_vm_put(ce->vm);
1129 ce->vm = i915_vm_get(eb->context->vm);
1131 rq = intel_context_create_request(ce);
1132 intel_context_put(ce);
1139 err = intel_gt_buffer_pool_mark_active(pool, rq);
1143 i915_vma_lock(batch);
1144 err = i915_request_await_object(rq, batch->obj, false);
1146 err = i915_vma_move_to_active(batch, rq, 0);
1147 i915_vma_unlock(batch);
1152 i915_vma_unpin(batch);
1155 cache->rq_cmd = cmd;
1157 cache->rq_vma = batch;
1159 /* Return with batch mapping (cmd) still pinned */
1163 i915_request_set_error_once(rq, err);
1165 i915_request_add(rq);
1167 i915_vma_unpin(batch);
1169 i915_gem_object_unpin_map(pool->obj);
1171 intel_gt_buffer_pool_put(pool);
1175 static bool reloc_can_use_engine(const struct intel_engine_cs *engine)
1177 return engine->class != VIDEO_DECODE_CLASS || !IS_GEN(engine->i915, 6);
1180 static u32 *reloc_gpu(struct i915_execbuffer *eb,
1181 struct i915_vma *vma,
1184 struct reloc_cache *cache = &eb->reloc_cache;
1188 if (unlikely(!cache->rq)) {
1189 struct intel_engine_cs *engine = eb->engine;
1191 if (!reloc_can_use_engine(engine)) {
1192 engine = engine->gt->engine_class[COPY_ENGINE_CLASS][0];
1194 return ERR_PTR(-ENODEV);
1197 err = __reloc_gpu_alloc(eb, engine, len);
1199 return ERR_PTR(err);
1202 if (vma != cache->target) {
1203 err = reloc_move_to_gpu(cache->rq, vma);
1204 if (unlikely(err)) {
1205 i915_request_set_error_once(cache->rq, err);
1206 return ERR_PTR(err);
1209 cache->target = vma;
1212 if (unlikely(cache->rq_size + len >
1213 PAGE_SIZE / sizeof(u32) - RELOC_TAIL)) {
1214 err = reloc_gpu_chain(cache);
1215 if (unlikely(err)) {
1216 i915_request_set_error_once(cache->rq, err);
1217 return ERR_PTR(err);
1221 GEM_BUG_ON(cache->rq_size + len >= PAGE_SIZE / sizeof(u32));
1222 cmd = cache->rq_cmd + cache->rq_size;
1223 cache->rq_size += len;
1228 static unsigned long vma_phys_addr(struct i915_vma *vma, u32 offset)
1233 GEM_BUG_ON(vma->pages != vma->obj->mm.pages);
1235 page = i915_gem_object_get_page(vma->obj, offset >> PAGE_SHIFT);
1236 addr = PFN_PHYS(page_to_pfn(page));
1237 GEM_BUG_ON(overflows_type(addr, u32)); /* expected dma32 */
1239 return addr + offset_in_page(offset);
1242 static int __reloc_entry_gpu(struct i915_execbuffer *eb,
1243 struct i915_vma *vma,
1247 const unsigned int gen = eb->reloc_cache.gen;
1253 len = offset & 7 ? 8 : 5;
1259 batch = reloc_gpu(eb, vma, len);
1261 return PTR_ERR(batch);
1263 addr = gen8_canonical_addr(vma->node.start + offset);
1266 *batch++ = MI_STORE_DWORD_IMM_GEN4;
1267 *batch++ = lower_32_bits(addr);
1268 *batch++ = upper_32_bits(addr);
1269 *batch++ = lower_32_bits(target_addr);
1271 addr = gen8_canonical_addr(addr + 4);
1273 *batch++ = MI_STORE_DWORD_IMM_GEN4;
1274 *batch++ = lower_32_bits(addr);
1275 *batch++ = upper_32_bits(addr);
1276 *batch++ = upper_32_bits(target_addr);
1278 *batch++ = (MI_STORE_DWORD_IMM_GEN4 | (1 << 21)) + 1;
1279 *batch++ = lower_32_bits(addr);
1280 *batch++ = upper_32_bits(addr);
1281 *batch++ = lower_32_bits(target_addr);
1282 *batch++ = upper_32_bits(target_addr);
1284 } else if (gen >= 6) {
1285 *batch++ = MI_STORE_DWORD_IMM_GEN4;
1288 *batch++ = target_addr;
1289 } else if (IS_I965G(eb->i915)) {
1290 *batch++ = MI_STORE_DWORD_IMM_GEN4;
1292 *batch++ = vma_phys_addr(vma, offset);
1293 *batch++ = target_addr;
1294 } else if (gen >= 4) {
1295 *batch++ = MI_STORE_DWORD_IMM_GEN4 | MI_USE_GGTT;
1298 *batch++ = target_addr;
1299 } else if (gen >= 3 &&
1300 !(IS_I915G(eb->i915) || IS_I915GM(eb->i915))) {
1301 *batch++ = MI_STORE_DWORD_IMM | MI_MEM_VIRTUAL;
1303 *batch++ = target_addr;
1305 *batch++ = MI_STORE_DWORD_IMM;
1306 *batch++ = vma_phys_addr(vma, offset);
1307 *batch++ = target_addr;
1314 relocate_entry(struct i915_execbuffer *eb,
1315 struct i915_vma *vma,
1316 const struct drm_i915_gem_relocation_entry *reloc,
1317 const struct i915_vma *target)
1319 u64 target_addr = relocation_target(reloc, target);
1322 err = __reloc_entry_gpu(eb, vma, reloc->offset, target_addr);
1326 return target->node.start | UPDATE;
1330 eb_relocate_entry(struct i915_execbuffer *eb,
1332 const struct drm_i915_gem_relocation_entry *reloc)
1334 struct drm_i915_private *i915 = eb->i915;
1335 struct eb_vma *target;
1338 /* we've already hold a reference to all valid objects */
1339 target = eb_get_vma(eb, reloc->target_handle);
1340 if (unlikely(!target))
1343 /* Validate that the target is in a valid r/w GPU domain */
1344 if (unlikely(reloc->write_domain & (reloc->write_domain - 1))) {
1345 drm_dbg(&i915->drm, "reloc with multiple write domains: "
1346 "target %d offset %d "
1347 "read %08x write %08x",
1348 reloc->target_handle,
1349 (int) reloc->offset,
1350 reloc->read_domains,
1351 reloc->write_domain);
1354 if (unlikely((reloc->write_domain | reloc->read_domains)
1355 & ~I915_GEM_GPU_DOMAINS)) {
1356 drm_dbg(&i915->drm, "reloc with read/write non-GPU domains: "
1357 "target %d offset %d "
1358 "read %08x write %08x",
1359 reloc->target_handle,
1360 (int) reloc->offset,
1361 reloc->read_domains,
1362 reloc->write_domain);
1366 if (reloc->write_domain) {
1367 target->flags |= EXEC_OBJECT_WRITE;
1370 * Sandybridge PPGTT errata: We need a global gtt mapping
1371 * for MI and pipe_control writes because the gpu doesn't
1372 * properly redirect them through the ppgtt for non_secure
1375 if (reloc->write_domain == I915_GEM_DOMAIN_INSTRUCTION &&
1376 IS_GEN(eb->i915, 6)) {
1377 err = i915_vma_bind(target->vma,
1378 target->vma->obj->cache_level,
1386 * If the relocation already has the right value in it, no
1387 * more work needs to be done.
1389 if (gen8_canonical_addr(target->vma->node.start) == reloc->presumed_offset)
1392 /* Check that the relocation address is valid... */
1393 if (unlikely(reloc->offset >
1394 ev->vma->size - (eb->reloc_cache.use_64bit_reloc ? 8 : 4))) {
1395 drm_dbg(&i915->drm, "Relocation beyond object bounds: "
1396 "target %d offset %d size %d.\n",
1397 reloc->target_handle,
1399 (int)ev->vma->size);
1402 if (unlikely(reloc->offset & 3)) {
1403 drm_dbg(&i915->drm, "Relocation not 4-byte aligned: "
1404 "target %d offset %d.\n",
1405 reloc->target_handle,
1406 (int)reloc->offset);
1411 * If we write into the object, we need to force the synchronisation
1412 * barrier, either with an asynchronous clflush or if we executed the
1413 * patching using the GPU (though that should be serialised by the
1414 * timeline). To be completely sure, and since we are required to
1415 * do relocations we are already stalling, disable the user's opt
1416 * out of our synchronisation.
1418 ev->flags &= ~EXEC_OBJECT_ASYNC;
1420 /* and update the user's relocation entry */
1421 return relocate_entry(eb, ev->vma, reloc, target->vma);
1424 static int eb_relocate_vma(struct i915_execbuffer *eb, struct eb_vma *ev)
1426 #define N_RELOC(x) ((x) / sizeof(struct drm_i915_gem_relocation_entry))
1427 struct drm_i915_gem_relocation_entry stack[N_RELOC(512)];
1428 const struct drm_i915_gem_exec_object2 *entry = ev->exec;
1429 struct drm_i915_gem_relocation_entry __user *urelocs =
1430 u64_to_user_ptr(entry->relocs_ptr);
1431 unsigned long remain = entry->relocation_count;
1433 if (unlikely(remain > N_RELOC(ULONG_MAX)))
1437 * We must check that the entire relocation array is safe
1438 * to read. However, if the array is not writable the user loses
1439 * the updated relocation values.
1441 if (unlikely(!access_ok(urelocs, remain * sizeof(*urelocs))))
1445 struct drm_i915_gem_relocation_entry *r = stack;
1446 unsigned int count =
1447 min_t(unsigned long, remain, ARRAY_SIZE(stack));
1448 unsigned int copied;
1451 * This is the fast path and we cannot handle a pagefault
1452 * whilst holding the struct mutex lest the user pass in the
1453 * relocations contained within a mmaped bo. For in such a case
1454 * we, the page fault handler would call i915_gem_fault() and
1455 * we would try to acquire the struct mutex again. Obviously
1456 * this is bad and so lockdep complains vehemently.
1458 copied = __copy_from_user(r, urelocs, count * sizeof(r[0]));
1459 if (unlikely(copied))
1464 u64 offset = eb_relocate_entry(eb, ev, r);
1466 if (likely(offset == 0)) {
1467 } else if ((s64)offset < 0) {
1471 * Note that reporting an error now
1472 * leaves everything in an inconsistent
1473 * state as we have *already* changed
1474 * the relocation value inside the
1475 * object. As we have not changed the
1476 * reloc.presumed_offset or will not
1477 * change the execobject.offset, on the
1478 * call we may not rewrite the value
1479 * inside the object, leaving it
1480 * dangling and causing a GPU hang. Unless
1481 * userspace dynamically rebuilds the
1482 * relocations on each execbuf rather than
1483 * presume a static tree.
1485 * We did previously check if the relocations
1486 * were writable (access_ok), an error now
1487 * would be a strange race with mprotect,
1488 * having already demonstrated that we
1489 * can read from this userspace address.
1491 offset = gen8_canonical_addr(offset & ~UPDATE);
1493 &urelocs[r - stack].presumed_offset);
1495 } while (r++, --count);
1496 urelocs += ARRAY_SIZE(stack);
1502 static int eb_relocate(struct i915_execbuffer *eb)
1506 err = eb_lookup_vmas(eb);
1510 if (!list_empty(&eb->unbound)) {
1511 err = eb_reserve(eb);
1516 /* The objects are in their final locations, apply the relocations. */
1517 if (eb->args->flags & __EXEC_HAS_RELOC) {
1521 list_for_each_entry(ev, &eb->relocs, reloc_link) {
1522 err = eb_relocate_vma(eb, ev);
1527 flush = reloc_gpu_flush(&eb->reloc_cache);
1535 static int eb_move_to_gpu(struct i915_execbuffer *eb)
1537 const unsigned int count = eb->buffer_count;
1538 struct ww_acquire_ctx acquire;
1542 ww_acquire_init(&acquire, &reservation_ww_class);
1544 for (i = 0; i < count; i++) {
1545 struct eb_vma *ev = &eb->vma[i];
1546 struct i915_vma *vma = ev->vma;
1548 err = ww_mutex_lock_interruptible(&vma->resv->lock, &acquire);
1549 if (err == -EDEADLK) {
1554 ww_mutex_unlock(&eb->vma[j].vma->resv->lock);
1556 swap(eb->vma[i], eb->vma[j]);
1559 err = ww_mutex_lock_slow_interruptible(&vma->resv->lock,
1565 ww_acquire_done(&acquire);
1568 struct eb_vma *ev = &eb->vma[i];
1569 struct i915_vma *vma = ev->vma;
1570 unsigned int flags = ev->flags;
1571 struct drm_i915_gem_object *obj = vma->obj;
1573 assert_vma_held(vma);
1575 if (flags & EXEC_OBJECT_CAPTURE) {
1576 struct i915_capture_list *capture;
1578 capture = kmalloc(sizeof(*capture), GFP_KERNEL);
1580 capture->next = eb->request->capture_list;
1582 eb->request->capture_list = capture;
1587 * If the GPU is not _reading_ through the CPU cache, we need
1588 * to make sure that any writes (both previous GPU writes from
1589 * before a change in snooping levels and normal CPU writes)
1590 * caught in that cache are flushed to main memory.
1593 * obj->cache_dirty &&
1594 * !(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ)
1595 * but gcc's optimiser doesn't handle that as well and emits
1596 * two jumps instead of one. Maybe one day...
1598 if (unlikely(obj->cache_dirty & ~obj->cache_coherent)) {
1599 if (i915_gem_clflush_object(obj, 0))
1600 flags &= ~EXEC_OBJECT_ASYNC;
1603 if (err == 0 && !(flags & EXEC_OBJECT_ASYNC)) {
1604 err = i915_request_await_object
1605 (eb->request, obj, flags & EXEC_OBJECT_WRITE);
1609 err = i915_vma_move_to_active(vma, eb->request, flags);
1611 i915_vma_unlock(vma);
1612 eb_unreserve_vma(ev);
1614 ww_acquire_fini(&acquire);
1616 eb_vma_array_put(fetch_and_zero(&eb->array));
1621 /* Unconditionally flush any chipset caches (for streaming writes). */
1622 intel_gt_chipset_flush(eb->engine->gt);
1626 i915_request_set_error_once(eb->request, err);
1630 static int i915_gem_check_execbuffer(struct drm_i915_gem_execbuffer2 *exec)
1632 if (exec->flags & __I915_EXEC_ILLEGAL_FLAGS)
1635 /* Kernel clipping was a DRI1 misfeature */
1636 if (!(exec->flags & (I915_EXEC_FENCE_ARRAY |
1637 I915_EXEC_USE_EXTENSIONS))) {
1638 if (exec->num_cliprects || exec->cliprects_ptr)
1642 if (exec->DR4 == 0xffffffff) {
1643 DRM_DEBUG("UXA submitting garbage DR4, fixing up\n");
1646 if (exec->DR1 || exec->DR4)
1649 if ((exec->batch_start_offset | exec->batch_len) & 0x7)
1655 static int i915_reset_gen7_sol_offsets(struct i915_request *rq)
1660 if (!IS_GEN(rq->engine->i915, 7) || rq->engine->id != RCS0) {
1661 drm_dbg(&rq->engine->i915->drm, "sol reset is gen7/rcs only\n");
1665 cs = intel_ring_begin(rq, 4 * 2 + 2);
1669 *cs++ = MI_LOAD_REGISTER_IMM(4);
1670 for (i = 0; i < 4; i++) {
1671 *cs++ = i915_mmio_reg_offset(GEN7_SO_WRITE_OFFSET(i));
1675 intel_ring_advance(rq, cs);
1680 static struct i915_vma *
1681 shadow_batch_pin(struct drm_i915_gem_object *obj,
1682 struct i915_address_space *vm,
1685 struct i915_vma *vma;
1688 vma = i915_vma_instance(obj, vm, NULL);
1692 err = i915_vma_pin(vma, 0, 0, flags);
1694 return ERR_PTR(err);
1699 struct eb_parse_work {
1700 struct dma_fence_work base;
1701 struct intel_engine_cs *engine;
1702 struct i915_vma *batch;
1703 struct i915_vma *shadow;
1704 struct i915_vma *trampoline;
1705 unsigned int batch_offset;
1706 unsigned int batch_length;
1709 static int __eb_parse(struct dma_fence_work *work)
1711 struct eb_parse_work *pw = container_of(work, typeof(*pw), base);
1713 return intel_engine_cmd_parser(pw->engine,
1721 static void __eb_parse_release(struct dma_fence_work *work)
1723 struct eb_parse_work *pw = container_of(work, typeof(*pw), base);
1726 i915_active_release(&pw->trampoline->active);
1727 i915_active_release(&pw->shadow->active);
1728 i915_active_release(&pw->batch->active);
1731 static const struct dma_fence_work_ops eb_parse_ops = {
1734 .release = __eb_parse_release,
1738 __parser_mark_active(struct i915_vma *vma,
1739 struct intel_timeline *tl,
1740 struct dma_fence *fence)
1742 struct intel_gt_buffer_pool_node *node = vma->private;
1744 return i915_active_ref(&node->active, tl->fence_context, fence);
1748 parser_mark_active(struct eb_parse_work *pw, struct intel_timeline *tl)
1752 mutex_lock(&tl->mutex);
1754 err = __parser_mark_active(pw->shadow, tl, &pw->base.dma);
1758 if (pw->trampoline) {
1759 err = __parser_mark_active(pw->trampoline, tl, &pw->base.dma);
1765 mutex_unlock(&tl->mutex);
1769 static int eb_parse_pipeline(struct i915_execbuffer *eb,
1770 struct i915_vma *shadow,
1771 struct i915_vma *trampoline)
1773 struct eb_parse_work *pw;
1776 pw = kzalloc(sizeof(*pw), GFP_KERNEL);
1780 err = i915_active_acquire(&eb->batch->vma->active);
1784 err = i915_active_acquire(&shadow->active);
1789 err = i915_active_acquire(&trampoline->active);
1794 dma_fence_work_init(&pw->base, &eb_parse_ops);
1796 pw->engine = eb->engine;
1797 pw->batch = eb->batch->vma;
1798 pw->batch_offset = eb->batch_start_offset;
1799 pw->batch_length = eb->batch_len;
1800 pw->shadow = shadow;
1801 pw->trampoline = trampoline;
1803 /* Mark active refs early for this worker, in case we get interrupted */
1804 err = parser_mark_active(pw, eb->context->timeline);
1808 err = dma_resv_lock_interruptible(pw->batch->resv, NULL);
1812 err = dma_resv_reserve_shared(pw->batch->resv, 1);
1814 goto err_commit_unlock;
1816 /* Wait for all writes (and relocs) into the batch to complete */
1817 err = i915_sw_fence_await_reservation(&pw->base.chain,
1818 pw->batch->resv, NULL, false,
1821 goto err_commit_unlock;
1823 /* Keep the batch alive and unwritten as we parse */
1824 dma_resv_add_shared_fence(pw->batch->resv, &pw->base.dma);
1826 dma_resv_unlock(pw->batch->resv);
1828 /* Force execution to wait for completion of the parser */
1829 dma_resv_lock(shadow->resv, NULL);
1830 dma_resv_add_excl_fence(shadow->resv, &pw->base.dma);
1831 dma_resv_unlock(shadow->resv);
1833 dma_fence_work_commit_imm(&pw->base);
1837 dma_resv_unlock(pw->batch->resv);
1839 i915_sw_fence_set_error_once(&pw->base.chain, err);
1840 dma_fence_work_commit_imm(&pw->base);
1844 i915_active_release(&shadow->active);
1846 i915_active_release(&eb->batch->vma->active);
1852 static int eb_parse(struct i915_execbuffer *eb)
1854 struct drm_i915_private *i915 = eb->i915;
1855 struct intel_gt_buffer_pool_node *pool;
1856 struct i915_vma *shadow, *trampoline;
1860 if (!eb_use_cmdparser(eb))
1863 len = eb->batch_len;
1864 if (!CMDPARSER_USES_GGTT(eb->i915)) {
1866 * ppGTT backed shadow buffers must be mapped RO, to prevent
1867 * post-scan tampering
1869 if (!eb->context->vm->has_read_only) {
1871 "Cannot prevent post-scan tampering without RO capable vm\n");
1875 len += I915_CMD_PARSER_TRAMPOLINE_SIZE;
1878 pool = intel_gt_get_buffer_pool(eb->engine->gt, len);
1880 return PTR_ERR(pool);
1882 shadow = shadow_batch_pin(pool->obj, eb->context->vm, PIN_USER);
1883 if (IS_ERR(shadow)) {
1884 err = PTR_ERR(shadow);
1887 i915_gem_object_set_readonly(shadow->obj);
1888 shadow->private = pool;
1891 if (CMDPARSER_USES_GGTT(eb->i915)) {
1892 trampoline = shadow;
1894 shadow = shadow_batch_pin(pool->obj,
1895 &eb->engine->gt->ggtt->vm,
1897 if (IS_ERR(shadow)) {
1898 err = PTR_ERR(shadow);
1899 shadow = trampoline;
1902 shadow->private = pool;
1904 eb->batch_flags |= I915_DISPATCH_SECURE;
1907 err = eb_parse_pipeline(eb, shadow, trampoline);
1909 goto err_trampoline;
1911 eb->vma[eb->buffer_count].vma = i915_vma_get(shadow);
1912 eb->vma[eb->buffer_count].flags = __EXEC_OBJECT_HAS_PIN;
1913 eb->batch = &eb->vma[eb->buffer_count++];
1914 eb->vma[eb->buffer_count].vma = NULL;
1916 eb->trampoline = trampoline;
1917 eb->batch_start_offset = 0;
1923 i915_vma_unpin(trampoline);
1925 i915_vma_unpin(shadow);
1927 intel_gt_buffer_pool_put(pool);
1931 static int eb_submit(struct i915_execbuffer *eb, struct i915_vma *batch)
1935 err = eb_move_to_gpu(eb);
1939 if (eb->args->flags & I915_EXEC_GEN7_SOL_RESET) {
1940 err = i915_reset_gen7_sol_offsets(eb->request);
1946 * After we completed waiting for other engines (using HW semaphores)
1947 * then we can signal that this request/batch is ready to run. This
1948 * allows us to determine if the batch is still waiting on the GPU
1949 * or actually running by checking the breadcrumb.
1951 if (eb->engine->emit_init_breadcrumb) {
1952 err = eb->engine->emit_init_breadcrumb(eb->request);
1957 err = eb->engine->emit_bb_start(eb->request,
1959 eb->batch_start_offset,
1965 if (eb->trampoline) {
1966 GEM_BUG_ON(eb->batch_start_offset);
1967 err = eb->engine->emit_bb_start(eb->request,
1968 eb->trampoline->node.start +
1975 if (intel_context_nopreempt(eb->context))
1976 __set_bit(I915_FENCE_FLAG_NOPREEMPT, &eb->request->fence.flags);
1981 static int num_vcs_engines(const struct drm_i915_private *i915)
1983 return hweight64(VDBOX_MASK(&i915->gt));
1987 * Find one BSD ring to dispatch the corresponding BSD command.
1988 * The engine index is returned.
1991 gen8_dispatch_bsd_engine(struct drm_i915_private *dev_priv,
1992 struct drm_file *file)
1994 struct drm_i915_file_private *file_priv = file->driver_priv;
1996 /* Check whether the file_priv has already selected one ring. */
1997 if ((int)file_priv->bsd_engine < 0)
1998 file_priv->bsd_engine =
1999 get_random_int() % num_vcs_engines(dev_priv);
2001 return file_priv->bsd_engine;
2004 static const enum intel_engine_id user_ring_map[] = {
2005 [I915_EXEC_DEFAULT] = RCS0,
2006 [I915_EXEC_RENDER] = RCS0,
2007 [I915_EXEC_BLT] = BCS0,
2008 [I915_EXEC_BSD] = VCS0,
2009 [I915_EXEC_VEBOX] = VECS0
2012 static struct i915_request *eb_throttle(struct intel_context *ce)
2014 struct intel_ring *ring = ce->ring;
2015 struct intel_timeline *tl = ce->timeline;
2016 struct i915_request *rq;
2019 * Completely unscientific finger-in-the-air estimates for suitable
2020 * maximum user request size (to avoid blocking) and then backoff.
2022 if (intel_ring_update_space(ring) >= PAGE_SIZE)
2026 * Find a request that after waiting upon, there will be at least half
2027 * the ring available. The hysteresis allows us to compete for the
2028 * shared ring and should mean that we sleep less often prior to
2029 * claiming our resources, but not so long that the ring completely
2030 * drains before we can submit our next request.
2032 list_for_each_entry(rq, &tl->requests, link) {
2033 if (rq->ring != ring)
2036 if (__intel_ring_space(rq->postfix,
2037 ring->emit, ring->size) > ring->size / 2)
2040 if (&rq->link == &tl->requests)
2041 return NULL; /* weird, we will check again later for real */
2043 return i915_request_get(rq);
2046 static int __eb_pin_engine(struct i915_execbuffer *eb, struct intel_context *ce)
2048 struct intel_timeline *tl;
2049 struct i915_request *rq;
2053 * ABI: Before userspace accesses the GPU (e.g. execbuffer), report
2054 * EIO if the GPU is already wedged.
2056 err = intel_gt_terminally_wedged(ce->engine->gt);
2060 if (unlikely(intel_context_is_banned(ce)))
2064 * Pinning the contexts may generate requests in order to acquire
2065 * GGTT space, so do this first before we reserve a seqno for
2068 err = intel_context_pin(ce);
2073 * Take a local wakeref for preparing to dispatch the execbuf as
2074 * we expect to access the hardware fairly frequently in the
2075 * process, and require the engine to be kept awake between accesses.
2076 * Upon dispatch, we acquire another prolonged wakeref that we hold
2077 * until the timeline is idle, which in turn releases the wakeref
2078 * taken on the engine, and the parent device.
2080 tl = intel_context_timeline_lock(ce);
2086 intel_context_enter(ce);
2087 rq = eb_throttle(ce);
2089 intel_context_timeline_unlock(tl);
2092 bool nonblock = eb->file->filp->f_flags & O_NONBLOCK;
2095 timeout = MAX_SCHEDULE_TIMEOUT;
2099 timeout = i915_request_wait(rq,
2100 I915_WAIT_INTERRUPTIBLE,
2102 i915_request_put(rq);
2105 err = nonblock ? -EWOULDBLOCK : timeout;
2110 eb->engine = ce->engine;
2115 mutex_lock(&tl->mutex);
2116 intel_context_exit(ce);
2117 intel_context_timeline_unlock(tl);
2119 intel_context_unpin(ce);
2123 static void eb_unpin_engine(struct i915_execbuffer *eb)
2125 struct intel_context *ce = eb->context;
2126 struct intel_timeline *tl = ce->timeline;
2128 mutex_lock(&tl->mutex);
2129 intel_context_exit(ce);
2130 mutex_unlock(&tl->mutex);
2132 intel_context_unpin(ce);
2136 eb_select_legacy_ring(struct i915_execbuffer *eb,
2137 struct drm_file *file,
2138 struct drm_i915_gem_execbuffer2 *args)
2140 struct drm_i915_private *i915 = eb->i915;
2141 unsigned int user_ring_id = args->flags & I915_EXEC_RING_MASK;
2143 if (user_ring_id != I915_EXEC_BSD &&
2144 (args->flags & I915_EXEC_BSD_MASK)) {
2146 "execbuf with non bsd ring but with invalid "
2147 "bsd dispatch flags: %d\n", (int)(args->flags));
2151 if (user_ring_id == I915_EXEC_BSD && num_vcs_engines(i915) > 1) {
2152 unsigned int bsd_idx = args->flags & I915_EXEC_BSD_MASK;
2154 if (bsd_idx == I915_EXEC_BSD_DEFAULT) {
2155 bsd_idx = gen8_dispatch_bsd_engine(i915, file);
2156 } else if (bsd_idx >= I915_EXEC_BSD_RING1 &&
2157 bsd_idx <= I915_EXEC_BSD_RING2) {
2158 bsd_idx >>= I915_EXEC_BSD_SHIFT;
2162 "execbuf with unknown bsd ring: %u\n",
2167 return _VCS(bsd_idx);
2170 if (user_ring_id >= ARRAY_SIZE(user_ring_map)) {
2171 drm_dbg(&i915->drm, "execbuf with unknown ring: %u\n",
2176 return user_ring_map[user_ring_id];
2180 eb_pin_engine(struct i915_execbuffer *eb,
2181 struct drm_file *file,
2182 struct drm_i915_gem_execbuffer2 *args)
2184 struct intel_context *ce;
2188 if (i915_gem_context_user_engines(eb->gem_context))
2189 idx = args->flags & I915_EXEC_RING_MASK;
2191 idx = eb_select_legacy_ring(eb, file, args);
2193 ce = i915_gem_context_get_engine(eb->gem_context, idx);
2197 err = __eb_pin_engine(eb, ce);
2198 intel_context_put(ce);
2204 __free_fence_array(struct eb_fence *fences, unsigned int n)
2207 drm_syncobj_put(ptr_mask_bits(fences[n].syncobj, 2));
2208 dma_fence_put(fences[n].dma_fence);
2209 kfree(fences[n].chain_fence);
2215 add_timeline_fence_array(struct i915_execbuffer *eb,
2216 const struct drm_i915_gem_execbuffer_ext_timeline_fences *timeline_fences)
2218 struct drm_i915_gem_exec_fence __user *user_fences;
2219 u64 __user *user_values;
2224 nfences = timeline_fences->fence_count;
2228 /* Check multiplication overflow for access_ok() and kvmalloc_array() */
2229 BUILD_BUG_ON(sizeof(size_t) > sizeof(unsigned long));
2230 if (nfences > min_t(unsigned long,
2231 ULONG_MAX / sizeof(*user_fences),
2232 SIZE_MAX / sizeof(*f)) - eb->num_fences)
2235 user_fences = u64_to_user_ptr(timeline_fences->handles_ptr);
2236 if (!access_ok(user_fences, nfences * sizeof(*user_fences)))
2239 user_values = u64_to_user_ptr(timeline_fences->values_ptr);
2240 if (!access_ok(user_values, nfences * sizeof(*user_values)))
2243 f = krealloc(eb->fences,
2244 (eb->num_fences + nfences) * sizeof(*f),
2245 __GFP_NOWARN | GFP_KERNEL);
2250 f += eb->num_fences;
2252 BUILD_BUG_ON(~(ARCH_KMALLOC_MINALIGN - 1) &
2253 ~__I915_EXEC_FENCE_UNKNOWN_FLAGS);
2256 struct drm_i915_gem_exec_fence user_fence;
2257 struct drm_syncobj *syncobj;
2258 struct dma_fence *fence = NULL;
2261 if (__copy_from_user(&user_fence,
2263 sizeof(user_fence)))
2266 if (user_fence.flags & __I915_EXEC_FENCE_UNKNOWN_FLAGS)
2269 if (__get_user(point, user_values++))
2272 syncobj = drm_syncobj_find(eb->file, user_fence.handle);
2274 DRM_DEBUG("Invalid syncobj handle provided\n");
2278 fence = drm_syncobj_fence_get(syncobj);
2280 if (!fence && user_fence.flags &&
2281 !(user_fence.flags & I915_EXEC_FENCE_SIGNAL)) {
2282 DRM_DEBUG("Syncobj handle has no fence\n");
2283 drm_syncobj_put(syncobj);
2288 err = dma_fence_chain_find_seqno(&fence, point);
2290 if (err && !(user_fence.flags & I915_EXEC_FENCE_SIGNAL)) {
2291 DRM_DEBUG("Syncobj handle missing requested point %llu\n", point);
2292 dma_fence_put(fence);
2293 drm_syncobj_put(syncobj);
2298 * A point might have been signaled already and
2299 * garbage collected from the timeline. In this case
2300 * just ignore the point and carry on.
2302 if (!fence && !(user_fence.flags & I915_EXEC_FENCE_SIGNAL)) {
2303 drm_syncobj_put(syncobj);
2308 * For timeline syncobjs we need to preallocate chains for
2311 if (point != 0 && user_fence.flags & I915_EXEC_FENCE_SIGNAL) {
2313 * Waiting and signaling the same point (when point !=
2314 * 0) would break the timeline.
2316 if (user_fence.flags & I915_EXEC_FENCE_WAIT) {
2317 DRM_DEBUG("Trying to wait & signal the same timeline point.\n");
2318 dma_fence_put(fence);
2319 drm_syncobj_put(syncobj);
2324 kmalloc(sizeof(*f->chain_fence),
2326 if (!f->chain_fence) {
2327 drm_syncobj_put(syncobj);
2328 dma_fence_put(fence);
2332 f->chain_fence = NULL;
2335 f->syncobj = ptr_pack_bits(syncobj, user_fence.flags, 2);
2336 f->dma_fence = fence;
2345 static int add_fence_array(struct i915_execbuffer *eb)
2347 struct drm_i915_gem_execbuffer2 *args = eb->args;
2348 struct drm_i915_gem_exec_fence __user *user;
2349 unsigned long num_fences = args->num_cliprects;
2352 if (!(args->flags & I915_EXEC_FENCE_ARRAY))
2358 /* Check multiplication overflow for access_ok() and kvmalloc_array() */
2359 BUILD_BUG_ON(sizeof(size_t) > sizeof(unsigned long));
2360 if (num_fences > min_t(unsigned long,
2361 ULONG_MAX / sizeof(*user),
2362 SIZE_MAX / sizeof(*f) - eb->num_fences))
2365 user = u64_to_user_ptr(args->cliprects_ptr);
2366 if (!access_ok(user, num_fences * sizeof(*user)))
2369 f = krealloc(eb->fences,
2370 (eb->num_fences + num_fences) * sizeof(*f),
2371 __GFP_NOWARN | GFP_KERNEL);
2376 f += eb->num_fences;
2377 while (num_fences--) {
2378 struct drm_i915_gem_exec_fence user_fence;
2379 struct drm_syncobj *syncobj;
2380 struct dma_fence *fence = NULL;
2382 if (__copy_from_user(&user_fence, user++, sizeof(user_fence)))
2385 if (user_fence.flags & __I915_EXEC_FENCE_UNKNOWN_FLAGS)
2388 syncobj = drm_syncobj_find(eb->file, user_fence.handle);
2390 DRM_DEBUG("Invalid syncobj handle provided\n");
2394 if (user_fence.flags & I915_EXEC_FENCE_WAIT) {
2395 fence = drm_syncobj_fence_get(syncobj);
2397 DRM_DEBUG("Syncobj handle has no fence\n");
2398 drm_syncobj_put(syncobj);
2403 BUILD_BUG_ON(~(ARCH_KMALLOC_MINALIGN - 1) &
2404 ~__I915_EXEC_FENCE_UNKNOWN_FLAGS);
2406 f->syncobj = ptr_pack_bits(syncobj, user_fence.flags, 2);
2407 f->dma_fence = fence;
2409 f->chain_fence = NULL;
2417 static void put_fence_array(struct eb_fence *fences, int num_fences)
2420 __free_fence_array(fences, num_fences);
2424 await_fence_array(struct i915_execbuffer *eb)
2429 for (n = 0; n < eb->num_fences; n++) {
2430 struct drm_syncobj *syncobj;
2433 syncobj = ptr_unpack_bits(eb->fences[n].syncobj, &flags, 2);
2435 if (!eb->fences[n].dma_fence)
2438 err = i915_request_await_dma_fence(eb->request,
2439 eb->fences[n].dma_fence);
2447 static void signal_fence_array(const struct i915_execbuffer *eb)
2449 struct dma_fence * const fence = &eb->request->fence;
2452 for (n = 0; n < eb->num_fences; n++) {
2453 struct drm_syncobj *syncobj;
2456 syncobj = ptr_unpack_bits(eb->fences[n].syncobj, &flags, 2);
2457 if (!(flags & I915_EXEC_FENCE_SIGNAL))
2460 if (eb->fences[n].chain_fence) {
2461 drm_syncobj_add_point(syncobj,
2462 eb->fences[n].chain_fence,
2464 eb->fences[n].value);
2466 * The chain's ownership is transferred to the
2469 eb->fences[n].chain_fence = NULL;
2471 drm_syncobj_replace_fence(syncobj, fence);
2477 parse_timeline_fences(struct i915_user_extension __user *ext, void *data)
2479 struct i915_execbuffer *eb = data;
2480 struct drm_i915_gem_execbuffer_ext_timeline_fences timeline_fences;
2482 if (copy_from_user(&timeline_fences, ext, sizeof(timeline_fences)))
2485 return add_timeline_fence_array(eb, &timeline_fences);
2488 static void retire_requests(struct intel_timeline *tl, struct i915_request *end)
2490 struct i915_request *rq, *rn;
2492 list_for_each_entry_safe(rq, rn, &tl->requests, link)
2493 if (rq == end || !i915_request_retire(rq))
2497 static void eb_request_add(struct i915_execbuffer *eb)
2499 struct i915_request *rq = eb->request;
2500 struct intel_timeline * const tl = i915_request_timeline(rq);
2501 struct i915_sched_attr attr = {};
2502 struct i915_request *prev;
2504 lockdep_assert_held(&tl->mutex);
2505 lockdep_unpin_lock(&tl->mutex, rq->cookie);
2507 trace_i915_request_add(rq);
2509 prev = __i915_request_commit(rq);
2511 /* Check that the context wasn't destroyed before submission */
2512 if (likely(!intel_context_is_closed(eb->context))) {
2513 attr = eb->gem_context->sched;
2515 /* Serialise with context_close via the add_to_timeline */
2516 i915_request_set_error_once(rq, -ENOENT);
2517 __i915_request_skip(rq);
2520 __i915_request_queue(rq, &attr);
2522 /* Try to clean up the client's timeline after submitting the request */
2524 retire_requests(tl, prev);
2526 mutex_unlock(&tl->mutex);
2529 static const i915_user_extension_fn execbuf_extensions[] = {
2530 [DRM_I915_GEM_EXECBUFFER_EXT_TIMELINE_FENCES] = parse_timeline_fences,
2534 parse_execbuf2_extensions(struct drm_i915_gem_execbuffer2 *args,
2535 struct i915_execbuffer *eb)
2537 if (!(args->flags & I915_EXEC_USE_EXTENSIONS))
2540 /* The execbuf2 extension mechanism reuses cliprects_ptr. So we cannot
2541 * have another flag also using it at the same time.
2543 if (eb->args->flags & I915_EXEC_FENCE_ARRAY)
2546 if (args->num_cliprects != 0)
2549 return i915_user_extensions(u64_to_user_ptr(args->cliprects_ptr),
2551 ARRAY_SIZE(execbuf_extensions),
2556 i915_gem_do_execbuffer(struct drm_device *dev,
2557 struct drm_file *file,
2558 struct drm_i915_gem_execbuffer2 *args,
2559 struct drm_i915_gem_exec_object2 *exec)
2561 struct drm_i915_private *i915 = to_i915(dev);
2562 struct i915_execbuffer eb;
2563 struct dma_fence *in_fence = NULL;
2564 struct sync_file *out_fence = NULL;
2565 struct i915_vma *batch;
2566 int out_fence_fd = -1;
2569 BUILD_BUG_ON(__EXEC_INTERNAL_FLAGS & ~__I915_EXEC_ILLEGAL_FLAGS);
2570 BUILD_BUG_ON(__EXEC_OBJECT_INTERNAL_FLAGS &
2571 ~__EXEC_OBJECT_UNKNOWN_FLAGS);
2576 if (!(args->flags & I915_EXEC_NO_RELOC))
2577 args->flags |= __EXEC_HAS_RELOC;
2581 eb.invalid_flags = __EXEC_OBJECT_UNKNOWN_FLAGS;
2582 reloc_cache_init(&eb.reloc_cache, eb.i915);
2584 eb.buffer_count = args->buffer_count;
2585 eb.batch_start_offset = args->batch_start_offset;
2586 eb.batch_len = args->batch_len;
2587 eb.trampoline = NULL;
2593 if (args->flags & I915_EXEC_SECURE) {
2594 if (INTEL_GEN(i915) >= 11)
2597 /* Return -EPERM to trigger fallback code on old binaries. */
2598 if (!HAS_SECURE_BATCHES(i915))
2601 if (!drm_is_current_master(file) || !capable(CAP_SYS_ADMIN))
2604 eb.batch_flags |= I915_DISPATCH_SECURE;
2606 if (args->flags & I915_EXEC_IS_PINNED)
2607 eb.batch_flags |= I915_DISPATCH_PINNED;
2609 err = parse_execbuf2_extensions(args, &eb);
2613 err = add_fence_array(&eb);
2617 #define IN_FENCES (I915_EXEC_FENCE_IN | I915_EXEC_FENCE_SUBMIT)
2618 if (args->flags & IN_FENCES) {
2619 if ((args->flags & IN_FENCES) == IN_FENCES)
2622 in_fence = sync_file_get_fence(lower_32_bits(args->rsvd2));
2630 if (args->flags & I915_EXEC_FENCE_OUT) {
2631 out_fence_fd = get_unused_fd_flags(O_CLOEXEC);
2632 if (out_fence_fd < 0) {
2638 err = eb_create(&eb);
2642 GEM_BUG_ON(!eb.lut_size);
2644 err = eb_select_context(&eb);
2648 err = eb_pin_engine(&eb, file, args);
2652 err = eb_relocate(&eb);
2655 * If the user expects the execobject.offset and
2656 * reloc.presumed_offset to be an exact match,
2657 * as for using NO_RELOC, then we cannot update
2658 * the execobject.offset until we have completed
2661 args->flags &= ~__EXEC_HAS_RELOC;
2665 if (unlikely(eb.batch->flags & EXEC_OBJECT_WRITE)) {
2667 "Attempting to use self-modifying batch buffer\n");
2672 if (range_overflows_t(u64,
2673 eb.batch_start_offset, eb.batch_len,
2674 eb.batch->vma->size)) {
2675 drm_dbg(&i915->drm, "Attempting to use out-of-bounds batch\n");
2680 if (eb.batch_len == 0)
2681 eb.batch_len = eb.batch->vma->size - eb.batch_start_offset;
2683 err = eb_parse(&eb);
2688 * snb/ivb/vlv conflate the "batch in ppgtt" bit with the "non-secure
2689 * batch" bit. Hence we need to pin secure batches into the global gtt.
2690 * hsw should have this fixed, but bdw mucks it up again. */
2691 batch = eb.batch->vma;
2692 if (eb.batch_flags & I915_DISPATCH_SECURE) {
2693 struct i915_vma *vma;
2696 * So on first glance it looks freaky that we pin the batch here
2697 * outside of the reservation loop. But:
2698 * - The batch is already pinned into the relevant ppgtt, so we
2699 * already have the backing storage fully allocated.
2700 * - No other BO uses the global gtt (well contexts, but meh),
2701 * so we don't really have issues with multiple objects not
2702 * fitting due to fragmentation.
2703 * So this is actually safe.
2705 vma = i915_gem_object_ggtt_pin(batch->obj, NULL, 0, 0, 0);
2714 /* All GPU relocation batches must be submitted prior to the user rq */
2715 GEM_BUG_ON(eb.reloc_cache.rq);
2717 /* Allocate a request for this batch buffer nice and early. */
2718 eb.request = i915_request_create(eb.context);
2719 if (IS_ERR(eb.request)) {
2720 err = PTR_ERR(eb.request);
2721 goto err_batch_unpin;
2725 if (args->flags & I915_EXEC_FENCE_SUBMIT)
2726 err = i915_request_await_execution(eb.request,
2728 eb.engine->bond_execute);
2730 err = i915_request_await_dma_fence(eb.request,
2737 err = await_fence_array(&eb);
2742 if (out_fence_fd != -1) {
2743 out_fence = sync_file_create(&eb.request->fence);
2751 * Whilst this request exists, batch_obj will be on the
2752 * active_list, and so will hold the active reference. Only when this
2753 * request is retired will the the batch_obj be moved onto the
2754 * inactive_list and lose its active reference. Hence we do not need
2755 * to explicitly hold another reference here.
2757 eb.request->batch = batch;
2759 intel_gt_buffer_pool_mark_active(batch->private, eb.request);
2761 trace_i915_request_queue(eb.request, eb.batch_flags);
2762 err = eb_submit(&eb, batch);
2764 i915_request_get(eb.request);
2765 eb_request_add(&eb);
2768 signal_fence_array(&eb);
2772 fd_install(out_fence_fd, out_fence->file);
2773 args->rsvd2 &= GENMASK_ULL(31, 0); /* keep in-fence */
2774 args->rsvd2 |= (u64)out_fence_fd << 32;
2777 fput(out_fence->file);
2780 i915_request_put(eb.request);
2783 if (eb.batch_flags & I915_DISPATCH_SECURE)
2784 i915_vma_unpin(batch);
2787 intel_gt_buffer_pool_put(batch->private);
2790 i915_vma_unpin(eb.trampoline);
2791 eb_unpin_engine(&eb);
2793 i915_gem_context_put(eb.gem_context);
2797 if (out_fence_fd != -1)
2798 put_unused_fd(out_fence_fd);
2800 dma_fence_put(in_fence);
2802 put_fence_array(eb.fences, eb.num_fences);
2806 static size_t eb_element_size(void)
2808 return sizeof(struct drm_i915_gem_exec_object2);
2811 static bool check_buffer_count(size_t count)
2813 const size_t sz = eb_element_size();
2816 * When using LUT_HANDLE, we impose a limit of INT_MAX for the lookup
2817 * array size (see eb_create()). Otherwise, we can accept an array as
2818 * large as can be addressed (though use large arrays at your peril)!
2821 return !(count < 1 || count > INT_MAX || count > SIZE_MAX / sz - 1);
2825 * Legacy execbuffer just creates an exec2 list from the original exec object
2826 * list array and passes it to the real function.
2829 i915_gem_execbuffer_ioctl(struct drm_device *dev, void *data,
2830 struct drm_file *file)
2832 struct drm_i915_private *i915 = to_i915(dev);
2833 struct drm_i915_gem_execbuffer *args = data;
2834 struct drm_i915_gem_execbuffer2 exec2;
2835 struct drm_i915_gem_exec_object *exec_list = NULL;
2836 struct drm_i915_gem_exec_object2 *exec2_list = NULL;
2837 const size_t count = args->buffer_count;
2841 if (!check_buffer_count(count)) {
2842 drm_dbg(&i915->drm, "execbuf2 with %zd buffers\n", count);
2846 exec2.buffers_ptr = args->buffers_ptr;
2847 exec2.buffer_count = args->buffer_count;
2848 exec2.batch_start_offset = args->batch_start_offset;
2849 exec2.batch_len = args->batch_len;
2850 exec2.DR1 = args->DR1;
2851 exec2.DR4 = args->DR4;
2852 exec2.num_cliprects = args->num_cliprects;
2853 exec2.cliprects_ptr = args->cliprects_ptr;
2854 exec2.flags = I915_EXEC_RENDER;
2855 i915_execbuffer2_set_context_id(exec2, 0);
2857 err = i915_gem_check_execbuffer(&exec2);
2861 /* Copy in the exec list from userland */
2862 exec_list = kvmalloc_array(count, sizeof(*exec_list),
2863 __GFP_NOWARN | GFP_KERNEL);
2864 exec2_list = kvmalloc_array(count, eb_element_size(),
2865 __GFP_NOWARN | GFP_KERNEL);
2866 if (exec_list == NULL || exec2_list == NULL) {
2868 "Failed to allocate exec list for %d buffers\n",
2869 args->buffer_count);
2874 err = copy_from_user(exec_list,
2875 u64_to_user_ptr(args->buffers_ptr),
2876 sizeof(*exec_list) * count);
2878 drm_dbg(&i915->drm, "copy %d exec entries failed %d\n",
2879 args->buffer_count, err);
2885 for (i = 0; i < args->buffer_count; i++) {
2886 exec2_list[i].handle = exec_list[i].handle;
2887 exec2_list[i].relocation_count = exec_list[i].relocation_count;
2888 exec2_list[i].relocs_ptr = exec_list[i].relocs_ptr;
2889 exec2_list[i].alignment = exec_list[i].alignment;
2890 exec2_list[i].offset = exec_list[i].offset;
2891 if (INTEL_GEN(to_i915(dev)) < 4)
2892 exec2_list[i].flags = EXEC_OBJECT_NEEDS_FENCE;
2894 exec2_list[i].flags = 0;
2897 err = i915_gem_do_execbuffer(dev, file, &exec2, exec2_list);
2898 if (exec2.flags & __EXEC_HAS_RELOC) {
2899 struct drm_i915_gem_exec_object __user *user_exec_list =
2900 u64_to_user_ptr(args->buffers_ptr);
2902 /* Copy the new buffer offsets back to the user's exec list. */
2903 for (i = 0; i < args->buffer_count; i++) {
2904 if (!(exec2_list[i].offset & UPDATE))
2907 exec2_list[i].offset =
2908 gen8_canonical_addr(exec2_list[i].offset & PIN_OFFSET_MASK);
2909 exec2_list[i].offset &= PIN_OFFSET_MASK;
2910 if (__copy_to_user(&user_exec_list[i].offset,
2911 &exec2_list[i].offset,
2912 sizeof(user_exec_list[i].offset)))
2923 i915_gem_execbuffer2_ioctl(struct drm_device *dev, void *data,
2924 struct drm_file *file)
2926 struct drm_i915_private *i915 = to_i915(dev);
2927 struct drm_i915_gem_execbuffer2 *args = data;
2928 struct drm_i915_gem_exec_object2 *exec2_list;
2929 const size_t count = args->buffer_count;
2932 if (!check_buffer_count(count)) {
2933 drm_dbg(&i915->drm, "execbuf2 with %zd buffers\n", count);
2937 err = i915_gem_check_execbuffer(args);
2941 exec2_list = kvmalloc_array(count, eb_element_size(),
2942 __GFP_NOWARN | GFP_KERNEL);
2943 if (exec2_list == NULL) {
2944 drm_dbg(&i915->drm, "Failed to allocate exec list for %zd buffers\n",
2948 if (copy_from_user(exec2_list,
2949 u64_to_user_ptr(args->buffers_ptr),
2950 sizeof(*exec2_list) * count)) {
2951 drm_dbg(&i915->drm, "copy %zd exec entries failed\n", count);
2956 err = i915_gem_do_execbuffer(dev, file, args, exec2_list);
2959 * Now that we have begun execution of the batchbuffer, we ignore
2960 * any new error after this point. Also given that we have already
2961 * updated the associated relocations, we try to write out the current
2962 * object locations irrespective of any error.
2964 if (args->flags & __EXEC_HAS_RELOC) {
2965 struct drm_i915_gem_exec_object2 __user *user_exec_list =
2966 u64_to_user_ptr(args->buffers_ptr);
2969 /* Copy the new buffer offsets back to the user's exec list. */
2971 * Note: count * sizeof(*user_exec_list) does not overflow,
2972 * because we checked 'count' in check_buffer_count().
2974 * And this range already got effectively checked earlier
2975 * when we did the "copy_from_user()" above.
2977 if (!user_write_access_begin(user_exec_list,
2978 count * sizeof(*user_exec_list)))
2981 for (i = 0; i < args->buffer_count; i++) {
2982 if (!(exec2_list[i].offset & UPDATE))
2985 exec2_list[i].offset =
2986 gen8_canonical_addr(exec2_list[i].offset & PIN_OFFSET_MASK);
2987 unsafe_put_user(exec2_list[i].offset,
2988 &user_exec_list[i].offset,
2992 user_write_access_end();
2996 args->flags &= ~__I915_EXEC_UNKNOWN_FLAGS;
3001 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
3002 #include "selftests/i915_gem_execbuffer.c"