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