xref: /openbsd-src/sys/dev/pci/drm/i915/gem/i915_gem_execbuffer.c (revision 25c4e8bd056e974b28f4a0ffd39d76c190a56013)
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_unmap(struct reloc_cache *cache)
1074 {
1075 	void *vaddr;
1076 
1077 	if (!cache->vaddr)
1078 		return;
1079 
1080 	vaddr = unmask_page(cache->vaddr);
1081 	if (cache->vaddr & KMAP)
1082 		kunmap_atomic(vaddr);
1083 	else
1084 #ifdef __linux__
1085 		io_mapping_unmap_atomic((void __iomem *)vaddr);
1086 #else
1087 		agp_unmap_atomic(cache->map, cache->ioh);
1088 #endif
1089 }
1090 
1091 static void reloc_cache_remap(struct reloc_cache *cache,
1092 			      struct drm_i915_gem_object *obj)
1093 {
1094 	void *vaddr;
1095 
1096 	if (!cache->vaddr)
1097 		return;
1098 
1099 	if (cache->vaddr & KMAP) {
1100 		struct vm_page *page = i915_gem_object_get_page(obj, cache->page);
1101 
1102 		vaddr = kmap_atomic(page);
1103 		cache->vaddr = unmask_flags(cache->vaddr) |
1104 			(unsigned long)vaddr;
1105 	} else {
1106 		struct i915_ggtt *ggtt = cache_to_ggtt(cache);
1107 		unsigned long offset;
1108 
1109 		offset = cache->node.start;
1110 		if (!drm_mm_node_allocated(&cache->node))
1111 			offset += cache->page << PAGE_SHIFT;
1112 
1113 #ifdef __linux__
1114 		cache->vaddr = (unsigned long)
1115 			io_mapping_map_atomic_wc(&ggtt->iomap, offset);
1116 #else
1117 		agp_map_atomic(cache->map, offset, &cache->ioh);
1118 		cache->vaddr = (unsigned long)
1119 			bus_space_vaddr(cache->iot, cache->ioh);
1120 #endif
1121 	}
1122 }
1123 
1124 static void reloc_cache_reset(struct reloc_cache *cache, struct i915_execbuffer *eb)
1125 {
1126 	void *vaddr;
1127 
1128 	if (!cache->vaddr)
1129 		return;
1130 
1131 	vaddr = unmask_page(cache->vaddr);
1132 	if (cache->vaddr & KMAP) {
1133 		struct drm_i915_gem_object *obj =
1134 			(struct drm_i915_gem_object *)cache->node.mm;
1135 		if (cache->vaddr & CLFLUSH_AFTER)
1136 			mb();
1137 
1138 		kunmap_atomic(vaddr);
1139 		i915_gem_object_finish_access(obj);
1140 	} else {
1141 		struct i915_ggtt *ggtt = cache_to_ggtt(cache);
1142 
1143 		intel_gt_flush_ggtt_writes(ggtt->vm.gt);
1144 #ifdef __linux__
1145 		io_mapping_unmap_atomic((void __iomem *)vaddr);
1146 #else
1147 		agp_unmap_atomic(cache->map, cache->ioh);
1148 #endif
1149 
1150 		if (drm_mm_node_allocated(&cache->node)) {
1151 			ggtt->vm.clear_range(&ggtt->vm,
1152 					     cache->node.start,
1153 					     cache->node.size);
1154 			mutex_lock(&ggtt->vm.mutex);
1155 			drm_mm_remove_node(&cache->node);
1156 			mutex_unlock(&ggtt->vm.mutex);
1157 		} else {
1158 			i915_vma_unpin((struct i915_vma *)cache->node.mm);
1159 		}
1160 	}
1161 
1162 	cache->vaddr = 0;
1163 	cache->page = -1;
1164 }
1165 
1166 static void *reloc_kmap(struct drm_i915_gem_object *obj,
1167 			struct reloc_cache *cache,
1168 			unsigned long pageno)
1169 {
1170 	void *vaddr;
1171 	struct vm_page *page;
1172 
1173 	if (cache->vaddr) {
1174 		kunmap_atomic(unmask_page(cache->vaddr));
1175 	} else {
1176 		unsigned int flushes;
1177 		int err;
1178 
1179 		err = i915_gem_object_prepare_write(obj, &flushes);
1180 		if (err)
1181 			return ERR_PTR(err);
1182 
1183 		BUILD_BUG_ON(KMAP & CLFLUSH_FLAGS);
1184 		BUILD_BUG_ON((KMAP | CLFLUSH_FLAGS) & LINUX_PAGE_MASK);
1185 
1186 		cache->vaddr = flushes | KMAP;
1187 		cache->node.mm = (void *)obj;
1188 		if (flushes)
1189 			mb();
1190 	}
1191 
1192 	page = i915_gem_object_get_page(obj, pageno);
1193 	if (!obj->mm.dirty)
1194 		set_page_dirty(page);
1195 
1196 	vaddr = kmap_atomic(page);
1197 	cache->vaddr = unmask_flags(cache->vaddr) | (unsigned long)vaddr;
1198 	cache->page = pageno;
1199 
1200 	return vaddr;
1201 }
1202 
1203 static void *reloc_iomap(struct drm_i915_gem_object *obj,
1204 			 struct i915_execbuffer *eb,
1205 			 unsigned long page)
1206 {
1207 	struct reloc_cache *cache = &eb->reloc_cache;
1208 	struct i915_ggtt *ggtt = cache_to_ggtt(cache);
1209 	unsigned long offset;
1210 	void *vaddr;
1211 
1212 	if (cache->vaddr) {
1213 		intel_gt_flush_ggtt_writes(ggtt->vm.gt);
1214 #ifdef __linux__
1215 		io_mapping_unmap_atomic((void __force __iomem *) unmask_page(cache->vaddr));
1216 #else
1217 		agp_unmap_atomic(cache->map, cache->ioh);
1218 #endif
1219 	} else {
1220 		struct i915_vma *vma;
1221 		int err;
1222 
1223 		if (i915_gem_object_is_tiled(obj))
1224 			return ERR_PTR(-EINVAL);
1225 
1226 		if (use_cpu_reloc(cache, obj))
1227 			return NULL;
1228 
1229 		err = i915_gem_object_set_to_gtt_domain(obj, true);
1230 		if (err)
1231 			return ERR_PTR(err);
1232 
1233 		vma = i915_gem_object_ggtt_pin_ww(obj, &eb->ww, NULL, 0, 0,
1234 						  PIN_MAPPABLE |
1235 						  PIN_NONBLOCK /* NOWARN */ |
1236 						  PIN_NOEVICT);
1237 		if (vma == ERR_PTR(-EDEADLK))
1238 			return vma;
1239 
1240 		if (IS_ERR(vma)) {
1241 			memset(&cache->node, 0, sizeof(cache->node));
1242 			mutex_lock(&ggtt->vm.mutex);
1243 			err = drm_mm_insert_node_in_range
1244 				(&ggtt->vm.mm, &cache->node,
1245 				 PAGE_SIZE, 0, I915_COLOR_UNEVICTABLE,
1246 				 0, ggtt->mappable_end,
1247 				 DRM_MM_INSERT_LOW);
1248 			mutex_unlock(&ggtt->vm.mutex);
1249 			if (err) /* no inactive aperture space, use cpu reloc */
1250 				return NULL;
1251 		} else {
1252 			cache->node.start = vma->node.start;
1253 			cache->node.mm = (void *)vma;
1254 		}
1255 	}
1256 
1257 	offset = cache->node.start;
1258 	if (drm_mm_node_allocated(&cache->node)) {
1259 		ggtt->vm.insert_page(&ggtt->vm,
1260 				     i915_gem_object_get_dma_address(obj, page),
1261 				     offset, I915_CACHE_NONE, 0);
1262 	} else {
1263 		offset += page << PAGE_SHIFT;
1264 	}
1265 
1266 #ifdef __linux__
1267 	vaddr = (void __force *)io_mapping_map_atomic_wc(&ggtt->iomap,
1268 							 offset);
1269 #else
1270 	agp_map_atomic(cache->map, offset, &cache->ioh);
1271 	vaddr = bus_space_vaddr(cache->iot, cache->ioh);
1272 #endif
1273 	cache->page = page;
1274 	cache->vaddr = (unsigned long)vaddr;
1275 
1276 	return vaddr;
1277 }
1278 
1279 static void *reloc_vaddr(struct drm_i915_gem_object *obj,
1280 			 struct i915_execbuffer *eb,
1281 			 unsigned long page)
1282 {
1283 	struct reloc_cache *cache = &eb->reloc_cache;
1284 	void *vaddr;
1285 
1286 	if (cache->page == page) {
1287 		vaddr = unmask_page(cache->vaddr);
1288 	} else {
1289 		vaddr = NULL;
1290 		if ((cache->vaddr & KMAP) == 0)
1291 			vaddr = reloc_iomap(obj, eb, page);
1292 		if (!vaddr)
1293 			vaddr = reloc_kmap(obj, cache, page);
1294 	}
1295 
1296 	return vaddr;
1297 }
1298 
1299 static void clflush_write32(u32 *addr, u32 value, unsigned int flushes)
1300 {
1301 	if (unlikely(flushes & (CLFLUSH_BEFORE | CLFLUSH_AFTER))) {
1302 		if (flushes & CLFLUSH_BEFORE) {
1303 			clflushopt(addr);
1304 			mb();
1305 		}
1306 
1307 		*addr = value;
1308 
1309 		/*
1310 		 * Writes to the same cacheline are serialised by the CPU
1311 		 * (including clflush). On the write path, we only require
1312 		 * that it hits memory in an orderly fashion and place
1313 		 * mb barriers at the start and end of the relocation phase
1314 		 * to ensure ordering of clflush wrt to the system.
1315 		 */
1316 		if (flushes & CLFLUSH_AFTER)
1317 			clflushopt(addr);
1318 	} else
1319 		*addr = value;
1320 }
1321 
1322 static u64
1323 relocate_entry(struct i915_vma *vma,
1324 	       const struct drm_i915_gem_relocation_entry *reloc,
1325 	       struct i915_execbuffer *eb,
1326 	       const struct i915_vma *target)
1327 {
1328 	u64 target_addr = relocation_target(reloc, target);
1329 	u64 offset = reloc->offset;
1330 	bool wide = eb->reloc_cache.use_64bit_reloc;
1331 	void *vaddr;
1332 
1333 repeat:
1334 	vaddr = reloc_vaddr(vma->obj, eb,
1335 			    offset >> PAGE_SHIFT);
1336 	if (IS_ERR(vaddr))
1337 		return PTR_ERR(vaddr);
1338 
1339 	GEM_BUG_ON(!IS_ALIGNED(offset, sizeof(u32)));
1340 	clflush_write32(vaddr + offset_in_page(offset),
1341 			lower_32_bits(target_addr),
1342 			eb->reloc_cache.vaddr);
1343 
1344 	if (wide) {
1345 		offset += sizeof(u32);
1346 		target_addr >>= 32;
1347 		wide = false;
1348 		goto repeat;
1349 	}
1350 
1351 	return target->node.start | UPDATE;
1352 }
1353 
1354 static u64
1355 eb_relocate_entry(struct i915_execbuffer *eb,
1356 		  struct eb_vma *ev,
1357 		  const struct drm_i915_gem_relocation_entry *reloc)
1358 {
1359 	struct drm_i915_private *i915 = eb->i915;
1360 	struct eb_vma *target;
1361 	int err;
1362 
1363 	/* we've already hold a reference to all valid objects */
1364 	target = eb_get_vma(eb, reloc->target_handle);
1365 	if (unlikely(!target))
1366 		return -ENOENT;
1367 
1368 	/* Validate that the target is in a valid r/w GPU domain */
1369 	if (unlikely(reloc->write_domain & (reloc->write_domain - 1))) {
1370 		drm_dbg(&i915->drm, "reloc with multiple write domains: "
1371 			  "target %d offset %d "
1372 			  "read %08x write %08x",
1373 			  reloc->target_handle,
1374 			  (int) reloc->offset,
1375 			  reloc->read_domains,
1376 			  reloc->write_domain);
1377 		return -EINVAL;
1378 	}
1379 	if (unlikely((reloc->write_domain | reloc->read_domains)
1380 		     & ~I915_GEM_GPU_DOMAINS)) {
1381 		drm_dbg(&i915->drm, "reloc with read/write non-GPU domains: "
1382 			  "target %d offset %d "
1383 			  "read %08x write %08x",
1384 			  reloc->target_handle,
1385 			  (int) reloc->offset,
1386 			  reloc->read_domains,
1387 			  reloc->write_domain);
1388 		return -EINVAL;
1389 	}
1390 
1391 	if (reloc->write_domain) {
1392 		target->flags |= EXEC_OBJECT_WRITE;
1393 
1394 		/*
1395 		 * Sandybridge PPGTT errata: We need a global gtt mapping
1396 		 * for MI and pipe_control writes because the gpu doesn't
1397 		 * properly redirect them through the ppgtt for non_secure
1398 		 * batchbuffers.
1399 		 */
1400 		if (reloc->write_domain == I915_GEM_DOMAIN_INSTRUCTION &&
1401 		    GRAPHICS_VER(eb->i915) == 6 &&
1402 		    !i915_vma_is_bound(target->vma, I915_VMA_GLOBAL_BIND)) {
1403 			struct i915_vma *vma = target->vma;
1404 
1405 			reloc_cache_unmap(&eb->reloc_cache);
1406 			mutex_lock(&vma->vm->mutex);
1407 			err = i915_vma_bind(target->vma,
1408 					    target->vma->obj->cache_level,
1409 					    PIN_GLOBAL, NULL);
1410 			mutex_unlock(&vma->vm->mutex);
1411 			reloc_cache_remap(&eb->reloc_cache, ev->vma->obj);
1412 			if (err)
1413 				return err;
1414 		}
1415 	}
1416 
1417 	/*
1418 	 * If the relocation already has the right value in it, no
1419 	 * more work needs to be done.
1420 	 */
1421 	if (!DBG_FORCE_RELOC &&
1422 	    gen8_canonical_addr(target->vma->node.start) == reloc->presumed_offset)
1423 		return 0;
1424 
1425 	/* Check that the relocation address is valid... */
1426 	if (unlikely(reloc->offset >
1427 		     ev->vma->size - (eb->reloc_cache.use_64bit_reloc ? 8 : 4))) {
1428 		drm_dbg(&i915->drm, "Relocation beyond object bounds: "
1429 			  "target %d offset %d size %d.\n",
1430 			  reloc->target_handle,
1431 			  (int)reloc->offset,
1432 			  (int)ev->vma->size);
1433 		return -EINVAL;
1434 	}
1435 	if (unlikely(reloc->offset & 3)) {
1436 		drm_dbg(&i915->drm, "Relocation not 4-byte aligned: "
1437 			  "target %d offset %d.\n",
1438 			  reloc->target_handle,
1439 			  (int)reloc->offset);
1440 		return -EINVAL;
1441 	}
1442 
1443 	/*
1444 	 * If we write into the object, we need to force the synchronisation
1445 	 * barrier, either with an asynchronous clflush or if we executed the
1446 	 * patching using the GPU (though that should be serialised by the
1447 	 * timeline). To be completely sure, and since we are required to
1448 	 * do relocations we are already stalling, disable the user's opt
1449 	 * out of our synchronisation.
1450 	 */
1451 	ev->flags &= ~EXEC_OBJECT_ASYNC;
1452 
1453 	/* and update the user's relocation entry */
1454 	return relocate_entry(ev->vma, reloc, eb, target->vma);
1455 }
1456 
1457 static int eb_relocate_vma(struct i915_execbuffer *eb, struct eb_vma *ev)
1458 {
1459 #define N_RELOC(x) ((x) / sizeof(struct drm_i915_gem_relocation_entry))
1460 	struct drm_i915_gem_relocation_entry stack[N_RELOC(512)];
1461 	const struct drm_i915_gem_exec_object2 *entry = ev->exec;
1462 	struct drm_i915_gem_relocation_entry __user *urelocs =
1463 		u64_to_user_ptr(entry->relocs_ptr);
1464 	unsigned long remain = entry->relocation_count;
1465 
1466 	if (unlikely(remain > N_RELOC(ULONG_MAX)))
1467 		return -EINVAL;
1468 
1469 	/*
1470 	 * We must check that the entire relocation array is safe
1471 	 * to read. However, if the array is not writable the user loses
1472 	 * the updated relocation values.
1473 	 */
1474 	if (unlikely(!access_ok(urelocs, remain * sizeof(*urelocs))))
1475 		return -EFAULT;
1476 
1477 	do {
1478 		struct drm_i915_gem_relocation_entry *r = stack;
1479 		unsigned int count =
1480 			min_t(unsigned long, remain, ARRAY_SIZE(stack));
1481 		unsigned int copied;
1482 
1483 		/*
1484 		 * This is the fast path and we cannot handle a pagefault
1485 		 * whilst holding the struct mutex lest the user pass in the
1486 		 * relocations contained within a mmaped bo. For in such a case
1487 		 * we, the page fault handler would call i915_gem_fault() and
1488 		 * we would try to acquire the struct mutex again. Obviously
1489 		 * this is bad and so lockdep complains vehemently.
1490 		 */
1491 		pagefault_disable();
1492 		copied = __copy_from_user_inatomic(r, urelocs, count * sizeof(r[0]));
1493 		pagefault_enable();
1494 		if (unlikely(copied)) {
1495 			remain = -EFAULT;
1496 			goto out;
1497 		}
1498 
1499 		remain -= count;
1500 		do {
1501 			u64 offset = eb_relocate_entry(eb, ev, r);
1502 
1503 			if (likely(offset == 0)) {
1504 			} else if ((s64)offset < 0) {
1505 				remain = (int)offset;
1506 				goto out;
1507 			} else {
1508 				/*
1509 				 * Note that reporting an error now
1510 				 * leaves everything in an inconsistent
1511 				 * state as we have *already* changed
1512 				 * the relocation value inside the
1513 				 * object. As we have not changed the
1514 				 * reloc.presumed_offset or will not
1515 				 * change the execobject.offset, on the
1516 				 * call we may not rewrite the value
1517 				 * inside the object, leaving it
1518 				 * dangling and causing a GPU hang. Unless
1519 				 * userspace dynamically rebuilds the
1520 				 * relocations on each execbuf rather than
1521 				 * presume a static tree.
1522 				 *
1523 				 * We did previously check if the relocations
1524 				 * were writable (access_ok), an error now
1525 				 * would be a strange race with mprotect,
1526 				 * having already demonstrated that we
1527 				 * can read from this userspace address.
1528 				 */
1529 				offset = gen8_canonical_addr(offset & ~UPDATE);
1530 				__put_user(offset,
1531 					   &urelocs[r - stack].presumed_offset);
1532 			}
1533 		} while (r++, --count);
1534 		urelocs += ARRAY_SIZE(stack);
1535 	} while (remain);
1536 out:
1537 	reloc_cache_reset(&eb->reloc_cache, eb);
1538 	return remain;
1539 }
1540 
1541 static int
1542 eb_relocate_vma_slow(struct i915_execbuffer *eb, struct eb_vma *ev)
1543 {
1544 	const struct drm_i915_gem_exec_object2 *entry = ev->exec;
1545 	struct drm_i915_gem_relocation_entry *relocs =
1546 		u64_to_ptr(typeof(*relocs), entry->relocs_ptr);
1547 	unsigned int i;
1548 	int err;
1549 
1550 	for (i = 0; i < entry->relocation_count; i++) {
1551 		u64 offset = eb_relocate_entry(eb, ev, &relocs[i]);
1552 
1553 		if ((s64)offset < 0) {
1554 			err = (int)offset;
1555 			goto err;
1556 		}
1557 	}
1558 	err = 0;
1559 err:
1560 	reloc_cache_reset(&eb->reloc_cache, eb);
1561 	return err;
1562 }
1563 
1564 static int check_relocations(const struct drm_i915_gem_exec_object2 *entry)
1565 {
1566 	const char __user *addr, *end;
1567 	unsigned long size;
1568 	char __maybe_unused c;
1569 
1570 	size = entry->relocation_count;
1571 	if (size == 0)
1572 		return 0;
1573 
1574 	if (size > N_RELOC(ULONG_MAX))
1575 		return -EINVAL;
1576 
1577 	addr = u64_to_user_ptr(entry->relocs_ptr);
1578 	size *= sizeof(struct drm_i915_gem_relocation_entry);
1579 	if (!access_ok(addr, size))
1580 		return -EFAULT;
1581 
1582 	end = addr + size;
1583 	for (; addr < end; addr += PAGE_SIZE) {
1584 		int err = __get_user(c, addr);
1585 		if (err)
1586 			return err;
1587 	}
1588 	return __get_user(c, end - 1);
1589 }
1590 
1591 static int eb_copy_relocations(const struct i915_execbuffer *eb)
1592 {
1593 	struct drm_i915_gem_relocation_entry *relocs;
1594 	const unsigned int count = eb->buffer_count;
1595 	unsigned int i;
1596 	int err;
1597 
1598 	for (i = 0; i < count; i++) {
1599 		const unsigned int nreloc = eb->exec[i].relocation_count;
1600 		struct drm_i915_gem_relocation_entry __user *urelocs;
1601 		unsigned long size;
1602 		unsigned long copied;
1603 
1604 		if (nreloc == 0)
1605 			continue;
1606 
1607 		err = check_relocations(&eb->exec[i]);
1608 		if (err)
1609 			goto err;
1610 
1611 		urelocs = u64_to_user_ptr(eb->exec[i].relocs_ptr);
1612 		size = nreloc * sizeof(*relocs);
1613 
1614 		relocs = kvmalloc_array(size, 1, GFP_KERNEL);
1615 		if (!relocs) {
1616 			err = -ENOMEM;
1617 			goto err;
1618 		}
1619 
1620 		/* copy_from_user is limited to < 4GiB */
1621 		copied = 0;
1622 		do {
1623 			unsigned int len =
1624 				min_t(u64, BIT_ULL(31), size - copied);
1625 
1626 			if (__copy_from_user((char *)relocs + copied,
1627 					     (char __user *)urelocs + copied,
1628 					     len))
1629 				goto end;
1630 
1631 			copied += len;
1632 		} while (copied < size);
1633 
1634 		/*
1635 		 * As we do not update the known relocation offsets after
1636 		 * relocating (due to the complexities in lock handling),
1637 		 * we need to mark them as invalid now so that we force the
1638 		 * relocation processing next time. Just in case the target
1639 		 * object is evicted and then rebound into its old
1640 		 * presumed_offset before the next execbuffer - if that
1641 		 * happened we would make the mistake of assuming that the
1642 		 * relocations were valid.
1643 		 */
1644 		if (!user_access_begin(urelocs, size))
1645 			goto end;
1646 
1647 		for (copied = 0; copied < nreloc; copied++)
1648 			unsafe_put_user(-1,
1649 					&urelocs[copied].presumed_offset,
1650 					end_user);
1651 		user_access_end();
1652 
1653 		eb->exec[i].relocs_ptr = (uintptr_t)relocs;
1654 	}
1655 
1656 	return 0;
1657 
1658 end_user:
1659 	user_access_end();
1660 end:
1661 	kvfree(relocs);
1662 	err = -EFAULT;
1663 err:
1664 	while (i--) {
1665 		relocs = u64_to_ptr(typeof(*relocs), eb->exec[i].relocs_ptr);
1666 		if (eb->exec[i].relocation_count)
1667 			kvfree(relocs);
1668 	}
1669 	return err;
1670 }
1671 
1672 static int eb_prefault_relocations(const struct i915_execbuffer *eb)
1673 {
1674 	const unsigned int count = eb->buffer_count;
1675 	unsigned int i;
1676 
1677 	for (i = 0; i < count; i++) {
1678 		int err;
1679 
1680 		err = check_relocations(&eb->exec[i]);
1681 		if (err)
1682 			return err;
1683 	}
1684 
1685 	return 0;
1686 }
1687 
1688 static int eb_reinit_userptr(struct i915_execbuffer *eb)
1689 {
1690 	const unsigned int count = eb->buffer_count;
1691 	unsigned int i;
1692 	int ret;
1693 
1694 	if (likely(!(eb->args->flags & __EXEC_USERPTR_USED)))
1695 		return 0;
1696 
1697 	for (i = 0; i < count; i++) {
1698 		struct eb_vma *ev = &eb->vma[i];
1699 
1700 		if (!i915_gem_object_is_userptr(ev->vma->obj))
1701 			continue;
1702 
1703 		ret = i915_gem_object_userptr_submit_init(ev->vma->obj);
1704 		if (ret)
1705 			return ret;
1706 
1707 		ev->flags |= __EXEC_OBJECT_USERPTR_INIT;
1708 	}
1709 
1710 	return 0;
1711 }
1712 
1713 static noinline int eb_relocate_parse_slow(struct i915_execbuffer *eb,
1714 					   struct i915_request *rq)
1715 {
1716 	bool have_copy = false;
1717 	struct eb_vma *ev;
1718 	int err = 0;
1719 
1720 repeat:
1721 	if (signal_pending(current)) {
1722 		err = -ERESTARTSYS;
1723 		goto out;
1724 	}
1725 
1726 	/* We may process another execbuffer during the unlock... */
1727 	eb_release_vmas(eb, false);
1728 	i915_gem_ww_ctx_fini(&eb->ww);
1729 
1730 	if (rq) {
1731 		/* nonblocking is always false */
1732 		if (i915_request_wait(rq, I915_WAIT_INTERRUPTIBLE,
1733 				      MAX_SCHEDULE_TIMEOUT) < 0) {
1734 			i915_request_put(rq);
1735 			rq = NULL;
1736 
1737 			err = -EINTR;
1738 			goto err_relock;
1739 		}
1740 
1741 		i915_request_put(rq);
1742 		rq = NULL;
1743 	}
1744 
1745 	/*
1746 	 * We take 3 passes through the slowpatch.
1747 	 *
1748 	 * 1 - we try to just prefault all the user relocation entries and
1749 	 * then attempt to reuse the atomic pagefault disabled fast path again.
1750 	 *
1751 	 * 2 - we copy the user entries to a local buffer here outside of the
1752 	 * local and allow ourselves to wait upon any rendering before
1753 	 * relocations
1754 	 *
1755 	 * 3 - we already have a local copy of the relocation entries, but
1756 	 * were interrupted (EAGAIN) whilst waiting for the objects, try again.
1757 	 */
1758 	if (!err) {
1759 		err = eb_prefault_relocations(eb);
1760 	} else if (!have_copy) {
1761 		err = eb_copy_relocations(eb);
1762 		have_copy = err == 0;
1763 	} else {
1764 		cond_resched();
1765 		err = 0;
1766 	}
1767 
1768 	if (!err)
1769 		err = eb_reinit_userptr(eb);
1770 
1771 err_relock:
1772 	i915_gem_ww_ctx_init(&eb->ww, true);
1773 	if (err)
1774 		goto out;
1775 
1776 	/* reacquire the objects */
1777 repeat_validate:
1778 	rq = eb_pin_engine(eb, false);
1779 	if (IS_ERR(rq)) {
1780 		err = PTR_ERR(rq);
1781 		rq = NULL;
1782 		goto err;
1783 	}
1784 
1785 	/* We didn't throttle, should be NULL */
1786 	GEM_WARN_ON(rq);
1787 
1788 	err = eb_validate_vmas(eb);
1789 	if (err)
1790 		goto err;
1791 
1792 	GEM_BUG_ON(!eb->batch);
1793 
1794 	list_for_each_entry(ev, &eb->relocs, reloc_link) {
1795 		if (!have_copy) {
1796 			err = eb_relocate_vma(eb, ev);
1797 			if (err)
1798 				break;
1799 		} else {
1800 			err = eb_relocate_vma_slow(eb, ev);
1801 			if (err)
1802 				break;
1803 		}
1804 	}
1805 
1806 	if (err == -EDEADLK)
1807 		goto err;
1808 
1809 	if (err && !have_copy)
1810 		goto repeat;
1811 
1812 	if (err)
1813 		goto err;
1814 
1815 	/* as last step, parse the command buffer */
1816 	err = eb_parse(eb);
1817 	if (err)
1818 		goto err;
1819 
1820 	/*
1821 	 * Leave the user relocations as are, this is the painfully slow path,
1822 	 * and we want to avoid the complication of dropping the lock whilst
1823 	 * having buffers reserved in the aperture and so causing spurious
1824 	 * ENOSPC for random operations.
1825 	 */
1826 
1827 err:
1828 	if (err == -EDEADLK) {
1829 		eb_release_vmas(eb, false);
1830 		err = i915_gem_ww_ctx_backoff(&eb->ww);
1831 		if (!err)
1832 			goto repeat_validate;
1833 	}
1834 
1835 	if (err == -EAGAIN)
1836 		goto repeat;
1837 
1838 out:
1839 	if (have_copy) {
1840 		const unsigned int count = eb->buffer_count;
1841 		unsigned int i;
1842 
1843 		for (i = 0; i < count; i++) {
1844 			const struct drm_i915_gem_exec_object2 *entry =
1845 				&eb->exec[i];
1846 			struct drm_i915_gem_relocation_entry *relocs;
1847 
1848 			if (!entry->relocation_count)
1849 				continue;
1850 
1851 			relocs = u64_to_ptr(typeof(*relocs), entry->relocs_ptr);
1852 			kvfree(relocs);
1853 		}
1854 	}
1855 
1856 	if (rq)
1857 		i915_request_put(rq);
1858 
1859 	return err;
1860 }
1861 
1862 static int eb_relocate_parse(struct i915_execbuffer *eb)
1863 {
1864 	int err;
1865 	struct i915_request *rq = NULL;
1866 	bool throttle = true;
1867 
1868 retry:
1869 	rq = eb_pin_engine(eb, throttle);
1870 	if (IS_ERR(rq)) {
1871 		err = PTR_ERR(rq);
1872 		rq = NULL;
1873 		if (err != -EDEADLK)
1874 			return err;
1875 
1876 		goto err;
1877 	}
1878 
1879 	if (rq) {
1880 #ifdef __linux__
1881 		bool nonblock = eb->file->filp->f_flags & O_NONBLOCK;
1882 #else
1883 		bool nonblock = eb->file->filp->f_flag & FNONBLOCK;
1884 #endif
1885 
1886 		/* Need to drop all locks now for throttling, take slowpath */
1887 		err = i915_request_wait(rq, I915_WAIT_INTERRUPTIBLE, 0);
1888 		if (err == -ETIME) {
1889 			if (nonblock) {
1890 				err = -EWOULDBLOCK;
1891 				i915_request_put(rq);
1892 				goto err;
1893 			}
1894 			goto slow;
1895 		}
1896 		i915_request_put(rq);
1897 		rq = NULL;
1898 	}
1899 
1900 	/* only throttle once, even if we didn't need to throttle */
1901 	throttle = false;
1902 
1903 	err = eb_validate_vmas(eb);
1904 	if (err == -EAGAIN)
1905 		goto slow;
1906 	else if (err)
1907 		goto err;
1908 
1909 	/* The objects are in their final locations, apply the relocations. */
1910 	if (eb->args->flags & __EXEC_HAS_RELOC) {
1911 		struct eb_vma *ev;
1912 
1913 		list_for_each_entry(ev, &eb->relocs, reloc_link) {
1914 			err = eb_relocate_vma(eb, ev);
1915 			if (err)
1916 				break;
1917 		}
1918 
1919 		if (err == -EDEADLK)
1920 			goto err;
1921 		else if (err)
1922 			goto slow;
1923 	}
1924 
1925 	if (!err)
1926 		err = eb_parse(eb);
1927 
1928 err:
1929 	if (err == -EDEADLK) {
1930 		eb_release_vmas(eb, false);
1931 		err = i915_gem_ww_ctx_backoff(&eb->ww);
1932 		if (!err)
1933 			goto retry;
1934 	}
1935 
1936 	return err;
1937 
1938 slow:
1939 	err = eb_relocate_parse_slow(eb, rq);
1940 	if (err)
1941 		/*
1942 		 * If the user expects the execobject.offset and
1943 		 * reloc.presumed_offset to be an exact match,
1944 		 * as for using NO_RELOC, then we cannot update
1945 		 * the execobject.offset until we have completed
1946 		 * relocation.
1947 		 */
1948 		eb->args->flags &= ~__EXEC_HAS_RELOC;
1949 
1950 	return err;
1951 }
1952 
1953 static int eb_move_to_gpu(struct i915_execbuffer *eb)
1954 {
1955 	const unsigned int count = eb->buffer_count;
1956 	unsigned int i = count;
1957 	int err = 0;
1958 
1959 	while (i--) {
1960 		struct eb_vma *ev = &eb->vma[i];
1961 		struct i915_vma *vma = ev->vma;
1962 		unsigned int flags = ev->flags;
1963 		struct drm_i915_gem_object *obj = vma->obj;
1964 
1965 		assert_vma_held(vma);
1966 
1967 		if (flags & EXEC_OBJECT_CAPTURE) {
1968 			struct i915_capture_list *capture;
1969 
1970 			capture = kmalloc(sizeof(*capture), GFP_KERNEL);
1971 			if (capture) {
1972 				capture->next = eb->request->capture_list;
1973 				capture->vma = vma;
1974 				eb->request->capture_list = capture;
1975 			}
1976 		}
1977 
1978 		/*
1979 		 * If the GPU is not _reading_ through the CPU cache, we need
1980 		 * to make sure that any writes (both previous GPU writes from
1981 		 * before a change in snooping levels and normal CPU writes)
1982 		 * caught in that cache are flushed to main memory.
1983 		 *
1984 		 * We want to say
1985 		 *   obj->cache_dirty &&
1986 		 *   !(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ)
1987 		 * but gcc's optimiser doesn't handle that as well and emits
1988 		 * two jumps instead of one. Maybe one day...
1989 		 */
1990 		if (unlikely(obj->cache_dirty & ~obj->cache_coherent)) {
1991 			if (i915_gem_clflush_object(obj, 0))
1992 				flags &= ~EXEC_OBJECT_ASYNC;
1993 		}
1994 
1995 		if (err == 0 && !(flags & EXEC_OBJECT_ASYNC)) {
1996 			err = i915_request_await_object
1997 				(eb->request, obj, flags & EXEC_OBJECT_WRITE);
1998 		}
1999 
2000 		if (err == 0)
2001 			err = i915_vma_move_to_active(vma, eb->request,
2002 						      flags | __EXEC_OBJECT_NO_RESERVE);
2003 	}
2004 
2005 #ifdef CONFIG_MMU_NOTIFIER
2006 	if (!err && (eb->args->flags & __EXEC_USERPTR_USED)) {
2007 		read_lock(&eb->i915->mm.notifier_lock);
2008 
2009 		/*
2010 		 * count is always at least 1, otherwise __EXEC_USERPTR_USED
2011 		 * could not have been set
2012 		 */
2013 		for (i = 0; i < count; i++) {
2014 			struct eb_vma *ev = &eb->vma[i];
2015 			struct drm_i915_gem_object *obj = ev->vma->obj;
2016 
2017 			if (!i915_gem_object_is_userptr(obj))
2018 				continue;
2019 
2020 			err = i915_gem_object_userptr_submit_done(obj);
2021 			if (err)
2022 				break;
2023 		}
2024 
2025 		read_unlock(&eb->i915->mm.notifier_lock);
2026 	}
2027 #endif
2028 
2029 	if (unlikely(err))
2030 		goto err_skip;
2031 
2032 	/* Unconditionally flush any chipset caches (for streaming writes). */
2033 	intel_gt_chipset_flush(eb->engine->gt);
2034 	return 0;
2035 
2036 err_skip:
2037 	i915_request_set_error_once(eb->request, err);
2038 	return err;
2039 }
2040 
2041 static int i915_gem_check_execbuffer(struct drm_i915_gem_execbuffer2 *exec)
2042 {
2043 	if (exec->flags & __I915_EXEC_ILLEGAL_FLAGS)
2044 		return -EINVAL;
2045 
2046 	/* Kernel clipping was a DRI1 misfeature */
2047 	if (!(exec->flags & (I915_EXEC_FENCE_ARRAY |
2048 			     I915_EXEC_USE_EXTENSIONS))) {
2049 		if (exec->num_cliprects || exec->cliprects_ptr)
2050 			return -EINVAL;
2051 	}
2052 
2053 	if (exec->DR4 == 0xffffffff) {
2054 		DRM_DEBUG("UXA submitting garbage DR4, fixing up\n");
2055 		exec->DR4 = 0;
2056 	}
2057 	if (exec->DR1 || exec->DR4)
2058 		return -EINVAL;
2059 
2060 	if ((exec->batch_start_offset | exec->batch_len) & 0x7)
2061 		return -EINVAL;
2062 
2063 	return 0;
2064 }
2065 
2066 static int i915_reset_gen7_sol_offsets(struct i915_request *rq)
2067 {
2068 	u32 *cs;
2069 	int i;
2070 
2071 	if (GRAPHICS_VER(rq->engine->i915) != 7 || rq->engine->id != RCS0) {
2072 		drm_dbg(&rq->engine->i915->drm, "sol reset is gen7/rcs only\n");
2073 		return -EINVAL;
2074 	}
2075 
2076 	cs = intel_ring_begin(rq, 4 * 2 + 2);
2077 	if (IS_ERR(cs))
2078 		return PTR_ERR(cs);
2079 
2080 	*cs++ = MI_LOAD_REGISTER_IMM(4);
2081 	for (i = 0; i < 4; i++) {
2082 		*cs++ = i915_mmio_reg_offset(GEN7_SO_WRITE_OFFSET(i));
2083 		*cs++ = 0;
2084 	}
2085 	*cs++ = MI_NOOP;
2086 	intel_ring_advance(rq, cs);
2087 
2088 	return 0;
2089 }
2090 
2091 static struct i915_vma *
2092 shadow_batch_pin(struct i915_execbuffer *eb,
2093 		 struct drm_i915_gem_object *obj,
2094 		 struct i915_address_space *vm,
2095 		 unsigned int flags)
2096 {
2097 	struct i915_vma *vma;
2098 	int err;
2099 
2100 	vma = i915_vma_instance(obj, vm, NULL);
2101 	if (IS_ERR(vma))
2102 		return vma;
2103 
2104 	err = i915_vma_pin_ww(vma, &eb->ww, 0, 0, flags);
2105 	if (err)
2106 		return ERR_PTR(err);
2107 
2108 	return vma;
2109 }
2110 
2111 static struct i915_vma *eb_dispatch_secure(struct i915_execbuffer *eb, struct i915_vma *vma)
2112 {
2113 	/*
2114 	 * snb/ivb/vlv conflate the "batch in ppgtt" bit with the "non-secure
2115 	 * batch" bit. Hence we need to pin secure batches into the global gtt.
2116 	 * hsw should have this fixed, but bdw mucks it up again. */
2117 	if (eb->batch_flags & I915_DISPATCH_SECURE)
2118 		return i915_gem_object_ggtt_pin_ww(vma->obj, &eb->ww, NULL, 0, 0, 0);
2119 
2120 	return NULL;
2121 }
2122 
2123 static int eb_parse(struct i915_execbuffer *eb)
2124 {
2125 	struct drm_i915_private *i915 = eb->i915;
2126 	struct intel_gt_buffer_pool_node *pool = eb->batch_pool;
2127 	struct i915_vma *shadow, *trampoline, *batch;
2128 	unsigned long len;
2129 	int err;
2130 
2131 	if (!eb_use_cmdparser(eb)) {
2132 		batch = eb_dispatch_secure(eb, eb->batch->vma);
2133 		if (IS_ERR(batch))
2134 			return PTR_ERR(batch);
2135 
2136 		goto secure_batch;
2137 	}
2138 
2139 	len = eb->batch_len;
2140 	if (!CMDPARSER_USES_GGTT(eb->i915)) {
2141 		/*
2142 		 * ppGTT backed shadow buffers must be mapped RO, to prevent
2143 		 * post-scan tampering
2144 		 */
2145 		if (!eb->context->vm->has_read_only) {
2146 			drm_dbg(&i915->drm,
2147 				"Cannot prevent post-scan tampering without RO capable vm\n");
2148 			return -EINVAL;
2149 		}
2150 	} else {
2151 		len += I915_CMD_PARSER_TRAMPOLINE_SIZE;
2152 	}
2153 	if (unlikely(len < eb->batch_len)) /* last paranoid check of overflow */
2154 		return -EINVAL;
2155 
2156 	if (!pool) {
2157 		pool = intel_gt_get_buffer_pool(eb->engine->gt, len,
2158 						I915_MAP_WB);
2159 		if (IS_ERR(pool))
2160 			return PTR_ERR(pool);
2161 		eb->batch_pool = pool;
2162 	}
2163 
2164 	err = i915_gem_object_lock(pool->obj, &eb->ww);
2165 	if (err)
2166 		goto err;
2167 
2168 	shadow = shadow_batch_pin(eb, pool->obj, eb->context->vm, PIN_USER);
2169 	if (IS_ERR(shadow)) {
2170 		err = PTR_ERR(shadow);
2171 		goto err;
2172 	}
2173 	intel_gt_buffer_pool_mark_used(pool);
2174 	i915_gem_object_set_readonly(shadow->obj);
2175 	shadow->private = pool;
2176 
2177 	trampoline = NULL;
2178 	if (CMDPARSER_USES_GGTT(eb->i915)) {
2179 		trampoline = shadow;
2180 
2181 		shadow = shadow_batch_pin(eb, pool->obj,
2182 					  &eb->engine->gt->ggtt->vm,
2183 					  PIN_GLOBAL);
2184 		if (IS_ERR(shadow)) {
2185 			err = PTR_ERR(shadow);
2186 			shadow = trampoline;
2187 			goto err_shadow;
2188 		}
2189 		shadow->private = pool;
2190 
2191 		eb->batch_flags |= I915_DISPATCH_SECURE;
2192 	}
2193 
2194 	batch = eb_dispatch_secure(eb, shadow);
2195 	if (IS_ERR(batch)) {
2196 		err = PTR_ERR(batch);
2197 		goto err_trampoline;
2198 	}
2199 
2200 	err = dma_resv_reserve_shared(shadow->resv, 1);
2201 	if (err)
2202 		goto err_trampoline;
2203 
2204 	err = intel_engine_cmd_parser(eb->engine,
2205 				      eb->batch->vma,
2206 				      eb->batch_start_offset,
2207 				      eb->batch_len,
2208 				      shadow, trampoline);
2209 	if (err)
2210 		goto err_unpin_batch;
2211 
2212 	eb->batch = &eb->vma[eb->buffer_count++];
2213 	eb->batch->vma = i915_vma_get(shadow);
2214 	eb->batch->flags = __EXEC_OBJECT_HAS_PIN;
2215 
2216 	eb->trampoline = trampoline;
2217 	eb->batch_start_offset = 0;
2218 
2219 secure_batch:
2220 	if (batch) {
2221 		eb->batch = &eb->vma[eb->buffer_count++];
2222 		eb->batch->flags = __EXEC_OBJECT_HAS_PIN;
2223 		eb->batch->vma = i915_vma_get(batch);
2224 	}
2225 	return 0;
2226 
2227 err_unpin_batch:
2228 	if (batch)
2229 		i915_vma_unpin(batch);
2230 err_trampoline:
2231 	if (trampoline)
2232 		i915_vma_unpin(trampoline);
2233 err_shadow:
2234 	i915_vma_unpin(shadow);
2235 err:
2236 	return err;
2237 }
2238 
2239 static int eb_submit(struct i915_execbuffer *eb, struct i915_vma *batch)
2240 {
2241 	int err;
2242 
2243 	if (intel_context_nopreempt(eb->context))
2244 		__set_bit(I915_FENCE_FLAG_NOPREEMPT, &eb->request->fence.flags);
2245 
2246 	err = eb_move_to_gpu(eb);
2247 	if (err)
2248 		return err;
2249 
2250 	if (eb->args->flags & I915_EXEC_GEN7_SOL_RESET) {
2251 		err = i915_reset_gen7_sol_offsets(eb->request);
2252 		if (err)
2253 			return err;
2254 	}
2255 
2256 	/*
2257 	 * After we completed waiting for other engines (using HW semaphores)
2258 	 * then we can signal that this request/batch is ready to run. This
2259 	 * allows us to determine if the batch is still waiting on the GPU
2260 	 * or actually running by checking the breadcrumb.
2261 	 */
2262 	if (eb->engine->emit_init_breadcrumb) {
2263 		err = eb->engine->emit_init_breadcrumb(eb->request);
2264 		if (err)
2265 			return err;
2266 	}
2267 
2268 	err = eb->engine->emit_bb_start(eb->request,
2269 					batch->node.start +
2270 					eb->batch_start_offset,
2271 					eb->batch_len,
2272 					eb->batch_flags);
2273 	if (err)
2274 		return err;
2275 
2276 	if (eb->trampoline) {
2277 		GEM_BUG_ON(eb->batch_start_offset);
2278 		err = eb->engine->emit_bb_start(eb->request,
2279 						eb->trampoline->node.start +
2280 						eb->batch_len,
2281 						0, 0);
2282 		if (err)
2283 			return err;
2284 	}
2285 
2286 	return 0;
2287 }
2288 
2289 static int num_vcs_engines(const struct drm_i915_private *i915)
2290 {
2291 	return hweight_long(VDBOX_MASK(&i915->gt));
2292 }
2293 
2294 /*
2295  * Find one BSD ring to dispatch the corresponding BSD command.
2296  * The engine index is returned.
2297  */
2298 static unsigned int
2299 gen8_dispatch_bsd_engine(struct drm_i915_private *dev_priv,
2300 			 struct drm_file *file)
2301 {
2302 	struct drm_i915_file_private *file_priv = file->driver_priv;
2303 
2304 	/* Check whether the file_priv has already selected one ring. */
2305 	if ((int)file_priv->bsd_engine < 0)
2306 		file_priv->bsd_engine =
2307 			get_random_int() % num_vcs_engines(dev_priv);
2308 
2309 	return file_priv->bsd_engine;
2310 }
2311 
2312 static const enum intel_engine_id user_ring_map[] = {
2313 	[I915_EXEC_DEFAULT]	= RCS0,
2314 	[I915_EXEC_RENDER]	= RCS0,
2315 	[I915_EXEC_BLT]		= BCS0,
2316 	[I915_EXEC_BSD]		= VCS0,
2317 	[I915_EXEC_VEBOX]	= VECS0
2318 };
2319 
2320 static struct i915_request *eb_throttle(struct i915_execbuffer *eb, struct intel_context *ce)
2321 {
2322 	struct intel_ring *ring = ce->ring;
2323 	struct intel_timeline *tl = ce->timeline;
2324 	struct i915_request *rq;
2325 
2326 	/*
2327 	 * Completely unscientific finger-in-the-air estimates for suitable
2328 	 * maximum user request size (to avoid blocking) and then backoff.
2329 	 */
2330 	if (intel_ring_update_space(ring) >= PAGE_SIZE)
2331 		return NULL;
2332 
2333 	/*
2334 	 * Find a request that after waiting upon, there will be at least half
2335 	 * the ring available. The hysteresis allows us to compete for the
2336 	 * shared ring and should mean that we sleep less often prior to
2337 	 * claiming our resources, but not so long that the ring completely
2338 	 * drains before we can submit our next request.
2339 	 */
2340 	list_for_each_entry(rq, &tl->requests, link) {
2341 		if (rq->ring != ring)
2342 			continue;
2343 
2344 		if (__intel_ring_space(rq->postfix,
2345 				       ring->emit, ring->size) > ring->size / 2)
2346 			break;
2347 	}
2348 	if (&rq->link == &tl->requests)
2349 		return NULL; /* weird, we will check again later for real */
2350 
2351 	return i915_request_get(rq);
2352 }
2353 
2354 static struct i915_request *eb_pin_engine(struct i915_execbuffer *eb, bool throttle)
2355 {
2356 	struct intel_context *ce = eb->context;
2357 	struct intel_timeline *tl;
2358 	struct i915_request *rq = NULL;
2359 	int err;
2360 
2361 	GEM_BUG_ON(eb->args->flags & __EXEC_ENGINE_PINNED);
2362 
2363 	if (unlikely(intel_context_is_banned(ce)))
2364 		return ERR_PTR(-EIO);
2365 
2366 	/*
2367 	 * Pinning the contexts may generate requests in order to acquire
2368 	 * GGTT space, so do this first before we reserve a seqno for
2369 	 * ourselves.
2370 	 */
2371 	err = intel_context_pin_ww(ce, &eb->ww);
2372 	if (err)
2373 		return ERR_PTR(err);
2374 
2375 	/*
2376 	 * Take a local wakeref for preparing to dispatch the execbuf as
2377 	 * we expect to access the hardware fairly frequently in the
2378 	 * process, and require the engine to be kept awake between accesses.
2379 	 * Upon dispatch, we acquire another prolonged wakeref that we hold
2380 	 * until the timeline is idle, which in turn releases the wakeref
2381 	 * taken on the engine, and the parent device.
2382 	 */
2383 	tl = intel_context_timeline_lock(ce);
2384 	if (IS_ERR(tl)) {
2385 		intel_context_unpin(ce);
2386 		return ERR_CAST(tl);
2387 	}
2388 
2389 	intel_context_enter(ce);
2390 	if (throttle)
2391 		rq = eb_throttle(eb, ce);
2392 	intel_context_timeline_unlock(tl);
2393 
2394 	eb->args->flags |= __EXEC_ENGINE_PINNED;
2395 	return rq;
2396 }
2397 
2398 static void eb_unpin_engine(struct i915_execbuffer *eb)
2399 {
2400 	struct intel_context *ce = eb->context;
2401 	struct intel_timeline *tl = ce->timeline;
2402 
2403 	if (!(eb->args->flags & __EXEC_ENGINE_PINNED))
2404 		return;
2405 
2406 	eb->args->flags &= ~__EXEC_ENGINE_PINNED;
2407 
2408 	mutex_lock(&tl->mutex);
2409 	intel_context_exit(ce);
2410 	mutex_unlock(&tl->mutex);
2411 
2412 	intel_context_unpin(ce);
2413 }
2414 
2415 static unsigned int
2416 eb_select_legacy_ring(struct i915_execbuffer *eb)
2417 {
2418 	struct drm_i915_private *i915 = eb->i915;
2419 	struct drm_i915_gem_execbuffer2 *args = eb->args;
2420 	unsigned int user_ring_id = args->flags & I915_EXEC_RING_MASK;
2421 
2422 	if (user_ring_id != I915_EXEC_BSD &&
2423 	    (args->flags & I915_EXEC_BSD_MASK)) {
2424 		drm_dbg(&i915->drm,
2425 			"execbuf with non bsd ring but with invalid "
2426 			"bsd dispatch flags: %d\n", (int)(args->flags));
2427 		return -1;
2428 	}
2429 
2430 	if (user_ring_id == I915_EXEC_BSD && num_vcs_engines(i915) > 1) {
2431 		unsigned int bsd_idx = args->flags & I915_EXEC_BSD_MASK;
2432 
2433 		if (bsd_idx == I915_EXEC_BSD_DEFAULT) {
2434 			bsd_idx = gen8_dispatch_bsd_engine(i915, eb->file);
2435 		} else if (bsd_idx >= I915_EXEC_BSD_RING1 &&
2436 			   bsd_idx <= I915_EXEC_BSD_RING2) {
2437 			bsd_idx >>= I915_EXEC_BSD_SHIFT;
2438 			bsd_idx--;
2439 		} else {
2440 			drm_dbg(&i915->drm,
2441 				"execbuf with unknown bsd ring: %u\n",
2442 				bsd_idx);
2443 			return -1;
2444 		}
2445 
2446 		return _VCS(bsd_idx);
2447 	}
2448 
2449 	if (user_ring_id >= ARRAY_SIZE(user_ring_map)) {
2450 		drm_dbg(&i915->drm, "execbuf with unknown ring: %u\n",
2451 			user_ring_id);
2452 		return -1;
2453 	}
2454 
2455 	return user_ring_map[user_ring_id];
2456 }
2457 
2458 static int
2459 eb_select_engine(struct i915_execbuffer *eb)
2460 {
2461 	struct intel_context *ce;
2462 	unsigned int idx;
2463 	int err;
2464 
2465 	if (i915_gem_context_user_engines(eb->gem_context))
2466 		idx = eb->args->flags & I915_EXEC_RING_MASK;
2467 	else
2468 		idx = eb_select_legacy_ring(eb);
2469 
2470 	ce = i915_gem_context_get_engine(eb->gem_context, idx);
2471 	if (IS_ERR(ce))
2472 		return PTR_ERR(ce);
2473 
2474 	intel_gt_pm_get(ce->engine->gt);
2475 
2476 	if (!test_bit(CONTEXT_ALLOC_BIT, &ce->flags)) {
2477 		err = intel_context_alloc_state(ce);
2478 		if (err)
2479 			goto err;
2480 	}
2481 
2482 	/*
2483 	 * ABI: Before userspace accesses the GPU (e.g. execbuffer), report
2484 	 * EIO if the GPU is already wedged.
2485 	 */
2486 	err = intel_gt_terminally_wedged(ce->engine->gt);
2487 	if (err)
2488 		goto err;
2489 
2490 	eb->context = ce;
2491 	eb->engine = ce->engine;
2492 
2493 	/*
2494 	 * Make sure engine pool stays alive even if we call intel_context_put
2495 	 * during ww handling. The pool is destroyed when last pm reference
2496 	 * is dropped, which breaks our -EDEADLK handling.
2497 	 */
2498 	return err;
2499 
2500 err:
2501 	intel_gt_pm_put(ce->engine->gt);
2502 	intel_context_put(ce);
2503 	return err;
2504 }
2505 
2506 static void
2507 eb_put_engine(struct i915_execbuffer *eb)
2508 {
2509 	intel_gt_pm_put(eb->engine->gt);
2510 	intel_context_put(eb->context);
2511 }
2512 
2513 static void
2514 __free_fence_array(struct eb_fence *fences, unsigned int n)
2515 {
2516 	while (n--) {
2517 		drm_syncobj_put(ptr_mask_bits(fences[n].syncobj, 2));
2518 		dma_fence_put(fences[n].dma_fence);
2519 		dma_fence_chain_free(fences[n].chain_fence);
2520 	}
2521 	kvfree(fences);
2522 }
2523 
2524 static int
2525 add_timeline_fence_array(struct i915_execbuffer *eb,
2526 			 const struct drm_i915_gem_execbuffer_ext_timeline_fences *timeline_fences)
2527 {
2528 	struct drm_i915_gem_exec_fence __user *user_fences;
2529 	u64 __user *user_values;
2530 	struct eb_fence *f;
2531 	u64 nfences;
2532 	int err = 0;
2533 
2534 	nfences = timeline_fences->fence_count;
2535 	if (!nfences)
2536 		return 0;
2537 
2538 	/* Check multiplication overflow for access_ok() and kvmalloc_array() */
2539 	BUILD_BUG_ON(sizeof(size_t) > sizeof(unsigned long));
2540 	if (nfences > min_t(unsigned long,
2541 			    ULONG_MAX / sizeof(*user_fences),
2542 			    SIZE_MAX / sizeof(*f)) - eb->num_fences)
2543 		return -EINVAL;
2544 
2545 	user_fences = u64_to_user_ptr(timeline_fences->handles_ptr);
2546 	if (!access_ok(user_fences, nfences * sizeof(*user_fences)))
2547 		return -EFAULT;
2548 
2549 	user_values = u64_to_user_ptr(timeline_fences->values_ptr);
2550 	if (!access_ok(user_values, nfences * sizeof(*user_values)))
2551 		return -EFAULT;
2552 
2553 #ifdef __linux__
2554 	f = krealloc(eb->fences,
2555 		     (eb->num_fences + nfences) * sizeof(*f),
2556 		     __GFP_NOWARN | GFP_KERNEL);
2557 	if (!f)
2558 		return -ENOMEM;
2559 #else
2560 	f = kmalloc((eb->num_fences + nfences) * sizeof(*f),
2561 		     __GFP_NOWARN | GFP_KERNEL);
2562 	if (!f)
2563 		return -ENOMEM;
2564 	memcpy(f, eb->fences, eb->num_fences * sizeof(*f));
2565 	kfree(eb->fences);
2566 #endif
2567 
2568 	eb->fences = f;
2569 	f += eb->num_fences;
2570 
2571 #ifdef notyet
2572 	BUILD_BUG_ON(~(ARCH_KMALLOC_MINALIGN - 1) &
2573 		     ~__I915_EXEC_FENCE_UNKNOWN_FLAGS);
2574 #endif
2575 
2576 	while (nfences--) {
2577 		struct drm_i915_gem_exec_fence user_fence;
2578 		struct drm_syncobj *syncobj;
2579 		struct dma_fence *fence = NULL;
2580 		u64 point;
2581 
2582 		if (__copy_from_user(&user_fence,
2583 				     user_fences++,
2584 				     sizeof(user_fence)))
2585 			return -EFAULT;
2586 
2587 		if (user_fence.flags & __I915_EXEC_FENCE_UNKNOWN_FLAGS)
2588 			return -EINVAL;
2589 
2590 		if (__get_user(point, user_values++))
2591 			return -EFAULT;
2592 
2593 		syncobj = drm_syncobj_find(eb->file, user_fence.handle);
2594 		if (!syncobj) {
2595 			DRM_DEBUG("Invalid syncobj handle provided\n");
2596 			return -ENOENT;
2597 		}
2598 
2599 		fence = drm_syncobj_fence_get(syncobj);
2600 
2601 		if (!fence && user_fence.flags &&
2602 		    !(user_fence.flags & I915_EXEC_FENCE_SIGNAL)) {
2603 			DRM_DEBUG("Syncobj handle has no fence\n");
2604 			drm_syncobj_put(syncobj);
2605 			return -EINVAL;
2606 		}
2607 
2608 		if (fence)
2609 			err = dma_fence_chain_find_seqno(&fence, point);
2610 
2611 		if (err && !(user_fence.flags & I915_EXEC_FENCE_SIGNAL)) {
2612 			DRM_DEBUG("Syncobj handle missing requested point %llu\n", point);
2613 			dma_fence_put(fence);
2614 			drm_syncobj_put(syncobj);
2615 			return err;
2616 		}
2617 
2618 		/*
2619 		 * A point might have been signaled already and
2620 		 * garbage collected from the timeline. In this case
2621 		 * just ignore the point and carry on.
2622 		 */
2623 		if (!fence && !(user_fence.flags & I915_EXEC_FENCE_SIGNAL)) {
2624 			drm_syncobj_put(syncobj);
2625 			continue;
2626 		}
2627 
2628 		/*
2629 		 * For timeline syncobjs we need to preallocate chains for
2630 		 * later signaling.
2631 		 */
2632 		if (point != 0 && user_fence.flags & I915_EXEC_FENCE_SIGNAL) {
2633 			/*
2634 			 * Waiting and signaling the same point (when point !=
2635 			 * 0) would break the timeline.
2636 			 */
2637 			if (user_fence.flags & I915_EXEC_FENCE_WAIT) {
2638 				DRM_DEBUG("Trying to wait & signal the same timeline point.\n");
2639 				dma_fence_put(fence);
2640 				drm_syncobj_put(syncobj);
2641 				return -EINVAL;
2642 			}
2643 
2644 			f->chain_fence = dma_fence_chain_alloc();
2645 			if (!f->chain_fence) {
2646 				drm_syncobj_put(syncobj);
2647 				dma_fence_put(fence);
2648 				return -ENOMEM;
2649 			}
2650 		} else {
2651 			f->chain_fence = NULL;
2652 		}
2653 
2654 		f->syncobj = ptr_pack_bits(syncobj, user_fence.flags, 2);
2655 		f->dma_fence = fence;
2656 		f->value = point;
2657 		f++;
2658 		eb->num_fences++;
2659 	}
2660 
2661 	return 0;
2662 }
2663 
2664 static int add_fence_array(struct i915_execbuffer *eb)
2665 {
2666 	struct drm_i915_gem_execbuffer2 *args = eb->args;
2667 	struct drm_i915_gem_exec_fence __user *user;
2668 	unsigned long num_fences = args->num_cliprects;
2669 	struct eb_fence *f;
2670 
2671 	if (!(args->flags & I915_EXEC_FENCE_ARRAY))
2672 		return 0;
2673 
2674 	if (!num_fences)
2675 		return 0;
2676 
2677 	/* Check multiplication overflow for access_ok() and kvmalloc_array() */
2678 	BUILD_BUG_ON(sizeof(size_t) > sizeof(unsigned long));
2679 	if (num_fences > min_t(unsigned long,
2680 			       ULONG_MAX / sizeof(*user),
2681 			       SIZE_MAX / sizeof(*f) - eb->num_fences))
2682 		return -EINVAL;
2683 
2684 	user = u64_to_user_ptr(args->cliprects_ptr);
2685 	if (!access_ok(user, num_fences * sizeof(*user)))
2686 		return -EFAULT;
2687 
2688 #ifdef __linux__
2689 	f = krealloc(eb->fences,
2690 		     (eb->num_fences + num_fences) * sizeof(*f),
2691 		     __GFP_NOWARN | GFP_KERNEL);
2692 	if (!f)
2693 		return -ENOMEM;
2694 #else
2695 	f = kmalloc((eb->num_fences + num_fences) * sizeof(*f),
2696 		     __GFP_NOWARN | GFP_KERNEL);
2697 	if (!f)
2698 		return -ENOMEM;
2699 	memcpy(f, eb->fences, eb->num_fences * sizeof(*f));
2700 	kfree(eb->fences);
2701 #endif
2702 
2703 	eb->fences = f;
2704 	f += eb->num_fences;
2705 	while (num_fences--) {
2706 		struct drm_i915_gem_exec_fence user_fence;
2707 		struct drm_syncobj *syncobj;
2708 		struct dma_fence *fence = NULL;
2709 
2710 		if (__copy_from_user(&user_fence, user++, sizeof(user_fence)))
2711 			return -EFAULT;
2712 
2713 		if (user_fence.flags & __I915_EXEC_FENCE_UNKNOWN_FLAGS)
2714 			return -EINVAL;
2715 
2716 		syncobj = drm_syncobj_find(eb->file, user_fence.handle);
2717 		if (!syncobj) {
2718 			DRM_DEBUG("Invalid syncobj handle provided\n");
2719 			return -ENOENT;
2720 		}
2721 
2722 		if (user_fence.flags & I915_EXEC_FENCE_WAIT) {
2723 			fence = drm_syncobj_fence_get(syncobj);
2724 			if (!fence) {
2725 				DRM_DEBUG("Syncobj handle has no fence\n");
2726 				drm_syncobj_put(syncobj);
2727 				return -EINVAL;
2728 			}
2729 		}
2730 
2731 #ifdef notyet
2732 		BUILD_BUG_ON(~(ARCH_KMALLOC_MINALIGN - 1) &
2733 			     ~__I915_EXEC_FENCE_UNKNOWN_FLAGS);
2734 #endif
2735 
2736 		f->syncobj = ptr_pack_bits(syncobj, user_fence.flags, 2);
2737 		f->dma_fence = fence;
2738 		f->value = 0;
2739 		f->chain_fence = NULL;
2740 		f++;
2741 		eb->num_fences++;
2742 	}
2743 
2744 	return 0;
2745 }
2746 
2747 static void put_fence_array(struct eb_fence *fences, int num_fences)
2748 {
2749 	if (fences)
2750 		__free_fence_array(fences, num_fences);
2751 }
2752 
2753 static int
2754 await_fence_array(struct i915_execbuffer *eb)
2755 {
2756 	unsigned int n;
2757 	int err;
2758 
2759 	for (n = 0; n < eb->num_fences; n++) {
2760 		struct drm_syncobj *syncobj;
2761 		unsigned int flags;
2762 
2763 		syncobj = ptr_unpack_bits(eb->fences[n].syncobj, &flags, 2);
2764 
2765 		if (!eb->fences[n].dma_fence)
2766 			continue;
2767 
2768 		err = i915_request_await_dma_fence(eb->request,
2769 						   eb->fences[n].dma_fence);
2770 		if (err < 0)
2771 			return err;
2772 	}
2773 
2774 	return 0;
2775 }
2776 
2777 static void signal_fence_array(const struct i915_execbuffer *eb)
2778 {
2779 	struct dma_fence * const fence = &eb->request->fence;
2780 	unsigned int n;
2781 
2782 	for (n = 0; n < eb->num_fences; n++) {
2783 		struct drm_syncobj *syncobj;
2784 		unsigned int flags;
2785 
2786 		syncobj = ptr_unpack_bits(eb->fences[n].syncobj, &flags, 2);
2787 		if (!(flags & I915_EXEC_FENCE_SIGNAL))
2788 			continue;
2789 
2790 		if (eb->fences[n].chain_fence) {
2791 			drm_syncobj_add_point(syncobj,
2792 					      eb->fences[n].chain_fence,
2793 					      fence,
2794 					      eb->fences[n].value);
2795 			/*
2796 			 * The chain's ownership is transferred to the
2797 			 * timeline.
2798 			 */
2799 			eb->fences[n].chain_fence = NULL;
2800 		} else {
2801 			drm_syncobj_replace_fence(syncobj, fence);
2802 		}
2803 	}
2804 }
2805 
2806 static int
2807 parse_timeline_fences(struct i915_user_extension __user *ext, void *data)
2808 {
2809 	struct i915_execbuffer *eb = data;
2810 	struct drm_i915_gem_execbuffer_ext_timeline_fences timeline_fences;
2811 
2812 	if (copy_from_user(&timeline_fences, ext, sizeof(timeline_fences)))
2813 		return -EFAULT;
2814 
2815 	return add_timeline_fence_array(eb, &timeline_fences);
2816 }
2817 
2818 static void retire_requests(struct intel_timeline *tl, struct i915_request *end)
2819 {
2820 	struct i915_request *rq, *rn;
2821 
2822 	list_for_each_entry_safe(rq, rn, &tl->requests, link)
2823 		if (rq == end || !i915_request_retire(rq))
2824 			break;
2825 }
2826 
2827 static int eb_request_add(struct i915_execbuffer *eb, int err)
2828 {
2829 	struct i915_request *rq = eb->request;
2830 	struct intel_timeline * const tl = i915_request_timeline(rq);
2831 	struct i915_sched_attr attr = {};
2832 	struct i915_request *prev;
2833 
2834 	lockdep_assert_held(&tl->mutex);
2835 	lockdep_unpin_lock(&tl->mutex, rq->cookie);
2836 
2837 	trace_i915_request_add(rq);
2838 
2839 	prev = __i915_request_commit(rq);
2840 
2841 	/* Check that the context wasn't destroyed before submission */
2842 	if (likely(!intel_context_is_closed(eb->context))) {
2843 		attr = eb->gem_context->sched;
2844 	} else {
2845 		/* Serialise with context_close via the add_to_timeline */
2846 		i915_request_set_error_once(rq, -ENOENT);
2847 		__i915_request_skip(rq);
2848 		err = -ENOENT; /* override any transient errors */
2849 	}
2850 
2851 	__i915_request_queue(rq, &attr);
2852 
2853 	/* Try to clean up the client's timeline after submitting the request */
2854 	if (prev)
2855 		retire_requests(tl, prev);
2856 
2857 	mutex_unlock(&tl->mutex);
2858 
2859 	return err;
2860 }
2861 
2862 static const i915_user_extension_fn execbuf_extensions[] = {
2863 	[DRM_I915_GEM_EXECBUFFER_EXT_TIMELINE_FENCES] = parse_timeline_fences,
2864 };
2865 
2866 static int
2867 parse_execbuf2_extensions(struct drm_i915_gem_execbuffer2 *args,
2868 			  struct i915_execbuffer *eb)
2869 {
2870 	if (!(args->flags & I915_EXEC_USE_EXTENSIONS))
2871 		return 0;
2872 
2873 	/* The execbuf2 extension mechanism reuses cliprects_ptr. So we cannot
2874 	 * have another flag also using it at the same time.
2875 	 */
2876 	if (eb->args->flags & I915_EXEC_FENCE_ARRAY)
2877 		return -EINVAL;
2878 
2879 	if (args->num_cliprects != 0)
2880 		return -EINVAL;
2881 
2882 	return i915_user_extensions(u64_to_user_ptr(args->cliprects_ptr),
2883 				    execbuf_extensions,
2884 				    ARRAY_SIZE(execbuf_extensions),
2885 				    eb);
2886 }
2887 
2888 static int
2889 i915_gem_do_execbuffer(struct drm_device *dev,
2890 		       struct drm_file *file,
2891 		       struct drm_i915_gem_execbuffer2 *args,
2892 		       struct drm_i915_gem_exec_object2 *exec)
2893 {
2894 	struct drm_i915_private *i915 = to_i915(dev);
2895 	struct i915_execbuffer eb;
2896 	struct dma_fence *in_fence = NULL;
2897 	struct sync_file *out_fence = NULL;
2898 	struct i915_vma *batch;
2899 	int out_fence_fd = -1;
2900 	int err;
2901 
2902 	BUILD_BUG_ON(__EXEC_INTERNAL_FLAGS & ~__I915_EXEC_ILLEGAL_FLAGS);
2903 	BUILD_BUG_ON(__EXEC_OBJECT_INTERNAL_FLAGS &
2904 		     ~__EXEC_OBJECT_UNKNOWN_FLAGS);
2905 
2906 	eb.i915 = i915;
2907 	eb.file = file;
2908 	eb.args = args;
2909 	if (DBG_FORCE_RELOC || !(args->flags & I915_EXEC_NO_RELOC))
2910 		args->flags |= __EXEC_HAS_RELOC;
2911 
2912 	eb.exec = exec;
2913 	eb.vma = (struct eb_vma *)(exec + args->buffer_count + 1);
2914 	eb.vma[0].vma = NULL;
2915 	eb.batch_pool = NULL;
2916 
2917 	eb.invalid_flags = __EXEC_OBJECT_UNKNOWN_FLAGS;
2918 	reloc_cache_init(&eb.reloc_cache, eb.i915);
2919 
2920 	eb.buffer_count = args->buffer_count;
2921 	eb.batch_start_offset = args->batch_start_offset;
2922 	eb.batch_len = args->batch_len;
2923 	eb.trampoline = NULL;
2924 
2925 	eb.fences = NULL;
2926 	eb.num_fences = 0;
2927 
2928 	eb.batch_flags = 0;
2929 	if (args->flags & I915_EXEC_SECURE) {
2930 		if (GRAPHICS_VER(i915) >= 11)
2931 			return -ENODEV;
2932 
2933 		/* Return -EPERM to trigger fallback code on old binaries. */
2934 		if (!HAS_SECURE_BATCHES(i915))
2935 			return -EPERM;
2936 
2937 		if (!drm_is_current_master(file) || !capable(CAP_SYS_ADMIN))
2938 			return -EPERM;
2939 
2940 		eb.batch_flags |= I915_DISPATCH_SECURE;
2941 	}
2942 	if (args->flags & I915_EXEC_IS_PINNED)
2943 		eb.batch_flags |= I915_DISPATCH_PINNED;
2944 
2945 	err = parse_execbuf2_extensions(args, &eb);
2946 	if (err)
2947 		goto err_ext;
2948 
2949 	err = add_fence_array(&eb);
2950 	if (err)
2951 		goto err_ext;
2952 
2953 #define IN_FENCES (I915_EXEC_FENCE_IN | I915_EXEC_FENCE_SUBMIT)
2954 	if (args->flags & IN_FENCES) {
2955 		if ((args->flags & IN_FENCES) == IN_FENCES)
2956 			return -EINVAL;
2957 
2958 		in_fence = sync_file_get_fence(lower_32_bits(args->rsvd2));
2959 		if (!in_fence) {
2960 			err = -EINVAL;
2961 			goto err_ext;
2962 		}
2963 	}
2964 #undef IN_FENCES
2965 
2966 	if (args->flags & I915_EXEC_FENCE_OUT) {
2967 		out_fence_fd = get_unused_fd_flags(O_CLOEXEC);
2968 		if (out_fence_fd < 0) {
2969 			err = out_fence_fd;
2970 			goto err_in_fence;
2971 		}
2972 	}
2973 
2974 	err = eb_create(&eb);
2975 	if (err)
2976 		goto err_out_fence;
2977 
2978 	GEM_BUG_ON(!eb.lut_size);
2979 
2980 	err = eb_select_context(&eb);
2981 	if (unlikely(err))
2982 		goto err_destroy;
2983 
2984 	err = eb_select_engine(&eb);
2985 	if (unlikely(err))
2986 		goto err_context;
2987 
2988 	err = eb_lookup_vmas(&eb);
2989 	if (err) {
2990 		eb_release_vmas(&eb, true);
2991 		goto err_engine;
2992 	}
2993 
2994 	i915_gem_ww_ctx_init(&eb.ww, true);
2995 
2996 	err = eb_relocate_parse(&eb);
2997 	if (err) {
2998 		/*
2999 		 * If the user expects the execobject.offset and
3000 		 * reloc.presumed_offset to be an exact match,
3001 		 * as for using NO_RELOC, then we cannot update
3002 		 * the execobject.offset until we have completed
3003 		 * relocation.
3004 		 */
3005 		args->flags &= ~__EXEC_HAS_RELOC;
3006 		goto err_vma;
3007 	}
3008 
3009 	ww_acquire_done(&eb.ww.ctx);
3010 
3011 	batch = eb.batch->vma;
3012 
3013 	/* Allocate a request for this batch buffer nice and early. */
3014 	eb.request = i915_request_create(eb.context);
3015 	if (IS_ERR(eb.request)) {
3016 		err = PTR_ERR(eb.request);
3017 		goto err_vma;
3018 	}
3019 
3020 	if (unlikely(eb.gem_context->syncobj)) {
3021 		struct dma_fence *fence;
3022 
3023 		fence = drm_syncobj_fence_get(eb.gem_context->syncobj);
3024 		err = i915_request_await_dma_fence(eb.request, fence);
3025 		dma_fence_put(fence);
3026 		if (err)
3027 			goto err_ext;
3028 	}
3029 
3030 	if (in_fence) {
3031 		if (args->flags & I915_EXEC_FENCE_SUBMIT)
3032 			err = i915_request_await_execution(eb.request,
3033 							   in_fence);
3034 		else
3035 			err = i915_request_await_dma_fence(eb.request,
3036 							   in_fence);
3037 		if (err < 0)
3038 			goto err_request;
3039 	}
3040 
3041 	if (eb.fences) {
3042 		err = await_fence_array(&eb);
3043 		if (err)
3044 			goto err_request;
3045 	}
3046 
3047 	if (out_fence_fd != -1) {
3048 		out_fence = sync_file_create(&eb.request->fence);
3049 		if (!out_fence) {
3050 			err = -ENOMEM;
3051 			goto err_request;
3052 		}
3053 	}
3054 
3055 	/*
3056 	 * Whilst this request exists, batch_obj will be on the
3057 	 * active_list, and so will hold the active reference. Only when this
3058 	 * request is retired will the the batch_obj be moved onto the
3059 	 * inactive_list and lose its active reference. Hence we do not need
3060 	 * to explicitly hold another reference here.
3061 	 */
3062 	eb.request->batch = batch;
3063 	if (eb.batch_pool)
3064 		intel_gt_buffer_pool_mark_active(eb.batch_pool, eb.request);
3065 
3066 	trace_i915_request_queue(eb.request, eb.batch_flags);
3067 	err = eb_submit(&eb, batch);
3068 
3069 err_request:
3070 	i915_request_get(eb.request);
3071 	err = eb_request_add(&eb, err);
3072 
3073 	if (eb.fences)
3074 		signal_fence_array(&eb);
3075 
3076 	if (out_fence) {
3077 		if (err == 0) {
3078 			fd_install(out_fence_fd, out_fence->file);
3079 			args->rsvd2 &= GENMASK_ULL(31, 0); /* keep in-fence */
3080 			args->rsvd2 |= (u64)out_fence_fd << 32;
3081 			out_fence_fd = -1;
3082 		} else {
3083 			fput(out_fence->file);
3084 		}
3085 	}
3086 
3087 	if (unlikely(eb.gem_context->syncobj)) {
3088 		drm_syncobj_replace_fence(eb.gem_context->syncobj,
3089 					  &eb.request->fence);
3090 	}
3091 
3092 	i915_request_put(eb.request);
3093 
3094 err_vma:
3095 	eb_release_vmas(&eb, true);
3096 	if (eb.trampoline)
3097 		i915_vma_unpin(eb.trampoline);
3098 	WARN_ON(err == -EDEADLK);
3099 	i915_gem_ww_ctx_fini(&eb.ww);
3100 
3101 	if (eb.batch_pool)
3102 		intel_gt_buffer_pool_put(eb.batch_pool);
3103 err_engine:
3104 	eb_put_engine(&eb);
3105 err_context:
3106 	i915_gem_context_put(eb.gem_context);
3107 err_destroy:
3108 	eb_destroy(&eb);
3109 err_out_fence:
3110 	if (out_fence_fd != -1)
3111 		put_unused_fd(out_fence_fd);
3112 err_in_fence:
3113 	dma_fence_put(in_fence);
3114 err_ext:
3115 	put_fence_array(eb.fences, eb.num_fences);
3116 	return err;
3117 }
3118 
3119 static size_t eb_element_size(void)
3120 {
3121 	return sizeof(struct drm_i915_gem_exec_object2) + sizeof(struct eb_vma);
3122 }
3123 
3124 static bool check_buffer_count(size_t count)
3125 {
3126 	const size_t sz = eb_element_size();
3127 
3128 	/*
3129 	 * When using LUT_HANDLE, we impose a limit of INT_MAX for the lookup
3130 	 * array size (see eb_create()). Otherwise, we can accept an array as
3131 	 * large as can be addressed (though use large arrays at your peril)!
3132 	 */
3133 
3134 	return !(count < 1 || count > INT_MAX || count > SIZE_MAX / sz - 1);
3135 }
3136 
3137 int
3138 i915_gem_execbuffer2_ioctl(struct drm_device *dev, void *data,
3139 			   struct drm_file *file)
3140 {
3141 	struct drm_i915_private *i915 = to_i915(dev);
3142 	struct drm_i915_gem_execbuffer2 *args = data;
3143 	struct drm_i915_gem_exec_object2 *exec2_list;
3144 	const size_t count = args->buffer_count;
3145 	int err;
3146 
3147 	if (!check_buffer_count(count)) {
3148 		drm_dbg(&i915->drm, "execbuf2 with %zd buffers\n", count);
3149 		return -EINVAL;
3150 	}
3151 
3152 	err = i915_gem_check_execbuffer(args);
3153 	if (err)
3154 		return err;
3155 
3156 	/* Allocate extra slots for use by the command parser */
3157 	exec2_list = kvmalloc_array(count + 2, eb_element_size(),
3158 				    __GFP_NOWARN | GFP_KERNEL);
3159 	if (exec2_list == NULL) {
3160 		drm_dbg(&i915->drm, "Failed to allocate exec list for %zd buffers\n",
3161 			count);
3162 		return -ENOMEM;
3163 	}
3164 	if (copy_from_user(exec2_list,
3165 			   u64_to_user_ptr(args->buffers_ptr),
3166 			   sizeof(*exec2_list) * count)) {
3167 		drm_dbg(&i915->drm, "copy %zd exec entries failed\n", count);
3168 		kvfree(exec2_list);
3169 		return -EFAULT;
3170 	}
3171 
3172 	err = i915_gem_do_execbuffer(dev, file, args, exec2_list);
3173 
3174 	/*
3175 	 * Now that we have begun execution of the batchbuffer, we ignore
3176 	 * any new error after this point. Also given that we have already
3177 	 * updated the associated relocations, we try to write out the current
3178 	 * object locations irrespective of any error.
3179 	 */
3180 	if (args->flags & __EXEC_HAS_RELOC) {
3181 		struct drm_i915_gem_exec_object2 __user *user_exec_list =
3182 			u64_to_user_ptr(args->buffers_ptr);
3183 		unsigned int i;
3184 
3185 		/* Copy the new buffer offsets back to the user's exec list. */
3186 		/*
3187 		 * Note: count * sizeof(*user_exec_list) does not overflow,
3188 		 * because we checked 'count' in check_buffer_count().
3189 		 *
3190 		 * And this range already got effectively checked earlier
3191 		 * when we did the "copy_from_user()" above.
3192 		 */
3193 		if (!user_write_access_begin(user_exec_list,
3194 					     count * sizeof(*user_exec_list)))
3195 			goto end;
3196 
3197 		for (i = 0; i < args->buffer_count; i++) {
3198 			if (!(exec2_list[i].offset & UPDATE))
3199 				continue;
3200 
3201 			exec2_list[i].offset =
3202 				gen8_canonical_addr(exec2_list[i].offset & PIN_OFFSET_MASK);
3203 			unsafe_put_user(exec2_list[i].offset,
3204 					&user_exec_list[i].offset,
3205 					end_user);
3206 		}
3207 end_user:
3208 		user_write_access_end();
3209 end:;
3210 	}
3211 
3212 	args->flags &= ~__I915_EXEC_UNKNOWN_FLAGS;
3213 	kvfree(exec2_list);
3214 	return err;
3215 }
3216