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