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