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