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/pagemap.h>
35 
36 #define  __EXEC_OBJECT_HAS_PIN (1<<31)
37 #define  __EXEC_OBJECT_HAS_FENCE (1<<30)
38 #define  __EXEC_OBJECT_NEEDS_MAP (1<<29)
39 #define  __EXEC_OBJECT_NEEDS_BIAS (1<<28)
40 #define  __EXEC_OBJECT_PURGEABLE (1<<27)
41 
42 #define BATCH_OFFSET_BIAS (256*1024)
43 
44 struct eb_vmas {
45 	struct list_head vmas;
46 	int and;
47 	union {
48 		struct i915_vma *lut[0];
49 		struct hlist_head buckets[0];
50 	};
51 };
52 
53 static struct eb_vmas *
54 eb_create(struct drm_i915_gem_execbuffer2 *args)
55 {
56 	struct eb_vmas *eb = NULL;
57 
58 	if (args->flags & I915_EXEC_HANDLE_LUT) {
59 		unsigned size = args->buffer_count;
60 		size *= sizeof(struct i915_vma *);
61 		size += sizeof(struct eb_vmas);
62 		eb = kmalloc(size, M_DRM, M_NOWAIT);
63 	}
64 
65 	if (eb == NULL) {
66 		unsigned size = args->buffer_count;
67 		unsigned count = PAGE_SIZE / sizeof(struct hlist_head) / 2;
68 		BUILD_BUG_ON_NOT_POWER_OF_2(PAGE_SIZE / sizeof(struct hlist_head));
69 		while (count > 2*size)
70 			count >>= 1;
71 		eb = kzalloc(count*sizeof(struct hlist_head) +
72 			     sizeof(struct eb_vmas),
73 			     GFP_TEMPORARY);
74 		if (eb == NULL)
75 			return eb;
76 
77 		eb->and = count - 1;
78 	} else
79 		eb->and = -args->buffer_count;
80 
81 	INIT_LIST_HEAD(&eb->vmas);
82 	return eb;
83 }
84 
85 static void
86 eb_reset(struct eb_vmas *eb)
87 {
88 	if (eb->and >= 0)
89 		memset(eb->buckets, 0, (eb->and+1)*sizeof(struct hlist_head));
90 }
91 
92 static int
93 eb_lookup_vmas(struct eb_vmas *eb,
94 	       struct drm_i915_gem_exec_object2 *exec,
95 	       const struct drm_i915_gem_execbuffer2 *args,
96 	       struct i915_address_space *vm,
97 	       struct drm_file *file)
98 {
99 	struct drm_i915_gem_object *obj;
100 	struct list_head objects;
101 	int i, ret;
102 
103 	INIT_LIST_HEAD(&objects);
104 	lockmgr(&file->table_lock, LK_EXCLUSIVE);
105 	/* Grab a reference to the object and release the lock so we can lookup
106 	 * or create the VMA without using GFP_ATOMIC */
107 	for (i = 0; i < args->buffer_count; i++) {
108 		obj = to_intel_bo(idr_find(&file->object_idr, exec[i].handle));
109 		if (obj == NULL) {
110 			lockmgr(&file->table_lock, LK_RELEASE);
111 			DRM_DEBUG("Invalid object handle %d at index %d\n",
112 				   exec[i].handle, i);
113 			ret = -ENOENT;
114 			goto err;
115 		}
116 
117 		if (!list_empty(&obj->obj_exec_link)) {
118 			lockmgr(&file->table_lock, LK_RELEASE);
119 			DRM_DEBUG("Object %p [handle %d, index %d] appears more than once in object list\n",
120 				   obj, exec[i].handle, i);
121 			ret = -EINVAL;
122 			goto err;
123 		}
124 
125 		drm_gem_object_reference(&obj->base);
126 		list_add_tail(&obj->obj_exec_link, &objects);
127 	}
128 	lockmgr(&file->table_lock, LK_RELEASE);
129 
130 	i = 0;
131 	while (!list_empty(&objects)) {
132 		struct i915_vma *vma;
133 
134 		obj = list_first_entry(&objects,
135 				       struct drm_i915_gem_object,
136 				       obj_exec_link);
137 
138 		/*
139 		 * NOTE: We can leak any vmas created here when something fails
140 		 * later on. But that's no issue since vma_unbind can deal with
141 		 * vmas which are not actually bound. And since only
142 		 * lookup_or_create exists as an interface to get at the vma
143 		 * from the (obj, vm) we don't run the risk of creating
144 		 * duplicated vmas for the same vm.
145 		 */
146 		vma = i915_gem_obj_lookup_or_create_vma(obj, vm);
147 		if (IS_ERR(vma)) {
148 			DRM_DEBUG("Failed to lookup VMA\n");
149 			ret = PTR_ERR(vma);
150 			goto err;
151 		}
152 
153 		/* Transfer ownership from the objects list to the vmas list. */
154 		list_add_tail(&vma->exec_list, &eb->vmas);
155 		list_del_init(&obj->obj_exec_link);
156 
157 		vma->exec_entry = &exec[i];
158 		if (eb->and < 0) {
159 			eb->lut[i] = vma;
160 		} else {
161 			uint32_t handle = args->flags & I915_EXEC_HANDLE_LUT ? i : exec[i].handle;
162 			vma->exec_handle = handle;
163 			hlist_add_head(&vma->exec_node,
164 				       &eb->buckets[handle & eb->and]);
165 		}
166 		++i;
167 	}
168 
169 	return 0;
170 
171 
172 err:
173 	while (!list_empty(&objects)) {
174 		obj = list_first_entry(&objects,
175 				       struct drm_i915_gem_object,
176 				       obj_exec_link);
177 		list_del_init(&obj->obj_exec_link);
178 		drm_gem_object_unreference(&obj->base);
179 	}
180 	/*
181 	 * Objects already transfered to the vmas list will be unreferenced by
182 	 * eb_destroy.
183 	 */
184 
185 	return ret;
186 }
187 
188 static struct i915_vma *eb_get_vma(struct eb_vmas *eb, unsigned long handle)
189 {
190 	if (eb->and < 0) {
191 		if (handle >= -eb->and)
192 			return NULL;
193 		return eb->lut[handle];
194 	} else {
195 		struct hlist_head *head;
196 		struct hlist_node *node;
197 
198 		head = &eb->buckets[handle & eb->and];
199 		hlist_for_each(node, head) {
200 			struct i915_vma *vma;
201 
202 			vma = hlist_entry(node, struct i915_vma, exec_node);
203 			if (vma->exec_handle == handle)
204 				return vma;
205 		}
206 		return NULL;
207 	}
208 }
209 
210 static void
211 i915_gem_execbuffer_unreserve_vma(struct i915_vma *vma)
212 {
213 	struct drm_i915_gem_exec_object2 *entry;
214 	struct drm_i915_gem_object *obj = vma->obj;
215 
216 	if (!drm_mm_node_allocated(&vma->node))
217 		return;
218 
219 	entry = vma->exec_entry;
220 
221 	if (entry->flags & __EXEC_OBJECT_HAS_FENCE)
222 		i915_gem_object_unpin_fence(obj);
223 
224 	if (entry->flags & __EXEC_OBJECT_HAS_PIN)
225 		vma->pin_count--;
226 
227 	if (entry->flags & __EXEC_OBJECT_PURGEABLE)
228 		obj->madv = I915_MADV_DONTNEED;
229 
230 	entry->flags &= ~(__EXEC_OBJECT_HAS_FENCE |
231 			  __EXEC_OBJECT_HAS_PIN |
232 			  __EXEC_OBJECT_PURGEABLE);
233 }
234 
235 static void eb_destroy(struct eb_vmas *eb)
236 {
237 	while (!list_empty(&eb->vmas)) {
238 		struct i915_vma *vma;
239 
240 		vma = list_first_entry(&eb->vmas,
241 				       struct i915_vma,
242 				       exec_list);
243 		list_del_init(&vma->exec_list);
244 		i915_gem_execbuffer_unreserve_vma(vma);
245 		drm_gem_object_unreference(&vma->obj->base);
246 	}
247 	kfree(eb);
248 }
249 
250 static inline int use_cpu_reloc(struct drm_i915_gem_object *obj)
251 {
252 	return (HAS_LLC(obj->base.dev) ||
253 		obj->base.write_domain == I915_GEM_DOMAIN_CPU ||
254 		!obj->map_and_fenceable ||
255 		obj->cache_level != I915_CACHE_NONE);
256 }
257 
258 static int
259 relocate_entry_cpu(struct drm_i915_gem_object *obj,
260 		   struct drm_i915_gem_relocation_entry *reloc,
261 		   uint64_t target_offset)
262 {
263 	struct drm_device *dev = obj->base.dev;
264 	uint32_t page_offset = offset_in_page(reloc->offset);
265 	uint64_t delta = reloc->delta + target_offset;
266 	char *vaddr;
267 	int ret;
268 
269 	ret = i915_gem_object_set_to_cpu_domain(obj, true);
270 	if (ret)
271 		return ret;
272 
273 	vaddr = kmap_atomic(i915_gem_object_get_page(obj,
274 				reloc->offset >> PAGE_SHIFT));
275 	*(uint32_t *)(vaddr + page_offset) = lower_32_bits(delta);
276 
277 	if (INTEL_INFO(dev)->gen >= 8) {
278 		page_offset = offset_in_page(page_offset + sizeof(uint32_t));
279 
280 		if (page_offset == 0) {
281 			kunmap_atomic(vaddr);
282 			vaddr = kmap_atomic(i915_gem_object_get_page(obj,
283 			    (reloc->offset + sizeof(uint32_t)) >> PAGE_SHIFT));
284 		}
285 
286 		*(uint32_t *)(vaddr + page_offset) = upper_32_bits(delta);
287 	}
288 
289 	kunmap_atomic(vaddr);
290 
291 	return 0;
292 }
293 
294 static int
295 relocate_entry_gtt(struct drm_i915_gem_object *obj,
296 		   struct drm_i915_gem_relocation_entry *reloc,
297 		   uint64_t target_offset)
298 {
299 	struct drm_device *dev = obj->base.dev;
300 	struct drm_i915_private *dev_priv = dev->dev_private;
301 	uint64_t delta = reloc->delta + target_offset;
302 	uint64_t offset;
303 	void __iomem *reloc_page;
304 	int ret;
305 
306 	ret = i915_gem_object_set_to_gtt_domain(obj, true);
307 	if (ret)
308 		return ret;
309 
310 	ret = i915_gem_object_put_fence(obj);
311 	if (ret)
312 		return ret;
313 
314 	/* Map the page containing the relocation we're going to perform.  */
315 	offset = i915_gem_obj_ggtt_offset(obj);
316 	offset += reloc->offset;
317 	reloc_page = io_mapping_map_atomic_wc(dev_priv->gtt.mappable,
318 					      offset & ~PAGE_MASK);
319 	iowrite32(lower_32_bits(delta), reloc_page + offset_in_page(offset));
320 
321 	if (INTEL_INFO(dev)->gen >= 8) {
322 		offset += sizeof(uint32_t);
323 
324 		if (offset_in_page(offset) == 0) {
325 			io_mapping_unmap_atomic(reloc_page);
326 			reloc_page =
327 				io_mapping_map_atomic_wc(dev_priv->gtt.mappable,
328 							 offset);
329 		}
330 
331 		iowrite32(upper_32_bits(delta),
332 			  reloc_page + offset_in_page(offset));
333 	}
334 
335 	io_mapping_unmap_atomic(reloc_page);
336 
337 	return 0;
338 }
339 
340 static int
341 i915_gem_execbuffer_relocate_entry(struct drm_i915_gem_object *obj,
342 				   struct eb_vmas *eb,
343 				   struct drm_i915_gem_relocation_entry *reloc)
344 {
345 	struct drm_device *dev = obj->base.dev;
346 	struct drm_gem_object *target_obj;
347 	struct drm_i915_gem_object *target_i915_obj;
348 	struct i915_vma *target_vma;
349 	uint64_t target_offset;
350 	int ret;
351 
352 	/* we've already hold a reference to all valid objects */
353 	target_vma = eb_get_vma(eb, reloc->target_handle);
354 	if (unlikely(target_vma == NULL))
355 		return -ENOENT;
356 	target_i915_obj = target_vma->obj;
357 	target_obj = &target_vma->obj->base;
358 
359 	target_offset = target_vma->node.start;
360 
361 	/* Sandybridge PPGTT errata: We need a global gtt mapping for MI and
362 	 * pipe_control writes because the gpu doesn't properly redirect them
363 	 * through the ppgtt for non_secure batchbuffers. */
364 	if (unlikely(IS_GEN6(dev) &&
365 	    reloc->write_domain == I915_GEM_DOMAIN_INSTRUCTION &&
366 	    !(target_vma->bound & GLOBAL_BIND))) {
367 		ret = i915_vma_bind(target_vma, target_i915_obj->cache_level,
368 				    GLOBAL_BIND);
369 		if (WARN_ONCE(ret, "Unexpected failure to bind target VMA!"))
370 			return ret;
371 	}
372 
373 	/* Validate that the target is in a valid r/w GPU domain */
374 	if (unlikely(reloc->write_domain & (reloc->write_domain - 1))) {
375 		DRM_DEBUG("reloc with multiple write domains: "
376 			  "obj %p target %d offset %d "
377 			  "read %08x write %08x",
378 			  obj, reloc->target_handle,
379 			  (int) reloc->offset,
380 			  reloc->read_domains,
381 			  reloc->write_domain);
382 		return -EINVAL;
383 	}
384 	if (unlikely((reloc->write_domain | reloc->read_domains)
385 		     & ~I915_GEM_GPU_DOMAINS)) {
386 		DRM_DEBUG("reloc with read/write non-GPU domains: "
387 			  "obj %p target %d offset %d "
388 			  "read %08x write %08x",
389 			  obj, reloc->target_handle,
390 			  (int) reloc->offset,
391 			  reloc->read_domains,
392 			  reloc->write_domain);
393 		return -EINVAL;
394 	}
395 
396 	target_obj->pending_read_domains |= reloc->read_domains;
397 	target_obj->pending_write_domain |= reloc->write_domain;
398 
399 	/* If the relocation already has the right value in it, no
400 	 * more work needs to be done.
401 	 */
402 	if (target_offset == reloc->presumed_offset)
403 		return 0;
404 
405 	/* Check that the relocation address is valid... */
406 	if (unlikely(reloc->offset >
407 		obj->base.size - (INTEL_INFO(dev)->gen >= 8 ? 8 : 4))) {
408 		DRM_DEBUG("Relocation beyond object bounds: "
409 			  "obj %p target %d offset %d size %d.\n",
410 			  obj, reloc->target_handle,
411 			  (int) reloc->offset,
412 			  (int) obj->base.size);
413 		return -EINVAL;
414 	}
415 	if (unlikely(reloc->offset & 3)) {
416 		DRM_DEBUG("Relocation not 4-byte aligned: "
417 			  "obj %p target %d offset %d.\n",
418 			  obj, reloc->target_handle,
419 			  (int) reloc->offset);
420 		return -EINVAL;
421 	}
422 
423 	/* We can't wait for rendering with pagefaults disabled */
424 	if (obj->active && (curthread->td_flags & TDF_NOFAULT))
425 		return -EFAULT;
426 
427 	if (use_cpu_reloc(obj))
428 		ret = relocate_entry_cpu(obj, reloc, target_offset);
429 	else
430 		ret = relocate_entry_gtt(obj, reloc, target_offset);
431 
432 	if (ret)
433 		return ret;
434 
435 	/* and update the user's relocation entry */
436 	reloc->presumed_offset = target_offset;
437 
438 	return 0;
439 }
440 
441 static int
442 i915_gem_execbuffer_relocate_vma(struct i915_vma *vma,
443 				 struct eb_vmas *eb)
444 {
445 #define N_RELOC(x) ((x) / sizeof(struct drm_i915_gem_relocation_entry))
446 	struct drm_i915_gem_relocation_entry stack_reloc[N_RELOC(512)];
447 	struct drm_i915_gem_relocation_entry __user *user_relocs;
448 	struct drm_i915_gem_exec_object2 *entry = vma->exec_entry;
449 	int remain, ret;
450 
451 	user_relocs = to_user_ptr(entry->relocs_ptr);
452 
453 	remain = entry->relocation_count;
454 	while (remain) {
455 		struct drm_i915_gem_relocation_entry *r = stack_reloc;
456 		int count = remain;
457 		if (count > ARRAY_SIZE(stack_reloc))
458 			count = ARRAY_SIZE(stack_reloc);
459 		remain -= count;
460 
461 		if (__copy_from_user_inatomic(r, user_relocs, count*sizeof(r[0])))
462 			return -EFAULT;
463 
464 		do {
465 			u64 offset = r->presumed_offset;
466 
467 			ret = i915_gem_execbuffer_relocate_entry(vma->obj, eb, r);
468 			if (ret)
469 				return ret;
470 
471 			if (r->presumed_offset != offset &&
472 			    __copy_to_user_inatomic(&user_relocs->presumed_offset,
473 						    &r->presumed_offset,
474 						    sizeof(r->presumed_offset))) {
475 				return -EFAULT;
476 			}
477 
478 			user_relocs++;
479 			r++;
480 		} while (--count);
481 	}
482 
483 	return 0;
484 #undef N_RELOC
485 }
486 
487 static int
488 i915_gem_execbuffer_relocate_vma_slow(struct i915_vma *vma,
489 				      struct eb_vmas *eb,
490 				      struct drm_i915_gem_relocation_entry *relocs)
491 {
492 	const struct drm_i915_gem_exec_object2 *entry = vma->exec_entry;
493 	int i, ret;
494 
495 	for (i = 0; i < entry->relocation_count; i++) {
496 		ret = i915_gem_execbuffer_relocate_entry(vma->obj, eb, &relocs[i]);
497 		if (ret)
498 			return ret;
499 	}
500 
501 	return 0;
502 }
503 
504 static int
505 i915_gem_execbuffer_relocate(struct eb_vmas *eb)
506 {
507 	struct i915_vma *vma;
508 	int ret = 0;
509 
510 	/* This is the fast path and we cannot handle a pagefault whilst
511 	 * holding the struct mutex lest the user pass in the relocations
512 	 * contained within a mmaped bo. For in such a case we, the page
513 	 * fault handler would call i915_gem_fault() and we would try to
514 	 * acquire the struct mutex again. Obviously this is bad and so
515 	 * lockdep complains vehemently.
516 	 */
517 	pagefault_disable();
518 	list_for_each_entry(vma, &eb->vmas, exec_list) {
519 		ret = i915_gem_execbuffer_relocate_vma(vma, eb);
520 		if (ret)
521 			break;
522 	}
523 	pagefault_enable();
524 
525 	return ret;
526 }
527 
528 static int
529 i915_gem_execbuffer_reserve_vma(struct i915_vma *vma,
530 				struct intel_engine_cs *ring,
531 				bool *need_reloc)
532 {
533 	struct drm_i915_gem_object *obj = vma->obj;
534 	struct drm_i915_gem_exec_object2 *entry = vma->exec_entry;
535 	uint64_t flags;
536 	int ret;
537 
538 	flags = 0;
539 	if (entry->flags & __EXEC_OBJECT_NEEDS_MAP)
540 		flags |= PIN_GLOBAL | PIN_MAPPABLE;
541 	if (entry->flags & EXEC_OBJECT_NEEDS_GTT)
542 		flags |= PIN_GLOBAL;
543 	if (entry->flags & __EXEC_OBJECT_NEEDS_BIAS)
544 		flags |= BATCH_OFFSET_BIAS | PIN_OFFSET_BIAS;
545 
546 	ret = i915_gem_object_pin(obj, vma->vm, entry->alignment, flags);
547 	if (ret)
548 		return ret;
549 
550 	entry->flags |= __EXEC_OBJECT_HAS_PIN;
551 
552 	if (entry->flags & EXEC_OBJECT_NEEDS_FENCE) {
553 		ret = i915_gem_object_get_fence(obj);
554 		if (ret)
555 			return ret;
556 
557 		if (i915_gem_object_pin_fence(obj))
558 			entry->flags |= __EXEC_OBJECT_HAS_FENCE;
559 	}
560 
561 	if (entry->offset != vma->node.start) {
562 		entry->offset = vma->node.start;
563 		*need_reloc = true;
564 	}
565 
566 	if (entry->flags & EXEC_OBJECT_WRITE) {
567 		obj->base.pending_read_domains = I915_GEM_DOMAIN_RENDER;
568 		obj->base.pending_write_domain = I915_GEM_DOMAIN_RENDER;
569 	}
570 
571 	return 0;
572 }
573 
574 static bool
575 need_reloc_mappable(struct i915_vma *vma)
576 {
577 	struct drm_i915_gem_exec_object2 *entry = vma->exec_entry;
578 
579 	if (entry->relocation_count == 0)
580 		return false;
581 
582 	if (!i915_is_ggtt(vma->vm))
583 		return false;
584 
585 	/* See also use_cpu_reloc() */
586 	if (HAS_LLC(vma->obj->base.dev))
587 		return false;
588 
589 	if (vma->obj->base.write_domain == I915_GEM_DOMAIN_CPU)
590 		return false;
591 
592 	return true;
593 }
594 
595 static bool
596 eb_vma_misplaced(struct i915_vma *vma)
597 {
598 	struct drm_i915_gem_exec_object2 *entry = vma->exec_entry;
599 	struct drm_i915_gem_object *obj = vma->obj;
600 
601 	WARN_ON(entry->flags & __EXEC_OBJECT_NEEDS_MAP &&
602 	       !i915_is_ggtt(vma->vm));
603 
604 	if (entry->alignment &&
605 	    vma->node.start & (entry->alignment - 1))
606 		return true;
607 
608 	if (entry->flags & __EXEC_OBJECT_NEEDS_MAP && !obj->map_and_fenceable)
609 		return true;
610 
611 	if (entry->flags & __EXEC_OBJECT_NEEDS_BIAS &&
612 	    vma->node.start < BATCH_OFFSET_BIAS)
613 		return true;
614 
615 	return false;
616 }
617 
618 static int
619 i915_gem_execbuffer_reserve(struct intel_engine_cs *ring,
620 			    struct list_head *vmas,
621 			    bool *need_relocs)
622 {
623 	struct drm_i915_gem_object *obj;
624 	struct i915_vma *vma;
625 	struct i915_address_space *vm;
626 	struct list_head ordered_vmas;
627 	bool has_fenced_gpu_access = INTEL_INFO(ring->dev)->gen < 4;
628 	int retry;
629 
630 	i915_gem_retire_requests_ring(ring);
631 
632 	vm = list_first_entry(vmas, struct i915_vma, exec_list)->vm;
633 
634 	INIT_LIST_HEAD(&ordered_vmas);
635 	while (!list_empty(vmas)) {
636 		struct drm_i915_gem_exec_object2 *entry;
637 		bool need_fence, need_mappable;
638 
639 		vma = list_first_entry(vmas, struct i915_vma, exec_list);
640 		obj = vma->obj;
641 		entry = vma->exec_entry;
642 
643 		if (!has_fenced_gpu_access)
644 			entry->flags &= ~EXEC_OBJECT_NEEDS_FENCE;
645 		need_fence =
646 			entry->flags & EXEC_OBJECT_NEEDS_FENCE &&
647 			obj->tiling_mode != I915_TILING_NONE;
648 		need_mappable = need_fence || need_reloc_mappable(vma);
649 
650 		if (need_mappable) {
651 			entry->flags |= __EXEC_OBJECT_NEEDS_MAP;
652 			list_move(&vma->exec_list, &ordered_vmas);
653 		} else
654 			list_move_tail(&vma->exec_list, &ordered_vmas);
655 
656 		obj->base.pending_read_domains = I915_GEM_GPU_DOMAINS & ~I915_GEM_DOMAIN_COMMAND;
657 		obj->base.pending_write_domain = 0;
658 	}
659 	list_splice(&ordered_vmas, vmas);
660 
661 	/* Attempt to pin all of the buffers into the GTT.
662 	 * This is done in 3 phases:
663 	 *
664 	 * 1a. Unbind all objects that do not match the GTT constraints for
665 	 *     the execbuffer (fenceable, mappable, alignment etc).
666 	 * 1b. Increment pin count for already bound objects.
667 	 * 2.  Bind new objects.
668 	 * 3.  Decrement pin count.
669 	 *
670 	 * This avoid unnecessary unbinding of later objects in order to make
671 	 * room for the earlier objects *unless* we need to defragment.
672 	 */
673 	retry = 0;
674 	do {
675 		int ret = 0;
676 
677 		/* Unbind any ill-fitting objects or pin. */
678 		list_for_each_entry(vma, vmas, exec_list) {
679 			if (!drm_mm_node_allocated(&vma->node))
680 				continue;
681 
682 			if (eb_vma_misplaced(vma))
683 				ret = i915_vma_unbind(vma);
684 			else
685 				ret = i915_gem_execbuffer_reserve_vma(vma, ring, need_relocs);
686 			if (ret)
687 				goto err;
688 		}
689 
690 		/* Bind fresh objects */
691 		list_for_each_entry(vma, vmas, exec_list) {
692 			if (drm_mm_node_allocated(&vma->node))
693 				continue;
694 
695 			ret = i915_gem_execbuffer_reserve_vma(vma, ring, need_relocs);
696 			if (ret)
697 				goto err;
698 		}
699 
700 err:
701 		if (ret != -ENOSPC || retry++)
702 			return ret;
703 
704 		/* Decrement pin count for bound objects */
705 		list_for_each_entry(vma, vmas, exec_list)
706 			i915_gem_execbuffer_unreserve_vma(vma);
707 
708 		ret = i915_gem_evict_vm(vm, true);
709 		if (ret)
710 			return ret;
711 	} while (1);
712 }
713 
714 static int
715 i915_gem_execbuffer_relocate_slow(struct drm_device *dev,
716 				  struct drm_i915_gem_execbuffer2 *args,
717 				  struct drm_file *file,
718 				  struct intel_engine_cs *ring,
719 				  struct eb_vmas *eb,
720 				  struct drm_i915_gem_exec_object2 *exec)
721 {
722 	struct drm_i915_gem_relocation_entry *reloc;
723 	struct i915_address_space *vm;
724 	struct i915_vma *vma;
725 	bool need_relocs;
726 	int *reloc_offset;
727 	int i, total, ret;
728 	unsigned count = args->buffer_count;
729 
730 	vm = list_first_entry(&eb->vmas, struct i915_vma, exec_list)->vm;
731 
732 	/* We may process another execbuffer during the unlock... */
733 	while (!list_empty(&eb->vmas)) {
734 		vma = list_first_entry(&eb->vmas, struct i915_vma, exec_list);
735 		list_del_init(&vma->exec_list);
736 		i915_gem_execbuffer_unreserve_vma(vma);
737 		drm_gem_object_unreference(&vma->obj->base);
738 	}
739 
740 	mutex_unlock(&dev->struct_mutex);
741 
742 	total = 0;
743 	for (i = 0; i < count; i++)
744 		total += exec[i].relocation_count;
745 
746 	reloc_offset = drm_malloc_ab(count, sizeof(*reloc_offset));
747 	reloc = drm_malloc_ab(total, sizeof(*reloc));
748 	if (reloc == NULL || reloc_offset == NULL) {
749 		drm_free_large(reloc);
750 		drm_free_large(reloc_offset);
751 		mutex_lock(&dev->struct_mutex);
752 		return -ENOMEM;
753 	}
754 
755 	total = 0;
756 	for (i = 0; i < count; i++) {
757 		struct drm_i915_gem_relocation_entry __user *user_relocs;
758 		u64 invalid_offset = (u64)-1;
759 		int j;
760 
761 		user_relocs = to_user_ptr(exec[i].relocs_ptr);
762 
763 		if (copy_from_user(reloc+total, user_relocs,
764 				   exec[i].relocation_count * sizeof(*reloc))) {
765 			ret = -EFAULT;
766 			mutex_lock(&dev->struct_mutex);
767 			goto err;
768 		}
769 
770 		/* As we do not update the known relocation offsets after
771 		 * relocating (due to the complexities in lock handling),
772 		 * we need to mark them as invalid now so that we force the
773 		 * relocation processing next time. Just in case the target
774 		 * object is evicted and then rebound into its old
775 		 * presumed_offset before the next execbuffer - if that
776 		 * happened we would make the mistake of assuming that the
777 		 * relocations were valid.
778 		 */
779 		for (j = 0; j < exec[i].relocation_count; j++) {
780 			if (__copy_to_user(&user_relocs[j].presumed_offset,
781 					   &invalid_offset,
782 					   sizeof(invalid_offset))) {
783 				ret = -EFAULT;
784 				mutex_lock(&dev->struct_mutex);
785 				goto err;
786 			}
787 		}
788 
789 		reloc_offset[i] = total;
790 		total += exec[i].relocation_count;
791 	}
792 
793 	ret = i915_mutex_lock_interruptible(dev);
794 	if (ret) {
795 		mutex_lock(&dev->struct_mutex);
796 		goto err;
797 	}
798 
799 	/* reacquire the objects */
800 	eb_reset(eb);
801 	ret = eb_lookup_vmas(eb, exec, args, vm, file);
802 	if (ret)
803 		goto err;
804 
805 	need_relocs = (args->flags & I915_EXEC_NO_RELOC) == 0;
806 	ret = i915_gem_execbuffer_reserve(ring, &eb->vmas, &need_relocs);
807 	if (ret)
808 		goto err;
809 
810 	list_for_each_entry(vma, &eb->vmas, exec_list) {
811 		int offset = vma->exec_entry - exec;
812 		ret = i915_gem_execbuffer_relocate_vma_slow(vma, eb,
813 							    reloc + reloc_offset[offset]);
814 		if (ret)
815 			goto err;
816 	}
817 
818 	/* Leave the user relocations as are, this is the painfully slow path,
819 	 * and we want to avoid the complication of dropping the lock whilst
820 	 * having buffers reserved in the aperture and so causing spurious
821 	 * ENOSPC for random operations.
822 	 */
823 
824 err:
825 	drm_free_large(reloc);
826 	drm_free_large(reloc_offset);
827 	return ret;
828 }
829 
830 static int
831 i915_gem_execbuffer_move_to_gpu(struct intel_engine_cs *ring,
832 				struct list_head *vmas)
833 {
834 	struct i915_vma *vma;
835 	uint32_t flush_domains = 0;
836 	bool flush_chipset = false;
837 	int ret;
838 
839 	list_for_each_entry(vma, vmas, exec_list) {
840 		struct drm_i915_gem_object *obj = vma->obj;
841 		ret = i915_gem_object_sync(obj, ring);
842 		if (ret)
843 			return ret;
844 
845 		if (obj->base.write_domain & I915_GEM_DOMAIN_CPU)
846 			flush_chipset |= i915_gem_clflush_object(obj, false);
847 
848 		flush_domains |= obj->base.write_domain;
849 	}
850 
851 	if (flush_chipset)
852 		i915_gem_chipset_flush(ring->dev);
853 
854 	if (flush_domains & I915_GEM_DOMAIN_GTT)
855 		wmb();
856 
857 	/* Unconditionally invalidate gpu caches and ensure that we do flush
858 	 * any residual writes from the previous batch.
859 	 */
860 	return intel_ring_invalidate_all_caches(ring);
861 }
862 
863 static bool
864 i915_gem_check_execbuffer(struct drm_i915_gem_execbuffer2 *exec)
865 {
866 	if (exec->flags & __I915_EXEC_UNKNOWN_FLAGS)
867 		return false;
868 
869 	return ((exec->batch_start_offset | exec->batch_len) & 0x7) == 0;
870 }
871 
872 static int
873 validate_exec_list(struct drm_device *dev,
874 		   struct drm_i915_gem_exec_object2 *exec,
875 		   int count)
876 {
877 	unsigned relocs_total = 0;
878 	unsigned relocs_max = UINT_MAX / sizeof(struct drm_i915_gem_relocation_entry);
879 	unsigned invalid_flags;
880 	int i;
881 
882 	invalid_flags = __EXEC_OBJECT_UNKNOWN_FLAGS;
883 	if (USES_FULL_PPGTT(dev))
884 		invalid_flags |= EXEC_OBJECT_NEEDS_GTT;
885 
886 	for (i = 0; i < count; i++) {
887 		char __user *ptr = to_user_ptr(exec[i].relocs_ptr);
888 		int length; /* limited by fault_in_pages_readable() */
889 
890 		if (exec[i].flags & invalid_flags)
891 			return -EINVAL;
892 
893 		/* First check for malicious input causing overflow in
894 		 * the worst case where we need to allocate the entire
895 		 * relocation tree as a single array.
896 		 */
897 		if (exec[i].relocation_count > relocs_max - relocs_total)
898 			return -EINVAL;
899 		relocs_total += exec[i].relocation_count;
900 
901 		length = exec[i].relocation_count *
902 			sizeof(struct drm_i915_gem_relocation_entry);
903 		/*
904 		 * We must check that the entire relocation array is safe
905 		 * to read, but since we may need to update the presumed
906 		 * offsets during execution, check for full write access.
907 		 */
908 #if 0
909 		if (!access_ok(VERIFY_WRITE, ptr, length))
910 			return -EFAULT;
911 #endif
912 
913 		if (likely(!i915.prefault_disable)) {
914 			if (fault_in_multipages_readable(ptr, length))
915 				return -EFAULT;
916 		}
917 	}
918 
919 	return 0;
920 }
921 
922 static struct intel_context *
923 i915_gem_validate_context(struct drm_device *dev, struct drm_file *file,
924 			  struct intel_engine_cs *ring, const u32 ctx_id)
925 {
926 	struct intel_context *ctx = NULL;
927 	struct i915_ctx_hang_stats *hs;
928 
929 	if (ring->id != RCS && ctx_id != DEFAULT_CONTEXT_HANDLE)
930 		return ERR_PTR(-EINVAL);
931 
932 	ctx = i915_gem_context_get(file->driver_priv, ctx_id);
933 	if (IS_ERR(ctx))
934 		return ctx;
935 
936 	hs = &ctx->hang_stats;
937 	if (hs->banned) {
938 		DRM_DEBUG("Context %u tried to submit while banned\n", ctx_id);
939 		return ERR_PTR(-EIO);
940 	}
941 
942 	if (i915.enable_execlists && !ctx->engine[ring->id].state) {
943 		int ret = intel_lr_context_deferred_create(ctx, ring);
944 		if (ret) {
945 			DRM_DEBUG("Could not create LRC %u: %d\n", ctx_id, ret);
946 			return ERR_PTR(ret);
947 		}
948 	}
949 
950 	return ctx;
951 }
952 
953 void
954 i915_gem_execbuffer_move_to_active(struct list_head *vmas,
955 				   struct intel_engine_cs *ring)
956 {
957 	struct drm_i915_gem_request *req = intel_ring_get_request(ring);
958 	struct i915_vma *vma;
959 
960 	list_for_each_entry(vma, vmas, exec_list) {
961 		struct drm_i915_gem_exec_object2 *entry = vma->exec_entry;
962 		struct drm_i915_gem_object *obj = vma->obj;
963 		u32 old_read = obj->base.read_domains;
964 		u32 old_write = obj->base.write_domain;
965 
966 		obj->base.write_domain = obj->base.pending_write_domain;
967 		if (obj->base.write_domain == 0)
968 			obj->base.pending_read_domains |= obj->base.read_domains;
969 		obj->base.read_domains = obj->base.pending_read_domains;
970 
971 		i915_vma_move_to_active(vma, ring);
972 		if (obj->base.write_domain) {
973 			obj->dirty = 1;
974 			i915_gem_request_assign(&obj->last_write_req, req);
975 
976 			intel_fb_obj_invalidate(obj, ring);
977 
978 			/* update for the implicit flush after a batch */
979 			obj->base.write_domain &= ~I915_GEM_GPU_DOMAINS;
980 		}
981 		if (entry->flags & EXEC_OBJECT_NEEDS_FENCE) {
982 			i915_gem_request_assign(&obj->last_fenced_req, req);
983 			if (entry->flags & __EXEC_OBJECT_HAS_FENCE) {
984 				struct drm_i915_private *dev_priv = to_i915(ring->dev);
985 				list_move_tail(&dev_priv->fence_regs[obj->fence_reg].lru_list,
986 					       &dev_priv->mm.fence_list);
987 			}
988 		}
989 
990 		trace_i915_gem_object_change_domain(obj, old_read, old_write);
991 	}
992 }
993 
994 void
995 i915_gem_execbuffer_retire_commands(struct drm_device *dev,
996 				    struct drm_file *file,
997 				    struct intel_engine_cs *ring,
998 				    struct drm_i915_gem_object *obj)
999 {
1000 	/* Unconditionally force add_request to emit a full flush. */
1001 	ring->gpu_caches_dirty = true;
1002 
1003 	/* Add a breadcrumb for the completion of the batch buffer */
1004 	(void)__i915_add_request(ring, file, obj);
1005 }
1006 
1007 static int
1008 i915_reset_gen7_sol_offsets(struct drm_device *dev,
1009 			    struct intel_engine_cs *ring)
1010 {
1011 	struct drm_i915_private *dev_priv = dev->dev_private;
1012 	int ret, i;
1013 
1014 	if (!IS_GEN7(dev) || ring != &dev_priv->ring[RCS]) {
1015 		DRM_DEBUG("sol reset is gen7/rcs only\n");
1016 		return -EINVAL;
1017 	}
1018 
1019 	ret = intel_ring_begin(ring, 4 * 3);
1020 	if (ret)
1021 		return ret;
1022 
1023 	for (i = 0; i < 4; i++) {
1024 		intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
1025 		intel_ring_emit(ring, GEN7_SO_WRITE_OFFSET(i));
1026 		intel_ring_emit(ring, 0);
1027 	}
1028 
1029 	intel_ring_advance(ring);
1030 
1031 	return 0;
1032 }
1033 
1034 static int
1035 i915_emit_box(struct intel_engine_cs *ring,
1036 	      struct drm_clip_rect *box,
1037 	      int DR1, int DR4)
1038 {
1039 	int ret;
1040 
1041 	if (box->y2 <= box->y1 || box->x2 <= box->x1 ||
1042 	    box->y2 <= 0 || box->x2 <= 0) {
1043 		DRM_ERROR("Bad box %d,%d..%d,%d\n",
1044 			  box->x1, box->y1, box->x2, box->y2);
1045 		return -EINVAL;
1046 	}
1047 
1048 	if (INTEL_INFO(ring->dev)->gen >= 4) {
1049 		ret = intel_ring_begin(ring, 4);
1050 		if (ret)
1051 			return ret;
1052 
1053 		intel_ring_emit(ring, GFX_OP_DRAWRECT_INFO_I965);
1054 		intel_ring_emit(ring, (box->x1 & 0xffff) | box->y1 << 16);
1055 		intel_ring_emit(ring, ((box->x2 - 1) & 0xffff) | (box->y2 - 1) << 16);
1056 		intel_ring_emit(ring, DR4);
1057 	} else {
1058 		ret = intel_ring_begin(ring, 6);
1059 		if (ret)
1060 			return ret;
1061 
1062 		intel_ring_emit(ring, GFX_OP_DRAWRECT_INFO);
1063 		intel_ring_emit(ring, DR1);
1064 		intel_ring_emit(ring, (box->x1 & 0xffff) | box->y1 << 16);
1065 		intel_ring_emit(ring, ((box->x2 - 1) & 0xffff) | (box->y2 - 1) << 16);
1066 		intel_ring_emit(ring, DR4);
1067 		intel_ring_emit(ring, 0);
1068 	}
1069 	intel_ring_advance(ring);
1070 
1071 	return 0;
1072 }
1073 
1074 static struct drm_i915_gem_object*
1075 i915_gem_execbuffer_parse(struct intel_engine_cs *ring,
1076 			  struct drm_i915_gem_exec_object2 *shadow_exec_entry,
1077 			  struct eb_vmas *eb,
1078 			  struct drm_i915_gem_object *batch_obj,
1079 			  u32 batch_start_offset,
1080 			  u32 batch_len,
1081 			  bool is_master,
1082 			  u32 *flags)
1083 {
1084 	struct drm_i915_private *dev_priv = to_i915(batch_obj->base.dev);
1085 	struct drm_i915_gem_object *shadow_batch_obj;
1086 	bool need_reloc = false;
1087 	int ret;
1088 
1089 	shadow_batch_obj = i915_gem_batch_pool_get(&dev_priv->mm.batch_pool,
1090 						   batch_obj->base.size);
1091 	if (IS_ERR(shadow_batch_obj))
1092 		return shadow_batch_obj;
1093 
1094 	ret = i915_parse_cmds(ring,
1095 			      batch_obj,
1096 			      shadow_batch_obj,
1097 			      batch_start_offset,
1098 			      batch_len,
1099 			      is_master);
1100 	if (ret) {
1101 		if (ret == -EACCES)
1102 			return batch_obj;
1103 	} else {
1104 		struct i915_vma *vma;
1105 
1106 		memset(shadow_exec_entry, 0, sizeof(*shadow_exec_entry));
1107 
1108 		vma = i915_gem_obj_to_ggtt(shadow_batch_obj);
1109 		vma->exec_entry = shadow_exec_entry;
1110 		vma->exec_entry->flags = __EXEC_OBJECT_PURGEABLE;
1111 		drm_gem_object_reference(&shadow_batch_obj->base);
1112 		i915_gem_execbuffer_reserve_vma(vma, ring, &need_reloc);
1113 		list_add_tail(&vma->exec_list, &eb->vmas);
1114 
1115 		shadow_batch_obj->base.pending_read_domains =
1116 			batch_obj->base.pending_read_domains;
1117 
1118 		/*
1119 		 * Set the DISPATCH_SECURE bit to remove the NON_SECURE
1120 		 * bit from MI_BATCH_BUFFER_START commands issued in the
1121 		 * dispatch_execbuffer implementations. We specifically
1122 		 * don't want that set when the command parser is
1123 		 * enabled.
1124 		 *
1125 		 * FIXME: with aliasing ppgtt, buffers that should only
1126 		 * be in ggtt still end up in the aliasing ppgtt. remove
1127 		 * this check when that is fixed.
1128 		 */
1129 		if (USES_FULL_PPGTT(dev))
1130 			*flags |= I915_DISPATCH_SECURE;
1131 	}
1132 
1133 	return ret ? ERR_PTR(ret) : shadow_batch_obj;
1134 }
1135 
1136 int
1137 i915_gem_ringbuffer_submission(struct drm_device *dev, struct drm_file *file,
1138 			       struct intel_engine_cs *ring,
1139 			       struct intel_context *ctx,
1140 			       struct drm_i915_gem_execbuffer2 *args,
1141 			       struct list_head *vmas,
1142 			       struct drm_i915_gem_object *batch_obj,
1143 			       u64 exec_start, u32 flags)
1144 {
1145 	struct drm_clip_rect *cliprects = NULL;
1146 	struct drm_i915_private *dev_priv = dev->dev_private;
1147 	u64 exec_len;
1148 	int instp_mode;
1149 	u32 instp_mask;
1150 	int i, ret = 0;
1151 
1152 	if (args->num_cliprects != 0) {
1153 		if (ring != &dev_priv->ring[RCS]) {
1154 			DRM_DEBUG("clip rectangles are only valid with the render ring\n");
1155 			return -EINVAL;
1156 		}
1157 
1158 		if (INTEL_INFO(dev)->gen >= 5) {
1159 			DRM_DEBUG("clip rectangles are only valid on pre-gen5\n");
1160 			return -EINVAL;
1161 		}
1162 
1163 		if (args->num_cliprects > UINT_MAX / sizeof(*cliprects)) {
1164 			DRM_DEBUG("execbuf with %u cliprects\n",
1165 				  args->num_cliprects);
1166 			return -EINVAL;
1167 		}
1168 
1169 		cliprects = kcalloc(args->num_cliprects,
1170 				    sizeof(*cliprects),
1171 				    GFP_KERNEL);
1172 		if (cliprects == NULL) {
1173 			ret = -ENOMEM;
1174 			goto error;
1175 		}
1176 
1177 		if (copy_from_user(cliprects,
1178 				   to_user_ptr(args->cliprects_ptr),
1179 				   sizeof(*cliprects)*args->num_cliprects)) {
1180 			ret = -EFAULT;
1181 			goto error;
1182 		}
1183 	} else {
1184 		if (args->DR4 == 0xffffffff) {
1185 			DRM_DEBUG("UXA submitting garbage DR4, fixing up\n");
1186 			args->DR4 = 0;
1187 		}
1188 
1189 		if (args->DR1 || args->DR4 || args->cliprects_ptr) {
1190 			DRM_DEBUG("0 cliprects but dirt in cliprects fields\n");
1191 			return -EINVAL;
1192 		}
1193 	}
1194 
1195 	ret = i915_gem_execbuffer_move_to_gpu(ring, vmas);
1196 	if (ret)
1197 		goto error;
1198 
1199 	ret = i915_switch_context(ring, ctx);
1200 	if (ret)
1201 		goto error;
1202 
1203 	instp_mode = args->flags & I915_EXEC_CONSTANTS_MASK;
1204 	instp_mask = I915_EXEC_CONSTANTS_MASK;
1205 	switch (instp_mode) {
1206 	case I915_EXEC_CONSTANTS_REL_GENERAL:
1207 	case I915_EXEC_CONSTANTS_ABSOLUTE:
1208 	case I915_EXEC_CONSTANTS_REL_SURFACE:
1209 		if (instp_mode != 0 && ring != &dev_priv->ring[RCS]) {
1210 			DRM_DEBUG("non-0 rel constants mode on non-RCS\n");
1211 			ret = -EINVAL;
1212 			goto error;
1213 		}
1214 
1215 		if (instp_mode != dev_priv->relative_constants_mode) {
1216 			if (INTEL_INFO(dev)->gen < 4) {
1217 				DRM_DEBUG("no rel constants on pre-gen4\n");
1218 				ret = -EINVAL;
1219 				goto error;
1220 			}
1221 
1222 			if (INTEL_INFO(dev)->gen > 5 &&
1223 			    instp_mode == I915_EXEC_CONSTANTS_REL_SURFACE) {
1224 				DRM_DEBUG("rel surface constants mode invalid on gen5+\n");
1225 				ret = -EINVAL;
1226 				goto error;
1227 			}
1228 
1229 			/* The HW changed the meaning on this bit on gen6 */
1230 			if (INTEL_INFO(dev)->gen >= 6)
1231 				instp_mask &= ~I915_EXEC_CONSTANTS_REL_SURFACE;
1232 		}
1233 		break;
1234 	default:
1235 		DRM_DEBUG("execbuf with unknown constants: %d\n", instp_mode);
1236 		ret = -EINVAL;
1237 		goto error;
1238 	}
1239 
1240 	if (ring == &dev_priv->ring[RCS] &&
1241 			instp_mode != dev_priv->relative_constants_mode) {
1242 		ret = intel_ring_begin(ring, 4);
1243 		if (ret)
1244 			goto error;
1245 
1246 		intel_ring_emit(ring, MI_NOOP);
1247 		intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
1248 		intel_ring_emit(ring, INSTPM);
1249 		intel_ring_emit(ring, instp_mask << 16 | instp_mode);
1250 		intel_ring_advance(ring);
1251 
1252 		dev_priv->relative_constants_mode = instp_mode;
1253 	}
1254 
1255 	if (args->flags & I915_EXEC_GEN7_SOL_RESET) {
1256 		ret = i915_reset_gen7_sol_offsets(dev, ring);
1257 		if (ret)
1258 			goto error;
1259 	}
1260 
1261 	exec_len = args->batch_len;
1262 	if (cliprects) {
1263 		for (i = 0; i < args->num_cliprects; i++) {
1264 			ret = i915_emit_box(ring, &cliprects[i],
1265 					    args->DR1, args->DR4);
1266 			if (ret)
1267 				goto error;
1268 
1269 			ret = ring->dispatch_execbuffer(ring,
1270 							exec_start, exec_len,
1271 							flags);
1272 			if (ret)
1273 				goto error;
1274 		}
1275 	} else {
1276 		ret = ring->dispatch_execbuffer(ring,
1277 						exec_start, exec_len,
1278 						flags);
1279 		if (ret)
1280 			return ret;
1281 	}
1282 
1283 	trace_i915_gem_ring_dispatch(intel_ring_get_request(ring), flags);
1284 
1285 	i915_gem_execbuffer_move_to_active(vmas, ring);
1286 	i915_gem_execbuffer_retire_commands(dev, file, ring, batch_obj);
1287 
1288 error:
1289 	kfree(cliprects);
1290 	return ret;
1291 }
1292 
1293 /**
1294  * Find one BSD ring to dispatch the corresponding BSD command.
1295  * The Ring ID is returned.
1296  */
1297 static int gen8_dispatch_bsd_ring(struct drm_device *dev,
1298 				  struct drm_file *file)
1299 {
1300 	struct drm_i915_private *dev_priv = dev->dev_private;
1301 	struct drm_i915_file_private *file_priv = file->driver_priv;
1302 
1303 	/* Check whether the file_priv is using one ring */
1304 	if (file_priv->bsd_ring)
1305 		return file_priv->bsd_ring->id;
1306 	else {
1307 		/* If no, use the ping-pong mechanism to select one ring */
1308 		int ring_id;
1309 
1310 		mutex_lock(&dev->struct_mutex);
1311 		if (dev_priv->mm.bsd_ring_dispatch_index == 0) {
1312 			ring_id = VCS;
1313 			dev_priv->mm.bsd_ring_dispatch_index = 1;
1314 		} else {
1315 			ring_id = VCS2;
1316 			dev_priv->mm.bsd_ring_dispatch_index = 0;
1317 		}
1318 		file_priv->bsd_ring = &dev_priv->ring[ring_id];
1319 		mutex_unlock(&dev->struct_mutex);
1320 		return ring_id;
1321 	}
1322 }
1323 
1324 static struct drm_i915_gem_object *
1325 eb_get_batch(struct eb_vmas *eb)
1326 {
1327 	struct i915_vma *vma = list_entry(eb->vmas.prev, typeof(*vma), exec_list);
1328 
1329 	/*
1330 	 * SNA is doing fancy tricks with compressing batch buffers, which leads
1331 	 * to negative relocation deltas. Usually that works out ok since the
1332 	 * relocate address is still positive, except when the batch is placed
1333 	 * very low in the GTT. Ensure this doesn't happen.
1334 	 *
1335 	 * Note that actual hangs have only been observed on gen7, but for
1336 	 * paranoia do it everywhere.
1337 	 */
1338 	vma->exec_entry->flags |= __EXEC_OBJECT_NEEDS_BIAS;
1339 
1340 	return vma->obj;
1341 }
1342 
1343 static int
1344 i915_gem_do_execbuffer(struct drm_device *dev, void *data,
1345 		       struct drm_file *file,
1346 		       struct drm_i915_gem_execbuffer2 *args,
1347 		       struct drm_i915_gem_exec_object2 *exec)
1348 {
1349 	struct drm_i915_private *dev_priv = dev->dev_private;
1350 	struct eb_vmas *eb;
1351 	struct drm_i915_gem_object *batch_obj;
1352 	struct drm_i915_gem_exec_object2 shadow_exec_entry;
1353 	struct intel_engine_cs *ring;
1354 	struct intel_context *ctx;
1355 	struct i915_address_space *vm;
1356 	const u32 ctx_id = i915_execbuffer2_get_context_id(*args);
1357 	u64 exec_start = args->batch_start_offset;
1358 	u32 flags;
1359 	int ret;
1360 	bool need_relocs;
1361 
1362 	if (!i915_gem_check_execbuffer(args))
1363 		return -EINVAL;
1364 
1365 	ret = validate_exec_list(dev, exec, args->buffer_count);
1366 	if (ret)
1367 		return ret;
1368 
1369 	flags = 0;
1370 	if (args->flags & I915_EXEC_SECURE) {
1371 		flags |= I915_DISPATCH_SECURE;
1372 	}
1373 	if (args->flags & I915_EXEC_IS_PINNED)
1374 		flags |= I915_DISPATCH_PINNED;
1375 
1376 	if ((args->flags & I915_EXEC_RING_MASK) > LAST_USER_RING) {
1377 		DRM_DEBUG("execbuf with unknown ring: %d\n",
1378 			  (int)(args->flags & I915_EXEC_RING_MASK));
1379 		return -EINVAL;
1380 	}
1381 
1382 	if (((args->flags & I915_EXEC_RING_MASK) != I915_EXEC_BSD) &&
1383 	    ((args->flags & I915_EXEC_BSD_MASK) != 0)) {
1384 		DRM_DEBUG("execbuf with non bsd ring but with invalid "
1385 			"bsd dispatch flags: %d\n", (int)(args->flags));
1386 		return -EINVAL;
1387 	}
1388 
1389 	if ((args->flags & I915_EXEC_RING_MASK) == I915_EXEC_DEFAULT)
1390 		ring = &dev_priv->ring[RCS];
1391 	else if ((args->flags & I915_EXEC_RING_MASK) == I915_EXEC_BSD) {
1392 		if (HAS_BSD2(dev)) {
1393 			int ring_id;
1394 
1395 			switch (args->flags & I915_EXEC_BSD_MASK) {
1396 			case I915_EXEC_BSD_DEFAULT:
1397 				ring_id = gen8_dispatch_bsd_ring(dev, file);
1398 				ring = &dev_priv->ring[ring_id];
1399 				break;
1400 			case I915_EXEC_BSD_RING1:
1401 				ring = &dev_priv->ring[VCS];
1402 				break;
1403 			case I915_EXEC_BSD_RING2:
1404 				ring = &dev_priv->ring[VCS2];
1405 				break;
1406 			default:
1407 				DRM_DEBUG("execbuf with unknown bsd ring: %d\n",
1408 					  (int)(args->flags & I915_EXEC_BSD_MASK));
1409 				return -EINVAL;
1410 			}
1411 		} else
1412 			ring = &dev_priv->ring[VCS];
1413 	} else
1414 		ring = &dev_priv->ring[(args->flags & I915_EXEC_RING_MASK) - 1];
1415 
1416 	if (!intel_ring_initialized(ring)) {
1417 		DRM_DEBUG("execbuf with invalid ring: %d\n",
1418 			  (int)(args->flags & I915_EXEC_RING_MASK));
1419 		return -EINVAL;
1420 	}
1421 
1422 	if (args->buffer_count < 1) {
1423 		DRM_DEBUG("execbuf with %d buffers\n", args->buffer_count);
1424 		return -EINVAL;
1425 	}
1426 
1427 	intel_runtime_pm_get(dev_priv);
1428 
1429 	ret = i915_mutex_lock_interruptible(dev);
1430 	if (ret)
1431 		goto pre_mutex_err;
1432 
1433 	ctx = i915_gem_validate_context(dev, file, ring, ctx_id);
1434 	if (IS_ERR(ctx)) {
1435 		mutex_unlock(&dev->struct_mutex);
1436 		ret = PTR_ERR(ctx);
1437 		goto pre_mutex_err;
1438 	}
1439 
1440 	i915_gem_context_reference(ctx);
1441 
1442 	if (ctx->ppgtt)
1443 		vm = &ctx->ppgtt->base;
1444 	else
1445 		vm = &dev_priv->gtt.base;
1446 
1447 	eb = eb_create(args);
1448 	if (eb == NULL) {
1449 		i915_gem_context_unreference(ctx);
1450 		mutex_unlock(&dev->struct_mutex);
1451 		ret = -ENOMEM;
1452 		goto pre_mutex_err;
1453 	}
1454 
1455 	/* Look up object handles */
1456 	ret = eb_lookup_vmas(eb, exec, args, vm, file);
1457 	if (ret)
1458 		goto err;
1459 
1460 	/* take note of the batch buffer before we might reorder the lists */
1461 	batch_obj = eb_get_batch(eb);
1462 
1463 	/* Move the objects en-masse into the GTT, evicting if necessary. */
1464 	need_relocs = (args->flags & I915_EXEC_NO_RELOC) == 0;
1465 	ret = i915_gem_execbuffer_reserve(ring, &eb->vmas, &need_relocs);
1466 	if (ret)
1467 		goto err;
1468 
1469 	/* The objects are in their final locations, apply the relocations. */
1470 	if (need_relocs)
1471 		ret = i915_gem_execbuffer_relocate(eb);
1472 	if (ret) {
1473 		if (ret == -EFAULT) {
1474 			ret = i915_gem_execbuffer_relocate_slow(dev, args, file, ring,
1475 								eb, exec);
1476 			BUG_ON(!mutex_is_locked(&dev->struct_mutex));
1477 		}
1478 		if (ret)
1479 			goto err;
1480 	}
1481 
1482 	/* Set the pending read domains for the batch buffer to COMMAND */
1483 	if (batch_obj->base.pending_write_domain) {
1484 		DRM_DEBUG("Attempting to use self-modifying batch buffer\n");
1485 		ret = -EINVAL;
1486 		goto err;
1487 	}
1488 
1489 	if (i915_needs_cmd_parser(ring) && args->batch_len) {
1490 		batch_obj = i915_gem_execbuffer_parse(ring,
1491 						      &shadow_exec_entry,
1492 						      eb,
1493 						      batch_obj,
1494 						      args->batch_start_offset,
1495 						      args->batch_len,
1496 						      file->is_master,
1497 						      &flags);
1498 		if (IS_ERR(batch_obj)) {
1499 			ret = PTR_ERR(batch_obj);
1500 			goto err;
1501 		}
1502 	}
1503 
1504 	batch_obj->base.pending_read_domains |= I915_GEM_DOMAIN_COMMAND;
1505 
1506 	/* snb/ivb/vlv conflate the "batch in ppgtt" bit with the "non-secure
1507 	 * batch" bit. Hence we need to pin secure batches into the global gtt.
1508 	 * hsw should have this fixed, but bdw mucks it up again. */
1509 	if (flags & I915_DISPATCH_SECURE) {
1510 		/*
1511 		 * So on first glance it looks freaky that we pin the batch here
1512 		 * outside of the reservation loop. But:
1513 		 * - The batch is already pinned into the relevant ppgtt, so we
1514 		 *   already have the backing storage fully allocated.
1515 		 * - No other BO uses the global gtt (well contexts, but meh),
1516 		 *   so we don't really have issues with mutliple objects not
1517 		 *   fitting due to fragmentation.
1518 		 * So this is actually safe.
1519 		 */
1520 		ret = i915_gem_obj_ggtt_pin(batch_obj, 0, 0);
1521 		if (ret)
1522 			goto err;
1523 
1524 		exec_start += i915_gem_obj_ggtt_offset(batch_obj);
1525 	} else
1526 		exec_start += i915_gem_obj_offset(batch_obj, vm);
1527 
1528 	ret = dev_priv->gt.do_execbuf(dev, file, ring, ctx, args,
1529 				      &eb->vmas, batch_obj, exec_start, flags);
1530 
1531 	/*
1532 	 * FIXME: We crucially rely upon the active tracking for the (ppgtt)
1533 	 * batch vma for correctness. For less ugly and less fragility this
1534 	 * needs to be adjusted to also track the ggtt batch vma properly as
1535 	 * active.
1536 	 */
1537 	if (flags & I915_DISPATCH_SECURE)
1538 		i915_gem_object_ggtt_unpin(batch_obj);
1539 err:
1540 	/* the request owns the ref now */
1541 	i915_gem_context_unreference(ctx);
1542 	eb_destroy(eb);
1543 
1544 	mutex_unlock(&dev->struct_mutex);
1545 
1546 pre_mutex_err:
1547 	/* intel_gpu_busy should also get a ref, so it will free when the device
1548 	 * is really idle. */
1549 	intel_runtime_pm_put(dev_priv);
1550 	return ret;
1551 }
1552 
1553 /*
1554  * Legacy execbuffer just creates an exec2 list from the original exec object
1555  * list array and passes it to the real function.
1556  */
1557 int
1558 i915_gem_execbuffer(struct drm_device *dev, void *data,
1559 		    struct drm_file *file)
1560 {
1561 	struct drm_i915_gem_execbuffer *args = data;
1562 	struct drm_i915_gem_execbuffer2 exec2;
1563 	struct drm_i915_gem_exec_object *exec_list = NULL;
1564 	struct drm_i915_gem_exec_object2 *exec2_list = NULL;
1565 	int ret, i;
1566 
1567 	if (args->buffer_count < 1) {
1568 		DRM_DEBUG("execbuf with %d buffers\n", args->buffer_count);
1569 		return -EINVAL;
1570 	}
1571 
1572 	/* Copy in the exec list from userland */
1573 	exec_list = drm_malloc_ab(sizeof(*exec_list), args->buffer_count);
1574 	exec2_list = drm_malloc_ab(sizeof(*exec2_list), args->buffer_count);
1575 	if (exec_list == NULL || exec2_list == NULL) {
1576 		DRM_DEBUG("Failed to allocate exec list for %d buffers\n",
1577 			  args->buffer_count);
1578 		drm_free_large(exec_list);
1579 		drm_free_large(exec2_list);
1580 		return -ENOMEM;
1581 	}
1582 	ret = copy_from_user(exec_list,
1583 			     to_user_ptr(args->buffers_ptr),
1584 			     sizeof(*exec_list) * args->buffer_count);
1585 	if (ret != 0) {
1586 		DRM_DEBUG("copy %d exec entries failed %d\n",
1587 			  args->buffer_count, ret);
1588 		drm_free_large(exec_list);
1589 		drm_free_large(exec2_list);
1590 		return -EFAULT;
1591 	}
1592 
1593 	for (i = 0; i < args->buffer_count; i++) {
1594 		exec2_list[i].handle = exec_list[i].handle;
1595 		exec2_list[i].relocation_count = exec_list[i].relocation_count;
1596 		exec2_list[i].relocs_ptr = exec_list[i].relocs_ptr;
1597 		exec2_list[i].alignment = exec_list[i].alignment;
1598 		exec2_list[i].offset = exec_list[i].offset;
1599 		if (INTEL_INFO(dev)->gen < 4)
1600 			exec2_list[i].flags = EXEC_OBJECT_NEEDS_FENCE;
1601 		else
1602 			exec2_list[i].flags = 0;
1603 	}
1604 
1605 	exec2.buffers_ptr = args->buffers_ptr;
1606 	exec2.buffer_count = args->buffer_count;
1607 	exec2.batch_start_offset = args->batch_start_offset;
1608 	exec2.batch_len = args->batch_len;
1609 	exec2.DR1 = args->DR1;
1610 	exec2.DR4 = args->DR4;
1611 	exec2.num_cliprects = args->num_cliprects;
1612 	exec2.cliprects_ptr = args->cliprects_ptr;
1613 	exec2.flags = I915_EXEC_RENDER;
1614 	i915_execbuffer2_set_context_id(exec2, 0);
1615 
1616 	ret = i915_gem_do_execbuffer(dev, data, file, &exec2, exec2_list);
1617 	if (!ret) {
1618 		struct drm_i915_gem_exec_object __user *user_exec_list =
1619 			to_user_ptr(args->buffers_ptr);
1620 
1621 		/* Copy the new buffer offsets back to the user's exec list. */
1622 		for (i = 0; i < args->buffer_count; i++) {
1623 			ret = __copy_to_user(&user_exec_list[i].offset,
1624 					     &exec2_list[i].offset,
1625 					     sizeof(user_exec_list[i].offset));
1626 			if (ret) {
1627 				ret = -EFAULT;
1628 				DRM_DEBUG("failed to copy %d exec entries "
1629 					  "back to user (%d)\n",
1630 					  args->buffer_count, ret);
1631 				break;
1632 			}
1633 		}
1634 	}
1635 
1636 	drm_free_large(exec_list);
1637 	drm_free_large(exec2_list);
1638 	return ret;
1639 }
1640 
1641 int
1642 i915_gem_execbuffer2(struct drm_device *dev, void *data,
1643 		     struct drm_file *file)
1644 {
1645 	struct drm_i915_gem_execbuffer2 *args = data;
1646 	struct drm_i915_gem_exec_object2 *exec2_list = NULL;
1647 	int ret;
1648 
1649 	if (args->buffer_count < 1 ||
1650 	    args->buffer_count > UINT_MAX / sizeof(*exec2_list)) {
1651 		DRM_DEBUG("execbuf2 with %d buffers\n", args->buffer_count);
1652 		return -EINVAL;
1653 	}
1654 
1655 	if (args->rsvd2 != 0) {
1656 		DRM_DEBUG("dirty rvsd2 field\n");
1657 		return -EINVAL;
1658 	}
1659 
1660 	exec2_list = kmalloc(sizeof(*exec2_list)*args->buffer_count,
1661 			     M_DRM, M_NOWAIT);
1662 	if (exec2_list == NULL)
1663 		exec2_list = drm_malloc_ab(sizeof(*exec2_list),
1664 					   args->buffer_count);
1665 	if (exec2_list == NULL) {
1666 		DRM_DEBUG("Failed to allocate exec list for %d buffers\n",
1667 			  args->buffer_count);
1668 		return -ENOMEM;
1669 	}
1670 	ret = copy_from_user(exec2_list,
1671 			     to_user_ptr(args->buffers_ptr),
1672 			     sizeof(*exec2_list) * args->buffer_count);
1673 	if (ret != 0) {
1674 		DRM_DEBUG("copy %d exec entries failed %d\n",
1675 			  args->buffer_count, ret);
1676 		drm_free_large(exec2_list);
1677 		return -EFAULT;
1678 	}
1679 
1680 	ret = i915_gem_do_execbuffer(dev, data, file, args, exec2_list);
1681 	if (!ret) {
1682 		/* Copy the new buffer offsets back to the user's exec list. */
1683 		struct drm_i915_gem_exec_object2 __user *user_exec_list =
1684 				   to_user_ptr(args->buffers_ptr);
1685 		int i;
1686 
1687 		for (i = 0; i < args->buffer_count; i++) {
1688 			ret = __copy_to_user(&user_exec_list[i].offset,
1689 					     &exec2_list[i].offset,
1690 					     sizeof(user_exec_list[i].offset));
1691 			if (ret) {
1692 				ret = -EFAULT;
1693 				DRM_DEBUG("failed to copy %d exec entries "
1694 					  "back to user\n",
1695 					  args->buffer_count);
1696 				break;
1697 			}
1698 		}
1699 	}
1700 
1701 	drm_free_large(exec2_list);
1702 	return ret;
1703 }
1704