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