1 /*
2  * SPDX-License-Identifier: MIT
3  *
4  * Copyright © 2008,2010 Intel Corporation
5  */
6 
7 #include <linux/intel-iommu.h>
8 #include <linux/dma-resv.h>
9 #include <linux/sync_file.h>
10 #include <linux/uaccess.h>
11 
12 #include <drm/drm_syncobj.h>
13 
14 #include <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_engine_pool.h"
22 #include "gt/intel_gt.h"
23 #include "gt/intel_gt_pm.h"
24 #include "gt/intel_ring.h"
25 
26 #include "i915_drv.h"
27 #include "i915_gem_clflush.h"
28 #include "i915_gem_context.h"
29 #include "i915_gem_ioctls.h"
30 #include "i915_sw_fence_work.h"
31 #include "i915_trace.h"
32 
33 struct eb_vma {
34 	struct i915_vma *vma;
35 	unsigned int flags;
36 
37 	/** This vma's place in the execbuf reservation list */
38 	struct drm_i915_gem_exec_object2 *exec;
39 	struct list_head bind_link;
40 	struct list_head reloc_link;
41 
42 	struct hlist_node node;
43 	u32 handle;
44 };
45 
46 enum {
47 	FORCE_CPU_RELOC = 1,
48 	FORCE_GTT_RELOC,
49 	FORCE_GPU_RELOC,
50 #define DBG_FORCE_RELOC 0 /* choose one of the above! */
51 };
52 
53 #define __EXEC_OBJECT_HAS_PIN		BIT(31)
54 #define __EXEC_OBJECT_HAS_FENCE		BIT(30)
55 #define __EXEC_OBJECT_NEEDS_MAP		BIT(29)
56 #define __EXEC_OBJECT_NEEDS_BIAS	BIT(28)
57 #define __EXEC_OBJECT_INTERNAL_FLAGS	(~0u << 28) /* all of the above */
58 #define __EXEC_OBJECT_RESERVED (__EXEC_OBJECT_HAS_PIN | __EXEC_OBJECT_HAS_FENCE)
59 
60 #define __EXEC_HAS_RELOC	BIT(31)
61 #define __EXEC_INTERNAL_FLAGS	(~0u << 31)
62 #define UPDATE			PIN_OFFSET_FIXED
63 
64 #define BATCH_OFFSET_BIAS (256*1024)
65 
66 #define __I915_EXEC_ILLEGAL_FLAGS \
67 	(__I915_EXEC_UNKNOWN_FLAGS | \
68 	 I915_EXEC_CONSTANTS_MASK  | \
69 	 I915_EXEC_RESOURCE_STREAMER)
70 
71 /* Catch emission of unexpected errors for CI! */
72 #if IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM)
73 #undef EINVAL
74 #define EINVAL ({ \
75 	DRM_DEBUG_DRIVER("EINVAL at %s:%d\n", __func__, __LINE__); \
76 	22; \
77 })
78 #endif
79 
80 /**
81  * DOC: User command execution
82  *
83  * Userspace submits commands to be executed on the GPU as an instruction
84  * stream within a GEM object we call a batchbuffer. This instructions may
85  * refer to other GEM objects containing auxiliary state such as kernels,
86  * samplers, render targets and even secondary batchbuffers. Userspace does
87  * not know where in the GPU memory these objects reside and so before the
88  * batchbuffer is passed to the GPU for execution, those addresses in the
89  * batchbuffer and auxiliary objects are updated. This is known as relocation,
90  * or patching. To try and avoid having to relocate each object on the next
91  * execution, userspace is told the location of those objects in this pass,
92  * but this remains just a hint as the kernel may choose a new location for
93  * any object in the future.
94  *
95  * At the level of talking to the hardware, submitting a batchbuffer for the
96  * GPU to execute is to add content to a buffer from which the HW
97  * command streamer is reading.
98  *
99  * 1. Add a command to load the HW context. For Logical Ring Contexts, i.e.
100  *    Execlists, this command is not placed on the same buffer as the
101  *    remaining items.
102  *
103  * 2. Add a command to invalidate caches to the buffer.
104  *
105  * 3. Add a batchbuffer start command to the buffer; the start command is
106  *    essentially a token together with the GPU address of the batchbuffer
107  *    to be executed.
108  *
109  * 4. Add a pipeline flush to the buffer.
110  *
111  * 5. Add a memory write command to the buffer to record when the GPU
112  *    is done executing the batchbuffer. The memory write writes the
113  *    global sequence number of the request, ``i915_request::global_seqno``;
114  *    the i915 driver uses the current value in the register to determine
115  *    if the GPU has completed the batchbuffer.
116  *
117  * 6. Add a user interrupt command to the buffer. This command instructs
118  *    the GPU to issue an interrupt when the command, pipeline flush and
119  *    memory write are completed.
120  *
121  * 7. Inform the hardware of the additional commands added to the buffer
122  *    (by updating the tail pointer).
123  *
124  * Processing an execbuf ioctl is conceptually split up into a few phases.
125  *
126  * 1. Validation - Ensure all the pointers, handles and flags are valid.
127  * 2. Reservation - Assign GPU address space for every object
128  * 3. Relocation - Update any addresses to point to the final locations
129  * 4. Serialisation - Order the request with respect to its dependencies
130  * 5. Construction - Construct a request to execute the batchbuffer
131  * 6. Submission (at some point in the future execution)
132  *
133  * Reserving resources for the execbuf is the most complicated phase. We
134  * neither want to have to migrate the object in the address space, nor do
135  * we want to have to update any relocations pointing to this object. Ideally,
136  * we want to leave the object where it is and for all the existing relocations
137  * to match. If the object is given a new address, or if userspace thinks the
138  * object is elsewhere, we have to parse all the relocation entries and update
139  * the addresses. Userspace can set the I915_EXEC_NORELOC flag to hint that
140  * all the target addresses in all of its objects match the value in the
141  * relocation entries and that they all match the presumed offsets given by the
142  * list of execbuffer objects. Using this knowledge, we know that if we haven't
143  * moved any buffers, all the relocation entries are valid and we can skip
144  * the update. (If userspace is wrong, the likely outcome is an impromptu GPU
145  * hang.) The requirement for using I915_EXEC_NO_RELOC are:
146  *
147  *      The addresses written in the objects must match the corresponding
148  *      reloc.presumed_offset which in turn must match the corresponding
149  *      execobject.offset.
150  *
151  *      Any render targets written to in the batch must be flagged with
152  *      EXEC_OBJECT_WRITE.
153  *
154  *      To avoid stalling, execobject.offset should match the current
155  *      address of that object within the active context.
156  *
157  * The reservation is done is multiple phases. First we try and keep any
158  * object already bound in its current location - so as long as meets the
159  * constraints imposed by the new execbuffer. Any object left unbound after the
160  * first pass is then fitted into any available idle space. If an object does
161  * not fit, all objects are removed from the reservation and the process rerun
162  * after sorting the objects into a priority order (more difficult to fit
163  * objects are tried first). Failing that, the entire VM is cleared and we try
164  * to fit the execbuf once last time before concluding that it simply will not
165  * fit.
166  *
167  * A small complication to all of this is that we allow userspace not only to
168  * specify an alignment and a size for the object in the address space, but
169  * we also allow userspace to specify the exact offset. This objects are
170  * simpler to place (the location is known a priori) all we have to do is make
171  * sure the space is available.
172  *
173  * Once all the objects are in place, patching up the buried pointers to point
174  * to the final locations is a fairly simple job of walking over the relocation
175  * entry arrays, looking up the right address and rewriting the value into
176  * the object. Simple! ... The relocation entries are stored in user memory
177  * and so to access them we have to copy them into a local buffer. That copy
178  * has to avoid taking any pagefaults as they may lead back to a GEM object
179  * requiring the struct_mutex (i.e. recursive deadlock). So once again we split
180  * the relocation into multiple passes. First we try to do everything within an
181  * atomic context (avoid the pagefaults) which requires that we never wait. If
182  * we detect that we may wait, or if we need to fault, then we have to fallback
183  * to a slower path. The slowpath has to drop the mutex. (Can you hear alarm
184  * bells yet?) Dropping the mutex means that we lose all the state we have
185  * built up so far for the execbuf and we must reset any global data. However,
186  * we do leave the objects pinned in their final locations - which is a
187  * potential issue for concurrent execbufs. Once we have left the mutex, we can
188  * allocate and copy all the relocation entries into a large array at our
189  * leisure, reacquire the mutex, reclaim all the objects and other state and
190  * then proceed to update any incorrect addresses with the objects.
191  *
192  * As we process the relocation entries, we maintain a record of whether the
193  * object is being written to. Using NORELOC, we expect userspace to provide
194  * this information instead. We also check whether we can skip the relocation
195  * by comparing the expected value inside the relocation entry with the target's
196  * final address. If they differ, we have to map the current object and rewrite
197  * the 4 or 8 byte pointer within.
198  *
199  * Serialising an execbuf is quite simple according to the rules of the GEM
200  * ABI. Execution within each context is ordered by the order of submission.
201  * Writes to any GEM object are in order of submission and are exclusive. Reads
202  * from a GEM object are unordered with respect to other reads, but ordered by
203  * writes. A write submitted after a read cannot occur before the read, and
204  * similarly any read submitted after a write cannot occur before the write.
205  * Writes are ordered between engines such that only one write occurs at any
206  * time (completing any reads beforehand) - using semaphores where available
207  * and CPU serialisation otherwise. Other GEM access obey the same rules, any
208  * write (either via mmaps using set-domain, or via pwrite) must flush all GPU
209  * reads before starting, and any read (either using set-domain or pread) must
210  * flush all GPU writes before starting. (Note we only employ a barrier before,
211  * we currently rely on userspace not concurrently starting a new execution
212  * whilst reading or writing to an object. This may be an advantage or not
213  * depending on how much you trust userspace not to shoot themselves in the
214  * foot.) Serialisation may just result in the request being inserted into
215  * a DAG awaiting its turn, but most simple is to wait on the CPU until
216  * all dependencies are resolved.
217  *
218  * After all of that, is just a matter of closing the request and handing it to
219  * the hardware (well, leaving it in a queue to be executed). However, we also
220  * offer the ability for batchbuffers to be run with elevated privileges so
221  * that they access otherwise hidden registers. (Used to adjust L3 cache etc.)
222  * Before any batch is given extra privileges we first must check that it
223  * contains no nefarious instructions, we check that each instruction is from
224  * our whitelist and all registers are also from an allowed list. We first
225  * copy the user's batchbuffer to a shadow (so that the user doesn't have
226  * access to it, either by the CPU or GPU as we scan it) and then parse each
227  * instruction. If everything is ok, we set a flag telling the hardware to run
228  * the batchbuffer in trusted mode, otherwise the ioctl is rejected.
229  */
230 
231 struct i915_execbuffer {
232 	struct drm_i915_private *i915; /** i915 backpointer */
233 	struct drm_file *file; /** per-file lookup tables and limits */
234 	struct drm_i915_gem_execbuffer2 *args; /** ioctl parameters */
235 	struct drm_i915_gem_exec_object2 *exec; /** ioctl execobj[] */
236 	struct eb_vma *vma;
237 
238 	struct intel_engine_cs *engine; /** engine to queue the request to */
239 	struct intel_context *context; /* logical state for the request */
240 	struct i915_gem_context *gem_context; /** caller's context */
241 
242 	struct i915_request *request; /** our request to build */
243 	struct eb_vma *batch; /** identity of the batch obj/vma */
244 	struct i915_vma *trampoline; /** trampoline used for chaining */
245 
246 	/** actual size of execobj[] as we may extend it for the cmdparser */
247 	unsigned int buffer_count;
248 
249 	/** list of vma not yet bound during reservation phase */
250 	struct list_head unbound;
251 
252 	/** list of vma that have execobj.relocation_count */
253 	struct list_head relocs;
254 
255 	/**
256 	 * Track the most recently used object for relocations, as we
257 	 * frequently have to perform multiple relocations within the same
258 	 * obj/page
259 	 */
260 	struct reloc_cache {
261 		struct drm_mm_node node; /** temporary GTT binding */
262 		unsigned long vaddr; /** Current kmap address */
263 		unsigned long page; /** Currently mapped page index */
264 		unsigned int gen; /** Cached value of INTEL_GEN */
265 		bool use_64bit_reloc : 1;
266 		bool has_llc : 1;
267 		bool has_fence : 1;
268 		bool needs_unfenced : 1;
269 
270 		struct i915_request *rq;
271 		u32 *rq_cmd;
272 		unsigned int rq_size;
273 
274 		struct agp_map *map;
275 		bus_space_tag_t iot;
276 		bus_space_handle_t ioh;
277 	} reloc_cache;
278 
279 	u64 invalid_flags; /** Set of execobj.flags that are invalid */
280 	u32 context_flags; /** Set of execobj.flags to insert from the ctx */
281 
282 	u32 batch_start_offset; /** Location within object of batch */
283 	u32 batch_len; /** Length of batch within object */
284 	u32 batch_flags; /** Flags composed for emit_bb_start() */
285 
286 	/**
287 	 * Indicate either the size of the hastable used to resolve
288 	 * relocation handles, or if negative that we are using a direct
289 	 * index into the execobj[].
290 	 */
291 	int lut_size;
292 	struct hlist_head *buckets; /** ht for relocation handles */
293 };
294 
295 static inline bool eb_use_cmdparser(const struct i915_execbuffer *eb)
296 {
297 	return intel_engine_requires_cmd_parser(eb->engine) ||
298 		(intel_engine_using_cmd_parser(eb->engine) &&
299 		 eb->args->batch_len);
300 }
301 
302 static int eb_create(struct i915_execbuffer *eb)
303 {
304 	if (!(eb->args->flags & I915_EXEC_HANDLE_LUT)) {
305 		unsigned int size = 1 + ilog2(eb->buffer_count);
306 
307 		/*
308 		 * Without a 1:1 association between relocation handles and
309 		 * the execobject[] index, we instead create a hashtable.
310 		 * We size it dynamically based on available memory, starting
311 		 * first with 1:1 assocative hash and scaling back until
312 		 * the allocation succeeds.
313 		 *
314 		 * Later on we use a positive lut_size to indicate we are
315 		 * using this hashtable, and a negative value to indicate a
316 		 * direct lookup.
317 		 */
318 		do {
319 			gfp_t flags;
320 
321 			/* While we can still reduce the allocation size, don't
322 			 * raise a warning and allow the allocation to fail.
323 			 * On the last pass though, we want to try as hard
324 			 * as possible to perform the allocation and warn
325 			 * if it fails.
326 			 */
327 			flags = GFP_KERNEL;
328 			if (size > 1)
329 				flags |= __GFP_NORETRY | __GFP_NOWARN;
330 
331 			eb->buckets = kzalloc(sizeof(struct hlist_head) << size,
332 					      flags);
333 			if (eb->buckets)
334 				break;
335 		} while (--size);
336 
337 		if (unlikely(!size))
338 			return -ENOMEM;
339 
340 		eb->lut_size = size;
341 	} else {
342 		eb->lut_size = -eb->buffer_count;
343 	}
344 
345 	return 0;
346 }
347 
348 static bool
349 eb_vma_misplaced(const struct drm_i915_gem_exec_object2 *entry,
350 		 const struct i915_vma *vma,
351 		 unsigned int flags)
352 {
353 	if (vma->node.size < entry->pad_to_size)
354 		return true;
355 
356 	if (entry->alignment && !IS_ALIGNED(vma->node.start, entry->alignment))
357 		return true;
358 
359 	if (flags & EXEC_OBJECT_PINNED &&
360 	    vma->node.start != entry->offset)
361 		return true;
362 
363 	if (flags & __EXEC_OBJECT_NEEDS_BIAS &&
364 	    vma->node.start < BATCH_OFFSET_BIAS)
365 		return true;
366 
367 	if (!(flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS) &&
368 	    (vma->node.start + vma->node.size - 1) >> 32)
369 		return true;
370 
371 	if (flags & __EXEC_OBJECT_NEEDS_MAP &&
372 	    !i915_vma_is_map_and_fenceable(vma))
373 		return true;
374 
375 	return false;
376 }
377 
378 static inline bool
379 eb_pin_vma(struct i915_execbuffer *eb,
380 	   const struct drm_i915_gem_exec_object2 *entry,
381 	   struct eb_vma *ev)
382 {
383 	struct i915_vma *vma = ev->vma;
384 	u64 pin_flags;
385 
386 	if (vma->node.size)
387 		pin_flags = vma->node.start;
388 	else
389 		pin_flags = entry->offset & PIN_OFFSET_MASK;
390 
391 	pin_flags |= PIN_USER | PIN_NOEVICT | PIN_OFFSET_FIXED;
392 	if (unlikely(ev->flags & EXEC_OBJECT_NEEDS_GTT))
393 		pin_flags |= PIN_GLOBAL;
394 
395 	if (unlikely(i915_vma_pin(vma, 0, 0, pin_flags)))
396 		return false;
397 
398 	if (unlikely(ev->flags & EXEC_OBJECT_NEEDS_FENCE)) {
399 		if (unlikely(i915_vma_pin_fence(vma))) {
400 			i915_vma_unpin(vma);
401 			return false;
402 		}
403 
404 		if (vma->fence)
405 			ev->flags |= __EXEC_OBJECT_HAS_FENCE;
406 	}
407 
408 	ev->flags |= __EXEC_OBJECT_HAS_PIN;
409 	return !eb_vma_misplaced(entry, vma, ev->flags);
410 }
411 
412 static inline void __eb_unreserve_vma(struct i915_vma *vma, unsigned int flags)
413 {
414 	GEM_BUG_ON(!(flags & __EXEC_OBJECT_HAS_PIN));
415 
416 	if (unlikely(flags & __EXEC_OBJECT_HAS_FENCE))
417 		__i915_vma_unpin_fence(vma);
418 
419 	__i915_vma_unpin(vma);
420 }
421 
422 static inline void
423 eb_unreserve_vma(struct eb_vma *ev)
424 {
425 	if (!(ev->flags & __EXEC_OBJECT_HAS_PIN))
426 		return;
427 
428 	__eb_unreserve_vma(ev->vma, ev->flags);
429 	ev->flags &= ~__EXEC_OBJECT_RESERVED;
430 }
431 
432 static int
433 eb_validate_vma(struct i915_execbuffer *eb,
434 		struct drm_i915_gem_exec_object2 *entry,
435 		struct i915_vma *vma)
436 {
437 	if (unlikely(entry->flags & eb->invalid_flags))
438 		return -EINVAL;
439 
440 	if (unlikely(entry->alignment &&
441 		     !is_power_of_2_u64(entry->alignment)))
442 		return -EINVAL;
443 
444 	/*
445 	 * Offset can be used as input (EXEC_OBJECT_PINNED), reject
446 	 * any non-page-aligned or non-canonical addresses.
447 	 */
448 	if (unlikely(entry->flags & EXEC_OBJECT_PINNED &&
449 		     entry->offset != gen8_canonical_addr(entry->offset & I915_GTT_PAGE_MASK)))
450 		return -EINVAL;
451 
452 	/* pad_to_size was once a reserved field, so sanitize it */
453 	if (entry->flags & EXEC_OBJECT_PAD_TO_SIZE) {
454 		if (unlikely(offset_in_page(entry->pad_to_size)))
455 			return -EINVAL;
456 	} else {
457 		entry->pad_to_size = 0;
458 	}
459 	/*
460 	 * From drm_mm perspective address space is continuous,
461 	 * so from this point we're always using non-canonical
462 	 * form internally.
463 	 */
464 	entry->offset = gen8_noncanonical_addr(entry->offset);
465 
466 	if (!eb->reloc_cache.has_fence) {
467 		entry->flags &= ~EXEC_OBJECT_NEEDS_FENCE;
468 	} else {
469 		if ((entry->flags & EXEC_OBJECT_NEEDS_FENCE ||
470 		     eb->reloc_cache.needs_unfenced) &&
471 		    i915_gem_object_is_tiled(vma->obj))
472 			entry->flags |= EXEC_OBJECT_NEEDS_GTT | __EXEC_OBJECT_NEEDS_MAP;
473 	}
474 
475 	if (!(entry->flags & EXEC_OBJECT_PINNED))
476 		entry->flags |= eb->context_flags;
477 
478 	return 0;
479 }
480 
481 static void
482 eb_add_vma(struct i915_execbuffer *eb,
483 	   unsigned int i, unsigned batch_idx,
484 	   struct i915_vma *vma)
485 {
486 	struct drm_i915_gem_exec_object2 *entry = &eb->exec[i];
487 	struct eb_vma *ev = &eb->vma[i];
488 
489 	GEM_BUG_ON(i915_vma_is_closed(vma));
490 
491 	ev->vma = i915_vma_get(vma);
492 	ev->exec = entry;
493 	ev->flags = entry->flags;
494 
495 	if (eb->lut_size > 0) {
496 		ev->handle = entry->handle;
497 		hlist_add_head(&ev->node,
498 			       &eb->buckets[hash_32(entry->handle,
499 						    eb->lut_size)]);
500 	}
501 
502 	if (entry->relocation_count)
503 		list_add_tail(&ev->reloc_link, &eb->relocs);
504 
505 	/*
506 	 * SNA is doing fancy tricks with compressing batch buffers, which leads
507 	 * to negative relocation deltas. Usually that works out ok since the
508 	 * relocate address is still positive, except when the batch is placed
509 	 * very low in the GTT. Ensure this doesn't happen.
510 	 *
511 	 * Note that actual hangs have only been observed on gen7, but for
512 	 * paranoia do it everywhere.
513 	 */
514 	if (i == batch_idx) {
515 		if (entry->relocation_count &&
516 		    !(ev->flags & EXEC_OBJECT_PINNED))
517 			ev->flags |= __EXEC_OBJECT_NEEDS_BIAS;
518 		if (eb->reloc_cache.has_fence)
519 			ev->flags |= EXEC_OBJECT_NEEDS_FENCE;
520 
521 		eb->batch = ev;
522 	}
523 
524 	if (eb_pin_vma(eb, entry, ev)) {
525 		if (entry->offset != vma->node.start) {
526 			entry->offset = vma->node.start | UPDATE;
527 			eb->args->flags |= __EXEC_HAS_RELOC;
528 		}
529 	} else {
530 		eb_unreserve_vma(ev);
531 		list_add_tail(&ev->bind_link, &eb->unbound);
532 	}
533 }
534 
535 static inline int use_cpu_reloc(const struct reloc_cache *cache,
536 				const struct drm_i915_gem_object *obj)
537 {
538 	if (!i915_gem_object_has_struct_page(obj))
539 		return false;
540 
541 	if (DBG_FORCE_RELOC == FORCE_CPU_RELOC)
542 		return true;
543 
544 	if (DBG_FORCE_RELOC == FORCE_GTT_RELOC)
545 		return false;
546 
547 	return (cache->has_llc ||
548 		obj->cache_dirty ||
549 		obj->cache_level != I915_CACHE_NONE);
550 }
551 
552 static int eb_reserve_vma(const struct i915_execbuffer *eb,
553 			  struct eb_vma *ev,
554 			  u64 pin_flags)
555 {
556 	struct drm_i915_gem_exec_object2 *entry = ev->exec;
557 	unsigned int exec_flags = ev->flags;
558 	struct i915_vma *vma = ev->vma;
559 	int err;
560 
561 	if (exec_flags & EXEC_OBJECT_NEEDS_GTT)
562 		pin_flags |= PIN_GLOBAL;
563 
564 	/*
565 	 * Wa32bitGeneralStateOffset & Wa32bitInstructionBaseOffset,
566 	 * limit address to the first 4GBs for unflagged objects.
567 	 */
568 	if (!(exec_flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS))
569 		pin_flags |= PIN_ZONE_4G;
570 
571 	if (exec_flags & __EXEC_OBJECT_NEEDS_MAP)
572 		pin_flags |= PIN_MAPPABLE;
573 
574 	if (exec_flags & EXEC_OBJECT_PINNED)
575 		pin_flags |= entry->offset | PIN_OFFSET_FIXED;
576 	else if (exec_flags & __EXEC_OBJECT_NEEDS_BIAS)
577 		pin_flags |= BATCH_OFFSET_BIAS | PIN_OFFSET_BIAS;
578 
579 	if (drm_mm_node_allocated(&vma->node) &&
580 	    eb_vma_misplaced(entry, vma, ev->flags)) {
581 		err = i915_vma_unbind(vma);
582 		if (err)
583 			return err;
584 	}
585 
586 	err = i915_vma_pin(vma,
587 			   entry->pad_to_size, entry->alignment,
588 			   pin_flags);
589 	if (err)
590 		return err;
591 
592 	if (entry->offset != vma->node.start) {
593 		entry->offset = vma->node.start | UPDATE;
594 		eb->args->flags |= __EXEC_HAS_RELOC;
595 	}
596 
597 	if (unlikely(exec_flags & EXEC_OBJECT_NEEDS_FENCE)) {
598 		err = i915_vma_pin_fence(vma);
599 		if (unlikely(err)) {
600 			i915_vma_unpin(vma);
601 			return err;
602 		}
603 
604 		if (vma->fence)
605 			exec_flags |= __EXEC_OBJECT_HAS_FENCE;
606 	}
607 
608 	ev->flags = exec_flags | __EXEC_OBJECT_HAS_PIN;
609 	GEM_BUG_ON(eb_vma_misplaced(entry, vma, ev->flags));
610 
611 	return 0;
612 }
613 
614 static int eb_reserve(struct i915_execbuffer *eb)
615 {
616 	const unsigned int count = eb->buffer_count;
617 	unsigned int pin_flags = PIN_USER | PIN_NONBLOCK;
618 	struct list_head last;
619 	struct eb_vma *ev;
620 	unsigned int i, pass;
621 	int err = 0;
622 
623 	/*
624 	 * Attempt to pin all of the buffers into the GTT.
625 	 * This is done in 3 phases:
626 	 *
627 	 * 1a. Unbind all objects that do not match the GTT constraints for
628 	 *     the execbuffer (fenceable, mappable, alignment etc).
629 	 * 1b. Increment pin count for already bound objects.
630 	 * 2.  Bind new objects.
631 	 * 3.  Decrement pin count.
632 	 *
633 	 * This avoid unnecessary unbinding of later objects in order to make
634 	 * room for the earlier objects *unless* we need to defragment.
635 	 */
636 
637 	if (mutex_lock_interruptible(&eb->i915->drm.struct_mutex))
638 		return -EINTR;
639 
640 	pass = 0;
641 	do {
642 		list_for_each_entry(ev, &eb->unbound, bind_link) {
643 			err = eb_reserve_vma(eb, ev, pin_flags);
644 			if (err)
645 				break;
646 		}
647 		if (!(err == -ENOSPC || err == -EAGAIN))
648 			break;
649 
650 		/* Resort *all* the objects into priority order */
651 		INIT_LIST_HEAD(&eb->unbound);
652 		INIT_LIST_HEAD(&last);
653 		for (i = 0; i < count; i++) {
654 			unsigned int flags;
655 
656 			ev = &eb->vma[i];
657 			flags = ev->flags;
658 			if (flags & EXEC_OBJECT_PINNED &&
659 			    flags & __EXEC_OBJECT_HAS_PIN)
660 				continue;
661 
662 			eb_unreserve_vma(ev);
663 
664 			if (flags & EXEC_OBJECT_PINNED)
665 				/* Pinned must have their slot */
666 				list_add(&ev->bind_link, &eb->unbound);
667 			else if (flags & __EXEC_OBJECT_NEEDS_MAP)
668 				/* Map require the lowest 256MiB (aperture) */
669 				list_add_tail(&ev->bind_link, &eb->unbound);
670 			else if (!(flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS))
671 				/* Prioritise 4GiB region for restricted bo */
672 				list_add(&ev->bind_link, &last);
673 			else
674 				list_add_tail(&ev->bind_link, &last);
675 		}
676 		list_splice_tail(&last, &eb->unbound);
677 
678 		if (err == -EAGAIN) {
679 			mutex_unlock(&eb->i915->drm.struct_mutex);
680 			flush_workqueue(eb->i915->mm.userptr_wq);
681 			mutex_lock(&eb->i915->drm.struct_mutex);
682 			continue;
683 		}
684 
685 		switch (pass++) {
686 		case 0:
687 			break;
688 
689 		case 1:
690 			/* Too fragmented, unbind everything and retry */
691 			mutex_lock(&eb->context->vm->mutex);
692 			err = i915_gem_evict_vm(eb->context->vm);
693 			mutex_unlock(&eb->context->vm->mutex);
694 			if (err)
695 				goto unlock;
696 			break;
697 
698 		default:
699 			err = -ENOSPC;
700 			goto unlock;
701 		}
702 
703 		pin_flags = PIN_USER;
704 	} while (1);
705 
706 unlock:
707 	mutex_unlock(&eb->i915->drm.struct_mutex);
708 	return err;
709 }
710 
711 static unsigned int eb_batch_index(const struct i915_execbuffer *eb)
712 {
713 	if (eb->args->flags & I915_EXEC_BATCH_FIRST)
714 		return 0;
715 	else
716 		return eb->buffer_count - 1;
717 }
718 
719 static int eb_select_context(struct i915_execbuffer *eb)
720 {
721 	struct i915_gem_context *ctx;
722 
723 	ctx = i915_gem_context_lookup(eb->file->driver_priv, eb->args->rsvd1);
724 	if (unlikely(!ctx))
725 		return -ENOENT;
726 
727 	eb->gem_context = ctx;
728 	if (rcu_access_pointer(ctx->vm))
729 		eb->invalid_flags |= EXEC_OBJECT_NEEDS_GTT;
730 
731 	eb->context_flags = 0;
732 	if (test_bit(UCONTEXT_NO_ZEROMAP, &ctx->user_flags))
733 		eb->context_flags |= __EXEC_OBJECT_NEEDS_BIAS;
734 
735 	return 0;
736 }
737 
738 static int eb_lookup_vmas(struct i915_execbuffer *eb)
739 {
740 	struct radix_tree_root *handles_vma = &eb->gem_context->handles_vma;
741 	struct drm_i915_gem_object *obj;
742 	unsigned int i, batch;
743 	int err;
744 
745 	if (unlikely(i915_gem_context_is_closed(eb->gem_context)))
746 		return -ENOENT;
747 
748 	INIT_LIST_HEAD(&eb->relocs);
749 	INIT_LIST_HEAD(&eb->unbound);
750 
751 	batch = eb_batch_index(eb);
752 
753 	for (i = 0; i < eb->buffer_count; i++) {
754 		u32 handle = eb->exec[i].handle;
755 		struct i915_lut_handle *lut;
756 		struct i915_vma *vma;
757 
758 		vma = radix_tree_lookup(handles_vma, handle);
759 		if (likely(vma))
760 			goto add_vma;
761 
762 		obj = i915_gem_object_lookup(eb->file, handle);
763 		if (unlikely(!obj)) {
764 			err = -ENOENT;
765 			goto err_vma;
766 		}
767 
768 		vma = i915_vma_instance(obj, eb->context->vm, NULL);
769 		if (IS_ERR(vma)) {
770 			err = PTR_ERR(vma);
771 			goto err_obj;
772 		}
773 
774 		lut = i915_lut_handle_alloc();
775 		if (unlikely(!lut)) {
776 			err = -ENOMEM;
777 			goto err_obj;
778 		}
779 
780 		err = radix_tree_insert(handles_vma, handle, vma);
781 		if (unlikely(err)) {
782 			i915_lut_handle_free(lut);
783 			goto err_obj;
784 		}
785 
786 		/* transfer ref to lut */
787 		if (!atomic_fetch_inc(&vma->open_count))
788 			i915_vma_reopen(vma);
789 		lut->handle = handle;
790 		lut->ctx = eb->gem_context;
791 
792 		i915_gem_object_lock(obj);
793 		list_add(&lut->obj_link, &obj->lut_list);
794 		i915_gem_object_unlock(obj);
795 
796 add_vma:
797 		err = eb_validate_vma(eb, &eb->exec[i], vma);
798 		if (unlikely(err))
799 			goto err_vma;
800 
801 		eb_add_vma(eb, i, batch, vma);
802 	}
803 
804 	return 0;
805 
806 err_obj:
807 	i915_gem_object_put(obj);
808 err_vma:
809 	eb->vma[i].vma = NULL;
810 	return err;
811 }
812 
813 static struct eb_vma *
814 eb_get_vma(const struct i915_execbuffer *eb, unsigned long handle)
815 {
816 	if (eb->lut_size < 0) {
817 		if (handle >= -eb->lut_size)
818 			return NULL;
819 		return &eb->vma[handle];
820 	} else {
821 		struct hlist_head *head;
822 		struct eb_vma *ev;
823 
824 		head = &eb->buckets[hash_32(handle, eb->lut_size)];
825 		hlist_for_each_entry(ev, head, node) {
826 			if (ev->handle == handle)
827 				return ev;
828 		}
829 		return NULL;
830 	}
831 }
832 
833 static void eb_release_vmas(const struct i915_execbuffer *eb)
834 {
835 	const unsigned int count = eb->buffer_count;
836 	unsigned int i;
837 
838 	for (i = 0; i < count; i++) {
839 		struct eb_vma *ev = &eb->vma[i];
840 		struct i915_vma *vma = ev->vma;
841 
842 		if (!vma)
843 			break;
844 
845 		eb->vma[i].vma = NULL;
846 
847 		if (ev->flags & __EXEC_OBJECT_HAS_PIN)
848 			__eb_unreserve_vma(vma, ev->flags);
849 
850 		i915_vma_put(vma);
851 	}
852 }
853 
854 static void eb_destroy(const struct i915_execbuffer *eb)
855 {
856 	GEM_BUG_ON(eb->reloc_cache.rq);
857 
858 	if (eb->lut_size > 0)
859 		kfree(eb->buckets);
860 }
861 
862 static inline u64
863 relocation_target(const struct drm_i915_gem_relocation_entry *reloc,
864 		  const struct i915_vma *target)
865 {
866 	return gen8_canonical_addr((int)reloc->delta + target->node.start);
867 }
868 
869 static void reloc_cache_init(struct reloc_cache *cache,
870 			     struct drm_i915_private *i915)
871 {
872 	cache->page = -1;
873 	cache->vaddr = 0;
874 	/* Must be a variable in the struct to allow GCC to unroll. */
875 	cache->gen = INTEL_GEN(i915);
876 	cache->has_llc = HAS_LLC(i915);
877 	cache->use_64bit_reloc = HAS_64BIT_RELOC(i915);
878 	cache->has_fence = cache->gen < 4;
879 	cache->needs_unfenced = INTEL_INFO(i915)->unfenced_needs_alignment;
880 	cache->node.flags = 0;
881 	cache->rq = NULL;
882 	cache->rq_size = 0;
883 
884 	cache->map = i915->agph;
885 	cache->iot = i915->bst;
886 }
887 
888 static inline void *unmask_page(unsigned long p)
889 {
890 	return (void *)(uintptr_t)(p & ~PAGE_MASK);
891 }
892 
893 static inline unsigned int unmask_flags(unsigned long p)
894 {
895 	return p & PAGE_MASK;
896 }
897 
898 #define KMAP 0x4 /* after CLFLUSH_FLAGS */
899 
900 static inline struct i915_ggtt *cache_to_ggtt(struct reloc_cache *cache)
901 {
902 	struct drm_i915_private *i915 =
903 		container_of(cache, struct i915_execbuffer, reloc_cache)->i915;
904 	return &i915->ggtt;
905 }
906 
907 static void reloc_gpu_flush(struct reloc_cache *cache)
908 {
909 	struct drm_i915_gem_object *obj = cache->rq->batch->obj;
910 
911 	GEM_BUG_ON(cache->rq_size >= obj->base.size / sizeof(u32));
912 	cache->rq_cmd[cache->rq_size] = MI_BATCH_BUFFER_END;
913 
914 	__i915_gem_object_flush_map(obj, 0, sizeof(u32) * (cache->rq_size + 1));
915 	i915_gem_object_unpin_map(obj);
916 
917 	intel_gt_chipset_flush(cache->rq->engine->gt);
918 
919 	i915_request_add(cache->rq);
920 	cache->rq = NULL;
921 }
922 
923 static void reloc_cache_reset(struct reloc_cache *cache)
924 {
925 	void *vaddr;
926 
927 	if (cache->rq)
928 		reloc_gpu_flush(cache);
929 
930 	if (!cache->vaddr)
931 		return;
932 
933 	vaddr = unmask_page(cache->vaddr);
934 	if (cache->vaddr & KMAP) {
935 		if (cache->vaddr & CLFLUSH_AFTER)
936 			mb();
937 
938 		kunmap_atomic(vaddr);
939 		i915_gem_object_finish_access((struct drm_i915_gem_object *)cache->node.mm);
940 	} else {
941 		struct i915_ggtt *ggtt = cache_to_ggtt(cache);
942 
943 		intel_gt_flush_ggtt_writes(ggtt->vm.gt);
944 #ifdef __linux__
945 		io_mapping_unmap_atomic((void __iomem *)vaddr);
946 #else
947 		agp_unmap_atomic(cache->map, cache->ioh);
948 #endif
949 
950 		if (drm_mm_node_allocated(&cache->node)) {
951 			ggtt->vm.clear_range(&ggtt->vm,
952 					     cache->node.start,
953 					     cache->node.size);
954 			mutex_lock(&ggtt->vm.mutex);
955 			drm_mm_remove_node(&cache->node);
956 			mutex_unlock(&ggtt->vm.mutex);
957 		} else {
958 			i915_vma_unpin((struct i915_vma *)cache->node.mm);
959 		}
960 	}
961 
962 	cache->vaddr = 0;
963 	cache->page = -1;
964 }
965 
966 static void *reloc_kmap(struct drm_i915_gem_object *obj,
967 			struct reloc_cache *cache,
968 			unsigned long page)
969 {
970 	void *vaddr;
971 
972 	if (cache->vaddr) {
973 		kunmap_atomic(unmask_page(cache->vaddr));
974 	} else {
975 		unsigned int flushes;
976 		int err;
977 
978 		err = i915_gem_object_prepare_write(obj, &flushes);
979 		if (err)
980 			return ERR_PTR(err);
981 
982 		BUILD_BUG_ON(KMAP & CLFLUSH_FLAGS);
983 		BUILD_BUG_ON((KMAP | CLFLUSH_FLAGS) & ~PAGE_MASK);
984 
985 		cache->vaddr = flushes | KMAP;
986 		cache->node.mm = (void *)obj;
987 		if (flushes)
988 			mb();
989 	}
990 
991 	vaddr = kmap_atomic(i915_gem_object_get_dirty_page(obj, page));
992 	cache->vaddr = unmask_flags(cache->vaddr) | (unsigned long)vaddr;
993 	cache->page = page;
994 
995 	return vaddr;
996 }
997 
998 static void *reloc_iomap(struct drm_i915_gem_object *obj,
999 			 struct reloc_cache *cache,
1000 			 unsigned long page)
1001 {
1002 	struct i915_ggtt *ggtt = cache_to_ggtt(cache);
1003 	unsigned long offset;
1004 	void *vaddr;
1005 
1006 	if (cache->vaddr) {
1007 		intel_gt_flush_ggtt_writes(ggtt->vm.gt);
1008 #ifdef __linux__
1009 		io_mapping_unmap_atomic((void __force __iomem *) unmask_page(cache->vaddr));
1010 #else
1011 		agp_unmap_atomic(cache->map, cache->ioh);
1012 #endif
1013 	} else {
1014 		struct i915_vma *vma;
1015 		int err;
1016 
1017 		if (i915_gem_object_is_tiled(obj))
1018 			return ERR_PTR(-EINVAL);
1019 
1020 		if (use_cpu_reloc(cache, obj))
1021 			return NULL;
1022 
1023 		i915_gem_object_lock(obj);
1024 		err = i915_gem_object_set_to_gtt_domain(obj, true);
1025 		i915_gem_object_unlock(obj);
1026 		if (err)
1027 			return ERR_PTR(err);
1028 
1029 		vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
1030 					       PIN_MAPPABLE |
1031 					       PIN_NONBLOCK /* NOWARN */ |
1032 					       PIN_NOEVICT);
1033 		if (IS_ERR(vma)) {
1034 			memset(&cache->node, 0, sizeof(cache->node));
1035 			mutex_lock(&ggtt->vm.mutex);
1036 			err = drm_mm_insert_node_in_range
1037 				(&ggtt->vm.mm, &cache->node,
1038 				 PAGE_SIZE, 0, I915_COLOR_UNEVICTABLE,
1039 				 0, ggtt->mappable_end,
1040 				 DRM_MM_INSERT_LOW);
1041 			mutex_unlock(&ggtt->vm.mutex);
1042 			if (err) /* no inactive aperture space, use cpu reloc */
1043 				return NULL;
1044 		} else {
1045 			cache->node.start = vma->node.start;
1046 			cache->node.mm = (void *)vma;
1047 		}
1048 	}
1049 
1050 	offset = cache->node.start;
1051 	if (drm_mm_node_allocated(&cache->node)) {
1052 		ggtt->vm.insert_page(&ggtt->vm,
1053 				     i915_gem_object_get_dma_address(obj, page),
1054 				     offset, I915_CACHE_NONE, 0);
1055 	} else {
1056 		offset += page << PAGE_SHIFT;
1057 	}
1058 
1059 #ifdef __linux__
1060 	vaddr = (void __force *)io_mapping_map_atomic_wc(&ggtt->iomap,
1061 							 offset);
1062 #else
1063 	agp_map_atomic(cache->map, offset, &cache->ioh);
1064 	vaddr = bus_space_vaddr(cache->iot, cache->ioh);
1065 #endif
1066 	cache->page = page;
1067 	cache->vaddr = (unsigned long)vaddr;
1068 
1069 	return vaddr;
1070 }
1071 
1072 static void *reloc_vaddr(struct drm_i915_gem_object *obj,
1073 			 struct reloc_cache *cache,
1074 			 unsigned long page)
1075 {
1076 	void *vaddr;
1077 
1078 	if (cache->page == page) {
1079 		vaddr = unmask_page(cache->vaddr);
1080 	} else {
1081 		vaddr = NULL;
1082 		if ((cache->vaddr & KMAP) == 0)
1083 			vaddr = reloc_iomap(obj, cache, page);
1084 		if (!vaddr)
1085 			vaddr = reloc_kmap(obj, cache, page);
1086 	}
1087 
1088 	return vaddr;
1089 }
1090 
1091 static void clflush_write32(u32 *addr, u32 value, unsigned int flushes)
1092 {
1093 	if (unlikely(flushes & (CLFLUSH_BEFORE | CLFLUSH_AFTER))) {
1094 		if (flushes & CLFLUSH_BEFORE) {
1095 			clflushopt(addr);
1096 			mb();
1097 		}
1098 
1099 		*addr = value;
1100 
1101 		/*
1102 		 * Writes to the same cacheline are serialised by the CPU
1103 		 * (including clflush). On the write path, we only require
1104 		 * that it hits memory in an orderly fashion and place
1105 		 * mb barriers at the start and end of the relocation phase
1106 		 * to ensure ordering of clflush wrt to the system.
1107 		 */
1108 		if (flushes & CLFLUSH_AFTER)
1109 			clflushopt(addr);
1110 	} else
1111 		*addr = value;
1112 }
1113 
1114 static int reloc_move_to_gpu(struct i915_request *rq, struct i915_vma *vma)
1115 {
1116 	struct drm_i915_gem_object *obj = vma->obj;
1117 	int err;
1118 
1119 	i915_vma_lock(vma);
1120 
1121 	if (obj->cache_dirty & ~obj->cache_coherent)
1122 		i915_gem_clflush_object(obj, 0);
1123 	obj->write_domain = 0;
1124 
1125 	err = i915_request_await_object(rq, vma->obj, true);
1126 	if (err == 0)
1127 		err = i915_vma_move_to_active(vma, rq, EXEC_OBJECT_WRITE);
1128 
1129 	i915_vma_unlock(vma);
1130 
1131 	return err;
1132 }
1133 
1134 static int __reloc_gpu_alloc(struct i915_execbuffer *eb,
1135 			     struct i915_vma *vma,
1136 			     unsigned int len)
1137 {
1138 	struct reloc_cache *cache = &eb->reloc_cache;
1139 	struct intel_engine_pool_node *pool;
1140 	struct i915_request *rq;
1141 	struct i915_vma *batch;
1142 	u32 *cmd;
1143 	int err;
1144 
1145 	pool = intel_engine_get_pool(eb->engine, PAGE_SIZE);
1146 	if (IS_ERR(pool))
1147 		return PTR_ERR(pool);
1148 
1149 	cmd = i915_gem_object_pin_map(pool->obj,
1150 				      cache->has_llc ?
1151 				      I915_MAP_FORCE_WB :
1152 				      I915_MAP_FORCE_WC);
1153 	if (IS_ERR(cmd)) {
1154 		err = PTR_ERR(cmd);
1155 		goto out_pool;
1156 	}
1157 
1158 	batch = i915_vma_instance(pool->obj, vma->vm, NULL);
1159 	if (IS_ERR(batch)) {
1160 		err = PTR_ERR(batch);
1161 		goto err_unmap;
1162 	}
1163 
1164 	err = i915_vma_pin(batch, 0, 0, PIN_USER | PIN_NONBLOCK);
1165 	if (err)
1166 		goto err_unmap;
1167 
1168 	rq = i915_request_create(eb->context);
1169 	if (IS_ERR(rq)) {
1170 		err = PTR_ERR(rq);
1171 		goto err_unpin;
1172 	}
1173 
1174 	err = intel_engine_pool_mark_active(pool, rq);
1175 	if (err)
1176 		goto err_request;
1177 
1178 	err = reloc_move_to_gpu(rq, vma);
1179 	if (err)
1180 		goto err_request;
1181 
1182 	err = eb->engine->emit_bb_start(rq,
1183 					batch->node.start, PAGE_SIZE,
1184 					cache->gen > 5 ? 0 : I915_DISPATCH_SECURE);
1185 	if (err)
1186 		goto skip_request;
1187 
1188 	i915_vma_lock(batch);
1189 	err = i915_request_await_object(rq, batch->obj, false);
1190 	if (err == 0)
1191 		err = i915_vma_move_to_active(batch, rq, 0);
1192 	i915_vma_unlock(batch);
1193 	if (err)
1194 		goto skip_request;
1195 
1196 	rq->batch = batch;
1197 	i915_vma_unpin(batch);
1198 
1199 	cache->rq = rq;
1200 	cache->rq_cmd = cmd;
1201 	cache->rq_size = 0;
1202 
1203 	/* Return with batch mapping (cmd) still pinned */
1204 	goto out_pool;
1205 
1206 skip_request:
1207 	i915_request_set_error_once(rq, err);
1208 err_request:
1209 	i915_request_add(rq);
1210 err_unpin:
1211 	i915_vma_unpin(batch);
1212 err_unmap:
1213 	i915_gem_object_unpin_map(pool->obj);
1214 out_pool:
1215 	intel_engine_pool_put(pool);
1216 	return err;
1217 }
1218 
1219 static u32 *reloc_gpu(struct i915_execbuffer *eb,
1220 		      struct i915_vma *vma,
1221 		      unsigned int len)
1222 {
1223 	struct reloc_cache *cache = &eb->reloc_cache;
1224 	u32 *cmd;
1225 
1226 	if (cache->rq_size > PAGE_SIZE/sizeof(u32) - (len + 1))
1227 		reloc_gpu_flush(cache);
1228 
1229 	if (unlikely(!cache->rq)) {
1230 		int err;
1231 
1232 		if (!intel_engine_can_store_dword(eb->engine))
1233 			return ERR_PTR(-ENODEV);
1234 
1235 		err = __reloc_gpu_alloc(eb, vma, len);
1236 		if (unlikely(err))
1237 			return ERR_PTR(err);
1238 	}
1239 
1240 	cmd = cache->rq_cmd + cache->rq_size;
1241 	cache->rq_size += len;
1242 
1243 	return cmd;
1244 }
1245 
1246 static u64
1247 relocate_entry(struct i915_vma *vma,
1248 	       const struct drm_i915_gem_relocation_entry *reloc,
1249 	       struct i915_execbuffer *eb,
1250 	       const struct i915_vma *target)
1251 {
1252 	u64 offset = reloc->offset;
1253 	u64 target_offset = relocation_target(reloc, target);
1254 	bool wide = eb->reloc_cache.use_64bit_reloc;
1255 	void *vaddr;
1256 
1257 	if (!eb->reloc_cache.vaddr &&
1258 	    (DBG_FORCE_RELOC == FORCE_GPU_RELOC ||
1259 	     !dma_resv_test_signaled_rcu(vma->resv, true))) {
1260 		const unsigned int gen = eb->reloc_cache.gen;
1261 		unsigned int len;
1262 		u32 *batch;
1263 		u64 addr;
1264 
1265 		if (wide)
1266 			len = offset & 7 ? 8 : 5;
1267 		else if (gen >= 4)
1268 			len = 4;
1269 		else
1270 			len = 3;
1271 
1272 		batch = reloc_gpu(eb, vma, len);
1273 		if (IS_ERR(batch))
1274 			goto repeat;
1275 
1276 		addr = gen8_canonical_addr(vma->node.start + offset);
1277 		if (wide) {
1278 			if (offset & 7) {
1279 				*batch++ = MI_STORE_DWORD_IMM_GEN4;
1280 				*batch++ = lower_32_bits(addr);
1281 				*batch++ = upper_32_bits(addr);
1282 				*batch++ = lower_32_bits(target_offset);
1283 
1284 				addr = gen8_canonical_addr(addr + 4);
1285 
1286 				*batch++ = MI_STORE_DWORD_IMM_GEN4;
1287 				*batch++ = lower_32_bits(addr);
1288 				*batch++ = upper_32_bits(addr);
1289 				*batch++ = upper_32_bits(target_offset);
1290 			} else {
1291 				*batch++ = (MI_STORE_DWORD_IMM_GEN4 | (1 << 21)) + 1;
1292 				*batch++ = lower_32_bits(addr);
1293 				*batch++ = upper_32_bits(addr);
1294 				*batch++ = lower_32_bits(target_offset);
1295 				*batch++ = upper_32_bits(target_offset);
1296 			}
1297 		} else if (gen >= 6) {
1298 			*batch++ = MI_STORE_DWORD_IMM_GEN4;
1299 			*batch++ = 0;
1300 			*batch++ = addr;
1301 			*batch++ = target_offset;
1302 		} else if (gen >= 4) {
1303 			*batch++ = MI_STORE_DWORD_IMM_GEN4 | MI_USE_GGTT;
1304 			*batch++ = 0;
1305 			*batch++ = addr;
1306 			*batch++ = target_offset;
1307 		} else {
1308 			*batch++ = MI_STORE_DWORD_IMM | MI_MEM_VIRTUAL;
1309 			*batch++ = addr;
1310 			*batch++ = target_offset;
1311 		}
1312 
1313 		goto out;
1314 	}
1315 
1316 repeat:
1317 	vaddr = reloc_vaddr(vma->obj, &eb->reloc_cache, offset >> PAGE_SHIFT);
1318 	if (IS_ERR(vaddr))
1319 		return PTR_ERR(vaddr);
1320 
1321 	clflush_write32(vaddr + offset_in_page(offset),
1322 			lower_32_bits(target_offset),
1323 			eb->reloc_cache.vaddr);
1324 
1325 	if (wide) {
1326 		offset += sizeof(u32);
1327 		target_offset >>= 32;
1328 		wide = false;
1329 		goto repeat;
1330 	}
1331 
1332 out:
1333 	return target->node.start | UPDATE;
1334 }
1335 
1336 static u64
1337 eb_relocate_entry(struct i915_execbuffer *eb,
1338 		  struct eb_vma *ev,
1339 		  const struct drm_i915_gem_relocation_entry *reloc)
1340 {
1341 	struct drm_i915_private *i915 = eb->i915;
1342 	struct eb_vma *target;
1343 	int err;
1344 
1345 	/* we've already hold a reference to all valid objects */
1346 	target = eb_get_vma(eb, reloc->target_handle);
1347 	if (unlikely(!target))
1348 		return -ENOENT;
1349 
1350 	/* Validate that the target is in a valid r/w GPU domain */
1351 	if (unlikely(reloc->write_domain & (reloc->write_domain - 1))) {
1352 		drm_dbg(&i915->drm, "reloc with multiple write domains: "
1353 			  "target %d offset %d "
1354 			  "read %08x write %08x",
1355 			  reloc->target_handle,
1356 			  (int) reloc->offset,
1357 			  reloc->read_domains,
1358 			  reloc->write_domain);
1359 		return -EINVAL;
1360 	}
1361 	if (unlikely((reloc->write_domain | reloc->read_domains)
1362 		     & ~I915_GEM_GPU_DOMAINS)) {
1363 		drm_dbg(&i915->drm, "reloc with read/write non-GPU domains: "
1364 			  "target %d offset %d "
1365 			  "read %08x write %08x",
1366 			  reloc->target_handle,
1367 			  (int) reloc->offset,
1368 			  reloc->read_domains,
1369 			  reloc->write_domain);
1370 		return -EINVAL;
1371 	}
1372 
1373 	if (reloc->write_domain) {
1374 		target->flags |= EXEC_OBJECT_WRITE;
1375 
1376 		/*
1377 		 * Sandybridge PPGTT errata: We need a global gtt mapping
1378 		 * for MI and pipe_control writes because the gpu doesn't
1379 		 * properly redirect them through the ppgtt for non_secure
1380 		 * batchbuffers.
1381 		 */
1382 		if (reloc->write_domain == I915_GEM_DOMAIN_INSTRUCTION &&
1383 		    IS_GEN(eb->i915, 6)) {
1384 			err = i915_vma_bind(target->vma,
1385 					    target->vma->obj->cache_level,
1386 					    PIN_GLOBAL, NULL);
1387 			if (WARN_ONCE(err,
1388 				      "Unexpected failure to bind target VMA!"))
1389 				return err;
1390 		}
1391 	}
1392 
1393 	/*
1394 	 * If the relocation already has the right value in it, no
1395 	 * more work needs to be done.
1396 	 */
1397 	if (!DBG_FORCE_RELOC &&
1398 	    gen8_canonical_addr(target->vma->node.start) == reloc->presumed_offset)
1399 		return 0;
1400 
1401 	/* Check that the relocation address is valid... */
1402 	if (unlikely(reloc->offset >
1403 		     ev->vma->size - (eb->reloc_cache.use_64bit_reloc ? 8 : 4))) {
1404 		drm_dbg(&i915->drm, "Relocation beyond object bounds: "
1405 			  "target %d offset %d size %d.\n",
1406 			  reloc->target_handle,
1407 			  (int)reloc->offset,
1408 			  (int)ev->vma->size);
1409 		return -EINVAL;
1410 	}
1411 	if (unlikely(reloc->offset & 3)) {
1412 		drm_dbg(&i915->drm, "Relocation not 4-byte aligned: "
1413 			  "target %d offset %d.\n",
1414 			  reloc->target_handle,
1415 			  (int)reloc->offset);
1416 		return -EINVAL;
1417 	}
1418 
1419 	/*
1420 	 * If we write into the object, we need to force the synchronisation
1421 	 * barrier, either with an asynchronous clflush or if we executed the
1422 	 * patching using the GPU (though that should be serialised by the
1423 	 * timeline). To be completely sure, and since we are required to
1424 	 * do relocations we are already stalling, disable the user's opt
1425 	 * out of our synchronisation.
1426 	 */
1427 	ev->flags &= ~EXEC_OBJECT_ASYNC;
1428 
1429 	/* and update the user's relocation entry */
1430 	return relocate_entry(ev->vma, reloc, eb, target->vma);
1431 }
1432 
1433 static int eb_relocate_vma(struct i915_execbuffer *eb, struct eb_vma *ev)
1434 {
1435 #define N_RELOC(x) ((x) / sizeof(struct drm_i915_gem_relocation_entry))
1436 	struct drm_i915_gem_relocation_entry stack[N_RELOC(512)];
1437 	struct drm_i915_gem_relocation_entry __user *urelocs;
1438 	const struct drm_i915_gem_exec_object2 *entry = ev->exec;
1439 	unsigned int remain;
1440 
1441 	urelocs = u64_to_user_ptr(entry->relocs_ptr);
1442 	remain = entry->relocation_count;
1443 	if (unlikely(remain > N_RELOC(ULONG_MAX)))
1444 		return -EINVAL;
1445 
1446 	/*
1447 	 * We must check that the entire relocation array is safe
1448 	 * to read. However, if the array is not writable the user loses
1449 	 * the updated relocation values.
1450 	 */
1451 	if (unlikely(!access_ok(urelocs, remain*sizeof(*urelocs))))
1452 		return -EFAULT;
1453 
1454 	do {
1455 		struct drm_i915_gem_relocation_entry *r = stack;
1456 		unsigned int count =
1457 			min_t(unsigned int, remain, ARRAY_SIZE(stack));
1458 		unsigned int copied;
1459 
1460 		/*
1461 		 * This is the fast path and we cannot handle a pagefault
1462 		 * whilst holding the struct mutex lest the user pass in the
1463 		 * relocations contained within a mmaped bo. For in such a case
1464 		 * we, the page fault handler would call i915_gem_fault() and
1465 		 * we would try to acquire the struct mutex again. Obviously
1466 		 * this is bad and so lockdep complains vehemently.
1467 		 */
1468 		copied = __copy_from_user(r, urelocs, count * sizeof(r[0]));
1469 		if (unlikely(copied)) {
1470 			remain = -EFAULT;
1471 			goto out;
1472 		}
1473 
1474 		remain -= count;
1475 		do {
1476 			u64 offset = eb_relocate_entry(eb, ev, r);
1477 
1478 			if (likely(offset == 0)) {
1479 			} else if ((s64)offset < 0) {
1480 				remain = (int)offset;
1481 				goto out;
1482 			} else {
1483 				/*
1484 				 * Note that reporting an error now
1485 				 * leaves everything in an inconsistent
1486 				 * state as we have *already* changed
1487 				 * the relocation value inside the
1488 				 * object. As we have not changed the
1489 				 * reloc.presumed_offset or will not
1490 				 * change the execobject.offset, on the
1491 				 * call we may not rewrite the value
1492 				 * inside the object, leaving it
1493 				 * dangling and causing a GPU hang. Unless
1494 				 * userspace dynamically rebuilds the
1495 				 * relocations on each execbuf rather than
1496 				 * presume a static tree.
1497 				 *
1498 				 * We did previously check if the relocations
1499 				 * were writable (access_ok), an error now
1500 				 * would be a strange race with mprotect,
1501 				 * having already demonstrated that we
1502 				 * can read from this userspace address.
1503 				 */
1504 				offset = gen8_canonical_addr(offset & ~UPDATE);
1505 				__put_user(offset,
1506 					   &urelocs[r - stack].presumed_offset);
1507 			}
1508 		} while (r++, --count);
1509 		urelocs += ARRAY_SIZE(stack);
1510 	} while (remain);
1511 out:
1512 	reloc_cache_reset(&eb->reloc_cache);
1513 	return remain;
1514 }
1515 
1516 static int eb_relocate(struct i915_execbuffer *eb)
1517 {
1518 	int err;
1519 
1520 	mutex_lock(&eb->gem_context->mutex);
1521 	err = eb_lookup_vmas(eb);
1522 	mutex_unlock(&eb->gem_context->mutex);
1523 	if (err)
1524 		return err;
1525 
1526 	if (!list_empty(&eb->unbound)) {
1527 		err = eb_reserve(eb);
1528 		if (err)
1529 			return err;
1530 	}
1531 
1532 	/* The objects are in their final locations, apply the relocations. */
1533 	if (eb->args->flags & __EXEC_HAS_RELOC) {
1534 		struct eb_vma *ev;
1535 
1536 		list_for_each_entry(ev, &eb->relocs, reloc_link) {
1537 			err = eb_relocate_vma(eb, ev);
1538 			if (err)
1539 				return err;
1540 		}
1541 	}
1542 
1543 	return 0;
1544 }
1545 
1546 static int eb_move_to_gpu(struct i915_execbuffer *eb)
1547 {
1548 	const unsigned int count = eb->buffer_count;
1549 	struct ww_acquire_ctx acquire;
1550 	unsigned int i;
1551 	int err = 0;
1552 
1553 	ww_acquire_init(&acquire, &reservation_ww_class);
1554 
1555 	for (i = 0; i < count; i++) {
1556 		struct eb_vma *ev = &eb->vma[i];
1557 		struct i915_vma *vma = ev->vma;
1558 
1559 		err = ww_mutex_lock_interruptible(&vma->resv->lock, &acquire);
1560 		if (err == -EDEADLK) {
1561 			GEM_BUG_ON(i == 0);
1562 			do {
1563 				int j = i - 1;
1564 
1565 				ww_mutex_unlock(&eb->vma[j].vma->resv->lock);
1566 
1567 				swap(eb->vma[i],  eb->vma[j]);
1568 			} while (--i);
1569 
1570 			err = ww_mutex_lock_slow_interruptible(&vma->resv->lock,
1571 							       &acquire);
1572 		}
1573 		if (err)
1574 			break;
1575 	}
1576 	ww_acquire_done(&acquire);
1577 
1578 	while (i--) {
1579 		struct eb_vma *ev = &eb->vma[i];
1580 		struct i915_vma *vma = ev->vma;
1581 		unsigned int flags = ev->flags;
1582 		struct drm_i915_gem_object *obj = vma->obj;
1583 
1584 		assert_vma_held(vma);
1585 
1586 		if (flags & EXEC_OBJECT_CAPTURE) {
1587 			struct i915_capture_list *capture;
1588 
1589 			capture = kmalloc(sizeof(*capture), GFP_KERNEL);
1590 			if (capture) {
1591 				capture->next = eb->request->capture_list;
1592 				capture->vma = vma;
1593 				eb->request->capture_list = capture;
1594 			}
1595 		}
1596 
1597 		/*
1598 		 * If the GPU is not _reading_ through the CPU cache, we need
1599 		 * to make sure that any writes (both previous GPU writes from
1600 		 * before a change in snooping levels and normal CPU writes)
1601 		 * caught in that cache are flushed to main memory.
1602 		 *
1603 		 * We want to say
1604 		 *   obj->cache_dirty &&
1605 		 *   !(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ)
1606 		 * but gcc's optimiser doesn't handle that as well and emits
1607 		 * two jumps instead of one. Maybe one day...
1608 		 */
1609 		if (unlikely(obj->cache_dirty & ~obj->cache_coherent)) {
1610 			if (i915_gem_clflush_object(obj, 0))
1611 				flags &= ~EXEC_OBJECT_ASYNC;
1612 		}
1613 
1614 		if (err == 0 && !(flags & EXEC_OBJECT_ASYNC)) {
1615 			err = i915_request_await_object
1616 				(eb->request, obj, flags & EXEC_OBJECT_WRITE);
1617 		}
1618 
1619 		if (err == 0)
1620 			err = i915_vma_move_to_active(vma, eb->request, flags);
1621 
1622 		i915_vma_unlock(vma);
1623 
1624 		__eb_unreserve_vma(vma, flags);
1625 		i915_vma_put(vma);
1626 
1627 		ev->vma = NULL;
1628 	}
1629 	ww_acquire_fini(&acquire);
1630 
1631 	if (unlikely(err))
1632 		goto err_skip;
1633 
1634 	eb->exec = NULL;
1635 
1636 	/* Unconditionally flush any chipset caches (for streaming writes). */
1637 	intel_gt_chipset_flush(eb->engine->gt);
1638 	return 0;
1639 
1640 err_skip:
1641 	i915_request_set_error_once(eb->request, err);
1642 	return err;
1643 }
1644 
1645 static int i915_gem_check_execbuffer(struct drm_i915_gem_execbuffer2 *exec)
1646 {
1647 	if (exec->flags & __I915_EXEC_ILLEGAL_FLAGS)
1648 		return -EINVAL;
1649 
1650 	/* Kernel clipping was a DRI1 misfeature */
1651 	if (!(exec->flags & I915_EXEC_FENCE_ARRAY)) {
1652 		if (exec->num_cliprects || exec->cliprects_ptr)
1653 			return -EINVAL;
1654 	}
1655 
1656 	if (exec->DR4 == 0xffffffff) {
1657 		DRM_DEBUG("UXA submitting garbage DR4, fixing up\n");
1658 		exec->DR4 = 0;
1659 	}
1660 	if (exec->DR1 || exec->DR4)
1661 		return -EINVAL;
1662 
1663 	if ((exec->batch_start_offset | exec->batch_len) & 0x7)
1664 		return -EINVAL;
1665 
1666 	return 0;
1667 }
1668 
1669 static int i915_reset_gen7_sol_offsets(struct i915_request *rq)
1670 {
1671 	u32 *cs;
1672 	int i;
1673 
1674 	if (!IS_GEN(rq->i915, 7) || rq->engine->id != RCS0) {
1675 		drm_dbg(&rq->i915->drm, "sol reset is gen7/rcs only\n");
1676 		return -EINVAL;
1677 	}
1678 
1679 	cs = intel_ring_begin(rq, 4 * 2 + 2);
1680 	if (IS_ERR(cs))
1681 		return PTR_ERR(cs);
1682 
1683 	*cs++ = MI_LOAD_REGISTER_IMM(4);
1684 	for (i = 0; i < 4; i++) {
1685 		*cs++ = i915_mmio_reg_offset(GEN7_SO_WRITE_OFFSET(i));
1686 		*cs++ = 0;
1687 	}
1688 	*cs++ = MI_NOOP;
1689 	intel_ring_advance(rq, cs);
1690 
1691 	return 0;
1692 }
1693 
1694 static struct i915_vma *
1695 shadow_batch_pin(struct drm_i915_gem_object *obj,
1696 		 struct i915_address_space *vm,
1697 		 unsigned int flags)
1698 {
1699 	struct i915_vma *vma;
1700 	int err;
1701 
1702 	vma = i915_vma_instance(obj, vm, NULL);
1703 	if (IS_ERR(vma))
1704 		return vma;
1705 
1706 	err = i915_vma_pin(vma, 0, 0, flags);
1707 	if (err)
1708 		return ERR_PTR(err);
1709 
1710 	return vma;
1711 }
1712 
1713 struct eb_parse_work {
1714 	struct dma_fence_work base;
1715 	struct intel_engine_cs *engine;
1716 	struct i915_vma *batch;
1717 	struct i915_vma *shadow;
1718 	struct i915_vma *trampoline;
1719 	unsigned int batch_offset;
1720 	unsigned int batch_length;
1721 };
1722 
1723 static int __eb_parse(struct dma_fence_work *work)
1724 {
1725 	struct eb_parse_work *pw = container_of(work, typeof(*pw), base);
1726 
1727 	return intel_engine_cmd_parser(pw->engine,
1728 				       pw->batch,
1729 				       pw->batch_offset,
1730 				       pw->batch_length,
1731 				       pw->shadow,
1732 				       pw->trampoline);
1733 }
1734 
1735 static void __eb_parse_release(struct dma_fence_work *work)
1736 {
1737 	struct eb_parse_work *pw = container_of(work, typeof(*pw), base);
1738 
1739 	if (pw->trampoline)
1740 		i915_active_release(&pw->trampoline->active);
1741 	i915_active_release(&pw->shadow->active);
1742 	i915_active_release(&pw->batch->active);
1743 }
1744 
1745 static const struct dma_fence_work_ops eb_parse_ops = {
1746 	.name = "eb_parse",
1747 	.work = __eb_parse,
1748 	.release = __eb_parse_release,
1749 };
1750 
1751 static int eb_parse_pipeline(struct i915_execbuffer *eb,
1752 			     struct i915_vma *shadow,
1753 			     struct i915_vma *trampoline)
1754 {
1755 	struct eb_parse_work *pw;
1756 	int err;
1757 
1758 	pw = kzalloc(sizeof(*pw), GFP_KERNEL);
1759 	if (!pw)
1760 		return -ENOMEM;
1761 
1762 	err = i915_active_acquire(&eb->batch->vma->active);
1763 	if (err)
1764 		goto err_free;
1765 
1766 	err = i915_active_acquire(&shadow->active);
1767 	if (err)
1768 		goto err_batch;
1769 
1770 	if (trampoline) {
1771 		err = i915_active_acquire(&trampoline->active);
1772 		if (err)
1773 			goto err_shadow;
1774 	}
1775 
1776 	dma_fence_work_init(&pw->base, &eb_parse_ops);
1777 
1778 	pw->engine = eb->engine;
1779 	pw->batch = eb->batch->vma;
1780 	pw->batch_offset = eb->batch_start_offset;
1781 	pw->batch_length = eb->batch_len;
1782 	pw->shadow = shadow;
1783 	pw->trampoline = trampoline;
1784 
1785 	err = dma_resv_lock_interruptible(pw->batch->resv, NULL);
1786 	if (err)
1787 		goto err_trampoline;
1788 
1789 	err = dma_resv_reserve_shared(pw->batch->resv, 1);
1790 	if (err)
1791 		goto err_batch_unlock;
1792 
1793 	/* Wait for all writes (and relocs) into the batch to complete */
1794 	err = i915_sw_fence_await_reservation(&pw->base.chain,
1795 					      pw->batch->resv, NULL, false,
1796 					      0, I915_FENCE_GFP);
1797 	if (err < 0)
1798 		goto err_batch_unlock;
1799 
1800 	/* Keep the batch alive and unwritten as we parse */
1801 	dma_resv_add_shared_fence(pw->batch->resv, &pw->base.dma);
1802 
1803 	dma_resv_unlock(pw->batch->resv);
1804 
1805 	/* Force execution to wait for completion of the parser */
1806 	dma_resv_lock(shadow->resv, NULL);
1807 	dma_resv_add_excl_fence(shadow->resv, &pw->base.dma);
1808 	dma_resv_unlock(shadow->resv);
1809 
1810 	dma_fence_work_commit(&pw->base);
1811 	return 0;
1812 
1813 err_batch_unlock:
1814 	dma_resv_unlock(pw->batch->resv);
1815 err_trampoline:
1816 	if (trampoline)
1817 		i915_active_release(&trampoline->active);
1818 err_shadow:
1819 	i915_active_release(&shadow->active);
1820 err_batch:
1821 	i915_active_release(&eb->batch->vma->active);
1822 err_free:
1823 	kfree(pw);
1824 	return err;
1825 }
1826 
1827 static int eb_parse(struct i915_execbuffer *eb)
1828 {
1829 	struct drm_i915_private *i915 = eb->i915;
1830 	struct intel_engine_pool_node *pool;
1831 	struct i915_vma *shadow, *trampoline;
1832 	unsigned int len;
1833 	int err;
1834 
1835 	if (!eb_use_cmdparser(eb))
1836 		return 0;
1837 
1838 	len = eb->batch_len;
1839 	if (!CMDPARSER_USES_GGTT(eb->i915)) {
1840 		/*
1841 		 * ppGTT backed shadow buffers must be mapped RO, to prevent
1842 		 * post-scan tampering
1843 		 */
1844 		if (!eb->context->vm->has_read_only) {
1845 			drm_dbg(&i915->drm,
1846 				"Cannot prevent post-scan tampering without RO capable vm\n");
1847 			return -EINVAL;
1848 		}
1849 	} else {
1850 		len += I915_CMD_PARSER_TRAMPOLINE_SIZE;
1851 	}
1852 
1853 	pool = intel_engine_get_pool(eb->engine, len);
1854 	if (IS_ERR(pool))
1855 		return PTR_ERR(pool);
1856 
1857 	shadow = shadow_batch_pin(pool->obj, eb->context->vm, PIN_USER);
1858 	if (IS_ERR(shadow)) {
1859 		err = PTR_ERR(shadow);
1860 		goto err;
1861 	}
1862 	i915_gem_object_set_readonly(shadow->obj);
1863 
1864 	trampoline = NULL;
1865 	if (CMDPARSER_USES_GGTT(eb->i915)) {
1866 		trampoline = shadow;
1867 
1868 		shadow = shadow_batch_pin(pool->obj,
1869 					  &eb->engine->gt->ggtt->vm,
1870 					  PIN_GLOBAL);
1871 		if (IS_ERR(shadow)) {
1872 			err = PTR_ERR(shadow);
1873 			shadow = trampoline;
1874 			goto err_shadow;
1875 		}
1876 
1877 		eb->batch_flags |= I915_DISPATCH_SECURE;
1878 	}
1879 
1880 	err = eb_parse_pipeline(eb, shadow, trampoline);
1881 	if (err)
1882 		goto err_trampoline;
1883 
1884 	eb->vma[eb->buffer_count].vma = i915_vma_get(shadow);
1885 	eb->vma[eb->buffer_count].flags = __EXEC_OBJECT_HAS_PIN;
1886 	eb->batch = &eb->vma[eb->buffer_count++];
1887 
1888 	eb->trampoline = trampoline;
1889 	eb->batch_start_offset = 0;
1890 
1891 	shadow->private = pool;
1892 	return 0;
1893 
1894 err_trampoline:
1895 	if (trampoline)
1896 		i915_vma_unpin(trampoline);
1897 err_shadow:
1898 	i915_vma_unpin(shadow);
1899 err:
1900 	intel_engine_pool_put(pool);
1901 	return err;
1902 }
1903 
1904 static void
1905 add_to_client(struct i915_request *rq, struct drm_file *file)
1906 {
1907 	struct drm_i915_file_private *file_priv = file->driver_priv;
1908 
1909 	rq->file_priv = file_priv;
1910 
1911 	spin_lock(&file_priv->mm.lock);
1912 	list_add_tail(&rq->client_link, &file_priv->mm.request_list);
1913 	spin_unlock(&file_priv->mm.lock);
1914 }
1915 
1916 static int eb_submit(struct i915_execbuffer *eb, struct i915_vma *batch)
1917 {
1918 	int err;
1919 
1920 	err = eb_move_to_gpu(eb);
1921 	if (err)
1922 		return err;
1923 
1924 	if (eb->args->flags & I915_EXEC_GEN7_SOL_RESET) {
1925 		err = i915_reset_gen7_sol_offsets(eb->request);
1926 		if (err)
1927 			return err;
1928 	}
1929 
1930 	/*
1931 	 * After we completed waiting for other engines (using HW semaphores)
1932 	 * then we can signal that this request/batch is ready to run. This
1933 	 * allows us to determine if the batch is still waiting on the GPU
1934 	 * or actually running by checking the breadcrumb.
1935 	 */
1936 	if (eb->engine->emit_init_breadcrumb) {
1937 		err = eb->engine->emit_init_breadcrumb(eb->request);
1938 		if (err)
1939 			return err;
1940 	}
1941 
1942 	err = eb->engine->emit_bb_start(eb->request,
1943 					batch->node.start +
1944 					eb->batch_start_offset,
1945 					eb->batch_len,
1946 					eb->batch_flags);
1947 	if (err)
1948 		return err;
1949 
1950 	if (eb->trampoline) {
1951 		GEM_BUG_ON(eb->batch_start_offset);
1952 		err = eb->engine->emit_bb_start(eb->request,
1953 						eb->trampoline->node.start +
1954 						eb->batch_len,
1955 						0, 0);
1956 		if (err)
1957 			return err;
1958 	}
1959 
1960 	if (intel_context_nopreempt(eb->context))
1961 		__set_bit(I915_FENCE_FLAG_NOPREEMPT, &eb->request->fence.flags);
1962 
1963 	return 0;
1964 }
1965 
1966 static int num_vcs_engines(const struct drm_i915_private *i915)
1967 {
1968 	return hweight64(INTEL_INFO(i915)->engine_mask &
1969 			 GENMASK_ULL(VCS0 + I915_MAX_VCS - 1, VCS0));
1970 }
1971 
1972 /*
1973  * Find one BSD ring to dispatch the corresponding BSD command.
1974  * The engine index is returned.
1975  */
1976 static unsigned int
1977 gen8_dispatch_bsd_engine(struct drm_i915_private *dev_priv,
1978 			 struct drm_file *file)
1979 {
1980 	struct drm_i915_file_private *file_priv = file->driver_priv;
1981 
1982 	/* Check whether the file_priv has already selected one ring. */
1983 	if ((int)file_priv->bsd_engine < 0)
1984 		file_priv->bsd_engine =
1985 			get_random_int() % num_vcs_engines(dev_priv);
1986 
1987 	return file_priv->bsd_engine;
1988 }
1989 
1990 static const enum intel_engine_id user_ring_map[] = {
1991 	[I915_EXEC_DEFAULT]	= RCS0,
1992 	[I915_EXEC_RENDER]	= RCS0,
1993 	[I915_EXEC_BLT]		= BCS0,
1994 	[I915_EXEC_BSD]		= VCS0,
1995 	[I915_EXEC_VEBOX]	= VECS0
1996 };
1997 
1998 static struct i915_request *eb_throttle(struct intel_context *ce)
1999 {
2000 	struct intel_ring *ring = ce->ring;
2001 	struct intel_timeline *tl = ce->timeline;
2002 	struct i915_request *rq;
2003 
2004 	/*
2005 	 * Completely unscientific finger-in-the-air estimates for suitable
2006 	 * maximum user request size (to avoid blocking) and then backoff.
2007 	 */
2008 	if (intel_ring_update_space(ring) >= PAGE_SIZE)
2009 		return NULL;
2010 
2011 	/*
2012 	 * Find a request that after waiting upon, there will be at least half
2013 	 * the ring available. The hysteresis allows us to compete for the
2014 	 * shared ring and should mean that we sleep less often prior to
2015 	 * claiming our resources, but not so long that the ring completely
2016 	 * drains before we can submit our next request.
2017 	 */
2018 	list_for_each_entry(rq, &tl->requests, link) {
2019 		if (rq->ring != ring)
2020 			continue;
2021 
2022 		if (__intel_ring_space(rq->postfix,
2023 				       ring->emit, ring->size) > ring->size / 2)
2024 			break;
2025 	}
2026 	if (&rq->link == &tl->requests)
2027 		return NULL; /* weird, we will check again later for real */
2028 
2029 	return i915_request_get(rq);
2030 }
2031 
2032 static int __eb_pin_engine(struct i915_execbuffer *eb, struct intel_context *ce)
2033 {
2034 	struct intel_timeline *tl;
2035 	struct i915_request *rq;
2036 	int err;
2037 
2038 	/*
2039 	 * ABI: Before userspace accesses the GPU (e.g. execbuffer), report
2040 	 * EIO if the GPU is already wedged.
2041 	 */
2042 	err = intel_gt_terminally_wedged(ce->engine->gt);
2043 	if (err)
2044 		return err;
2045 
2046 	if (unlikely(intel_context_is_banned(ce)))
2047 		return -EIO;
2048 
2049 	/*
2050 	 * Pinning the contexts may generate requests in order to acquire
2051 	 * GGTT space, so do this first before we reserve a seqno for
2052 	 * ourselves.
2053 	 */
2054 	err = intel_context_pin(ce);
2055 	if (err)
2056 		return err;
2057 
2058 	/*
2059 	 * Take a local wakeref for preparing to dispatch the execbuf as
2060 	 * we expect to access the hardware fairly frequently in the
2061 	 * process, and require the engine to be kept awake between accesses.
2062 	 * Upon dispatch, we acquire another prolonged wakeref that we hold
2063 	 * until the timeline is idle, which in turn releases the wakeref
2064 	 * taken on the engine, and the parent device.
2065 	 */
2066 	tl = intel_context_timeline_lock(ce);
2067 	if (IS_ERR(tl)) {
2068 		err = PTR_ERR(tl);
2069 		goto err_unpin;
2070 	}
2071 
2072 	intel_context_enter(ce);
2073 	rq = eb_throttle(ce);
2074 
2075 	intel_context_timeline_unlock(tl);
2076 
2077 	if (rq) {
2078 #ifdef __linux__
2079 		bool nonblock = eb->file->filp->f_flags & O_NONBLOCK;
2080 #else
2081 		bool nonblock = eb->file->filp->f_flag & FNONBLOCK;
2082 #endif
2083 		long timeout;
2084 
2085 		timeout = MAX_SCHEDULE_TIMEOUT;
2086 		if (nonblock)
2087 			timeout = 0;
2088 
2089 		timeout = i915_request_wait(rq,
2090 					    I915_WAIT_INTERRUPTIBLE,
2091 					    timeout);
2092 		i915_request_put(rq);
2093 
2094 		if (timeout < 0) {
2095 			err = nonblock ? -EWOULDBLOCK : timeout;
2096 			goto err_exit;
2097 		}
2098 	}
2099 
2100 	eb->engine = ce->engine;
2101 	eb->context = ce;
2102 	return 0;
2103 
2104 err_exit:
2105 	mutex_lock(&tl->mutex);
2106 	intel_context_exit(ce);
2107 	intel_context_timeline_unlock(tl);
2108 err_unpin:
2109 	intel_context_unpin(ce);
2110 	return err;
2111 }
2112 
2113 static void eb_unpin_engine(struct i915_execbuffer *eb)
2114 {
2115 	struct intel_context *ce = eb->context;
2116 	struct intel_timeline *tl = ce->timeline;
2117 
2118 	mutex_lock(&tl->mutex);
2119 	intel_context_exit(ce);
2120 	mutex_unlock(&tl->mutex);
2121 
2122 	intel_context_unpin(ce);
2123 }
2124 
2125 static unsigned int
2126 eb_select_legacy_ring(struct i915_execbuffer *eb,
2127 		      struct drm_file *file,
2128 		      struct drm_i915_gem_execbuffer2 *args)
2129 {
2130 	struct drm_i915_private *i915 = eb->i915;
2131 	unsigned int user_ring_id = args->flags & I915_EXEC_RING_MASK;
2132 
2133 	if (user_ring_id != I915_EXEC_BSD &&
2134 	    (args->flags & I915_EXEC_BSD_MASK)) {
2135 		drm_dbg(&i915->drm,
2136 			"execbuf with non bsd ring but with invalid "
2137 			"bsd dispatch flags: %d\n", (int)(args->flags));
2138 		return -1;
2139 	}
2140 
2141 	if (user_ring_id == I915_EXEC_BSD && num_vcs_engines(i915) > 1) {
2142 		unsigned int bsd_idx = args->flags & I915_EXEC_BSD_MASK;
2143 
2144 		if (bsd_idx == I915_EXEC_BSD_DEFAULT) {
2145 			bsd_idx = gen8_dispatch_bsd_engine(i915, file);
2146 		} else if (bsd_idx >= I915_EXEC_BSD_RING1 &&
2147 			   bsd_idx <= I915_EXEC_BSD_RING2) {
2148 			bsd_idx >>= I915_EXEC_BSD_SHIFT;
2149 			bsd_idx--;
2150 		} else {
2151 			drm_dbg(&i915->drm,
2152 				"execbuf with unknown bsd ring: %u\n",
2153 				bsd_idx);
2154 			return -1;
2155 		}
2156 
2157 		return _VCS(bsd_idx);
2158 	}
2159 
2160 	if (user_ring_id >= ARRAY_SIZE(user_ring_map)) {
2161 		drm_dbg(&i915->drm, "execbuf with unknown ring: %u\n",
2162 			user_ring_id);
2163 		return -1;
2164 	}
2165 
2166 	return user_ring_map[user_ring_id];
2167 }
2168 
2169 static int
2170 eb_pin_engine(struct i915_execbuffer *eb,
2171 	      struct drm_file *file,
2172 	      struct drm_i915_gem_execbuffer2 *args)
2173 {
2174 	struct intel_context *ce;
2175 	unsigned int idx;
2176 	int err;
2177 
2178 	if (i915_gem_context_user_engines(eb->gem_context))
2179 		idx = args->flags & I915_EXEC_RING_MASK;
2180 	else
2181 		idx = eb_select_legacy_ring(eb, file, args);
2182 
2183 	ce = i915_gem_context_get_engine(eb->gem_context, idx);
2184 	if (IS_ERR(ce))
2185 		return PTR_ERR(ce);
2186 
2187 	err = __eb_pin_engine(eb, ce);
2188 	intel_context_put(ce);
2189 
2190 	return err;
2191 }
2192 
2193 static void
2194 __free_fence_array(struct drm_syncobj **fences, unsigned int n)
2195 {
2196 	while (n--)
2197 		drm_syncobj_put(ptr_mask_bits(fences[n], 2));
2198 	kvfree(fences);
2199 }
2200 
2201 static struct drm_syncobj **
2202 get_fence_array(struct drm_i915_gem_execbuffer2 *args,
2203 		struct drm_file *file)
2204 {
2205 	const unsigned long nfences = args->num_cliprects;
2206 	struct drm_i915_gem_exec_fence __user *user;
2207 	struct drm_syncobj **fences;
2208 	unsigned long n;
2209 	int err;
2210 
2211 	if (!(args->flags & I915_EXEC_FENCE_ARRAY))
2212 		return NULL;
2213 
2214 	/* Check multiplication overflow for access_ok() and kvmalloc_array() */
2215 	BUILD_BUG_ON(sizeof(size_t) > sizeof(unsigned long));
2216 	if (nfences > min_t(unsigned long,
2217 			    ULONG_MAX / sizeof(*user),
2218 			    SIZE_MAX / sizeof(*fences)))
2219 		return ERR_PTR(-EINVAL);
2220 
2221 	user = u64_to_user_ptr(args->cliprects_ptr);
2222 	if (!access_ok(user, nfences * sizeof(*user)))
2223 		return ERR_PTR(-EFAULT);
2224 
2225 	fences = kvmalloc_array(nfences, sizeof(*fences),
2226 				__GFP_NOWARN | GFP_KERNEL);
2227 	if (!fences)
2228 		return ERR_PTR(-ENOMEM);
2229 
2230 	for (n = 0; n < nfences; n++) {
2231 		struct drm_i915_gem_exec_fence fence;
2232 		struct drm_syncobj *syncobj;
2233 
2234 		if (__copy_from_user(&fence, user++, sizeof(fence))) {
2235 			err = -EFAULT;
2236 			goto err;
2237 		}
2238 
2239 		if (fence.flags & __I915_EXEC_FENCE_UNKNOWN_FLAGS) {
2240 			err = -EINVAL;
2241 			goto err;
2242 		}
2243 
2244 		syncobj = drm_syncobj_find(file, fence.handle);
2245 		if (!syncobj) {
2246 			DRM_DEBUG("Invalid syncobj handle provided\n");
2247 			err = -ENOENT;
2248 			goto err;
2249 		}
2250 
2251 #ifdef notyet
2252 		BUILD_BUG_ON(~(ARCH_KMALLOC_MINALIGN - 1) &
2253 			     ~__I915_EXEC_FENCE_UNKNOWN_FLAGS);
2254 #endif
2255 
2256 		fences[n] = ptr_pack_bits(syncobj, fence.flags, 2);
2257 	}
2258 
2259 	return fences;
2260 
2261 err:
2262 	__free_fence_array(fences, n);
2263 	return ERR_PTR(err);
2264 }
2265 
2266 static void
2267 put_fence_array(struct drm_i915_gem_execbuffer2 *args,
2268 		struct drm_syncobj **fences)
2269 {
2270 	if (fences)
2271 		__free_fence_array(fences, args->num_cliprects);
2272 }
2273 
2274 static int
2275 await_fence_array(struct i915_execbuffer *eb,
2276 		  struct drm_syncobj **fences)
2277 {
2278 	const unsigned int nfences = eb->args->num_cliprects;
2279 	unsigned int n;
2280 	int err;
2281 
2282 	for (n = 0; n < nfences; n++) {
2283 		struct drm_syncobj *syncobj;
2284 		struct dma_fence *fence;
2285 		unsigned int flags;
2286 
2287 		syncobj = ptr_unpack_bits(fences[n], &flags, 2);
2288 		if (!(flags & I915_EXEC_FENCE_WAIT))
2289 			continue;
2290 
2291 		fence = drm_syncobj_fence_get(syncobj);
2292 		if (!fence)
2293 			return -EINVAL;
2294 
2295 		err = i915_request_await_dma_fence(eb->request, fence);
2296 		dma_fence_put(fence);
2297 		if (err < 0)
2298 			return err;
2299 	}
2300 
2301 	return 0;
2302 }
2303 
2304 static void
2305 signal_fence_array(struct i915_execbuffer *eb,
2306 		   struct drm_syncobj **fences)
2307 {
2308 	const unsigned int nfences = eb->args->num_cliprects;
2309 	struct dma_fence * const fence = &eb->request->fence;
2310 	unsigned int n;
2311 
2312 	for (n = 0; n < nfences; n++) {
2313 		struct drm_syncobj *syncobj;
2314 		unsigned int flags;
2315 
2316 		syncobj = ptr_unpack_bits(fences[n], &flags, 2);
2317 		if (!(flags & I915_EXEC_FENCE_SIGNAL))
2318 			continue;
2319 
2320 		drm_syncobj_replace_fence(syncobj, fence);
2321 	}
2322 }
2323 
2324 static void retire_requests(struct intel_timeline *tl, struct i915_request *end)
2325 {
2326 	struct i915_request *rq, *rn;
2327 
2328 	list_for_each_entry_safe(rq, rn, &tl->requests, link)
2329 		if (rq == end || !i915_request_retire(rq))
2330 			break;
2331 }
2332 
2333 static void eb_request_add(struct i915_execbuffer *eb)
2334 {
2335 	struct i915_request *rq = eb->request;
2336 	struct intel_timeline * const tl = i915_request_timeline(rq);
2337 	struct i915_sched_attr attr = {};
2338 	struct i915_request *prev;
2339 
2340 	lockdep_assert_held(&tl->mutex);
2341 	lockdep_unpin_lock(&tl->mutex, rq->cookie);
2342 
2343 	trace_i915_request_add(rq);
2344 
2345 	prev = __i915_request_commit(rq);
2346 
2347 	/* Check that the context wasn't destroyed before submission */
2348 	if (likely(!intel_context_is_closed(eb->context))) {
2349 		attr = eb->gem_context->sched;
2350 
2351 		/*
2352 		 * Boost actual workloads past semaphores!
2353 		 *
2354 		 * With semaphores we spin on one engine waiting for another,
2355 		 * simply to reduce the latency of starting our work when
2356 		 * the signaler completes. However, if there is any other
2357 		 * work that we could be doing on this engine instead, that
2358 		 * is better utilisation and will reduce the overall duration
2359 		 * of the current work. To avoid PI boosting a semaphore
2360 		 * far in the distance past over useful work, we keep a history
2361 		 * of any semaphore use along our dependency chain.
2362 		 */
2363 		if (!(rq->sched.flags & I915_SCHED_HAS_SEMAPHORE_CHAIN))
2364 			attr.priority |= I915_PRIORITY_NOSEMAPHORE;
2365 
2366 		/*
2367 		 * Boost priorities to new clients (new request flows).
2368 		 *
2369 		 * Allow interactive/synchronous clients to jump ahead of
2370 		 * the bulk clients. (FQ_CODEL)
2371 		 */
2372 		if (list_empty(&rq->sched.signalers_list))
2373 			attr.priority |= I915_PRIORITY_WAIT;
2374 	} else {
2375 		/* Serialise with context_close via the add_to_timeline */
2376 		i915_request_set_error_once(rq, -ENOENT);
2377 		__i915_request_skip(rq);
2378 	}
2379 
2380 	local_bh_disable();
2381 	__i915_request_queue(rq, &attr);
2382 	local_bh_enable(); /* Kick the execlists tasklet if just scheduled */
2383 
2384 	/* Try to clean up the client's timeline after submitting the request */
2385 	if (prev)
2386 		retire_requests(tl, prev);
2387 
2388 	mutex_unlock(&tl->mutex);
2389 }
2390 
2391 static int
2392 i915_gem_do_execbuffer(struct drm_device *dev,
2393 		       struct drm_file *file,
2394 		       struct drm_i915_gem_execbuffer2 *args,
2395 		       struct drm_i915_gem_exec_object2 *exec,
2396 		       struct drm_syncobj **fences)
2397 {
2398 	struct drm_i915_private *i915 = to_i915(dev);
2399 	struct i915_execbuffer eb;
2400 	struct dma_fence *in_fence = NULL;
2401 	struct dma_fence *exec_fence = NULL;
2402 	struct sync_file *out_fence = NULL;
2403 	struct i915_vma *batch;
2404 	int out_fence_fd = -1;
2405 	int err;
2406 
2407 	BUILD_BUG_ON(__EXEC_INTERNAL_FLAGS & ~__I915_EXEC_ILLEGAL_FLAGS);
2408 	BUILD_BUG_ON(__EXEC_OBJECT_INTERNAL_FLAGS &
2409 		     ~__EXEC_OBJECT_UNKNOWN_FLAGS);
2410 
2411 	eb.i915 = i915;
2412 	eb.file = file;
2413 	eb.args = args;
2414 	if (DBG_FORCE_RELOC || !(args->flags & I915_EXEC_NO_RELOC))
2415 		args->flags |= __EXEC_HAS_RELOC;
2416 
2417 	eb.exec = exec;
2418 	eb.vma = (struct eb_vma *)(exec + args->buffer_count + 1);
2419 	eb.vma[0].vma = NULL;
2420 
2421 	eb.invalid_flags = __EXEC_OBJECT_UNKNOWN_FLAGS;
2422 	reloc_cache_init(&eb.reloc_cache, eb.i915);
2423 
2424 	eb.buffer_count = args->buffer_count;
2425 	eb.batch_start_offset = args->batch_start_offset;
2426 	eb.batch_len = args->batch_len;
2427 	eb.trampoline = NULL;
2428 
2429 	eb.batch_flags = 0;
2430 	if (args->flags & I915_EXEC_SECURE) {
2431 		if (INTEL_GEN(i915) >= 11)
2432 			return -ENODEV;
2433 
2434 		/* Return -EPERM to trigger fallback code on old binaries. */
2435 		if (!HAS_SECURE_BATCHES(i915))
2436 			return -EPERM;
2437 
2438 		if (!drm_is_current_master(file) || !capable(CAP_SYS_ADMIN))
2439 			return -EPERM;
2440 
2441 		eb.batch_flags |= I915_DISPATCH_SECURE;
2442 	}
2443 	if (args->flags & I915_EXEC_IS_PINNED)
2444 		eb.batch_flags |= I915_DISPATCH_PINNED;
2445 
2446 	if (args->flags & I915_EXEC_FENCE_IN) {
2447 		in_fence = sync_file_get_fence(lower_32_bits(args->rsvd2));
2448 		if (!in_fence)
2449 			return -EINVAL;
2450 	}
2451 
2452 	if (args->flags & I915_EXEC_FENCE_SUBMIT) {
2453 		if (in_fence) {
2454 			err = -EINVAL;
2455 			goto err_in_fence;
2456 		}
2457 
2458 		exec_fence = sync_file_get_fence(lower_32_bits(args->rsvd2));
2459 		if (!exec_fence) {
2460 			err = -EINVAL;
2461 			goto err_in_fence;
2462 		}
2463 	}
2464 
2465 	if (args->flags & I915_EXEC_FENCE_OUT) {
2466 		out_fence_fd = get_unused_fd_flags(O_CLOEXEC);
2467 		if (out_fence_fd < 0) {
2468 			err = out_fence_fd;
2469 			goto err_exec_fence;
2470 		}
2471 	}
2472 
2473 	err = eb_create(&eb);
2474 	if (err)
2475 		goto err_out_fence;
2476 
2477 	GEM_BUG_ON(!eb.lut_size);
2478 
2479 	err = eb_select_context(&eb);
2480 	if (unlikely(err))
2481 		goto err_destroy;
2482 
2483 	err = eb_pin_engine(&eb, file, args);
2484 	if (unlikely(err))
2485 		goto err_context;
2486 
2487 	err = eb_relocate(&eb);
2488 	if (err) {
2489 		/*
2490 		 * If the user expects the execobject.offset and
2491 		 * reloc.presumed_offset to be an exact match,
2492 		 * as for using NO_RELOC, then we cannot update
2493 		 * the execobject.offset until we have completed
2494 		 * relocation.
2495 		 */
2496 		args->flags &= ~__EXEC_HAS_RELOC;
2497 		goto err_vma;
2498 	}
2499 
2500 	if (unlikely(eb.batch->flags & EXEC_OBJECT_WRITE)) {
2501 		drm_dbg(&i915->drm,
2502 			"Attempting to use self-modifying batch buffer\n");
2503 		err = -EINVAL;
2504 		goto err_vma;
2505 	}
2506 
2507 	if (range_overflows_t(u64,
2508 			      eb.batch_start_offset, eb.batch_len,
2509 			      eb.batch->vma->size)) {
2510 		drm_dbg(&i915->drm, "Attempting to use out-of-bounds batch\n");
2511 		err = -EINVAL;
2512 		goto err_vma;
2513 	}
2514 
2515 	if (eb.batch_len == 0)
2516 		eb.batch_len = eb.batch->vma->size - eb.batch_start_offset;
2517 
2518 	err = eb_parse(&eb);
2519 	if (err)
2520 		goto err_vma;
2521 
2522 	/*
2523 	 * snb/ivb/vlv conflate the "batch in ppgtt" bit with the "non-secure
2524 	 * batch" bit. Hence we need to pin secure batches into the global gtt.
2525 	 * hsw should have this fixed, but bdw mucks it up again. */
2526 	batch = eb.batch->vma;
2527 	if (eb.batch_flags & I915_DISPATCH_SECURE) {
2528 		struct i915_vma *vma;
2529 
2530 		/*
2531 		 * So on first glance it looks freaky that we pin the batch here
2532 		 * outside of the reservation loop. But:
2533 		 * - The batch is already pinned into the relevant ppgtt, so we
2534 		 *   already have the backing storage fully allocated.
2535 		 * - No other BO uses the global gtt (well contexts, but meh),
2536 		 *   so we don't really have issues with multiple objects not
2537 		 *   fitting due to fragmentation.
2538 		 * So this is actually safe.
2539 		 */
2540 		vma = i915_gem_object_ggtt_pin(batch->obj, NULL, 0, 0, 0);
2541 		if (IS_ERR(vma)) {
2542 			err = PTR_ERR(vma);
2543 			goto err_parse;
2544 		}
2545 
2546 		batch = vma;
2547 	}
2548 
2549 	/* All GPU relocation batches must be submitted prior to the user rq */
2550 	GEM_BUG_ON(eb.reloc_cache.rq);
2551 
2552 	/* Allocate a request for this batch buffer nice and early. */
2553 	eb.request = i915_request_create(eb.context);
2554 	if (IS_ERR(eb.request)) {
2555 		err = PTR_ERR(eb.request);
2556 		goto err_batch_unpin;
2557 	}
2558 
2559 	if (in_fence) {
2560 		err = i915_request_await_dma_fence(eb.request, in_fence);
2561 		if (err < 0)
2562 			goto err_request;
2563 	}
2564 
2565 	if (exec_fence) {
2566 		err = i915_request_await_execution(eb.request, exec_fence,
2567 						   eb.engine->bond_execute);
2568 		if (err < 0)
2569 			goto err_request;
2570 	}
2571 
2572 	if (fences) {
2573 		err = await_fence_array(&eb, fences);
2574 		if (err)
2575 			goto err_request;
2576 	}
2577 
2578 	if (out_fence_fd != -1) {
2579 		out_fence = sync_file_create(&eb.request->fence);
2580 		if (!out_fence) {
2581 			err = -ENOMEM;
2582 			goto err_request;
2583 		}
2584 	}
2585 
2586 	/*
2587 	 * Whilst this request exists, batch_obj will be on the
2588 	 * active_list, and so will hold the active reference. Only when this
2589 	 * request is retired will the the batch_obj be moved onto the
2590 	 * inactive_list and lose its active reference. Hence we do not need
2591 	 * to explicitly hold another reference here.
2592 	 */
2593 	eb.request->batch = batch;
2594 	if (batch->private)
2595 		intel_engine_pool_mark_active(batch->private, eb.request);
2596 
2597 	trace_i915_request_queue(eb.request, eb.batch_flags);
2598 	err = eb_submit(&eb, batch);
2599 err_request:
2600 	add_to_client(eb.request, file);
2601 	i915_request_get(eb.request);
2602 	eb_request_add(&eb);
2603 
2604 	if (fences)
2605 		signal_fence_array(&eb, fences);
2606 
2607 	if (out_fence) {
2608 		if (err == 0) {
2609 			fd_install(out_fence_fd, out_fence->file);
2610 			args->rsvd2 &= GENMASK_ULL(31, 0); /* keep in-fence */
2611 			args->rsvd2 |= (u64)out_fence_fd << 32;
2612 			out_fence_fd = -1;
2613 		} else {
2614 			fput(out_fence->file);
2615 		}
2616 	}
2617 	i915_request_put(eb.request);
2618 
2619 err_batch_unpin:
2620 	if (eb.batch_flags & I915_DISPATCH_SECURE)
2621 		i915_vma_unpin(batch);
2622 err_parse:
2623 	if (batch->private)
2624 		intel_engine_pool_put(batch->private);
2625 err_vma:
2626 	if (eb.exec)
2627 		eb_release_vmas(&eb);
2628 	if (eb.trampoline)
2629 		i915_vma_unpin(eb.trampoline);
2630 	eb_unpin_engine(&eb);
2631 err_context:
2632 	i915_gem_context_put(eb.gem_context);
2633 err_destroy:
2634 	eb_destroy(&eb);
2635 err_out_fence:
2636 	if (out_fence_fd != -1)
2637 		put_unused_fd(out_fence_fd);
2638 err_exec_fence:
2639 	dma_fence_put(exec_fence);
2640 err_in_fence:
2641 	dma_fence_put(in_fence);
2642 	return err;
2643 }
2644 
2645 static size_t eb_element_size(void)
2646 {
2647 	return sizeof(struct drm_i915_gem_exec_object2) + sizeof(struct eb_vma);
2648 }
2649 
2650 static bool check_buffer_count(size_t count)
2651 {
2652 	const size_t sz = eb_element_size();
2653 
2654 	/*
2655 	 * When using LUT_HANDLE, we impose a limit of INT_MAX for the lookup
2656 	 * array size (see eb_create()). Otherwise, we can accept an array as
2657 	 * large as can be addressed (though use large arrays at your peril)!
2658 	 */
2659 
2660 	return !(count < 1 || count > INT_MAX || count > SIZE_MAX / sz - 1);
2661 }
2662 
2663 /*
2664  * Legacy execbuffer just creates an exec2 list from the original exec object
2665  * list array and passes it to the real function.
2666  */
2667 int
2668 i915_gem_execbuffer_ioctl(struct drm_device *dev, void *data,
2669 			  struct drm_file *file)
2670 {
2671 	struct drm_i915_private *i915 = to_i915(dev);
2672 	struct drm_i915_gem_execbuffer *args = data;
2673 	struct drm_i915_gem_execbuffer2 exec2;
2674 	struct drm_i915_gem_exec_object *exec_list = NULL;
2675 	struct drm_i915_gem_exec_object2 *exec2_list = NULL;
2676 	const size_t count = args->buffer_count;
2677 	unsigned int i;
2678 	int err;
2679 
2680 	if (!check_buffer_count(count)) {
2681 		drm_dbg(&i915->drm, "execbuf2 with %zd buffers\n", count);
2682 		return -EINVAL;
2683 	}
2684 
2685 	exec2.buffers_ptr = args->buffers_ptr;
2686 	exec2.buffer_count = args->buffer_count;
2687 	exec2.batch_start_offset = args->batch_start_offset;
2688 	exec2.batch_len = args->batch_len;
2689 	exec2.DR1 = args->DR1;
2690 	exec2.DR4 = args->DR4;
2691 	exec2.num_cliprects = args->num_cliprects;
2692 	exec2.cliprects_ptr = args->cliprects_ptr;
2693 	exec2.flags = I915_EXEC_RENDER;
2694 	i915_execbuffer2_set_context_id(exec2, 0);
2695 
2696 	err = i915_gem_check_execbuffer(&exec2);
2697 	if (err)
2698 		return err;
2699 
2700 	/* Copy in the exec list from userland */
2701 	exec_list = kvmalloc_array(count, sizeof(*exec_list),
2702 				   __GFP_NOWARN | GFP_KERNEL);
2703 	exec2_list = kvmalloc_array(count + 1, eb_element_size(),
2704 				    __GFP_NOWARN | GFP_KERNEL);
2705 	if (exec_list == NULL || exec2_list == NULL) {
2706 		drm_dbg(&i915->drm,
2707 			"Failed to allocate exec list for %d buffers\n",
2708 			args->buffer_count);
2709 		kvfree(exec_list);
2710 		kvfree(exec2_list);
2711 		return -ENOMEM;
2712 	}
2713 	err = copy_from_user(exec_list,
2714 			     u64_to_user_ptr(args->buffers_ptr),
2715 			     sizeof(*exec_list) * count);
2716 	if (err) {
2717 		drm_dbg(&i915->drm, "copy %d exec entries failed %d\n",
2718 			args->buffer_count, err);
2719 		kvfree(exec_list);
2720 		kvfree(exec2_list);
2721 		return -EFAULT;
2722 	}
2723 
2724 	for (i = 0; i < args->buffer_count; i++) {
2725 		exec2_list[i].handle = exec_list[i].handle;
2726 		exec2_list[i].relocation_count = exec_list[i].relocation_count;
2727 		exec2_list[i].relocs_ptr = exec_list[i].relocs_ptr;
2728 		exec2_list[i].alignment = exec_list[i].alignment;
2729 		exec2_list[i].offset = exec_list[i].offset;
2730 		if (INTEL_GEN(to_i915(dev)) < 4)
2731 			exec2_list[i].flags = EXEC_OBJECT_NEEDS_FENCE;
2732 		else
2733 			exec2_list[i].flags = 0;
2734 	}
2735 
2736 	err = i915_gem_do_execbuffer(dev, file, &exec2, exec2_list, NULL);
2737 	if (exec2.flags & __EXEC_HAS_RELOC) {
2738 		struct drm_i915_gem_exec_object __user *user_exec_list =
2739 			u64_to_user_ptr(args->buffers_ptr);
2740 
2741 		/* Copy the new buffer offsets back to the user's exec list. */
2742 		for (i = 0; i < args->buffer_count; i++) {
2743 			if (!(exec2_list[i].offset & UPDATE))
2744 				continue;
2745 
2746 			exec2_list[i].offset =
2747 				gen8_canonical_addr(exec2_list[i].offset & PIN_OFFSET_MASK);
2748 			exec2_list[i].offset &= PIN_OFFSET_MASK;
2749 			if (__copy_to_user(&user_exec_list[i].offset,
2750 					   &exec2_list[i].offset,
2751 					   sizeof(user_exec_list[i].offset)))
2752 				break;
2753 		}
2754 	}
2755 
2756 	kvfree(exec_list);
2757 	kvfree(exec2_list);
2758 	return err;
2759 }
2760 
2761 int
2762 i915_gem_execbuffer2_ioctl(struct drm_device *dev, void *data,
2763 			   struct drm_file *file)
2764 {
2765 	struct drm_i915_private *i915 = to_i915(dev);
2766 	struct drm_i915_gem_execbuffer2 *args = data;
2767 	struct drm_i915_gem_exec_object2 *exec2_list;
2768 	struct drm_syncobj **fences = NULL;
2769 	const size_t count = args->buffer_count;
2770 	int err;
2771 
2772 	if (!check_buffer_count(count)) {
2773 		drm_dbg(&i915->drm, "execbuf2 with %zd buffers\n", count);
2774 		return -EINVAL;
2775 	}
2776 
2777 	err = i915_gem_check_execbuffer(args);
2778 	if (err)
2779 		return err;
2780 
2781 	/* Allocate an extra slot for use by the command parser */
2782 	exec2_list = kvmalloc_array(count + 1, eb_element_size(),
2783 				    __GFP_NOWARN | GFP_KERNEL);
2784 	if (exec2_list == NULL) {
2785 		drm_dbg(&i915->drm, "Failed to allocate exec list for %zd buffers\n",
2786 			count);
2787 		return -ENOMEM;
2788 	}
2789 	if (copy_from_user(exec2_list,
2790 			   u64_to_user_ptr(args->buffers_ptr),
2791 			   sizeof(*exec2_list) * count)) {
2792 		drm_dbg(&i915->drm, "copy %zd exec entries failed\n", count);
2793 		kvfree(exec2_list);
2794 		return -EFAULT;
2795 	}
2796 
2797 	if (args->flags & I915_EXEC_FENCE_ARRAY) {
2798 		fences = get_fence_array(args, file);
2799 		if (IS_ERR(fences)) {
2800 			kvfree(exec2_list);
2801 			return PTR_ERR(fences);
2802 		}
2803 	}
2804 
2805 	err = i915_gem_do_execbuffer(dev, file, args, exec2_list, fences);
2806 
2807 	/*
2808 	 * Now that we have begun execution of the batchbuffer, we ignore
2809 	 * any new error after this point. Also given that we have already
2810 	 * updated the associated relocations, we try to write out the current
2811 	 * object locations irrespective of any error.
2812 	 */
2813 	if (args->flags & __EXEC_HAS_RELOC) {
2814 		struct drm_i915_gem_exec_object2 __user *user_exec_list =
2815 			u64_to_user_ptr(args->buffers_ptr);
2816 		unsigned int i;
2817 
2818 		/* Copy the new buffer offsets back to the user's exec list. */
2819 		/*
2820 		 * Note: count * sizeof(*user_exec_list) does not overflow,
2821 		 * because we checked 'count' in check_buffer_count().
2822 		 *
2823 		 * And this range already got effectively checked earlier
2824 		 * when we did the "copy_from_user()" above.
2825 		 */
2826 		if (!user_access_begin(user_exec_list, count * sizeof(*user_exec_list)))
2827 			goto end;
2828 
2829 		for (i = 0; i < args->buffer_count; i++) {
2830 			if (!(exec2_list[i].offset & UPDATE))
2831 				continue;
2832 
2833 			exec2_list[i].offset =
2834 				gen8_canonical_addr(exec2_list[i].offset & PIN_OFFSET_MASK);
2835 			unsafe_put_user(exec2_list[i].offset,
2836 					&user_exec_list[i].offset,
2837 					end_user);
2838 		}
2839 end_user:
2840 		user_access_end();
2841 end:;
2842 	}
2843 
2844 	args->flags &= ~__I915_EXEC_UNKNOWN_FLAGS;
2845 	put_fence_array(args, fences);
2846 	kvfree(exec2_list);
2847 	return err;
2848 }
2849