i915_gem.c 130.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/*
 * Copyright © 2008 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 *
 * Authors:
 *    Eric Anholt <eric@anholt.net>
 *
 */

#include "drmP.h"
#include "drm.h"
#include "i915_drm.h"
#include "i915_drv.h"
C
Chris Wilson 已提交
32
#include "i915_trace.h"
33
#include "intel_drv.h"
34
#include <linux/slab.h>
35
#include <linux/swap.h>
J
Jesse Barnes 已提交
36
#include <linux/pci.h>
37

38 39 40 41 42 43
struct change_domains {
	uint32_t invalidate_domains;
	uint32_t flush_domains;
	uint32_t flush_rings;
};

44
static int i915_gem_object_flush_gpu_write_domain(struct drm_i915_gem_object *obj,
45
						  struct intel_ring_buffer *pipelined);
46 47 48
static void i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj);
static void i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj);
static int i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj,
49
					     bool write);
50
static int i915_gem_object_set_cpu_read_domain_range(struct drm_i915_gem_object *obj,
51 52
						     uint64_t offset,
						     uint64_t size);
53 54
static void i915_gem_object_set_to_full_cpu_read_domain(struct drm_i915_gem_object *obj);
static int i915_gem_object_wait_rendering(struct drm_i915_gem_object *obj,
55
					  bool interruptible);
56
static int i915_gem_object_bind_to_gtt(struct drm_i915_gem_object *obj,
57
				       unsigned alignment,
58
				       bool map_and_fenceable);
59 60 61
static void i915_gem_clear_fence_reg(struct drm_i915_gem_object *obj);
static int i915_gem_phys_pwrite(struct drm_device *dev,
				struct drm_i915_gem_object *obj,
62
				struct drm_i915_gem_pwrite *args,
63 64
				struct drm_file *file);
static void i915_gem_free_object_tail(struct drm_i915_gem_object *obj);
65

66 67 68 69
static int i915_gem_inactive_shrink(struct shrinker *shrinker,
				    int nr_to_scan,
				    gfp_t gfp_mask);

70

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
/* some bookkeeping */
static void i915_gem_info_add_obj(struct drm_i915_private *dev_priv,
				  size_t size)
{
	dev_priv->mm.object_count++;
	dev_priv->mm.object_memory += size;
}

static void i915_gem_info_remove_obj(struct drm_i915_private *dev_priv,
				     size_t size)
{
	dev_priv->mm.object_count--;
	dev_priv->mm.object_memory -= size;
}

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
int
i915_gem_check_is_wedged(struct drm_device *dev)
{
	struct drm_i915_private *dev_priv = dev->dev_private;
	struct completion *x = &dev_priv->error_completion;
	unsigned long flags;
	int ret;

	if (!atomic_read(&dev_priv->mm.wedged))
		return 0;

	ret = wait_for_completion_interruptible(x);
	if (ret)
		return ret;

	/* Success, we reset the GPU! */
	if (!atomic_read(&dev_priv->mm.wedged))
		return 0;

	/* GPU is hung, bump the completion count to account for
	 * the token we just consumed so that we never hit zero and
	 * end up waiting upon a subsequent completion event that
	 * will never happen.
	 */
	spin_lock_irqsave(&x->wait.lock, flags);
	x->done++;
	spin_unlock_irqrestore(&x->wait.lock, flags);
	return -EIO;
}

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
static int i915_mutex_lock_interruptible(struct drm_device *dev)
{
	struct drm_i915_private *dev_priv = dev->dev_private;
	int ret;

	ret = i915_gem_check_is_wedged(dev);
	if (ret)
		return ret;

	ret = mutex_lock_interruptible(&dev->struct_mutex);
	if (ret)
		return ret;

	if (atomic_read(&dev_priv->mm.wedged)) {
		mutex_unlock(&dev->struct_mutex);
		return -EAGAIN;
	}

134
	WARN_ON(i915_verify_lists(dev));
135 136
	return 0;
}
137

138
static inline bool
139
i915_gem_object_is_inactive(struct drm_i915_gem_object *obj)
140
{
141
	return obj->gtt_space && !obj->active && obj->pin_count == 0;
142 143
}

144 145 146 147
void i915_gem_do_init(struct drm_device *dev,
		      unsigned long start,
		      unsigned long mappable_end,
		      unsigned long end)
148 149 150
{
	drm_i915_private_t *dev_priv = dev->dev_private;

J
Jesse Barnes 已提交
151 152
	drm_mm_init(&dev_priv->mm.gtt_space, start,
		    end - start);
153

154
	dev_priv->mm.gtt_total = end - start;
155
	dev_priv->mm.mappable_gtt_total = min(end, mappable_end) - start;
D
Daniel Vetter 已提交
156
	dev_priv->mm.gtt_mappable_end = mappable_end;
J
Jesse Barnes 已提交
157
}
158

J
Jesse Barnes 已提交
159 160
int
i915_gem_init_ioctl(struct drm_device *dev, void *data,
161
		    struct drm_file *file)
J
Jesse Barnes 已提交
162 163
{
	struct drm_i915_gem_init *args = data;
164 165 166 167

	if (args->gtt_start >= args->gtt_end ||
	    (args->gtt_end | args->gtt_start) & (PAGE_SIZE - 1))
		return -EINVAL;
J
Jesse Barnes 已提交
168 169

	mutex_lock(&dev->struct_mutex);
170
	i915_gem_do_init(dev, args->gtt_start, args->gtt_end, args->gtt_end);
171 172
	mutex_unlock(&dev->struct_mutex);

173
	return 0;
174 175
}

176 177
int
i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
178
			    struct drm_file *file)
179
{
180
	struct drm_i915_private *dev_priv = dev->dev_private;
181
	struct drm_i915_gem_get_aperture *args = data;
182 183
	struct drm_i915_gem_object *obj;
	size_t pinned;
184 185 186 187

	if (!(dev->driver->driver_features & DRIVER_GEM))
		return -ENODEV;

188
	pinned = 0;
189
	mutex_lock(&dev->struct_mutex);
190 191
	list_for_each_entry(obj, &dev_priv->mm.pinned_list, mm_list)
		pinned += obj->gtt_space->size;
192
	mutex_unlock(&dev->struct_mutex);
193

194 195 196
	args->aper_size = dev_priv->mm.gtt_total;
	args->aper_available_size = args->aper_size -pinned;

197 198 199
	return 0;
}

200 201 202 203 204
/**
 * Creates a new mm object and returns a handle to it.
 */
int
i915_gem_create_ioctl(struct drm_device *dev, void *data,
205
		      struct drm_file *file)
206 207
{
	struct drm_i915_gem_create *args = data;
208
	struct drm_i915_gem_object *obj;
209 210
	int ret;
	u32 handle;
211 212 213 214

	args->size = roundup(args->size, PAGE_SIZE);

	/* Allocate the new object */
215
	obj = i915_gem_alloc_object(dev, args->size);
216 217 218
	if (obj == NULL)
		return -ENOMEM;

219
	ret = drm_gem_handle_create(file, &obj->base, &handle);
220
	if (ret) {
221 222
		drm_gem_object_release(&obj->base);
		i915_gem_info_remove_obj(dev->dev_private, obj->base.size);
223
		kfree(obj);
224
		return ret;
225
	}
226

227
	/* drop reference from allocate - handle holds it now */
228
	drm_gem_object_unreference(&obj->base);
229 230
	trace_i915_gem_object_create(obj);

231
	args->handle = handle;
232 233 234
	return 0;
}

235
static int i915_gem_object_needs_bit17_swizzle(struct drm_i915_gem_object *obj)
236
{
237
	drm_i915_private_t *dev_priv = obj->base.dev->dev_private;
238 239

	return dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_9_10_17 &&
240
		obj->tiling_mode != I915_TILING_NONE;
241 242
}

243
static inline void
244 245 246 247 248 249 250 251
slow_shmem_copy(struct page *dst_page,
		int dst_offset,
		struct page *src_page,
		int src_offset,
		int length)
{
	char *dst_vaddr, *src_vaddr;

252 253
	dst_vaddr = kmap(dst_page);
	src_vaddr = kmap(src_page);
254 255 256

	memcpy(dst_vaddr + dst_offset, src_vaddr + src_offset, length);

257 258
	kunmap(src_page);
	kunmap(dst_page);
259 260
}

261
static inline void
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
slow_shmem_bit17_copy(struct page *gpu_page,
		      int gpu_offset,
		      struct page *cpu_page,
		      int cpu_offset,
		      int length,
		      int is_read)
{
	char *gpu_vaddr, *cpu_vaddr;

	/* Use the unswizzled path if this page isn't affected. */
	if ((page_to_phys(gpu_page) & (1 << 17)) == 0) {
		if (is_read)
			return slow_shmem_copy(cpu_page, cpu_offset,
					       gpu_page, gpu_offset, length);
		else
			return slow_shmem_copy(gpu_page, gpu_offset,
					       cpu_page, cpu_offset, length);
	}

281 282
	gpu_vaddr = kmap(gpu_page);
	cpu_vaddr = kmap(cpu_page);
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305

	/* Copy the data, XORing A6 with A17 (1). The user already knows he's
	 * XORing with the other bits (A9 for Y, A9 and A10 for X)
	 */
	while (length > 0) {
		int cacheline_end = ALIGN(gpu_offset + 1, 64);
		int this_length = min(cacheline_end - gpu_offset, length);
		int swizzled_gpu_offset = gpu_offset ^ 64;

		if (is_read) {
			memcpy(cpu_vaddr + cpu_offset,
			       gpu_vaddr + swizzled_gpu_offset,
			       this_length);
		} else {
			memcpy(gpu_vaddr + swizzled_gpu_offset,
			       cpu_vaddr + cpu_offset,
			       this_length);
		}
		cpu_offset += this_length;
		gpu_offset += this_length;
		length -= this_length;
	}

306 307
	kunmap(cpu_page);
	kunmap(gpu_page);
308 309
}

310 311 312 313 314 315
/**
 * This is the fast shmem pread path, which attempts to copy_from_user directly
 * from the backing pages of the object to the user's address space.  On a
 * fault, it fails so we can fall back to i915_gem_shmem_pwrite_slow().
 */
static int
316 317
i915_gem_shmem_pread_fast(struct drm_device *dev,
			  struct drm_i915_gem_object *obj,
318
			  struct drm_i915_gem_pread *args,
319
			  struct drm_file *file)
320
{
321
	struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
322
	ssize_t remain;
323
	loff_t offset;
324 325 326 327 328 329 330 331 332
	char __user *user_data;
	int page_offset, page_length;

	user_data = (char __user *) (uintptr_t) args->data_ptr;
	remain = args->size;

	offset = args->offset;

	while (remain > 0) {
333 334 335 336
		struct page *page;
		char *vaddr;
		int ret;

337 338 339 340 341 342 343 344 345 346
		/* Operation in this page
		 *
		 * page_offset = offset within page
		 * page_length = bytes to copy for this page
		 */
		page_offset = offset & (PAGE_SIZE-1);
		page_length = remain;
		if ((page_offset + remain) > PAGE_SIZE)
			page_length = PAGE_SIZE - page_offset;

347 348 349 350 351 352 353 354 355 356 357 358 359 360
		page = read_cache_page_gfp(mapping, offset >> PAGE_SHIFT,
					   GFP_HIGHUSER | __GFP_RECLAIMABLE);
		if (IS_ERR(page))
			return PTR_ERR(page);

		vaddr = kmap_atomic(page);
		ret = __copy_to_user_inatomic(user_data,
					      vaddr + page_offset,
					      page_length);
		kunmap_atomic(vaddr);

		mark_page_accessed(page);
		page_cache_release(page);
		if (ret)
361
			return -EFAULT;
362 363 364 365 366 367

		remain -= page_length;
		user_data += page_length;
		offset += page_length;
	}

368
	return 0;
369 370 371 372 373 374 375 376 377
}

/**
 * This is the fallback shmem pread path, which allocates temporary storage
 * in kernel space to copy_to_user into outside of the struct_mutex, so we
 * can copy out of the object's backing pages while holding the struct mutex
 * and not take page faults.
 */
static int
378 379
i915_gem_shmem_pread_slow(struct drm_device *dev,
			  struct drm_i915_gem_object *obj,
380
			  struct drm_i915_gem_pread *args,
381
			  struct drm_file *file)
382
{
383
	struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
384 385 386 387 388
	struct mm_struct *mm = current->mm;
	struct page **user_pages;
	ssize_t remain;
	loff_t offset, pinned_pages, i;
	loff_t first_data_page, last_data_page, num_pages;
389 390
	int shmem_page_offset;
	int data_page_index, data_page_offset;
391 392 393
	int page_length;
	int ret;
	uint64_t data_ptr = args->data_ptr;
394
	int do_bit17_swizzling;
395 396 397 398 399 400 401 402 403 404 405

	remain = args->size;

	/* Pin the user pages containing the data.  We can't fault while
	 * holding the struct mutex, yet we want to hold it while
	 * dereferencing the user data.
	 */
	first_data_page = data_ptr / PAGE_SIZE;
	last_data_page = (data_ptr + args->size - 1) / PAGE_SIZE;
	num_pages = last_data_page - first_data_page + 1;

406
	user_pages = drm_malloc_ab(num_pages, sizeof(struct page *));
407 408 409
	if (user_pages == NULL)
		return -ENOMEM;

410
	mutex_unlock(&dev->struct_mutex);
411 412
	down_read(&mm->mmap_sem);
	pinned_pages = get_user_pages(current, mm, (uintptr_t)args->data_ptr,
413
				      num_pages, 1, 0, user_pages, NULL);
414
	up_read(&mm->mmap_sem);
415
	mutex_lock(&dev->struct_mutex);
416 417
	if (pinned_pages < num_pages) {
		ret = -EFAULT;
418
		goto out;
419 420
	}

421 422 423
	ret = i915_gem_object_set_cpu_read_domain_range(obj,
							args->offset,
							args->size);
424
	if (ret)
425
		goto out;
426

427
	do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
428 429 430 431

	offset = args->offset;

	while (remain > 0) {
432 433
		struct page *page;

434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
		/* Operation in this page
		 *
		 * shmem_page_offset = offset within page in shmem file
		 * data_page_index = page number in get_user_pages return
		 * data_page_offset = offset with data_page_index page.
		 * page_length = bytes to copy for this page
		 */
		shmem_page_offset = offset & ~PAGE_MASK;
		data_page_index = data_ptr / PAGE_SIZE - first_data_page;
		data_page_offset = data_ptr & ~PAGE_MASK;

		page_length = remain;
		if ((shmem_page_offset + page_length) > PAGE_SIZE)
			page_length = PAGE_SIZE - shmem_page_offset;
		if ((data_page_offset + page_length) > PAGE_SIZE)
			page_length = PAGE_SIZE - data_page_offset;

451 452 453 454 455
		page = read_cache_page_gfp(mapping, offset >> PAGE_SHIFT,
					   GFP_HIGHUSER | __GFP_RECLAIMABLE);
		if (IS_ERR(page))
			return PTR_ERR(page);

456
		if (do_bit17_swizzling) {
457
			slow_shmem_bit17_copy(page,
458
					      shmem_page_offset,
459 460 461 462 463 464 465
					      user_pages[data_page_index],
					      data_page_offset,
					      page_length,
					      1);
		} else {
			slow_shmem_copy(user_pages[data_page_index],
					data_page_offset,
466
					page,
467 468
					shmem_page_offset,
					page_length);
469
		}
470

471 472 473
		mark_page_accessed(page);
		page_cache_release(page);

474 475 476 477 478
		remain -= page_length;
		data_ptr += page_length;
		offset += page_length;
	}

479
out:
480 481
	for (i = 0; i < pinned_pages; i++) {
		SetPageDirty(user_pages[i]);
482
		mark_page_accessed(user_pages[i]);
483 484
		page_cache_release(user_pages[i]);
	}
485
	drm_free_large(user_pages);
486 487 488 489

	return ret;
}

490 491 492 493 494 495 496
/**
 * Reads data from the object referenced by handle.
 *
 * On error, the contents of *data are undefined.
 */
int
i915_gem_pread_ioctl(struct drm_device *dev, void *data,
497
		     struct drm_file *file)
498 499
{
	struct drm_i915_gem_pread *args = data;
500
	struct drm_i915_gem_object *obj;
501
	int ret = 0;
502

503 504 505 506 507 508 509 510 511 512 513 514 515
	if (args->size == 0)
		return 0;

	if (!access_ok(VERIFY_WRITE,
		       (char __user *)(uintptr_t)args->data_ptr,
		       args->size))
		return -EFAULT;

	ret = fault_in_pages_writeable((char __user *)(uintptr_t)args->data_ptr,
				       args->size);
	if (ret)
		return -EFAULT;

516
	ret = i915_mutex_lock_interruptible(dev);
517
	if (ret)
518
		return ret;
519

520
	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
521 522 523
	if (obj == NULL) {
		ret = -ENOENT;
		goto unlock;
524
	}
525

526
	/* Bounds check source.  */
527 528
	if (args->offset > obj->base.size ||
	    args->size > obj->base.size - args->offset) {
C
Chris Wilson 已提交
529
		ret = -EINVAL;
530
		goto out;
C
Chris Wilson 已提交
531 532
	}

533 534 535 536
	ret = i915_gem_object_set_cpu_read_domain_range(obj,
							args->offset,
							args->size);
	if (ret)
537
		goto out;
538 539 540

	ret = -EFAULT;
	if (!i915_gem_object_needs_bit17_swizzle(obj))
541
		ret = i915_gem_shmem_pread_fast(dev, obj, args, file);
542
	if (ret == -EFAULT)
543
		ret = i915_gem_shmem_pread_slow(dev, obj, args, file);
544

545
out:
546
	drm_gem_object_unreference(&obj->base);
547
unlock:
548
	mutex_unlock(&dev->struct_mutex);
549
	return ret;
550 551
}

552 553
/* This is the fast write path which cannot handle
 * page faults in the source data
554
 */
555 556 557 558 559 560

static inline int
fast_user_write(struct io_mapping *mapping,
		loff_t page_base, int page_offset,
		char __user *user_data,
		int length)
561 562
{
	char *vaddr_atomic;
563
	unsigned long unwritten;
564

P
Peter Zijlstra 已提交
565
	vaddr_atomic = io_mapping_map_atomic_wc(mapping, page_base);
566 567
	unwritten = __copy_from_user_inatomic_nocache(vaddr_atomic + page_offset,
						      user_data, length);
P
Peter Zijlstra 已提交
568
	io_mapping_unmap_atomic(vaddr_atomic);
569
	return unwritten;
570 571 572 573 574 575
}

/* Here's the write path which can sleep for
 * page faults
 */

576
static inline void
577 578 579 580
slow_kernel_write(struct io_mapping *mapping,
		  loff_t gtt_base, int gtt_offset,
		  struct page *user_page, int user_offset,
		  int length)
581
{
582 583
	char __iomem *dst_vaddr;
	char *src_vaddr;
584

585 586 587 588 589 590 591 592 593
	dst_vaddr = io_mapping_map_wc(mapping, gtt_base);
	src_vaddr = kmap(user_page);

	memcpy_toio(dst_vaddr + gtt_offset,
		    src_vaddr + user_offset,
		    length);

	kunmap(user_page);
	io_mapping_unmap(dst_vaddr);
594 595
}

596 597 598 599
/**
 * This is the fast pwrite path, where we copy the data directly from the
 * user into the GTT, uncached.
 */
600
static int
601 602
i915_gem_gtt_pwrite_fast(struct drm_device *dev,
			 struct drm_i915_gem_object *obj,
603
			 struct drm_i915_gem_pwrite *args,
604
			 struct drm_file *file)
605
{
606
	drm_i915_private_t *dev_priv = dev->dev_private;
607
	ssize_t remain;
608
	loff_t offset, page_base;
609
	char __user *user_data;
610
	int page_offset, page_length;
611 612 613 614

	user_data = (char __user *) (uintptr_t) args->data_ptr;
	remain = args->size;

615
	offset = obj->gtt_offset + args->offset;
616 617 618 619

	while (remain > 0) {
		/* Operation in this page
		 *
620 621 622
		 * page_base = page offset within aperture
		 * page_offset = offset within page
		 * page_length = bytes to copy for this page
623
		 */
624 625 626 627 628 629 630
		page_base = (offset & ~(PAGE_SIZE-1));
		page_offset = offset & (PAGE_SIZE-1);
		page_length = remain;
		if ((page_offset + remain) > PAGE_SIZE)
			page_length = PAGE_SIZE - page_offset;

		/* If we get a fault while copying data, then (presumably) our
631 632
		 * source page isn't available.  Return the error and we'll
		 * retry in the slow path.
633
		 */
634 635 636 637
		if (fast_user_write(dev_priv->mm.gtt_mapping, page_base,
				    page_offset, user_data, page_length))

			return -EFAULT;
638

639 640 641
		remain -= page_length;
		user_data += page_length;
		offset += page_length;
642 643
	}

644
	return 0;
645 646
}

647 648 649 650 651 652 653
/**
 * This is the fallback GTT pwrite path, which uses get_user_pages to pin
 * the memory and maps it using kmap_atomic for copying.
 *
 * This code resulted in x11perf -rgb10text consuming about 10% more CPU
 * than using i915_gem_gtt_pwrite_fast on a G45 (32-bit).
 */
654
static int
655 656
i915_gem_gtt_pwrite_slow(struct drm_device *dev,
			 struct drm_i915_gem_object *obj,
657
			 struct drm_i915_gem_pwrite *args,
658
			 struct drm_file *file)
659
{
660 661 662 663 664 665 666 667
	drm_i915_private_t *dev_priv = dev->dev_private;
	ssize_t remain;
	loff_t gtt_page_base, offset;
	loff_t first_data_page, last_data_page, num_pages;
	loff_t pinned_pages, i;
	struct page **user_pages;
	struct mm_struct *mm = current->mm;
	int gtt_page_offset, data_page_offset, data_page_index, page_length;
668
	int ret;
669 670 671 672 673 674 675 676 677 678 679 680
	uint64_t data_ptr = args->data_ptr;

	remain = args->size;

	/* Pin the user pages containing the data.  We can't fault while
	 * holding the struct mutex, and all of the pwrite implementations
	 * want to hold it while dereferencing the user data.
	 */
	first_data_page = data_ptr / PAGE_SIZE;
	last_data_page = (data_ptr + args->size - 1) / PAGE_SIZE;
	num_pages = last_data_page - first_data_page + 1;

681
	user_pages = drm_malloc_ab(num_pages, sizeof(struct page *));
682 683 684
	if (user_pages == NULL)
		return -ENOMEM;

685
	mutex_unlock(&dev->struct_mutex);
686 687 688 689
	down_read(&mm->mmap_sem);
	pinned_pages = get_user_pages(current, mm, (uintptr_t)args->data_ptr,
				      num_pages, 0, 0, user_pages, NULL);
	up_read(&mm->mmap_sem);
690
	mutex_lock(&dev->struct_mutex);
691 692 693 694
	if (pinned_pages < num_pages) {
		ret = -EFAULT;
		goto out_unpin_pages;
	}
695

696 697
	ret = i915_gem_object_set_to_gtt_domain(obj, 1);
	if (ret)
698
		goto out_unpin_pages;
699

700
	offset = obj->gtt_offset + args->offset;
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721

	while (remain > 0) {
		/* Operation in this page
		 *
		 * gtt_page_base = page offset within aperture
		 * gtt_page_offset = offset within page in aperture
		 * data_page_index = page number in get_user_pages return
		 * data_page_offset = offset with data_page_index page.
		 * page_length = bytes to copy for this page
		 */
		gtt_page_base = offset & PAGE_MASK;
		gtt_page_offset = offset & ~PAGE_MASK;
		data_page_index = data_ptr / PAGE_SIZE - first_data_page;
		data_page_offset = data_ptr & ~PAGE_MASK;

		page_length = remain;
		if ((gtt_page_offset + page_length) > PAGE_SIZE)
			page_length = PAGE_SIZE - gtt_page_offset;
		if ((data_page_offset + page_length) > PAGE_SIZE)
			page_length = PAGE_SIZE - data_page_offset;

722 723 724 725 726
		slow_kernel_write(dev_priv->mm.gtt_mapping,
				  gtt_page_base, gtt_page_offset,
				  user_pages[data_page_index],
				  data_page_offset,
				  page_length);
727 728 729 730 731 732 733 734 735

		remain -= page_length;
		offset += page_length;
		data_ptr += page_length;
	}

out_unpin_pages:
	for (i = 0; i < pinned_pages; i++)
		page_cache_release(user_pages[i]);
736
	drm_free_large(user_pages);
737 738 739 740

	return ret;
}

