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