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