741 742 743 744
/**
 * This is the fast shmem pwrite path, which attempts to directly
 * copy_from_user into the kmapped pages backing the object.
 */
745
static int
746 747
i915_gem_shmem_pwrite_fast(struct drm_device *dev,
			   struct drm_i915_gem_object *obj,
748
			   struct drm_i915_gem_pwrite *args,
749
			   struct drm_file *file)
750
{
751
	struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
752
	ssize_t remain;
753
	loff_t offset;
754 755 756 757 758
	char __user *user_data;
	int page_offset, page_length;

	user_data = (char __user *) (uintptr_t) args->data_ptr;
	remain = args->size;
759

760
	offset = args->offset;
761
	obj->dirty = 1;
762 763

	while (remain > 0) {
764 765 766 767
		struct page *page;
		char *vaddr;
		int ret;

768 769 770 771 772 773 774 775 776 777
		/* Operation in this page
		 *
		 * page_offset = offset within page
		 * page_length = bytes to copy for this page
		 */
		page_offset = offset & (PAGE_SIZE-1);
		page_length = remain;
		if ((page_offset + remain) > PAGE_SIZE)
			page_length = PAGE_SIZE - page_offset;

778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
		page = read_cache_page_gfp(mapping, offset >> PAGE_SHIFT,
					   GFP_HIGHUSER | __GFP_RECLAIMABLE);
		if (IS_ERR(page))
			return PTR_ERR(page);

		vaddr = kmap_atomic(page, KM_USER0);
		ret = __copy_from_user_inatomic(vaddr + page_offset,
						user_data,
						page_length);
		kunmap_atomic(vaddr, KM_USER0);

		set_page_dirty(page);
		mark_page_accessed(page);
		page_cache_release(page);

		/* If we get a fault while copying data, then (presumably) our
		 * source page isn't available.  Return the error and we'll
		 * retry in the slow path.
		 */
		if (ret)
798
			return -EFAULT;
799 800 801 802 803 804

		remain -= page_length;
		user_data += page_length;
		offset += page_length;
	}

805
	return 0;
806 807 808 809 810 811 812 813 814 815
}

/**
 * This is the fallback shmem pwrite path, which uses get_user_pages to pin
 * the memory and maps it using kmap_atomic for copying.
 *
 * This avoids taking mmap_sem for faulting on the user's address while the
 * struct_mutex is held.
 */
static int
816 817
i915_gem_shmem_pwrite_slow(struct drm_device *dev,
			   struct drm_i915_gem_object *obj,
818
			   struct drm_i915_gem_pwrite *args,
819
			   struct drm_file *file)
820
{
821
	struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
822 823 824 825 826
	struct mm_struct *mm = current->mm;
	struct page **user_pages;
	ssize_t remain;
	loff_t offset, pinned_pages, i;
	loff_t first_data_page, last_data_page, num_pages;
827
	int shmem_page_offset;
828 829 830 831
	int data_page_index,  data_page_offset;
	int page_length;
	int ret;
	uint64_t data_ptr = args->data_ptr;
832
	int do_bit17_swizzling;
833 834 835 836 837 838 839 840 841 842 843

	remain = args->size;

	/* Pin the user pages containing the data.  We can't fault while
	 * holding the struct mutex, and all of the pwrite implementations
	 * want to hold it while dereferencing the user data.
	 */
	first_data_page = data_ptr / PAGE_SIZE;
	last_data_page = (data_ptr + args->size - 1) / PAGE_SIZE;
	num_pages = last_data_page - first_data_page + 1;

844
	user_pages = drm_malloc_ab(num_pages, sizeof(struct page *));
845 846 847
	if (user_pages == NULL)
		return -ENOMEM;

848
	mutex_unlock(&dev->struct_mutex);
849 850 851 852
	down_read(&mm->mmap_sem);
	pinned_pages = get_user_pages(current, mm, (uintptr_t)args->data_ptr,
				      num_pages, 0, 0, user_pages, NULL);
	up_read(&mm->mmap_sem);
853
	mutex_lock(&dev->struct_mutex);
854 855
	if (pinned_pages < num_pages) {
		ret = -EFAULT;
856
		goto out;
857 858
	}

859
	ret = i915_gem_object_set_to_cpu_domain(obj, 1);
860
	if (ret)
861
		goto out;
862

863
	do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
864

865
	offset = args->offset;
866
	obj->dirty = 1;
867

868
	while (remain > 0) {
869 870
		struct page *page;

871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
		/* Operation in this page
		 *
		 * shmem_page_offset = offset within page in shmem file
		 * data_page_index = page number in get_user_pages return
		 * data_page_offset = offset with data_page_index page.
		 * page_length = bytes to copy for this page
		 */
		shmem_page_offset = offset & ~PAGE_MASK;
		data_page_index = data_ptr / PAGE_SIZE - first_data_page;
		data_page_offset = data_ptr & ~PAGE_MASK;

		page_length = remain;
		if ((shmem_page_offset + page_length) > PAGE_SIZE)
			page_length = PAGE_SIZE - shmem_page_offset;
		if ((data_page_offset + page_length) > PAGE_SIZE)
			page_length = PAGE_SIZE - data_page_offset;

888 889 890 891 892 893 894
		page = read_cache_page_gfp(mapping, offset >> PAGE_SHIFT,
					   GFP_HIGHUSER | __GFP_RECLAIMABLE);
		if (IS_ERR(page)) {
			ret = PTR_ERR(page);
			goto out;
		}

895
		if (do_bit17_swizzling) {
896
			slow_shmem_bit17_copy(page,
897 898 899
					      shmem_page_offset,
					      user_pages[data_page_index],
					      data_page_offset,
900 901 902
					      page_length,
					      0);
		} else {
903
			slow_shmem_copy(page,
904 905 906 907
					shmem_page_offset,
					user_pages[data_page_index],
					data_page_offset,
					page_length);
908
		}
909

910 911 912 913
		set_page_dirty(page);
		mark_page_accessed(page);
		page_cache_release(page);

914 915 916
		remain -= page_length;
		data_ptr += page_length;
		offset += page_length;
917 918
	}

919
out:
920 921
	for (i = 0; i < pinned_pages; i++)
		page_cache_release(user_pages[i]);
922
	drm_free_large(user_pages);
923

924
	return ret;
925 926 927 928 929 930 931 932 933
}

/**
 * Writes data to the object referenced by handle.
 *
 * On error, the contents of the buffer that were to be modified are undefined.
 */
int
i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
934
		      struct drm_file *file)
935 936
{
	struct drm_i915_gem_pwrite *args = data;
937
	struct drm_i915_gem_object *obj;
938 939 940 941 942 943 944 945 946 947 948 949 950 951
	int ret;

	if (args->size == 0)
		return 0;

	if (!access_ok(VERIFY_READ,
		       (char __user *)(uintptr_t)args->data_ptr,
		       args->size))
		return -EFAULT;

	ret = fault_in_pages_readable((char __user *)(uintptr_t)args->data_ptr,
				      args->size);
	if (ret)
		return -EFAULT;
952

953
	ret = i915_mutex_lock_interruptible(dev);
954
	if (ret)
955
		return ret;
956

957
	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
958 959 960
	if (obj == NULL) {
		ret = -ENOENT;
		goto unlock;
961
	}
962

963
	/* Bounds check destination. */
964 965
	if (args->offset > obj->base.size ||
	    args->size > obj->base.size - args->offset) {
C
Chris Wilson 已提交
966
		ret = -EINVAL;
967
		goto out;
C
Chris Wilson 已提交
968 969
	}

970 971 972 973 974 975
	/* We can only do the GTT pwrite on untiled buffers, as otherwise
	 * it would end up going through the fenced access, and we'll get
	 * different detiling behavior between reading and writing.
	 * pread/pwrite currently are reading and writing from the CPU
	 * perspective, requiring manual detiling by the client.
	 */
976
	if (obj->phys_obj)
977
		ret = i915_gem_phys_pwrite(dev, obj, args, file);
978 979 980
	else if (obj->tiling_mode == I915_TILING_NONE &&
		 obj->gtt_space &&
		 obj->base.write_domain != I915_GEM_DOMAIN_CPU) {
981
		ret = i915_gem_object_pin(obj, 0, true);
982 983 984 985 986 987 988 989 990 991 992 993 994
		if (ret)
			goto out;

		ret = i915_gem_object_set_to_gtt_domain(obj, 1);
		if (ret)
			goto out_unpin;

		ret = i915_gem_gtt_pwrite_fast(dev, obj, args, file);
		if (ret == -EFAULT)
			ret = i915_gem_gtt_pwrite_slow(dev, obj, args, file);

out_unpin:
		i915_gem_object_unpin(obj);
995
	} else {
996 997
		ret = i915_gem_object_set_to_cpu_domain(obj, 1);
		if (ret)
998
			goto out;
999

1000 1001 1002 1003 1004 1005
		ret = -EFAULT;
		if (!i915_gem_object_needs_bit17_swizzle(obj))
			ret = i915_gem_shmem_pwrite_fast(dev, obj, args, file);
		if (ret == -EFAULT)
			ret = i915_gem_shmem_pwrite_slow(dev, obj, args, file);
	}
1006

1007
out:
1008
	drm_gem_object_unreference(&obj->base);
1009
unlock:
1010
	mutex_unlock(&dev->struct_mutex);
1011 1012 1013 1014
	return ret;
}

/**
1015 1016
 * Called when user space prepares to use an object with the CPU, either
 * through the mmap ioctl's mapping or a GTT mapping.
1017 1018 1019
 */
int
i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
1020
			  struct drm_file *file)
1021
{
1022
	struct drm_i915_private *dev_priv = dev->dev_private;
1023
	struct drm_i915_gem_set_domain *args = data;
1024
	struct drm_i915_gem_object *obj;
1025 1026
	uint32_t read_domains = args->read_domains;
	uint32_t write_domain = args->write_domain;
1027 1028 1029 1030 1031
	int ret;

	if (!(dev->driver->driver_features & DRIVER_GEM))
		return -ENODEV;

1032
	/* Only handle setting domains to types used by the CPU. */
1033
	if (write_domain & I915_GEM_GPU_DOMAINS)
1034 1035
		return -EINVAL;

1036
	if (read_domains & I915_GEM_GPU_DOMAINS)
1037 1038 1039 1040 1041 1042 1043 1044
		return -EINVAL;

	/* Having something in the write domain implies it's in the read
	 * domain, and only that read domain.  Enforce that in the request.
	 */
	if (write_domain != 0 && read_domains != write_domain)
		return -EINVAL;

1045
	ret = i915_mutex_lock_interruptible(dev);
1046
	if (ret)
1047
		return ret;
1048

1049
	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
1050 1051 1052
	if (obj == NULL) {
		ret = -ENOENT;
		goto unlock;
1053
	}
1054

1055 1056
	intel_mark_busy(dev, obj);

1057 1058
	if (read_domains & I915_GEM_DOMAIN_GTT) {
		ret = i915_gem_object_set_to_gtt_domain(obj, write_domain != 0);
1059

1060 1061 1062
		/* Update the LRU on the fence for the CPU access that's
		 * about to occur.
		 */
1063
		if (obj->fence_reg != I915_FENCE_REG_NONE) {
1064
			struct drm_i915_fence_reg *reg =
1065
				&dev_priv->fence_regs[obj->fence_reg];
1066
			list_move_tail(&reg->lru_list,
1067 1068 1069
				       &dev_priv->mm.fence_list);
		}

1070 1071 1072 1073 1074 1075
		/* Silently promote "you're not bound, there was nothing to do"
		 * to success, since the client was just asking us to
		 * make sure everything was done.
		 */
		if (ret == -EINVAL)
			ret = 0;
1076
	} else {
1077
		ret = i915_gem_object_set_to_cpu_domain(obj, write_domain != 0);
1078 1079
	}

1080
	/* Maintain LRU order of "inactive" objects */
1081 1082
	if (ret == 0 && i915_gem_object_is_inactive(obj))
		list_move_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
1083

1084
	drm_gem_object_unreference(&obj->base);
1085
unlock:
1086 1087 1088 1089 1090 1091 1092 1093 1094
	mutex_unlock(&dev->struct_mutex);
	return ret;
}

/**
 * Called when user space has done writes to this buffer
 */
int
i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
1095
			 struct drm_file *file)
1096 1097
{
	struct drm_i915_gem_sw_finish *args = data;
1098
	struct drm_i915_gem_object *obj;
1099 1100 1101 1102 1103
	int ret = 0;

	if (!(dev->driver->driver_features & DRIVER_GEM))
		return -ENODEV;

1104
	ret = i915_mutex_lock_interruptible(dev);
1105
	if (ret)
1106
		return ret;
1107

1108
	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
1109
	if (obj == NULL) {
1110 1111
		ret = -ENOENT;
		goto unlock;
1112 1113 1114
	}

	/* Pinned buffers may be scanout, so flush the cache */
1115
	if (obj->pin_count)
1116 1117
		i915_gem_object_flush_cpu_write_domain(obj);

1118
	drm_gem_object_unreference(&obj->base);
1119
unlock:
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
	mutex_unlock(&dev->struct_mutex);
	return ret;
}

/**
 * Maps the contents of an object, returning the address it is mapped
 * into.
 *
 * While the mapping holds a reference on the contents of the object, it doesn't
 * imply a ref on the object itself.
 */
int
i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
1133
		    struct drm_file *file)
1134
{
1135
	struct drm_i915_private *dev_priv = dev->dev_private;
1136 1137 1138 1139 1140 1141 1142 1143
	struct drm_i915_gem_mmap *args = data;
	struct drm_gem_object *obj;
	loff_t offset;
	unsigned long addr;

	if (!(dev->driver->driver_features & DRIVER_GEM))
		return -ENODEV;

1144
	obj = drm_gem_object_lookup(dev, file, args->handle);
1145
	if (obj == NULL)
1146
		return -ENOENT;
1147

1148 1149 1150 1151 1152
	if (obj->size > dev_priv->mm.gtt_mappable_end) {
		drm_gem_object_unreference_unlocked(obj);
		return -E2BIG;
	}

1153 1154 1155 1156 1157 1158 1159
	offset = args->offset;

	down_write(&current->mm->mmap_sem);
	addr = do_mmap(obj->filp, 0, args->size,
		       PROT_READ | PROT_WRITE, MAP_SHARED,
		       args->offset);
	up_write(&current->mm->mmap_sem);
1160
	drm_gem_object_unreference_unlocked(obj);
1161 1162 1163 1164 1165 1166 1167 1168
	if (IS_ERR((void *)addr))
		return addr;

	args->addr_ptr = (uint64_t) addr;

	return 0;
}

1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
/**
 * i915_gem_fault - fault a page into the GTT
 * vma: VMA in question
 * vmf: fault info
 *
 * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
 * from userspace.  The fault handler takes care of binding the object to
 * the GTT (if needed), allocating and programming a fence register (again,
 * only if needed based on whether the old reg is still valid or the object
 * is tiled) and inserting a new PTE into the faulting process.
 *
 * Note that the faulting process may involve evicting existing objects
 * from the GTT and/or fence registers to make room.  So performance may
 * suffer if the GTT working set is large or there are few fence registers
 * left.
 */
int i915_gem_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
1187 1188
	struct drm_i915_gem_object *obj = to_intel_bo(vma->vm_private_data);
	struct drm_device *dev = obj->base.dev;
1189
	drm_i915_private_t *dev_priv = dev->dev_private;
1190 1191 1192
	pgoff_t page_offset;
	unsigned long pfn;
	int ret = 0;
1193
	bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
1194 1195 1196 1197 1198 1199 1200

	/* We don't use vmf->pgoff since that has the fake offset */
	page_offset = ((unsigned long)vmf->virtual_address - vma->vm_start) >>
		PAGE_SHIFT;

	/* Now bind it into the GTT if needed */
	mutex_lock(&dev->struct_mutex);
1201

1202 1203 1204 1205
	if (!obj->map_and_fenceable) {
		ret = i915_gem_object_unbind(obj);
		if (ret)
			goto unlock;
1206
	}
1207
	if (!obj->gtt_space) {
1208
		ret = i915_gem_object_bind_to_gtt(obj, 0, true);
1209 1210
		if (ret)
			goto unlock;
1211 1212
	}

1213 1214 1215 1216
	ret = i915_gem_object_set_to_gtt_domain(obj, write);
	if (ret)
		goto unlock;

1217
	/* Need a new fence register? */
1218
	if (obj->tiling_mode != I915_TILING_NONE) {
1219
		ret = i915_gem_object_get_fence_reg(obj, true);
1220 1221
		if (ret)
			goto unlock;
1222
	}
1223

1224 1225
	if (i915_gem_object_is_inactive(obj))
		list_move_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
1226

1227 1228
	obj->fault_mappable = true;

1229
	pfn = ((dev->agp->base + obj->gtt_offset) >> PAGE_SHIFT) +
1230 1231 1232 1233
		page_offset;

	/* Finally, remap it using the new GTT offset */
	ret = vm_insert_pfn(vma, (unsigned long)vmf->virtual_address, pfn);
1234
unlock:
1235 1236 1237
	mutex_unlock(&dev->struct_mutex);

	switch (ret) {
1238 1239
	case -EAGAIN:
		set_need_resched();
1240 1241 1242
	case 0:
	case -ERESTARTSYS:
		return VM_FAULT_NOPAGE;
1243 1244 1245
	case -ENOMEM:
		return VM_FAULT_OOM;
	default:
1246
		return VM_FAULT_SIGBUS;
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
	}
}

/**
 * i915_gem_create_mmap_offset - create a fake mmap offset for an object
 * @obj: obj in question
 *
 * GEM memory mapping works by handing back to userspace a fake mmap offset
 * it can use in a subsequent mmap(2) call.  The DRM core code then looks
 * up the object based on the offset and sets up the various memory mapping
 * structures.
 *
 * This routine allocates and attaches a fake offset for @obj.
 */
static int
1262
i915_gem_create_mmap_offset(struct drm_i915_gem_object *obj)
1263
{
1264
	struct drm_device *dev = obj->base.dev;
1265 1266
	struct drm_gem_mm *mm = dev->mm_private;
	struct drm_map_list *list;
1267
	struct drm_local_map *map;
1268 1269 1270
	int ret = 0;

	/* Set the object up for mmap'ing */
1271
	list = &obj->base.map_list;
1272
	list->map = kzalloc(sizeof(struct drm_map_list), GFP_KERNEL);
1273 1274 1275 1276 1277
	if (!list->map)
		return -ENOMEM;

	map = list->map;
	map->type = _DRM_GEM;
1278
	map->size = obj->base.size;
1279 1280 1281 1282
	map->handle = obj;

	/* Get a DRM GEM mmap offset allocated... */
	list->file_offset_node = drm_mm_search_free(&mm->offset_manager,
1283 1284
						    obj->base.size / PAGE_SIZE,
						    0, 0);
1285
	if (!list->file_offset_node) {
1286 1287
		DRM_ERROR("failed to allocate offset for bo %d\n",
			  obj->base.name);
1288
		ret = -ENOSPC;
1289 1290 1291 1292
		goto out_free_list;
	}

	list->file_offset_node = drm_mm_get_block(list->file_offset_node,
1293 1294
						  obj->base.size / PAGE_SIZE,
						  0);
1295 1296 1297 1298 1299 1300
	if (!list->file_offset_node) {
		ret = -ENOMEM;
		goto out_free_list;
	}

	list->hash.key = list->file_offset_node->start;
1301 1302
	ret = drm_ht_insert_item(&mm->offset_hash, &list->hash);
	if (ret) {
1303 1304 1305 1306 1307 1308 1309 1310 1311
		DRM_ERROR("failed to add to map hash\n");
		goto out_free_mm;
	}

	return 0;

out_free_mm:
	drm_mm_put_block(list->file_offset_node);
out_free_list:
1312
	kfree(list->map);
C
Chris Wilson 已提交
1313
	list->map = NULL;
1314 1315 1316 1317

	return ret;
}

1318 1319 1320 1321
/**
 * i915_gem_release_mmap - remove physical page mappings
 * @obj: obj in question
 *
1322
 * Preserve the reservation of the mmapping with the DRM core code, but
1323 1324 1325 1326 1327 1328 1329 1330 1331
 * relinquish ownership of the pages back to the system.
 *
 * It is vital that we remove the page mapping if we have mapped a tiled
 * object through the GTT and then lose the fence register due to
 * resource pressure. Similarly if the object has been moved out of the
 * aperture, than pages mapped into userspace must be revoked. Removing the
 * mapping will then trigger a page fault on the next user access, allowing
 * fixup by i915_gem_fault().
 */
1332
void
1333
i915_gem_release_mmap(struct drm_i915_gem_object *obj)
1334
{
1335 1336
	if (!obj->fault_mappable)
		return;
1337

1338 1339 1340
	unmap_mapping_range(obj->base.dev->dev_mapping,
			    (loff_t)obj->base.map_list.hash.key<<PAGE_SHIFT,
			    obj->base.size, 1);
1341

1342
	obj->fault_mappable = false;
1343 1344
}

1345
static void
1346
i915_gem_free_mmap_offset(struct drm_i915_gem_object *obj)
1347
{
1348
	struct drm_device *dev = obj->base.dev;
1349
	struct drm_gem_mm *mm = dev->mm_private;
1350
	struct drm_map_list *list = &obj->base.map_list;
1351 1352

	drm_ht_remove_item(&mm->offset_hash, &list->hash);
C
Chris Wilson 已提交
1353 1354 1355
	drm_mm_put_block(list->file_offset_node);
	kfree(list->map);
	list->map = NULL;
1356 1357
}

1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
static uint32_t
i915_gem_get_gtt_size(struct drm_i915_gem_object *obj)
{
	struct drm_device *dev = obj->base.dev;
	uint32_t size;

	if (INTEL_INFO(dev)->gen >= 4 ||
	    obj->tiling_mode == I915_TILING_NONE)
		return obj->base.size;

	/* Previous chips need a power-of-two fence region when tiling */
	if (INTEL_INFO(dev)->gen == 3)
		size = 1024*1024;
	else
		size = 512*1024;

	while (size < obj->base.size)
		size <<= 1;

	return size;
}

1380 1381 1382 1383 1384
/**
 * i915_gem_get_gtt_alignment - return required GTT alignment for an object
 * @obj: object to check
 *
 * Return the required GTT alignment for an object, taking into account
1385
 * potential fence register mapping.
1386 1387
 */
