1 // SPDX-License-Identifier: MIT
2 /*
3 * Copyright © 2008,2010 Intel Corporation
4 */
5
6 #include <linux/dma-resv.h>
7 #include <linux/highmem.h>
8 #include <linux/sync_file.h>
9 #include <linux/uaccess.h>
10
11 #include <drm/drm_auth.h>
12 #include <drm/drm_print.h>
13 #include <drm/drm_syncobj.h>
14
15 #include "gem/i915_gem_ioctls.h"
16 #include "gt/intel_context.h"
17 #include "gt/intel_gpu_commands.h"
18 #include "gt/intel_gt.h"
19 #include "gt/intel_gt_buffer_pool.h"
20 #include "gt/intel_gt_pm.h"
21 #include "gt/intel_ring.h"
22
23 #include "pxp/intel_pxp.h"
24
25 #include "i915_cmd_parser.h"
26 #include "i915_drv.h"
27 #include "i915_file_private.h"
28 #include "i915_gem_clflush.h"
29 #include "i915_gem_context.h"
30 #include "i915_gem_evict.h"
31 #include "i915_gem_ioctls.h"
32 #include "i915_reg.h"
33 #include "i915_trace.h"
34 #include "i915_user_extensions.h"
35
36 struct eb_vma {
37 struct i915_vma *vma;
38 unsigned int flags;
39
40 /** This vma's place in the execbuf reservation list */
41 struct drm_i915_gem_exec_object2 *exec;
42 struct list_head bind_link;
43 struct list_head reloc_link;
44
45 struct hlist_node node;
46 u32 handle;
47 };
48
49 enum {
50 FORCE_CPU_RELOC = 1,
51 FORCE_GTT_RELOC,
52 FORCE_GPU_RELOC,
53 #define DBG_FORCE_RELOC 0 /* choose one of the above! */
54 };
55
56 /* __EXEC_OBJECT_ flags > BIT(29) defined in i915_vma.h */
57 #define __EXEC_OBJECT_HAS_PIN BIT(29)
58 #define __EXEC_OBJECT_HAS_FENCE BIT(28)
59 #define __EXEC_OBJECT_USERPTR_INIT BIT(27)
60 #define __EXEC_OBJECT_NEEDS_MAP BIT(26)
61 #define __EXEC_OBJECT_NEEDS_BIAS BIT(25)
62 #define __EXEC_OBJECT_INTERNAL_FLAGS (~0u << 25) /* all of the above + */
63 #define __EXEC_OBJECT_RESERVED (__EXEC_OBJECT_HAS_PIN | __EXEC_OBJECT_HAS_FENCE)
64
65 #define __EXEC_HAS_RELOC BIT(31)
66 #define __EXEC_ENGINE_PINNED BIT(30)
67 #define __EXEC_USERPTR_USED BIT(29)
68 #define __EXEC_INTERNAL_FLAGS (~0u << 29)
69 #define UPDATE PIN_OFFSET_FIXED
70
71 #define BATCH_OFFSET_BIAS (256*1024)
72
73 #define __I915_EXEC_ILLEGAL_FLAGS \
74 (__I915_EXEC_UNKNOWN_FLAGS | \
75 I915_EXEC_CONSTANTS_MASK | \
76 I915_EXEC_RESOURCE_STREAMER)
77
78 /* Catch emission of unexpected errors for CI! */
79 #if IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM)
80 #undef EINVAL
81 #define EINVAL ({ \
82 DRM_DEBUG_DRIVER("EINVAL at %s:%d\n", __func__, __LINE__); \
83 22; \
84 })
85 #endif
86
87 /**
88 * DOC: User command execution
89 *
90 * Userspace submits commands to be executed on the GPU as an instruction
91 * stream within a GEM object we call a batchbuffer. This instructions may
92 * refer to other GEM objects containing auxiliary state such as kernels,
93 * samplers, render targets and even secondary batchbuffers. Userspace does
94 * not know where in the GPU memory these objects reside and so before the
95 * batchbuffer is passed to the GPU for execution, those addresses in the
96 * batchbuffer and auxiliary objects are updated. This is known as relocation,
97 * or patching. To try and avoid having to relocate each object on the next
98 * execution, userspace is told the location of those objects in this pass,
99 * but this remains just a hint as the kernel may choose a new location for
100 * any object in the future.
101 *
102 * At the level of talking to the hardware, submitting a batchbuffer for the
103 * GPU to execute is to add content to a buffer from which the HW
104 * command streamer is reading.
105 *
106 * 1. Add a command to load the HW context. For Logical Ring Contexts, i.e.
107 * Execlists, this command is not placed on the same buffer as the
108 * remaining items.
109 *
110 * 2. Add a command to invalidate caches to the buffer.
111 *
112 * 3. Add a batchbuffer start command to the buffer; the start command is
113 * essentially a token together with the GPU address of the batchbuffer
114 * to be executed.
115 *
116 * 4. Add a pipeline flush to the buffer.
117 *
118 * 5. Add a memory write command to the buffer to record when the GPU
119 * is done executing the batchbuffer. The memory write writes the
120 * global sequence number of the request, ``i915_request::global_seqno``;
121 * the i915 driver uses the current value in the register to determine
122 * if the GPU has completed the batchbuffer.
123 *
124 * 6. Add a user interrupt command to the buffer. This command instructs
125 * the GPU to issue an interrupt when the command, pipeline flush and
126 * memory write are completed.
127 *
128 * 7. Inform the hardware of the additional commands added to the buffer
129 * (by updating the tail pointer).
130 *
131 * Processing an execbuf ioctl is conceptually split up into a few phases.
132 *
133 * 1. Validation - Ensure all the pointers, handles and flags are valid.
134 * 2. Reservation - Assign GPU address space for every object
135 * 3. Relocation - Update any addresses to point to the final locations
136 * 4. Serialisation - Order the request with respect to its dependencies
137 * 5. Construction - Construct a request to execute the batchbuffer
138 * 6. Submission (at some point in the future execution)
139 *
140 * Reserving resources for the execbuf is the most complicated phase. We
141 * neither want to have to migrate the object in the address space, nor do
142 * we want to have to update any relocations pointing to this object. Ideally,
143 * we want to leave the object where it is and for all the existing relocations
144 * to match. If the object is given a new address, or if userspace thinks the
145 * object is elsewhere, we have to parse all the relocation entries and update
146 * the addresses. Userspace can set the I915_EXEC_NO_RELOC flag to hint that
147 * all the target addresses in all of its objects match the value in the
148 * relocation entries and that they all match the presumed offsets given by the
149 * list of execbuffer objects. Using this knowledge, we know that if we haven't
150 * moved any buffers, all the relocation entries are valid and we can skip
151 * the update. (If userspace is wrong, the likely outcome is an impromptu GPU
152 * hang.) The requirement for using I915_EXEC_NO_RELOC are:
153 *
154 * The addresses written in the objects must match the corresponding
155 * reloc.presumed_offset which in turn must match the corresponding
156 * execobject.offset.
157 *
158 * Any render targets written to in the batch must be flagged with
159 * EXEC_OBJECT_WRITE.
160 *
161 * To avoid stalling, execobject.offset should match the current
162 * address of that object within the active context.
163 *
164 * The reservation is done is multiple phases. First we try and keep any
165 * object already bound in its current location - so as long as meets the
166 * constraints imposed by the new execbuffer. Any object left unbound after the
167 * first pass is then fitted into any available idle space. If an object does
168 * not fit, all objects are removed from the reservation and the process rerun
169 * after sorting the objects into a priority order (more difficult to fit
170 * objects are tried first). Failing that, the entire VM is cleared and we try
171 * to fit the execbuf once last time before concluding that it simply will not
172 * fit.
173 *
174 * A small complication to all of this is that we allow userspace not only to
175 * specify an alignment and a size for the object in the address space, but
176 * we also allow userspace to specify the exact offset. This objects are
177 * simpler to place (the location is known a priori) all we have to do is make
178 * sure the space is available.
179 *
180 * Once all the objects are in place, patching up the buried pointers to point
181 * to the final locations is a fairly simple job of walking over the relocation
182 * entry arrays, looking up the right address and rewriting the value into
183 * the object. Simple! ... The relocation entries are stored in user memory
184 * and so to access them we have to copy them into a local buffer. That copy
185 * has to avoid taking any pagefaults as they may lead back to a GEM object
186 * requiring the vm->mutex (i.e. recursive deadlock). So once again we split
187 * the relocation into multiple passes. First we try to do everything within an
188 * atomic context (avoid the pagefaults) which requires that we never wait. If
189 * we detect that we may wait, or if we need to fault, then we have to fallback
190 * to a slower path. The slowpath has to drop the mutex. (Can you hear alarm
191 * bells yet?) Dropping the mutex means that we lose all the state we have
192 * built up so far for the execbuf and we must reset any global data. However,
193 * we do leave the objects pinned in their final locations - which is a
194 * potential issue for concurrent execbufs. Once we have left the mutex, we can
195 * allocate and copy all the relocation entries into a large array at our
196 * leisure, reacquire the mutex, reclaim all the objects and other state and
197 * then proceed to update any incorrect addresses with the objects.
198 *
199 * As we process the relocation entries, we maintain a record of whether the
200 * object is being written to. Using NORELOC, we expect userspace to provide
201 * this information instead. We also check whether we can skip the relocation
202 * by comparing the expected value inside the relocation entry with the target's
203 * final address. If they differ, we have to map the current object and rewrite
204 * the 4 or 8 byte pointer within.
205 *
206 * Serialising an execbuf is quite simple according to the rules of the GEM
207 * ABI. Execution within each context is ordered by the order of submission.
208 * Writes to any GEM object are in order of submission and are exclusive. Reads
209 * from a GEM object are unordered with respect to other reads, but ordered by
210 * writes. A write submitted after a read cannot occur before the read, and
211 * similarly any read submitted after a write cannot occur before the write.
212 * Writes are ordered between engines such that only one write occurs at any
213 * time (completing any reads beforehand) - using semaphores where available
214 * and CPU serialisation otherwise. Other GEM access obey the same rules, any
215 * write (either via mmaps using set-domain, or via pwrite) must flush all GPU
216 * reads before starting, and any read (either using set-domain or pread) must
217 * flush all GPU writes before starting. (Note we only employ a barrier before,
218 * we currently rely on userspace not concurrently starting a new execution
219 * whilst reading or writing to an object. This may be an advantage or not
220 * depending on how much you trust userspace not to shoot themselves in the
221 * foot.) Serialisation may just result in the request being inserted into
222 * a DAG awaiting its turn, but most simple is to wait on the CPU until
223 * all dependencies are resolved.
224 *
225 * After all of that, is just a matter of closing the request and handing it to
226 * the hardware (well, leaving it in a queue to be executed). However, we also
227 * offer the ability for batchbuffers to be run with elevated privileges so
228 * that they access otherwise hidden registers. (Used to adjust L3 cache etc.)
229 * Before any batch is given extra privileges we first must check that it
230 * contains no nefarious instructions, we check that each instruction is from
231 * our whitelist and all registers are also from an allowed list. We first
232 * copy the user's batchbuffer to a shadow (so that the user doesn't have
233 * access to it, either by the CPU or GPU as we scan it) and then parse each
234 * instruction. If everything is ok, we set a flag telling the hardware to run
235 * the batchbuffer in trusted mode, otherwise the ioctl is rejected.
236 */
237
238 struct eb_fence {
239 struct drm_syncobj *syncobj; /* Use with ptr_mask_bits() */
240 struct dma_fence *dma_fence;
241 u64 value;
242 struct dma_fence_chain *chain_fence;
243 };
244
245 struct i915_execbuffer {
246 struct drm_i915_private *i915; /** i915 backpointer */
247 struct drm_file *file; /** per-file lookup tables and limits */
248 struct drm_i915_gem_execbuffer2 *args; /** ioctl parameters */
249 struct drm_i915_gem_exec_object2 *exec; /** ioctl execobj[] */
250 struct eb_vma *vma;
251
252 struct intel_gt *gt; /* gt for the execbuf */
253 struct intel_context *context; /* logical state for the request */
254 struct i915_gem_context *gem_context; /** caller's context */
255 intel_wakeref_t wakeref;
256 intel_wakeref_t wakeref_gt0;
257
258 /** our requests to build */
259 struct i915_request *requests[MAX_ENGINE_INSTANCE + 1];
260 /** identity of the batch obj/vma */
261 struct eb_vma *batches[MAX_ENGINE_INSTANCE + 1];
262 struct i915_vma *trampoline; /** trampoline used for chaining */
263
264 /** used for excl fence in dma_resv objects when > 1 BB submitted */
265 struct dma_fence *composite_fence;
266
267 /** actual size of execobj[] as we may extend it for the cmdparser */
268 unsigned int buffer_count;
269
270 /* number of batches in execbuf IOCTL */
271 unsigned int num_batches;
272
273 /** list of vma not yet bound during reservation phase */
274 struct list_head unbound;
275
276 /** list of vma that have execobj.relocation_count */
277 struct list_head relocs;
278
279 struct i915_gem_ww_ctx ww;
280
281 /**
282 * Track the most recently used object for relocations, as we
283 * frequently have to perform multiple relocations within the same
284 * obj/page
285 */
286 struct reloc_cache {
287 struct drm_mm_node node; /** temporary GTT binding */
288 unsigned long vaddr; /** Current kmap address */
289 unsigned long page; /** Currently mapped page index */
290 unsigned int graphics_ver; /** Cached value of GRAPHICS_VER */
291 bool use_64bit_reloc : 1;
292 bool has_llc : 1;
293 bool has_fence : 1;
294 bool needs_unfenced : 1;
295 } reloc_cache;
296
297 u64 invalid_flags; /** Set of execobj.flags that are invalid */
298
299 /** Length of batch within object */
300 u64 batch_len[MAX_ENGINE_INSTANCE + 1];
301 u32 batch_start_offset; /** Location within object of batch */
302 u32 batch_flags; /** Flags composed for emit_bb_start() */
303 struct intel_gt_buffer_pool_node *batch_pool; /** pool node for batch buffer */
304
305 /**
306 * Indicate either the size of the hashtable used to resolve
307 * relocation handles, or if negative that we are using a direct
308 * index into the execobj[].
309 */
310 int lut_size;
311 struct hlist_head *buckets; /** ht for relocation handles */
312
313 struct eb_fence *fences;
314 unsigned long num_fences;
315 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
316 struct i915_capture_list *capture_lists[MAX_ENGINE_INSTANCE + 1];
317 #endif
318 };
319
320 static int eb_parse(struct i915_execbuffer *eb);
321 static int eb_pin_engine(struct i915_execbuffer *eb, bool throttle);
322 static void eb_unpin_engine(struct i915_execbuffer *eb);
323 static void eb_capture_release(struct i915_execbuffer *eb);
324
eb_use_cmdparser(const struct i915_execbuffer * eb)325 static bool eb_use_cmdparser(const struct i915_execbuffer *eb)
326 {
327 return intel_engine_requires_cmd_parser(eb->context->engine) ||
328 (intel_engine_using_cmd_parser(eb->context->engine) &&
329 eb->args->batch_len);
330 }
331
eb_create(struct i915_execbuffer * eb)332 static int eb_create(struct i915_execbuffer *eb)
333 {
334 if (!(eb->args->flags & I915_EXEC_HANDLE_LUT)) {
335 unsigned int size = 1 + ilog2(eb->buffer_count);
336
337 /*
338 * Without a 1:1 association between relocation handles and
339 * the execobject[] index, we instead create a hashtable.
340 * We size it dynamically based on available memory, starting
341 * first with 1:1 associative hash and scaling back until
342 * the allocation succeeds.
343 *
344 * Later on we use a positive lut_size to indicate we are
345 * using this hashtable, and a negative value to indicate a
346 * direct lookup.
347 */
348 do {
349 gfp_t flags;
350
351 /* While we can still reduce the allocation size, don't
352 * raise a warning and allow the allocation to fail.
353 * On the last pass though, we want to try as hard
354 * as possible to perform the allocation and warn
355 * if it fails.
356 */
357 flags = GFP_KERNEL;
358 if (size > 1)
359 flags |= __GFP_NORETRY | __GFP_NOWARN;
360
361 eb->buckets = kzalloc(sizeof(struct hlist_head) << size,
362 flags);
363 if (eb->buckets)
364 break;
365 } while (--size);
366
367 if (unlikely(!size))
368 return -ENOMEM;
369
370 eb->lut_size = size;
371 } else {
372 eb->lut_size = -eb->buffer_count;
373 }
374
375 return 0;
376 }
377
378 static bool
eb_vma_misplaced(const struct drm_i915_gem_exec_object2 * entry,const struct i915_vma * vma,unsigned int flags)379 eb_vma_misplaced(const struct drm_i915_gem_exec_object2 *entry,
380 const struct i915_vma *vma,
381 unsigned int flags)
382 {
383 const u64 start = i915_vma_offset(vma);
384 const u64 size = i915_vma_size(vma);
385
386 if (size < entry->pad_to_size)
387 return true;
388
389 if (entry->alignment && !IS_ALIGNED(start, entry->alignment))
390 return true;
391
392 if (flags & EXEC_OBJECT_PINNED &&
393 start != entry->offset)
394 return true;
395
396 if (flags & __EXEC_OBJECT_NEEDS_BIAS &&
397 start < BATCH_OFFSET_BIAS)
398 return true;
399
400 if (!(flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS) &&
401 (start + size + 4095) >> 32)
402 return true;
403
404 if (flags & __EXEC_OBJECT_NEEDS_MAP &&
405 !i915_vma_is_map_and_fenceable(vma))
406 return true;
407
408 return false;
409 }
410
eb_pin_flags(const struct drm_i915_gem_exec_object2 * entry,unsigned int exec_flags)411 static u64 eb_pin_flags(const struct drm_i915_gem_exec_object2 *entry,
412 unsigned int exec_flags)
413 {
414 u64 pin_flags = 0;
415
416 if (exec_flags & EXEC_OBJECT_NEEDS_GTT)
417 pin_flags |= PIN_GLOBAL;
418
419 /*
420 * Wa32bitGeneralStateOffset & Wa32bitInstructionBaseOffset,
421 * limit address to the first 4GBs for unflagged objects.
422 */
423 if (!(exec_flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS))
424 pin_flags |= PIN_ZONE_4G;
425
426 if (exec_flags & __EXEC_OBJECT_NEEDS_MAP)
427 pin_flags |= PIN_MAPPABLE;
428
429 if (exec_flags & EXEC_OBJECT_PINNED)
430 pin_flags |= entry->offset | PIN_OFFSET_FIXED;
431 else if (exec_flags & __EXEC_OBJECT_NEEDS_BIAS)
432 pin_flags |= BATCH_OFFSET_BIAS | PIN_OFFSET_BIAS;
433
434 return pin_flags;
435 }
436
437 static int
eb_pin_vma(struct i915_execbuffer * eb,const struct drm_i915_gem_exec_object2 * entry,struct eb_vma * ev)438 eb_pin_vma(struct i915_execbuffer *eb,
439 const struct drm_i915_gem_exec_object2 *entry,
440 struct eb_vma *ev)
441 {
442 struct i915_vma *vma = ev->vma;
443 u64 pin_flags;
444 int err;
445
446 if (vma->node.size)
447 pin_flags = __i915_vma_offset(vma);
448 else
449 pin_flags = entry->offset & PIN_OFFSET_MASK;
450
451 pin_flags |= PIN_USER | PIN_NOEVICT | PIN_OFFSET_FIXED | PIN_VALIDATE;
452 if (unlikely(ev->flags & EXEC_OBJECT_NEEDS_GTT))
453 pin_flags |= PIN_GLOBAL;
454
455 /* Attempt to reuse the current location if available */
456 err = i915_vma_pin_ww(vma, &eb->ww, 0, 0, pin_flags);
457 if (err == -EDEADLK)
458 return err;
459
460 if (unlikely(err)) {
461 if (entry->flags & EXEC_OBJECT_PINNED)
462 return err;
463
464 /* Failing that pick any _free_ space if suitable */
465 err = i915_vma_pin_ww(vma, &eb->ww,
466 entry->pad_to_size,
467 entry->alignment,
468 eb_pin_flags(entry, ev->flags) |
469 PIN_USER | PIN_NOEVICT | PIN_VALIDATE);
470 if (unlikely(err))
471 return err;
472 }
473
474 if (unlikely(ev->flags & EXEC_OBJECT_NEEDS_FENCE)) {
475 err = i915_vma_pin_fence(vma);
476 if (unlikely(err))
477 return err;
478
479 if (vma->fence)
480 ev->flags |= __EXEC_OBJECT_HAS_FENCE;
481 }
482
483 ev->flags |= __EXEC_OBJECT_HAS_PIN;
484 if (eb_vma_misplaced(entry, vma, ev->flags))
485 return -EBADSLT;
486
487 return 0;
488 }
489
490 static void
eb_unreserve_vma(struct eb_vma * ev)491 eb_unreserve_vma(struct eb_vma *ev)
492 {
493 if (unlikely(ev->flags & __EXEC_OBJECT_HAS_FENCE))
494 __i915_vma_unpin_fence(ev->vma);
495
496 ev->flags &= ~__EXEC_OBJECT_RESERVED;
497 }
498
499 static int
eb_validate_vma(struct i915_execbuffer * eb,struct drm_i915_gem_exec_object2 * entry,struct i915_vma * vma)500 eb_validate_vma(struct i915_execbuffer *eb,
501 struct drm_i915_gem_exec_object2 *entry,
502 struct i915_vma *vma)
503 {
504 /* Relocations are disallowed for all platforms after TGL-LP. This
505 * also covers all platforms with local memory.
506 */
507 if (entry->relocation_count &&
508 GRAPHICS_VER(eb->i915) >= 12 && !IS_TIGERLAKE(eb->i915))
509 return -EINVAL;
510
511 if (unlikely(entry->flags & eb->invalid_flags))
512 return -EINVAL;
513
514 if (unlikely(entry->alignment &&
515 !is_power_of_2_u64(entry->alignment)))
516 return -EINVAL;
517
518 /*
519 * Offset can be used as input (EXEC_OBJECT_PINNED), reject
520 * any non-page-aligned or non-canonical addresses.
521 */
522 if (unlikely(entry->flags & EXEC_OBJECT_PINNED &&
523 entry->offset != gen8_canonical_addr(entry->offset & I915_GTT_PAGE_MASK)))
524 return -EINVAL;
525
526 /* pad_to_size was once a reserved field, so sanitize it */
527 if (entry->flags & EXEC_OBJECT_PAD_TO_SIZE) {
528 if (unlikely(offset_in_page(entry->pad_to_size)))
529 return -EINVAL;
530 } else {
531 entry->pad_to_size = 0;
532 }
533 /*
534 * From drm_mm perspective address space is continuous,
535 * so from this point we're always using non-canonical
536 * form internally.
537 */
538 entry->offset = gen8_noncanonical_addr(entry->offset);
539
540 if (!eb->reloc_cache.has_fence) {
541 entry->flags &= ~EXEC_OBJECT_NEEDS_FENCE;
542 } else {
543 if ((entry->flags & EXEC_OBJECT_NEEDS_FENCE ||
544 eb->reloc_cache.needs_unfenced) &&
545 i915_gem_object_is_tiled(vma->obj))
546 entry->flags |= EXEC_OBJECT_NEEDS_GTT | __EXEC_OBJECT_NEEDS_MAP;
547 }
548
549 return 0;
550 }
551
552 static bool
is_batch_buffer(struct i915_execbuffer * eb,unsigned int buffer_idx)553 is_batch_buffer(struct i915_execbuffer *eb, unsigned int buffer_idx)
554 {
555 return eb->args->flags & I915_EXEC_BATCH_FIRST ?
556 buffer_idx < eb->num_batches :
557 buffer_idx >= eb->args->buffer_count - eb->num_batches;
558 }
559
560 static int
eb_add_vma(struct i915_execbuffer * eb,unsigned int * current_batch,unsigned int i,struct i915_vma * vma)561 eb_add_vma(struct i915_execbuffer *eb,
562 unsigned int *current_batch,
563 unsigned int i,
564 struct i915_vma *vma)
565 {
566 struct drm_i915_private *i915 = eb->i915;
567 struct drm_i915_gem_exec_object2 *entry = &eb->exec[i];
568 struct eb_vma *ev = &eb->vma[i];
569
570 ev->vma = vma;
571 ev->exec = entry;
572 ev->flags = entry->flags;
573
574 if (eb->lut_size > 0) {
575 ev->handle = entry->handle;
576 hlist_add_head(&ev->node,
577 &eb->buckets[hash_32(entry->handle,
578 eb->lut_size)]);
579 }
580
581 if (entry->relocation_count)
582 list_add_tail(&ev->reloc_link, &eb->relocs);
583
584 /*
585 * SNA is doing fancy tricks with compressing batch buffers, which leads
586 * to negative relocation deltas. Usually that works out ok since the
587 * relocate address is still positive, except when the batch is placed
588 * very low in the GTT. Ensure this doesn't happen.
589 *
590 * Note that actual hangs have only been observed on gen7, but for
591 * paranoia do it everywhere.
592 */
593 if (is_batch_buffer(eb, i)) {
594 if (entry->relocation_count &&
595 !(ev->flags & EXEC_OBJECT_PINNED))
596 ev->flags |= __EXEC_OBJECT_NEEDS_BIAS;
597 if (eb->reloc_cache.has_fence)
598 ev->flags |= EXEC_OBJECT_NEEDS_FENCE;
599
600 eb->batches[*current_batch] = ev;
601
602 if (unlikely(ev->flags & EXEC_OBJECT_WRITE)) {
603 drm_dbg(&i915->drm,
604 "Attempting to use self-modifying batch buffer\n");
605 return -EINVAL;
606 }
607
608 if (range_overflows_t(u64,
609 eb->batch_start_offset,
610 eb->args->batch_len,
611 ev->vma->size)) {
612 drm_dbg(&i915->drm, "Attempting to use out-of-bounds batch\n");
613 return -EINVAL;
614 }
615
616 if (eb->args->batch_len == 0)
617 eb->batch_len[*current_batch] = ev->vma->size -
618 eb->batch_start_offset;
619 else
620 eb->batch_len[*current_batch] = eb->args->batch_len;
621 if (unlikely(eb->batch_len[*current_batch] == 0)) { /* impossible! */
622 drm_dbg(&i915->drm, "Invalid batch length\n");
623 return -EINVAL;
624 }
625
626 ++*current_batch;
627 }
628
629 return 0;
630 }
631
use_cpu_reloc(const struct reloc_cache * cache,const struct drm_i915_gem_object * obj)632 static int use_cpu_reloc(const struct reloc_cache *cache,
633 const struct drm_i915_gem_object *obj)
634 {
635 if (!i915_gem_object_has_struct_page(obj))
636 return false;
637
638 if (DBG_FORCE_RELOC == FORCE_CPU_RELOC)
639 return true;
640
641 if (DBG_FORCE_RELOC == FORCE_GTT_RELOC)
642 return false;
643
644 /*
645 * For objects created by userspace through GEM_CREATE with pat_index
646 * set by set_pat extension, i915_gem_object_has_cache_level() always
647 * return true, otherwise the call would fall back to checking whether
648 * the object is un-cached.
649 */
650 return (cache->has_llc ||
651 obj->cache_dirty ||
652 !i915_gem_object_has_cache_level(obj, I915_CACHE_NONE));
653 }
654
eb_reserve_vma(struct i915_execbuffer * eb,struct eb_vma * ev,u64 pin_flags)655 static int eb_reserve_vma(struct i915_execbuffer *eb,
656 struct eb_vma *ev,
657 u64 pin_flags)
658 {
659 struct drm_i915_gem_exec_object2 *entry = ev->exec;
660 struct i915_vma *vma = ev->vma;
661 int err;
662
663 if (drm_mm_node_allocated(&vma->node) &&
664 eb_vma_misplaced(entry, vma, ev->flags)) {
665 err = i915_vma_unbind(vma);
666 if (err)
667 return err;
668 }
669
670 err = i915_vma_pin_ww(vma, &eb->ww,
671 entry->pad_to_size, entry->alignment,
672 eb_pin_flags(entry, ev->flags) | pin_flags);
673 if (err)
674 return err;
675
676 if (entry->offset != i915_vma_offset(vma)) {
677 entry->offset = i915_vma_offset(vma) | UPDATE;
678 eb->args->flags |= __EXEC_HAS_RELOC;
679 }
680
681 if (unlikely(ev->flags & EXEC_OBJECT_NEEDS_FENCE)) {
682 err = i915_vma_pin_fence(vma);
683 if (unlikely(err))
684 return err;
685
686 if (vma->fence)
687 ev->flags |= __EXEC_OBJECT_HAS_FENCE;
688 }
689
690 ev->flags |= __EXEC_OBJECT_HAS_PIN;
691 GEM_BUG_ON(eb_vma_misplaced(entry, vma, ev->flags));
692
693 return 0;
694 }
695
eb_unbind(struct i915_execbuffer * eb,bool force)696 static bool eb_unbind(struct i915_execbuffer *eb, bool force)
697 {
698 const unsigned int count = eb->buffer_count;
699 unsigned int i;
700 struct list_head last;
701 bool unpinned = false;
702
703 /* Resort *all* the objects into priority order */
704 INIT_LIST_HEAD(&eb->unbound);
705 INIT_LIST_HEAD(&last);
706
707 for (i = 0; i < count; i++) {
708 struct eb_vma *ev = &eb->vma[i];
709 unsigned int flags = ev->flags;
710
711 if (!force && flags & EXEC_OBJECT_PINNED &&
712 flags & __EXEC_OBJECT_HAS_PIN)
713 continue;
714
715 unpinned = true;
716 eb_unreserve_vma(ev);
717
718 if (flags & EXEC_OBJECT_PINNED)
719 /* Pinned must have their slot */
720 list_add(&ev->bind_link, &eb->unbound);
721 else if (flags & __EXEC_OBJECT_NEEDS_MAP)
722 /* Map require the lowest 256MiB (aperture) */
723 list_add_tail(&ev->bind_link, &eb->unbound);
724 else if (!(flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS))
725 /* Prioritise 4GiB region for restricted bo */
726 list_add(&ev->bind_link, &last);
727 else
728 list_add_tail(&ev->bind_link, &last);
729 }
730
731 list_splice_tail(&last, &eb->unbound);
732 return unpinned;
733 }
734
eb_reserve(struct i915_execbuffer * eb)735 static int eb_reserve(struct i915_execbuffer *eb)
736 {
737 struct eb_vma *ev;
738 unsigned int pass;
739 int err = 0;
740
741 /*
742 * We have one more buffers that we couldn't bind, which could be due to
743 * various reasons. To resolve this we have 4 passes, with every next
744 * level turning the screws tighter:
745 *
746 * 0. Unbind all objects that do not match the GTT constraints for the
747 * execbuffer (fenceable, mappable, alignment etc). Bind all new
748 * objects. This avoids unnecessary unbinding of later objects in order
749 * to make room for the earlier objects *unless* we need to defragment.
750 *
751 * 1. Reorder the buffers, where objects with the most restrictive
752 * placement requirements go first (ignoring fixed location buffers for
753 * now). For example, objects needing the mappable aperture (the first
754 * 256M of GTT), should go first vs objects that can be placed just
755 * about anywhere. Repeat the previous pass.
756 *
757 * 2. Consider buffers that are pinned at a fixed location. Also try to
758 * evict the entire VM this time, leaving only objects that we were
759 * unable to lock. Try again to bind the buffers. (still using the new
760 * buffer order).
761 *
762 * 3. We likely have object lock contention for one or more stubborn
763 * objects in the VM, for which we need to evict to make forward
764 * progress (perhaps we are fighting the shrinker?). When evicting the
765 * VM this time around, anything that we can't lock we now track using
766 * the busy_bo, using the full lock (after dropping the vm->mutex to
767 * prevent deadlocks), instead of trylock. We then continue to evict the
768 * VM, this time with the stubborn object locked, which we can now
769 * hopefully unbind (if still bound in the VM). Repeat until the VM is
770 * evicted. Finally we should be able bind everything.
771 */
772 for (pass = 0; pass <= 3; pass++) {
773 int pin_flags = PIN_USER | PIN_VALIDATE;
774
775 if (pass == 0)
776 pin_flags |= PIN_NONBLOCK;
777
778 if (pass >= 1)
779 eb_unbind(eb, pass >= 2);
780
781 if (pass == 2) {
782 err = mutex_lock_interruptible(&eb->context->vm->mutex);
783 if (!err) {
784 err = i915_gem_evict_vm(eb->context->vm, &eb->ww, NULL);
785 mutex_unlock(&eb->context->vm->mutex);
786 }
787 if (err)
788 return err;
789 }
790
791 if (pass == 3) {
792 retry:
793 err = mutex_lock_interruptible(&eb->context->vm->mutex);
794 if (!err) {
795 struct drm_i915_gem_object *busy_bo = NULL;
796
797 err = i915_gem_evict_vm(eb->context->vm, &eb->ww, &busy_bo);
798 mutex_unlock(&eb->context->vm->mutex);
799 if (err && busy_bo) {
800 err = i915_gem_object_lock(busy_bo, &eb->ww);
801 i915_gem_object_put(busy_bo);
802 if (!err)
803 goto retry;
804 }
805 }
806 if (err)
807 return err;
808 }
809
810 list_for_each_entry(ev, &eb->unbound, bind_link) {
811 err = eb_reserve_vma(eb, ev, pin_flags);
812 if (err)
813 break;
814 }
815
816 if (err != -ENOSPC)
817 break;
818 }
819
820 return err;
821 }
822
eb_select_context(struct i915_execbuffer * eb)823 static int eb_select_context(struct i915_execbuffer *eb)
824 {
825 struct i915_gem_context *ctx;
826
827 ctx = i915_gem_context_lookup(eb->file->driver_priv, eb->args->rsvd1);
828 if (IS_ERR(ctx))
829 return PTR_ERR(ctx);
830
831 eb->gem_context = ctx;
832 if (i915_gem_context_has_full_ppgtt(ctx))
833 eb->invalid_flags |= EXEC_OBJECT_NEEDS_GTT;
834
835 return 0;
836 }
837
__eb_add_lut(struct i915_execbuffer * eb,u32 handle,struct i915_vma * vma)838 static int __eb_add_lut(struct i915_execbuffer *eb,
839 u32 handle, struct i915_vma *vma)
840 {
841 struct i915_gem_context *ctx = eb->gem_context;
842 struct i915_lut_handle *lut;
843 int err;
844
845 lut = i915_lut_handle_alloc();
846 if (unlikely(!lut))
847 return -ENOMEM;
848
849 i915_vma_get(vma);
850 if (!atomic_fetch_inc(&vma->open_count))
851 i915_vma_reopen(vma);
852 lut->handle = handle;
853 lut->ctx = ctx;
854
855 /* Check that the context hasn't been closed in the meantime */
856 err = -EINTR;
857 if (!mutex_lock_interruptible(&ctx->lut_mutex)) {
858 if (likely(!i915_gem_context_is_closed(ctx)))
859 err = radix_tree_insert(&ctx->handles_vma, handle, vma);
860 else
861 err = -ENOENT;
862 if (err == 0) { /* And nor has this handle */
863 struct drm_i915_gem_object *obj = vma->obj;
864
865 spin_lock(&obj->lut_lock);
866 if (idr_find(&eb->file->object_idr, handle) == obj) {
867 list_add(&lut->obj_link, &obj->lut_list);
868 } else {
869 radix_tree_delete(&ctx->handles_vma, handle);
870 err = -ENOENT;
871 }
872 spin_unlock(&obj->lut_lock);
873 }
874 mutex_unlock(&ctx->lut_mutex);
875 }
876 if (unlikely(err))
877 goto err;
878
879 return 0;
880
881 err:
882 i915_vma_close(vma);
883 i915_vma_put(vma);
884 i915_lut_handle_free(lut);
885 return err;
886 }
887
eb_lookup_vma(struct i915_execbuffer * eb,u32 handle)888 static struct i915_vma *eb_lookup_vma(struct i915_execbuffer *eb, u32 handle)
889 {
890 struct i915_address_space *vm = eb->context->vm;
891
892 do {
893 struct drm_i915_gem_object *obj;
894 struct i915_vma *vma;
895 int err;
896
897 rcu_read_lock();
898 vma = radix_tree_lookup(&eb->gem_context->handles_vma, handle);
899 if (likely(vma && vma->vm == vm))
900 vma = i915_vma_tryget(vma);
901 else
902 vma = NULL;
903 rcu_read_unlock();
904 if (likely(vma))
905 return vma;
906
907 obj = i915_gem_object_lookup(eb->file, handle);
908 if (unlikely(!obj))
909 return ERR_PTR(-ENOENT);
910
911 /*
912 * If the user has opted-in for protected-object tracking, make
913 * sure the object encryption can be used.
914 * We only need to do this when the object is first used with
915 * this context, because the context itself will be banned when
916 * the protected objects become invalid.
917 */
918 if (i915_gem_context_uses_protected_content(eb->gem_context) &&
919 i915_gem_object_is_protected(obj)) {
920 err = intel_pxp_key_check(intel_bo_to_drm_bo(obj), true);
921 if (err) {
922 i915_gem_object_put(obj);
923 return ERR_PTR(err);
924 }
925 }
926
927 vma = i915_vma_instance(obj, vm, NULL);
928 if (IS_ERR(vma)) {
929 i915_gem_object_put(obj);
930 return vma;
931 }
932
933 err = __eb_add_lut(eb, handle, vma);
934 if (likely(!err))
935 return vma;
936
937 i915_gem_object_put(obj);
938 if (err != -EEXIST)
939 return ERR_PTR(err);
940 } while (1);
941 }
942
eb_lookup_vmas(struct i915_execbuffer * eb)943 static int eb_lookup_vmas(struct i915_execbuffer *eb)
944 {
945 unsigned int i, current_batch = 0;
946 int err = 0;
947
948 INIT_LIST_HEAD(&eb->relocs);
949
950 for (i = 0; i < eb->buffer_count; i++) {
951 struct i915_vma *vma;
952
953 vma = eb_lookup_vma(eb, eb->exec[i].handle);
954 if (IS_ERR(vma)) {
955 err = PTR_ERR(vma);
956 return err;
957 }
958
959 err = eb_validate_vma(eb, &eb->exec[i], vma);
960 if (unlikely(err)) {
961 i915_vma_put(vma);
962 return err;
963 }
964
965 err = eb_add_vma(eb, ¤t_batch, i, vma);
966 if (err)
967 return err;
968
969 if (i915_gem_object_is_userptr(vma->obj)) {
970 err = i915_gem_object_userptr_submit_init(vma->obj);
971 if (err)
972 return err;
973
974 eb->vma[i].flags |= __EXEC_OBJECT_USERPTR_INIT;
975 eb->args->flags |= __EXEC_USERPTR_USED;
976 }
977 }
978
979 return 0;
980 }
981
eb_lock_vmas(struct i915_execbuffer * eb)982 static int eb_lock_vmas(struct i915_execbuffer *eb)
983 {
984 unsigned int i;
985 int err;
986
987 for (i = 0; i < eb->buffer_count; i++) {
988 struct eb_vma *ev = &eb->vma[i];
989 struct i915_vma *vma = ev->vma;
990
991 err = i915_gem_object_lock(vma->obj, &eb->ww);
992 if (err)
993 return err;
994 }
995
996 return 0;
997 }
998
eb_validate_vmas(struct i915_execbuffer * eb)999 static int eb_validate_vmas(struct i915_execbuffer *eb)
1000 {
1001 unsigned int i;
1002 int err;
1003
1004 INIT_LIST_HEAD(&eb->unbound);
1005
1006 err = eb_lock_vmas(eb);
1007 if (err)
1008 return err;
1009
1010 for (i = 0; i < eb->buffer_count; i++) {
1011 struct drm_i915_gem_exec_object2 *entry = &eb->exec[i];
1012 struct eb_vma *ev = &eb->vma[i];
1013 struct i915_vma *vma = ev->vma;
1014
1015 err = eb_pin_vma(eb, entry, ev);
1016 if (err == -EDEADLK)
1017 return err;
1018
1019 if (!err) {
1020 if (entry->offset != i915_vma_offset(vma)) {
1021 entry->offset = i915_vma_offset(vma) | UPDATE;
1022 eb->args->flags |= __EXEC_HAS_RELOC;
1023 }
1024 } else {
1025 eb_unreserve_vma(ev);
1026
1027 list_add_tail(&ev->bind_link, &eb->unbound);
1028 if (drm_mm_node_allocated(&vma->node)) {
1029 err = i915_vma_unbind(vma);
1030 if (err)
1031 return err;
1032 }
1033 }
1034
1035 /* Reserve enough slots to accommodate composite fences */
1036 err = dma_resv_reserve_fences(vma->obj->base.resv, eb->num_batches);
1037 if (err)
1038 return err;
1039
1040 GEM_BUG_ON(drm_mm_node_allocated(&vma->node) &&
1041 eb_vma_misplaced(&eb->exec[i], vma, ev->flags));
1042 }
1043
1044 if (!list_empty(&eb->unbound))
1045 return eb_reserve(eb);
1046
1047 return 0;
1048 }
1049
1050 static struct eb_vma *
eb_get_vma(const struct i915_execbuffer * eb,unsigned long handle)1051 eb_get_vma(const struct i915_execbuffer *eb, unsigned long handle)
1052 {
1053 if (eb->lut_size < 0) {
1054 if (handle >= -eb->lut_size)
1055 return NULL;
1056 return &eb->vma[handle];
1057 } else {
1058 struct hlist_head *head;
1059 struct eb_vma *ev;
1060
1061 head = &eb->buckets[hash_32(handle, eb->lut_size)];
1062 hlist_for_each_entry(ev, head, node) {
1063 if (ev->handle == handle)
1064 return ev;
1065 }
1066 return NULL;
1067 }
1068 }
1069
eb_release_vmas(struct i915_execbuffer * eb,bool final)1070 static void eb_release_vmas(struct i915_execbuffer *eb, bool final)
1071 {
1072 const unsigned int count = eb->buffer_count;
1073 unsigned int i;
1074
1075 for (i = 0; i < count; i++) {
1076 struct eb_vma *ev = &eb->vma[i];
1077 struct i915_vma *vma = ev->vma;
1078
1079 if (!vma)
1080 break;
1081
1082 eb_unreserve_vma(ev);
1083
1084 if (final)
1085 i915_vma_put(vma);
1086 }
1087
1088 eb_capture_release(eb);
1089 eb_unpin_engine(eb);
1090 }
1091
eb_destroy(const struct i915_execbuffer * eb)1092 static void eb_destroy(const struct i915_execbuffer *eb)
1093 {
1094 if (eb->lut_size > 0)
1095 kfree(eb->buckets);
1096 }
1097
1098 static u64
relocation_target(const struct drm_i915_gem_relocation_entry * reloc,const struct i915_vma * target)1099 relocation_target(const struct drm_i915_gem_relocation_entry *reloc,
1100 const struct i915_vma *target)
1101 {
1102 return gen8_canonical_addr((int)reloc->delta + i915_vma_offset(target));
1103 }
1104
reloc_cache_init(struct reloc_cache * cache,struct drm_i915_private * i915)1105 static void reloc_cache_init(struct reloc_cache *cache,
1106 struct drm_i915_private *i915)
1107 {
1108 cache->page = -1;
1109 cache->vaddr = 0;
1110 /* Must be a variable in the struct to allow GCC to unroll. */
1111 cache->graphics_ver = GRAPHICS_VER(i915);
1112 cache->has_llc = HAS_LLC(i915);
1113 cache->use_64bit_reloc = HAS_64BIT_RELOC(i915);
1114 cache->has_fence = cache->graphics_ver < 4;
1115 cache->needs_unfenced = INTEL_INFO(i915)->unfenced_needs_alignment;
1116 cache->node.flags = 0;
1117 }
1118
unmask_page(unsigned long p)1119 static void *unmask_page(unsigned long p)
1120 {
1121 return (void *)(uintptr_t)(p & PAGE_MASK);
1122 }
1123
unmask_flags(unsigned long p)1124 static unsigned int unmask_flags(unsigned long p)
1125 {
1126 return p & ~PAGE_MASK;
1127 }
1128
1129 #define KMAP 0x4 /* after CLFLUSH_FLAGS */
1130
cache_to_ggtt(struct reloc_cache * cache)1131 static struct i915_ggtt *cache_to_ggtt(struct reloc_cache *cache)
1132 {
1133 struct drm_i915_private *i915 =
1134 container_of(cache, struct i915_execbuffer, reloc_cache)->i915;
1135 return to_gt(i915)->ggtt;
1136 }
1137
reloc_cache_unmap(struct reloc_cache * cache)1138 static void reloc_cache_unmap(struct reloc_cache *cache)
1139 {
1140 void *vaddr;
1141
1142 if (!cache->vaddr)
1143 return;
1144
1145 vaddr = unmask_page(cache->vaddr);
1146 if (cache->vaddr & KMAP)
1147 kunmap_local(vaddr);
1148 else
1149 io_mapping_unmap_atomic((void __iomem *)vaddr);
1150 }
1151
reloc_cache_remap(struct reloc_cache * cache,struct drm_i915_gem_object * obj)1152 static void reloc_cache_remap(struct reloc_cache *cache,
1153 struct drm_i915_gem_object *obj)
1154 {
1155 void *vaddr;
1156
1157 if (!cache->vaddr)
1158 return;
1159
1160 if (cache->vaddr & KMAP) {
1161 struct page *page = i915_gem_object_get_page(obj, cache->page);
1162
1163 vaddr = kmap_local_page(page);
1164 cache->vaddr = unmask_flags(cache->vaddr) |
1165 (unsigned long)vaddr;
1166 } else {
1167 struct i915_ggtt *ggtt = cache_to_ggtt(cache);
1168 unsigned long offset;
1169
1170 offset = cache->node.start;
1171 if (!drm_mm_node_allocated(&cache->node))
1172 offset += cache->page << PAGE_SHIFT;
1173
1174 cache->vaddr = (unsigned long)
1175 io_mapping_map_atomic_wc(&ggtt->iomap, offset);
1176 }
1177 }
1178
reloc_cache_reset(struct reloc_cache * cache,struct i915_execbuffer * eb)1179 static void reloc_cache_reset(struct reloc_cache *cache, struct i915_execbuffer *eb)
1180 {
1181 void *vaddr;
1182
1183 if (!cache->vaddr)
1184 return;
1185
1186 vaddr = unmask_page(cache->vaddr);
1187 if (cache->vaddr & KMAP) {
1188 struct drm_i915_gem_object *obj =
1189 (struct drm_i915_gem_object *)cache->node.mm;
1190 if (cache->vaddr & CLFLUSH_AFTER)
1191 mb();
1192
1193 kunmap_local(vaddr);
1194 i915_gem_object_finish_access(obj);
1195 } else {
1196 struct i915_ggtt *ggtt = cache_to_ggtt(cache);
1197
1198 intel_gt_flush_ggtt_writes(ggtt->vm.gt);
1199 io_mapping_unmap_atomic((void __iomem *)vaddr);
1200
1201 if (drm_mm_node_allocated(&cache->node)) {
1202 ggtt->vm.clear_range(&ggtt->vm,
1203 cache->node.start,
1204 cache->node.size);
1205 mutex_lock(&ggtt->vm.mutex);
1206 drm_mm_remove_node(&cache->node);
1207 mutex_unlock(&ggtt->vm.mutex);
1208 } else {
1209 i915_vma_unpin((struct i915_vma *)cache->node.mm);
1210 }
1211 }
1212
1213 cache->vaddr = 0;
1214 cache->page = -1;
1215 }
1216
reloc_kmap(struct drm_i915_gem_object * obj,struct reloc_cache * cache,unsigned long pageno)1217 static void *reloc_kmap(struct drm_i915_gem_object *obj,
1218 struct reloc_cache *cache,
1219 unsigned long pageno)
1220 {
1221 void *vaddr;
1222 struct page *page;
1223
1224 if (cache->vaddr) {
1225 kunmap_local(unmask_page(cache->vaddr));
1226 } else {
1227 unsigned int flushes;
1228 int err;
1229
1230 err = i915_gem_object_prepare_write(obj, &flushes);
1231 if (err)
1232 return ERR_PTR(err);
1233
1234 BUILD_BUG_ON(KMAP & CLFLUSH_FLAGS);
1235 BUILD_BUG_ON((KMAP | CLFLUSH_FLAGS) & PAGE_MASK);
1236
1237 cache->vaddr = flushes | KMAP;
1238 cache->node.mm = (void *)obj;
1239 if (flushes)
1240 mb();
1241 }
1242
1243 page = i915_gem_object_get_page(obj, pageno);
1244 if (!obj->mm.dirty)
1245 set_page_dirty(page);
1246
1247 vaddr = kmap_local_page(page);
1248 cache->vaddr = unmask_flags(cache->vaddr) | (unsigned long)vaddr;
1249 cache->page = pageno;
1250
1251 return vaddr;
1252 }
1253
reloc_iomap(struct i915_vma * batch,struct i915_execbuffer * eb,unsigned long page)1254 static void *reloc_iomap(struct i915_vma *batch,
1255 struct i915_execbuffer *eb,
1256 unsigned long page)
1257 {
1258 struct drm_i915_gem_object *obj = batch->obj;
1259 struct reloc_cache *cache = &eb->reloc_cache;
1260 struct i915_ggtt *ggtt = cache_to_ggtt(cache);
1261 unsigned long offset;
1262 void *vaddr;
1263
1264 if (cache->vaddr) {
1265 intel_gt_flush_ggtt_writes(ggtt->vm.gt);
1266 io_mapping_unmap_atomic((void __force __iomem *) unmask_page(cache->vaddr));
1267 } else {
1268 struct i915_vma *vma = ERR_PTR(-ENODEV);
1269 int err;
1270
1271 if (i915_gem_object_is_tiled(obj))
1272 return ERR_PTR(-EINVAL);
1273
1274 if (use_cpu_reloc(cache, obj))
1275 return NULL;
1276
1277 err = i915_gem_object_set_to_gtt_domain(obj, true);
1278 if (err)
1279 return ERR_PTR(err);
1280
1281 /*
1282 * i915_gem_object_ggtt_pin_ww may attempt to remove the batch
1283 * VMA from the object list because we no longer pin.
1284 *
1285 * Only attempt to pin the batch buffer to ggtt if the current batch
1286 * is not inside ggtt, or the batch buffer is not misplaced.
1287 */
1288 if (!i915_is_ggtt(batch->vm) ||
1289 !i915_vma_misplaced(batch, 0, 0, PIN_MAPPABLE)) {
1290 vma = i915_gem_object_ggtt_pin_ww(obj, &eb->ww, NULL, 0, 0,
1291 PIN_MAPPABLE |
1292 PIN_NONBLOCK /* NOWARN */ |
1293 PIN_NOEVICT);
1294 }
1295
1296 if (vma == ERR_PTR(-EDEADLK))
1297 return vma;
1298
1299 if (IS_ERR(vma)) {
1300 memset(&cache->node, 0, sizeof(cache->node));
1301 mutex_lock(&ggtt->vm.mutex);
1302 err = drm_mm_insert_node_in_range
1303 (&ggtt->vm.mm, &cache->node,
1304 PAGE_SIZE, 0, I915_COLOR_UNEVICTABLE,
1305 0, ggtt->mappable_end,
1306 DRM_MM_INSERT_LOW);
1307 mutex_unlock(&ggtt->vm.mutex);
1308 if (err) /* no inactive aperture space, use cpu reloc */
1309 return NULL;
1310 } else {
1311 cache->node.start = i915_ggtt_offset(vma);
1312 cache->node.mm = (void *)vma;
1313 }
1314 }
1315
1316 offset = cache->node.start;
1317 if (drm_mm_node_allocated(&cache->node)) {
1318 ggtt->vm.insert_page(&ggtt->vm,
1319 i915_gem_object_get_dma_address(obj, page),
1320 offset,
1321 i915_gem_get_pat_index(ggtt->vm.i915,
1322 I915_CACHE_NONE),
1323 0);
1324 } else {
1325 offset += page << PAGE_SHIFT;
1326 }
1327
1328 vaddr = (void __force *)io_mapping_map_atomic_wc(&ggtt->iomap,
1329 offset);
1330 cache->page = page;
1331 cache->vaddr = (unsigned long)vaddr;
1332
1333 return vaddr;
1334 }
1335
reloc_vaddr(struct i915_vma * vma,struct i915_execbuffer * eb,unsigned long page)1336 static void *reloc_vaddr(struct i915_vma *vma,
1337 struct i915_execbuffer *eb,
1338 unsigned long page)
1339 {
1340 struct reloc_cache *cache = &eb->reloc_cache;
1341 void *vaddr;
1342
1343 if (cache->page == page) {
1344 vaddr = unmask_page(cache->vaddr);
1345 } else {
1346 vaddr = NULL;
1347 if ((cache->vaddr & KMAP) == 0)
1348 vaddr = reloc_iomap(vma, eb, page);
1349 if (!vaddr)
1350 vaddr = reloc_kmap(vma->obj, cache, page);
1351 }
1352
1353 return vaddr;
1354 }
1355
clflush_write32(u32 * addr,u32 value,unsigned int flushes)1356 static void clflush_write32(u32 *addr, u32 value, unsigned int flushes)
1357 {
1358 if (unlikely(flushes & (CLFLUSH_BEFORE | CLFLUSH_AFTER))) {
1359 if (flushes & CLFLUSH_BEFORE)
1360 drm_clflush_virt_range(addr, sizeof(*addr));
1361
1362 *addr = value;
1363
1364 /*
1365 * Writes to the same cacheline are serialised by the CPU
1366 * (including clflush). On the write path, we only require
1367 * that it hits memory in an orderly fashion and place
1368 * mb barriers at the start and end of the relocation phase
1369 * to ensure ordering of clflush wrt to the system.
1370 */
1371 if (flushes & CLFLUSH_AFTER)
1372 drm_clflush_virt_range(addr, sizeof(*addr));
1373 } else {
1374 *addr = value;
1375 }
1376 }
1377
1378 static u64
relocate_entry(struct i915_vma * vma,const struct drm_i915_gem_relocation_entry * reloc,struct i915_execbuffer * eb,const struct i915_vma * target)1379 relocate_entry(struct i915_vma *vma,
1380 const struct drm_i915_gem_relocation_entry *reloc,
1381 struct i915_execbuffer *eb,
1382 const struct i915_vma *target)
1383 {
1384 u64 target_addr = relocation_target(reloc, target);
1385 u64 offset = reloc->offset;
1386 bool wide = eb->reloc_cache.use_64bit_reloc;
1387 void *vaddr;
1388
1389 repeat:
1390 vaddr = reloc_vaddr(vma, eb,
1391 offset >> PAGE_SHIFT);
1392 if (IS_ERR(vaddr))
1393 return PTR_ERR(vaddr);
1394
1395 GEM_BUG_ON(!IS_ALIGNED(offset, sizeof(u32)));
1396 clflush_write32(vaddr + offset_in_page(offset),
1397 lower_32_bits(target_addr),
1398 eb->reloc_cache.vaddr);
1399
1400 if (wide) {
1401 offset += sizeof(u32);
1402 target_addr >>= 32;
1403 wide = false;
1404 goto repeat;
1405 }
1406
1407 return target->node.start | UPDATE;
1408 }
1409
1410 static u64
eb_relocate_entry(struct i915_execbuffer * eb,struct eb_vma * ev,const struct drm_i915_gem_relocation_entry * reloc)1411 eb_relocate_entry(struct i915_execbuffer *eb,
1412 struct eb_vma *ev,
1413 const struct drm_i915_gem_relocation_entry *reloc)
1414 {
1415 struct drm_i915_private *i915 = eb->i915;
1416 struct eb_vma *target;
1417 int err;
1418
1419 /* we've already hold a reference to all valid objects */
1420 target = eb_get_vma(eb, reloc->target_handle);
1421 if (unlikely(!target))
1422 return -ENOENT;
1423
1424 /* Validate that the target is in a valid r/w GPU domain */
1425 if (unlikely(reloc->write_domain & (reloc->write_domain - 1))) {
1426 drm_dbg(&i915->drm, "reloc with multiple write domains: "
1427 "target %d offset %d "
1428 "read %08x write %08x\n",
1429 reloc->target_handle,
1430 (int) reloc->offset,
1431 reloc->read_domains,
1432 reloc->write_domain);
1433 return -EINVAL;
1434 }
1435 if (unlikely((reloc->write_domain | reloc->read_domains)
1436 & ~I915_GEM_GPU_DOMAINS)) {
1437 drm_dbg(&i915->drm, "reloc with read/write non-GPU domains: "
1438 "target %d offset %d "
1439 "read %08x write %08x\n",
1440 reloc->target_handle,
1441 (int) reloc->offset,
1442 reloc->read_domains,
1443 reloc->write_domain);
1444 return -EINVAL;
1445 }
1446
1447 if (reloc->write_domain) {
1448 target->flags |= EXEC_OBJECT_WRITE;
1449
1450 /*
1451 * Sandybridge PPGTT errata: We need a global gtt mapping
1452 * for MI and pipe_control writes because the gpu doesn't
1453 * properly redirect them through the ppgtt for non_secure
1454 * batchbuffers.
1455 */
1456 if (reloc->write_domain == I915_GEM_DOMAIN_INSTRUCTION &&
1457 GRAPHICS_VER(eb->i915) == 6 &&
1458 !i915_vma_is_bound(target->vma, I915_VMA_GLOBAL_BIND)) {
1459 struct i915_vma *vma = target->vma;
1460
1461 reloc_cache_unmap(&eb->reloc_cache);
1462 mutex_lock(&vma->vm->mutex);
1463 err = i915_vma_bind(target->vma,
1464 target->vma->obj->pat_index,
1465 PIN_GLOBAL, NULL, NULL);
1466 mutex_unlock(&vma->vm->mutex);
1467 reloc_cache_remap(&eb->reloc_cache, ev->vma->obj);
1468 if (err)
1469 return err;
1470 }
1471 }
1472
1473 /*
1474 * If the relocation already has the right value in it, no
1475 * more work needs to be done.
1476 */
1477 if (!DBG_FORCE_RELOC &&
1478 gen8_canonical_addr(i915_vma_offset(target->vma)) == reloc->presumed_offset)
1479 return 0;
1480
1481 /* Check that the relocation address is valid... */
1482 if (unlikely(reloc->offset >
1483 ev->vma->size - (eb->reloc_cache.use_64bit_reloc ? 8 : 4))) {
1484 drm_dbg(&i915->drm, "Relocation beyond object bounds: "
1485 "target %d offset %d size %d.\n",
1486 reloc->target_handle,
1487 (int)reloc->offset,
1488 (int)ev->vma->size);
1489 return -EINVAL;
1490 }
1491 if (unlikely(reloc->offset & 3)) {
1492 drm_dbg(&i915->drm, "Relocation not 4-byte aligned: "
1493 "target %d offset %d.\n",
1494 reloc->target_handle,
1495 (int)reloc->offset);
1496 return -EINVAL;
1497 }
1498
1499 /*
1500 * If we write into the object, we need to force the synchronisation
1501 * barrier, either with an asynchronous clflush or if we executed the
1502 * patching using the GPU (though that should be serialised by the
1503 * timeline). To be completely sure, and since we are required to
1504 * do relocations we are already stalling, disable the user's opt
1505 * out of our synchronisation.
1506 */
1507 ev->flags &= ~EXEC_OBJECT_ASYNC;
1508
1509 /* and update the user's relocation entry */
1510 return relocate_entry(ev->vma, reloc, eb, target->vma);
1511 }
1512
eb_relocate_vma(struct i915_execbuffer * eb,struct eb_vma * ev)1513 static int eb_relocate_vma(struct i915_execbuffer *eb, struct eb_vma *ev)
1514 {
1515 #define N_RELOC(x) ((x) / sizeof(struct drm_i915_gem_relocation_entry))
1516 struct drm_i915_gem_relocation_entry stack[N_RELOC(512)];
1517 const struct drm_i915_gem_exec_object2 *entry = ev->exec;
1518 struct drm_i915_gem_relocation_entry __user *urelocs =
1519 u64_to_user_ptr(entry->relocs_ptr);
1520 unsigned long remain = entry->relocation_count;
1521
1522 if (unlikely(remain > N_RELOC(INT_MAX)))
1523 return -EINVAL;
1524
1525 /*
1526 * We must check that the entire relocation array is safe
1527 * to read. However, if the array is not writable the user loses
1528 * the updated relocation values.
1529 */
1530 if (unlikely(!access_ok(urelocs, remain * sizeof(*urelocs))))
1531 return -EFAULT;
1532
1533 do {
1534 struct drm_i915_gem_relocation_entry *r = stack;
1535 unsigned int count =
1536 min_t(unsigned long, remain, ARRAY_SIZE(stack));
1537 unsigned int copied;
1538
1539 /*
1540 * This is the fast path and we cannot handle a pagefault
1541 * whilst holding the struct mutex lest the user pass in the
1542 * relocations contained within a mmaped bo. For in such a case
1543 * we, the page fault handler would call i915_gem_fault() and
1544 * we would try to acquire the struct mutex again. Obviously
1545 * this is bad and so lockdep complains vehemently.
1546 */
1547 pagefault_disable();
1548 copied = __copy_from_user_inatomic(r, urelocs, count * sizeof(r[0]));
1549 pagefault_enable();
1550 if (unlikely(copied)) {
1551 remain = -EFAULT;
1552 goto out;
1553 }
1554
1555 remain -= count;
1556 do {
1557 u64 offset = eb_relocate_entry(eb, ev, r);
1558
1559 if (likely(offset == 0))
1560 continue;
1561
1562 if ((s64)offset < 0) {
1563 remain = (int)offset;
1564 goto out;
1565 }
1566 /*
1567 * Note that reporting an error now
1568 * leaves everything in an inconsistent
1569 * state as we have *already* changed
1570 * the relocation value inside the
1571 * object. As we have not changed the
1572 * reloc.presumed_offset or will not
1573 * change the execobject.offset, on the
1574 * call we may not rewrite the value
1575 * inside the object, leaving it
1576 * dangling and causing a GPU hang. Unless
1577 * userspace dynamically rebuilds the
1578 * relocations on each execbuf rather than
1579 * presume a static tree.
1580 *
1581 * We did previously check if the relocations
1582 * were writable (access_ok), an error now
1583 * would be a strange race with mprotect,
1584 * having already demonstrated that we
1585 * can read from this userspace address.
1586 */
1587 offset = gen8_canonical_addr(offset & ~UPDATE);
1588 __put_user(offset, &urelocs[r - stack].presumed_offset);
1589 } while (r++, --count);
1590 urelocs += ARRAY_SIZE(stack);
1591 } while (remain);
1592 out:
1593 reloc_cache_reset(&eb->reloc_cache, eb);
1594 return remain;
1595 }
1596
1597 static int
eb_relocate_vma_slow(struct i915_execbuffer * eb,struct eb_vma * ev)1598 eb_relocate_vma_slow(struct i915_execbuffer *eb, struct eb_vma *ev)
1599 {
1600 const struct drm_i915_gem_exec_object2 *entry = ev->exec;
1601 struct drm_i915_gem_relocation_entry *relocs =
1602 u64_to_ptr(typeof(*relocs), entry->relocs_ptr);
1603 unsigned int i;
1604 int err;
1605
1606 for (i = 0; i < entry->relocation_count; i++) {
1607 u64 offset = eb_relocate_entry(eb, ev, &relocs[i]);
1608
1609 if ((s64)offset < 0) {
1610 err = (int)offset;
1611 goto err;
1612 }
1613 }
1614 err = 0;
1615 err:
1616 reloc_cache_reset(&eb->reloc_cache, eb);
1617 return err;
1618 }
1619
check_relocations(const struct drm_i915_gem_exec_object2 * entry)1620 static int check_relocations(const struct drm_i915_gem_exec_object2 *entry)
1621 {
1622 const char __user *addr, *end;
1623 unsigned long size;
1624 char __maybe_unused c;
1625
1626 size = entry->relocation_count;
1627 if (size == 0)
1628 return 0;
1629
1630 if (size > N_RELOC(INT_MAX))
1631 return -EINVAL;
1632
1633 addr = u64_to_user_ptr(entry->relocs_ptr);
1634 size *= sizeof(struct drm_i915_gem_relocation_entry);
1635 if (!access_ok(addr, size))
1636 return -EFAULT;
1637
1638 end = addr + size;
1639 for (; addr < end; addr += PAGE_SIZE) {
1640 int err = __get_user(c, addr);
1641 if (err)
1642 return err;
1643 }
1644 return __get_user(c, end - 1);
1645 }
1646
eb_copy_relocations(const struct i915_execbuffer * eb)1647 static int eb_copy_relocations(const struct i915_execbuffer *eb)
1648 {
1649 struct drm_i915_gem_relocation_entry *relocs;
1650 const unsigned int count = eb->buffer_count;
1651 unsigned int i;
1652 int err;
1653
1654 for (i = 0; i < count; i++) {
1655 const unsigned int nreloc = eb->exec[i].relocation_count;
1656 struct drm_i915_gem_relocation_entry __user *urelocs;
1657 unsigned long size;
1658 unsigned long copied;
1659
1660 if (nreloc == 0)
1661 continue;
1662
1663 err = check_relocations(&eb->exec[i]);
1664 if (err)
1665 goto err;
1666
1667 urelocs = u64_to_user_ptr(eb->exec[i].relocs_ptr);
1668 size = nreloc * sizeof(*relocs);
1669
1670 relocs = kvmalloc_array(1, size, GFP_KERNEL);
1671 if (!relocs) {
1672 err = -ENOMEM;
1673 goto err;
1674 }
1675
1676 /* copy_from_user is limited to < 4GiB */
1677 copied = 0;
1678 do {
1679 unsigned int len =
1680 min_t(u64, BIT_ULL(31), size - copied);
1681
1682 if (__copy_from_user((char *)relocs + copied,
1683 (char __user *)urelocs + copied,
1684 len))
1685 goto end;
1686
1687 copied += len;
1688 } while (copied < size);
1689
1690 /*
1691 * As we do not update the known relocation offsets after
1692 * relocating (due to the complexities in lock handling),
1693 * we need to mark them as invalid now so that we force the
1694 * relocation processing next time. Just in case the target
1695 * object is evicted and then rebound into its old
1696 * presumed_offset before the next execbuffer - if that
1697 * happened we would make the mistake of assuming that the
1698 * relocations were valid.
1699 */
1700 if (!user_access_begin(urelocs, size))
1701 goto end;
1702
1703 for (copied = 0; copied < nreloc; copied++)
1704 unsafe_put_user(-1,
1705 &urelocs[copied].presumed_offset,
1706 end_user);
1707 user_access_end();
1708
1709 eb->exec[i].relocs_ptr = (uintptr_t)relocs;
1710 }
1711
1712 return 0;
1713
1714 end_user:
1715 user_access_end();
1716 end:
1717 kvfree(relocs);
1718 err = -EFAULT;
1719 err:
1720 while (i--) {
1721 relocs = u64_to_ptr(typeof(*relocs), eb->exec[i].relocs_ptr);
1722 if (eb->exec[i].relocation_count)
1723 kvfree(relocs);
1724 }
1725 return err;
1726 }
1727
eb_prefault_relocations(const struct i915_execbuffer * eb)1728 static int eb_prefault_relocations(const struct i915_execbuffer *eb)
1729 {
1730 const unsigned int count = eb->buffer_count;
1731 unsigned int i;
1732
1733 for (i = 0; i < count; i++) {
1734 int err;
1735
1736 err = check_relocations(&eb->exec[i]);
1737 if (err)
1738 return err;
1739 }
1740
1741 return 0;
1742 }
1743
eb_reinit_userptr(struct i915_execbuffer * eb)1744 static int eb_reinit_userptr(struct i915_execbuffer *eb)
1745 {
1746 const unsigned int count = eb->buffer_count;
1747 unsigned int i;
1748 int ret;
1749
1750 if (likely(!(eb->args->flags & __EXEC_USERPTR_USED)))
1751 return 0;
1752
1753 for (i = 0; i < count; i++) {
1754 struct eb_vma *ev = &eb->vma[i];
1755
1756 if (!i915_gem_object_is_userptr(ev->vma->obj))
1757 continue;
1758
1759 ret = i915_gem_object_userptr_submit_init(ev->vma->obj);
1760 if (ret)
1761 return ret;
1762
1763 ev->flags |= __EXEC_OBJECT_USERPTR_INIT;
1764 }
1765
1766 return 0;
1767 }
1768
eb_relocate_parse_slow(struct i915_execbuffer * eb)1769 static noinline int eb_relocate_parse_slow(struct i915_execbuffer *eb)
1770 {
1771 bool have_copy = false;
1772 struct eb_vma *ev;
1773 int err = 0;
1774
1775 repeat:
1776 if (signal_pending(current)) {
1777 err = -ERESTARTSYS;
1778 goto out;
1779 }
1780
1781 /* We may process another execbuffer during the unlock... */
1782 eb_release_vmas(eb, false);
1783 i915_gem_ww_ctx_fini(&eb->ww);
1784
1785 /*
1786 * We take 3 passes through the slowpatch.
1787 *
1788 * 1 - we try to just prefault all the user relocation entries and
1789 * then attempt to reuse the atomic pagefault disabled fast path again.
1790 *
1791 * 2 - we copy the user entries to a local buffer here outside of the
1792 * local and allow ourselves to wait upon any rendering before
1793 * relocations
1794 *
1795 * 3 - we already have a local copy of the relocation entries, but
1796 * were interrupted (EAGAIN) whilst waiting for the objects, try again.
1797 */
1798 if (!err) {
1799 err = eb_prefault_relocations(eb);
1800 } else if (!have_copy) {
1801 err = eb_copy_relocations(eb);
1802 have_copy = err == 0;
1803 } else {
1804 cond_resched();
1805 err = 0;
1806 }
1807
1808 if (!err)
1809 err = eb_reinit_userptr(eb);
1810
1811 i915_gem_ww_ctx_init(&eb->ww, true);
1812 if (err)
1813 goto out;
1814
1815 /* reacquire the objects */
1816 repeat_validate:
1817 err = eb_pin_engine(eb, false);
1818 if (err)
1819 goto err;
1820
1821 err = eb_validate_vmas(eb);
1822 if (err)
1823 goto err;
1824
1825 GEM_BUG_ON(!eb->batches[0]);
1826
1827 list_for_each_entry(ev, &eb->relocs, reloc_link) {
1828 if (!have_copy) {
1829 err = eb_relocate_vma(eb, ev);
1830 if (err)
1831 break;
1832 } else {
1833 err = eb_relocate_vma_slow(eb, ev);
1834 if (err)
1835 break;
1836 }
1837 }
1838
1839 if (err == -EDEADLK)
1840 goto err;
1841
1842 if (err && !have_copy)
1843 goto repeat;
1844
1845 if (err)
1846 goto err;
1847
1848 /* as last step, parse the command buffer */
1849 err = eb_parse(eb);
1850 if (err)
1851 goto err;
1852
1853 /*
1854 * Leave the user relocations as are, this is the painfully slow path,
1855 * and we want to avoid the complication of dropping the lock whilst
1856 * having buffers reserved in the aperture and so causing spurious
1857 * ENOSPC for random operations.
1858 */
1859
1860 err:
1861 if (err == -EDEADLK) {
1862 eb_release_vmas(eb, false);
1863 err = i915_gem_ww_ctx_backoff(&eb->ww);
1864 if (!err)
1865 goto repeat_validate;
1866 }
1867
1868 if (err == -EAGAIN)
1869 goto repeat;
1870
1871 out:
1872 if (have_copy) {
1873 const unsigned int count = eb->buffer_count;
1874 unsigned int i;
1875
1876 for (i = 0; i < count; i++) {
1877 const struct drm_i915_gem_exec_object2 *entry =
1878 &eb->exec[i];
1879 struct drm_i915_gem_relocation_entry *relocs;
1880
1881 if (!entry->relocation_count)
1882 continue;
1883
1884 relocs = u64_to_ptr(typeof(*relocs), entry->relocs_ptr);
1885 kvfree(relocs);
1886 }
1887 }
1888
1889 return err;
1890 }
1891
eb_relocate_parse(struct i915_execbuffer * eb)1892 static int eb_relocate_parse(struct i915_execbuffer *eb)
1893 {
1894 int err;
1895 bool throttle = true;
1896
1897 retry:
1898 err = eb_pin_engine(eb, throttle);
1899 if (err) {
1900 if (err != -EDEADLK)
1901 return err;
1902
1903 goto err;
1904 }
1905
1906 /* only throttle once, even if we didn't need to throttle */
1907 throttle = false;
1908
1909 err = eb_validate_vmas(eb);
1910 if (err == -EAGAIN)
1911 goto slow;
1912 else if (err)
1913 goto err;
1914
1915 /* The objects are in their final locations, apply the relocations. */
1916 if (eb->args->flags & __EXEC_HAS_RELOC) {
1917 struct eb_vma *ev;
1918
1919 list_for_each_entry(ev, &eb->relocs, reloc_link) {
1920 err = eb_relocate_vma(eb, ev);
1921 if (err)
1922 break;
1923 }
1924
1925 if (err == -EDEADLK)
1926 goto err;
1927 else if (err)
1928 goto slow;
1929 }
1930
1931 if (!err)
1932 err = eb_parse(eb);
1933
1934 err:
1935 if (err == -EDEADLK) {
1936 eb_release_vmas(eb, false);
1937 err = i915_gem_ww_ctx_backoff(&eb->ww);
1938 if (!err)
1939 goto retry;
1940 }
1941
1942 return err;
1943
1944 slow:
1945 err = eb_relocate_parse_slow(eb);
1946 if (err)
1947 /*
1948 * If the user expects the execobject.offset and
1949 * reloc.presumed_offset to be an exact match,
1950 * as for using NO_RELOC, then we cannot update
1951 * the execobject.offset until we have completed
1952 * relocation.
1953 */
1954 eb->args->flags &= ~__EXEC_HAS_RELOC;
1955
1956 return err;
1957 }
1958
1959 /*
1960 * Using two helper loops for the order of which requests / batches are created
1961 * and added the to backend. Requests are created in order from the parent to
1962 * the last child. Requests are added in the reverse order, from the last child
1963 * to parent. This is done for locking reasons as the timeline lock is acquired
1964 * during request creation and released when the request is added to the
1965 * backend. To make lockdep happy (see intel_context_timeline_lock) this must be
1966 * the ordering.
1967 */
1968 #define for_each_batch_create_order(_eb, _i) \
1969 for ((_i) = 0; (_i) < (_eb)->num_batches; ++(_i))
1970 #define for_each_batch_add_order(_eb, _i) \
1971 BUILD_BUG_ON(!typecheck(int, _i)); \
1972 for ((_i) = (_eb)->num_batches - 1; (_i) >= 0; --(_i))
1973
1974 static struct i915_request *
eb_find_first_request_added(struct i915_execbuffer * eb)1975 eb_find_first_request_added(struct i915_execbuffer *eb)
1976 {
1977 int i;
1978
1979 for_each_batch_add_order(eb, i)
1980 if (eb->requests[i])
1981 return eb->requests[i];
1982
1983 GEM_BUG_ON("Request not found");
1984
1985 return NULL;
1986 }
1987
1988 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
1989
1990 /* Stage with GFP_KERNEL allocations before we enter the signaling critical path */
eb_capture_stage(struct i915_execbuffer * eb)1991 static int eb_capture_stage(struct i915_execbuffer *eb)
1992 {
1993 const unsigned int count = eb->buffer_count;
1994 unsigned int i = count, j;
1995
1996 while (i--) {
1997 struct eb_vma *ev = &eb->vma[i];
1998 struct i915_vma *vma = ev->vma;
1999 unsigned int flags = ev->flags;
2000
2001 if (!(flags & EXEC_OBJECT_CAPTURE))
2002 continue;
2003
2004 if (i915_gem_context_is_recoverable(eb->gem_context) &&
2005 (IS_DGFX(eb->i915) || GRAPHICS_VER_FULL(eb->i915) > IP_VER(12, 0)))
2006 return -EINVAL;
2007
2008 for_each_batch_create_order(eb, j) {
2009 struct i915_capture_list *capture;
2010
2011 capture = kmalloc_obj(*capture);
2012 if (!capture)
2013 continue;
2014
2015 capture->next = eb->capture_lists[j];
2016 capture->vma_res = i915_vma_resource_get(vma->resource);
2017 eb->capture_lists[j] = capture;
2018 }
2019 }
2020
2021 return 0;
2022 }
2023
2024 /* Commit once we're in the critical path */
eb_capture_commit(struct i915_execbuffer * eb)2025 static void eb_capture_commit(struct i915_execbuffer *eb)
2026 {
2027 unsigned int j;
2028
2029 for_each_batch_create_order(eb, j) {
2030 struct i915_request *rq = eb->requests[j];
2031
2032 if (!rq)
2033 break;
2034
2035 rq->capture_list = eb->capture_lists[j];
2036 eb->capture_lists[j] = NULL;
2037 }
2038 }
2039
2040 /*
2041 * Release anything that didn't get committed due to errors.
2042 * The capture_list will otherwise be freed at request retire.
2043 */
eb_capture_release(struct i915_execbuffer * eb)2044 static void eb_capture_release(struct i915_execbuffer *eb)
2045 {
2046 unsigned int j;
2047
2048 for_each_batch_create_order(eb, j) {
2049 if (eb->capture_lists[j]) {
2050 i915_request_free_capture_list(eb->capture_lists[j]);
2051 eb->capture_lists[j] = NULL;
2052 }
2053 }
2054 }
2055
eb_capture_list_clear(struct i915_execbuffer * eb)2056 static void eb_capture_list_clear(struct i915_execbuffer *eb)
2057 {
2058 memset(eb->capture_lists, 0, sizeof(eb->capture_lists));
2059 }
2060
2061 #else
2062
eb_capture_stage(struct i915_execbuffer * eb)2063 static int eb_capture_stage(struct i915_execbuffer *eb)
2064 {
2065 return 0;
2066 }
2067
eb_capture_commit(struct i915_execbuffer * eb)2068 static void eb_capture_commit(struct i915_execbuffer *eb)
2069 {
2070 }
2071
eb_capture_release(struct i915_execbuffer * eb)2072 static void eb_capture_release(struct i915_execbuffer *eb)
2073 {
2074 }
2075
eb_capture_list_clear(struct i915_execbuffer * eb)2076 static void eb_capture_list_clear(struct i915_execbuffer *eb)
2077 {
2078 }
2079
2080 #endif
2081
eb_move_to_gpu(struct i915_execbuffer * eb)2082 static int eb_move_to_gpu(struct i915_execbuffer *eb)
2083 {
2084 const unsigned int count = eb->buffer_count;
2085 unsigned int i = count;
2086 int err = 0, j;
2087
2088 while (i--) {
2089 struct eb_vma *ev = &eb->vma[i];
2090 struct i915_vma *vma = ev->vma;
2091 unsigned int flags = ev->flags;
2092 struct drm_i915_gem_object *obj = vma->obj;
2093
2094 assert_vma_held(vma);
2095
2096 /*
2097 * If the GPU is not _reading_ through the CPU cache, we need
2098 * to make sure that any writes (both previous GPU writes from
2099 * before a change in snooping levels and normal CPU writes)
2100 * caught in that cache are flushed to main memory.
2101 *
2102 * We want to say
2103 * obj->cache_dirty &&
2104 * !(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ)
2105 * but gcc's optimiser doesn't handle that as well and emits
2106 * two jumps instead of one. Maybe one day...
2107 *
2108 * FIXME: There is also sync flushing in set_pages(), which
2109 * serves a different purpose(some of the time at least).
2110 *
2111 * We should consider:
2112 *
2113 * 1. Rip out the async flush code.
2114 *
2115 * 2. Or make the sync flushing use the async clflush path
2116 * using mandatory fences underneath. Currently the below
2117 * async flush happens after we bind the object.
2118 */
2119 if (unlikely(obj->cache_dirty & ~obj->cache_coherent)) {
2120 if (i915_gem_clflush_object(obj, 0))
2121 flags &= ~EXEC_OBJECT_ASYNC;
2122 }
2123
2124 /* We only need to await on the first request */
2125 if (err == 0 && !(flags & EXEC_OBJECT_ASYNC)) {
2126 err = i915_request_await_object
2127 (eb_find_first_request_added(eb), obj,
2128 flags & EXEC_OBJECT_WRITE);
2129 }
2130
2131 for_each_batch_add_order(eb, j) {
2132 if (err)
2133 break;
2134 if (!eb->requests[j])
2135 continue;
2136
2137 err = _i915_vma_move_to_active(vma, eb->requests[j],
2138 j ? NULL :
2139 eb->composite_fence ?
2140 eb->composite_fence :
2141 &eb->requests[j]->fence,
2142 flags | __EXEC_OBJECT_NO_RESERVE |
2143 __EXEC_OBJECT_NO_REQUEST_AWAIT);
2144 }
2145 }
2146
2147 #ifdef CONFIG_MMU_NOTIFIER
2148 if (!err && (eb->args->flags & __EXEC_USERPTR_USED)) {
2149 for (i = 0; i < count; i++) {
2150 struct eb_vma *ev = &eb->vma[i];
2151 struct drm_i915_gem_object *obj = ev->vma->obj;
2152
2153 if (!i915_gem_object_is_userptr(obj))
2154 continue;
2155
2156 err = i915_gem_object_userptr_submit_done(obj);
2157 if (err)
2158 break;
2159 }
2160 }
2161 #endif
2162
2163 if (unlikely(err))
2164 goto err_skip;
2165
2166 /* Unconditionally flush any chipset caches (for streaming writes). */
2167 intel_gt_chipset_flush(eb->gt);
2168 eb_capture_commit(eb);
2169
2170 return 0;
2171
2172 err_skip:
2173 for_each_batch_create_order(eb, j) {
2174 if (!eb->requests[j])
2175 break;
2176
2177 i915_request_set_error_once(eb->requests[j], err);
2178 }
2179 return err;
2180 }
2181
i915_gem_check_execbuffer(struct drm_i915_private * i915,struct drm_i915_gem_execbuffer2 * exec)2182 static int i915_gem_check_execbuffer(struct drm_i915_private *i915,
2183 struct drm_i915_gem_execbuffer2 *exec)
2184 {
2185 if (exec->flags & __I915_EXEC_ILLEGAL_FLAGS)
2186 return -EINVAL;
2187
2188 /* Kernel clipping was a DRI1 misfeature */
2189 if (!(exec->flags & (I915_EXEC_FENCE_ARRAY |
2190 I915_EXEC_USE_EXTENSIONS))) {
2191 if (exec->num_cliprects || exec->cliprects_ptr)
2192 return -EINVAL;
2193 }
2194
2195 if (exec->DR4 == 0xffffffff) {
2196 drm_dbg(&i915->drm, "UXA submitting garbage DR4, fixing up\n");
2197 exec->DR4 = 0;
2198 }
2199 if (exec->DR1 || exec->DR4)
2200 return -EINVAL;
2201
2202 if ((exec->batch_start_offset | exec->batch_len) & 0x7)
2203 return -EINVAL;
2204
2205 return 0;
2206 }
2207
i915_reset_gen7_sol_offsets(struct i915_request * rq)2208 static int i915_reset_gen7_sol_offsets(struct i915_request *rq)
2209 {
2210 u32 *cs;
2211 int i;
2212
2213 if (GRAPHICS_VER(rq->i915) != 7 || rq->engine->id != RCS0) {
2214 drm_dbg(&rq->i915->drm, "sol reset is gen7/rcs only\n");
2215 return -EINVAL;
2216 }
2217
2218 cs = intel_ring_begin(rq, 4 * 2 + 2);
2219 if (IS_ERR(cs))
2220 return PTR_ERR(cs);
2221
2222 *cs++ = MI_LOAD_REGISTER_IMM(4);
2223 for (i = 0; i < 4; i++) {
2224 *cs++ = i915_mmio_reg_offset(GEN7_SO_WRITE_OFFSET(i));
2225 *cs++ = 0;
2226 }
2227 *cs++ = MI_NOOP;
2228 intel_ring_advance(rq, cs);
2229
2230 return 0;
2231 }
2232
2233 static struct i915_vma *
shadow_batch_pin(struct i915_execbuffer * eb,struct drm_i915_gem_object * obj,struct i915_address_space * vm,unsigned int flags)2234 shadow_batch_pin(struct i915_execbuffer *eb,
2235 struct drm_i915_gem_object *obj,
2236 struct i915_address_space *vm,
2237 unsigned int flags)
2238 {
2239 struct i915_vma *vma;
2240 int err;
2241
2242 vma = i915_vma_instance(obj, vm, NULL);
2243 if (IS_ERR(vma))
2244 return vma;
2245
2246 err = i915_vma_pin_ww(vma, &eb->ww, 0, 0, flags | PIN_VALIDATE);
2247 if (err)
2248 return ERR_PTR(err);
2249
2250 return vma;
2251 }
2252
eb_dispatch_secure(struct i915_execbuffer * eb,struct i915_vma * vma)2253 static struct i915_vma *eb_dispatch_secure(struct i915_execbuffer *eb, struct i915_vma *vma)
2254 {
2255 /*
2256 * snb/ivb/vlv conflate the "batch in ppgtt" bit with the "non-secure
2257 * batch" bit. Hence we need to pin secure batches into the global gtt.
2258 * hsw should have this fixed, but bdw mucks it up again. */
2259 if (eb->batch_flags & I915_DISPATCH_SECURE)
2260 return i915_gem_object_ggtt_pin_ww(vma->obj, &eb->ww, NULL, 0, 0, PIN_VALIDATE);
2261
2262 return NULL;
2263 }
2264
eb_parse(struct i915_execbuffer * eb)2265 static int eb_parse(struct i915_execbuffer *eb)
2266 {
2267 struct drm_i915_private *i915 = eb->i915;
2268 struct intel_gt_buffer_pool_node *pool = eb->batch_pool;
2269 struct i915_vma *shadow, *trampoline, *batch;
2270 unsigned long len;
2271 int err;
2272
2273 if (!eb_use_cmdparser(eb)) {
2274 batch = eb_dispatch_secure(eb, eb->batches[0]->vma);
2275 if (IS_ERR(batch))
2276 return PTR_ERR(batch);
2277
2278 goto secure_batch;
2279 }
2280
2281 if (intel_context_is_parallel(eb->context))
2282 return -EINVAL;
2283
2284 len = eb->batch_len[0];
2285 if (!CMDPARSER_USES_GGTT(eb->i915)) {
2286 /*
2287 * ppGTT backed shadow buffers must be mapped RO, to prevent
2288 * post-scan tampering
2289 */
2290 if (!eb->context->vm->has_read_only) {
2291 drm_dbg(&i915->drm,
2292 "Cannot prevent post-scan tampering without RO capable vm\n");
2293 return -EINVAL;
2294 }
2295 } else {
2296 len += I915_CMD_PARSER_TRAMPOLINE_SIZE;
2297 }
2298 if (unlikely(len < eb->batch_len[0])) /* last paranoid check of overflow */
2299 return -EINVAL;
2300
2301 if (!pool) {
2302 pool = intel_gt_get_buffer_pool(eb->gt, len,
2303 I915_MAP_WB);
2304 if (IS_ERR(pool))
2305 return PTR_ERR(pool);
2306 eb->batch_pool = pool;
2307 }
2308
2309 err = i915_gem_object_lock(pool->obj, &eb->ww);
2310 if (err)
2311 return err;
2312
2313 shadow = shadow_batch_pin(eb, pool->obj, eb->context->vm, PIN_USER);
2314 if (IS_ERR(shadow))
2315 return PTR_ERR(shadow);
2316
2317 intel_gt_buffer_pool_mark_used(pool);
2318 i915_gem_object_set_readonly(shadow->obj);
2319 shadow->private = pool;
2320
2321 trampoline = NULL;
2322 if (CMDPARSER_USES_GGTT(eb->i915)) {
2323 trampoline = shadow;
2324
2325 shadow = shadow_batch_pin(eb, pool->obj,
2326 &eb->gt->ggtt->vm,
2327 PIN_GLOBAL);
2328 if (IS_ERR(shadow))
2329 return PTR_ERR(shadow);
2330
2331 shadow->private = pool;
2332
2333 eb->batch_flags |= I915_DISPATCH_SECURE;
2334 }
2335
2336 batch = eb_dispatch_secure(eb, shadow);
2337 if (IS_ERR(batch))
2338 return PTR_ERR(batch);
2339
2340 err = dma_resv_reserve_fences(shadow->obj->base.resv, 1);
2341 if (err)
2342 return err;
2343
2344 err = intel_engine_cmd_parser(eb->context->engine,
2345 eb->batches[0]->vma,
2346 eb->batch_start_offset,
2347 eb->batch_len[0],
2348 shadow, trampoline);
2349 if (err)
2350 return err;
2351
2352 eb->batches[0] = &eb->vma[eb->buffer_count++];
2353 eb->batches[0]->vma = i915_vma_get(shadow);
2354 eb->batches[0]->flags = __EXEC_OBJECT_HAS_PIN;
2355
2356 eb->trampoline = trampoline;
2357 eb->batch_start_offset = 0;
2358
2359 secure_batch:
2360 if (batch) {
2361 if (intel_context_is_parallel(eb->context))
2362 return -EINVAL;
2363
2364 eb->batches[0] = &eb->vma[eb->buffer_count++];
2365 eb->batches[0]->flags = __EXEC_OBJECT_HAS_PIN;
2366 eb->batches[0]->vma = i915_vma_get(batch);
2367 }
2368 return 0;
2369 }
2370
eb_request_submit(struct i915_execbuffer * eb,struct i915_request * rq,struct i915_vma * batch,u64 batch_len)2371 static int eb_request_submit(struct i915_execbuffer *eb,
2372 struct i915_request *rq,
2373 struct i915_vma *batch,
2374 u64 batch_len)
2375 {
2376 int err;
2377
2378 if (intel_context_nopreempt(rq->context))
2379 __set_bit(I915_FENCE_FLAG_NOPREEMPT, &rq->fence.flags);
2380
2381 if (eb->args->flags & I915_EXEC_GEN7_SOL_RESET) {
2382 err = i915_reset_gen7_sol_offsets(rq);
2383 if (err)
2384 return err;
2385 }
2386
2387 /*
2388 * After we completed waiting for other engines (using HW semaphores)
2389 * then we can signal that this request/batch is ready to run. This
2390 * allows us to determine if the batch is still waiting on the GPU
2391 * or actually running by checking the breadcrumb.
2392 */
2393 if (rq->context->engine->emit_init_breadcrumb) {
2394 err = rq->context->engine->emit_init_breadcrumb(rq);
2395 if (err)
2396 return err;
2397 }
2398
2399 err = rq->context->engine->emit_bb_start(rq,
2400 i915_vma_offset(batch) +
2401 eb->batch_start_offset,
2402 batch_len,
2403 eb->batch_flags);
2404 if (err)
2405 return err;
2406
2407 if (eb->trampoline) {
2408 GEM_BUG_ON(intel_context_is_parallel(rq->context));
2409 GEM_BUG_ON(eb->batch_start_offset);
2410 err = rq->context->engine->emit_bb_start(rq,
2411 i915_vma_offset(eb->trampoline) +
2412 batch_len, 0, 0);
2413 if (err)
2414 return err;
2415 }
2416
2417 return 0;
2418 }
2419
eb_submit(struct i915_execbuffer * eb)2420 static int eb_submit(struct i915_execbuffer *eb)
2421 {
2422 unsigned int i;
2423 int err;
2424
2425 err = eb_move_to_gpu(eb);
2426
2427 for_each_batch_create_order(eb, i) {
2428 if (!eb->requests[i])
2429 break;
2430
2431 trace_i915_request_queue(eb->requests[i], eb->batch_flags);
2432 if (!err)
2433 err = eb_request_submit(eb, eb->requests[i],
2434 eb->batches[i]->vma,
2435 eb->batch_len[i]);
2436 }
2437
2438 return err;
2439 }
2440
2441 /*
2442 * Find one BSD ring to dispatch the corresponding BSD command.
2443 * The engine index is returned.
2444 */
2445 static unsigned int
gen8_dispatch_bsd_engine(struct drm_i915_private * i915,struct drm_file * file)2446 gen8_dispatch_bsd_engine(struct drm_i915_private *i915,
2447 struct drm_file *file)
2448 {
2449 struct drm_i915_file_private *file_priv = file->driver_priv;
2450
2451 /* Check whether the file_priv has already selected one ring. */
2452 if ((int)file_priv->bsd_engine < 0)
2453 file_priv->bsd_engine =
2454 get_random_u32_below(i915->engine_uabi_class_count[I915_ENGINE_CLASS_VIDEO]);
2455
2456 return file_priv->bsd_engine;
2457 }
2458
2459 static const enum intel_engine_id user_ring_map[] = {
2460 [I915_EXEC_DEFAULT] = RCS0,
2461 [I915_EXEC_RENDER] = RCS0,
2462 [I915_EXEC_BLT] = BCS0,
2463 [I915_EXEC_BSD] = VCS0,
2464 [I915_EXEC_VEBOX] = VECS0
2465 };
2466
eb_throttle(struct i915_execbuffer * eb,struct intel_context * ce)2467 static struct i915_request *eb_throttle(struct i915_execbuffer *eb, struct intel_context *ce)
2468 {
2469 struct intel_ring *ring = ce->ring;
2470 struct intel_timeline *tl = ce->timeline;
2471 struct i915_request *rq;
2472
2473 /*
2474 * Completely unscientific finger-in-the-air estimates for suitable
2475 * maximum user request size (to avoid blocking) and then backoff.
2476 */
2477 if (intel_ring_update_space(ring) >= PAGE_SIZE)
2478 return NULL;
2479
2480 /*
2481 * Find a request that after waiting upon, there will be at least half
2482 * the ring available. The hysteresis allows us to compete for the
2483 * shared ring and should mean that we sleep less often prior to
2484 * claiming our resources, but not so long that the ring completely
2485 * drains before we can submit our next request.
2486 */
2487 list_for_each_entry(rq, &tl->requests, link) {
2488 if (rq->ring != ring)
2489 continue;
2490
2491 if (__intel_ring_space(rq->postfix,
2492 ring->emit, ring->size) > ring->size / 2)
2493 break;
2494 }
2495 if (&rq->link == &tl->requests)
2496 return NULL; /* weird, we will check again later for real */
2497
2498 return i915_request_get(rq);
2499 }
2500
eb_pin_timeline(struct i915_execbuffer * eb,struct intel_context * ce,bool throttle)2501 static int eb_pin_timeline(struct i915_execbuffer *eb, struct intel_context *ce,
2502 bool throttle)
2503 {
2504 struct intel_timeline *tl;
2505 struct i915_request *rq = NULL;
2506
2507 /*
2508 * Take a local wakeref for preparing to dispatch the execbuf as
2509 * we expect to access the hardware fairly frequently in the
2510 * process, and require the engine to be kept awake between accesses.
2511 * Upon dispatch, we acquire another prolonged wakeref that we hold
2512 * until the timeline is idle, which in turn releases the wakeref
2513 * taken on the engine, and the parent device.
2514 */
2515 tl = intel_context_timeline_lock(ce);
2516 if (IS_ERR(tl))
2517 return PTR_ERR(tl);
2518
2519 intel_context_enter(ce);
2520 if (throttle)
2521 rq = eb_throttle(eb, ce);
2522 intel_context_timeline_unlock(tl);
2523
2524 if (rq) {
2525 bool nonblock = eb->file->filp->f_flags & O_NONBLOCK;
2526 long timeout = nonblock ? 0 : MAX_SCHEDULE_TIMEOUT;
2527
2528 if (i915_request_wait(rq, I915_WAIT_INTERRUPTIBLE,
2529 timeout) < 0) {
2530 i915_request_put(rq);
2531
2532 /*
2533 * Error path, cannot use intel_context_timeline_lock as
2534 * that is user interruptible and this clean up step
2535 * must be done.
2536 */
2537 mutex_lock(&ce->timeline->mutex);
2538 intel_context_exit(ce);
2539 mutex_unlock(&ce->timeline->mutex);
2540
2541 if (nonblock)
2542 return -EWOULDBLOCK;
2543 else
2544 return -EINTR;
2545 }
2546 i915_request_put(rq);
2547 }
2548
2549 return 0;
2550 }
2551
eb_pin_engine(struct i915_execbuffer * eb,bool throttle)2552 static int eb_pin_engine(struct i915_execbuffer *eb, bool throttle)
2553 {
2554 struct intel_context *ce = eb->context, *child;
2555 int err;
2556 int i = 0, j = 0;
2557
2558 GEM_BUG_ON(eb->args->flags & __EXEC_ENGINE_PINNED);
2559
2560 if (unlikely(intel_context_is_banned(ce)))
2561 return -EIO;
2562
2563 /*
2564 * Pinning the contexts may generate requests in order to acquire
2565 * GGTT space, so do this first before we reserve a seqno for
2566 * ourselves.
2567 */
2568 err = intel_context_pin_ww(ce, &eb->ww);
2569 if (err)
2570 return err;
2571 for_each_child(ce, child) {
2572 err = intel_context_pin_ww(child, &eb->ww);
2573 GEM_BUG_ON(err); /* perma-pinned should incr a counter */
2574 }
2575
2576 for_each_child(ce, child) {
2577 err = eb_pin_timeline(eb, child, throttle);
2578 if (err)
2579 goto unwind;
2580 ++i;
2581 }
2582 err = eb_pin_timeline(eb, ce, throttle);
2583 if (err)
2584 goto unwind;
2585
2586 eb->args->flags |= __EXEC_ENGINE_PINNED;
2587 return 0;
2588
2589 unwind:
2590 for_each_child(ce, child) {
2591 if (j++ < i) {
2592 mutex_lock(&child->timeline->mutex);
2593 intel_context_exit(child);
2594 mutex_unlock(&child->timeline->mutex);
2595 }
2596 }
2597 for_each_child(ce, child)
2598 intel_context_unpin(child);
2599 intel_context_unpin(ce);
2600 return err;
2601 }
2602
eb_unpin_engine(struct i915_execbuffer * eb)2603 static void eb_unpin_engine(struct i915_execbuffer *eb)
2604 {
2605 struct intel_context *ce = eb->context, *child;
2606
2607 if (!(eb->args->flags & __EXEC_ENGINE_PINNED))
2608 return;
2609
2610 eb->args->flags &= ~__EXEC_ENGINE_PINNED;
2611
2612 for_each_child(ce, child) {
2613 mutex_lock(&child->timeline->mutex);
2614 intel_context_exit(child);
2615 mutex_unlock(&child->timeline->mutex);
2616
2617 intel_context_unpin(child);
2618 }
2619
2620 mutex_lock(&ce->timeline->mutex);
2621 intel_context_exit(ce);
2622 mutex_unlock(&ce->timeline->mutex);
2623
2624 intel_context_unpin(ce);
2625 }
2626
2627 static unsigned int
eb_select_legacy_ring(struct i915_execbuffer * eb)2628 eb_select_legacy_ring(struct i915_execbuffer *eb)
2629 {
2630 struct drm_i915_private *i915 = eb->i915;
2631 struct drm_i915_gem_execbuffer2 *args = eb->args;
2632 unsigned int user_ring_id = args->flags & I915_EXEC_RING_MASK;
2633
2634 if (user_ring_id != I915_EXEC_BSD &&
2635 (args->flags & I915_EXEC_BSD_MASK)) {
2636 drm_dbg(&i915->drm,
2637 "execbuf with non bsd ring but with invalid "
2638 "bsd dispatch flags: %d\n", (int)(args->flags));
2639 return -1;
2640 }
2641
2642 if (user_ring_id == I915_EXEC_BSD &&
2643 i915->engine_uabi_class_count[I915_ENGINE_CLASS_VIDEO] > 1) {
2644 unsigned int bsd_idx = args->flags & I915_EXEC_BSD_MASK;
2645
2646 if (bsd_idx == I915_EXEC_BSD_DEFAULT) {
2647 bsd_idx = gen8_dispatch_bsd_engine(i915, eb->file);
2648 } else if (bsd_idx >= I915_EXEC_BSD_RING1 &&
2649 bsd_idx <= I915_EXEC_BSD_RING2) {
2650 bsd_idx >>= I915_EXEC_BSD_SHIFT;
2651 bsd_idx--;
2652 } else {
2653 drm_dbg(&i915->drm,
2654 "execbuf with unknown bsd ring: %u\n",
2655 bsd_idx);
2656 return -1;
2657 }
2658
2659 return _VCS(bsd_idx);
2660 }
2661
2662 if (user_ring_id >= ARRAY_SIZE(user_ring_map)) {
2663 drm_dbg(&i915->drm, "execbuf with unknown ring: %u\n",
2664 user_ring_id);
2665 return -1;
2666 }
2667
2668 return user_ring_map[user_ring_id];
2669 }
2670
2671 static int
eb_select_engine(struct i915_execbuffer * eb)2672 eb_select_engine(struct i915_execbuffer *eb)
2673 {
2674 struct intel_context *ce, *child;
2675 struct intel_gt *gt;
2676 unsigned int idx;
2677 int err;
2678
2679 if (i915_gem_context_user_engines(eb->gem_context))
2680 idx = eb->args->flags & I915_EXEC_RING_MASK;
2681 else
2682 idx = eb_select_legacy_ring(eb);
2683
2684 ce = i915_gem_context_get_engine(eb->gem_context, idx);
2685 if (IS_ERR(ce))
2686 return PTR_ERR(ce);
2687
2688 if (intel_context_is_parallel(ce)) {
2689 if (eb->buffer_count < ce->parallel.number_children + 1) {
2690 intel_context_put(ce);
2691 return -EINVAL;
2692 }
2693 if (eb->batch_start_offset || eb->args->batch_len) {
2694 intel_context_put(ce);
2695 return -EINVAL;
2696 }
2697 }
2698 eb->num_batches = ce->parallel.number_children + 1;
2699 gt = ce->engine->gt;
2700
2701 for_each_child(ce, child)
2702 intel_context_get(child);
2703 eb->wakeref = intel_gt_pm_get(ce->engine->gt);
2704 /*
2705 * Keep GT0 active on MTL so that i915_vma_parked() doesn't
2706 * free VMAs while execbuf ioctl is validating VMAs.
2707 */
2708 if (gt->info.id)
2709 eb->wakeref_gt0 = intel_gt_pm_get(to_gt(gt->i915));
2710
2711 if (!test_bit(CONTEXT_ALLOC_BIT, &ce->flags)) {
2712 err = intel_context_alloc_state(ce);
2713 if (err)
2714 goto err;
2715 }
2716 for_each_child(ce, child) {
2717 if (!test_bit(CONTEXT_ALLOC_BIT, &child->flags)) {
2718 err = intel_context_alloc_state(child);
2719 if (err)
2720 goto err;
2721 }
2722 }
2723
2724 /*
2725 * ABI: Before userspace accesses the GPU (e.g. execbuffer), report
2726 * EIO if the GPU is already wedged.
2727 */
2728 err = intel_gt_terminally_wedged(ce->engine->gt);
2729 if (err)
2730 goto err;
2731
2732 if (!i915_vm_tryget(ce->vm)) {
2733 err = -ENOENT;
2734 goto err;
2735 }
2736
2737 eb->context = ce;
2738 eb->gt = ce->engine->gt;
2739
2740 /*
2741 * Make sure engine pool stays alive even if we call intel_context_put
2742 * during ww handling. The pool is destroyed when last pm reference
2743 * is dropped, which breaks our -EDEADLK handling.
2744 */
2745 return err;
2746
2747 err:
2748 if (gt->info.id)
2749 intel_gt_pm_put(to_gt(gt->i915), eb->wakeref_gt0);
2750
2751 intel_gt_pm_put(ce->engine->gt, eb->wakeref);
2752 for_each_child(ce, child)
2753 intel_context_put(child);
2754 intel_context_put(ce);
2755 return err;
2756 }
2757
2758 static void
eb_put_engine(struct i915_execbuffer * eb)2759 eb_put_engine(struct i915_execbuffer *eb)
2760 {
2761 struct intel_context *child;
2762
2763 i915_vm_put(eb->context->vm);
2764 /*
2765 * This works in conjunction with eb_select_engine() to prevent
2766 * i915_vma_parked() from interfering while execbuf validates vmas.
2767 */
2768 if (eb->gt->info.id)
2769 intel_gt_pm_put(to_gt(eb->gt->i915), eb->wakeref_gt0);
2770 intel_gt_pm_put(eb->context->engine->gt, eb->wakeref);
2771 for_each_child(eb->context, child)
2772 intel_context_put(child);
2773 intel_context_put(eb->context);
2774 }
2775
2776 static void
__free_fence_array(struct eb_fence * fences,unsigned int n)2777 __free_fence_array(struct eb_fence *fences, unsigned int n)
2778 {
2779 while (n--) {
2780 drm_syncobj_put(ptr_mask_bits(fences[n].syncobj, 2));
2781 dma_fence_put(fences[n].dma_fence);
2782 dma_fence_chain_free(fences[n].chain_fence);
2783 }
2784 kvfree(fences);
2785 }
2786
2787 static int
add_timeline_fence_array(struct i915_execbuffer * eb,const struct drm_i915_gem_execbuffer_ext_timeline_fences * timeline_fences)2788 add_timeline_fence_array(struct i915_execbuffer *eb,
2789 const struct drm_i915_gem_execbuffer_ext_timeline_fences *timeline_fences)
2790 {
2791 struct drm_i915_gem_exec_fence __user *user_fences;
2792 u64 __user *user_values;
2793 struct eb_fence *f;
2794 u64 nfences;
2795 int err = 0;
2796
2797 nfences = timeline_fences->fence_count;
2798 if (!nfences)
2799 return 0;
2800
2801 /* Check multiplication overflow for access_ok() and kvmalloc_array() */
2802 BUILD_BUG_ON(sizeof(size_t) > sizeof(unsigned long));
2803 if (nfences > min_t(unsigned long,
2804 ULONG_MAX / sizeof(*user_fences),
2805 SIZE_MAX / sizeof(*f)) - eb->num_fences)
2806 return -EINVAL;
2807
2808 user_fences = u64_to_user_ptr(timeline_fences->handles_ptr);
2809 if (!access_ok(user_fences, nfences * sizeof(*user_fences)))
2810 return -EFAULT;
2811
2812 user_values = u64_to_user_ptr(timeline_fences->values_ptr);
2813 if (!access_ok(user_values, nfences * sizeof(*user_values)))
2814 return -EFAULT;
2815
2816 f = krealloc(eb->fences,
2817 (eb->num_fences + nfences) * sizeof(*f),
2818 __GFP_NOWARN | GFP_KERNEL);
2819 if (!f)
2820 return -ENOMEM;
2821
2822 eb->fences = f;
2823 f += eb->num_fences;
2824
2825 BUILD_BUG_ON(~(ARCH_KMALLOC_MINALIGN - 1) &
2826 ~__I915_EXEC_FENCE_UNKNOWN_FLAGS);
2827
2828 while (nfences--) {
2829 struct drm_i915_gem_exec_fence user_fence;
2830 struct drm_syncobj *syncobj;
2831 struct dma_fence *fence = NULL;
2832 u64 point;
2833
2834 if (__copy_from_user(&user_fence,
2835 user_fences++,
2836 sizeof(user_fence)))
2837 return -EFAULT;
2838
2839 if (user_fence.flags & __I915_EXEC_FENCE_UNKNOWN_FLAGS)
2840 return -EINVAL;
2841
2842 if (__get_user(point, user_values++))
2843 return -EFAULT;
2844
2845 syncobj = drm_syncobj_find(eb->file, user_fence.handle);
2846 if (!syncobj) {
2847 drm_dbg(&eb->i915->drm,
2848 "Invalid syncobj handle provided\n");
2849 return -ENOENT;
2850 }
2851
2852 fence = drm_syncobj_fence_get(syncobj);
2853
2854 if (!fence && user_fence.flags &&
2855 !(user_fence.flags & I915_EXEC_FENCE_SIGNAL)) {
2856 drm_dbg(&eb->i915->drm,
2857 "Syncobj handle has no fence\n");
2858 drm_syncobj_put(syncobj);
2859 return -EINVAL;
2860 }
2861
2862 if (fence)
2863 err = dma_fence_chain_find_seqno(&fence, point);
2864
2865 if (err && !(user_fence.flags & I915_EXEC_FENCE_SIGNAL)) {
2866 drm_dbg(&eb->i915->drm,
2867 "Syncobj handle missing requested point %llu\n",
2868 point);
2869 dma_fence_put(fence);
2870 drm_syncobj_put(syncobj);
2871 return err;
2872 }
2873
2874 /*
2875 * A point might have been signaled already and
2876 * garbage collected from the timeline. In this case
2877 * just ignore the point and carry on.
2878 */
2879 if (!fence && !(user_fence.flags & I915_EXEC_FENCE_SIGNAL)) {
2880 drm_syncobj_put(syncobj);
2881 continue;
2882 }
2883
2884 /*
2885 * For timeline syncobjs we need to preallocate chains for
2886 * later signaling.
2887 */
2888 if (point != 0 && user_fence.flags & I915_EXEC_FENCE_SIGNAL) {
2889 /*
2890 * Waiting and signaling the same point (when point !=
2891 * 0) would break the timeline.
2892 */
2893 if (user_fence.flags & I915_EXEC_FENCE_WAIT) {
2894 drm_dbg(&eb->i915->drm,
2895 "Trying to wait & signal the same timeline point.\n");
2896 dma_fence_put(fence);
2897 drm_syncobj_put(syncobj);
2898 return -EINVAL;
2899 }
2900
2901 f->chain_fence = dma_fence_chain_alloc();
2902 if (!f->chain_fence) {
2903 drm_syncobj_put(syncobj);
2904 dma_fence_put(fence);
2905 return -ENOMEM;
2906 }
2907 } else {
2908 f->chain_fence = NULL;
2909 }
2910
2911 f->syncobj = ptr_pack_bits(syncobj, user_fence.flags, 2);
2912 f->dma_fence = fence;
2913 f->value = point;
2914 f++;
2915 eb->num_fences++;
2916 }
2917
2918 return 0;
2919 }
2920
add_fence_array(struct i915_execbuffer * eb)2921 static int add_fence_array(struct i915_execbuffer *eb)
2922 {
2923 struct drm_i915_gem_execbuffer2 *args = eb->args;
2924 struct drm_i915_gem_exec_fence __user *user;
2925 unsigned long num_fences = args->num_cliprects;
2926 struct eb_fence *f;
2927
2928 if (!(args->flags & I915_EXEC_FENCE_ARRAY))
2929 return 0;
2930
2931 if (!num_fences)
2932 return 0;
2933
2934 /* Check multiplication overflow for access_ok() and kvmalloc_array() */
2935 BUILD_BUG_ON(sizeof(size_t) > sizeof(unsigned long));
2936 if (num_fences > min_t(unsigned long,
2937 ULONG_MAX / sizeof(*user),
2938 SIZE_MAX / sizeof(*f) - eb->num_fences))
2939 return -EINVAL;
2940
2941 user = u64_to_user_ptr(args->cliprects_ptr);
2942 if (!access_ok(user, num_fences * sizeof(*user)))
2943 return -EFAULT;
2944
2945 f = krealloc(eb->fences,
2946 (eb->num_fences + num_fences) * sizeof(*f),
2947 __GFP_NOWARN | GFP_KERNEL);
2948 if (!f)
2949 return -ENOMEM;
2950
2951 eb->fences = f;
2952 f += eb->num_fences;
2953 while (num_fences--) {
2954 struct drm_i915_gem_exec_fence user_fence;
2955 struct drm_syncobj *syncobj;
2956 struct dma_fence *fence = NULL;
2957
2958 if (__copy_from_user(&user_fence, user++, sizeof(user_fence)))
2959 return -EFAULT;
2960
2961 if (user_fence.flags & __I915_EXEC_FENCE_UNKNOWN_FLAGS)
2962 return -EINVAL;
2963
2964 syncobj = drm_syncobj_find(eb->file, user_fence.handle);
2965 if (!syncobj) {
2966 drm_dbg(&eb->i915->drm,
2967 "Invalid syncobj handle provided\n");
2968 return -ENOENT;
2969 }
2970
2971 if (user_fence.flags & I915_EXEC_FENCE_WAIT) {
2972 fence = drm_syncobj_fence_get(syncobj);
2973 if (!fence) {
2974 drm_dbg(&eb->i915->drm,
2975 "Syncobj handle has no fence\n");
2976 drm_syncobj_put(syncobj);
2977 return -EINVAL;
2978 }
2979 }
2980
2981 BUILD_BUG_ON(~(ARCH_KMALLOC_MINALIGN - 1) &
2982 ~__I915_EXEC_FENCE_UNKNOWN_FLAGS);
2983
2984 f->syncobj = ptr_pack_bits(syncobj, user_fence.flags, 2);
2985 f->dma_fence = fence;
2986 f->value = 0;
2987 f->chain_fence = NULL;
2988 f++;
2989 eb->num_fences++;
2990 }
2991
2992 return 0;
2993 }
2994
put_fence_array(struct eb_fence * fences,int num_fences)2995 static void put_fence_array(struct eb_fence *fences, int num_fences)
2996 {
2997 if (fences)
2998 __free_fence_array(fences, num_fences);
2999 }
3000
3001 static int
await_fence_array(struct i915_execbuffer * eb,struct i915_request * rq)3002 await_fence_array(struct i915_execbuffer *eb,
3003 struct i915_request *rq)
3004 {
3005 unsigned int n;
3006 int err;
3007
3008 for (n = 0; n < eb->num_fences; n++) {
3009 if (!eb->fences[n].dma_fence)
3010 continue;
3011
3012 err = i915_request_await_dma_fence(rq, eb->fences[n].dma_fence);
3013 if (err < 0)
3014 return err;
3015 }
3016
3017 return 0;
3018 }
3019
signal_fence_array(const struct i915_execbuffer * eb,struct dma_fence * const fence)3020 static void signal_fence_array(const struct i915_execbuffer *eb,
3021 struct dma_fence * const fence)
3022 {
3023 unsigned int n;
3024
3025 for (n = 0; n < eb->num_fences; n++) {
3026 struct drm_syncobj *syncobj;
3027 unsigned int flags;
3028
3029 syncobj = ptr_unpack_bits(eb->fences[n].syncobj, &flags, 2);
3030 if (!(flags & I915_EXEC_FENCE_SIGNAL))
3031 continue;
3032
3033 if (eb->fences[n].chain_fence) {
3034 drm_syncobj_add_point(syncobj,
3035 eb->fences[n].chain_fence,
3036 fence,
3037 eb->fences[n].value);
3038 /*
3039 * The chain's ownership is transferred to the
3040 * timeline.
3041 */
3042 eb->fences[n].chain_fence = NULL;
3043 } else {
3044 drm_syncobj_replace_fence(syncobj, fence);
3045 }
3046 }
3047 }
3048
3049 static int
parse_timeline_fences(struct i915_user_extension __user * ext,void * data)3050 parse_timeline_fences(struct i915_user_extension __user *ext, void *data)
3051 {
3052 struct i915_execbuffer *eb = data;
3053 struct drm_i915_gem_execbuffer_ext_timeline_fences timeline_fences;
3054
3055 if (copy_from_user(&timeline_fences, ext, sizeof(timeline_fences)))
3056 return -EFAULT;
3057
3058 return add_timeline_fence_array(eb, &timeline_fences);
3059 }
3060
retire_requests(struct intel_timeline * tl,struct i915_request * end)3061 static void retire_requests(struct intel_timeline *tl, struct i915_request *end)
3062 {
3063 struct i915_request *rq, *rn;
3064
3065 list_for_each_entry_safe(rq, rn, &tl->requests, link)
3066 if (rq == end || !i915_request_retire(rq))
3067 break;
3068 }
3069
eb_request_add(struct i915_execbuffer * eb,struct i915_request * rq,int err,bool last_parallel)3070 static int eb_request_add(struct i915_execbuffer *eb, struct i915_request *rq,
3071 int err, bool last_parallel)
3072 {
3073 struct intel_timeline * const tl = i915_request_timeline(rq);
3074 struct i915_sched_attr attr = {};
3075 struct i915_request *prev;
3076
3077 lockdep_assert_held(&tl->mutex);
3078 lockdep_unpin_lock(&tl->mutex, rq->cookie);
3079
3080 trace_i915_request_add(rq);
3081
3082 prev = __i915_request_commit(rq);
3083
3084 /* Check that the context wasn't destroyed before submission */
3085 if (likely(!intel_context_is_closed(eb->context))) {
3086 attr = eb->gem_context->sched;
3087 } else {
3088 /* Serialise with context_close via the add_to_timeline */
3089 i915_request_set_error_once(rq, -ENOENT);
3090 __i915_request_skip(rq);
3091 err = -ENOENT; /* override any transient errors */
3092 }
3093
3094 if (intel_context_is_parallel(eb->context)) {
3095 if (err) {
3096 __i915_request_skip(rq);
3097 set_bit(I915_FENCE_FLAG_SKIP_PARALLEL,
3098 &rq->fence.flags);
3099 }
3100 if (last_parallel)
3101 set_bit(I915_FENCE_FLAG_SUBMIT_PARALLEL,
3102 &rq->fence.flags);
3103 }
3104
3105 __i915_request_queue(rq, &attr);
3106
3107 /* Try to clean up the client's timeline after submitting the request */
3108 if (prev)
3109 retire_requests(tl, prev);
3110
3111 mutex_unlock(&tl->mutex);
3112
3113 return err;
3114 }
3115
eb_requests_add(struct i915_execbuffer * eb,int err)3116 static int eb_requests_add(struct i915_execbuffer *eb, int err)
3117 {
3118 int i;
3119
3120 /*
3121 * We iterate in reverse order of creation to release timeline mutexes in
3122 * same order.
3123 */
3124 for_each_batch_add_order(eb, i) {
3125 struct i915_request *rq = eb->requests[i];
3126
3127 if (!rq)
3128 continue;
3129 err |= eb_request_add(eb, rq, err, i == 0);
3130 }
3131
3132 return err;
3133 }
3134
3135 static const i915_user_extension_fn execbuf_extensions[] = {
3136 [DRM_I915_GEM_EXECBUFFER_EXT_TIMELINE_FENCES] = parse_timeline_fences,
3137 };
3138
3139 static int
parse_execbuf2_extensions(struct drm_i915_gem_execbuffer2 * args,struct i915_execbuffer * eb)3140 parse_execbuf2_extensions(struct drm_i915_gem_execbuffer2 *args,
3141 struct i915_execbuffer *eb)
3142 {
3143 if (!(args->flags & I915_EXEC_USE_EXTENSIONS))
3144 return 0;
3145
3146 /* The execbuf2 extension mechanism reuses cliprects_ptr. So we cannot
3147 * have another flag also using it at the same time.
3148 */
3149 if (eb->args->flags & I915_EXEC_FENCE_ARRAY)
3150 return -EINVAL;
3151
3152 if (args->num_cliprects != 0)
3153 return -EINVAL;
3154
3155 return i915_user_extensions(u64_to_user_ptr(args->cliprects_ptr),
3156 execbuf_extensions,
3157 ARRAY_SIZE(execbuf_extensions),
3158 eb);
3159 }
3160
eb_requests_get(struct i915_execbuffer * eb)3161 static void eb_requests_get(struct i915_execbuffer *eb)
3162 {
3163 unsigned int i;
3164
3165 for_each_batch_create_order(eb, i) {
3166 if (!eb->requests[i])
3167 break;
3168
3169 i915_request_get(eb->requests[i]);
3170 }
3171 }
3172
eb_requests_put(struct i915_execbuffer * eb)3173 static void eb_requests_put(struct i915_execbuffer *eb)
3174 {
3175 unsigned int i;
3176
3177 for_each_batch_create_order(eb, i) {
3178 if (!eb->requests[i])
3179 break;
3180
3181 i915_request_put(eb->requests[i]);
3182 }
3183 }
3184
3185 static struct sync_file *
eb_composite_fence_create(struct i915_execbuffer * eb,int out_fence_fd)3186 eb_composite_fence_create(struct i915_execbuffer *eb, int out_fence_fd)
3187 {
3188 struct sync_file *out_fence = NULL;
3189 struct dma_fence_array *fence_array;
3190 struct dma_fence **fences;
3191 unsigned int i;
3192
3193 GEM_BUG_ON(!intel_context_is_parent(eb->context));
3194
3195 fences = kmalloc_objs(*fences, eb->num_batches);
3196 if (!fences)
3197 return ERR_PTR(-ENOMEM);
3198
3199 for_each_batch_create_order(eb, i) {
3200 fences[i] = &eb->requests[i]->fence;
3201 __set_bit(I915_FENCE_FLAG_COMPOSITE,
3202 &eb->requests[i]->fence.flags);
3203 }
3204
3205 fence_array = dma_fence_array_create(eb->num_batches,
3206 fences,
3207 eb->context->parallel.fence_context,
3208 eb->context->parallel.seqno++,
3209 false);
3210 if (!fence_array) {
3211 kfree(fences);
3212 return ERR_PTR(-ENOMEM);
3213 }
3214
3215 /* Move ownership to the dma_fence_array created above */
3216 for_each_batch_create_order(eb, i)
3217 dma_fence_get(fences[i]);
3218
3219 if (out_fence_fd != -1) {
3220 out_fence = sync_file_create(&fence_array->base);
3221 /* sync_file now owns fence_arry, drop creation ref */
3222 dma_fence_put(&fence_array->base);
3223 if (!out_fence)
3224 return ERR_PTR(-ENOMEM);
3225 }
3226
3227 eb->composite_fence = &fence_array->base;
3228
3229 return out_fence;
3230 }
3231
3232 static struct sync_file *
eb_fences_add(struct i915_execbuffer * eb,struct i915_request * rq,struct dma_fence * in_fence,int out_fence_fd)3233 eb_fences_add(struct i915_execbuffer *eb, struct i915_request *rq,
3234 struct dma_fence *in_fence, int out_fence_fd)
3235 {
3236 struct sync_file *out_fence = NULL;
3237 int err;
3238
3239 if (unlikely(eb->gem_context->syncobj)) {
3240 struct dma_fence *fence;
3241
3242 fence = drm_syncobj_fence_get(eb->gem_context->syncobj);
3243 err = i915_request_await_dma_fence(rq, fence);
3244 dma_fence_put(fence);
3245 if (err)
3246 return ERR_PTR(err);
3247 }
3248
3249 if (in_fence) {
3250 if (eb->args->flags & I915_EXEC_FENCE_SUBMIT)
3251 err = i915_request_await_execution(rq, in_fence);
3252 else
3253 err = i915_request_await_dma_fence(rq, in_fence);
3254 if (err < 0)
3255 return ERR_PTR(err);
3256 }
3257
3258 if (eb->fences) {
3259 err = await_fence_array(eb, rq);
3260 if (err)
3261 return ERR_PTR(err);
3262 }
3263
3264 if (intel_context_is_parallel(eb->context)) {
3265 out_fence = eb_composite_fence_create(eb, out_fence_fd);
3266 if (IS_ERR(out_fence))
3267 return ERR_PTR(-ENOMEM);
3268 } else if (out_fence_fd != -1) {
3269 out_fence = sync_file_create(&rq->fence);
3270 if (!out_fence)
3271 return ERR_PTR(-ENOMEM);
3272 }
3273
3274 return out_fence;
3275 }
3276
3277 static struct intel_context *
eb_find_context(struct i915_execbuffer * eb,unsigned int context_number)3278 eb_find_context(struct i915_execbuffer *eb, unsigned int context_number)
3279 {
3280 struct intel_context *child;
3281
3282 if (likely(context_number == 0))
3283 return eb->context;
3284
3285 for_each_child(eb->context, child)
3286 if (!--context_number)
3287 return child;
3288
3289 GEM_BUG_ON("Context not found");
3290
3291 return NULL;
3292 }
3293
3294 static struct sync_file *
eb_requests_create(struct i915_execbuffer * eb,struct dma_fence * in_fence,int out_fence_fd)3295 eb_requests_create(struct i915_execbuffer *eb, struct dma_fence *in_fence,
3296 int out_fence_fd)
3297 {
3298 struct sync_file *out_fence = NULL;
3299 unsigned int i;
3300
3301 for_each_batch_create_order(eb, i) {
3302 /* Allocate a request for this batch buffer nice and early. */
3303 eb->requests[i] = i915_request_create(eb_find_context(eb, i));
3304 if (IS_ERR(eb->requests[i])) {
3305 out_fence = ERR_CAST(eb->requests[i]);
3306 eb->requests[i] = NULL;
3307 return out_fence;
3308 }
3309
3310 /*
3311 * Only the first request added (committed to backend) has to
3312 * take the in fences into account as all subsequent requests
3313 * will have fences inserted inbetween them.
3314 */
3315 if (i + 1 == eb->num_batches) {
3316 out_fence = eb_fences_add(eb, eb->requests[i],
3317 in_fence, out_fence_fd);
3318 if (IS_ERR(out_fence))
3319 return out_fence;
3320 }
3321
3322 /*
3323 * Not really on stack, but we don't want to call
3324 * kfree on the batch_snapshot when we put it, so use the
3325 * _onstack interface.
3326 */
3327 if (eb->batches[i]->vma)
3328 eb->requests[i]->batch_res =
3329 i915_vma_resource_get(eb->batches[i]->vma->resource);
3330 if (eb->batch_pool) {
3331 GEM_BUG_ON(intel_context_is_parallel(eb->context));
3332 intel_gt_buffer_pool_mark_active(eb->batch_pool,
3333 eb->requests[i]);
3334 }
3335 }
3336
3337 return out_fence;
3338 }
3339
3340 static int
i915_gem_do_execbuffer(struct drm_device * dev,struct drm_file * file,struct drm_i915_gem_execbuffer2 * args,struct drm_i915_gem_exec_object2 * exec)3341 i915_gem_do_execbuffer(struct drm_device *dev,
3342 struct drm_file *file,
3343 struct drm_i915_gem_execbuffer2 *args,
3344 struct drm_i915_gem_exec_object2 *exec)
3345 {
3346 struct drm_i915_private *i915 = to_i915(dev);
3347 struct i915_execbuffer eb;
3348 struct dma_fence *in_fence = NULL;
3349 struct sync_file *out_fence = NULL;
3350 int out_fence_fd = -1;
3351 int err;
3352
3353 BUILD_BUG_ON(__EXEC_INTERNAL_FLAGS & ~__I915_EXEC_ILLEGAL_FLAGS);
3354 BUILD_BUG_ON(__EXEC_OBJECT_INTERNAL_FLAGS &
3355 ~__EXEC_OBJECT_UNKNOWN_FLAGS);
3356
3357 eb.i915 = i915;
3358 eb.file = file;
3359 eb.args = args;
3360 if (DBG_FORCE_RELOC || !(args->flags & I915_EXEC_NO_RELOC))
3361 args->flags |= __EXEC_HAS_RELOC;
3362
3363 eb.exec = exec;
3364 eb.vma = (struct eb_vma *)(exec + args->buffer_count + 1);
3365 memset(eb.vma, 0, (args->buffer_count + 1) * sizeof(struct eb_vma));
3366
3367 eb.batch_pool = NULL;
3368
3369 eb.invalid_flags = __EXEC_OBJECT_UNKNOWN_FLAGS;
3370 reloc_cache_init(&eb.reloc_cache, eb.i915);
3371
3372 eb.buffer_count = args->buffer_count;
3373 eb.batch_start_offset = args->batch_start_offset;
3374 eb.trampoline = NULL;
3375
3376 eb.fences = NULL;
3377 eb.num_fences = 0;
3378
3379 eb_capture_list_clear(&eb);
3380
3381 memset(eb.requests, 0, sizeof(struct i915_request *) *
3382 ARRAY_SIZE(eb.requests));
3383 eb.composite_fence = NULL;
3384
3385 eb.batch_flags = 0;
3386 if (args->flags & I915_EXEC_SECURE) {
3387 if (GRAPHICS_VER(i915) >= 11)
3388 return -ENODEV;
3389
3390 /* Return -EPERM to trigger fallback code on old binaries. */
3391 if (!HAS_SECURE_BATCHES(i915))
3392 return -EPERM;
3393
3394 if (!drm_is_current_master(file) || !capable(CAP_SYS_ADMIN))
3395 return -EPERM;
3396
3397 eb.batch_flags |= I915_DISPATCH_SECURE;
3398 }
3399 if (args->flags & I915_EXEC_IS_PINNED)
3400 eb.batch_flags |= I915_DISPATCH_PINNED;
3401
3402 err = parse_execbuf2_extensions(args, &eb);
3403 if (err)
3404 goto err_ext;
3405
3406 err = add_fence_array(&eb);
3407 if (err)
3408 goto err_ext;
3409
3410 #define IN_FENCES (I915_EXEC_FENCE_IN | I915_EXEC_FENCE_SUBMIT)
3411 if (args->flags & IN_FENCES) {
3412 if ((args->flags & IN_FENCES) == IN_FENCES)
3413 return -EINVAL;
3414
3415 in_fence = sync_file_get_fence(lower_32_bits(args->rsvd2));
3416 if (!in_fence) {
3417 err = -EINVAL;
3418 goto err_ext;
3419 }
3420 }
3421 #undef IN_FENCES
3422
3423 if (args->flags & I915_EXEC_FENCE_OUT) {
3424 out_fence_fd = get_unused_fd_flags(O_CLOEXEC);
3425 if (out_fence_fd < 0) {
3426 err = out_fence_fd;
3427 goto err_in_fence;
3428 }
3429 }
3430
3431 err = eb_create(&eb);
3432 if (err)
3433 goto err_out_fence;
3434
3435 GEM_BUG_ON(!eb.lut_size);
3436
3437 err = eb_select_context(&eb);
3438 if (unlikely(err))
3439 goto err_destroy;
3440
3441 err = eb_select_engine(&eb);
3442 if (unlikely(err))
3443 goto err_context;
3444
3445 err = eb_lookup_vmas(&eb);
3446 if (err) {
3447 eb_release_vmas(&eb, true);
3448 goto err_engine;
3449 }
3450
3451 i915_gem_ww_ctx_init(&eb.ww, true);
3452
3453 err = eb_relocate_parse(&eb);
3454 if (err) {
3455 /*
3456 * If the user expects the execobject.offset and
3457 * reloc.presumed_offset to be an exact match,
3458 * as for using NO_RELOC, then we cannot update
3459 * the execobject.offset until we have completed
3460 * relocation.
3461 */
3462 args->flags &= ~__EXEC_HAS_RELOC;
3463 goto err_vma;
3464 }
3465
3466 ww_acquire_done(&eb.ww.ctx);
3467 err = eb_capture_stage(&eb);
3468 if (err)
3469 goto err_vma;
3470
3471 out_fence = eb_requests_create(&eb, in_fence, out_fence_fd);
3472 if (IS_ERR(out_fence)) {
3473 err = PTR_ERR(out_fence);
3474 out_fence = NULL;
3475 if (eb.requests[0])
3476 goto err_request;
3477 else
3478 goto err_vma;
3479 }
3480
3481 err = eb_submit(&eb);
3482
3483 err_request:
3484 eb_requests_get(&eb);
3485 err = eb_requests_add(&eb, err);
3486
3487 if (eb.fences)
3488 signal_fence_array(&eb, eb.composite_fence ?
3489 eb.composite_fence :
3490 &eb.requests[0]->fence);
3491
3492 if (unlikely(eb.gem_context->syncobj)) {
3493 drm_syncobj_replace_fence(eb.gem_context->syncobj,
3494 eb.composite_fence ?
3495 eb.composite_fence :
3496 &eb.requests[0]->fence);
3497 }
3498
3499 if (out_fence) {
3500 if (err == 0) {
3501 fd_install(out_fence_fd, out_fence->file);
3502 args->rsvd2 &= GENMASK_ULL(31, 0); /* keep in-fence */
3503 args->rsvd2 |= (u64)out_fence_fd << 32;
3504 out_fence_fd = -1;
3505 } else {
3506 fput(out_fence->file);
3507 }
3508 }
3509
3510 if (!out_fence && eb.composite_fence)
3511 dma_fence_put(eb.composite_fence);
3512
3513 eb_requests_put(&eb);
3514
3515 err_vma:
3516 eb_release_vmas(&eb, true);
3517 WARN_ON(err == -EDEADLK);
3518 i915_gem_ww_ctx_fini(&eb.ww);
3519
3520 if (eb.batch_pool)
3521 intel_gt_buffer_pool_put(eb.batch_pool);
3522 err_engine:
3523 eb_put_engine(&eb);
3524 err_context:
3525 i915_gem_context_put(eb.gem_context);
3526 err_destroy:
3527 eb_destroy(&eb);
3528 err_out_fence:
3529 if (out_fence_fd != -1)
3530 put_unused_fd(out_fence_fd);
3531 err_in_fence:
3532 dma_fence_put(in_fence);
3533 err_ext:
3534 put_fence_array(eb.fences, eb.num_fences);
3535 return err;
3536 }
3537
eb_element_size(void)3538 static size_t eb_element_size(void)
3539 {
3540 return sizeof(struct drm_i915_gem_exec_object2) + sizeof(struct eb_vma);
3541 }
3542
check_buffer_count(size_t count)3543 static bool check_buffer_count(size_t count)
3544 {
3545 const size_t sz = eb_element_size();
3546
3547 /*
3548 * When using LUT_HANDLE, we impose a limit of INT_MAX for the lookup
3549 * array size (see eb_create()). Otherwise, we can accept an array as
3550 * large as can be addressed (though use large arrays at your peril)!
3551 */
3552
3553 return !(count < 1 || count > INT_MAX || count > SIZE_MAX / sz - 1);
3554 }
3555
3556 int
i915_gem_execbuffer2_ioctl(struct drm_device * dev,void * data,struct drm_file * file)3557 i915_gem_execbuffer2_ioctl(struct drm_device *dev, void *data,
3558 struct drm_file *file)
3559 {
3560 struct drm_i915_private *i915 = to_i915(dev);
3561 struct drm_i915_gem_execbuffer2 *args = data;
3562 struct drm_i915_gem_exec_object2 *exec2_list;
3563 const size_t count = args->buffer_count;
3564 int err;
3565
3566 if (!check_buffer_count(count)) {
3567 drm_dbg(&i915->drm, "execbuf2 with %zd buffers\n", count);
3568 return -EINVAL;
3569 }
3570
3571 err = i915_gem_check_execbuffer(i915, args);
3572 if (err)
3573 return err;
3574
3575 /*
3576 * Allocate extra slots for use by the command parser.
3577 *
3578 * Note that this allocation handles two different arrays (the
3579 * exec2_list array, and the eventual eb.vma array introduced in
3580 * i915_gem_do_execbuffer()), that reside in virtually contiguous
3581 * memory. Also note that the allocation intentionally doesn't fill the
3582 * area with zeros, because the exec2_list part doesn't need to be, as
3583 * it's immediately overwritten by user data a few lines below.
3584 * However, the eb.vma part is explicitly zeroed later in
3585 * i915_gem_do_execbuffer().
3586 */
3587 exec2_list = kvmalloc_array(count + 2, eb_element_size(),
3588 __GFP_NOWARN | GFP_KERNEL);
3589 if (exec2_list == NULL) {
3590 drm_dbg(&i915->drm, "Failed to allocate exec list for %zd buffers\n",
3591 count);
3592 return -ENOMEM;
3593 }
3594 if (copy_from_user(exec2_list,
3595 u64_to_user_ptr(args->buffers_ptr),
3596 sizeof(*exec2_list) * count)) {
3597 drm_dbg(&i915->drm, "copy %zd exec entries failed\n", count);
3598 kvfree(exec2_list);
3599 return -EFAULT;
3600 }
3601
3602 err = i915_gem_do_execbuffer(dev, file, args, exec2_list);
3603
3604 /*
3605 * Now that we have begun execution of the batchbuffer, we ignore
3606 * any new error after this point. Also given that we have already
3607 * updated the associated relocations, we try to write out the current
3608 * object locations irrespective of any error.
3609 */
3610 if (args->flags & __EXEC_HAS_RELOC) {
3611 struct drm_i915_gem_exec_object2 __user *user_exec_list =
3612 u64_to_user_ptr(args->buffers_ptr);
3613 unsigned int i;
3614
3615 /* Copy the new buffer offsets back to the user's exec list. */
3616 /*
3617 * Note: count * sizeof(*user_exec_list) does not overflow,
3618 * because we checked 'count' in check_buffer_count().
3619 *
3620 * And this range already got effectively checked earlier
3621 * when we did the "copy_from_user()" above.
3622 */
3623 if (!user_write_access_begin(user_exec_list,
3624 count * sizeof(*user_exec_list)))
3625 goto end;
3626
3627 for (i = 0; i < args->buffer_count; i++) {
3628 if (!(exec2_list[i].offset & UPDATE))
3629 continue;
3630
3631 exec2_list[i].offset =
3632 gen8_canonical_addr(exec2_list[i].offset & PIN_OFFSET_MASK);
3633 unsafe_put_user(exec2_list[i].offset,
3634 &user_exec_list[i].offset,
3635 end_user);
3636 }
3637 end_user:
3638 user_write_access_end();
3639 end:;
3640 }
3641
3642 args->flags &= ~__I915_EXEC_UNKNOWN_FLAGS;
3643 kvfree(exec2_list);
3644 return err;
3645 }
3646