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