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