static uint32_t
1388
i915_gem_get_gtt_alignment(struct drm_i915_gem_object *obj)
1389
{
1390
	struct drm_device *dev = obj->base.dev;
1391 1392 1393 1394 1395

	/*
	 * Minimum alignment is 4k (GTT page size), but might be greater
	 * if a fence register is needed for the object.
	 */
1396
	if (INTEL_INFO(dev)->gen >= 4 ||
1397
	    obj->tiling_mode == I915_TILING_NONE)
1398 1399
		return 4096;

1400 1401 1402 1403
	/*
	 * Previous chips need to be aligned to the size of the smallest
	 * fence register that can contain the object.
	 */
1404
	return i915_gem_get_gtt_size(obj);
1405 1406
}

1407 1408 1409 1410 1411 1412 1413 1414 1415
/**
 * i915_gem_get_unfenced_gtt_alignment - return required GTT alignment for an
 *					 unfenced object
 * @obj: object to check
 *
 * Return the required GTT alignment for an object, only taking into account
 * unfenced tiled surface requirements.
 */
static uint32_t
1416
i915_gem_get_unfenced_gtt_alignment(struct drm_i915_gem_object *obj)
1417
{
1418
	struct drm_device *dev = obj->base.dev;
1419 1420 1421 1422 1423 1424
	int tile_height;

	/*
	 * Minimum alignment is 4k (GTT page size) for sane hw.
	 */
	if (INTEL_INFO(dev)->gen >= 4 || IS_G33(dev) ||
1425
	    obj->tiling_mode == I915_TILING_NONE)
1426 1427 1428 1429 1430 1431 1432 1433
		return 4096;

	/*
	 * Older chips need unfenced tiled buffers to be aligned to the left
	 * edge of an even tile row (where tile rows are counted as if the bo is
	 * placed in a fenced gtt region).
	 */
	if (IS_GEN2(dev) ||
1434
	    (obj->tiling_mode == I915_TILING_Y && HAS_128_BYTE_Y_TILING(dev)))
1435 1436 1437 1438
		tile_height = 32;
	else
		tile_height = 8;

1439
	return tile_height * obj->stride * 2;
1440 1441
}

1442 1443 1444 1445
/**
 * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
 * @dev: DRM device
 * @data: GTT mapping ioctl data
1446
 * @file: GEM object info
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
 *
 * Simply returns the fake offset to userspace so it can mmap it.
 * The mmap call will end up in drm_gem_mmap(), which will set things
 * up so we can get faults in the handler above.
 *
 * The fault handler will take care of binding the object into the GTT
 * (since it may have been evicted to make room for something), allocating
 * a fence register, and mapping the appropriate aperture address into
 * userspace.
 */
int
i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
1459
			struct drm_file *file)
1460
{
1461
	struct drm_i915_private *dev_priv = dev->dev_private;
1462
	struct drm_i915_gem_mmap_gtt *args = data;
1463
	struct drm_i915_gem_object *obj;
1464 1465 1466 1467 1468
	int ret;

	if (!(dev->driver->driver_features & DRIVER_GEM))
		return -ENODEV;

1469
	ret = i915_mutex_lock_interruptible(dev);
1470
	if (ret)
1471
		return ret;
1472

1473
	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
1474 1475 1476 1477
	if (obj == NULL) {
		ret = -ENOENT;
		goto unlock;
	}
1478

1479
	if (obj->base.size > dev_priv->mm.gtt_mappable_end) {
1480 1481 1482 1483
		ret = -E2BIG;
		goto unlock;
	}

1484
	if (obj->madv != I915_MADV_WILLNEED) {
1485
		DRM_ERROR("Attempting to mmap a purgeable buffer\n");
1486 1487
		ret = -EINVAL;
		goto out;
1488 1489
	}

1490
	if (!obj->base.map_list.map) {
1491
		ret = i915_gem_create_mmap_offset(obj);
1492 1493
		if (ret)
			goto out;
1494 1495
	}

1496
	args->offset = (u64)obj->base.map_list.hash.key << PAGE_SHIFT;
1497

1498
out:
1499
	drm_gem_object_unreference(&obj->base);
1500
unlock:
1501
	mutex_unlock(&dev->struct_mutex);
1502
	return ret;
1503 1504
}

1505
static int
1506
i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj,
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
			      gfp_t gfpmask)
{
	int page_count, i;
	struct address_space *mapping;
	struct inode *inode;
	struct page *page;

	/* Get the list of pages out of our struct file.  They'll be pinned
	 * at this point until we release them.
	 */
1517 1518 1519 1520
	page_count = obj->base.size / PAGE_SIZE;
	BUG_ON(obj->pages != NULL);
	obj->pages = drm_malloc_ab(page_count, sizeof(struct page *));
	if (obj->pages == NULL)
1521 1522
		return -ENOMEM;

1523
	inode = obj->base.filp->f_path.dentry->d_inode;
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
	mapping = inode->i_mapping;
	for (i = 0; i < page_count; i++) {
		page = read_cache_page_gfp(mapping, i,
					   GFP_HIGHUSER |
					   __GFP_COLD |
					   __GFP_RECLAIMABLE |
					   gfpmask);
		if (IS_ERR(page))
			goto err_pages;

1534
		obj->pages[i] = page;
1535 1536
	}

1537
	if (obj->tiling_mode != I915_TILING_NONE)
1538 1539 1540 1541 1542 1543
		i915_gem_object_do_bit_17_swizzle(obj);

	return 0;

err_pages:
	while (i--)
1544
		page_cache_release(obj->pages[i]);
1545

1546 1547
	drm_free_large(obj->pages);
	obj->pages = NULL;
1548 1549 1550
	return PTR_ERR(page);
}

1551
static void
1552
i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj)
1553
{
1554
	int page_count = obj->base.size / PAGE_SIZE;
1555 1556
	int i;

1557
	BUG_ON(obj->madv == __I915_MADV_PURGED);
1558

1559
	if (obj->tiling_mode != I915_TILING_NONE)
1560 1561
		i915_gem_object_save_bit_17_swizzle(obj);

1562 1563
	if (obj->madv == I915_MADV_DONTNEED)
		obj->dirty = 0;
1564 1565

	for (i = 0; i < page_count; i++) {
1566 1567
		if (obj->dirty)
			set_page_dirty(obj->pages[i]);
1568

1569 1570
		if (obj->madv == I915_MADV_WILLNEED)
			mark_page_accessed(obj->pages[i]);
1571

1572
		page_cache_release(obj->pages[i]);
1573
	}
1574
	obj->dirty = 0;
1575

1576 1577
	drm_free_large(obj->pages);
	obj->pages = NULL;
1578 1579
}

1580 1581 1582 1583 1584
static uint32_t
i915_gem_next_request_seqno(struct drm_device *dev,
			    struct intel_ring_buffer *ring)
{
	drm_i915_private_t *dev_priv = dev->dev_private;
1585
	return ring->outstanding_lazy_request = dev_priv->next_seqno;
1586 1587
}

1588
static void
1589
i915_gem_object_move_to_active(struct drm_i915_gem_object *obj,
1590
			       struct intel_ring_buffer *ring)
1591
{
1592
	struct drm_device *dev = obj->base.dev;
1593
	struct drm_i915_private *dev_priv = dev->dev_private;
1594
	uint32_t seqno = i915_gem_next_request_seqno(dev, ring);
1595

1596
	BUG_ON(ring == NULL);
1597
	obj->ring = ring;
1598 1599

	/* Add a reference if we're newly entering the active list. */
1600 1601 1602
	if (!obj->active) {
		drm_gem_object_reference(&obj->base);
		obj->active = 1;
1603
	}
1604

1605
	/* Move from whatever list we were on to the tail of execution. */
1606 1607
	list_move_tail(&obj->mm_list, &dev_priv->mm.active_list);
	list_move_tail(&obj->ring_list, &ring->active_list);
1608

1609
	obj->last_rendering_seqno = seqno;
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
	if (obj->fenced_gpu_access) {
		struct drm_i915_fence_reg *reg;

		BUG_ON(obj->fence_reg == I915_FENCE_REG_NONE);

		obj->last_fenced_seqno = seqno;
		obj->last_fenced_ring = ring;

		reg = &dev_priv->fence_regs[obj->fence_reg];
		list_move_tail(&reg->lru_list, &dev_priv->mm.fence_list);
	}
}

static void
i915_gem_object_move_off_active(struct drm_i915_gem_object *obj)
{
	list_del_init(&obj->ring_list);
	obj->last_rendering_seqno = 0;
	obj->last_fenced_seqno = 0;
1629 1630
}

1631
static void
1632
i915_gem_object_move_to_flushing(struct drm_i915_gem_object *obj)
1633
{
1634
	struct drm_device *dev = obj->base.dev;
1635 1636
	drm_i915_private_t *dev_priv = dev->dev_private;

1637 1638
	BUG_ON(!obj->active);
	list_move_tail(&obj->mm_list, &dev_priv->mm.flushing_list);
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665

	i915_gem_object_move_off_active(obj);
}

static void
i915_gem_object_move_to_inactive(struct drm_i915_gem_object *obj)
{
	struct drm_device *dev = obj->base.dev;
	struct drm_i915_private *dev_priv = dev->dev_private;

	if (obj->pin_count != 0)
		list_move_tail(&obj->mm_list, &dev_priv->mm.pinned_list);
	else
		list_move_tail(&obj->mm_list, &dev_priv->mm.inactive_list);

	BUG_ON(!list_empty(&obj->gpu_write_list));
	BUG_ON(!obj->active);
	obj->ring = NULL;

	i915_gem_object_move_off_active(obj);
	obj->fenced_gpu_access = false;
	obj->last_fenced_ring = NULL;

	obj->active = 0;
	drm_gem_object_unreference(&obj->base);

	WARN_ON(i915_verify_lists(dev));
1666
}
1667

1668 1669
/* Immediately discard the backing storage */
static void
1670
i915_gem_object_truncate(struct drm_i915_gem_object *obj)
1671
{
C
Chris Wilson 已提交
1672
	struct inode *inode;
1673

1674 1675 1676 1677 1678 1679
	/* Our goal here is to return as much of the memory as
	 * is possible back to the system as we are called from OOM.
	 * To do this we must instruct the shmfs to drop all of its
	 * backing pages, *now*. Here we mirror the actions taken
	 * when by shmem_delete_inode() to release the backing store.
	 */
1680
	inode = obj->base.filp->f_path.dentry->d_inode;
1681 1682 1683
	truncate_inode_pages(inode->i_mapping, 0);
	if (inode->i_op->truncate_range)
		inode->i_op->truncate_range(inode, 0, (loff_t)-1);
C
Chris Wilson 已提交
1684

1685
	obj->madv = __I915_MADV_PURGED;
1686 1687 1688
}

static inline int
1689
i915_gem_object_is_purgeable(struct drm_i915_gem_object *obj)
1690
{
1691
	return obj->madv == I915_MADV_DONTNEED;
1692 1693
}

1694 1695
static void
i915_gem_process_flushing_list(struct drm_device *dev,
1696
			       uint32_t flush_domains,
1697
			       struct intel_ring_buffer *ring)
1698
{
1699
	struct drm_i915_gem_object *obj, *next;
1700

1701
	list_for_each_entry_safe(obj, next,
1702
				 &ring->gpu_write_list,
1703
				 gpu_write_list) {
1704 1705
		if (obj->base.write_domain & flush_domains) {
			uint32_t old_write_domain = obj->base.write_domain;
1706

1707 1708
			obj->base.write_domain = 0;
			list_del_init(&obj->gpu_write_list);
1709
			i915_gem_object_move_to_active(obj, ring);
1710 1711

			trace_i915_gem_object_change_domain(obj,
1712
							    obj->base.read_domains,
1713 1714 1715 1716
							    old_write_domain);
		}
	}
}
1717

1718
int
1719
i915_add_request(struct drm_device *dev,
1720
		 struct drm_file *file,
C
Chris Wilson 已提交
1721
		 struct drm_i915_gem_request *request,
1722
		 struct intel_ring_buffer *ring)
1723 1724
{
	drm_i915_private_t *dev_priv = dev->dev_private;
1725
	struct drm_i915_file_private *file_priv = NULL;
1726 1727
	uint32_t seqno;
	int was_empty;
1728 1729 1730
	int ret;

	BUG_ON(request == NULL);
1731

1732 1733
	if (file != NULL)
		file_priv = file->driver_priv;
1734

1735 1736 1737
	ret = ring->add_request(ring, &seqno);
	if (ret)
	    return ret;
1738

1739
	ring->outstanding_lazy_request = false;
1740 1741

	request->seqno = seqno;
1742
	request->ring = ring;
1743
	request->emitted_jiffies = jiffies;
1744 1745 1746
	was_empty = list_empty(&ring->request_list);
	list_add_tail(&request->list, &ring->request_list);

1747
	if (file_priv) {
1748
		spin_lock(&file_priv->mm.lock);
1749
		request->file_priv = file_priv;
1750
		list_add_tail(&request->client_list,
1751
			      &file_priv->mm.request_list);
1752
		spin_unlock(&file_priv->mm.lock);
1753
	}
1754

B
Ben Gamari 已提交
1755
	if (!dev_priv->mm.suspended) {
1756 1757
		mod_timer(&dev_priv->hangcheck_timer,
			  jiffies + msecs_to_jiffies(DRM_I915_HANGCHECK_PERIOD));
B
Ben Gamari 已提交
1758
		if (was_empty)
1759 1760
			queue_delayed_work(dev_priv->wq,
					   &dev_priv->mm.retire_work, HZ);
B
Ben Gamari 已提交
1761
	}
1762
	return 0;
1763 1764 1765 1766 1767 1768 1769 1770
}

/**
 * Command execution barrier
 *
 * Ensures that all commands in the ring are finished
 * before signalling the CPU
 */
1771
static void
1772
i915_retire_commands(struct drm_device *dev, struct intel_ring_buffer *ring)
1773 1774 1775 1776
{
	uint32_t flush_domains = 0;

	/* The sampler always gets flushed on i965 (sigh) */
1777
	if (INTEL_INFO(dev)->gen >= 4)
1778
		flush_domains |= I915_GEM_DOMAIN_SAMPLER;
1779

1780
	ring->flush(ring, I915_GEM_DOMAIN_COMMAND, flush_domains);
1781 1782
}

1783 1784
static inline void
i915_gem_request_remove_from_client(struct drm_i915_gem_request *request)
1785
{
1786
	struct drm_i915_file_private *file_priv = request->file_priv;
1787

1788 1789
	if (!file_priv)
		return;
C
Chris Wilson 已提交
1790

1791 1792 1793 1794
	spin_lock(&file_priv->mm.lock);
	list_del(&request->client_list);
	request->file_priv = NULL;
	spin_unlock(&file_priv->mm.lock);
1795 1796
}

1797 1798
static void i915_gem_reset_ring_lists(struct drm_i915_private *dev_priv,
				      struct intel_ring_buffer *ring)
1799
{
1800 1801
	while (!list_empty(&ring->request_list)) {
		struct drm_i915_gem_request *request;
1802

1803 1804 1805
		request = list_first_entry(&ring->request_list,
					   struct drm_i915_gem_request,
					   list);
1806

1807
		list_del(&request->list);
1808
		i915_gem_request_remove_from_client(request);
1809 1810
		kfree(request);
	}
1811

1812
	while (!list_empty(&ring->active_list)) {
1813
		struct drm_i915_gem_object *obj;
1814

1815 1816 1817
		obj = list_first_entry(&ring->active_list,
				       struct drm_i915_gem_object,
				       ring_list);
1818

1819 1820 1821
		obj->base.write_domain = 0;
		list_del_init(&obj->gpu_write_list);
		i915_gem_object_move_to_inactive(obj);
1822 1823 1824
	}
}

1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
static void i915_gem_reset_fences(struct drm_device *dev)
{
	struct drm_i915_private *dev_priv = dev->dev_private;
	int i;

	for (i = 0; i < 16; i++) {
		struct drm_i915_fence_reg *reg = &dev_priv->fence_regs[i];
		if (reg->obj)
			i915_gem_clear_fence_reg(reg->obj);
	}
}

1837
void i915_gem_reset(struct drm_device *dev)
1838
{
1839
	struct drm_i915_private *dev_priv = dev->dev_private;
1840
	struct drm_i915_gem_object *obj;
1841

1842
	i915_gem_reset_ring_lists(dev_priv, &dev_priv->render_ring);
1843
	i915_gem_reset_ring_lists(dev_priv, &dev_priv->bsd_ring);
1844
	i915_gem_reset_ring_lists(dev_priv, &dev_priv->blt_ring);
1845 1846 1847 1848 1849 1850

	/* Remove anything from the flushing lists. The GPU cache is likely
	 * to be lost on reset along with the data, so simply move the
	 * lost bo to the inactive list.
	 */
	while (!list_empty(&dev_priv->mm.flushing_list)) {
1851 1852 1853
		obj= list_first_entry(&dev_priv->mm.flushing_list,
				      struct drm_i915_gem_object,
				      mm_list);
1854

1855 1856 1857
		obj->base.write_domain = 0;
		list_del_init(&obj->gpu_write_list);
		i915_gem_object_move_to_inactive(obj);
1858 1859 1860 1861 1862
	}

	/* Move everything out of the GPU domains to ensure we do any
	 * necessary invalidation upon reuse.
	 */
1863
	list_for_each_entry(obj,
1864
			    &dev_priv->mm.inactive_list,
1865
			    mm_list)
1866
	{
1867
		obj->base.read_domains &= ~I915_GEM_GPU_DOMAINS;
1868
	}
1869 1870

	/* The fence registers are invalidated so clear them out */
1871
	i915_gem_reset_fences(dev);
1872 1873 1874 1875 1876
}

/**
 * This function clears the request list as sequence numbers are passed.
 */
1877 1878 1879
static void
i915_gem_retire_requests_ring(struct drm_device *dev,
			      struct intel_ring_buffer *ring)
1880 1881 1882 1883
{
	drm_i915_private_t *dev_priv = dev->dev_private;
	uint32_t seqno;

1884 1885
	if (!ring->status_page.page_addr ||
	    list_empty(&ring->request_list))
1886 1887
		return;

1888
	WARN_ON(i915_verify_lists(dev));
1889

1890
	seqno = ring->get_seqno(ring);
1891
	while (!list_empty(&ring->request_list)) {
1892 1893
		struct drm_i915_gem_request *request;

1894
		request = list_first_entry(&ring->request_list,
1895 1896 1897
					   struct drm_i915_gem_request,
					   list);

1898
		if (!i915_seqno_passed(seqno, request->seqno))
1899 1900 1901 1902 1903
			break;

		trace_i915_gem_request_retire(dev, request->seqno);

		list_del(&request->list);
1904
		i915_gem_request_remove_from_client(request);
1905 1906
		kfree(request);
	}
1907

1908 1909 1910 1911
	/* Move any buffers on the active list that are no longer referenced
	 * by the ringbuffer to the flushing/inactive lists as appropriate.
	 */
	while (!list_empty(&ring->active_list)) {
1912
		struct drm_i915_gem_object *obj;
1913

1914 1915 1916
		obj= list_first_entry(&ring->active_list,
				      struct drm_i915_gem_object,
				      ring_list);
1917

1918
		if (!i915_seqno_passed(seqno, obj->last_rendering_seqno))
1919
			break;
1920

1921
		if (obj->base.write_domain != 0)
1922 1923 1924
			i915_gem_object_move_to_flushing(obj);
		else
			i915_gem_object_move_to_inactive(obj);
1925
	}
1926 1927 1928

	if (unlikely (dev_priv->trace_irq_seqno &&
		      i915_seqno_passed(dev_priv->trace_irq_seqno, seqno))) {
1929
		ring->user_irq_put(ring);
1930 1931
		dev_priv->trace_irq_seqno = 0;
	}
1932 1933

	WARN_ON(i915_verify_lists(dev));
1934 1935
}

1936 1937 1938 1939 1940
void
i915_gem_retire_requests(struct drm_device *dev)
{
	drm_i915_private_t *dev_priv = dev->dev_private;

1941
	if (!list_empty(&dev_priv->mm.deferred_free_list)) {
1942
	    struct drm_i915_gem_object *obj, *next;
1943 1944 1945 1946 1947 1948

	    /* We must be careful that during unbind() we do not
	     * accidentally infinitely recurse into retire requests.
	     * Currently:
	     *   retire -> free -> unbind -> wait -> retire_ring
	     */
1949
	    list_for_each_entry_safe(obj, next,
1950
				     &dev_priv->mm.deferred_free_list,
1951
				     mm_list)
1952
		    i915_gem_free_object_tail(obj);
1953 1954
	}

1955
	i915_gem_retire_requests_ring(dev, &dev_priv->render_ring);
1956
	i915_gem_retire_requests_ring(dev, &dev_priv->bsd_ring);
1957
	i915_gem_retire_requests_ring(dev, &dev_priv->blt_ring);
1958 1959
}

1960
static void
1961 1962 1963 1964 1965 1966 1967 1968 1969
i915_gem_retire_work_handler(struct work_struct *work)
{
	drm_i915_private_t *dev_priv;
	struct drm_device *dev;

	dev_priv = container_of(work, drm_i915_private_t,
				mm.retire_work.work);
	dev = dev_priv->dev;

1970 1971 1972 1973 1974 1975
	/* Come back later if the device is busy... */
	if (!mutex_trylock(&dev->struct_mutex)) {
		queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, HZ);
		return;
	}

1976
	i915_gem_retire_requests(dev);
1977

1978
	if (!dev_priv->mm.suspended &&
1979
		(!list_empty(&dev_priv->render_ring.request_list) ||
1980 1981
		 !list_empty(&dev_priv->bsd_ring.request_list) ||
		 !list_empty(&dev_priv->blt_ring.request_list)))
1982
		queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, HZ);
1983 1984 1985
	mutex_unlock(&dev->struct_mutex);
}

1986
int
1987
i915_do_wait_request(struct drm_device *dev, uint32_t seqno,
1988
		     bool interruptible, struct intel_ring_buffer *ring)
1989 1990
{
	drm_i915_private_t *dev_priv = dev->dev_private;
1991
	u32 ier;
1992 1993 1994 1995
	int ret = 0;

	BUG_ON(seqno == 0);

1996
	if (atomic_read(&dev_priv->mm.wedged))
1997 1998
		return -EAGAIN;

1999
	if (seqno == ring->outstanding_lazy_request) {
2000 2001 2002 2003
		struct drm_i915_gem_request *request;

		request = kzalloc(sizeof(*request), GFP_KERNEL);
		if (request == NULL)
2004
			return -ENOMEM;
2005 2006 2007 2008 2009 2010 2011 2012

		ret = i915_add_request(dev, NULL, request, ring);
		if (ret) {
			kfree(request);
			return ret;
		}

		seqno = request->seqno;
2013
	}
2014

2015
	if (!i915_seqno_passed(ring->get_seqno(ring), seqno)) {
2016
		if (HAS_PCH_SPLIT(dev))
2017 2018 2019
			ier = I915_READ(DEIER) | I915_READ(GTIER);
		else
			ier = I915_READ(IER);
2020 2021 2022 2023 2024 2025 2026
		if (!ier) {
			DRM_ERROR("something (likely vbetool) disabled "
				  "interrupts, re-enabling\n");
			i915_driver_irq_preinstall(dev);
			i915_driver_irq_postinstall(dev);
		}

C
Chris Wilson 已提交
2027 2028
		trace_i915_gem_request_wait_begin(dev, seqno);

2029
		ring->waiting_seqno = seqno;
2030
		ring->user_irq_get(ring);
2031
		if (interruptible)
2032
			ret = wait_event_interruptible(ring->irq_queue,
2033
				i915_seqno_passed(ring->get_seqno(ring), seqno)
2034
				|| atomic_read(&dev_priv->mm.wedged));
2035
		else
2036
			wait_event(ring->irq_queue,
2037
				i915_seqno_passed(ring->get_seqno(ring), seqno)
2038
				|| atomic_read(&dev_priv->mm.wedged));
2039

2040
		ring->user_irq_put(ring);
2041
		ring->waiting_seqno = 0;
C
Chris Wilson 已提交
2042 2043

		trace_i915_gem_request_wait_end(dev, seqno);
2044
	}
2045
	if (atomic_read(&dev_priv->mm.wedged))
2046
		ret = -EAGAIN;
2047 2048

	if (ret && ret != -ERESTARTSYS)
2049
		DRM_ERROR("%s returns %d (awaiting %d at %d, next %d)\n",
2050
			  __func__, ret, seqno, ring->get_seqno(ring),
2051
			  dev_priv->next_seqno);
2052 2053 2054 2055 2056 2057 2058

	/* Directly dispatch request retiring.  While we have the work queue
	 * to handle this, the waiter on a request often wants an associated
	 * buffer to have made it to the inactive list, and we would need
	 * a separate wait queue to handle that.
	 */
	if (ret == 0)
2059
		i915_gem_retire_requests_ring(dev, ring);
2060 2061 2062 2063

	return ret;
}

