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