2 * Copyright © 2008,2010 Intel Corporation
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
24 * Eric Anholt <eric@anholt.net>
25 * Chris Wilson <chris@chris-wilson.co.uk>
29 #include <linux/dma_remapping.h>
30 #include <linux/reservation.h>
31 #include <linux/sync_file.h>
32 #include <linux/uaccess.h>
35 #include <drm/drm_syncobj.h>
36 #include <drm/i915_drm.h>
39 #include "i915_gem_clflush.h"
40 #include "i915_trace.h"
41 #include "intel_drv.h"
42 #include "intel_frontbuffer.h"
48 #define DBG_FORCE_RELOC 0 /* choose one of the above! */
51 #define __EXEC_OBJECT_HAS_REF BIT(31)
52 #define __EXEC_OBJECT_HAS_PIN BIT(30)
53 #define __EXEC_OBJECT_HAS_FENCE BIT(29)
54 #define __EXEC_OBJECT_NEEDS_MAP BIT(28)
55 #define __EXEC_OBJECT_NEEDS_BIAS BIT(27)
56 #define __EXEC_OBJECT_INTERNAL_FLAGS (~0u << 27) /* all of the above */
57 #define __EXEC_OBJECT_RESERVED (__EXEC_OBJECT_HAS_PIN | __EXEC_OBJECT_HAS_FENCE)
59 #define __EXEC_HAS_RELOC BIT(31)
60 #define __EXEC_VALIDATED BIT(30)
61 #define UPDATE PIN_OFFSET_FIXED
63 #define BATCH_OFFSET_BIAS (256*1024)
65 #define __I915_EXEC_ILLEGAL_FLAGS \
66 (__I915_EXEC_UNKNOWN_FLAGS | I915_EXEC_CONSTANTS_MASK)
69 * DOC: User command execution
71 * Userspace submits commands to be executed on the GPU as an instruction
72 * stream within a GEM object we call a batchbuffer. This instructions may
73 * refer to other GEM objects containing auxiliary state such as kernels,
74 * samplers, render targets and even secondary batchbuffers. Userspace does
75 * not know where in the GPU memory these objects reside and so before the
76 * batchbuffer is passed to the GPU for execution, those addresses in the
77 * batchbuffer and auxiliary objects are updated. This is known as relocation,
78 * or patching. To try and avoid having to relocate each object on the next
79 * execution, userspace is told the location of those objects in this pass,
80 * but this remains just a hint as the kernel may choose a new location for
81 * any object in the future.
83 * Processing an execbuf ioctl is conceptually split up into a few phases.
85 * 1. Validation - Ensure all the pointers, handles and flags are valid.
86 * 2. Reservation - Assign GPU address space for every object
87 * 3. Relocation - Update any addresses to point to the final locations
88 * 4. Serialisation - Order the request with respect to its dependencies
89 * 5. Construction - Construct a request to execute the batchbuffer
90 * 6. Submission (at some point in the future execution)
92 * Reserving resources for the execbuf is the most complicated phase. We
93 * neither want to have to migrate the object in the address space, nor do
94 * we want to have to update any relocations pointing to this object. Ideally,
95 * we want to leave the object where it is and for all the existing relocations
96 * to match. If the object is given a new address, or if userspace thinks the
97 * object is elsewhere, we have to parse all the relocation entries and update
98 * the addresses. Userspace can set the I915_EXEC_NORELOC flag to hint that
99 * all the target addresses in all of its objects match the value in the
100 * relocation entries and that they all match the presumed offsets given by the
101 * list of execbuffer objects. Using this knowledge, we know that if we haven't
102 * moved any buffers, all the relocation entries are valid and we can skip
103 * the update. (If userspace is wrong, the likely outcome is an impromptu GPU
104 * hang.) The requirement for using I915_EXEC_NO_RELOC are:
106 * The addresses written in the objects must match the corresponding
107 * reloc.presumed_offset which in turn must match the corresponding
110 * Any render targets written to in the batch must be flagged with
113 * To avoid stalling, execobject.offset should match the current
114 * address of that object within the active context.
116 * The reservation is done is multiple phases. First we try and keep any
117 * object already bound in its current location - so as long as meets the
118 * constraints imposed by the new execbuffer. Any object left unbound after the
119 * first pass is then fitted into any available idle space. If an object does
120 * not fit, all objects are removed from the reservation and the process rerun
121 * after sorting the objects into a priority order (more difficult to fit
122 * objects are tried first). Failing that, the entire VM is cleared and we try
123 * to fit the execbuf once last time before concluding that it simply will not
126 * A small complication to all of this is that we allow userspace not only to
127 * specify an alignment and a size for the object in the address space, but
128 * we also allow userspace to specify the exact offset. This objects are
129 * simpler to place (the location is known a priori) all we have to do is make
130 * sure the space is available.
132 * Once all the objects are in place, patching up the buried pointers to point
133 * to the final locations is a fairly simple job of walking over the relocation
134 * entry arrays, looking up the right address and rewriting the value into
135 * the object. Simple! ... The relocation entries are stored in user memory
136 * and so to access them we have to copy them into a local buffer. That copy
137 * has to avoid taking any pagefaults as they may lead back to a GEM object
138 * requiring the struct_mutex (i.e. recursive deadlock). So once again we split
139 * the relocation into multiple passes. First we try to do everything within an
140 * atomic context (avoid the pagefaults) which requires that we never wait. If
141 * we detect that we may wait, or if we need to fault, then we have to fallback
142 * to a slower path. The slowpath has to drop the mutex. (Can you hear alarm
143 * bells yet?) Dropping the mutex means that we lose all the state we have
144 * built up so far for the execbuf and we must reset any global data. However,
145 * we do leave the objects pinned in their final locations - which is a
146 * potential issue for concurrent execbufs. Once we have left the mutex, we can
147 * allocate and copy all the relocation entries into a large array at our
148 * leisure, reacquire the mutex, reclaim all the objects and other state and
149 * then proceed to update any incorrect addresses with the objects.
151 * As we process the relocation entries, we maintain a record of whether the
152 * object is being written to. Using NORELOC, we expect userspace to provide
153 * this information instead. We also check whether we can skip the relocation
154 * by comparing the expected value inside the relocation entry with the target's
155 * final address. If they differ, we have to map the current object and rewrite
156 * the 4 or 8 byte pointer within.
158 * Serialising an execbuf is quite simple according to the rules of the GEM
159 * ABI. Execution within each context is ordered by the order of submission.
160 * Writes to any GEM object are in order of submission and are exclusive. Reads
161 * from a GEM object are unordered with respect to other reads, but ordered by
162 * writes. A write submitted after a read cannot occur before the read, and
163 * similarly any read submitted after a write cannot occur before the write.
164 * Writes are ordered between engines such that only one write occurs at any
165 * time (completing any reads beforehand) - using semaphores where available
166 * and CPU serialisation otherwise. Other GEM access obey the same rules, any
167 * write (either via mmaps using set-domain, or via pwrite) must flush all GPU
168 * reads before starting, and any read (either using set-domain or pread) must
169 * flush all GPU writes before starting. (Note we only employ a barrier before,
170 * we currently rely on userspace not concurrently starting a new execution
171 * whilst reading or writing to an object. This may be an advantage or not
172 * depending on how much you trust userspace not to shoot themselves in the
173 * foot.) Serialisation may just result in the request being inserted into
174 * a DAG awaiting its turn, but most simple is to wait on the CPU until
175 * all dependencies are resolved.
177 * After all of that, is just a matter of closing the request and handing it to
178 * the hardware (well, leaving it in a queue to be executed). However, we also
179 * offer the ability for batchbuffers to be run with elevated privileges so
180 * that they access otherwise hidden registers. (Used to adjust L3 cache etc.)
181 * Before any batch is given extra privileges we first must check that it
182 * contains no nefarious instructions, we check that each instruction is from
183 * our whitelist and all registers are also from an allowed list. We first
184 * copy the user's batchbuffer to a shadow (so that the user doesn't have
185 * access to it, either by the CPU or GPU as we scan it) and then parse each
186 * instruction. If everything is ok, we set a flag telling the hardware to run
187 * the batchbuffer in trusted mode, otherwise the ioctl is rejected.
190 struct i915_execbuffer {
191 struct drm_i915_private *i915; /** i915 backpointer */
192 struct drm_file *file; /** per-file lookup tables and limits */
193 struct drm_i915_gem_execbuffer2 *args; /** ioctl parameters */
194 struct drm_i915_gem_exec_object2 *exec; /** ioctl execobj[] */
195 struct i915_vma **vma;
198 struct intel_engine_cs *engine; /** engine to queue the request to */
199 struct i915_gem_context *ctx; /** context for building the request */
200 struct i915_address_space *vm; /** GTT and vma for the request */
202 struct drm_i915_gem_request *request; /** our request to build */
203 struct i915_vma *batch; /** identity of the batch obj/vma */
205 /** actual size of execobj[] as we may extend it for the cmdparser */
206 unsigned int buffer_count;
208 /** list of vma not yet bound during reservation phase */
209 struct list_head unbound;
211 /** list of vma that have execobj.relocation_count */
212 struct list_head relocs;
215 * Track the most recently used object for relocations, as we
216 * frequently have to perform multiple relocations within the same
220 struct drm_mm_node node; /** temporary GTT binding */
221 unsigned long vaddr; /** Current kmap address */
222 unsigned long page; /** Currently mapped page index */
223 unsigned int gen; /** Cached value of INTEL_GEN */
224 bool use_64bit_reloc : 1;
227 bool needs_unfenced : 1;
229 struct drm_i915_gem_request *rq;
231 unsigned int rq_size;
234 u64 invalid_flags; /** Set of execobj.flags that are invalid */
235 u32 context_flags; /** Set of execobj.flags to insert from the ctx */
237 u32 batch_start_offset; /** Location within object of batch */
238 u32 batch_len; /** Length of batch within object */
239 u32 batch_flags; /** Flags composed for emit_bb_start() */
242 * Indicate either the size of the hastable used to resolve
243 * relocation handles, or if negative that we are using a direct
244 * index into the execobj[].
247 struct hlist_head *buckets; /** ht for relocation handles */
250 #define exec_entry(EB, VMA) (&(EB)->exec[(VMA)->exec_flags - (EB)->flags])
253 * Used to convert any address to canonical form.
254 * Starting from gen8, some commands (e.g. STATE_BASE_ADDRESS,
255 * MI_LOAD_REGISTER_MEM and others, see Broadwell PRM Vol2a) require the
256 * addresses to be in a canonical form:
257 * "GraphicsAddress[63:48] are ignored by the HW and assumed to be in correct
258 * canonical form [63:48] == [47]."
260 #define GEN8_HIGH_ADDRESS_BIT 47
261 static inline u64 gen8_canonical_addr(u64 address)
263 return sign_extend64(address, GEN8_HIGH_ADDRESS_BIT);
266 static inline u64 gen8_noncanonical_addr(u64 address)
268 return address & GENMASK_ULL(GEN8_HIGH_ADDRESS_BIT, 0);
271 static inline bool eb_use_cmdparser(const struct i915_execbuffer *eb)
273 return intel_engine_requires_cmd_parser(eb->engine) ||
274 (intel_engine_using_cmd_parser(eb->engine) &&
275 eb->args->batch_len);
278 static int eb_create(struct i915_execbuffer *eb)
280 if (!(eb->args->flags & I915_EXEC_HANDLE_LUT)) {
281 unsigned int size = 1 + ilog2(eb->buffer_count);
284 * Without a 1:1 association between relocation handles and
285 * the execobject[] index, we instead create a hashtable.
286 * We size it dynamically based on available memory, starting
287 * first with 1:1 assocative hash and scaling back until
288 * the allocation succeeds.
290 * Later on we use a positive lut_size to indicate we are
291 * using this hashtable, and a negative value to indicate a
297 /* While we can still reduce the allocation size, don't
298 * raise a warning and allow the allocation to fail.
299 * On the last pass though, we want to try as hard
300 * as possible to perform the allocation and warn
305 flags |= __GFP_NORETRY | __GFP_NOWARN;
307 eb->buckets = kzalloc(sizeof(struct hlist_head) << size,
318 eb->lut_size = -eb->buffer_count;
325 eb_vma_misplaced(const struct drm_i915_gem_exec_object2 *entry,
326 const struct i915_vma *vma,
329 if (vma->node.size < entry->pad_to_size)
332 if (entry->alignment && !IS_ALIGNED(vma->node.start, entry->alignment))
335 if (flags & EXEC_OBJECT_PINNED &&
336 vma->node.start != entry->offset)
339 if (flags & __EXEC_OBJECT_NEEDS_BIAS &&
340 vma->node.start < BATCH_OFFSET_BIAS)
343 if (!(flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS) &&
344 (vma->node.start + vma->node.size + 4095) >> 32)
347 if (flags & __EXEC_OBJECT_NEEDS_MAP &&
348 !i915_vma_is_map_and_fenceable(vma))
355 eb_pin_vma(struct i915_execbuffer *eb,
356 const struct drm_i915_gem_exec_object2 *entry,
357 struct i915_vma *vma)
359 unsigned int exec_flags = *vma->exec_flags;
363 pin_flags = vma->node.start;
365 pin_flags = entry->offset & PIN_OFFSET_MASK;
367 pin_flags |= PIN_USER | PIN_NOEVICT | PIN_OFFSET_FIXED;
368 if (unlikely(exec_flags & EXEC_OBJECT_NEEDS_GTT))
369 pin_flags |= PIN_GLOBAL;
371 if (unlikely(i915_vma_pin(vma, 0, 0, pin_flags)))
374 if (unlikely(exec_flags & EXEC_OBJECT_NEEDS_FENCE)) {
375 if (unlikely(i915_vma_get_fence(vma))) {
380 if (i915_vma_pin_fence(vma))
381 exec_flags |= __EXEC_OBJECT_HAS_FENCE;
384 *vma->exec_flags = exec_flags | __EXEC_OBJECT_HAS_PIN;
385 return !eb_vma_misplaced(entry, vma, exec_flags);
388 static inline void __eb_unreserve_vma(struct i915_vma *vma, unsigned int flags)
390 GEM_BUG_ON(!(flags & __EXEC_OBJECT_HAS_PIN));
392 if (unlikely(flags & __EXEC_OBJECT_HAS_FENCE))
393 i915_vma_unpin_fence(vma);
395 __i915_vma_unpin(vma);
399 eb_unreserve_vma(struct i915_vma *vma, unsigned int *flags)
401 if (!(*flags & __EXEC_OBJECT_HAS_PIN))
404 __eb_unreserve_vma(vma, *flags);
405 *flags &= ~__EXEC_OBJECT_RESERVED;
409 eb_validate_vma(struct i915_execbuffer *eb,
410 struct drm_i915_gem_exec_object2 *entry,
411 struct i915_vma *vma)
413 if (unlikely(entry->flags & eb->invalid_flags))
416 if (unlikely(entry->alignment && !is_power_of_2(entry->alignment)))
420 * Offset can be used as input (EXEC_OBJECT_PINNED), reject
421 * any non-page-aligned or non-canonical addresses.
423 if (unlikely(entry->flags & EXEC_OBJECT_PINNED &&
424 entry->offset != gen8_canonical_addr(entry->offset & PAGE_MASK)))
427 /* pad_to_size was once a reserved field, so sanitize it */
428 if (entry->flags & EXEC_OBJECT_PAD_TO_SIZE) {
429 if (unlikely(offset_in_page(entry->pad_to_size)))
432 entry->pad_to_size = 0;
435 if (unlikely(vma->exec_flags)) {
436 DRM_DEBUG("Object [handle %d, index %d] appears more than once in object list\n",
437 entry->handle, (int)(entry - eb->exec));
442 * From drm_mm perspective address space is continuous,
443 * so from this point we're always using non-canonical
446 entry->offset = gen8_noncanonical_addr(entry->offset);
448 if (!eb->reloc_cache.has_fence) {
449 entry->flags &= ~EXEC_OBJECT_NEEDS_FENCE;
451 if ((entry->flags & EXEC_OBJECT_NEEDS_FENCE ||
452 eb->reloc_cache.needs_unfenced) &&
453 i915_gem_object_is_tiled(vma->obj))
454 entry->flags |= EXEC_OBJECT_NEEDS_GTT | __EXEC_OBJECT_NEEDS_MAP;
457 if (!(entry->flags & EXEC_OBJECT_PINNED))
458 entry->flags |= eb->context_flags;
464 eb_add_vma(struct i915_execbuffer *eb, unsigned int i, struct i915_vma *vma)
466 struct drm_i915_gem_exec_object2 *entry = &eb->exec[i];
469 GEM_BUG_ON(i915_vma_is_closed(vma));
471 if (!(eb->args->flags & __EXEC_VALIDATED)) {
472 err = eb_validate_vma(eb, entry, vma);
477 if (eb->lut_size > 0) {
478 vma->exec_handle = entry->handle;
479 hlist_add_head(&vma->exec_node,
480 &eb->buckets[hash_32(entry->handle,
484 if (entry->relocation_count)
485 list_add_tail(&vma->reloc_link, &eb->relocs);
488 * Stash a pointer from the vma to execobj, so we can query its flags,
489 * size, alignment etc as provided by the user. Also we stash a pointer
490 * to the vma inside the execobj so that we can use a direct lookup
491 * to find the right target VMA when doing relocations.
494 eb->flags[i] = entry->flags;
495 vma->exec_flags = &eb->flags[i];
498 if (eb_pin_vma(eb, entry, vma)) {
499 if (entry->offset != vma->node.start) {
500 entry->offset = vma->node.start | UPDATE;
501 eb->args->flags |= __EXEC_HAS_RELOC;
504 eb_unreserve_vma(vma, vma->exec_flags);
506 list_add_tail(&vma->exec_link, &eb->unbound);
507 if (drm_mm_node_allocated(&vma->node))
508 err = i915_vma_unbind(vma);
510 vma->exec_flags = NULL;
515 static inline int use_cpu_reloc(const struct reloc_cache *cache,
516 const struct drm_i915_gem_object *obj)
518 if (!i915_gem_object_has_struct_page(obj))
521 if (DBG_FORCE_RELOC == FORCE_CPU_RELOC)
524 if (DBG_FORCE_RELOC == FORCE_GTT_RELOC)
527 return (cache->has_llc ||
529 obj->cache_level != I915_CACHE_NONE);
532 static int eb_reserve_vma(const struct i915_execbuffer *eb,
533 struct i915_vma *vma)
535 struct drm_i915_gem_exec_object2 *entry = exec_entry(eb, vma);
536 unsigned int exec_flags = *vma->exec_flags;
540 pin_flags = PIN_USER | PIN_NONBLOCK;
541 if (exec_flags & EXEC_OBJECT_NEEDS_GTT)
542 pin_flags |= PIN_GLOBAL;
545 * Wa32bitGeneralStateOffset & Wa32bitInstructionBaseOffset,
546 * limit address to the first 4GBs for unflagged objects.
548 if (!(exec_flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS))
549 pin_flags |= PIN_ZONE_4G;
551 if (exec_flags & __EXEC_OBJECT_NEEDS_MAP)
552 pin_flags |= PIN_MAPPABLE;
554 if (exec_flags & EXEC_OBJECT_PINNED) {
555 pin_flags |= entry->offset | PIN_OFFSET_FIXED;
556 pin_flags &= ~PIN_NONBLOCK; /* force overlapping checks */
557 } else if (exec_flags & __EXEC_OBJECT_NEEDS_BIAS) {
558 pin_flags |= BATCH_OFFSET_BIAS | PIN_OFFSET_BIAS;
561 err = i915_vma_pin(vma,
562 entry->pad_to_size, entry->alignment,
567 if (entry->offset != vma->node.start) {
568 entry->offset = vma->node.start | UPDATE;
569 eb->args->flags |= __EXEC_HAS_RELOC;
572 if (unlikely(exec_flags & EXEC_OBJECT_NEEDS_FENCE)) {
573 err = i915_vma_get_fence(vma);
579 if (i915_vma_pin_fence(vma))
580 exec_flags |= __EXEC_OBJECT_HAS_FENCE;
583 *vma->exec_flags = exec_flags | __EXEC_OBJECT_HAS_PIN;
584 GEM_BUG_ON(eb_vma_misplaced(entry, vma, exec_flags));
589 static int eb_reserve(struct i915_execbuffer *eb)
591 const unsigned int count = eb->buffer_count;
592 struct list_head last;
593 struct i915_vma *vma;
594 unsigned int i, pass;
598 * Attempt to pin all of the buffers into the GTT.
599 * This is done in 3 phases:
601 * 1a. Unbind all objects that do not match the GTT constraints for
602 * the execbuffer (fenceable, mappable, alignment etc).
603 * 1b. Increment pin count for already bound objects.
604 * 2. Bind new objects.
605 * 3. Decrement pin count.
607 * This avoid unnecessary unbinding of later objects in order to make
608 * room for the earlier objects *unless* we need to defragment.
614 list_for_each_entry(vma, &eb->unbound, exec_link) {
615 err = eb_reserve_vma(eb, vma);
622 /* Resort *all* the objects into priority order */
623 INIT_LIST_HEAD(&eb->unbound);
624 INIT_LIST_HEAD(&last);
625 for (i = 0; i < count; i++) {
626 unsigned int flags = eb->flags[i];
627 struct i915_vma *vma = eb->vma[i];
629 if (flags & EXEC_OBJECT_PINNED &&
630 flags & __EXEC_OBJECT_HAS_PIN)
633 eb_unreserve_vma(vma, &eb->flags[i]);
635 if (flags & EXEC_OBJECT_PINNED)
636 list_add(&vma->exec_link, &eb->unbound);
637 else if (flags & __EXEC_OBJECT_NEEDS_MAP)
638 list_add_tail(&vma->exec_link, &eb->unbound);
640 list_add_tail(&vma->exec_link, &last);
642 list_splice_tail(&last, &eb->unbound);
649 /* Too fragmented, unbind everything and retry */
650 err = i915_gem_evict_vm(eb->vm);
661 static unsigned int eb_batch_index(const struct i915_execbuffer *eb)
663 if (eb->args->flags & I915_EXEC_BATCH_FIRST)
666 return eb->buffer_count - 1;
669 static int eb_select_context(struct i915_execbuffer *eb)
671 struct i915_gem_context *ctx;
673 ctx = i915_gem_context_lookup(eb->file->driver_priv, eb->args->rsvd1);
678 eb->vm = ctx->ppgtt ? &ctx->ppgtt->base : &eb->i915->ggtt.base;
680 eb->context_flags = 0;
681 if (ctx->flags & CONTEXT_NO_ZEROMAP)
682 eb->context_flags |= __EXEC_OBJECT_NEEDS_BIAS;
687 static int eb_lookup_vmas(struct i915_execbuffer *eb)
689 struct radix_tree_root *handles_vma = &eb->ctx->handles_vma;
690 struct drm_i915_gem_object *uninitialized_var(obj);
694 if (unlikely(i915_gem_context_is_closed(eb->ctx)))
697 if (unlikely(i915_gem_context_is_banned(eb->ctx)))
700 INIT_LIST_HEAD(&eb->relocs);
701 INIT_LIST_HEAD(&eb->unbound);
703 for (i = 0; i < eb->buffer_count; i++) {
704 u32 handle = eb->exec[i].handle;
705 struct i915_lut_handle *lut;
706 struct i915_vma *vma;
708 vma = radix_tree_lookup(handles_vma, handle);
712 obj = i915_gem_object_lookup(eb->file, handle);
713 if (unlikely(!obj)) {
718 vma = i915_vma_instance(obj, eb->vm, NULL);
719 if (unlikely(IS_ERR(vma))) {
724 lut = kmem_cache_alloc(eb->i915->luts, GFP_KERNEL);
725 if (unlikely(!lut)) {
730 err = radix_tree_insert(handles_vma, handle, vma);
732 kmem_cache_free(eb->i915->luts, lut);
737 list_add(&lut->obj_link, &obj->lut_list);
738 list_add(&lut->ctx_link, &eb->ctx->handles_list);
740 lut->handle = handle;
742 /* transfer ref to ctx */
746 err = eb_add_vma(eb, i, vma);
750 GEM_BUG_ON(vma != eb->vma[i]);
751 GEM_BUG_ON(vma->exec_flags != &eb->flags[i]);
754 /* take note of the batch buffer before we might reorder the lists */
755 i = eb_batch_index(eb);
756 eb->batch = eb->vma[i];
757 GEM_BUG_ON(eb->batch->exec_flags != &eb->flags[i]);
760 * SNA is doing fancy tricks with compressing batch buffers, which leads
761 * to negative relocation deltas. Usually that works out ok since the
762 * relocate address is still positive, except when the batch is placed
763 * very low in the GTT. Ensure this doesn't happen.
765 * Note that actual hangs have only been observed on gen7, but for
766 * paranoia do it everywhere.
768 if (!(eb->flags[i] & EXEC_OBJECT_PINNED))
769 eb->flags[i] |= __EXEC_OBJECT_NEEDS_BIAS;
770 if (eb->reloc_cache.has_fence)
771 eb->flags[i] |= EXEC_OBJECT_NEEDS_FENCE;
773 eb->args->flags |= __EXEC_VALIDATED;
774 return eb_reserve(eb);
778 i915_gem_object_put(obj);
784 static struct i915_vma *
785 eb_get_vma(const struct i915_execbuffer *eb, unsigned long handle)
787 if (eb->lut_size < 0) {
788 if (handle >= -eb->lut_size)
790 return eb->vma[handle];
792 struct hlist_head *head;
793 struct i915_vma *vma;
795 head = &eb->buckets[hash_32(handle, eb->lut_size)];
796 hlist_for_each_entry(vma, head, exec_node) {
797 if (vma->exec_handle == handle)
804 static void eb_release_vmas(const struct i915_execbuffer *eb)
806 const unsigned int count = eb->buffer_count;
809 for (i = 0; i < count; i++) {
810 struct i915_vma *vma = eb->vma[i];
811 unsigned int flags = eb->flags[i];
816 GEM_BUG_ON(vma->exec_flags != &eb->flags[i]);
817 vma->exec_flags = NULL;
820 if (flags & __EXEC_OBJECT_HAS_PIN)
821 __eb_unreserve_vma(vma, flags);
823 if (flags & __EXEC_OBJECT_HAS_REF)
828 static void eb_reset_vmas(const struct i915_execbuffer *eb)
831 if (eb->lut_size > 0)
832 memset(eb->buckets, 0,
833 sizeof(struct hlist_head) << eb->lut_size);
836 static void eb_destroy(const struct i915_execbuffer *eb)
838 GEM_BUG_ON(eb->reloc_cache.rq);
840 if (eb->lut_size > 0)
845 relocation_target(const struct drm_i915_gem_relocation_entry *reloc,
846 const struct i915_vma *target)
848 return gen8_canonical_addr((int)reloc->delta + target->node.start);
851 static void reloc_cache_init(struct reloc_cache *cache,
852 struct drm_i915_private *i915)
856 /* Must be a variable in the struct to allow GCC to unroll. */
857 cache->gen = INTEL_GEN(i915);
858 cache->has_llc = HAS_LLC(i915);
859 cache->use_64bit_reloc = HAS_64BIT_RELOC(i915);
860 cache->has_fence = cache->gen < 4;
861 cache->needs_unfenced = INTEL_INFO(i915)->unfenced_needs_alignment;
862 cache->node.allocated = false;
867 static inline void *unmask_page(unsigned long p)
869 return (void *)(uintptr_t)(p & PAGE_MASK);
872 static inline unsigned int unmask_flags(unsigned long p)
874 return p & ~PAGE_MASK;
877 #define KMAP 0x4 /* after CLFLUSH_FLAGS */
879 static inline struct i915_ggtt *cache_to_ggtt(struct reloc_cache *cache)
881 struct drm_i915_private *i915 =
882 container_of(cache, struct i915_execbuffer, reloc_cache)->i915;
886 static void reloc_gpu_flush(struct reloc_cache *cache)
888 GEM_BUG_ON(cache->rq_size >= cache->rq->batch->obj->base.size / sizeof(u32));
889 cache->rq_cmd[cache->rq_size] = MI_BATCH_BUFFER_END;
890 i915_gem_object_unpin_map(cache->rq->batch->obj);
891 i915_gem_chipset_flush(cache->rq->i915);
893 __i915_add_request(cache->rq, true);
897 static void reloc_cache_reset(struct reloc_cache *cache)
902 reloc_gpu_flush(cache);
907 vaddr = unmask_page(cache->vaddr);
908 if (cache->vaddr & KMAP) {
909 if (cache->vaddr & CLFLUSH_AFTER)
912 kunmap_atomic(vaddr);
913 i915_gem_obj_finish_shmem_access((struct drm_i915_gem_object *)cache->node.mm);
916 io_mapping_unmap_atomic((void __iomem *)vaddr);
917 if (cache->node.allocated) {
918 struct i915_ggtt *ggtt = cache_to_ggtt(cache);
920 ggtt->base.clear_range(&ggtt->base,
923 drm_mm_remove_node(&cache->node);
925 i915_vma_unpin((struct i915_vma *)cache->node.mm);
933 static void *reloc_kmap(struct drm_i915_gem_object *obj,
934 struct reloc_cache *cache,
940 kunmap_atomic(unmask_page(cache->vaddr));
942 unsigned int flushes;
945 err = i915_gem_obj_prepare_shmem_write(obj, &flushes);
949 BUILD_BUG_ON(KMAP & CLFLUSH_FLAGS);
950 BUILD_BUG_ON((KMAP | CLFLUSH_FLAGS) & PAGE_MASK);
952 cache->vaddr = flushes | KMAP;
953 cache->node.mm = (void *)obj;
958 vaddr = kmap_atomic(i915_gem_object_get_dirty_page(obj, page));
959 cache->vaddr = unmask_flags(cache->vaddr) | (unsigned long)vaddr;
965 static void *reloc_iomap(struct drm_i915_gem_object *obj,
966 struct reloc_cache *cache,
969 struct i915_ggtt *ggtt = cache_to_ggtt(cache);
970 unsigned long offset;
974 io_mapping_unmap_atomic((void __force __iomem *) unmask_page(cache->vaddr));
976 struct i915_vma *vma;
979 if (use_cpu_reloc(cache, obj))
982 err = i915_gem_object_set_to_gtt_domain(obj, true);
986 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
987 PIN_MAPPABLE | PIN_NONBLOCK);
989 memset(&cache->node, 0, sizeof(cache->node));
990 err = drm_mm_insert_node_in_range
991 (&ggtt->base.mm, &cache->node,
992 PAGE_SIZE, 0, I915_COLOR_UNEVICTABLE,
993 0, ggtt->mappable_end,
995 if (err) /* no inactive aperture space, use cpu reloc */
998 err = i915_vma_put_fence(vma);
1000 i915_vma_unpin(vma);
1001 return ERR_PTR(err);
1004 cache->node.start = vma->node.start;
1005 cache->node.mm = (void *)vma;
1009 offset = cache->node.start;
1010 if (cache->node.allocated) {
1012 ggtt->base.insert_page(&ggtt->base,
1013 i915_gem_object_get_dma_address(obj, page),
1014 offset, I915_CACHE_NONE, 0);
1016 offset += page << PAGE_SHIFT;
1019 vaddr = (void __force *)io_mapping_map_atomic_wc(&ggtt->mappable,
1022 cache->vaddr = (unsigned long)vaddr;
1027 static void *reloc_vaddr(struct drm_i915_gem_object *obj,
1028 struct reloc_cache *cache,
1033 if (cache->page == page) {
1034 vaddr = unmask_page(cache->vaddr);
1037 if ((cache->vaddr & KMAP) == 0)
1038 vaddr = reloc_iomap(obj, cache, page);
1040 vaddr = reloc_kmap(obj, cache, page);
1046 static void clflush_write32(u32 *addr, u32 value, unsigned int flushes)
1048 if (unlikely(flushes & (CLFLUSH_BEFORE | CLFLUSH_AFTER))) {
1049 if (flushes & CLFLUSH_BEFORE) {
1057 * Writes to the same cacheline are serialised by the CPU
1058 * (including clflush). On the write path, we only require
1059 * that it hits memory in an orderly fashion and place
1060 * mb barriers at the start and end of the relocation phase
1061 * to ensure ordering of clflush wrt to the system.
1063 if (flushes & CLFLUSH_AFTER)
1069 static int __reloc_gpu_alloc(struct i915_execbuffer *eb,
1070 struct i915_vma *vma,
1073 struct reloc_cache *cache = &eb->reloc_cache;
1074 struct drm_i915_gem_object *obj;
1075 struct drm_i915_gem_request *rq;
1076 struct i915_vma *batch;
1080 GEM_BUG_ON(vma->obj->base.write_domain & I915_GEM_DOMAIN_CPU);
1082 obj = i915_gem_batch_pool_get(&eb->engine->batch_pool, PAGE_SIZE);
1084 return PTR_ERR(obj);
1086 cmd = i915_gem_object_pin_map(obj,
1090 i915_gem_object_unpin_pages(obj);
1092 return PTR_ERR(cmd);
1094 err = i915_gem_object_set_to_wc_domain(obj, false);
1098 batch = i915_vma_instance(obj, vma->vm, NULL);
1099 if (IS_ERR(batch)) {
1100 err = PTR_ERR(batch);
1104 err = i915_vma_pin(batch, 0, 0, PIN_USER | PIN_NONBLOCK);
1108 rq = i915_gem_request_alloc(eb->engine, eb->ctx);
1114 err = i915_gem_request_await_object(rq, vma->obj, true);
1118 err = eb->engine->emit_flush(rq, EMIT_INVALIDATE);
1122 err = i915_switch_context(rq);
1126 err = eb->engine->emit_bb_start(rq,
1127 batch->node.start, PAGE_SIZE,
1128 cache->gen > 5 ? 0 : I915_DISPATCH_SECURE);
1132 GEM_BUG_ON(!reservation_object_test_signaled_rcu(batch->resv, true));
1133 i915_vma_move_to_active(batch, rq, 0);
1134 reservation_object_lock(batch->resv, NULL);
1135 reservation_object_add_excl_fence(batch->resv, &rq->fence);
1136 reservation_object_unlock(batch->resv);
1137 i915_vma_unpin(batch);
1139 i915_vma_move_to_active(vma, rq, EXEC_OBJECT_WRITE);
1140 reservation_object_lock(vma->resv, NULL);
1141 reservation_object_add_excl_fence(vma->resv, &rq->fence);
1142 reservation_object_unlock(vma->resv);
1147 cache->rq_cmd = cmd;
1150 /* Return with batch mapping (cmd) still pinned */
1154 i915_add_request(rq);
1156 i915_vma_unpin(batch);
1158 i915_gem_object_unpin_map(obj);
1162 static u32 *reloc_gpu(struct i915_execbuffer *eb,
1163 struct i915_vma *vma,
1166 struct reloc_cache *cache = &eb->reloc_cache;
1169 if (cache->rq_size > PAGE_SIZE/sizeof(u32) - (len + 1))
1170 reloc_gpu_flush(cache);
1172 if (unlikely(!cache->rq)) {
1175 /* If we need to copy for the cmdparser, we will stall anyway */
1176 if (eb_use_cmdparser(eb))
1177 return ERR_PTR(-EWOULDBLOCK);
1179 err = __reloc_gpu_alloc(eb, vma, len);
1181 return ERR_PTR(err);
1184 cmd = cache->rq_cmd + cache->rq_size;
1185 cache->rq_size += len;
1191 relocate_entry(struct i915_vma *vma,
1192 const struct drm_i915_gem_relocation_entry *reloc,
1193 struct i915_execbuffer *eb,
1194 const struct i915_vma *target)
1196 u64 offset = reloc->offset;
1197 u64 target_offset = relocation_target(reloc, target);
1198 bool wide = eb->reloc_cache.use_64bit_reloc;
1201 if (!eb->reloc_cache.vaddr &&
1202 (DBG_FORCE_RELOC == FORCE_GPU_RELOC ||
1203 !reservation_object_test_signaled_rcu(vma->resv, true)) &&
1204 __intel_engine_can_store_dword(eb->reloc_cache.gen,
1205 eb->engine->class)) {
1206 const unsigned int gen = eb->reloc_cache.gen;
1212 len = offset & 7 ? 8 : 5;
1218 batch = reloc_gpu(eb, vma, len);
1222 addr = gen8_canonical_addr(vma->node.start + offset);
1225 *batch++ = MI_STORE_DWORD_IMM_GEN4;
1226 *batch++ = lower_32_bits(addr);
1227 *batch++ = upper_32_bits(addr);
1228 *batch++ = lower_32_bits(target_offset);
1230 addr = gen8_canonical_addr(addr + 4);
1232 *batch++ = MI_STORE_DWORD_IMM_GEN4;
1233 *batch++ = lower_32_bits(addr);
1234 *batch++ = upper_32_bits(addr);
1235 *batch++ = upper_32_bits(target_offset);
1237 *batch++ = (MI_STORE_DWORD_IMM_GEN4 | (1 << 21)) + 1;
1238 *batch++ = lower_32_bits(addr);
1239 *batch++ = upper_32_bits(addr);
1240 *batch++ = lower_32_bits(target_offset);
1241 *batch++ = upper_32_bits(target_offset);
1243 } else if (gen >= 6) {
1244 *batch++ = MI_STORE_DWORD_IMM_GEN4;
1247 *batch++ = target_offset;
1248 } else if (gen >= 4) {
1249 *batch++ = MI_STORE_DWORD_IMM_GEN4 | MI_USE_GGTT;
1252 *batch++ = target_offset;
1254 *batch++ = MI_STORE_DWORD_IMM | MI_MEM_VIRTUAL;
1256 *batch++ = target_offset;
1263 vaddr = reloc_vaddr(vma->obj, &eb->reloc_cache, offset >> PAGE_SHIFT);
1265 return PTR_ERR(vaddr);
1267 clflush_write32(vaddr + offset_in_page(offset),
1268 lower_32_bits(target_offset),
1269 eb->reloc_cache.vaddr);
1272 offset += sizeof(u32);
1273 target_offset >>= 32;
1279 return target->node.start | UPDATE;
1283 eb_relocate_entry(struct i915_execbuffer *eb,
1284 struct i915_vma *vma,
1285 const struct drm_i915_gem_relocation_entry *reloc)
1287 struct i915_vma *target;
1290 /* we've already hold a reference to all valid objects */
1291 target = eb_get_vma(eb, reloc->target_handle);
1292 if (unlikely(!target))
1295 /* Validate that the target is in a valid r/w GPU domain */
1296 if (unlikely(reloc->write_domain & (reloc->write_domain - 1))) {
1297 DRM_DEBUG("reloc with multiple write domains: "
1298 "target %d offset %d "
1299 "read %08x write %08x",
1300 reloc->target_handle,
1301 (int) reloc->offset,
1302 reloc->read_domains,
1303 reloc->write_domain);
1306 if (unlikely((reloc->write_domain | reloc->read_domains)
1307 & ~I915_GEM_GPU_DOMAINS)) {
1308 DRM_DEBUG("reloc with read/write non-GPU domains: "
1309 "target %d offset %d "
1310 "read %08x write %08x",
1311 reloc->target_handle,
1312 (int) reloc->offset,
1313 reloc->read_domains,
1314 reloc->write_domain);
1318 if (reloc->write_domain) {
1319 *target->exec_flags |= EXEC_OBJECT_WRITE;
1322 * Sandybridge PPGTT errata: We need a global gtt mapping
1323 * for MI and pipe_control writes because the gpu doesn't
1324 * properly redirect them through the ppgtt for non_secure
1327 if (reloc->write_domain == I915_GEM_DOMAIN_INSTRUCTION &&
1328 IS_GEN6(eb->i915)) {
1329 err = i915_vma_bind(target, target->obj->cache_level,
1332 "Unexpected failure to bind target VMA!"))
1338 * If the relocation already has the right value in it, no
1339 * more work needs to be done.
1341 if (!DBG_FORCE_RELOC &&
1342 gen8_canonical_addr(target->node.start) == reloc->presumed_offset)
1345 /* Check that the relocation address is valid... */
1346 if (unlikely(reloc->offset >
1347 vma->size - (eb->reloc_cache.use_64bit_reloc ? 8 : 4))) {
1348 DRM_DEBUG("Relocation beyond object bounds: "
1349 "target %d offset %d size %d.\n",
1350 reloc->target_handle,
1355 if (unlikely(reloc->offset & 3)) {
1356 DRM_DEBUG("Relocation not 4-byte aligned: "
1357 "target %d offset %d.\n",
1358 reloc->target_handle,
1359 (int)reloc->offset);
1364 * If we write into the object, we need to force the synchronisation
1365 * barrier, either with an asynchronous clflush or if we executed the
1366 * patching using the GPU (though that should be serialised by the
1367 * timeline). To be completely sure, and since we are required to
1368 * do relocations we are already stalling, disable the user's opt
1369 * out of our synchronisation.
1371 *vma->exec_flags &= ~EXEC_OBJECT_ASYNC;
1373 /* and update the user's relocation entry */
1374 return relocate_entry(vma, reloc, eb, target);
1377 static int eb_relocate_vma(struct i915_execbuffer *eb, struct i915_vma *vma)
1379 #define N_RELOC(x) ((x) / sizeof(struct drm_i915_gem_relocation_entry))
1380 struct drm_i915_gem_relocation_entry stack[N_RELOC(512)];
1381 struct drm_i915_gem_relocation_entry __user *urelocs;
1382 const struct drm_i915_gem_exec_object2 *entry = exec_entry(eb, vma);
1383 unsigned int remain;
1385 urelocs = u64_to_user_ptr(entry->relocs_ptr);
1386 remain = entry->relocation_count;
1387 if (unlikely(remain > N_RELOC(ULONG_MAX)))
1391 * We must check that the entire relocation array is safe
1392 * to read. However, if the array is not writable the user loses
1393 * the updated relocation values.
1395 if (unlikely(!access_ok(VERIFY_READ, urelocs, remain*sizeof(*urelocs))))
1399 struct drm_i915_gem_relocation_entry *r = stack;
1400 unsigned int count =
1401 min_t(unsigned int, remain, ARRAY_SIZE(stack));
1402 unsigned int copied;
1405 * This is the fast path and we cannot handle a pagefault
1406 * whilst holding the struct mutex lest the user pass in the
1407 * relocations contained within a mmaped bo. For in such a case
1408 * we, the page fault handler would call i915_gem_fault() and
1409 * we would try to acquire the struct mutex again. Obviously
1410 * this is bad and so lockdep complains vehemently.
1412 pagefault_disable();
1413 copied = __copy_from_user_inatomic(r, urelocs, count * sizeof(r[0]));
1415 if (unlikely(copied)) {
1422 u64 offset = eb_relocate_entry(eb, vma, r);
1424 if (likely(offset == 0)) {
1425 } else if ((s64)offset < 0) {
1426 remain = (int)offset;
1430 * Note that reporting an error now
1431 * leaves everything in an inconsistent
1432 * state as we have *already* changed
1433 * the relocation value inside the
1434 * object. As we have not changed the
1435 * reloc.presumed_offset or will not
1436 * change the execobject.offset, on the
1437 * call we may not rewrite the value
1438 * inside the object, leaving it
1439 * dangling and causing a GPU hang. Unless
1440 * userspace dynamically rebuilds the
1441 * relocations on each execbuf rather than
1442 * presume a static tree.
1444 * We did previously check if the relocations
1445 * were writable (access_ok), an error now
1446 * would be a strange race with mprotect,
1447 * having already demonstrated that we
1448 * can read from this userspace address.
1450 offset = gen8_canonical_addr(offset & ~UPDATE);
1452 &urelocs[r-stack].presumed_offset);
1454 } while (r++, --count);
1455 urelocs += ARRAY_SIZE(stack);
1458 reloc_cache_reset(&eb->reloc_cache);
1463 eb_relocate_vma_slow(struct i915_execbuffer *eb, struct i915_vma *vma)
1465 const struct drm_i915_gem_exec_object2 *entry = exec_entry(eb, vma);
1466 struct drm_i915_gem_relocation_entry *relocs =
1467 u64_to_ptr(typeof(*relocs), entry->relocs_ptr);
1471 for (i = 0; i < entry->relocation_count; i++) {
1472 u64 offset = eb_relocate_entry(eb, vma, &relocs[i]);
1474 if ((s64)offset < 0) {
1481 reloc_cache_reset(&eb->reloc_cache);
1485 static int check_relocations(const struct drm_i915_gem_exec_object2 *entry)
1487 const char __user *addr, *end;
1489 char __maybe_unused c;
1491 size = entry->relocation_count;
1495 if (size > N_RELOC(ULONG_MAX))
1498 addr = u64_to_user_ptr(entry->relocs_ptr);
1499 size *= sizeof(struct drm_i915_gem_relocation_entry);
1500 if (!access_ok(VERIFY_READ, addr, size))
1504 for (; addr < end; addr += PAGE_SIZE) {
1505 int err = __get_user(c, addr);
1509 return __get_user(c, end - 1);
1512 static int eb_copy_relocations(const struct i915_execbuffer *eb)
1514 const unsigned int count = eb->buffer_count;
1518 for (i = 0; i < count; i++) {
1519 const unsigned int nreloc = eb->exec[i].relocation_count;
1520 struct drm_i915_gem_relocation_entry __user *urelocs;
1521 struct drm_i915_gem_relocation_entry *relocs;
1523 unsigned long copied;
1528 err = check_relocations(&eb->exec[i]);
1532 urelocs = u64_to_user_ptr(eb->exec[i].relocs_ptr);
1533 size = nreloc * sizeof(*relocs);
1535 relocs = kvmalloc_array(size, 1, GFP_KERNEL);
1542 /* copy_from_user is limited to < 4GiB */
1546 min_t(u64, BIT_ULL(31), size - copied);
1548 if (__copy_from_user((char *)relocs + copied,
1549 (char __user *)urelocs + copied,
1557 } while (copied < size);
1560 * As we do not update the known relocation offsets after
1561 * relocating (due to the complexities in lock handling),
1562 * we need to mark them as invalid now so that we force the
1563 * relocation processing next time. Just in case the target
1564 * object is evicted and then rebound into its old
1565 * presumed_offset before the next execbuffer - if that
1566 * happened we would make the mistake of assuming that the
1567 * relocations were valid.
1569 if (!user_access_begin(VERIFY_WRITE, urelocs, size))
1572 for (copied = 0; copied < nreloc; copied++)
1574 &urelocs[copied].presumed_offset,
1579 eb->exec[i].relocs_ptr = (uintptr_t)relocs;
1586 struct drm_i915_gem_relocation_entry *relocs =
1587 u64_to_ptr(typeof(*relocs), eb->exec[i].relocs_ptr);
1588 if (eb->exec[i].relocation_count)
1594 static int eb_prefault_relocations(const struct i915_execbuffer *eb)
1596 const unsigned int count = eb->buffer_count;
1599 if (unlikely(i915.prefault_disable))
1602 for (i = 0; i < count; i++) {
1605 err = check_relocations(&eb->exec[i]);
1613 static noinline int eb_relocate_slow(struct i915_execbuffer *eb)
1615 struct drm_device *dev = &eb->i915->drm;
1616 bool have_copy = false;
1617 struct i915_vma *vma;
1621 if (signal_pending(current)) {
1626 /* We may process another execbuffer during the unlock... */
1628 mutex_unlock(&dev->struct_mutex);
1631 * We take 3 passes through the slowpatch.
1633 * 1 - we try to just prefault all the user relocation entries and
1634 * then attempt to reuse the atomic pagefault disabled fast path again.
1636 * 2 - we copy the user entries to a local buffer here outside of the
1637 * local and allow ourselves to wait upon any rendering before
1640 * 3 - we already have a local copy of the relocation entries, but
1641 * were interrupted (EAGAIN) whilst waiting for the objects, try again.
1644 err = eb_prefault_relocations(eb);
1645 } else if (!have_copy) {
1646 err = eb_copy_relocations(eb);
1647 have_copy = err == 0;
1653 mutex_lock(&dev->struct_mutex);
1657 /* A frequent cause for EAGAIN are currently unavailable client pages */
1658 flush_workqueue(eb->i915->mm.userptr_wq);
1660 err = i915_mutex_lock_interruptible(dev);
1662 mutex_lock(&dev->struct_mutex);
1666 /* reacquire the objects */
1667 err = eb_lookup_vmas(eb);
1671 GEM_BUG_ON(!eb->batch);
1673 list_for_each_entry(vma, &eb->relocs, reloc_link) {
1675 pagefault_disable();
1676 err = eb_relocate_vma(eb, vma);
1681 err = eb_relocate_vma_slow(eb, vma);
1688 * Leave the user relocations as are, this is the painfully slow path,
1689 * and we want to avoid the complication of dropping the lock whilst
1690 * having buffers reserved in the aperture and so causing spurious
1691 * ENOSPC for random operations.
1700 const unsigned int count = eb->buffer_count;
1703 for (i = 0; i < count; i++) {
1704 const struct drm_i915_gem_exec_object2 *entry =
1706 struct drm_i915_gem_relocation_entry *relocs;
1708 if (!entry->relocation_count)
1711 relocs = u64_to_ptr(typeof(*relocs), entry->relocs_ptr);
1719 static int eb_relocate(struct i915_execbuffer *eb)
1721 if (eb_lookup_vmas(eb))
1724 /* The objects are in their final locations, apply the relocations. */
1725 if (eb->args->flags & __EXEC_HAS_RELOC) {
1726 struct i915_vma *vma;
1728 list_for_each_entry(vma, &eb->relocs, reloc_link) {
1729 if (eb_relocate_vma(eb, vma))
1737 return eb_relocate_slow(eb);
1740 static void eb_export_fence(struct i915_vma *vma,
1741 struct drm_i915_gem_request *req,
1744 struct reservation_object *resv = vma->resv;
1747 * Ignore errors from failing to allocate the new fence, we can't
1748 * handle an error right now. Worst case should be missed
1749 * synchronisation leading to rendering corruption.
1751 reservation_object_lock(resv, NULL);
1752 if (flags & EXEC_OBJECT_WRITE)
1753 reservation_object_add_excl_fence(resv, &req->fence);
1754 else if (reservation_object_reserve_shared(resv) == 0)
1755 reservation_object_add_shared_fence(resv, &req->fence);
1756 reservation_object_unlock(resv);
1759 static int eb_move_to_gpu(struct i915_execbuffer *eb)
1761 const unsigned int count = eb->buffer_count;
1765 for (i = 0; i < count; i++) {
1766 unsigned int flags = eb->flags[i];
1767 struct i915_vma *vma = eb->vma[i];
1768 struct drm_i915_gem_object *obj = vma->obj;
1770 if (flags & EXEC_OBJECT_CAPTURE) {
1771 struct i915_gem_capture_list *capture;
1773 capture = kmalloc(sizeof(*capture), GFP_KERNEL);
1774 if (unlikely(!capture))
1777 capture->next = eb->request->capture_list;
1778 capture->vma = eb->vma[i];
1779 eb->request->capture_list = capture;
1783 * If the GPU is not _reading_ through the CPU cache, we need
1784 * to make sure that any writes (both previous GPU writes from
1785 * before a change in snooping levels and normal CPU writes)
1786 * caught in that cache are flushed to main memory.
1789 * obj->cache_dirty &&
1790 * !(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ)
1791 * but gcc's optimiser doesn't handle that as well and emits
1792 * two jumps instead of one. Maybe one day...
1794 if (unlikely(obj->cache_dirty & ~obj->cache_coherent)) {
1795 if (i915_gem_clflush_object(obj, 0))
1796 flags &= ~EXEC_OBJECT_ASYNC;
1799 if (flags & EXEC_OBJECT_ASYNC)
1802 err = i915_gem_request_await_object
1803 (eb->request, obj, flags & EXEC_OBJECT_WRITE);
1808 for (i = 0; i < count; i++) {
1809 unsigned int flags = eb->flags[i];
1810 struct i915_vma *vma = eb->vma[i];
1812 i915_vma_move_to_active(vma, eb->request, flags);
1813 eb_export_fence(vma, eb->request, flags);
1815 __eb_unreserve_vma(vma, flags);
1816 vma->exec_flags = NULL;
1818 if (unlikely(flags & __EXEC_OBJECT_HAS_REF))
1823 /* Unconditionally flush any chipset caches (for streaming writes). */
1824 i915_gem_chipset_flush(eb->i915);
1826 /* Unconditionally invalidate GPU caches and TLBs. */
1827 return eb->engine->emit_flush(eb->request, EMIT_INVALIDATE);
1830 static bool i915_gem_check_execbuffer(struct drm_i915_gem_execbuffer2 *exec)
1832 if (exec->flags & __I915_EXEC_ILLEGAL_FLAGS)
1835 /* Kernel clipping was a DRI1 misfeature */
1836 if (!(exec->flags & I915_EXEC_FENCE_ARRAY)) {
1837 if (exec->num_cliprects || exec->cliprects_ptr)
1841 if (exec->DR4 == 0xffffffff) {
1842 DRM_DEBUG("UXA submitting garbage DR4, fixing up\n");
1845 if (exec->DR1 || exec->DR4)
1848 if ((exec->batch_start_offset | exec->batch_len) & 0x7)
1854 void i915_vma_move_to_active(struct i915_vma *vma,
1855 struct drm_i915_gem_request *req,
1858 struct drm_i915_gem_object *obj = vma->obj;
1859 const unsigned int idx = req->engine->id;
1861 lockdep_assert_held(&req->i915->drm.struct_mutex);
1862 GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
1865 * Add a reference if we're newly entering the active list.
1866 * The order in which we add operations to the retirement queue is
1867 * vital here: mark_active adds to the start of the callback list,
1868 * such that subsequent callbacks are called first. Therefore we
1869 * add the active reference first and queue for it to be dropped
1872 if (!i915_vma_is_active(vma))
1873 obj->active_count++;
1874 i915_vma_set_active(vma, idx);
1875 i915_gem_active_set(&vma->last_read[idx], req);
1876 list_move_tail(&vma->vm_link, &vma->vm->active_list);
1878 obj->base.write_domain = 0;
1879 if (flags & EXEC_OBJECT_WRITE) {
1880 obj->base.write_domain = I915_GEM_DOMAIN_RENDER;
1882 if (intel_fb_obj_invalidate(obj, ORIGIN_CS))
1883 i915_gem_active_set(&obj->frontbuffer_write, req);
1885 obj->base.read_domains = 0;
1887 obj->base.read_domains |= I915_GEM_GPU_DOMAINS;
1889 if (flags & EXEC_OBJECT_NEEDS_FENCE)
1890 i915_gem_active_set(&vma->last_fence, req);
1893 static int i915_reset_gen7_sol_offsets(struct drm_i915_gem_request *req)
1898 if (!IS_GEN7(req->i915) || req->engine->id != RCS) {
1899 DRM_DEBUG("sol reset is gen7/rcs only\n");
1903 cs = intel_ring_begin(req, 4 * 2 + 2);
1907 *cs++ = MI_LOAD_REGISTER_IMM(4);
1908 for (i = 0; i < 4; i++) {
1909 *cs++ = i915_mmio_reg_offset(GEN7_SO_WRITE_OFFSET(i));
1913 intel_ring_advance(req, cs);
1918 static struct i915_vma *
1919 shadow_batch_pin(struct i915_execbuffer *eb, struct drm_i915_gem_object *obj)
1921 struct drm_i915_private *dev_priv = eb->i915;
1922 struct i915_address_space *vm;
1926 * PPGTT backed shadow buffers must be mapped RO, to prevent
1927 * post-scan tampering
1929 if (CMDPARSER_USES_GGTT(dev_priv)) {
1931 vm = &dev_priv->ggtt.base;
1932 } else if (eb->vm->has_read_only) {
1935 i915_gem_object_set_readonly(obj);
1937 DRM_DEBUG("Cannot prevent post-scan tampering without RO capable vm\n");
1938 return ERR_PTR(-EINVAL);
1941 return i915_gem_object_pin(obj, vm, NULL, 0, 0, flags);
1944 static struct i915_vma *eb_parse(struct i915_execbuffer *eb)
1946 struct drm_i915_gem_object *shadow_batch_obj;
1947 struct i915_vma *vma;
1949 u64 shadow_batch_start;
1952 shadow_batch_obj = i915_gem_batch_pool_get(&eb->engine->batch_pool,
1953 PAGE_ALIGN(eb->batch_len));
1954 if (IS_ERR(shadow_batch_obj))
1955 return ERR_CAST(shadow_batch_obj);
1957 vma = shadow_batch_pin(eb, shadow_batch_obj);
1961 batch_start = gen8_canonical_addr(eb->batch->node.start) +
1962 eb->batch_start_offset;
1964 shadow_batch_start = gen8_canonical_addr(vma->node.start);
1966 err = intel_engine_cmd_parser(eb->ctx,
1970 eb->batch_start_offset,
1973 shadow_batch_start);
1976 i915_vma_unpin(vma);
1979 * Unsafe GGTT-backed buffers can still be submitted safely
1981 * For PPGTT backing however, we have no choice but to forcibly
1982 * reject unsafe buffers
1984 if (CMDPARSER_USES_GGTT(eb->i915) && (err == -EACCES))
1985 /* Execute original buffer non-secure */
1993 eb->vma[eb->buffer_count] = i915_vma_get(vma);
1994 eb->flags[eb->buffer_count] =
1995 __EXEC_OBJECT_HAS_PIN | __EXEC_OBJECT_HAS_REF;
1996 vma->exec_flags = &eb->flags[eb->buffer_count];
1998 eb->batch_start_offset = 0;
2000 /* eb->batch_len unchanged */
2002 if (CMDPARSER_USES_GGTT(eb->i915))
2003 eb->batch_flags |= I915_DISPATCH_SECURE;
2006 i915_gem_object_unpin_pages(shadow_batch_obj);
2011 add_to_client(struct drm_i915_gem_request *req, struct drm_file *file)
2013 req->file_priv = file->driver_priv;
2014 list_add_tail(&req->client_link, &req->file_priv->mm.request_list);
2017 static int eb_submit(struct i915_execbuffer *eb)
2021 err = eb_move_to_gpu(eb);
2025 err = i915_switch_context(eb->request);
2029 if (eb->args->flags & I915_EXEC_GEN7_SOL_RESET) {
2030 err = i915_reset_gen7_sol_offsets(eb->request);
2035 err = eb->engine->emit_bb_start(eb->request,
2036 eb->batch->node.start +
2037 eb->batch_start_offset,
2047 * Find one BSD ring to dispatch the corresponding BSD command.
2048 * The engine index is returned.
2051 gen8_dispatch_bsd_engine(struct drm_i915_private *dev_priv,
2052 struct drm_file *file)
2054 struct drm_i915_file_private *file_priv = file->driver_priv;
2056 /* Check whether the file_priv has already selected one ring. */
2057 if ((int)file_priv->bsd_engine < 0)
2058 file_priv->bsd_engine = atomic_fetch_xor(1,
2059 &dev_priv->mm.bsd_engine_dispatch_index);
2061 return file_priv->bsd_engine;
2064 #define I915_USER_RINGS (4)
2066 static const enum intel_engine_id user_ring_map[I915_USER_RINGS + 1] = {
2067 [I915_EXEC_DEFAULT] = RCS,
2068 [I915_EXEC_RENDER] = RCS,
2069 [I915_EXEC_BLT] = BCS,
2070 [I915_EXEC_BSD] = VCS,
2071 [I915_EXEC_VEBOX] = VECS
2074 static struct intel_engine_cs *
2075 eb_select_engine(struct drm_i915_private *dev_priv,
2076 struct drm_file *file,
2077 struct drm_i915_gem_execbuffer2 *args)
2079 unsigned int user_ring_id = args->flags & I915_EXEC_RING_MASK;
2080 struct intel_engine_cs *engine;
2082 if (user_ring_id > I915_USER_RINGS) {
2083 DRM_DEBUG("execbuf with unknown ring: %u\n", user_ring_id);
2087 if ((user_ring_id != I915_EXEC_BSD) &&
2088 ((args->flags & I915_EXEC_BSD_MASK) != 0)) {
2089 DRM_DEBUG("execbuf with non bsd ring but with invalid "
2090 "bsd dispatch flags: %d\n", (int)(args->flags));
2094 if (user_ring_id == I915_EXEC_BSD && HAS_BSD2(dev_priv)) {
2095 unsigned int bsd_idx = args->flags & I915_EXEC_BSD_MASK;
2097 if (bsd_idx == I915_EXEC_BSD_DEFAULT) {
2098 bsd_idx = gen8_dispatch_bsd_engine(dev_priv, file);
2099 } else if (bsd_idx >= I915_EXEC_BSD_RING1 &&
2100 bsd_idx <= I915_EXEC_BSD_RING2) {
2101 bsd_idx >>= I915_EXEC_BSD_SHIFT;
2104 DRM_DEBUG("execbuf with unknown bsd ring: %u\n",
2109 engine = dev_priv->engine[_VCS(bsd_idx)];
2111 engine = dev_priv->engine[user_ring_map[user_ring_id]];
2115 DRM_DEBUG("execbuf with invalid ring: %u\n", user_ring_id);
2123 __free_fence_array(struct drm_syncobj **fences, unsigned int n)
2126 drm_syncobj_put(ptr_mask_bits(fences[n], 2));
2130 static struct drm_syncobj **
2131 get_fence_array(struct drm_i915_gem_execbuffer2 *args,
2132 struct drm_file *file)
2134 const unsigned int nfences = args->num_cliprects;
2135 struct drm_i915_gem_exec_fence __user *user;
2136 struct drm_syncobj **fences;
2140 if (!(args->flags & I915_EXEC_FENCE_ARRAY))
2143 if (nfences > SIZE_MAX / sizeof(*fences))
2144 return ERR_PTR(-EINVAL);
2146 user = u64_to_user_ptr(args->cliprects_ptr);
2147 if (!access_ok(VERIFY_READ, user, nfences * 2 * sizeof(u32)))
2148 return ERR_PTR(-EFAULT);
2150 fences = kvmalloc_array(args->num_cliprects, sizeof(*fences),
2151 __GFP_NOWARN | GFP_KERNEL);
2153 return ERR_PTR(-ENOMEM);
2155 for (n = 0; n < nfences; n++) {
2156 struct drm_i915_gem_exec_fence fence;
2157 struct drm_syncobj *syncobj;
2159 if (__copy_from_user(&fence, user++, sizeof(fence))) {
2164 if (fence.flags & __I915_EXEC_FENCE_UNKNOWN_FLAGS) {
2169 syncobj = drm_syncobj_find(file, fence.handle);
2171 DRM_DEBUG("Invalid syncobj handle provided\n");
2176 BUILD_BUG_ON(~(ARCH_KMALLOC_MINALIGN - 1) &
2177 ~__I915_EXEC_FENCE_UNKNOWN_FLAGS);
2179 fences[n] = ptr_pack_bits(syncobj, fence.flags, 2);
2185 __free_fence_array(fences, n);
2186 return ERR_PTR(err);
2190 put_fence_array(struct drm_i915_gem_execbuffer2 *args,
2191 struct drm_syncobj **fences)
2194 __free_fence_array(fences, args->num_cliprects);
2198 await_fence_array(struct i915_execbuffer *eb,
2199 struct drm_syncobj **fences)
2201 const unsigned int nfences = eb->args->num_cliprects;
2205 for (n = 0; n < nfences; n++) {
2206 struct drm_syncobj *syncobj;
2207 struct dma_fence *fence;
2210 syncobj = ptr_unpack_bits(fences[n], &flags, 2);
2211 if (!(flags & I915_EXEC_FENCE_WAIT))
2214 fence = drm_syncobj_fence_get(syncobj);
2218 err = i915_gem_request_await_dma_fence(eb->request, fence);
2219 dma_fence_put(fence);
2228 signal_fence_array(struct i915_execbuffer *eb,
2229 struct drm_syncobj **fences)
2231 const unsigned int nfences = eb->args->num_cliprects;
2232 struct dma_fence * const fence = &eb->request->fence;
2235 for (n = 0; n < nfences; n++) {
2236 struct drm_syncobj *syncobj;
2239 syncobj = ptr_unpack_bits(fences[n], &flags, 2);
2240 if (!(flags & I915_EXEC_FENCE_SIGNAL))
2243 drm_syncobj_replace_fence(syncobj, fence);
2248 i915_gem_do_execbuffer(struct drm_device *dev,
2249 struct drm_file *file,
2250 struct drm_i915_gem_execbuffer2 *args,
2251 struct drm_i915_gem_exec_object2 *exec,
2252 struct drm_syncobj **fences)
2254 struct drm_i915_private *dev_priv = to_i915(dev);
2255 struct i915_execbuffer eb;
2256 struct dma_fence *in_fence = NULL;
2257 struct sync_file *out_fence = NULL;
2258 int out_fence_fd = -1;
2261 BUILD_BUG_ON(__EXEC_OBJECT_INTERNAL_FLAGS &
2262 ~__EXEC_OBJECT_UNKNOWN_FLAGS);
2267 if (DBG_FORCE_RELOC || !(args->flags & I915_EXEC_NO_RELOC))
2268 args->flags |= __EXEC_HAS_RELOC;
2271 eb.vma = (struct i915_vma **)(exec + args->buffer_count + 1);
2273 eb.flags = (unsigned int *)(eb.vma + args->buffer_count + 1);
2275 eb.invalid_flags = __EXEC_OBJECT_UNKNOWN_FLAGS;
2276 if (USES_FULL_PPGTT(eb.i915))
2277 eb.invalid_flags |= EXEC_OBJECT_NEEDS_GTT;
2278 reloc_cache_init(&eb.reloc_cache, eb.i915);
2280 eb.buffer_count = args->buffer_count;
2281 eb.batch_start_offset = args->batch_start_offset;
2282 eb.batch_len = args->batch_len;
2285 if (args->flags & I915_EXEC_SECURE) {
2286 if (INTEL_GEN(dev_priv) >= 11)
2289 /* Return -EPERM to trigger fallback code on old binaries. */
2290 if (!HAS_SECURE_BATCHES(dev_priv))
2293 if (!drm_is_current_master(file) || !capable(CAP_SYS_ADMIN))
2296 eb.batch_flags |= I915_DISPATCH_SECURE;
2298 if (args->flags & I915_EXEC_IS_PINNED)
2299 eb.batch_flags |= I915_DISPATCH_PINNED;
2301 eb.engine = eb_select_engine(eb.i915, file, args);
2305 if (args->flags & I915_EXEC_RESOURCE_STREAMER) {
2306 if (!HAS_RESOURCE_STREAMER(eb.i915)) {
2307 DRM_DEBUG("RS is only allowed for Haswell, Gen8 and above\n");
2310 if (eb.engine->id != RCS) {
2311 DRM_DEBUG("RS is not available on %s\n",
2316 eb.batch_flags |= I915_DISPATCH_RS;
2319 if (args->flags & I915_EXEC_FENCE_IN) {
2320 in_fence = sync_file_get_fence(lower_32_bits(args->rsvd2));
2325 if (args->flags & I915_EXEC_FENCE_OUT) {
2326 out_fence_fd = get_unused_fd_flags(O_CLOEXEC);
2327 if (out_fence_fd < 0) {
2333 err = eb_create(&eb);
2337 GEM_BUG_ON(!eb.lut_size);
2339 err = eb_select_context(&eb);
2344 * Take a local wakeref for preparing to dispatch the execbuf as
2345 * we expect to access the hardware fairly frequently in the
2346 * process. Upon first dispatch, we acquire another prolonged
2347 * wakeref that we hold until the GPU has been idle for at least
2350 intel_runtime_pm_get(eb.i915);
2352 err = i915_mutex_lock_interruptible(dev);
2356 err = eb_relocate(&eb);
2359 * If the user expects the execobject.offset and
2360 * reloc.presumed_offset to be an exact match,
2361 * as for using NO_RELOC, then we cannot update
2362 * the execobject.offset until we have completed
2365 args->flags &= ~__EXEC_HAS_RELOC;
2369 if (unlikely(*eb.batch->exec_flags & EXEC_OBJECT_WRITE)) {
2370 DRM_DEBUG("Attempting to use self-modifying batch buffer\n");
2374 if (eb.batch_start_offset > eb.batch->size ||
2375 eb.batch_len > eb.batch->size - eb.batch_start_offset) {
2376 DRM_DEBUG("Attempting to use out-of-bounds batch\n");
2381 if (eb.batch_len == 0)
2382 eb.batch_len = eb.batch->size - eb.batch_start_offset;
2384 if (eb_use_cmdparser(&eb)) {
2385 struct i915_vma *vma;
2387 vma = eb_parse(&eb);
2395 * snb/ivb/vlv conflate the "batch in ppgtt" bit with the "non-secure
2396 * batch" bit. Hence we need to pin secure batches into the global gtt.
2397 * hsw should have this fixed, but bdw mucks it up again. */
2398 if (eb.batch_flags & I915_DISPATCH_SECURE) {
2399 struct i915_vma *vma;
2402 * So on first glance it looks freaky that we pin the batch here
2403 * outside of the reservation loop. But:
2404 * - The batch is already pinned into the relevant ppgtt, so we
2405 * already have the backing storage fully allocated.
2406 * - No other BO uses the global gtt (well contexts, but meh),
2407 * so we don't really have issues with multiple objects not
2408 * fitting due to fragmentation.
2409 * So this is actually safe.
2411 vma = i915_gem_object_ggtt_pin(eb.batch->obj, NULL, 0, 0, 0);
2420 /* All GPU relocation batches must be submitted prior to the user rq */
2421 GEM_BUG_ON(eb.reloc_cache.rq);
2423 /* Allocate a request for this batch buffer nice and early. */
2424 eb.request = i915_gem_request_alloc(eb.engine, eb.ctx);
2425 if (IS_ERR(eb.request)) {
2426 err = PTR_ERR(eb.request);
2427 goto err_batch_unpin;
2431 err = i915_gem_request_await_dma_fence(eb.request, in_fence);
2437 err = await_fence_array(&eb, fences);
2442 if (out_fence_fd != -1) {
2443 out_fence = sync_file_create(&eb.request->fence);
2451 * Whilst this request exists, batch_obj will be on the
2452 * active_list, and so will hold the active reference. Only when this
2453 * request is retired will the the batch_obj be moved onto the
2454 * inactive_list and lose its active reference. Hence we do not need
2455 * to explicitly hold another reference here.
2457 eb.request->batch = eb.batch;
2459 trace_i915_gem_request_queue(eb.request, eb.batch_flags);
2460 err = eb_submit(&eb);
2462 __i915_add_request(eb.request, err == 0);
2463 add_to_client(eb.request, file);
2466 signal_fence_array(&eb, fences);
2470 fd_install(out_fence_fd, out_fence->file);
2471 args->rsvd2 &= GENMASK_ULL(31, 0); /* keep in-fence */
2472 args->rsvd2 |= (u64)out_fence_fd << 32;
2475 fput(out_fence->file);
2480 if (eb.batch_flags & I915_DISPATCH_SECURE)
2481 i915_vma_unpin(eb.batch);
2484 eb_release_vmas(&eb);
2485 mutex_unlock(&dev->struct_mutex);
2487 intel_runtime_pm_put(eb.i915);
2488 i915_gem_context_put(eb.ctx);
2492 if (out_fence_fd != -1)
2493 put_unused_fd(out_fence_fd);
2495 dma_fence_put(in_fence);
2500 * Legacy execbuffer just creates an exec2 list from the original exec object
2501 * list array and passes it to the real function.
2504 i915_gem_execbuffer(struct drm_device *dev, void *data,
2505 struct drm_file *file)
2507 const size_t sz = (sizeof(struct drm_i915_gem_exec_object2) +
2508 sizeof(struct i915_vma *) +
2509 sizeof(unsigned int));
2510 struct drm_i915_gem_execbuffer *args = data;
2511 struct drm_i915_gem_execbuffer2 exec2;
2512 struct drm_i915_gem_exec_object *exec_list = NULL;
2513 struct drm_i915_gem_exec_object2 *exec2_list = NULL;
2517 if (args->buffer_count < 1 || args->buffer_count > SIZE_MAX / sz - 1) {
2518 DRM_DEBUG("execbuf2 with %d buffers\n", args->buffer_count);
2522 exec2.buffers_ptr = args->buffers_ptr;
2523 exec2.buffer_count = args->buffer_count;
2524 exec2.batch_start_offset = args->batch_start_offset;
2525 exec2.batch_len = args->batch_len;
2526 exec2.DR1 = args->DR1;
2527 exec2.DR4 = args->DR4;
2528 exec2.num_cliprects = args->num_cliprects;
2529 exec2.cliprects_ptr = args->cliprects_ptr;
2530 exec2.flags = I915_EXEC_RENDER;
2531 i915_execbuffer2_set_context_id(exec2, 0);
2533 if (!i915_gem_check_execbuffer(&exec2))
2536 /* Copy in the exec list from userland */
2537 exec_list = kvmalloc_array(args->buffer_count, sizeof(*exec_list),
2538 __GFP_NOWARN | GFP_KERNEL);
2539 exec2_list = kvmalloc_array(args->buffer_count + 1, sz,
2540 __GFP_NOWARN | GFP_KERNEL);
2541 if (exec_list == NULL || exec2_list == NULL) {
2542 DRM_DEBUG("Failed to allocate exec list for %d buffers\n",
2543 args->buffer_count);
2548 err = copy_from_user(exec_list,
2549 u64_to_user_ptr(args->buffers_ptr),
2550 sizeof(*exec_list) * args->buffer_count);
2552 DRM_DEBUG("copy %d exec entries failed %d\n",
2553 args->buffer_count, err);
2559 for (i = 0; i < args->buffer_count; i++) {
2560 exec2_list[i].handle = exec_list[i].handle;
2561 exec2_list[i].relocation_count = exec_list[i].relocation_count;
2562 exec2_list[i].relocs_ptr = exec_list[i].relocs_ptr;
2563 exec2_list[i].alignment = exec_list[i].alignment;
2564 exec2_list[i].offset = exec_list[i].offset;
2565 if (INTEL_GEN(to_i915(dev)) < 4)
2566 exec2_list[i].flags = EXEC_OBJECT_NEEDS_FENCE;
2568 exec2_list[i].flags = 0;
2571 err = i915_gem_do_execbuffer(dev, file, &exec2, exec2_list, NULL);
2572 if (exec2.flags & __EXEC_HAS_RELOC) {
2573 struct drm_i915_gem_exec_object __user *user_exec_list =
2574 u64_to_user_ptr(args->buffers_ptr);
2576 /* Copy the new buffer offsets back to the user's exec list. */
2577 for (i = 0; i < args->buffer_count; i++) {
2578 if (!(exec2_list[i].offset & UPDATE))
2581 exec2_list[i].offset =
2582 gen8_canonical_addr(exec2_list[i].offset & PIN_OFFSET_MASK);
2583 exec2_list[i].offset &= PIN_OFFSET_MASK;
2584 if (__copy_to_user(&user_exec_list[i].offset,
2585 &exec2_list[i].offset,
2586 sizeof(user_exec_list[i].offset)))
2597 i915_gem_execbuffer2(struct drm_device *dev, void *data,
2598 struct drm_file *file)
2600 const size_t sz = (sizeof(struct drm_i915_gem_exec_object2) +
2601 sizeof(struct i915_vma *) +
2602 sizeof(unsigned int));
2603 struct drm_i915_gem_execbuffer2 *args = data;
2604 struct drm_i915_gem_exec_object2 *exec2_list;
2605 struct drm_syncobj **fences = NULL;
2606 const size_t count = args->buffer_count;
2609 if (args->buffer_count < 1 || args->buffer_count > SIZE_MAX / sz - 1) {
2610 DRM_DEBUG("execbuf2 with %d buffers\n", args->buffer_count);
2614 if (!i915_gem_check_execbuffer(args))
2617 /* Allocate an extra slot for use by the command parser */
2618 exec2_list = kvmalloc_array(args->buffer_count + 1, sz,
2619 __GFP_NOWARN | GFP_KERNEL);
2620 if (exec2_list == NULL) {
2621 DRM_DEBUG("Failed to allocate exec list for %d buffers\n",
2622 args->buffer_count);
2625 if (copy_from_user(exec2_list,
2626 u64_to_user_ptr(args->buffers_ptr),
2627 sizeof(*exec2_list) * args->buffer_count)) {
2628 DRM_DEBUG("copy %d exec entries failed\n", args->buffer_count);
2633 if (args->flags & I915_EXEC_FENCE_ARRAY) {
2634 fences = get_fence_array(args, file);
2635 if (IS_ERR(fences)) {
2637 return PTR_ERR(fences);
2641 err = i915_gem_do_execbuffer(dev, file, args, exec2_list, fences);
2644 * Now that we have begun execution of the batchbuffer, we ignore
2645 * any new error after this point. Also given that we have already
2646 * updated the associated relocations, we try to write out the current
2647 * object locations irrespective of any error.
2649 if (args->flags & __EXEC_HAS_RELOC) {
2650 struct drm_i915_gem_exec_object2 __user *user_exec_list =
2651 u64_to_user_ptr(args->buffers_ptr);
2654 /* Copy the new buffer offsets back to the user's exec list. */
2656 * Note: count * sizeof(*user_exec_list) does not overflow,
2657 * because we checked 'count' in check_buffer_count().
2659 * And this range already got effectively checked earlier
2660 * when we did the "copy_from_user()" above.
2662 if (!user_access_begin(VERIFY_WRITE, user_exec_list,
2663 count * sizeof(*user_exec_list)))
2666 for (i = 0; i < args->buffer_count; i++) {
2667 if (!(exec2_list[i].offset & UPDATE))
2670 exec2_list[i].offset =
2671 gen8_canonical_addr(exec2_list[i].offset & PIN_OFFSET_MASK);
2672 unsafe_put_user(exec2_list[i].offset,
2673 &user_exec_list[i].offset,
2680 args->flags &= ~__I915_EXEC_UNKNOWN_FLAGS;
2681 put_fence_array(args, fences);