xref: /linux/drivers/gpu/drm/i915/gem/i915_gem_execbuffer.c (revision 14b482c98dfe9683b12338561a6e9bd44f7337a9)
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 
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 
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
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 
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
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
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
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
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
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 
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 
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 
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 
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 
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 
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 
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))
900 			vma = i915_vma_tryget(vma);
901 		rcu_read_unlock();
902 		if (likely(vma))
903 			return vma;
904 
905 		obj = i915_gem_object_lookup(eb->file, handle);
906 		if (unlikely(!obj))
907 			return ERR_PTR(-ENOENT);
908 
909 		/*
910 		 * If the user has opted-in for protected-object tracking, make
911 		 * sure the object encryption can be used.
912 		 * We only need to do this when the object is first used with
913 		 * this context, because the context itself will be banned when
914 		 * the protected objects become invalid.
915 		 */
916 		if (i915_gem_context_uses_protected_content(eb->gem_context) &&
917 		    i915_gem_object_is_protected(obj)) {
918 			err = intel_pxp_key_check(intel_bo_to_drm_bo(obj), true);
919 			if (err) {
920 				i915_gem_object_put(obj);
921 				return ERR_PTR(err);
922 			}
923 		}
924 
925 		vma = i915_vma_instance(obj, vm, NULL);
926 		if (IS_ERR(vma)) {
927 			i915_gem_object_put(obj);
928 			return vma;
929 		}
930 
931 		err = __eb_add_lut(eb, handle, vma);
932 		if (likely(!err))
933 			return vma;
934 
935 		i915_gem_object_put(obj);
936 		if (err != -EEXIST)
937 			return ERR_PTR(err);
938 	} while (1);
939 }
940 
941 static int eb_lookup_vmas(struct i915_execbuffer *eb)
942 {
943 	unsigned int i, current_batch = 0;
944 	int err = 0;
945 
946 	INIT_LIST_HEAD(&eb->relocs);
947 
948 	for (i = 0; i < eb->buffer_count; i++) {
949 		struct i915_vma *vma;
950 
951 		vma = eb_lookup_vma(eb, eb->exec[i].handle);
952 		if (IS_ERR(vma)) {
953 			err = PTR_ERR(vma);
954 			return err;
955 		}
956 
957 		err = eb_validate_vma(eb, &eb->exec[i], vma);
958 		if (unlikely(err)) {
959 			i915_vma_put(vma);
960 			return err;
961 		}
962 
963 		err = eb_add_vma(eb, &current_batch, i, vma);
964 		if (err)
965 			return err;
966 
967 		if (i915_gem_object_is_userptr(vma->obj)) {
968 			err = i915_gem_object_userptr_submit_init(vma->obj);
969 			if (err)
970 				return err;
971 
972 			eb->vma[i].flags |= __EXEC_OBJECT_USERPTR_INIT;
973 			eb->args->flags |= __EXEC_USERPTR_USED;
974 		}
975 	}
976 
977 	return 0;
978 }
979 
980 static int eb_lock_vmas(struct i915_execbuffer *eb)
981 {
982 	unsigned int i;
983 	int err;
984 
985 	for (i = 0; i < eb->buffer_count; i++) {
986 		struct eb_vma *ev = &eb->vma[i];
987 		struct i915_vma *vma = ev->vma;
988 
989 		err = i915_gem_object_lock(vma->obj, &eb->ww);
990 		if (err)
991 			return err;
992 	}
993 
994 	return 0;
995 }
996 
997 static int eb_validate_vmas(struct i915_execbuffer *eb)
998 {
999 	unsigned int i;
1000 	int err;
1001 
1002 	INIT_LIST_HEAD(&eb->unbound);
1003 
1004 	err = eb_lock_vmas(eb);
1005 	if (err)
1006 		return err;
1007 
1008 	for (i = 0; i < eb->buffer_count; i++) {
1009 		struct drm_i915_gem_exec_object2 *entry = &eb->exec[i];
1010 		struct eb_vma *ev = &eb->vma[i];
1011 		struct i915_vma *vma = ev->vma;
1012 
1013 		err = eb_pin_vma(eb, entry, ev);
1014 		if (err == -EDEADLK)
1015 			return err;
1016 
1017 		if (!err) {
1018 			if (entry->offset != i915_vma_offset(vma)) {
1019 				entry->offset = i915_vma_offset(vma) | UPDATE;
1020 				eb->args->flags |= __EXEC_HAS_RELOC;
1021 			}
1022 		} else {
1023 			eb_unreserve_vma(ev);
1024 
1025 			list_add_tail(&ev->bind_link, &eb->unbound);
1026 			if (drm_mm_node_allocated(&vma->node)) {
1027 				err = i915_vma_unbind(vma);
1028 				if (err)
1029 					return err;
1030 			}
1031 		}
1032 
1033 		/* Reserve enough slots to accommodate composite fences */
1034 		err = dma_resv_reserve_fences(vma->obj->base.resv, eb->num_batches);
1035 		if (err)
1036 			return err;
1037 
1038 		GEM_BUG_ON(drm_mm_node_allocated(&vma->node) &&
1039 			   eb_vma_misplaced(&eb->exec[i], vma, ev->flags));
1040 	}
1041 
1042 	if (!list_empty(&eb->unbound))
1043 		return eb_reserve(eb);
1044 
1045 	return 0;
1046 }
1047 
1048 static struct eb_vma *
1049 eb_get_vma(const struct i915_execbuffer *eb, unsigned long handle)
1050 {
1051 	if (eb->lut_size < 0) {
1052 		if (handle >= -eb->lut_size)
1053 			return NULL;
1054 		return &eb->vma[handle];
1055 	} else {
1056 		struct hlist_head *head;
1057 		struct eb_vma *ev;
1058 
1059 		head = &eb->buckets[hash_32(handle, eb->lut_size)];
1060 		hlist_for_each_entry(ev, head, node) {
1061 			if (ev->handle == handle)
1062 				return ev;
1063 		}
1064 		return NULL;
1065 	}
1066 }
1067 
1068 static void eb_release_vmas(struct i915_execbuffer *eb, bool final)
1069 {
1070 	const unsigned int count = eb->buffer_count;
1071 	unsigned int i;
1072 
1073 	for (i = 0; i < count; i++) {
1074 		struct eb_vma *ev = &eb->vma[i];
1075 		struct i915_vma *vma = ev->vma;
1076 
1077 		if (!vma)
1078 			break;
1079 
1080 		eb_unreserve_vma(ev);
1081 
1082 		if (final)
1083 			i915_vma_put(vma);
1084 	}
1085 
1086 	eb_capture_release(eb);
1087 	eb_unpin_engine(eb);
1088 }
1089 
1090 static void eb_destroy(const struct i915_execbuffer *eb)
1091 {
1092 	if (eb->lut_size > 0)
1093 		kfree(eb->buckets);
1094 }
1095 
1096 static u64
1097 relocation_target(const struct drm_i915_gem_relocation_entry *reloc,
1098 		  const struct i915_vma *target)
1099 {
1100 	return gen8_canonical_addr((int)reloc->delta + i915_vma_offset(target));
1101 }
1102 
1103 static void reloc_cache_init(struct reloc_cache *cache,
1104 			     struct drm_i915_private *i915)
1105 {
1106 	cache->page = -1;
1107 	cache->vaddr = 0;
1108 	/* Must be a variable in the struct to allow GCC to unroll. */
1109 	cache->graphics_ver = GRAPHICS_VER(i915);
1110 	cache->has_llc = HAS_LLC(i915);
1111 	cache->use_64bit_reloc = HAS_64BIT_RELOC(i915);
1112 	cache->has_fence = cache->graphics_ver < 4;
1113 	cache->needs_unfenced = INTEL_INFO(i915)->unfenced_needs_alignment;
1114 	cache->node.flags = 0;
1115 }
1116 
1117 static void *unmask_page(unsigned long p)
1118 {
1119 	return (void *)(uintptr_t)(p & PAGE_MASK);
1120 }
1121 
1122 static unsigned int unmask_flags(unsigned long p)
1123 {
1124 	return p & ~PAGE_MASK;
1125 }
1126 
1127 #define KMAP 0x4 /* after CLFLUSH_FLAGS */
1128 
1129 static struct i915_ggtt *cache_to_ggtt(struct reloc_cache *cache)
1130 {
1131 	struct drm_i915_private *i915 =
1132 		container_of(cache, struct i915_execbuffer, reloc_cache)->i915;
1133 	return to_gt(i915)->ggtt;
1134 }
1135 
1136 static void reloc_cache_unmap(struct reloc_cache *cache)
1137 {
1138 	void *vaddr;
1139 
1140 	if (!cache->vaddr)
1141 		return;
1142 
1143 	vaddr = unmask_page(cache->vaddr);
1144 	if (cache->vaddr & KMAP)
1145 		kunmap_local(vaddr);
1146 	else
1147 		io_mapping_unmap_atomic((void __iomem *)vaddr);
1148 }
1149 
1150 static void reloc_cache_remap(struct reloc_cache *cache,
1151 			      struct drm_i915_gem_object *obj)
1152 {
1153 	void *vaddr;
1154 
1155 	if (!cache->vaddr)
1156 		return;
1157 
1158 	if (cache->vaddr & KMAP) {
1159 		struct page *page = i915_gem_object_get_page(obj, cache->page);
1160 
1161 		vaddr = kmap_local_page(page);
1162 		cache->vaddr = unmask_flags(cache->vaddr) |
1163 			(unsigned long)vaddr;
1164 	} else {
1165 		struct i915_ggtt *ggtt = cache_to_ggtt(cache);
1166 		unsigned long offset;
1167 
1168 		offset = cache->node.start;
1169 		if (!drm_mm_node_allocated(&cache->node))
1170 			offset += cache->page << PAGE_SHIFT;
1171 
1172 		cache->vaddr = (unsigned long)
1173 			io_mapping_map_atomic_wc(&ggtt->iomap, offset);
1174 	}
1175 }
1176 
1177 static void reloc_cache_reset(struct reloc_cache *cache, struct i915_execbuffer *eb)
1178 {
1179 	void *vaddr;
1180 
1181 	if (!cache->vaddr)
1182 		return;
1183 
1184 	vaddr = unmask_page(cache->vaddr);
1185 	if (cache->vaddr & KMAP) {
1186 		struct drm_i915_gem_object *obj =
1187 			(struct drm_i915_gem_object *)cache->node.mm;
1188 		if (cache->vaddr & CLFLUSH_AFTER)
1189 			mb();
1190 
1191 		kunmap_local(vaddr);
1192 		i915_gem_object_finish_access(obj);
1193 	} else {
1194 		struct i915_ggtt *ggtt = cache_to_ggtt(cache);
1195 
1196 		intel_gt_flush_ggtt_writes(ggtt->vm.gt);
1197 		io_mapping_unmap_atomic((void __iomem *)vaddr);
1198 
1199 		if (drm_mm_node_allocated(&cache->node)) {
1200 			ggtt->vm.clear_range(&ggtt->vm,
1201 					     cache->node.start,
1202 					     cache->node.size);
1203 			mutex_lock(&ggtt->vm.mutex);
1204 			drm_mm_remove_node(&cache->node);
1205 			mutex_unlock(&ggtt->vm.mutex);
1206 		} else {
1207 			i915_vma_unpin((struct i915_vma *)cache->node.mm);
1208 		}
1209 	}
1210 
1211 	cache->vaddr = 0;
1212 	cache->page = -1;
1213 }
1214 
1215 static void *reloc_kmap(struct drm_i915_gem_object *obj,
1216 			struct reloc_cache *cache,
1217 			unsigned long pageno)
1218 {
1219 	void *vaddr;
1220 	struct page *page;
1221 
1222 	if (cache->vaddr) {
1223 		kunmap_local(unmask_page(cache->vaddr));
1224 	} else {
1225 		unsigned int flushes;
1226 		int err;
1227 
1228 		err = i915_gem_object_prepare_write(obj, &flushes);
1229 		if (err)
1230 			return ERR_PTR(err);
1231 
1232 		BUILD_BUG_ON(KMAP & CLFLUSH_FLAGS);
1233 		BUILD_BUG_ON((KMAP | CLFLUSH_FLAGS) & PAGE_MASK);
1234 
1235 		cache->vaddr = flushes | KMAP;
1236 		cache->node.mm = (void *)obj;
1237 		if (flushes)
1238 			mb();
1239 	}
1240 
1241 	page = i915_gem_object_get_page(obj, pageno);
1242 	if (!obj->mm.dirty)
1243 		set_page_dirty(page);
1244 
1245 	vaddr = kmap_local_page(page);
1246 	cache->vaddr = unmask_flags(cache->vaddr) | (unsigned long)vaddr;
1247 	cache->page = pageno;
1248 
1249 	return vaddr;
1250 }
1251 
1252 static void *reloc_iomap(struct i915_vma *batch,
1253 			 struct i915_execbuffer *eb,
1254 			 unsigned long page)
1255 {
1256 	struct drm_i915_gem_object *obj = batch->obj;
1257 	struct reloc_cache *cache = &eb->reloc_cache;
1258 	struct i915_ggtt *ggtt = cache_to_ggtt(cache);
1259 	unsigned long offset;
1260 	void *vaddr;
1261 
1262 	if (cache->vaddr) {
1263 		intel_gt_flush_ggtt_writes(ggtt->vm.gt);
1264 		io_mapping_unmap_atomic((void __force __iomem *) unmask_page(cache->vaddr));
1265 	} else {
1266 		struct i915_vma *vma = ERR_PTR(-ENODEV);
1267 		int err;
1268 
1269 		if (i915_gem_object_is_tiled(obj))
1270 			return ERR_PTR(-EINVAL);
1271 
1272 		if (use_cpu_reloc(cache, obj))
1273 			return NULL;
1274 
1275 		err = i915_gem_object_set_to_gtt_domain(obj, true);
1276 		if (err)
1277 			return ERR_PTR(err);
1278 
1279 		/*
1280 		 * i915_gem_object_ggtt_pin_ww may attempt to remove the batch
1281 		 * VMA from the object list because we no longer pin.
1282 		 *
1283 		 * Only attempt to pin the batch buffer to ggtt if the current batch
1284 		 * is not inside ggtt, or the batch buffer is not misplaced.
1285 		 */
1286 		if (!i915_is_ggtt(batch->vm) ||
1287 		    !i915_vma_misplaced(batch, 0, 0, PIN_MAPPABLE)) {
1288 			vma = i915_gem_object_ggtt_pin_ww(obj, &eb->ww, NULL, 0, 0,
1289 							  PIN_MAPPABLE |
1290 							  PIN_NONBLOCK /* NOWARN */ |
1291 							  PIN_NOEVICT);
1292 		}
1293 
1294 		if (vma == ERR_PTR(-EDEADLK))
1295 			return vma;
1296 
1297 		if (IS_ERR(vma)) {
1298 			memset(&cache->node, 0, sizeof(cache->node));
1299 			mutex_lock(&ggtt->vm.mutex);
1300 			err = drm_mm_insert_node_in_range
1301 				(&ggtt->vm.mm, &cache->node,
1302 				 PAGE_SIZE, 0, I915_COLOR_UNEVICTABLE,
1303 				 0, ggtt->mappable_end,
1304 				 DRM_MM_INSERT_LOW);
1305 			mutex_unlock(&ggtt->vm.mutex);
1306 			if (err) /* no inactive aperture space, use cpu reloc */
1307 				return NULL;
1308 		} else {
1309 			cache->node.start = i915_ggtt_offset(vma);
1310 			cache->node.mm = (void *)vma;
1311 		}
1312 	}
1313 
1314 	offset = cache->node.start;
1315 	if (drm_mm_node_allocated(&cache->node)) {
1316 		ggtt->vm.insert_page(&ggtt->vm,
1317 				     i915_gem_object_get_dma_address(obj, page),
1318 				     offset,
1319 				     i915_gem_get_pat_index(ggtt->vm.i915,
1320 							    I915_CACHE_NONE),
1321 				     0);
1322 	} else {
1323 		offset += page << PAGE_SHIFT;
1324 	}
1325 
1326 	vaddr = (void __force *)io_mapping_map_atomic_wc(&ggtt->iomap,
1327 							 offset);
1328 	cache->page = page;
1329 	cache->vaddr = (unsigned long)vaddr;
1330 
1331 	return vaddr;
1332 }
1333 
1334 static void *reloc_vaddr(struct i915_vma *vma,
1335 			 struct i915_execbuffer *eb,
1336 			 unsigned long page)
1337 {
1338 	struct reloc_cache *cache = &eb->reloc_cache;
1339 	void *vaddr;
1340 
1341 	if (cache->page == page) {
1342 		vaddr = unmask_page(cache->vaddr);
1343 	} else {
1344 		vaddr = NULL;
1345 		if ((cache->vaddr & KMAP) == 0)
1346 			vaddr = reloc_iomap(vma, eb, page);
1347 		if (!vaddr)
1348 			vaddr = reloc_kmap(vma->obj, cache, page);
1349 	}
1350 
1351 	return vaddr;
1352 }
1353 
1354 static void clflush_write32(u32 *addr, u32 value, unsigned int flushes)
1355 {
1356 	if (unlikely(flushes & (CLFLUSH_BEFORE | CLFLUSH_AFTER))) {
1357 		if (flushes & CLFLUSH_BEFORE)
1358 			drm_clflush_virt_range(addr, sizeof(*addr));
1359 
1360 		*addr = value;
1361 
1362 		/*
1363 		 * Writes to the same cacheline are serialised by the CPU
1364 		 * (including clflush). On the write path, we only require
1365 		 * that it hits memory in an orderly fashion and place
1366 		 * mb barriers at the start and end of the relocation phase
1367 		 * to ensure ordering of clflush wrt to the system.
1368 		 */
1369 		if (flushes & CLFLUSH_AFTER)
1370 			drm_clflush_virt_range(addr, sizeof(*addr));
1371 	} else {
1372 		*addr = value;
1373 	}
1374 }
1375 
1376 static u64
1377 relocate_entry(struct i915_vma *vma,
1378 	       const struct drm_i915_gem_relocation_entry *reloc,
1379 	       struct i915_execbuffer *eb,
1380 	       const struct i915_vma *target)
1381 {
1382 	u64 target_addr = relocation_target(reloc, target);
1383 	u64 offset = reloc->offset;
1384 	bool wide = eb->reloc_cache.use_64bit_reloc;
1385 	void *vaddr;
1386 
1387 repeat:
1388 	vaddr = reloc_vaddr(vma, eb,
1389 			    offset >> PAGE_SHIFT);
1390 	if (IS_ERR(vaddr))
1391 		return PTR_ERR(vaddr);
1392 
1393 	GEM_BUG_ON(!IS_ALIGNED(offset, sizeof(u32)));
1394 	clflush_write32(vaddr + offset_in_page(offset),
1395 			lower_32_bits(target_addr),
1396 			eb->reloc_cache.vaddr);
1397 
1398 	if (wide) {
1399 		offset += sizeof(u32);
1400 		target_addr >>= 32;
1401 		wide = false;
1402 		goto repeat;
1403 	}
1404 
1405 	return target->node.start | UPDATE;
1406 }
1407 
1408 static u64
1409 eb_relocate_entry(struct i915_execbuffer *eb,
1410 		  struct eb_vma *ev,
1411 		  const struct drm_i915_gem_relocation_entry *reloc)
1412 {
1413 	struct drm_i915_private *i915 = eb->i915;
1414 	struct eb_vma *target;
1415 	int err;
1416 
1417 	/* we've already hold a reference to all valid objects */
1418 	target = eb_get_vma(eb, reloc->target_handle);
1419 	if (unlikely(!target))
1420 		return -ENOENT;
1421 
1422 	/* Validate that the target is in a valid r/w GPU domain */
1423 	if (unlikely(reloc->write_domain & (reloc->write_domain - 1))) {
1424 		drm_dbg(&i915->drm, "reloc with multiple write domains: "
1425 			  "target %d offset %d "
1426 			  "read %08x write %08x\n",
1427 			  reloc->target_handle,
1428 			  (int) reloc->offset,
1429 			  reloc->read_domains,
1430 			  reloc->write_domain);
1431 		return -EINVAL;
1432 	}
1433 	if (unlikely((reloc->write_domain | reloc->read_domains)
1434 		     & ~I915_GEM_GPU_DOMAINS)) {
1435 		drm_dbg(&i915->drm, "reloc with read/write non-GPU domains: "
1436 			  "target %d offset %d "
1437 			  "read %08x write %08x\n",
1438 			  reloc->target_handle,
1439 			  (int) reloc->offset,
1440 			  reloc->read_domains,
1441 			  reloc->write_domain);
1442 		return -EINVAL;
1443 	}
1444 
1445 	if (reloc->write_domain) {
1446 		target->flags |= EXEC_OBJECT_WRITE;
1447 
1448 		/*
1449 		 * Sandybridge PPGTT errata: We need a global gtt mapping
1450 		 * for MI and pipe_control writes because the gpu doesn't
1451 		 * properly redirect them through the ppgtt for non_secure
1452 		 * batchbuffers.
1453 		 */
1454 		if (reloc->write_domain == I915_GEM_DOMAIN_INSTRUCTION &&
1455 		    GRAPHICS_VER(eb->i915) == 6 &&
1456 		    !i915_vma_is_bound(target->vma, I915_VMA_GLOBAL_BIND)) {
1457 			struct i915_vma *vma = target->vma;
1458 
1459 			reloc_cache_unmap(&eb->reloc_cache);
1460 			mutex_lock(&vma->vm->mutex);
1461 			err = i915_vma_bind(target->vma,
1462 					    target->vma->obj->pat_index,
1463 					    PIN_GLOBAL, NULL, NULL);
1464 			mutex_unlock(&vma->vm->mutex);
1465 			reloc_cache_remap(&eb->reloc_cache, ev->vma->obj);
1466 			if (err)
1467 				return err;
1468 		}
1469 	}
1470 
1471 	/*
1472 	 * If the relocation already has the right value in it, no
1473 	 * more work needs to be done.
1474 	 */
1475 	if (!DBG_FORCE_RELOC &&
1476 	    gen8_canonical_addr(i915_vma_offset(target->vma)) == reloc->presumed_offset)
1477 		return 0;
1478 
1479 	/* Check that the relocation address is valid... */
1480 	if (unlikely(reloc->offset >
1481 		     ev->vma->size - (eb->reloc_cache.use_64bit_reloc ? 8 : 4))) {
1482 		drm_dbg(&i915->drm, "Relocation beyond object bounds: "
1483 			  "target %d offset %d size %d.\n",
1484 			  reloc->target_handle,
1485 			  (int)reloc->offset,
1486 			  (int)ev->vma->size);
1487 		return -EINVAL;
1488 	}
1489 	if (unlikely(reloc->offset & 3)) {
1490 		drm_dbg(&i915->drm, "Relocation not 4-byte aligned: "
1491 			  "target %d offset %d.\n",
1492 			  reloc->target_handle,
1493 			  (int)reloc->offset);
1494 		return -EINVAL;
1495 	}
1496 
1497 	/*
1498 	 * If we write into the object, we need to force the synchronisation
1499 	 * barrier, either with an asynchronous clflush or if we executed the
1500 	 * patching using the GPU (though that should be serialised by the
1501 	 * timeline). To be completely sure, and since we are required to
1502 	 * do relocations we are already stalling, disable the user's opt
1503 	 * out of our synchronisation.
1504 	 */
1505 	ev->flags &= ~EXEC_OBJECT_ASYNC;
1506 
1507 	/* and update the user's relocation entry */
1508 	return relocate_entry(ev->vma, reloc, eb, target->vma);
1509 }
1510 
1511 static int eb_relocate_vma(struct i915_execbuffer *eb, struct eb_vma *ev)
1512 {
1513 #define N_RELOC(x) ((x) / sizeof(struct drm_i915_gem_relocation_entry))
1514 	struct drm_i915_gem_relocation_entry stack[N_RELOC(512)];
1515 	const struct drm_i915_gem_exec_object2 *entry = ev->exec;
1516 	struct drm_i915_gem_relocation_entry __user *urelocs =
1517 		u64_to_user_ptr(entry->relocs_ptr);
1518 	unsigned long remain = entry->relocation_count;
1519 
1520 	if (unlikely(remain > N_RELOC(INT_MAX)))
1521 		return -EINVAL;
1522 
1523 	/*
1524 	 * We must check that the entire relocation array is safe
1525 	 * to read. Whether it is also writable only shows when we
1526 	 * write back the presumed offsets below, and if that fails we
1527 	 * fall back to the slow path.
1528 	 */
1529 	if (unlikely(!access_ok(urelocs, remain * sizeof(*urelocs))))
1530 		return -EFAULT;
1531 
1532 	do {
1533 		struct drm_i915_gem_relocation_entry *r = stack;
1534 		unsigned int count =
1535 			min_t(unsigned long, remain, ARRAY_SIZE(stack));
1536 		unsigned int copied;
1537 
1538 		/*
1539 		 * This is the fast path and we cannot handle a pagefault
1540 		 * whilst holding the struct mutex lest the user pass in the
1541 		 * relocations contained within a mmaped bo. For in such a case
1542 		 * we, the page fault handler would call i915_gem_fault() and
1543 		 * we would try to acquire the struct mutex again. Obviously
1544 		 * this is bad and so lockdep complains vehemently.
1545 		 */
1546 		pagefault_disable();
1547 		copied = __copy_from_user_inatomic(r, urelocs, count * sizeof(r[0]));
1548 		pagefault_enable();
1549 		if (unlikely(copied)) {
1550 			remain = -EFAULT;
1551 			goto out;
1552 		}
1553 
1554 		remain -= count;
1555 		do {
1556 			u64 offset = eb_relocate_entry(eb, ev, r);
1557 			int err;
1558 
1559 			if (likely(offset == 0))
1560 				continue;
1561 
1562 			if ((s64)offset < 0) {
1563 				remain = (int)offset;
1564 				goto out;
1565 			}
1566 			/*
1567 			 * Write back the presumed offset. We hold the
1568 			 * objects' dma_resv locks here, so this must not
1569 			 * take a page fault: that would take mmap_lock
1570 			 * under dma_resv, the opposite of the order our
1571 			 * own fault handler uses.
1572 			 *
1573 			 * If the write fails (the page is read-only,
1574 			 * copy-on-write, or gone since we read it), we
1575 			 * must not just carry on. We have already changed
1576 			 * the relocation value inside the object, and a
1577 			 * stale presumed_offset could later match again
1578 			 * and make us skip a relocation that is needed,
1579 			 * hanging the GPU. So fall back to the slow path,
1580 			 * as for a failed read: it retries after
1581 			 * prefaulting and, failing that, marks every
1582 			 * presumed_offset invalid with faults allowed and
1583 			 * no locks held.
1584 			 */
1585 			offset = gen8_canonical_addr(offset & ~UPDATE);
1586 			pagefault_disable();
1587 			err = put_user(offset, &urelocs[r - stack].presumed_offset);
1588 			pagefault_enable();
1589 
1590 			/*
1591 			 * Error handling is disabled on purpose. No, it makes
1592 			 * no sense, and the code will loop over the relocations
1593 			 * without writing them back and just waste CPU time,
1594 			 * but that's apparently what the mprotect test-cases
1595 			 * want. See commit 97a37c919f62 ("drm/i915/gem: Ignore
1596 			 * readonly failures when updating relocs")
1597 			 */
1598 			if (unlikely(err) && 0) {
1599 				remain = -EFAULT;
1600 				goto out;
1601 			}
1602 		} while (r++, --count);
1603 		urelocs += ARRAY_SIZE(stack);
1604 	} while (remain);
1605 out:
1606 	reloc_cache_reset(&eb->reloc_cache, eb);
1607 	return remain;
1608 }
1609 
1610 static int
1611 eb_relocate_vma_slow(struct i915_execbuffer *eb, struct eb_vma *ev)
1612 {
1613 	const struct drm_i915_gem_exec_object2 *entry = ev->exec;
1614 	struct drm_i915_gem_relocation_entry *relocs =
1615 		u64_to_ptr(typeof(*relocs), entry->relocs_ptr);
1616 	unsigned int i;
1617 	int err;
1618 
1619 	for (i = 0; i < entry->relocation_count; i++) {
1620 		u64 offset = eb_relocate_entry(eb, ev, &relocs[i]);
1621 
1622 		if ((s64)offset < 0) {
1623 			err = (int)offset;
1624 			goto err;
1625 		}
1626 	}
1627 	err = 0;
1628 err:
1629 	reloc_cache_reset(&eb->reloc_cache, eb);
1630 	return err;
1631 }
1632 
1633 static int check_relocations(const struct drm_i915_gem_exec_object2 *entry)
1634 {
1635 	const char __user *addr, *end;
1636 	unsigned long size;
1637 	char __maybe_unused c;
1638 
1639 	size = entry->relocation_count;
1640 	if (size == 0)
1641 		return 0;
1642 
1643 	if (size > N_RELOC(INT_MAX))
1644 		return -EINVAL;
1645 
1646 	addr = u64_to_user_ptr(entry->relocs_ptr);
1647 	size *= sizeof(struct drm_i915_gem_relocation_entry);
1648 	if (!access_ok(addr, size))
1649 		return -EFAULT;
1650 
1651 	end = addr + size;
1652 	for (; addr < end; addr += PAGE_SIZE) {
1653 		int err = get_user(c, addr);
1654 		if (err)
1655 			return err;
1656 	}
1657 	return get_user(c, end - 1);
1658 }
1659 
1660 static int eb_copy_relocations(const struct i915_execbuffer *eb)
1661 {
1662 	struct drm_i915_gem_relocation_entry *relocs;
1663 	const unsigned int count = eb->buffer_count;
1664 	unsigned int i;
1665 	int err;
1666 
1667 	for (i = 0; i < count; i++) {
1668 		const unsigned int nreloc = eb->exec[i].relocation_count;
1669 		struct drm_i915_gem_relocation_entry __user *urelocs;
1670 		unsigned long size;
1671 		unsigned long copied;
1672 
1673 		if (nreloc == 0)
1674 			continue;
1675 
1676 		err = check_relocations(&eb->exec[i]);
1677 		if (err)
1678 			goto err;
1679 
1680 		urelocs = u64_to_user_ptr(eb->exec[i].relocs_ptr);
1681 		size = nreloc * sizeof(*relocs);
1682 
1683 		relocs = kvmalloc_array(1, size, GFP_KERNEL);
1684 		if (!relocs) {
1685 			err = -ENOMEM;
1686 			goto err;
1687 		}
1688 
1689 		/* copy_from_user is limited to < 4GiB */
1690 		copied = 0;
1691 		do {
1692 			unsigned int len =
1693 				min_t(u64, BIT_ULL(31), size - copied);
1694 
1695 			if (__copy_from_user((char *)relocs + copied,
1696 					     (char __user *)urelocs + copied,
1697 					     len))
1698 				goto end;
1699 
1700 			copied += len;
1701 		} while (copied < size);
1702 
1703 		/*
1704 		 * As we do not update the known relocation offsets after
1705 		 * relocating (due to the complexities in lock handling),
1706 		 * we need to mark them as invalid now so that we force the
1707 		 * relocation processing next time. Just in case the target
1708 		 * object is evicted and then rebound into its old
1709 		 * presumed_offset before the next execbuffer - if that
1710 		 * happened we would make the mistake of assuming that the
1711 		 * relocations were valid.
1712 		 */
1713 		if (!user_access_begin(urelocs, size))
1714 			goto end;
1715 
1716 		for (copied = 0; copied < nreloc; copied++)
1717 			unsafe_put_user(-1,
1718 					&urelocs[copied].presumed_offset,
1719 					end_user);
1720 		user_access_end();
1721 
1722 		eb->exec[i].relocs_ptr = (uintptr_t)relocs;
1723 	}
1724 
1725 	return 0;
1726 
1727 end_user:
1728 	user_access_end();
1729 end:
1730 	kvfree(relocs);
1731 	err = -EFAULT;
1732 err:
1733 	while (i--) {
1734 		relocs = u64_to_ptr(typeof(*relocs), eb->exec[i].relocs_ptr);
1735 		if (eb->exec[i].relocation_count)
1736 			kvfree(relocs);
1737 	}
1738 	return err;
1739 }
1740 
1741 static int eb_prefault_relocations(const struct i915_execbuffer *eb)
1742 {
1743 	const unsigned int count = eb->buffer_count;
1744 	unsigned int i;
1745 
1746 	for (i = 0; i < count; i++) {
1747 		int err;
1748 
1749 		err = check_relocations(&eb->exec[i]);
1750 		if (err)
1751 			return err;
1752 	}
1753 
1754 	return 0;
1755 }
1756 
1757 static int eb_reinit_userptr(struct i915_execbuffer *eb)
1758 {
1759 	const unsigned int count = eb->buffer_count;
1760 	unsigned int i;
1761 	int ret;
1762 
1763 	if (likely(!(eb->args->flags & __EXEC_USERPTR_USED)))
1764 		return 0;
1765 
1766 	for (i = 0; i < count; i++) {
1767 		struct eb_vma *ev = &eb->vma[i];
1768 
1769 		if (!i915_gem_object_is_userptr(ev->vma->obj))
1770 			continue;
1771 
1772 		ret = i915_gem_object_userptr_submit_init(ev->vma->obj);
1773 		if (ret)
1774 			return ret;
1775 
1776 		ev->flags |= __EXEC_OBJECT_USERPTR_INIT;
1777 	}
1778 
1779 	return 0;
1780 }
1781 
1782 static noinline int eb_relocate_parse_slow(struct i915_execbuffer *eb)
1783 {
1784 	const unsigned int count = eb->buffer_count;
1785 	bool have_copy = false;
1786 	struct eb_vma *ev;
1787 	int err = 0;
1788 
1789 repeat:
1790 	if (signal_pending(current)) {
1791 		err = -ERESTARTSYS;
1792 		goto out;
1793 	}
1794 
1795 	/* We may process another execbuffer during the unlock... */
1796 	eb_release_vmas(eb, false);
1797 	i915_gem_ww_ctx_fini(&eb->ww);
1798 
1799 	/*
1800 	 * We take 3 passes through the slowpatch.
1801 	 *
1802 	 * 1 - we try to just prefault all the user relocation entries and
1803 	 * then attempt to reuse the atomic pagefault disabled fast path again.
1804 	 *
1805 	 * 2 - we copy the user entries to a local buffer here outside of the
1806 	 * local and allow ourselves to wait upon any rendering before
1807 	 * relocations
1808 	 *
1809 	 * 3 - we already have a local copy of the relocation entries, but
1810 	 * were interrupted (EAGAIN) whilst waiting for the objects, try again.
1811 	 */
1812 	if (!err) {
1813 		err = eb_prefault_relocations(eb);
1814 	} else if (!have_copy) {
1815 		err = eb_copy_relocations(eb);
1816 		have_copy = err == 0;
1817 	} else {
1818 		cond_resched();
1819 		err = 0;
1820 	}
1821 
1822 	if (!err)
1823 		err = eb_reinit_userptr(eb);
1824 
1825 	i915_gem_ww_ctx_init(&eb->ww, true);
1826 	if (err)
1827 		goto out;
1828 
1829 	/* reacquire the objects */
1830 repeat_validate:
1831 	err = eb_pin_engine(eb, false);
1832 	if (err)
1833 		goto err;
1834 
1835 	err = eb_validate_vmas(eb);
1836 	if (err)
1837 		goto err;
1838 
1839 	GEM_BUG_ON(!eb->batches[0]);
1840 
1841 	list_for_each_entry(ev, &eb->relocs, reloc_link) {
1842 		if (!have_copy) {
1843 			err = eb_relocate_vma(eb, ev);
1844 			if (err)
1845 				break;
1846 		} else {
1847 			err = eb_relocate_vma_slow(eb, ev);
1848 			if (err)
1849 				break;
1850 		}
1851 	}
1852 
1853 	if (err == -EDEADLK)
1854 		goto err;
1855 
1856 	if (err && !have_copy)
1857 		goto repeat;
1858 
1859 	if (err)
1860 		goto err;
1861 
1862 	/* as last step, parse the command buffer */
1863 	err = eb_parse(eb);
1864 	if (err)
1865 		goto err;
1866 
1867 	/*
1868 	 * Leave the user relocations as are, this is the painfully slow path,
1869 	 * and we want to avoid the complication of dropping the lock whilst
1870 	 * having buffers reserved in the aperture and so causing spurious
1871 	 * ENOSPC for random operations.
1872 	 */
1873 
1874 err:
1875 	if (err == -EDEADLK) {
1876 		eb_release_vmas(eb, false);
1877 		err = i915_gem_ww_ctx_backoff(&eb->ww);
1878 		if (!err)
1879 			goto repeat_validate;
1880 	}
1881 
1882 	if (err == -EAGAIN)
1883 		goto repeat;
1884 
1885 out:
1886 	if (have_copy) {
1887 		unsigned int i;
1888 
1889 		for (i = 0; i < count; i++) {
1890 			const struct drm_i915_gem_exec_object2 *entry =
1891 				&eb->exec[i];
1892 			struct drm_i915_gem_relocation_entry *relocs;
1893 
1894 			if (!entry->relocation_count)
1895 				continue;
1896 
1897 			relocs = u64_to_ptr(typeof(*relocs), entry->relocs_ptr);
1898 			kvfree(relocs);
1899 		}
1900 	}
1901 
1902 	return err;
1903 }
1904 
1905 static int eb_relocate_parse(struct i915_execbuffer *eb)
1906 {
1907 	int err;
1908 	bool throttle = true;
1909 
1910 retry:
1911 	err = eb_pin_engine(eb, throttle);
1912 	if (err) {
1913 		if (err != -EDEADLK)
1914 			return err;
1915 
1916 		goto err;
1917 	}
1918 
1919 	/* only throttle once, even if we didn't need to throttle */
1920 	throttle = false;
1921 
1922 	err = eb_validate_vmas(eb);
1923 	if (err == -EAGAIN)
1924 		goto slow;
1925 	else if (err)
1926 		goto err;
1927 
1928 	/* The objects are in their final locations, apply the relocations. */
1929 	if (eb->args->flags & __EXEC_HAS_RELOC) {
1930 		struct eb_vma *ev;
1931 
1932 		list_for_each_entry(ev, &eb->relocs, reloc_link) {
1933 			err = eb_relocate_vma(eb, ev);
1934 			if (err)
1935 				break;
1936 		}
1937 
1938 		if (err == -EDEADLK)
1939 			goto err;
1940 		else if (err)
1941 			goto slow;
1942 	}
1943 
1944 	if (!err)
1945 		err = eb_parse(eb);
1946 
1947 err:
1948 	if (err == -EDEADLK) {
1949 		eb_release_vmas(eb, false);
1950 		err = i915_gem_ww_ctx_backoff(&eb->ww);
1951 		if (!err)
1952 			goto retry;
1953 	}
1954 
1955 	return err;
1956 
1957 slow:
1958 	err = eb_relocate_parse_slow(eb);
1959 	if (err)
1960 		/*
1961 		 * If the user expects the execobject.offset and
1962 		 * reloc.presumed_offset to be an exact match,
1963 		 * as for using NO_RELOC, then we cannot update
1964 		 * the execobject.offset until we have completed
1965 		 * relocation.
1966 		 */
1967 		eb->args->flags &= ~__EXEC_HAS_RELOC;
1968 
1969 	return err;
1970 }
1971 
1972 /*
1973  * Using two helper loops for the order of which requests / batches are created
1974  * and added the to backend. Requests are created in order from the parent to
1975  * the last child. Requests are added in the reverse order, from the last child
1976  * to parent. This is done for locking reasons as the timeline lock is acquired
1977  * during request creation and released when the request is added to the
1978  * backend. To make lockdep happy (see intel_context_timeline_lock) this must be
1979  * the ordering.
1980  */
1981 #define for_each_batch_create_order(_eb, _i) \
1982 	for ((_i) = 0; (_i) < (_eb)->num_batches; ++(_i))
1983 #define for_each_batch_add_order(_eb, _i) \
1984 	BUILD_BUG_ON(!typecheck(int, _i)); \
1985 	for ((_i) = (_eb)->num_batches - 1; (_i) >= 0; --(_i))
1986 
1987 static struct i915_request *
1988 eb_find_first_request_added(struct i915_execbuffer *eb)
1989 {
1990 	int i;
1991 
1992 	for_each_batch_add_order(eb, i)
1993 		if (eb->requests[i])
1994 			return eb->requests[i];
1995 
1996 	GEM_BUG_ON("Request not found");
1997 
1998 	return NULL;
1999 }
2000 
2001 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
2002 
2003 /* Stage with GFP_KERNEL allocations before we enter the signaling critical path */
2004 static int eb_capture_stage(struct i915_execbuffer *eb)
2005 {
2006 	const unsigned int count = eb->buffer_count;
2007 	unsigned int i = count, j;
2008 
2009 	while (i--) {
2010 		struct eb_vma *ev = &eb->vma[i];
2011 		struct i915_vma *vma = ev->vma;
2012 		unsigned int flags = ev->flags;
2013 
2014 		if (!(flags & EXEC_OBJECT_CAPTURE))
2015 			continue;
2016 
2017 		if (i915_gem_context_is_recoverable(eb->gem_context) &&
2018 		    (IS_DGFX(eb->i915) || GRAPHICS_VER_FULL(eb->i915) > IP_VER(12, 0)))
2019 			return -EINVAL;
2020 
2021 		for_each_batch_create_order(eb, j) {
2022 			struct i915_capture_list *capture;
2023 
2024 			capture = kmalloc_obj(*capture);
2025 			if (!capture)
2026 				continue;
2027 
2028 			capture->next = eb->capture_lists[j];
2029 			capture->vma_res = i915_vma_resource_get(vma->resource);
2030 			eb->capture_lists[j] = capture;
2031 		}
2032 	}
2033 
2034 	return 0;
2035 }
2036 
2037 /* Commit once we're in the critical path */
2038 static void eb_capture_commit(struct i915_execbuffer *eb)
2039 {
2040 	unsigned int j;
2041 
2042 	for_each_batch_create_order(eb, j) {
2043 		struct i915_request *rq = eb->requests[j];
2044 
2045 		if (!rq)
2046 			break;
2047 
2048 		rq->capture_list = eb->capture_lists[j];
2049 		eb->capture_lists[j] = NULL;
2050 	}
2051 }
2052 
2053 /*
2054  * Release anything that didn't get committed due to errors.
2055  * The capture_list will otherwise be freed at request retire.
2056  */
2057 static void eb_capture_release(struct i915_execbuffer *eb)
2058 {
2059 	unsigned int j;
2060 
2061 	for_each_batch_create_order(eb, j) {
2062 		if (eb->capture_lists[j]) {
2063 			i915_request_free_capture_list(eb->capture_lists[j]);
2064 			eb->capture_lists[j] = NULL;
2065 		}
2066 	}
2067 }
2068 
2069 static void eb_capture_list_clear(struct i915_execbuffer *eb)
2070 {
2071 	memset(eb->capture_lists, 0, sizeof(eb->capture_lists));
2072 }
2073 
2074 #else
2075 
2076 static int eb_capture_stage(struct i915_execbuffer *eb)
2077 {
2078 	return 0;
2079 }
2080 
2081 static void eb_capture_commit(struct i915_execbuffer *eb)
2082 {
2083 }
2084 
2085 static void eb_capture_release(struct i915_execbuffer *eb)
2086 {
2087 }
2088 
2089 static void eb_capture_list_clear(struct i915_execbuffer *eb)
2090 {
2091 }
2092 
2093 #endif
2094 
2095 static int eb_move_to_gpu(struct i915_execbuffer *eb)
2096 {
2097 	const unsigned int count = eb->buffer_count;
2098 	unsigned int i = count;
2099 	int err = 0, j;
2100 
2101 	while (i--) {
2102 		struct eb_vma *ev = &eb->vma[i];
2103 		struct i915_vma *vma = ev->vma;
2104 		unsigned int flags = ev->flags;
2105 		struct drm_i915_gem_object *obj = vma->obj;
2106 
2107 		assert_vma_held(vma);
2108 
2109 		/*
2110 		 * If the GPU is not _reading_ through the CPU cache, we need
2111 		 * to make sure that any writes (both previous GPU writes from
2112 		 * before a change in snooping levels and normal CPU writes)
2113 		 * caught in that cache are flushed to main memory.
2114 		 *
2115 		 * We want to say
2116 		 *   obj->cache_dirty &&
2117 		 *   !(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ)
2118 		 * but gcc's optimiser doesn't handle that as well and emits
2119 		 * two jumps instead of one. Maybe one day...
2120 		 *
2121 		 * FIXME: There is also sync flushing in set_pages(), which
2122 		 * serves a different purpose(some of the time at least).
2123 		 *
2124 		 * We should consider:
2125 		 *
2126 		 *   1. Rip out the async flush code.
2127 		 *
2128 		 *   2. Or make the sync flushing use the async clflush path
2129 		 *   using mandatory fences underneath. Currently the below
2130 		 *   async flush happens after we bind the object.
2131 		 */
2132 		if (unlikely(obj->cache_dirty & ~obj->cache_coherent)) {
2133 			if (i915_gem_clflush_object(obj, 0))
2134 				flags &= ~EXEC_OBJECT_ASYNC;
2135 		}
2136 
2137 		/* We only need to await on the first request */
2138 		if (err == 0 && !(flags & EXEC_OBJECT_ASYNC)) {
2139 			err = i915_request_await_object
2140 				(eb_find_first_request_added(eb), obj,
2141 				 flags & EXEC_OBJECT_WRITE);
2142 		}
2143 
2144 		for_each_batch_add_order(eb, j) {
2145 			if (err)
2146 				break;
2147 			if (!eb->requests[j])
2148 				continue;
2149 
2150 			err = _i915_vma_move_to_active(vma, eb->requests[j],
2151 						       j ? NULL :
2152 						       eb->composite_fence ?
2153 						       eb->composite_fence :
2154 						       &eb->requests[j]->fence,
2155 						       flags | __EXEC_OBJECT_NO_RESERVE |
2156 						       __EXEC_OBJECT_NO_REQUEST_AWAIT);
2157 		}
2158 	}
2159 
2160 #ifdef CONFIG_MMU_NOTIFIER
2161 	if (!err && (eb->args->flags & __EXEC_USERPTR_USED)) {
2162 		for (i = 0; i < count; i++) {
2163 			struct eb_vma *ev = &eb->vma[i];
2164 			struct drm_i915_gem_object *obj = ev->vma->obj;
2165 
2166 			if (!i915_gem_object_is_userptr(obj))
2167 				continue;
2168 
2169 			err = i915_gem_object_userptr_submit_done(obj);
2170 			if (err)
2171 				break;
2172 		}
2173 	}
2174 #endif
2175 
2176 	if (unlikely(err))
2177 		goto err_skip;
2178 
2179 	/* Unconditionally flush any chipset caches (for streaming writes). */
2180 	intel_gt_chipset_flush(eb->gt);
2181 	eb_capture_commit(eb);
2182 
2183 	return 0;
2184 
2185 err_skip:
2186 	for_each_batch_create_order(eb, j) {
2187 		if (!eb->requests[j])
2188 			break;
2189 
2190 		i915_request_set_error_once(eb->requests[j], err);
2191 	}
2192 	return err;
2193 }
2194 
2195 static int i915_gem_check_execbuffer(struct drm_i915_private *i915,
2196 				     struct drm_i915_gem_execbuffer2 *exec)
2197 {
2198 	if (exec->flags & __I915_EXEC_ILLEGAL_FLAGS)
2199 		return -EINVAL;
2200 
2201 	/* Kernel clipping was a DRI1 misfeature */
2202 	if (!(exec->flags & (I915_EXEC_FENCE_ARRAY |
2203 			     I915_EXEC_USE_EXTENSIONS))) {
2204 		if (exec->num_cliprects || exec->cliprects_ptr)
2205 			return -EINVAL;
2206 	}
2207 
2208 	if (exec->DR4 == 0xffffffff) {
2209 		drm_dbg(&i915->drm, "UXA submitting garbage DR4, fixing up\n");
2210 		exec->DR4 = 0;
2211 	}
2212 	if (exec->DR1 || exec->DR4)
2213 		return -EINVAL;
2214 
2215 	if ((exec->batch_start_offset | exec->batch_len) & 0x7)
2216 		return -EINVAL;
2217 
2218 	return 0;
2219 }
2220 
2221 static int i915_reset_gen7_sol_offsets(struct i915_request *rq)
2222 {
2223 	u32 *cs;
2224 	int i;
2225 
2226 	if (GRAPHICS_VER(rq->i915) != 7 || rq->engine->id != RCS0) {
2227 		drm_dbg(&rq->i915->drm, "sol reset is gen7/rcs only\n");
2228 		return -EINVAL;
2229 	}
2230 
2231 	cs = intel_ring_begin(rq, 4 * 2 + 2);
2232 	if (IS_ERR(cs))
2233 		return PTR_ERR(cs);
2234 
2235 	*cs++ = MI_LOAD_REGISTER_IMM(4);
2236 	for (i = 0; i < 4; i++) {
2237 		*cs++ = i915_mmio_reg_offset(GEN7_SO_WRITE_OFFSET(i));
2238 		*cs++ = 0;
2239 	}
2240 	*cs++ = MI_NOOP;
2241 	intel_ring_advance(rq, cs);
2242 
2243 	return 0;
2244 }
2245 
2246 static struct i915_vma *
2247 shadow_batch_pin(struct i915_execbuffer *eb,
2248 		 struct drm_i915_gem_object *obj,
2249 		 struct i915_address_space *vm,
2250 		 unsigned int flags)
2251 {
2252 	struct i915_vma *vma;
2253 	int err;
2254 
2255 	vma = i915_vma_instance(obj, vm, NULL);
2256 	if (IS_ERR(vma))
2257 		return vma;
2258 
2259 	err = i915_vma_pin_ww(vma, &eb->ww, 0, 0, flags | PIN_VALIDATE);
2260 	if (err)
2261 		return ERR_PTR(err);
2262 
2263 	return vma;
2264 }
2265 
2266 static struct i915_vma *eb_dispatch_secure(struct i915_execbuffer *eb, struct i915_vma *vma)
2267 {
2268 	/*
2269 	 * snb/ivb/vlv conflate the "batch in ppgtt" bit with the "non-secure
2270 	 * batch" bit. Hence we need to pin secure batches into the global gtt.
2271 	 * hsw should have this fixed, but bdw mucks it up again. */
2272 	if (eb->batch_flags & I915_DISPATCH_SECURE)
2273 		return i915_gem_object_ggtt_pin_ww(vma->obj, &eb->ww, NULL, 0, 0, PIN_VALIDATE);
2274 
2275 	return NULL;
2276 }
2277 
2278 static int eb_parse(struct i915_execbuffer *eb)
2279 {
2280 	struct drm_i915_private *i915 = eb->i915;
2281 	struct intel_gt_buffer_pool_node *pool = eb->batch_pool;
2282 	struct i915_vma *shadow, *trampoline, *batch;
2283 	unsigned long len;
2284 	int err;
2285 
2286 	if (!eb_use_cmdparser(eb)) {
2287 		batch = eb_dispatch_secure(eb, eb->batches[0]->vma);
2288 		if (IS_ERR(batch))
2289 			return PTR_ERR(batch);
2290 
2291 		goto secure_batch;
2292 	}
2293 
2294 	if (intel_context_is_parallel(eb->context))
2295 		return -EINVAL;
2296 
2297 	len = eb->batch_len[0];
2298 	if (!CMDPARSER_USES_GGTT(eb->i915)) {
2299 		/*
2300 		 * ppGTT backed shadow buffers must be mapped RO, to prevent
2301 		 * post-scan tampering
2302 		 */
2303 		if (!eb->context->vm->has_read_only) {
2304 			drm_dbg(&i915->drm,
2305 				"Cannot prevent post-scan tampering without RO capable vm\n");
2306 			return -EINVAL;
2307 		}
2308 	} else {
2309 		len += I915_CMD_PARSER_TRAMPOLINE_SIZE;
2310 	}
2311 	if (unlikely(len < eb->batch_len[0])) /* last paranoid check of overflow */
2312 		return -EINVAL;
2313 
2314 	if (!pool) {
2315 		pool = intel_gt_get_buffer_pool(eb->gt, len,
2316 						I915_MAP_WB);
2317 		if (IS_ERR(pool))
2318 			return PTR_ERR(pool);
2319 		eb->batch_pool = pool;
2320 	}
2321 
2322 	err = i915_gem_object_lock(pool->obj, &eb->ww);
2323 	if (err)
2324 		return err;
2325 
2326 	shadow = shadow_batch_pin(eb, pool->obj, eb->context->vm, PIN_USER);
2327 	if (IS_ERR(shadow))
2328 		return PTR_ERR(shadow);
2329 
2330 	intel_gt_buffer_pool_mark_used(pool);
2331 	i915_gem_object_set_readonly(shadow->obj);
2332 	shadow->private = pool;
2333 
2334 	trampoline = NULL;
2335 	if (CMDPARSER_USES_GGTT(eb->i915)) {
2336 		trampoline = shadow;
2337 
2338 		shadow = shadow_batch_pin(eb, pool->obj,
2339 					  &eb->gt->ggtt->vm,
2340 					  PIN_GLOBAL);
2341 		if (IS_ERR(shadow))
2342 			return PTR_ERR(shadow);
2343 
2344 		shadow->private = pool;
2345 
2346 		eb->batch_flags |= I915_DISPATCH_SECURE;
2347 	}
2348 
2349 	batch = eb_dispatch_secure(eb, shadow);
2350 	if (IS_ERR(batch))
2351 		return PTR_ERR(batch);
2352 
2353 	err = dma_resv_reserve_fences(shadow->obj->base.resv, 1);
2354 	if (err)
2355 		return err;
2356 
2357 	err = intel_engine_cmd_parser(eb->context->engine,
2358 				      eb->batches[0]->vma,
2359 				      eb->batch_start_offset,
2360 				      eb->batch_len[0],
2361 				      shadow, trampoline);
2362 	if (err)
2363 		return err;
2364 
2365 	eb->batches[0] = &eb->vma[eb->buffer_count++];
2366 	eb->batches[0]->vma = i915_vma_get(shadow);
2367 	eb->batches[0]->flags = __EXEC_OBJECT_HAS_PIN;
2368 
2369 	eb->trampoline = trampoline;
2370 	eb->batch_start_offset = 0;
2371 
2372 secure_batch:
2373 	if (batch) {
2374 		if (intel_context_is_parallel(eb->context))
2375 			return -EINVAL;
2376 
2377 		eb->batches[0] = &eb->vma[eb->buffer_count++];
2378 		eb->batches[0]->flags = __EXEC_OBJECT_HAS_PIN;
2379 		eb->batches[0]->vma = i915_vma_get(batch);
2380 	}
2381 	return 0;
2382 }
2383 
2384 static int eb_request_submit(struct i915_execbuffer *eb,
2385 			     struct i915_request *rq,
2386 			     struct i915_vma *batch,
2387 			     u64 batch_len)
2388 {
2389 	int err;
2390 
2391 	if (intel_context_nopreempt(rq->context))
2392 		__set_bit(I915_FENCE_FLAG_NOPREEMPT, &rq->fence.flags);
2393 
2394 	if (eb->args->flags & I915_EXEC_GEN7_SOL_RESET) {
2395 		err = i915_reset_gen7_sol_offsets(rq);
2396 		if (err)
2397 			return err;
2398 	}
2399 
2400 	/*
2401 	 * After we completed waiting for other engines (using HW semaphores)
2402 	 * then we can signal that this request/batch is ready to run. This
2403 	 * allows us to determine if the batch is still waiting on the GPU
2404 	 * or actually running by checking the breadcrumb.
2405 	 */
2406 	if (rq->context->engine->emit_init_breadcrumb) {
2407 		err = rq->context->engine->emit_init_breadcrumb(rq);
2408 		if (err)
2409 			return err;
2410 	}
2411 
2412 	err = rq->context->engine->emit_bb_start(rq,
2413 						 i915_vma_offset(batch) +
2414 						 eb->batch_start_offset,
2415 						 batch_len,
2416 						 eb->batch_flags);
2417 	if (err)
2418 		return err;
2419 
2420 	if (eb->trampoline) {
2421 		GEM_BUG_ON(intel_context_is_parallel(rq->context));
2422 		GEM_BUG_ON(eb->batch_start_offset);
2423 		err = rq->context->engine->emit_bb_start(rq,
2424 							 i915_vma_offset(eb->trampoline) +
2425 							 batch_len, 0, 0);
2426 		if (err)
2427 			return err;
2428 	}
2429 
2430 	return 0;
2431 }
2432 
2433 static int eb_submit(struct i915_execbuffer *eb)
2434 {
2435 	unsigned int i;
2436 	int err;
2437 
2438 	err = eb_move_to_gpu(eb);
2439 
2440 	for_each_batch_create_order(eb, i) {
2441 		if (!eb->requests[i])
2442 			break;
2443 
2444 		trace_i915_request_queue(eb->requests[i], eb->batch_flags);
2445 		if (!err)
2446 			err = eb_request_submit(eb, eb->requests[i],
2447 						eb->batches[i]->vma,
2448 						eb->batch_len[i]);
2449 	}
2450 
2451 	return err;
2452 }
2453 
2454 /*
2455  * Find one BSD ring to dispatch the corresponding BSD command.
2456  * The engine index is returned.
2457  */
2458 static unsigned int
2459 gen8_dispatch_bsd_engine(struct drm_i915_private *i915,
2460 			 struct drm_file *file)
2461 {
2462 	struct drm_i915_file_private *file_priv = file->driver_priv;
2463 
2464 	/* Check whether the file_priv has already selected one ring. */
2465 	if ((int)file_priv->bsd_engine < 0)
2466 		file_priv->bsd_engine =
2467 			get_random_u32_below(i915->engine_uabi_class_count[I915_ENGINE_CLASS_VIDEO]);
2468 
2469 	return file_priv->bsd_engine;
2470 }
2471 
2472 static const enum intel_engine_id user_ring_map[] = {
2473 	[I915_EXEC_DEFAULT]	= RCS0,
2474 	[I915_EXEC_RENDER]	= RCS0,
2475 	[I915_EXEC_BLT]		= BCS0,
2476 	[I915_EXEC_BSD]		= VCS0,
2477 	[I915_EXEC_VEBOX]	= VECS0
2478 };
2479 
2480 static struct i915_request *eb_throttle(struct i915_execbuffer *eb, struct intel_context *ce)
2481 {
2482 	struct intel_ring *ring = ce->ring;
2483 	struct intel_timeline *tl = ce->timeline;
2484 	struct i915_request *rq;
2485 
2486 	/*
2487 	 * Completely unscientific finger-in-the-air estimates for suitable
2488 	 * maximum user request size (to avoid blocking) and then backoff.
2489 	 */
2490 	if (intel_ring_update_space(ring) >= PAGE_SIZE)
2491 		return NULL;
2492 
2493 	/*
2494 	 * Find a request that after waiting upon, there will be at least half
2495 	 * the ring available. The hysteresis allows us to compete for the
2496 	 * shared ring and should mean that we sleep less often prior to
2497 	 * claiming our resources, but not so long that the ring completely
2498 	 * drains before we can submit our next request.
2499 	 */
2500 	list_for_each_entry(rq, &tl->requests, link) {
2501 		if (rq->ring != ring)
2502 			continue;
2503 
2504 		if (__intel_ring_space(rq->postfix,
2505 				       ring->emit, ring->size) > ring->size / 2)
2506 			break;
2507 	}
2508 	if (&rq->link == &tl->requests)
2509 		return NULL; /* weird, we will check again later for real */
2510 
2511 	return i915_request_get(rq);
2512 }
2513 
2514 static int eb_pin_timeline(struct i915_execbuffer *eb, struct intel_context *ce,
2515 			   bool throttle)
2516 {
2517 	struct intel_timeline *tl;
2518 	struct i915_request *rq = NULL;
2519 
2520 	/*
2521 	 * Take a local wakeref for preparing to dispatch the execbuf as
2522 	 * we expect to access the hardware fairly frequently in the
2523 	 * process, and require the engine to be kept awake between accesses.
2524 	 * Upon dispatch, we acquire another prolonged wakeref that we hold
2525 	 * until the timeline is idle, which in turn releases the wakeref
2526 	 * taken on the engine, and the parent device.
2527 	 */
2528 	tl = intel_context_timeline_lock(ce);
2529 	if (IS_ERR(tl))
2530 		return PTR_ERR(tl);
2531 
2532 	intel_context_enter(ce);
2533 	if (throttle)
2534 		rq = eb_throttle(eb, ce);
2535 	intel_context_timeline_unlock(tl);
2536 
2537 	if (rq) {
2538 		bool nonblock = eb->file->filp->f_flags & O_NONBLOCK;
2539 		long timeout = nonblock ? 0 : MAX_SCHEDULE_TIMEOUT;
2540 
2541 		if (i915_request_wait(rq, I915_WAIT_INTERRUPTIBLE,
2542 				      timeout) < 0) {
2543 			i915_request_put(rq);
2544 
2545 			/*
2546 			 * Error path, cannot use intel_context_timeline_lock as
2547 			 * that is user interruptible and this clean up step
2548 			 * must be done.
2549 			 */
2550 			mutex_lock(&ce->timeline->mutex);
2551 			intel_context_exit(ce);
2552 			mutex_unlock(&ce->timeline->mutex);
2553 
2554 			if (nonblock)
2555 				return -EWOULDBLOCK;
2556 			else
2557 				return -EINTR;
2558 		}
2559 		i915_request_put(rq);
2560 	}
2561 
2562 	return 0;
2563 }
2564 
2565 static int eb_pin_engine(struct i915_execbuffer *eb, bool throttle)
2566 {
2567 	struct intel_context *ce = eb->context, *child;
2568 	int err;
2569 	int i = 0, j = 0;
2570 
2571 	GEM_BUG_ON(eb->args->flags & __EXEC_ENGINE_PINNED);
2572 
2573 	if (unlikely(intel_context_is_banned(ce)))
2574 		return -EIO;
2575 
2576 	/*
2577 	 * Pinning the contexts may generate requests in order to acquire
2578 	 * GGTT space, so do this first before we reserve a seqno for
2579 	 * ourselves.
2580 	 */
2581 	err = intel_context_pin_ww(ce, &eb->ww);
2582 	if (err)
2583 		return err;
2584 	for_each_child(ce, child) {
2585 		err = intel_context_pin_ww(child, &eb->ww);
2586 		GEM_BUG_ON(err);	/* perma-pinned should incr a counter */
2587 	}
2588 
2589 	for_each_child(ce, child) {
2590 		err = eb_pin_timeline(eb, child, throttle);
2591 		if (err)
2592 			goto unwind;
2593 		++i;
2594 	}
2595 	err = eb_pin_timeline(eb, ce, throttle);
2596 	if (err)
2597 		goto unwind;
2598 
2599 	eb->args->flags |= __EXEC_ENGINE_PINNED;
2600 	return 0;
2601 
2602 unwind:
2603 	for_each_child(ce, child) {
2604 		if (j++ < i) {
2605 			mutex_lock(&child->timeline->mutex);
2606 			intel_context_exit(child);
2607 			mutex_unlock(&child->timeline->mutex);
2608 		}
2609 	}
2610 	for_each_child(ce, child)
2611 		intel_context_unpin(child);
2612 	intel_context_unpin(ce);
2613 	return err;
2614 }
2615 
2616 static void eb_unpin_engine(struct i915_execbuffer *eb)
2617 {
2618 	struct intel_context *ce = eb->context, *child;
2619 
2620 	if (!(eb->args->flags & __EXEC_ENGINE_PINNED))
2621 		return;
2622 
2623 	eb->args->flags &= ~__EXEC_ENGINE_PINNED;
2624 
2625 	for_each_child(ce, child) {
2626 		mutex_lock(&child->timeline->mutex);
2627 		intel_context_exit(child);
2628 		mutex_unlock(&child->timeline->mutex);
2629 
2630 		intel_context_unpin(child);
2631 	}
2632 
2633 	mutex_lock(&ce->timeline->mutex);
2634 	intel_context_exit(ce);
2635 	mutex_unlock(&ce->timeline->mutex);
2636 
2637 	intel_context_unpin(ce);
2638 }
2639 
2640 static unsigned int
2641 eb_select_legacy_ring(struct i915_execbuffer *eb)
2642 {
2643 	struct drm_i915_private *i915 = eb->i915;
2644 	struct drm_i915_gem_execbuffer2 *args = eb->args;
2645 	unsigned int user_ring_id = args->flags & I915_EXEC_RING_MASK;
2646 
2647 	if (user_ring_id != I915_EXEC_BSD &&
2648 	    (args->flags & I915_EXEC_BSD_MASK)) {
2649 		drm_dbg(&i915->drm,
2650 			"execbuf with non bsd ring but with invalid "
2651 			"bsd dispatch flags: %d\n", (int)(args->flags));
2652 		return -1;
2653 	}
2654 
2655 	if (user_ring_id == I915_EXEC_BSD &&
2656 	    i915->engine_uabi_class_count[I915_ENGINE_CLASS_VIDEO] > 1) {
2657 		unsigned int bsd_idx = args->flags & I915_EXEC_BSD_MASK;
2658 
2659 		if (bsd_idx == I915_EXEC_BSD_DEFAULT) {
2660 			bsd_idx = gen8_dispatch_bsd_engine(i915, eb->file);
2661 		} else if (bsd_idx >= I915_EXEC_BSD_RING1 &&
2662 			   bsd_idx <= I915_EXEC_BSD_RING2) {
2663 			bsd_idx >>= I915_EXEC_BSD_SHIFT;
2664 			bsd_idx--;
2665 		} else {
2666 			drm_dbg(&i915->drm,
2667 				"execbuf with unknown bsd ring: %u\n",
2668 				bsd_idx);
2669 			return -1;
2670 		}
2671 
2672 		return _VCS(bsd_idx);
2673 	}
2674 
2675 	if (user_ring_id >= ARRAY_SIZE(user_ring_map)) {
2676 		drm_dbg(&i915->drm, "execbuf with unknown ring: %u\n",
2677 			user_ring_id);
2678 		return -1;
2679 	}
2680 
2681 	return user_ring_map[user_ring_id];
2682 }
2683 
2684 static int
2685 eb_select_engine(struct i915_execbuffer *eb)
2686 {
2687 	struct intel_context *ce, *child;
2688 	struct intel_gt *gt;
2689 	unsigned int idx;
2690 	int err;
2691 
2692 	if (i915_gem_context_user_engines(eb->gem_context))
2693 		idx = eb->args->flags & I915_EXEC_RING_MASK;
2694 	else
2695 		idx = eb_select_legacy_ring(eb);
2696 
2697 	ce = i915_gem_context_get_engine(eb->gem_context, idx);
2698 	if (IS_ERR(ce))
2699 		return PTR_ERR(ce);
2700 
2701 	if (intel_context_is_parallel(ce)) {
2702 		if (eb->buffer_count < ce->parallel.number_children + 1) {
2703 			intel_context_put(ce);
2704 			return -EINVAL;
2705 		}
2706 		if (eb->batch_start_offset || eb->args->batch_len) {
2707 			intel_context_put(ce);
2708 			return -EINVAL;
2709 		}
2710 	}
2711 	eb->num_batches = ce->parallel.number_children + 1;
2712 	gt = ce->engine->gt;
2713 
2714 	for_each_child(ce, child)
2715 		intel_context_get(child);
2716 	eb->wakeref = intel_gt_pm_get(ce->engine->gt);
2717 	/*
2718 	 * Keep GT0 active on MTL so that i915_vma_parked() doesn't
2719 	 * free VMAs while execbuf ioctl is validating VMAs.
2720 	 */
2721 	if (gt->info.id)
2722 		eb->wakeref_gt0 = intel_gt_pm_get(to_gt(gt->i915));
2723 
2724 	if (!test_bit(CONTEXT_ALLOC_BIT, &ce->flags)) {
2725 		err = intel_context_alloc_state(ce);
2726 		if (err)
2727 			goto err;
2728 	}
2729 	for_each_child(ce, child) {
2730 		if (!test_bit(CONTEXT_ALLOC_BIT, &child->flags)) {
2731 			err = intel_context_alloc_state(child);
2732 			if (err)
2733 				goto err;
2734 		}
2735 	}
2736 
2737 	/*
2738 	 * ABI: Before userspace accesses the GPU (e.g. execbuffer), report
2739 	 * EIO if the GPU is already wedged.
2740 	 */
2741 	err = intel_gt_terminally_wedged(ce->engine->gt);
2742 	if (err)
2743 		goto err;
2744 
2745 	if (!i915_vm_tryget(ce->vm)) {
2746 		err = -ENOENT;
2747 		goto err;
2748 	}
2749 
2750 	eb->context = ce;
2751 	eb->gt = ce->engine->gt;
2752 
2753 	/*
2754 	 * Make sure engine pool stays alive even if we call intel_context_put
2755 	 * during ww handling. The pool is destroyed when last pm reference
2756 	 * is dropped, which breaks our -EDEADLK handling.
2757 	 */
2758 	return err;
2759 
2760 err:
2761 	if (gt->info.id)
2762 		intel_gt_pm_put(to_gt(gt->i915), eb->wakeref_gt0);
2763 
2764 	intel_gt_pm_put(ce->engine->gt, eb->wakeref);
2765 	for_each_child(ce, child)
2766 		intel_context_put(child);
2767 	intel_context_put(ce);
2768 	return err;
2769 }
2770 
2771 static void
2772 eb_put_engine(struct i915_execbuffer *eb)
2773 {
2774 	struct intel_context *child;
2775 
2776 	i915_vm_put(eb->context->vm);
2777 	/*
2778 	 * This works in conjunction with eb_select_engine() to prevent
2779 	 * i915_vma_parked() from interfering while execbuf validates vmas.
2780 	 */
2781 	if (eb->gt->info.id)
2782 		intel_gt_pm_put(to_gt(eb->gt->i915), eb->wakeref_gt0);
2783 	intel_gt_pm_put(eb->context->engine->gt, eb->wakeref);
2784 	for_each_child(eb->context, child)
2785 		intel_context_put(child);
2786 	intel_context_put(eb->context);
2787 }
2788 
2789 static void
2790 __free_fence_array(struct eb_fence *fences, unsigned int n)
2791 {
2792 	while (n--) {
2793 		drm_syncobj_put(ptr_mask_bits(fences[n].syncobj, 2));
2794 		dma_fence_put(fences[n].dma_fence);
2795 		dma_fence_chain_free(fences[n].chain_fence);
2796 	}
2797 	kvfree(fences);
2798 }
2799 
2800 static int
2801 add_timeline_fence_array(struct i915_execbuffer *eb,
2802 			 const struct drm_i915_gem_execbuffer_ext_timeline_fences *timeline_fences)
2803 {
2804 	struct drm_i915_gem_exec_fence __user *user_fences;
2805 	u64 __user *user_values;
2806 	struct eb_fence *f;
2807 	u64 nfences;
2808 	int err = 0;
2809 
2810 	nfences = timeline_fences->fence_count;
2811 	if (!nfences)
2812 		return 0;
2813 
2814 	/* Check multiplication overflow for access_ok() and kvmalloc_array() */
2815 	BUILD_BUG_ON(sizeof(size_t) > sizeof(unsigned long));
2816 	if (nfences > min_t(unsigned long,
2817 			    ULONG_MAX / sizeof(*user_fences),
2818 			    SIZE_MAX / sizeof(*f)) - eb->num_fences)
2819 		return -EINVAL;
2820 
2821 	user_fences = u64_to_user_ptr(timeline_fences->handles_ptr);
2822 	if (!access_ok(user_fences, nfences * sizeof(*user_fences)))
2823 		return -EFAULT;
2824 
2825 	user_values = u64_to_user_ptr(timeline_fences->values_ptr);
2826 	if (!access_ok(user_values, nfences * sizeof(*user_values)))
2827 		return -EFAULT;
2828 
2829 	f = krealloc(eb->fences,
2830 		     (eb->num_fences + nfences) * sizeof(*f),
2831 		     __GFP_NOWARN | GFP_KERNEL);
2832 	if (!f)
2833 		return -ENOMEM;
2834 
2835 	eb->fences = f;
2836 	f += eb->num_fences;
2837 
2838 	BUILD_BUG_ON(~(ARCH_KMALLOC_MINALIGN - 1) &
2839 		     ~__I915_EXEC_FENCE_UNKNOWN_FLAGS);
2840 
2841 	while (nfences--) {
2842 		struct drm_i915_gem_exec_fence user_fence;
2843 		struct drm_syncobj *syncobj;
2844 		struct dma_fence *fence = NULL;
2845 		u64 point;
2846 
2847 		if (__copy_from_user(&user_fence,
2848 				     user_fences++,
2849 				     sizeof(user_fence)))
2850 			return -EFAULT;
2851 
2852 		if (user_fence.flags & __I915_EXEC_FENCE_UNKNOWN_FLAGS)
2853 			return -EINVAL;
2854 
2855 		if (get_user(point, user_values++))
2856 			return -EFAULT;
2857 
2858 		syncobj = drm_syncobj_find(eb->file, user_fence.handle);
2859 		if (!syncobj) {
2860 			drm_dbg(&eb->i915->drm,
2861 				"Invalid syncobj handle provided\n");
2862 			return -ENOENT;
2863 		}
2864 
2865 		fence = drm_syncobj_fence_get(syncobj);
2866 
2867 		if (!fence && user_fence.flags &&
2868 		    !(user_fence.flags & I915_EXEC_FENCE_SIGNAL)) {
2869 			drm_dbg(&eb->i915->drm,
2870 				"Syncobj handle has no fence\n");
2871 			drm_syncobj_put(syncobj);
2872 			return -EINVAL;
2873 		}
2874 
2875 		if (fence)
2876 			err = dma_fence_chain_find_seqno(&fence, point);
2877 
2878 		if (err && !(user_fence.flags & I915_EXEC_FENCE_SIGNAL)) {
2879 			drm_dbg(&eb->i915->drm,
2880 				"Syncobj handle missing requested point %llu\n",
2881 				point);
2882 			dma_fence_put(fence);
2883 			drm_syncobj_put(syncobj);
2884 			return err;
2885 		}
2886 
2887 		/*
2888 		 * A point might have been signaled already and
2889 		 * garbage collected from the timeline. In this case
2890 		 * just ignore the point and carry on.
2891 		 */
2892 		if (!fence && !(user_fence.flags & I915_EXEC_FENCE_SIGNAL)) {
2893 			drm_syncobj_put(syncobj);
2894 			continue;
2895 		}
2896 
2897 		/*
2898 		 * For timeline syncobjs we need to preallocate chains for
2899 		 * later signaling.
2900 		 */
2901 		if (point != 0 && user_fence.flags & I915_EXEC_FENCE_SIGNAL) {
2902 			/*
2903 			 * Waiting and signaling the same point (when point !=
2904 			 * 0) would break the timeline.
2905 			 */
2906 			if (user_fence.flags & I915_EXEC_FENCE_WAIT) {
2907 				drm_dbg(&eb->i915->drm,
2908 					"Trying to wait & signal the same timeline point.\n");
2909 				dma_fence_put(fence);
2910 				drm_syncobj_put(syncobj);
2911 				return -EINVAL;
2912 			}
2913 
2914 			f->chain_fence = dma_fence_chain_alloc();
2915 			if (!f->chain_fence) {
2916 				drm_syncobj_put(syncobj);
2917 				dma_fence_put(fence);
2918 				return -ENOMEM;
2919 			}
2920 		} else {
2921 			f->chain_fence = NULL;
2922 		}
2923 
2924 		f->syncobj = ptr_pack_bits(syncobj, user_fence.flags, 2);
2925 		f->dma_fence = fence;
2926 		f->value = point;
2927 		f++;
2928 		eb->num_fences++;
2929 	}
2930 
2931 	return 0;
2932 }
2933 
2934 static int add_fence_array(struct i915_execbuffer *eb)
2935 {
2936 	struct drm_i915_gem_execbuffer2 *args = eb->args;
2937 	struct drm_i915_gem_exec_fence __user *user;
2938 	unsigned long num_fences = args->num_cliprects;
2939 	struct eb_fence *f;
2940 
2941 	if (!(args->flags & I915_EXEC_FENCE_ARRAY))
2942 		return 0;
2943 
2944 	if (!num_fences)
2945 		return 0;
2946 
2947 	/* Check multiplication overflow for access_ok() and kvmalloc_array() */
2948 	BUILD_BUG_ON(sizeof(size_t) > sizeof(unsigned long));
2949 	if (num_fences > min_t(unsigned long,
2950 			       ULONG_MAX / sizeof(*user),
2951 			       SIZE_MAX / sizeof(*f) - eb->num_fences))
2952 		return -EINVAL;
2953 
2954 	user = u64_to_user_ptr(args->cliprects_ptr);
2955 	if (!access_ok(user, num_fences * sizeof(*user)))
2956 		return -EFAULT;
2957 
2958 	f = krealloc(eb->fences,
2959 		     (eb->num_fences + num_fences) * sizeof(*f),
2960 		     __GFP_NOWARN | GFP_KERNEL);
2961 	if (!f)
2962 		return -ENOMEM;
2963 
2964 	eb->fences = f;
2965 	f += eb->num_fences;
2966 	while (num_fences--) {
2967 		struct drm_i915_gem_exec_fence user_fence;
2968 		struct drm_syncobj *syncobj;
2969 		struct dma_fence *fence = NULL;
2970 
2971 		if (__copy_from_user(&user_fence, user++, sizeof(user_fence)))
2972 			return -EFAULT;
2973 
2974 		if (user_fence.flags & __I915_EXEC_FENCE_UNKNOWN_FLAGS)
2975 			return -EINVAL;
2976 
2977 		syncobj = drm_syncobj_find(eb->file, user_fence.handle);
2978 		if (!syncobj) {
2979 			drm_dbg(&eb->i915->drm,
2980 				"Invalid syncobj handle provided\n");
2981 			return -ENOENT;
2982 		}
2983 
2984 		if (user_fence.flags & I915_EXEC_FENCE_WAIT) {
2985 			fence = drm_syncobj_fence_get(syncobj);
2986 			if (!fence) {
2987 				drm_dbg(&eb->i915->drm,
2988 					"Syncobj handle has no fence\n");
2989 				drm_syncobj_put(syncobj);
2990 				return -EINVAL;
2991 			}
2992 		}
2993 
2994 		BUILD_BUG_ON(~(ARCH_KMALLOC_MINALIGN - 1) &
2995 			     ~__I915_EXEC_FENCE_UNKNOWN_FLAGS);
2996 
2997 		f->syncobj = ptr_pack_bits(syncobj, user_fence.flags, 2);
2998 		f->dma_fence = fence;
2999 		f->value = 0;
3000 		f->chain_fence = NULL;
3001 		f++;
3002 		eb->num_fences++;
3003 	}
3004 
3005 	return 0;
3006 }
3007 
3008 static void put_fence_array(struct eb_fence *fences, int num_fences)
3009 {
3010 	if (fences)
3011 		__free_fence_array(fences, num_fences);
3012 }
3013 
3014 static int
3015 await_fence_array(struct i915_execbuffer *eb,
3016 		  struct i915_request *rq)
3017 {
3018 	unsigned int n;
3019 	int err;
3020 
3021 	for (n = 0; n < eb->num_fences; n++) {
3022 		if (!eb->fences[n].dma_fence)
3023 			continue;
3024 
3025 		err = i915_request_await_dma_fence(rq, eb->fences[n].dma_fence);
3026 		if (err < 0)
3027 			return err;
3028 	}
3029 
3030 	return 0;
3031 }
3032 
3033 static void signal_fence_array(const struct i915_execbuffer *eb,
3034 			       struct dma_fence * const fence)
3035 {
3036 	unsigned int n;
3037 
3038 	for (n = 0; n < eb->num_fences; n++) {
3039 		struct drm_syncobj *syncobj;
3040 		unsigned int flags;
3041 
3042 		syncobj = ptr_unpack_bits(eb->fences[n].syncobj, &flags, 2);
3043 		if (!(flags & I915_EXEC_FENCE_SIGNAL))
3044 			continue;
3045 
3046 		if (eb->fences[n].chain_fence) {
3047 			drm_syncobj_add_point(syncobj,
3048 					      eb->fences[n].chain_fence,
3049 					      fence,
3050 					      eb->fences[n].value);
3051 			/*
3052 			 * The chain's ownership is transferred to the
3053 			 * timeline.
3054 			 */
3055 			eb->fences[n].chain_fence = NULL;
3056 		} else {
3057 			drm_syncobj_replace_fence(syncobj, fence);
3058 		}
3059 	}
3060 }
3061 
3062 static int
3063 parse_timeline_fences(struct i915_user_extension __user *ext, void *data)
3064 {
3065 	struct i915_execbuffer *eb = data;
3066 	struct drm_i915_gem_execbuffer_ext_timeline_fences timeline_fences;
3067 
3068 	if (copy_from_user(&timeline_fences, ext, sizeof(timeline_fences)))
3069 		return -EFAULT;
3070 
3071 	return add_timeline_fence_array(eb, &timeline_fences);
3072 }
3073 
3074 static void retire_requests(struct intel_timeline *tl, struct i915_request *end)
3075 {
3076 	struct i915_request *rq, *rn;
3077 
3078 	list_for_each_entry_safe(rq, rn, &tl->requests, link)
3079 		if (rq == end || !i915_request_retire(rq))
3080 			break;
3081 }
3082 
3083 static int eb_request_add(struct i915_execbuffer *eb, struct i915_request *rq,
3084 			  int err, bool last_parallel)
3085 {
3086 	struct intel_timeline * const tl = i915_request_timeline(rq);
3087 	struct i915_sched_attr attr = {};
3088 	struct i915_request *prev;
3089 
3090 	lockdep_assert_held(&tl->mutex);
3091 	lockdep_unpin_lock(&tl->mutex, rq->cookie);
3092 
3093 	trace_i915_request_add(rq);
3094 
3095 	prev = __i915_request_commit(rq);
3096 
3097 	/* Check that the context wasn't destroyed before submission */
3098 	if (likely(!intel_context_is_closed(eb->context))) {
3099 		attr = eb->gem_context->sched;
3100 	} else {
3101 		/* Serialise with context_close via the add_to_timeline */
3102 		i915_request_set_error_once(rq, -ENOENT);
3103 		__i915_request_skip(rq);
3104 		err = -ENOENT; /* override any transient errors */
3105 	}
3106 
3107 	if (intel_context_is_parallel(eb->context)) {
3108 		if (err) {
3109 			__i915_request_skip(rq);
3110 			set_bit(I915_FENCE_FLAG_SKIP_PARALLEL,
3111 				&rq->fence.flags);
3112 		}
3113 		if (last_parallel)
3114 			set_bit(I915_FENCE_FLAG_SUBMIT_PARALLEL,
3115 				&rq->fence.flags);
3116 	}
3117 
3118 	__i915_request_queue(rq, &attr);
3119 
3120 	/* Try to clean up the client's timeline after submitting the request */
3121 	if (prev)
3122 		retire_requests(tl, prev);
3123 
3124 	mutex_unlock(&tl->mutex);
3125 
3126 	return err;
3127 }
3128 
3129 static int eb_requests_add(struct i915_execbuffer *eb, int err)
3130 {
3131 	int i;
3132 
3133 	/*
3134 	 * We iterate in reverse order of creation to release timeline mutexes in
3135 	 * same order.
3136 	 */
3137 	for_each_batch_add_order(eb, i) {
3138 		struct i915_request *rq = eb->requests[i];
3139 
3140 		if (!rq)
3141 			continue;
3142 		err |= eb_request_add(eb, rq, err, i == 0);
3143 	}
3144 
3145 	return err;
3146 }
3147 
3148 static const i915_user_extension_fn execbuf_extensions[] = {
3149 	[DRM_I915_GEM_EXECBUFFER_EXT_TIMELINE_FENCES] = parse_timeline_fences,
3150 };
3151 
3152 static int
3153 parse_execbuf2_extensions(struct drm_i915_gem_execbuffer2 *args,
3154 			  struct i915_execbuffer *eb)
3155 {
3156 	if (!(args->flags & I915_EXEC_USE_EXTENSIONS))
3157 		return 0;
3158 
3159 	/* The execbuf2 extension mechanism reuses cliprects_ptr. So we cannot
3160 	 * have another flag also using it at the same time.
3161 	 */
3162 	if (eb->args->flags & I915_EXEC_FENCE_ARRAY)
3163 		return -EINVAL;
3164 
3165 	if (args->num_cliprects != 0)
3166 		return -EINVAL;
3167 
3168 	return i915_user_extensions(u64_to_user_ptr(args->cliprects_ptr),
3169 				    execbuf_extensions,
3170 				    ARRAY_SIZE(execbuf_extensions),
3171 				    eb);
3172 }
3173 
3174 static void eb_requests_get(struct i915_execbuffer *eb)
3175 {
3176 	unsigned int i;
3177 
3178 	for_each_batch_create_order(eb, i) {
3179 		if (!eb->requests[i])
3180 			break;
3181 
3182 		i915_request_get(eb->requests[i]);
3183 	}
3184 }
3185 
3186 static void eb_requests_put(struct i915_execbuffer *eb)
3187 {
3188 	unsigned int i;
3189 
3190 	for_each_batch_create_order(eb, i) {
3191 		if (!eb->requests[i])
3192 			break;
3193 
3194 		i915_request_put(eb->requests[i]);
3195 	}
3196 }
3197 
3198 static struct sync_file *
3199 eb_composite_fence_create(struct i915_execbuffer *eb, int out_fence_fd)
3200 {
3201 	struct sync_file *out_fence = NULL;
3202 	struct dma_fence_array *fence_array;
3203 	struct dma_fence **fences;
3204 	unsigned int i;
3205 
3206 	GEM_BUG_ON(!intel_context_is_parent(eb->context));
3207 
3208 	fences = kmalloc_objs(*fences, eb->num_batches);
3209 	if (!fences)
3210 		return ERR_PTR(-ENOMEM);
3211 
3212 	for_each_batch_create_order(eb, i) {
3213 		fences[i] = &eb->requests[i]->fence;
3214 		__set_bit(I915_FENCE_FLAG_COMPOSITE,
3215 			  &eb->requests[i]->fence.flags);
3216 	}
3217 
3218 	fence_array = dma_fence_array_create(eb->num_batches,
3219 					     fences,
3220 					     eb->context->parallel.fence_context,
3221 					     eb->context->parallel.seqno++);
3222 	if (!fence_array) {
3223 		kfree(fences);
3224 		return ERR_PTR(-ENOMEM);
3225 	}
3226 
3227 	/* Move ownership to the dma_fence_array created above */
3228 	for_each_batch_create_order(eb, i)
3229 		dma_fence_get(fences[i]);
3230 
3231 	if (out_fence_fd != -1) {
3232 		out_fence = sync_file_create(&fence_array->base);
3233 		/* sync_file now owns fence_arry, drop creation ref */
3234 		dma_fence_put(&fence_array->base);
3235 		if (!out_fence)
3236 			return ERR_PTR(-ENOMEM);
3237 	}
3238 
3239 	eb->composite_fence = &fence_array->base;
3240 
3241 	return out_fence;
3242 }
3243 
3244 static struct sync_file *
3245 eb_fences_add(struct i915_execbuffer *eb, struct i915_request *rq,
3246 	      struct dma_fence *in_fence, int out_fence_fd)
3247 {
3248 	struct sync_file *out_fence = NULL;
3249 	int err;
3250 
3251 	if (unlikely(eb->gem_context->syncobj)) {
3252 		struct dma_fence *fence;
3253 
3254 		fence = drm_syncobj_fence_get(eb->gem_context->syncobj);
3255 		err = i915_request_await_dma_fence(rq, fence);
3256 		dma_fence_put(fence);
3257 		if (err)
3258 			return ERR_PTR(err);
3259 	}
3260 
3261 	if (in_fence) {
3262 		if (eb->args->flags & I915_EXEC_FENCE_SUBMIT)
3263 			err = i915_request_await_execution(rq, in_fence);
3264 		else
3265 			err = i915_request_await_dma_fence(rq, in_fence);
3266 		if (err < 0)
3267 			return ERR_PTR(err);
3268 	}
3269 
3270 	if (eb->fences) {
3271 		err = await_fence_array(eb, rq);
3272 		if (err)
3273 			return ERR_PTR(err);
3274 	}
3275 
3276 	if (intel_context_is_parallel(eb->context)) {
3277 		out_fence = eb_composite_fence_create(eb, out_fence_fd);
3278 		if (IS_ERR(out_fence))
3279 			return ERR_PTR(-ENOMEM);
3280 	} else if (out_fence_fd != -1) {
3281 		out_fence = sync_file_create(&rq->fence);
3282 		if (!out_fence)
3283 			return ERR_PTR(-ENOMEM);
3284 	}
3285 
3286 	return out_fence;
3287 }
3288 
3289 static struct intel_context *
3290 eb_find_context(struct i915_execbuffer *eb, unsigned int context_number)
3291 {
3292 	struct intel_context *child;
3293 
3294 	if (likely(context_number == 0))
3295 		return eb->context;
3296 
3297 	for_each_child(eb->context, child)
3298 		if (!--context_number)
3299 			return child;
3300 
3301 	GEM_BUG_ON("Context not found");
3302 
3303 	return NULL;
3304 }
3305 
3306 static struct sync_file *
3307 eb_requests_create(struct i915_execbuffer *eb, struct dma_fence *in_fence,
3308 		   int out_fence_fd)
3309 {
3310 	struct sync_file *out_fence = NULL;
3311 	unsigned int i;
3312 
3313 	for_each_batch_create_order(eb, i) {
3314 		/* Allocate a request for this batch buffer nice and early. */
3315 		eb->requests[i] = i915_request_create(eb_find_context(eb, i));
3316 		if (IS_ERR(eb->requests[i])) {
3317 			out_fence = ERR_CAST(eb->requests[i]);
3318 			eb->requests[i] = NULL;
3319 			return out_fence;
3320 		}
3321 
3322 		/*
3323 		 * Only the first request added (committed to backend) has to
3324 		 * take the in fences into account as all subsequent requests
3325 		 * will have fences inserted inbetween them.
3326 		 */
3327 		if (i + 1 == eb->num_batches) {
3328 			out_fence = eb_fences_add(eb, eb->requests[i],
3329 						  in_fence, out_fence_fd);
3330 			if (IS_ERR(out_fence))
3331 				return out_fence;
3332 		}
3333 
3334 		/*
3335 		 * Not really on stack, but we don't want to call
3336 		 * kfree on the batch_snapshot when we put it, so use the
3337 		 * _onstack interface.
3338 		 */
3339 		if (eb->batches[i]->vma)
3340 			eb->requests[i]->batch_res =
3341 				i915_vma_resource_get(eb->batches[i]->vma->resource);
3342 		if (eb->batch_pool) {
3343 			GEM_BUG_ON(intel_context_is_parallel(eb->context));
3344 			intel_gt_buffer_pool_mark_active(eb->batch_pool,
3345 							 eb->requests[i]);
3346 		}
3347 	}
3348 
3349 	return out_fence;
3350 }
3351 
3352 static int
3353 i915_gem_do_execbuffer(struct drm_device *dev,
3354 		       struct drm_file *file,
3355 		       struct drm_i915_gem_execbuffer2 *args,
3356 		       struct drm_i915_gem_exec_object2 *exec)
3357 {
3358 	struct drm_i915_private *i915 = to_i915(dev);
3359 	struct i915_execbuffer eb;
3360 	struct dma_fence *in_fence = NULL;
3361 	struct sync_file *out_fence = NULL;
3362 	int out_fence_fd = -1;
3363 	int err;
3364 
3365 	BUILD_BUG_ON(__EXEC_INTERNAL_FLAGS & ~__I915_EXEC_ILLEGAL_FLAGS);
3366 	BUILD_BUG_ON(__EXEC_OBJECT_INTERNAL_FLAGS &
3367 		     ~__EXEC_OBJECT_UNKNOWN_FLAGS);
3368 
3369 	eb.i915 = i915;
3370 	eb.file = file;
3371 	eb.args = args;
3372 	if (DBG_FORCE_RELOC || !(args->flags & I915_EXEC_NO_RELOC))
3373 		args->flags |= __EXEC_HAS_RELOC;
3374 
3375 	eb.exec = exec;
3376 	eb.vma = (struct eb_vma *)(exec + args->buffer_count + 1);
3377 	memset(eb.vma, 0, (args->buffer_count + 1) * sizeof(struct eb_vma));
3378 
3379 	eb.batch_pool = NULL;
3380 
3381 	eb.invalid_flags = __EXEC_OBJECT_UNKNOWN_FLAGS;
3382 	reloc_cache_init(&eb.reloc_cache, eb.i915);
3383 
3384 	eb.buffer_count = args->buffer_count;
3385 	eb.batch_start_offset = args->batch_start_offset;
3386 	eb.trampoline = NULL;
3387 
3388 	eb.fences = NULL;
3389 	eb.num_fences = 0;
3390 
3391 	eb_capture_list_clear(&eb);
3392 
3393 	memset(eb.requests, 0, sizeof(struct i915_request *) *
3394 	       ARRAY_SIZE(eb.requests));
3395 	eb.composite_fence = NULL;
3396 
3397 	eb.batch_flags = 0;
3398 	if (args->flags & I915_EXEC_SECURE) {
3399 		if (GRAPHICS_VER(i915) >= 11)
3400 			return -ENODEV;
3401 
3402 		/* Return -EPERM to trigger fallback code on old binaries. */
3403 		if (!HAS_SECURE_BATCHES(i915))
3404 			return -EPERM;
3405 
3406 		if (!drm_is_current_master(file) || !capable(CAP_SYS_ADMIN))
3407 			return -EPERM;
3408 
3409 		eb.batch_flags |= I915_DISPATCH_SECURE;
3410 	}
3411 	if (args->flags & I915_EXEC_IS_PINNED)
3412 		eb.batch_flags |= I915_DISPATCH_PINNED;
3413 
3414 	err = parse_execbuf2_extensions(args, &eb);
3415 	if (err)
3416 		goto err_ext;
3417 
3418 	err = add_fence_array(&eb);
3419 	if (err)
3420 		goto err_ext;
3421 
3422 #define IN_FENCES (I915_EXEC_FENCE_IN | I915_EXEC_FENCE_SUBMIT)
3423 	if (args->flags & IN_FENCES) {
3424 		if ((args->flags & IN_FENCES) == IN_FENCES)
3425 			return -EINVAL;
3426 
3427 		in_fence = sync_file_get_fence(lower_32_bits(args->rsvd2));
3428 		if (!in_fence) {
3429 			err = -EINVAL;
3430 			goto err_ext;
3431 		}
3432 	}
3433 #undef IN_FENCES
3434 
3435 	if (args->flags & I915_EXEC_FENCE_OUT) {
3436 		out_fence_fd = get_unused_fd_flags(O_CLOEXEC);
3437 		if (out_fence_fd < 0) {
3438 			err = out_fence_fd;
3439 			goto err_in_fence;
3440 		}
3441 	}
3442 
3443 	err = eb_create(&eb);
3444 	if (err)
3445 		goto err_out_fence;
3446 
3447 	GEM_BUG_ON(!eb.lut_size);
3448 
3449 	err = eb_select_context(&eb);
3450 	if (unlikely(err))
3451 		goto err_destroy;
3452 
3453 	err = eb_select_engine(&eb);
3454 	if (unlikely(err))
3455 		goto err_context;
3456 
3457 	err = eb_lookup_vmas(&eb);
3458 	if (err) {
3459 		eb_release_vmas(&eb, true);
3460 		goto err_engine;
3461 	}
3462 
3463 	i915_gem_ww_ctx_init(&eb.ww, true);
3464 
3465 	err = eb_relocate_parse(&eb);
3466 	if (err) {
3467 		/*
3468 		 * If the user expects the execobject.offset and
3469 		 * reloc.presumed_offset to be an exact match,
3470 		 * as for using NO_RELOC, then we cannot update
3471 		 * the execobject.offset until we have completed
3472 		 * relocation.
3473 		 */
3474 		args->flags &= ~__EXEC_HAS_RELOC;
3475 		goto err_vma;
3476 	}
3477 
3478 	ww_acquire_done(&eb.ww.ctx);
3479 	err = eb_capture_stage(&eb);
3480 	if (err)
3481 		goto err_vma;
3482 
3483 	out_fence = eb_requests_create(&eb, in_fence, out_fence_fd);
3484 	if (IS_ERR(out_fence)) {
3485 		err = PTR_ERR(out_fence);
3486 		out_fence = NULL;
3487 		if (eb.requests[0])
3488 			goto err_request;
3489 		else
3490 			goto err_vma;
3491 	}
3492 
3493 	err = eb_submit(&eb);
3494 
3495 err_request:
3496 	eb_requests_get(&eb);
3497 	err = eb_requests_add(&eb, err);
3498 
3499 	if (eb.fences)
3500 		signal_fence_array(&eb, eb.composite_fence ?
3501 				   eb.composite_fence :
3502 				   &eb.requests[0]->fence);
3503 
3504 	if (unlikely(eb.gem_context->syncobj)) {
3505 		drm_syncobj_replace_fence(eb.gem_context->syncobj,
3506 					  eb.composite_fence ?
3507 					  eb.composite_fence :
3508 					  &eb.requests[0]->fence);
3509 	}
3510 
3511 	if (out_fence) {
3512 		if (err == 0) {
3513 			fd_install(out_fence_fd, out_fence->file);
3514 			args->rsvd2 &= GENMASK_ULL(31, 0); /* keep in-fence */
3515 			args->rsvd2 |= (u64)out_fence_fd << 32;
3516 			out_fence_fd = -1;
3517 		} else {
3518 			fput(out_fence->file);
3519 		}
3520 	}
3521 
3522 	if (!out_fence && eb.composite_fence)
3523 		dma_fence_put(eb.composite_fence);
3524 
3525 	eb_requests_put(&eb);
3526 
3527 err_vma:
3528 	eb_release_vmas(&eb, true);
3529 	WARN_ON(err == -EDEADLK);
3530 	i915_gem_ww_ctx_fini(&eb.ww);
3531 
3532 	if (eb.batch_pool)
3533 		intel_gt_buffer_pool_put(eb.batch_pool);
3534 err_engine:
3535 	eb_put_engine(&eb);
3536 err_context:
3537 	i915_gem_context_put(eb.gem_context);
3538 err_destroy:
3539 	eb_destroy(&eb);
3540 err_out_fence:
3541 	if (out_fence_fd != -1)
3542 		put_unused_fd(out_fence_fd);
3543 err_in_fence:
3544 	dma_fence_put(in_fence);
3545 err_ext:
3546 	put_fence_array(eb.fences, eb.num_fences);
3547 	return err;
3548 }
3549 
3550 static size_t eb_element_size(void)
3551 {
3552 	return sizeof(struct drm_i915_gem_exec_object2) + sizeof(struct eb_vma);
3553 }
3554 
3555 static bool check_buffer_count(size_t count)
3556 {
3557 	const size_t sz = eb_element_size();
3558 
3559 	/*
3560 	 * When using LUT_HANDLE, we impose a limit of INT_MAX for the lookup
3561 	 * array size (see eb_create()). Otherwise, we can accept an array as
3562 	 * large as can be addressed (though use large arrays at your peril)!
3563 	 */
3564 
3565 	return !(count < 1 || count > INT_MAX || count > SIZE_MAX / sz - 1);
3566 }
3567 
3568 int
3569 i915_gem_execbuffer2_ioctl(struct drm_device *dev, void *data,
3570 			   struct drm_file *file)
3571 {
3572 	struct drm_i915_private *i915 = to_i915(dev);
3573 	struct drm_i915_gem_execbuffer2 *args = data;
3574 	struct drm_i915_gem_exec_object2 *exec2_list;
3575 	const size_t count = args->buffer_count;
3576 	int err;
3577 
3578 	if (!check_buffer_count(count)) {
3579 		drm_dbg(&i915->drm, "execbuf2 with %zd buffers\n", count);
3580 		return -EINVAL;
3581 	}
3582 
3583 	err = i915_gem_check_execbuffer(i915, args);
3584 	if (err)
3585 		return err;
3586 
3587 	/*
3588 	 * Allocate extra slots for use by the command parser.
3589 	 *
3590 	 * Note that this allocation handles two different arrays (the
3591 	 * exec2_list array, and the eventual eb.vma array introduced in
3592 	 * i915_gem_do_execbuffer()), that reside in virtually contiguous
3593 	 * memory. Also note that the allocation intentionally doesn't fill the
3594 	 * area with zeros, because the exec2_list part doesn't need to be, as
3595 	 * it's immediately overwritten by user data a few lines below.
3596 	 * However, the eb.vma part is explicitly zeroed later in
3597 	 * i915_gem_do_execbuffer().
3598 	 */
3599 	exec2_list = kvmalloc_array(count + 2, eb_element_size(),
3600 				    __GFP_NOWARN | GFP_KERNEL);
3601 	if (exec2_list == NULL) {
3602 		drm_dbg(&i915->drm, "Failed to allocate exec list for %zd buffers\n",
3603 			count);
3604 		return -ENOMEM;
3605 	}
3606 	if (copy_from_user(exec2_list,
3607 			   u64_to_user_ptr(args->buffers_ptr),
3608 			   sizeof(*exec2_list) * count)) {
3609 		drm_dbg(&i915->drm, "copy %zd exec entries failed\n", count);
3610 		kvfree(exec2_list);
3611 		return -EFAULT;
3612 	}
3613 
3614 	err = i915_gem_do_execbuffer(dev, file, args, exec2_list);
3615 
3616 	/*
3617 	 * Now that we have begun execution of the batchbuffer, we ignore
3618 	 * any new error after this point. Also given that we have already
3619 	 * updated the associated relocations, we try to write out the current
3620 	 * object locations irrespective of any error.
3621 	 */
3622 	if (args->flags & __EXEC_HAS_RELOC) {
3623 		struct drm_i915_gem_exec_object2 __user *user_exec_list =
3624 			u64_to_user_ptr(args->buffers_ptr);
3625 		unsigned int i;
3626 
3627 		/* Copy the new buffer offsets back to the user's exec list. */
3628 		/*
3629 		 * Note: count * sizeof(*user_exec_list) does not overflow,
3630 		 * because we checked 'count' in check_buffer_count().
3631 		 *
3632 		 * And this range already got effectively checked earlier
3633 		 * when we did the "copy_from_user()" above.
3634 		 */
3635 		if (!user_write_access_begin(user_exec_list,
3636 					     count * sizeof(*user_exec_list)))
3637 			goto end;
3638 
3639 		for (i = 0; i < args->buffer_count; i++) {
3640 			if (!(exec2_list[i].offset & UPDATE))
3641 				continue;
3642 
3643 			exec2_list[i].offset =
3644 				gen8_canonical_addr(exec2_list[i].offset & PIN_OFFSET_MASK);
3645 			unsafe_put_user(exec2_list[i].offset,
3646 					&user_exec_list[i].offset,
3647 					end_user);
3648 		}
3649 end_user:
3650 		user_write_access_end();
3651 end:;
3652 	}
3653 
3654 	args->flags &= ~__I915_EXEC_UNKNOWN_FLAGS;
3655 	kvfree(exec2_list);
3656 	return err;
3657 }
3658