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