make 'user_access_begin()' do 'access_ok()'
[linux-2.6-microblaze.git] / drivers / gpu / drm / i915 / i915_gem_execbuffer.c
1 /*
2  * Copyright © 2008,2010 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *    Eric Anholt <eric@anholt.net>
25  *    Chris Wilson <chris@chris-wilson.co.uk>
26  *
27  */
28
29 #include <linux/intel-iommu.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 & I915_GTT_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                                 /* Pinned must have their slot */
697                                 list_add(&vma->exec_link, &eb->unbound);
698                         else if (flags & __EXEC_OBJECT_NEEDS_MAP)
699                                 /* Map require the lowest 256MiB (aperture) */
700                                 list_add_tail(&vma->exec_link, &eb->unbound);
701                         else if (!(flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS))
702                                 /* Prioritise 4GiB region for restricted bo */
703                                 list_add(&vma->exec_link, &last);
704                         else
705                                 list_add_tail(&vma->exec_link, &last);
706                 }
707                 list_splice_tail(&last, &eb->unbound);
708
709                 switch (pass++) {
710                 case 0:
711                         break;
712
713                 case 1:
714                         /* Too fragmented, unbind everything and retry */
715                         err = i915_gem_evict_vm(eb->vm);
716                         if (err)
717                                 return err;
718                         break;
719
720                 default:
721                         return -ENOSPC;
722                 }
723         } while (1);
724 }
725
726 static unsigned int eb_batch_index(const struct i915_execbuffer *eb)
727 {
728         if (eb->args->flags & I915_EXEC_BATCH_FIRST)
729                 return 0;
730         else
731                 return eb->buffer_count - 1;
732 }
733
734 static int eb_select_context(struct i915_execbuffer *eb)
735 {
736         struct i915_gem_context *ctx;
737
738         ctx = i915_gem_context_lookup(eb->file->driver_priv, eb->args->rsvd1);
739         if (unlikely(!ctx))
740                 return -ENOENT;
741
742         eb->ctx = ctx;
743         if (ctx->ppgtt) {
744                 eb->vm = &ctx->ppgtt->vm;
745                 eb->invalid_flags |= EXEC_OBJECT_NEEDS_GTT;
746         } else {
747                 eb->vm = &eb->i915->ggtt.vm;
748         }
749
750         eb->context_flags = 0;
751         if (test_bit(UCONTEXT_NO_ZEROMAP, &ctx->user_flags))
752                 eb->context_flags |= __EXEC_OBJECT_NEEDS_BIAS;
753
754         return 0;
755 }
756
757 static int eb_lookup_vmas(struct i915_execbuffer *eb)
758 {
759         struct radix_tree_root *handles_vma = &eb->ctx->handles_vma;
760         struct drm_i915_gem_object *obj;
761         unsigned int i, batch;
762         int err;
763
764         if (unlikely(i915_gem_context_is_closed(eb->ctx)))
765                 return -ENOENT;
766
767         if (unlikely(i915_gem_context_is_banned(eb->ctx)))
768                 return -EIO;
769
770         INIT_LIST_HEAD(&eb->relocs);
771         INIT_LIST_HEAD(&eb->unbound);
772
773         batch = eb_batch_index(eb);
774
775         for (i = 0; i < eb->buffer_count; i++) {
776                 u32 handle = eb->exec[i].handle;
777                 struct i915_lut_handle *lut;
778                 struct i915_vma *vma;
779
780                 vma = radix_tree_lookup(handles_vma, handle);
781                 if (likely(vma))
782                         goto add_vma;
783
784                 obj = i915_gem_object_lookup(eb->file, handle);
785                 if (unlikely(!obj)) {
786                         err = -ENOENT;
787                         goto err_vma;
788                 }
789
790                 vma = i915_vma_instance(obj, eb->vm, NULL);
791                 if (unlikely(IS_ERR(vma))) {
792                         err = PTR_ERR(vma);
793                         goto err_obj;
794                 }
795
796                 lut = kmem_cache_alloc(eb->i915->luts, GFP_KERNEL);
797                 if (unlikely(!lut)) {
798                         err = -ENOMEM;
799                         goto err_obj;
800                 }
801
802                 err = radix_tree_insert(handles_vma, handle, vma);
803                 if (unlikely(err)) {
804                         kmem_cache_free(eb->i915->luts, lut);
805                         goto err_obj;
806                 }
807
808                 /* transfer ref to ctx */
809                 if (!vma->open_count++)
810                         i915_vma_reopen(vma);
811                 list_add(&lut->obj_link, &obj->lut_list);
812                 list_add(&lut->ctx_link, &eb->ctx->handles_list);
813                 lut->ctx = eb->ctx;
814                 lut->handle = handle;
815
816 add_vma:
817                 err = eb_add_vma(eb, i, batch, vma);
818                 if (unlikely(err))
819                         goto err_vma;
820
821                 GEM_BUG_ON(vma != eb->vma[i]);
822                 GEM_BUG_ON(vma->exec_flags != &eb->flags[i]);
823                 GEM_BUG_ON(drm_mm_node_allocated(&vma->node) &&
824                            eb_vma_misplaced(&eb->exec[i], vma, eb->flags[i]));
825         }
826
827         eb->args->flags |= __EXEC_VALIDATED;
828         return eb_reserve(eb);
829
830 err_obj:
831         i915_gem_object_put(obj);
832 err_vma:
833         eb->vma[i] = NULL;
834         return err;
835 }
836
837 static struct i915_vma *
838 eb_get_vma(const struct i915_execbuffer *eb, unsigned long handle)
839 {
840         if (eb->lut_size < 0) {
841                 if (handle >= -eb->lut_size)
842                         return NULL;
843                 return eb->vma[handle];
844         } else {
845                 struct hlist_head *head;
846                 struct i915_vma *vma;
847
848                 head = &eb->buckets[hash_32(handle, eb->lut_size)];
849                 hlist_for_each_entry(vma, head, exec_node) {
850                         if (vma->exec_handle == handle)
851                                 return vma;
852                 }
853                 return NULL;
854         }
855 }
856
857 static void eb_release_vmas(const struct i915_execbuffer *eb)
858 {
859         const unsigned int count = eb->buffer_count;
860         unsigned int i;
861
862         for (i = 0; i < count; i++) {
863                 struct i915_vma *vma = eb->vma[i];
864                 unsigned int flags = eb->flags[i];
865
866                 if (!vma)
867                         break;
868
869                 GEM_BUG_ON(vma->exec_flags != &eb->flags[i]);
870                 vma->exec_flags = NULL;
871                 eb->vma[i] = NULL;
872
873                 if (flags & __EXEC_OBJECT_HAS_PIN)
874                         __eb_unreserve_vma(vma, flags);
875
876                 if (flags & __EXEC_OBJECT_HAS_REF)
877                         i915_vma_put(vma);
878         }
879 }
880
881 static void eb_reset_vmas(const struct i915_execbuffer *eb)
882 {
883         eb_release_vmas(eb);
884         if (eb->lut_size > 0)
885                 memset(eb->buckets, 0,
886                        sizeof(struct hlist_head) << eb->lut_size);
887 }
888
889 static void eb_destroy(const struct i915_execbuffer *eb)
890 {
891         GEM_BUG_ON(eb->reloc_cache.rq);
892
893         if (eb->lut_size > 0)
894                 kfree(eb->buckets);
895 }
896
897 static inline u64
898 relocation_target(const struct drm_i915_gem_relocation_entry *reloc,
899                   const struct i915_vma *target)
900 {
901         return gen8_canonical_addr((int)reloc->delta + target->node.start);
902 }
903
904 static void reloc_cache_init(struct reloc_cache *cache,
905                              struct drm_i915_private *i915)
906 {
907         cache->page = -1;
908         cache->vaddr = 0;
909         /* Must be a variable in the struct to allow GCC to unroll. */
910         cache->gen = INTEL_GEN(i915);
911         cache->has_llc = HAS_LLC(i915);
912         cache->use_64bit_reloc = HAS_64BIT_RELOC(i915);
913         cache->has_fence = cache->gen < 4;
914         cache->needs_unfenced = INTEL_INFO(i915)->unfenced_needs_alignment;
915         cache->node.allocated = false;
916         cache->rq = NULL;
917         cache->rq_size = 0;
918 }
919
920 static inline void *unmask_page(unsigned long p)
921 {
922         return (void *)(uintptr_t)(p & PAGE_MASK);
923 }
924
925 static inline unsigned int unmask_flags(unsigned long p)
926 {
927         return p & ~PAGE_MASK;
928 }
929
930 #define KMAP 0x4 /* after CLFLUSH_FLAGS */
931
932 static inline struct i915_ggtt *cache_to_ggtt(struct reloc_cache *cache)
933 {
934         struct drm_i915_private *i915 =
935                 container_of(cache, struct i915_execbuffer, reloc_cache)->i915;
936         return &i915->ggtt;
937 }
938
939 static void reloc_gpu_flush(struct reloc_cache *cache)
940 {
941         GEM_BUG_ON(cache->rq_size >= cache->rq->batch->obj->base.size / sizeof(u32));
942         cache->rq_cmd[cache->rq_size] = MI_BATCH_BUFFER_END;
943         i915_gem_object_unpin_map(cache->rq->batch->obj);
944         i915_gem_chipset_flush(cache->rq->i915);
945
946         i915_request_add(cache->rq);
947         cache->rq = NULL;
948 }
949
950 static void reloc_cache_reset(struct reloc_cache *cache)
951 {
952         void *vaddr;
953
954         if (cache->rq)
955                 reloc_gpu_flush(cache);
956
957         if (!cache->vaddr)
958                 return;
959
960         vaddr = unmask_page(cache->vaddr);
961         if (cache->vaddr & KMAP) {
962                 if (cache->vaddr & CLFLUSH_AFTER)
963                         mb();
964
965                 kunmap_atomic(vaddr);
966                 i915_gem_obj_finish_shmem_access((struct drm_i915_gem_object *)cache->node.mm);
967         } else {
968                 wmb();
969                 io_mapping_unmap_atomic((void __iomem *)vaddr);
970                 if (cache->node.allocated) {
971                         struct i915_ggtt *ggtt = cache_to_ggtt(cache);
972
973                         ggtt->vm.clear_range(&ggtt->vm,
974                                              cache->node.start,
975                                              cache->node.size);
976                         drm_mm_remove_node(&cache->node);
977                 } else {
978                         i915_vma_unpin((struct i915_vma *)cache->node.mm);
979                 }
980         }
981
982         cache->vaddr = 0;
983         cache->page = -1;
984 }
985
986 static void *reloc_kmap(struct drm_i915_gem_object *obj,
987                         struct reloc_cache *cache,
988                         unsigned long page)
989 {
990         void *vaddr;
991
992         if (cache->vaddr) {
993                 kunmap_atomic(unmask_page(cache->vaddr));
994         } else {
995                 unsigned int flushes;
996                 int err;
997
998                 err = i915_gem_obj_prepare_shmem_write(obj, &flushes);
999                 if (err)
1000                         return ERR_PTR(err);
1001
1002                 BUILD_BUG_ON(KMAP & CLFLUSH_FLAGS);
1003                 BUILD_BUG_ON((KMAP | CLFLUSH_FLAGS) & PAGE_MASK);
1004
1005                 cache->vaddr = flushes | KMAP;
1006                 cache->node.mm = (void *)obj;
1007                 if (flushes)
1008                         mb();
1009         }
1010
1011         vaddr = kmap_atomic(i915_gem_object_get_dirty_page(obj, page));
1012         cache->vaddr = unmask_flags(cache->vaddr) | (unsigned long)vaddr;
1013         cache->page = page;
1014
1015         return vaddr;
1016 }
1017
1018 static void *reloc_iomap(struct drm_i915_gem_object *obj,
1019                          struct reloc_cache *cache,
1020                          unsigned long page)
1021 {
1022         struct i915_ggtt *ggtt = cache_to_ggtt(cache);
1023         unsigned long offset;
1024         void *vaddr;
1025
1026         if (cache->vaddr) {
1027                 io_mapping_unmap_atomic((void __force __iomem *) unmask_page(cache->vaddr));
1028         } else {
1029                 struct i915_vma *vma;
1030                 int err;
1031
1032                 if (use_cpu_reloc(cache, obj))
1033                         return NULL;
1034
1035                 err = i915_gem_object_set_to_gtt_domain(obj, true);
1036                 if (err)
1037                         return ERR_PTR(err);
1038
1039                 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
1040                                                PIN_MAPPABLE |
1041                                                PIN_NONBLOCK |
1042                                                PIN_NONFAULT);
1043                 if (IS_ERR(vma)) {
1044                         memset(&cache->node, 0, sizeof(cache->node));
1045                         err = drm_mm_insert_node_in_range
1046                                 (&ggtt->vm.mm, &cache->node,
1047                                  PAGE_SIZE, 0, I915_COLOR_UNEVICTABLE,
1048                                  0, ggtt->mappable_end,
1049                                  DRM_MM_INSERT_LOW);
1050                         if (err) /* no inactive aperture space, use cpu reloc */
1051                                 return NULL;
1052                 } else {
1053                         err = i915_vma_put_fence(vma);
1054                         if (err) {
1055                                 i915_vma_unpin(vma);
1056                                 return ERR_PTR(err);
1057                         }
1058
1059                         cache->node.start = vma->node.start;
1060                         cache->node.mm = (void *)vma;
1061                 }
1062         }
1063
1064         offset = cache->node.start;
1065         if (cache->node.allocated) {
1066                 wmb();
1067                 ggtt->vm.insert_page(&ggtt->vm,
1068                                      i915_gem_object_get_dma_address(obj, page),
1069                                      offset, I915_CACHE_NONE, 0);
1070         } else {
1071                 offset += page << PAGE_SHIFT;
1072         }
1073
1074         vaddr = (void __force *)io_mapping_map_atomic_wc(&ggtt->iomap,
1075                                                          offset);
1076         cache->page = page;
1077         cache->vaddr = (unsigned long)vaddr;
1078
1079         return vaddr;
1080 }
1081
1082 static void *reloc_vaddr(struct drm_i915_gem_object *obj,
1083                          struct reloc_cache *cache,
1084                          unsigned long page)
1085 {
1086         void *vaddr;
1087
1088         if (cache->page == page) {
1089                 vaddr = unmask_page(cache->vaddr);
1090         } else {
1091                 vaddr = NULL;
1092                 if ((cache->vaddr & KMAP) == 0)
1093                         vaddr = reloc_iomap(obj, cache, page);
1094                 if (!vaddr)
1095                         vaddr = reloc_kmap(obj, cache, page);
1096         }
1097
1098         return vaddr;
1099 }
1100
1101 static void clflush_write32(u32 *addr, u32 value, unsigned int flushes)
1102 {
1103         if (unlikely(flushes & (CLFLUSH_BEFORE | CLFLUSH_AFTER))) {
1104                 if (flushes & CLFLUSH_BEFORE) {
1105                         clflushopt(addr);
1106                         mb();
1107                 }
1108
1109                 *addr = value;
1110
1111                 /*
1112                  * Writes to the same cacheline are serialised by the CPU
1113                  * (including clflush). On the write path, we only require
1114                  * that it hits memory in an orderly fashion and place
1115                  * mb barriers at the start and end of the relocation phase
1116                  * to ensure ordering of clflush wrt to the system.
1117                  */
1118                 if (flushes & CLFLUSH_AFTER)
1119                         clflushopt(addr);
1120         } else
1121                 *addr = value;
1122 }
1123
1124 static int __reloc_gpu_alloc(struct i915_execbuffer *eb,
1125                              struct i915_vma *vma,
1126                              unsigned int len)
1127 {
1128         struct reloc_cache *cache = &eb->reloc_cache;
1129         struct drm_i915_gem_object *obj;
1130         struct i915_request *rq;
1131         struct i915_vma *batch;
1132         u32 *cmd;
1133         int err;
1134
1135         if (DBG_FORCE_RELOC == FORCE_GPU_RELOC) {
1136                 obj = vma->obj;
1137                 if (obj->cache_dirty & ~obj->cache_coherent)
1138                         i915_gem_clflush_object(obj, 0);
1139                 obj->write_domain = 0;
1140         }
1141
1142         GEM_BUG_ON(vma->obj->write_domain & I915_GEM_DOMAIN_CPU);
1143
1144         obj = i915_gem_batch_pool_get(&eb->engine->batch_pool, PAGE_SIZE);
1145         if (IS_ERR(obj))
1146                 return PTR_ERR(obj);
1147
1148         cmd = i915_gem_object_pin_map(obj,
1149                                       cache->has_llc ?
1150                                       I915_MAP_FORCE_WB :
1151                                       I915_MAP_FORCE_WC);
1152         i915_gem_object_unpin_pages(obj);
1153         if (IS_ERR(cmd))
1154                 return PTR_ERR(cmd);
1155
1156         err = i915_gem_object_set_to_wc_domain(obj, false);
1157         if (err)
1158                 goto err_unmap;
1159
1160         batch = i915_vma_instance(obj, vma->vm, NULL);
1161         if (IS_ERR(batch)) {
1162                 err = PTR_ERR(batch);
1163                 goto err_unmap;
1164         }
1165
1166         err = i915_vma_pin(batch, 0, 0, PIN_USER | PIN_NONBLOCK);
1167         if (err)
1168                 goto err_unmap;
1169
1170         rq = i915_request_alloc(eb->engine, eb->ctx);
1171         if (IS_ERR(rq)) {
1172                 err = PTR_ERR(rq);
1173                 goto err_unpin;
1174         }
1175
1176         err = i915_request_await_object(rq, vma->obj, true);
1177         if (err)
1178                 goto err_request;
1179
1180         err = eb->engine->emit_bb_start(rq,
1181                                         batch->node.start, PAGE_SIZE,
1182                                         cache->gen > 5 ? 0 : I915_DISPATCH_SECURE);
1183         if (err)
1184                 goto err_request;
1185
1186         GEM_BUG_ON(!reservation_object_test_signaled_rcu(batch->resv, true));
1187         err = i915_vma_move_to_active(batch, rq, 0);
1188         if (err)
1189                 goto skip_request;
1190
1191         err = i915_vma_move_to_active(vma, rq, EXEC_OBJECT_WRITE);
1192         if (err)
1193                 goto skip_request;
1194
1195         rq->batch = batch;
1196         i915_vma_unpin(batch);
1197
1198         cache->rq = rq;
1199         cache->rq_cmd = cmd;
1200         cache->rq_size = 0;
1201
1202         /* Return with batch mapping (cmd) still pinned */
1203         return 0;
1204
1205 skip_request:
1206         i915_request_skip(rq, err);
1207 err_request:
1208         i915_request_add(rq);
1209 err_unpin:
1210         i915_vma_unpin(batch);
1211 err_unmap:
1212         i915_gem_object_unpin_map(obj);
1213         return err;
1214 }
1215
1216 static u32 *reloc_gpu(struct i915_execbuffer *eb,
1217                       struct i915_vma *vma,
1218                       unsigned int len)
1219 {
1220         struct reloc_cache *cache = &eb->reloc_cache;
1221         u32 *cmd;
1222
1223         if (cache->rq_size > PAGE_SIZE/sizeof(u32) - (len + 1))
1224                 reloc_gpu_flush(cache);
1225
1226         if (unlikely(!cache->rq)) {
1227                 int err;
1228
1229                 /* If we need to copy for the cmdparser, we will stall anyway */
1230                 if (eb_use_cmdparser(eb))
1231                         return ERR_PTR(-EWOULDBLOCK);
1232
1233                 if (!intel_engine_can_store_dword(eb->engine))
1234                         return ERR_PTR(-ENODEV);
1235
1236                 err = __reloc_gpu_alloc(eb, vma, len);
1237                 if (unlikely(err))
1238                         return ERR_PTR(err);
1239         }
1240
1241         cmd = cache->rq_cmd + cache->rq_size;
1242         cache->rq_size += len;
1243
1244         return cmd;
1245 }
1246
1247 static u64
1248 relocate_entry(struct i915_vma *vma,
1249                const struct drm_i915_gem_relocation_entry *reloc,
1250                struct i915_execbuffer *eb,
1251                const struct i915_vma *target)
1252 {
1253         u64 offset = reloc->offset;
1254         u64 target_offset = relocation_target(reloc, target);
1255         bool wide = eb->reloc_cache.use_64bit_reloc;
1256         void *vaddr;
1257
1258         if (!eb->reloc_cache.vaddr &&
1259             (DBG_FORCE_RELOC == FORCE_GPU_RELOC ||
1260              !reservation_object_test_signaled_rcu(vma->resv, true))) {
1261                 const unsigned int gen = eb->reloc_cache.gen;
1262                 unsigned int len;
1263                 u32 *batch;
1264                 u64 addr;
1265
1266                 if (wide)
1267                         len = offset & 7 ? 8 : 5;
1268                 else if (gen >= 4)
1269                         len = 4;
1270                 else
1271                         len = 3;
1272
1273                 batch = reloc_gpu(eb, vma, len);
1274                 if (IS_ERR(batch))
1275                         goto repeat;
1276
1277                 addr = gen8_canonical_addr(vma->node.start + offset);
1278                 if (wide) {
1279                         if (offset & 7) {
1280                                 *batch++ = MI_STORE_DWORD_IMM_GEN4;
1281                                 *batch++ = lower_32_bits(addr);
1282                                 *batch++ = upper_32_bits(addr);
1283                                 *batch++ = lower_32_bits(target_offset);
1284
1285                                 addr = gen8_canonical_addr(addr + 4);
1286
1287                                 *batch++ = MI_STORE_DWORD_IMM_GEN4;
1288                                 *batch++ = lower_32_bits(addr);
1289                                 *batch++ = upper_32_bits(addr);
1290                                 *batch++ = upper_32_bits(target_offset);
1291                         } else {
1292                                 *batch++ = (MI_STORE_DWORD_IMM_GEN4 | (1 << 21)) + 1;
1293                                 *batch++ = lower_32_bits(addr);
1294                                 *batch++ = upper_32_bits(addr);
1295                                 *batch++ = lower_32_bits(target_offset);
1296                                 *batch++ = upper_32_bits(target_offset);
1297                         }
1298                 } else if (gen >= 6) {
1299                         *batch++ = MI_STORE_DWORD_IMM_GEN4;
1300                         *batch++ = 0;
1301                         *batch++ = addr;
1302                         *batch++ = target_offset;
1303                 } else if (gen >= 4) {
1304                         *batch++ = MI_STORE_DWORD_IMM_GEN4 | MI_USE_GGTT;
1305                         *batch++ = 0;
1306                         *batch++ = addr;
1307                         *batch++ = target_offset;
1308                 } else {
1309                         *batch++ = MI_STORE_DWORD_IMM | MI_MEM_VIRTUAL;
1310                         *batch++ = addr;
1311                         *batch++ = target_offset;
1312                 }
1313
1314                 goto out;
1315         }
1316
1317 repeat:
1318         vaddr = reloc_vaddr(vma->obj, &eb->reloc_cache, offset >> PAGE_SHIFT);
1319         if (IS_ERR(vaddr))
1320                 return PTR_ERR(vaddr);
1321
1322         clflush_write32(vaddr + offset_in_page(offset),
1323                         lower_32_bits(target_offset),
1324                         eb->reloc_cache.vaddr);
1325
1326         if (wide) {
1327                 offset += sizeof(u32);
1328                 target_offset >>= 32;
1329                 wide = false;
1330                 goto repeat;
1331         }
1332
1333 out:
1334         return target->node.start | UPDATE;
1335 }
1336
1337 static u64
1338 eb_relocate_entry(struct i915_execbuffer *eb,
1339                   struct i915_vma *vma,
1340                   const struct drm_i915_gem_relocation_entry *reloc)
1341 {
1342         struct i915_vma *target;
1343         int err;
1344
1345         /* we've already hold a reference to all valid objects */
1346         target = eb_get_vma(eb, reloc->target_handle);
1347         if (unlikely(!target))
1348                 return -ENOENT;
1349
1350         /* Validate that the target is in a valid r/w GPU domain */
1351         if (unlikely(reloc->write_domain & (reloc->write_domain - 1))) {
1352                 DRM_DEBUG("reloc with multiple write domains: "
1353                           "target %d offset %d "
1354                           "read %08x write %08x",
1355                           reloc->target_handle,
1356                           (int) reloc->offset,
1357                           reloc->read_domains,
1358                           reloc->write_domain);
1359                 return -EINVAL;
1360         }
1361         if (unlikely((reloc->write_domain | reloc->read_domains)
1362                      & ~I915_GEM_GPU_DOMAINS)) {
1363                 DRM_DEBUG("reloc with read/write non-GPU domains: "
1364                           "target %d offset %d "
1365                           "read %08x write %08x",
1366                           reloc->target_handle,
1367                           (int) reloc->offset,
1368                           reloc->read_domains,
1369                           reloc->write_domain);
1370                 return -EINVAL;
1371         }
1372
1373         if (reloc->write_domain) {
1374                 *target->exec_flags |= EXEC_OBJECT_WRITE;
1375
1376                 /*
1377                  * Sandybridge PPGTT errata: We need a global gtt mapping
1378                  * for MI and pipe_control writes because the gpu doesn't
1379                  * properly redirect them through the ppgtt for non_secure
1380                  * batchbuffers.
1381                  */
1382                 if (reloc->write_domain == I915_GEM_DOMAIN_INSTRUCTION &&
1383                     IS_GEN6(eb->i915)) {
1384                         err = i915_vma_bind(target, target->obj->cache_level,
1385                                             PIN_GLOBAL);
1386                         if (WARN_ONCE(err,
1387                                       "Unexpected failure to bind target VMA!"))
1388                                 return err;
1389                 }
1390         }
1391
1392         /*
1393          * If the relocation already has the right value in it, no
1394          * more work needs to be done.
1395          */
1396         if (!DBG_FORCE_RELOC &&
1397             gen8_canonical_addr(target->node.start) == reloc->presumed_offset)
1398                 return 0;
1399
1400         /* Check that the relocation address is valid... */
1401         if (unlikely(reloc->offset >
1402                      vma->size - (eb->reloc_cache.use_64bit_reloc ? 8 : 4))) {
1403                 DRM_DEBUG("Relocation beyond object bounds: "
1404                           "target %d offset %d size %d.\n",
1405                           reloc->target_handle,
1406                           (int)reloc->offset,
1407                           (int)vma->size);
1408                 return -EINVAL;
1409         }
1410         if (unlikely(reloc->offset & 3)) {
1411                 DRM_DEBUG("Relocation not 4-byte aligned: "
1412                           "target %d offset %d.\n",
1413                           reloc->target_handle,
1414                           (int)reloc->offset);
1415                 return -EINVAL;
1416         }
1417
1418         /*
1419          * If we write into the object, we need to force the synchronisation
1420          * barrier, either with an asynchronous clflush or if we executed the
1421          * patching using the GPU (though that should be serialised by the
1422          * timeline). To be completely sure, and since we are required to
1423          * do relocations we are already stalling, disable the user's opt
1424          * out of our synchronisation.
1425          */
1426         *vma->exec_flags &= ~EXEC_OBJECT_ASYNC;
1427
1428         /* and update the user's relocation entry */
1429         return relocate_entry(vma, reloc, eb, target);
1430 }
1431
1432 static int eb_relocate_vma(struct i915_execbuffer *eb, struct i915_vma *vma)
1433 {
1434 #define N_RELOC(x) ((x) / sizeof(struct drm_i915_gem_relocation_entry))
1435         struct drm_i915_gem_relocation_entry stack[N_RELOC(512)];
1436         struct drm_i915_gem_relocation_entry __user *urelocs;
1437         const struct drm_i915_gem_exec_object2 *entry = exec_entry(eb, vma);
1438         unsigned int remain;
1439
1440         urelocs = u64_to_user_ptr(entry->relocs_ptr);
1441         remain = entry->relocation_count;
1442         if (unlikely(remain > N_RELOC(ULONG_MAX)))
1443                 return -EINVAL;
1444
1445         /*
1446          * We must check that the entire relocation array is safe
1447          * to read. However, if the array is not writable the user loses
1448          * the updated relocation values.
1449          */
1450         if (unlikely(!access_ok(urelocs, remain*sizeof(*urelocs))))
1451                 return -EFAULT;
1452
1453         do {
1454                 struct drm_i915_gem_relocation_entry *r = stack;
1455                 unsigned int count =
1456                         min_t(unsigned int, remain, ARRAY_SIZE(stack));
1457                 unsigned int copied;
1458
1459                 /*
1460                  * This is the fast path and we cannot handle a pagefault
1461                  * whilst holding the struct mutex lest the user pass in the
1462                  * relocations contained within a mmaped bo. For in such a case
1463                  * we, the page fault handler would call i915_gem_fault() and
1464                  * we would try to acquire the struct mutex again. Obviously
1465                  * this is bad and so lockdep complains vehemently.
1466                  */
1467                 pagefault_disable();
1468                 copied = __copy_from_user_inatomic(r, urelocs, count * sizeof(r[0]));
1469                 pagefault_enable();
1470                 if (unlikely(copied)) {
1471                         remain = -EFAULT;
1472                         goto out;
1473                 }
1474
1475                 remain -= count;
1476                 do {
1477                         u64 offset = eb_relocate_entry(eb, vma, r);
1478
1479                         if (likely(offset == 0)) {
1480                         } else if ((s64)offset < 0) {
1481                                 remain = (int)offset;
1482                                 goto out;
1483                         } else {
1484                                 /*
1485                                  * Note that reporting an error now
1486                                  * leaves everything in an inconsistent
1487                                  * state as we have *already* changed
1488                                  * the relocation value inside the
1489                                  * object. As we have not changed the
1490                                  * reloc.presumed_offset or will not
1491                                  * change the execobject.offset, on the
1492                                  * call we may not rewrite the value
1493                                  * inside the object, leaving it
1494                                  * dangling and causing a GPU hang. Unless
1495                                  * userspace dynamically rebuilds the
1496                                  * relocations on each execbuf rather than
1497                                  * presume a static tree.
1498                                  *
1499                                  * We did previously check if the relocations
1500                                  * were writable (access_ok), an error now
1501                                  * would be a strange race with mprotect,
1502                                  * having already demonstrated that we
1503                                  * can read from this userspace address.
1504                                  */
1505                                 offset = gen8_canonical_addr(offset & ~UPDATE);
1506                                 if (unlikely(__put_user(offset, &urelocs[r-stack].presumed_offset))) {
1507                                         remain = -EFAULT;
1508                                         goto out;
1509                                 }
1510                         }
1511                 } while (r++, --count);
1512                 urelocs += ARRAY_SIZE(stack);
1513         } while (remain);
1514 out:
1515         reloc_cache_reset(&eb->reloc_cache);
1516         return remain;
1517 }
1518
1519 static int
1520 eb_relocate_vma_slow(struct i915_execbuffer *eb, struct i915_vma *vma)
1521 {
1522         const struct drm_i915_gem_exec_object2 *entry = exec_entry(eb, vma);
1523         struct drm_i915_gem_relocation_entry *relocs =
1524                 u64_to_ptr(typeof(*relocs), entry->relocs_ptr);
1525         unsigned int i;
1526         int err;
1527
1528         for (i = 0; i < entry->relocation_count; i++) {
1529                 u64 offset = eb_relocate_entry(eb, vma, &relocs[i]);
1530
1531                 if ((s64)offset < 0) {
1532                         err = (int)offset;
1533                         goto err;
1534                 }
1535         }
1536         err = 0;
1537 err:
1538         reloc_cache_reset(&eb->reloc_cache);
1539         return err;
1540 }
1541
1542 static int check_relocations(const struct drm_i915_gem_exec_object2 *entry)
1543 {
1544         const char __user *addr, *end;
1545         unsigned long size;
1546         char __maybe_unused c;
1547
1548         size = entry->relocation_count;
1549         if (size == 0)
1550                 return 0;
1551
1552         if (size > N_RELOC(ULONG_MAX))
1553                 return -EINVAL;
1554
1555         addr = u64_to_user_ptr(entry->relocs_ptr);
1556         size *= sizeof(struct drm_i915_gem_relocation_entry);
1557         if (!access_ok(addr, size))
1558                 return -EFAULT;
1559
1560         end = addr + size;
1561         for (; addr < end; addr += PAGE_SIZE) {
1562                 int err = __get_user(c, addr);
1563                 if (err)
1564                         return err;
1565         }
1566         return __get_user(c, end - 1);
1567 }
1568
1569 static int eb_copy_relocations(const struct i915_execbuffer *eb)
1570 {
1571         const unsigned int count = eb->buffer_count;
1572         unsigned int i;
1573         int err;
1574
1575         for (i = 0; i < count; i++) {
1576                 const unsigned int nreloc = eb->exec[i].relocation_count;
1577                 struct drm_i915_gem_relocation_entry __user *urelocs;
1578                 struct drm_i915_gem_relocation_entry *relocs;
1579                 unsigned long size;
1580                 unsigned long copied;
1581
1582                 if (nreloc == 0)
1583                         continue;
1584
1585                 err = check_relocations(&eb->exec[i]);
1586                 if (err)
1587                         goto err;
1588
1589                 urelocs = u64_to_user_ptr(eb->exec[i].relocs_ptr);
1590                 size = nreloc * sizeof(*relocs);
1591
1592                 relocs = kvmalloc_array(size, 1, GFP_KERNEL);
1593                 if (!relocs) {
1594                         err = -ENOMEM;
1595                         goto err;
1596                 }
1597
1598                 /* copy_from_user is limited to < 4GiB */
1599                 copied = 0;
1600                 do {
1601                         unsigned int len =
1602                                 min_t(u64, BIT_ULL(31), size - copied);
1603
1604                         if (__copy_from_user((char *)relocs + copied,
1605                                              (char __user *)urelocs + copied,
1606                                              len)) {
1607 end_user:
1608                                 user_access_end();
1609                                 kvfree(relocs);
1610                                 err = -EFAULT;
1611                                 goto err;
1612                         }
1613
1614                         copied += len;
1615                 } while (copied < size);
1616
1617                 /*
1618                  * As we do not update the known relocation offsets after
1619                  * relocating (due to the complexities in lock handling),
1620                  * we need to mark them as invalid now so that we force the
1621                  * relocation processing next time. Just in case the target
1622                  * object is evicted and then rebound into its old
1623                  * presumed_offset before the next execbuffer - if that
1624                  * happened we would make the mistake of assuming that the
1625                  * relocations were valid.
1626                  */
1627                 if (!user_access_begin(urelocs, size))
1628                         goto end_user;
1629
1630                 for (copied = 0; copied < nreloc; copied++)
1631                         unsafe_put_user(-1,
1632                                         &urelocs[copied].presumed_offset,
1633                                         end_user);
1634                 user_access_end();
1635
1636                 eb->exec[i].relocs_ptr = (uintptr_t)relocs;
1637         }
1638
1639         return 0;
1640
1641 err:
1642         while (i--) {
1643                 struct drm_i915_gem_relocation_entry *relocs =
1644                         u64_to_ptr(typeof(*relocs), eb->exec[i].relocs_ptr);
1645                 if (eb->exec[i].relocation_count)
1646                         kvfree(relocs);
1647         }
1648         return err;
1649 }
1650
1651 static int eb_prefault_relocations(const struct i915_execbuffer *eb)
1652 {
1653         const unsigned int count = eb->buffer_count;
1654         unsigned int i;
1655
1656         if (unlikely(i915_modparams.prefault_disable))
1657                 return 0;
1658
1659         for (i = 0; i < count; i++) {
1660                 int err;
1661
1662                 err = check_relocations(&eb->exec[i]);
1663                 if (err)
1664                         return err;
1665         }
1666
1667         return 0;
1668 }
1669
1670 static noinline int eb_relocate_slow(struct i915_execbuffer *eb)
1671 {
1672         struct drm_device *dev = &eb->i915->drm;
1673         bool have_copy = false;
1674         struct i915_vma *vma;
1675         int err = 0;
1676
1677 repeat:
1678         if (signal_pending(current)) {
1679                 err = -ERESTARTSYS;
1680                 goto out;
1681         }
1682
1683         /* We may process another execbuffer during the unlock... */
1684         eb_reset_vmas(eb);
1685         mutex_unlock(&dev->struct_mutex);
1686
1687         /*
1688          * We take 3 passes through the slowpatch.
1689          *
1690          * 1 - we try to just prefault all the user relocation entries and
1691          * then attempt to reuse the atomic pagefault disabled fast path again.
1692          *
1693          * 2 - we copy the user entries to a local buffer here outside of the
1694          * local and allow ourselves to wait upon any rendering before
1695          * relocations
1696          *
1697          * 3 - we already have a local copy of the relocation entries, but
1698          * were interrupted (EAGAIN) whilst waiting for the objects, try again.
1699          */
1700         if (!err) {
1701                 err = eb_prefault_relocations(eb);
1702         } else if (!have_copy) {
1703                 err = eb_copy_relocations(eb);
1704                 have_copy = err == 0;
1705         } else {
1706                 cond_resched();
1707                 err = 0;
1708         }
1709         if (err) {
1710                 mutex_lock(&dev->struct_mutex);
1711                 goto out;
1712         }
1713
1714         /* A frequent cause for EAGAIN are currently unavailable client pages */
1715         flush_workqueue(eb->i915->mm.userptr_wq);
1716
1717         err = i915_mutex_lock_interruptible(dev);
1718         if (err) {
1719                 mutex_lock(&dev->struct_mutex);
1720                 goto out;
1721         }
1722
1723         /* reacquire the objects */
1724         err = eb_lookup_vmas(eb);
1725         if (err)
1726                 goto err;
1727
1728         GEM_BUG_ON(!eb->batch);
1729
1730         list_for_each_entry(vma, &eb->relocs, reloc_link) {
1731                 if (!have_copy) {
1732                         pagefault_disable();
1733                         err = eb_relocate_vma(eb, vma);
1734                         pagefault_enable();
1735                         if (err)
1736                                 goto repeat;
1737                 } else {
1738                         err = eb_relocate_vma_slow(eb, vma);
1739                         if (err)
1740                                 goto err;
1741                 }
1742         }
1743
1744         /*
1745          * Leave the user relocations as are, this is the painfully slow path,
1746          * and we want to avoid the complication of dropping the lock whilst
1747          * having buffers reserved in the aperture and so causing spurious
1748          * ENOSPC for random operations.
1749          */
1750
1751 err:
1752         if (err == -EAGAIN)
1753                 goto repeat;
1754
1755 out:
1756         if (have_copy) {
1757                 const unsigned int count = eb->buffer_count;
1758                 unsigned int i;
1759
1760                 for (i = 0; i < count; i++) {
1761                         const struct drm_i915_gem_exec_object2 *entry =
1762                                 &eb->exec[i];
1763                         struct drm_i915_gem_relocation_entry *relocs;
1764
1765                         if (!entry->relocation_count)
1766                                 continue;
1767
1768                         relocs = u64_to_ptr(typeof(*relocs), entry->relocs_ptr);
1769                         kvfree(relocs);
1770                 }
1771         }
1772
1773         return err;
1774 }
1775
1776 static int eb_relocate(struct i915_execbuffer *eb)
1777 {
1778         if (eb_lookup_vmas(eb))
1779                 goto slow;
1780
1781         /* The objects are in their final locations, apply the relocations. */
1782         if (eb->args->flags & __EXEC_HAS_RELOC) {
1783                 struct i915_vma *vma;
1784
1785                 list_for_each_entry(vma, &eb->relocs, reloc_link) {
1786                         if (eb_relocate_vma(eb, vma))
1787                                 goto slow;
1788                 }
1789         }
1790
1791         return 0;
1792
1793 slow:
1794         return eb_relocate_slow(eb);
1795 }
1796
1797 static int eb_move_to_gpu(struct i915_execbuffer *eb)
1798 {
1799         const unsigned int count = eb->buffer_count;
1800         unsigned int i;
1801         int err;
1802
1803         for (i = 0; i < count; i++) {
1804                 unsigned int flags = eb->flags[i];
1805                 struct i915_vma *vma = eb->vma[i];
1806                 struct drm_i915_gem_object *obj = vma->obj;
1807
1808                 if (flags & EXEC_OBJECT_CAPTURE) {
1809                         struct i915_capture_list *capture;
1810
1811                         capture = kmalloc(sizeof(*capture), GFP_KERNEL);
1812                         if (unlikely(!capture))
1813                                 return -ENOMEM;
1814
1815                         capture->next = eb->request->capture_list;
1816                         capture->vma = eb->vma[i];
1817                         eb->request->capture_list = capture;
1818                 }
1819
1820                 /*
1821                  * If the GPU is not _reading_ through the CPU cache, we need
1822                  * to make sure that any writes (both previous GPU writes from
1823                  * before a change in snooping levels and normal CPU writes)
1824                  * caught in that cache are flushed to main memory.
1825                  *
1826                  * We want to say
1827                  *   obj->cache_dirty &&
1828                  *   !(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ)
1829                  * but gcc's optimiser doesn't handle that as well and emits
1830                  * two jumps instead of one. Maybe one day...
1831                  */
1832                 if (unlikely(obj->cache_dirty & ~obj->cache_coherent)) {
1833                         if (i915_gem_clflush_object(obj, 0))
1834                                 flags &= ~EXEC_OBJECT_ASYNC;
1835                 }
1836
1837                 if (flags & EXEC_OBJECT_ASYNC)
1838                         continue;
1839
1840                 err = i915_request_await_object
1841                         (eb->request, obj, flags & EXEC_OBJECT_WRITE);
1842                 if (err)
1843                         return err;
1844         }
1845
1846         for (i = 0; i < count; i++) {
1847                 unsigned int flags = eb->flags[i];
1848                 struct i915_vma *vma = eb->vma[i];
1849
1850                 err = i915_vma_move_to_active(vma, eb->request, flags);
1851                 if (unlikely(err)) {
1852                         i915_request_skip(eb->request, err);
1853                         return err;
1854                 }
1855
1856                 __eb_unreserve_vma(vma, flags);
1857                 vma->exec_flags = NULL;
1858
1859                 if (unlikely(flags & __EXEC_OBJECT_HAS_REF))
1860                         i915_vma_put(vma);
1861         }
1862         eb->exec = NULL;
1863
1864         /* Unconditionally flush any chipset caches (for streaming writes). */
1865         i915_gem_chipset_flush(eb->i915);
1866
1867         return 0;
1868 }
1869
1870 static bool i915_gem_check_execbuffer(struct drm_i915_gem_execbuffer2 *exec)
1871 {
1872         if (exec->flags & __I915_EXEC_ILLEGAL_FLAGS)
1873                 return false;
1874
1875         /* Kernel clipping was a DRI1 misfeature */
1876         if (!(exec->flags & I915_EXEC_FENCE_ARRAY)) {
1877                 if (exec->num_cliprects || exec->cliprects_ptr)
1878                         return false;
1879         }
1880
1881         if (exec->DR4 == 0xffffffff) {
1882                 DRM_DEBUG("UXA submitting garbage DR4, fixing up\n");
1883                 exec->DR4 = 0;
1884         }
1885         if (exec->DR1 || exec->DR4)
1886                 return false;
1887
1888         if ((exec->batch_start_offset | exec->batch_len) & 0x7)
1889                 return false;
1890
1891         return true;
1892 }
1893
1894 static int i915_reset_gen7_sol_offsets(struct i915_request *rq)
1895 {
1896         u32 *cs;
1897         int i;
1898
1899         if (!IS_GEN7(rq->i915) || rq->engine->id != RCS) {
1900                 DRM_DEBUG("sol reset is gen7/rcs only\n");
1901                 return -EINVAL;
1902         }
1903
1904         cs = intel_ring_begin(rq, 4 * 2 + 2);
1905         if (IS_ERR(cs))
1906                 return PTR_ERR(cs);
1907
1908         *cs++ = MI_LOAD_REGISTER_IMM(4);
1909         for (i = 0; i < 4; i++) {
1910                 *cs++ = i915_mmio_reg_offset(GEN7_SO_WRITE_OFFSET(i));
1911                 *cs++ = 0;
1912         }
1913         *cs++ = MI_NOOP;
1914         intel_ring_advance(rq, cs);
1915
1916         return 0;
1917 }
1918
1919 static struct i915_vma *eb_parse(struct i915_execbuffer *eb, bool is_master)
1920 {
1921         struct drm_i915_gem_object *shadow_batch_obj;
1922         struct i915_vma *vma;
1923         int err;
1924
1925         shadow_batch_obj = i915_gem_batch_pool_get(&eb->engine->batch_pool,
1926                                                    PAGE_ALIGN(eb->batch_len));
1927         if (IS_ERR(shadow_batch_obj))
1928                 return ERR_CAST(shadow_batch_obj);
1929
1930         err = intel_engine_cmd_parser(eb->engine,
1931                                       eb->batch->obj,
1932                                       shadow_batch_obj,
1933                                       eb->batch_start_offset,
1934                                       eb->batch_len,
1935                                       is_master);
1936         if (err) {
1937                 if (err == -EACCES) /* unhandled chained batch */
1938                         vma = NULL;
1939                 else
1940                         vma = ERR_PTR(err);
1941                 goto out;
1942         }
1943
1944         vma = i915_gem_object_ggtt_pin(shadow_batch_obj, NULL, 0, 0, 0);
1945         if (IS_ERR(vma))
1946                 goto out;
1947
1948         eb->vma[eb->buffer_count] = i915_vma_get(vma);
1949         eb->flags[eb->buffer_count] =
1950                 __EXEC_OBJECT_HAS_PIN | __EXEC_OBJECT_HAS_REF;
1951         vma->exec_flags = &eb->flags[eb->buffer_count];
1952         eb->buffer_count++;
1953
1954 out:
1955         i915_gem_object_unpin_pages(shadow_batch_obj);
1956         return vma;
1957 }
1958
1959 static void
1960 add_to_client(struct i915_request *rq, struct drm_file *file)
1961 {
1962         rq->file_priv = file->driver_priv;
1963         list_add_tail(&rq->client_link, &rq->file_priv->mm.request_list);
1964 }
1965
1966 static int eb_submit(struct i915_execbuffer *eb)
1967 {
1968         int err;
1969
1970         err = eb_move_to_gpu(eb);
1971         if (err)
1972                 return err;
1973
1974         if (eb->args->flags & I915_EXEC_GEN7_SOL_RESET) {
1975                 err = i915_reset_gen7_sol_offsets(eb->request);
1976                 if (err)
1977                         return err;
1978         }
1979
1980         err = eb->engine->emit_bb_start(eb->request,
1981                                         eb->batch->node.start +
1982                                         eb->batch_start_offset,
1983                                         eb->batch_len,
1984                                         eb->batch_flags);
1985         if (err)
1986                 return err;
1987
1988         return 0;
1989 }
1990
1991 /*
1992  * Find one BSD ring to dispatch the corresponding BSD command.
1993  * The engine index is returned.
1994  */
1995 static unsigned int
1996 gen8_dispatch_bsd_engine(struct drm_i915_private *dev_priv,
1997                          struct drm_file *file)
1998 {
1999         struct drm_i915_file_private *file_priv = file->driver_priv;
2000
2001         /* Check whether the file_priv has already selected one ring. */
2002         if ((int)file_priv->bsd_engine < 0)
2003                 file_priv->bsd_engine = atomic_fetch_xor(1,
2004                          &dev_priv->mm.bsd_engine_dispatch_index);
2005
2006         return file_priv->bsd_engine;
2007 }
2008
2009 #define I915_USER_RINGS (4)
2010
2011 static const enum intel_engine_id user_ring_map[I915_USER_RINGS + 1] = {
2012         [I915_EXEC_DEFAULT]     = RCS,
2013         [I915_EXEC_RENDER]      = RCS,
2014         [I915_EXEC_BLT]         = BCS,
2015         [I915_EXEC_BSD]         = VCS,
2016         [I915_EXEC_VEBOX]       = VECS
2017 };
2018
2019 static struct intel_engine_cs *
2020 eb_select_engine(struct drm_i915_private *dev_priv,
2021                  struct drm_file *file,
2022                  struct drm_i915_gem_execbuffer2 *args)
2023 {
2024         unsigned int user_ring_id = args->flags & I915_EXEC_RING_MASK;
2025         struct intel_engine_cs *engine;
2026
2027         if (user_ring_id > I915_USER_RINGS) {
2028                 DRM_DEBUG("execbuf with unknown ring: %u\n", user_ring_id);
2029                 return NULL;
2030         }
2031
2032         if ((user_ring_id != I915_EXEC_BSD) &&
2033             ((args->flags & I915_EXEC_BSD_MASK) != 0)) {
2034                 DRM_DEBUG("execbuf with non bsd ring but with invalid "
2035                           "bsd dispatch flags: %d\n", (int)(args->flags));
2036                 return NULL;
2037         }
2038
2039         if (user_ring_id == I915_EXEC_BSD && HAS_BSD2(dev_priv)) {
2040                 unsigned int bsd_idx = args->flags & I915_EXEC_BSD_MASK;
2041
2042                 if (bsd_idx == I915_EXEC_BSD_DEFAULT) {
2043                         bsd_idx = gen8_dispatch_bsd_engine(dev_priv, file);
2044                 } else if (bsd_idx >= I915_EXEC_BSD_RING1 &&
2045                            bsd_idx <= I915_EXEC_BSD_RING2) {
2046                         bsd_idx >>= I915_EXEC_BSD_SHIFT;
2047                         bsd_idx--;
2048                 } else {
2049                         DRM_DEBUG("execbuf with unknown bsd ring: %u\n",
2050                                   bsd_idx);
2051                         return NULL;
2052                 }
2053
2054                 engine = dev_priv->engine[_VCS(bsd_idx)];
2055         } else {
2056                 engine = dev_priv->engine[user_ring_map[user_ring_id]];
2057         }
2058
2059         if (!engine) {
2060                 DRM_DEBUG("execbuf with invalid ring: %u\n", user_ring_id);
2061                 return NULL;
2062         }
2063
2064         return engine;
2065 }
2066
2067 static void
2068 __free_fence_array(struct drm_syncobj **fences, unsigned int n)
2069 {
2070         while (n--)
2071                 drm_syncobj_put(ptr_mask_bits(fences[n], 2));
2072         kvfree(fences);
2073 }
2074
2075 static struct drm_syncobj **
2076 get_fence_array(struct drm_i915_gem_execbuffer2 *args,
2077                 struct drm_file *file)
2078 {
2079         const unsigned long nfences = args->num_cliprects;
2080         struct drm_i915_gem_exec_fence __user *user;
2081         struct drm_syncobj **fences;
2082         unsigned long n;
2083         int err;
2084
2085         if (!(args->flags & I915_EXEC_FENCE_ARRAY))
2086                 return NULL;
2087
2088         /* Check multiplication overflow for access_ok() and kvmalloc_array() */
2089         BUILD_BUG_ON(sizeof(size_t) > sizeof(unsigned long));
2090         if (nfences > min_t(unsigned long,
2091                             ULONG_MAX / sizeof(*user),
2092                             SIZE_MAX / sizeof(*fences)))
2093                 return ERR_PTR(-EINVAL);
2094
2095         user = u64_to_user_ptr(args->cliprects_ptr);
2096         if (!access_ok(user, nfences * sizeof(*user)))
2097                 return ERR_PTR(-EFAULT);
2098
2099         fences = kvmalloc_array(nfences, sizeof(*fences),
2100                                 __GFP_NOWARN | GFP_KERNEL);
2101         if (!fences)
2102                 return ERR_PTR(-ENOMEM);
2103
2104         for (n = 0; n < nfences; n++) {
2105                 struct drm_i915_gem_exec_fence fence;
2106                 struct drm_syncobj *syncobj;
2107
2108                 if (__copy_from_user(&fence, user++, sizeof(fence))) {
2109                         err = -EFAULT;
2110                         goto err;
2111                 }
2112
2113                 if (fence.flags & __I915_EXEC_FENCE_UNKNOWN_FLAGS) {
2114                         err = -EINVAL;
2115                         goto err;
2116                 }
2117
2118                 syncobj = drm_syncobj_find(file, fence.handle);
2119                 if (!syncobj) {
2120                         DRM_DEBUG("Invalid syncobj handle provided\n");
2121                         err = -ENOENT;
2122                         goto err;
2123                 }
2124
2125                 BUILD_BUG_ON(~(ARCH_KMALLOC_MINALIGN - 1) &
2126                              ~__I915_EXEC_FENCE_UNKNOWN_FLAGS);
2127
2128                 fences[n] = ptr_pack_bits(syncobj, fence.flags, 2);
2129         }
2130
2131         return fences;
2132
2133 err:
2134         __free_fence_array(fences, n);
2135         return ERR_PTR(err);
2136 }
2137
2138 static void
2139 put_fence_array(struct drm_i915_gem_execbuffer2 *args,
2140                 struct drm_syncobj **fences)
2141 {
2142         if (fences)
2143                 __free_fence_array(fences, args->num_cliprects);
2144 }
2145
2146 static int
2147 await_fence_array(struct i915_execbuffer *eb,
2148                   struct drm_syncobj **fences)
2149 {
2150         const unsigned int nfences = eb->args->num_cliprects;
2151         unsigned int n;
2152         int err;
2153
2154         for (n = 0; n < nfences; n++) {
2155                 struct drm_syncobj *syncobj;
2156                 struct dma_fence *fence;
2157                 unsigned int flags;
2158
2159                 syncobj = ptr_unpack_bits(fences[n], &flags, 2);
2160                 if (!(flags & I915_EXEC_FENCE_WAIT))
2161                         continue;
2162
2163                 fence = drm_syncobj_fence_get(syncobj);
2164                 if (!fence)
2165                         return -EINVAL;
2166
2167                 err = i915_request_await_dma_fence(eb->request, fence);
2168                 dma_fence_put(fence);
2169                 if (err < 0)
2170                         return err;
2171         }
2172
2173         return 0;
2174 }
2175
2176 static void
2177 signal_fence_array(struct i915_execbuffer *eb,
2178                    struct drm_syncobj **fences)
2179 {
2180         const unsigned int nfences = eb->args->num_cliprects;
2181         struct dma_fence * const fence = &eb->request->fence;
2182         unsigned int n;
2183
2184         for (n = 0; n < nfences; n++) {
2185                 struct drm_syncobj *syncobj;
2186                 unsigned int flags;
2187
2188                 syncobj = ptr_unpack_bits(fences[n], &flags, 2);
2189                 if (!(flags & I915_EXEC_FENCE_SIGNAL))
2190                         continue;
2191
2192                 drm_syncobj_replace_fence(syncobj, fence);
2193         }
2194 }
2195
2196 static int
2197 i915_gem_do_execbuffer(struct drm_device *dev,
2198                        struct drm_file *file,
2199                        struct drm_i915_gem_execbuffer2 *args,
2200                        struct drm_i915_gem_exec_object2 *exec,
2201                        struct drm_syncobj **fences)
2202 {
2203         struct i915_execbuffer eb;
2204         struct dma_fence *in_fence = NULL;
2205         struct sync_file *out_fence = NULL;
2206         int out_fence_fd = -1;
2207         int err;
2208
2209         BUILD_BUG_ON(__EXEC_INTERNAL_FLAGS & ~__I915_EXEC_ILLEGAL_FLAGS);
2210         BUILD_BUG_ON(__EXEC_OBJECT_INTERNAL_FLAGS &
2211                      ~__EXEC_OBJECT_UNKNOWN_FLAGS);
2212
2213         eb.i915 = to_i915(dev);
2214         eb.file = file;
2215         eb.args = args;
2216         if (DBG_FORCE_RELOC || !(args->flags & I915_EXEC_NO_RELOC))
2217                 args->flags |= __EXEC_HAS_RELOC;
2218
2219         eb.exec = exec;
2220         eb.vma = (struct i915_vma **)(exec + args->buffer_count + 1);
2221         eb.vma[0] = NULL;
2222         eb.flags = (unsigned int *)(eb.vma + args->buffer_count + 1);
2223
2224         eb.invalid_flags = __EXEC_OBJECT_UNKNOWN_FLAGS;
2225         reloc_cache_init(&eb.reloc_cache, eb.i915);
2226
2227         eb.buffer_count = args->buffer_count;
2228         eb.batch_start_offset = args->batch_start_offset;
2229         eb.batch_len = args->batch_len;
2230
2231         eb.batch_flags = 0;
2232         if (args->flags & I915_EXEC_SECURE) {
2233                 if (!drm_is_current_master(file) || !capable(CAP_SYS_ADMIN))
2234                     return -EPERM;
2235
2236                 eb.batch_flags |= I915_DISPATCH_SECURE;
2237         }
2238         if (args->flags & I915_EXEC_IS_PINNED)
2239                 eb.batch_flags |= I915_DISPATCH_PINNED;
2240
2241         eb.engine = eb_select_engine(eb.i915, file, args);
2242         if (!eb.engine)
2243                 return -EINVAL;
2244
2245         if (args->flags & I915_EXEC_FENCE_IN) {
2246                 in_fence = sync_file_get_fence(lower_32_bits(args->rsvd2));
2247                 if (!in_fence)
2248                         return -EINVAL;
2249         }
2250
2251         if (args->flags & I915_EXEC_FENCE_OUT) {
2252                 out_fence_fd = get_unused_fd_flags(O_CLOEXEC);
2253                 if (out_fence_fd < 0) {
2254                         err = out_fence_fd;
2255                         goto err_in_fence;
2256                 }
2257         }
2258
2259         err = eb_create(&eb);
2260         if (err)
2261                 goto err_out_fence;
2262
2263         GEM_BUG_ON(!eb.lut_size);
2264
2265         err = eb_select_context(&eb);
2266         if (unlikely(err))
2267                 goto err_destroy;
2268
2269         /*
2270          * Take a local wakeref for preparing to dispatch the execbuf as
2271          * we expect to access the hardware fairly frequently in the
2272          * process. Upon first dispatch, we acquire another prolonged
2273          * wakeref that we hold until the GPU has been idle for at least
2274          * 100ms.
2275          */
2276         intel_runtime_pm_get(eb.i915);
2277
2278         err = i915_mutex_lock_interruptible(dev);
2279         if (err)
2280                 goto err_rpm;
2281
2282         err = eb_relocate(&eb);
2283         if (err) {
2284                 /*
2285                  * If the user expects the execobject.offset and
2286                  * reloc.presumed_offset to be an exact match,
2287                  * as for using NO_RELOC, then we cannot update
2288                  * the execobject.offset until we have completed
2289                  * relocation.
2290                  */
2291                 args->flags &= ~__EXEC_HAS_RELOC;
2292                 goto err_vma;
2293         }
2294
2295         if (unlikely(*eb.batch->exec_flags & EXEC_OBJECT_WRITE)) {
2296                 DRM_DEBUG("Attempting to use self-modifying batch buffer\n");
2297                 err = -EINVAL;
2298                 goto err_vma;
2299         }
2300         if (eb.batch_start_offset > eb.batch->size ||
2301             eb.batch_len > eb.batch->size - eb.batch_start_offset) {
2302                 DRM_DEBUG("Attempting to use out-of-bounds batch\n");
2303                 err = -EINVAL;
2304                 goto err_vma;
2305         }
2306
2307         if (eb_use_cmdparser(&eb)) {
2308                 struct i915_vma *vma;
2309
2310                 vma = eb_parse(&eb, drm_is_current_master(file));
2311                 if (IS_ERR(vma)) {
2312                         err = PTR_ERR(vma);
2313                         goto err_vma;
2314                 }
2315
2316                 if (vma) {
2317                         /*
2318                          * Batch parsed and accepted:
2319                          *
2320                          * Set the DISPATCH_SECURE bit to remove the NON_SECURE
2321                          * bit from MI_BATCH_BUFFER_START commands issued in
2322                          * the dispatch_execbuffer implementations. We
2323                          * specifically don't want that set on batches the
2324                          * command parser has accepted.
2325                          */
2326                         eb.batch_flags |= I915_DISPATCH_SECURE;
2327                         eb.batch_start_offset = 0;
2328                         eb.batch = vma;
2329                 }
2330         }
2331
2332         if (eb.batch_len == 0)
2333                 eb.batch_len = eb.batch->size - eb.batch_start_offset;
2334
2335         /*
2336          * snb/ivb/vlv conflate the "batch in ppgtt" bit with the "non-secure
2337          * batch" bit. Hence we need to pin secure batches into the global gtt.
2338          * hsw should have this fixed, but bdw mucks it up again. */
2339         if (eb.batch_flags & I915_DISPATCH_SECURE) {
2340                 struct i915_vma *vma;
2341
2342                 /*
2343                  * So on first glance it looks freaky that we pin the batch here
2344                  * outside of the reservation loop. But:
2345                  * - The batch is already pinned into the relevant ppgtt, so we
2346                  *   already have the backing storage fully allocated.
2347                  * - No other BO uses the global gtt (well contexts, but meh),
2348                  *   so we don't really have issues with multiple objects not
2349                  *   fitting due to fragmentation.
2350                  * So this is actually safe.
2351                  */
2352                 vma = i915_gem_object_ggtt_pin(eb.batch->obj, NULL, 0, 0, 0);
2353                 if (IS_ERR(vma)) {
2354                         err = PTR_ERR(vma);
2355                         goto err_vma;
2356                 }
2357
2358                 eb.batch = vma;
2359         }
2360
2361         /* All GPU relocation batches must be submitted prior to the user rq */
2362         GEM_BUG_ON(eb.reloc_cache.rq);
2363
2364         /* Allocate a request for this batch buffer nice and early. */
2365         eb.request = i915_request_alloc(eb.engine, eb.ctx);
2366         if (IS_ERR(eb.request)) {
2367                 err = PTR_ERR(eb.request);
2368                 goto err_batch_unpin;
2369         }
2370
2371         if (in_fence) {
2372                 err = i915_request_await_dma_fence(eb.request, in_fence);
2373                 if (err < 0)
2374                         goto err_request;
2375         }
2376
2377         if (fences) {
2378                 err = await_fence_array(&eb, fences);
2379                 if (err)
2380                         goto err_request;
2381         }
2382
2383         if (out_fence_fd != -1) {
2384                 out_fence = sync_file_create(&eb.request->fence);
2385                 if (!out_fence) {
2386                         err = -ENOMEM;
2387                         goto err_request;
2388                 }
2389         }
2390
2391         /*
2392          * Whilst this request exists, batch_obj will be on the
2393          * active_list, and so will hold the active reference. Only when this
2394          * request is retired will the the batch_obj be moved onto the
2395          * inactive_list and lose its active reference. Hence we do not need
2396          * to explicitly hold another reference here.
2397          */
2398         eb.request->batch = eb.batch;
2399
2400         trace_i915_request_queue(eb.request, eb.batch_flags);
2401         err = eb_submit(&eb);
2402 err_request:
2403         i915_request_add(eb.request);
2404         add_to_client(eb.request, file);
2405
2406         if (fences)
2407                 signal_fence_array(&eb, fences);
2408
2409         if (out_fence) {
2410                 if (err == 0) {
2411                         fd_install(out_fence_fd, out_fence->file);
2412                         args->rsvd2 &= GENMASK_ULL(31, 0); /* keep in-fence */
2413                         args->rsvd2 |= (u64)out_fence_fd << 32;
2414                         out_fence_fd = -1;
2415                 } else {
2416                         fput(out_fence->file);
2417                 }
2418         }
2419
2420 err_batch_unpin:
2421         if (eb.batch_flags & I915_DISPATCH_SECURE)
2422                 i915_vma_unpin(eb.batch);
2423 err_vma:
2424         if (eb.exec)
2425                 eb_release_vmas(&eb);
2426         mutex_unlock(&dev->struct_mutex);
2427 err_rpm:
2428         intel_runtime_pm_put(eb.i915);
2429         i915_gem_context_put(eb.ctx);
2430 err_destroy:
2431         eb_destroy(&eb);
2432 err_out_fence:
2433         if (out_fence_fd != -1)
2434                 put_unused_fd(out_fence_fd);
2435 err_in_fence:
2436         dma_fence_put(in_fence);
2437         return err;
2438 }
2439
2440 static size_t eb_element_size(void)
2441 {
2442         return (sizeof(struct drm_i915_gem_exec_object2) +
2443                 sizeof(struct i915_vma *) +
2444                 sizeof(unsigned int));
2445 }
2446
2447 static bool check_buffer_count(size_t count)
2448 {
2449         const size_t sz = eb_element_size();
2450
2451         /*
2452          * When using LUT_HANDLE, we impose a limit of INT_MAX for the lookup
2453          * array size (see eb_create()). Otherwise, we can accept an array as
2454          * large as can be addressed (though use large arrays at your peril)!
2455          */
2456
2457         return !(count < 1 || count > INT_MAX || count > SIZE_MAX / sz - 1);
2458 }
2459
2460 /*
2461  * Legacy execbuffer just creates an exec2 list from the original exec object
2462  * list array and passes it to the real function.
2463  */
2464 int
2465 i915_gem_execbuffer_ioctl(struct drm_device *dev, void *data,
2466                           struct drm_file *file)
2467 {
2468         struct drm_i915_gem_execbuffer *args = data;
2469         struct drm_i915_gem_execbuffer2 exec2;
2470         struct drm_i915_gem_exec_object *exec_list = NULL;
2471         struct drm_i915_gem_exec_object2 *exec2_list = NULL;
2472         const size_t count = args->buffer_count;
2473         unsigned int i;
2474         int err;
2475
2476         if (!check_buffer_count(count)) {
2477                 DRM_DEBUG("execbuf2 with %zd buffers\n", count);
2478                 return -EINVAL;
2479         }
2480
2481         exec2.buffers_ptr = args->buffers_ptr;
2482         exec2.buffer_count = args->buffer_count;
2483         exec2.batch_start_offset = args->batch_start_offset;
2484         exec2.batch_len = args->batch_len;
2485         exec2.DR1 = args->DR1;
2486         exec2.DR4 = args->DR4;
2487         exec2.num_cliprects = args->num_cliprects;
2488         exec2.cliprects_ptr = args->cliprects_ptr;
2489         exec2.flags = I915_EXEC_RENDER;
2490         i915_execbuffer2_set_context_id(exec2, 0);
2491
2492         if (!i915_gem_check_execbuffer(&exec2))
2493                 return -EINVAL;
2494
2495         /* Copy in the exec list from userland */
2496         exec_list = kvmalloc_array(count, sizeof(*exec_list),
2497                                    __GFP_NOWARN | GFP_KERNEL);
2498         exec2_list = kvmalloc_array(count + 1, eb_element_size(),
2499                                     __GFP_NOWARN | GFP_KERNEL);
2500         if (exec_list == NULL || exec2_list == NULL) {
2501                 DRM_DEBUG("Failed to allocate exec list for %d buffers\n",
2502                           args->buffer_count);
2503                 kvfree(exec_list);
2504                 kvfree(exec2_list);
2505                 return -ENOMEM;
2506         }
2507         err = copy_from_user(exec_list,
2508                              u64_to_user_ptr(args->buffers_ptr),
2509                              sizeof(*exec_list) * count);
2510         if (err) {
2511                 DRM_DEBUG("copy %d exec entries failed %d\n",
2512                           args->buffer_count, err);
2513                 kvfree(exec_list);
2514                 kvfree(exec2_list);
2515                 return -EFAULT;
2516         }
2517
2518         for (i = 0; i < args->buffer_count; i++) {
2519                 exec2_list[i].handle = exec_list[i].handle;
2520                 exec2_list[i].relocation_count = exec_list[i].relocation_count;
2521                 exec2_list[i].relocs_ptr = exec_list[i].relocs_ptr;
2522                 exec2_list[i].alignment = exec_list[i].alignment;
2523                 exec2_list[i].offset = exec_list[i].offset;
2524                 if (INTEL_GEN(to_i915(dev)) < 4)
2525                         exec2_list[i].flags = EXEC_OBJECT_NEEDS_FENCE;
2526                 else
2527                         exec2_list[i].flags = 0;
2528         }
2529
2530         err = i915_gem_do_execbuffer(dev, file, &exec2, exec2_list, NULL);
2531         if (exec2.flags & __EXEC_HAS_RELOC) {
2532                 struct drm_i915_gem_exec_object __user *user_exec_list =
2533                         u64_to_user_ptr(args->buffers_ptr);
2534
2535                 /* Copy the new buffer offsets back to the user's exec list. */
2536                 for (i = 0; i < args->buffer_count; i++) {
2537                         if (!(exec2_list[i].offset & UPDATE))
2538                                 continue;
2539
2540                         exec2_list[i].offset =
2541                                 gen8_canonical_addr(exec2_list[i].offset & PIN_OFFSET_MASK);
2542                         exec2_list[i].offset &= PIN_OFFSET_MASK;
2543                         if (__copy_to_user(&user_exec_list[i].offset,
2544                                            &exec2_list[i].offset,
2545                                            sizeof(user_exec_list[i].offset)))
2546                                 break;
2547                 }
2548         }
2549
2550         kvfree(exec_list);
2551         kvfree(exec2_list);
2552         return err;
2553 }
2554
2555 int
2556 i915_gem_execbuffer2_ioctl(struct drm_device *dev, void *data,
2557                            struct drm_file *file)
2558 {
2559         struct drm_i915_gem_execbuffer2 *args = data;
2560         struct drm_i915_gem_exec_object2 *exec2_list;
2561         struct drm_syncobj **fences = NULL;
2562         const size_t count = args->buffer_count;
2563         int err;
2564
2565         if (!check_buffer_count(count)) {
2566                 DRM_DEBUG("execbuf2 with %zd buffers\n", count);
2567                 return -EINVAL;
2568         }
2569
2570         if (!i915_gem_check_execbuffer(args))
2571                 return -EINVAL;
2572
2573         /* Allocate an extra slot for use by the command parser */
2574         exec2_list = kvmalloc_array(count + 1, eb_element_size(),
2575                                     __GFP_NOWARN | GFP_KERNEL);
2576         if (exec2_list == NULL) {
2577                 DRM_DEBUG("Failed to allocate exec list for %zd buffers\n",
2578                           count);
2579                 return -ENOMEM;
2580         }
2581         if (copy_from_user(exec2_list,
2582                            u64_to_user_ptr(args->buffers_ptr),
2583                            sizeof(*exec2_list) * count)) {
2584                 DRM_DEBUG("copy %zd exec entries failed\n", count);
2585                 kvfree(exec2_list);
2586                 return -EFAULT;
2587         }
2588
2589         if (args->flags & I915_EXEC_FENCE_ARRAY) {
2590                 fences = get_fence_array(args, file);
2591                 if (IS_ERR(fences)) {
2592                         kvfree(exec2_list);
2593                         return PTR_ERR(fences);
2594                 }
2595         }
2596
2597         err = i915_gem_do_execbuffer(dev, file, args, exec2_list, fences);
2598
2599         /*
2600          * Now that we have begun execution of the batchbuffer, we ignore
2601          * any new error after this point. Also given that we have already
2602          * updated the associated relocations, we try to write out the current
2603          * object locations irrespective of any error.
2604          */
2605         if (args->flags & __EXEC_HAS_RELOC) {
2606                 struct drm_i915_gem_exec_object2 __user *user_exec_list =
2607                         u64_to_user_ptr(args->buffers_ptr);
2608                 unsigned int i;
2609
2610                 /* Copy the new buffer offsets back to the user's exec list. */
2611                 /*
2612                  * Note: count * sizeof(*user_exec_list) does not overflow,
2613                  * because we checked 'count' in check_buffer_count().
2614                  *
2615                  * And this range already got effectively checked earlier
2616                  * when we did the "copy_from_user()" above.
2617                  */
2618                 if (!user_access_begin(user_exec_list, count * sizeof(*user_exec_list)))
2619                         goto end_user;
2620
2621                 for (i = 0; i < args->buffer_count; i++) {
2622                         if (!(exec2_list[i].offset & UPDATE))
2623                                 continue;
2624
2625                         exec2_list[i].offset =
2626                                 gen8_canonical_addr(exec2_list[i].offset & PIN_OFFSET_MASK);
2627                         unsafe_put_user(exec2_list[i].offset,
2628                                         &user_exec_list[i].offset,
2629                                         end_user);
2630                 }
2631 end_user:
2632                 user_access_end();
2633         }
2634
2635         args->flags &= ~__I915_EXEC_UNKNOWN_FLAGS;
2636         put_fence_array(args, fences);
2637         kvfree(exec2_list);
2638         return err;
2639 }