Merge branch 'linux-4.12' of git://github.com/skeggsb/linux into drm-next
[platform/kernel/linux-starfive.git] / drivers / gpu / drm / i915 / i915_gem_execbuffer.c
1 /*
2  * Copyright © 2008,2010 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *    Eric Anholt <eric@anholt.net>
25  *    Chris Wilson <chris@chris-wilson.co.uk>
26  *
27  */
28
29 #include <linux/dma_remapping.h>
30 #include <linux/reservation.h>
31 #include <linux/sync_file.h>
32 #include <linux/uaccess.h>
33
34 #include <drm/drmP.h>
35 #include <drm/i915_drm.h>
36
37 #include "i915_drv.h"
38 #include "i915_gem_clflush.h"
39 #include "i915_trace.h"
40 #include "intel_drv.h"
41 #include "intel_frontbuffer.h"
42
43 #define DBG_USE_CPU_RELOC 0 /* -1 force GTT relocs; 1 force CPU relocs */
44
45 #define  __EXEC_OBJECT_HAS_PIN          (1<<31)
46 #define  __EXEC_OBJECT_HAS_FENCE        (1<<30)
47 #define  __EXEC_OBJECT_NEEDS_MAP        (1<<29)
48 #define  __EXEC_OBJECT_NEEDS_BIAS       (1<<28)
49 #define  __EXEC_OBJECT_INTERNAL_FLAGS (0xf<<28) /* all of the above */
50
51 #define BATCH_OFFSET_BIAS (256*1024)
52
53 struct i915_execbuffer_params {
54         struct drm_device               *dev;
55         struct drm_file                 *file;
56         struct i915_vma                 *batch;
57         u32                             dispatch_flags;
58         u32                             args_batch_start_offset;
59         struct intel_engine_cs          *engine;
60         struct i915_gem_context         *ctx;
61         struct drm_i915_gem_request     *request;
62 };
63
64 struct eb_vmas {
65         struct drm_i915_private *i915;
66         struct list_head vmas;
67         int and;
68         union {
69                 struct i915_vma *lut[0];
70                 struct hlist_head buckets[0];
71         };
72 };
73
74 static struct eb_vmas *
75 eb_create(struct drm_i915_private *i915,
76           struct drm_i915_gem_execbuffer2 *args)
77 {
78         struct eb_vmas *eb = NULL;
79
80         if (args->flags & I915_EXEC_HANDLE_LUT) {
81                 unsigned size = args->buffer_count;
82                 size *= sizeof(struct i915_vma *);
83                 size += sizeof(struct eb_vmas);
84                 eb = kmalloc(size, GFP_TEMPORARY | __GFP_NOWARN | __GFP_NORETRY);
85         }
86
87         if (eb == NULL) {
88                 unsigned size = args->buffer_count;
89                 unsigned count = PAGE_SIZE / sizeof(struct hlist_head) / 2;
90                 BUILD_BUG_ON_NOT_POWER_OF_2(PAGE_SIZE / sizeof(struct hlist_head));
91                 while (count > 2*size)
92                         count >>= 1;
93                 eb = kzalloc(count*sizeof(struct hlist_head) +
94                              sizeof(struct eb_vmas),
95                              GFP_TEMPORARY);
96                 if (eb == NULL)
97                         return eb;
98
99                 eb->and = count - 1;
100         } else
101                 eb->and = -args->buffer_count;
102
103         eb->i915 = i915;
104         INIT_LIST_HEAD(&eb->vmas);
105         return eb;
106 }
107
108 static void
109 eb_reset(struct eb_vmas *eb)
110 {
111         if (eb->and >= 0)
112                 memset(eb->buckets, 0, (eb->and+1)*sizeof(struct hlist_head));
113 }
114
115 static struct i915_vma *
116 eb_get_batch(struct eb_vmas *eb)
117 {
118         struct i915_vma *vma = list_entry(eb->vmas.prev, typeof(*vma), exec_list);
119
120         /*
121          * SNA is doing fancy tricks with compressing batch buffers, which leads
122          * to negative relocation deltas. Usually that works out ok since the
123          * relocate address is still positive, except when the batch is placed
124          * very low in the GTT. Ensure this doesn't happen.
125          *
126          * Note that actual hangs have only been observed on gen7, but for
127          * paranoia do it everywhere.
128          */
129         if ((vma->exec_entry->flags & EXEC_OBJECT_PINNED) == 0)
130                 vma->exec_entry->flags |= __EXEC_OBJECT_NEEDS_BIAS;
131
132         return vma;
133 }
134
135 static int
136 eb_lookup_vmas(struct eb_vmas *eb,
137                struct drm_i915_gem_exec_object2 *exec,
138                const struct drm_i915_gem_execbuffer2 *args,
139                struct i915_address_space *vm,
140                struct drm_file *file)
141 {
142         struct drm_i915_gem_object *obj;
143         struct list_head objects;
144         int i, ret;
145
146         INIT_LIST_HEAD(&objects);
147         spin_lock(&file->table_lock);
148         /* Grab a reference to the object and release the lock so we can lookup
149          * or create the VMA without using GFP_ATOMIC */
150         for (i = 0; i < args->buffer_count; i++) {
151                 obj = to_intel_bo(idr_find(&file->object_idr, exec[i].handle));
152                 if (obj == NULL) {
153                         spin_unlock(&file->table_lock);
154                         DRM_DEBUG("Invalid object handle %d at index %d\n",
155                                    exec[i].handle, i);
156                         ret = -ENOENT;
157                         goto err;
158                 }
159
160                 if (!list_empty(&obj->obj_exec_link)) {
161                         spin_unlock(&file->table_lock);
162                         DRM_DEBUG("Object %p [handle %d, index %d] appears more than once in object list\n",
163                                    obj, exec[i].handle, i);
164                         ret = -EINVAL;
165                         goto err;
166                 }
167
168                 i915_gem_object_get(obj);
169                 list_add_tail(&obj->obj_exec_link, &objects);
170         }
171         spin_unlock(&file->table_lock);
172
173         i = 0;
174         while (!list_empty(&objects)) {
175                 struct i915_vma *vma;
176
177                 obj = list_first_entry(&objects,
178                                        struct drm_i915_gem_object,
179                                        obj_exec_link);
180
181                 /*
182                  * NOTE: We can leak any vmas created here when something fails
183                  * later on. But that's no issue since vma_unbind can deal with
184                  * vmas which are not actually bound. And since only
185                  * lookup_or_create exists as an interface to get at the vma
186                  * from the (obj, vm) we don't run the risk of creating
187                  * duplicated vmas for the same vm.
188                  */
189                 vma = i915_vma_instance(obj, vm, NULL);
190                 if (unlikely(IS_ERR(vma))) {
191                         DRM_DEBUG("Failed to lookup VMA\n");
192                         ret = PTR_ERR(vma);
193                         goto err;
194                 }
195
196                 /* Transfer ownership from the objects list to the vmas list. */
197                 list_add_tail(&vma->exec_list, &eb->vmas);
198                 list_del_init(&obj->obj_exec_link);
199
200                 vma->exec_entry = &exec[i];
201                 if (eb->and < 0) {
202                         eb->lut[i] = vma;
203                 } else {
204                         uint32_t handle = args->flags & I915_EXEC_HANDLE_LUT ? i : exec[i].handle;
205                         vma->exec_handle = handle;
206                         hlist_add_head(&vma->exec_node,
207                                        &eb->buckets[handle & eb->and]);
208                 }
209                 ++i;
210         }
211
212         return 0;
213
214
215 err:
216         while (!list_empty(&objects)) {
217                 obj = list_first_entry(&objects,
218                                        struct drm_i915_gem_object,
219                                        obj_exec_link);
220                 list_del_init(&obj->obj_exec_link);
221                 i915_gem_object_put(obj);
222         }
223         /*
224          * Objects already transfered to the vmas list will be unreferenced by
225          * eb_destroy.
226          */
227
228         return ret;
229 }
230
231 static struct i915_vma *eb_get_vma(struct eb_vmas *eb, unsigned long handle)
232 {
233         if (eb->and < 0) {
234                 if (handle >= -eb->and)
235                         return NULL;
236                 return eb->lut[handle];
237         } else {
238                 struct hlist_head *head;
239                 struct i915_vma *vma;
240
241                 head = &eb->buckets[handle & eb->and];
242                 hlist_for_each_entry(vma, head, exec_node) {
243                         if (vma->exec_handle == handle)
244                                 return vma;
245                 }
246                 return NULL;
247         }
248 }
249
250 static void
251 i915_gem_execbuffer_unreserve_vma(struct i915_vma *vma)
252 {
253         struct drm_i915_gem_exec_object2 *entry;
254
255         if (!drm_mm_node_allocated(&vma->node))
256                 return;
257
258         entry = vma->exec_entry;
259
260         if (entry->flags & __EXEC_OBJECT_HAS_FENCE)
261                 i915_vma_unpin_fence(vma);
262
263         if (entry->flags & __EXEC_OBJECT_HAS_PIN)
264                 __i915_vma_unpin(vma);
265
266         entry->flags &= ~(__EXEC_OBJECT_HAS_FENCE | __EXEC_OBJECT_HAS_PIN);
267 }
268
269 static void eb_destroy(struct eb_vmas *eb)
270 {
271         while (!list_empty(&eb->vmas)) {
272                 struct i915_vma *vma;
273
274                 vma = list_first_entry(&eb->vmas,
275                                        struct i915_vma,
276                                        exec_list);
277                 list_del_init(&vma->exec_list);
278                 i915_gem_execbuffer_unreserve_vma(vma);
279                 vma->exec_entry = NULL;
280                 i915_vma_put(vma);
281         }
282         kfree(eb);
283 }
284
285 static inline int use_cpu_reloc(struct drm_i915_gem_object *obj)
286 {
287         if (!i915_gem_object_has_struct_page(obj))
288                 return false;
289
290         if (DBG_USE_CPU_RELOC)
291                 return DBG_USE_CPU_RELOC > 0;
292
293         return (HAS_LLC(to_i915(obj->base.dev)) ||
294                 obj->base.write_domain == I915_GEM_DOMAIN_CPU ||
295                 obj->cache_level != I915_CACHE_NONE);
296 }
297
298 /* Used to convert any address to canonical form.
299  * Starting from gen8, some commands (e.g. STATE_BASE_ADDRESS,
300  * MI_LOAD_REGISTER_MEM and others, see Broadwell PRM Vol2a) require the
301  * addresses to be in a canonical form:
302  * "GraphicsAddress[63:48] are ignored by the HW and assumed to be in correct
303  * canonical form [63:48] == [47]."
304  */
305 #define GEN8_HIGH_ADDRESS_BIT 47
306 static inline uint64_t gen8_canonical_addr(uint64_t address)
307 {
308         return sign_extend64(address, GEN8_HIGH_ADDRESS_BIT);
309 }
310
311 static inline uint64_t gen8_noncanonical_addr(uint64_t address)
312 {
313         return address & ((1ULL << (GEN8_HIGH_ADDRESS_BIT + 1)) - 1);
314 }
315
316 static inline uint64_t
317 relocation_target(const struct drm_i915_gem_relocation_entry *reloc,
318                   uint64_t target_offset)
319 {
320         return gen8_canonical_addr((int)reloc->delta + target_offset);
321 }
322
323 struct reloc_cache {
324         struct drm_i915_private *i915;
325         struct drm_mm_node node;
326         unsigned long vaddr;
327         unsigned int page;
328         bool use_64bit_reloc;
329 };
330
331 static void reloc_cache_init(struct reloc_cache *cache,
332                              struct drm_i915_private *i915)
333 {
334         cache->page = -1;
335         cache->vaddr = 0;
336         cache->i915 = i915;
337         /* Must be a variable in the struct to allow GCC to unroll. */
338         cache->use_64bit_reloc = HAS_64BIT_RELOC(i915);
339         cache->node.allocated = false;
340 }
341
342 static inline void *unmask_page(unsigned long p)
343 {
344         return (void *)(uintptr_t)(p & PAGE_MASK);
345 }
346
347 static inline unsigned int unmask_flags(unsigned long p)
348 {
349         return p & ~PAGE_MASK;
350 }
351
352 #define KMAP 0x4 /* after CLFLUSH_FLAGS */
353
354 static void reloc_cache_fini(struct reloc_cache *cache)
355 {
356         void *vaddr;
357
358         if (!cache->vaddr)
359                 return;
360
361         vaddr = unmask_page(cache->vaddr);
362         if (cache->vaddr & KMAP) {
363                 if (cache->vaddr & CLFLUSH_AFTER)
364                         mb();
365
366                 kunmap_atomic(vaddr);
367                 i915_gem_obj_finish_shmem_access((struct drm_i915_gem_object *)cache->node.mm);
368         } else {
369                 wmb();
370                 io_mapping_unmap_atomic((void __iomem *)vaddr);
371                 if (cache->node.allocated) {
372                         struct i915_ggtt *ggtt = &cache->i915->ggtt;
373
374                         ggtt->base.clear_range(&ggtt->base,
375                                                cache->node.start,
376                                                cache->node.size);
377                         drm_mm_remove_node(&cache->node);
378                 } else {
379                         i915_vma_unpin((struct i915_vma *)cache->node.mm);
380                 }
381         }
382 }
383
384 static void *reloc_kmap(struct drm_i915_gem_object *obj,
385                         struct reloc_cache *cache,
386                         int page)
387 {
388         void *vaddr;
389
390         if (cache->vaddr) {
391                 kunmap_atomic(unmask_page(cache->vaddr));
392         } else {
393                 unsigned int flushes;
394                 int ret;
395
396                 ret = i915_gem_obj_prepare_shmem_write(obj, &flushes);
397                 if (ret)
398                         return ERR_PTR(ret);
399
400                 BUILD_BUG_ON(KMAP & CLFLUSH_FLAGS);
401                 BUILD_BUG_ON((KMAP | CLFLUSH_FLAGS) & PAGE_MASK);
402
403                 cache->vaddr = flushes | KMAP;
404                 cache->node.mm = (void *)obj;
405                 if (flushes)
406                         mb();
407         }
408
409         vaddr = kmap_atomic(i915_gem_object_get_dirty_page(obj, page));
410         cache->vaddr = unmask_flags(cache->vaddr) | (unsigned long)vaddr;
411         cache->page = page;
412
413         return vaddr;
414 }
415
416 static void *reloc_iomap(struct drm_i915_gem_object *obj,
417                          struct reloc_cache *cache,
418                          int page)
419 {
420         struct i915_ggtt *ggtt = &cache->i915->ggtt;
421         unsigned long offset;
422         void *vaddr;
423
424         if (cache->vaddr) {
425                 io_mapping_unmap_atomic((void __force __iomem *) unmask_page(cache->vaddr));
426         } else {
427                 struct i915_vma *vma;
428                 int ret;
429
430                 if (use_cpu_reloc(obj))
431                         return NULL;
432
433                 ret = i915_gem_object_set_to_gtt_domain(obj, true);
434                 if (ret)
435                         return ERR_PTR(ret);
436
437                 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
438                                                PIN_MAPPABLE | PIN_NONBLOCK);
439                 if (IS_ERR(vma)) {
440                         memset(&cache->node, 0, sizeof(cache->node));
441                         ret = drm_mm_insert_node_in_range
442                                 (&ggtt->base.mm, &cache->node,
443                                  PAGE_SIZE, 0, I915_COLOR_UNEVICTABLE,
444                                  0, ggtt->mappable_end,
445                                  DRM_MM_INSERT_LOW);
446                         if (ret) /* no inactive aperture space, use cpu reloc */
447                                 return NULL;
448                 } else {
449                         ret = i915_vma_put_fence(vma);
450                         if (ret) {
451                                 i915_vma_unpin(vma);
452                                 return ERR_PTR(ret);
453                         }
454
455                         cache->node.start = vma->node.start;
456                         cache->node.mm = (void *)vma;
457                 }
458         }
459
460         offset = cache->node.start;
461         if (cache->node.allocated) {
462                 wmb();
463                 ggtt->base.insert_page(&ggtt->base,
464                                        i915_gem_object_get_dma_address(obj, page),
465                                        offset, I915_CACHE_NONE, 0);
466         } else {
467                 offset += page << PAGE_SHIFT;
468         }
469
470         vaddr = (void __force *) io_mapping_map_atomic_wc(&cache->i915->ggtt.mappable, offset);
471         cache->page = page;
472         cache->vaddr = (unsigned long)vaddr;
473
474         return vaddr;
475 }
476
477 static void *reloc_vaddr(struct drm_i915_gem_object *obj,
478                          struct reloc_cache *cache,
479                          int page)
480 {
481         void *vaddr;
482
483         if (cache->page == page) {
484                 vaddr = unmask_page(cache->vaddr);
485         } else {
486                 vaddr = NULL;
487                 if ((cache->vaddr & KMAP) == 0)
488                         vaddr = reloc_iomap(obj, cache, page);
489                 if (!vaddr)
490                         vaddr = reloc_kmap(obj, cache, page);
491         }
492
493         return vaddr;
494 }
495
496 static void clflush_write32(u32 *addr, u32 value, unsigned int flushes)
497 {
498         if (unlikely(flushes & (CLFLUSH_BEFORE | CLFLUSH_AFTER))) {
499                 if (flushes & CLFLUSH_BEFORE) {
500                         clflushopt(addr);
501                         mb();
502                 }
503
504                 *addr = value;
505
506                 /* Writes to the same cacheline are serialised by the CPU
507                  * (including clflush). On the write path, we only require
508                  * that it hits memory in an orderly fashion and place
509                  * mb barriers at the start and end of the relocation phase
510                  * to ensure ordering of clflush wrt to the system.
511                  */
512                 if (flushes & CLFLUSH_AFTER)
513                         clflushopt(addr);
514         } else
515                 *addr = value;
516 }
517
518 static int
519 relocate_entry(struct drm_i915_gem_object *obj,
520                const struct drm_i915_gem_relocation_entry *reloc,
521                struct reloc_cache *cache,
522                u64 target_offset)
523 {
524         u64 offset = reloc->offset;
525         bool wide = cache->use_64bit_reloc;
526         void *vaddr;
527
528         target_offset = relocation_target(reloc, target_offset);
529 repeat:
530         vaddr = reloc_vaddr(obj, cache, offset >> PAGE_SHIFT);
531         if (IS_ERR(vaddr))
532                 return PTR_ERR(vaddr);
533
534         clflush_write32(vaddr + offset_in_page(offset),
535                         lower_32_bits(target_offset),
536                         cache->vaddr);
537
538         if (wide) {
539                 offset += sizeof(u32);
540                 target_offset >>= 32;
541                 wide = false;
542                 goto repeat;
543         }
544
545         return 0;
546 }
547
548 static int
549 i915_gem_execbuffer_relocate_entry(struct drm_i915_gem_object *obj,
550                                    struct eb_vmas *eb,
551                                    struct drm_i915_gem_relocation_entry *reloc,
552                                    struct reloc_cache *cache)
553 {
554         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
555         struct drm_gem_object *target_obj;
556         struct drm_i915_gem_object *target_i915_obj;
557         struct i915_vma *target_vma;
558         uint64_t target_offset;
559         int ret;
560
561         /* we've already hold a reference to all valid objects */
562         target_vma = eb_get_vma(eb, reloc->target_handle);
563         if (unlikely(target_vma == NULL))
564                 return -ENOENT;
565         target_i915_obj = target_vma->obj;
566         target_obj = &target_vma->obj->base;
567
568         target_offset = gen8_canonical_addr(target_vma->node.start);
569
570         /* Sandybridge PPGTT errata: We need a global gtt mapping for MI and
571          * pipe_control writes because the gpu doesn't properly redirect them
572          * through the ppgtt for non_secure batchbuffers. */
573         if (unlikely(IS_GEN6(dev_priv) &&
574             reloc->write_domain == I915_GEM_DOMAIN_INSTRUCTION)) {
575                 ret = i915_vma_bind(target_vma, target_i915_obj->cache_level,
576                                     PIN_GLOBAL);
577                 if (WARN_ONCE(ret, "Unexpected failure to bind target VMA!"))
578                         return ret;
579         }
580
581         /* Validate that the target is in a valid r/w GPU domain */
582         if (unlikely(reloc->write_domain & (reloc->write_domain - 1))) {
583                 DRM_DEBUG("reloc with multiple write domains: "
584                           "obj %p target %d offset %d "
585                           "read %08x write %08x",
586                           obj, reloc->target_handle,
587                           (int) reloc->offset,
588                           reloc->read_domains,
589                           reloc->write_domain);
590                 return -EINVAL;
591         }
592         if (unlikely((reloc->write_domain | reloc->read_domains)
593                      & ~I915_GEM_GPU_DOMAINS)) {
594                 DRM_DEBUG("reloc with read/write non-GPU domains: "
595                           "obj %p target %d offset %d "
596                           "read %08x write %08x",
597                           obj, reloc->target_handle,
598                           (int) reloc->offset,
599                           reloc->read_domains,
600                           reloc->write_domain);
601                 return -EINVAL;
602         }
603
604         target_obj->pending_read_domains |= reloc->read_domains;
605         target_obj->pending_write_domain |= reloc->write_domain;
606
607         /* If the relocation already has the right value in it, no
608          * more work needs to be done.
609          */
610         if (target_offset == reloc->presumed_offset)
611                 return 0;
612
613         /* Check that the relocation address is valid... */
614         if (unlikely(reloc->offset >
615                      obj->base.size - (cache->use_64bit_reloc ? 8 : 4))) {
616                 DRM_DEBUG("Relocation beyond object bounds: "
617                           "obj %p target %d offset %d size %d.\n",
618                           obj, reloc->target_handle,
619                           (int) reloc->offset,
620                           (int) obj->base.size);
621                 return -EINVAL;
622         }
623         if (unlikely(reloc->offset & 3)) {
624                 DRM_DEBUG("Relocation not 4-byte aligned: "
625                           "obj %p target %d offset %d.\n",
626                           obj, reloc->target_handle,
627                           (int) reloc->offset);
628                 return -EINVAL;
629         }
630
631         ret = relocate_entry(obj, reloc, cache, target_offset);
632         if (ret)
633                 return ret;
634
635         /* and update the user's relocation entry */
636         reloc->presumed_offset = target_offset;
637         return 0;
638 }
639
640 static int
641 i915_gem_execbuffer_relocate_vma(struct i915_vma *vma,
642                                  struct eb_vmas *eb)
643 {
644 #define N_RELOC(x) ((x) / sizeof(struct drm_i915_gem_relocation_entry))
645         struct drm_i915_gem_relocation_entry stack_reloc[N_RELOC(512)];
646         struct drm_i915_gem_relocation_entry __user *user_relocs;
647         struct drm_i915_gem_exec_object2 *entry = vma->exec_entry;
648         struct reloc_cache cache;
649         int remain, ret = 0;
650
651         user_relocs = u64_to_user_ptr(entry->relocs_ptr);
652         reloc_cache_init(&cache, eb->i915);
653
654         remain = entry->relocation_count;
655         while (remain) {
656                 struct drm_i915_gem_relocation_entry *r = stack_reloc;
657                 unsigned long unwritten;
658                 unsigned int count;
659
660                 count = min_t(unsigned int, remain, ARRAY_SIZE(stack_reloc));
661                 remain -= count;
662
663                 /* This is the fast path and we cannot handle a pagefault
664                  * whilst holding the struct mutex lest the user pass in the
665                  * relocations contained within a mmaped bo. For in such a case
666                  * we, the page fault handler would call i915_gem_fault() and
667                  * we would try to acquire the struct mutex again. Obviously
668                  * this is bad and so lockdep complains vehemently.
669                  */
670                 pagefault_disable();
671                 unwritten = __copy_from_user_inatomic(r, user_relocs, count*sizeof(r[0]));
672                 pagefault_enable();
673                 if (unlikely(unwritten)) {
674                         ret = -EFAULT;
675                         goto out;
676                 }
677
678                 do {
679                         u64 offset = r->presumed_offset;
680
681                         ret = i915_gem_execbuffer_relocate_entry(vma->obj, eb, r, &cache);
682                         if (ret)
683                                 goto out;
684
685                         if (r->presumed_offset != offset) {
686                                 pagefault_disable();
687                                 unwritten = __put_user(r->presumed_offset,
688                                                        &user_relocs->presumed_offset);
689                                 pagefault_enable();
690                                 if (unlikely(unwritten)) {
691                                         /* Note that reporting an error now
692                                          * leaves everything in an inconsistent
693                                          * state as we have *already* changed
694                                          * the relocation value inside the
695                                          * object. As we have not changed the
696                                          * reloc.presumed_offset or will not
697                                          * change the execobject.offset, on the
698                                          * call we may not rewrite the value
699                                          * inside the object, leaving it
700                                          * dangling and causing a GPU hang.
701                                          */
702                                         ret = -EFAULT;
703                                         goto out;
704                                 }
705                         }
706
707                         user_relocs++;
708                         r++;
709                 } while (--count);
710         }
711
712 out:
713         reloc_cache_fini(&cache);
714         return ret;
715 #undef N_RELOC
716 }
717
718 static int
719 i915_gem_execbuffer_relocate_vma_slow(struct i915_vma *vma,
720                                       struct eb_vmas *eb,
721                                       struct drm_i915_gem_relocation_entry *relocs)
722 {
723         const struct drm_i915_gem_exec_object2 *entry = vma->exec_entry;
724         struct reloc_cache cache;
725         int i, ret = 0;
726
727         reloc_cache_init(&cache, eb->i915);
728         for (i = 0; i < entry->relocation_count; i++) {
729                 ret = i915_gem_execbuffer_relocate_entry(vma->obj, eb, &relocs[i], &cache);
730                 if (ret)
731                         break;
732         }
733         reloc_cache_fini(&cache);
734
735         return ret;
736 }
737
738 static int
739 i915_gem_execbuffer_relocate(struct eb_vmas *eb)
740 {
741         struct i915_vma *vma;
742         int ret = 0;
743
744         list_for_each_entry(vma, &eb->vmas, exec_list) {
745                 ret = i915_gem_execbuffer_relocate_vma(vma, eb);
746                 if (ret)
747                         break;
748         }
749
750         return ret;
751 }
752
753 static bool only_mappable_for_reloc(unsigned int flags)
754 {
755         return (flags & (EXEC_OBJECT_NEEDS_FENCE | __EXEC_OBJECT_NEEDS_MAP)) ==
756                 __EXEC_OBJECT_NEEDS_MAP;
757 }
758
759 static int
760 i915_gem_execbuffer_reserve_vma(struct i915_vma *vma,
761                                 struct intel_engine_cs *engine,
762                                 bool *need_reloc)
763 {
764         struct drm_i915_gem_object *obj = vma->obj;
765         struct drm_i915_gem_exec_object2 *entry = vma->exec_entry;
766         uint64_t flags;
767         int ret;
768
769         flags = PIN_USER;
770         if (entry->flags & EXEC_OBJECT_NEEDS_GTT)
771                 flags |= PIN_GLOBAL;
772
773         if (!drm_mm_node_allocated(&vma->node)) {
774                 /* Wa32bitGeneralStateOffset & Wa32bitInstructionBaseOffset,
775                  * limit address to the first 4GBs for unflagged objects.
776                  */
777                 if ((entry->flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS) == 0)
778                         flags |= PIN_ZONE_4G;
779                 if (entry->flags & __EXEC_OBJECT_NEEDS_MAP)
780                         flags |= PIN_GLOBAL | PIN_MAPPABLE;
781                 if (entry->flags & __EXEC_OBJECT_NEEDS_BIAS)
782                         flags |= BATCH_OFFSET_BIAS | PIN_OFFSET_BIAS;
783                 if (entry->flags & EXEC_OBJECT_PINNED)
784                         flags |= entry->offset | PIN_OFFSET_FIXED;
785                 if ((flags & PIN_MAPPABLE) == 0)
786                         flags |= PIN_HIGH;
787         }
788
789         ret = i915_vma_pin(vma,
790                            entry->pad_to_size,
791                            entry->alignment,
792                            flags);
793         if ((ret == -ENOSPC || ret == -E2BIG) &&
794             only_mappable_for_reloc(entry->flags))
795                 ret = i915_vma_pin(vma,
796                                    entry->pad_to_size,
797                                    entry->alignment,
798                                    flags & ~PIN_MAPPABLE);
799         if (ret)
800                 return ret;
801
802         entry->flags |= __EXEC_OBJECT_HAS_PIN;
803
804         if (entry->flags & EXEC_OBJECT_NEEDS_FENCE) {
805                 ret = i915_vma_get_fence(vma);
806                 if (ret)
807                         return ret;
808
809                 if (i915_vma_pin_fence(vma))
810                         entry->flags |= __EXEC_OBJECT_HAS_FENCE;
811         }
812
813         if (entry->offset != vma->node.start) {
814                 entry->offset = vma->node.start;
815                 *need_reloc = true;
816         }
817
818         if (entry->flags & EXEC_OBJECT_WRITE) {
819                 obj->base.pending_read_domains = I915_GEM_DOMAIN_RENDER;
820                 obj->base.pending_write_domain = I915_GEM_DOMAIN_RENDER;
821         }
822
823         return 0;
824 }
825
826 static bool
827 need_reloc_mappable(struct i915_vma *vma)
828 {
829         struct drm_i915_gem_exec_object2 *entry = vma->exec_entry;
830
831         if (entry->relocation_count == 0)
832                 return false;
833
834         if (!i915_vma_is_ggtt(vma))
835                 return false;
836
837         /* See also use_cpu_reloc() */
838         if (HAS_LLC(to_i915(vma->obj->base.dev)))
839                 return false;
840
841         if (vma->obj->base.write_domain == I915_GEM_DOMAIN_CPU)
842                 return false;
843
844         return true;
845 }
846
847 static bool
848 eb_vma_misplaced(struct i915_vma *vma)
849 {
850         struct drm_i915_gem_exec_object2 *entry = vma->exec_entry;
851
852         WARN_ON(entry->flags & __EXEC_OBJECT_NEEDS_MAP &&
853                 !i915_vma_is_ggtt(vma));
854
855         if (entry->alignment && !IS_ALIGNED(vma->node.start, entry->alignment))
856                 return true;
857
858         if (vma->node.size < entry->pad_to_size)
859                 return true;
860
861         if (entry->flags & EXEC_OBJECT_PINNED &&
862             vma->node.start != entry->offset)
863                 return true;
864
865         if (entry->flags & __EXEC_OBJECT_NEEDS_BIAS &&
866             vma->node.start < BATCH_OFFSET_BIAS)
867                 return true;
868
869         /* avoid costly ping-pong once a batch bo ended up non-mappable */
870         if (entry->flags & __EXEC_OBJECT_NEEDS_MAP &&
871             !i915_vma_is_map_and_fenceable(vma))
872                 return !only_mappable_for_reloc(entry->flags);
873
874         if ((entry->flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS) == 0 &&
875             (vma->node.start + vma->node.size - 1) >> 32)
876                 return true;
877
878         return false;
879 }
880
881 static int
882 i915_gem_execbuffer_reserve(struct intel_engine_cs *engine,
883                             struct list_head *vmas,
884                             struct i915_gem_context *ctx,
885                             bool *need_relocs)
886 {
887         struct drm_i915_gem_object *obj;
888         struct i915_vma *vma;
889         struct i915_address_space *vm;
890         struct list_head ordered_vmas;
891         struct list_head pinned_vmas;
892         bool has_fenced_gpu_access = INTEL_GEN(engine->i915) < 4;
893         int retry;
894
895         vm = list_first_entry(vmas, struct i915_vma, exec_list)->vm;
896
897         INIT_LIST_HEAD(&ordered_vmas);
898         INIT_LIST_HEAD(&pinned_vmas);
899         while (!list_empty(vmas)) {
900                 struct drm_i915_gem_exec_object2 *entry;
901                 bool need_fence, need_mappable;
902
903                 vma = list_first_entry(vmas, struct i915_vma, exec_list);
904                 obj = vma->obj;
905                 entry = vma->exec_entry;
906
907                 if (ctx->flags & CONTEXT_NO_ZEROMAP)
908                         entry->flags |= __EXEC_OBJECT_NEEDS_BIAS;
909
910                 if (!has_fenced_gpu_access)
911                         entry->flags &= ~EXEC_OBJECT_NEEDS_FENCE;
912                 need_fence =
913                         entry->flags & EXEC_OBJECT_NEEDS_FENCE &&
914                         i915_gem_object_is_tiled(obj);
915                 need_mappable = need_fence || need_reloc_mappable(vma);
916
917                 if (entry->flags & EXEC_OBJECT_PINNED)
918                         list_move_tail(&vma->exec_list, &pinned_vmas);
919                 else if (need_mappable) {
920                         entry->flags |= __EXEC_OBJECT_NEEDS_MAP;
921                         list_move(&vma->exec_list, &ordered_vmas);
922                 } else
923                         list_move_tail(&vma->exec_list, &ordered_vmas);
924
925                 obj->base.pending_read_domains = I915_GEM_GPU_DOMAINS & ~I915_GEM_DOMAIN_COMMAND;
926                 obj->base.pending_write_domain = 0;
927         }
928         list_splice(&ordered_vmas, vmas);
929         list_splice(&pinned_vmas, vmas);
930
931         /* Attempt to pin all of the buffers into the GTT.
932          * This is done in 3 phases:
933          *
934          * 1a. Unbind all objects that do not match the GTT constraints for
935          *     the execbuffer (fenceable, mappable, alignment etc).
936          * 1b. Increment pin count for already bound objects.
937          * 2.  Bind new objects.
938          * 3.  Decrement pin count.
939          *
940          * This avoid unnecessary unbinding of later objects in order to make
941          * room for the earlier objects *unless* we need to defragment.
942          */
943         retry = 0;
944         do {
945                 int ret = 0;
946
947                 /* Unbind any ill-fitting objects or pin. */
948                 list_for_each_entry(vma, vmas, exec_list) {
949                         if (!drm_mm_node_allocated(&vma->node))
950                                 continue;
951
952                         if (eb_vma_misplaced(vma))
953                                 ret = i915_vma_unbind(vma);
954                         else
955                                 ret = i915_gem_execbuffer_reserve_vma(vma,
956                                                                       engine,
957                                                                       need_relocs);
958                         if (ret)
959                                 goto err;
960                 }
961
962                 /* Bind fresh objects */
963                 list_for_each_entry(vma, vmas, exec_list) {
964                         if (drm_mm_node_allocated(&vma->node))
965                                 continue;
966
967                         ret = i915_gem_execbuffer_reserve_vma(vma, engine,
968                                                               need_relocs);
969                         if (ret)
970                                 goto err;
971                 }
972
973 err:
974                 if (ret != -ENOSPC || retry++)
975                         return ret;
976
977                 /* Decrement pin count for bound objects */
978                 list_for_each_entry(vma, vmas, exec_list)
979                         i915_gem_execbuffer_unreserve_vma(vma);
980
981                 ret = i915_gem_evict_vm(vm, true);
982                 if (ret)
983                         return ret;
984         } while (1);
985 }
986
987 static int
988 i915_gem_execbuffer_relocate_slow(struct drm_device *dev,
989                                   struct drm_i915_gem_execbuffer2 *args,
990                                   struct drm_file *file,
991                                   struct intel_engine_cs *engine,
992                                   struct eb_vmas *eb,
993                                   struct drm_i915_gem_exec_object2 *exec,
994                                   struct i915_gem_context *ctx)
995 {
996         struct drm_i915_gem_relocation_entry *reloc;
997         struct i915_address_space *vm;
998         struct i915_vma *vma;
999         bool need_relocs;
1000         int *reloc_offset;
1001         int i, total, ret;
1002         unsigned count = args->buffer_count;
1003
1004         vm = list_first_entry(&eb->vmas, struct i915_vma, exec_list)->vm;
1005
1006         /* We may process another execbuffer during the unlock... */
1007         while (!list_empty(&eb->vmas)) {
1008                 vma = list_first_entry(&eb->vmas, struct i915_vma, exec_list);
1009                 list_del_init(&vma->exec_list);
1010                 i915_gem_execbuffer_unreserve_vma(vma);
1011                 i915_vma_put(vma);
1012         }
1013
1014         mutex_unlock(&dev->struct_mutex);
1015
1016         total = 0;
1017         for (i = 0; i < count; i++)
1018                 total += exec[i].relocation_count;
1019
1020         reloc_offset = drm_malloc_ab(count, sizeof(*reloc_offset));
1021         reloc = drm_malloc_ab(total, sizeof(*reloc));
1022         if (reloc == NULL || reloc_offset == NULL) {
1023                 drm_free_large(reloc);
1024                 drm_free_large(reloc_offset);
1025                 mutex_lock(&dev->struct_mutex);
1026                 return -ENOMEM;
1027         }
1028
1029         total = 0;
1030         for (i = 0; i < count; i++) {
1031                 struct drm_i915_gem_relocation_entry __user *user_relocs;
1032                 u64 invalid_offset = (u64)-1;
1033                 int j;
1034
1035                 user_relocs = u64_to_user_ptr(exec[i].relocs_ptr);
1036
1037                 if (copy_from_user(reloc+total, user_relocs,
1038                                    exec[i].relocation_count * sizeof(*reloc))) {
1039                         ret = -EFAULT;
1040                         mutex_lock(&dev->struct_mutex);
1041                         goto err;
1042                 }
1043
1044                 /* As we do not update the known relocation offsets after
1045                  * relocating (due to the complexities in lock handling),
1046                  * we need to mark them as invalid now so that we force the
1047                  * relocation processing next time. Just in case the target
1048                  * object is evicted and then rebound into its old
1049                  * presumed_offset before the next execbuffer - if that
1050                  * happened we would make the mistake of assuming that the
1051                  * relocations were valid.
1052                  */
1053                 for (j = 0; j < exec[i].relocation_count; j++) {
1054                         if (__copy_to_user(&user_relocs[j].presumed_offset,
1055                                            &invalid_offset,
1056                                            sizeof(invalid_offset))) {
1057                                 ret = -EFAULT;
1058                                 mutex_lock(&dev->struct_mutex);
1059                                 goto err;
1060                         }
1061                 }
1062
1063                 reloc_offset[i] = total;
1064                 total += exec[i].relocation_count;
1065         }
1066
1067         ret = i915_mutex_lock_interruptible(dev);
1068         if (ret) {
1069                 mutex_lock(&dev->struct_mutex);
1070                 goto err;
1071         }
1072
1073         /* reacquire the objects */
1074         eb_reset(eb);
1075         ret = eb_lookup_vmas(eb, exec, args, vm, file);
1076         if (ret)
1077                 goto err;
1078
1079         need_relocs = (args->flags & I915_EXEC_NO_RELOC) == 0;
1080         ret = i915_gem_execbuffer_reserve(engine, &eb->vmas, ctx,
1081                                           &need_relocs);
1082         if (ret)
1083                 goto err;
1084
1085         list_for_each_entry(vma, &eb->vmas, exec_list) {
1086                 int offset = vma->exec_entry - exec;
1087                 ret = i915_gem_execbuffer_relocate_vma_slow(vma, eb,
1088                                                             reloc + reloc_offset[offset]);
1089                 if (ret)
1090                         goto err;
1091         }
1092
1093         /* Leave the user relocations as are, this is the painfully slow path,
1094          * and we want to avoid the complication of dropping the lock whilst
1095          * having buffers reserved in the aperture and so causing spurious
1096          * ENOSPC for random operations.
1097          */
1098
1099 err:
1100         drm_free_large(reloc);
1101         drm_free_large(reloc_offset);
1102         return ret;
1103 }
1104
1105 static int
1106 i915_gem_execbuffer_move_to_gpu(struct drm_i915_gem_request *req,
1107                                 struct list_head *vmas)
1108 {
1109         struct i915_vma *vma;
1110         int ret;
1111
1112         list_for_each_entry(vma, vmas, exec_list) {
1113                 struct drm_i915_gem_object *obj = vma->obj;
1114
1115                 if (vma->exec_entry->flags & EXEC_OBJECT_ASYNC)
1116                         continue;
1117
1118                 if (obj->base.write_domain & I915_GEM_DOMAIN_CPU) {
1119                         i915_gem_clflush_object(obj, 0);
1120                         obj->base.write_domain = 0;
1121                 }
1122
1123                 ret = i915_gem_request_await_object
1124                         (req, obj, obj->base.pending_write_domain);
1125                 if (ret)
1126                         return ret;
1127         }
1128
1129         /* Unconditionally flush any chipset caches (for streaming writes). */
1130         i915_gem_chipset_flush(req->engine->i915);
1131
1132         /* Unconditionally invalidate GPU caches and TLBs. */
1133         return req->engine->emit_flush(req, EMIT_INVALIDATE);
1134 }
1135
1136 static bool
1137 i915_gem_check_execbuffer(struct drm_i915_gem_execbuffer2 *exec)
1138 {
1139         if (exec->flags & __I915_EXEC_UNKNOWN_FLAGS)
1140                 return false;
1141
1142         /* Kernel clipping was a DRI1 misfeature */
1143         if (exec->num_cliprects || exec->cliprects_ptr)
1144                 return false;
1145
1146         if (exec->DR4 == 0xffffffff) {
1147                 DRM_DEBUG("UXA submitting garbage DR4, fixing up\n");
1148                 exec->DR4 = 0;
1149         }
1150         if (exec->DR1 || exec->DR4)
1151                 return false;
1152
1153         if ((exec->batch_start_offset | exec->batch_len) & 0x7)
1154                 return false;
1155
1156         return true;
1157 }
1158
1159 static int
1160 validate_exec_list(struct drm_device *dev,
1161                    struct drm_i915_gem_exec_object2 *exec,
1162                    int count)
1163 {
1164         unsigned relocs_total = 0;
1165         unsigned relocs_max = UINT_MAX / sizeof(struct drm_i915_gem_relocation_entry);
1166         unsigned invalid_flags;
1167         int i;
1168
1169         /* INTERNAL flags must not overlap with external ones */
1170         BUILD_BUG_ON(__EXEC_OBJECT_INTERNAL_FLAGS & ~__EXEC_OBJECT_UNKNOWN_FLAGS);
1171
1172         invalid_flags = __EXEC_OBJECT_UNKNOWN_FLAGS;
1173         if (USES_FULL_PPGTT(dev))
1174                 invalid_flags |= EXEC_OBJECT_NEEDS_GTT;
1175
1176         for (i = 0; i < count; i++) {
1177                 char __user *ptr = u64_to_user_ptr(exec[i].relocs_ptr);
1178                 int length; /* limited by fault_in_pages_readable() */
1179
1180                 if (exec[i].flags & invalid_flags)
1181                         return -EINVAL;
1182
1183                 /* Offset can be used as input (EXEC_OBJECT_PINNED), reject
1184                  * any non-page-aligned or non-canonical addresses.
1185                  */
1186                 if (exec[i].flags & EXEC_OBJECT_PINNED) {
1187                         if (exec[i].offset !=
1188                             gen8_canonical_addr(exec[i].offset & PAGE_MASK))
1189                                 return -EINVAL;
1190                 }
1191
1192                 /* From drm_mm perspective address space is continuous,
1193                  * so from this point we're always using non-canonical
1194                  * form internally.
1195                  */
1196                 exec[i].offset = gen8_noncanonical_addr(exec[i].offset);
1197
1198                 if (exec[i].alignment && !is_power_of_2(exec[i].alignment))
1199                         return -EINVAL;
1200
1201                 /* pad_to_size was once a reserved field, so sanitize it */
1202                 if (exec[i].flags & EXEC_OBJECT_PAD_TO_SIZE) {
1203                         if (offset_in_page(exec[i].pad_to_size))
1204                                 return -EINVAL;
1205                 } else {
1206                         exec[i].pad_to_size = 0;
1207                 }
1208
1209                 /* First check for malicious input causing overflow in
1210                  * the worst case where we need to allocate the entire
1211                  * relocation tree as a single array.
1212                  */
1213                 if (exec[i].relocation_count > relocs_max - relocs_total)
1214                         return -EINVAL;
1215                 relocs_total += exec[i].relocation_count;
1216
1217                 length = exec[i].relocation_count *
1218                         sizeof(struct drm_i915_gem_relocation_entry);
1219                 /*
1220                  * We must check that the entire relocation array is safe
1221                  * to read, but since we may need to update the presumed
1222                  * offsets during execution, check for full write access.
1223                  */
1224                 if (!access_ok(VERIFY_WRITE, ptr, length))
1225                         return -EFAULT;
1226
1227                 if (likely(!i915.prefault_disable)) {
1228                         if (fault_in_pages_readable(ptr, length))
1229                                 return -EFAULT;
1230                 }
1231         }
1232
1233         return 0;
1234 }
1235
1236 static struct i915_gem_context *
1237 i915_gem_validate_context(struct drm_device *dev, struct drm_file *file,
1238                           struct intel_engine_cs *engine, const u32 ctx_id)
1239 {
1240         struct i915_gem_context *ctx;
1241
1242         ctx = i915_gem_context_lookup(file->driver_priv, ctx_id);
1243         if (IS_ERR(ctx))
1244                 return ctx;
1245
1246         if (i915_gem_context_is_banned(ctx)) {
1247                 DRM_DEBUG("Context %u tried to submit while banned\n", ctx_id);
1248                 return ERR_PTR(-EIO);
1249         }
1250
1251         return ctx;
1252 }
1253
1254 static bool gpu_write_needs_clflush(struct drm_i915_gem_object *obj)
1255 {
1256         return !(obj->cache_level == I915_CACHE_NONE ||
1257                  obj->cache_level == I915_CACHE_WT);
1258 }
1259
1260 void i915_vma_move_to_active(struct i915_vma *vma,
1261                              struct drm_i915_gem_request *req,
1262                              unsigned int flags)
1263 {
1264         struct drm_i915_gem_object *obj = vma->obj;
1265         const unsigned int idx = req->engine->id;
1266
1267         lockdep_assert_held(&req->i915->drm.struct_mutex);
1268         GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
1269
1270         /* Add a reference if we're newly entering the active list.
1271          * The order in which we add operations to the retirement queue is
1272          * vital here: mark_active adds to the start of the callback list,
1273          * such that subsequent callbacks are called first. Therefore we
1274          * add the active reference first and queue for it to be dropped
1275          * *last*.
1276          */
1277         if (!i915_vma_is_active(vma))
1278                 obj->active_count++;
1279         i915_vma_set_active(vma, idx);
1280         i915_gem_active_set(&vma->last_read[idx], req);
1281         list_move_tail(&vma->vm_link, &vma->vm->active_list);
1282
1283         if (flags & EXEC_OBJECT_WRITE) {
1284                 if (intel_fb_obj_invalidate(obj, ORIGIN_CS))
1285                         i915_gem_active_set(&obj->frontbuffer_write, req);
1286
1287                 /* update for the implicit flush after a batch */
1288                 obj->base.write_domain &= ~I915_GEM_GPU_DOMAINS;
1289                 if (!obj->cache_dirty && gpu_write_needs_clflush(obj))
1290                         obj->cache_dirty = true;
1291         }
1292
1293         if (flags & EXEC_OBJECT_NEEDS_FENCE)
1294                 i915_gem_active_set(&vma->last_fence, req);
1295 }
1296
1297 static void eb_export_fence(struct drm_i915_gem_object *obj,
1298                             struct drm_i915_gem_request *req,
1299                             unsigned int flags)
1300 {
1301         struct reservation_object *resv = obj->resv;
1302
1303         /* Ignore errors from failing to allocate the new fence, we can't
1304          * handle an error right now. Worst case should be missed
1305          * synchronisation leading to rendering corruption.
1306          */
1307         reservation_object_lock(resv, NULL);
1308         if (flags & EXEC_OBJECT_WRITE)
1309                 reservation_object_add_excl_fence(resv, &req->fence);
1310         else if (reservation_object_reserve_shared(resv) == 0)
1311                 reservation_object_add_shared_fence(resv, &req->fence);
1312         reservation_object_unlock(resv);
1313 }
1314
1315 static void
1316 i915_gem_execbuffer_move_to_active(struct list_head *vmas,
1317                                    struct drm_i915_gem_request *req)
1318 {
1319         struct i915_vma *vma;
1320
1321         list_for_each_entry(vma, vmas, exec_list) {
1322                 struct drm_i915_gem_object *obj = vma->obj;
1323
1324                 obj->base.write_domain = obj->base.pending_write_domain;
1325                 if (obj->base.write_domain)
1326                         vma->exec_entry->flags |= EXEC_OBJECT_WRITE;
1327                 else
1328                         obj->base.pending_read_domains |= obj->base.read_domains;
1329                 obj->base.read_domains = obj->base.pending_read_domains;
1330
1331                 i915_vma_move_to_active(vma, req, vma->exec_entry->flags);
1332                 eb_export_fence(obj, req, vma->exec_entry->flags);
1333         }
1334 }
1335
1336 static int
1337 i915_reset_gen7_sol_offsets(struct drm_i915_gem_request *req)
1338 {
1339         u32 *cs;
1340         int i;
1341
1342         if (!IS_GEN7(req->i915) || req->engine->id != RCS) {
1343                 DRM_DEBUG("sol reset is gen7/rcs only\n");
1344                 return -EINVAL;
1345         }
1346
1347         cs = intel_ring_begin(req, 4 * 3);
1348         if (IS_ERR(cs))
1349                 return PTR_ERR(cs);
1350
1351         for (i = 0; i < 4; i++) {
1352                 *cs++ = MI_LOAD_REGISTER_IMM(1);
1353                 *cs++ = i915_mmio_reg_offset(GEN7_SO_WRITE_OFFSET(i));
1354                 *cs++ = 0;
1355         }
1356
1357         intel_ring_advance(req, cs);
1358
1359         return 0;
1360 }
1361
1362 static struct i915_vma *
1363 i915_gem_execbuffer_parse(struct intel_engine_cs *engine,
1364                           struct drm_i915_gem_exec_object2 *shadow_exec_entry,
1365                           struct drm_i915_gem_object *batch_obj,
1366                           struct eb_vmas *eb,
1367                           u32 batch_start_offset,
1368                           u32 batch_len,
1369                           bool is_master)
1370 {
1371         struct drm_i915_gem_object *shadow_batch_obj;
1372         struct i915_vma *vma;
1373         int ret;
1374
1375         shadow_batch_obj = i915_gem_batch_pool_get(&engine->batch_pool,
1376                                                    PAGE_ALIGN(batch_len));
1377         if (IS_ERR(shadow_batch_obj))
1378                 return ERR_CAST(shadow_batch_obj);
1379
1380         ret = intel_engine_cmd_parser(engine,
1381                                       batch_obj,
1382                                       shadow_batch_obj,
1383                                       batch_start_offset,
1384                                       batch_len,
1385                                       is_master);
1386         if (ret) {
1387                 if (ret == -EACCES) /* unhandled chained batch */
1388                         vma = NULL;
1389                 else
1390                         vma = ERR_PTR(ret);
1391                 goto out;
1392         }
1393
1394         vma = i915_gem_object_ggtt_pin(shadow_batch_obj, NULL, 0, 0, 0);
1395         if (IS_ERR(vma))
1396                 goto out;
1397
1398         memset(shadow_exec_entry, 0, sizeof(*shadow_exec_entry));
1399
1400         vma->exec_entry = shadow_exec_entry;
1401         vma->exec_entry->flags = __EXEC_OBJECT_HAS_PIN;
1402         i915_gem_object_get(shadow_batch_obj);
1403         list_add_tail(&vma->exec_list, &eb->vmas);
1404
1405 out:
1406         i915_gem_object_unpin_pages(shadow_batch_obj);
1407         return vma;
1408 }
1409
1410 static void
1411 add_to_client(struct drm_i915_gem_request *req,
1412               struct drm_file *file)
1413 {
1414         req->file_priv = file->driver_priv;
1415         list_add_tail(&req->client_link, &req->file_priv->mm.request_list);
1416 }
1417
1418 static int
1419 execbuf_submit(struct i915_execbuffer_params *params,
1420                struct drm_i915_gem_execbuffer2 *args,
1421                struct list_head *vmas)
1422 {
1423         u64 exec_start, exec_len;
1424         int ret;
1425
1426         ret = i915_gem_execbuffer_move_to_gpu(params->request, vmas);
1427         if (ret)
1428                 return ret;
1429
1430         ret = i915_switch_context(params->request);
1431         if (ret)
1432                 return ret;
1433
1434         if (args->flags & I915_EXEC_CONSTANTS_MASK) {
1435                 DRM_DEBUG("I915_EXEC_CONSTANTS_* unsupported\n");
1436                 return -EINVAL;
1437         }
1438
1439         if (args->flags & I915_EXEC_GEN7_SOL_RESET) {
1440                 ret = i915_reset_gen7_sol_offsets(params->request);
1441                 if (ret)
1442                         return ret;
1443         }
1444
1445         exec_len   = args->batch_len;
1446         exec_start = params->batch->node.start +
1447                      params->args_batch_start_offset;
1448
1449         if (exec_len == 0)
1450                 exec_len = params->batch->size - params->args_batch_start_offset;
1451
1452         ret = params->engine->emit_bb_start(params->request,
1453                                             exec_start, exec_len,
1454                                             params->dispatch_flags);
1455         if (ret)
1456                 return ret;
1457
1458         i915_gem_execbuffer_move_to_active(vmas, params->request);
1459
1460         return 0;
1461 }
1462
1463 /**
1464  * Find one BSD ring to dispatch the corresponding BSD command.
1465  * The engine index is returned.
1466  */
1467 static unsigned int
1468 gen8_dispatch_bsd_engine(struct drm_i915_private *dev_priv,
1469                          struct drm_file *file)
1470 {
1471         struct drm_i915_file_private *file_priv = file->driver_priv;
1472
1473         /* Check whether the file_priv has already selected one ring. */
1474         if ((int)file_priv->bsd_engine < 0)
1475                 file_priv->bsd_engine = atomic_fetch_xor(1,
1476                          &dev_priv->mm.bsd_engine_dispatch_index);
1477
1478         return file_priv->bsd_engine;
1479 }
1480
1481 #define I915_USER_RINGS (4)
1482
1483 static const enum intel_engine_id user_ring_map[I915_USER_RINGS + 1] = {
1484         [I915_EXEC_DEFAULT]     = RCS,
1485         [I915_EXEC_RENDER]      = RCS,
1486         [I915_EXEC_BLT]         = BCS,
1487         [I915_EXEC_BSD]         = VCS,
1488         [I915_EXEC_VEBOX]       = VECS
1489 };
1490
1491 static struct intel_engine_cs *
1492 eb_select_engine(struct drm_i915_private *dev_priv,
1493                  struct drm_file *file,
1494                  struct drm_i915_gem_execbuffer2 *args)
1495 {
1496         unsigned int user_ring_id = args->flags & I915_EXEC_RING_MASK;
1497         struct intel_engine_cs *engine;
1498
1499         if (user_ring_id > I915_USER_RINGS) {
1500                 DRM_DEBUG("execbuf with unknown ring: %u\n", user_ring_id);
1501                 return NULL;
1502         }
1503
1504         if ((user_ring_id != I915_EXEC_BSD) &&
1505             ((args->flags & I915_EXEC_BSD_MASK) != 0)) {
1506                 DRM_DEBUG("execbuf with non bsd ring but with invalid "
1507                           "bsd dispatch flags: %d\n", (int)(args->flags));
1508                 return NULL;
1509         }
1510
1511         if (user_ring_id == I915_EXEC_BSD && HAS_BSD2(dev_priv)) {
1512                 unsigned int bsd_idx = args->flags & I915_EXEC_BSD_MASK;
1513
1514                 if (bsd_idx == I915_EXEC_BSD_DEFAULT) {
1515                         bsd_idx = gen8_dispatch_bsd_engine(dev_priv, file);
1516                 } else if (bsd_idx >= I915_EXEC_BSD_RING1 &&
1517                            bsd_idx <= I915_EXEC_BSD_RING2) {
1518                         bsd_idx >>= I915_EXEC_BSD_SHIFT;
1519                         bsd_idx--;
1520                 } else {
1521                         DRM_DEBUG("execbuf with unknown bsd ring: %u\n",
1522                                   bsd_idx);
1523                         return NULL;
1524                 }
1525
1526                 engine = dev_priv->engine[_VCS(bsd_idx)];
1527         } else {
1528                 engine = dev_priv->engine[user_ring_map[user_ring_id]];
1529         }
1530
1531         if (!engine) {
1532                 DRM_DEBUG("execbuf with invalid ring: %u\n", user_ring_id);
1533                 return NULL;
1534         }
1535
1536         return engine;
1537 }
1538
1539 static int
1540 i915_gem_do_execbuffer(struct drm_device *dev, void *data,
1541                        struct drm_file *file,
1542                        struct drm_i915_gem_execbuffer2 *args,
1543                        struct drm_i915_gem_exec_object2 *exec)
1544 {
1545         struct drm_i915_private *dev_priv = to_i915(dev);
1546         struct i915_ggtt *ggtt = &dev_priv->ggtt;
1547         struct eb_vmas *eb;
1548         struct drm_i915_gem_exec_object2 shadow_exec_entry;
1549         struct intel_engine_cs *engine;
1550         struct i915_gem_context *ctx;
1551         struct i915_address_space *vm;
1552         struct i915_execbuffer_params params_master; /* XXX: will be removed later */
1553         struct i915_execbuffer_params *params = &params_master;
1554         const u32 ctx_id = i915_execbuffer2_get_context_id(*args);
1555         u32 dispatch_flags;
1556         struct dma_fence *in_fence = NULL;
1557         struct sync_file *out_fence = NULL;
1558         int out_fence_fd = -1;
1559         int ret;
1560         bool need_relocs;
1561
1562         if (!i915_gem_check_execbuffer(args))
1563                 return -EINVAL;
1564
1565         ret = validate_exec_list(dev, exec, args->buffer_count);
1566         if (ret)
1567                 return ret;
1568
1569         dispatch_flags = 0;
1570         if (args->flags & I915_EXEC_SECURE) {
1571                 if (!drm_is_current_master(file) || !capable(CAP_SYS_ADMIN))
1572                     return -EPERM;
1573
1574                 dispatch_flags |= I915_DISPATCH_SECURE;
1575         }
1576         if (args->flags & I915_EXEC_IS_PINNED)
1577                 dispatch_flags |= I915_DISPATCH_PINNED;
1578
1579         engine = eb_select_engine(dev_priv, file, args);
1580         if (!engine)
1581                 return -EINVAL;
1582
1583         if (args->buffer_count < 1) {
1584                 DRM_DEBUG("execbuf with %d buffers\n", args->buffer_count);
1585                 return -EINVAL;
1586         }
1587
1588         if (args->flags & I915_EXEC_RESOURCE_STREAMER) {
1589                 if (!HAS_RESOURCE_STREAMER(dev_priv)) {
1590                         DRM_DEBUG("RS is only allowed for Haswell, Gen8 and above\n");
1591                         return -EINVAL;
1592                 }
1593                 if (engine->id != RCS) {
1594                         DRM_DEBUG("RS is not available on %s\n",
1595                                  engine->name);
1596                         return -EINVAL;
1597                 }
1598
1599                 dispatch_flags |= I915_DISPATCH_RS;
1600         }
1601
1602         if (args->flags & I915_EXEC_FENCE_IN) {
1603                 in_fence = sync_file_get_fence(lower_32_bits(args->rsvd2));
1604                 if (!in_fence)
1605                         return -EINVAL;
1606         }
1607
1608         if (args->flags & I915_EXEC_FENCE_OUT) {
1609                 out_fence_fd = get_unused_fd_flags(O_CLOEXEC);
1610                 if (out_fence_fd < 0) {
1611                         ret = out_fence_fd;
1612                         goto err_in_fence;
1613                 }
1614         }
1615
1616         /* Take a local wakeref for preparing to dispatch the execbuf as
1617          * we expect to access the hardware fairly frequently in the
1618          * process. Upon first dispatch, we acquire another prolonged
1619          * wakeref that we hold until the GPU has been idle for at least
1620          * 100ms.
1621          */
1622         intel_runtime_pm_get(dev_priv);
1623
1624         ret = i915_mutex_lock_interruptible(dev);
1625         if (ret)
1626                 goto pre_mutex_err;
1627
1628         ctx = i915_gem_validate_context(dev, file, engine, ctx_id);
1629         if (IS_ERR(ctx)) {
1630                 mutex_unlock(&dev->struct_mutex);
1631                 ret = PTR_ERR(ctx);
1632                 goto pre_mutex_err;
1633         }
1634
1635         i915_gem_context_get(ctx);
1636
1637         if (ctx->ppgtt)
1638                 vm = &ctx->ppgtt->base;
1639         else
1640                 vm = &ggtt->base;
1641
1642         memset(&params_master, 0x00, sizeof(params_master));
1643
1644         eb = eb_create(dev_priv, args);
1645         if (eb == NULL) {
1646                 i915_gem_context_put(ctx);
1647                 mutex_unlock(&dev->struct_mutex);
1648                 ret = -ENOMEM;
1649                 goto pre_mutex_err;
1650         }
1651
1652         /* Look up object handles */
1653         ret = eb_lookup_vmas(eb, exec, args, vm, file);
1654         if (ret)
1655                 goto err;
1656
1657         /* take note of the batch buffer before we might reorder the lists */
1658         params->batch = eb_get_batch(eb);
1659
1660         /* Move the objects en-masse into the GTT, evicting if necessary. */
1661         need_relocs = (args->flags & I915_EXEC_NO_RELOC) == 0;
1662         ret = i915_gem_execbuffer_reserve(engine, &eb->vmas, ctx,
1663                                           &need_relocs);
1664         if (ret)
1665                 goto err;
1666
1667         /* The objects are in their final locations, apply the relocations. */
1668         if (need_relocs)
1669                 ret = i915_gem_execbuffer_relocate(eb);
1670         if (ret) {
1671                 if (ret == -EFAULT) {
1672                         ret = i915_gem_execbuffer_relocate_slow(dev, args, file,
1673                                                                 engine,
1674                                                                 eb, exec, ctx);
1675                         BUG_ON(!mutex_is_locked(&dev->struct_mutex));
1676                 }
1677                 if (ret)
1678                         goto err;
1679         }
1680
1681         /* Set the pending read domains for the batch buffer to COMMAND */
1682         if (params->batch->obj->base.pending_write_domain) {
1683                 DRM_DEBUG("Attempting to use self-modifying batch buffer\n");
1684                 ret = -EINVAL;
1685                 goto err;
1686         }
1687         if (args->batch_start_offset > params->batch->size ||
1688             args->batch_len > params->batch->size - args->batch_start_offset) {
1689                 DRM_DEBUG("Attempting to use out-of-bounds batch\n");
1690                 ret = -EINVAL;
1691                 goto err;
1692         }
1693
1694         params->args_batch_start_offset = args->batch_start_offset;
1695         if (engine->needs_cmd_parser && args->batch_len) {
1696                 struct i915_vma *vma;
1697
1698                 vma = i915_gem_execbuffer_parse(engine, &shadow_exec_entry,
1699                                                 params->batch->obj,
1700                                                 eb,
1701                                                 args->batch_start_offset,
1702                                                 args->batch_len,
1703                                                 drm_is_current_master(file));
1704                 if (IS_ERR(vma)) {
1705                         ret = PTR_ERR(vma);
1706                         goto err;
1707                 }
1708
1709                 if (vma) {
1710                         /*
1711                          * Batch parsed and accepted:
1712                          *
1713                          * Set the DISPATCH_SECURE bit to remove the NON_SECURE
1714                          * bit from MI_BATCH_BUFFER_START commands issued in
1715                          * the dispatch_execbuffer implementations. We
1716                          * specifically don't want that set on batches the
1717                          * command parser has accepted.
1718                          */
1719                         dispatch_flags |= I915_DISPATCH_SECURE;
1720                         params->args_batch_start_offset = 0;
1721                         params->batch = vma;
1722                 }
1723         }
1724
1725         params->batch->obj->base.pending_read_domains |= I915_GEM_DOMAIN_COMMAND;
1726
1727         /* snb/ivb/vlv conflate the "batch in ppgtt" bit with the "non-secure
1728          * batch" bit. Hence we need to pin secure batches into the global gtt.
1729          * hsw should have this fixed, but bdw mucks it up again. */
1730         if (dispatch_flags & I915_DISPATCH_SECURE) {
1731                 struct drm_i915_gem_object *obj = params->batch->obj;
1732                 struct i915_vma *vma;
1733
1734                 /*
1735                  * So on first glance it looks freaky that we pin the batch here
1736                  * outside of the reservation loop. But:
1737                  * - The batch is already pinned into the relevant ppgtt, so we
1738                  *   already have the backing storage fully allocated.
1739                  * - No other BO uses the global gtt (well contexts, but meh),
1740                  *   so we don't really have issues with multiple objects not
1741                  *   fitting due to fragmentation.
1742                  * So this is actually safe.
1743                  */
1744                 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0, 0);
1745                 if (IS_ERR(vma)) {
1746                         ret = PTR_ERR(vma);
1747                         goto err;
1748                 }
1749
1750                 params->batch = vma;
1751         }
1752
1753         /* Allocate a request for this batch buffer nice and early. */
1754         params->request = i915_gem_request_alloc(engine, ctx);
1755         if (IS_ERR(params->request)) {
1756                 ret = PTR_ERR(params->request);
1757                 goto err_batch_unpin;
1758         }
1759
1760         if (in_fence) {
1761                 ret = i915_gem_request_await_dma_fence(params->request,
1762                                                        in_fence);
1763                 if (ret < 0)
1764                         goto err_request;
1765         }
1766
1767         if (out_fence_fd != -1) {
1768                 out_fence = sync_file_create(&params->request->fence);
1769                 if (!out_fence) {
1770                         ret = -ENOMEM;
1771                         goto err_request;
1772                 }
1773         }
1774
1775         /* Whilst this request exists, batch_obj will be on the
1776          * active_list, and so will hold the active reference. Only when this
1777          * request is retired will the the batch_obj be moved onto the
1778          * inactive_list and lose its active reference. Hence we do not need
1779          * to explicitly hold another reference here.
1780          */
1781         params->request->batch = params->batch;
1782
1783         /*
1784          * Save assorted stuff away to pass through to *_submission().
1785          * NB: This data should be 'persistent' and not local as it will
1786          * kept around beyond the duration of the IOCTL once the GPU
1787          * scheduler arrives.
1788          */
1789         params->dev                     = dev;
1790         params->file                    = file;
1791         params->engine                    = engine;
1792         params->dispatch_flags          = dispatch_flags;
1793         params->ctx                     = ctx;
1794
1795         trace_i915_gem_request_queue(params->request, dispatch_flags);
1796
1797         ret = execbuf_submit(params, args, &eb->vmas);
1798 err_request:
1799         __i915_add_request(params->request, ret == 0);
1800         add_to_client(params->request, file);
1801
1802         if (out_fence) {
1803                 if (ret == 0) {
1804                         fd_install(out_fence_fd, out_fence->file);
1805                         args->rsvd2 &= GENMASK_ULL(0, 31); /* keep in-fence */
1806                         args->rsvd2 |= (u64)out_fence_fd << 32;
1807                         out_fence_fd = -1;
1808                 } else {
1809                         fput(out_fence->file);
1810                 }
1811         }
1812
1813 err_batch_unpin:
1814         /*
1815          * FIXME: We crucially rely upon the active tracking for the (ppgtt)
1816          * batch vma for correctness. For less ugly and less fragility this
1817          * needs to be adjusted to also track the ggtt batch vma properly as
1818          * active.
1819          */
1820         if (dispatch_flags & I915_DISPATCH_SECURE)
1821                 i915_vma_unpin(params->batch);
1822 err:
1823         /* the request owns the ref now */
1824         i915_gem_context_put(ctx);
1825         eb_destroy(eb);
1826
1827         mutex_unlock(&dev->struct_mutex);
1828
1829 pre_mutex_err:
1830         /* intel_gpu_busy should also get a ref, so it will free when the device
1831          * is really idle. */
1832         intel_runtime_pm_put(dev_priv);
1833         if (out_fence_fd != -1)
1834                 put_unused_fd(out_fence_fd);
1835 err_in_fence:
1836         dma_fence_put(in_fence);
1837         return ret;
1838 }
1839
1840 /*
1841  * Legacy execbuffer just creates an exec2 list from the original exec object
1842  * list array and passes it to the real function.
1843  */
1844 int
1845 i915_gem_execbuffer(struct drm_device *dev, void *data,
1846                     struct drm_file *file)
1847 {
1848         struct drm_i915_gem_execbuffer *args = data;
1849         struct drm_i915_gem_execbuffer2 exec2;
1850         struct drm_i915_gem_exec_object *exec_list = NULL;
1851         struct drm_i915_gem_exec_object2 *exec2_list = NULL;
1852         int ret, i;
1853
1854         if (args->buffer_count < 1) {
1855                 DRM_DEBUG("execbuf with %d buffers\n", args->buffer_count);
1856                 return -EINVAL;
1857         }
1858
1859         /* Copy in the exec list from userland */
1860         exec_list = drm_malloc_ab(sizeof(*exec_list), args->buffer_count);
1861         exec2_list = drm_malloc_ab(sizeof(*exec2_list), args->buffer_count);
1862         if (exec_list == NULL || exec2_list == NULL) {
1863                 DRM_DEBUG("Failed to allocate exec list for %d buffers\n",
1864                           args->buffer_count);
1865                 drm_free_large(exec_list);
1866                 drm_free_large(exec2_list);
1867                 return -ENOMEM;
1868         }
1869         ret = copy_from_user(exec_list,
1870                              u64_to_user_ptr(args->buffers_ptr),
1871                              sizeof(*exec_list) * args->buffer_count);
1872         if (ret != 0) {
1873                 DRM_DEBUG("copy %d exec entries failed %d\n",
1874                           args->buffer_count, ret);
1875                 drm_free_large(exec_list);
1876                 drm_free_large(exec2_list);
1877                 return -EFAULT;
1878         }
1879
1880         for (i = 0; i < args->buffer_count; i++) {
1881                 exec2_list[i].handle = exec_list[i].handle;
1882                 exec2_list[i].relocation_count = exec_list[i].relocation_count;
1883                 exec2_list[i].relocs_ptr = exec_list[i].relocs_ptr;
1884                 exec2_list[i].alignment = exec_list[i].alignment;
1885                 exec2_list[i].offset = exec_list[i].offset;
1886                 if (INTEL_GEN(to_i915(dev)) < 4)
1887                         exec2_list[i].flags = EXEC_OBJECT_NEEDS_FENCE;
1888                 else
1889                         exec2_list[i].flags = 0;
1890         }
1891
1892         exec2.buffers_ptr = args->buffers_ptr;
1893         exec2.buffer_count = args->buffer_count;
1894         exec2.batch_start_offset = args->batch_start_offset;
1895         exec2.batch_len = args->batch_len;
1896         exec2.DR1 = args->DR1;
1897         exec2.DR4 = args->DR4;
1898         exec2.num_cliprects = args->num_cliprects;
1899         exec2.cliprects_ptr = args->cliprects_ptr;
1900         exec2.flags = I915_EXEC_RENDER;
1901         i915_execbuffer2_set_context_id(exec2, 0);
1902
1903         ret = i915_gem_do_execbuffer(dev, data, file, &exec2, exec2_list);
1904         if (!ret) {
1905                 struct drm_i915_gem_exec_object __user *user_exec_list =
1906                         u64_to_user_ptr(args->buffers_ptr);
1907
1908                 /* Copy the new buffer offsets back to the user's exec list. */
1909                 for (i = 0; i < args->buffer_count; i++) {
1910                         exec2_list[i].offset =
1911                                 gen8_canonical_addr(exec2_list[i].offset);
1912                         ret = __copy_to_user(&user_exec_list[i].offset,
1913                                              &exec2_list[i].offset,
1914                                              sizeof(user_exec_list[i].offset));
1915                         if (ret) {
1916                                 ret = -EFAULT;
1917                                 DRM_DEBUG("failed to copy %d exec entries "
1918                                           "back to user (%d)\n",
1919                                           args->buffer_count, ret);
1920                                 break;
1921                         }
1922                 }
1923         }
1924
1925         drm_free_large(exec_list);
1926         drm_free_large(exec2_list);
1927         return ret;
1928 }
1929
1930 int
1931 i915_gem_execbuffer2(struct drm_device *dev, void *data,
1932                      struct drm_file *file)
1933 {
1934         struct drm_i915_gem_execbuffer2 *args = data;
1935         struct drm_i915_gem_exec_object2 *exec2_list = NULL;
1936         int ret;
1937
1938         if (args->buffer_count < 1 ||
1939             args->buffer_count > UINT_MAX / sizeof(*exec2_list)) {
1940                 DRM_DEBUG("execbuf2 with %d buffers\n", args->buffer_count);
1941                 return -EINVAL;
1942         }
1943
1944         exec2_list = drm_malloc_gfp(args->buffer_count,
1945                                     sizeof(*exec2_list),
1946                                     GFP_TEMPORARY);
1947         if (exec2_list == NULL) {
1948                 DRM_DEBUG("Failed to allocate exec list for %d buffers\n",
1949                           args->buffer_count);
1950                 return -ENOMEM;
1951         }
1952         ret = copy_from_user(exec2_list,
1953                              u64_to_user_ptr(args->buffers_ptr),
1954                              sizeof(*exec2_list) * args->buffer_count);
1955         if (ret != 0) {
1956                 DRM_DEBUG("copy %d exec entries failed %d\n",
1957                           args->buffer_count, ret);
1958                 drm_free_large(exec2_list);
1959                 return -EFAULT;
1960         }
1961
1962         ret = i915_gem_do_execbuffer(dev, data, file, args, exec2_list);
1963         if (!ret) {
1964                 /* Copy the new buffer offsets back to the user's exec list. */
1965                 struct drm_i915_gem_exec_object2 __user *user_exec_list =
1966                                    u64_to_user_ptr(args->buffers_ptr);
1967                 int i;
1968
1969                 for (i = 0; i < args->buffer_count; i++) {
1970                         exec2_list[i].offset =
1971                                 gen8_canonical_addr(exec2_list[i].offset);
1972                         ret = __copy_to_user(&user_exec_list[i].offset,
1973                                              &exec2_list[i].offset,
1974                                              sizeof(user_exec_list[i].offset));
1975                         if (ret) {
1976                                 ret = -EFAULT;
1977                                 DRM_DEBUG("failed to copy %d exec entries "
1978                                           "back to user\n",
1979                                           args->buffer_count);
1980                                 break;
1981                         }
1982                 }
1983         }
1984
1985         drm_free_large(exec2_list);
1986         return ret;
1987 }