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