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