2064 2065 2066 2067 2068
/**
 * Waits for a sequence number to be signaled, and cleans up the
 * request and object lists appropriately for that event.
 */
static int
2069
i915_wait_request(struct drm_device *dev, uint32_t seqno,
2070
		  struct intel_ring_buffer *ring)
2071
{
2072
	return i915_do_wait_request(dev, seqno, 1, ring);
2073 2074
}

2075
static void
2076 2077 2078 2079 2080
i915_gem_flush_ring(struct drm_device *dev,
		    struct intel_ring_buffer *ring,
		    uint32_t invalidate_domains,
		    uint32_t flush_domains)
{
2081
	ring->flush(ring, invalidate_domains, flush_domains);
2082 2083 2084
	i915_gem_process_flushing_list(dev, flush_domains, ring);
}

2085 2086 2087
static void
i915_gem_flush(struct drm_device *dev,
	       uint32_t invalidate_domains,
2088 2089
	       uint32_t flush_domains,
	       uint32_t flush_rings)
2090 2091
{
	drm_i915_private_t *dev_priv = dev->dev_private;
2092

2093
	if (flush_domains & I915_GEM_DOMAIN_CPU)
2094
		intel_gtt_chipset_flush();
2095

2096 2097
	if ((flush_domains | invalidate_domains) & I915_GEM_GPU_DOMAINS) {
		if (flush_rings & RING_RENDER)
2098
			i915_gem_flush_ring(dev, &dev_priv->render_ring,
2099 2100
					    invalidate_domains, flush_domains);
		if (flush_rings & RING_BSD)
2101
			i915_gem_flush_ring(dev, &dev_priv->bsd_ring,
2102
					    invalidate_domains, flush_domains);
2103
		if (flush_rings & RING_BLT)
2104
			i915_gem_flush_ring(dev, &dev_priv->blt_ring,
2105
					    invalidate_domains, flush_domains);
2106
	}
2107 2108
}

2109 2110 2111 2112 2113
/**
 * Ensures that all rendering to the object has completed and the object is
 * safe to unbind from the GTT or access from the CPU.
 */
static int
2114
i915_gem_object_wait_rendering(struct drm_i915_gem_object *obj,
2115
			       bool interruptible)
2116
{
2117
	struct drm_device *dev = obj->base.dev;
2118 2119
	int ret;

2120 2121
	/* This function only exists to support waiting for existing rendering,
	 * not for emitting required flushes.
2122
	 */
2123
	BUG_ON((obj->base.write_domain & I915_GEM_GPU_DOMAINS) != 0);
2124 2125 2126 2127

	/* If there is rendering queued on the buffer being evicted, wait for
	 * it.
	 */
2128
	if (obj->active) {
2129
		ret = i915_do_wait_request(dev,
2130
					   obj->last_rendering_seqno,
2131
					   interruptible,
2132
					   obj->ring);
2133
		if (ret)
2134 2135 2136 2137 2138 2139 2140 2141 2142
			return ret;
	}

	return 0;
}

/**
 * Unbinds an object from the GTT aperture.
 */
2143
int
2144
i915_gem_object_unbind(struct drm_i915_gem_object *obj)
2145 2146 2147
{
	int ret = 0;

2148
	if (obj->gtt_space == NULL)
2149 2150
		return 0;

2151
	if (obj->pin_count != 0) {
2152 2153 2154 2155
		DRM_ERROR("Attempting to unbind pinned buffer\n");
		return -EINVAL;
	}

2156 2157 2158
	/* blow away mappings if mapped through GTT */
	i915_gem_release_mmap(obj);

2159 2160 2161 2162 2163 2164
	/* Move the object to the CPU domain to ensure that
	 * any possible CPU writes while it's not in the GTT
	 * are flushed when we go to remap it. This will
	 * also ensure that all pending GPU writes are finished
	 * before we unbind.
	 */
2165
	ret = i915_gem_object_set_to_cpu_domain(obj, 1);
2166
	if (ret == -ERESTARTSYS)
2167
		return ret;
2168 2169 2170 2171
	/* Continue on if we fail due to EIO, the GPU is hung so we
	 * should be safe and we need to cleanup or else we might
	 * cause memory corruption through use-after-free.
	 */
2172 2173
	if (ret) {
		i915_gem_clflush_object(obj);
2174
		obj->base.read_domains = obj->base.write_domain = I915_GEM_DOMAIN_CPU;
2175
	}
2176

2177
	/* release the fence reg _after_ flushing */
2178
	if (obj->fence_reg != I915_FENCE_REG_NONE)
2179 2180
		i915_gem_clear_fence_reg(obj);

2181
	i915_gem_gtt_unbind_object(obj);
2182
	i915_gem_object_put_pages_gtt(obj);
2183

2184
	list_del_init(&obj->gtt_list);
2185
	list_del_init(&obj->mm_list);
2186
	/* Avoid an unnecessary call to unbind on rebind. */
2187
	obj->map_and_fenceable = true;
2188

2189 2190 2191
	drm_mm_put_block(obj->gtt_space);
	obj->gtt_space = NULL;
	obj->gtt_offset = 0;
2192

2193
	if (i915_gem_object_is_purgeable(obj))
2194 2195
		i915_gem_object_truncate(obj);

C
Chris Wilson 已提交
2196 2197
	trace_i915_gem_object_unbind(obj);

2198
	return ret;
2199 2200
}

2201 2202 2203
static int i915_ring_idle(struct drm_device *dev,
			  struct intel_ring_buffer *ring)
{
2204
	if (list_empty(&ring->gpu_write_list) && list_empty(&ring->active_list))
2205 2206
		return 0;

2207
	i915_gem_flush_ring(dev, ring,
2208 2209 2210 2211 2212 2213
			    I915_GEM_GPU_DOMAINS, I915_GEM_GPU_DOMAINS);
	return i915_wait_request(dev,
				 i915_gem_next_request_seqno(dev, ring),
				 ring);
}

2214
int
2215 2216 2217 2218
i915_gpu_idle(struct drm_device *dev)
{
	drm_i915_private_t *dev_priv = dev->dev_private;
	bool lists_empty;
2219
	int ret;
2220

2221
	lists_empty = (list_empty(&dev_priv->mm.flushing_list) &&
2222
		       list_empty(&dev_priv->mm.active_list));
2223 2224 2225 2226
	if (lists_empty)
		return 0;

	/* Flush everything onto the inactive list. */
2227
	ret = i915_ring_idle(dev, &dev_priv->render_ring);
2228 2229
	if (ret)
		return ret;
2230

2231 2232 2233
	ret = i915_ring_idle(dev, &dev_priv->bsd_ring);
	if (ret)
		return ret;
2234

2235 2236 2237
	ret = i915_ring_idle(dev, &dev_priv->blt_ring);
	if (ret)
		return ret;
2238

2239
	return 0;
2240 2241
}

2242 2243
static int sandybridge_write_fence_reg(struct drm_i915_gem_object *obj,
				       struct intel_ring_buffer *pipelined)
2244
{
2245
	struct drm_device *dev = obj->base.dev;
2246
	drm_i915_private_t *dev_priv = dev->dev_private;
2247 2248
	u32 size = obj->gtt_space->size;
	int regnum = obj->fence_reg;
2249 2250
	uint64_t val;

2251
	val = (uint64_t)((obj->gtt_offset + size - 4096) &
2252
			 0xfffff000) << 32;
2253 2254
	val |= obj->gtt_offset & 0xfffff000;
	val |= (uint64_t)((obj->stride / 128) - 1) <<
2255 2256
		SANDYBRIDGE_FENCE_PITCH_SHIFT;

2257
	if (obj->tiling_mode == I915_TILING_Y)
2258 2259 2260
		val |= 1 << I965_FENCE_TILING_Y_SHIFT;
	val |= I965_FENCE_REG_VALID;

2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276
	if (pipelined) {
		int ret = intel_ring_begin(pipelined, 6);
		if (ret)
			return ret;

		intel_ring_emit(pipelined, MI_NOOP);
		intel_ring_emit(pipelined, MI_LOAD_REGISTER_IMM(2));
		intel_ring_emit(pipelined, FENCE_REG_SANDYBRIDGE_0 + regnum*8);
		intel_ring_emit(pipelined, (u32)val);
		intel_ring_emit(pipelined, FENCE_REG_SANDYBRIDGE_0 + regnum*8 + 4);
		intel_ring_emit(pipelined, (u32)(val >> 32));
		intel_ring_advance(pipelined);
	} else
		I915_WRITE64(FENCE_REG_SANDYBRIDGE_0 + regnum * 8, val);

	return 0;
2277 2278
}

2279 2280
static int i965_write_fence_reg(struct drm_i915_gem_object *obj,
				struct intel_ring_buffer *pipelined)
2281
{
2282
	struct drm_device *dev = obj->base.dev;
2283
	drm_i915_private_t *dev_priv = dev->dev_private;
2284 2285
	u32 size = obj->gtt_space->size;
	int regnum = obj->fence_reg;
2286 2287
	uint64_t val;

2288
	val = (uint64_t)((obj->gtt_offset + size - 4096) &
2289
		    0xfffff000) << 32;
2290 2291 2292
	val |= obj->gtt_offset & 0xfffff000;
	val |= ((obj->stride / 128) - 1) << I965_FENCE_PITCH_SHIFT;
	if (obj->tiling_mode == I915_TILING_Y)
2293 2294 2295
		val |= 1 << I965_FENCE_TILING_Y_SHIFT;
	val |= I965_FENCE_REG_VALID;

2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311
	if (pipelined) {
		int ret = intel_ring_begin(pipelined, 6);
		if (ret)
			return ret;

		intel_ring_emit(pipelined, MI_NOOP);
		intel_ring_emit(pipelined, MI_LOAD_REGISTER_IMM(2));
		intel_ring_emit(pipelined, FENCE_REG_965_0 + regnum*8);
		intel_ring_emit(pipelined, (u32)val);
		intel_ring_emit(pipelined, FENCE_REG_965_0 + regnum*8 + 4);
		intel_ring_emit(pipelined, (u32)(val >> 32));
		intel_ring_advance(pipelined);
	} else
		I915_WRITE64(FENCE_REG_965_0 + regnum * 8, val);

	return 0;
2312 2313
}

2314 2315
static int i915_write_fence_reg(struct drm_i915_gem_object *obj,
				struct intel_ring_buffer *pipelined)
2316
{
2317
	struct drm_device *dev = obj->base.dev;
2318
	drm_i915_private_t *dev_priv = dev->dev_private;
2319
	u32 size = obj->gtt_space->size;
2320
	u32 fence_reg, val, pitch_val;
2321
	int tile_width;
2322

2323 2324 2325 2326 2327 2328
	if (WARN((obj->gtt_offset & ~I915_FENCE_START_MASK) ||
		 (size & -size) != size ||
		 (obj->gtt_offset & (size - 1)),
		 "object 0x%08x [fenceable? %d] not 1M or pot-size (0x%08x) aligned\n",
		 obj->gtt_offset, obj->map_and_fenceable, size))
		return -EINVAL;
2329

2330
	if (obj->tiling_mode == I915_TILING_Y && HAS_128_BYTE_Y_TILING(dev))
2331
		tile_width = 128;
2332
	else
2333 2334 2335
		tile_width = 512;

	/* Note: pitch better be a power of two tile widths */
2336
	pitch_val = obj->stride / tile_width;
2337
	pitch_val = ffs(pitch_val) - 1;
2338

2339 2340
	val = obj->gtt_offset;
	if (obj->tiling_mode == I915_TILING_Y)
2341
		val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2342
	val |= I915_FENCE_SIZE_BITS(size);
2343 2344 2345
	val |= pitch_val << I830_FENCE_PITCH_SHIFT;
	val |= I830_FENCE_REG_VALID;

2346
	fence_reg = obj->fence_reg;
2347 2348
	if (fence_reg < 8)
		fence_reg = FENCE_REG_830_0 + fence_reg * 4;
2349
	else
2350
		fence_reg = FENCE_REG_945_8 + (fence_reg - 8) * 4;
2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365

	if (pipelined) {
		int ret = intel_ring_begin(pipelined, 4);
		if (ret)
			return ret;

		intel_ring_emit(pipelined, MI_NOOP);
		intel_ring_emit(pipelined, MI_LOAD_REGISTER_IMM(1));
		intel_ring_emit(pipelined, fence_reg);
		intel_ring_emit(pipelined, val);
		intel_ring_advance(pipelined);
	} else
		I915_WRITE(fence_reg, val);

	return 0;
2366 2367
}

2368 2369
static int i830_write_fence_reg(struct drm_i915_gem_object *obj,
				struct intel_ring_buffer *pipelined)
2370
{
2371
	struct drm_device *dev = obj->base.dev;
2372
	drm_i915_private_t *dev_priv = dev->dev_private;
2373 2374
	u32 size = obj->gtt_space->size;
	int regnum = obj->fence_reg;
2375 2376 2377
	uint32_t val;
	uint32_t pitch_val;

2378 2379 2380 2381 2382 2383
	if (WARN((obj->gtt_offset & ~I830_FENCE_START_MASK) ||
		 (size & -size) != size ||
		 (obj->gtt_offset & (size - 1)),
		 "object 0x%08x not 512K or pot-size 0x%08x aligned\n",
		 obj->gtt_offset, size))
		return -EINVAL;
2384

2385
	pitch_val = obj->stride / 128;
2386 2387
	pitch_val = ffs(pitch_val) - 1;

2388 2389
	val = obj->gtt_offset;
	if (obj->tiling_mode == I915_TILING_Y)
2390
		val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2391
	val |= I830_FENCE_SIZE_BITS(size);
2392 2393 2394
	val |= pitch_val << I830_FENCE_PITCH_SHIFT;
	val |= I830_FENCE_REG_VALID;

2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408
	if (pipelined) {
		int ret = intel_ring_begin(pipelined, 4);
		if (ret)
			return ret;

		intel_ring_emit(pipelined, MI_NOOP);
		intel_ring_emit(pipelined, MI_LOAD_REGISTER_IMM(1));
		intel_ring_emit(pipelined, FENCE_REG_830_0 + regnum*4);
		intel_ring_emit(pipelined, val);
		intel_ring_advance(pipelined);
	} else
		I915_WRITE(FENCE_REG_830_0 + regnum * 4, val);

	return 0;
2409 2410
}

2411 2412
static int i915_find_fence_reg(struct drm_device *dev,
			       bool interruptible)
2413 2414
{
	struct drm_i915_private *dev_priv = dev->dev_private;
2415
	struct drm_i915_fence_reg *reg;
2416
	struct drm_i915_gem_object *obj = NULL;
2417 2418 2419 2420 2421 2422 2423 2424 2425
	int i, avail, ret;

	/* First try to find a free reg */
	avail = 0;
	for (i = dev_priv->fence_reg_start; i < dev_priv->num_fence_regs; i++) {
		reg = &dev_priv->fence_regs[i];
		if (!reg->obj)
			return i;

2426 2427
		if (!reg->obj->pin_count)
			avail++;
2428 2429 2430 2431 2432 2433
	}

	if (avail == 0)
		return -ENOSPC;

	/* None available, try to steal one or wait for a user to finish */
2434
	avail = I915_FENCE_REG_NONE;
2435 2436
	list_for_each_entry(reg, &dev_priv->mm.fence_list,
			    lru_list) {
2437 2438
		obj = reg->obj;
		if (obj->pin_count)
2439 2440 2441
			continue;

		/* found one! */
2442
		avail = obj->fence_reg;
2443 2444 2445
		break;
	}

2446
	BUG_ON(avail == I915_FENCE_REG_NONE);
2447 2448 2449 2450 2451

	/* We only have a reference on obj from the active list. put_fence_reg
	 * might drop that one, causing a use-after-free in it. So hold a
	 * private reference to obj like the other callers of put_fence_reg
	 * (set_tiling ioctl) do. */
2452 2453 2454
	drm_gem_object_reference(&obj->base);
	ret = i915_gem_object_put_fence_reg(obj, interruptible);
	drm_gem_object_unreference(&obj->base);
2455 2456 2457
	if (ret != 0)
		return ret;

2458
	return avail;
2459 2460
}

2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473
/**
 * i915_gem_object_get_fence_reg - set up a fence reg for an object
 * @obj: object to map through a fence reg
 *
 * When mapping objects through the GTT, userspace wants to be able to write
 * to them without having to worry about swizzling if the object is tiled.
 *
 * This function walks the fence regs looking for a free one for @obj,
 * stealing one if it can't find any.
 *
 * It then sets up the reg based on the object's properties: address, pitch
 * and tiling format.
 */
2474
int
2475
i915_gem_object_get_fence_reg(struct drm_i915_gem_object *obj,
2476
			      bool interruptible)
2477
{
2478
	struct drm_device *dev = obj->base.dev;
J
Jesse Barnes 已提交
2479
	struct drm_i915_private *dev_priv = dev->dev_private;
2480
	struct drm_i915_fence_reg *reg = NULL;
2481
	struct intel_ring_buffer *pipelined = NULL;
2482
	int ret;
2483

2484
	/* Just update our place in the LRU if our fence is getting used. */
2485 2486
	if (obj->fence_reg != I915_FENCE_REG_NONE) {
		reg = &dev_priv->fence_regs[obj->fence_reg];
2487
		list_move_tail(&reg->lru_list, &dev_priv->mm.fence_list);
2488 2489 2490
		return 0;
	}

2491
	switch (obj->tiling_mode) {
2492 2493 2494 2495
	case I915_TILING_NONE:
		WARN(1, "allocating a fence for non-tiled object?\n");
		break;
	case I915_TILING_X:
2496
		if (!obj->stride)
2497
			return -EINVAL;
2498
		WARN((obj->stride & (512 - 1)),
2499
		     "object 0x%08x is X tiled but has non-512B pitch\n",
2500
		     obj->gtt_offset);
2501 2502
		break;
	case I915_TILING_Y:
2503
		if (!obj->stride)
2504
			return -EINVAL;
2505
		WARN((obj->stride & (128 - 1)),
2506
		     "object 0x%08x is Y tiled but has non-128B pitch\n",
2507
		     obj->gtt_offset);
2508 2509 2510
		break;
	}

2511
	ret = i915_find_fence_reg(dev, interruptible);
2512 2513
	if (ret < 0)
		return ret;
2514

2515 2516
	obj->fence_reg = ret;
	reg = &dev_priv->fence_regs[obj->fence_reg];
2517
	list_add_tail(&reg->lru_list, &dev_priv->mm.fence_list);
2518

2519 2520
	reg->obj = obj;

2521 2522
	switch (INTEL_INFO(dev)->gen) {
	case 6:
2523
		ret = sandybridge_write_fence_reg(obj, pipelined);
2524 2525 2526
		break;
	case 5:
	case 4:
2527
		ret = i965_write_fence_reg(obj, pipelined);
2528 2529
		break;
	case 3:
2530
		ret = i915_write_fence_reg(obj, pipelined);
2531 2532
		break;
	case 2:
2533
		ret = i830_write_fence_reg(obj, pipelined);
2534 2535
		break;
	}
2536

2537
	trace_i915_gem_object_get_fence(obj,
2538 2539
					obj->fence_reg,
					obj->tiling_mode);
2540
	return ret;
2541 2542 2543 2544 2545 2546 2547
}

/**
 * i915_gem_clear_fence_reg - clear out fence register info
 * @obj: object to clear
 *
 * Zeroes out the fence register itself and clears out the associated
2548
 * data structures in dev_priv and obj.
2549 2550
 */
static void
2551
i915_gem_clear_fence_reg(struct drm_i915_gem_object *obj)
2552
{
2553
	struct drm_device *dev = obj->base.dev;
J
Jesse Barnes 已提交
2554
	drm_i915_private_t *dev_priv = dev->dev_private;
2555
	struct drm_i915_fence_reg *reg = &dev_priv->fence_regs[obj->fence_reg];
2556
	uint32_t fence_reg;
2557

2558 2559
	switch (INTEL_INFO(dev)->gen) {
	case 6:
2560
		I915_WRITE64(FENCE_REG_SANDYBRIDGE_0 +
2561
			     (obj->fence_reg * 8), 0);
2562 2563 2564
		break;
	case 5:
	case 4:
2565
		I915_WRITE64(FENCE_REG_965_0 + (obj->fence_reg * 8), 0);
2566 2567
		break;
	case 3:
2568 2569
		if (obj->fence_reg >= 8)
			fence_reg = FENCE_REG_945_8 + (obj->fence_reg - 8) * 4;
2570
		else
2571
	case 2:
2572
			fence_reg = FENCE_REG_830_0 + obj->fence_reg * 4;
2573 2574

		I915_WRITE(fence_reg, 0);
2575
		break;
2576
	}
2577

2578
	reg->obj = NULL;
2579
	obj->fence_reg = I915_FENCE_REG_NONE;
2580
	list_del_init(&reg->lru_list);
2581 2582
}

2583 2584 2585 2586
/**
 * i915_gem_object_put_fence_reg - waits on outstanding fenced access
 * to the buffer to finish, and then resets the fence register.
 * @obj: tiled object holding a fence register.
2587
 * @bool: whether the wait upon the fence is interruptible
2588 2589
 *
 * Zeroes out the fence register itself and clears out the associated
2590
 * data structures in dev_priv and obj.
2591 2592
 */
int
2593
i915_gem_object_put_fence_reg(struct drm_i915_gem_object *obj,
2594
			      bool interruptible)
2595
{
2596
	struct drm_device *dev = obj->base.dev;
2597
	int ret;
2598

2599
	if (obj->fence_reg == I915_FENCE_REG_NONE)
2600 2601
		return 0;

2602 2603 2604 2605 2606 2607
	/* If we've changed tiling, GTT-mappings of the object
	 * need to re-fault to ensure that the correct fence register
	 * setup is in place.
	 */
	i915_gem_release_mmap(obj);

2608 2609 2610 2611
	/* On the i915, GPU access to tiled buffers is via a fence,
	 * therefore we must wait for any outstanding access to complete
	 * before clearing the fence.
	 */
2612
	if (obj->fenced_gpu_access) {
2613
		ret = i915_gem_object_flush_gpu_write_domain(obj, NULL);
2614
		if (ret)
2615 2616
			return ret;

2617 2618 2619 2620 2621 2622 2623 2624
		obj->fenced_gpu_access = false;
	}

	if (obj->last_fenced_seqno) {
		ret = i915_do_wait_request(dev,
					   obj->last_fenced_seqno,
					   interruptible,
					   obj->last_fenced_ring);
2625
		if (ret)
2626
			return ret;
C
Chris Wilson 已提交
2627

2628
		obj->last_fenced_seqno = false;
2629 2630
	}

2631
	i915_gem_object_flush_gtt_write_domain(obj);
2632
	i915_gem_clear_fence_reg(obj);
2633 2634 2635 2636

	return 0;
}

