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