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