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