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