2637 2638 2639 2640
/**
 * Finds free space in the GTT aperture and binds the object there.
 */
static int
2641
i915_gem_object_bind_to_gtt(struct drm_i915_gem_object *obj,
2642
			    unsigned alignment,
2643
			    bool map_and_fenceable)
2644
{
2645
	struct drm_device *dev = obj->base.dev;
2646 2647
	drm_i915_private_t *dev_priv = dev->dev_private;
	struct drm_mm_node *free_space;
2648
	gfp_t gfpmask = __GFP_NORETRY | __GFP_NOWARN;
2649
	u32 size, fence_size, fence_alignment, unfenced_alignment;
2650
	bool mappable, fenceable;
2651
	int ret;
2652

2653
	if (obj->madv != I915_MADV_WILLNEED) {
2654 2655 2656 2657
		DRM_ERROR("Attempting to bind a purgeable object\n");
		return -EINVAL;
	}

2658 2659 2660
	fence_size = i915_gem_get_gtt_size(obj);
	fence_alignment = i915_gem_get_gtt_alignment(obj);
	unfenced_alignment = i915_gem_get_unfenced_gtt_alignment(obj);
2661

2662
	if (alignment == 0)
2663 2664
		alignment = map_and_fenceable ? fence_alignment :
						unfenced_alignment;
2665
	if (map_and_fenceable && alignment & (fence_alignment - 1)) {
2666 2667 2668 2669
		DRM_ERROR("Invalid object alignment requested %u\n", alignment);
		return -EINVAL;
	}

2670
	size = map_and_fenceable ? fence_size : obj->base.size;
2671

2672 2673 2674
	/* If the object is bigger than the entire aperture, reject it early
	 * before evicting everything in a vain attempt to find space.
	 */
2675
	if (obj->base.size >
2676
	    (map_and_fenceable ? dev_priv->mm.gtt_mappable_end : dev_priv->mm.gtt_total)) {
2677 2678 2679 2680
		DRM_ERROR("Attempting to bind an object larger than the aperture\n");
		return -E2BIG;
	}

2681
 search_free:
2682
	if (map_and_fenceable)
2683 2684
		free_space =
			drm_mm_search_free_in_range(&dev_priv->mm.gtt_space,
2685
						    size, alignment, 0,
2686 2687 2688 2689
						    dev_priv->mm.gtt_mappable_end,
						    0);
	else
		free_space = drm_mm_search_free(&dev_priv->mm.gtt_space,
2690
						size, alignment, 0);
2691 2692

	if (free_space != NULL) {
2693
		if (map_and_fenceable)
2694
			obj->gtt_space =
2695
				drm_mm_get_block_range_generic(free_space,
2696
							       size, alignment, 0,
2697 2698 2699
							       dev_priv->mm.gtt_mappable_end,
							       0);
		else
2700
			obj->gtt_space =
2701
				drm_mm_get_block(free_space, size, alignment);
2702
	}
2703
	if (obj->gtt_space == NULL) {
2704 2705 2706
		/* If the gtt is empty and we're still having trouble
		 * fitting our object in, we're out of memory.
		 */
2707 2708
		ret = i915_gem_evict_something(dev, size, alignment,
					       map_and_fenceable);
2709
		if (ret)
2710
			return ret;
2711

2712 2713 2714
		goto search_free;
	}

2715
	ret = i915_gem_object_get_pages_gtt(obj, gfpmask);
2716
	if (ret) {
2717 2718
		drm_mm_put_block(obj->gtt_space);
		obj->gtt_space = NULL;
2719 2720 2721

		if (ret == -ENOMEM) {
			/* first try to clear up some space from the GTT */
2722
			ret = i915_gem_evict_something(dev, size,
2723 2724
						       alignment,
						       map_and_fenceable);
2725 2726
			if (ret) {
				/* now try to shrink everyone else */
2727 2728 2729
				if (gfpmask) {
					gfpmask = 0;
					goto search_free;
2730 2731 2732 2733 2734 2735 2736 2737
				}

				return ret;
			}

			goto search_free;
		}

2738 2739 2740
		return ret;
	}

2741 2742
	ret = i915_gem_gtt_bind_object(obj);
	if (ret) {
2743
		i915_gem_object_put_pages_gtt(obj);
2744 2745
		drm_mm_put_block(obj->gtt_space);
		obj->gtt_space = NULL;
2746

2747
		ret = i915_gem_evict_something(dev, size,
2748
					       alignment, map_and_fenceable);
2749
		if (ret)
2750 2751 2752
			return ret;

		goto search_free;
2753 2754
	}

2755
	list_add_tail(&obj->gtt_list, &dev_priv->mm.gtt_list);
2756
	list_add_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
2757

2758 2759 2760 2761
	/* Assert that the object is not currently in any GPU domain. As it
	 * wasn't in the GTT, there shouldn't be any way it could have been in
	 * a GPU cache
	 */
2762 2763
	BUG_ON(obj->base.read_domains & I915_GEM_GPU_DOMAINS);
	BUG_ON(obj->base.write_domain & I915_GEM_GPU_DOMAINS);
2764

2765
	obj->gtt_offset = obj->gtt_space->start;
C
Chris Wilson 已提交
2766

2767
	fenceable =
2768 2769
		obj->gtt_space->size == fence_size &&
		(obj->gtt_space->start & (fence_alignment -1)) == 0;
2770

2771
	mappable =
2772
		obj->gtt_offset + obj->base.size <= dev_priv->mm.gtt_mappable_end;
2773

2774
	obj->map_and_fenceable = mappable && fenceable;
2775

2776
	trace_i915_gem_object_bind(obj, obj->gtt_offset, map_and_fenceable);
2777 2778 2779 2780
	return 0;
}

void
2781
i915_gem_clflush_object(struct drm_i915_gem_object *obj)
2782 2783 2784 2785 2786
{
	/* If we don't have a page list set up, then we're not pinned
	 * to GPU, and we can ignore the cache flush because it'll happen
	 * again at bind time.
	 */
2787
	if (obj->pages == NULL)
2788 2789
		return;

C
Chris Wilson 已提交
2790
	trace_i915_gem_object_clflush(obj);
2791

2792
	drm_clflush_pages(obj->pages, obj->base.size / PAGE_SIZE);
2793 2794
}

2795
/** Flushes any GPU write domain for the object if it's dirty. */
2796
static int
2797
i915_gem_object_flush_gpu_write_domain(struct drm_i915_gem_object *obj,
2798
				       struct intel_ring_buffer *pipelined)
2799
{
2800
	struct drm_device *dev = obj->base.dev;
2801

2802
	if ((obj->base.write_domain & I915_GEM_GPU_DOMAINS) == 0)
2803
		return 0;
2804 2805

	/* Queue the GPU write cache flushing we need. */
2806 2807
	i915_gem_flush_ring(dev, obj->ring, 0, obj->base.write_domain);
	BUG_ON(obj->base.write_domain);
C
Chris Wilson 已提交
2808

2809
	if (pipelined && pipelined == obj->ring)
2810 2811
		return 0;

2812
	return i915_gem_object_wait_rendering(obj, true);
2813 2814 2815 2816
}

/** Flushes the GTT write domain for the object if it's dirty. */
static void
2817
i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj)
2818
{
C
Chris Wilson 已提交
2819 2820
	uint32_t old_write_domain;

2821
	if (obj->base.write_domain != I915_GEM_DOMAIN_GTT)
2822 2823 2824 2825 2826 2827
		return;

	/* No actual flushing is required for the GTT write domain.   Writes
	 * to it immediately go to main memory as far as we know, so there's
	 * no chipset flush.  It also doesn't land in render cache.
	 */
2828 2829
	i915_gem_release_mmap(obj);

2830 2831
	old_write_domain = obj->base.write_domain;
	obj->base.write_domain = 0;
C
Chris Wilson 已提交
2832 2833

	trace_i915_gem_object_change_domain(obj,
2834
					    obj->base.read_domains,
C
Chris Wilson 已提交
2835
					    old_write_domain);
2836 2837 2838 2839
}

/** Flushes the CPU write domain for the object if it's dirty. */
static void
2840
i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj)
2841
{
C
Chris Wilson 已提交
2842
	uint32_t old_write_domain;
2843

2844
	if (obj->base.write_domain != I915_GEM_DOMAIN_CPU)
2845 2846 2847
		return;

	i915_gem_clflush_object(obj);
2848
	intel_gtt_chipset_flush();
2849 2850
	old_write_domain = obj->base.write_domain;
	obj->base.write_domain = 0;
C
Chris Wilson 已提交
2851 2852

	trace_i915_gem_object_change_domain(obj,
2853
					    obj->base.read_domains,
C
Chris Wilson 已提交
2854
					    old_write_domain);
2855 2856
}

2857 2858 2859 2860 2861 2862
/**
 * Moves a single object to the GTT read, and possibly write domain.
 *
 * This function returns when the move is complete, including waiting on
 * flushes to occur.
 */
J
Jesse Barnes 已提交
2863
int
2864
i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, bool write)
2865
{
C
Chris Wilson 已提交
2866
	uint32_t old_write_domain, old_read_domains;
2867
	int ret;
2868

2869
	/* Not valid to be called on unbound objects. */
2870
	if (obj->gtt_space == NULL)
2871 2872
		return -EINVAL;

2873
	ret = i915_gem_object_flush_gpu_write_domain(obj, NULL);
2874 2875 2876
	if (ret != 0)
		return ret;

2877
	i915_gem_object_flush_cpu_write_domain(obj);
C
Chris Wilson 已提交
2878

2879
	if (write) {
2880
		ret = i915_gem_object_wait_rendering(obj, true);
2881 2882 2883
		if (ret)
			return ret;
	}
2884

2885 2886
	old_write_domain = obj->base.write_domain;
	old_read_domains = obj->base.read_domains;
C
Chris Wilson 已提交
2887

2888 2889 2890
	/* It should now be out of any other write domains, and we can update
	 * the domain values for our changes.
	 */
2891 2892
	BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
	obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
2893
	if (write) {
2894 2895 2896
		obj->base.read_domains = I915_GEM_DOMAIN_GTT;
		obj->base.write_domain = I915_GEM_DOMAIN_GTT;
		obj->dirty = 1;
2897 2898
	}

C
Chris Wilson 已提交
2899 2900 2901 2902
	trace_i915_gem_object_change_domain(obj,
					    old_read_domains,
					    old_write_domain);

2903 2904 2905
	return 0;
}

2906 2907 2908 2909 2910
/*
 * Prepare buffer for display plane. Use uninterruptible for possible flush
 * wait, as in modesetting process we're not supposed to be interrupted.
 */
int
2911
i915_gem_object_set_to_display_plane(struct drm_i915_gem_object *obj,
2912
				     struct intel_ring_buffer *pipelined)
2913
{
2914
	uint32_t old_read_domains;
2915 2916 2917
	int ret;

	/* Not valid to be called on unbound objects. */
2918
	if (obj->gtt_space == NULL)
2919 2920
		return -EINVAL;

2921
	ret = i915_gem_object_flush_gpu_write_domain(obj, pipelined);
2922 2923
	if (ret)
		return ret;
2924

2925 2926 2927 2928
	/* Currently, we are always called from an non-interruptible context. */
	if (!pipelined) {
		ret = i915_gem_object_wait_rendering(obj, false);
		if (ret)
2929 2930 2931
			return ret;
	}

2932 2933
	i915_gem_object_flush_cpu_write_domain(obj);

2934 2935
	old_read_domains = obj->base.read_domains;
	obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
2936 2937 2938

	trace_i915_gem_object_change_domain(obj,
					    old_read_domains,
2939
					    obj->base.write_domain);
2940 2941 2942 2943

	return 0;
}

2944 2945 2946 2947 2948 2949 2950 2951
int
i915_gem_object_flush_gpu(struct drm_i915_gem_object *obj,
			  bool interruptible)
{
	if (!obj->active)
		return 0;

	if (obj->base.write_domain & I915_GEM_GPU_DOMAINS)
2952
		i915_gem_flush_ring(obj->base.dev, obj->ring,
2953 2954
				    0, obj->base.write_domain);

2955
	return i915_gem_object_wait_rendering(obj, interruptible);
2956 2957
}

2958 2959 2960 2961 2962 2963 2964
/**
 * Moves a single object to the CPU read, and possibly write domain.
 *
 * This function returns when the move is complete, including waiting on
 * flushes to occur.
 */
static int
2965
i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj, bool write)
2966
{
C
Chris Wilson 已提交
2967
	uint32_t old_write_domain, old_read_domains;
2968 2969
	int ret;

2970
	ret = i915_gem_object_flush_gpu_write_domain(obj, false);
2971 2972
	if (ret != 0)
		return ret;
2973

2974
	i915_gem_object_flush_gtt_write_domain(obj);
2975

2976 2977
	/* If we have a partially-valid cache of the object in the CPU,
	 * finish invalidating it and free the per-page flags.
2978
	 */
2979
	i915_gem_object_set_to_full_cpu_read_domain(obj);
2980

2981
	if (write) {
2982
		ret = i915_gem_object_wait_rendering(obj, true);
2983 2984 2985 2986
		if (ret)
			return ret;
	}

2987 2988
	old_write_domain = obj->base.write_domain;
	old_read_domains = obj->base.read_domains;
C
Chris Wilson 已提交
2989

2990
	/* Flush the CPU cache if it's still invalid. */
2991
	if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0) {
2992 2993
		i915_gem_clflush_object(obj);

2994
		obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
2995 2996 2997 2998 2999
	}

	/* It should now be out of any other write domains, and we can update
	 * the domain values for our changes.
	 */
3000
	BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
3001 3002 3003 3004 3005

	/* If we're writing through the CPU, then the GPU read domains will
	 * need to be invalidated at next use.
	 */
	if (write) {
3006 3007
		obj->base.read_domains = I915_GEM_DOMAIN_CPU;
		obj->base.write_domain = I915_GEM_DOMAIN_CPU;
3008
	}
3009

C
Chris Wilson 已提交
3010 3011 3012 3013
	trace_i915_gem_object_change_domain(obj,
					    old_read_domains,
					    old_write_domain);

3014 3015 3016
	return 0;
}

3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127
/*
 * Set the next domain for the specified object. This
 * may not actually perform the necessary flushing/invaliding though,
 * as that may want to be batched with other set_domain operations
 *
 * This is (we hope) the only really tricky part of gem. The goal
 * is fairly simple -- track which caches hold bits of the object
 * and make sure they remain coherent. A few concrete examples may
 * help to explain how it works. For shorthand, we use the notation
 * (read_domains, write_domain), e.g. (CPU, CPU) to indicate the
 * a pair of read and write domain masks.
 *
 * Case 1: the batch buffer
 *
 *	1. Allocated
 *	2. Written by CPU
 *	3. Mapped to GTT
 *	4. Read by GPU
 *	5. Unmapped from GTT
 *	6. Freed
 *
 *	Let's take these a step at a time
 *
 *	1. Allocated
 *		Pages allocated from the kernel may still have
 *		cache contents, so we set them to (CPU, CPU) always.
 *	2. Written by CPU (using pwrite)
 *		The pwrite function calls set_domain (CPU, CPU) and
 *		this function does nothing (as nothing changes)
 *	3. Mapped by GTT
 *		This function asserts that the object is not
 *		currently in any GPU-based read or write domains
 *	4. Read by GPU
 *		i915_gem_execbuffer calls set_domain (COMMAND, 0).
 *		As write_domain is zero, this function adds in the
 *		current read domains (CPU+COMMAND, 0).
 *		flush_domains is set to CPU.
 *		invalidate_domains is set to COMMAND
 *		clflush is run to get data out of the CPU caches
 *		then i915_dev_set_domain calls i915_gem_flush to
 *		emit an MI_FLUSH and drm_agp_chipset_flush
 *	5. Unmapped from GTT
 *		i915_gem_object_unbind calls set_domain (CPU, CPU)
 *		flush_domains and invalidate_domains end up both zero
 *		so no flushing/invalidating happens
 *	6. Freed
 *		yay, done
 *
 * Case 2: The shared render buffer
 *
 *	1. Allocated
 *	2. Mapped to GTT
 *	3. Read/written by GPU
 *	4. set_domain to (CPU,CPU)
 *	5. Read/written by CPU
 *	6. Read/written by GPU
 *
 *	1. Allocated
 *		Same as last example, (CPU, CPU)
 *	2. Mapped to GTT
 *		Nothing changes (assertions find that it is not in the GPU)
 *	3. Read/written by GPU
 *		execbuffer calls set_domain (RENDER, RENDER)
 *		flush_domains gets CPU
 *		invalidate_domains gets GPU
 *		clflush (obj)
 *		MI_FLUSH and drm_agp_chipset_flush
 *	4. set_domain (CPU, CPU)
 *		flush_domains gets GPU
 *		invalidate_domains gets CPU
 *		wait_rendering (obj) to make sure all drawing is complete.
 *		This will include an MI_FLUSH to get the data from GPU
 *		to memory
 *		clflush (obj) to invalidate the CPU cache
 *		Another MI_FLUSH in i915_gem_flush (eliminate this somehow?)
 *	5. Read/written by CPU
 *		cache lines are loaded and dirtied
 *	6. Read written by GPU
 *		Same as last GPU access
 *
 * Case 3: The constant buffer
 *
 *	1. Allocated
 *	2. Written by CPU
 *	3. Read by GPU
 *	4. Updated (written) by CPU again
 *	5. Read by GPU
 *
 *	1. Allocated
 *		(CPU, CPU)
 *	2. Written by CPU
 *		(CPU, CPU)
 *	3. Read by GPU
 *		(CPU+RENDER, 0)
 *		flush_domains = CPU
 *		invalidate_domains = RENDER
 *		clflush (obj)
 *		MI_FLUSH
 *		drm_agp_chipset_flush
 *	4. Updated (written) by CPU again
 *		(CPU, CPU)
 *		flush_domains = 0 (no previous write domain)
 *		invalidate_domains = 0 (no new read domains)
 *	5. Read by GPU
 *		(CPU+RENDER, 0)
 *		flush_domains = CPU
 *		invalidate_domains = RENDER
 *		clflush (obj)
 *		MI_FLUSH
 *		drm_agp_chipset_flush
 */
3128
static void
3129
i915_gem_object_set_to_gpu_domain(struct drm_i915_gem_object *obj,
3130 3131
				  struct intel_ring_buffer *ring,
				  struct change_domains *cd)
3132
{
3133
	uint32_t invalidate_domains = 0, flush_domains = 0;
3134

3135 3136 3137 3138
	/*
	 * If the object isn't moving to a new write domain,
	 * let the object stay in multiple read domains
	 */
3139 3140
	if (obj->base.pending_write_domain == 0)
		obj->base.pending_read_domains |= obj->base.read_domains;
3141 3142 3143 3144 3145 3146 3147

	/*
	 * Flush the current write domain if
	 * the new read domains don't match. Invalidate
	 * any read domains which differ from the old
	 * write domain
	 */
3148
	if (obj->base.write_domain &&
3149 3150 3151
	    (((obj->base.write_domain != obj->base.pending_read_domains ||
	       obj->ring != ring)) ||
	     (obj->fenced_gpu_access && !obj->pending_fenced_gpu_access))) {
3152
		flush_domains |= obj->base.write_domain;
3153
		invalidate_domains |=
3154
			obj->base.pending_read_domains & ~obj->base.write_domain;
3155 3156 3157 3158 3159
	}
	/*
	 * Invalidate any read caches which may have
	 * stale data. That is, any new read domains.
	 */
3160
	invalidate_domains |= obj->base.pending_read_domains & ~obj->base.read_domains;
3161
	if ((flush_domains | invalidate_domains) & I915_GEM_DOMAIN_CPU)
3162 3163
		i915_gem_clflush_object(obj);

3164 3165 3166 3167
	/* blow away mappings if mapped through GTT */
	if ((flush_domains | invalidate_domains) & I915_GEM_DOMAIN_GTT)
		i915_gem_release_mmap(obj);

3168 3169 3170 3171 3172 3173
	/* The actual obj->write_domain will be updated with
	 * pending_write_domain after we emit the accumulated flush for all
	 * of our domain changes in execbuffers (which clears objects'
	 * write_domains).  So if we have a current write domain that we
	 * aren't changing, set pending_write_domain to that.
	 */
3174 3175
	if (flush_domains == 0 && obj->base.pending_write_domain == 0)
		obj->base.pending_write_domain = obj->base.write_domain;
3176

3177 3178
	cd->invalidate_domains |= invalidate_domains;
	cd->flush_domains |= flush_domains;
3179
	if (flush_domains & I915_GEM_GPU_DOMAINS)
3180
		cd->flush_rings |= obj->ring->id;
3181
	if (invalidate_domains & I915_GEM_GPU_DOMAINS)
3182
		cd->flush_rings |= ring->id;
3183 3184 3185
}

/**
3186
 * Moves the object from a partially CPU read to a full one.
3187
 *
3188 3189
 * Note that this only resolves i915_gem_object_set_cpu_read_domain_range(),
 * and doesn't handle transitioning from !(read_domains & I915_GEM_DOMAIN_CPU).
3190
 */
3191
static void
3192
i915_gem_object_set_to_full_cpu_read_domain(struct drm_i915_gem_object *obj)
3193
{
3194
	if (!obj->page_cpu_valid)
3195 3196 3197 3198
		return;

	/* If we're partially in the CPU read domain, finish moving it in.
	 */
3199
	if (obj->base.read_domains & I915_GEM_DOMAIN_CPU) {
3200 3201
		int i;

3202 3203
		for (i = 0; i <= (obj->base.size - 1) / PAGE_SIZE; i++) {
			if (obj->page_cpu_valid[i])
3204
				continue;
3205
			drm_clflush_pages(obj->pages + i, 1);
3206 3207 3208 3209 3210 3211
		}
	}

	/* Free the page_cpu_valid mappings which are now stale, whether
	 * or not we've got I915_GEM_DOMAIN_CPU.
	 */
3212 3213
	kfree(obj->page_cpu_valid);
	obj->page_cpu_valid = NULL;
3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228
}

/**
 * Set the CPU read domain on a range of the object.
 *
 * The object ends up with I915_GEM_DOMAIN_CPU in its read flags although it's
 * not entirely valid.  The page_cpu_valid member of the object flags which
 * pages have been flushed, and will be respected by
 * i915_gem_object_set_to_cpu_domain() if it's called on to get a valid mapping
 * of the whole object.
 *
 * This function returns when the move is complete, including waiting on
 * flushes to occur.
 */
