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>
13 #include <drm/i915_drm.h>
15 #include "display/intel_frontbuffer.h"
17 #include "gem/i915_gem_ioctls.h"
18 #include "gt/intel_context.h"
19 #include "gt/intel_engine_pool.h"
20 #include "gt/intel_gt.h"
21 #include "gt/intel_gt_pm.h"
22 #include "gt/intel_ring.h"
25 #include "i915_gem_clflush.h"
26 #include "i915_gem_context.h"
27 #include "i915_gem_ioctls.h"
28 #include "i915_sw_fence_work.h"
29 #include "i915_trace.h"
35 #define DBG_FORCE_RELOC 0 /* choose one of the above! */
38 #define __EXEC_OBJECT_HAS_REF BIT(31)
39 #define __EXEC_OBJECT_HAS_PIN BIT(30)
40 #define __EXEC_OBJECT_HAS_FENCE BIT(29)
41 #define __EXEC_OBJECT_NEEDS_MAP BIT(28)
42 #define __EXEC_OBJECT_NEEDS_BIAS BIT(27)
43 #define __EXEC_OBJECT_INTERNAL_FLAGS (~0u << 27) /* all of the above */
44 #define __EXEC_OBJECT_RESERVED (__EXEC_OBJECT_HAS_PIN | __EXEC_OBJECT_HAS_FENCE)
46 #define __EXEC_HAS_RELOC BIT(31)
47 #define __EXEC_VALIDATED BIT(30)
48 #define __EXEC_INTERNAL_FLAGS (~0u << 30)
49 #define UPDATE PIN_OFFSET_FIXED
51 #define BATCH_OFFSET_BIAS (256*1024)
53 #define __I915_EXEC_ILLEGAL_FLAGS \
54 (__I915_EXEC_UNKNOWN_FLAGS | \
55 I915_EXEC_CONSTANTS_MASK | \
56 I915_EXEC_RESOURCE_STREAMER)
58 /* Catch emission of unexpected errors for CI! */
59 #if IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM)
62 DRM_DEBUG_DRIVER("EINVAL at %s:%d\n", __func__, __LINE__); \
68 * DOC: User command execution
70 * Userspace submits commands to be executed on the GPU as an instruction
71 * stream within a GEM object we call a batchbuffer. This instructions may
72 * refer to other GEM objects containing auxiliary state such as kernels,
73 * samplers, render targets and even secondary batchbuffers. Userspace does
74 * not know where in the GPU memory these objects reside and so before the
75 * batchbuffer is passed to the GPU for execution, those addresses in the
76 * batchbuffer and auxiliary objects are updated. This is known as relocation,
77 * or patching. To try and avoid having to relocate each object on the next
78 * execution, userspace is told the location of those objects in this pass,
79 * but this remains just a hint as the kernel may choose a new location for
80 * any object in the future.
82 * At the level of talking to the hardware, submitting a batchbuffer for the
83 * GPU to execute is to add content to a buffer from which the HW
84 * command streamer is reading.
86 * 1. Add a command to load the HW context. For Logical Ring Contexts, i.e.
87 * Execlists, this command is not placed on the same buffer as the
90 * 2. Add a command to invalidate caches to the buffer.
92 * 3. Add a batchbuffer start command to the buffer; the start command is
93 * essentially a token together with the GPU address of the batchbuffer
96 * 4. Add a pipeline flush to the buffer.
98 * 5. Add a memory write command to the buffer to record when the GPU
99 * is done executing the batchbuffer. The memory write writes the
100 * global sequence number of the request, ``i915_request::global_seqno``;
101 * the i915 driver uses the current value in the register to determine
102 * if the GPU has completed the batchbuffer.
104 * 6. Add a user interrupt command to the buffer. This command instructs
105 * the GPU to issue an interrupt when the command, pipeline flush and
106 * memory write are completed.
108 * 7. Inform the hardware of the additional commands added to the buffer
109 * (by updating the tail pointer).
111 * Processing an execbuf ioctl is conceptually split up into a few phases.
113 * 1. Validation - Ensure all the pointers, handles and flags are valid.
114 * 2. Reservation - Assign GPU address space for every object
115 * 3. Relocation - Update any addresses to point to the final locations
116 * 4. Serialisation - Order the request with respect to its dependencies
117 * 5. Construction - Construct a request to execute the batchbuffer
118 * 6. Submission (at some point in the future execution)
120 * Reserving resources for the execbuf is the most complicated phase. We
121 * neither want to have to migrate the object in the address space, nor do
122 * we want to have to update any relocations pointing to this object. Ideally,
123 * we want to leave the object where it is and for all the existing relocations
124 * to match. If the object is given a new address, or if userspace thinks the
125 * object is elsewhere, we have to parse all the relocation entries and update
126 * the addresses. Userspace can set the I915_EXEC_NORELOC flag to hint that
127 * all the target addresses in all of its objects match the value in the
128 * relocation entries and that they all match the presumed offsets given by the
129 * list of execbuffer objects. Using this knowledge, we know that if we haven't
130 * moved any buffers, all the relocation entries are valid and we can skip
131 * the update. (If userspace is wrong, the likely outcome is an impromptu GPU
132 * hang.) The requirement for using I915_EXEC_NO_RELOC are:
134 * The addresses written in the objects must match the corresponding
135 * reloc.presumed_offset which in turn must match the corresponding
138 * Any render targets written to in the batch must be flagged with
141 * To avoid stalling, execobject.offset should match the current
142 * address of that object within the active context.
144 * The reservation is done is multiple phases. First we try and keep any
145 * object already bound in its current location - so as long as meets the
146 * constraints imposed by the new execbuffer. Any object left unbound after the
147 * first pass is then fitted into any available idle space. If an object does
148 * not fit, all objects are removed from the reservation and the process rerun
149 * after sorting the objects into a priority order (more difficult to fit
150 * objects are tried first). Failing that, the entire VM is cleared and we try
151 * to fit the execbuf once last time before concluding that it simply will not
154 * A small complication to all of this is that we allow userspace not only to
155 * specify an alignment and a size for the object in the address space, but
156 * we also allow userspace to specify the exact offset. This objects are
157 * simpler to place (the location is known a priori) all we have to do is make
158 * sure the space is available.
160 * Once all the objects are in place, patching up the buried pointers to point
161 * to the final locations is a fairly simple job of walking over the relocation
162 * entry arrays, looking up the right address and rewriting the value into
163 * the object. Simple! ... The relocation entries are stored in user memory
164 * and so to access them we have to copy them into a local buffer. That copy
165 * has to avoid taking any pagefaults as they may lead back to a GEM object
166 * requiring the struct_mutex (i.e. recursive deadlock). So once again we split
167 * the relocation into multiple passes. First we try to do everything within an
168 * atomic context (avoid the pagefaults) which requires that we never wait. If
169 * we detect that we may wait, or if we need to fault, then we have to fallback
170 * to a slower path. The slowpath has to drop the mutex. (Can you hear alarm
171 * bells yet?) Dropping the mutex means that we lose all the state we have
172 * built up so far for the execbuf and we must reset any global data. However,
173 * we do leave the objects pinned in their final locations - which is a
174 * potential issue for concurrent execbufs. Once we have left the mutex, we can
175 * allocate and copy all the relocation entries into a large array at our
176 * leisure, reacquire the mutex, reclaim all the objects and other state and
177 * then proceed to update any incorrect addresses with the objects.
179 * As we process the relocation entries, we maintain a record of whether the
180 * object is being written to. Using NORELOC, we expect userspace to provide
181 * this information instead. We also check whether we can skip the relocation
182 * by comparing the expected value inside the relocation entry with the target's
183 * final address. If they differ, we have to map the current object and rewrite
184 * the 4 or 8 byte pointer within.
186 * Serialising an execbuf is quite simple according to the rules of the GEM
187 * ABI. Execution within each context is ordered by the order of submission.
188 * Writes to any GEM object are in order of submission and are exclusive. Reads
189 * from a GEM object are unordered with respect to other reads, but ordered by
190 * writes. A write submitted after a read cannot occur before the read, and
191 * similarly any read submitted after a write cannot occur before the write.
192 * Writes are ordered between engines such that only one write occurs at any
193 * time (completing any reads beforehand) - using semaphores where available
194 * and CPU serialisation otherwise. Other GEM access obey the same rules, any
195 * write (either via mmaps using set-domain, or via pwrite) must flush all GPU
196 * reads before starting, and any read (either using set-domain or pread) must
197 * flush all GPU writes before starting. (Note we only employ a barrier before,
198 * we currently rely on userspace not concurrently starting a new execution
199 * whilst reading or writing to an object. This may be an advantage or not
200 * depending on how much you trust userspace not to shoot themselves in the
201 * foot.) Serialisation may just result in the request being inserted into
202 * a DAG awaiting its turn, but most simple is to wait on the CPU until
203 * all dependencies are resolved.
205 * After all of that, is just a matter of closing the request and handing it to
206 * the hardware (well, leaving it in a queue to be executed). However, we also
207 * offer the ability for batchbuffers to be run with elevated privileges so
208 * that they access otherwise hidden registers. (Used to adjust L3 cache etc.)
209 * Before any batch is given extra privileges we first must check that it
210 * contains no nefarious instructions, we check that each instruction is from
211 * our whitelist and all registers are also from an allowed list. We first
212 * copy the user's batchbuffer to a shadow (so that the user doesn't have
213 * access to it, either by the CPU or GPU as we scan it) and then parse each
214 * instruction. If everything is ok, we set a flag telling the hardware to run
215 * the batchbuffer in trusted mode, otherwise the ioctl is rejected.
218 struct i915_execbuffer {
219 struct drm_i915_private *i915; /** i915 backpointer */
220 struct drm_file *file; /** per-file lookup tables and limits */
221 struct drm_i915_gem_execbuffer2 *args; /** ioctl parameters */
222 struct drm_i915_gem_exec_object2 *exec; /** ioctl execobj[] */
223 struct i915_vma **vma;
226 struct intel_engine_cs *engine; /** engine to queue the request to */
227 struct intel_context *context; /* logical state for the request */
228 struct i915_gem_context *gem_context; /** caller's context */
230 struct i915_request *request; /** our request to build */
231 struct i915_vma *batch; /** identity of the batch obj/vma */
232 struct i915_vma *trampoline; /** trampoline used for chaining */
234 /** actual size of execobj[] as we may extend it for the cmdparser */
235 unsigned int buffer_count;
237 /** list of vma not yet bound during reservation phase */
238 struct list_head unbound;
240 /** list of vma that have execobj.relocation_count */
241 struct list_head relocs;
244 * Track the most recently used object for relocations, as we
245 * frequently have to perform multiple relocations within the same
249 struct drm_mm_node node; /** temporary GTT binding */
250 unsigned long vaddr; /** Current kmap address */
251 unsigned long page; /** Currently mapped page index */
252 unsigned int gen; /** Cached value of INTEL_GEN */
253 bool use_64bit_reloc : 1;
256 bool needs_unfenced : 1;
258 struct i915_request *rq;
260 unsigned int rq_size;
263 u64 invalid_flags; /** Set of execobj.flags that are invalid */
264 u32 context_flags; /** Set of execobj.flags to insert from the ctx */
266 u32 batch_start_offset; /** Location within object of batch */
267 u32 batch_len; /** Length of batch within object */
268 u32 batch_flags; /** Flags composed for emit_bb_start() */
271 * Indicate either the size of the hastable used to resolve
272 * relocation handles, or if negative that we are using a direct
273 * index into the execobj[].
276 struct hlist_head *buckets; /** ht for relocation handles */
279 #define exec_entry(EB, VMA) (&(EB)->exec[(VMA)->exec_flags - (EB)->flags])
281 static inline bool eb_use_cmdparser(const struct i915_execbuffer *eb)
283 return intel_engine_requires_cmd_parser(eb->engine) ||
284 (intel_engine_using_cmd_parser(eb->engine) &&
285 eb->args->batch_len);
288 static int eb_create(struct i915_execbuffer *eb)
290 if (!(eb->args->flags & I915_EXEC_HANDLE_LUT)) {
291 unsigned int size = 1 + ilog2(eb->buffer_count);
294 * Without a 1:1 association between relocation handles and
295 * the execobject[] index, we instead create a hashtable.
296 * We size it dynamically based on available memory, starting
297 * first with 1:1 assocative hash and scaling back until
298 * the allocation succeeds.
300 * Later on we use a positive lut_size to indicate we are
301 * using this hashtable, and a negative value to indicate a
307 /* While we can still reduce the allocation size, don't
308 * raise a warning and allow the allocation to fail.
309 * On the last pass though, we want to try as hard
310 * as possible to perform the allocation and warn
315 flags |= __GFP_NORETRY | __GFP_NOWARN;
317 eb->buckets = kzalloc(sizeof(struct hlist_head) << size,
328 eb->lut_size = -eb->buffer_count;
335 eb_vma_misplaced(const struct drm_i915_gem_exec_object2 *entry,
336 const struct i915_vma *vma,
339 if (vma->node.size < entry->pad_to_size)
342 if (entry->alignment && !IS_ALIGNED(vma->node.start, entry->alignment))
345 if (flags & EXEC_OBJECT_PINNED &&
346 vma->node.start != entry->offset)
349 if (flags & __EXEC_OBJECT_NEEDS_BIAS &&
350 vma->node.start < BATCH_OFFSET_BIAS)
353 if (!(flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS) &&
354 (vma->node.start + vma->node.size - 1) >> 32)
357 if (flags & __EXEC_OBJECT_NEEDS_MAP &&
358 !i915_vma_is_map_and_fenceable(vma))
365 eb_pin_vma(struct i915_execbuffer *eb,
366 const struct drm_i915_gem_exec_object2 *entry,
367 struct i915_vma *vma)
369 unsigned int exec_flags = *vma->exec_flags;
373 pin_flags = vma->node.start;
375 pin_flags = entry->offset & PIN_OFFSET_MASK;
377 pin_flags |= PIN_USER | PIN_NOEVICT | PIN_OFFSET_FIXED;
378 if (unlikely(exec_flags & EXEC_OBJECT_NEEDS_GTT))
379 pin_flags |= PIN_GLOBAL;
381 if (unlikely(i915_vma_pin(vma, 0, 0, pin_flags)))
384 if (unlikely(exec_flags & EXEC_OBJECT_NEEDS_FENCE)) {
385 if (unlikely(i915_vma_pin_fence(vma))) {
391 exec_flags |= __EXEC_OBJECT_HAS_FENCE;
394 *vma->exec_flags = exec_flags | __EXEC_OBJECT_HAS_PIN;
395 return !eb_vma_misplaced(entry, vma, exec_flags);
398 static inline void __eb_unreserve_vma(struct i915_vma *vma, unsigned int flags)
400 GEM_BUG_ON(!(flags & __EXEC_OBJECT_HAS_PIN));
402 if (unlikely(flags & __EXEC_OBJECT_HAS_FENCE))
403 __i915_vma_unpin_fence(vma);
405 __i915_vma_unpin(vma);
409 eb_unreserve_vma(struct i915_vma *vma, unsigned int *flags)
411 if (!(*flags & __EXEC_OBJECT_HAS_PIN))
414 __eb_unreserve_vma(vma, *flags);
415 *flags &= ~__EXEC_OBJECT_RESERVED;
419 eb_validate_vma(struct i915_execbuffer *eb,
420 struct drm_i915_gem_exec_object2 *entry,
421 struct i915_vma *vma)
423 if (unlikely(entry->flags & eb->invalid_flags))
426 if (unlikely(entry->alignment &&
427 !is_power_of_2_u64(entry->alignment)))
431 * Offset can be used as input (EXEC_OBJECT_PINNED), reject
432 * any non-page-aligned or non-canonical addresses.
434 if (unlikely(entry->flags & EXEC_OBJECT_PINNED &&
435 entry->offset != gen8_canonical_addr(entry->offset & I915_GTT_PAGE_MASK)))
438 /* pad_to_size was once a reserved field, so sanitize it */
439 if (entry->flags & EXEC_OBJECT_PAD_TO_SIZE) {
440 if (unlikely(offset_in_page(entry->pad_to_size)))
443 entry->pad_to_size = 0;
446 if (unlikely(vma->exec_flags)) {
447 DRM_DEBUG("Object [handle %d, index %d] appears more than once in object list\n",
448 entry->handle, (int)(entry - eb->exec));
453 * From drm_mm perspective address space is continuous,
454 * so from this point we're always using non-canonical
457 entry->offset = gen8_noncanonical_addr(entry->offset);
459 if (!eb->reloc_cache.has_fence) {
460 entry->flags &= ~EXEC_OBJECT_NEEDS_FENCE;
462 if ((entry->flags & EXEC_OBJECT_NEEDS_FENCE ||
463 eb->reloc_cache.needs_unfenced) &&
464 i915_gem_object_is_tiled(vma->obj))
465 entry->flags |= EXEC_OBJECT_NEEDS_GTT | __EXEC_OBJECT_NEEDS_MAP;
468 if (!(entry->flags & EXEC_OBJECT_PINNED))
469 entry->flags |= eb->context_flags;
475 eb_add_vma(struct i915_execbuffer *eb,
476 unsigned int i, unsigned batch_idx,
477 struct i915_vma *vma)
479 struct drm_i915_gem_exec_object2 *entry = &eb->exec[i];
482 GEM_BUG_ON(i915_vma_is_closed(vma));
484 if (!(eb->args->flags & __EXEC_VALIDATED)) {
485 err = eb_validate_vma(eb, entry, vma);
490 if (eb->lut_size > 0) {
491 vma->exec_handle = entry->handle;
492 hlist_add_head(&vma->exec_node,
493 &eb->buckets[hash_32(entry->handle,
497 if (entry->relocation_count)
498 list_add_tail(&vma->reloc_link, &eb->relocs);
501 * Stash a pointer from the vma to execobj, so we can query its flags,
502 * size, alignment etc as provided by the user. Also we stash a pointer
503 * to the vma inside the execobj so that we can use a direct lookup
504 * to find the right target VMA when doing relocations.
507 eb->flags[i] = entry->flags;
508 vma->exec_flags = &eb->flags[i];
511 * SNA is doing fancy tricks with compressing batch buffers, which leads
512 * to negative relocation deltas. Usually that works out ok since the
513 * relocate address is still positive, except when the batch is placed
514 * very low in the GTT. Ensure this doesn't happen.
516 * Note that actual hangs have only been observed on gen7, but for
517 * paranoia do it everywhere.
519 if (i == batch_idx) {
520 if (entry->relocation_count &&
521 !(eb->flags[i] & EXEC_OBJECT_PINNED))
522 eb->flags[i] |= __EXEC_OBJECT_NEEDS_BIAS;
523 if (eb->reloc_cache.has_fence)
524 eb->flags[i] |= EXEC_OBJECT_NEEDS_FENCE;
530 if (eb_pin_vma(eb, entry, vma)) {
531 if (entry->offset != vma->node.start) {
532 entry->offset = vma->node.start | UPDATE;
533 eb->args->flags |= __EXEC_HAS_RELOC;
536 eb_unreserve_vma(vma, vma->exec_flags);
538 list_add_tail(&vma->exec_link, &eb->unbound);
539 if (drm_mm_node_allocated(&vma->node))
540 err = i915_vma_unbind(vma);
542 vma->exec_flags = NULL;
547 static inline int use_cpu_reloc(const struct reloc_cache *cache,
548 const struct drm_i915_gem_object *obj)
550 if (!i915_gem_object_has_struct_page(obj))
553 if (DBG_FORCE_RELOC == FORCE_CPU_RELOC)
556 if (DBG_FORCE_RELOC == FORCE_GTT_RELOC)
559 return (cache->has_llc ||
561 obj->cache_level != I915_CACHE_NONE);
564 static int eb_reserve_vma(const struct i915_execbuffer *eb,
565 struct i915_vma *vma)
567 struct drm_i915_gem_exec_object2 *entry = exec_entry(eb, vma);
568 unsigned int exec_flags = *vma->exec_flags;
572 pin_flags = PIN_USER | PIN_NONBLOCK;
573 if (exec_flags & EXEC_OBJECT_NEEDS_GTT)
574 pin_flags |= PIN_GLOBAL;
577 * Wa32bitGeneralStateOffset & Wa32bitInstructionBaseOffset,
578 * limit address to the first 4GBs for unflagged objects.
580 if (!(exec_flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS))
581 pin_flags |= PIN_ZONE_4G;
583 if (exec_flags & __EXEC_OBJECT_NEEDS_MAP)
584 pin_flags |= PIN_MAPPABLE;
586 if (exec_flags & EXEC_OBJECT_PINNED) {
587 pin_flags |= entry->offset | PIN_OFFSET_FIXED;
588 pin_flags &= ~PIN_NONBLOCK; /* force overlapping checks */
589 } else if (exec_flags & __EXEC_OBJECT_NEEDS_BIAS) {
590 pin_flags |= BATCH_OFFSET_BIAS | PIN_OFFSET_BIAS;
593 err = i915_vma_pin(vma,
594 entry->pad_to_size, entry->alignment,
599 if (entry->offset != vma->node.start) {
600 entry->offset = vma->node.start | UPDATE;
601 eb->args->flags |= __EXEC_HAS_RELOC;
604 if (unlikely(exec_flags & EXEC_OBJECT_NEEDS_FENCE)) {
605 err = i915_vma_pin_fence(vma);
612 exec_flags |= __EXEC_OBJECT_HAS_FENCE;
615 *vma->exec_flags = exec_flags | __EXEC_OBJECT_HAS_PIN;
616 GEM_BUG_ON(eb_vma_misplaced(entry, vma, exec_flags));
621 static int eb_reserve(struct i915_execbuffer *eb)
623 const unsigned int count = eb->buffer_count;
624 struct list_head last;
625 struct i915_vma *vma;
626 unsigned int i, pass;
630 * Attempt to pin all of the buffers into the GTT.
631 * This is done in 3 phases:
633 * 1a. Unbind all objects that do not match the GTT constraints for
634 * the execbuffer (fenceable, mappable, alignment etc).
635 * 1b. Increment pin count for already bound objects.
636 * 2. Bind new objects.
637 * 3. Decrement pin count.
639 * This avoid unnecessary unbinding of later objects in order to make
640 * room for the earlier objects *unless* we need to defragment.
646 list_for_each_entry(vma, &eb->unbound, exec_link) {
647 err = eb_reserve_vma(eb, vma);
654 /* Resort *all* the objects into priority order */
655 INIT_LIST_HEAD(&eb->unbound);
656 INIT_LIST_HEAD(&last);
657 for (i = 0; i < count; i++) {
658 unsigned int flags = eb->flags[i];
659 struct i915_vma *vma = eb->vma[i];
661 if (flags & EXEC_OBJECT_PINNED &&
662 flags & __EXEC_OBJECT_HAS_PIN)
665 eb_unreserve_vma(vma, &eb->flags[i]);
667 if (flags & EXEC_OBJECT_PINNED)
668 /* Pinned must have their slot */
669 list_add(&vma->exec_link, &eb->unbound);
670 else if (flags & __EXEC_OBJECT_NEEDS_MAP)
671 /* Map require the lowest 256MiB (aperture) */
672 list_add_tail(&vma->exec_link, &eb->unbound);
673 else if (!(flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS))
674 /* Prioritise 4GiB region for restricted bo */
675 list_add(&vma->exec_link, &last);
677 list_add_tail(&vma->exec_link, &last);
679 list_splice_tail(&last, &eb->unbound);
686 /* Too fragmented, unbind everything and retry */
687 mutex_lock(&eb->context->vm->mutex);
688 err = i915_gem_evict_vm(eb->context->vm);
689 mutex_unlock(&eb->context->vm->mutex);
700 static unsigned int eb_batch_index(const struct i915_execbuffer *eb)
702 if (eb->args->flags & I915_EXEC_BATCH_FIRST)
705 return eb->buffer_count - 1;
708 static int eb_select_context(struct i915_execbuffer *eb)
710 struct i915_gem_context *ctx;
712 ctx = i915_gem_context_lookup(eb->file->driver_priv, eb->args->rsvd1);
716 eb->gem_context = ctx;
717 if (rcu_access_pointer(ctx->vm))
718 eb->invalid_flags |= EXEC_OBJECT_NEEDS_GTT;
720 eb->context_flags = 0;
721 if (test_bit(UCONTEXT_NO_ZEROMAP, &ctx->user_flags))
722 eb->context_flags |= __EXEC_OBJECT_NEEDS_BIAS;
727 static int eb_lookup_vmas(struct i915_execbuffer *eb)
729 struct radix_tree_root *handles_vma = &eb->gem_context->handles_vma;
730 struct drm_i915_gem_object *obj;
731 unsigned int i, batch;
734 INIT_LIST_HEAD(&eb->relocs);
735 INIT_LIST_HEAD(&eb->unbound);
737 batch = eb_batch_index(eb);
739 mutex_lock(&eb->gem_context->mutex);
740 if (unlikely(i915_gem_context_is_closed(eb->gem_context))) {
745 for (i = 0; i < eb->buffer_count; i++) {
746 u32 handle = eb->exec[i].handle;
747 struct i915_lut_handle *lut;
748 struct i915_vma *vma;
750 vma = radix_tree_lookup(handles_vma, handle);
754 obj = i915_gem_object_lookup(eb->file, handle);
755 if (unlikely(!obj)) {
760 vma = i915_vma_instance(obj, eb->context->vm, NULL);
766 lut = i915_lut_handle_alloc();
767 if (unlikely(!lut)) {
772 err = radix_tree_insert(handles_vma, handle, vma);
774 i915_lut_handle_free(lut);
778 /* transfer ref to lut */
779 if (!atomic_fetch_inc(&vma->open_count))
780 i915_vma_reopen(vma);
781 lut->handle = handle;
782 lut->ctx = eb->gem_context;
784 i915_gem_object_lock(obj);
785 list_add(&lut->obj_link, &obj->lut_list);
786 i915_gem_object_unlock(obj);
789 err = eb_add_vma(eb, i, batch, vma);
793 GEM_BUG_ON(vma != eb->vma[i]);
794 GEM_BUG_ON(vma->exec_flags != &eb->flags[i]);
795 GEM_BUG_ON(drm_mm_node_allocated(&vma->node) &&
796 eb_vma_misplaced(&eb->exec[i], vma, eb->flags[i]));
799 mutex_unlock(&eb->gem_context->mutex);
801 eb->args->flags |= __EXEC_VALIDATED;
802 return eb_reserve(eb);
805 i915_gem_object_put(obj);
809 mutex_unlock(&eb->gem_context->mutex);
813 static struct i915_vma *
814 eb_get_vma(const struct i915_execbuffer *eb, unsigned long handle)
816 if (eb->lut_size < 0) {
817 if (handle >= -eb->lut_size)
819 return eb->vma[handle];
821 struct hlist_head *head;
822 struct i915_vma *vma;
824 head = &eb->buckets[hash_32(handle, eb->lut_size)];
825 hlist_for_each_entry(vma, head, exec_node) {
826 if (vma->exec_handle == handle)
833 static void eb_release_vmas(const struct i915_execbuffer *eb)
835 const unsigned int count = eb->buffer_count;
838 for (i = 0; i < count; i++) {
839 struct i915_vma *vma = eb->vma[i];
840 unsigned int flags = eb->flags[i];
845 GEM_BUG_ON(vma->exec_flags != &eb->flags[i]);
846 vma->exec_flags = NULL;
849 if (flags & __EXEC_OBJECT_HAS_PIN)
850 __eb_unreserve_vma(vma, flags);
852 if (flags & __EXEC_OBJECT_HAS_REF)
857 static void eb_reset_vmas(const struct i915_execbuffer *eb)
860 if (eb->lut_size > 0)
861 memset(eb->buckets, 0,
862 sizeof(struct hlist_head) << eb->lut_size);
865 static void eb_destroy(const struct i915_execbuffer *eb)
867 GEM_BUG_ON(eb->reloc_cache.rq);
869 if (eb->lut_size > 0)
874 relocation_target(const struct drm_i915_gem_relocation_entry *reloc,
875 const struct i915_vma *target)
877 return gen8_canonical_addr((int)reloc->delta + target->node.start);
880 static void reloc_cache_init(struct reloc_cache *cache,
881 struct drm_i915_private *i915)
885 /* Must be a variable in the struct to allow GCC to unroll. */
886 cache->gen = INTEL_GEN(i915);
887 cache->has_llc = HAS_LLC(i915);
888 cache->use_64bit_reloc = HAS_64BIT_RELOC(i915);
889 cache->has_fence = cache->gen < 4;
890 cache->needs_unfenced = INTEL_INFO(i915)->unfenced_needs_alignment;
891 cache->node.flags = 0;
896 static inline void *unmask_page(unsigned long p)
898 return (void *)(uintptr_t)(p & PAGE_MASK);
901 static inline unsigned int unmask_flags(unsigned long p)
903 return p & ~PAGE_MASK;
906 #define KMAP 0x4 /* after CLFLUSH_FLAGS */
908 static inline struct i915_ggtt *cache_to_ggtt(struct reloc_cache *cache)
910 struct drm_i915_private *i915 =
911 container_of(cache, struct i915_execbuffer, reloc_cache)->i915;
915 static void reloc_gpu_flush(struct reloc_cache *cache)
917 GEM_BUG_ON(cache->rq_size >= cache->rq->batch->obj->base.size / sizeof(u32));
918 cache->rq_cmd[cache->rq_size] = MI_BATCH_BUFFER_END;
920 __i915_gem_object_flush_map(cache->rq->batch->obj, 0, cache->rq_size);
921 i915_gem_object_unpin_map(cache->rq->batch->obj);
923 intel_gt_chipset_flush(cache->rq->engine->gt);
925 i915_request_add(cache->rq);
929 static void reloc_cache_reset(struct reloc_cache *cache)
934 reloc_gpu_flush(cache);
939 vaddr = unmask_page(cache->vaddr);
940 if (cache->vaddr & KMAP) {
941 if (cache->vaddr & CLFLUSH_AFTER)
944 kunmap_atomic(vaddr);
945 i915_gem_object_finish_access((struct drm_i915_gem_object *)cache->node.mm);
947 struct i915_ggtt *ggtt = cache_to_ggtt(cache);
949 intel_gt_flush_ggtt_writes(ggtt->vm.gt);
950 io_mapping_unmap_atomic((void __iomem *)vaddr);
952 if (drm_mm_node_allocated(&cache->node)) {
953 ggtt->vm.clear_range(&ggtt->vm,
956 mutex_lock(&ggtt->vm.mutex);
957 drm_mm_remove_node(&cache->node);
958 mutex_unlock(&ggtt->vm.mutex);
960 i915_vma_unpin((struct i915_vma *)cache->node.mm);
968 static void *reloc_kmap(struct drm_i915_gem_object *obj,
969 struct reloc_cache *cache,
975 kunmap_atomic(unmask_page(cache->vaddr));
977 unsigned int flushes;
980 err = i915_gem_object_prepare_write(obj, &flushes);
984 BUILD_BUG_ON(KMAP & CLFLUSH_FLAGS);
985 BUILD_BUG_ON((KMAP | CLFLUSH_FLAGS) & PAGE_MASK);
987 cache->vaddr = flushes | KMAP;
988 cache->node.mm = (void *)obj;
993 vaddr = kmap_atomic(i915_gem_object_get_dirty_page(obj, page));
994 cache->vaddr = unmask_flags(cache->vaddr) | (unsigned long)vaddr;
1000 static void *reloc_iomap(struct drm_i915_gem_object *obj,
1001 struct reloc_cache *cache,
1004 struct i915_ggtt *ggtt = cache_to_ggtt(cache);
1005 unsigned long offset;
1009 intel_gt_flush_ggtt_writes(ggtt->vm.gt);
1010 io_mapping_unmap_atomic((void __force __iomem *) unmask_page(cache->vaddr));
1012 struct i915_vma *vma;
1015 if (i915_gem_object_is_tiled(obj))
1016 return ERR_PTR(-EINVAL);
1018 if (use_cpu_reloc(cache, obj))
1021 i915_gem_object_lock(obj);
1022 err = i915_gem_object_set_to_gtt_domain(obj, true);
1023 i915_gem_object_unlock(obj);
1025 return ERR_PTR(err);
1027 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
1029 PIN_NONBLOCK /* NOWARN */ |
1032 memset(&cache->node, 0, sizeof(cache->node));
1033 mutex_lock(&ggtt->vm.mutex);
1034 err = drm_mm_insert_node_in_range
1035 (&ggtt->vm.mm, &cache->node,
1036 PAGE_SIZE, 0, I915_COLOR_UNEVICTABLE,
1037 0, ggtt->mappable_end,
1039 mutex_unlock(&ggtt->vm.mutex);
1040 if (err) /* no inactive aperture space, use cpu reloc */
1043 cache->node.start = vma->node.start;
1044 cache->node.mm = (void *)vma;
1048 offset = cache->node.start;
1049 if (drm_mm_node_allocated(&cache->node)) {
1050 ggtt->vm.insert_page(&ggtt->vm,
1051 i915_gem_object_get_dma_address(obj, page),
1052 offset, I915_CACHE_NONE, 0);
1054 offset += page << PAGE_SHIFT;
1057 vaddr = (void __force *)io_mapping_map_atomic_wc(&ggtt->iomap,
1060 cache->vaddr = (unsigned long)vaddr;
1065 static void *reloc_vaddr(struct drm_i915_gem_object *obj,
1066 struct reloc_cache *cache,
1071 if (cache->page == page) {
1072 vaddr = unmask_page(cache->vaddr);
1075 if ((cache->vaddr & KMAP) == 0)
1076 vaddr = reloc_iomap(obj, cache, page);
1078 vaddr = reloc_kmap(obj, cache, page);
1084 static void clflush_write32(u32 *addr, u32 value, unsigned int flushes)
1086 if (unlikely(flushes & (CLFLUSH_BEFORE | CLFLUSH_AFTER))) {
1087 if (flushes & CLFLUSH_BEFORE) {
1095 * Writes to the same cacheline are serialised by the CPU
1096 * (including clflush). On the write path, we only require
1097 * that it hits memory in an orderly fashion and place
1098 * mb barriers at the start and end of the relocation phase
1099 * to ensure ordering of clflush wrt to the system.
1101 if (flushes & CLFLUSH_AFTER)
1107 static int reloc_move_to_gpu(struct i915_request *rq, struct i915_vma *vma)
1109 struct drm_i915_gem_object *obj = vma->obj;
1114 if (obj->cache_dirty & ~obj->cache_coherent)
1115 i915_gem_clflush_object(obj, 0);
1116 obj->write_domain = 0;
1118 err = i915_request_await_object(rq, vma->obj, true);
1120 err = i915_vma_move_to_active(vma, rq, EXEC_OBJECT_WRITE);
1122 i915_vma_unlock(vma);
1127 static int __reloc_gpu_alloc(struct i915_execbuffer *eb,
1128 struct i915_vma *vma,
1131 struct reloc_cache *cache = &eb->reloc_cache;
1132 struct intel_engine_pool_node *pool;
1133 struct i915_request *rq;
1134 struct i915_vma *batch;
1138 pool = intel_engine_get_pool(eb->engine, PAGE_SIZE);
1140 return PTR_ERR(pool);
1142 cmd = i915_gem_object_pin_map(pool->obj,
1151 batch = i915_vma_instance(pool->obj, vma->vm, NULL);
1152 if (IS_ERR(batch)) {
1153 err = PTR_ERR(batch);
1157 err = i915_vma_pin(batch, 0, 0, PIN_USER | PIN_NONBLOCK);
1161 rq = i915_request_create(eb->context);
1167 err = intel_engine_pool_mark_active(pool, rq);
1171 err = reloc_move_to_gpu(rq, vma);
1175 err = eb->engine->emit_bb_start(rq,
1176 batch->node.start, PAGE_SIZE,
1177 cache->gen > 5 ? 0 : I915_DISPATCH_SECURE);
1181 i915_vma_lock(batch);
1182 err = i915_request_await_object(rq, batch->obj, false);
1184 err = i915_vma_move_to_active(batch, rq, 0);
1185 i915_vma_unlock(batch);
1190 i915_vma_unpin(batch);
1193 cache->rq_cmd = cmd;
1196 /* Return with batch mapping (cmd) still pinned */
1200 i915_request_skip(rq, err);
1202 i915_request_add(rq);
1204 i915_vma_unpin(batch);
1206 i915_gem_object_unpin_map(pool->obj);
1208 intel_engine_pool_put(pool);
1212 static u32 *reloc_gpu(struct i915_execbuffer *eb,
1213 struct i915_vma *vma,
1216 struct reloc_cache *cache = &eb->reloc_cache;
1219 if (cache->rq_size > PAGE_SIZE/sizeof(u32) - (len + 1))
1220 reloc_gpu_flush(cache);
1222 if (unlikely(!cache->rq)) {
1225 if (!intel_engine_can_store_dword(eb->engine))
1226 return ERR_PTR(-ENODEV);
1228 err = __reloc_gpu_alloc(eb, vma, len);
1230 return ERR_PTR(err);
1233 cmd = cache->rq_cmd + cache->rq_size;
1234 cache->rq_size += len;
1240 relocate_entry(struct i915_vma *vma,
1241 const struct drm_i915_gem_relocation_entry *reloc,
1242 struct i915_execbuffer *eb,
1243 const struct i915_vma *target)
1245 u64 offset = reloc->offset;
1246 u64 target_offset = relocation_target(reloc, target);
1247 bool wide = eb->reloc_cache.use_64bit_reloc;
1250 if (!eb->reloc_cache.vaddr &&
1251 (DBG_FORCE_RELOC == FORCE_GPU_RELOC ||
1252 !dma_resv_test_signaled_rcu(vma->resv, true))) {
1253 const unsigned int gen = eb->reloc_cache.gen;
1259 len = offset & 7 ? 8 : 5;
1265 batch = reloc_gpu(eb, vma, len);
1269 addr = gen8_canonical_addr(vma->node.start + offset);
1272 *batch++ = MI_STORE_DWORD_IMM_GEN4;
1273 *batch++ = lower_32_bits(addr);
1274 *batch++ = upper_32_bits(addr);
1275 *batch++ = lower_32_bits(target_offset);
1277 addr = gen8_canonical_addr(addr + 4);
1279 *batch++ = MI_STORE_DWORD_IMM_GEN4;
1280 *batch++ = lower_32_bits(addr);
1281 *batch++ = upper_32_bits(addr);
1282 *batch++ = upper_32_bits(target_offset);
1284 *batch++ = (MI_STORE_DWORD_IMM_GEN4 | (1 << 21)) + 1;
1285 *batch++ = lower_32_bits(addr);
1286 *batch++ = upper_32_bits(addr);
1287 *batch++ = lower_32_bits(target_offset);
1288 *batch++ = upper_32_bits(target_offset);
1290 } else if (gen >= 6) {
1291 *batch++ = MI_STORE_DWORD_IMM_GEN4;
1294 *batch++ = target_offset;
1295 } else if (gen >= 4) {
1296 *batch++ = MI_STORE_DWORD_IMM_GEN4 | MI_USE_GGTT;
1299 *batch++ = target_offset;
1301 *batch++ = MI_STORE_DWORD_IMM | MI_MEM_VIRTUAL;
1303 *batch++ = target_offset;
1310 vaddr = reloc_vaddr(vma->obj, &eb->reloc_cache, offset >> PAGE_SHIFT);
1312 return PTR_ERR(vaddr);
1314 clflush_write32(vaddr + offset_in_page(offset),
1315 lower_32_bits(target_offset),
1316 eb->reloc_cache.vaddr);
1319 offset += sizeof(u32);
1320 target_offset >>= 32;
1326 return target->node.start | UPDATE;
1330 eb_relocate_entry(struct i915_execbuffer *eb,
1331 struct i915_vma *vma,
1332 const struct drm_i915_gem_relocation_entry *reloc)
1334 struct i915_vma *target;
1337 /* we've already hold a reference to all valid objects */
1338 target = eb_get_vma(eb, reloc->target_handle);
1339 if (unlikely(!target))
1342 /* Validate that the target is in a valid r/w GPU domain */
1343 if (unlikely(reloc->write_domain & (reloc->write_domain - 1))) {
1344 DRM_DEBUG("reloc with multiple write domains: "
1345 "target %d offset %d "
1346 "read %08x write %08x",
1347 reloc->target_handle,
1348 (int) reloc->offset,
1349 reloc->read_domains,
1350 reloc->write_domain);
1353 if (unlikely((reloc->write_domain | reloc->read_domains)
1354 & ~I915_GEM_GPU_DOMAINS)) {
1355 DRM_DEBUG("reloc with read/write non-GPU domains: "
1356 "target %d offset %d "
1357 "read %08x write %08x",
1358 reloc->target_handle,
1359 (int) reloc->offset,
1360 reloc->read_domains,
1361 reloc->write_domain);
1365 if (reloc->write_domain) {
1366 *target->exec_flags |= EXEC_OBJECT_WRITE;
1369 * Sandybridge PPGTT errata: We need a global gtt mapping
1370 * for MI and pipe_control writes because the gpu doesn't
1371 * properly redirect them through the ppgtt for non_secure
1374 if (reloc->write_domain == I915_GEM_DOMAIN_INSTRUCTION &&
1375 IS_GEN(eb->i915, 6)) {
1376 err = i915_vma_bind(target, target->obj->cache_level,
1379 "Unexpected failure to bind target VMA!"))
1385 * If the relocation already has the right value in it, no
1386 * more work needs to be done.
1388 if (!DBG_FORCE_RELOC &&
1389 gen8_canonical_addr(target->node.start) == reloc->presumed_offset)
1392 /* Check that the relocation address is valid... */
1393 if (unlikely(reloc->offset >
1394 vma->size - (eb->reloc_cache.use_64bit_reloc ? 8 : 4))) {
1395 DRM_DEBUG("Relocation beyond object bounds: "
1396 "target %d offset %d size %d.\n",
1397 reloc->target_handle,
1402 if (unlikely(reloc->offset & 3)) {
1403 DRM_DEBUG("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 *vma->exec_flags &= ~EXEC_OBJECT_ASYNC;
1420 /* and update the user's relocation entry */
1421 return relocate_entry(vma, reloc, eb, target);
1424 static int eb_relocate_vma(struct i915_execbuffer *eb, struct i915_vma *vma)
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 struct drm_i915_gem_relocation_entry __user *urelocs;
1429 const struct drm_i915_gem_exec_object2 *entry = exec_entry(eb, vma);
1430 unsigned int remain;
1432 urelocs = u64_to_user_ptr(entry->relocs_ptr);
1433 remain = entry->relocation_count;
1434 if (unlikely(remain > N_RELOC(ULONG_MAX)))
1438 * We must check that the entire relocation array is safe
1439 * to read. However, if the array is not writable the user loses
1440 * the updated relocation values.
1442 if (unlikely(!access_ok(urelocs, remain*sizeof(*urelocs))))
1446 struct drm_i915_gem_relocation_entry *r = stack;
1447 unsigned int count =
1448 min_t(unsigned int, remain, ARRAY_SIZE(stack));
1449 unsigned int copied;
1452 * This is the fast path and we cannot handle a pagefault
1453 * whilst holding the struct mutex lest the user pass in the
1454 * relocations contained within a mmaped bo. For in such a case
1455 * we, the page fault handler would call i915_gem_fault() and
1456 * we would try to acquire the struct mutex again. Obviously
1457 * this is bad and so lockdep complains vehemently.
1459 pagefault_disable();
1460 copied = __copy_from_user_inatomic(r, urelocs, count * sizeof(r[0]));
1462 if (unlikely(copied)) {
1469 u64 offset = eb_relocate_entry(eb, vma, r);
1471 if (likely(offset == 0)) {
1472 } else if ((s64)offset < 0) {
1473 remain = (int)offset;
1477 * Note that reporting an error now
1478 * leaves everything in an inconsistent
1479 * state as we have *already* changed
1480 * the relocation value inside the
1481 * object. As we have not changed the
1482 * reloc.presumed_offset or will not
1483 * change the execobject.offset, on the
1484 * call we may not rewrite the value
1485 * inside the object, leaving it
1486 * dangling and causing a GPU hang. Unless
1487 * userspace dynamically rebuilds the
1488 * relocations on each execbuf rather than
1489 * presume a static tree.
1491 * We did previously check if the relocations
1492 * were writable (access_ok), an error now
1493 * would be a strange race with mprotect,
1494 * having already demonstrated that we
1495 * can read from this userspace address.
1497 offset = gen8_canonical_addr(offset & ~UPDATE);
1498 if (unlikely(__put_user(offset, &urelocs[r-stack].presumed_offset))) {
1503 } while (r++, --count);
1504 urelocs += ARRAY_SIZE(stack);
1507 reloc_cache_reset(&eb->reloc_cache);
1512 eb_relocate_vma_slow(struct i915_execbuffer *eb, struct i915_vma *vma)
1514 const struct drm_i915_gem_exec_object2 *entry = exec_entry(eb, vma);
1515 struct drm_i915_gem_relocation_entry *relocs =
1516 u64_to_ptr(typeof(*relocs), entry->relocs_ptr);
1520 for (i = 0; i < entry->relocation_count; i++) {
1521 u64 offset = eb_relocate_entry(eb, vma, &relocs[i]);
1523 if ((s64)offset < 0) {
1530 reloc_cache_reset(&eb->reloc_cache);
1534 static int check_relocations(const struct drm_i915_gem_exec_object2 *entry)
1536 const char __user *addr, *end;
1538 char __maybe_unused c;
1540 size = entry->relocation_count;
1544 if (size > N_RELOC(ULONG_MAX))
1547 addr = u64_to_user_ptr(entry->relocs_ptr);
1548 size *= sizeof(struct drm_i915_gem_relocation_entry);
1549 if (!access_ok(addr, size))
1553 for (; addr < end; addr += PAGE_SIZE) {
1554 int err = __get_user(c, addr);
1558 return __get_user(c, end - 1);
1561 static int eb_copy_relocations(const struct i915_execbuffer *eb)
1563 struct drm_i915_gem_relocation_entry *relocs;
1564 const unsigned int count = eb->buffer_count;
1568 for (i = 0; i < count; i++) {
1569 const unsigned int nreloc = eb->exec[i].relocation_count;
1570 struct drm_i915_gem_relocation_entry __user *urelocs;
1572 unsigned long copied;
1577 err = check_relocations(&eb->exec[i]);
1581 urelocs = u64_to_user_ptr(eb->exec[i].relocs_ptr);
1582 size = nreloc * sizeof(*relocs);
1584 relocs = kvmalloc_array(size, 1, GFP_KERNEL);
1590 /* copy_from_user is limited to < 4GiB */
1594 min_t(u64, BIT_ULL(31), size - copied);
1596 if (__copy_from_user((char *)relocs + copied,
1597 (char __user *)urelocs + copied,
1602 } while (copied < size);
1605 * As we do not update the known relocation offsets after
1606 * relocating (due to the complexities in lock handling),
1607 * we need to mark them as invalid now so that we force the
1608 * relocation processing next time. Just in case the target
1609 * object is evicted and then rebound into its old
1610 * presumed_offset before the next execbuffer - if that
1611 * happened we would make the mistake of assuming that the
1612 * relocations were valid.
1614 if (!user_access_begin(urelocs, size))
1617 for (copied = 0; copied < nreloc; copied++)
1619 &urelocs[copied].presumed_offset,
1623 eb->exec[i].relocs_ptr = (uintptr_t)relocs;
1635 relocs = u64_to_ptr(typeof(*relocs), eb->exec[i].relocs_ptr);
1636 if (eb->exec[i].relocation_count)
1642 static int eb_prefault_relocations(const struct i915_execbuffer *eb)
1644 const unsigned int count = eb->buffer_count;
1647 if (unlikely(i915_modparams.prefault_disable))
1650 for (i = 0; i < count; i++) {
1653 err = check_relocations(&eb->exec[i]);
1661 static noinline int eb_relocate_slow(struct i915_execbuffer *eb)
1663 struct drm_device *dev = &eb->i915->drm;
1664 bool have_copy = false;
1665 struct i915_vma *vma;
1669 if (signal_pending(current)) {
1674 /* We may process another execbuffer during the unlock... */
1676 mutex_unlock(&dev->struct_mutex);
1679 * We take 3 passes through the slowpatch.
1681 * 1 - we try to just prefault all the user relocation entries and
1682 * then attempt to reuse the atomic pagefault disabled fast path again.
1684 * 2 - we copy the user entries to a local buffer here outside of the
1685 * local and allow ourselves to wait upon any rendering before
1688 * 3 - we already have a local copy of the relocation entries, but
1689 * were interrupted (EAGAIN) whilst waiting for the objects, try again.
1692 err = eb_prefault_relocations(eb);
1693 } else if (!have_copy) {
1694 err = eb_copy_relocations(eb);
1695 have_copy = err == 0;
1701 mutex_lock(&dev->struct_mutex);
1705 /* A frequent cause for EAGAIN are currently unavailable client pages */
1706 flush_workqueue(eb->i915->mm.userptr_wq);
1708 err = i915_mutex_lock_interruptible(dev);
1710 mutex_lock(&dev->struct_mutex);
1714 /* reacquire the objects */
1715 err = eb_lookup_vmas(eb);
1719 GEM_BUG_ON(!eb->batch);
1721 list_for_each_entry(vma, &eb->relocs, reloc_link) {
1723 pagefault_disable();
1724 err = eb_relocate_vma(eb, vma);
1729 err = eb_relocate_vma_slow(eb, vma);
1736 * Leave the user relocations as are, this is the painfully slow path,
1737 * and we want to avoid the complication of dropping the lock whilst
1738 * having buffers reserved in the aperture and so causing spurious
1739 * ENOSPC for random operations.
1748 const unsigned int count = eb->buffer_count;
1751 for (i = 0; i < count; i++) {
1752 const struct drm_i915_gem_exec_object2 *entry =
1754 struct drm_i915_gem_relocation_entry *relocs;
1756 if (!entry->relocation_count)
1759 relocs = u64_to_ptr(typeof(*relocs), entry->relocs_ptr);
1767 static int eb_relocate(struct i915_execbuffer *eb)
1769 if (eb_lookup_vmas(eb))
1772 /* The objects are in their final locations, apply the relocations. */
1773 if (eb->args->flags & __EXEC_HAS_RELOC) {
1774 struct i915_vma *vma;
1776 list_for_each_entry(vma, &eb->relocs, reloc_link) {
1777 if (eb_relocate_vma(eb, vma))
1785 return eb_relocate_slow(eb);
1788 static int eb_move_to_gpu(struct i915_execbuffer *eb)
1790 const unsigned int count = eb->buffer_count;
1791 struct ww_acquire_ctx acquire;
1795 ww_acquire_init(&acquire, &reservation_ww_class);
1797 for (i = 0; i < count; i++) {
1798 struct i915_vma *vma = eb->vma[i];
1800 err = ww_mutex_lock_interruptible(&vma->resv->lock, &acquire);
1804 GEM_BUG_ON(err == -EALREADY); /* No duplicate vma */
1806 if (err == -EDEADLK) {
1811 ww_mutex_unlock(&eb->vma[j]->resv->lock);
1813 swap(eb->flags[i], eb->flags[j]);
1814 swap(eb->vma[i], eb->vma[j]);
1815 eb->vma[i]->exec_flags = &eb->flags[i];
1817 GEM_BUG_ON(vma != eb->vma[0]);
1818 vma->exec_flags = &eb->flags[0];
1820 err = ww_mutex_lock_slow_interruptible(&vma->resv->lock,
1826 ww_acquire_done(&acquire);
1829 unsigned int flags = eb->flags[i];
1830 struct i915_vma *vma = eb->vma[i];
1831 struct drm_i915_gem_object *obj = vma->obj;
1833 assert_vma_held(vma);
1835 if (flags & EXEC_OBJECT_CAPTURE) {
1836 struct i915_capture_list *capture;
1838 capture = kmalloc(sizeof(*capture), GFP_KERNEL);
1840 capture->next = eb->request->capture_list;
1842 eb->request->capture_list = capture;
1847 * If the GPU is not _reading_ through the CPU cache, we need
1848 * to make sure that any writes (both previous GPU writes from
1849 * before a change in snooping levels and normal CPU writes)
1850 * caught in that cache are flushed to main memory.
1853 * obj->cache_dirty &&
1854 * !(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ)
1855 * but gcc's optimiser doesn't handle that as well and emits
1856 * two jumps instead of one. Maybe one day...
1858 if (unlikely(obj->cache_dirty & ~obj->cache_coherent)) {
1859 if (i915_gem_clflush_object(obj, 0))
1860 flags &= ~EXEC_OBJECT_ASYNC;
1863 if (err == 0 && !(flags & EXEC_OBJECT_ASYNC)) {
1864 err = i915_request_await_object
1865 (eb->request, obj, flags & EXEC_OBJECT_WRITE);
1869 err = i915_vma_move_to_active(vma, eb->request, flags);
1871 i915_vma_unlock(vma);
1873 __eb_unreserve_vma(vma, flags);
1874 vma->exec_flags = NULL;
1876 if (unlikely(flags & __EXEC_OBJECT_HAS_REF))
1879 ww_acquire_fini(&acquire);
1886 /* Unconditionally flush any chipset caches (for streaming writes). */
1887 intel_gt_chipset_flush(eb->engine->gt);
1891 i915_request_skip(eb->request, err);
1895 static int i915_gem_check_execbuffer(struct drm_i915_gem_execbuffer2 *exec)
1897 if (exec->flags & __I915_EXEC_ILLEGAL_FLAGS)
1900 /* Kernel clipping was a DRI1 misfeature */
1901 if (!(exec->flags & I915_EXEC_FENCE_ARRAY)) {
1902 if (exec->num_cliprects || exec->cliprects_ptr)
1906 if (exec->DR4 == 0xffffffff) {
1907 DRM_DEBUG("UXA submitting garbage DR4, fixing up\n");
1910 if (exec->DR1 || exec->DR4)
1913 if ((exec->batch_start_offset | exec->batch_len) & 0x7)
1919 static int i915_reset_gen7_sol_offsets(struct i915_request *rq)
1924 if (!IS_GEN(rq->i915, 7) || rq->engine->id != RCS0) {
1925 DRM_DEBUG("sol reset is gen7/rcs only\n");
1929 cs = intel_ring_begin(rq, 4 * 2 + 2);
1933 *cs++ = MI_LOAD_REGISTER_IMM(4);
1934 for (i = 0; i < 4; i++) {
1935 *cs++ = i915_mmio_reg_offset(GEN7_SO_WRITE_OFFSET(i));
1939 intel_ring_advance(rq, cs);
1944 static struct i915_vma *
1945 shadow_batch_pin(struct drm_i915_gem_object *obj,
1946 struct i915_address_space *vm,
1949 struct i915_vma *vma;
1952 vma = i915_vma_instance(obj, vm, NULL);
1956 err = i915_vma_pin(vma, 0, 0, flags);
1958 return ERR_PTR(err);
1963 struct eb_parse_work {
1964 struct dma_fence_work base;
1965 struct intel_engine_cs *engine;
1966 struct i915_vma *batch;
1967 struct i915_vma *shadow;
1968 struct i915_vma *trampoline;
1969 unsigned int batch_offset;
1970 unsigned int batch_length;
1973 static int __eb_parse(struct dma_fence_work *work)
1975 struct eb_parse_work *pw = container_of(work, typeof(*pw), base);
1977 return intel_engine_cmd_parser(pw->engine,
1985 static void __eb_parse_release(struct dma_fence_work *work)
1987 struct eb_parse_work *pw = container_of(work, typeof(*pw), base);
1990 i915_active_release(&pw->trampoline->active);
1991 i915_active_release(&pw->shadow->active);
1992 i915_active_release(&pw->batch->active);
1995 static const struct dma_fence_work_ops eb_parse_ops = {
1998 .release = __eb_parse_release,
2001 static int eb_parse_pipeline(struct i915_execbuffer *eb,
2002 struct i915_vma *shadow,
2003 struct i915_vma *trampoline)
2005 struct eb_parse_work *pw;
2008 pw = kzalloc(sizeof(*pw), GFP_KERNEL);
2012 err = i915_active_acquire(&eb->batch->active);
2016 err = i915_active_acquire(&shadow->active);
2021 err = i915_active_acquire(&trampoline->active);
2026 dma_fence_work_init(&pw->base, &eb_parse_ops);
2028 pw->engine = eb->engine;
2029 pw->batch = eb->batch;
2030 pw->batch_offset = eb->batch_start_offset;
2031 pw->batch_length = eb->batch_len;
2032 pw->shadow = shadow;
2033 pw->trampoline = trampoline;
2035 err = dma_resv_lock_interruptible(pw->batch->resv, NULL);
2037 goto err_trampoline;
2039 err = dma_resv_reserve_shared(pw->batch->resv, 1);
2041 goto err_batch_unlock;
2043 /* Wait for all writes (and relocs) into the batch to complete */
2044 err = i915_sw_fence_await_reservation(&pw->base.chain,
2045 pw->batch->resv, NULL, false,
2048 goto err_batch_unlock;
2050 /* Keep the batch alive and unwritten as we parse */
2051 dma_resv_add_shared_fence(pw->batch->resv, &pw->base.dma);
2053 dma_resv_unlock(pw->batch->resv);
2055 /* Force execution to wait for completion of the parser */
2056 dma_resv_lock(shadow->resv, NULL);
2057 dma_resv_add_excl_fence(shadow->resv, &pw->base.dma);
2058 dma_resv_unlock(shadow->resv);
2060 dma_fence_work_commit(&pw->base);
2064 dma_resv_unlock(pw->batch->resv);
2067 i915_active_release(&trampoline->active);
2069 i915_active_release(&shadow->active);
2071 i915_active_release(&eb->batch->active);
2077 static int eb_parse(struct i915_execbuffer *eb)
2079 struct intel_engine_pool_node *pool;
2080 struct i915_vma *shadow, *trampoline;
2084 if (!eb_use_cmdparser(eb))
2087 len = eb->batch_len;
2088 if (!CMDPARSER_USES_GGTT(eb->i915)) {
2090 * ppGTT backed shadow buffers must be mapped RO, to prevent
2091 * post-scan tampering
2093 if (!eb->context->vm->has_read_only) {
2094 DRM_DEBUG("Cannot prevent post-scan tampering without RO capable vm\n");
2098 len += I915_CMD_PARSER_TRAMPOLINE_SIZE;
2101 pool = intel_engine_get_pool(eb->engine, len);
2103 return PTR_ERR(pool);
2105 shadow = shadow_batch_pin(pool->obj, eb->context->vm, PIN_USER);
2106 if (IS_ERR(shadow)) {
2107 err = PTR_ERR(shadow);
2110 i915_gem_object_set_readonly(shadow->obj);
2113 if (CMDPARSER_USES_GGTT(eb->i915)) {
2114 trampoline = shadow;
2116 shadow = shadow_batch_pin(pool->obj,
2117 &eb->engine->gt->ggtt->vm,
2119 if (IS_ERR(shadow)) {
2120 err = PTR_ERR(shadow);
2121 shadow = trampoline;
2125 eb->batch_flags |= I915_DISPATCH_SECURE;
2128 err = eb_parse_pipeline(eb, shadow, trampoline);
2130 goto err_trampoline;
2132 eb->vma[eb->buffer_count] = i915_vma_get(shadow);
2133 eb->flags[eb->buffer_count] =
2134 __EXEC_OBJECT_HAS_PIN | __EXEC_OBJECT_HAS_REF;
2135 shadow->exec_flags = &eb->flags[eb->buffer_count];
2138 eb->trampoline = trampoline;
2139 eb->batch_start_offset = 0;
2142 shadow->private = pool;
2147 i915_vma_unpin(trampoline);
2149 i915_vma_unpin(shadow);
2151 intel_engine_pool_put(pool);
2156 add_to_client(struct i915_request *rq, struct drm_file *file)
2158 struct drm_i915_file_private *file_priv = file->driver_priv;
2160 rq->file_priv = file_priv;
2162 spin_lock(&file_priv->mm.lock);
2163 list_add_tail(&rq->client_link, &file_priv->mm.request_list);
2164 spin_unlock(&file_priv->mm.lock);
2167 static int eb_submit(struct i915_execbuffer *eb)
2171 err = eb_move_to_gpu(eb);
2175 if (eb->args->flags & I915_EXEC_GEN7_SOL_RESET) {
2176 err = i915_reset_gen7_sol_offsets(eb->request);
2182 * After we completed waiting for other engines (using HW semaphores)
2183 * then we can signal that this request/batch is ready to run. This
2184 * allows us to determine if the batch is still waiting on the GPU
2185 * or actually running by checking the breadcrumb.
2187 if (eb->engine->emit_init_breadcrumb) {
2188 err = eb->engine->emit_init_breadcrumb(eb->request);
2193 err = eb->engine->emit_bb_start(eb->request,
2194 eb->batch->node.start +
2195 eb->batch_start_offset,
2201 if (eb->trampoline) {
2202 GEM_BUG_ON(eb->batch_start_offset);
2203 err = eb->engine->emit_bb_start(eb->request,
2204 eb->trampoline->node.start +
2211 if (intel_context_nopreempt(eb->context))
2212 __set_bit(I915_FENCE_FLAG_NOPREEMPT, &eb->request->fence.flags);
2217 static int num_vcs_engines(const struct drm_i915_private *i915)
2219 return hweight64(INTEL_INFO(i915)->engine_mask &
2220 GENMASK_ULL(VCS0 + I915_MAX_VCS - 1, VCS0));
2224 * Find one BSD ring to dispatch the corresponding BSD command.
2225 * The engine index is returned.
2228 gen8_dispatch_bsd_engine(struct drm_i915_private *dev_priv,
2229 struct drm_file *file)
2231 struct drm_i915_file_private *file_priv = file->driver_priv;
2233 /* Check whether the file_priv has already selected one ring. */
2234 if ((int)file_priv->bsd_engine < 0)
2235 file_priv->bsd_engine =
2236 get_random_int() % num_vcs_engines(dev_priv);
2238 return file_priv->bsd_engine;
2241 static const enum intel_engine_id user_ring_map[] = {
2242 [I915_EXEC_DEFAULT] = RCS0,
2243 [I915_EXEC_RENDER] = RCS0,
2244 [I915_EXEC_BLT] = BCS0,
2245 [I915_EXEC_BSD] = VCS0,
2246 [I915_EXEC_VEBOX] = VECS0
2249 static struct i915_request *eb_throttle(struct intel_context *ce)
2251 struct intel_ring *ring = ce->ring;
2252 struct intel_timeline *tl = ce->timeline;
2253 struct i915_request *rq;
2256 * Completely unscientific finger-in-the-air estimates for suitable
2257 * maximum user request size (to avoid blocking) and then backoff.
2259 if (intel_ring_update_space(ring) >= PAGE_SIZE)
2263 * Find a request that after waiting upon, there will be at least half
2264 * the ring available. The hysteresis allows us to compete for the
2265 * shared ring and should mean that we sleep less often prior to
2266 * claiming our resources, but not so long that the ring completely
2267 * drains before we can submit our next request.
2269 list_for_each_entry(rq, &tl->requests, link) {
2270 if (rq->ring != ring)
2273 if (__intel_ring_space(rq->postfix,
2274 ring->emit, ring->size) > ring->size / 2)
2277 if (&rq->link == &tl->requests)
2278 return NULL; /* weird, we will check again later for real */
2280 return i915_request_get(rq);
2283 static int __eb_pin_engine(struct i915_execbuffer *eb, struct intel_context *ce)
2285 struct intel_timeline *tl;
2286 struct i915_request *rq;
2290 * ABI: Before userspace accesses the GPU (e.g. execbuffer), report
2291 * EIO if the GPU is already wedged.
2293 err = intel_gt_terminally_wedged(ce->engine->gt);
2297 if (unlikely(intel_context_is_banned(ce)))
2301 * Pinning the contexts may generate requests in order to acquire
2302 * GGTT space, so do this first before we reserve a seqno for
2305 err = intel_context_pin(ce);
2310 * Take a local wakeref for preparing to dispatch the execbuf as
2311 * we expect to access the hardware fairly frequently in the
2312 * process, and require the engine to be kept awake between accesses.
2313 * Upon dispatch, we acquire another prolonged wakeref that we hold
2314 * until the timeline is idle, which in turn releases the wakeref
2315 * taken on the engine, and the parent device.
2317 tl = intel_context_timeline_lock(ce);
2323 intel_context_enter(ce);
2324 rq = eb_throttle(ce);
2326 intel_context_timeline_unlock(tl);
2329 if (i915_request_wait(rq,
2330 I915_WAIT_INTERRUPTIBLE,
2331 MAX_SCHEDULE_TIMEOUT) < 0) {
2332 i915_request_put(rq);
2337 i915_request_put(rq);
2340 eb->engine = ce->engine;
2345 mutex_lock(&tl->mutex);
2346 intel_context_exit(ce);
2347 intel_context_timeline_unlock(tl);
2349 intel_context_unpin(ce);
2353 static void eb_unpin_engine(struct i915_execbuffer *eb)
2355 struct intel_context *ce = eb->context;
2356 struct intel_timeline *tl = ce->timeline;
2358 mutex_lock(&tl->mutex);
2359 intel_context_exit(ce);
2360 mutex_unlock(&tl->mutex);
2362 intel_context_unpin(ce);
2366 eb_select_legacy_ring(struct i915_execbuffer *eb,
2367 struct drm_file *file,
2368 struct drm_i915_gem_execbuffer2 *args)
2370 struct drm_i915_private *i915 = eb->i915;
2371 unsigned int user_ring_id = args->flags & I915_EXEC_RING_MASK;
2373 if (user_ring_id != I915_EXEC_BSD &&
2374 (args->flags & I915_EXEC_BSD_MASK)) {
2375 DRM_DEBUG("execbuf with non bsd ring but with invalid "
2376 "bsd dispatch flags: %d\n", (int)(args->flags));
2380 if (user_ring_id == I915_EXEC_BSD && num_vcs_engines(i915) > 1) {
2381 unsigned int bsd_idx = args->flags & I915_EXEC_BSD_MASK;
2383 if (bsd_idx == I915_EXEC_BSD_DEFAULT) {
2384 bsd_idx = gen8_dispatch_bsd_engine(i915, file);
2385 } else if (bsd_idx >= I915_EXEC_BSD_RING1 &&
2386 bsd_idx <= I915_EXEC_BSD_RING2) {
2387 bsd_idx >>= I915_EXEC_BSD_SHIFT;
2390 DRM_DEBUG("execbuf with unknown bsd ring: %u\n",
2395 return _VCS(bsd_idx);
2398 if (user_ring_id >= ARRAY_SIZE(user_ring_map)) {
2399 DRM_DEBUG("execbuf with unknown ring: %u\n", user_ring_id);
2403 return user_ring_map[user_ring_id];
2407 eb_pin_engine(struct i915_execbuffer *eb,
2408 struct drm_file *file,
2409 struct drm_i915_gem_execbuffer2 *args)
2411 struct intel_context *ce;
2415 if (i915_gem_context_user_engines(eb->gem_context))
2416 idx = args->flags & I915_EXEC_RING_MASK;
2418 idx = eb_select_legacy_ring(eb, file, args);
2420 ce = i915_gem_context_get_engine(eb->gem_context, idx);
2424 err = __eb_pin_engine(eb, ce);
2425 intel_context_put(ce);
2431 __free_fence_array(struct drm_syncobj **fences, unsigned int n)
2434 drm_syncobj_put(ptr_mask_bits(fences[n], 2));
2438 static struct drm_syncobj **
2439 get_fence_array(struct drm_i915_gem_execbuffer2 *args,
2440 struct drm_file *file)
2442 const unsigned long nfences = args->num_cliprects;
2443 struct drm_i915_gem_exec_fence __user *user;
2444 struct drm_syncobj **fences;
2448 if (!(args->flags & I915_EXEC_FENCE_ARRAY))
2451 /* Check multiplication overflow for access_ok() and kvmalloc_array() */
2452 BUILD_BUG_ON(sizeof(size_t) > sizeof(unsigned long));
2453 if (nfences > min_t(unsigned long,
2454 ULONG_MAX / sizeof(*user),
2455 SIZE_MAX / sizeof(*fences)))
2456 return ERR_PTR(-EINVAL);
2458 user = u64_to_user_ptr(args->cliprects_ptr);
2459 if (!access_ok(user, nfences * sizeof(*user)))
2460 return ERR_PTR(-EFAULT);
2462 fences = kvmalloc_array(nfences, sizeof(*fences),
2463 __GFP_NOWARN | GFP_KERNEL);
2465 return ERR_PTR(-ENOMEM);
2467 for (n = 0; n < nfences; n++) {
2468 struct drm_i915_gem_exec_fence fence;
2469 struct drm_syncobj *syncobj;
2471 if (__copy_from_user(&fence, user++, sizeof(fence))) {
2476 if (fence.flags & __I915_EXEC_FENCE_UNKNOWN_FLAGS) {
2481 syncobj = drm_syncobj_find(file, fence.handle);
2483 DRM_DEBUG("Invalid syncobj handle provided\n");
2488 BUILD_BUG_ON(~(ARCH_KMALLOC_MINALIGN - 1) &
2489 ~__I915_EXEC_FENCE_UNKNOWN_FLAGS);
2491 fences[n] = ptr_pack_bits(syncobj, fence.flags, 2);
2497 __free_fence_array(fences, n);
2498 return ERR_PTR(err);
2502 put_fence_array(struct drm_i915_gem_execbuffer2 *args,
2503 struct drm_syncobj **fences)
2506 __free_fence_array(fences, args->num_cliprects);
2510 await_fence_array(struct i915_execbuffer *eb,
2511 struct drm_syncobj **fences)
2513 const unsigned int nfences = eb->args->num_cliprects;
2517 for (n = 0; n < nfences; n++) {
2518 struct drm_syncobj *syncobj;
2519 struct dma_fence *fence;
2522 syncobj = ptr_unpack_bits(fences[n], &flags, 2);
2523 if (!(flags & I915_EXEC_FENCE_WAIT))
2526 fence = drm_syncobj_fence_get(syncobj);
2530 err = i915_request_await_dma_fence(eb->request, fence);
2531 dma_fence_put(fence);
2540 signal_fence_array(struct i915_execbuffer *eb,
2541 struct drm_syncobj **fences)
2543 const unsigned int nfences = eb->args->num_cliprects;
2544 struct dma_fence * const fence = &eb->request->fence;
2547 for (n = 0; n < nfences; n++) {
2548 struct drm_syncobj *syncobj;
2551 syncobj = ptr_unpack_bits(fences[n], &flags, 2);
2552 if (!(flags & I915_EXEC_FENCE_SIGNAL))
2555 drm_syncobj_replace_fence(syncobj, fence);
2560 i915_gem_do_execbuffer(struct drm_device *dev,
2561 struct drm_file *file,
2562 struct drm_i915_gem_execbuffer2 *args,
2563 struct drm_i915_gem_exec_object2 *exec,
2564 struct drm_syncobj **fences)
2566 struct drm_i915_private *i915 = to_i915(dev);
2567 struct i915_execbuffer eb;
2568 struct dma_fence *in_fence = NULL;
2569 struct dma_fence *exec_fence = NULL;
2570 struct sync_file *out_fence = NULL;
2571 int out_fence_fd = -1;
2574 BUILD_BUG_ON(__EXEC_INTERNAL_FLAGS & ~__I915_EXEC_ILLEGAL_FLAGS);
2575 BUILD_BUG_ON(__EXEC_OBJECT_INTERNAL_FLAGS &
2576 ~__EXEC_OBJECT_UNKNOWN_FLAGS);
2581 if (DBG_FORCE_RELOC || !(args->flags & I915_EXEC_NO_RELOC))
2582 args->flags |= __EXEC_HAS_RELOC;
2585 eb.vma = (struct i915_vma **)(exec + args->buffer_count + 1);
2587 eb.flags = (unsigned int *)(eb.vma + args->buffer_count + 1);
2589 eb.invalid_flags = __EXEC_OBJECT_UNKNOWN_FLAGS;
2590 reloc_cache_init(&eb.reloc_cache, eb.i915);
2592 eb.buffer_count = args->buffer_count;
2593 eb.batch_start_offset = args->batch_start_offset;
2594 eb.batch_len = args->batch_len;
2595 eb.trampoline = NULL;
2598 if (args->flags & I915_EXEC_SECURE) {
2599 if (INTEL_GEN(i915) >= 11)
2602 /* Return -EPERM to trigger fallback code on old binaries. */
2603 if (!HAS_SECURE_BATCHES(i915))
2606 if (!drm_is_current_master(file) || !capable(CAP_SYS_ADMIN))
2609 eb.batch_flags |= I915_DISPATCH_SECURE;
2611 if (args->flags & I915_EXEC_IS_PINNED)
2612 eb.batch_flags |= I915_DISPATCH_PINNED;
2614 if (args->flags & I915_EXEC_FENCE_IN) {
2615 in_fence = sync_file_get_fence(lower_32_bits(args->rsvd2));
2620 if (args->flags & I915_EXEC_FENCE_SUBMIT) {
2626 exec_fence = sync_file_get_fence(lower_32_bits(args->rsvd2));
2633 if (args->flags & I915_EXEC_FENCE_OUT) {
2634 out_fence_fd = get_unused_fd_flags(O_CLOEXEC);
2635 if (out_fence_fd < 0) {
2637 goto err_exec_fence;
2641 err = eb_create(&eb);
2645 GEM_BUG_ON(!eb.lut_size);
2647 err = eb_select_context(&eb);
2651 err = eb_pin_engine(&eb, file, args);
2655 err = i915_mutex_lock_interruptible(dev);
2659 err = eb_relocate(&eb);
2662 * If the user expects the execobject.offset and
2663 * reloc.presumed_offset to be an exact match,
2664 * as for using NO_RELOC, then we cannot update
2665 * the execobject.offset until we have completed
2668 args->flags &= ~__EXEC_HAS_RELOC;
2672 if (unlikely(*eb.batch->exec_flags & EXEC_OBJECT_WRITE)) {
2673 DRM_DEBUG("Attempting to use self-modifying batch buffer\n");
2677 if (eb.batch_start_offset > eb.batch->size ||
2678 eb.batch_len > eb.batch->size - eb.batch_start_offset) {
2679 DRM_DEBUG("Attempting to use out-of-bounds batch\n");
2684 if (eb.batch_len == 0)
2685 eb.batch_len = eb.batch->size - eb.batch_start_offset;
2687 err = eb_parse(&eb);
2692 * snb/ivb/vlv conflate the "batch in ppgtt" bit with the "non-secure
2693 * batch" bit. Hence we need to pin secure batches into the global gtt.
2694 * hsw should have this fixed, but bdw mucks it up again. */
2695 if (eb.batch_flags & I915_DISPATCH_SECURE) {
2696 struct i915_vma *vma;
2699 * So on first glance it looks freaky that we pin the batch here
2700 * outside of the reservation loop. But:
2701 * - The batch is already pinned into the relevant ppgtt, so we
2702 * already have the backing storage fully allocated.
2703 * - No other BO uses the global gtt (well contexts, but meh),
2704 * so we don't really have issues with multiple objects not
2705 * fitting due to fragmentation.
2706 * So this is actually safe.
2708 vma = i915_gem_object_ggtt_pin(eb.batch->obj, NULL, 0, 0, 0);
2717 /* All GPU relocation batches must be submitted prior to the user rq */
2718 GEM_BUG_ON(eb.reloc_cache.rq);
2720 /* Allocate a request for this batch buffer nice and early. */
2721 eb.request = i915_request_create(eb.context);
2722 if (IS_ERR(eb.request)) {
2723 err = PTR_ERR(eb.request);
2724 goto err_batch_unpin;
2728 err = i915_request_await_dma_fence(eb.request, in_fence);
2734 err = i915_request_await_execution(eb.request, exec_fence,
2735 eb.engine->bond_execute);
2741 err = await_fence_array(&eb, fences);
2746 if (out_fence_fd != -1) {
2747 out_fence = sync_file_create(&eb.request->fence);
2755 * Whilst this request exists, batch_obj will be on the
2756 * active_list, and so will hold the active reference. Only when this
2757 * request is retired will the the batch_obj be moved onto the
2758 * inactive_list and lose its active reference. Hence we do not need
2759 * to explicitly hold another reference here.
2761 eb.request->batch = eb.batch;
2762 if (eb.batch->private)
2763 intel_engine_pool_mark_active(eb.batch->private, eb.request);
2765 trace_i915_request_queue(eb.request, eb.batch_flags);
2766 err = eb_submit(&eb);
2768 add_to_client(eb.request, file);
2769 i915_request_get(eb.request);
2770 i915_request_add(eb.request);
2773 signal_fence_array(&eb, fences);
2777 fd_install(out_fence_fd, out_fence->file);
2778 args->rsvd2 &= GENMASK_ULL(31, 0); /* keep in-fence */
2779 args->rsvd2 |= (u64)out_fence_fd << 32;
2782 fput(out_fence->file);
2785 i915_request_put(eb.request);
2788 if (eb.batch_flags & I915_DISPATCH_SECURE)
2789 i915_vma_unpin(eb.batch);
2790 if (eb.batch->private)
2791 intel_engine_pool_put(eb.batch->private);
2794 eb_release_vmas(&eb);
2796 i915_vma_unpin(eb.trampoline);
2797 mutex_unlock(&dev->struct_mutex);
2799 eb_unpin_engine(&eb);
2801 i915_gem_context_put(eb.gem_context);
2805 if (out_fence_fd != -1)
2806 put_unused_fd(out_fence_fd);
2808 dma_fence_put(exec_fence);
2810 dma_fence_put(in_fence);
2814 static size_t eb_element_size(void)
2816 return (sizeof(struct drm_i915_gem_exec_object2) +
2817 sizeof(struct i915_vma *) +
2818 sizeof(unsigned int));
2821 static bool check_buffer_count(size_t count)
2823 const size_t sz = eb_element_size();
2826 * When using LUT_HANDLE, we impose a limit of INT_MAX for the lookup
2827 * array size (see eb_create()). Otherwise, we can accept an array as
2828 * large as can be addressed (though use large arrays at your peril)!
2831 return !(count < 1 || count > INT_MAX || count > SIZE_MAX / sz - 1);
2835 * Legacy execbuffer just creates an exec2 list from the original exec object
2836 * list array and passes it to the real function.
2839 i915_gem_execbuffer_ioctl(struct drm_device *dev, void *data,
2840 struct drm_file *file)
2842 struct drm_i915_gem_execbuffer *args = data;
2843 struct drm_i915_gem_execbuffer2 exec2;
2844 struct drm_i915_gem_exec_object *exec_list = NULL;
2845 struct drm_i915_gem_exec_object2 *exec2_list = NULL;
2846 const size_t count = args->buffer_count;
2850 if (!check_buffer_count(count)) {
2851 DRM_DEBUG("execbuf2 with %zd buffers\n", count);
2855 exec2.buffers_ptr = args->buffers_ptr;
2856 exec2.buffer_count = args->buffer_count;
2857 exec2.batch_start_offset = args->batch_start_offset;
2858 exec2.batch_len = args->batch_len;
2859 exec2.DR1 = args->DR1;
2860 exec2.DR4 = args->DR4;
2861 exec2.num_cliprects = args->num_cliprects;
2862 exec2.cliprects_ptr = args->cliprects_ptr;
2863 exec2.flags = I915_EXEC_RENDER;
2864 i915_execbuffer2_set_context_id(exec2, 0);
2866 err = i915_gem_check_execbuffer(&exec2);
2870 /* Copy in the exec list from userland */
2871 exec_list = kvmalloc_array(count, sizeof(*exec_list),
2872 __GFP_NOWARN | GFP_KERNEL);
2873 exec2_list = kvmalloc_array(count + 1, eb_element_size(),
2874 __GFP_NOWARN | GFP_KERNEL);
2875 if (exec_list == NULL || exec2_list == NULL) {
2876 DRM_DEBUG("Failed to allocate exec list for %d buffers\n",
2877 args->buffer_count);
2882 err = copy_from_user(exec_list,
2883 u64_to_user_ptr(args->buffers_ptr),
2884 sizeof(*exec_list) * count);
2886 DRM_DEBUG("copy %d exec entries failed %d\n",
2887 args->buffer_count, err);
2893 for (i = 0; i < args->buffer_count; i++) {
2894 exec2_list[i].handle = exec_list[i].handle;
2895 exec2_list[i].relocation_count = exec_list[i].relocation_count;
2896 exec2_list[i].relocs_ptr = exec_list[i].relocs_ptr;
2897 exec2_list[i].alignment = exec_list[i].alignment;
2898 exec2_list[i].offset = exec_list[i].offset;
2899 if (INTEL_GEN(to_i915(dev)) < 4)
2900 exec2_list[i].flags = EXEC_OBJECT_NEEDS_FENCE;
2902 exec2_list[i].flags = 0;
2905 err = i915_gem_do_execbuffer(dev, file, &exec2, exec2_list, NULL);
2906 if (exec2.flags & __EXEC_HAS_RELOC) {
2907 struct drm_i915_gem_exec_object __user *user_exec_list =
2908 u64_to_user_ptr(args->buffers_ptr);
2910 /* Copy the new buffer offsets back to the user's exec list. */
2911 for (i = 0; i < args->buffer_count; i++) {
2912 if (!(exec2_list[i].offset & UPDATE))
2915 exec2_list[i].offset =
2916 gen8_canonical_addr(exec2_list[i].offset & PIN_OFFSET_MASK);
2917 exec2_list[i].offset &= PIN_OFFSET_MASK;
2918 if (__copy_to_user(&user_exec_list[i].offset,
2919 &exec2_list[i].offset,
2920 sizeof(user_exec_list[i].offset)))
2931 i915_gem_execbuffer2_ioctl(struct drm_device *dev, void *data,
2932 struct drm_file *file)
2934 struct drm_i915_gem_execbuffer2 *args = data;
2935 struct drm_i915_gem_exec_object2 *exec2_list;
2936 struct drm_syncobj **fences = NULL;
2937 const size_t count = args->buffer_count;
2940 if (!check_buffer_count(count)) {
2941 DRM_DEBUG("execbuf2 with %zd buffers\n", count);
2945 err = i915_gem_check_execbuffer(args);
2949 /* Allocate an extra slot for use by the command parser */
2950 exec2_list = kvmalloc_array(count + 1, eb_element_size(),
2951 __GFP_NOWARN | GFP_KERNEL);
2952 if (exec2_list == NULL) {
2953 DRM_DEBUG("Failed to allocate exec list for %zd buffers\n",
2957 if (copy_from_user(exec2_list,
2958 u64_to_user_ptr(args->buffers_ptr),
2959 sizeof(*exec2_list) * count)) {
2960 DRM_DEBUG("copy %zd exec entries failed\n", count);
2965 if (args->flags & I915_EXEC_FENCE_ARRAY) {
2966 fences = get_fence_array(args, file);
2967 if (IS_ERR(fences)) {
2969 return PTR_ERR(fences);
2973 err = i915_gem_do_execbuffer(dev, file, args, exec2_list, fences);
2976 * Now that we have begun execution of the batchbuffer, we ignore
2977 * any new error after this point. Also given that we have already
2978 * updated the associated relocations, we try to write out the current
2979 * object locations irrespective of any error.
2981 if (args->flags & __EXEC_HAS_RELOC) {
2982 struct drm_i915_gem_exec_object2 __user *user_exec_list =
2983 u64_to_user_ptr(args->buffers_ptr);
2986 /* Copy the new buffer offsets back to the user's exec list. */
2988 * Note: count * sizeof(*user_exec_list) does not overflow,
2989 * because we checked 'count' in check_buffer_count().
2991 * And this range already got effectively checked earlier
2992 * when we did the "copy_from_user()" above.
2994 if (!user_access_begin(user_exec_list, count * sizeof(*user_exec_list)))
2997 for (i = 0; i < args->buffer_count; i++) {
2998 if (!(exec2_list[i].offset & UPDATE))
3001 exec2_list[i].offset =
3002 gen8_canonical_addr(exec2_list[i].offset & PIN_OFFSET_MASK);
3003 unsafe_put_user(exec2_list[i].offset,
3004 &user_exec_list[i].offset,
3012 args->flags &= ~__I915_EXEC_UNKNOWN_FLAGS;
3013 put_fence_array(args, fences);