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