static int
3229
i915_gem_object_set_cpu_read_domain_range(struct drm_i915_gem_object *obj,
3230 3231
					  uint64_t offset, uint64_t size)
{
C
Chris Wilson 已提交
3232
	uint32_t old_read_domains;
3233
	int i, ret;
3234

3235
	if (offset == 0 && size == obj->base.size)
3236
		return i915_gem_object_set_to_cpu_domain(obj, 0);
3237

3238
	ret = i915_gem_object_flush_gpu_write_domain(obj, false);
3239
	if (ret != 0)
3240
		return ret;
3241 3242 3243
	i915_gem_object_flush_gtt_write_domain(obj);

	/* If we're already fully in the CPU read domain, we're done. */
3244 3245
	if (obj->page_cpu_valid == NULL &&
	    (obj->base.read_domains & I915_GEM_DOMAIN_CPU) != 0)
3246
		return 0;
3247

3248 3249 3250
	/* Otherwise, create/clear the per-page CPU read domain flag if we're
	 * newly adding I915_GEM_DOMAIN_CPU
	 */
3251 3252 3253 3254
	if (obj->page_cpu_valid == NULL) {
		obj->page_cpu_valid = kzalloc(obj->base.size / PAGE_SIZE,
					      GFP_KERNEL);
		if (obj->page_cpu_valid == NULL)
3255
			return -ENOMEM;
3256 3257
	} else if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0)
		memset(obj->page_cpu_valid, 0, obj->base.size / PAGE_SIZE);
3258 3259 3260 3261

	/* Flush the cache on any pages that are still invalid from the CPU's
	 * perspective.
	 */
3262 3263
	for (i = offset / PAGE_SIZE; i <= (offset + size - 1) / PAGE_SIZE;
	     i++) {
3264
		if (obj->page_cpu_valid[i])
3265 3266
			continue;

3267
		drm_clflush_pages(obj->pages + i, 1);
3268

3269
		obj->page_cpu_valid[i] = 1;
3270 3271
	}

3272 3273 3274
	/* It should now be out of any other write domains, and we can update
	 * the domain values for our changes.
	 */
3275
	BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
3276

3277 3278
	old_read_domains = obj->base.read_domains;
	obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
3279

C
Chris Wilson 已提交
3280 3281
	trace_i915_gem_object_change_domain(obj,
					    old_read_domains,
3282
					    obj->base.write_domain);
C
Chris Wilson 已提交
3283

3284 3285 3286 3287
	return 0;
}

static int
3288 3289 3290 3291
i915_gem_execbuffer_relocate_entry(struct drm_i915_gem_object *obj,
				   struct drm_file *file_priv,
				   struct drm_i915_gem_exec_object2 *entry,
				   struct drm_i915_gem_relocation_entry *reloc)
3292
{
3293
	struct drm_device *dev = obj->base.dev;
3294 3295 3296
	struct drm_gem_object *target_obj;
	uint32_t target_offset;
	int ret = -EINVAL;
3297

3298 3299 3300 3301
	target_obj = drm_gem_object_lookup(dev, file_priv,
					   reloc->target_handle);
	if (target_obj == NULL)
		return -ENOENT;
3302

3303
	target_offset = to_intel_bo(target_obj)->gtt_offset;
J
Jesse Barnes 已提交
3304

3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318
#if WATCH_RELOC
	DRM_INFO("%s: obj %p offset %08x target %d "
		 "read %08x write %08x gtt %08x "
		 "presumed %08x delta %08x\n",
		 __func__,
		 obj,
		 (int) reloc->offset,
		 (int) reloc->target_handle,
		 (int) reloc->read_domains,
		 (int) reloc->write_domain,
		 (int) target_offset,
		 (int) reloc->presumed_offset,
		 reloc->delta);
#endif
3319

3320 3321 3322 3323 3324 3325 3326 3327
	/* The target buffer should have appeared before us in the
	 * exec_object list, so it should have a GTT space bound by now.
	 */
	if (target_offset == 0) {
		DRM_ERROR("No GTT space found for object %d\n",
			  reloc->target_handle);
		goto err;
	}
3328

3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361
	/* Validate that the target is in a valid r/w GPU domain */
	if (reloc->write_domain & (reloc->write_domain - 1)) {
		DRM_ERROR("reloc with multiple write domains: "
			  "obj %p target %d offset %d "
			  "read %08x write %08x",
			  obj, reloc->target_handle,
			  (int) reloc->offset,
			  reloc->read_domains,
			  reloc->write_domain);
		goto err;
	}
	if (reloc->write_domain & I915_GEM_DOMAIN_CPU ||
	    reloc->read_domains & I915_GEM_DOMAIN_CPU) {
		DRM_ERROR("reloc with read/write CPU domains: "
			  "obj %p target %d offset %d "
			  "read %08x write %08x",
			  obj, reloc->target_handle,
			  (int) reloc->offset,
			  reloc->read_domains,
			  reloc->write_domain);
		goto err;
	}
	if (reloc->write_domain && target_obj->pending_write_domain &&
	    reloc->write_domain != target_obj->pending_write_domain) {
		DRM_ERROR("Write domain conflict: "
			  "obj %p target %d offset %d "
			  "new %08x old %08x\n",
			  obj, reloc->target_handle,
			  (int) reloc->offset,
			  reloc->write_domain,
			  target_obj->pending_write_domain);
		goto err;
	}
3362

3363 3364
	target_obj->pending_read_domains |= reloc->read_domains;
	target_obj->pending_write_domain |= reloc->write_domain;
3365

3366 3367 3368 3369 3370
	/* If the relocation already has the right value in it, no
	 * more work needs to be done.
	 */
	if (target_offset == reloc->presumed_offset)
		goto out;
3371

3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387
	/* Check that the relocation address is valid... */
	if (reloc->offset > obj->base.size - 4) {
		DRM_ERROR("Relocation beyond object bounds: "
			  "obj %p target %d offset %d size %d.\n",
			  obj, reloc->target_handle,
			  (int) reloc->offset,
			  (int) obj->base.size);
		goto err;
	}
	if (reloc->offset & 3) {
		DRM_ERROR("Relocation not 4-byte aligned: "
			  "obj %p target %d offset %d.\n",
			  obj, reloc->target_handle,
			  (int) reloc->offset);
		goto err;
	}
3388

3389 3390 3391 3392 3393 3394 3395 3396 3397
	/* and points to somewhere within the target object. */
	if (reloc->delta >= target_obj->size) {
		DRM_ERROR("Relocation beyond target object bounds: "
			  "obj %p target %d delta %d size %d.\n",
			  obj, reloc->target_handle,
			  (int) reloc->delta,
			  (int) target_obj->size);
		goto err;
	}
3398

3399 3400 3401 3402
	reloc->delta += target_offset;
	if (obj->base.write_domain == I915_GEM_DOMAIN_CPU) {
		uint32_t page_offset = reloc->offset & ~PAGE_MASK;
		char *vaddr;
3403

3404 3405 3406 3407 3408 3409 3410
		vaddr = kmap_atomic(obj->pages[reloc->offset >> PAGE_SHIFT]);
		*(uint32_t *)(vaddr + page_offset) = reloc->delta;
		kunmap_atomic(vaddr);
	} else {
		struct drm_i915_private *dev_priv = dev->dev_private;
		uint32_t __iomem *reloc_entry;
		void __iomem *reloc_page;
3411

3412
		ret = i915_gem_object_set_to_gtt_domain(obj, 1);
3413 3414
		if (ret)
			goto err;
3415

3416 3417 3418 3419 3420 3421 3422 3423 3424
		/* Map the page containing the relocation we're going to perform.  */
		reloc->offset += obj->gtt_offset;
		reloc_page = io_mapping_map_atomic_wc(dev_priv->mm.gtt_mapping,
						      reloc->offset & PAGE_MASK);
		reloc_entry = (uint32_t __iomem *)
			(reloc_page + (reloc->offset & ~PAGE_MASK));
		iowrite32(reloc->delta, reloc_entry);
		io_mapping_unmap_atomic(reloc_page);
	}
3425

3426 3427
	/* and update the user's relocation entry */
	reloc->presumed_offset = target_offset;
3428

3429 3430 3431 3432 3433 3434
out:
	ret = 0;
err:
	drm_gem_object_unreference(target_obj);
	return ret;
}
3435

3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455
static int
i915_gem_execbuffer_relocate_object(struct drm_i915_gem_object *obj,
				    struct drm_file *file_priv,
				    struct drm_i915_gem_exec_object2 *entry)
{
	struct drm_i915_gem_relocation_entry __user *user_relocs;
	int i, ret;

	user_relocs = (void __user *)(uintptr_t)entry->relocs_ptr;
	for (i = 0; i < entry->relocation_count; i++) {
		struct drm_i915_gem_relocation_entry reloc;

		if (__copy_from_user_inatomic(&reloc,
					      user_relocs+i,
					      sizeof(reloc)))
			return -EFAULT;

		ret = i915_gem_execbuffer_relocate_entry(obj, file_priv, entry, &reloc);
		if (ret)
			return ret;
3456

3457
		if (__copy_to_user_inatomic(&user_relocs[i].presumed_offset,
3458 3459 3460
					    &reloc.presumed_offset,
					    sizeof(reloc.presumed_offset)))
			return -EFAULT;
3461 3462
	}

3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480
	return 0;
}

static int
i915_gem_execbuffer_relocate_object_slow(struct drm_i915_gem_object *obj,
					 struct drm_file *file_priv,
					 struct drm_i915_gem_exec_object2 *entry,
					 struct drm_i915_gem_relocation_entry *relocs)
{
	int i, ret;

	for (i = 0; i < entry->relocation_count; i++) {
		ret = i915_gem_execbuffer_relocate_entry(obj, file_priv, entry, &relocs[i]);
		if (ret)
			return ret;
	}

	return 0;
3481 3482
}

3483
static int
3484 3485
i915_gem_execbuffer_relocate(struct drm_device *dev,
			     struct drm_file *file,
3486
			     struct drm_i915_gem_object **object_list,
3487 3488 3489 3490 3491 3492
			     struct drm_i915_gem_exec_object2 *exec_list,
			     int count)
{
	int i, ret;

	for (i = 0; i < count; i++) {
3493
		struct drm_i915_gem_object *obj = object_list[i];
3494 3495 3496 3497 3498 3499 3500 3501 3502
		obj->base.pending_read_domains = 0;
		obj->base.pending_write_domain = 0;
		ret = i915_gem_execbuffer_relocate_object(obj, file,
							  &exec_list[i]);
		if (ret)
			return ret;
	}

	return 0;
3503 3504
}

3505
static int
3506 3507
i915_gem_execbuffer_reserve(struct drm_device *dev,
			    struct drm_file *file,
3508
			    struct drm_i915_gem_object **object_list,
3509 3510
			    struct drm_i915_gem_exec_object2 *exec_list,
			    int count)
3511
{
3512
	int ret, i, retry;
3513

C
Chris Wilson 已提交
3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525
	/* Attempt to pin all of the buffers into the GTT.
	 * This is done in 3 phases:
	 *
	 * 1a. Unbind all objects that do not match the GTT constraints for
	 *     the execbuffer (fenceable, mappable, alignment etc).
	 * 1b. Increment pin count for already bound objects.
	 * 2.  Bind new objects.
	 * 3.  Decrement pin count.
	 *
	 * This avoid unnecessary unbinding of later objects in order to makr
	 * room for the earlier objects *unless* we need to defragment.
	 */
3526 3527
	retry = 0;
	do {
3528
		ret = 0;
C
Chris Wilson 已提交
3529 3530

		/* Unbind any ill-fitting objects or pin. */
3531
		for (i = 0; i < count; i++) {
3532
			struct drm_i915_gem_object *obj = object_list[i];
C
Chris Wilson 已提交
3533 3534 3535 3536 3537 3538 3539
			struct drm_i915_gem_exec_object2 *entry = &exec_list[i];
			bool need_fence, need_mappable;

			if (!obj->gtt_space)
				continue;

			need_fence =
3540 3541
				entry->flags & EXEC_OBJECT_NEEDS_FENCE &&
				obj->tiling_mode != I915_TILING_NONE;
C
Chris Wilson 已提交
3542
			need_mappable =
3543 3544
				entry->relocation_count ? true : need_fence;

C
Chris Wilson 已提交
3545 3546
			if ((entry->alignment && obj->gtt_offset & (entry->alignment - 1)) ||
			    (need_mappable && !obj->map_and_fenceable))
3547
				ret = i915_gem_object_unbind(obj);
C
Chris Wilson 已提交
3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574
			else
				ret = i915_gem_object_pin(obj,
							  entry->alignment,
							  need_mappable);
			if (ret) {
				count = i;
				goto err;
			}
		}

		/* Bind fresh objects */
		for (i = 0; i < count; i++) {
			struct drm_i915_gem_exec_object2 *entry = &exec_list[i];
			struct drm_i915_gem_object *obj = object_list[i];
			bool need_fence;

			need_fence =
				entry->flags & EXEC_OBJECT_NEEDS_FENCE &&
				obj->tiling_mode != I915_TILING_NONE;

			if (!obj->gtt_space) {
				bool need_mappable =
					entry->relocation_count ? true : need_fence;

				ret = i915_gem_object_pin(obj,
							  entry->alignment,
							  need_mappable);
3575 3576 3577
				if (ret)
					break;
			}
3578

3579
			if (need_fence) {
3580
				ret = i915_gem_object_get_fence_reg(obj, true);
C
Chris Wilson 已提交
3581
				if (ret)
3582
					break;
3583

3584
				obj->pending_fenced_gpu_access = true;
3585
			}
3586

3587
			entry->offset = obj->gtt_offset;
3588 3589
		}

C
Chris Wilson 已提交
3590 3591 3592 3593 3594 3595
err:		/* Decrement pin count for bound objects */
		for (i = 0; i < count; i++) {
			struct drm_i915_gem_object *obj = object_list[i];
			if (obj->gtt_space)
				i915_gem_object_unpin(obj);
		}
3596

3597
		if (ret != -ENOSPC || retry > 1)
3598 3599
			return ret;

3600 3601 3602 3603
		/* First attempt, just clear anything that is purgeable.
		 * Second attempt, clear the entire GTT.
		 */
		ret = i915_gem_evict_everything(dev, retry == 0);
3604 3605
		if (ret)
			return ret;
3606

3607 3608
		retry++;
	} while (1);
3609 3610
}

3611 3612 3613
static int
i915_gem_execbuffer_relocate_slow(struct drm_device *dev,
				  struct drm_file *file,
3614
				  struct drm_i915_gem_object **object_list,
3615 3616 3617 3618 3619 3620
				  struct drm_i915_gem_exec_object2 *exec_list,
				  int count)
{
	struct drm_i915_gem_relocation_entry *reloc;
	int i, total, ret;

3621 3622
	for (i = 0; i < count; i++)
		object_list[i]->in_execbuffer = false;
3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666

	mutex_unlock(&dev->struct_mutex);

	total = 0;
	for (i = 0; i < count; i++)
		total += exec_list[i].relocation_count;

	reloc = drm_malloc_ab(total, sizeof(*reloc));
	if (reloc == NULL) {
		mutex_lock(&dev->struct_mutex);
		return -ENOMEM;
	}

	total = 0;
	for (i = 0; i < count; i++) {
		struct drm_i915_gem_relocation_entry __user *user_relocs;

		user_relocs = (void __user *)(uintptr_t)exec_list[i].relocs_ptr;

		if (copy_from_user(reloc+total, user_relocs,
				   exec_list[i].relocation_count *
				   sizeof(*reloc))) {
			ret = -EFAULT;
			mutex_lock(&dev->struct_mutex);
			goto err;
		}

		total += exec_list[i].relocation_count;
	}

	ret = i915_mutex_lock_interruptible(dev);
	if (ret) {
		mutex_lock(&dev->struct_mutex);
		goto err;
	}

	ret = i915_gem_execbuffer_reserve(dev, file,
					  object_list, exec_list,
					  count);
	if (ret)
		goto err;

	total = 0;
	for (i = 0; i < count; i++) {
3667
		struct drm_i915_gem_object *obj = object_list[i];
3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689
		obj->base.pending_read_domains = 0;
		obj->base.pending_write_domain = 0;
		ret = i915_gem_execbuffer_relocate_object_slow(obj, file,
							       &exec_list[i],
							       reloc + total);
		if (ret)
			goto err;

		total += exec_list[i].relocation_count;
	}

	/* Leave the user relocations as are, this is the painfully slow path,
	 * and we want to avoid the complication of dropping the lock whilst
	 * having buffers reserved in the aperture and so causing spurious
	 * ENOSPC for random operations.
	 */

err:
	drm_free_large(reloc);
	return ret;
}

3690 3691 3692 3693
static int
i915_gem_execbuffer_move_to_gpu(struct drm_device *dev,
				struct drm_file *file,
				struct intel_ring_buffer *ring,
3694
				struct drm_i915_gem_object **objects,
3695 3696
				int count)
{
3697
	struct change_domains cd;
3698 3699
	int ret, i;

3700 3701 3702
	cd.invalidate_domains = 0;
	cd.flush_domains = 0;
	cd.flush_rings = 0;
3703
	for (i = 0; i < count; i++)
3704
		i915_gem_object_set_to_gpu_domain(objects[i], ring, &cd);
3705

3706
	if (cd.invalidate_domains | cd.flush_domains) {
3707 3708 3709
#if WATCH_EXEC
		DRM_INFO("%s: invalidate_domains %08x flush_domains %08x\n",
			  __func__,
3710 3711
			 cd.invalidate_domains,
			 cd.flush_domains);
3712
#endif
3713
		i915_gem_flush(dev,
3714 3715 3716
			       cd.invalidate_domains,
			       cd.flush_domains,
			       cd.flush_rings);
3717 3718 3719
	}

	for (i = 0; i < count; i++) {
3720
		struct drm_i915_gem_object *obj = objects[i];
3721 3722
		/* XXX replace with semaphores */
		if (obj->ring && ring != obj->ring) {
3723
			ret = i915_gem_object_wait_rendering(obj, true);
3724 3725 3726 3727 3728 3729 3730 3731
			if (ret)
				return ret;
		}
	}

	return 0;
}

3732 3733 3734
/* Throttle our rendering by waiting until the ring has completed our requests
 * emitted over 20 msec ago.
 *
3735 3736 3737 3738
 * Note that if we were to use the current jiffies each time around the loop,
 * we wouldn't escape the function with any frames outstanding if the time to
 * render a frame was over 20ms.
 *
3739 3740 3741
 * This should get us reasonable parallelism between CPU and GPU but also
 * relatively low latency when blocking on a particular request to finish.
 */
3742
static int
3743
i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file)
3744
{
3745 3746
	struct drm_i915_private *dev_priv = dev->dev_private;
	struct drm_i915_file_private *file_priv = file->driver_priv;
3747
	unsigned long recent_enough = jiffies - msecs_to_jiffies(20);
3748 3749 3750 3751
	struct drm_i915_gem_request *request;
	struct intel_ring_buffer *ring = NULL;
	u32 seqno = 0;
	int ret;
3752

3753
	spin_lock(&file_priv->mm.lock);
3754
	list_for_each_entry(request, &file_priv->mm.request_list, client_list) {
3755 3756
		if (time_after_eq(request->emitted_jiffies, recent_enough))
			break;
3757

3758 3759
		ring = request->ring;
		seqno = request->seqno;
3760
	}
3761
	spin_unlock(&file_priv->mm.lock);
3762

3763 3764
	if (seqno == 0)
		return 0;
3765

3766
	ret = 0;
3767
	if (!i915_seqno_passed(ring->get_seqno(ring), seqno)) {
3768 3769 3770 3771 3772
		/* And wait for the seqno passing without holding any locks and
		 * causing extra latency for others. This is safe as the irq
		 * generation is designed to be run atomically and so is
		 * lockless.
		 */
3773
		ring->user_irq_get(ring);
3774
		ret = wait_event_interruptible(ring->irq_queue,
3775
					       i915_seqno_passed(ring->get_seqno(ring), seqno)
3776
					       || atomic_read(&dev_priv->mm.wedged));
3777
		ring->user_irq_put(ring);
3778

3779 3780
		if (ret == 0 && atomic_read(&dev_priv->mm.wedged))
			ret = -EIO;
3781 3782
	}

3783 3784
	if (ret == 0)
		queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, 0);
3785 3786 3787 3788

	return ret;
}

3789
static int
3790 3791
i915_gem_check_execbuffer(struct drm_i915_gem_execbuffer2 *exec,
			  uint64_t exec_offset)
3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806
{
	uint32_t exec_start, exec_len;

	exec_start = (uint32_t) exec_offset + exec->batch_start_offset;
	exec_len = (uint32_t) exec->batch_len;

	if ((exec_start | exec_len) & 0x7)
		return -EINVAL;

	if (!exec_start)
		return -EINVAL;

	return 0;
}

3807
static int
3808 3809
validate_exec_list(struct drm_i915_gem_exec_object2 *exec,
		   int count)
3810
{
3811
	int i;
3812

3813 3814
	for (i = 0; i < count; i++) {
		char __user *ptr = (char __user *)(uintptr_t)exec[i].relocs_ptr;
3815
		int length; /* limited by fault_in_pages_readable() */
3816

3817 3818 3819 3820
		/* First check for malicious input causing overflow */
		if (exec[i].relocation_count >
		    INT_MAX / sizeof(struct drm_i915_gem_relocation_entry))
			return -EINVAL;
3821

3822 3823
		length = exec[i].relocation_count *
			sizeof(struct drm_i915_gem_relocation_entry);
3824 3825
		if (!access_ok(VERIFY_READ, ptr, length))
			return -EFAULT;
3826

3827 3828 3829 3830
		/* we may also need to update the presumed offsets */
		if (!access_ok(VERIFY_WRITE, ptr, length))
			return -EFAULT;

3831 3832
		if (fault_in_pages_readable(ptr, length))
			return -EFAULT;
3833 3834
	}

3835
	return 0;
3836 3837
}

C
Chris Wilson 已提交
3838
static int
J
Jesse Barnes 已提交
3839
i915_gem_do_execbuffer(struct drm_device *dev, void *data,
3840
		       struct drm_file *file,
J
Jesse Barnes 已提交
3841 3842
		       struct drm_i915_gem_execbuffer2 *args,
		       struct drm_i915_gem_exec_object2 *exec_list)
