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/i915_drm.h>
38 #include "i915_gem_clflush.h"
39 #include "i915_trace.h"
40 #include "intel_drv.h"
41 #include "intel_frontbuffer.h"
43 #define DBG_USE_CPU_RELOC 0 /* -1 force GTT relocs; 1 force CPU relocs */
45 #define __EXEC_OBJECT_HAS_REF BIT(31)
46 #define __EXEC_OBJECT_HAS_PIN BIT(30)
47 #define __EXEC_OBJECT_HAS_FENCE BIT(29)
48 #define __EXEC_OBJECT_NEEDS_MAP BIT(28)
49 #define __EXEC_OBJECT_NEEDS_BIAS BIT(27)
50 #define __EXEC_OBJECT_INTERNAL_FLAGS (~0u << 27) /* all of the above */
51 #define __EXEC_OBJECT_RESERVED (__EXEC_OBJECT_HAS_PIN | __EXEC_OBJECT_HAS_FENCE)
53 #define __EXEC_HAS_RELOC BIT(31)
54 #define __EXEC_VALIDATED BIT(30)
55 #define UPDATE PIN_OFFSET_FIXED
57 #define BATCH_OFFSET_BIAS (256*1024)
59 #define __I915_EXEC_ILLEGAL_FLAGS \
60 (__I915_EXEC_UNKNOWN_FLAGS | I915_EXEC_CONSTANTS_MASK)
63 * DOC: User command execution
65 * Userspace submits commands to be executed on the GPU as an instruction
66 * stream within a GEM object we call a batchbuffer. This instructions may
67 * refer to other GEM objects containing auxiliary state such as kernels,
68 * samplers, render targets and even secondary batchbuffers. Userspace does
69 * not know where in the GPU memory these objects reside and so before the
70 * batchbuffer is passed to the GPU for execution, those addresses in the
71 * batchbuffer and auxiliary objects are updated. This is known as relocation,
72 * or patching. To try and avoid having to relocate each object on the next
73 * execution, userspace is told the location of those objects in this pass,
74 * but this remains just a hint as the kernel may choose a new location for
75 * any object in the future.
77 * Processing an execbuf ioctl is conceptually split up into a few phases.
79 * 1. Validation - Ensure all the pointers, handles and flags are valid.
80 * 2. Reservation - Assign GPU address space for every object
81 * 3. Relocation - Update any addresses to point to the final locations
82 * 4. Serialisation - Order the request with respect to its dependencies
83 * 5. Construction - Construct a request to execute the batchbuffer
84 * 6. Submission (at some point in the future execution)
86 * Reserving resources for the execbuf is the most complicated phase. We
87 * neither want to have to migrate the object in the address space, nor do
88 * we want to have to update any relocations pointing to this object. Ideally,
89 * we want to leave the object where it is and for all the existing relocations
90 * to match. If the object is given a new address, or if userspace thinks the
91 * object is elsewhere, we have to parse all the relocation entries and update
92 * the addresses. Userspace can set the I915_EXEC_NORELOC flag to hint that
93 * all the target addresses in all of its objects match the value in the
94 * relocation entries and that they all match the presumed offsets given by the
95 * list of execbuffer objects. Using this knowledge, we know that if we haven't
96 * moved any buffers, all the relocation entries are valid and we can skip
97 * the update. (If userspace is wrong, the likely outcome is an impromptu GPU
98 * hang.) The requirement for using I915_EXEC_NO_RELOC are:
100 * The addresses written in the objects must match the corresponding
101 * reloc.presumed_offset which in turn must match the corresponding
104 * Any render targets written to in the batch must be flagged with
107 * To avoid stalling, execobject.offset should match the current
108 * address of that object within the active context.
110 * The reservation is done is multiple phases. First we try and keep any
111 * object already bound in its current location - so as long as meets the
112 * constraints imposed by the new execbuffer. Any object left unbound after the
113 * first pass is then fitted into any available idle space. If an object does
114 * not fit, all objects are removed from the reservation and the process rerun
115 * after sorting the objects into a priority order (more difficult to fit
116 * objects are tried first). Failing that, the entire VM is cleared and we try
117 * to fit the execbuf once last time before concluding that it simply will not
120 * A small complication to all of this is that we allow userspace not only to
121 * specify an alignment and a size for the object in the address space, but
122 * we also allow userspace to specify the exact offset. This objects are
123 * simpler to place (the location is known a priori) all we have to do is make
124 * sure the space is available.
126 * Once all the objects are in place, patching up the buried pointers to point
127 * to the final locations is a fairly simple job of walking over the relocation
128 * entry arrays, looking up the right address and rewriting the value into
129 * the object. Simple! ... The relocation entries are stored in user memory
130 * and so to access them we have to copy them into a local buffer. That copy
131 * has to avoid taking any pagefaults as they may lead back to a GEM object
132 * requiring the struct_mutex (i.e. recursive deadlock). So once again we split
133 * the relocation into multiple passes. First we try to do everything within an
134 * atomic context (avoid the pagefaults) which requires that we never wait. If
135 * we detect that we may wait, or if we need to fault, then we have to fallback
136 * to a slower path. The slowpath has to drop the mutex. (Can you hear alarm
137 * bells yet?) Dropping the mutex means that we lose all the state we have
138 * built up so far for the execbuf and we must reset any global data. However,
139 * we do leave the objects pinned in their final locations - which is a
140 * potential issue for concurrent execbufs. Once we have left the mutex, we can
141 * allocate and copy all the relocation entries into a large array at our
142 * leisure, reacquire the mutex, reclaim all the objects and other state and
143 * then proceed to update any incorrect addresses with the objects.
145 * As we process the relocation entries, we maintain a record of whether the
146 * object is being written to. Using NORELOC, we expect userspace to provide
147 * this information instead. We also check whether we can skip the relocation
148 * by comparing the expected value inside the relocation entry with the target's
149 * final address. If they differ, we have to map the current object and rewrite
150 * the 4 or 8 byte pointer within.
152 * Serialising an execbuf is quite simple according to the rules of the GEM
153 * ABI. Execution within each context is ordered by the order of submission.
154 * Writes to any GEM object are in order of submission and are exclusive. Reads
155 * from a GEM object are unordered with respect to other reads, but ordered by
156 * writes. A write submitted after a read cannot occur before the read, and
157 * similarly any read submitted after a write cannot occur before the write.
158 * Writes are ordered between engines such that only one write occurs at any
159 * time (completing any reads beforehand) - using semaphores where available
160 * and CPU serialisation otherwise. Other GEM access obey the same rules, any
161 * write (either via mmaps using set-domain, or via pwrite) must flush all GPU
162 * reads before starting, and any read (either using set-domain or pread) must
163 * flush all GPU writes before starting. (Note we only employ a barrier before,
164 * we currently rely on userspace not concurrently starting a new execution
165 * whilst reading or writing to an object. This may be an advantage or not
166 * depending on how much you trust userspace not to shoot themselves in the
167 * foot.) Serialisation may just result in the request being inserted into
168 * a DAG awaiting its turn, but most simple is to wait on the CPU until
169 * all dependencies are resolved.
171 * After all of that, is just a matter of closing the request and handing it to
172 * the hardware (well, leaving it in a queue to be executed). However, we also
173 * offer the ability for batchbuffers to be run with elevated privileges so
174 * that they access otherwise hidden registers. (Used to adjust L3 cache etc.)
175 * Before any batch is given extra privileges we first must check that it
176 * contains no nefarious instructions, we check that each instruction is from
177 * our whitelist and all registers are also from an allowed list. We first
178 * copy the user's batchbuffer to a shadow (so that the user doesn't have
179 * access to it, either by the CPU or GPU as we scan it) and then parse each
180 * instruction. If everything is ok, we set a flag telling the hardware to run
181 * the batchbuffer in trusted mode, otherwise the ioctl is rejected.
184 struct i915_execbuffer {
185 struct drm_i915_private *i915; /** i915 backpointer */
186 struct drm_file *file; /** per-file lookup tables and limits */
187 struct drm_i915_gem_execbuffer2 *args; /** ioctl parameters */
188 struct drm_i915_gem_exec_object2 *exec; /** ioctl execobj[] */
190 struct intel_engine_cs *engine; /** engine to queue the request to */
191 struct i915_gem_context *ctx; /** context for building the request */
192 struct i915_address_space *vm; /** GTT and vma for the request */
194 struct drm_i915_gem_request *request; /** our request to build */
195 struct i915_vma *batch; /** identity of the batch obj/vma */
197 /** actual size of execobj[] as we may extend it for the cmdparser */
198 unsigned int buffer_count;
200 /** list of vma not yet bound during reservation phase */
201 struct list_head unbound;
203 /** list of vma that have execobj.relocation_count */
204 struct list_head relocs;
207 * Track the most recently used object for relocations, as we
208 * frequently have to perform multiple relocations within the same
212 struct drm_mm_node node; /** temporary GTT binding */
213 unsigned long vaddr; /** Current kmap address */
214 unsigned long page; /** Currently mapped page index */
215 bool use_64bit_reloc : 1;
218 bool needs_unfenced : 1;
221 u64 invalid_flags; /** Set of execobj.flags that are invalid */
222 u32 context_flags; /** Set of execobj.flags to insert from the ctx */
224 u32 batch_start_offset; /** Location within object of batch */
225 u32 batch_len; /** Length of batch within object */
226 u32 batch_flags; /** Flags composed for emit_bb_start() */
229 * Indicate either the size of the hastable used to resolve
230 * relocation handles, or if negative that we are using a direct
231 * index into the execobj[].
234 struct hlist_head *buckets; /** ht for relocation handles */
238 * As an alternative to creating a hashtable of handle-to-vma for a batch,
239 * we used the last available reserved field in the execobject[] and stash
240 * a link from the execobj to its vma.
242 #define __exec_to_vma(ee) (ee)->rsvd2
243 #define exec_to_vma(ee) u64_to_ptr(struct i915_vma, __exec_to_vma(ee))
246 * Used to convert any address to canonical form.
247 * Starting from gen8, some commands (e.g. STATE_BASE_ADDRESS,
248 * MI_LOAD_REGISTER_MEM and others, see Broadwell PRM Vol2a) require the
249 * addresses to be in a canonical form:
250 * "GraphicsAddress[63:48] are ignored by the HW and assumed to be in correct
251 * canonical form [63:48] == [47]."
253 #define GEN8_HIGH_ADDRESS_BIT 47
254 static inline u64 gen8_canonical_addr(u64 address)
256 return sign_extend64(address, GEN8_HIGH_ADDRESS_BIT);
259 static inline u64 gen8_noncanonical_addr(u64 address)
261 return address & GENMASK_ULL(GEN8_HIGH_ADDRESS_BIT, 0);
264 static int eb_create(struct i915_execbuffer *eb)
266 if (!(eb->args->flags & I915_EXEC_HANDLE_LUT)) {
267 unsigned int size = 1 + ilog2(eb->buffer_count);
270 * Without a 1:1 association between relocation handles and
271 * the execobject[] index, we instead create a hashtable.
272 * We size it dynamically based on available memory, starting
273 * first with 1:1 assocative hash and scaling back until
274 * the allocation succeeds.
276 * Later on we use a positive lut_size to indicate we are
277 * using this hashtable, and a negative value to indicate a
281 eb->buckets = kzalloc(sizeof(struct hlist_head) << size,
289 if (unlikely(!eb->buckets)) {
290 eb->buckets = kzalloc(sizeof(struct hlist_head),
292 if (unlikely(!eb->buckets))
298 eb->lut_size = -eb->buffer_count;
305 eb_vma_misplaced(const struct drm_i915_gem_exec_object2 *entry,
306 const struct i915_vma *vma)
308 if (!(entry->flags & __EXEC_OBJECT_HAS_PIN))
311 if (vma->node.size < entry->pad_to_size)
314 if (entry->alignment && !IS_ALIGNED(vma->node.start, entry->alignment))
317 if (entry->flags & EXEC_OBJECT_PINNED &&
318 vma->node.start != entry->offset)
321 if (entry->flags & __EXEC_OBJECT_NEEDS_BIAS &&
322 vma->node.start < BATCH_OFFSET_BIAS)
325 if (!(entry->flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS) &&
326 (vma->node.start + vma->node.size - 1) >> 32)
333 eb_pin_vma(struct i915_execbuffer *eb,
334 struct drm_i915_gem_exec_object2 *entry,
335 struct i915_vma *vma)
340 flags = vma->node.start;
342 flags = entry->offset & PIN_OFFSET_MASK;
344 flags |= PIN_USER | PIN_NOEVICT | PIN_OFFSET_FIXED;
345 if (unlikely(entry->flags & EXEC_OBJECT_NEEDS_GTT))
348 if (unlikely(i915_vma_pin(vma, 0, 0, flags)))
351 if (unlikely(entry->flags & EXEC_OBJECT_NEEDS_FENCE)) {
352 if (unlikely(i915_vma_get_fence(vma))) {
357 if (i915_vma_pin_fence(vma))
358 entry->flags |= __EXEC_OBJECT_HAS_FENCE;
361 entry->flags |= __EXEC_OBJECT_HAS_PIN;
365 __eb_unreserve_vma(struct i915_vma *vma,
366 const struct drm_i915_gem_exec_object2 *entry)
368 GEM_BUG_ON(!(entry->flags & __EXEC_OBJECT_HAS_PIN));
370 if (unlikely(entry->flags & __EXEC_OBJECT_HAS_FENCE))
371 i915_vma_unpin_fence(vma);
373 __i915_vma_unpin(vma);
377 eb_unreserve_vma(struct i915_vma *vma,
378 struct drm_i915_gem_exec_object2 *entry)
380 if (!(entry->flags & __EXEC_OBJECT_HAS_PIN))
383 __eb_unreserve_vma(vma, entry);
384 entry->flags &= ~__EXEC_OBJECT_RESERVED;
388 eb_validate_vma(struct i915_execbuffer *eb,
389 struct drm_i915_gem_exec_object2 *entry,
390 struct i915_vma *vma)
392 if (unlikely(entry->flags & eb->invalid_flags))
395 if (unlikely(entry->alignment && !is_power_of_2(entry->alignment)))
399 * Offset can be used as input (EXEC_OBJECT_PINNED), reject
400 * any non-page-aligned or non-canonical addresses.
402 if (unlikely(entry->flags & EXEC_OBJECT_PINNED &&
403 entry->offset != gen8_canonical_addr(entry->offset & PAGE_MASK)))
406 /* pad_to_size was once a reserved field, so sanitize it */
407 if (entry->flags & EXEC_OBJECT_PAD_TO_SIZE) {
408 if (unlikely(offset_in_page(entry->pad_to_size)))
411 entry->pad_to_size = 0;
414 if (unlikely(vma->exec_entry)) {
415 DRM_DEBUG("Object [handle %d, index %d] appears more than once in object list\n",
416 entry->handle, (int)(entry - eb->exec));
421 * From drm_mm perspective address space is continuous,
422 * so from this point we're always using non-canonical
425 entry->offset = gen8_noncanonical_addr(entry->offset);
431 eb_add_vma(struct i915_execbuffer *eb,
432 struct drm_i915_gem_exec_object2 *entry,
433 struct i915_vma *vma)
437 GEM_BUG_ON(i915_vma_is_closed(vma));
439 if (!(eb->args->flags & __EXEC_VALIDATED)) {
440 err = eb_validate_vma(eb, entry, vma);
445 if (eb->lut_size >= 0) {
446 vma->exec_handle = entry->handle;
447 hlist_add_head(&vma->exec_node,
448 &eb->buckets[hash_32(entry->handle,
452 if (entry->relocation_count)
453 list_add_tail(&vma->reloc_link, &eb->relocs);
455 if (!eb->reloc_cache.has_fence) {
456 entry->flags &= ~EXEC_OBJECT_NEEDS_FENCE;
458 if ((entry->flags & EXEC_OBJECT_NEEDS_FENCE ||
459 eb->reloc_cache.needs_unfenced) &&
460 i915_gem_object_is_tiled(vma->obj))
461 entry->flags |= EXEC_OBJECT_NEEDS_GTT | __EXEC_OBJECT_NEEDS_MAP;
464 if (!(entry->flags & EXEC_OBJECT_PINNED))
465 entry->flags |= eb->context_flags;
468 * Stash a pointer from the vma to execobj, so we can query its flags,
469 * size, alignment etc as provided by the user. Also we stash a pointer
470 * to the vma inside the execobj so that we can use a direct lookup
471 * to find the right target VMA when doing relocations.
473 vma->exec_entry = entry;
474 __exec_to_vma(entry) = (uintptr_t)vma;
477 eb_pin_vma(eb, entry, vma);
478 if (eb_vma_misplaced(entry, vma)) {
479 eb_unreserve_vma(vma, entry);
481 list_add_tail(&vma->exec_link, &eb->unbound);
482 if (drm_mm_node_allocated(&vma->node))
483 err = i915_vma_unbind(vma);
485 if (entry->offset != vma->node.start) {
486 entry->offset = vma->node.start | UPDATE;
487 eb->args->flags |= __EXEC_HAS_RELOC;
493 static inline int use_cpu_reloc(const struct reloc_cache *cache,
494 const struct drm_i915_gem_object *obj)
496 if (!i915_gem_object_has_struct_page(obj))
499 if (DBG_USE_CPU_RELOC)
500 return DBG_USE_CPU_RELOC > 0;
502 return (cache->has_llc ||
504 obj->cache_level != I915_CACHE_NONE);
507 static int eb_reserve_vma(const struct i915_execbuffer *eb,
508 struct i915_vma *vma)
510 struct drm_i915_gem_exec_object2 *entry = vma->exec_entry;
514 flags = PIN_USER | PIN_NONBLOCK;
515 if (entry->flags & EXEC_OBJECT_NEEDS_GTT)
519 * Wa32bitGeneralStateOffset & Wa32bitInstructionBaseOffset,
520 * limit address to the first 4GBs for unflagged objects.
522 if (!(entry->flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS))
523 flags |= PIN_ZONE_4G;
525 if (entry->flags & __EXEC_OBJECT_NEEDS_MAP)
526 flags |= PIN_MAPPABLE;
528 if (entry->flags & EXEC_OBJECT_PINNED) {
529 flags |= entry->offset | PIN_OFFSET_FIXED;
530 flags &= ~PIN_NONBLOCK; /* force overlapping PINNED checks */
531 } else if (entry->flags & __EXEC_OBJECT_NEEDS_BIAS) {
532 flags |= BATCH_OFFSET_BIAS | PIN_OFFSET_BIAS;
535 err = i915_vma_pin(vma, entry->pad_to_size, entry->alignment, flags);
539 if (entry->offset != vma->node.start) {
540 entry->offset = vma->node.start | UPDATE;
541 eb->args->flags |= __EXEC_HAS_RELOC;
544 entry->flags |= __EXEC_OBJECT_HAS_PIN;
545 GEM_BUG_ON(eb_vma_misplaced(entry, vma));
547 if (unlikely(entry->flags & EXEC_OBJECT_NEEDS_FENCE)) {
548 err = i915_vma_get_fence(vma);
554 if (i915_vma_pin_fence(vma))
555 entry->flags |= __EXEC_OBJECT_HAS_FENCE;
561 static int eb_reserve(struct i915_execbuffer *eb)
563 const unsigned int count = eb->buffer_count;
564 struct list_head last;
565 struct i915_vma *vma;
566 unsigned int i, pass;
570 * Attempt to pin all of the buffers into the GTT.
571 * This is done in 3 phases:
573 * 1a. Unbind all objects that do not match the GTT constraints for
574 * the execbuffer (fenceable, mappable, alignment etc).
575 * 1b. Increment pin count for already bound objects.
576 * 2. Bind new objects.
577 * 3. Decrement pin count.
579 * This avoid unnecessary unbinding of later objects in order to make
580 * room for the earlier objects *unless* we need to defragment.
586 list_for_each_entry(vma, &eb->unbound, exec_link) {
587 err = eb_reserve_vma(eb, vma);
594 /* Resort *all* the objects into priority order */
595 INIT_LIST_HEAD(&eb->unbound);
596 INIT_LIST_HEAD(&last);
597 for (i = 0; i < count; i++) {
598 struct drm_i915_gem_exec_object2 *entry = &eb->exec[i];
600 if (entry->flags & EXEC_OBJECT_PINNED &&
601 entry->flags & __EXEC_OBJECT_HAS_PIN)
604 vma = exec_to_vma(entry);
605 eb_unreserve_vma(vma, entry);
607 if (entry->flags & EXEC_OBJECT_PINNED)
608 list_add(&vma->exec_link, &eb->unbound);
609 else if (entry->flags & __EXEC_OBJECT_NEEDS_MAP)
610 list_add_tail(&vma->exec_link, &eb->unbound);
612 list_add_tail(&vma->exec_link, &last);
614 list_splice_tail(&last, &eb->unbound);
621 /* Too fragmented, unbind everything and retry */
622 err = i915_gem_evict_vm(eb->vm);
633 static inline struct hlist_head *
634 ht_head(const struct i915_gem_context_vma_lut *lut, u32 handle)
636 return &lut->ht[hash_32(handle, lut->ht_bits)];
640 ht_needs_resize(const struct i915_gem_context_vma_lut *lut)
642 return (4*lut->ht_count > 3*lut->ht_size ||
643 4*lut->ht_count + 1 < lut->ht_size);
646 static unsigned int eb_batch_index(const struct i915_execbuffer *eb)
648 return eb->buffer_count - 1;
651 static int eb_select_context(struct i915_execbuffer *eb)
653 struct i915_gem_context *ctx;
655 ctx = i915_gem_context_lookup(eb->file->driver_priv, eb->args->rsvd1);
656 if (unlikely(IS_ERR(ctx)))
659 if (unlikely(i915_gem_context_is_banned(ctx))) {
660 DRM_DEBUG("Context %u tried to submit while banned\n",
665 eb->ctx = i915_gem_context_get(ctx);
666 eb->vm = ctx->ppgtt ? &ctx->ppgtt->base : &eb->i915->ggtt.base;
668 eb->context_flags = 0;
669 if (ctx->flags & CONTEXT_NO_ZEROMAP)
670 eb->context_flags |= __EXEC_OBJECT_NEEDS_BIAS;
675 static int eb_lookup_vmas(struct i915_execbuffer *eb)
677 #define INTERMEDIATE BIT(0)
678 const unsigned int count = eb->buffer_count;
679 struct i915_gem_context_vma_lut *lut = &eb->ctx->vma_lut;
680 struct i915_vma *vma;
686 INIT_LIST_HEAD(&eb->relocs);
687 INIT_LIST_HEAD(&eb->unbound);
689 if (unlikely(lut->ht_size & I915_CTX_RESIZE_IN_PROGRESS))
690 flush_work(&lut->resize);
691 GEM_BUG_ON(lut->ht_size & I915_CTX_RESIZE_IN_PROGRESS);
693 for (i = 0; i < count; i++) {
694 __exec_to_vma(&eb->exec[i]) = 0;
696 hlist_for_each_entry(vma,
697 ht_head(lut, eb->exec[i].handle),
699 if (vma->ctx_handle != eb->exec[i].handle)
702 err = eb_add_vma(eb, &eb->exec[i], vma);
717 spin_lock(&eb->file->table_lock);
719 * Grab a reference to the object and release the lock so we can lookup
720 * or create the VMA without using GFP_ATOMIC
722 idr = &eb->file->object_idr;
723 for (i = slow_pass; i < count; i++) {
724 struct drm_i915_gem_object *obj;
726 if (__exec_to_vma(&eb->exec[i]))
729 obj = to_intel_bo(idr_find(idr, eb->exec[i].handle));
730 if (unlikely(!obj)) {
731 spin_unlock(&eb->file->table_lock);
732 DRM_DEBUG("Invalid object handle %d at index %d\n",
733 eb->exec[i].handle, i);
738 __exec_to_vma(&eb->exec[i]) = INTERMEDIATE | (uintptr_t)obj;
740 spin_unlock(&eb->file->table_lock);
742 for (i = slow_pass; i < count; i++) {
743 struct drm_i915_gem_object *obj;
745 if (!(__exec_to_vma(&eb->exec[i]) & INTERMEDIATE))
749 * NOTE: We can leak any vmas created here when something fails
750 * later on. But that's no issue since vma_unbind can deal with
751 * vmas which are not actually bound. And since only
752 * lookup_or_create exists as an interface to get at the vma
753 * from the (obj, vm) we don't run the risk of creating
754 * duplicated vmas for the same vm.
756 obj = u64_to_ptr(typeof(*obj),
757 __exec_to_vma(&eb->exec[i]) & ~INTERMEDIATE);
758 vma = i915_vma_instance(obj, eb->vm, NULL);
759 if (unlikely(IS_ERR(vma))) {
760 DRM_DEBUG("Failed to lookup VMA\n");
765 /* First come, first served */
768 vma->ctx_handle = eb->exec[i].handle;
769 hlist_add_head(&vma->ctx_node,
770 ht_head(lut, eb->exec[i].handle));
772 lut->ht_size |= I915_CTX_RESIZE_IN_PROGRESS;
773 if (i915_vma_is_ggtt(vma)) {
774 GEM_BUG_ON(obj->vma_hashed);
775 obj->vma_hashed = vma;
781 err = eb_add_vma(eb, &eb->exec[i], vma);
785 /* Only after we validated the user didn't use our bits */
786 if (vma->ctx != eb->ctx) {
788 eb->exec[i].flags |= __EXEC_OBJECT_HAS_REF;
792 if (lut->ht_size & I915_CTX_RESIZE_IN_PROGRESS) {
793 if (ht_needs_resize(lut))
794 queue_work(system_highpri_wq, &lut->resize);
796 lut->ht_size &= ~I915_CTX_RESIZE_IN_PROGRESS;
800 /* take note of the batch buffer before we might reorder the lists */
801 i = eb_batch_index(eb);
802 eb->batch = exec_to_vma(&eb->exec[i]);
805 * SNA is doing fancy tricks with compressing batch buffers, which leads
806 * to negative relocation deltas. Usually that works out ok since the
807 * relocate address is still positive, except when the batch is placed
808 * very low in the GTT. Ensure this doesn't happen.
810 * Note that actual hangs have only been observed on gen7, but for
811 * paranoia do it everywhere.
813 if (!(eb->exec[i].flags & EXEC_OBJECT_PINNED))
814 eb->exec[i].flags |= __EXEC_OBJECT_NEEDS_BIAS;
815 if (eb->reloc_cache.has_fence)
816 eb->exec[i].flags |= EXEC_OBJECT_NEEDS_FENCE;
818 eb->args->flags |= __EXEC_VALIDATED;
819 return eb_reserve(eb);
822 for (i = slow_pass; i < count; i++) {
823 if (__exec_to_vma(&eb->exec[i]) & INTERMEDIATE)
824 __exec_to_vma(&eb->exec[i]) = 0;
826 lut->ht_size &= ~I915_CTX_RESIZE_IN_PROGRESS;
831 static struct i915_vma *
832 eb_get_vma(const struct i915_execbuffer *eb, unsigned long handle)
834 if (eb->lut_size < 0) {
835 if (handle >= -eb->lut_size)
837 return exec_to_vma(&eb->exec[handle]);
839 struct hlist_head *head;
840 struct i915_vma *vma;
842 head = &eb->buckets[hash_32(handle, eb->lut_size)];
843 hlist_for_each_entry(vma, head, exec_node) {
844 if (vma->exec_handle == handle)
851 static void eb_release_vmas(const struct i915_execbuffer *eb)
853 const unsigned int count = eb->buffer_count;
856 for (i = 0; i < count; i++) {
857 struct drm_i915_gem_exec_object2 *entry = &eb->exec[i];
858 struct i915_vma *vma = exec_to_vma(entry);
863 GEM_BUG_ON(vma->exec_entry != entry);
864 vma->exec_entry = NULL;
866 if (entry->flags & __EXEC_OBJECT_HAS_PIN)
867 __eb_unreserve_vma(vma, entry);
869 if (entry->flags & __EXEC_OBJECT_HAS_REF)
873 ~(__EXEC_OBJECT_RESERVED | __EXEC_OBJECT_HAS_REF);
877 static void eb_reset_vmas(const struct i915_execbuffer *eb)
880 if (eb->lut_size >= 0)
881 memset(eb->buckets, 0,
882 sizeof(struct hlist_head) << eb->lut_size);
885 static void eb_destroy(const struct i915_execbuffer *eb)
887 if (eb->lut_size >= 0)
892 relocation_target(const struct drm_i915_gem_relocation_entry *reloc,
893 const struct i915_vma *target)
895 return gen8_canonical_addr((int)reloc->delta + target->node.start);
898 static void reloc_cache_init(struct reloc_cache *cache,
899 struct drm_i915_private *i915)
903 /* Must be a variable in the struct to allow GCC to unroll. */
904 cache->has_llc = HAS_LLC(i915);
905 cache->has_fence = INTEL_GEN(i915) < 4;
906 cache->needs_unfenced = INTEL_INFO(i915)->unfenced_needs_alignment;
907 cache->use_64bit_reloc = HAS_64BIT_RELOC(i915);
908 cache->node.allocated = false;
911 static inline void *unmask_page(unsigned long p)
913 return (void *)(uintptr_t)(p & PAGE_MASK);
916 static inline unsigned int unmask_flags(unsigned long p)
918 return p & ~PAGE_MASK;
921 #define KMAP 0x4 /* after CLFLUSH_FLAGS */
923 static inline struct i915_ggtt *cache_to_ggtt(struct reloc_cache *cache)
925 struct drm_i915_private *i915 =
926 container_of(cache, struct i915_execbuffer, reloc_cache)->i915;
930 static void reloc_cache_reset(struct reloc_cache *cache)
937 vaddr = unmask_page(cache->vaddr);
938 if (cache->vaddr & KMAP) {
939 if (cache->vaddr & CLFLUSH_AFTER)
942 kunmap_atomic(vaddr);
943 i915_gem_obj_finish_shmem_access((struct drm_i915_gem_object *)cache->node.mm);
946 io_mapping_unmap_atomic((void __iomem *)vaddr);
947 if (cache->node.allocated) {
948 struct i915_ggtt *ggtt = cache_to_ggtt(cache);
950 ggtt->base.clear_range(&ggtt->base,
953 drm_mm_remove_node(&cache->node);
955 i915_vma_unpin((struct i915_vma *)cache->node.mm);
963 static void *reloc_kmap(struct drm_i915_gem_object *obj,
964 struct reloc_cache *cache,
970 kunmap_atomic(unmask_page(cache->vaddr));
972 unsigned int flushes;
975 err = i915_gem_obj_prepare_shmem_write(obj, &flushes);
979 BUILD_BUG_ON(KMAP & CLFLUSH_FLAGS);
980 BUILD_BUG_ON((KMAP | CLFLUSH_FLAGS) & PAGE_MASK);
982 cache->vaddr = flushes | KMAP;
983 cache->node.mm = (void *)obj;
988 vaddr = kmap_atomic(i915_gem_object_get_dirty_page(obj, page));
989 cache->vaddr = unmask_flags(cache->vaddr) | (unsigned long)vaddr;
995 static void *reloc_iomap(struct drm_i915_gem_object *obj,
996 struct reloc_cache *cache,
999 struct i915_ggtt *ggtt = cache_to_ggtt(cache);
1000 unsigned long offset;
1004 io_mapping_unmap_atomic((void __force __iomem *) unmask_page(cache->vaddr));
1006 struct i915_vma *vma;
1009 if (use_cpu_reloc(cache, obj))
1012 err = i915_gem_object_set_to_gtt_domain(obj, true);
1014 return ERR_PTR(err);
1016 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
1017 PIN_MAPPABLE | PIN_NONBLOCK);
1019 memset(&cache->node, 0, sizeof(cache->node));
1020 err = drm_mm_insert_node_in_range
1021 (&ggtt->base.mm, &cache->node,
1022 PAGE_SIZE, 0, I915_COLOR_UNEVICTABLE,
1023 0, ggtt->mappable_end,
1025 if (err) /* no inactive aperture space, use cpu reloc */
1028 err = i915_vma_put_fence(vma);
1030 i915_vma_unpin(vma);
1031 return ERR_PTR(err);
1034 cache->node.start = vma->node.start;
1035 cache->node.mm = (void *)vma;
1039 offset = cache->node.start;
1040 if (cache->node.allocated) {
1042 ggtt->base.insert_page(&ggtt->base,
1043 i915_gem_object_get_dma_address(obj, page),
1044 offset, I915_CACHE_NONE, 0);
1046 offset += page << PAGE_SHIFT;
1049 vaddr = (void __force *)io_mapping_map_atomic_wc(&ggtt->mappable,
1052 cache->vaddr = (unsigned long)vaddr;
1057 static void *reloc_vaddr(struct drm_i915_gem_object *obj,
1058 struct reloc_cache *cache,
1063 if (cache->page == page) {
1064 vaddr = unmask_page(cache->vaddr);
1067 if ((cache->vaddr & KMAP) == 0)
1068 vaddr = reloc_iomap(obj, cache, page);
1070 vaddr = reloc_kmap(obj, cache, page);
1076 static void clflush_write32(u32 *addr, u32 value, unsigned int flushes)
1078 if (unlikely(flushes & (CLFLUSH_BEFORE | CLFLUSH_AFTER))) {
1079 if (flushes & CLFLUSH_BEFORE) {
1087 * Writes to the same cacheline are serialised by the CPU
1088 * (including clflush). On the write path, we only require
1089 * that it hits memory in an orderly fashion and place
1090 * mb barriers at the start and end of the relocation phase
1091 * to ensure ordering of clflush wrt to the system.
1093 if (flushes & CLFLUSH_AFTER)
1100 relocate_entry(struct i915_vma *vma,
1101 const struct drm_i915_gem_relocation_entry *reloc,
1102 struct i915_execbuffer *eb,
1103 const struct i915_vma *target)
1105 struct drm_i915_gem_object *obj = vma->obj;
1106 u64 offset = reloc->offset;
1107 u64 target_offset = relocation_target(reloc, target);
1108 bool wide = eb->reloc_cache.use_64bit_reloc;
1112 vaddr = reloc_vaddr(obj, &eb->reloc_cache, offset >> PAGE_SHIFT);
1114 return PTR_ERR(vaddr);
1116 clflush_write32(vaddr + offset_in_page(offset),
1117 lower_32_bits(target_offset),
1118 eb->reloc_cache.vaddr);
1121 offset += sizeof(u32);
1122 target_offset >>= 32;
1127 return target->node.start | UPDATE;
1131 eb_relocate_entry(struct i915_execbuffer *eb,
1132 struct i915_vma *vma,
1133 const struct drm_i915_gem_relocation_entry *reloc)
1135 struct i915_vma *target;
1138 /* we've already hold a reference to all valid objects */
1139 target = eb_get_vma(eb, reloc->target_handle);
1140 if (unlikely(!target))
1143 /* Validate that the target is in a valid r/w GPU domain */
1144 if (unlikely(reloc->write_domain & (reloc->write_domain - 1))) {
1145 DRM_DEBUG("reloc with multiple write domains: "
1146 "target %d offset %d "
1147 "read %08x write %08x",
1148 reloc->target_handle,
1149 (int) reloc->offset,
1150 reloc->read_domains,
1151 reloc->write_domain);
1154 if (unlikely((reloc->write_domain | reloc->read_domains)
1155 & ~I915_GEM_GPU_DOMAINS)) {
1156 DRM_DEBUG("reloc with read/write non-GPU domains: "
1157 "target %d offset %d "
1158 "read %08x write %08x",
1159 reloc->target_handle,
1160 (int) reloc->offset,
1161 reloc->read_domains,
1162 reloc->write_domain);
1166 if (reloc->write_domain) {
1167 target->exec_entry->flags |= EXEC_OBJECT_WRITE;
1170 * Sandybridge PPGTT errata: We need a global gtt mapping
1171 * for MI and pipe_control writes because the gpu doesn't
1172 * properly redirect them through the ppgtt for non_secure
1175 if (reloc->write_domain == I915_GEM_DOMAIN_INSTRUCTION &&
1176 IS_GEN6(eb->i915)) {
1177 err = i915_vma_bind(target, target->obj->cache_level,
1180 "Unexpected failure to bind target VMA!"))
1186 * If the relocation already has the right value in it, no
1187 * more work needs to be done.
1189 if (gen8_canonical_addr(target->node.start) == reloc->presumed_offset)
1192 /* Check that the relocation address is valid... */
1193 if (unlikely(reloc->offset >
1194 vma->size - (eb->reloc_cache.use_64bit_reloc ? 8 : 4))) {
1195 DRM_DEBUG("Relocation beyond object bounds: "
1196 "target %d offset %d size %d.\n",
1197 reloc->target_handle,
1202 if (unlikely(reloc->offset & 3)) {
1203 DRM_DEBUG("Relocation not 4-byte aligned: "
1204 "target %d offset %d.\n",
1205 reloc->target_handle,
1206 (int)reloc->offset);
1211 * If we write into the object, we need to force the synchronisation
1212 * barrier, either with an asynchronous clflush or if we executed the
1213 * patching using the GPU (though that should be serialised by the
1214 * timeline). To be completely sure, and since we are required to
1215 * do relocations we are already stalling, disable the user's opt
1216 * of our synchronisation.
1218 vma->exec_entry->flags &= ~EXEC_OBJECT_ASYNC;
1220 /* and update the user's relocation entry */
1221 return relocate_entry(vma, reloc, eb, target);
1224 static int eb_relocate_vma(struct i915_execbuffer *eb, struct i915_vma *vma)
1226 #define N_RELOC(x) ((x) / sizeof(struct drm_i915_gem_relocation_entry))
1227 struct drm_i915_gem_relocation_entry stack[N_RELOC(512)];
1228 struct drm_i915_gem_relocation_entry __user *urelocs;
1229 const struct drm_i915_gem_exec_object2 *entry = vma->exec_entry;
1230 unsigned int remain;
1232 urelocs = u64_to_user_ptr(entry->relocs_ptr);
1233 remain = entry->relocation_count;
1234 if (unlikely(remain > N_RELOC(ULONG_MAX)))
1238 * We must check that the entire relocation array is safe
1239 * to read. However, if the array is not writable the user loses
1240 * the updated relocation values.
1242 if (unlikely(!access_ok(VERIFY_READ, urelocs, remain*sizeof(urelocs))))
1246 struct drm_i915_gem_relocation_entry *r = stack;
1247 unsigned int count =
1248 min_t(unsigned int, remain, ARRAY_SIZE(stack));
1249 unsigned int copied;
1252 * This is the fast path and we cannot handle a pagefault
1253 * whilst holding the struct mutex lest the user pass in the
1254 * relocations contained within a mmaped bo. For in such a case
1255 * we, the page fault handler would call i915_gem_fault() and
1256 * we would try to acquire the struct mutex again. Obviously
1257 * this is bad and so lockdep complains vehemently.
1259 pagefault_disable();
1260 copied = __copy_from_user_inatomic(r, urelocs, count * sizeof(r[0]));
1262 if (unlikely(copied)) {
1269 u64 offset = eb_relocate_entry(eb, vma, r);
1271 if (likely(offset == 0)) {
1272 } else if ((s64)offset < 0) {
1273 remain = (int)offset;
1277 * Note that reporting an error now
1278 * leaves everything in an inconsistent
1279 * state as we have *already* changed
1280 * the relocation value inside the
1281 * object. As we have not changed the
1282 * reloc.presumed_offset or will not
1283 * change the execobject.offset, on the
1284 * call we may not rewrite the value
1285 * inside the object, leaving it
1286 * dangling and causing a GPU hang. Unless
1287 * userspace dynamically rebuilds the
1288 * relocations on each execbuf rather than
1289 * presume a static tree.
1291 * We did previously check if the relocations
1292 * were writable (access_ok), an error now
1293 * would be a strange race with mprotect,
1294 * having already demonstrated that we
1295 * can read from this userspace address.
1297 offset = gen8_canonical_addr(offset & ~UPDATE);
1299 &urelocs[r-stack].presumed_offset);
1301 } while (r++, --count);
1302 urelocs += ARRAY_SIZE(stack);
1305 reloc_cache_reset(&eb->reloc_cache);
1310 eb_relocate_vma_slow(struct i915_execbuffer *eb, struct i915_vma *vma)
1312 const struct drm_i915_gem_exec_object2 *entry = vma->exec_entry;
1313 struct drm_i915_gem_relocation_entry *relocs =
1314 u64_to_ptr(typeof(*relocs), entry->relocs_ptr);
1318 for (i = 0; i < entry->relocation_count; i++) {
1319 u64 offset = eb_relocate_entry(eb, vma, &relocs[i]);
1321 if ((s64)offset < 0) {
1328 reloc_cache_reset(&eb->reloc_cache);
1332 static int check_relocations(const struct drm_i915_gem_exec_object2 *entry)
1334 const char __user *addr, *end;
1336 char __maybe_unused c;
1338 size = entry->relocation_count;
1342 if (size > N_RELOC(ULONG_MAX))
1345 addr = u64_to_user_ptr(entry->relocs_ptr);
1346 size *= sizeof(struct drm_i915_gem_relocation_entry);
1347 if (!access_ok(VERIFY_READ, addr, size))
1351 for (; addr < end; addr += PAGE_SIZE) {
1352 int err = __get_user(c, addr);
1356 return __get_user(c, end - 1);
1359 static int eb_copy_relocations(const struct i915_execbuffer *eb)
1361 const unsigned int count = eb->buffer_count;
1365 for (i = 0; i < count; i++) {
1366 const unsigned int nreloc = eb->exec[i].relocation_count;
1367 struct drm_i915_gem_relocation_entry __user *urelocs;
1368 struct drm_i915_gem_relocation_entry *relocs;
1370 unsigned long copied;
1375 err = check_relocations(&eb->exec[i]);
1379 urelocs = u64_to_user_ptr(eb->exec[i].relocs_ptr);
1380 size = nreloc * sizeof(*relocs);
1382 relocs = kvmalloc_array(size, 1, GFP_TEMPORARY);
1389 /* copy_from_user is limited to < 4GiB */
1393 min_t(u64, BIT_ULL(31), size - copied);
1395 if (__copy_from_user((char *)relocs + copied,
1396 (char *)urelocs + copied,
1404 } while (copied < size);
1407 * As we do not update the known relocation offsets after
1408 * relocating (due to the complexities in lock handling),
1409 * we need to mark them as invalid now so that we force the
1410 * relocation processing next time. Just in case the target
1411 * object is evicted and then rebound into its old
1412 * presumed_offset before the next execbuffer - if that
1413 * happened we would make the mistake of assuming that the
1414 * relocations were valid.
1416 user_access_begin();
1417 for (copied = 0; copied < nreloc; copied++)
1419 &urelocs[copied].presumed_offset,
1424 eb->exec[i].relocs_ptr = (uintptr_t)relocs;
1431 struct drm_i915_gem_relocation_entry *relocs =
1432 u64_to_ptr(typeof(*relocs), eb->exec[i].relocs_ptr);
1433 if (eb->exec[i].relocation_count)
1439 static int eb_prefault_relocations(const struct i915_execbuffer *eb)
1441 const unsigned int count = eb->buffer_count;
1444 if (unlikely(i915.prefault_disable))
1447 for (i = 0; i < count; i++) {
1450 err = check_relocations(&eb->exec[i]);
1458 static noinline int eb_relocate_slow(struct i915_execbuffer *eb)
1460 struct drm_device *dev = &eb->i915->drm;
1461 bool have_copy = false;
1462 struct i915_vma *vma;
1466 if (signal_pending(current)) {
1471 /* We may process another execbuffer during the unlock... */
1473 mutex_unlock(&dev->struct_mutex);
1476 * We take 3 passes through the slowpatch.
1478 * 1 - we try to just prefault all the user relocation entries and
1479 * then attempt to reuse the atomic pagefault disabled fast path again.
1481 * 2 - we copy the user entries to a local buffer here outside of the
1482 * local and allow ourselves to wait upon any rendering before
1485 * 3 - we already have a local copy of the relocation entries, but
1486 * were interrupted (EAGAIN) whilst waiting for the objects, try again.
1489 err = eb_prefault_relocations(eb);
1490 } else if (!have_copy) {
1491 err = eb_copy_relocations(eb);
1492 have_copy = err == 0;
1498 mutex_lock(&dev->struct_mutex);
1502 err = i915_mutex_lock_interruptible(dev);
1504 mutex_lock(&dev->struct_mutex);
1508 /* reacquire the objects */
1509 err = eb_lookup_vmas(eb);
1513 list_for_each_entry(vma, &eb->relocs, reloc_link) {
1515 pagefault_disable();
1516 err = eb_relocate_vma(eb, vma);
1521 err = eb_relocate_vma_slow(eb, vma);
1528 * Leave the user relocations as are, this is the painfully slow path,
1529 * and we want to avoid the complication of dropping the lock whilst
1530 * having buffers reserved in the aperture and so causing spurious
1531 * ENOSPC for random operations.
1540 const unsigned int count = eb->buffer_count;
1543 for (i = 0; i < count; i++) {
1544 const struct drm_i915_gem_exec_object2 *entry =
1546 struct drm_i915_gem_relocation_entry *relocs;
1548 if (!entry->relocation_count)
1551 relocs = u64_to_ptr(typeof(*relocs), entry->relocs_ptr);
1556 return err ?: have_copy;
1559 static int eb_relocate(struct i915_execbuffer *eb)
1561 if (eb_lookup_vmas(eb))
1564 /* The objects are in their final locations, apply the relocations. */
1565 if (eb->args->flags & __EXEC_HAS_RELOC) {
1566 struct i915_vma *vma;
1568 list_for_each_entry(vma, &eb->relocs, reloc_link) {
1569 if (eb_relocate_vma(eb, vma))
1577 return eb_relocate_slow(eb);
1580 static void eb_export_fence(struct drm_i915_gem_object *obj,
1581 struct drm_i915_gem_request *req,
1584 struct reservation_object *resv = obj->resv;
1587 * Ignore errors from failing to allocate the new fence, we can't
1588 * handle an error right now. Worst case should be missed
1589 * synchronisation leading to rendering corruption.
1591 reservation_object_lock(resv, NULL);
1592 if (flags & EXEC_OBJECT_WRITE)
1593 reservation_object_add_excl_fence(resv, &req->fence);
1594 else if (reservation_object_reserve_shared(resv) == 0)
1595 reservation_object_add_shared_fence(resv, &req->fence);
1596 reservation_object_unlock(resv);
1599 static int eb_move_to_gpu(struct i915_execbuffer *eb)
1601 const unsigned int count = eb->buffer_count;
1605 for (i = 0; i < count; i++) {
1606 const struct drm_i915_gem_exec_object2 *entry = &eb->exec[i];
1607 struct i915_vma *vma = exec_to_vma(entry);
1608 struct drm_i915_gem_object *obj = vma->obj;
1610 if (entry->flags & EXEC_OBJECT_CAPTURE) {
1611 struct i915_gem_capture_list *capture;
1613 capture = kmalloc(sizeof(*capture), GFP_KERNEL);
1614 if (unlikely(!capture))
1617 capture->next = eb->request->capture_list;
1619 eb->request->capture_list = capture;
1622 if (entry->flags & EXEC_OBJECT_ASYNC)
1625 if (unlikely(obj->cache_dirty && !obj->cache_coherent))
1626 i915_gem_clflush_object(obj, 0);
1628 err = i915_gem_request_await_object
1629 (eb->request, obj, entry->flags & EXEC_OBJECT_WRITE);
1634 i915_vma_move_to_active(vma, eb->request, entry->flags);
1635 __eb_unreserve_vma(vma, entry);
1636 vma->exec_entry = NULL;
1639 for (i = 0; i < count; i++) {
1640 const struct drm_i915_gem_exec_object2 *entry = &eb->exec[i];
1641 struct i915_vma *vma = exec_to_vma(entry);
1643 eb_export_fence(vma->obj, eb->request, entry->flags);
1644 if (unlikely(entry->flags & __EXEC_OBJECT_HAS_REF))
1649 /* Unconditionally flush any chipset caches (for streaming writes). */
1650 i915_gem_chipset_flush(eb->i915);
1652 /* Unconditionally invalidate GPU caches and TLBs. */
1653 return eb->engine->emit_flush(eb->request, EMIT_INVALIDATE);
1656 static bool i915_gem_check_execbuffer(struct drm_i915_gem_execbuffer2 *exec)
1658 if (exec->flags & __I915_EXEC_ILLEGAL_FLAGS)
1661 /* Kernel clipping was a DRI1 misfeature */
1662 if (exec->num_cliprects || exec->cliprects_ptr)
1665 if (exec->DR4 == 0xffffffff) {
1666 DRM_DEBUG("UXA submitting garbage DR4, fixing up\n");
1669 if (exec->DR1 || exec->DR4)
1672 if ((exec->batch_start_offset | exec->batch_len) & 0x7)
1678 void i915_vma_move_to_active(struct i915_vma *vma,
1679 struct drm_i915_gem_request *req,
1682 struct drm_i915_gem_object *obj = vma->obj;
1683 const unsigned int idx = req->engine->id;
1685 lockdep_assert_held(&req->i915->drm.struct_mutex);
1686 GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
1689 * Add a reference if we're newly entering the active list.
1690 * The order in which we add operations to the retirement queue is
1691 * vital here: mark_active adds to the start of the callback list,
1692 * such that subsequent callbacks are called first. Therefore we
1693 * add the active reference first and queue for it to be dropped
1696 if (!i915_vma_is_active(vma))
1697 obj->active_count++;
1698 i915_vma_set_active(vma, idx);
1699 i915_gem_active_set(&vma->last_read[idx], req);
1700 list_move_tail(&vma->vm_link, &vma->vm->active_list);
1702 obj->base.write_domain = 0;
1703 if (flags & EXEC_OBJECT_WRITE) {
1704 obj->base.write_domain = I915_GEM_DOMAIN_RENDER;
1706 if (intel_fb_obj_invalidate(obj, ORIGIN_CS))
1707 i915_gem_active_set(&obj->frontbuffer_write, req);
1709 obj->base.read_domains = 0;
1711 obj->base.read_domains |= I915_GEM_GPU_DOMAINS;
1713 if (flags & EXEC_OBJECT_NEEDS_FENCE)
1714 i915_gem_active_set(&vma->last_fence, req);
1717 static int i915_reset_gen7_sol_offsets(struct drm_i915_gem_request *req)
1722 if (!IS_GEN7(req->i915) || req->engine->id != RCS) {
1723 DRM_DEBUG("sol reset is gen7/rcs only\n");
1727 cs = intel_ring_begin(req, 4 * 2 + 2);
1731 *cs++ = MI_LOAD_REGISTER_IMM(4);
1732 for (i = 0; i < 4; i++) {
1733 *cs++ = i915_mmio_reg_offset(GEN7_SO_WRITE_OFFSET(i));
1737 intel_ring_advance(req, cs);
1742 static struct i915_vma *eb_parse(struct i915_execbuffer *eb, bool is_master)
1744 struct drm_i915_gem_object *shadow_batch_obj;
1745 struct i915_vma *vma;
1748 shadow_batch_obj = i915_gem_batch_pool_get(&eb->engine->batch_pool,
1749 PAGE_ALIGN(eb->batch_len));
1750 if (IS_ERR(shadow_batch_obj))
1751 return ERR_CAST(shadow_batch_obj);
1753 err = intel_engine_cmd_parser(eb->engine,
1756 eb->batch_start_offset,
1760 if (err == -EACCES) /* unhandled chained batch */
1767 vma = i915_gem_object_ggtt_pin(shadow_batch_obj, NULL, 0, 0, 0);
1772 memset(&eb->exec[eb->buffer_count++],
1773 0, sizeof(*vma->exec_entry));
1774 vma->exec_entry->flags = __EXEC_OBJECT_HAS_PIN | __EXEC_OBJECT_HAS_REF;
1775 __exec_to_vma(vma->exec_entry) = (uintptr_t)i915_vma_get(vma);
1778 i915_gem_object_unpin_pages(shadow_batch_obj);
1783 add_to_client(struct drm_i915_gem_request *req, struct drm_file *file)
1785 req->file_priv = file->driver_priv;
1786 list_add_tail(&req->client_link, &req->file_priv->mm.request_list);
1789 static int eb_submit(struct i915_execbuffer *eb)
1793 err = eb_move_to_gpu(eb);
1797 err = i915_switch_context(eb->request);
1801 if (eb->args->flags & I915_EXEC_GEN7_SOL_RESET) {
1802 err = i915_reset_gen7_sol_offsets(eb->request);
1807 err = eb->engine->emit_bb_start(eb->request,
1808 eb->batch->node.start +
1809 eb->batch_start_offset,
1819 * Find one BSD ring to dispatch the corresponding BSD command.
1820 * The engine index is returned.
1823 gen8_dispatch_bsd_engine(struct drm_i915_private *dev_priv,
1824 struct drm_file *file)
1826 struct drm_i915_file_private *file_priv = file->driver_priv;
1828 /* Check whether the file_priv has already selected one ring. */
1829 if ((int)file_priv->bsd_engine < 0)
1830 file_priv->bsd_engine = atomic_fetch_xor(1,
1831 &dev_priv->mm.bsd_engine_dispatch_index);
1833 return file_priv->bsd_engine;
1836 #define I915_USER_RINGS (4)
1838 static const enum intel_engine_id user_ring_map[I915_USER_RINGS + 1] = {
1839 [I915_EXEC_DEFAULT] = RCS,
1840 [I915_EXEC_RENDER] = RCS,
1841 [I915_EXEC_BLT] = BCS,
1842 [I915_EXEC_BSD] = VCS,
1843 [I915_EXEC_VEBOX] = VECS
1846 static struct intel_engine_cs *
1847 eb_select_engine(struct drm_i915_private *dev_priv,
1848 struct drm_file *file,
1849 struct drm_i915_gem_execbuffer2 *args)
1851 unsigned int user_ring_id = args->flags & I915_EXEC_RING_MASK;
1852 struct intel_engine_cs *engine;
1854 if (user_ring_id > I915_USER_RINGS) {
1855 DRM_DEBUG("execbuf with unknown ring: %u\n", user_ring_id);
1859 if ((user_ring_id != I915_EXEC_BSD) &&
1860 ((args->flags & I915_EXEC_BSD_MASK) != 0)) {
1861 DRM_DEBUG("execbuf with non bsd ring but with invalid "
1862 "bsd dispatch flags: %d\n", (int)(args->flags));
1866 if (user_ring_id == I915_EXEC_BSD && HAS_BSD2(dev_priv)) {
1867 unsigned int bsd_idx = args->flags & I915_EXEC_BSD_MASK;
1869 if (bsd_idx == I915_EXEC_BSD_DEFAULT) {
1870 bsd_idx = gen8_dispatch_bsd_engine(dev_priv, file);
1871 } else if (bsd_idx >= I915_EXEC_BSD_RING1 &&
1872 bsd_idx <= I915_EXEC_BSD_RING2) {
1873 bsd_idx >>= I915_EXEC_BSD_SHIFT;
1876 DRM_DEBUG("execbuf with unknown bsd ring: %u\n",
1881 engine = dev_priv->engine[_VCS(bsd_idx)];
1883 engine = dev_priv->engine[user_ring_map[user_ring_id]];
1887 DRM_DEBUG("execbuf with invalid ring: %u\n", user_ring_id);
1895 i915_gem_do_execbuffer(struct drm_device *dev,
1896 struct drm_file *file,
1897 struct drm_i915_gem_execbuffer2 *args,
1898 struct drm_i915_gem_exec_object2 *exec)
1900 struct i915_execbuffer eb;
1901 struct dma_fence *in_fence = NULL;
1902 struct sync_file *out_fence = NULL;
1903 int out_fence_fd = -1;
1906 BUILD_BUG_ON(__EXEC_OBJECT_INTERNAL_FLAGS &
1907 ~__EXEC_OBJECT_UNKNOWN_FLAGS);
1909 eb.i915 = to_i915(dev);
1912 if (!(args->flags & I915_EXEC_NO_RELOC))
1913 args->flags |= __EXEC_HAS_RELOC;
1916 eb.invalid_flags = __EXEC_OBJECT_UNKNOWN_FLAGS;
1917 if (USES_FULL_PPGTT(eb.i915))
1918 eb.invalid_flags |= EXEC_OBJECT_NEEDS_GTT;
1919 reloc_cache_init(&eb.reloc_cache, eb.i915);
1921 eb.buffer_count = args->buffer_count;
1922 eb.batch_start_offset = args->batch_start_offset;
1923 eb.batch_len = args->batch_len;
1926 if (args->flags & I915_EXEC_SECURE) {
1927 if (!drm_is_current_master(file) || !capable(CAP_SYS_ADMIN))
1930 eb.batch_flags |= I915_DISPATCH_SECURE;
1932 if (args->flags & I915_EXEC_IS_PINNED)
1933 eb.batch_flags |= I915_DISPATCH_PINNED;
1935 eb.engine = eb_select_engine(eb.i915, file, args);
1939 if (args->flags & I915_EXEC_RESOURCE_STREAMER) {
1940 if (!HAS_RESOURCE_STREAMER(eb.i915)) {
1941 DRM_DEBUG("RS is only allowed for Haswell, Gen8 and above\n");
1944 if (eb.engine->id != RCS) {
1945 DRM_DEBUG("RS is not available on %s\n",
1950 eb.batch_flags |= I915_DISPATCH_RS;
1953 if (args->flags & I915_EXEC_FENCE_IN) {
1954 in_fence = sync_file_get_fence(lower_32_bits(args->rsvd2));
1959 if (args->flags & I915_EXEC_FENCE_OUT) {
1960 out_fence_fd = get_unused_fd_flags(O_CLOEXEC);
1961 if (out_fence_fd < 0) {
1971 * Take a local wakeref for preparing to dispatch the execbuf as
1972 * we expect to access the hardware fairly frequently in the
1973 * process. Upon first dispatch, we acquire another prolonged
1974 * wakeref that we hold until the GPU has been idle for at least
1977 intel_runtime_pm_get(eb.i915);
1978 err = i915_mutex_lock_interruptible(dev);
1982 err = eb_select_context(&eb);
1986 err = eb_relocate(&eb);
1989 * If the user expects the execobject.offset and
1990 * reloc.presumed_offset to be an exact match,
1991 * as for using NO_RELOC, then we cannot update
1992 * the execobject.offset until we have completed
1995 args->flags &= ~__EXEC_HAS_RELOC;
1999 if (unlikely(eb.batch->exec_entry->flags & EXEC_OBJECT_WRITE)) {
2000 DRM_DEBUG("Attempting to use self-modifying batch buffer\n");
2004 if (eb.batch_start_offset > eb.batch->size ||
2005 eb.batch_len > eb.batch->size - eb.batch_start_offset) {
2006 DRM_DEBUG("Attempting to use out-of-bounds batch\n");
2011 if (eb.engine->needs_cmd_parser && eb.batch_len) {
2012 struct i915_vma *vma;
2014 vma = eb_parse(&eb, drm_is_current_master(file));
2022 * Batch parsed and accepted:
2024 * Set the DISPATCH_SECURE bit to remove the NON_SECURE
2025 * bit from MI_BATCH_BUFFER_START commands issued in
2026 * the dispatch_execbuffer implementations. We
2027 * specifically don't want that set on batches the
2028 * command parser has accepted.
2030 eb.batch_flags |= I915_DISPATCH_SECURE;
2031 eb.batch_start_offset = 0;
2036 if (eb.batch_len == 0)
2037 eb.batch_len = eb.batch->size - eb.batch_start_offset;
2040 * snb/ivb/vlv conflate the "batch in ppgtt" bit with the "non-secure
2041 * batch" bit. Hence we need to pin secure batches into the global gtt.
2042 * hsw should have this fixed, but bdw mucks it up again. */
2043 if (eb.batch_flags & I915_DISPATCH_SECURE) {
2044 struct i915_vma *vma;
2047 * So on first glance it looks freaky that we pin the batch here
2048 * outside of the reservation loop. But:
2049 * - The batch is already pinned into the relevant ppgtt, so we
2050 * already have the backing storage fully allocated.
2051 * - No other BO uses the global gtt (well contexts, but meh),
2052 * so we don't really have issues with multiple objects not
2053 * fitting due to fragmentation.
2054 * So this is actually safe.
2056 vma = i915_gem_object_ggtt_pin(eb.batch->obj, NULL, 0, 0, 0);
2065 /* Allocate a request for this batch buffer nice and early. */
2066 eb.request = i915_gem_request_alloc(eb.engine, eb.ctx);
2067 if (IS_ERR(eb.request)) {
2068 err = PTR_ERR(eb.request);
2069 goto err_batch_unpin;
2073 err = i915_gem_request_await_dma_fence(eb.request, in_fence);
2078 if (out_fence_fd != -1) {
2079 out_fence = sync_file_create(&eb.request->fence);
2087 * Whilst this request exists, batch_obj will be on the
2088 * active_list, and so will hold the active reference. Only when this
2089 * request is retired will the the batch_obj be moved onto the
2090 * inactive_list and lose its active reference. Hence we do not need
2091 * to explicitly hold another reference here.
2093 eb.request->batch = eb.batch;
2095 trace_i915_gem_request_queue(eb.request, eb.batch_flags);
2096 err = eb_submit(&eb);
2098 __i915_add_request(eb.request, err == 0);
2099 add_to_client(eb.request, file);
2103 fd_install(out_fence_fd, out_fence->file);
2104 args->rsvd2 &= GENMASK_ULL(0, 31); /* keep in-fence */
2105 args->rsvd2 |= (u64)out_fence_fd << 32;
2108 fput(out_fence->file);
2113 if (eb.batch_flags & I915_DISPATCH_SECURE)
2114 i915_vma_unpin(eb.batch);
2117 eb_release_vmas(&eb);
2118 i915_gem_context_put(eb.ctx);
2120 mutex_unlock(&dev->struct_mutex);
2122 intel_runtime_pm_put(eb.i915);
2124 if (out_fence_fd != -1)
2125 put_unused_fd(out_fence_fd);
2127 dma_fence_put(in_fence);
2132 * Legacy execbuffer just creates an exec2 list from the original exec object
2133 * list array and passes it to the real function.
2136 i915_gem_execbuffer(struct drm_device *dev, void *data,
2137 struct drm_file *file)
2139 const size_t sz = sizeof(struct drm_i915_gem_exec_object2);
2140 struct drm_i915_gem_execbuffer *args = data;
2141 struct drm_i915_gem_execbuffer2 exec2;
2142 struct drm_i915_gem_exec_object *exec_list = NULL;
2143 struct drm_i915_gem_exec_object2 *exec2_list = NULL;
2147 if (args->buffer_count < 1 || args->buffer_count > SIZE_MAX / sz - 1) {
2148 DRM_DEBUG("execbuf2 with %d buffers\n", args->buffer_count);
2152 exec2.buffers_ptr = args->buffers_ptr;
2153 exec2.buffer_count = args->buffer_count;
2154 exec2.batch_start_offset = args->batch_start_offset;
2155 exec2.batch_len = args->batch_len;
2156 exec2.DR1 = args->DR1;
2157 exec2.DR4 = args->DR4;
2158 exec2.num_cliprects = args->num_cliprects;
2159 exec2.cliprects_ptr = args->cliprects_ptr;
2160 exec2.flags = I915_EXEC_RENDER;
2161 i915_execbuffer2_set_context_id(exec2, 0);
2163 if (!i915_gem_check_execbuffer(&exec2))
2166 /* Copy in the exec list from userland */
2167 exec_list = kvmalloc_array(args->buffer_count, sizeof(*exec_list),
2168 __GFP_NOWARN | GFP_TEMPORARY);
2169 exec2_list = kvmalloc_array(args->buffer_count + 1, sz,
2170 __GFP_NOWARN | GFP_TEMPORARY);
2171 if (exec_list == NULL || exec2_list == NULL) {
2172 DRM_DEBUG("Failed to allocate exec list for %d buffers\n",
2173 args->buffer_count);
2178 err = copy_from_user(exec_list,
2179 u64_to_user_ptr(args->buffers_ptr),
2180 sizeof(*exec_list) * args->buffer_count);
2182 DRM_DEBUG("copy %d exec entries failed %d\n",
2183 args->buffer_count, err);
2189 for (i = 0; i < args->buffer_count; i++) {
2190 exec2_list[i].handle = exec_list[i].handle;
2191 exec2_list[i].relocation_count = exec_list[i].relocation_count;
2192 exec2_list[i].relocs_ptr = exec_list[i].relocs_ptr;
2193 exec2_list[i].alignment = exec_list[i].alignment;
2194 exec2_list[i].offset = exec_list[i].offset;
2195 if (INTEL_GEN(to_i915(dev)) < 4)
2196 exec2_list[i].flags = EXEC_OBJECT_NEEDS_FENCE;
2198 exec2_list[i].flags = 0;
2201 err = i915_gem_do_execbuffer(dev, file, &exec2, exec2_list);
2202 if (exec2.flags & __EXEC_HAS_RELOC) {
2203 struct drm_i915_gem_exec_object __user *user_exec_list =
2204 u64_to_user_ptr(args->buffers_ptr);
2206 /* Copy the new buffer offsets back to the user's exec list. */
2207 for (i = 0; i < args->buffer_count; i++) {
2208 if (!(exec2_list[i].offset & UPDATE))
2211 exec2_list[i].offset =
2212 gen8_canonical_addr(exec2_list[i].offset & PIN_OFFSET_MASK);
2213 exec2_list[i].offset &= PIN_OFFSET_MASK;
2214 if (__copy_to_user(&user_exec_list[i].offset,
2215 &exec2_list[i].offset,
2216 sizeof(user_exec_list[i].offset)))
2227 i915_gem_execbuffer2(struct drm_device *dev, void *data,
2228 struct drm_file *file)
2230 const size_t sz = sizeof(struct drm_i915_gem_exec_object2);
2231 struct drm_i915_gem_execbuffer2 *args = data;
2232 struct drm_i915_gem_exec_object2 *exec2_list;
2235 if (args->buffer_count < 1 || args->buffer_count > SIZE_MAX / sz - 1) {
2236 DRM_DEBUG("execbuf2 with %d buffers\n", args->buffer_count);
2240 if (!i915_gem_check_execbuffer(args))
2243 /* Allocate an extra slot for use by the command parser */
2244 exec2_list = kvmalloc_array(args->buffer_count + 1, sz,
2245 __GFP_NOWARN | GFP_TEMPORARY);
2246 if (exec2_list == NULL) {
2247 DRM_DEBUG("Failed to allocate exec list for %d buffers\n",
2248 args->buffer_count);
2251 if (copy_from_user(exec2_list,
2252 u64_to_user_ptr(args->buffers_ptr),
2253 sizeof(*exec2_list) * args->buffer_count)) {
2254 DRM_DEBUG("copy %d exec entries failed\n", args->buffer_count);
2259 err = i915_gem_do_execbuffer(dev, file, args, exec2_list);
2262 * Now that we have begun execution of the batchbuffer, we ignore
2263 * any new error after this point. Also given that we have already
2264 * updated the associated relocations, we try to write out the current
2265 * object locations irrespective of any error.
2267 if (args->flags & __EXEC_HAS_RELOC) {
2268 struct drm_i915_gem_exec_object2 __user *user_exec_list =
2269 u64_to_user_ptr(args->buffers_ptr);
2272 /* Copy the new buffer offsets back to the user's exec list. */
2273 user_access_begin();
2274 for (i = 0; i < args->buffer_count; i++) {
2275 if (!(exec2_list[i].offset & UPDATE))
2278 exec2_list[i].offset =
2279 gen8_canonical_addr(exec2_list[i].offset & PIN_OFFSET_MASK);
2280 unsafe_put_user(exec2_list[i].offset,
2281 &user_exec_list[i].offset,
2288 args->flags &= ~__I915_EXEC_UNKNOWN_FLAGS;