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