3843 3844
{
	drm_i915_private_t *dev_priv = dev->dev_private;
3845 3846
	struct drm_i915_gem_object **object_list = NULL;
	struct drm_i915_gem_object *batch_obj;
3847
	struct drm_clip_rect *cliprects = NULL;
C
Chris Wilson 已提交
3848
	struct drm_i915_gem_request *request = NULL;
3849
	int ret, i, flips;
3850 3851
	uint64_t exec_offset;

3852 3853
	struct intel_ring_buffer *ring = NULL;

3854 3855 3856 3857
	ret = i915_gem_check_is_wedged(dev);
	if (ret)
		return ret;

3858 3859 3860 3861
	ret = validate_exec_list(exec_list, args->buffer_count);
	if (ret)
		return ret;

3862 3863 3864 3865
#if WATCH_EXEC
	DRM_INFO("buffers_ptr %d buffer_count %d len %08x\n",
		  (int) args->buffers_ptr, args->buffer_count, args->batch_len);
#endif
3866 3867 3868 3869 3870 3871
	switch (args->flags & I915_EXEC_RING_MASK) {
	case I915_EXEC_DEFAULT:
	case I915_EXEC_RENDER:
		ring = &dev_priv->render_ring;
		break;
	case I915_EXEC_BSD:
3872
		if (!HAS_BSD(dev)) {
3873
			DRM_ERROR("execbuf with invalid ring (BSD)\n");
3874 3875 3876
			return -EINVAL;
		}
		ring = &dev_priv->bsd_ring;
3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888
		break;
	case I915_EXEC_BLT:
		if (!HAS_BLT(dev)) {
			DRM_ERROR("execbuf with invalid ring (BLT)\n");
			return -EINVAL;
		}
		ring = &dev_priv->blt_ring;
		break;
	default:
		DRM_ERROR("execbuf with unknown ring: %d\n",
			  (int)(args->flags & I915_EXEC_RING_MASK));
		return -EINVAL;
3889 3890
	}

3891 3892 3893 3894
	if (args->buffer_count < 1) {
		DRM_ERROR("execbuf with %d buffers\n", args->buffer_count);
		return -EINVAL;
	}
3895
	object_list = drm_malloc_ab(sizeof(*object_list), args->buffer_count);
J
Jesse Barnes 已提交
3896 3897
	if (object_list == NULL) {
		DRM_ERROR("Failed to allocate object list for %d buffers\n",
3898 3899 3900 3901 3902
			  args->buffer_count);
		ret = -ENOMEM;
		goto pre_mutex_err;
	}

3903
	if (args->num_cliprects != 0) {
3904 3905
		cliprects = kcalloc(args->num_cliprects, sizeof(*cliprects),
				    GFP_KERNEL);
3906 3907
		if (cliprects == NULL) {
			ret = -ENOMEM;
3908
			goto pre_mutex_err;
3909
		}
3910 3911 3912 3913 3914 3915 3916 3917

		ret = copy_from_user(cliprects,
				     (struct drm_clip_rect __user *)
				     (uintptr_t) args->cliprects_ptr,
				     sizeof(*cliprects) * args->num_cliprects);
		if (ret != 0) {
			DRM_ERROR("copy %d cliprects failed: %d\n",
				  args->num_cliprects, ret);
3918
			ret = -EFAULT;
3919 3920 3921 3922
			goto pre_mutex_err;
		}
	}

C
Chris Wilson 已提交
3923 3924 3925
	request = kzalloc(sizeof(*request), GFP_KERNEL);
	if (request == NULL) {
		ret = -ENOMEM;
3926
		goto pre_mutex_err;
C
Chris Wilson 已提交
3927
	}
3928

3929 3930
	ret = i915_mutex_lock_interruptible(dev);
	if (ret)
3931
		goto pre_mutex_err;
3932 3933 3934

	if (dev_priv->mm.suspended) {
		mutex_unlock(&dev->struct_mutex);
3935 3936
		ret = -EBUSY;
		goto pre_mutex_err;
3937 3938
	}

3939
	/* Look up object handles */
3940
	for (i = 0; i < args->buffer_count; i++) {
3941
		struct drm_i915_gem_object *obj;
3942

3943 3944 3945
		obj = to_intel_bo (drm_gem_object_lookup(dev, file,
							 exec_list[i].handle));
		if (obj == NULL) {
3946 3947
			DRM_ERROR("Invalid object handle %d at index %d\n",
				   exec_list[i].handle, i);
3948
			/* prevent error path from reading uninitialized data */
3949
			args->buffer_count = i;
3950
			ret = -ENOENT;
3951 3952
			goto err;
		}
3953
		object_list[i] = obj;
3954

3955
		if (obj->in_execbuffer) {
3956
			DRM_ERROR("Object %p appears more than once in object list\n",
3957
				   obj);
3958 3959
			/* prevent error path from reading uninitialized data */
			args->buffer_count = i + 1;
3960
			ret = -EINVAL;
3961 3962
			goto err;
		}
3963
		obj->in_execbuffer = true;
3964
		obj->pending_fenced_gpu_access = false;
3965
	}
3966

3967
	/* Move the objects en-masse into the GTT, evicting if necessary. */
3968 3969 3970
	ret = i915_gem_execbuffer_reserve(dev, file,
					  object_list, exec_list,
					  args->buffer_count);
3971 3972
	if (ret)
		goto err;
3973

3974
	/* The objects are in their final locations, apply the relocations. */
3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985
	ret = i915_gem_execbuffer_relocate(dev, file,
					   object_list, exec_list,
					   args->buffer_count);
	if (ret) {
		if (ret == -EFAULT) {
			ret = i915_gem_execbuffer_relocate_slow(dev, file,
								object_list,
								exec_list,
								args->buffer_count);
			BUG_ON(!mutex_is_locked(&dev->struct_mutex));
		}
3986
		if (ret)
3987
			goto err;
3988 3989 3990 3991
	}

	/* Set the pending read domains for the batch buffer to COMMAND */
	batch_obj = object_list[args->buffer_count-1];
3992
	if (batch_obj->base.pending_write_domain) {
3993 3994 3995 3996
		DRM_ERROR("Attempting to use self-modifying batch buffer\n");
		ret = -EINVAL;
		goto err;
	}
3997
	batch_obj->base.pending_read_domains |= I915_GEM_DOMAIN_COMMAND;
3998

3999
	/* Sanity check the batch buffer */
4000
	exec_offset = batch_obj->gtt_offset;
4001
	ret = i915_gem_check_execbuffer(args, exec_offset);
4002 4003 4004 4005 4006
	if (ret != 0) {
		DRM_ERROR("execbuf with invalid offset/length\n");
		goto err;
	}

4007 4008 4009 4010
	ret = i915_gem_execbuffer_move_to_gpu(dev, file, ring,
					      object_list, args->buffer_count);
	if (ret)
		goto err;
4011 4012 4013 4014 4015 4016 4017 4018 4019

#if WATCH_COHERENCY
	for (i = 0; i < args->buffer_count; i++) {
		i915_gem_object_check_coherency(object_list[i],
						exec_list[i].handle);
	}
#endif

#if WATCH_EXEC
4020
	i915_gem_dump_object(batch_obj,
4021 4022 4023 4024 4025
			      args->batch_len,
			      __func__,
			      ~0);
#endif

4026 4027 4028 4029 4030 4031
	/* Check for any pending flips. As we only maintain a flip queue depth
	 * of 1, we can simply insert a WAIT for the next display flip prior
	 * to executing the batch and avoid stalling the CPU.
	 */
	flips = 0;
	for (i = 0; i < args->buffer_count; i++) {
4032 4033
		if (object_list[i]->base.write_domain)
			flips |= atomic_read(&object_list[i]->pending_flip);
4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046
	}
	if (flips) {
		int plane, flip_mask;

		for (plane = 0; flips >> plane; plane++) {
			if (((flips >> plane) & 1) == 0)
				continue;

			if (plane)
				flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
			else
				flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;

4047 4048 4049 4050
			ret = intel_ring_begin(ring, 2);
			if (ret)
				goto err;

4051 4052 4053
			intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
			intel_ring_emit(ring, MI_NOOP);
			intel_ring_advance(ring);
4054 4055 4056
		}
	}

4057
	/* Exec the batchbuffer */
4058
	ret = ring->dispatch_execbuffer(ring, args, cliprects, exec_offset);
4059 4060 4061 4062 4063 4064
	if (ret) {
		DRM_ERROR("dispatch failed %d\n", ret);
		goto err;
	}

	for (i = 0; i < args->buffer_count; i++) {
4065
		struct drm_i915_gem_object *obj = object_list[i];
4066

4067 4068
		obj->base.read_domains = obj->base.pending_read_domains;
		obj->base.write_domain = obj->base.pending_write_domain;
4069
		obj->fenced_gpu_access = obj->pending_fenced_gpu_access;
4070

4071
		i915_gem_object_move_to_active(obj, ring);
4072 4073 4074
		if (obj->base.write_domain) {
			obj->dirty = 1;
			list_move_tail(&obj->gpu_write_list,
4075
				       &ring->gpu_write_list);
4076 4077 4078 4079
			intel_mark_busy(dev, obj);
		}

		trace_i915_gem_object_change_domain(obj,
4080 4081
						    obj->base.read_domains,
						    obj->base.write_domain);
4082 4083
	}

4084 4085 4086 4087 4088 4089
	/*
	 * Ensure that the commands in the batch buffer are
	 * finished before the interrupt fires
	 */
	i915_retire_commands(dev, ring);

4090
	if (i915_add_request(dev, file, request, ring))
4091
		i915_gem_next_request_seqno(dev, ring);
4092 4093
	else
		request = NULL;
4094 4095

err:
4096
	for (i = 0; i < args->buffer_count; i++) {
4097 4098
		object_list[i]->in_execbuffer = false;
		drm_gem_object_unreference(&object_list[i]->base);
4099
	}
4100 4101 4102

	mutex_unlock(&dev->struct_mutex);

4103
pre_mutex_err:
4104
	drm_free_large(object_list);
4105
	kfree(cliprects);
C
Chris Wilson 已提交
4106
	kfree(request);
4107 4108 4109 4110

	return ret;
}

J
Jesse Barnes 已提交
4111 4112 4113 4114 4115 4116
/*
 * Legacy execbuffer just creates an exec2 list from the original exec object
 * list array and passes it to the real function.
 */
int
i915_gem_execbuffer(struct drm_device *dev, void *data,
4117
		    struct drm_file *file)
J
Jesse Barnes 已提交
4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162
{
	struct drm_i915_gem_execbuffer *args = data;
	struct drm_i915_gem_execbuffer2 exec2;
	struct drm_i915_gem_exec_object *exec_list = NULL;
	struct drm_i915_gem_exec_object2 *exec2_list = NULL;
	int ret, i;

#if WATCH_EXEC
	DRM_INFO("buffers_ptr %d buffer_count %d len %08x\n",
		  (int) args->buffers_ptr, args->buffer_count, args->batch_len);
#endif

	if (args->buffer_count < 1) {
		DRM_ERROR("execbuf with %d buffers\n", args->buffer_count);
		return -EINVAL;
	}

	/* Copy in the exec list from userland */
	exec_list = drm_malloc_ab(sizeof(*exec_list), args->buffer_count);
	exec2_list = drm_malloc_ab(sizeof(*exec2_list), args->buffer_count);
	if (exec_list == NULL || exec2_list == NULL) {
		DRM_ERROR("Failed to allocate exec list for %d buffers\n",
			  args->buffer_count);
		drm_free_large(exec_list);
		drm_free_large(exec2_list);
		return -ENOMEM;
	}
	ret = copy_from_user(exec_list,
			     (struct drm_i915_relocation_entry __user *)
			     (uintptr_t) args->buffers_ptr,
			     sizeof(*exec_list) * args->buffer_count);
	if (ret != 0) {
		DRM_ERROR("copy %d exec entries failed %d\n",
			  args->buffer_count, ret);
		drm_free_large(exec_list);
		drm_free_large(exec2_list);
		return -EFAULT;
	}

	for (i = 0; i < args->buffer_count; i++) {
		exec2_list[i].handle = exec_list[i].handle;
		exec2_list[i].relocation_count = exec_list[i].relocation_count;
		exec2_list[i].relocs_ptr = exec_list[i].relocs_ptr;
		exec2_list[i].alignment = exec_list[i].alignment;
		exec2_list[i].offset = exec_list[i].offset;
4163
		if (INTEL_INFO(dev)->gen < 4)
J
Jesse Barnes 已提交
4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176
			exec2_list[i].flags = EXEC_OBJECT_NEEDS_FENCE;
		else
			exec2_list[i].flags = 0;
	}

	exec2.buffers_ptr = args->buffers_ptr;
	exec2.buffer_count = args->buffer_count;
	exec2.batch_start_offset = args->batch_start_offset;
	exec2.batch_len = args->batch_len;
	exec2.DR1 = args->DR1;
	exec2.DR4 = args->DR4;
	exec2.num_cliprects = args->num_cliprects;
	exec2.cliprects_ptr = args->cliprects_ptr;
4177
	exec2.flags = I915_EXEC_RENDER;
J
Jesse Barnes 已提交
4178

4179
	ret = i915_gem_do_execbuffer(dev, data, file, &exec2, exec2_list);
J
Jesse Barnes 已提交
4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203
	if (!ret) {
		/* Copy the new buffer offsets back to the user's exec list. */
		for (i = 0; i < args->buffer_count; i++)
			exec_list[i].offset = exec2_list[i].offset;
		/* ... and back out to userspace */
		ret = copy_to_user((struct drm_i915_relocation_entry __user *)
				   (uintptr_t) args->buffers_ptr,
				   exec_list,
				   sizeof(*exec_list) * args->buffer_count);
		if (ret) {
			ret = -EFAULT;
			DRM_ERROR("failed to copy %d exec entries "
				  "back to user (%d)\n",
				  args->buffer_count, ret);
		}
	}

	drm_free_large(exec_list);
	drm_free_large(exec2_list);
	return ret;
}

int
i915_gem_execbuffer2(struct drm_device *dev, void *data,
4204
		     struct drm_file *file)
J
Jesse Barnes 已提交
4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236
{
	struct drm_i915_gem_execbuffer2 *args = data;
	struct drm_i915_gem_exec_object2 *exec2_list = NULL;
	int ret;

#if WATCH_EXEC
	DRM_INFO("buffers_ptr %d buffer_count %d len %08x\n",
		  (int) args->buffers_ptr, args->buffer_count, args->batch_len);
#endif

	if (args->buffer_count < 1) {
		DRM_ERROR("execbuf2 with %d buffers\n", args->buffer_count);
		return -EINVAL;
	}

	exec2_list = drm_malloc_ab(sizeof(*exec2_list), args->buffer_count);
	if (exec2_list == NULL) {
		DRM_ERROR("Failed to allocate exec list for %d buffers\n",
			  args->buffer_count);
		return -ENOMEM;
	}
	ret = copy_from_user(exec2_list,
			     (struct drm_i915_relocation_entry __user *)
			     (uintptr_t) args->buffers_ptr,
			     sizeof(*exec2_list) * args->buffer_count);
	if (ret != 0) {
		DRM_ERROR("copy %d exec entries failed %d\n",
			  args->buffer_count, ret);
		drm_free_large(exec2_list);
		return -EFAULT;
	}

4237
	ret = i915_gem_do_execbuffer(dev, data, file, args, exec2_list);
J
Jesse Barnes 已提交
4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255
	if (!ret) {
		/* Copy the new buffer offsets back to the user's exec list. */
		ret = copy_to_user((struct drm_i915_relocation_entry __user *)
				   (uintptr_t) args->buffers_ptr,
				   exec2_list,
				   sizeof(*exec2_list) * args->buffer_count);
		if (ret) {
			ret = -EFAULT;
			DRM_ERROR("failed to copy %d exec entries "
				  "back to user (%d)\n",
				  args->buffer_count, ret);
		}
	}

	drm_free_large(exec2_list);
	return ret;
}

4256
int
4257 4258
i915_gem_object_pin(struct drm_i915_gem_object *obj,
		    uint32_t alignment,
4259
		    bool map_and_fenceable)
4260
{
4261
	struct drm_device *dev = obj->base.dev;
C
Chris Wilson 已提交
4262
	struct drm_i915_private *dev_priv = dev->dev_private;
4263 4264
	int ret;

4265
	BUG_ON(obj->pin_count == DRM_I915_GEM_OBJECT_MAX_PIN_COUNT);
4266
	WARN_ON(i915_verify_lists(dev));
4267

4268 4269 4270 4271
	if (obj->gtt_space != NULL) {
		if ((alignment && obj->gtt_offset & (alignment - 1)) ||
		    (map_and_fenceable && !obj->map_and_fenceable)) {
			WARN(obj->pin_count,
4272
			     "bo is already pinned with incorrect alignment:"
4273 4274
			     " offset=%x, req.alignment=%x, req.map_and_fenceable=%d,"
			     " obj->map_and_fenceable=%d\n",
4275
			     obj->gtt_offset, alignment,
4276
			     map_and_fenceable,
4277
			     obj->map_and_fenceable);
4278 4279 4280 4281 4282 4283
			ret = i915_gem_object_unbind(obj);
			if (ret)
				return ret;
		}
	}

4284
	if (obj->gtt_space == NULL) {
4285
		ret = i915_gem_object_bind_to_gtt(obj, alignment,
4286
						  map_and_fenceable);
4287
		if (ret)
4288
			return ret;
4289
	}
J
Jesse Barnes 已提交
4290

4291 4292 4293
	if (obj->pin_count++ == 0) {
		if (!obj->active)
			list_move_tail(&obj->mm_list,
C
Chris Wilson 已提交
4294
				       &dev_priv->mm.pinned_list);
4295
	}
4296
	obj->pin_mappable |= map_and_fenceable;
4297

4298
	WARN_ON(i915_verify_lists(dev));
4299 4300 4301 4302
	return 0;
}

void
4303
i915_gem_object_unpin(struct drm_i915_gem_object *obj)
4304
{
4305
	struct drm_device *dev = obj->base.dev;
4306 4307
	drm_i915_private_t *dev_priv = dev->dev_private;

4308
	WARN_ON(i915_verify_lists(dev));
4309 4310
	BUG_ON(obj->pin_count == 0);
	BUG_ON(obj->gtt_space == NULL);
4311

4312 4313 4314
	if (--obj->pin_count == 0) {
		if (!obj->active)
			list_move_tail(&obj->mm_list,
4315
				       &dev_priv->mm.inactive_list);
4316
		obj->pin_mappable = false;
4317
	}
4318
	WARN_ON(i915_verify_lists(dev));
4319 4320 4321 4322
}

int
i915_gem_pin_ioctl(struct drm_device *dev, void *data,
4323
		   struct drm_file *file)
4324 4325
{
	struct drm_i915_gem_pin *args = data;
4326
	struct drm_i915_gem_object *obj;
4327 4328
	int ret;

4329 4330 4331
	ret = i915_mutex_lock_interruptible(dev);
	if (ret)
		return ret;
4332

4333
	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
4334
	if (obj == NULL) {
4335 4336
		ret = -ENOENT;
		goto unlock;
4337 4338
	}

4339
	if (obj->madv != I915_MADV_WILLNEED) {
C
Chris Wilson 已提交
4340
		DRM_ERROR("Attempting to pin a purgeable buffer\n");
4341 4342
		ret = -EINVAL;
		goto out;
4343 4344
	}

4345
	if (obj->pin_filp != NULL && obj->pin_filp != file) {
J
Jesse Barnes 已提交
4346 4347
		DRM_ERROR("Already pinned in i915_gem_pin_ioctl(): %d\n",
			  args->handle);
4348 4349
		ret = -EINVAL;
		goto out;
J
Jesse Barnes 已提交
4350 4351
	}

4352 4353 4354
	obj->user_pin_count++;
	obj->pin_filp = file;
	if (obj->user_pin_count == 1) {
4355
		ret = i915_gem_object_pin(obj, args->alignment, true);
4356 4357
		if (ret)
			goto out;
4358 4359 4360 4361 4362
	}

	/* XXX - flush the CPU caches for pinned objects
	 * as the X server doesn't manage domains yet
	 */
4363
	i915_gem_object_flush_cpu_write_domain(obj);
4364
	args->offset = obj->gtt_offset;
4365
out:
4366
	drm_gem_object_unreference(&obj->base);
4367
unlock:
4368
	mutex_unlock(&dev->struct_mutex);
4369
	return ret;
4370 4371 4372 4373
}

int
i915_gem_unpin_ioctl(struct drm_device *dev, void *data,
4374
		     struct drm_file *file)
4375 4376
{
	struct drm_i915_gem_pin *args = data;
4377
	struct drm_i915_gem_object *obj;
4378
	int ret;
4379

4380 4381 4382
	ret = i915_mutex_lock_interruptible(dev);
	if (ret)
		return ret;
4383

4384
	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
4385
	if (obj == NULL) {
4386 4387
		ret = -ENOENT;
		goto unlock;
4388
	}
4389

4390
	if (obj->pin_filp != file) {
J
Jesse Barnes 已提交
4391 4392
		DRM_ERROR("Not pinned by caller in i915_gem_pin_ioctl(): %d\n",
			  args->handle);
4393 4394
		ret = -EINVAL;
		goto out;
J
Jesse Barnes 已提交
4395
	}
4396 4397 4398
	obj->user_pin_count--;
	if (obj->user_pin_count == 0) {
		obj->pin_filp = NULL;
J
Jesse Barnes 已提交
4399 4400
		i915_gem_object_unpin(obj);
	}
4401

4402
out:
4403
	drm_gem_object_unreference(&obj->base);
4404
unlock:
4405
	mutex_unlock(&dev->struct_mutex);
4406
	return ret;
4407 4408 4409 4410
}

int
i915_gem_busy_ioctl(struct drm_device *dev, void *data,
4411
		    struct drm_file *file)
4412 4413
{
	struct drm_i915_gem_busy *args = data;
4414
	struct drm_i915_gem_object *obj;
4415 4416
	int ret;

4417
	ret = i915_mutex_lock_interruptible(dev);
4418
	if (ret)
4419
		return ret;
4420

4421
	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
4422
	if (obj == NULL) {
4423 4424
		ret = -ENOENT;
		goto unlock;
4425
	}
4426

4427 4428 4429 4430
	/* Count all active objects as busy, even if they are currently not used
	 * by the gpu. Users of this interface expect objects to eventually
	 * become non-busy without any further actions, therefore emit any
	 * necessary flushes here.
4431
	 */
4432
	args->busy = obj->active;
4433 4434 4435 4436 4437 4438
	if (args->busy) {
		/* Unconditionally flush objects, even when the gpu still uses this
		 * object. Userspace calling this function indicates that it wants to
		 * use this buffer rather sooner than later, so issuing the required
		 * flush earlier is beneficial.
		 */
4439 4440 4441
		if (obj->base.write_domain & I915_GEM_GPU_DOMAINS)
			i915_gem_flush_ring(dev, obj->ring,
					    0, obj->base.write_domain);
4442 4443 4444 4445 4446 4447

		/* Update the active list for the hardware's current position.
		 * Otherwise this only updates on a delayed timer or when irqs
		 * are actually unmasked, and our working set ends up being
		 * larger than required.
		 */
4448
		i915_gem_retire_requests_ring(dev, obj->ring);
4449

4450
		args->busy = obj->active;
4451
	}
4452

4453
	drm_gem_object_unreference(&obj->base);
4454
unlock:
4455
	mutex_unlock(&dev->struct_mutex);
4456
	return ret;
4457 4458 4459 4460 4461 4462 4463 4464 4465
}

int
i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
			struct drm_file *file_priv)
{
    return i915_gem_ring_throttle(dev, file_priv);
}

4466 4467 4468 4469 4470
int
i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
		       struct drm_file *file_priv)
{
	struct drm_i915_gem_madvise *args = data;
4471
	struct drm_i915_gem_object *obj;
4472
	int ret;
4473 4474 4475 4476 4477 4478 4479 4480 4481

	switch (args->madv) {
	case I915_MADV_DONTNEED:
	case I915_MADV_WILLNEED:
	    break;
	default:
	    return -EINVAL;
	}

4482 4483 4484 4485
	ret = i915_mutex_lock_interruptible(dev);
	if (ret)
		return ret;

4486
	obj = to_intel_bo(drm_gem_object_lookup(dev, file_priv, args->handle));
4487
	if (obj == NULL) {
4488 4489
		ret = -ENOENT;
		goto unlock;
4490 4491
	}

4492
	if (obj->pin_count) {
4493 4494
		ret = -EINVAL;
		goto out;
4495 4496
	}

4497 4498
	if (obj->madv != __I915_MADV_PURGED)
		obj->madv = args->madv;
4499

4500
	/* if the object is no longer bound, discard its backing storage */
4501 4502
	if (i915_gem_object_is_purgeable(obj) &&
	    obj->gtt_space == NULL)
4503 4504
		i915_gem_object_truncate(obj);

4505
	args->retained = obj->madv != __I915_MADV_PURGED;
C
Chris Wilson 已提交
4506

4507
out:
4508
	drm_gem_object_unreference(&obj->base);
4509
unlock:
4510
	mutex_unlock(&dev->struct_mutex);
4511
	return ret;
4512 4513
}

4514 4515
struct drm_i915_gem_object *i915_gem_alloc_object(struct drm_device *dev,
						  size_t size)
