Merge branch 'next' of git://git.kernel.org/pub/scm/linux/kernel/git/djbw/async_tx
[cascardo/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 "drmP.h"
30 #include "drm.h"
31 #include "i915_drm.h"
32 #include "i915_drv.h"
33 #include "i915_trace.h"
34 #include "intel_drv.h"
35
36 struct change_domains {
37         uint32_t invalidate_domains;
38         uint32_t flush_domains;
39         uint32_t flush_rings;
40         uint32_t flips;
41 };
42
43 /*
44  * Set the next domain for the specified object. This
45  * may not actually perform the necessary flushing/invaliding though,
46  * as that may want to be batched with other set_domain operations
47  *
48  * This is (we hope) the only really tricky part of gem. The goal
49  * is fairly simple -- track which caches hold bits of the object
50  * and make sure they remain coherent. A few concrete examples may
51  * help to explain how it works. For shorthand, we use the notation
52  * (read_domains, write_domain), e.g. (CPU, CPU) to indicate the
53  * a pair of read and write domain masks.
54  *
55  * Case 1: the batch buffer
56  *
57  *      1. Allocated
58  *      2. Written by CPU
59  *      3. Mapped to GTT
60  *      4. Read by GPU
61  *      5. Unmapped from GTT
62  *      6. Freed
63  *
64  *      Let's take these a step at a time
65  *
66  *      1. Allocated
67  *              Pages allocated from the kernel may still have
68  *              cache contents, so we set them to (CPU, CPU) always.
69  *      2. Written by CPU (using pwrite)
70  *              The pwrite function calls set_domain (CPU, CPU) and
71  *              this function does nothing (as nothing changes)
72  *      3. Mapped by GTT
73  *              This function asserts that the object is not
74  *              currently in any GPU-based read or write domains
75  *      4. Read by GPU
76  *              i915_gem_execbuffer calls set_domain (COMMAND, 0).
77  *              As write_domain is zero, this function adds in the
78  *              current read domains (CPU+COMMAND, 0).
79  *              flush_domains is set to CPU.
80  *              invalidate_domains is set to COMMAND
81  *              clflush is run to get data out of the CPU caches
82  *              then i915_dev_set_domain calls i915_gem_flush to
83  *              emit an MI_FLUSH and drm_agp_chipset_flush
84  *      5. Unmapped from GTT
85  *              i915_gem_object_unbind calls set_domain (CPU, CPU)
86  *              flush_domains and invalidate_domains end up both zero
87  *              so no flushing/invalidating happens
88  *      6. Freed
89  *              yay, done
90  *
91  * Case 2: The shared render buffer
92  *
93  *      1. Allocated
94  *      2. Mapped to GTT
95  *      3. Read/written by GPU
96  *      4. set_domain to (CPU,CPU)
97  *      5. Read/written by CPU
98  *      6. Read/written by GPU
99  *
100  *      1. Allocated
101  *              Same as last example, (CPU, CPU)
102  *      2. Mapped to GTT
103  *              Nothing changes (assertions find that it is not in the GPU)
104  *      3. Read/written by GPU
105  *              execbuffer calls set_domain (RENDER, RENDER)
106  *              flush_domains gets CPU
107  *              invalidate_domains gets GPU
108  *              clflush (obj)
109  *              MI_FLUSH and drm_agp_chipset_flush
110  *      4. set_domain (CPU, CPU)
111  *              flush_domains gets GPU
112  *              invalidate_domains gets CPU
113  *              wait_rendering (obj) to make sure all drawing is complete.
114  *              This will include an MI_FLUSH to get the data from GPU
115  *              to memory
116  *              clflush (obj) to invalidate the CPU cache
117  *              Another MI_FLUSH in i915_gem_flush (eliminate this somehow?)
118  *      5. Read/written by CPU
119  *              cache lines are loaded and dirtied
120  *      6. Read written by GPU
121  *              Same as last GPU access
122  *
123  * Case 3: The constant buffer
124  *
125  *      1. Allocated
126  *      2. Written by CPU
127  *      3. Read by GPU
128  *      4. Updated (written) by CPU again
129  *      5. Read by GPU
130  *
131  *      1. Allocated
132  *              (CPU, CPU)
133  *      2. Written by CPU
134  *              (CPU, CPU)
135  *      3. Read by GPU
136  *              (CPU+RENDER, 0)
137  *              flush_domains = CPU
138  *              invalidate_domains = RENDER
139  *              clflush (obj)
140  *              MI_FLUSH
141  *              drm_agp_chipset_flush
142  *      4. Updated (written) by CPU again
143  *              (CPU, CPU)
144  *              flush_domains = 0 (no previous write domain)
145  *              invalidate_domains = 0 (no new read domains)
146  *      5. Read by GPU
147  *              (CPU+RENDER, 0)
148  *              flush_domains = CPU
149  *              invalidate_domains = RENDER
150  *              clflush (obj)
151  *              MI_FLUSH
152  *              drm_agp_chipset_flush
153  */
154 static void
155 i915_gem_object_set_to_gpu_domain(struct drm_i915_gem_object *obj,
156                                   struct intel_ring_buffer *ring,
157                                   struct change_domains *cd)
158 {
159         uint32_t invalidate_domains = 0, flush_domains = 0;
160
161         /*
162          * If the object isn't moving to a new write domain,
163          * let the object stay in multiple read domains
164          */
165         if (obj->base.pending_write_domain == 0)
166                 obj->base.pending_read_domains |= obj->base.read_domains;
167
168         /*
169          * Flush the current write domain if
170          * the new read domains don't match. Invalidate
171          * any read domains which differ from the old
172          * write domain
173          */
174         if (obj->base.write_domain &&
175             (((obj->base.write_domain != obj->base.pending_read_domains ||
176                obj->ring != ring)) ||
177              (obj->fenced_gpu_access && !obj->pending_fenced_gpu_access))) {
178                 flush_domains |= obj->base.write_domain;
179                 invalidate_domains |=
180                         obj->base.pending_read_domains & ~obj->base.write_domain;
181         }
182         /*
183          * Invalidate any read caches which may have
184          * stale data. That is, any new read domains.
185          */
186         invalidate_domains |= obj->base.pending_read_domains & ~obj->base.read_domains;
187         if ((flush_domains | invalidate_domains) & I915_GEM_DOMAIN_CPU)
188                 i915_gem_clflush_object(obj);
189
190         /* blow away mappings if mapped through GTT */
191         if ((flush_domains | invalidate_domains) & I915_GEM_DOMAIN_GTT)
192                 i915_gem_release_mmap(obj);
193
194         if (obj->base.pending_write_domain)
195                 cd->flips |= atomic_read(&obj->pending_flip);
196
197         /* The actual obj->write_domain will be updated with
198          * pending_write_domain after we emit the accumulated flush for all
199          * of our domain changes in execbuffers (which clears objects'
200          * write_domains).  So if we have a current write domain that we
201          * aren't changing, set pending_write_domain to that.
202          */
203         if (flush_domains == 0 && obj->base.pending_write_domain == 0)
204                 obj->base.pending_write_domain = obj->base.write_domain;
205
206         cd->invalidate_domains |= invalidate_domains;
207         cd->flush_domains |= flush_domains;
208         if (flush_domains & I915_GEM_GPU_DOMAINS)
209                 cd->flush_rings |= obj->ring->id;
210         if (invalidate_domains & I915_GEM_GPU_DOMAINS)
211                 cd->flush_rings |= ring->id;
212 }
213
214 struct eb_objects {
215         int and;
216         struct hlist_head buckets[0];
217 };
218
219 static struct eb_objects *
220 eb_create(int size)
221 {
222         struct eb_objects *eb;
223         int count = PAGE_SIZE / sizeof(struct hlist_head) / 2;
224         while (count > size)
225                 count >>= 1;
226         eb = kzalloc(count*sizeof(struct hlist_head) +
227                      sizeof(struct eb_objects),
228                      GFP_KERNEL);
229         if (eb == NULL)
230                 return eb;
231
232         eb->and = count - 1;
233         return eb;
234 }
235
236 static void
237 eb_reset(struct eb_objects *eb)
238 {
239         memset(eb->buckets, 0, (eb->and+1)*sizeof(struct hlist_head));
240 }
241
242 static void
243 eb_add_object(struct eb_objects *eb, struct drm_i915_gem_object *obj)
244 {
245         hlist_add_head(&obj->exec_node,
246                        &eb->buckets[obj->exec_handle & eb->and]);
247 }
248
249 static struct drm_i915_gem_object *
250 eb_get_object(struct eb_objects *eb, unsigned long handle)
251 {
252         struct hlist_head *head;
253         struct hlist_node *node;
254         struct drm_i915_gem_object *obj;
255
256         head = &eb->buckets[handle & eb->and];
257         hlist_for_each(node, head) {
258                 obj = hlist_entry(node, struct drm_i915_gem_object, exec_node);
259                 if (obj->exec_handle == handle)
260                         return obj;
261         }
262
263         return NULL;
264 }
265
266 static void
267 eb_destroy(struct eb_objects *eb)
268 {
269         kfree(eb);
270 }
271
272 static int
273 i915_gem_execbuffer_relocate_entry(struct drm_i915_gem_object *obj,
274                                    struct eb_objects *eb,
275                                    struct drm_i915_gem_relocation_entry *reloc)
276 {
277         struct drm_device *dev = obj->base.dev;
278         struct drm_gem_object *target_obj;
279         uint32_t target_offset;
280         int ret = -EINVAL;
281
282         /* we've already hold a reference to all valid objects */
283         target_obj = &eb_get_object(eb, reloc->target_handle)->base;
284         if (unlikely(target_obj == NULL))
285                 return -ENOENT;
286
287         target_offset = to_intel_bo(target_obj)->gtt_offset;
288
289         /* The target buffer should have appeared before us in the
290          * exec_object list, so it should have a GTT space bound by now.
291          */
292         if (unlikely(target_offset == 0)) {
293                 DRM_ERROR("No GTT space found for object %d\n",
294                           reloc->target_handle);
295                 return ret;
296         }
297
298         /* Validate that the target is in a valid r/w GPU domain */
299         if (unlikely(reloc->write_domain & (reloc->write_domain - 1))) {
300                 DRM_ERROR("reloc with multiple write domains: "
301                           "obj %p target %d offset %d "
302                           "read %08x write %08x",
303                           obj, reloc->target_handle,
304                           (int) reloc->offset,
305                           reloc->read_domains,
306                           reloc->write_domain);
307                 return ret;
308         }
309         if (unlikely((reloc->write_domain | reloc->read_domains) & I915_GEM_DOMAIN_CPU)) {
310                 DRM_ERROR("reloc with read/write CPU domains: "
311                           "obj %p target %d offset %d "
312                           "read %08x write %08x",
313                           obj, reloc->target_handle,
314                           (int) reloc->offset,
315                           reloc->read_domains,
316                           reloc->write_domain);
317                 return ret;
318         }
319         if (unlikely(reloc->write_domain && target_obj->pending_write_domain &&
320                      reloc->write_domain != target_obj->pending_write_domain)) {
321                 DRM_ERROR("Write domain conflict: "
322                           "obj %p target %d offset %d "
323                           "new %08x old %08x\n",
324                           obj, reloc->target_handle,
325                           (int) reloc->offset,
326                           reloc->write_domain,
327                           target_obj->pending_write_domain);
328                 return ret;
329         }
330
331         target_obj->pending_read_domains |= reloc->read_domains;
332         target_obj->pending_write_domain |= reloc->write_domain;
333
334         /* If the relocation already has the right value in it, no
335          * more work needs to be done.
336          */
337         if (target_offset == reloc->presumed_offset)
338                 return 0;
339
340         /* Check that the relocation address is valid... */
341         if (unlikely(reloc->offset > obj->base.size - 4)) {
342                 DRM_ERROR("Relocation beyond object bounds: "
343                           "obj %p target %d offset %d size %d.\n",
344                           obj, reloc->target_handle,
345                           (int) reloc->offset,
346                           (int) obj->base.size);
347                 return ret;
348         }
349         if (unlikely(reloc->offset & 3)) {
350                 DRM_ERROR("Relocation not 4-byte aligned: "
351                           "obj %p target %d offset %d.\n",
352                           obj, reloc->target_handle,
353                           (int) reloc->offset);
354                 return ret;
355         }
356
357         reloc->delta += target_offset;
358         if (obj->base.write_domain == I915_GEM_DOMAIN_CPU) {
359                 uint32_t page_offset = reloc->offset & ~PAGE_MASK;
360                 char *vaddr;
361
362                 vaddr = kmap_atomic(obj->pages[reloc->offset >> PAGE_SHIFT]);
363                 *(uint32_t *)(vaddr + page_offset) = reloc->delta;
364                 kunmap_atomic(vaddr);
365         } else {
366                 struct drm_i915_private *dev_priv = dev->dev_private;
367                 uint32_t __iomem *reloc_entry;
368                 void __iomem *reloc_page;
369
370                 ret = i915_gem_object_set_to_gtt_domain(obj, 1);
371                 if (ret)
372                         return ret;
373
374                 /* Map the page containing the relocation we're going to perform.  */
375                 reloc->offset += obj->gtt_offset;
376                 reloc_page = io_mapping_map_atomic_wc(dev_priv->mm.gtt_mapping,
377                                                       reloc->offset & PAGE_MASK);
378                 reloc_entry = (uint32_t __iomem *)
379                         (reloc_page + (reloc->offset & ~PAGE_MASK));
380                 iowrite32(reloc->delta, reloc_entry);
381                 io_mapping_unmap_atomic(reloc_page);
382         }
383
384         /* and update the user's relocation entry */
385         reloc->presumed_offset = target_offset;
386
387         return 0;
388 }
389
390 static int
391 i915_gem_execbuffer_relocate_object(struct drm_i915_gem_object *obj,
392                                     struct eb_objects *eb)
393 {
394         struct drm_i915_gem_relocation_entry __user *user_relocs;
395         struct drm_i915_gem_exec_object2 *entry = obj->exec_entry;
396         int i, ret;
397
398         user_relocs = (void __user *)(uintptr_t)entry->relocs_ptr;
399         for (i = 0; i < entry->relocation_count; i++) {
400                 struct drm_i915_gem_relocation_entry reloc;
401
402                 if (__copy_from_user_inatomic(&reloc,
403                                               user_relocs+i,
404                                               sizeof(reloc)))
405                         return -EFAULT;
406
407                 ret = i915_gem_execbuffer_relocate_entry(obj, eb, &reloc);
408                 if (ret)
409                         return ret;
410
411                 if (__copy_to_user_inatomic(&user_relocs[i].presumed_offset,
412                                             &reloc.presumed_offset,
413                                             sizeof(reloc.presumed_offset)))
414                         return -EFAULT;
415         }
416
417         return 0;
418 }
419
420 static int
421 i915_gem_execbuffer_relocate_object_slow(struct drm_i915_gem_object *obj,
422                                          struct eb_objects *eb,
423                                          struct drm_i915_gem_relocation_entry *relocs)
424 {
425         const struct drm_i915_gem_exec_object2 *entry = obj->exec_entry;
426         int i, ret;
427
428         for (i = 0; i < entry->relocation_count; i++) {
429                 ret = i915_gem_execbuffer_relocate_entry(obj, eb, &relocs[i]);
430                 if (ret)
431                         return ret;
432         }
433
434         return 0;
435 }
436
437 static int
438 i915_gem_execbuffer_relocate(struct drm_device *dev,
439                              struct eb_objects *eb,
440                              struct list_head *objects)
441 {
442         struct drm_i915_gem_object *obj;
443         int ret;
444
445         list_for_each_entry(obj, objects, exec_list) {
446                 ret = i915_gem_execbuffer_relocate_object(obj, eb);
447                 if (ret)
448                         return ret;
449         }
450
451         return 0;
452 }
453
454 static int
455 i915_gem_execbuffer_reserve(struct intel_ring_buffer *ring,
456                             struct drm_file *file,
457                             struct list_head *objects)
458 {
459         struct drm_i915_gem_object *obj;
460         int ret, retry;
461         bool has_fenced_gpu_access = INTEL_INFO(ring->dev)->gen < 4;
462         struct list_head ordered_objects;
463
464         INIT_LIST_HEAD(&ordered_objects);
465         while (!list_empty(objects)) {
466                 struct drm_i915_gem_exec_object2 *entry;
467                 bool need_fence, need_mappable;
468
469                 obj = list_first_entry(objects,
470                                        struct drm_i915_gem_object,
471                                        exec_list);
472                 entry = obj->exec_entry;
473
474                 need_fence =
475                         has_fenced_gpu_access &&
476                         entry->flags & EXEC_OBJECT_NEEDS_FENCE &&
477                         obj->tiling_mode != I915_TILING_NONE;
478                 need_mappable =
479                         entry->relocation_count ? true : need_fence;
480
481                 if (need_mappable)
482                         list_move(&obj->exec_list, &ordered_objects);
483                 else
484                         list_move_tail(&obj->exec_list, &ordered_objects);
485
486                 obj->base.pending_read_domains = 0;
487                 obj->base.pending_write_domain = 0;
488         }
489         list_splice(&ordered_objects, objects);
490
491         /* Attempt to pin all of the buffers into the GTT.
492          * This is done in 3 phases:
493          *
494          * 1a. Unbind all objects that do not match the GTT constraints for
495          *     the execbuffer (fenceable, mappable, alignment etc).
496          * 1b. Increment pin count for already bound objects.
497          * 2.  Bind new objects.
498          * 3.  Decrement pin count.
499          *
500          * This avoid unnecessary unbinding of later objects in order to makr
501          * room for the earlier objects *unless* we need to defragment.
502          */
503         retry = 0;
504         do {
505                 ret = 0;
506
507                 /* Unbind any ill-fitting objects or pin. */
508                 list_for_each_entry(obj, objects, exec_list) {
509                         struct drm_i915_gem_exec_object2 *entry = obj->exec_entry;
510                         bool need_fence, need_mappable;
511                         if (!obj->gtt_space)
512                                 continue;
513
514                         need_fence =
515                                 has_fenced_gpu_access &&
516                                 entry->flags & EXEC_OBJECT_NEEDS_FENCE &&
517                                 obj->tiling_mode != I915_TILING_NONE;
518                         need_mappable =
519                                 entry->relocation_count ? true : need_fence;
520
521                         if ((entry->alignment && obj->gtt_offset & (entry->alignment - 1)) ||
522                             (need_mappable && !obj->map_and_fenceable))
523                                 ret = i915_gem_object_unbind(obj);
524                         else
525                                 ret = i915_gem_object_pin(obj,
526                                                           entry->alignment,
527                                                           need_mappable);
528                         if (ret)
529                                 goto err;
530
531                         entry++;
532                 }
533
534                 /* Bind fresh objects */
535                 list_for_each_entry(obj, objects, exec_list) {
536                         struct drm_i915_gem_exec_object2 *entry = obj->exec_entry;
537                         bool need_fence;
538
539                         need_fence =
540                                 has_fenced_gpu_access &&
541                                 entry->flags & EXEC_OBJECT_NEEDS_FENCE &&
542                                 obj->tiling_mode != I915_TILING_NONE;
543
544                         if (!obj->gtt_space) {
545                                 bool need_mappable =
546                                         entry->relocation_count ? true : need_fence;
547
548                                 ret = i915_gem_object_pin(obj,
549                                                           entry->alignment,
550                                                           need_mappable);
551                                 if (ret)
552                                         break;
553                         }
554
555                         if (has_fenced_gpu_access) {
556                                 if (need_fence) {
557                                         ret = i915_gem_object_get_fence(obj, ring);
558                                         if (ret)
559                                                 break;
560                                 } else if (entry->flags & EXEC_OBJECT_NEEDS_FENCE &&
561                                            obj->tiling_mode == I915_TILING_NONE) {
562                                         /* XXX pipelined! */
563                                         ret = i915_gem_object_put_fence(obj);
564                                         if (ret)
565                                                 break;
566                                 }
567                                 obj->pending_fenced_gpu_access = need_fence;
568                         }
569
570                         entry->offset = obj->gtt_offset;
571                 }
572
573                 /* Decrement pin count for bound objects */
574                 list_for_each_entry(obj, objects, exec_list) {
575                         if (obj->gtt_space)
576                                 i915_gem_object_unpin(obj);
577                 }
578
579                 if (ret != -ENOSPC || retry > 1)
580                         return ret;
581
582                 /* First attempt, just clear anything that is purgeable.
583                  * Second attempt, clear the entire GTT.
584                  */
585                 ret = i915_gem_evict_everything(ring->dev, retry == 0);
586                 if (ret)
587                         return ret;
588
589                 retry++;
590         } while (1);
591
592 err:
593         obj = list_entry(obj->exec_list.prev,
594                          struct drm_i915_gem_object,
595                          exec_list);
596         while (objects != &obj->exec_list) {
597                 if (obj->gtt_space)
598                         i915_gem_object_unpin(obj);
599
600                 obj = list_entry(obj->exec_list.prev,
601                                  struct drm_i915_gem_object,
602                                  exec_list);
603         }
604
605         return ret;
606 }
607
608 static int
609 i915_gem_execbuffer_relocate_slow(struct drm_device *dev,
610                                   struct drm_file *file,
611                                   struct intel_ring_buffer *ring,
612                                   struct list_head *objects,
613                                   struct eb_objects *eb,
614                                   struct drm_i915_gem_exec_object2 *exec,
615                                   int count)
616 {
617         struct drm_i915_gem_relocation_entry *reloc;
618         struct drm_i915_gem_object *obj;
619         int *reloc_offset;
620         int i, total, ret;
621
622         /* We may process another execbuffer during the unlock... */
623         while (!list_empty(objects)) {
624                 obj = list_first_entry(objects,
625                                        struct drm_i915_gem_object,
626                                        exec_list);
627                 list_del_init(&obj->exec_list);
628                 drm_gem_object_unreference(&obj->base);
629         }
630
631         mutex_unlock(&dev->struct_mutex);
632
633         total = 0;
634         for (i = 0; i < count; i++)
635                 total += exec[i].relocation_count;
636
637         reloc_offset = drm_malloc_ab(count, sizeof(*reloc_offset));
638         reloc = drm_malloc_ab(total, sizeof(*reloc));
639         if (reloc == NULL || reloc_offset == NULL) {
640                 drm_free_large(reloc);
641                 drm_free_large(reloc_offset);
642                 mutex_lock(&dev->struct_mutex);
643                 return -ENOMEM;
644         }
645
646         total = 0;
647         for (i = 0; i < count; i++) {
648                 struct drm_i915_gem_relocation_entry __user *user_relocs;
649
650                 user_relocs = (void __user *)(uintptr_t)exec[i].relocs_ptr;
651
652                 if (copy_from_user(reloc+total, user_relocs,
653                                    exec[i].relocation_count * sizeof(*reloc))) {
654                         ret = -EFAULT;
655                         mutex_lock(&dev->struct_mutex);
656                         goto err;
657                 }
658
659                 reloc_offset[i] = total;
660                 total += exec[i].relocation_count;
661         }
662
663         ret = i915_mutex_lock_interruptible(dev);
664         if (ret) {
665                 mutex_lock(&dev->struct_mutex);
666                 goto err;
667         }
668
669         /* reacquire the objects */
670         eb_reset(eb);
671         for (i = 0; i < count; i++) {
672                 obj = to_intel_bo(drm_gem_object_lookup(dev, file,
673                                                         exec[i].handle));
674                 if (&obj->base == NULL) {
675                         DRM_ERROR("Invalid object handle %d at index %d\n",
676                                    exec[i].handle, i);
677                         ret = -ENOENT;
678                         goto err;
679                 }
680
681                 list_add_tail(&obj->exec_list, objects);
682                 obj->exec_handle = exec[i].handle;
683                 obj->exec_entry = &exec[i];
684                 eb_add_object(eb, obj);
685         }
686
687         ret = i915_gem_execbuffer_reserve(ring, file, objects);
688         if (ret)
689                 goto err;
690
691         list_for_each_entry(obj, objects, exec_list) {
692                 int offset = obj->exec_entry - exec;
693                 ret = i915_gem_execbuffer_relocate_object_slow(obj, eb,
694                                                                reloc + reloc_offset[offset]);
695                 if (ret)
696                         goto err;
697         }
698
699         /* Leave the user relocations as are, this is the painfully slow path,
700          * and we want to avoid the complication of dropping the lock whilst
701          * having buffers reserved in the aperture and so causing spurious
702          * ENOSPC for random operations.
703          */
704
705 err:
706         drm_free_large(reloc);
707         drm_free_large(reloc_offset);
708         return ret;
709 }
710
711 static int
712 i915_gem_execbuffer_flush(struct drm_device *dev,
713                           uint32_t invalidate_domains,
714                           uint32_t flush_domains,
715                           uint32_t flush_rings)
716 {
717         drm_i915_private_t *dev_priv = dev->dev_private;
718         int i, ret;
719
720         if (flush_domains & I915_GEM_DOMAIN_CPU)
721                 intel_gtt_chipset_flush();
722
723         if (flush_domains & I915_GEM_DOMAIN_GTT)
724                 wmb();
725
726         if ((flush_domains | invalidate_domains) & I915_GEM_GPU_DOMAINS) {
727                 for (i = 0; i < I915_NUM_RINGS; i++)
728                         if (flush_rings & (1 << i)) {
729                                 ret = i915_gem_flush_ring(&dev_priv->ring[i],
730                                                           invalidate_domains,
731                                                           flush_domains);
732                                 if (ret)
733                                         return ret;
734                         }
735         }
736
737         return 0;
738 }
739
740 static int
741 i915_gem_execbuffer_sync_rings(struct drm_i915_gem_object *obj,
742                                struct intel_ring_buffer *to)
743 {
744         struct intel_ring_buffer *from = obj->ring;
745         u32 seqno;
746         int ret, idx;
747
748         if (from == NULL || to == from)
749                 return 0;
750
751         /* XXX gpu semaphores are implicated in various hard hangs on SNB */
752         if (INTEL_INFO(obj->base.dev)->gen < 6 || !i915_semaphores)
753                 return i915_gem_object_wait_rendering(obj);
754
755         idx = intel_ring_sync_index(from, to);
756
757         seqno = obj->last_rendering_seqno;
758         if (seqno <= from->sync_seqno[idx])
759                 return 0;
760
761         if (seqno == from->outstanding_lazy_request) {
762                 struct drm_i915_gem_request *request;
763
764                 request = kzalloc(sizeof(*request), GFP_KERNEL);
765                 if (request == NULL)
766                         return -ENOMEM;
767
768                 ret = i915_add_request(from, NULL, request);
769                 if (ret) {
770                         kfree(request);
771                         return ret;
772                 }
773
774                 seqno = request->seqno;
775         }
776
777         from->sync_seqno[idx] = seqno;
778         return intel_ring_sync(to, from, seqno - 1);
779 }
780
781 static int
782 i915_gem_execbuffer_wait_for_flips(struct intel_ring_buffer *ring, u32 flips)
783 {
784         u32 plane, flip_mask;
785         int ret;
786
787         /* Check for any pending flips. As we only maintain a flip queue depth
788          * of 1, we can simply insert a WAIT for the next display flip prior
789          * to executing the batch and avoid stalling the CPU.
790          */
791
792         for (plane = 0; flips >> plane; plane++) {
793                 if (((flips >> plane) & 1) == 0)
794                         continue;
795
796                 if (plane)
797                         flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
798                 else
799                         flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
800
801                 ret = intel_ring_begin(ring, 2);
802                 if (ret)
803                         return ret;
804
805                 intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
806                 intel_ring_emit(ring, MI_NOOP);
807                 intel_ring_advance(ring);
808         }
809
810         return 0;
811 }
812
813
814 static int
815 i915_gem_execbuffer_move_to_gpu(struct intel_ring_buffer *ring,
816                                 struct list_head *objects)
817 {
818         struct drm_i915_gem_object *obj;
819         struct change_domains cd;
820         int ret;
821
822         memset(&cd, 0, sizeof(cd));
823         list_for_each_entry(obj, objects, exec_list)
824                 i915_gem_object_set_to_gpu_domain(obj, ring, &cd);
825
826         if (cd.invalidate_domains | cd.flush_domains) {
827                 ret = i915_gem_execbuffer_flush(ring->dev,
828                                                 cd.invalidate_domains,
829                                                 cd.flush_domains,
830                                                 cd.flush_rings);
831                 if (ret)
832                         return ret;
833         }
834
835         if (cd.flips) {
836                 ret = i915_gem_execbuffer_wait_for_flips(ring, cd.flips);
837                 if (ret)
838                         return ret;
839         }
840
841         list_for_each_entry(obj, objects, exec_list) {
842                 ret = i915_gem_execbuffer_sync_rings(obj, ring);
843                 if (ret)
844                         return ret;
845         }
846
847         return 0;
848 }
849
850 static bool
851 i915_gem_check_execbuffer(struct drm_i915_gem_execbuffer2 *exec)
852 {
853         return ((exec->batch_start_offset | exec->batch_len) & 0x7) == 0;
854 }
855
856 static int
857 validate_exec_list(struct drm_i915_gem_exec_object2 *exec,
858                    int count)
859 {
860         int i;
861
862         for (i = 0; i < count; i++) {
863                 char __user *ptr = (char __user *)(uintptr_t)exec[i].relocs_ptr;
864                 int length; /* limited by fault_in_pages_readable() */
865
866                 /* First check for malicious input causing overflow */
867                 if (exec[i].relocation_count >
868                     INT_MAX / sizeof(struct drm_i915_gem_relocation_entry))
869                         return -EINVAL;
870
871                 length = exec[i].relocation_count *
872                         sizeof(struct drm_i915_gem_relocation_entry);
873                 if (!access_ok(VERIFY_READ, ptr, length))
874                         return -EFAULT;
875
876                 /* we may also need to update the presumed offsets */
877                 if (!access_ok(VERIFY_WRITE, ptr, length))
878                         return -EFAULT;
879
880                 if (fault_in_pages_readable(ptr, length))
881                         return -EFAULT;
882         }
883
884         return 0;
885 }
886
887 static void
888 i915_gem_execbuffer_move_to_active(struct list_head *objects,
889                                    struct intel_ring_buffer *ring,
890                                    u32 seqno)
891 {
892         struct drm_i915_gem_object *obj;
893
894         list_for_each_entry(obj, objects, exec_list) {
895                   u32 old_read = obj->base.read_domains;
896                   u32 old_write = obj->base.write_domain;
897
898
899                 obj->base.read_domains = obj->base.pending_read_domains;
900                 obj->base.write_domain = obj->base.pending_write_domain;
901                 obj->fenced_gpu_access = obj->pending_fenced_gpu_access;
902
903                 i915_gem_object_move_to_active(obj, ring, seqno);
904                 if (obj->base.write_domain) {
905                         obj->dirty = 1;
906                         obj->pending_gpu_write = true;
907                         list_move_tail(&obj->gpu_write_list,
908                                        &ring->gpu_write_list);
909                         intel_mark_busy(ring->dev, obj);
910                 }
911
912                 trace_i915_gem_object_change_domain(obj, old_read, old_write);
913         }
914 }
915
916 static void
917 i915_gem_execbuffer_retire_commands(struct drm_device *dev,
918                                     struct drm_file *file,
919                                     struct intel_ring_buffer *ring)
920 {
921         struct drm_i915_gem_request *request;
922         u32 invalidate;
923
924         /*
925          * Ensure that the commands in the batch buffer are
926          * finished before the interrupt fires.
927          *
928          * The sampler always gets flushed on i965 (sigh).
929          */
930         invalidate = I915_GEM_DOMAIN_COMMAND;
931         if (INTEL_INFO(dev)->gen >= 4)
932                 invalidate |= I915_GEM_DOMAIN_SAMPLER;
933         if (ring->flush(ring, invalidate, 0)) {
934                 i915_gem_next_request_seqno(ring);
935                 return;
936         }
937
938         /* Add a breadcrumb for the completion of the batch buffer */
939         request = kzalloc(sizeof(*request), GFP_KERNEL);
940         if (request == NULL || i915_add_request(ring, file, request)) {
941                 i915_gem_next_request_seqno(ring);
942                 kfree(request);
943         }
944 }
945
946 static int
947 i915_gem_do_execbuffer(struct drm_device *dev, void *data,
948                        struct drm_file *file,
949                        struct drm_i915_gem_execbuffer2 *args,
950                        struct drm_i915_gem_exec_object2 *exec)
951 {
952         drm_i915_private_t *dev_priv = dev->dev_private;
953         struct list_head objects;
954         struct eb_objects *eb;
955         struct drm_i915_gem_object *batch_obj;
956         struct drm_clip_rect *cliprects = NULL;
957         struct intel_ring_buffer *ring;
958         u32 exec_start, exec_len;
959         u32 seqno;
960         int ret, mode, i;
961
962         if (!i915_gem_check_execbuffer(args)) {
963                 DRM_ERROR("execbuf with invalid offset/length\n");
964                 return -EINVAL;
965         }
966
967         ret = validate_exec_list(exec, args->buffer_count);
968         if (ret)
969                 return ret;
970
971         switch (args->flags & I915_EXEC_RING_MASK) {
972         case I915_EXEC_DEFAULT:
973         case I915_EXEC_RENDER:
974                 ring = &dev_priv->ring[RCS];
975                 break;
976         case I915_EXEC_BSD:
977                 if (!HAS_BSD(dev)) {
978                         DRM_ERROR("execbuf with invalid ring (BSD)\n");
979                         return -EINVAL;
980                 }
981                 ring = &dev_priv->ring[VCS];
982                 break;
983         case I915_EXEC_BLT:
984                 if (!HAS_BLT(dev)) {
985                         DRM_ERROR("execbuf with invalid ring (BLT)\n");
986                         return -EINVAL;
987                 }
988                 ring = &dev_priv->ring[BCS];
989                 break;
990         default:
991                 DRM_ERROR("execbuf with unknown ring: %d\n",
992                           (int)(args->flags & I915_EXEC_RING_MASK));
993                 return -EINVAL;
994         }
995
996         mode = args->flags & I915_EXEC_CONSTANTS_MASK;
997         switch (mode) {
998         case I915_EXEC_CONSTANTS_REL_GENERAL:
999         case I915_EXEC_CONSTANTS_ABSOLUTE:
1000         case I915_EXEC_CONSTANTS_REL_SURFACE:
1001                 if (ring == &dev_priv->ring[RCS] &&
1002                     mode != dev_priv->relative_constants_mode) {
1003                         if (INTEL_INFO(dev)->gen < 4)
1004                                 return -EINVAL;
1005
1006                         if (INTEL_INFO(dev)->gen > 5 &&
1007                             mode == I915_EXEC_CONSTANTS_REL_SURFACE)
1008                                 return -EINVAL;
1009
1010                         ret = intel_ring_begin(ring, 4);
1011                         if (ret)
1012                                 return ret;
1013
1014                         intel_ring_emit(ring, MI_NOOP);
1015                         intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
1016                         intel_ring_emit(ring, INSTPM);
1017                         intel_ring_emit(ring,
1018                                         I915_EXEC_CONSTANTS_MASK << 16 | mode);
1019                         intel_ring_advance(ring);
1020
1021                         dev_priv->relative_constants_mode = mode;
1022                 }
1023                 break;
1024         default:
1025                 DRM_ERROR("execbuf with unknown constants: %d\n", mode);
1026                 return -EINVAL;
1027         }
1028
1029         if (args->buffer_count < 1) {
1030                 DRM_ERROR("execbuf with %d buffers\n", args->buffer_count);
1031                 return -EINVAL;
1032         }
1033
1034         if (args->num_cliprects != 0) {
1035                 if (ring != &dev_priv->ring[RCS]) {
1036                         DRM_ERROR("clip rectangles are only valid with the render ring\n");
1037                         return -EINVAL;
1038                 }
1039
1040                 cliprects = kmalloc(args->num_cliprects * sizeof(*cliprects),
1041                                     GFP_KERNEL);
1042                 if (cliprects == NULL) {
1043                         ret = -ENOMEM;
1044                         goto pre_mutex_err;
1045                 }
1046
1047                 if (copy_from_user(cliprects,
1048                                      (struct drm_clip_rect __user *)(uintptr_t)
1049                                      args->cliprects_ptr,
1050                                      sizeof(*cliprects)*args->num_cliprects)) {
1051                         ret = -EFAULT;
1052                         goto pre_mutex_err;
1053                 }
1054         }
1055
1056         ret = i915_mutex_lock_interruptible(dev);
1057         if (ret)
1058                 goto pre_mutex_err;
1059
1060         if (dev_priv->mm.suspended) {
1061                 mutex_unlock(&dev->struct_mutex);
1062                 ret = -EBUSY;
1063                 goto pre_mutex_err;
1064         }
1065
1066         eb = eb_create(args->buffer_count);
1067         if (eb == NULL) {
1068                 mutex_unlock(&dev->struct_mutex);
1069                 ret = -ENOMEM;
1070                 goto pre_mutex_err;
1071         }
1072
1073         /* Look up object handles */
1074         INIT_LIST_HEAD(&objects);
1075         for (i = 0; i < args->buffer_count; i++) {
1076                 struct drm_i915_gem_object *obj;
1077
1078                 obj = to_intel_bo(drm_gem_object_lookup(dev, file,
1079                                                         exec[i].handle));
1080                 if (&obj->base == NULL) {
1081                         DRM_ERROR("Invalid object handle %d at index %d\n",
1082                                    exec[i].handle, i);
1083                         /* prevent error path from reading uninitialized data */
1084                         ret = -ENOENT;
1085                         goto err;
1086                 }
1087
1088                 if (!list_empty(&obj->exec_list)) {
1089                         DRM_ERROR("Object %p [handle %d, index %d] appears more than once in object list\n",
1090                                    obj, exec[i].handle, i);
1091                         ret = -EINVAL;
1092                         goto err;
1093                 }
1094
1095                 list_add_tail(&obj->exec_list, &objects);
1096                 obj->exec_handle = exec[i].handle;
1097                 obj->exec_entry = &exec[i];
1098                 eb_add_object(eb, obj);
1099         }
1100
1101         /* take note of the batch buffer before we might reorder the lists */
1102         batch_obj = list_entry(objects.prev,
1103                                struct drm_i915_gem_object,
1104                                exec_list);
1105
1106         /* Move the objects en-masse into the GTT, evicting if necessary. */
1107         ret = i915_gem_execbuffer_reserve(ring, file, &objects);
1108         if (ret)
1109                 goto err;
1110
1111         /* The objects are in their final locations, apply the relocations. */
1112         ret = i915_gem_execbuffer_relocate(dev, eb, &objects);
1113         if (ret) {
1114                 if (ret == -EFAULT) {
1115                         ret = i915_gem_execbuffer_relocate_slow(dev, file, ring,
1116                                                                 &objects, eb,
1117                                                                 exec,
1118                                                                 args->buffer_count);
1119                         BUG_ON(!mutex_is_locked(&dev->struct_mutex));
1120                 }
1121                 if (ret)
1122                         goto err;
1123         }
1124
1125         /* Set the pending read domains for the batch buffer to COMMAND */
1126         if (batch_obj->base.pending_write_domain) {
1127                 DRM_ERROR("Attempting to use self-modifying batch buffer\n");
1128                 ret = -EINVAL;
1129                 goto err;
1130         }
1131         batch_obj->base.pending_read_domains |= I915_GEM_DOMAIN_COMMAND;
1132
1133         ret = i915_gem_execbuffer_move_to_gpu(ring, &objects);
1134         if (ret)
1135                 goto err;
1136
1137         seqno = i915_gem_next_request_seqno(ring);
1138         for (i = 0; i < ARRAY_SIZE(ring->sync_seqno); i++) {
1139                 if (seqno < ring->sync_seqno[i]) {
1140                         /* The GPU can not handle its semaphore value wrapping,
1141                          * so every billion or so execbuffers, we need to stall
1142                          * the GPU in order to reset the counters.
1143                          */
1144                         ret = i915_gpu_idle(dev);
1145                         if (ret)
1146                                 goto err;
1147
1148                         BUG_ON(ring->sync_seqno[i]);
1149                 }
1150         }
1151
1152         trace_i915_gem_ring_dispatch(ring, seqno);
1153
1154         exec_start = batch_obj->gtt_offset + args->batch_start_offset;
1155         exec_len = args->batch_len;
1156         if (cliprects) {
1157                 for (i = 0; i < args->num_cliprects; i++) {
1158                         ret = i915_emit_box(dev, &cliprects[i],
1159                                             args->DR1, args->DR4);
1160                         if (ret)
1161                                 goto err;
1162
1163                         ret = ring->dispatch_execbuffer(ring,
1164                                                         exec_start, exec_len);
1165                         if (ret)
1166                                 goto err;
1167                 }
1168         } else {
1169                 ret = ring->dispatch_execbuffer(ring, exec_start, exec_len);
1170                 if (ret)
1171                         goto err;
1172         }
1173
1174         i915_gem_execbuffer_move_to_active(&objects, ring, seqno);
1175         i915_gem_execbuffer_retire_commands(dev, file, ring);
1176
1177 err:
1178         eb_destroy(eb);
1179         while (!list_empty(&objects)) {
1180                 struct drm_i915_gem_object *obj;
1181
1182                 obj = list_first_entry(&objects,
1183                                        struct drm_i915_gem_object,
1184                                        exec_list);
1185                 list_del_init(&obj->exec_list);
1186                 drm_gem_object_unreference(&obj->base);
1187         }
1188
1189         mutex_unlock(&dev->struct_mutex);
1190
1191 pre_mutex_err:
1192         kfree(cliprects);
1193         return ret;
1194 }
1195
1196 /*
1197  * Legacy execbuffer just creates an exec2 list from the original exec object
1198  * list array and passes it to the real function.
1199  */
1200 int
1201 i915_gem_execbuffer(struct drm_device *dev, void *data,
1202                     struct drm_file *file)
1203 {
1204         struct drm_i915_gem_execbuffer *args = data;
1205         struct drm_i915_gem_execbuffer2 exec2;
1206         struct drm_i915_gem_exec_object *exec_list = NULL;
1207         struct drm_i915_gem_exec_object2 *exec2_list = NULL;
1208         int ret, i;
1209
1210         if (args->buffer_count < 1) {
1211                 DRM_ERROR("execbuf with %d buffers\n", args->buffer_count);
1212                 return -EINVAL;
1213         }
1214
1215         /* Copy in the exec list from userland */
1216         exec_list = drm_malloc_ab(sizeof(*exec_list), args->buffer_count);
1217         exec2_list = drm_malloc_ab(sizeof(*exec2_list), args->buffer_count);
1218         if (exec_list == NULL || exec2_list == NULL) {
1219                 DRM_ERROR("Failed to allocate exec list for %d buffers\n",
1220                           args->buffer_count);
1221                 drm_free_large(exec_list);
1222                 drm_free_large(exec2_list);
1223                 return -ENOMEM;
1224         }
1225         ret = copy_from_user(exec_list,
1226                              (struct drm_i915_relocation_entry __user *)
1227                              (uintptr_t) args->buffers_ptr,
1228                              sizeof(*exec_list) * args->buffer_count);
1229         if (ret != 0) {
1230                 DRM_ERROR("copy %d exec entries failed %d\n",
1231                           args->buffer_count, ret);
1232                 drm_free_large(exec_list);
1233                 drm_free_large(exec2_list);
1234                 return -EFAULT;
1235         }
1236
1237         for (i = 0; i < args->buffer_count; i++) {
1238                 exec2_list[i].handle = exec_list[i].handle;
1239                 exec2_list[i].relocation_count = exec_list[i].relocation_count;
1240                 exec2_list[i].relocs_ptr = exec_list[i].relocs_ptr;
1241                 exec2_list[i].alignment = exec_list[i].alignment;
1242                 exec2_list[i].offset = exec_list[i].offset;
1243                 if (INTEL_INFO(dev)->gen < 4)
1244                         exec2_list[i].flags = EXEC_OBJECT_NEEDS_FENCE;
1245                 else
1246                         exec2_list[i].flags = 0;
1247         }
1248
1249         exec2.buffers_ptr = args->buffers_ptr;
1250         exec2.buffer_count = args->buffer_count;
1251         exec2.batch_start_offset = args->batch_start_offset;
1252         exec2.batch_len = args->batch_len;
1253         exec2.DR1 = args->DR1;
1254         exec2.DR4 = args->DR4;
1255         exec2.num_cliprects = args->num_cliprects;
1256         exec2.cliprects_ptr = args->cliprects_ptr;
1257         exec2.flags = I915_EXEC_RENDER;
1258
1259         ret = i915_gem_do_execbuffer(dev, data, file, &exec2, exec2_list);
1260         if (!ret) {
1261                 /* Copy the new buffer offsets back to the user's exec list. */
1262                 for (i = 0; i < args->buffer_count; i++)
1263                         exec_list[i].offset = exec2_list[i].offset;
1264                 /* ... and back out to userspace */
1265                 ret = copy_to_user((struct drm_i915_relocation_entry __user *)
1266                                    (uintptr_t) args->buffers_ptr,
1267                                    exec_list,
1268                                    sizeof(*exec_list) * args->buffer_count);
1269                 if (ret) {
1270                         ret = -EFAULT;
1271                         DRM_ERROR("failed to copy %d exec entries "
1272                                   "back to user (%d)\n",
1273                                   args->buffer_count, ret);
1274                 }
1275         }
1276
1277         drm_free_large(exec_list);
1278         drm_free_large(exec2_list);
1279         return ret;
1280 }
1281
1282 int
1283 i915_gem_execbuffer2(struct drm_device *dev, void *data,
1284                      struct drm_file *file)
1285 {
1286         struct drm_i915_gem_execbuffer2 *args = data;
1287         struct drm_i915_gem_exec_object2 *exec2_list = NULL;
1288         int ret;
1289
1290         if (args->buffer_count < 1) {
1291                 DRM_ERROR("execbuf2 with %d buffers\n", args->buffer_count);
1292                 return -EINVAL;
1293         }
1294
1295         exec2_list = kmalloc(sizeof(*exec2_list)*args->buffer_count,
1296                              GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY);
1297         if (exec2_list == NULL)
1298                 exec2_list = drm_malloc_ab(sizeof(*exec2_list),
1299                                            args->buffer_count);
1300         if (exec2_list == NULL) {
1301                 DRM_ERROR("Failed to allocate exec list for %d buffers\n",
1302                           args->buffer_count);
1303                 return -ENOMEM;
1304         }
1305         ret = copy_from_user(exec2_list,
1306                              (struct drm_i915_relocation_entry __user *)
1307                              (uintptr_t) args->buffers_ptr,
1308                              sizeof(*exec2_list) * args->buffer_count);
1309         if (ret != 0) {
1310                 DRM_ERROR("copy %d exec entries failed %d\n",
1311                           args->buffer_count, ret);
1312                 drm_free_large(exec2_list);
1313                 return -EFAULT;
1314         }
1315
1316         ret = i915_gem_do_execbuffer(dev, data, file, args, exec2_list);
1317         if (!ret) {
1318                 /* Copy the new buffer offsets back to the user's exec list. */
1319                 ret = copy_to_user((struct drm_i915_relocation_entry __user *)
1320                                    (uintptr_t) args->buffers_ptr,
1321                                    exec2_list,
1322                                    sizeof(*exec2_list) * args->buffer_count);
1323                 if (ret) {
1324                         ret = -EFAULT;
1325                         DRM_ERROR("failed to copy %d exec entries "
1326                                   "back to user (%d)\n",
1327                                   args->buffer_count, ret);
1328                 }
1329         }
1330
1331         drm_free_large(exec2_list);
1332         return ret;
1333 }