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