4516
{
4517
	struct drm_i915_private *dev_priv = dev->dev_private;
4518
	struct drm_i915_gem_object *obj;
4519

4520 4521 4522
	obj = kzalloc(sizeof(*obj), GFP_KERNEL);
	if (obj == NULL)
		return NULL;
4523

4524 4525 4526 4527
	if (drm_gem_object_init(dev, &obj->base, size) != 0) {
		kfree(obj);
		return NULL;
	}
4528

4529 4530
	i915_gem_info_add_obj(dev_priv, size);

4531 4532
	obj->base.write_domain = I915_GEM_DOMAIN_CPU;
	obj->base.read_domains = I915_GEM_DOMAIN_CPU;
4533

4534
	obj->agp_type = AGP_USER_MEMORY;
4535
	obj->base.driver_private = NULL;
4536
	obj->fence_reg = I915_FENCE_REG_NONE;
4537
	INIT_LIST_HEAD(&obj->mm_list);
D
Daniel Vetter 已提交
4538
	INIT_LIST_HEAD(&obj->gtt_list);
4539
	INIT_LIST_HEAD(&obj->ring_list);
4540 4541
	INIT_LIST_HEAD(&obj->gpu_write_list);
	obj->madv = I915_MADV_WILLNEED;
4542 4543
	/* Avoid an unnecessary call to unbind on the first bind. */
	obj->map_and_fenceable = true;
4544

4545
	return obj;
4546 4547 4548 4549 4550
}

int i915_gem_init_object(struct drm_gem_object *obj)
{
	BUG();
4551

4552 4553 4554
	return 0;
}

4555
static void i915_gem_free_object_tail(struct drm_i915_gem_object *obj)
4556
{
4557
	struct drm_device *dev = obj->base.dev;
4558 4559
	drm_i915_private_t *dev_priv = dev->dev_private;
	int ret;
4560

4561 4562
	ret = i915_gem_object_unbind(obj);
	if (ret == -ERESTARTSYS) {
4563
		list_move(&obj->mm_list,
4564 4565 4566
			  &dev_priv->mm.deferred_free_list);
		return;
	}
4567

4568
	if (obj->base.map_list.map)
4569
		i915_gem_free_mmap_offset(obj);
4570

4571 4572
	drm_gem_object_release(&obj->base);
	i915_gem_info_remove_obj(dev_priv, obj->base.size);
4573

4574 4575 4576
	kfree(obj->page_cpu_valid);
	kfree(obj->bit_17);
	kfree(obj);
4577 4578
}

4579
void i915_gem_free_object(struct drm_gem_object *gem_obj)
4580
{
4581 4582
	struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
	struct drm_device *dev = obj->base.dev;
4583 4584 4585

	trace_i915_gem_object_destroy(obj);

4586
	while (obj->pin_count > 0)
4587 4588
		i915_gem_object_unpin(obj);

4589
	if (obj->phys_obj)
4590 4591 4592 4593 4594
		i915_gem_detach_phys_object(dev, obj);

	i915_gem_free_object_tail(obj);
}

4595 4596 4597 4598 4599
int
i915_gem_idle(struct drm_device *dev)
{
	drm_i915_private_t *dev_priv = dev->dev_private;
	int ret;
4600

4601
	mutex_lock(&dev->struct_mutex);
C
Chris Wilson 已提交
4602

4603
	if (dev_priv->mm.suspended) {
4604 4605
		mutex_unlock(&dev->struct_mutex);
		return 0;
4606 4607
	}

4608
	ret = i915_gpu_idle(dev);
4609 4610
	if (ret) {
		mutex_unlock(&dev->struct_mutex);
4611
		return ret;
4612
	}
4613

4614 4615
	/* Under UMS, be paranoid and evict. */
	if (!drm_core_check_feature(dev, DRIVER_MODESET)) {
4616
		ret = i915_gem_evict_inactive(dev, false);
4617 4618 4619 4620 4621 4622
		if (ret) {
			mutex_unlock(&dev->struct_mutex);
			return ret;
		}
	}

4623 4624
	i915_gem_reset_fences(dev);

4625 4626 4627 4628 4629
	/* Hack!  Don't let anybody do execbuf while we don't control the chip.
	 * We need to replace this with a semaphore, or something.
	 * And not confound mm.suspended!
	 */
	dev_priv->mm.suspended = 1;
4630
	del_timer_sync(&dev_priv->hangcheck_timer);
4631 4632

	i915_kernel_lost_context(dev);
4633
	i915_gem_cleanup_ringbuffer(dev);
4634

4635 4636
	mutex_unlock(&dev->struct_mutex);

4637 4638 4639
	/* Cancel the retire work handler, which should be idle now. */
	cancel_delayed_work_sync(&dev_priv->mm.retire_work);

4640 4641 4642
	return 0;
}

4643 4644 4645 4646 4647
int
i915_gem_init_ringbuffer(struct drm_device *dev)
{
	drm_i915_private_t *dev_priv = dev->dev_private;
	int ret;
4648

4649
	ret = intel_init_render_ring_buffer(dev);
4650
	if (ret)
4651
		return ret;
4652 4653

	if (HAS_BSD(dev)) {
4654
		ret = intel_init_bsd_ring_buffer(dev);
4655 4656
		if (ret)
			goto cleanup_render_ring;
4657
	}
4658

4659 4660 4661 4662 4663 4664
	if (HAS_BLT(dev)) {
		ret = intel_init_blt_ring_buffer(dev);
		if (ret)
			goto cleanup_bsd_ring;
	}

4665 4666
	dev_priv->next_seqno = 1;

4667 4668
	return 0;

4669
cleanup_bsd_ring:
4670
	intel_cleanup_ring_buffer(&dev_priv->bsd_ring);
4671
cleanup_render_ring:
4672
	intel_cleanup_ring_buffer(&dev_priv->render_ring);
4673 4674 4675 4676 4677 4678 4679 4680
	return ret;
}

void
i915_gem_cleanup_ringbuffer(struct drm_device *dev)
{
	drm_i915_private_t *dev_priv = dev->dev_private;

4681 4682 4683
	intel_cleanup_ring_buffer(&dev_priv->render_ring);
	intel_cleanup_ring_buffer(&dev_priv->bsd_ring);
	intel_cleanup_ring_buffer(&dev_priv->blt_ring);
4684 4685
}

4686 4687 4688 4689 4690 4691 4692
int
i915_gem_entervt_ioctl(struct drm_device *dev, void *data,
		       struct drm_file *file_priv)
{
	drm_i915_private_t *dev_priv = dev->dev_private;
	int ret;

J
Jesse Barnes 已提交
4693 4694 4695
	if (drm_core_check_feature(dev, DRIVER_MODESET))
		return 0;

4696
	if (atomic_read(&dev_priv->mm.wedged)) {
4697
		DRM_ERROR("Reenabling wedged hardware, good luck\n");
4698
		atomic_set(&dev_priv->mm.wedged, 0);
4699 4700 4701
	}

	mutex_lock(&dev->struct_mutex);
4702 4703 4704
	dev_priv->mm.suspended = 0;

	ret = i915_gem_init_ringbuffer(dev);
4705 4706
	if (ret != 0) {
		mutex_unlock(&dev->struct_mutex);
4707
		return ret;
4708
	}
4709

4710
	BUG_ON(!list_empty(&dev_priv->mm.active_list));
4711
	BUG_ON(!list_empty(&dev_priv->render_ring.active_list));
4712
	BUG_ON(!list_empty(&dev_priv->bsd_ring.active_list));
4713
	BUG_ON(!list_empty(&dev_priv->blt_ring.active_list));
4714 4715
	BUG_ON(!list_empty(&dev_priv->mm.flushing_list));
	BUG_ON(!list_empty(&dev_priv->mm.inactive_list));
4716
	BUG_ON(!list_empty(&dev_priv->render_ring.request_list));
4717
	BUG_ON(!list_empty(&dev_priv->bsd_ring.request_list));
4718
	BUG_ON(!list_empty(&dev_priv->blt_ring.request_list));
4719
	mutex_unlock(&dev->struct_mutex);
4720

4721 4722 4723
	ret = drm_irq_install(dev);
	if (ret)
		goto cleanup_ringbuffer;
4724

4725
	return 0;
4726 4727 4728 4729 4730 4731 4732 4733

cleanup_ringbuffer:
	mutex_lock(&dev->struct_mutex);
	i915_gem_cleanup_ringbuffer(dev);
	dev_priv->mm.suspended = 1;
	mutex_unlock(&dev->struct_mutex);

	return ret;
4734 4735 4736 4737 4738 4739
}

int
i915_gem_leavevt_ioctl(struct drm_device *dev, void *data,
		       struct drm_file *file_priv)
{
J
Jesse Barnes 已提交
4740 4741 4742
	if (drm_core_check_feature(dev, DRIVER_MODESET))
		return 0;

4743
	drm_irq_uninstall(dev);
4744
	return i915_gem_idle(dev);
4745 4746 4747 4748 4749 4750 4751
}

void
i915_gem_lastclose(struct drm_device *dev)
{
	int ret;

4752 4753 4754
	if (drm_core_check_feature(dev, DRIVER_MODESET))
		return;

4755 4756 4757
	ret = i915_gem_idle(dev);
	if (ret)
		DRM_ERROR("failed to idle hardware: %d\n", ret);
4758 4759
}

4760 4761 4762 4763 4764 4765 4766 4767
static void
init_ring_lists(struct intel_ring_buffer *ring)
{
	INIT_LIST_HEAD(&ring->active_list);
	INIT_LIST_HEAD(&ring->request_list);
	INIT_LIST_HEAD(&ring->gpu_write_list);
}

4768 4769 4770
void
i915_gem_load(struct drm_device *dev)
{
4771
	int i;
4772 4773
	drm_i915_private_t *dev_priv = dev->dev_private;

4774
	INIT_LIST_HEAD(&dev_priv->mm.active_list);
4775 4776
	INIT_LIST_HEAD(&dev_priv->mm.flushing_list);
	INIT_LIST_HEAD(&dev_priv->mm.inactive_list);
C
Chris Wilson 已提交
4777
	INIT_LIST_HEAD(&dev_priv->mm.pinned_list);
4778
	INIT_LIST_HEAD(&dev_priv->mm.fence_list);
4779
	INIT_LIST_HEAD(&dev_priv->mm.deferred_free_list);
D
Daniel Vetter 已提交
4780
	INIT_LIST_HEAD(&dev_priv->mm.gtt_list);
4781 4782 4783
	init_ring_lists(&dev_priv->render_ring);
	init_ring_lists(&dev_priv->bsd_ring);
	init_ring_lists(&dev_priv->blt_ring);
4784 4785
	for (i = 0; i < 16; i++)
		INIT_LIST_HEAD(&dev_priv->fence_regs[i].lru_list);
4786 4787
	INIT_DELAYED_WORK(&dev_priv->mm.retire_work,
			  i915_gem_retire_work_handler);
4788
	init_completion(&dev_priv->error_completion);
4789

4790 4791 4792 4793 4794 4795 4796 4797 4798 4799
	/* On GEN3 we really need to make sure the ARB C3 LP bit is set */
	if (IS_GEN3(dev)) {
		u32 tmp = I915_READ(MI_ARB_STATE);
		if (!(tmp & MI_ARB_C3_LP_WRITE_ENABLE)) {
			/* arb state is a masked write, so set bit + bit in mask */
			tmp = MI_ARB_C3_LP_WRITE_ENABLE | (MI_ARB_C3_LP_WRITE_ENABLE << MI_ARB_MASK_SHIFT);
			I915_WRITE(MI_ARB_STATE, tmp);
		}
	}

4800
	/* Old X drivers will take 0-2 for front, back, depth buffers */
4801 4802
	if (!drm_core_check_feature(dev, DRIVER_MODESET))
		dev_priv->fence_reg_start = 3;
4803

4804
	if (INTEL_INFO(dev)->gen >= 4 || IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
4805 4806 4807 4808
		dev_priv->num_fence_regs = 16;
	else
		dev_priv->num_fence_regs = 8;

4809
	/* Initialize fence registers to zero */
4810 4811 4812 4813 4814 4815 4816
	switch (INTEL_INFO(dev)->gen) {
	case 6:
		for (i = 0; i < 16; i++)
			I915_WRITE64(FENCE_REG_SANDYBRIDGE_0 + (i * 8), 0);
		break;
	case 5:
	case 4:
4817 4818
		for (i = 0; i < 16; i++)
			I915_WRITE64(FENCE_REG_965_0 + (i * 8), 0);
4819 4820
		break;
	case 3:
4821 4822 4823
		if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
			for (i = 0; i < 8; i++)
				I915_WRITE(FENCE_REG_945_8 + (i * 4), 0);
4824 4825 4826 4827
	case 2:
		for (i = 0; i < 8; i++)
			I915_WRITE(FENCE_REG_830_0 + (i * 4), 0);
		break;
4828
	}
4829
	i915_gem_detect_bit_6_swizzle(dev);
4830
	init_waitqueue_head(&dev_priv->pending_flip_queue);
4831 4832 4833 4834

	dev_priv->mm.inactive_shrinker.shrink = i915_gem_inactive_shrink;
	dev_priv->mm.inactive_shrinker.seeks = DEFAULT_SEEKS;
	register_shrinker(&dev_priv->mm.inactive_shrinker);
4835
}
4836 4837 4838 4839 4840

/*
 * Create a physically contiguous memory object for this object
 * e.g. for cursor + overlay regs
 */
4841 4842
static int i915_gem_init_phys_object(struct drm_device *dev,
				     int id, int size, int align)
4843 4844 4845 4846 4847 4848 4849 4850
{
	drm_i915_private_t *dev_priv = dev->dev_private;
	struct drm_i915_gem_phys_object *phys_obj;
	int ret;

	if (dev_priv->mm.phys_objs[id - 1] || !size)
		return 0;

4851
	phys_obj = kzalloc(sizeof(struct drm_i915_gem_phys_object), GFP_KERNEL);
4852 4853 4854 4855 4856
	if (!phys_obj)
		return -ENOMEM;

	phys_obj->id = id;

4857
	phys_obj->handle = drm_pci_alloc(dev, size, align);
4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869
	if (!phys_obj->handle) {
		ret = -ENOMEM;
		goto kfree_obj;
	}
#ifdef CONFIG_X86
	set_memory_wc((unsigned long)phys_obj->handle->vaddr, phys_obj->handle->size / PAGE_SIZE);
#endif

	dev_priv->mm.phys_objs[id - 1] = phys_obj;

	return 0;
kfree_obj:
4870
	kfree(phys_obj);
4871 4872 4873
	return ret;
}

4874
static void i915_gem_free_phys_object(struct drm_device *dev, int id)
4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898
{
	drm_i915_private_t *dev_priv = dev->dev_private;
	struct drm_i915_gem_phys_object *phys_obj;

	if (!dev_priv->mm.phys_objs[id - 1])
		return;

	phys_obj = dev_priv->mm.phys_objs[id - 1];
	if (phys_obj->cur_obj) {
		i915_gem_detach_phys_object(dev, phys_obj->cur_obj);
	}

#ifdef CONFIG_X86
	set_memory_wb((unsigned long)phys_obj->handle->vaddr, phys_obj->handle->size / PAGE_SIZE);
#endif
	drm_pci_free(dev, phys_obj->handle);
	kfree(phys_obj);
	dev_priv->mm.phys_objs[id - 1] = NULL;
}

void i915_gem_free_all_phys_object(struct drm_device *dev)
{
	int i;

4899
	for (i = I915_GEM_PHYS_CURSOR_0; i <= I915_MAX_PHYS_OBJECT; i++)
4900 4901 4902 4903
		i915_gem_free_phys_object(dev, i);
}

void i915_gem_detach_phys_object(struct drm_device *dev,
4904
				 struct drm_i915_gem_object *obj)
4905
{
4906
	struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
4907
	char *vaddr;
4908 4909 4910
	int i;
	int page_count;

4911
	if (!obj->phys_obj)
4912
		return;
4913
	vaddr = obj->phys_obj->handle->vaddr;
4914

4915
	page_count = obj->base.size / PAGE_SIZE;
4916
	for (i = 0; i < page_count; i++) {
4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929
		struct page *page = read_cache_page_gfp(mapping, i,
							GFP_HIGHUSER | __GFP_RECLAIMABLE);
		if (!IS_ERR(page)) {
			char *dst = kmap_atomic(page);
			memcpy(dst, vaddr + i*PAGE_SIZE, PAGE_SIZE);
			kunmap_atomic(dst);

			drm_clflush_pages(&page, 1);

			set_page_dirty(page);
			mark_page_accessed(page);
			page_cache_release(page);
		}
4930
	}
4931
	intel_gtt_chipset_flush();
4932

4933 4934
	obj->phys_obj->cur_obj = NULL;
	obj->phys_obj = NULL;
4935 4936 4937 4938
}

int
i915_gem_attach_phys_object(struct drm_device *dev,
4939
			    struct drm_i915_gem_object *obj,
4940 4941
			    int id,
			    int align)
4942
{
4943
	struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
4944 4945 4946 4947 4948 4949 4950 4951
	drm_i915_private_t *dev_priv = dev->dev_private;
	int ret = 0;
	int page_count;
	int i;

	if (id > I915_MAX_PHYS_OBJECT)
		return -EINVAL;

4952 4953
	if (obj->phys_obj) {
		if (obj->phys_obj->id == id)
4954 4955 4956 4957 4958 4959 4960
			return 0;
		i915_gem_detach_phys_object(dev, obj);
	}

	/* create a new object */
	if (!dev_priv->mm.phys_objs[id - 1]) {
		ret = i915_gem_init_phys_object(dev, id,
4961
						obj->base.size, align);
4962
		if (ret) {
4963 4964
			DRM_ERROR("failed to init phys object %d size: %zu\n",
				  id, obj->base.size);
4965
			return ret;
4966 4967 4968 4969
		}
	}

	/* bind to the object */
4970 4971
	obj->phys_obj = dev_priv->mm.phys_objs[id - 1];
	obj->phys_obj->cur_obj = obj;
4972

4973
	page_count = obj->base.size / PAGE_SIZE;
4974 4975

	for (i = 0; i < page_count; i++) {
4976 4977 4978 4979 4980 4981 4982
		struct page *page;
		char *dst, *src;

		page = read_cache_page_gfp(mapping, i,
					   GFP_HIGHUSER | __GFP_RECLAIMABLE);
		if (IS_ERR(page))
			return PTR_ERR(page);
4983

4984
		src = kmap_atomic(page);
4985
		dst = obj->phys_obj->handle->vaddr + (i * PAGE_SIZE);
4986
		memcpy(dst, src, PAGE_SIZE);
P
Peter Zijlstra 已提交
4987
		kunmap_atomic(src);
4988

4989 4990 4991
		mark_page_accessed(page);
		page_cache_release(page);
	}
4992

4993 4994 4995 4996
	return 0;
}

static int
4997 4998
i915_gem_phys_pwrite(struct drm_device *dev,
		     struct drm_i915_gem_object *obj,
4999 5000 5001
		     struct drm_i915_gem_pwrite *args,
		     struct drm_file *file_priv)
{
5002
	void *vaddr = obj->phys_obj->handle->vaddr + args->offset;
5003
	char __user *user_data = (char __user *) (uintptr_t) args->data_ptr;
5004

5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017
	if (__copy_from_user_inatomic_nocache(vaddr, user_data, args->size)) {
		unsigned long unwritten;

		/* The physical object once assigned is fixed for the lifetime
		 * of the obj, so we can safely drop the lock and continue
		 * to access vaddr.
		 */
		mutex_unlock(&dev->struct_mutex);
		unwritten = copy_from_user(vaddr, user_data, args->size);
		mutex_lock(&dev->struct_mutex);
		if (unwritten)
			return -EFAULT;
	}
5018

5019
	intel_gtt_chipset_flush();
5020 5021
	return 0;
}
5022

5023
void i915_gem_release(struct drm_device *dev, struct drm_file *file)
5024
{
5025
	struct drm_i915_file_private *file_priv = file->driver_priv;
5026 5027 5028 5029 5030

	/* Clean up our request list when the client is going away, so that
	 * later retire_requests won't dereference our soon-to-be-gone
	 * file_priv.
	 */
5031
	spin_lock(&file_priv->mm.lock);
5032 5033 5034 5035 5036 5037 5038 5039 5040
	while (!list_empty(&file_priv->mm.request_list)) {
		struct drm_i915_gem_request *request;

		request = list_first_entry(&file_priv->mm.request_list,
					   struct drm_i915_gem_request,
					   client_list);
		list_del(&request->client_list);
		request->file_priv = NULL;
	}
5041
	spin_unlock(&file_priv->mm.lock);
5042
}
5043

5044 5045 5046 5047 5048 5049 5050
static int
i915_gpu_is_active(struct drm_device *dev)
{
	drm_i915_private_t *dev_priv = dev->dev_private;
	int lists_empty;

	lists_empty = list_empty(&dev_priv->mm.flushing_list) &&
5051
		      list_empty(&dev_priv->mm.active_list);
5052 5053 5054 5055

	return !lists_empty;
}

5056
static int
5057 5058 5059
i915_gem_inactive_shrink(struct shrinker *shrinker,
			 int nr_to_scan,
			 gfp_t gfp_mask)
5060
{
5061 5062 5063 5064 5065 5066 5067 5068 5069
	struct drm_i915_private *dev_priv =
		container_of(shrinker,
			     struct drm_i915_private,
			     mm.inactive_shrinker);
	struct drm_device *dev = dev_priv->dev;
	struct drm_i915_gem_object *obj, *next;
	int cnt;

	if (!mutex_trylock(&dev->struct_mutex))
5070
		return 0;
5071 5072 5073

	/* "fast-path" to count number of available objects */
	if (nr_to_scan == 0) {
5074 5075 5076 5077 5078 5079 5080
		cnt = 0;
		list_for_each_entry(obj,
				    &dev_priv->mm.inactive_list,
				    mm_list)
			cnt++;
		mutex_unlock(&dev->struct_mutex);
		return cnt / 100 * sysctl_vfs_cache_pressure;
5081 5082
	}

5083
rescan:
5084
	/* first scan for clean buffers */
5085
	i915_gem_retire_requests(dev);
5086

5087 5088 5089 5090
	list_for_each_entry_safe(obj, next,
				 &dev_priv->mm.inactive_list,
				 mm_list) {
		if (i915_gem_object_is_purgeable(obj)) {
5091 5092
			if (i915_gem_object_unbind(obj) == 0 &&
			    --nr_to_scan == 0)
5093
				break;
5094 5095 5096 5097
		}
	}

	/* second pass, evict/count anything still on the inactive list */
5098 5099 5100 5101
	cnt = 0;
	list_for_each_entry_safe(obj, next,
				 &dev_priv->mm.inactive_list,
				 mm_list) {
5102 5103
		if (nr_to_scan &&
		    i915_gem_object_unbind(obj) == 0)
5104
			nr_to_scan--;
5105
		else
5106 5107 5108 5109
			cnt++;
	}

	if (nr_to_scan && i915_gpu_is_active(dev)) {
5110 5111 5112 5113 5114 5115
		/*
		 * We are desperate for pages, so as a last resort, wait
		 * for the GPU to finish and discard whatever we can.
		 * This has a dramatic impact to reduce the number of
		 * OOM-killer events whilst running the GPU aggressively.
		 */
5116
		if (i915_gpu_idle(dev) == 0)
5117 5118
			goto rescan;
	}
5119 5120
	mutex_unlock(&dev->struct_mutex);
	return cnt / 100 * sysctl_vfs_cache_pressure;
5121
}