]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/gpu/drm/i915/i915_gem_execbuffer.c
986eb98f0d253c8f13d23a236e50b323a7e90bc0
[karo-tx-linux.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 <drm/drmP.h>
30 #include <drm/i915_drm.h>
31 #include "i915_drv.h"
32 #include "i915_trace.h"
33 #include "intel_drv.h"
34 #include <linux/dma_remapping.h>
35
36 struct eb_objects {
37         int and;
38         struct hlist_head buckets[0];
39 };
40
41 static struct eb_objects *
42 eb_create(int size)
43 {
44         struct eb_objects *eb;
45         int count = PAGE_SIZE / sizeof(struct hlist_head) / 2;
46         BUILD_BUG_ON(!is_power_of_2(PAGE_SIZE / sizeof(struct hlist_head)));
47         while (count > size)
48                 count >>= 1;
49         eb = kzalloc(count*sizeof(struct hlist_head) +
50                      sizeof(struct eb_objects),
51                      GFP_KERNEL);
52         if (eb == NULL)
53                 return eb;
54
55         eb->and = count - 1;
56         return eb;
57 }
58
59 static void
60 eb_reset(struct eb_objects *eb)
61 {
62         memset(eb->buckets, 0, (eb->and+1)*sizeof(struct hlist_head));
63 }
64
65 static void
66 eb_add_object(struct eb_objects *eb, struct drm_i915_gem_object *obj)
67 {
68         hlist_add_head(&obj->exec_node,
69                        &eb->buckets[obj->exec_handle & eb->and]);
70 }
71
72 static struct drm_i915_gem_object *
73 eb_get_object(struct eb_objects *eb, unsigned long handle)
74 {
75         struct hlist_head *head;
76         struct hlist_node *node;
77         struct drm_i915_gem_object *obj;
78
79         head = &eb->buckets[handle & eb->and];
80         hlist_for_each(node, head) {
81                 obj = hlist_entry(node, struct drm_i915_gem_object, exec_node);
82                 if (obj->exec_handle == handle)
83                         return obj;
84         }
85
86         return NULL;
87 }
88
89 static void
90 eb_destroy(struct eb_objects *eb)
91 {
92         kfree(eb);
93 }
94
95 static inline int use_cpu_reloc(struct drm_i915_gem_object *obj)
96 {
97         return (obj->base.write_domain == I915_GEM_DOMAIN_CPU ||
98                 !obj->map_and_fenceable ||
99                 obj->cache_level != I915_CACHE_NONE);
100 }
101
102 static int
103 i915_gem_execbuffer_relocate_entry(struct drm_i915_gem_object *obj,
104                                    struct eb_objects *eb,
105                                    struct drm_i915_gem_relocation_entry *reloc)
106 {
107         struct drm_device *dev = obj->base.dev;
108         struct drm_gem_object *target_obj;
109         struct drm_i915_gem_object *target_i915_obj;
110         uint32_t target_offset;
111         int ret = -EINVAL;
112
113         /* we've already hold a reference to all valid objects */
114         target_obj = &eb_get_object(eb, reloc->target_handle)->base;
115         if (unlikely(target_obj == NULL))
116                 return -ENOENT;
117
118         target_i915_obj = to_intel_bo(target_obj);
119         target_offset = target_i915_obj->gtt_offset;
120
121         /* Sandybridge PPGTT errata: We need a global gtt mapping for MI and
122          * pipe_control writes because the gpu doesn't properly redirect them
123          * through the ppgtt for non_secure batchbuffers. */
124         if (unlikely(IS_GEN6(dev) &&
125             reloc->write_domain == I915_GEM_DOMAIN_INSTRUCTION &&
126             !target_i915_obj->has_global_gtt_mapping)) {
127                 i915_gem_gtt_bind_object(target_i915_obj,
128                                          target_i915_obj->cache_level);
129         }
130
131         /* Validate that the target is in a valid r/w GPU domain */
132         if (unlikely(reloc->write_domain & (reloc->write_domain - 1))) {
133                 DRM_DEBUG("reloc with multiple write domains: "
134                           "obj %p target %d offset %d "
135                           "read %08x write %08x",
136                           obj, reloc->target_handle,
137                           (int) reloc->offset,
138                           reloc->read_domains,
139                           reloc->write_domain);
140                 return ret;
141         }
142         if (unlikely((reloc->write_domain | reloc->read_domains)
143                      & ~I915_GEM_GPU_DOMAINS)) {
144                 DRM_DEBUG("reloc with read/write non-GPU domains: "
145                           "obj %p target %d offset %d "
146                           "read %08x write %08x",
147                           obj, reloc->target_handle,
148                           (int) reloc->offset,
149                           reloc->read_domains,
150                           reloc->write_domain);
151                 return ret;
152         }
153
154         target_obj->pending_read_domains |= reloc->read_domains;
155         target_obj->pending_write_domain |= reloc->write_domain;
156
157         /* If the relocation already has the right value in it, no
158          * more work needs to be done.
159          */
160         if (target_offset == reloc->presumed_offset)
161                 return 0;
162
163         /* Check that the relocation address is valid... */
164         if (unlikely(reloc->offset > obj->base.size - 4)) {
165                 DRM_DEBUG("Relocation beyond object bounds: "
166                           "obj %p target %d offset %d size %d.\n",
167                           obj, reloc->target_handle,
168                           (int) reloc->offset,
169                           (int) obj->base.size);
170                 return ret;
171         }
172         if (unlikely(reloc->offset & 3)) {
173                 DRM_DEBUG("Relocation not 4-byte aligned: "
174                           "obj %p target %d offset %d.\n",
175                           obj, reloc->target_handle,
176                           (int) reloc->offset);
177                 return ret;
178         }
179
180         /* We can't wait for rendering with pagefaults disabled */
181         if (obj->active && in_atomic())
182                 return -EFAULT;
183
184         reloc->delta += target_offset;
185         if (use_cpu_reloc(obj)) {
186                 uint32_t page_offset = reloc->offset & ~PAGE_MASK;
187                 char *vaddr;
188
189                 ret = i915_gem_object_set_to_cpu_domain(obj, 1);
190                 if (ret)
191                         return ret;
192
193                 vaddr = kmap_atomic(i915_gem_object_get_page(obj,
194                                                              reloc->offset >> PAGE_SHIFT));
195                 *(uint32_t *)(vaddr + page_offset) = reloc->delta;
196                 kunmap_atomic(vaddr);
197         } else {
198                 struct drm_i915_private *dev_priv = dev->dev_private;
199                 uint32_t __iomem *reloc_entry;
200                 void __iomem *reloc_page;
201
202                 ret = i915_gem_object_set_to_gtt_domain(obj, true);
203                 if (ret)
204                         return ret;
205
206                 ret = i915_gem_object_put_fence(obj);
207                 if (ret)
208                         return ret;
209
210                 /* Map the page containing the relocation we're going to perform.  */
211                 reloc->offset += obj->gtt_offset;
212                 reloc_page = io_mapping_map_atomic_wc(dev_priv->mm.gtt_mapping,
213                                                       reloc->offset & PAGE_MASK);
214                 reloc_entry = (uint32_t __iomem *)
215                         (reloc_page + (reloc->offset & ~PAGE_MASK));
216                 iowrite32(reloc->delta, reloc_entry);
217                 io_mapping_unmap_atomic(reloc_page);
218         }
219
220         /* and update the user's relocation entry */
221         reloc->presumed_offset = target_offset;
222
223         return 0;
224 }
225
226 static int
227 i915_gem_execbuffer_relocate_object(struct drm_i915_gem_object *obj,
228                                     struct eb_objects *eb)
229 {
230 #define N_RELOC(x) ((x) / sizeof(struct drm_i915_gem_relocation_entry))
231         struct drm_i915_gem_relocation_entry stack_reloc[N_RELOC(512)];
232         struct drm_i915_gem_relocation_entry __user *user_relocs;
233         struct drm_i915_gem_exec_object2 *entry = obj->exec_entry;
234         int remain, ret;
235
236         user_relocs = (void __user *)(uintptr_t)entry->relocs_ptr;
237
238         remain = entry->relocation_count;
239         while (remain) {
240                 struct drm_i915_gem_relocation_entry *r = stack_reloc;
241                 int count = remain;
242                 if (count > ARRAY_SIZE(stack_reloc))
243                         count = ARRAY_SIZE(stack_reloc);
244                 remain -= count;
245
246                 if (__copy_from_user_inatomic(r, user_relocs, count*sizeof(r[0])))
247                         return -EFAULT;
248
249                 do {
250                         u64 offset = r->presumed_offset;
251
252                         ret = i915_gem_execbuffer_relocate_entry(obj, eb, r);
253                         if (ret)
254                                 return ret;
255
256                         if (r->presumed_offset != offset &&
257                             __copy_to_user_inatomic(&user_relocs->presumed_offset,
258                                                     &r->presumed_offset,
259                                                     sizeof(r->presumed_offset))) {
260                                 return -EFAULT;
261                         }
262
263                         user_relocs++;
264                         r++;
265                 } while (--count);
266         }
267
268         return 0;
269 #undef N_RELOC
270 }
271
272 static int
273 i915_gem_execbuffer_relocate_object_slow(struct drm_i915_gem_object *obj,
274                                          struct eb_objects *eb,
275                                          struct drm_i915_gem_relocation_entry *relocs)
276 {
277         const struct drm_i915_gem_exec_object2 *entry = obj->exec_entry;
278         int i, ret;
279
280         for (i = 0; i < entry->relocation_count; i++) {
281                 ret = i915_gem_execbuffer_relocate_entry(obj, eb, &relocs[i]);
282                 if (ret)
283                         return ret;
284         }
285
286         return 0;
287 }
288
289 static int
290 i915_gem_execbuffer_relocate(struct drm_device *dev,
291                              struct eb_objects *eb,
292                              struct list_head *objects)
293 {
294         struct drm_i915_gem_object *obj;
295         int ret = 0;
296
297         /* This is the fast path and we cannot handle a pagefault whilst
298          * holding the struct mutex lest the user pass in the relocations
299          * contained within a mmaped bo. For in such a case we, the page
300          * fault handler would call i915_gem_fault() and we would try to
301          * acquire the struct mutex again. Obviously this is bad and so
302          * lockdep complains vehemently.
303          */
304         pagefault_disable();
305         list_for_each_entry(obj, objects, exec_list) {
306                 ret = i915_gem_execbuffer_relocate_object(obj, eb);
307                 if (ret)
308                         break;
309         }
310         pagefault_enable();
311
312         return ret;
313 }
314
315 #define  __EXEC_OBJECT_HAS_PIN (1<<31)
316 #define  __EXEC_OBJECT_HAS_FENCE (1<<30)
317
318 static int
319 need_reloc_mappable(struct drm_i915_gem_object *obj)
320 {
321         struct drm_i915_gem_exec_object2 *entry = obj->exec_entry;
322         return entry->relocation_count && !use_cpu_reloc(obj);
323 }
324
325 static int
326 i915_gem_execbuffer_reserve_object(struct drm_i915_gem_object *obj,
327                                    struct intel_ring_buffer *ring)
328 {
329         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
330         struct drm_i915_gem_exec_object2 *entry = obj->exec_entry;
331         bool has_fenced_gpu_access = INTEL_INFO(ring->dev)->gen < 4;
332         bool need_fence, need_mappable;
333         int ret;
334
335         need_fence =
336                 has_fenced_gpu_access &&
337                 entry->flags & EXEC_OBJECT_NEEDS_FENCE &&
338                 obj->tiling_mode != I915_TILING_NONE;
339         need_mappable = need_fence || need_reloc_mappable(obj);
340
341         ret = i915_gem_object_pin(obj, entry->alignment, need_mappable, false);
342         if (ret)
343                 return ret;
344
345         entry->flags |= __EXEC_OBJECT_HAS_PIN;
346
347         if (has_fenced_gpu_access) {
348                 if (entry->flags & EXEC_OBJECT_NEEDS_FENCE) {
349                         ret = i915_gem_object_get_fence(obj);
350                         if (ret)
351                                 return ret;
352
353                         if (i915_gem_object_pin_fence(obj))
354                                 entry->flags |= __EXEC_OBJECT_HAS_FENCE;
355
356                         obj->pending_fenced_gpu_access = true;
357                 }
358         }
359
360         /* Ensure ppgtt mapping exists if needed */
361         if (dev_priv->mm.aliasing_ppgtt && !obj->has_aliasing_ppgtt_mapping) {
362                 i915_ppgtt_bind_object(dev_priv->mm.aliasing_ppgtt,
363                                        obj, obj->cache_level);
364
365                 obj->has_aliasing_ppgtt_mapping = 1;
366         }
367
368         entry->offset = obj->gtt_offset;
369         return 0;
370 }
371
372 static void
373 i915_gem_execbuffer_unreserve_object(struct drm_i915_gem_object *obj)
374 {
375         struct drm_i915_gem_exec_object2 *entry;
376
377         if (!obj->gtt_space)
378                 return;
379
380         entry = obj->exec_entry;
381
382         if (entry->flags & __EXEC_OBJECT_HAS_FENCE)
383                 i915_gem_object_unpin_fence(obj);
384
385         if (entry->flags & __EXEC_OBJECT_HAS_PIN)
386                 i915_gem_object_unpin(obj);
387
388         entry->flags &= ~(__EXEC_OBJECT_HAS_FENCE | __EXEC_OBJECT_HAS_PIN);
389 }
390
391 static int
392 i915_gem_execbuffer_reserve(struct intel_ring_buffer *ring,
393                             struct drm_file *file,
394                             struct list_head *objects)
395 {
396         struct drm_i915_gem_object *obj;
397         struct list_head ordered_objects;
398         bool has_fenced_gpu_access = INTEL_INFO(ring->dev)->gen < 4;
399         int retry;
400
401         INIT_LIST_HEAD(&ordered_objects);
402         while (!list_empty(objects)) {
403                 struct drm_i915_gem_exec_object2 *entry;
404                 bool need_fence, need_mappable;
405
406                 obj = list_first_entry(objects,
407                                        struct drm_i915_gem_object,
408                                        exec_list);
409                 entry = obj->exec_entry;
410
411                 need_fence =
412                         has_fenced_gpu_access &&
413                         entry->flags & EXEC_OBJECT_NEEDS_FENCE &&
414                         obj->tiling_mode != I915_TILING_NONE;
415                 need_mappable = need_fence || need_reloc_mappable(obj);
416
417                 if (need_mappable)
418                         list_move(&obj->exec_list, &ordered_objects);
419                 else
420                         list_move_tail(&obj->exec_list, &ordered_objects);
421
422                 obj->base.pending_read_domains = 0;
423                 obj->base.pending_write_domain = 0;
424                 obj->pending_fenced_gpu_access = false;
425         }
426         list_splice(&ordered_objects, objects);
427
428         /* Attempt to pin all of the buffers into the GTT.
429          * This is done in 3 phases:
430          *
431          * 1a. Unbind all objects that do not match the GTT constraints for
432          *     the execbuffer (fenceable, mappable, alignment etc).
433          * 1b. Increment pin count for already bound objects.
434          * 2.  Bind new objects.
435          * 3.  Decrement pin count.
436          *
437          * This avoid unnecessary unbinding of later objects in order to make
438          * room for the earlier objects *unless* we need to defragment.
439          */
440         retry = 0;
441         do {
442                 int ret = 0;
443
444                 /* Unbind any ill-fitting objects or pin. */
445                 list_for_each_entry(obj, objects, exec_list) {
446                         struct drm_i915_gem_exec_object2 *entry = obj->exec_entry;
447                         bool need_fence, need_mappable;
448
449                         if (!obj->gtt_space)
450                                 continue;
451
452                         need_fence =
453                                 has_fenced_gpu_access &&
454                                 entry->flags & EXEC_OBJECT_NEEDS_FENCE &&
455                                 obj->tiling_mode != I915_TILING_NONE;
456                         need_mappable = need_fence || need_reloc_mappable(obj);
457
458                         if ((entry->alignment && obj->gtt_offset & (entry->alignment - 1)) ||
459                             (need_mappable && !obj->map_and_fenceable))
460                                 ret = i915_gem_object_unbind(obj);
461                         else
462                                 ret = i915_gem_execbuffer_reserve_object(obj, ring);
463                         if (ret)
464                                 goto err;
465                 }
466
467                 /* Bind fresh objects */
468                 list_for_each_entry(obj, objects, exec_list) {
469                         if (obj->gtt_space)
470                                 continue;
471
472                         ret = i915_gem_execbuffer_reserve_object(obj, ring);
473                         if (ret)
474                                 goto err;
475                 }
476
477 err:            /* Decrement pin count for bound objects */
478                 list_for_each_entry(obj, objects, exec_list)
479                         i915_gem_execbuffer_unreserve_object(obj);
480
481                 if (ret != -ENOSPC || retry++)
482                         return ret;
483
484                 ret = i915_gem_evict_everything(ring->dev);
485                 if (ret)
486                         return ret;
487         } while (1);
488 }
489
490 static int
491 i915_gem_execbuffer_relocate_slow(struct drm_device *dev,
492                                   struct drm_file *file,
493                                   struct intel_ring_buffer *ring,
494                                   struct list_head *objects,
495                                   struct eb_objects *eb,
496                                   struct drm_i915_gem_exec_object2 *exec,
497                                   int count)
498 {
499         struct drm_i915_gem_relocation_entry *reloc;
500         struct drm_i915_gem_object *obj;
501         int *reloc_offset;
502         int i, total, ret;
503
504         /* We may process another execbuffer during the unlock... */
505         while (!list_empty(objects)) {
506                 obj = list_first_entry(objects,
507                                        struct drm_i915_gem_object,
508                                        exec_list);
509                 list_del_init(&obj->exec_list);
510                 drm_gem_object_unreference(&obj->base);
511         }
512
513         mutex_unlock(&dev->struct_mutex);
514
515         total = 0;
516         for (i = 0; i < count; i++)
517                 total += exec[i].relocation_count;
518
519         reloc_offset = drm_malloc_ab(count, sizeof(*reloc_offset));
520         reloc = drm_malloc_ab(total, sizeof(*reloc));
521         if (reloc == NULL || reloc_offset == NULL) {
522                 drm_free_large(reloc);
523                 drm_free_large(reloc_offset);
524                 mutex_lock(&dev->struct_mutex);
525                 return -ENOMEM;
526         }
527
528         total = 0;
529         for (i = 0; i < count; i++) {
530                 struct drm_i915_gem_relocation_entry __user *user_relocs;
531
532                 user_relocs = (void __user *)(uintptr_t)exec[i].relocs_ptr;
533
534                 if (copy_from_user(reloc+total, user_relocs,
535                                    exec[i].relocation_count * sizeof(*reloc))) {
536                         ret = -EFAULT;
537                         mutex_lock(&dev->struct_mutex);
538                         goto err;
539                 }
540
541                 reloc_offset[i] = total;
542                 total += exec[i].relocation_count;
543         }
544
545         ret = i915_mutex_lock_interruptible(dev);
546         if (ret) {
547                 mutex_lock(&dev->struct_mutex);
548                 goto err;
549         }
550
551         /* reacquire the objects */
552         eb_reset(eb);
553         for (i = 0; i < count; i++) {
554                 obj = to_intel_bo(drm_gem_object_lookup(dev, file,
555                                                         exec[i].handle));
556                 if (&obj->base == NULL) {
557                         DRM_DEBUG("Invalid object handle %d at index %d\n",
558                                    exec[i].handle, i);
559                         ret = -ENOENT;
560                         goto err;
561                 }
562
563                 list_add_tail(&obj->exec_list, objects);
564                 obj->exec_handle = exec[i].handle;
565                 obj->exec_entry = &exec[i];
566                 eb_add_object(eb, obj);
567         }
568
569         ret = i915_gem_execbuffer_reserve(ring, file, objects);
570         if (ret)
571                 goto err;
572
573         list_for_each_entry(obj, objects, exec_list) {
574                 int offset = obj->exec_entry - exec;
575                 ret = i915_gem_execbuffer_relocate_object_slow(obj, eb,
576                                                                reloc + reloc_offset[offset]);
577                 if (ret)
578                         goto err;
579         }
580
581         /* Leave the user relocations as are, this is the painfully slow path,
582          * and we want to avoid the complication of dropping the lock whilst
583          * having buffers reserved in the aperture and so causing spurious
584          * ENOSPC for random operations.
585          */
586
587 err:
588         drm_free_large(reloc);
589         drm_free_large(reloc_offset);
590         return ret;
591 }
592
593 static int
594 i915_gem_execbuffer_move_to_gpu(struct intel_ring_buffer *ring,
595                                 struct list_head *objects)
596 {
597         struct drm_i915_gem_object *obj;
598         uint32_t flush_domains = 0;
599         int ret;
600
601         list_for_each_entry(obj, objects, exec_list) {
602                 ret = i915_gem_object_sync(obj, ring);
603                 if (ret)
604                         return ret;
605
606                 if (obj->base.write_domain & I915_GEM_DOMAIN_CPU)
607                         i915_gem_clflush_object(obj);
608
609                 flush_domains |= obj->base.write_domain;
610         }
611
612         if (flush_domains & I915_GEM_DOMAIN_CPU)
613                 i915_gem_chipset_flush(ring->dev);
614
615         if (flush_domains & I915_GEM_DOMAIN_GTT)
616                 wmb();
617
618         /* Unconditionally invalidate gpu caches and ensure that we do flush
619          * any residual writes from the previous batch.
620          */
621         return intel_ring_invalidate_all_caches(ring);
622 }
623
624 static bool
625 i915_gem_check_execbuffer(struct drm_i915_gem_execbuffer2 *exec)
626 {
627         return ((exec->batch_start_offset | exec->batch_len) & 0x7) == 0;
628 }
629
630 static int
631 validate_exec_list(struct drm_i915_gem_exec_object2 *exec,
632                    int count)
633 {
634         int i;
635
636         for (i = 0; i < count; i++) {
637                 char __user *ptr = (char __user *)(uintptr_t)exec[i].relocs_ptr;
638                 int length; /* limited by fault_in_pages_readable() */
639
640                 /* First check for malicious input causing overflow */
641                 if (exec[i].relocation_count >
642                     INT_MAX / sizeof(struct drm_i915_gem_relocation_entry))
643                         return -EINVAL;
644
645                 length = exec[i].relocation_count *
646                         sizeof(struct drm_i915_gem_relocation_entry);
647                 if (!access_ok(VERIFY_READ, ptr, length))
648                         return -EFAULT;
649
650                 /* we may also need to update the presumed offsets */
651                 if (!access_ok(VERIFY_WRITE, ptr, length))
652                         return -EFAULT;
653
654                 if (fault_in_multipages_readable(ptr, length))
655                         return -EFAULT;
656         }
657
658         return 0;
659 }
660
661 static void
662 i915_gem_execbuffer_move_to_active(struct list_head *objects,
663                                    struct intel_ring_buffer *ring)
664 {
665         struct drm_i915_gem_object *obj;
666
667         list_for_each_entry(obj, objects, exec_list) {
668                 u32 old_read = obj->base.read_domains;
669                 u32 old_write = obj->base.write_domain;
670
671                 obj->base.read_domains = obj->base.pending_read_domains;
672                 obj->base.write_domain = obj->base.pending_write_domain;
673                 obj->fenced_gpu_access = obj->pending_fenced_gpu_access;
674
675                 i915_gem_object_move_to_active(obj, ring);
676                 if (obj->base.write_domain) {
677                         obj->dirty = 1;
678                         obj->last_write_seqno = intel_ring_get_seqno(ring);
679                         if (obj->pin_count) /* check for potential scanout */
680                                 intel_mark_fb_busy(obj);
681                 }
682
683                 trace_i915_gem_object_change_domain(obj, old_read, old_write);
684         }
685 }
686
687 static void
688 i915_gem_execbuffer_retire_commands(struct drm_device *dev,
689                                     struct drm_file *file,
690                                     struct intel_ring_buffer *ring)
691 {
692         /* Unconditionally force add_request to emit a full flush. */
693         ring->gpu_caches_dirty = true;
694
695         /* Add a breadcrumb for the completion of the batch buffer */
696         (void)i915_add_request(ring, file, NULL);
697 }
698
699 static int
700 i915_reset_gen7_sol_offsets(struct drm_device *dev,
701                             struct intel_ring_buffer *ring)
702 {
703         drm_i915_private_t *dev_priv = dev->dev_private;
704         int ret, i;
705
706         if (!IS_GEN7(dev) || ring != &dev_priv->ring[RCS])
707                 return 0;
708
709         ret = intel_ring_begin(ring, 4 * 3);
710         if (ret)
711                 return ret;
712
713         for (i = 0; i < 4; i++) {
714                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
715                 intel_ring_emit(ring, GEN7_SO_WRITE_OFFSET(i));
716                 intel_ring_emit(ring, 0);
717         }
718
719         intel_ring_advance(ring);
720
721         return 0;
722 }
723
724 static int
725 i915_gem_do_execbuffer(struct drm_device *dev, void *data,
726                        struct drm_file *file,
727                        struct drm_i915_gem_execbuffer2 *args,
728                        struct drm_i915_gem_exec_object2 *exec)
729 {
730         drm_i915_private_t *dev_priv = dev->dev_private;
731         struct list_head objects;
732         struct eb_objects *eb;
733         struct drm_i915_gem_object *batch_obj;
734         struct drm_clip_rect *cliprects = NULL;
735         struct intel_ring_buffer *ring;
736         u32 ctx_id = i915_execbuffer2_get_context_id(*args);
737         u32 exec_start, exec_len;
738         u32 mask;
739         u32 flags;
740         int ret, mode, i;
741
742         if (!i915_gem_check_execbuffer(args)) {
743                 DRM_DEBUG("execbuf with invalid offset/length\n");
744                 return -EINVAL;
745         }
746
747         ret = validate_exec_list(exec, args->buffer_count);
748         if (ret)
749                 return ret;
750
751         flags = 0;
752         if (args->flags & I915_EXEC_SECURE) {
753                 if (!file->is_master || !capable(CAP_SYS_ADMIN))
754                     return -EPERM;
755
756                 flags |= I915_DISPATCH_SECURE;
757         }
758         if (args->flags & I915_EXEC_IS_PINNED)
759                 flags |= I915_DISPATCH_PINNED;
760
761         switch (args->flags & I915_EXEC_RING_MASK) {
762         case I915_EXEC_DEFAULT:
763         case I915_EXEC_RENDER:
764                 ring = &dev_priv->ring[RCS];
765                 break;
766         case I915_EXEC_BSD:
767                 ring = &dev_priv->ring[VCS];
768                 if (ctx_id != 0) {
769                         DRM_DEBUG("Ring %s doesn't support contexts\n",
770                                   ring->name);
771                         return -EPERM;
772                 }
773                 break;
774         case I915_EXEC_BLT:
775                 ring = &dev_priv->ring[BCS];
776                 if (ctx_id != 0) {
777                         DRM_DEBUG("Ring %s doesn't support contexts\n",
778                                   ring->name);
779                         return -EPERM;
780                 }
781                 break;
782         default:
783                 DRM_DEBUG("execbuf with unknown ring: %d\n",
784                           (int)(args->flags & I915_EXEC_RING_MASK));
785                 return -EINVAL;
786         }
787         if (!intel_ring_initialized(ring)) {
788                 DRM_DEBUG("execbuf with invalid ring: %d\n",
789                           (int)(args->flags & I915_EXEC_RING_MASK));
790                 return -EINVAL;
791         }
792
793         mode = args->flags & I915_EXEC_CONSTANTS_MASK;
794         mask = I915_EXEC_CONSTANTS_MASK;
795         switch (mode) {
796         case I915_EXEC_CONSTANTS_REL_GENERAL:
797         case I915_EXEC_CONSTANTS_ABSOLUTE:
798         case I915_EXEC_CONSTANTS_REL_SURFACE:
799                 if (ring == &dev_priv->ring[RCS] &&
800                     mode != dev_priv->relative_constants_mode) {
801                         if (INTEL_INFO(dev)->gen < 4)
802                                 return -EINVAL;
803
804                         if (INTEL_INFO(dev)->gen > 5 &&
805                             mode == I915_EXEC_CONSTANTS_REL_SURFACE)
806                                 return -EINVAL;
807
808                         /* The HW changed the meaning on this bit on gen6 */
809                         if (INTEL_INFO(dev)->gen >= 6)
810                                 mask &= ~I915_EXEC_CONSTANTS_REL_SURFACE;
811                 }
812                 break;
813         default:
814                 DRM_DEBUG("execbuf with unknown constants: %d\n", mode);
815                 return -EINVAL;
816         }
817
818         if (args->buffer_count < 1) {
819                 DRM_DEBUG("execbuf with %d buffers\n", args->buffer_count);
820                 return -EINVAL;
821         }
822
823         if (args->num_cliprects != 0) {
824                 if (ring != &dev_priv->ring[RCS]) {
825                         DRM_DEBUG("clip rectangles are only valid with the render ring\n");
826                         return -EINVAL;
827                 }
828
829                 if (INTEL_INFO(dev)->gen >= 5) {
830                         DRM_DEBUG("clip rectangles are only valid on pre-gen5\n");
831                         return -EINVAL;
832                 }
833
834                 if (args->num_cliprects > UINT_MAX / sizeof(*cliprects)) {
835                         DRM_DEBUG("execbuf with %u cliprects\n",
836                                   args->num_cliprects);
837                         return -EINVAL;
838                 }
839
840                 cliprects = kmalloc(args->num_cliprects * sizeof(*cliprects),
841                                     GFP_KERNEL);
842                 if (cliprects == NULL) {
843                         ret = -ENOMEM;
844                         goto pre_mutex_err;
845                 }
846
847                 if (copy_from_user(cliprects,
848                                      (struct drm_clip_rect __user *)(uintptr_t)
849                                      args->cliprects_ptr,
850                                      sizeof(*cliprects)*args->num_cliprects)) {
851                         ret = -EFAULT;
852                         goto pre_mutex_err;
853                 }
854         }
855
856         ret = i915_mutex_lock_interruptible(dev);
857         if (ret)
858                 goto pre_mutex_err;
859
860         if (dev_priv->mm.suspended) {
861                 mutex_unlock(&dev->struct_mutex);
862                 ret = -EBUSY;
863                 goto pre_mutex_err;
864         }
865
866         eb = eb_create(args->buffer_count);
867         if (eb == NULL) {
868                 mutex_unlock(&dev->struct_mutex);
869                 ret = -ENOMEM;
870                 goto pre_mutex_err;
871         }
872
873         /* Look up object handles */
874         INIT_LIST_HEAD(&objects);
875         for (i = 0; i < args->buffer_count; i++) {
876                 struct drm_i915_gem_object *obj;
877
878                 obj = to_intel_bo(drm_gem_object_lookup(dev, file,
879                                                         exec[i].handle));
880                 if (&obj->base == NULL) {
881                         DRM_DEBUG("Invalid object handle %d at index %d\n",
882                                    exec[i].handle, i);
883                         /* prevent error path from reading uninitialized data */
884                         ret = -ENOENT;
885                         goto err;
886                 }
887
888                 if (!list_empty(&obj->exec_list)) {
889                         DRM_DEBUG("Object %p [handle %d, index %d] appears more than once in object list\n",
890                                    obj, exec[i].handle, i);
891                         ret = -EINVAL;
892                         goto err;
893                 }
894
895                 list_add_tail(&obj->exec_list, &objects);
896                 obj->exec_handle = exec[i].handle;
897                 obj->exec_entry = &exec[i];
898                 eb_add_object(eb, obj);
899         }
900
901         /* take note of the batch buffer before we might reorder the lists */
902         batch_obj = list_entry(objects.prev,
903                                struct drm_i915_gem_object,
904                                exec_list);
905
906         /* Move the objects en-masse into the GTT, evicting if necessary. */
907         ret = i915_gem_execbuffer_reserve(ring, file, &objects);
908         if (ret)
909                 goto err;
910
911         /* The objects are in their final locations, apply the relocations. */
912         ret = i915_gem_execbuffer_relocate(dev, eb, &objects);
913         if (ret) {
914                 if (ret == -EFAULT) {
915                         ret = i915_gem_execbuffer_relocate_slow(dev, file, ring,
916                                                                 &objects, eb,
917                                                                 exec,
918                                                                 args->buffer_count);
919                         BUG_ON(!mutex_is_locked(&dev->struct_mutex));
920                 }
921                 if (ret)
922                         goto err;
923         }
924
925         /* Set the pending read domains for the batch buffer to COMMAND */
926         if (batch_obj->base.pending_write_domain) {
927                 DRM_DEBUG("Attempting to use self-modifying batch buffer\n");
928                 ret = -EINVAL;
929                 goto err;
930         }
931         batch_obj->base.pending_read_domains |= I915_GEM_DOMAIN_COMMAND;
932
933         /* snb/ivb/vlv conflate the "batch in ppgtt" bit with the "non-secure
934          * batch" bit. Hence we need to pin secure batches into the global gtt.
935          * hsw should have this fixed, but let's be paranoid and do it
936          * unconditionally for now. */
937         if (flags & I915_DISPATCH_SECURE && !batch_obj->has_global_gtt_mapping)
938                 i915_gem_gtt_bind_object(batch_obj, batch_obj->cache_level);
939
940         ret = i915_gem_execbuffer_move_to_gpu(ring, &objects);
941         if (ret)
942                 goto err;
943
944         ret = i915_switch_context(ring, file, ctx_id);
945         if (ret)
946                 goto err;
947
948         if (ring == &dev_priv->ring[RCS] &&
949             mode != dev_priv->relative_constants_mode) {
950                 ret = intel_ring_begin(ring, 4);
951                 if (ret)
952                                 goto err;
953
954                 intel_ring_emit(ring, MI_NOOP);
955                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
956                 intel_ring_emit(ring, INSTPM);
957                 intel_ring_emit(ring, mask << 16 | mode);
958                 intel_ring_advance(ring);
959
960                 dev_priv->relative_constants_mode = mode;
961         }
962
963         if (args->flags & I915_EXEC_GEN7_SOL_RESET) {
964                 ret = i915_reset_gen7_sol_offsets(dev, ring);
965                 if (ret)
966                         goto err;
967         }
968
969         exec_start = batch_obj->gtt_offset + args->batch_start_offset;
970         exec_len = args->batch_len;
971         if (cliprects) {
972                 for (i = 0; i < args->num_cliprects; i++) {
973                         ret = i915_emit_box(dev, &cliprects[i],
974                                             args->DR1, args->DR4);
975                         if (ret)
976                                 goto err;
977
978                         ret = ring->dispatch_execbuffer(ring,
979                                                         exec_start, exec_len,
980                                                         flags);
981                         if (ret)
982                                 goto err;
983                 }
984         } else {
985                 ret = ring->dispatch_execbuffer(ring,
986                                                 exec_start, exec_len,
987                                                 flags);
988                 if (ret)
989                         goto err;
990         }
991
992         trace_i915_gem_ring_dispatch(ring, intel_ring_get_seqno(ring), flags);
993
994         i915_gem_execbuffer_move_to_active(&objects, ring);
995         i915_gem_execbuffer_retire_commands(dev, file, ring);
996
997 err:
998         eb_destroy(eb);
999         while (!list_empty(&objects)) {
1000                 struct drm_i915_gem_object *obj;
1001
1002                 obj = list_first_entry(&objects,
1003                                        struct drm_i915_gem_object,
1004                                        exec_list);
1005                 list_del_init(&obj->exec_list);
1006                 drm_gem_object_unreference(&obj->base);
1007         }
1008
1009         mutex_unlock(&dev->struct_mutex);
1010
1011 pre_mutex_err:
1012         kfree(cliprects);
1013         return ret;
1014 }
1015
1016 /*
1017  * Legacy execbuffer just creates an exec2 list from the original exec object
1018  * list array and passes it to the real function.
1019  */
1020 int
1021 i915_gem_execbuffer(struct drm_device *dev, void *data,
1022                     struct drm_file *file)
1023 {
1024         struct drm_i915_gem_execbuffer *args = data;
1025         struct drm_i915_gem_execbuffer2 exec2;
1026         struct drm_i915_gem_exec_object *exec_list = NULL;
1027         struct drm_i915_gem_exec_object2 *exec2_list = NULL;
1028         int ret, i;
1029
1030         if (args->buffer_count < 1) {
1031                 DRM_DEBUG("execbuf with %d buffers\n", args->buffer_count);
1032                 return -EINVAL;
1033         }
1034
1035         /* Copy in the exec list from userland */
1036         exec_list = drm_malloc_ab(sizeof(*exec_list), args->buffer_count);
1037         exec2_list = drm_malloc_ab(sizeof(*exec2_list), args->buffer_count);
1038         if (exec_list == NULL || exec2_list == NULL) {
1039                 DRM_DEBUG("Failed to allocate exec list for %d buffers\n",
1040                           args->buffer_count);
1041                 drm_free_large(exec_list);
1042                 drm_free_large(exec2_list);
1043                 return -ENOMEM;
1044         }
1045         ret = copy_from_user(exec_list,
1046                              (void __user *)(uintptr_t)args->buffers_ptr,
1047                              sizeof(*exec_list) * args->buffer_count);
1048         if (ret != 0) {
1049                 DRM_DEBUG("copy %d exec entries failed %d\n",
1050                           args->buffer_count, ret);
1051                 drm_free_large(exec_list);
1052                 drm_free_large(exec2_list);
1053                 return -EFAULT;
1054         }
1055
1056         for (i = 0; i < args->buffer_count; i++) {
1057                 exec2_list[i].handle = exec_list[i].handle;
1058                 exec2_list[i].relocation_count = exec_list[i].relocation_count;
1059                 exec2_list[i].relocs_ptr = exec_list[i].relocs_ptr;
1060                 exec2_list[i].alignment = exec_list[i].alignment;
1061                 exec2_list[i].offset = exec_list[i].offset;
1062                 if (INTEL_INFO(dev)->gen < 4)
1063                         exec2_list[i].flags = EXEC_OBJECT_NEEDS_FENCE;
1064                 else
1065                         exec2_list[i].flags = 0;
1066         }
1067
1068         exec2.buffers_ptr = args->buffers_ptr;
1069         exec2.buffer_count = args->buffer_count;
1070         exec2.batch_start_offset = args->batch_start_offset;
1071         exec2.batch_len = args->batch_len;
1072         exec2.DR1 = args->DR1;
1073         exec2.DR4 = args->DR4;
1074         exec2.num_cliprects = args->num_cliprects;
1075         exec2.cliprects_ptr = args->cliprects_ptr;
1076         exec2.flags = I915_EXEC_RENDER;
1077         i915_execbuffer2_set_context_id(exec2, 0);
1078
1079         ret = i915_gem_do_execbuffer(dev, data, file, &exec2, exec2_list);
1080         if (!ret) {
1081                 /* Copy the new buffer offsets back to the user's exec list. */
1082                 for (i = 0; i < args->buffer_count; i++)
1083                         exec_list[i].offset = exec2_list[i].offset;
1084                 /* ... and back out to userspace */
1085                 ret = copy_to_user((void __user *)(uintptr_t)args->buffers_ptr,
1086                                    exec_list,
1087                                    sizeof(*exec_list) * args->buffer_count);
1088                 if (ret) {
1089                         ret = -EFAULT;
1090                         DRM_DEBUG("failed to copy %d exec entries "
1091                                   "back to user (%d)\n",
1092                                   args->buffer_count, ret);
1093                 }
1094         }
1095
1096         drm_free_large(exec_list);
1097         drm_free_large(exec2_list);
1098         return ret;
1099 }
1100
1101 int
1102 i915_gem_execbuffer2(struct drm_device *dev, void *data,
1103                      struct drm_file *file)
1104 {
1105         struct drm_i915_gem_execbuffer2 *args = data;
1106         struct drm_i915_gem_exec_object2 *exec2_list = NULL;
1107         int ret;
1108
1109         if (args->buffer_count < 1 ||
1110             args->buffer_count > UINT_MAX / sizeof(*exec2_list)) {
1111                 DRM_DEBUG("execbuf2 with %d buffers\n", args->buffer_count);
1112                 return -EINVAL;
1113         }
1114
1115         exec2_list = kmalloc(sizeof(*exec2_list)*args->buffer_count,
1116                              GFP_TEMPORARY | __GFP_NOWARN | __GFP_NORETRY);
1117         if (exec2_list == NULL)
1118                 exec2_list = drm_malloc_ab(sizeof(*exec2_list),
1119                                            args->buffer_count);
1120         if (exec2_list == NULL) {
1121                 DRM_DEBUG("Failed to allocate exec list for %d buffers\n",
1122                           args->buffer_count);
1123                 return -ENOMEM;
1124         }
1125         ret = copy_from_user(exec2_list,
1126                              (struct drm_i915_relocation_entry __user *)
1127                              (uintptr_t) args->buffers_ptr,
1128                              sizeof(*exec2_list) * args->buffer_count);
1129         if (ret != 0) {
1130                 DRM_DEBUG("copy %d exec entries failed %d\n",
1131                           args->buffer_count, ret);
1132                 drm_free_large(exec2_list);
1133                 return -EFAULT;
1134         }
1135
1136         ret = i915_gem_do_execbuffer(dev, data, file, args, exec2_list);
1137         if (!ret) {
1138                 /* Copy the new buffer offsets back to the user's exec list. */
1139                 ret = copy_to_user((void __user *)(uintptr_t)args->buffers_ptr,
1140                                    exec2_list,
1141                                    sizeof(*exec2_list) * args->buffer_count);
1142                 if (ret) {
1143                         ret = -EFAULT;
1144                         DRM_DEBUG("failed to copy %d exec entries "
1145                                   "back to user (%d)\n",
1146                                   args->buffer_count, ret);
1147                 }
1148         }
1149
1150         drm_free_large(exec2_list);
1151         return ret;
1152 }