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/intel-iommu.h>
30 #include <linux/reservation.h>
31 #include <linux/sync_file.h>
32 #include <linux/uaccess.h>
34 #include <drm/drm_syncobj.h>
35 #include <drm/i915_drm.h>
37 #include "gt/intel_gt_pm.h"
40 #include "i915_gem_clflush.h"
41 #include "i915_trace.h"
42 #include "intel_drv.h"
43 #include "intel_frontbuffer.h"
49 #define DBG_FORCE_RELOC 0 /* choose one of the above! */
52 #define __EXEC_OBJECT_HAS_REF BIT(31)
53 #define __EXEC_OBJECT_HAS_PIN BIT(30)
54 #define __EXEC_OBJECT_HAS_FENCE BIT(29)
55 #define __EXEC_OBJECT_NEEDS_MAP BIT(28)
56 #define __EXEC_OBJECT_NEEDS_BIAS BIT(27)
57 #define __EXEC_OBJECT_INTERNAL_FLAGS (~0u << 27) /* all of the above */
58 #define __EXEC_OBJECT_RESERVED (__EXEC_OBJECT_HAS_PIN | __EXEC_OBJECT_HAS_FENCE)
60 #define __EXEC_HAS_RELOC BIT(31)
61 #define __EXEC_VALIDATED BIT(30)
62 #define __EXEC_INTERNAL_FLAGS (~0u << 30)
63 #define UPDATE PIN_OFFSET_FIXED
65 #define BATCH_OFFSET_BIAS (256*1024)
67 #define __I915_EXEC_ILLEGAL_FLAGS \
68 (__I915_EXEC_UNKNOWN_FLAGS | \
69 I915_EXEC_CONSTANTS_MASK | \
70 I915_EXEC_RESOURCE_STREAMER)
72 /* Catch emission of unexpected errors for CI! */
73 #if IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM)
76 DRM_DEBUG_DRIVER("EINVAL at %s:%d\n", __func__, __LINE__); \
82 * DOC: User command execution
84 * Userspace submits commands to be executed on the GPU as an instruction
85 * stream within a GEM object we call a batchbuffer. This instructions may
86 * refer to other GEM objects containing auxiliary state such as kernels,
87 * samplers, render targets and even secondary batchbuffers. Userspace does
88 * not know where in the GPU memory these objects reside and so before the
89 * batchbuffer is passed to the GPU for execution, those addresses in the
90 * batchbuffer and auxiliary objects are updated. This is known as relocation,
91 * or patching. To try and avoid having to relocate each object on the next
92 * execution, userspace is told the location of those objects in this pass,
93 * but this remains just a hint as the kernel may choose a new location for
94 * any object in the future.
96 * At the level of talking to the hardware, submitting a batchbuffer for the
97 * GPU to execute is to add content to a buffer from which the HW
98 * command streamer is reading.
100 * 1. Add a command to load the HW context. For Logical Ring Contexts, i.e.
101 * Execlists, this command is not placed on the same buffer as the
104 * 2. Add a command to invalidate caches to the buffer.
106 * 3. Add a batchbuffer start command to the buffer; the start command is
107 * essentially a token together with the GPU address of the batchbuffer
110 * 4. Add a pipeline flush to the buffer.
112 * 5. Add a memory write command to the buffer to record when the GPU
113 * is done executing the batchbuffer. The memory write writes the
114 * global sequence number of the request, ``i915_request::global_seqno``;
115 * the i915 driver uses the current value in the register to determine
116 * if the GPU has completed the batchbuffer.
118 * 6. Add a user interrupt command to the buffer. This command instructs
119 * the GPU to issue an interrupt when the command, pipeline flush and
120 * memory write are completed.
122 * 7. Inform the hardware of the additional commands added to the buffer
123 * (by updating the tail pointer).
125 * Processing an execbuf ioctl is conceptually split up into a few phases.
127 * 1. Validation - Ensure all the pointers, handles and flags are valid.
128 * 2. Reservation - Assign GPU address space for every object
129 * 3. Relocation - Update any addresses to point to the final locations
130 * 4. Serialisation - Order the request with respect to its dependencies
131 * 5. Construction - Construct a request to execute the batchbuffer
132 * 6. Submission (at some point in the future execution)
134 * Reserving resources for the execbuf is the most complicated phase. We
135 * neither want to have to migrate the object in the address space, nor do
136 * we want to have to update any relocations pointing to this object. Ideally,
137 * we want to leave the object where it is and for all the existing relocations
138 * to match. If the object is given a new address, or if userspace thinks the
139 * object is elsewhere, we have to parse all the relocation entries and update
140 * the addresses. Userspace can set the I915_EXEC_NORELOC flag to hint that
141 * all the target addresses in all of its objects match the value in the
142 * relocation entries and that they all match the presumed offsets given by the
143 * list of execbuffer objects. Using this knowledge, we know that if we haven't
144 * moved any buffers, all the relocation entries are valid and we can skip
145 * the update. (If userspace is wrong, the likely outcome is an impromptu GPU
146 * hang.) The requirement for using I915_EXEC_NO_RELOC are:
148 * The addresses written in the objects must match the corresponding
149 * reloc.presumed_offset which in turn must match the corresponding
152 * Any render targets written to in the batch must be flagged with
155 * To avoid stalling, execobject.offset should match the current
156 * address of that object within the active context.
158 * The reservation is done is multiple phases. First we try and keep any
159 * object already bound in its current location - so as long as meets the
160 * constraints imposed by the new execbuffer. Any object left unbound after the
161 * first pass is then fitted into any available idle space. If an object does
162 * not fit, all objects are removed from the reservation and the process rerun
163 * after sorting the objects into a priority order (more difficult to fit
164 * objects are tried first). Failing that, the entire VM is cleared and we try
165 * to fit the execbuf once last time before concluding that it simply will not
168 * A small complication to all of this is that we allow userspace not only to
169 * specify an alignment and a size for the object in the address space, but
170 * we also allow userspace to specify the exact offset. This objects are
171 * simpler to place (the location is known a priori) all we have to do is make
172 * sure the space is available.
174 * Once all the objects are in place, patching up the buried pointers to point
175 * to the final locations is a fairly simple job of walking over the relocation
176 * entry arrays, looking up the right address and rewriting the value into
177 * the object. Simple! ... The relocation entries are stored in user memory
178 * and so to access them we have to copy them into a local buffer. That copy
179 * has to avoid taking any pagefaults as they may lead back to a GEM object
180 * requiring the struct_mutex (i.e. recursive deadlock). So once again we split
181 * the relocation into multiple passes. First we try to do everything within an
182 * atomic context (avoid the pagefaults) which requires that we never wait. If
183 * we detect that we may wait, or if we need to fault, then we have to fallback
184 * to a slower path. The slowpath has to drop the mutex. (Can you hear alarm
185 * bells yet?) Dropping the mutex means that we lose all the state we have
186 * built up so far for the execbuf and we must reset any global data. However,
187 * we do leave the objects pinned in their final locations - which is a
188 * potential issue for concurrent execbufs. Once we have left the mutex, we can
189 * allocate and copy all the relocation entries into a large array at our
190 * leisure, reacquire the mutex, reclaim all the objects and other state and
191 * then proceed to update any incorrect addresses with the objects.
193 * As we process the relocation entries, we maintain a record of whether the
194 * object is being written to. Using NORELOC, we expect userspace to provide
195 * this information instead. We also check whether we can skip the relocation
196 * by comparing the expected value inside the relocation entry with the target's
197 * final address. If they differ, we have to map the current object and rewrite
198 * the 4 or 8 byte pointer within.
200 * Serialising an execbuf is quite simple according to the rules of the GEM
201 * ABI. Execution within each context is ordered by the order of submission.
202 * Writes to any GEM object are in order of submission and are exclusive. Reads
203 * from a GEM object are unordered with respect to other reads, but ordered by
204 * writes. A write submitted after a read cannot occur before the read, and
205 * similarly any read submitted after a write cannot occur before the write.
206 * Writes are ordered between engines such that only one write occurs at any
207 * time (completing any reads beforehand) - using semaphores where available
208 * and CPU serialisation otherwise. Other GEM access obey the same rules, any
209 * write (either via mmaps using set-domain, or via pwrite) must flush all GPU
210 * reads before starting, and any read (either using set-domain or pread) must
211 * flush all GPU writes before starting. (Note we only employ a barrier before,
212 * we currently rely on userspace not concurrently starting a new execution
213 * whilst reading or writing to an object. This may be an advantage or not
214 * depending on how much you trust userspace not to shoot themselves in the
215 * foot.) Serialisation may just result in the request being inserted into
216 * a DAG awaiting its turn, but most simple is to wait on the CPU until
217 * all dependencies are resolved.
219 * After all of that, is just a matter of closing the request and handing it to
220 * the hardware (well, leaving it in a queue to be executed). However, we also
221 * offer the ability for batchbuffers to be run with elevated privileges so
222 * that they access otherwise hidden registers. (Used to adjust L3 cache etc.)
223 * Before any batch is given extra privileges we first must check that it
224 * contains no nefarious instructions, we check that each instruction is from
225 * our whitelist and all registers are also from an allowed list. We first
226 * copy the user's batchbuffer to a shadow (so that the user doesn't have
227 * access to it, either by the CPU or GPU as we scan it) and then parse each
228 * instruction. If everything is ok, we set a flag telling the hardware to run
229 * the batchbuffer in trusted mode, otherwise the ioctl is rejected.
232 struct i915_execbuffer {
233 struct drm_i915_private *i915; /** i915 backpointer */
234 struct drm_file *file; /** per-file lookup tables and limits */
235 struct drm_i915_gem_execbuffer2 *args; /** ioctl parameters */
236 struct drm_i915_gem_exec_object2 *exec; /** ioctl execobj[] */
237 struct i915_vma **vma;
240 struct intel_engine_cs *engine; /** engine to queue the request to */
241 struct intel_context *context; /* logical state for the request */
242 struct i915_gem_context *gem_context; /** caller's context */
243 struct i915_address_space *vm; /** GTT and vma for the request */
245 struct i915_request *request; /** our request to build */
246 struct i915_vma *batch; /** identity of the batch obj/vma */
248 /** actual size of execobj[] as we may extend it for the cmdparser */
249 unsigned int buffer_count;
251 /** list of vma not yet bound during reservation phase */
252 struct list_head unbound;
254 /** list of vma that have execobj.relocation_count */
255 struct list_head relocs;
258 * Track the most recently used object for relocations, as we
259 * frequently have to perform multiple relocations within the same
263 struct drm_mm_node node; /** temporary GTT binding */
264 unsigned long vaddr; /** Current kmap address */
265 unsigned long page; /** Currently mapped page index */
266 unsigned int gen; /** Cached value of INTEL_GEN */
267 bool use_64bit_reloc : 1;
270 bool needs_unfenced : 1;
272 struct i915_request *rq;
274 unsigned int rq_size;
277 u64 invalid_flags; /** Set of execobj.flags that are invalid */
278 u32 context_flags; /** Set of execobj.flags to insert from the ctx */
280 u32 batch_start_offset; /** Location within object of batch */
281 u32 batch_len; /** Length of batch within object */
282 u32 batch_flags; /** Flags composed for emit_bb_start() */
285 * Indicate either the size of the hastable used to resolve
286 * relocation handles, or if negative that we are using a direct
287 * index into the execobj[].
290 struct hlist_head *buckets; /** ht for relocation handles */
293 #define exec_entry(EB, VMA) (&(EB)->exec[(VMA)->exec_flags - (EB)->flags])
296 * Used to convert any address to canonical form.
297 * Starting from gen8, some commands (e.g. STATE_BASE_ADDRESS,
298 * MI_LOAD_REGISTER_MEM and others, see Broadwell PRM Vol2a) require the
299 * addresses to be in a canonical form:
300 * "GraphicsAddress[63:48] are ignored by the HW and assumed to be in correct
301 * canonical form [63:48] == [47]."
303 #define GEN8_HIGH_ADDRESS_BIT 47
304 static inline u64 gen8_canonical_addr(u64 address)
306 return sign_extend64(address, GEN8_HIGH_ADDRESS_BIT);
309 static inline u64 gen8_noncanonical_addr(u64 address)
311 return address & GENMASK_ULL(GEN8_HIGH_ADDRESS_BIT, 0);
314 static inline bool eb_use_cmdparser(const struct i915_execbuffer *eb)
316 return intel_engine_needs_cmd_parser(eb->engine) && eb->batch_len;
319 static int eb_create(struct i915_execbuffer *eb)
321 if (!(eb->args->flags & I915_EXEC_HANDLE_LUT)) {
322 unsigned int size = 1 + ilog2(eb->buffer_count);
325 * Without a 1:1 association between relocation handles and
326 * the execobject[] index, we instead create a hashtable.
327 * We size it dynamically based on available memory, starting
328 * first with 1:1 assocative hash and scaling back until
329 * the allocation succeeds.
331 * Later on we use a positive lut_size to indicate we are
332 * using this hashtable, and a negative value to indicate a
338 /* While we can still reduce the allocation size, don't
339 * raise a warning and allow the allocation to fail.
340 * On the last pass though, we want to try as hard
341 * as possible to perform the allocation and warn
346 flags |= __GFP_NORETRY | __GFP_NOWARN;
348 eb->buckets = kzalloc(sizeof(struct hlist_head) << size,
359 eb->lut_size = -eb->buffer_count;
366 eb_vma_misplaced(const struct drm_i915_gem_exec_object2 *entry,
367 const struct i915_vma *vma,
370 if (vma->node.size < entry->pad_to_size)
373 if (entry->alignment && !IS_ALIGNED(vma->node.start, entry->alignment))
376 if (flags & EXEC_OBJECT_PINNED &&
377 vma->node.start != entry->offset)
380 if (flags & __EXEC_OBJECT_NEEDS_BIAS &&
381 vma->node.start < BATCH_OFFSET_BIAS)
384 if (!(flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS) &&
385 (vma->node.start + vma->node.size - 1) >> 32)
388 if (flags & __EXEC_OBJECT_NEEDS_MAP &&
389 !i915_vma_is_map_and_fenceable(vma))
396 eb_pin_vma(struct i915_execbuffer *eb,
397 const struct drm_i915_gem_exec_object2 *entry,
398 struct i915_vma *vma)
400 unsigned int exec_flags = *vma->exec_flags;
404 pin_flags = vma->node.start;
406 pin_flags = entry->offset & PIN_OFFSET_MASK;
408 pin_flags |= PIN_USER | PIN_NOEVICT | PIN_OFFSET_FIXED;
409 if (unlikely(exec_flags & EXEC_OBJECT_NEEDS_GTT))
410 pin_flags |= PIN_GLOBAL;
412 if (unlikely(i915_vma_pin(vma, 0, 0, pin_flags)))
415 if (unlikely(exec_flags & EXEC_OBJECT_NEEDS_FENCE)) {
416 if (unlikely(i915_vma_pin_fence(vma))) {
422 exec_flags |= __EXEC_OBJECT_HAS_FENCE;
425 *vma->exec_flags = exec_flags | __EXEC_OBJECT_HAS_PIN;
426 return !eb_vma_misplaced(entry, vma, exec_flags);
429 static inline void __eb_unreserve_vma(struct i915_vma *vma, unsigned int flags)
431 GEM_BUG_ON(!(flags & __EXEC_OBJECT_HAS_PIN));
433 if (unlikely(flags & __EXEC_OBJECT_HAS_FENCE))
434 __i915_vma_unpin_fence(vma);
436 __i915_vma_unpin(vma);
440 eb_unreserve_vma(struct i915_vma *vma, unsigned int *flags)
442 if (!(*flags & __EXEC_OBJECT_HAS_PIN))
445 __eb_unreserve_vma(vma, *flags);
446 *flags &= ~__EXEC_OBJECT_RESERVED;
450 eb_validate_vma(struct i915_execbuffer *eb,
451 struct drm_i915_gem_exec_object2 *entry,
452 struct i915_vma *vma)
454 if (unlikely(entry->flags & eb->invalid_flags))
457 if (unlikely(entry->alignment && !is_power_of_2(entry->alignment)))
461 * Offset can be used as input (EXEC_OBJECT_PINNED), reject
462 * any non-page-aligned or non-canonical addresses.
464 if (unlikely(entry->flags & EXEC_OBJECT_PINNED &&
465 entry->offset != gen8_canonical_addr(entry->offset & I915_GTT_PAGE_MASK)))
468 /* pad_to_size was once a reserved field, so sanitize it */
469 if (entry->flags & EXEC_OBJECT_PAD_TO_SIZE) {
470 if (unlikely(offset_in_page(entry->pad_to_size)))
473 entry->pad_to_size = 0;
476 if (unlikely(vma->exec_flags)) {
477 DRM_DEBUG("Object [handle %d, index %d] appears more than once in object list\n",
478 entry->handle, (int)(entry - eb->exec));
483 * From drm_mm perspective address space is continuous,
484 * so from this point we're always using non-canonical
487 entry->offset = gen8_noncanonical_addr(entry->offset);
489 if (!eb->reloc_cache.has_fence) {
490 entry->flags &= ~EXEC_OBJECT_NEEDS_FENCE;
492 if ((entry->flags & EXEC_OBJECT_NEEDS_FENCE ||
493 eb->reloc_cache.needs_unfenced) &&
494 i915_gem_object_is_tiled(vma->obj))
495 entry->flags |= EXEC_OBJECT_NEEDS_GTT | __EXEC_OBJECT_NEEDS_MAP;
498 if (!(entry->flags & EXEC_OBJECT_PINNED))
499 entry->flags |= eb->context_flags;
505 eb_add_vma(struct i915_execbuffer *eb,
506 unsigned int i, unsigned batch_idx,
507 struct i915_vma *vma)
509 struct drm_i915_gem_exec_object2 *entry = &eb->exec[i];
512 GEM_BUG_ON(i915_vma_is_closed(vma));
514 if (!(eb->args->flags & __EXEC_VALIDATED)) {
515 err = eb_validate_vma(eb, entry, vma);
520 if (eb->lut_size > 0) {
521 vma->exec_handle = entry->handle;
522 hlist_add_head(&vma->exec_node,
523 &eb->buckets[hash_32(entry->handle,
527 if (entry->relocation_count)
528 list_add_tail(&vma->reloc_link, &eb->relocs);
531 * Stash a pointer from the vma to execobj, so we can query its flags,
532 * size, alignment etc as provided by the user. Also we stash a pointer
533 * to the vma inside the execobj so that we can use a direct lookup
534 * to find the right target VMA when doing relocations.
537 eb->flags[i] = entry->flags;
538 vma->exec_flags = &eb->flags[i];
541 * SNA is doing fancy tricks with compressing batch buffers, which leads
542 * to negative relocation deltas. Usually that works out ok since the
543 * relocate address is still positive, except when the batch is placed
544 * very low in the GTT. Ensure this doesn't happen.
546 * Note that actual hangs have only been observed on gen7, but for
547 * paranoia do it everywhere.
549 if (i == batch_idx) {
550 if (entry->relocation_count &&
551 !(eb->flags[i] & EXEC_OBJECT_PINNED))
552 eb->flags[i] |= __EXEC_OBJECT_NEEDS_BIAS;
553 if (eb->reloc_cache.has_fence)
554 eb->flags[i] |= EXEC_OBJECT_NEEDS_FENCE;
560 if (eb_pin_vma(eb, entry, vma)) {
561 if (entry->offset != vma->node.start) {
562 entry->offset = vma->node.start | UPDATE;
563 eb->args->flags |= __EXEC_HAS_RELOC;
566 eb_unreserve_vma(vma, vma->exec_flags);
568 list_add_tail(&vma->exec_link, &eb->unbound);
569 if (drm_mm_node_allocated(&vma->node))
570 err = i915_vma_unbind(vma);
572 vma->exec_flags = NULL;
577 static inline int use_cpu_reloc(const struct reloc_cache *cache,
578 const struct drm_i915_gem_object *obj)
580 if (!i915_gem_object_has_struct_page(obj))
583 if (DBG_FORCE_RELOC == FORCE_CPU_RELOC)
586 if (DBG_FORCE_RELOC == FORCE_GTT_RELOC)
589 return (cache->has_llc ||
591 obj->cache_level != I915_CACHE_NONE);
594 static int eb_reserve_vma(const struct i915_execbuffer *eb,
595 struct i915_vma *vma)
597 struct drm_i915_gem_exec_object2 *entry = exec_entry(eb, vma);
598 unsigned int exec_flags = *vma->exec_flags;
602 pin_flags = PIN_USER | PIN_NONBLOCK;
603 if (exec_flags & EXEC_OBJECT_NEEDS_GTT)
604 pin_flags |= PIN_GLOBAL;
607 * Wa32bitGeneralStateOffset & Wa32bitInstructionBaseOffset,
608 * limit address to the first 4GBs for unflagged objects.
610 if (!(exec_flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS))
611 pin_flags |= PIN_ZONE_4G;
613 if (exec_flags & __EXEC_OBJECT_NEEDS_MAP)
614 pin_flags |= PIN_MAPPABLE;
616 if (exec_flags & EXEC_OBJECT_PINNED) {
617 pin_flags |= entry->offset | PIN_OFFSET_FIXED;
618 pin_flags &= ~PIN_NONBLOCK; /* force overlapping checks */
619 } else if (exec_flags & __EXEC_OBJECT_NEEDS_BIAS) {
620 pin_flags |= BATCH_OFFSET_BIAS | PIN_OFFSET_BIAS;
623 err = i915_vma_pin(vma,
624 entry->pad_to_size, entry->alignment,
629 if (entry->offset != vma->node.start) {
630 entry->offset = vma->node.start | UPDATE;
631 eb->args->flags |= __EXEC_HAS_RELOC;
634 if (unlikely(exec_flags & EXEC_OBJECT_NEEDS_FENCE)) {
635 err = i915_vma_pin_fence(vma);
642 exec_flags |= __EXEC_OBJECT_HAS_FENCE;
645 *vma->exec_flags = exec_flags | __EXEC_OBJECT_HAS_PIN;
646 GEM_BUG_ON(eb_vma_misplaced(entry, vma, exec_flags));
651 static int eb_reserve(struct i915_execbuffer *eb)
653 const unsigned int count = eb->buffer_count;
654 struct list_head last;
655 struct i915_vma *vma;
656 unsigned int i, pass;
660 * Attempt to pin all of the buffers into the GTT.
661 * This is done in 3 phases:
663 * 1a. Unbind all objects that do not match the GTT constraints for
664 * the execbuffer (fenceable, mappable, alignment etc).
665 * 1b. Increment pin count for already bound objects.
666 * 2. Bind new objects.
667 * 3. Decrement pin count.
669 * This avoid unnecessary unbinding of later objects in order to make
670 * room for the earlier objects *unless* we need to defragment.
676 list_for_each_entry(vma, &eb->unbound, exec_link) {
677 err = eb_reserve_vma(eb, vma);
684 /* Resort *all* the objects into priority order */
685 INIT_LIST_HEAD(&eb->unbound);
686 INIT_LIST_HEAD(&last);
687 for (i = 0; i < count; i++) {
688 unsigned int flags = eb->flags[i];
689 struct i915_vma *vma = eb->vma[i];
691 if (flags & EXEC_OBJECT_PINNED &&
692 flags & __EXEC_OBJECT_HAS_PIN)
695 eb_unreserve_vma(vma, &eb->flags[i]);
697 if (flags & EXEC_OBJECT_PINNED)
698 /* Pinned must have their slot */
699 list_add(&vma->exec_link, &eb->unbound);
700 else if (flags & __EXEC_OBJECT_NEEDS_MAP)
701 /* Map require the lowest 256MiB (aperture) */
702 list_add_tail(&vma->exec_link, &eb->unbound);
703 else if (!(flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS))
704 /* Prioritise 4GiB region for restricted bo */
705 list_add(&vma->exec_link, &last);
707 list_add_tail(&vma->exec_link, &last);
709 list_splice_tail(&last, &eb->unbound);
716 /* Too fragmented, unbind everything and retry */
717 err = i915_gem_evict_vm(eb->vm);
728 static unsigned int eb_batch_index(const struct i915_execbuffer *eb)
730 if (eb->args->flags & I915_EXEC_BATCH_FIRST)
733 return eb->buffer_count - 1;
736 static int eb_select_context(struct i915_execbuffer *eb)
738 struct i915_gem_context *ctx;
740 ctx = i915_gem_context_lookup(eb->file->driver_priv, eb->args->rsvd1);
744 eb->gem_context = ctx;
746 eb->vm = &ctx->ppgtt->vm;
747 eb->invalid_flags |= EXEC_OBJECT_NEEDS_GTT;
749 eb->vm = &eb->i915->ggtt.vm;
752 eb->context_flags = 0;
753 if (test_bit(UCONTEXT_NO_ZEROMAP, &ctx->user_flags))
754 eb->context_flags |= __EXEC_OBJECT_NEEDS_BIAS;
759 static struct i915_request *__eb_wait_for_ring(struct intel_ring *ring)
761 struct i915_request *rq;
764 * Completely unscientific finger-in-the-air estimates for suitable
765 * maximum user request size (to avoid blocking) and then backoff.
767 if (intel_ring_update_space(ring) >= PAGE_SIZE)
771 * Find a request that after waiting upon, there will be at least half
772 * the ring available. The hysteresis allows us to compete for the
773 * shared ring and should mean that we sleep less often prior to
774 * claiming our resources, but not so long that the ring completely
775 * drains before we can submit our next request.
777 list_for_each_entry(rq, &ring->request_list, ring_link) {
778 if (__intel_ring_space(rq->postfix,
779 ring->emit, ring->size) > ring->size / 2)
782 if (&rq->ring_link == &ring->request_list)
783 return NULL; /* weird, we will check again later for real */
785 return i915_request_get(rq);
788 static int eb_wait_for_ring(const struct i915_execbuffer *eb)
790 struct i915_request *rq;
794 * Apply a light amount of backpressure to prevent excessive hogs
795 * from blocking waiting for space whilst holding struct_mutex and
796 * keeping all of their resources pinned.
799 rq = __eb_wait_for_ring(eb->context->ring);
801 mutex_unlock(&eb->i915->drm.struct_mutex);
803 if (i915_request_wait(rq,
804 I915_WAIT_INTERRUPTIBLE,
805 MAX_SCHEDULE_TIMEOUT) < 0)
808 i915_request_put(rq);
810 mutex_lock(&eb->i915->drm.struct_mutex);
816 static int eb_lookup_vmas(struct i915_execbuffer *eb)
818 struct radix_tree_root *handles_vma = &eb->gem_context->handles_vma;
819 struct drm_i915_gem_object *obj;
820 unsigned int i, batch;
823 if (unlikely(i915_gem_context_is_closed(eb->gem_context)))
826 if (unlikely(i915_gem_context_is_banned(eb->gem_context)))
829 INIT_LIST_HEAD(&eb->relocs);
830 INIT_LIST_HEAD(&eb->unbound);
832 batch = eb_batch_index(eb);
834 for (i = 0; i < eb->buffer_count; i++) {
835 u32 handle = eb->exec[i].handle;
836 struct i915_lut_handle *lut;
837 struct i915_vma *vma;
839 vma = radix_tree_lookup(handles_vma, handle);
843 obj = i915_gem_object_lookup(eb->file, handle);
844 if (unlikely(!obj)) {
849 vma = i915_vma_instance(obj, eb->vm, NULL);
855 lut = i915_lut_handle_alloc();
856 if (unlikely(!lut)) {
861 err = radix_tree_insert(handles_vma, handle, vma);
863 i915_lut_handle_free(lut);
867 /* transfer ref to ctx */
868 if (!vma->open_count++)
869 i915_vma_reopen(vma);
870 list_add(&lut->obj_link, &obj->lut_list);
871 list_add(&lut->ctx_link, &eb->gem_context->handles_list);
872 lut->ctx = eb->gem_context;
873 lut->handle = handle;
876 err = eb_add_vma(eb, i, batch, vma);
880 GEM_BUG_ON(vma != eb->vma[i]);
881 GEM_BUG_ON(vma->exec_flags != &eb->flags[i]);
882 GEM_BUG_ON(drm_mm_node_allocated(&vma->node) &&
883 eb_vma_misplaced(&eb->exec[i], vma, eb->flags[i]));
886 eb->args->flags |= __EXEC_VALIDATED;
887 return eb_reserve(eb);
890 i915_gem_object_put(obj);
896 static struct i915_vma *
897 eb_get_vma(const struct i915_execbuffer *eb, unsigned long handle)
899 if (eb->lut_size < 0) {
900 if (handle >= -eb->lut_size)
902 return eb->vma[handle];
904 struct hlist_head *head;
905 struct i915_vma *vma;
907 head = &eb->buckets[hash_32(handle, eb->lut_size)];
908 hlist_for_each_entry(vma, head, exec_node) {
909 if (vma->exec_handle == handle)
916 static void eb_release_vmas(const struct i915_execbuffer *eb)
918 const unsigned int count = eb->buffer_count;
921 for (i = 0; i < count; i++) {
922 struct i915_vma *vma = eb->vma[i];
923 unsigned int flags = eb->flags[i];
928 GEM_BUG_ON(vma->exec_flags != &eb->flags[i]);
929 vma->exec_flags = NULL;
932 if (flags & __EXEC_OBJECT_HAS_PIN)
933 __eb_unreserve_vma(vma, flags);
935 if (flags & __EXEC_OBJECT_HAS_REF)
940 static void eb_reset_vmas(const struct i915_execbuffer *eb)
943 if (eb->lut_size > 0)
944 memset(eb->buckets, 0,
945 sizeof(struct hlist_head) << eb->lut_size);
948 static void eb_destroy(const struct i915_execbuffer *eb)
950 GEM_BUG_ON(eb->reloc_cache.rq);
952 if (eb->lut_size > 0)
957 relocation_target(const struct drm_i915_gem_relocation_entry *reloc,
958 const struct i915_vma *target)
960 return gen8_canonical_addr((int)reloc->delta + target->node.start);
963 static void reloc_cache_init(struct reloc_cache *cache,
964 struct drm_i915_private *i915)
968 /* Must be a variable in the struct to allow GCC to unroll. */
969 cache->gen = INTEL_GEN(i915);
970 cache->has_llc = HAS_LLC(i915);
971 cache->use_64bit_reloc = HAS_64BIT_RELOC(i915);
972 cache->has_fence = cache->gen < 4;
973 cache->needs_unfenced = INTEL_INFO(i915)->unfenced_needs_alignment;
974 cache->node.allocated = false;
979 static inline void *unmask_page(unsigned long p)
981 return (void *)(uintptr_t)(p & PAGE_MASK);
984 static inline unsigned int unmask_flags(unsigned long p)
986 return p & ~PAGE_MASK;
989 #define KMAP 0x4 /* after CLFLUSH_FLAGS */
991 static inline struct i915_ggtt *cache_to_ggtt(struct reloc_cache *cache)
993 struct drm_i915_private *i915 =
994 container_of(cache, struct i915_execbuffer, reloc_cache)->i915;
998 static void reloc_gpu_flush(struct reloc_cache *cache)
1000 GEM_BUG_ON(cache->rq_size >= cache->rq->batch->obj->base.size / sizeof(u32));
1001 cache->rq_cmd[cache->rq_size] = MI_BATCH_BUFFER_END;
1003 __i915_gem_object_flush_map(cache->rq->batch->obj, 0, cache->rq_size);
1004 i915_gem_object_unpin_map(cache->rq->batch->obj);
1006 i915_gem_chipset_flush(cache->rq->i915);
1008 i915_request_add(cache->rq);
1012 static void reloc_cache_reset(struct reloc_cache *cache)
1017 reloc_gpu_flush(cache);
1022 vaddr = unmask_page(cache->vaddr);
1023 if (cache->vaddr & KMAP) {
1024 if (cache->vaddr & CLFLUSH_AFTER)
1027 kunmap_atomic(vaddr);
1028 i915_gem_obj_finish_shmem_access((struct drm_i915_gem_object *)cache->node.mm);
1031 io_mapping_unmap_atomic((void __iomem *)vaddr);
1032 if (cache->node.allocated) {
1033 struct i915_ggtt *ggtt = cache_to_ggtt(cache);
1035 ggtt->vm.clear_range(&ggtt->vm,
1038 drm_mm_remove_node(&cache->node);
1040 i915_vma_unpin((struct i915_vma *)cache->node.mm);
1048 static void *reloc_kmap(struct drm_i915_gem_object *obj,
1049 struct reloc_cache *cache,
1055 kunmap_atomic(unmask_page(cache->vaddr));
1057 unsigned int flushes;
1060 err = i915_gem_obj_prepare_shmem_write(obj, &flushes);
1062 return ERR_PTR(err);
1064 BUILD_BUG_ON(KMAP & CLFLUSH_FLAGS);
1065 BUILD_BUG_ON((KMAP | CLFLUSH_FLAGS) & PAGE_MASK);
1067 cache->vaddr = flushes | KMAP;
1068 cache->node.mm = (void *)obj;
1073 vaddr = kmap_atomic(i915_gem_object_get_dirty_page(obj, page));
1074 cache->vaddr = unmask_flags(cache->vaddr) | (unsigned long)vaddr;
1080 static void *reloc_iomap(struct drm_i915_gem_object *obj,
1081 struct reloc_cache *cache,
1084 struct i915_ggtt *ggtt = cache_to_ggtt(cache);
1085 unsigned long offset;
1089 io_mapping_unmap_atomic((void __force __iomem *) unmask_page(cache->vaddr));
1091 struct i915_vma *vma;
1094 if (use_cpu_reloc(cache, obj))
1097 err = i915_gem_object_set_to_gtt_domain(obj, true);
1099 return ERR_PTR(err);
1101 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
1106 memset(&cache->node, 0, sizeof(cache->node));
1107 err = drm_mm_insert_node_in_range
1108 (&ggtt->vm.mm, &cache->node,
1109 PAGE_SIZE, 0, I915_COLOR_UNEVICTABLE,
1110 0, ggtt->mappable_end,
1112 if (err) /* no inactive aperture space, use cpu reloc */
1115 err = i915_vma_put_fence(vma);
1117 i915_vma_unpin(vma);
1118 return ERR_PTR(err);
1121 cache->node.start = vma->node.start;
1122 cache->node.mm = (void *)vma;
1126 offset = cache->node.start;
1127 if (cache->node.allocated) {
1129 ggtt->vm.insert_page(&ggtt->vm,
1130 i915_gem_object_get_dma_address(obj, page),
1131 offset, I915_CACHE_NONE, 0);
1133 offset += page << PAGE_SHIFT;
1136 vaddr = (void __force *)io_mapping_map_atomic_wc(&ggtt->iomap,
1139 cache->vaddr = (unsigned long)vaddr;
1144 static void *reloc_vaddr(struct drm_i915_gem_object *obj,
1145 struct reloc_cache *cache,
1150 if (cache->page == page) {
1151 vaddr = unmask_page(cache->vaddr);
1154 if ((cache->vaddr & KMAP) == 0)
1155 vaddr = reloc_iomap(obj, cache, page);
1157 vaddr = reloc_kmap(obj, cache, page);
1163 static void clflush_write32(u32 *addr, u32 value, unsigned int flushes)
1165 if (unlikely(flushes & (CLFLUSH_BEFORE | CLFLUSH_AFTER))) {
1166 if (flushes & CLFLUSH_BEFORE) {
1174 * Writes to the same cacheline are serialised by the CPU
1175 * (including clflush). On the write path, we only require
1176 * that it hits memory in an orderly fashion and place
1177 * mb barriers at the start and end of the relocation phase
1178 * to ensure ordering of clflush wrt to the system.
1180 if (flushes & CLFLUSH_AFTER)
1186 static int __reloc_gpu_alloc(struct i915_execbuffer *eb,
1187 struct i915_vma *vma,
1190 struct reloc_cache *cache = &eb->reloc_cache;
1191 struct drm_i915_gem_object *obj;
1192 struct i915_request *rq;
1193 struct i915_vma *batch;
1197 if (DBG_FORCE_RELOC == FORCE_GPU_RELOC) {
1199 if (obj->cache_dirty & ~obj->cache_coherent)
1200 i915_gem_clflush_object(obj, 0);
1201 obj->write_domain = 0;
1204 GEM_BUG_ON(vma->obj->write_domain & I915_GEM_DOMAIN_CPU);
1206 obj = i915_gem_batch_pool_get(&eb->engine->batch_pool, PAGE_SIZE);
1208 return PTR_ERR(obj);
1210 cmd = i915_gem_object_pin_map(obj,
1214 i915_gem_object_unpin_pages(obj);
1216 return PTR_ERR(cmd);
1218 batch = i915_vma_instance(obj, vma->vm, NULL);
1219 if (IS_ERR(batch)) {
1220 err = PTR_ERR(batch);
1224 err = i915_vma_pin(batch, 0, 0, PIN_USER | PIN_NONBLOCK);
1228 rq = i915_request_create(eb->context);
1234 err = i915_request_await_object(rq, vma->obj, true);
1238 err = eb->engine->emit_bb_start(rq,
1239 batch->node.start, PAGE_SIZE,
1240 cache->gen > 5 ? 0 : I915_DISPATCH_SECURE);
1244 GEM_BUG_ON(!reservation_object_test_signaled_rcu(batch->resv, true));
1245 err = i915_vma_move_to_active(batch, rq, 0);
1249 err = i915_vma_move_to_active(vma, rq, EXEC_OBJECT_WRITE);
1254 i915_vma_unpin(batch);
1257 cache->rq_cmd = cmd;
1260 /* Return with batch mapping (cmd) still pinned */
1264 i915_request_skip(rq, err);
1266 i915_request_add(rq);
1268 i915_vma_unpin(batch);
1270 i915_gem_object_unpin_map(obj);
1274 static u32 *reloc_gpu(struct i915_execbuffer *eb,
1275 struct i915_vma *vma,
1278 struct reloc_cache *cache = &eb->reloc_cache;
1281 if (cache->rq_size > PAGE_SIZE/sizeof(u32) - (len + 1))
1282 reloc_gpu_flush(cache);
1284 if (unlikely(!cache->rq)) {
1287 /* If we need to copy for the cmdparser, we will stall anyway */
1288 if (eb_use_cmdparser(eb))
1289 return ERR_PTR(-EWOULDBLOCK);
1291 if (!intel_engine_can_store_dword(eb->engine))
1292 return ERR_PTR(-ENODEV);
1294 err = __reloc_gpu_alloc(eb, vma, len);
1296 return ERR_PTR(err);
1299 cmd = cache->rq_cmd + cache->rq_size;
1300 cache->rq_size += len;
1306 relocate_entry(struct i915_vma *vma,
1307 const struct drm_i915_gem_relocation_entry *reloc,
1308 struct i915_execbuffer *eb,
1309 const struct i915_vma *target)
1311 u64 offset = reloc->offset;
1312 u64 target_offset = relocation_target(reloc, target);
1313 bool wide = eb->reloc_cache.use_64bit_reloc;
1316 if (!eb->reloc_cache.vaddr &&
1317 (DBG_FORCE_RELOC == FORCE_GPU_RELOC ||
1318 !reservation_object_test_signaled_rcu(vma->resv, true))) {
1319 const unsigned int gen = eb->reloc_cache.gen;
1325 len = offset & 7 ? 8 : 5;
1331 batch = reloc_gpu(eb, vma, len);
1335 addr = gen8_canonical_addr(vma->node.start + offset);
1338 *batch++ = MI_STORE_DWORD_IMM_GEN4;
1339 *batch++ = lower_32_bits(addr);
1340 *batch++ = upper_32_bits(addr);
1341 *batch++ = lower_32_bits(target_offset);
1343 addr = gen8_canonical_addr(addr + 4);
1345 *batch++ = MI_STORE_DWORD_IMM_GEN4;
1346 *batch++ = lower_32_bits(addr);
1347 *batch++ = upper_32_bits(addr);
1348 *batch++ = upper_32_bits(target_offset);
1350 *batch++ = (MI_STORE_DWORD_IMM_GEN4 | (1 << 21)) + 1;
1351 *batch++ = lower_32_bits(addr);
1352 *batch++ = upper_32_bits(addr);
1353 *batch++ = lower_32_bits(target_offset);
1354 *batch++ = upper_32_bits(target_offset);
1356 } else if (gen >= 6) {
1357 *batch++ = MI_STORE_DWORD_IMM_GEN4;
1360 *batch++ = target_offset;
1361 } else if (gen >= 4) {
1362 *batch++ = MI_STORE_DWORD_IMM_GEN4 | MI_USE_GGTT;
1365 *batch++ = target_offset;
1367 *batch++ = MI_STORE_DWORD_IMM | MI_MEM_VIRTUAL;
1369 *batch++ = target_offset;
1376 vaddr = reloc_vaddr(vma->obj, &eb->reloc_cache, offset >> PAGE_SHIFT);
1378 return PTR_ERR(vaddr);
1380 clflush_write32(vaddr + offset_in_page(offset),
1381 lower_32_bits(target_offset),
1382 eb->reloc_cache.vaddr);
1385 offset += sizeof(u32);
1386 target_offset >>= 32;
1392 return target->node.start | UPDATE;
1396 eb_relocate_entry(struct i915_execbuffer *eb,
1397 struct i915_vma *vma,
1398 const struct drm_i915_gem_relocation_entry *reloc)
1400 struct i915_vma *target;
1403 /* we've already hold a reference to all valid objects */
1404 target = eb_get_vma(eb, reloc->target_handle);
1405 if (unlikely(!target))
1408 /* Validate that the target is in a valid r/w GPU domain */
1409 if (unlikely(reloc->write_domain & (reloc->write_domain - 1))) {
1410 DRM_DEBUG("reloc with multiple write domains: "
1411 "target %d offset %d "
1412 "read %08x write %08x",
1413 reloc->target_handle,
1414 (int) reloc->offset,
1415 reloc->read_domains,
1416 reloc->write_domain);
1419 if (unlikely((reloc->write_domain | reloc->read_domains)
1420 & ~I915_GEM_GPU_DOMAINS)) {
1421 DRM_DEBUG("reloc with read/write non-GPU domains: "
1422 "target %d offset %d "
1423 "read %08x write %08x",
1424 reloc->target_handle,
1425 (int) reloc->offset,
1426 reloc->read_domains,
1427 reloc->write_domain);
1431 if (reloc->write_domain) {
1432 *target->exec_flags |= EXEC_OBJECT_WRITE;
1435 * Sandybridge PPGTT errata: We need a global gtt mapping
1436 * for MI and pipe_control writes because the gpu doesn't
1437 * properly redirect them through the ppgtt for non_secure
1440 if (reloc->write_domain == I915_GEM_DOMAIN_INSTRUCTION &&
1441 IS_GEN(eb->i915, 6)) {
1442 err = i915_vma_bind(target, target->obj->cache_level,
1445 "Unexpected failure to bind target VMA!"))
1451 * If the relocation already has the right value in it, no
1452 * more work needs to be done.
1454 if (!DBG_FORCE_RELOC &&
1455 gen8_canonical_addr(target->node.start) == reloc->presumed_offset)
1458 /* Check that the relocation address is valid... */
1459 if (unlikely(reloc->offset >
1460 vma->size - (eb->reloc_cache.use_64bit_reloc ? 8 : 4))) {
1461 DRM_DEBUG("Relocation beyond object bounds: "
1462 "target %d offset %d size %d.\n",
1463 reloc->target_handle,
1468 if (unlikely(reloc->offset & 3)) {
1469 DRM_DEBUG("Relocation not 4-byte aligned: "
1470 "target %d offset %d.\n",
1471 reloc->target_handle,
1472 (int)reloc->offset);
1477 * If we write into the object, we need to force the synchronisation
1478 * barrier, either with an asynchronous clflush or if we executed the
1479 * patching using the GPU (though that should be serialised by the
1480 * timeline). To be completely sure, and since we are required to
1481 * do relocations we are already stalling, disable the user's opt
1482 * out of our synchronisation.
1484 *vma->exec_flags &= ~EXEC_OBJECT_ASYNC;
1486 /* and update the user's relocation entry */
1487 return relocate_entry(vma, reloc, eb, target);
1490 static int eb_relocate_vma(struct i915_execbuffer *eb, struct i915_vma *vma)
1492 #define N_RELOC(x) ((x) / sizeof(struct drm_i915_gem_relocation_entry))
1493 struct drm_i915_gem_relocation_entry stack[N_RELOC(512)];
1494 struct drm_i915_gem_relocation_entry __user *urelocs;
1495 const struct drm_i915_gem_exec_object2 *entry = exec_entry(eb, vma);
1496 unsigned int remain;
1498 urelocs = u64_to_user_ptr(entry->relocs_ptr);
1499 remain = entry->relocation_count;
1500 if (unlikely(remain > N_RELOC(ULONG_MAX)))
1504 * We must check that the entire relocation array is safe
1505 * to read. However, if the array is not writable the user loses
1506 * the updated relocation values.
1508 if (unlikely(!access_ok(urelocs, remain*sizeof(*urelocs))))
1512 struct drm_i915_gem_relocation_entry *r = stack;
1513 unsigned int count =
1514 min_t(unsigned int, remain, ARRAY_SIZE(stack));
1515 unsigned int copied;
1518 * This is the fast path and we cannot handle a pagefault
1519 * whilst holding the struct mutex lest the user pass in the
1520 * relocations contained within a mmaped bo. For in such a case
1521 * we, the page fault handler would call i915_gem_fault() and
1522 * we would try to acquire the struct mutex again. Obviously
1523 * this is bad and so lockdep complains vehemently.
1525 pagefault_disable();
1526 copied = __copy_from_user_inatomic(r, urelocs, count * sizeof(r[0]));
1528 if (unlikely(copied)) {
1535 u64 offset = eb_relocate_entry(eb, vma, r);
1537 if (likely(offset == 0)) {
1538 } else if ((s64)offset < 0) {
1539 remain = (int)offset;
1543 * Note that reporting an error now
1544 * leaves everything in an inconsistent
1545 * state as we have *already* changed
1546 * the relocation value inside the
1547 * object. As we have not changed the
1548 * reloc.presumed_offset or will not
1549 * change the execobject.offset, on the
1550 * call we may not rewrite the value
1551 * inside the object, leaving it
1552 * dangling and causing a GPU hang. Unless
1553 * userspace dynamically rebuilds the
1554 * relocations on each execbuf rather than
1555 * presume a static tree.
1557 * We did previously check if the relocations
1558 * were writable (access_ok), an error now
1559 * would be a strange race with mprotect,
1560 * having already demonstrated that we
1561 * can read from this userspace address.
1563 offset = gen8_canonical_addr(offset & ~UPDATE);
1564 if (unlikely(__put_user(offset, &urelocs[r-stack].presumed_offset))) {
1569 } while (r++, --count);
1570 urelocs += ARRAY_SIZE(stack);
1573 reloc_cache_reset(&eb->reloc_cache);
1578 eb_relocate_vma_slow(struct i915_execbuffer *eb, struct i915_vma *vma)
1580 const struct drm_i915_gem_exec_object2 *entry = exec_entry(eb, vma);
1581 struct drm_i915_gem_relocation_entry *relocs =
1582 u64_to_ptr(typeof(*relocs), entry->relocs_ptr);
1586 for (i = 0; i < entry->relocation_count; i++) {
1587 u64 offset = eb_relocate_entry(eb, vma, &relocs[i]);
1589 if ((s64)offset < 0) {
1596 reloc_cache_reset(&eb->reloc_cache);
1600 static int check_relocations(const struct drm_i915_gem_exec_object2 *entry)
1602 const char __user *addr, *end;
1604 char __maybe_unused c;
1606 size = entry->relocation_count;
1610 if (size > N_RELOC(ULONG_MAX))
1613 addr = u64_to_user_ptr(entry->relocs_ptr);
1614 size *= sizeof(struct drm_i915_gem_relocation_entry);
1615 if (!access_ok(addr, size))
1619 for (; addr < end; addr += PAGE_SIZE) {
1620 int err = __get_user(c, addr);
1624 return __get_user(c, end - 1);
1627 static int eb_copy_relocations(const struct i915_execbuffer *eb)
1629 const unsigned int count = eb->buffer_count;
1633 for (i = 0; i < count; i++) {
1634 const unsigned int nreloc = eb->exec[i].relocation_count;
1635 struct drm_i915_gem_relocation_entry __user *urelocs;
1636 struct drm_i915_gem_relocation_entry *relocs;
1638 unsigned long copied;
1643 err = check_relocations(&eb->exec[i]);
1647 urelocs = u64_to_user_ptr(eb->exec[i].relocs_ptr);
1648 size = nreloc * sizeof(*relocs);
1650 relocs = kvmalloc_array(size, 1, GFP_KERNEL);
1656 /* copy_from_user is limited to < 4GiB */
1660 min_t(u64, BIT_ULL(31), size - copied);
1662 if (__copy_from_user((char *)relocs + copied,
1663 (char __user *)urelocs + copied,
1674 } while (copied < size);
1677 * As we do not update the known relocation offsets after
1678 * relocating (due to the complexities in lock handling),
1679 * we need to mark them as invalid now so that we force the
1680 * relocation processing next time. Just in case the target
1681 * object is evicted and then rebound into its old
1682 * presumed_offset before the next execbuffer - if that
1683 * happened we would make the mistake of assuming that the
1684 * relocations were valid.
1686 if (!user_access_begin(urelocs, size))
1689 for (copied = 0; copied < nreloc; copied++)
1691 &urelocs[copied].presumed_offset,
1695 eb->exec[i].relocs_ptr = (uintptr_t)relocs;
1702 struct drm_i915_gem_relocation_entry *relocs =
1703 u64_to_ptr(typeof(*relocs), eb->exec[i].relocs_ptr);
1704 if (eb->exec[i].relocation_count)
1710 static int eb_prefault_relocations(const struct i915_execbuffer *eb)
1712 const unsigned int count = eb->buffer_count;
1715 if (unlikely(i915_modparams.prefault_disable))
1718 for (i = 0; i < count; i++) {
1721 err = check_relocations(&eb->exec[i]);
1729 static noinline int eb_relocate_slow(struct i915_execbuffer *eb)
1731 struct drm_device *dev = &eb->i915->drm;
1732 bool have_copy = false;
1733 struct i915_vma *vma;
1737 if (signal_pending(current)) {
1742 /* We may process another execbuffer during the unlock... */
1744 mutex_unlock(&dev->struct_mutex);
1747 * We take 3 passes through the slowpatch.
1749 * 1 - we try to just prefault all the user relocation entries and
1750 * then attempt to reuse the atomic pagefault disabled fast path again.
1752 * 2 - we copy the user entries to a local buffer here outside of the
1753 * local and allow ourselves to wait upon any rendering before
1756 * 3 - we already have a local copy of the relocation entries, but
1757 * were interrupted (EAGAIN) whilst waiting for the objects, try again.
1760 err = eb_prefault_relocations(eb);
1761 } else if (!have_copy) {
1762 err = eb_copy_relocations(eb);
1763 have_copy = err == 0;
1769 mutex_lock(&dev->struct_mutex);
1773 /* A frequent cause for EAGAIN are currently unavailable client pages */
1774 flush_workqueue(eb->i915->mm.userptr_wq);
1776 err = i915_mutex_lock_interruptible(dev);
1778 mutex_lock(&dev->struct_mutex);
1782 /* reacquire the objects */
1783 err = eb_lookup_vmas(eb);
1787 GEM_BUG_ON(!eb->batch);
1789 list_for_each_entry(vma, &eb->relocs, reloc_link) {
1791 pagefault_disable();
1792 err = eb_relocate_vma(eb, vma);
1797 err = eb_relocate_vma_slow(eb, vma);
1804 * Leave the user relocations as are, this is the painfully slow path,
1805 * and we want to avoid the complication of dropping the lock whilst
1806 * having buffers reserved in the aperture and so causing spurious
1807 * ENOSPC for random operations.
1816 const unsigned int count = eb->buffer_count;
1819 for (i = 0; i < count; i++) {
1820 const struct drm_i915_gem_exec_object2 *entry =
1822 struct drm_i915_gem_relocation_entry *relocs;
1824 if (!entry->relocation_count)
1827 relocs = u64_to_ptr(typeof(*relocs), entry->relocs_ptr);
1835 static int eb_relocate(struct i915_execbuffer *eb)
1837 if (eb_lookup_vmas(eb))
1840 /* The objects are in their final locations, apply the relocations. */
1841 if (eb->args->flags & __EXEC_HAS_RELOC) {
1842 struct i915_vma *vma;
1844 list_for_each_entry(vma, &eb->relocs, reloc_link) {
1845 if (eb_relocate_vma(eb, vma))
1853 return eb_relocate_slow(eb);
1856 static int eb_move_to_gpu(struct i915_execbuffer *eb)
1858 const unsigned int count = eb->buffer_count;
1862 for (i = 0; i < count; i++) {
1863 unsigned int flags = eb->flags[i];
1864 struct i915_vma *vma = eb->vma[i];
1865 struct drm_i915_gem_object *obj = vma->obj;
1867 if (flags & EXEC_OBJECT_CAPTURE) {
1868 struct i915_capture_list *capture;
1870 capture = kmalloc(sizeof(*capture), GFP_KERNEL);
1871 if (unlikely(!capture))
1874 capture->next = eb->request->capture_list;
1875 capture->vma = eb->vma[i];
1876 eb->request->capture_list = capture;
1880 * If the GPU is not _reading_ through the CPU cache, we need
1881 * to make sure that any writes (both previous GPU writes from
1882 * before a change in snooping levels and normal CPU writes)
1883 * caught in that cache are flushed to main memory.
1886 * obj->cache_dirty &&
1887 * !(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ)
1888 * but gcc's optimiser doesn't handle that as well and emits
1889 * two jumps instead of one. Maybe one day...
1891 if (unlikely(obj->cache_dirty & ~obj->cache_coherent)) {
1892 if (i915_gem_clflush_object(obj, 0))
1893 flags &= ~EXEC_OBJECT_ASYNC;
1896 if (flags & EXEC_OBJECT_ASYNC)
1899 err = i915_request_await_object
1900 (eb->request, obj, flags & EXEC_OBJECT_WRITE);
1905 for (i = 0; i < count; i++) {
1906 unsigned int flags = eb->flags[i];
1907 struct i915_vma *vma = eb->vma[i];
1909 err = i915_vma_move_to_active(vma, eb->request, flags);
1910 if (unlikely(err)) {
1911 i915_request_skip(eb->request, err);
1915 __eb_unreserve_vma(vma, flags);
1916 vma->exec_flags = NULL;
1918 if (unlikely(flags & __EXEC_OBJECT_HAS_REF))
1923 /* Unconditionally flush any chipset caches (for streaming writes). */
1924 i915_gem_chipset_flush(eb->i915);
1929 static bool i915_gem_check_execbuffer(struct drm_i915_gem_execbuffer2 *exec)
1931 if (exec->flags & __I915_EXEC_ILLEGAL_FLAGS)
1934 /* Kernel clipping was a DRI1 misfeature */
1935 if (!(exec->flags & I915_EXEC_FENCE_ARRAY)) {
1936 if (exec->num_cliprects || exec->cliprects_ptr)
1940 if (exec->DR4 == 0xffffffff) {
1941 DRM_DEBUG("UXA submitting garbage DR4, fixing up\n");
1944 if (exec->DR1 || exec->DR4)
1947 if ((exec->batch_start_offset | exec->batch_len) & 0x7)
1953 static int i915_reset_gen7_sol_offsets(struct i915_request *rq)
1958 if (!IS_GEN(rq->i915, 7) || rq->engine->id != RCS0) {
1959 DRM_DEBUG("sol reset is gen7/rcs only\n");
1963 cs = intel_ring_begin(rq, 4 * 2 + 2);
1967 *cs++ = MI_LOAD_REGISTER_IMM(4);
1968 for (i = 0; i < 4; i++) {
1969 *cs++ = i915_mmio_reg_offset(GEN7_SO_WRITE_OFFSET(i));
1973 intel_ring_advance(rq, cs);
1978 static struct i915_vma *eb_parse(struct i915_execbuffer *eb, bool is_master)
1980 struct drm_i915_gem_object *shadow_batch_obj;
1981 struct i915_vma *vma;
1984 shadow_batch_obj = i915_gem_batch_pool_get(&eb->engine->batch_pool,
1985 PAGE_ALIGN(eb->batch_len));
1986 if (IS_ERR(shadow_batch_obj))
1987 return ERR_CAST(shadow_batch_obj);
1989 err = intel_engine_cmd_parser(eb->engine,
1992 eb->batch_start_offset,
1996 if (err == -EACCES) /* unhandled chained batch */
2003 vma = i915_gem_object_ggtt_pin(shadow_batch_obj, NULL, 0, 0, 0);
2007 eb->vma[eb->buffer_count] = i915_vma_get(vma);
2008 eb->flags[eb->buffer_count] =
2009 __EXEC_OBJECT_HAS_PIN | __EXEC_OBJECT_HAS_REF;
2010 vma->exec_flags = &eb->flags[eb->buffer_count];
2014 i915_gem_object_unpin_pages(shadow_batch_obj);
2019 add_to_client(struct i915_request *rq, struct drm_file *file)
2021 rq->file_priv = file->driver_priv;
2022 list_add_tail(&rq->client_link, &rq->file_priv->mm.request_list);
2025 static int eb_submit(struct i915_execbuffer *eb)
2029 err = eb_move_to_gpu(eb);
2033 if (eb->args->flags & I915_EXEC_GEN7_SOL_RESET) {
2034 err = i915_reset_gen7_sol_offsets(eb->request);
2040 * After we completed waiting for other engines (using HW semaphores)
2041 * then we can signal that this request/batch is ready to run. This
2042 * allows us to determine if the batch is still waiting on the GPU
2043 * or actually running by checking the breadcrumb.
2045 if (eb->engine->emit_init_breadcrumb) {
2046 err = eb->engine->emit_init_breadcrumb(eb->request);
2051 err = eb->engine->emit_bb_start(eb->request,
2052 eb->batch->node.start +
2053 eb->batch_start_offset,
2063 * Find one BSD ring to dispatch the corresponding BSD command.
2064 * The engine index is returned.
2067 gen8_dispatch_bsd_engine(struct drm_i915_private *dev_priv,
2068 struct drm_file *file)
2070 struct drm_i915_file_private *file_priv = file->driver_priv;
2072 /* Check whether the file_priv has already selected one ring. */
2073 if ((int)file_priv->bsd_engine < 0)
2074 file_priv->bsd_engine = atomic_fetch_xor(1,
2075 &dev_priv->mm.bsd_engine_dispatch_index);
2077 return file_priv->bsd_engine;
2080 static const enum intel_engine_id user_ring_map[] = {
2081 [I915_EXEC_DEFAULT] = RCS0,
2082 [I915_EXEC_RENDER] = RCS0,
2083 [I915_EXEC_BLT] = BCS0,
2084 [I915_EXEC_BSD] = VCS0,
2085 [I915_EXEC_VEBOX] = VECS0
2088 static int eb_pin_context(struct i915_execbuffer *eb, struct intel_context *ce)
2093 * ABI: Before userspace accesses the GPU (e.g. execbuffer), report
2094 * EIO if the GPU is already wedged.
2096 err = i915_terminally_wedged(eb->i915);
2101 * Pinning the contexts may generate requests in order to acquire
2102 * GGTT space, so do this first before we reserve a seqno for
2105 err = intel_context_pin(ce);
2109 eb->engine = ce->engine;
2114 static void eb_unpin_context(struct i915_execbuffer *eb)
2116 intel_context_unpin(eb->context);
2120 eb_select_legacy_ring(struct i915_execbuffer *eb,
2121 struct drm_file *file,
2122 struct drm_i915_gem_execbuffer2 *args)
2124 struct drm_i915_private *i915 = eb->i915;
2125 unsigned int user_ring_id = args->flags & I915_EXEC_RING_MASK;
2127 if (user_ring_id != I915_EXEC_BSD &&
2128 (args->flags & I915_EXEC_BSD_MASK)) {
2129 DRM_DEBUG("execbuf with non bsd ring but with invalid "
2130 "bsd dispatch flags: %d\n", (int)(args->flags));
2134 if (user_ring_id == I915_EXEC_BSD && HAS_ENGINE(i915, VCS1)) {
2135 unsigned int bsd_idx = args->flags & I915_EXEC_BSD_MASK;
2137 if (bsd_idx == I915_EXEC_BSD_DEFAULT) {
2138 bsd_idx = gen8_dispatch_bsd_engine(i915, file);
2139 } else if (bsd_idx >= I915_EXEC_BSD_RING1 &&
2140 bsd_idx <= I915_EXEC_BSD_RING2) {
2141 bsd_idx >>= I915_EXEC_BSD_SHIFT;
2144 DRM_DEBUG("execbuf with unknown bsd ring: %u\n",
2149 return _VCS(bsd_idx);
2152 if (user_ring_id >= ARRAY_SIZE(user_ring_map)) {
2153 DRM_DEBUG("execbuf with unknown ring: %u\n", user_ring_id);
2157 return user_ring_map[user_ring_id];
2161 eb_select_engine(struct i915_execbuffer *eb,
2162 struct drm_file *file,
2163 struct drm_i915_gem_execbuffer2 *args)
2165 struct intel_context *ce;
2169 if (i915_gem_context_user_engines(eb->gem_context))
2170 idx = args->flags & I915_EXEC_RING_MASK;
2172 idx = eb_select_legacy_ring(eb, file, args);
2174 ce = i915_gem_context_get_engine(eb->gem_context, idx);
2178 err = eb_pin_context(eb, ce);
2179 intel_context_put(ce);
2185 __free_fence_array(struct drm_syncobj **fences, unsigned int n)
2188 drm_syncobj_put(ptr_mask_bits(fences[n], 2));
2192 static struct drm_syncobj **
2193 get_fence_array(struct drm_i915_gem_execbuffer2 *args,
2194 struct drm_file *file)
2196 const unsigned long nfences = args->num_cliprects;
2197 struct drm_i915_gem_exec_fence __user *user;
2198 struct drm_syncobj **fences;
2202 if (!(args->flags & I915_EXEC_FENCE_ARRAY))
2205 /* Check multiplication overflow for access_ok() and kvmalloc_array() */
2206 BUILD_BUG_ON(sizeof(size_t) > sizeof(unsigned long));
2207 if (nfences > min_t(unsigned long,
2208 ULONG_MAX / sizeof(*user),
2209 SIZE_MAX / sizeof(*fences)))
2210 return ERR_PTR(-EINVAL);
2212 user = u64_to_user_ptr(args->cliprects_ptr);
2213 if (!access_ok(user, nfences * sizeof(*user)))
2214 return ERR_PTR(-EFAULT);
2216 fences = kvmalloc_array(nfences, sizeof(*fences),
2217 __GFP_NOWARN | GFP_KERNEL);
2219 return ERR_PTR(-ENOMEM);
2221 for (n = 0; n < nfences; n++) {
2222 struct drm_i915_gem_exec_fence fence;
2223 struct drm_syncobj *syncobj;
2225 if (__copy_from_user(&fence, user++, sizeof(fence))) {
2230 if (fence.flags & __I915_EXEC_FENCE_UNKNOWN_FLAGS) {
2235 syncobj = drm_syncobj_find(file, fence.handle);
2237 DRM_DEBUG("Invalid syncobj handle provided\n");
2242 BUILD_BUG_ON(~(ARCH_KMALLOC_MINALIGN - 1) &
2243 ~__I915_EXEC_FENCE_UNKNOWN_FLAGS);
2245 fences[n] = ptr_pack_bits(syncobj, fence.flags, 2);
2251 __free_fence_array(fences, n);
2252 return ERR_PTR(err);
2256 put_fence_array(struct drm_i915_gem_execbuffer2 *args,
2257 struct drm_syncobj **fences)
2260 __free_fence_array(fences, args->num_cliprects);
2264 await_fence_array(struct i915_execbuffer *eb,
2265 struct drm_syncobj **fences)
2267 const unsigned int nfences = eb->args->num_cliprects;
2271 for (n = 0; n < nfences; n++) {
2272 struct drm_syncobj *syncobj;
2273 struct dma_fence *fence;
2276 syncobj = ptr_unpack_bits(fences[n], &flags, 2);
2277 if (!(flags & I915_EXEC_FENCE_WAIT))
2280 fence = drm_syncobj_fence_get(syncobj);
2284 err = i915_request_await_dma_fence(eb->request, fence);
2285 dma_fence_put(fence);
2294 signal_fence_array(struct i915_execbuffer *eb,
2295 struct drm_syncobj **fences)
2297 const unsigned int nfences = eb->args->num_cliprects;
2298 struct dma_fence * const fence = &eb->request->fence;
2301 for (n = 0; n < nfences; n++) {
2302 struct drm_syncobj *syncobj;
2305 syncobj = ptr_unpack_bits(fences[n], &flags, 2);
2306 if (!(flags & I915_EXEC_FENCE_SIGNAL))
2309 drm_syncobj_replace_fence(syncobj, fence);
2314 i915_gem_do_execbuffer(struct drm_device *dev,
2315 struct drm_file *file,
2316 struct drm_i915_gem_execbuffer2 *args,
2317 struct drm_i915_gem_exec_object2 *exec,
2318 struct drm_syncobj **fences)
2320 struct i915_execbuffer eb;
2321 struct dma_fence *in_fence = NULL;
2322 struct dma_fence *exec_fence = NULL;
2323 struct sync_file *out_fence = NULL;
2324 int out_fence_fd = -1;
2327 BUILD_BUG_ON(__EXEC_INTERNAL_FLAGS & ~__I915_EXEC_ILLEGAL_FLAGS);
2328 BUILD_BUG_ON(__EXEC_OBJECT_INTERNAL_FLAGS &
2329 ~__EXEC_OBJECT_UNKNOWN_FLAGS);
2331 eb.i915 = to_i915(dev);
2334 if (DBG_FORCE_RELOC || !(args->flags & I915_EXEC_NO_RELOC))
2335 args->flags |= __EXEC_HAS_RELOC;
2338 eb.vma = (struct i915_vma **)(exec + args->buffer_count + 1);
2340 eb.flags = (unsigned int *)(eb.vma + args->buffer_count + 1);
2342 eb.invalid_flags = __EXEC_OBJECT_UNKNOWN_FLAGS;
2343 reloc_cache_init(&eb.reloc_cache, eb.i915);
2345 eb.buffer_count = args->buffer_count;
2346 eb.batch_start_offset = args->batch_start_offset;
2347 eb.batch_len = args->batch_len;
2350 if (args->flags & I915_EXEC_SECURE) {
2351 if (!drm_is_current_master(file) || !capable(CAP_SYS_ADMIN))
2354 eb.batch_flags |= I915_DISPATCH_SECURE;
2356 if (args->flags & I915_EXEC_IS_PINNED)
2357 eb.batch_flags |= I915_DISPATCH_PINNED;
2359 if (args->flags & I915_EXEC_FENCE_IN) {
2360 in_fence = sync_file_get_fence(lower_32_bits(args->rsvd2));
2365 if (args->flags & I915_EXEC_FENCE_SUBMIT) {
2371 exec_fence = sync_file_get_fence(lower_32_bits(args->rsvd2));
2378 if (args->flags & I915_EXEC_FENCE_OUT) {
2379 out_fence_fd = get_unused_fd_flags(O_CLOEXEC);
2380 if (out_fence_fd < 0) {
2382 goto err_exec_fence;
2386 err = eb_create(&eb);
2390 GEM_BUG_ON(!eb.lut_size);
2392 err = eb_select_context(&eb);
2397 * Take a local wakeref for preparing to dispatch the execbuf as
2398 * we expect to access the hardware fairly frequently in the
2399 * process. Upon first dispatch, we acquire another prolonged
2400 * wakeref that we hold until the GPU has been idle for at least
2403 intel_gt_pm_get(eb.i915);
2405 err = i915_mutex_lock_interruptible(dev);
2409 err = eb_select_engine(&eb, file, args);
2413 err = eb_wait_for_ring(&eb); /* may temporarily drop struct_mutex */
2417 err = eb_relocate(&eb);
2420 * If the user expects the execobject.offset and
2421 * reloc.presumed_offset to be an exact match,
2422 * as for using NO_RELOC, then we cannot update
2423 * the execobject.offset until we have completed
2426 args->flags &= ~__EXEC_HAS_RELOC;
2430 if (unlikely(*eb.batch->exec_flags & EXEC_OBJECT_WRITE)) {
2431 DRM_DEBUG("Attempting to use self-modifying batch buffer\n");
2435 if (eb.batch_start_offset > eb.batch->size ||
2436 eb.batch_len > eb.batch->size - eb.batch_start_offset) {
2437 DRM_DEBUG("Attempting to use out-of-bounds batch\n");
2442 if (eb_use_cmdparser(&eb)) {
2443 struct i915_vma *vma;
2445 vma = eb_parse(&eb, drm_is_current_master(file));
2453 * Batch parsed and accepted:
2455 * Set the DISPATCH_SECURE bit to remove the NON_SECURE
2456 * bit from MI_BATCH_BUFFER_START commands issued in
2457 * the dispatch_execbuffer implementations. We
2458 * specifically don't want that set on batches the
2459 * command parser has accepted.
2461 eb.batch_flags |= I915_DISPATCH_SECURE;
2462 eb.batch_start_offset = 0;
2467 if (eb.batch_len == 0)
2468 eb.batch_len = eb.batch->size - eb.batch_start_offset;
2471 * snb/ivb/vlv conflate the "batch in ppgtt" bit with the "non-secure
2472 * batch" bit. Hence we need to pin secure batches into the global gtt.
2473 * hsw should have this fixed, but bdw mucks it up again. */
2474 if (eb.batch_flags & I915_DISPATCH_SECURE) {
2475 struct i915_vma *vma;
2478 * So on first glance it looks freaky that we pin the batch here
2479 * outside of the reservation loop. But:
2480 * - The batch is already pinned into the relevant ppgtt, so we
2481 * already have the backing storage fully allocated.
2482 * - No other BO uses the global gtt (well contexts, but meh),
2483 * so we don't really have issues with multiple objects not
2484 * fitting due to fragmentation.
2485 * So this is actually safe.
2487 vma = i915_gem_object_ggtt_pin(eb.batch->obj, NULL, 0, 0, 0);
2496 /* All GPU relocation batches must be submitted prior to the user rq */
2497 GEM_BUG_ON(eb.reloc_cache.rq);
2499 /* Allocate a request for this batch buffer nice and early. */
2500 eb.request = i915_request_create(eb.context);
2501 if (IS_ERR(eb.request)) {
2502 err = PTR_ERR(eb.request);
2503 goto err_batch_unpin;
2507 err = i915_request_await_dma_fence(eb.request, in_fence);
2513 err = i915_request_await_execution(eb.request, exec_fence,
2514 eb.engine->bond_execute);
2520 err = await_fence_array(&eb, fences);
2525 if (out_fence_fd != -1) {
2526 out_fence = sync_file_create(&eb.request->fence);
2534 * Whilst this request exists, batch_obj will be on the
2535 * active_list, and so will hold the active reference. Only when this
2536 * request is retired will the the batch_obj be moved onto the
2537 * inactive_list and lose its active reference. Hence we do not need
2538 * to explicitly hold another reference here.
2540 eb.request->batch = eb.batch;
2542 trace_i915_request_queue(eb.request, eb.batch_flags);
2543 err = eb_submit(&eb);
2545 add_to_client(eb.request, file);
2546 i915_request_add(eb.request);
2549 signal_fence_array(&eb, fences);
2553 fd_install(out_fence_fd, out_fence->file);
2554 args->rsvd2 &= GENMASK_ULL(31, 0); /* keep in-fence */
2555 args->rsvd2 |= (u64)out_fence_fd << 32;
2558 fput(out_fence->file);
2563 if (eb.batch_flags & I915_DISPATCH_SECURE)
2564 i915_vma_unpin(eb.batch);
2567 eb_release_vmas(&eb);
2569 eb_unpin_context(&eb);
2571 mutex_unlock(&dev->struct_mutex);
2573 intel_gt_pm_put(eb.i915);
2574 i915_gem_context_put(eb.gem_context);
2578 if (out_fence_fd != -1)
2579 put_unused_fd(out_fence_fd);
2581 dma_fence_put(exec_fence);
2583 dma_fence_put(in_fence);
2587 static size_t eb_element_size(void)
2589 return (sizeof(struct drm_i915_gem_exec_object2) +
2590 sizeof(struct i915_vma *) +
2591 sizeof(unsigned int));
2594 static bool check_buffer_count(size_t count)
2596 const size_t sz = eb_element_size();
2599 * When using LUT_HANDLE, we impose a limit of INT_MAX for the lookup
2600 * array size (see eb_create()). Otherwise, we can accept an array as
2601 * large as can be addressed (though use large arrays at your peril)!
2604 return !(count < 1 || count > INT_MAX || count > SIZE_MAX / sz - 1);
2608 * Legacy execbuffer just creates an exec2 list from the original exec object
2609 * list array and passes it to the real function.
2612 i915_gem_execbuffer_ioctl(struct drm_device *dev, void *data,
2613 struct drm_file *file)
2615 struct drm_i915_gem_execbuffer *args = data;
2616 struct drm_i915_gem_execbuffer2 exec2;
2617 struct drm_i915_gem_exec_object *exec_list = NULL;
2618 struct drm_i915_gem_exec_object2 *exec2_list = NULL;
2619 const size_t count = args->buffer_count;
2623 if (!check_buffer_count(count)) {
2624 DRM_DEBUG("execbuf2 with %zd buffers\n", count);
2628 exec2.buffers_ptr = args->buffers_ptr;
2629 exec2.buffer_count = args->buffer_count;
2630 exec2.batch_start_offset = args->batch_start_offset;
2631 exec2.batch_len = args->batch_len;
2632 exec2.DR1 = args->DR1;
2633 exec2.DR4 = args->DR4;
2634 exec2.num_cliprects = args->num_cliprects;
2635 exec2.cliprects_ptr = args->cliprects_ptr;
2636 exec2.flags = I915_EXEC_RENDER;
2637 i915_execbuffer2_set_context_id(exec2, 0);
2639 if (!i915_gem_check_execbuffer(&exec2))
2642 /* Copy in the exec list from userland */
2643 exec_list = kvmalloc_array(count, sizeof(*exec_list),
2644 __GFP_NOWARN | GFP_KERNEL);
2645 exec2_list = kvmalloc_array(count + 1, eb_element_size(),
2646 __GFP_NOWARN | GFP_KERNEL);
2647 if (exec_list == NULL || exec2_list == NULL) {
2648 DRM_DEBUG("Failed to allocate exec list for %d buffers\n",
2649 args->buffer_count);
2654 err = copy_from_user(exec_list,
2655 u64_to_user_ptr(args->buffers_ptr),
2656 sizeof(*exec_list) * count);
2658 DRM_DEBUG("copy %d exec entries failed %d\n",
2659 args->buffer_count, err);
2665 for (i = 0; i < args->buffer_count; i++) {
2666 exec2_list[i].handle = exec_list[i].handle;
2667 exec2_list[i].relocation_count = exec_list[i].relocation_count;
2668 exec2_list[i].relocs_ptr = exec_list[i].relocs_ptr;
2669 exec2_list[i].alignment = exec_list[i].alignment;
2670 exec2_list[i].offset = exec_list[i].offset;
2671 if (INTEL_GEN(to_i915(dev)) < 4)
2672 exec2_list[i].flags = EXEC_OBJECT_NEEDS_FENCE;
2674 exec2_list[i].flags = 0;
2677 err = i915_gem_do_execbuffer(dev, file, &exec2, exec2_list, NULL);
2678 if (exec2.flags & __EXEC_HAS_RELOC) {
2679 struct drm_i915_gem_exec_object __user *user_exec_list =
2680 u64_to_user_ptr(args->buffers_ptr);
2682 /* Copy the new buffer offsets back to the user's exec list. */
2683 for (i = 0; i < args->buffer_count; i++) {
2684 if (!(exec2_list[i].offset & UPDATE))
2687 exec2_list[i].offset =
2688 gen8_canonical_addr(exec2_list[i].offset & PIN_OFFSET_MASK);
2689 exec2_list[i].offset &= PIN_OFFSET_MASK;
2690 if (__copy_to_user(&user_exec_list[i].offset,
2691 &exec2_list[i].offset,
2692 sizeof(user_exec_list[i].offset)))
2703 i915_gem_execbuffer2_ioctl(struct drm_device *dev, void *data,
2704 struct drm_file *file)
2706 struct drm_i915_gem_execbuffer2 *args = data;
2707 struct drm_i915_gem_exec_object2 *exec2_list;
2708 struct drm_syncobj **fences = NULL;
2709 const size_t count = args->buffer_count;
2712 if (!check_buffer_count(count)) {
2713 DRM_DEBUG("execbuf2 with %zd buffers\n", count);
2717 if (!i915_gem_check_execbuffer(args))
2720 /* Allocate an extra slot for use by the command parser */
2721 exec2_list = kvmalloc_array(count + 1, eb_element_size(),
2722 __GFP_NOWARN | GFP_KERNEL);
2723 if (exec2_list == NULL) {
2724 DRM_DEBUG("Failed to allocate exec list for %zd buffers\n",
2728 if (copy_from_user(exec2_list,
2729 u64_to_user_ptr(args->buffers_ptr),
2730 sizeof(*exec2_list) * count)) {
2731 DRM_DEBUG("copy %zd exec entries failed\n", count);
2736 if (args->flags & I915_EXEC_FENCE_ARRAY) {
2737 fences = get_fence_array(args, file);
2738 if (IS_ERR(fences)) {
2740 return PTR_ERR(fences);
2744 err = i915_gem_do_execbuffer(dev, file, args, exec2_list, fences);
2747 * Now that we have begun execution of the batchbuffer, we ignore
2748 * any new error after this point. Also given that we have already
2749 * updated the associated relocations, we try to write out the current
2750 * object locations irrespective of any error.
2752 if (args->flags & __EXEC_HAS_RELOC) {
2753 struct drm_i915_gem_exec_object2 __user *user_exec_list =
2754 u64_to_user_ptr(args->buffers_ptr);
2757 /* Copy the new buffer offsets back to the user's exec list. */
2759 * Note: count * sizeof(*user_exec_list) does not overflow,
2760 * because we checked 'count' in check_buffer_count().
2762 * And this range already got effectively checked earlier
2763 * when we did the "copy_from_user()" above.
2765 if (!user_access_begin(user_exec_list, count * sizeof(*user_exec_list)))
2768 for (i = 0; i < args->buffer_count; i++) {
2769 if (!(exec2_list[i].offset & UPDATE))
2772 exec2_list[i].offset =
2773 gen8_canonical_addr(exec2_list[i].offset & PIN_OFFSET_MASK);
2774 unsafe_put_user(exec2_list[i].offset,
2775 &user_exec_list[i].offset,
2783 args->flags &= ~__I915_EXEC_UNKNOWN_FLAGS;
2784 put_fence_array(args, fences);