i915_gem.c 130.6 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
						  bool 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
					     int 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 86
/* 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;
}

static void i915_gem_info_add_gtt(struct drm_i915_private *dev_priv,
87
				  struct drm_i915_gem_object *obj)
88 89
{
	dev_priv->mm.gtt_count++;
90 91
	dev_priv->mm.gtt_memory += obj->gtt_space->size;
	if (obj->gtt_offset < dev_priv->mm.gtt_mappable_end) {
92
		dev_priv->mm.mappable_gtt_used +=
93 94
			min_t(size_t, obj->gtt_space->size,
			      dev_priv->mm.gtt_mappable_end - obj->gtt_offset);
95
	}
D
Daniel Vetter 已提交
96
	list_add_tail(&obj->gtt_list, &dev_priv->mm.gtt_list);
97 98 99
}

static void i915_gem_info_remove_gtt(struct drm_i915_private *dev_priv,
100
				     struct drm_i915_gem_object *obj)
101 102
{
	dev_priv->mm.gtt_count--;
103 104
	dev_priv->mm.gtt_memory -= obj->gtt_space->size;
	if (obj->gtt_offset < dev_priv->mm.gtt_mappable_end) {
105
		dev_priv->mm.mappable_gtt_used -=
106 107
			min_t(size_t, obj->gtt_space->size,
			      dev_priv->mm.gtt_mappable_end - obj->gtt_offset);
108
	}
D
Daniel Vetter 已提交
109
	list_del_init(&obj->gtt_list);
110 111 112 113 114 115 116 117 118
}

/**
 * Update the mappable working set counters. Call _only_ when there is a change
 * in one of (pin|fault)_mappable and update *_mappable _before_ calling.
 * @mappable: new state the changed mappable flag (either pin_ or fault_).
 */
static void
i915_gem_info_update_mappable(struct drm_i915_private *dev_priv,
119
			      struct drm_i915_gem_object *obj,
120 121 122
			      bool mappable)
{
	if (mappable) {
123
		if (obj->pin_mappable && obj->fault_mappable)
124 125 126
			/* Combined state was already mappable. */
			return;
		dev_priv->mm.gtt_mappable_count++;
127
		dev_priv->mm.gtt_mappable_memory += obj->gtt_space->size;
128
	} else {
129
		if (obj->pin_mappable || obj->fault_mappable)
130 131 132
			/* Combined state still mappable. */
			return;
		dev_priv->mm.gtt_mappable_count--;
133
		dev_priv->mm.gtt_mappable_memory -= obj->gtt_space->size;
134
	}
135 136 137
}

static void i915_gem_info_add_pin(struct drm_i915_private *dev_priv,
138
				  struct drm_i915_gem_object *obj,
139
				  bool mappable)
140 141
{
	dev_priv->mm.pin_count++;
142
	dev_priv->mm.pin_memory += obj->gtt_space->size;
143
	if (mappable) {
144
		obj->pin_mappable = true;
145 146
		i915_gem_info_update_mappable(dev_priv, obj, true);
	}
147 148 149
}

static void i915_gem_info_remove_pin(struct drm_i915_private *dev_priv,
150
				     struct drm_i915_gem_object *obj)
151 152
{
	dev_priv->mm.pin_count--;
153 154 155
	dev_priv->mm.pin_memory -= obj->gtt_space->size;
	if (obj->pin_mappable) {
		obj->pin_mappable = false;
156 157
		i915_gem_info_update_mappable(dev_priv, obj, false);
	}
158 159
}

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
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;
}

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
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;
	}

208
	WARN_ON(i915_verify_lists(dev));
209 210
	return 0;
}
211

212
static inline bool
213
i915_gem_object_is_inactive(struct drm_i915_gem_object *obj)
214
{
215
	return obj->gtt_space && !obj->active && obj->pin_count == 0;
216 217
}

218 219
int i915_gem_do_init(struct drm_device *dev,
		     unsigned long start,
D
Daniel Vetter 已提交
220
		     unsigned long mappable_end,
J
Jesse Barnes 已提交
221
		     unsigned long end)
222 223 224
{
	drm_i915_private_t *dev_priv = dev->dev_private;

J
Jesse Barnes 已提交
225 226 227
	if (start >= end ||
	    (start & (PAGE_SIZE - 1)) != 0 ||
	    (end & (PAGE_SIZE - 1)) != 0) {
228 229 230
		return -EINVAL;
	}

J
Jesse Barnes 已提交
231 232
	drm_mm_init(&dev_priv->mm.gtt_space, start,
		    end - start);
233

234
	dev_priv->mm.gtt_total = end - start;
235
	dev_priv->mm.mappable_gtt_total = min(end, mappable_end) - start;
D
Daniel Vetter 已提交
236
	dev_priv->mm.gtt_mappable_end = mappable_end;
J
Jesse Barnes 已提交
237 238 239

	return 0;
}
240

J
Jesse Barnes 已提交
241 242
int
i915_gem_init_ioctl(struct drm_device *dev, void *data,
243
		    struct drm_file *file)
J
Jesse Barnes 已提交
244 245 246 247 248
{
	struct drm_i915_gem_init *args = data;
	int ret;

	mutex_lock(&dev->struct_mutex);
D
Daniel Vetter 已提交
249
	ret = i915_gem_do_init(dev, args->gtt_start, args->gtt_end, args->gtt_end);
250 251
	mutex_unlock(&dev->struct_mutex);

J
Jesse Barnes 已提交
252
	return ret;
253 254
}

255 256
int
i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
257
			    struct drm_file *file)
258
{
259
	struct drm_i915_private *dev_priv = dev->dev_private;
260 261 262 263 264
	struct drm_i915_gem_get_aperture *args = data;

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

265 266 267 268
	mutex_lock(&dev->struct_mutex);
	args->aper_size = dev_priv->mm.gtt_total;
	args->aper_available_size = args->aper_size - dev_priv->mm.pin_memory;
	mutex_unlock(&dev->struct_mutex);
269 270 271 272

	return 0;
}

273 274 275 276 277 278

/**
 * Creates a new mm object and returns a handle to it.
 */
int
i915_gem_create_ioctl(struct drm_device *dev, void *data,
279
		      struct drm_file *file)
280 281
{
	struct drm_i915_gem_create *args = data;
282
	struct drm_i915_gem_object *obj;
283 284
	int ret;
	u32 handle;
285 286 287 288

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

	/* Allocate the new object */
289
	obj = i915_gem_alloc_object(dev, args->size);
290 291 292
	if (obj == NULL)
		return -ENOMEM;

293
	ret = drm_gem_handle_create(file, &obj->base, &handle);
294
	if (ret) {
295 296
		drm_gem_object_release(&obj->base);
		i915_gem_info_remove_obj(dev->dev_private, obj->base.size);
297
		kfree(obj);
298
		return ret;
299
	}
300

301
	/* drop reference from allocate - handle holds it now */
302
	drm_gem_object_unreference(&obj->base);
303 304
	trace_i915_gem_object_create(obj);

305
	args->handle = handle;
306 307 308
	return 0;
}

309
static int i915_gem_object_needs_bit17_swizzle(struct drm_i915_gem_object *obj)
310
{
311
	drm_i915_private_t *dev_priv = obj->base.dev->dev_private;
312 313

	return dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_9_10_17 &&
314
		obj->tiling_mode != I915_TILING_NONE;
315 316
}

317
static inline void
318 319 320 321 322 323 324 325
slow_shmem_copy(struct page *dst_page,
		int dst_offset,
		struct page *src_page,
		int src_offset,
		int length)
{
	char *dst_vaddr, *src_vaddr;

326 327
	dst_vaddr = kmap(dst_page);
	src_vaddr = kmap(src_page);
328 329 330

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

331 332
	kunmap(src_page);
	kunmap(dst_page);
333 334
}

335
static inline void
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
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);
	}

355 356
	gpu_vaddr = kmap(gpu_page);
	cpu_vaddr = kmap(cpu_page);
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379

	/* 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;
	}

380 381
	kunmap(cpu_page);
	kunmap(gpu_page);
382 383
}

384 385 386 387 388 389
/**
 * 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
390 391
i915_gem_shmem_pread_fast(struct drm_device *dev,
			  struct drm_i915_gem_object *obj,
392
			  struct drm_i915_gem_pread *args,
393
			  struct drm_file *file)
394
{
395
	struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
396
	ssize_t remain;
397
	loff_t offset;
398 399 400 401 402 403 404 405 406
	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) {
407 408 409 410
		struct page *page;
		char *vaddr;
		int ret;

411 412 413 414 415 416 417 418 419 420
		/* 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;

421 422 423 424 425 426 427 428 429 430 431 432 433 434
		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)
435
			return -EFAULT;
436 437 438 439 440 441

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

442
	return 0;
443 444 445 446 447 448 449 450 451
}

/**
 * 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
452 453
i915_gem_shmem_pread_slow(struct drm_device *dev,
			  struct drm_i915_gem_object *obj,
454
			  struct drm_i915_gem_pread *args,
455
			  struct drm_file *file)
456
{
457
	struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
458 459 460 461 462
	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;
463 464
	int shmem_page_offset;
	int data_page_index, data_page_offset;
465 466 467
	int page_length;
	int ret;
	uint64_t data_ptr = args->data_ptr;
468
	int do_bit17_swizzling;
469 470 471 472 473 474 475 476 477 478 479

	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;

480
	user_pages = drm_malloc_ab(num_pages, sizeof(struct page *));
481 482 483
	if (user_pages == NULL)
		return -ENOMEM;

484
	mutex_unlock(&dev->struct_mutex);
485 486
	down_read(&mm->mmap_sem);
	pinned_pages = get_user_pages(current, mm, (uintptr_t)args->data_ptr,
487
				      num_pages, 1, 0, user_pages, NULL);
488
	up_read(&mm->mmap_sem);
489
	mutex_lock(&dev->struct_mutex);
490 491
	if (pinned_pages < num_pages) {
		ret = -EFAULT;
492
		goto out;
493 494
	}

495 496 497
	ret = i915_gem_object_set_cpu_read_domain_range(obj,
							args->offset,
							args->size);
498
	if (ret)
499
		goto out;
500

501
	do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
502 503 504 505

	offset = args->offset;

	while (remain > 0) {
506 507
		struct page *page;

508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
		/* 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;

525 526 527 528 529
		page = read_cache_page_gfp(mapping, offset >> PAGE_SHIFT,
					   GFP_HIGHUSER | __GFP_RECLAIMABLE);
		if (IS_ERR(page))
			return PTR_ERR(page);

530
		if (do_bit17_swizzling) {
531
			slow_shmem_bit17_copy(page,
532
					      shmem_page_offset,
533 534 535 536 537 538 539
					      user_pages[data_page_index],
					      data_page_offset,
					      page_length,
					      1);
		} else {
			slow_shmem_copy(user_pages[data_page_index],
					data_page_offset,
540
					page,
541 542
					shmem_page_offset,
					page_length);
543
		}
544

545 546 547
		mark_page_accessed(page);
		page_cache_release(page);

548 549 550 551 552
		remain -= page_length;
		data_ptr += page_length;
		offset += page_length;
	}

553
out:
554 555
	for (i = 0; i < pinned_pages; i++) {
		SetPageDirty(user_pages[i]);
556
		mark_page_accessed(user_pages[i]);
557 558
		page_cache_release(user_pages[i]);
	}
559
	drm_free_large(user_pages);
560 561 562 563

	return ret;
}

564 565 566 567 568 569 570
/**
 * 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,
571
		     struct drm_file *file)
572 573
{
	struct drm_i915_gem_pread *args = data;
574
	struct drm_i915_gem_object *obj;
575
	int ret = 0;
576

577 578 579 580 581 582 583 584 585 586 587 588 589
	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;

590
	ret = i915_mutex_lock_interruptible(dev);
591
	if (ret)
592
		return ret;
593

594
	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
595 596 597
	if (obj == NULL) {
		ret = -ENOENT;
		goto unlock;
598
	}
599

600
	/* Bounds check source.  */
601 602
	if (args->offset > obj->base.size ||
	    args->size > obj->base.size - args->offset) {
C
Chris Wilson 已提交
603
		ret = -EINVAL;
604
		goto out;
C
Chris Wilson 已提交
605 606
	}

607 608 609 610
	ret = i915_gem_object_set_cpu_read_domain_range(obj,
							args->offset,
							args->size);
	if (ret)
611
		goto out;
612 613 614

	ret = -EFAULT;
	if (!i915_gem_object_needs_bit17_swizzle(obj))
615
		ret = i915_gem_shmem_pread_fast(dev, obj, args, file);
616
	if (ret == -EFAULT)
617
		ret = i915_gem_shmem_pread_slow(dev, obj, args, file);
618

619
out:
620
	drm_gem_object_unreference(&obj->base);
621
unlock:
622
	mutex_unlock(&dev->struct_mutex);
623
	return ret;
624 625
}

626 627
/* This is the fast write path which cannot handle
 * page faults in the source data
628
 */
629 630 631 632 633 634

static inline int
fast_user_write(struct io_mapping *mapping,
		loff_t page_base, int page_offset,
		char __user *user_data,
		int length)
635 636
{
	char *vaddr_atomic;
637
	unsigned long unwritten;
638

P
Peter Zijlstra 已提交
639
	vaddr_atomic = io_mapping_map_atomic_wc(mapping, page_base);
640 641
	unwritten = __copy_from_user_inatomic_nocache(vaddr_atomic + page_offset,
						      user_data, length);
P
Peter Zijlstra 已提交
642
	io_mapping_unmap_atomic(vaddr_atomic);
643
	return unwritten;
644 645 646 647 648 649
}

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

650
static inline void
651 652 653 654
slow_kernel_write(struct io_mapping *mapping,
		  loff_t gtt_base, int gtt_offset,
		  struct page *user_page, int user_offset,
		  int length)
655
{
656 657
	char __iomem *dst_vaddr;
	char *src_vaddr;
658

659 660 661 662 663 664 665 666 667
	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);
668 669
}

670 671 672 673
/**
 * This is the fast pwrite path, where we copy the data directly from the
 * user into the GTT, uncached.
 */
674
static int
675 676
i915_gem_gtt_pwrite_fast(struct drm_device *dev,
			 struct drm_i915_gem_object *obj,
677
			 struct drm_i915_gem_pwrite *args,
678
			 struct drm_file *file)
679
{
680
	drm_i915_private_t *dev_priv = dev->dev_private;
681
	ssize_t remain;
682
	loff_t offset, page_base;
683
	char __user *user_data;
684
	int page_offset, page_length;
685 686 687 688

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

689
	offset = obj->gtt_offset + args->offset;
690 691 692 693

	while (remain > 0) {
		/* Operation in this page
		 *
694 695 696
		 * page_base = page offset within aperture
		 * page_offset = offset within page
		 * page_length = bytes to copy for this page
697
		 */
698 699 700 701 702 703 704
		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
705 706
		 * source page isn't available.  Return the error and we'll
		 * retry in the slow path.
707
		 */
708 709 710 711
		if (fast_user_write(dev_priv->mm.gtt_mapping, page_base,
				    page_offset, user_data, page_length))

			return -EFAULT;
712

713 714 715
		remain -= page_length;
		user_data += page_length;
		offset += page_length;
716 717
	}

718
	return 0;
719 720
}

721 722 723 724 725 726 727
/**
 * 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).
 */
728
static int
729 730
i915_gem_gtt_pwrite_slow(struct drm_device *dev,
			 struct drm_i915_gem_object *obj,
731
			 struct drm_i915_gem_pwrite *args,
732
			 struct drm_file *file)
733
{
734 735 736 737 738 739 740 741
	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;
742
	int ret;
743 744 745 746 747 748 749 750 751 752 753 754
	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;

755
	user_pages = drm_malloc_ab(num_pages, sizeof(struct page *));
756 757 758
	if (user_pages == NULL)
		return -ENOMEM;

759
	mutex_unlock(&dev->struct_mutex);
760 761 762 763
	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);
764
	mutex_lock(&dev->struct_mutex);
765 766 767 768
	if (pinned_pages < num_pages) {
		ret = -EFAULT;
		goto out_unpin_pages;
	}
769

770 771
	ret = i915_gem_object_set_to_gtt_domain(obj, 1);
	if (ret)
772
		goto out_unpin_pages;
773

774
	offset = obj->gtt_offset + args->offset;
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795

	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;

796 797 798 799 800
		slow_kernel_write(dev_priv->mm.gtt_mapping,
				  gtt_page_base, gtt_page_offset,
				  user_pages[data_page_index],
				  data_page_offset,
				  page_length);
801 802 803 804 805 806 807 808 809

		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]);
810
	drm_free_large(user_pages);
811 812 813 814

	return ret;
}

815 816 817 818
/**
 * This is the fast shmem pwrite path, which attempts to directly
 * copy_from_user into the kmapped pages backing the object.
 */
819
static int
820 821
i915_gem_shmem_pwrite_fast(struct drm_device *dev,
			   struct drm_i915_gem_object *obj,
822
			   struct drm_i915_gem_pwrite *args,
823
			   struct drm_file *file)
824
{
825
	struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
826
	ssize_t remain;
827
	loff_t offset;
828 829 830 831 832
	char __user *user_data;
	int page_offset, page_length;

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

834
	offset = args->offset;
835
	obj->dirty = 1;
836 837

	while (remain > 0) {
838 839 840 841
		struct page *page;
		char *vaddr;
		int ret;

842 843 844 845 846 847 848 849 850 851
		/* 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;

852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
		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)
872
			return -EFAULT;
873 874 875 876 877 878

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

879
	return 0;
880 881 882 883 884 885 886 887 888 889
}

/**
 * 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
890 891
i915_gem_shmem_pwrite_slow(struct drm_device *dev,
			   struct drm_i915_gem_object *obj,
892
			   struct drm_i915_gem_pwrite *args,
893
			   struct drm_file *file)
894
{
895
	struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
896 897 898 899 900
	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;
901
	int shmem_page_offset;
902 903 904 905
	int data_page_index,  data_page_offset;
	int page_length;
	int ret;
	uint64_t data_ptr = args->data_ptr;
906
	int do_bit17_swizzling;
907 908 909 910 911 912 913 914 915 916 917

	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;

918
	user_pages = drm_malloc_ab(num_pages, sizeof(struct page *));
919 920 921
	if (user_pages == NULL)
		return -ENOMEM;

922
	mutex_unlock(&dev->struct_mutex);
923 924 925 926
	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);
927
	mutex_lock(&dev->struct_mutex);
928 929
	if (pinned_pages < num_pages) {
		ret = -EFAULT;
930
		goto out;
931 932
	}

933
	ret = i915_gem_object_set_to_cpu_domain(obj, 1);
934
	if (ret)
935
		goto out;
936

937
	do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
938

939
	offset = args->offset;
940
	obj->dirty = 1;
941

942
	while (remain > 0) {
943 944
		struct page *page;

945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
		/* 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;

962 963 964 965 966 967 968
		page = read_cache_page_gfp(mapping, offset >> PAGE_SHIFT,
					   GFP_HIGHUSER | __GFP_RECLAIMABLE);
		if (IS_ERR(page)) {
			ret = PTR_ERR(page);
			goto out;
		}

969
		if (do_bit17_swizzling) {
970
			slow_shmem_bit17_copy(page,
971 972 973
					      shmem_page_offset,
					      user_pages[data_page_index],
					      data_page_offset,
974 975 976
					      page_length,
					      0);
		} else {
977
			slow_shmem_copy(page,
978 979 980 981
					shmem_page_offset,
					user_pages[data_page_index],
					data_page_offset,
					page_length);
982
		}
983

984 985 986 987
		set_page_dirty(page);
		mark_page_accessed(page);
		page_cache_release(page);

988 989 990
		remain -= page_length;
		data_ptr += page_length;
		offset += page_length;
991 992
	}

993
out:
994 995
	for (i = 0; i < pinned_pages; i++)
		page_cache_release(user_pages[i]);
996
	drm_free_large(user_pages);
997

998
	return ret;
999 1000 1001 1002 1003 1004 1005 1006 1007
}

/**
 * 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,
1008
		      struct drm_file *file)
1009 1010
{
	struct drm_i915_gem_pwrite *args = data;
1011
	struct drm_i915_gem_object *obj;
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
	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;
1026

1027
	ret = i915_mutex_lock_interruptible(dev);
1028
	if (ret)
1029
		return ret;
1030

1031
	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
1032 1033 1034
	if (obj == NULL) {
		ret = -ENOENT;
		goto unlock;
1035
	}
1036

1037
	/* Bounds check destination. */
1038 1039
	if (args->offset > obj->base.size ||
	    args->size > obj->base.size - args->offset) {
C
Chris Wilson 已提交
1040
		ret = -EINVAL;
1041
		goto out;
C
Chris Wilson 已提交
1042 1043
	}

1044 1045 1046 1047 1048 1049
	/* 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.
	 */
1050
	if (obj->phys_obj)
1051
		ret = i915_gem_phys_pwrite(dev, obj, args, file);
1052 1053 1054
	else if (obj->tiling_mode == I915_TILING_NONE &&
		 obj->gtt_space &&
		 obj->base.write_domain != I915_GEM_DOMAIN_CPU) {
1055
		ret = i915_gem_object_pin(obj, 0, true);
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
		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);
1069
	} else {
1070 1071
		ret = i915_gem_object_set_to_cpu_domain(obj, 1);
		if (ret)
1072
			goto out;
1073

1074 1075 1076 1077 1078 1079
		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);
	}
1080

1081
out:
1082
	drm_gem_object_unreference(&obj->base);
1083
unlock:
1084
	mutex_unlock(&dev->struct_mutex);
1085 1086 1087 1088
	return ret;
}

/**
1089 1090
 * Called when user space prepares to use an object with the CPU, either
 * through the mmap ioctl's mapping or a GTT mapping.
1091 1092 1093
 */
int
i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
1094
			  struct drm_file *file)
1095
{
1096
	struct drm_i915_private *dev_priv = dev->dev_private;
1097
	struct drm_i915_gem_set_domain *args = data;
1098
	struct drm_i915_gem_object *obj;
1099 1100
	uint32_t read_domains = args->read_domains;
	uint32_t write_domain = args->write_domain;
1101 1102 1103 1104 1105
	int ret;

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

1106
	/* Only handle setting domains to types used by the CPU. */
1107
	if (write_domain & I915_GEM_GPU_DOMAINS)
1108 1109
		return -EINVAL;

1110
	if (read_domains & I915_GEM_GPU_DOMAINS)
1111 1112 1113 1114 1115 1116 1117 1118
		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;

1119
	ret = i915_mutex_lock_interruptible(dev);
1120
	if (ret)
1121
		return ret;
1122

1123
	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
1124 1125 1126
	if (obj == NULL) {
		ret = -ENOENT;
		goto unlock;
1127
	}
1128

1129 1130
	intel_mark_busy(dev, obj);

1131 1132
	if (read_domains & I915_GEM_DOMAIN_GTT) {
		ret = i915_gem_object_set_to_gtt_domain(obj, write_domain != 0);
1133

1134 1135 1136
		/* Update the LRU on the fence for the CPU access that's
		 * about to occur.
		 */
1137
		if (obj->fence_reg != I915_FENCE_REG_NONE) {
1138
			struct drm_i915_fence_reg *reg =
1139
				&dev_priv->fence_regs[obj->fence_reg];
1140
			list_move_tail(&reg->lru_list,
1141 1142 1143
				       &dev_priv->mm.fence_list);
		}

1144 1145 1146 1147 1148 1149
		/* 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;
1150
	} else {
1151
		ret = i915_gem_object_set_to_cpu_domain(obj, write_domain != 0);
1152 1153
	}

1154
	/* Maintain LRU order of "inactive" objects */
1155 1156
	if (ret == 0 && i915_gem_object_is_inactive(obj))
		list_move_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
1157

1158
	drm_gem_object_unreference(&obj->base);
1159
unlock:
1160 1161 1162 1163 1164 1165 1166 1167 1168
	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,
1169
			 struct drm_file *file)
1170 1171
{
	struct drm_i915_gem_sw_finish *args = data;
1172
	struct drm_i915_gem_object *obj;
1173 1174 1175 1176 1177
	int ret = 0;

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

1178
	ret = i915_mutex_lock_interruptible(dev);
1179
	if (ret)
1180
		return ret;
1181

1182
	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
1183
	if (obj == NULL) {
1184 1185
		ret = -ENOENT;
		goto unlock;
1186 1187 1188
	}

	/* Pinned buffers may be scanout, so flush the cache */
1189
	if (obj->pin_count)
1190 1191
		i915_gem_object_flush_cpu_write_domain(obj);

1192
	drm_gem_object_unreference(&obj->base);
1193
unlock:
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
	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,
1207
		    struct drm_file *file)
1208
{
1209
	struct drm_i915_private *dev_priv = dev->dev_private;
1210 1211 1212 1213 1214 1215 1216 1217
	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;

1218
	obj = drm_gem_object_lookup(dev, file, args->handle);
1219
	if (obj == NULL)
1220
		return -ENOENT;
1221

1222 1223 1224 1225 1226
	if (obj->size > dev_priv->mm.gtt_mappable_end) {
		drm_gem_object_unreference_unlocked(obj);
		return -E2BIG;
	}

1227 1228 1229 1230 1231 1232 1233
	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);
1234
	drm_gem_object_unreference_unlocked(obj);
1235 1236 1237 1238 1239 1240 1241 1242
	if (IS_ERR((void *)addr))
		return addr;

	args->addr_ptr = (uint64_t) addr;

	return 0;
}

1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
/**
 * 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)
{
1261 1262
	struct drm_i915_gem_object *obj = to_intel_bo(vma->vm_private_data);
	struct drm_device *dev = obj->base.dev;
1263
	drm_i915_private_t *dev_priv = dev->dev_private;
1264 1265 1266
	pgoff_t page_offset;
	unsigned long pfn;
	int ret = 0;
1267
	bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
1268 1269 1270 1271 1272 1273 1274

	/* 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);
1275
	BUG_ON(obj->pin_count && !obj->pin_mappable);
1276

1277 1278
	if (obj->gtt_space) {
		if (!obj->map_and_fenceable) {
1279 1280 1281 1282 1283
			ret = i915_gem_object_unbind(obj);
			if (ret)
				goto unlock;
		}
	}
1284

1285
	if (!obj->gtt_space) {
1286
		ret = i915_gem_object_bind_to_gtt(obj, 0, true);
1287 1288
		if (ret)
			goto unlock;
1289 1290
	}

1291 1292 1293 1294
	ret = i915_gem_object_set_to_gtt_domain(obj, write);
	if (ret)
		goto unlock;

1295 1296 1297
	if (!obj->fault_mappable) {
		obj->fault_mappable = true;
		i915_gem_info_update_mappable(dev_priv, obj, true);
1298 1299
	}

1300
	/* Need a new fence register? */
1301
	if (obj->tiling_mode != I915_TILING_NONE) {
1302
		ret = i915_gem_object_get_fence_reg(obj, true);
1303 1304
		if (ret)
			goto unlock;
1305
	}
1306

1307 1308
	if (i915_gem_object_is_inactive(obj))
		list_move_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
1309

1310
	pfn = ((dev->agp->base + obj->gtt_offset) >> PAGE_SHIFT) +
1311 1312 1313 1314
		page_offset;

	/* Finally, remap it using the new GTT offset */
	ret = vm_insert_pfn(vma, (unsigned long)vmf->virtual_address, pfn);
1315
unlock:
1316 1317 1318
	mutex_unlock(&dev->struct_mutex);

	switch (ret) {
1319 1320
	case -EAGAIN:
		set_need_resched();
1321 1322 1323
	case 0:
	case -ERESTARTSYS:
		return VM_FAULT_NOPAGE;
1324 1325 1326
	case -ENOMEM:
		return VM_FAULT_OOM;
	default:
1327
		return VM_FAULT_SIGBUS;
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
	}
}

/**
 * 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
1343
i915_gem_create_mmap_offset(struct drm_i915_gem_object *obj)
1344
{
1345
	struct drm_device *dev = obj->base.dev;
1346 1347
	struct drm_gem_mm *mm = dev->mm_private;
	struct drm_map_list *list;
1348
	struct drm_local_map *map;
1349 1350 1351
	int ret = 0;

	/* Set the object up for mmap'ing */
1352
	list = &obj->base.map_list;
1353
	list->map = kzalloc(sizeof(struct drm_map_list), GFP_KERNEL);
1354 1355 1356 1357 1358
	if (!list->map)
		return -ENOMEM;

	map = list->map;
	map->type = _DRM_GEM;
1359
	map->size = obj->base.size;
1360 1361 1362 1363
	map->handle = obj;

	/* Get a DRM GEM mmap offset allocated... */
	list->file_offset_node = drm_mm_search_free(&mm->offset_manager,
1364 1365
						    obj->base.size / PAGE_SIZE,
						    0, 0);
1366
	if (!list->file_offset_node) {
1367 1368
		DRM_ERROR("failed to allocate offset for bo %d\n",
			  obj->base.name);
1369
		ret = -ENOSPC;
1370 1371 1372 1373
		goto out_free_list;
	}

	list->file_offset_node = drm_mm_get_block(list->file_offset_node,
1374 1375
						  obj->base.size / PAGE_SIZE,
						  0);
1376 1377 1378 1379 1380 1381
	if (!list->file_offset_node) {
		ret = -ENOMEM;
		goto out_free_list;
	}

	list->hash.key = list->file_offset_node->start;
1382 1383
	ret = drm_ht_insert_item(&mm->offset_hash, &list->hash);
	if (ret) {
1384 1385 1386 1387 1388 1389 1390 1391 1392
		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:
1393
	kfree(list->map);
C
Chris Wilson 已提交
1394
	list->map = NULL;
1395 1396 1397 1398

	return ret;
}

1399 1400 1401 1402
/**
 * i915_gem_release_mmap - remove physical page mappings
 * @obj: obj in question
 *
1403
 * Preserve the reservation of the mmapping with the DRM core code, but
1404 1405 1406 1407 1408 1409 1410 1411 1412
 * 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().
 */
1413
void
1414
i915_gem_release_mmap(struct drm_i915_gem_object *obj)
1415
{
1416
	struct drm_device *dev = obj->base.dev;
1417
	struct drm_i915_private *dev_priv = dev->dev_private;
1418

1419
	if (unlikely(obj->base.map_list.map && dev->dev_mapping))
1420
		unmap_mapping_range(dev->dev_mapping,
1421 1422
				    (loff_t)obj->base.map_list.hash.key<<PAGE_SHIFT,
				    obj->base.size, 1);
1423

1424 1425 1426
	if (obj->fault_mappable) {
		obj->fault_mappable = false;
		i915_gem_info_update_mappable(dev_priv, obj, false);
1427
	}
1428 1429
}

1430
static void
1431
i915_gem_free_mmap_offset(struct drm_i915_gem_object *obj)
1432
{
1433
	struct drm_device *dev = obj->base.dev;
1434
	struct drm_gem_mm *mm = dev->mm_private;
1435
	struct drm_map_list *list = &obj->base.map_list;
1436 1437

	drm_ht_remove_item(&mm->offset_hash, &list->hash);
C
Chris Wilson 已提交
1438 1439 1440
	drm_mm_put_block(list->file_offset_node);
	kfree(list->map);
	list->map = NULL;
1441 1442
}

1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
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;
}

1465 1466 1467 1468 1469
/**
 * 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
1470
 * potential fence register mapping.
1471 1472
 */
static uint32_t
1473
i915_gem_get_gtt_alignment(struct drm_i915_gem_object *obj)
1474
{
1475
	struct drm_device *dev = obj->base.dev;
1476 1477 1478 1479 1480

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

1485 1486 1487 1488
	/*
	 * Previous chips need to be aligned to the size of the smallest
	 * fence register that can contain the object.
	 */
1489
	return i915_gem_get_gtt_size(obj);
1490 1491
}

1492 1493 1494 1495 1496 1497 1498 1499 1500
/**
 * 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
1501
i915_gem_get_unfenced_gtt_alignment(struct drm_i915_gem_object *obj)
1502
{
1503
	struct drm_device *dev = obj->base.dev;
1504 1505 1506 1507 1508 1509
	int tile_height;

	/*
	 * Minimum alignment is 4k (GTT page size) for sane hw.
	 */
	if (INTEL_INFO(dev)->gen >= 4 || IS_G33(dev) ||
1510
	    obj->tiling_mode == I915_TILING_NONE)
1511 1512 1513 1514 1515 1516 1517 1518
		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) ||
1519
	    (obj->tiling_mode == I915_TILING_Y && HAS_128_BYTE_Y_TILING(dev)))
1520 1521 1522 1523
		tile_height = 32;
	else
		tile_height = 8;

1524
	return tile_height * obj->stride * 2;
1525 1526
}

1527 1528 1529 1530
/**
 * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
 * @dev: DRM device
 * @data: GTT mapping ioctl data
1531
 * @file: GEM object info
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
 *
 * 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,
1544
			struct drm_file *file)
1545
{
1546
	struct drm_i915_private *dev_priv = dev->dev_private;
1547
	struct drm_i915_gem_mmap_gtt *args = data;
1548
	struct drm_i915_gem_object *obj;
1549 1550 1551 1552 1553
	int ret;

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

1554
	ret = i915_mutex_lock_interruptible(dev);
1555
	if (ret)
1556
		return ret;
1557

1558
	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
1559 1560 1561 1562
	if (obj == NULL) {
		ret = -ENOENT;
		goto unlock;
	}
1563

1564
	if (obj->base.size > dev_priv->mm.gtt_mappable_end) {
1565 1566 1567 1568
		ret = -E2BIG;
		goto unlock;
	}

1569
	if (obj->madv != I915_MADV_WILLNEED) {
1570
		DRM_ERROR("Attempting to mmap a purgeable buffer\n");
1571 1572
		ret = -EINVAL;
		goto out;
1573 1574
	}

1575
	if (!obj->base.map_list.map) {
1576
		ret = i915_gem_create_mmap_offset(obj);
1577 1578
		if (ret)
			goto out;
1579 1580
	}

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

1583
out:
1584
	drm_gem_object_unreference(&obj->base);
1585
unlock:
1586
	mutex_unlock(&dev->struct_mutex);
1587
	return ret;
1588 1589
}

1590
static int
1591
i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj,
1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
			      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.
	 */
1602 1603 1604 1605
	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)
1606 1607
		return -ENOMEM;

1608
	inode = obj->base.filp->f_path.dentry->d_inode;
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
	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;

1619
		obj->pages[i] = page;
1620 1621
	}

1622
	if (obj->tiling_mode != I915_TILING_NONE)
1623 1624 1625 1626 1627 1628
		i915_gem_object_do_bit_17_swizzle(obj);

	return 0;

err_pages:
	while (i--)
1629
		page_cache_release(obj->pages[i]);
1630

1631 1632
	drm_free_large(obj->pages);
	obj->pages = NULL;
1633 1634 1635
	return PTR_ERR(page);
}

1636
static void
1637
i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj)
1638
{
1639
	int page_count = obj->base.size / PAGE_SIZE;
1640 1641
	int i;

1642
	BUG_ON(obj->madv == __I915_MADV_PURGED);
1643

1644
	if (obj->tiling_mode != I915_TILING_NONE)
1645 1646
		i915_gem_object_save_bit_17_swizzle(obj);

1647 1648
	if (obj->madv == I915_MADV_DONTNEED)
		obj->dirty = 0;
1649 1650

	for (i = 0; i < page_count; i++) {
1651 1652
		if (obj->dirty)
			set_page_dirty(obj->pages[i]);
1653

1654 1655
		if (obj->madv == I915_MADV_WILLNEED)
			mark_page_accessed(obj->pages[i]);
1656

1657
		page_cache_release(obj->pages[i]);
1658
	}
1659
	obj->dirty = 0;
1660

1661 1662
	drm_free_large(obj->pages);
	obj->pages = NULL;
1663 1664
}

1665 1666 1667 1668 1669
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;
1670
	return ring->outstanding_lazy_request = dev_priv->next_seqno;
1671 1672
}

1673
static void
1674
i915_gem_object_move_to_active(struct drm_i915_gem_object *obj,
1675
			       struct intel_ring_buffer *ring)
1676
{
1677
	struct drm_device *dev = obj->base.dev;
1678
	struct drm_i915_private *dev_priv = dev->dev_private;
1679
	uint32_t seqno = i915_gem_next_request_seqno(dev, ring);
1680

1681
	BUG_ON(ring == NULL);
1682
	obj->ring = ring;
1683 1684

	/* Add a reference if we're newly entering the active list. */
1685 1686 1687
	if (!obj->active) {
		drm_gem_object_reference(&obj->base);
		obj->active = 1;
1688
	}
1689

1690
	/* Move from whatever list we were on to the tail of execution. */
1691 1692 1693
	list_move_tail(&obj->mm_list, &dev_priv->mm.active_list);
	list_move_tail(&obj->ring_list, &ring->active_list);
	obj->last_rendering_seqno = seqno;
1694 1695
}

1696
static void
1697
i915_gem_object_move_to_flushing(struct drm_i915_gem_object *obj)
1698
{
1699
	struct drm_device *dev = obj->base.dev;
1700 1701
	drm_i915_private_t *dev_priv = dev->dev_private;

1702 1703 1704 1705
	BUG_ON(!obj->active);
	list_move_tail(&obj->mm_list, &dev_priv->mm.flushing_list);
	list_del_init(&obj->ring_list);
	obj->last_rendering_seqno = 0;
1706
}
1707

1708 1709
/* Immediately discard the backing storage */
static void
1710
i915_gem_object_truncate(struct drm_i915_gem_object *obj)
1711
{
C
Chris Wilson 已提交
1712
	struct inode *inode;
1713

1714 1715 1716 1717 1718 1719
	/* 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.
	 */
1720
	inode = obj->base.filp->f_path.dentry->d_inode;
1721 1722 1723
	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 已提交
1724

1725
	obj->madv = __I915_MADV_PURGED;
1726 1727 1728
}

static inline int
1729
i915_gem_object_is_purgeable(struct drm_i915_gem_object *obj)
1730
{
1731
	return obj->madv == I915_MADV_DONTNEED;
1732 1733
}

1734
static void
1735
i915_gem_object_move_to_inactive(struct drm_i915_gem_object *obj)
1736
{
1737
	struct drm_device *dev = obj->base.dev;
1738 1739
	drm_i915_private_t *dev_priv = dev->dev_private;

1740 1741
	if (obj->pin_count != 0)
		list_move_tail(&obj->mm_list, &dev_priv->mm.pinned_list);
1742
	else
1743 1744
		list_move_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
	list_del_init(&obj->ring_list);
1745

1746
	BUG_ON(!list_empty(&obj->gpu_write_list));
1747

1748 1749 1750 1751 1752
	obj->last_rendering_seqno = 0;
	obj->ring = NULL;
	if (obj->active) {
		obj->active = 0;
		drm_gem_object_unreference(&obj->base);
1753
	}
1754
	WARN_ON(i915_verify_lists(dev));
1755 1756
}

1757 1758
static void
i915_gem_process_flushing_list(struct drm_device *dev,
1759
			       uint32_t flush_domains,
1760
			       struct intel_ring_buffer *ring)
1761 1762
{
	drm_i915_private_t *dev_priv = dev->dev_private;
1763
	struct drm_i915_gem_object *obj, *next;
1764

1765
	list_for_each_entry_safe(obj, next,
1766
				 &ring->gpu_write_list,
1767
				 gpu_write_list) {
1768 1769
		if (obj->base.write_domain & flush_domains) {
			uint32_t old_write_domain = obj->base.write_domain;
1770

1771 1772
			obj->base.write_domain = 0;
			list_del_init(&obj->gpu_write_list);
1773
			i915_gem_object_move_to_active(obj, ring);
1774 1775

			/* update the fence lru list */
1776
			if (obj->fence_reg != I915_FENCE_REG_NONE) {
1777
				struct drm_i915_fence_reg *reg =
1778
					&dev_priv->fence_regs[obj->fence_reg];
1779
				list_move_tail(&reg->lru_list,
1780
						&dev_priv->mm.fence_list);
1781
			}
1782 1783

			trace_i915_gem_object_change_domain(obj,
1784
							    obj->base.read_domains,
1785 1786 1787 1788
							    old_write_domain);
		}
	}
}
1789

1790
int
1791
i915_add_request(struct drm_device *dev,
1792
		 struct drm_file *file,
C
Chris Wilson 已提交
1793
		 struct drm_i915_gem_request *request,
1794
		 struct intel_ring_buffer *ring)
1795 1796
{
	drm_i915_private_t *dev_priv = dev->dev_private;
1797
	struct drm_i915_file_private *file_priv = NULL;
1798 1799
	uint32_t seqno;
	int was_empty;
1800 1801 1802
	int ret;

	BUG_ON(request == NULL);
1803

1804 1805
	if (file != NULL)
		file_priv = file->driver_priv;
1806

1807 1808 1809
	ret = ring->add_request(ring, &seqno);
	if (ret)
	    return ret;
1810

1811
	ring->outstanding_lazy_request = false;
1812 1813

	request->seqno = seqno;
1814
	request->ring = ring;
1815
	request->emitted_jiffies = jiffies;
1816 1817 1818
	was_empty = list_empty(&ring->request_list);
	list_add_tail(&request->list, &ring->request_list);

1819
	if (file_priv) {
1820
		spin_lock(&file_priv->mm.lock);
1821
		request->file_priv = file_priv;
1822
		list_add_tail(&request->client_list,
1823
			      &file_priv->mm.request_list);
1824
		spin_unlock(&file_priv->mm.lock);
1825
	}
1826

B
Ben Gamari 已提交
1827
	if (!dev_priv->mm.suspended) {
1828 1829
		mod_timer(&dev_priv->hangcheck_timer,
			  jiffies + msecs_to_jiffies(DRM_I915_HANGCHECK_PERIOD));
B
Ben Gamari 已提交
1830
		if (was_empty)
1831 1832
			queue_delayed_work(dev_priv->wq,
					   &dev_priv->mm.retire_work, HZ);
B
Ben Gamari 已提交
1833
	}
1834
	return 0;
1835 1836 1837 1838 1839 1840 1841 1842
}

/**
 * Command execution barrier
 *
 * Ensures that all commands in the ring are finished
 * before signalling the CPU
 */
1843
static void
1844
i915_retire_commands(struct drm_device *dev, struct intel_ring_buffer *ring)
1845 1846 1847 1848
{
	uint32_t flush_domains = 0;

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

1852
	ring->flush(ring, I915_GEM_DOMAIN_COMMAND, flush_domains);
1853 1854
}

1855 1856
static inline void
i915_gem_request_remove_from_client(struct drm_i915_gem_request *request)
1857
{
1858
	struct drm_i915_file_private *file_priv = request->file_priv;
1859

1860 1861
	if (!file_priv)
		return;
C
Chris Wilson 已提交
1862

1863 1864 1865 1866
	spin_lock(&file_priv->mm.lock);
	list_del(&request->client_list);
	request->file_priv = NULL;
	spin_unlock(&file_priv->mm.lock);
1867 1868
}

1869 1870
static void i915_gem_reset_ring_lists(struct drm_i915_private *dev_priv,
				      struct intel_ring_buffer *ring)
1871
{
1872 1873
	while (!list_empty(&ring->request_list)) {
		struct drm_i915_gem_request *request;
1874

1875 1876 1877
		request = list_first_entry(&ring->request_list,
					   struct drm_i915_gem_request,
					   list);
1878

1879
		list_del(&request->list);
1880
		i915_gem_request_remove_from_client(request);
1881 1882
		kfree(request);
	}
1883

1884
	while (!list_empty(&ring->active_list)) {
1885
		struct drm_i915_gem_object *obj;
1886

1887 1888 1889
		obj = list_first_entry(&ring->active_list,
				       struct drm_i915_gem_object,
				       ring_list);
1890

1891 1892 1893
		obj->base.write_domain = 0;
		list_del_init(&obj->gpu_write_list);
		i915_gem_object_move_to_inactive(obj);
1894 1895 1896
	}
}

1897
void i915_gem_reset(struct drm_device *dev)
1898
{
1899
	struct drm_i915_private *dev_priv = dev->dev_private;
1900
	struct drm_i915_gem_object *obj;
1901
	int i;
1902

1903
	i915_gem_reset_ring_lists(dev_priv, &dev_priv->render_ring);
1904
	i915_gem_reset_ring_lists(dev_priv, &dev_priv->bsd_ring);
1905
	i915_gem_reset_ring_lists(dev_priv, &dev_priv->blt_ring);
1906 1907 1908 1909 1910 1911

	/* 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)) {
1912 1913 1914
		obj= list_first_entry(&dev_priv->mm.flushing_list,
				      struct drm_i915_gem_object,
				      mm_list);
1915

1916 1917 1918
		obj->base.write_domain = 0;
		list_del_init(&obj->gpu_write_list);
		i915_gem_object_move_to_inactive(obj);
1919 1920 1921 1922 1923
	}

	/* Move everything out of the GPU domains to ensure we do any
	 * necessary invalidation upon reuse.
	 */
1924
	list_for_each_entry(obj,
1925
			    &dev_priv->mm.inactive_list,
1926
			    mm_list)
1927
	{
1928
		obj->base.read_domains &= ~I915_GEM_GPU_DOMAINS;
1929
	}
1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940

	/* The fence registers are invalidated so clear them out */
	for (i = 0; i < 16; i++) {
		struct drm_i915_fence_reg *reg;

		reg = &dev_priv->fence_regs[i];
		if (!reg->obj)
			continue;

		i915_gem_clear_fence_reg(reg->obj);
	}
1941 1942 1943 1944 1945
}

/**
 * This function clears the request list as sequence numbers are passed.
 */
1946 1947 1948
static void
i915_gem_retire_requests_ring(struct drm_device *dev,
			      struct intel_ring_buffer *ring)
1949 1950 1951 1952
{
	drm_i915_private_t *dev_priv = dev->dev_private;
	uint32_t seqno;

1953 1954
	if (!ring->status_page.page_addr ||
	    list_empty(&ring->request_list))
1955 1956
		return;

1957
	WARN_ON(i915_verify_lists(dev));
1958

1959
	seqno = ring->get_seqno(ring);
1960
	while (!list_empty(&ring->request_list)) {
1961 1962
		struct drm_i915_gem_request *request;

1963
		request = list_first_entry(&ring->request_list,
1964 1965 1966
					   struct drm_i915_gem_request,
					   list);

1967
		if (!i915_seqno_passed(seqno, request->seqno))
1968 1969 1970 1971 1972
			break;

		trace_i915_gem_request_retire(dev, request->seqno);

		list_del(&request->list);
1973
		i915_gem_request_remove_from_client(request);
1974 1975
		kfree(request);
	}
1976

1977 1978 1979 1980
	/* 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)) {
1981
		struct drm_i915_gem_object *obj;
1982

1983 1984 1985
		obj= list_first_entry(&ring->active_list,
				      struct drm_i915_gem_object,
				      ring_list);
1986

1987
		if (!i915_seqno_passed(seqno, obj->last_rendering_seqno))
1988
			break;
1989

1990
		if (obj->base.write_domain != 0)
1991 1992 1993
			i915_gem_object_move_to_flushing(obj);
		else
			i915_gem_object_move_to_inactive(obj);
1994
	}
1995 1996 1997

	if (unlikely (dev_priv->trace_irq_seqno &&
		      i915_seqno_passed(dev_priv->trace_irq_seqno, seqno))) {
1998
		ring->user_irq_put(ring);
1999 2000
		dev_priv->trace_irq_seqno = 0;
	}
2001 2002

	WARN_ON(i915_verify_lists(dev));
2003 2004
}

2005 2006 2007 2008 2009
void
i915_gem_retire_requests(struct drm_device *dev)
{
	drm_i915_private_t *dev_priv = dev->dev_private;

2010
	if (!list_empty(&dev_priv->mm.deferred_free_list)) {
2011
	    struct drm_i915_gem_object *obj, *next;
2012 2013 2014 2015 2016 2017

	    /* We must be careful that during unbind() we do not
	     * accidentally infinitely recurse into retire requests.
	     * Currently:
	     *   retire -> free -> unbind -> wait -> retire_ring
	     */
2018
	    list_for_each_entry_safe(obj, next,
2019
				     &dev_priv->mm.deferred_free_list,
2020
				     mm_list)
2021
		    i915_gem_free_object_tail(obj);
2022 2023
	}

2024
	i915_gem_retire_requests_ring(dev, &dev_priv->render_ring);
2025
	i915_gem_retire_requests_ring(dev, &dev_priv->bsd_ring);
2026
	i915_gem_retire_requests_ring(dev, &dev_priv->blt_ring);
2027 2028
}

2029
static void
2030 2031 2032 2033 2034 2035 2036 2037 2038
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;

2039 2040 2041 2042 2043 2044
	/* 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;
	}

2045
	i915_gem_retire_requests(dev);
2046

2047
	if (!dev_priv->mm.suspended &&
2048
		(!list_empty(&dev_priv->render_ring.request_list) ||
2049 2050
		 !list_empty(&dev_priv->bsd_ring.request_list) ||
		 !list_empty(&dev_priv->blt_ring.request_list)))
2051
		queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, HZ);
2052 2053 2054
	mutex_unlock(&dev->struct_mutex);
}

2055
int
2056
i915_do_wait_request(struct drm_device *dev, uint32_t seqno,
2057
		     bool interruptible, struct intel_ring_buffer *ring)
2058 2059
{
	drm_i915_private_t *dev_priv = dev->dev_private;
2060
	u32 ier;
2061 2062 2063 2064
	int ret = 0;

	BUG_ON(seqno == 0);

2065
	if (atomic_read(&dev_priv->mm.wedged))
2066 2067
		return -EAGAIN;

2068
	if (seqno == ring->outstanding_lazy_request) {
2069 2070 2071 2072
		struct drm_i915_gem_request *request;

		request = kzalloc(sizeof(*request), GFP_KERNEL);
		if (request == NULL)
2073
			return -ENOMEM;
2074 2075 2076 2077 2078 2079 2080 2081

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

		seqno = request->seqno;
2082
	}
2083

2084
	if (!i915_seqno_passed(ring->get_seqno(ring), seqno)) {
2085
		if (HAS_PCH_SPLIT(dev))
2086 2087 2088
			ier = I915_READ(DEIER) | I915_READ(GTIER);
		else
			ier = I915_READ(IER);
2089 2090 2091 2092 2093 2094 2095
		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 已提交
2096 2097
		trace_i915_gem_request_wait_begin(dev, seqno);

2098
		ring->waiting_seqno = seqno;
2099
		ring->user_irq_get(ring);
2100
		if (interruptible)
2101
			ret = wait_event_interruptible(ring->irq_queue,
2102
				i915_seqno_passed(ring->get_seqno(ring), seqno)
2103
				|| atomic_read(&dev_priv->mm.wedged));
2104
		else
2105
			wait_event(ring->irq_queue,
2106
				i915_seqno_passed(ring->get_seqno(ring), seqno)
2107
				|| atomic_read(&dev_priv->mm.wedged));
2108

2109
		ring->user_irq_put(ring);
2110
		ring->waiting_seqno = 0;
C
Chris Wilson 已提交
2111 2112

		trace_i915_gem_request_wait_end(dev, seqno);
2113
	}
2114
	if (atomic_read(&dev_priv->mm.wedged))
2115
		ret = -EAGAIN;
2116 2117

	if (ret && ret != -ERESTARTSYS)
2118
		DRM_ERROR("%s returns %d (awaiting %d at %d, next %d)\n",
2119
			  __func__, ret, seqno, ring->get_seqno(ring),
2120
			  dev_priv->next_seqno);
2121 2122 2123 2124 2125 2126 2127

	/* 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)
2128
		i915_gem_retire_requests_ring(dev, ring);
2129 2130 2131 2132

	return ret;
}

2133 2134 2135 2136 2137
/**
 * Waits for a sequence number to be signaled, and cleans up the
 * request and object lists appropriately for that event.
 */
static int
2138
i915_wait_request(struct drm_device *dev, uint32_t seqno,
2139
		  struct intel_ring_buffer *ring)
2140
{
2141
	return i915_do_wait_request(dev, seqno, 1, ring);
2142 2143
}

2144
static void
2145 2146 2147 2148 2149
i915_gem_flush_ring(struct drm_device *dev,
		    struct intel_ring_buffer *ring,
		    uint32_t invalidate_domains,
		    uint32_t flush_domains)
{
2150
	ring->flush(ring, invalidate_domains, flush_domains);
2151 2152 2153
	i915_gem_process_flushing_list(dev, flush_domains, ring);
}

2154 2155 2156
static void
i915_gem_flush(struct drm_device *dev,
	       uint32_t invalidate_domains,
2157 2158
	       uint32_t flush_domains,
	       uint32_t flush_rings)
2159 2160
{
	drm_i915_private_t *dev_priv = dev->dev_private;
2161

2162
	if (flush_domains & I915_GEM_DOMAIN_CPU)
2163
		intel_gtt_chipset_flush();
2164

2165 2166
	if ((flush_domains | invalidate_domains) & I915_GEM_GPU_DOMAINS) {
		if (flush_rings & RING_RENDER)
2167
			i915_gem_flush_ring(dev, &dev_priv->render_ring,
2168 2169
					    invalidate_domains, flush_domains);
		if (flush_rings & RING_BSD)
2170
			i915_gem_flush_ring(dev, &dev_priv->bsd_ring,
2171
					    invalidate_domains, flush_domains);
2172
		if (flush_rings & RING_BLT)
2173
			i915_gem_flush_ring(dev, &dev_priv->blt_ring,
2174
					    invalidate_domains, flush_domains);
2175
	}
2176 2177
}

2178 2179 2180 2181 2182
/**
 * 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
2183
i915_gem_object_wait_rendering(struct drm_i915_gem_object *obj,
2184
			       bool interruptible)
2185
{
2186
	struct drm_device *dev = obj->base.dev;
2187 2188
	int ret;

2189 2190
	/* This function only exists to support waiting for existing rendering,
	 * not for emitting required flushes.
2191
	 */
2192
	BUG_ON((obj->base.write_domain & I915_GEM_GPU_DOMAINS) != 0);
2193 2194 2195 2196

	/* If there is rendering queued on the buffer being evicted, wait for
	 * it.
	 */
2197
	if (obj->active) {
2198
		ret = i915_do_wait_request(dev,
2199
					   obj->last_rendering_seqno,
2200
					   interruptible,
2201
					   obj->ring);
2202
		if (ret)
2203 2204 2205 2206 2207 2208 2209 2210 2211
			return ret;
	}

	return 0;
}

/**
 * Unbinds an object from the GTT aperture.
 */
2212
int
2213
i915_gem_object_unbind(struct drm_i915_gem_object *obj)
2214
{
2215
	struct drm_device *dev = obj->base.dev;
2216
	struct drm_i915_private *dev_priv = dev->dev_private;
2217 2218
	int ret = 0;

2219
	if (obj->gtt_space == NULL)
2220 2221
		return 0;

2222
	if (obj->pin_count != 0) {
2223 2224 2225 2226
		DRM_ERROR("Attempting to unbind pinned buffer\n");
		return -EINVAL;
	}

2227 2228 2229
	/* blow away mappings if mapped through GTT */
	i915_gem_release_mmap(obj);

2230 2231 2232 2233 2234 2235
	/* 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.
	 */
2236
	ret = i915_gem_object_set_to_cpu_domain(obj, 1);
2237
	if (ret == -ERESTARTSYS)
2238
		return ret;
2239 2240 2241 2242
	/* 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.
	 */
2243 2244
	if (ret) {
		i915_gem_clflush_object(obj);
2245
		obj->base.read_domains = obj->base.write_domain = I915_GEM_DOMAIN_CPU;
2246
	}
2247

2248
	/* release the fence reg _after_ flushing */
2249
	if (obj->fence_reg != I915_FENCE_REG_NONE)
2250 2251
		i915_gem_clear_fence_reg(obj);

2252
	i915_gem_gtt_unbind_object(obj);
2253

2254
	i915_gem_object_put_pages_gtt(obj);
2255

2256 2257
	i915_gem_info_remove_gtt(dev_priv, obj);
	list_del_init(&obj->mm_list);
2258
	/* Avoid an unnecessary call to unbind on rebind. */
2259
	obj->map_and_fenceable = true;
2260

2261 2262 2263
	drm_mm_put_block(obj->gtt_space);
	obj->gtt_space = NULL;
	obj->gtt_offset = 0;
2264

2265
	if (i915_gem_object_is_purgeable(obj))
2266 2267
		i915_gem_object_truncate(obj);

C
Chris Wilson 已提交
2268 2269
	trace_i915_gem_object_unbind(obj);

2270
	return ret;
2271 2272
}

2273 2274 2275
static int i915_ring_idle(struct drm_device *dev,
			  struct intel_ring_buffer *ring)
{
2276
	if (list_empty(&ring->gpu_write_list) && list_empty(&ring->active_list))
2277 2278
		return 0;

2279
	i915_gem_flush_ring(dev, ring,
2280 2281 2282 2283 2284 2285
			    I915_GEM_GPU_DOMAINS, I915_GEM_GPU_DOMAINS);
	return i915_wait_request(dev,
				 i915_gem_next_request_seqno(dev, ring),
				 ring);
}

2286
int
2287 2288 2289 2290
i915_gpu_idle(struct drm_device *dev)
{
	drm_i915_private_t *dev_priv = dev->dev_private;
	bool lists_empty;
2291
	int ret;
2292

2293
	lists_empty = (list_empty(&dev_priv->mm.flushing_list) &&
2294
		       list_empty(&dev_priv->mm.active_list));
2295 2296 2297 2298
	if (lists_empty)
		return 0;

	/* Flush everything onto the inactive list. */
2299
	ret = i915_ring_idle(dev, &dev_priv->render_ring);
2300 2301
	if (ret)
		return ret;
2302

2303 2304 2305
	ret = i915_ring_idle(dev, &dev_priv->bsd_ring);
	if (ret)
		return ret;
2306

2307 2308 2309
	ret = i915_ring_idle(dev, &dev_priv->blt_ring);
	if (ret)
		return ret;
2310

2311
	return 0;
2312 2313
}

2314
static void sandybridge_write_fence_reg(struct drm_i915_gem_object *obj)
2315
{
2316
	struct drm_device *dev = obj->base.dev;
2317
	drm_i915_private_t *dev_priv = dev->dev_private;
2318 2319
	u32 size = obj->gtt_space->size;
	int regnum = obj->fence_reg;
2320 2321
	uint64_t val;

2322
	val = (uint64_t)((obj->gtt_offset + size - 4096) &
2323
		    0xfffff000) << 32;
2324 2325
	val |= obj->gtt_offset & 0xfffff000;
	val |= (uint64_t)((obj->stride / 128) - 1) <<
2326 2327
		SANDYBRIDGE_FENCE_PITCH_SHIFT;

2328
	if (obj->tiling_mode == I915_TILING_Y)
2329 2330 2331 2332 2333 2334
		val |= 1 << I965_FENCE_TILING_Y_SHIFT;
	val |= I965_FENCE_REG_VALID;

	I915_WRITE64(FENCE_REG_SANDYBRIDGE_0 + (regnum * 8), val);
}

2335
static void i965_write_fence_reg(struct drm_i915_gem_object *obj)
2336
{
2337
	struct drm_device *dev = obj->base.dev;
2338
	drm_i915_private_t *dev_priv = dev->dev_private;
2339 2340
	u32 size = obj->gtt_space->size;
	int regnum = obj->fence_reg;
2341 2342
	uint64_t val;

2343
	val = (uint64_t)((obj->gtt_offset + size - 4096) &
2344
		    0xfffff000) << 32;
2345 2346 2347
	val |= obj->gtt_offset & 0xfffff000;
	val |= ((obj->stride / 128) - 1) << I965_FENCE_PITCH_SHIFT;
	if (obj->tiling_mode == I915_TILING_Y)
2348 2349 2350 2351 2352 2353
		val |= 1 << I965_FENCE_TILING_Y_SHIFT;
	val |= I965_FENCE_REG_VALID;

	I915_WRITE64(FENCE_REG_965_0 + (regnum * 8), val);
}

2354
static void i915_write_fence_reg(struct drm_i915_gem_object *obj)
2355
{
2356
	struct drm_device *dev = obj->base.dev;
2357
	drm_i915_private_t *dev_priv = dev->dev_private;
2358
	u32 size = obj->gtt_space->size;
2359
	uint32_t fence_reg, val, pitch_val;
2360
	int tile_width;
2361

2362 2363
	if ((obj->gtt_offset & ~I915_FENCE_START_MASK) ||
	    (obj->gtt_offset & (size - 1))) {
2364
		WARN(1, "%s: object 0x%08x [fenceable? %d] not 1M or size (0x%08x) aligned [gtt_space offset=%lx, size=%lx]\n",
2365 2366
		     __func__, obj->gtt_offset, obj->map_and_fenceable, size,
		     obj->gtt_space->start, obj->gtt_space->size);
2367 2368 2369
		return;
	}

2370
	if (obj->tiling_mode == I915_TILING_Y &&
2371 2372
	    HAS_128_BYTE_Y_TILING(dev))
		tile_width = 128;
2373
	else
2374 2375 2376
		tile_width = 512;

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

2380
	if (obj->tiling_mode == I915_TILING_Y &&
2381 2382 2383 2384 2385
	    HAS_128_BYTE_Y_TILING(dev))
		WARN_ON(pitch_val > I830_FENCE_MAX_PITCH_VAL);
	else
		WARN_ON(pitch_val > I915_FENCE_MAX_PITCH_VAL);

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

2393
	fence_reg = obj->fence_reg;
2394 2395
	if (fence_reg < 8)
		fence_reg = FENCE_REG_830_0 + fence_reg * 4;
2396
	else
2397
		fence_reg = FENCE_REG_945_8 + (fence_reg - 8) * 4;
2398
	I915_WRITE(fence_reg, val);
2399 2400
}

2401
static void i830_write_fence_reg(struct drm_i915_gem_object *obj)
2402
{
2403
	struct drm_device *dev = obj->base.dev;
2404
	drm_i915_private_t *dev_priv = dev->dev_private;
2405 2406
	u32 size = obj->gtt_space->size;
	int regnum = obj->fence_reg;
2407 2408
	uint32_t val;
	uint32_t pitch_val;
2409
	uint32_t fence_size_bits;
2410

2411 2412
	if ((obj->gtt_offset & ~I830_FENCE_START_MASK) ||
	    (obj->gtt_offset & (obj->base.size - 1))) {
2413
		WARN(1, "%s: object 0x%08x not 512K or size aligned\n",
2414
		     __func__, obj->gtt_offset);
2415 2416 2417
		return;
	}

2418
	pitch_val = obj->stride / 128;
2419 2420 2421
	pitch_val = ffs(pitch_val) - 1;
	WARN_ON(pitch_val > I830_FENCE_MAX_PITCH_VAL);

2422 2423
	val = obj->gtt_offset;
	if (obj->tiling_mode == I915_TILING_Y)
2424
		val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2425
	fence_size_bits = I830_FENCE_SIZE_BITS(size);
2426 2427
	WARN_ON(fence_size_bits & ~0x00000f00);
	val |= fence_size_bits;
2428 2429 2430 2431 2432 2433
	val |= pitch_val << I830_FENCE_PITCH_SHIFT;
	val |= I830_FENCE_REG_VALID;

	I915_WRITE(FENCE_REG_830_0 + (regnum * 4), val);
}

2434 2435
static int i915_find_fence_reg(struct drm_device *dev,
			       bool interruptible)
2436 2437
{
	struct drm_i915_private *dev_priv = dev->dev_private;
2438
	struct drm_i915_fence_reg *reg;
2439
	struct drm_i915_gem_object *obj = NULL;
2440 2441 2442 2443 2444 2445 2446 2447 2448
	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;

2449 2450
		if (!reg->obj->pin_count)
			avail++;
2451 2452 2453 2454 2455 2456
	}

	if (avail == 0)
		return -ENOSPC;

	/* None available, try to steal one or wait for a user to finish */
2457
	avail = I915_FENCE_REG_NONE;
2458 2459
	list_for_each_entry(reg, &dev_priv->mm.fence_list,
			    lru_list) {
2460 2461
		obj = reg->obj;
		if (obj->pin_count)
2462 2463 2464
			continue;

		/* found one! */
2465
		avail = obj->fence_reg;
2466 2467 2468
		break;
	}

2469
	BUG_ON(avail == I915_FENCE_REG_NONE);
2470 2471 2472 2473 2474

	/* 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. */
2475 2476 2477
	drm_gem_object_reference(&obj->base);
	ret = i915_gem_object_put_fence_reg(obj, interruptible);
	drm_gem_object_unreference(&obj->base);
2478 2479 2480
	if (ret != 0)
		return ret;

2481
	return avail;
2482 2483
}

2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496
/**
 * 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.
 */
2497
int
2498
i915_gem_object_get_fence_reg(struct drm_i915_gem_object *obj,
2499
			      bool interruptible)
2500
{
2501
	struct drm_device *dev = obj->base.dev;
J
Jesse Barnes 已提交
2502
	struct drm_i915_private *dev_priv = dev->dev_private;
2503
	struct drm_i915_fence_reg *reg = NULL;
2504
	int ret;
2505

2506
	/* Just update our place in the LRU if our fence is getting used. */
2507 2508
	if (obj->fence_reg != I915_FENCE_REG_NONE) {
		reg = &dev_priv->fence_regs[obj->fence_reg];
2509
		list_move_tail(&reg->lru_list, &dev_priv->mm.fence_list);
2510 2511 2512
		return 0;
	}

2513
	switch (obj->tiling_mode) {
2514 2515 2516 2517
	case I915_TILING_NONE:
		WARN(1, "allocating a fence for non-tiled object?\n");
		break;
	case I915_TILING_X:
2518
		if (!obj->stride)
2519
			return -EINVAL;
2520
		WARN((obj->stride & (512 - 1)),
2521
		     "object 0x%08x is X tiled but has non-512B pitch\n",
2522
		     obj->gtt_offset);
2523 2524
		break;
	case I915_TILING_Y:
2525
		if (!obj->stride)
2526
			return -EINVAL;
2527
		WARN((obj->stride & (128 - 1)),
2528
		     "object 0x%08x is Y tiled but has non-128B pitch\n",
2529
		     obj->gtt_offset);
2530 2531 2532
		break;
	}

2533
	ret = i915_find_fence_reg(dev, interruptible);
2534 2535
	if (ret < 0)
		return ret;
2536

2537 2538
	obj->fence_reg = ret;
	reg = &dev_priv->fence_regs[obj->fence_reg];
2539
	list_add_tail(&reg->lru_list, &dev_priv->mm.fence_list);
2540

2541 2542
	reg->obj = obj;

2543 2544
	switch (INTEL_INFO(dev)->gen) {
	case 6:
2545
		sandybridge_write_fence_reg(obj);
2546 2547 2548
		break;
	case 5:
	case 4:
2549
		i965_write_fence_reg(obj);
2550 2551
		break;
	case 3:
2552
		i915_write_fence_reg(obj);
2553 2554
		break;
	case 2:
2555
		i830_write_fence_reg(obj);
2556 2557
		break;
	}
2558

2559
	trace_i915_gem_object_get_fence(obj,
2560 2561
					obj->fence_reg,
					obj->tiling_mode);
C
Chris Wilson 已提交
2562

2563
	return 0;
2564 2565 2566 2567 2568 2569 2570
}

/**
 * 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
2571
 * data structures in dev_priv and obj.
2572 2573
 */
static void
2574
i915_gem_clear_fence_reg(struct drm_i915_gem_object *obj)
2575
{
2576
	struct drm_device *dev = obj->base.dev;
J
Jesse Barnes 已提交
2577
	drm_i915_private_t *dev_priv = dev->dev_private;
2578
	struct drm_i915_fence_reg *reg = &dev_priv->fence_regs[obj->fence_reg];
2579
	uint32_t fence_reg;
2580

2581 2582
	switch (INTEL_INFO(dev)->gen) {
	case 6:
2583
		I915_WRITE64(FENCE_REG_SANDYBRIDGE_0 +
2584
			     (obj->fence_reg * 8), 0);
2585 2586 2587
		break;
	case 5:
	case 4:
2588
		I915_WRITE64(FENCE_REG_965_0 + (obj->fence_reg * 8), 0);
2589 2590
		break;
	case 3:
2591 2592
		if (obj->fence_reg >= 8)
			fence_reg = FENCE_REG_945_8 + (obj->fence_reg - 8) * 4;
2593
		else
2594
	case 2:
2595
			fence_reg = FENCE_REG_830_0 + obj->fence_reg * 4;
2596 2597

		I915_WRITE(fence_reg, 0);
2598
		break;
2599
	}
2600

2601
	reg->obj = NULL;
2602
	obj->fence_reg = I915_FENCE_REG_NONE;
2603
	list_del_init(&reg->lru_list);
2604 2605
}

2606 2607 2608 2609
/**
 * 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.
2610
 * @bool: whether the wait upon the fence is interruptible
2611 2612
 *
 * Zeroes out the fence register itself and clears out the associated
2613
 * data structures in dev_priv and obj.
2614 2615
 */
int
2616
i915_gem_object_put_fence_reg(struct drm_i915_gem_object *obj,
2617
			      bool interruptible)
2618
{
2619
	struct drm_device *dev = obj->base.dev;
C
Chris Wilson 已提交
2620 2621
	struct drm_i915_private *dev_priv = dev->dev_private;
	struct drm_i915_fence_reg *reg;
2622

2623
	if (obj->fence_reg == I915_FENCE_REG_NONE)
2624 2625
		return 0;

2626 2627 2628 2629 2630 2631
	/* 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);

2632 2633 2634 2635
	/* 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.
	 */
2636
	reg = &dev_priv->fence_regs[obj->fence_reg];
C
Chris Wilson 已提交
2637
	if (reg->gpu) {
2638 2639
		int ret;

2640
		ret = i915_gem_object_flush_gpu_write_domain(obj, true);
2641
		if (ret)
2642 2643
			return ret;

2644
		ret = i915_gem_object_wait_rendering(obj, interruptible);
2645
		if (ret)
2646
			return ret;
C
Chris Wilson 已提交
2647 2648

		reg->gpu = false;
2649 2650
	}

2651
	i915_gem_object_flush_gtt_write_domain(obj);
2652
	i915_gem_clear_fence_reg(obj);
2653 2654 2655 2656

	return 0;
}

2657 2658 2659 2660
/**
 * Finds free space in the GTT aperture and binds the object there.
 */
static int
2661
i915_gem_object_bind_to_gtt(struct drm_i915_gem_object *obj,
2662
			    unsigned alignment,
2663
			    bool map_and_fenceable)
2664
{
2665
	struct drm_device *dev = obj->base.dev;
2666 2667
	drm_i915_private_t *dev_priv = dev->dev_private;
	struct drm_mm_node *free_space;
2668
	gfp_t gfpmask = __GFP_NORETRY | __GFP_NOWARN;
2669
	u32 size, fence_size, fence_alignment, unfenced_alignment;
2670
	bool mappable, fenceable;
2671
	int ret;
2672

2673
	if (obj->madv != I915_MADV_WILLNEED) {
2674 2675 2676 2677
		DRM_ERROR("Attempting to bind a purgeable object\n");
		return -EINVAL;
	}

2678 2679 2680
	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);
2681

2682
	if (alignment == 0)
2683 2684
		alignment = map_and_fenceable ? fence_alignment :
						unfenced_alignment;
2685
	if (map_and_fenceable && alignment & (fence_alignment - 1)) {
2686 2687 2688 2689
		DRM_ERROR("Invalid object alignment requested %u\n", alignment);
		return -EINVAL;
	}

2690
	size = map_and_fenceable ? fence_size : obj->base.size;
2691

2692 2693 2694
	/* If the object is bigger than the entire aperture, reject it early
	 * before evicting everything in a vain attempt to find space.
	 */
2695
	if (obj->base.size >
2696
	    (map_and_fenceable ? dev_priv->mm.gtt_mappable_end : dev_priv->mm.gtt_total)) {
2697 2698 2699 2700
		DRM_ERROR("Attempting to bind an object larger than the aperture\n");
		return -E2BIG;
	}

2701
 search_free:
2702
	if (map_and_fenceable)
2703 2704
		free_space =
			drm_mm_search_free_in_range(&dev_priv->mm.gtt_space,
2705
						    size, alignment, 0,
2706 2707 2708 2709
						    dev_priv->mm.gtt_mappable_end,
						    0);
	else
		free_space = drm_mm_search_free(&dev_priv->mm.gtt_space,
2710
						size, alignment, 0);
2711 2712

	if (free_space != NULL) {
2713
		if (map_and_fenceable)
2714
			obj->gtt_space =
2715
				drm_mm_get_block_range_generic(free_space,
2716
							       size, alignment, 0,
2717 2718 2719
							       dev_priv->mm.gtt_mappable_end,
							       0);
		else
2720
			obj->gtt_space =
2721
				drm_mm_get_block(free_space, size, alignment);
2722
	}
2723
	if (obj->gtt_space == NULL) {
2724 2725 2726
		/* If the gtt is empty and we're still having trouble
		 * fitting our object in, we're out of memory.
		 */
2727 2728
		ret = i915_gem_evict_something(dev, size, alignment,
					       map_and_fenceable);
2729
		if (ret)
2730
			return ret;
2731

2732 2733 2734
		goto search_free;
	}

2735
	ret = i915_gem_object_get_pages_gtt(obj, gfpmask);
2736
	if (ret) {
2737 2738
		drm_mm_put_block(obj->gtt_space);
		obj->gtt_space = NULL;
2739 2740 2741

		if (ret == -ENOMEM) {
			/* first try to clear up some space from the GTT */
2742
			ret = i915_gem_evict_something(dev, size,
2743 2744
						       alignment,
						       map_and_fenceable);
2745 2746
			if (ret) {
				/* now try to shrink everyone else */
2747 2748 2749
				if (gfpmask) {
					gfpmask = 0;
					goto search_free;
2750 2751 2752 2753 2754 2755 2756 2757
				}

				return ret;
			}

			goto search_free;
		}

2758 2759 2760
		return ret;
	}

2761 2762
	ret = i915_gem_gtt_bind_object(obj);
	if (ret) {
2763
		i915_gem_object_put_pages_gtt(obj);
2764 2765
		drm_mm_put_block(obj->gtt_space);
		obj->gtt_space = NULL;
2766

2767
		ret = i915_gem_evict_something(dev, size,
2768
					       alignment, map_and_fenceable);
2769
		if (ret)
2770 2771 2772
			return ret;

		goto search_free;
2773 2774
	}

2775
	obj->gtt_offset = obj->gtt_space->start;
2776

2777
	/* keep track of bounds object by adding it to the inactive list */
2778 2779
	list_add_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
	i915_gem_info_add_gtt(dev_priv, obj);
2780

2781 2782 2783 2784
	/* 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
	 */
2785 2786
	BUG_ON(obj->base.read_domains & I915_GEM_GPU_DOMAINS);
	BUG_ON(obj->base.write_domain & I915_GEM_GPU_DOMAINS);
2787

2788
	trace_i915_gem_object_bind(obj, obj->gtt_offset, map_and_fenceable);
C
Chris Wilson 已提交
2789

2790
	fenceable =
2791 2792
		obj->gtt_space->size == fence_size &&
		(obj->gtt_space->start & (fence_alignment -1)) == 0;
2793

2794
	mappable =
2795
		obj->gtt_offset + obj->base.size <= dev_priv->mm.gtt_mappable_end;
2796

2797
	obj->map_and_fenceable = mappable && fenceable;
2798

2799 2800 2801 2802
	return 0;
}

void
2803
i915_gem_clflush_object(struct drm_i915_gem_object *obj)
2804 2805 2806 2807 2808
{
	/* 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.
	 */
2809
	if (obj->pages == NULL)
2810 2811
		return;

C
Chris Wilson 已提交
2812
	trace_i915_gem_object_clflush(obj);
2813

2814
	drm_clflush_pages(obj->pages, obj->base.size / PAGE_SIZE);
2815 2816
}

2817
/** Flushes any GPU write domain for the object if it's dirty. */
2818
static int
2819
i915_gem_object_flush_gpu_write_domain(struct drm_i915_gem_object *obj,
2820
				       bool pipelined)
2821
{
2822
	struct drm_device *dev = obj->base.dev;
2823

2824
	if ((obj->base.write_domain & I915_GEM_GPU_DOMAINS) == 0)
2825
		return 0;
2826 2827

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

2831 2832 2833
	if (pipelined)
		return 0;

2834
	return i915_gem_object_wait_rendering(obj, true);
2835 2836 2837 2838
}

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

2843
	if (obj->base.write_domain != I915_GEM_DOMAIN_GTT)
2844 2845 2846 2847 2848 2849
		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.
	 */
2850 2851
	i915_gem_release_mmap(obj);

2852 2853
	old_write_domain = obj->base.write_domain;
	obj->base.write_domain = 0;
C
Chris Wilson 已提交
2854 2855

	trace_i915_gem_object_change_domain(obj,
2856
					    obj->base.read_domains,
C
Chris Wilson 已提交
2857
					    old_write_domain);
2858 2859 2860 2861
}

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

2866
	if (obj->base.write_domain != I915_GEM_DOMAIN_CPU)
2867 2868 2869
		return;

	i915_gem_clflush_object(obj);
2870
	intel_gtt_chipset_flush();
2871 2872
	old_write_domain = obj->base.write_domain;
	obj->base.write_domain = 0;
C
Chris Wilson 已提交
2873 2874

	trace_i915_gem_object_change_domain(obj,
2875
					    obj->base.read_domains,
C
Chris Wilson 已提交
2876
					    old_write_domain);
2877 2878
}

2879 2880 2881 2882 2883 2884
/**
 * 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 已提交
2885
int
2886
i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, int write)
2887
{
C
Chris Wilson 已提交
2888
	uint32_t old_write_domain, old_read_domains;
2889
	int ret;
2890

2891
	/* Not valid to be called on unbound objects. */
2892
	if (obj->gtt_space == NULL)
2893 2894
		return -EINVAL;

2895
	ret = i915_gem_object_flush_gpu_write_domain(obj, false);
2896 2897 2898
	if (ret != 0)
		return ret;

2899
	i915_gem_object_flush_cpu_write_domain(obj);
C
Chris Wilson 已提交
2900

2901
	if (write) {
2902
		ret = i915_gem_object_wait_rendering(obj, true);
2903 2904 2905
		if (ret)
			return ret;
	}
2906

2907 2908
	old_write_domain = obj->base.write_domain;
	old_read_domains = obj->base.read_domains;
C
Chris Wilson 已提交
2909

2910 2911 2912
	/* It should now be out of any other write domains, and we can update
	 * the domain values for our changes.
	 */
2913 2914
	BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
	obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
2915
	if (write) {
2916 2917 2918
		obj->base.read_domains = I915_GEM_DOMAIN_GTT;
		obj->base.write_domain = I915_GEM_DOMAIN_GTT;
		obj->dirty = 1;
2919 2920
	}

C
Chris Wilson 已提交
2921 2922 2923 2924
	trace_i915_gem_object_change_domain(obj,
					    old_read_domains,
					    old_write_domain);

2925 2926 2927
	return 0;
}

2928 2929 2930 2931 2932
/*
 * Prepare buffer for display plane. Use uninterruptible for possible flush
 * wait, as in modesetting process we're not supposed to be interrupted.
 */
int
2933
i915_gem_object_set_to_display_plane(struct drm_i915_gem_object *obj,
2934
				     bool pipelined)
2935
{
2936
	uint32_t old_read_domains;
2937 2938 2939
	int ret;

	/* Not valid to be called on unbound objects. */
2940
	if (obj->gtt_space == NULL)
2941 2942
		return -EINVAL;

2943
	ret = i915_gem_object_flush_gpu_write_domain(obj, true);
2944 2945
	if (ret)
		return ret;
2946

2947 2948 2949 2950
	/* Currently, we are always called from an non-interruptible context. */
	if (!pipelined) {
		ret = i915_gem_object_wait_rendering(obj, false);
		if (ret)
2951 2952 2953
			return ret;
	}

2954 2955
	i915_gem_object_flush_cpu_write_domain(obj);

2956 2957
	old_read_domains = obj->base.read_domains;
	obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
2958 2959 2960

	trace_i915_gem_object_change_domain(obj,
					    old_read_domains,
2961
					    obj->base.write_domain);
2962 2963 2964 2965

	return 0;
}

2966 2967 2968 2969 2970 2971 2972 2973
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)
2974
		i915_gem_flush_ring(obj->base.dev, obj->ring,
2975 2976
				    0, obj->base.write_domain);

2977
	return i915_gem_object_wait_rendering(obj, interruptible);
2978 2979
}

2980 2981 2982 2983 2984 2985 2986
/**
 * 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
2987
i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj, int write)
2988
{
C
Chris Wilson 已提交
2989
	uint32_t old_write_domain, old_read_domains;
2990 2991
	int ret;

2992
	ret = i915_gem_object_flush_gpu_write_domain(obj, false);
2993 2994
	if (ret != 0)
		return ret;
2995

2996
	i915_gem_object_flush_gtt_write_domain(obj);
2997

2998 2999
	/* If we have a partially-valid cache of the object in the CPU,
	 * finish invalidating it and free the per-page flags.
3000
	 */
3001
	i915_gem_object_set_to_full_cpu_read_domain(obj);
3002

3003
	if (write) {
3004
		ret = i915_gem_object_wait_rendering(obj, true);
3005 3006 3007 3008
		if (ret)
			return ret;
	}

3009 3010
	old_write_domain = obj->base.write_domain;
	old_read_domains = obj->base.read_domains;
C
Chris Wilson 已提交
3011

3012
	/* Flush the CPU cache if it's still invalid. */
3013
	if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0) {
3014 3015
		i915_gem_clflush_object(obj);

3016
		obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
3017 3018 3019 3020 3021
	}

	/* It should now be out of any other write domains, and we can update
	 * the domain values for our changes.
	 */
3022
	BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
3023 3024 3025 3026 3027

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

C
Chris Wilson 已提交
3032 3033 3034 3035
	trace_i915_gem_object_change_domain(obj,
					    old_read_domains,
					    old_write_domain);

3036 3037 3038
	return 0;
}

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 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149
/*
 * 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
 */
3150
static void
3151
i915_gem_object_set_to_gpu_domain(struct drm_i915_gem_object *obj,
3152 3153
				  struct intel_ring_buffer *ring,
				  struct change_domains *cd)
3154
{
3155
	uint32_t invalidate_domains = 0, flush_domains = 0;
3156

3157 3158 3159 3160
	/*
	 * If the object isn't moving to a new write domain,
	 * let the object stay in multiple read domains
	 */
3161 3162
	if (obj->base.pending_write_domain == 0)
		obj->base.pending_read_domains |= obj->base.read_domains;
3163 3164 3165 3166 3167 3168 3169

	/*
	 * Flush the current write domain if
	 * the new read domains don't match. Invalidate
	 * any read domains which differ from the old
	 * write domain
	 */
3170 3171 3172 3173
	if (obj->base.write_domain &&
	    (obj->base.write_domain != obj->base.pending_read_domains ||
	     obj->ring != ring)) {
		flush_domains |= obj->base.write_domain;
3174
		invalidate_domains |=
3175
			obj->base.pending_read_domains & ~obj->base.write_domain;
3176 3177 3178 3179 3180
	}
	/*
	 * Invalidate any read caches which may have
	 * stale data. That is, any new read domains.
	 */
3181
	invalidate_domains |= obj->base.pending_read_domains & ~obj->base.read_domains;
3182
	if ((flush_domains | invalidate_domains) & I915_GEM_DOMAIN_CPU)
3183 3184
		i915_gem_clflush_object(obj);

3185 3186 3187 3188
	/* blow away mappings if mapped through GTT */
	if ((flush_domains | invalidate_domains) & I915_GEM_DOMAIN_GTT)
		i915_gem_release_mmap(obj);

3189 3190 3191 3192 3193 3194
	/* 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.
	 */
3195 3196
	if (flush_domains == 0 && obj->base.pending_write_domain == 0)
		obj->base.pending_write_domain = obj->base.write_domain;
3197

3198 3199
	cd->invalidate_domains |= invalidate_domains;
	cd->flush_domains |= flush_domains;
3200
	if (flush_domains & I915_GEM_GPU_DOMAINS)
3201
		cd->flush_rings |= obj->ring->id;
3202
	if (invalidate_domains & I915_GEM_GPU_DOMAINS)
3203
		cd->flush_rings |= ring->id;
3204 3205 3206
}

/**
3207
 * Moves the object from a partially CPU read to a full one.
3208
 *
3209 3210
 * 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).
3211
 */
3212
static void
3213
i915_gem_object_set_to_full_cpu_read_domain(struct drm_i915_gem_object *obj)
3214
{
3215
	if (!obj->page_cpu_valid)
3216 3217 3218 3219
		return;

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

3223 3224
		for (i = 0; i <= (obj->base.size - 1) / PAGE_SIZE; i++) {
			if (obj->page_cpu_valid[i])
3225
				continue;
3226
			drm_clflush_pages(obj->pages + i, 1);
3227 3228 3229 3230 3231 3232
		}
	}

	/* Free the page_cpu_valid mappings which are now stale, whether
	 * or not we've got I915_GEM_DOMAIN_CPU.
	 */
3233 3234
	kfree(obj->page_cpu_valid);
	obj->page_cpu_valid = NULL;
3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249
}

/**
 * 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
3250
i915_gem_object_set_cpu_read_domain_range(struct drm_i915_gem_object *obj,
3251 3252
					  uint64_t offset, uint64_t size)
{
C
Chris Wilson 已提交
3253
	uint32_t old_read_domains;
3254
	int i, ret;
3255

3256
	if (offset == 0 && size == obj->base.size)
3257
		return i915_gem_object_set_to_cpu_domain(obj, 0);
3258

3259
	ret = i915_gem_object_flush_gpu_write_domain(obj, false);
3260
	if (ret != 0)
3261
		return ret;
3262 3263 3264
	i915_gem_object_flush_gtt_write_domain(obj);

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

3269 3270 3271
	/* Otherwise, create/clear the per-page CPU read domain flag if we're
	 * newly adding I915_GEM_DOMAIN_CPU
	 */
3272 3273 3274 3275
	if (obj->page_cpu_valid == NULL) {
		obj->page_cpu_valid = kzalloc(obj->base.size / PAGE_SIZE,
					      GFP_KERNEL);
		if (obj->page_cpu_valid == NULL)
3276
			return -ENOMEM;
3277 3278
	} else if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0)
		memset(obj->page_cpu_valid, 0, obj->base.size / PAGE_SIZE);
3279 3280 3281 3282

	/* Flush the cache on any pages that are still invalid from the CPU's
	 * perspective.
	 */
3283 3284
	for (i = offset / PAGE_SIZE; i <= (offset + size - 1) / PAGE_SIZE;
	     i++) {
3285
		if (obj->page_cpu_valid[i])
3286 3287
			continue;

3288
		drm_clflush_pages(obj->pages + i, 1);
3289

3290
		obj->page_cpu_valid[i] = 1;
3291 3292
	}

3293 3294 3295
	/* It should now be out of any other write domains, and we can update
	 * the domain values for our changes.
	 */
3296
	BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
3297

3298 3299
	old_read_domains = obj->base.read_domains;
	obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
3300

C
Chris Wilson 已提交
3301 3302
	trace_i915_gem_object_change_domain(obj,
					    old_read_domains,
3303
					    obj->base.write_domain);
C
Chris Wilson 已提交
3304

3305 3306 3307 3308
	return 0;
}

static int
3309 3310 3311 3312
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)
3313
{
3314
	struct drm_device *dev = obj->base.dev;
3315 3316 3317
	struct drm_gem_object *target_obj;
	uint32_t target_offset;
	int ret = -EINVAL;
3318

3319 3320 3321 3322
	target_obj = drm_gem_object_lookup(dev, file_priv,
					   reloc->target_handle);
	if (target_obj == NULL)
		return -ENOENT;
3323

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

3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339
#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
3340

3341 3342 3343 3344 3345 3346 3347 3348
	/* 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;
	}
3349

3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382
	/* 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;
	}
3383

3384 3385
	target_obj->pending_read_domains |= reloc->read_domains;
	target_obj->pending_write_domain |= reloc->write_domain;
3386

3387 3388 3389 3390 3391
	/* 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;
3392

3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408
	/* 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;
	}
3409

3410 3411 3412 3413 3414 3415 3416 3417 3418
	/* 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;
	}
3419

3420 3421 3422 3423
	reloc->delta += target_offset;
	if (obj->base.write_domain == I915_GEM_DOMAIN_CPU) {
		uint32_t page_offset = reloc->offset & ~PAGE_MASK;
		char *vaddr;
3424

3425 3426 3427 3428 3429 3430 3431
		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;
3432

3433
		ret = i915_gem_object_set_to_gtt_domain(obj, 1);
3434 3435
		if (ret)
			goto err;
3436

3437 3438 3439 3440 3441 3442 3443 3444 3445
		/* 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);
	}
3446

3447 3448
	/* and update the user's relocation entry */
	reloc->presumed_offset = target_offset;
3449

3450 3451 3452 3453 3454 3455
out:
	ret = 0;
err:
	drm_gem_object_unreference(target_obj);
	return ret;
}
3456

3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476
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;
3477

3478
		if (__copy_to_user_inatomic(&user_relocs[i].presumed_offset,
3479 3480 3481
					    &reloc.presumed_offset,
					    sizeof(reloc.presumed_offset)))
			return -EFAULT;
3482 3483
	}

3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501
	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;
3502 3503
}

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

	for (i = 0; i < count; i++) {
3514
		struct drm_i915_gem_object *obj = object_list[i];
3515 3516 3517 3518 3519 3520 3521 3522 3523
		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;
3524 3525
}

3526
static int
3527 3528
i915_gem_execbuffer_reserve(struct drm_device *dev,
			    struct drm_file *file,
3529
			    struct drm_i915_gem_object **object_list,
3530 3531
			    struct drm_i915_gem_exec_object2 *exec_list,
			    int count)
3532
{
3533 3534
	struct drm_i915_private *dev_priv = dev->dev_private;
	int ret, i, retry;
3535

3536
	/* attempt to pin all of the buffers into the GTT */
3537 3538
	retry = 0;
	do {
3539 3540 3541
		ret = 0;
		for (i = 0; i < count; i++) {
			struct drm_i915_gem_exec_object2 *entry = &exec_list[i];
3542
			struct drm_i915_gem_object *obj = object_list[i];
3543 3544 3545 3546
			bool need_fence =
				entry->flags & EXEC_OBJECT_NEEDS_FENCE &&
				obj->tiling_mode != I915_TILING_NONE;

3547 3548 3549 3550
			/* g33/pnv can't fence buffers in the unmappable part */
			bool need_mappable =
				entry->relocation_count ? true : need_fence;

3551
			/* Check fence reg constraints and rebind if necessary */
3552
			if (need_mappable && !obj->map_and_fenceable) {
3553
				ret = i915_gem_object_unbind(obj);
3554 3555 3556
				if (ret)
					break;
			}
3557

3558
			ret = i915_gem_object_pin(obj,
3559
						  entry->alignment,
3560
						  need_mappable);
3561 3562
			if (ret)
				break;
3563

3564 3565 3566 3567 3568
			/*
			 * Pre-965 chips need a fence register set up in order
			 * to properly handle blits to/from tiled surfaces.
			 */
			if (need_fence) {
3569
				ret = i915_gem_object_get_fence_reg(obj, true);
3570
				if (ret) {
3571
					i915_gem_object_unpin(obj);
3572 3573
					break;
				}
3574

3575 3576
				dev_priv->fence_regs[obj->fence_reg].gpu = true;
			}
3577

3578
			entry->offset = obj->gtt_offset;
3579 3580
		}

3581 3582 3583
		while (i--)
			i915_gem_object_unpin(object_list[i]);

3584
		if (ret != -ENOSPC || retry > 1)
3585 3586
			return ret;

3587 3588 3589 3590
		/* First attempt, just clear anything that is purgeable.
		 * Second attempt, clear the entire GTT.
		 */
		ret = i915_gem_evict_everything(dev, retry == 0);
3591 3592
		if (ret)
			return ret;
3593

3594 3595
		retry++;
	} while (1);
3596 3597
}

3598 3599 3600
static int
i915_gem_execbuffer_relocate_slow(struct drm_device *dev,
				  struct drm_file *file,
3601
				  struct drm_i915_gem_object **object_list,
3602 3603 3604 3605 3606 3607
				  struct drm_i915_gem_exec_object2 *exec_list,
				  int count)
{
	struct drm_i915_gem_relocation_entry *reloc;
	int i, total, ret;

3608 3609
	for (i = 0; i < count; i++)
		object_list[i]->in_execbuffer = false;
3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 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

	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++) {
3654
		struct drm_i915_gem_object *obj = object_list[i];
3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676
		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;
}

3677 3678 3679 3680
static int
i915_gem_execbuffer_move_to_gpu(struct drm_device *dev,
				struct drm_file *file,
				struct intel_ring_buffer *ring,
3681
				struct drm_i915_gem_object **objects,
3682 3683
				int count)
{
3684
	struct change_domains cd;
3685 3686
	int ret, i;

3687 3688 3689
	cd.invalidate_domains = 0;
	cd.flush_domains = 0;
	cd.flush_rings = 0;
3690
	for (i = 0; i < count; i++)
3691
		i915_gem_object_set_to_gpu_domain(objects[i], ring, &cd);
3692

3693
	if (cd.invalidate_domains | cd.flush_domains) {
3694 3695 3696
#if WATCH_EXEC
		DRM_INFO("%s: invalidate_domains %08x flush_domains %08x\n",
			  __func__,
3697 3698
			 cd.invalidate_domains,
			 cd.flush_domains);
3699
#endif
3700
		i915_gem_flush(dev,
3701 3702 3703
			       cd.invalidate_domains,
			       cd.flush_domains,
			       cd.flush_rings);
3704 3705 3706
	}

	for (i = 0; i < count; i++) {
3707
		struct drm_i915_gem_object *obj = objects[i];
3708 3709
		/* XXX replace with semaphores */
		if (obj->ring && ring != obj->ring) {
3710
			ret = i915_gem_object_wait_rendering(obj, true);
3711 3712 3713 3714 3715 3716 3717 3718
			if (ret)
				return ret;
		}
	}

	return 0;
}

3719 3720 3721
/* Throttle our rendering by waiting until the ring has completed our requests
 * emitted over 20 msec ago.
 *
3722 3723 3724 3725
 * 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.
 *
3726 3727 3728
 * This should get us reasonable parallelism between CPU and GPU but also
 * relatively low latency when blocking on a particular request to finish.
 */
3729
static int
3730
i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file)
3731
{
3732 3733
	struct drm_i915_private *dev_priv = dev->dev_private;
	struct drm_i915_file_private *file_priv = file->driver_priv;
3734
	unsigned long recent_enough = jiffies - msecs_to_jiffies(20);
3735 3736 3737 3738
	struct drm_i915_gem_request *request;
	struct intel_ring_buffer *ring = NULL;
	u32 seqno = 0;
	int ret;
3739

3740
	spin_lock(&file_priv->mm.lock);
3741
	list_for_each_entry(request, &file_priv->mm.request_list, client_list) {
3742 3743
		if (time_after_eq(request->emitted_jiffies, recent_enough))
			break;
3744

3745 3746
		ring = request->ring;
		seqno = request->seqno;
3747
	}
3748
	spin_unlock(&file_priv->mm.lock);
3749

3750 3751
	if (seqno == 0)
		return 0;
3752

3753
	ret = 0;
3754
	if (!i915_seqno_passed(ring->get_seqno(ring), seqno)) {
3755 3756 3757 3758 3759
		/* 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.
		 */
3760
		ring->user_irq_get(ring);
3761
		ret = wait_event_interruptible(ring->irq_queue,
3762
					       i915_seqno_passed(ring->get_seqno(ring), seqno)
3763
					       || atomic_read(&dev_priv->mm.wedged));
3764
		ring->user_irq_put(ring);
3765

3766 3767
		if (ret == 0 && atomic_read(&dev_priv->mm.wedged))
			ret = -EIO;
3768 3769
	}

3770 3771
	if (ret == 0)
		queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, 0);
3772 3773 3774 3775

	return ret;
}

3776
static int
3777 3778
i915_gem_check_execbuffer(struct drm_i915_gem_execbuffer2 *exec,
			  uint64_t exec_offset)
3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793
{
	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;
}

3794
static int
3795 3796
validate_exec_list(struct drm_i915_gem_exec_object2 *exec,
		   int count)
3797
{
3798
	int i;
3799

3800 3801
	for (i = 0; i < count; i++) {
		char __user *ptr = (char __user *)(uintptr_t)exec[i].relocs_ptr;
3802
		int length; /* limited by fault_in_pages_readable() */
3803

3804 3805 3806 3807
		/* First check for malicious input causing overflow */
		if (exec[i].relocation_count >
		    INT_MAX / sizeof(struct drm_i915_gem_relocation_entry))
			return -EINVAL;
3808

3809 3810
		length = exec[i].relocation_count *
			sizeof(struct drm_i915_gem_relocation_entry);
3811 3812
		if (!access_ok(VERIFY_READ, ptr, length))
			return -EFAULT;
3813

3814 3815 3816 3817
		/* we may also need to update the presumed offsets */
		if (!access_ok(VERIFY_WRITE, ptr, length))
			return -EFAULT;

3818 3819
		if (fault_in_pages_readable(ptr, length))
			return -EFAULT;
3820 3821
	}

3822
	return 0;
3823 3824
}

C
Chris Wilson 已提交
3825
static int
J
Jesse Barnes 已提交
3826
i915_gem_do_execbuffer(struct drm_device *dev, void *data,
3827
		       struct drm_file *file,
J
Jesse Barnes 已提交
3828 3829
		       struct drm_i915_gem_execbuffer2 *args,
		       struct drm_i915_gem_exec_object2 *exec_list)
3830 3831
{
	drm_i915_private_t *dev_priv = dev->dev_private;
3832 3833
	struct drm_i915_gem_object **object_list = NULL;
	struct drm_i915_gem_object *batch_obj;
3834
	struct drm_clip_rect *cliprects = NULL;
C
Chris Wilson 已提交
3835
	struct drm_i915_gem_request *request = NULL;
3836
	int ret, i, flips;
3837 3838
	uint64_t exec_offset;

3839 3840
	struct intel_ring_buffer *ring = NULL;

3841 3842 3843 3844
	ret = i915_gem_check_is_wedged(dev);
	if (ret)
		return ret;

3845 3846 3847 3848
	ret = validate_exec_list(exec_list, args->buffer_count);
	if (ret)
		return ret;

3849 3850 3851 3852
#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
3853 3854 3855 3856 3857 3858
	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:
3859
		if (!HAS_BSD(dev)) {
3860
			DRM_ERROR("execbuf with invalid ring (BSD)\n");
3861 3862 3863
			return -EINVAL;
		}
		ring = &dev_priv->bsd_ring;
3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875
		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;
3876 3877
	}

3878 3879 3880 3881
	if (args->buffer_count < 1) {
		DRM_ERROR("execbuf with %d buffers\n", args->buffer_count);
		return -EINVAL;
	}
3882
	object_list = drm_malloc_ab(sizeof(*object_list), args->buffer_count);
J
Jesse Barnes 已提交
3883 3884
	if (object_list == NULL) {
		DRM_ERROR("Failed to allocate object list for %d buffers\n",
3885 3886 3887 3888 3889
			  args->buffer_count);
		ret = -ENOMEM;
		goto pre_mutex_err;
	}

3890
	if (args->num_cliprects != 0) {
3891 3892
		cliprects = kcalloc(args->num_cliprects, sizeof(*cliprects),
				    GFP_KERNEL);
3893 3894
		if (cliprects == NULL) {
			ret = -ENOMEM;
3895
			goto pre_mutex_err;
3896
		}
3897 3898 3899 3900 3901 3902 3903 3904

		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);
3905
			ret = -EFAULT;
3906 3907 3908 3909
			goto pre_mutex_err;
		}
	}

C
Chris Wilson 已提交
3910 3911 3912
	request = kzalloc(sizeof(*request), GFP_KERNEL);
	if (request == NULL) {
		ret = -ENOMEM;
3913
		goto pre_mutex_err;
C
Chris Wilson 已提交
3914
	}
3915

3916 3917
	ret = i915_mutex_lock_interruptible(dev);
	if (ret)
3918
		goto pre_mutex_err;
3919 3920 3921

	if (dev_priv->mm.suspended) {
		mutex_unlock(&dev->struct_mutex);
3922 3923
		ret = -EBUSY;
		goto pre_mutex_err;
3924 3925
	}

3926
	/* Look up object handles */
3927
	for (i = 0; i < args->buffer_count; i++) {
3928
		struct drm_i915_gem_object *obj;
3929

3930 3931 3932
		obj = to_intel_bo (drm_gem_object_lookup(dev, file,
							 exec_list[i].handle));
		if (obj == NULL) {
3933 3934
			DRM_ERROR("Invalid object handle %d at index %d\n",
				   exec_list[i].handle, i);
3935
			/* prevent error path from reading uninitialized data */
3936
			args->buffer_count = i;
3937
			ret = -ENOENT;
3938 3939
			goto err;
		}
3940
		object_list[i] = obj;
3941

3942
		if (obj->in_execbuffer) {
3943
			DRM_ERROR("Object %p appears more than once in object list\n",
3944
				   obj);
3945 3946
			/* prevent error path from reading uninitialized data */
			args->buffer_count = i + 1;
3947
			ret = -EINVAL;
3948 3949
			goto err;
		}
3950
		obj->in_execbuffer = true;
3951
	}
3952

3953
	/* Move the objects en-masse into the GTT, evicting if necessary. */
3954 3955 3956
	ret = i915_gem_execbuffer_reserve(dev, file,
					  object_list, exec_list,
					  args->buffer_count);
3957 3958
	if (ret)
		goto err;
3959

3960
	/* The objects are in their final locations, apply the relocations. */
3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971
	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));
		}
3972
		if (ret)
3973
			goto err;
3974 3975 3976 3977
	}

	/* Set the pending read domains for the batch buffer to COMMAND */
	batch_obj = object_list[args->buffer_count-1];
3978
	if (batch_obj->base.pending_write_domain) {
3979 3980 3981 3982
		DRM_ERROR("Attempting to use self-modifying batch buffer\n");
		ret = -EINVAL;
		goto err;
	}
3983
	batch_obj->base.pending_read_domains |= I915_GEM_DOMAIN_COMMAND;
3984

3985
	/* Sanity check the batch buffer */
3986
	exec_offset = batch_obj->gtt_offset;
3987
	ret = i915_gem_check_execbuffer(args, exec_offset);
3988 3989 3990 3991 3992
	if (ret != 0) {
		DRM_ERROR("execbuf with invalid offset/length\n");
		goto err;
	}

3993 3994 3995 3996
	ret = i915_gem_execbuffer_move_to_gpu(dev, file, ring,
					      object_list, args->buffer_count);
	if (ret)
		goto err;
3997 3998 3999 4000 4001 4002 4003 4004 4005

#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
4006
	i915_gem_dump_object(batch_obj,
4007 4008 4009 4010 4011
			      args->batch_len,
			      __func__,
			      ~0);
#endif

4012 4013 4014 4015 4016 4017
	/* 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++) {
4018 4019
		if (object_list[i]->base.write_domain)
			flips |= atomic_read(&object_list[i]->pending_flip);
4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032
	}
	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;

4033 4034 4035 4036
			ret = intel_ring_begin(ring, 2);
			if (ret)
				goto err;

4037 4038 4039
			intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
			intel_ring_emit(ring, MI_NOOP);
			intel_ring_advance(ring);
4040 4041 4042
		}
	}

4043
	/* Exec the batchbuffer */
4044
	ret = ring->dispatch_execbuffer(ring, args, cliprects, exec_offset);
4045 4046 4047 4048 4049 4050
	if (ret) {
		DRM_ERROR("dispatch failed %d\n", ret);
		goto err;
	}

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

4053 4054
		obj->base.read_domains = obj->base.pending_read_domains;
		obj->base.write_domain = obj->base.pending_write_domain;
4055

4056
		i915_gem_object_move_to_active(obj, ring);
4057 4058 4059
		if (obj->base.write_domain) {
			obj->dirty = 1;
			list_move_tail(&obj->gpu_write_list,
4060
				       &ring->gpu_write_list);
4061 4062 4063 4064
			intel_mark_busy(dev, obj);
		}

		trace_i915_gem_object_change_domain(obj,
4065 4066
						    obj->base.read_domains,
						    obj->base.write_domain);
4067 4068
	}

4069 4070 4071 4072 4073 4074
	/*
	 * Ensure that the commands in the batch buffer are
	 * finished before the interrupt fires
	 */
	i915_retire_commands(dev, ring);

4075
	if (i915_add_request(dev, file, request, ring))
4076
		i915_gem_next_request_seqno(dev, ring);
4077 4078
	else
		request = NULL;
4079 4080

err:
4081
	for (i = 0; i < args->buffer_count; i++) {
4082 4083
		object_list[i]->in_execbuffer = false;
		drm_gem_object_unreference(&object_list[i]->base);
4084
	}
4085 4086 4087

	mutex_unlock(&dev->struct_mutex);

4088
pre_mutex_err:
4089
	drm_free_large(object_list);
4090
	kfree(cliprects);
C
Chris Wilson 已提交
4091
	kfree(request);
4092 4093 4094 4095

	return ret;
}

J
Jesse Barnes 已提交
4096 4097 4098 4099 4100 4101
/*
 * 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,
4102
		    struct drm_file *file)
J
Jesse Barnes 已提交
4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 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
{
	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;
4148
		if (INTEL_INFO(dev)->gen < 4)
J
Jesse Barnes 已提交
4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161
			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;
4162
	exec2.flags = I915_EXEC_RENDER;
J
Jesse Barnes 已提交
4163

4164
	ret = i915_gem_do_execbuffer(dev, data, file, &exec2, exec2_list);
J
Jesse Barnes 已提交
4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188
	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,
4189
		     struct drm_file *file)
J
Jesse Barnes 已提交
4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221
{
	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;
	}

4222
	ret = i915_gem_do_execbuffer(dev, data, file, args, exec2_list);
J
Jesse Barnes 已提交
4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240
	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;
}

4241
int
4242 4243
i915_gem_object_pin(struct drm_i915_gem_object *obj,
		    uint32_t alignment,
4244
		    bool map_and_fenceable)
4245
{
4246
	struct drm_device *dev = obj->base.dev;
C
Chris Wilson 已提交
4247
	struct drm_i915_private *dev_priv = dev->dev_private;
4248 4249
	int ret;

4250
	BUG_ON(obj->pin_count == DRM_I915_GEM_OBJECT_MAX_PIN_COUNT);
4251
	WARN_ON(i915_verify_lists(dev));
4252

4253 4254 4255 4256
	if (obj->gtt_space != NULL) {
		if ((alignment && obj->gtt_offset & (alignment - 1)) ||
		    (map_and_fenceable && !obj->map_and_fenceable)) {
			WARN(obj->pin_count,
4257
			     "bo is already pinned with incorrect alignment:"
4258 4259
			     " offset=%x, req.alignment=%x, req.map_and_fenceable=%d,"
			     " obj->map_and_fenceable=%d\n",
4260
			     obj->gtt_offset, alignment,
4261
			     map_and_fenceable,
4262
			     obj->map_and_fenceable);
4263 4264 4265 4266 4267 4268
			ret = i915_gem_object_unbind(obj);
			if (ret)
				return ret;
		}
	}

4269
	if (obj->gtt_space == NULL) {
4270
		ret = i915_gem_object_bind_to_gtt(obj, alignment,
4271
						  map_and_fenceable);
4272
		if (ret)
4273
			return ret;
4274
	}
J
Jesse Barnes 已提交
4275

4276 4277 4278 4279
	if (obj->pin_count++ == 0) {
		i915_gem_info_add_pin(dev_priv, obj, map_and_fenceable);
		if (!obj->active)
			list_move_tail(&obj->mm_list,
C
Chris Wilson 已提交
4280
				       &dev_priv->mm.pinned_list);
4281
	}
4282
	BUG_ON(!obj->pin_mappable && map_and_fenceable);
4283

4284
	WARN_ON(i915_verify_lists(dev));
4285 4286 4287 4288
	return 0;
}

void
4289
i915_gem_object_unpin(struct drm_i915_gem_object *obj)
4290
{
4291
	struct drm_device *dev = obj->base.dev;
4292 4293
	drm_i915_private_t *dev_priv = dev->dev_private;

4294
	WARN_ON(i915_verify_lists(dev));
4295 4296
	BUG_ON(obj->pin_count == 0);
	BUG_ON(obj->gtt_space == NULL);
4297

4298 4299 4300
	if (--obj->pin_count == 0) {
		if (!obj->active)
			list_move_tail(&obj->mm_list,
4301
				       &dev_priv->mm.inactive_list);
4302
		i915_gem_info_remove_pin(dev_priv, obj);
4303
	}
4304
	WARN_ON(i915_verify_lists(dev));
4305 4306 4307 4308
}

int
i915_gem_pin_ioctl(struct drm_device *dev, void *data,
4309
		   struct drm_file *file)
4310 4311
{
	struct drm_i915_gem_pin *args = data;
4312
	struct drm_i915_gem_object *obj;
4313 4314
	int ret;

4315 4316 4317
	ret = i915_mutex_lock_interruptible(dev);
	if (ret)
		return ret;
4318

4319
	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
4320
	if (obj == NULL) {
4321 4322
		ret = -ENOENT;
		goto unlock;
4323 4324
	}

4325
	if (obj->madv != I915_MADV_WILLNEED) {
C
Chris Wilson 已提交
4326
		DRM_ERROR("Attempting to pin a purgeable buffer\n");
4327 4328
		ret = -EINVAL;
		goto out;
4329 4330
	}

4331
	if (obj->pin_filp != NULL && obj->pin_filp != file) {
J
Jesse Barnes 已提交
4332 4333
		DRM_ERROR("Already pinned in i915_gem_pin_ioctl(): %d\n",
			  args->handle);
4334 4335
		ret = -EINVAL;
		goto out;
J
Jesse Barnes 已提交
4336 4337
	}

4338 4339 4340
	obj->user_pin_count++;
	obj->pin_filp = file;
	if (obj->user_pin_count == 1) {
4341
		ret = i915_gem_object_pin(obj, args->alignment, true);
4342 4343
		if (ret)
			goto out;
4344 4345 4346 4347 4348
	}

	/* XXX - flush the CPU caches for pinned objects
	 * as the X server doesn't manage domains yet
	 */
4349
	i915_gem_object_flush_cpu_write_domain(obj);
4350
	args->offset = obj->gtt_offset;
4351
out:
4352
	drm_gem_object_unreference(&obj->base);
4353
unlock:
4354
	mutex_unlock(&dev->struct_mutex);
4355
	return ret;
4356 4357 4358 4359
}

int
i915_gem_unpin_ioctl(struct drm_device *dev, void *data,
4360
		     struct drm_file *file)
4361 4362
{
	struct drm_i915_gem_pin *args = data;
4363
	struct drm_i915_gem_object *obj;
4364
	int ret;
4365

4366 4367 4368
	ret = i915_mutex_lock_interruptible(dev);
	if (ret)
		return ret;
4369

4370
	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
4371
	if (obj == NULL) {
4372 4373
		ret = -ENOENT;
		goto unlock;
4374
	}
4375

4376
	if (obj->pin_filp != file) {
J
Jesse Barnes 已提交
4377 4378
		DRM_ERROR("Not pinned by caller in i915_gem_pin_ioctl(): %d\n",
			  args->handle);
4379 4380
		ret = -EINVAL;
		goto out;
J
Jesse Barnes 已提交
4381
	}
4382 4383 4384
	obj->user_pin_count--;
	if (obj->user_pin_count == 0) {
		obj->pin_filp = NULL;
J
Jesse Barnes 已提交
4385 4386
		i915_gem_object_unpin(obj);
	}
4387

4388
out:
4389
	drm_gem_object_unreference(&obj->base);
4390
unlock:
4391
	mutex_unlock(&dev->struct_mutex);
4392
	return ret;
4393 4394 4395 4396
}

int
i915_gem_busy_ioctl(struct drm_device *dev, void *data,
4397
		    struct drm_file *file)
4398 4399
{
	struct drm_i915_gem_busy *args = data;
4400
	struct drm_i915_gem_object *obj;
4401 4402
	int ret;

4403
	ret = i915_mutex_lock_interruptible(dev);
4404
	if (ret)
4405
		return ret;
4406

4407
	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
4408
	if (obj == NULL) {
4409 4410
		ret = -ENOENT;
		goto unlock;
4411
	}
4412

4413 4414 4415 4416
	/* 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.
4417
	 */
4418
	args->busy = obj->active;
4419 4420 4421 4422 4423 4424
	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.
		 */
4425 4426 4427
		if (obj->base.write_domain & I915_GEM_GPU_DOMAINS)
			i915_gem_flush_ring(dev, obj->ring,
					    0, obj->base.write_domain);
4428 4429 4430 4431 4432 4433

		/* 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.
		 */
4434
		i915_gem_retire_requests_ring(dev, obj->ring);
4435

4436
		args->busy = obj->active;
4437
	}
4438

4439
	drm_gem_object_unreference(&obj->base);
4440
unlock:
4441
	mutex_unlock(&dev->struct_mutex);
4442
	return ret;
4443 4444 4445 4446 4447 4448 4449 4450 4451
}

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

4452 4453 4454 4455 4456
int
i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
		       struct drm_file *file_priv)
{
	struct drm_i915_gem_madvise *args = data;
4457
	struct drm_i915_gem_object *obj;
4458
	int ret;
4459 4460 4461 4462 4463 4464 4465 4466 4467

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

4468 4469 4470 4471
	ret = i915_mutex_lock_interruptible(dev);
	if (ret)
		return ret;

4472
	obj = to_intel_bo(drm_gem_object_lookup(dev, file_priv, args->handle));
4473
	if (obj == NULL) {
4474 4475
		ret = -ENOENT;
		goto unlock;
4476 4477
	}

4478
	if (obj->pin_count) {
4479 4480
		ret = -EINVAL;
		goto out;
4481 4482
	}

4483 4484
	if (obj->madv != __I915_MADV_PURGED)
		obj->madv = args->madv;
4485

4486
	/* if the object is no longer bound, discard its backing storage */
4487 4488
	if (i915_gem_object_is_purgeable(obj) &&
	    obj->gtt_space == NULL)
4489 4490
		i915_gem_object_truncate(obj);

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

4493
out:
4494
	drm_gem_object_unreference(&obj->base);
4495
unlock:
4496
	mutex_unlock(&dev->struct_mutex);
4497
	return ret;
4498 4499
}

4500 4501
struct drm_i915_gem_object *i915_gem_alloc_object(struct drm_device *dev,
						  size_t size)
4502
{
4503
	struct drm_i915_private *dev_priv = dev->dev_private;
4504
	struct drm_i915_gem_object *obj;
4505

4506 4507 4508
	obj = kzalloc(sizeof(*obj), GFP_KERNEL);
	if (obj == NULL)
		return NULL;
4509

4510 4511 4512 4513
	if (drm_gem_object_init(dev, &obj->base, size) != 0) {
		kfree(obj);
		return NULL;
	}
4514

4515 4516
	i915_gem_info_add_obj(dev_priv, size);

4517 4518
	obj->base.write_domain = I915_GEM_DOMAIN_CPU;
	obj->base.read_domains = I915_GEM_DOMAIN_CPU;
4519

4520
	obj->agp_type = AGP_USER_MEMORY;
4521
	obj->base.driver_private = NULL;
4522
	obj->fence_reg = I915_FENCE_REG_NONE;
4523
	INIT_LIST_HEAD(&obj->mm_list);
D
Daniel Vetter 已提交
4524
	INIT_LIST_HEAD(&obj->gtt_list);
4525
	INIT_LIST_HEAD(&obj->ring_list);
4526 4527
	INIT_LIST_HEAD(&obj->gpu_write_list);
	obj->madv = I915_MADV_WILLNEED;
4528 4529
	/* Avoid an unnecessary call to unbind on the first bind. */
	obj->map_and_fenceable = true;
4530

4531
	return obj;
4532 4533 4534 4535 4536
}

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

4538 4539 4540
	return 0;
}

4541
static void i915_gem_free_object_tail(struct drm_i915_gem_object *obj)
4542
{
4543
	struct drm_device *dev = obj->base.dev;
4544 4545
	drm_i915_private_t *dev_priv = dev->dev_private;
	int ret;
4546

4547 4548
	ret = i915_gem_object_unbind(obj);
	if (ret == -ERESTARTSYS) {
4549
		list_move(&obj->mm_list,
4550 4551 4552
			  &dev_priv->mm.deferred_free_list);
		return;
	}
4553

4554
	if (obj->base.map_list.map)
4555
		i915_gem_free_mmap_offset(obj);
4556

4557 4558
	drm_gem_object_release(&obj->base);
	i915_gem_info_remove_obj(dev_priv, obj->base.size);
4559

4560 4561 4562
	kfree(obj->page_cpu_valid);
	kfree(obj->bit_17);
	kfree(obj);
4563 4564
}

4565
void i915_gem_free_object(struct drm_gem_object *gem_obj)
4566
{
4567 4568
	struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
	struct drm_device *dev = obj->base.dev;
4569 4570 4571

	trace_i915_gem_object_destroy(obj);

4572
	while (obj->pin_count > 0)
4573 4574
		i915_gem_object_unpin(obj);

4575
	if (obj->phys_obj)
4576 4577 4578 4579 4580
		i915_gem_detach_phys_object(dev, obj);

	i915_gem_free_object_tail(obj);
}

4581 4582 4583 4584 4585
int
i915_gem_idle(struct drm_device *dev)
{
	drm_i915_private_t *dev_priv = dev->dev_private;
	int ret;
4586

4587
	mutex_lock(&dev->struct_mutex);
C
Chris Wilson 已提交
4588

4589
	if (dev_priv->mm.suspended) {
4590 4591
		mutex_unlock(&dev->struct_mutex);
		return 0;
4592 4593
	}

4594
	ret = i915_gpu_idle(dev);
4595 4596
	if (ret) {
		mutex_unlock(&dev->struct_mutex);
4597
		return ret;
4598
	}
4599

4600 4601
	/* Under UMS, be paranoid and evict. */
	if (!drm_core_check_feature(dev, DRIVER_MODESET)) {
4602
		ret = i915_gem_evict_inactive(dev, false);
4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613
		if (ret) {
			mutex_unlock(&dev->struct_mutex);
			return ret;
		}
	}

	/* 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;
4614
	del_timer_sync(&dev_priv->hangcheck_timer);
4615 4616

	i915_kernel_lost_context(dev);
4617
	i915_gem_cleanup_ringbuffer(dev);
4618

4619 4620
	mutex_unlock(&dev->struct_mutex);

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

4624 4625 4626
	return 0;
}

4627 4628 4629 4630 4631
int
i915_gem_init_ringbuffer(struct drm_device *dev)
{
	drm_i915_private_t *dev_priv = dev->dev_private;
	int ret;
4632

4633
	ret = intel_init_render_ring_buffer(dev);
4634
	if (ret)
4635
		return ret;
4636 4637

	if (HAS_BSD(dev)) {
4638
		ret = intel_init_bsd_ring_buffer(dev);
4639 4640
		if (ret)
			goto cleanup_render_ring;
4641
	}
4642

4643 4644 4645 4646 4647 4648
	if (HAS_BLT(dev)) {
		ret = intel_init_blt_ring_buffer(dev);
		if (ret)
			goto cleanup_bsd_ring;
	}

4649 4650
	dev_priv->next_seqno = 1;

4651 4652
	return 0;

4653
cleanup_bsd_ring:
4654
	intel_cleanup_ring_buffer(&dev_priv->bsd_ring);
4655
cleanup_render_ring:
4656
	intel_cleanup_ring_buffer(&dev_priv->render_ring);
4657 4658 4659 4660 4661 4662 4663 4664
	return ret;
}

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

4665 4666 4667
	intel_cleanup_ring_buffer(&dev_priv->render_ring);
	intel_cleanup_ring_buffer(&dev_priv->bsd_ring);
	intel_cleanup_ring_buffer(&dev_priv->blt_ring);
4668 4669
}

4670 4671 4672 4673 4674 4675 4676
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 已提交
4677 4678 4679
	if (drm_core_check_feature(dev, DRIVER_MODESET))
		return 0;

4680
	if (atomic_read(&dev_priv->mm.wedged)) {
4681
		DRM_ERROR("Reenabling wedged hardware, good luck\n");
4682
		atomic_set(&dev_priv->mm.wedged, 0);
4683 4684 4685
	}

	mutex_lock(&dev->struct_mutex);
4686 4687 4688
	dev_priv->mm.suspended = 0;

	ret = i915_gem_init_ringbuffer(dev);
4689 4690
	if (ret != 0) {
		mutex_unlock(&dev->struct_mutex);
4691
		return ret;
4692
	}
4693

4694
	BUG_ON(!list_empty(&dev_priv->mm.active_list));
4695
	BUG_ON(!list_empty(&dev_priv->render_ring.active_list));
4696
	BUG_ON(!list_empty(&dev_priv->bsd_ring.active_list));
4697
	BUG_ON(!list_empty(&dev_priv->blt_ring.active_list));
4698 4699
	BUG_ON(!list_empty(&dev_priv->mm.flushing_list));
	BUG_ON(!list_empty(&dev_priv->mm.inactive_list));
4700
	BUG_ON(!list_empty(&dev_priv->render_ring.request_list));
4701
	BUG_ON(!list_empty(&dev_priv->bsd_ring.request_list));
4702
	BUG_ON(!list_empty(&dev_priv->blt_ring.request_list));
4703
	mutex_unlock(&dev->struct_mutex);
4704

4705 4706 4707
	ret = drm_irq_install(dev);
	if (ret)
		goto cleanup_ringbuffer;
4708

4709
	return 0;
4710 4711 4712 4713 4714 4715 4716 4717

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

	return ret;
4718 4719 4720 4721 4722 4723
}

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

4727
	drm_irq_uninstall(dev);
4728
	return i915_gem_idle(dev);
4729 4730 4731 4732 4733 4734 4735
}

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

4736 4737 4738
	if (drm_core_check_feature(dev, DRIVER_MODESET))
		return;

4739 4740 4741
	ret = i915_gem_idle(dev);
	if (ret)
		DRM_ERROR("failed to idle hardware: %d\n", ret);
4742 4743
}

4744 4745 4746 4747 4748 4749 4750 4751
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);
}

4752 4753 4754
void
i915_gem_load(struct drm_device *dev)
{
4755
	int i;
4756 4757
	drm_i915_private_t *dev_priv = dev->dev_private;

4758
	INIT_LIST_HEAD(&dev_priv->mm.active_list);
4759 4760
	INIT_LIST_HEAD(&dev_priv->mm.flushing_list);
	INIT_LIST_HEAD(&dev_priv->mm.inactive_list);
C
Chris Wilson 已提交
4761
	INIT_LIST_HEAD(&dev_priv->mm.pinned_list);
4762
	INIT_LIST_HEAD(&dev_priv->mm.fence_list);
4763
	INIT_LIST_HEAD(&dev_priv->mm.deferred_free_list);
D
Daniel Vetter 已提交
4764
	INIT_LIST_HEAD(&dev_priv->mm.gtt_list);
4765 4766 4767
	init_ring_lists(&dev_priv->render_ring);
	init_ring_lists(&dev_priv->bsd_ring);
	init_ring_lists(&dev_priv->blt_ring);
4768 4769
	for (i = 0; i < 16; i++)
		INIT_LIST_HEAD(&dev_priv->fence_regs[i].lru_list);
4770 4771
	INIT_DELAYED_WORK(&dev_priv->mm.retire_work,
			  i915_gem_retire_work_handler);
4772
	init_completion(&dev_priv->error_completion);
4773

4774 4775 4776 4777 4778 4779 4780 4781 4782 4783
	/* 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);
		}
	}

4784
	/* Old X drivers will take 0-2 for front, back, depth buffers */
4785 4786
	if (!drm_core_check_feature(dev, DRIVER_MODESET))
		dev_priv->fence_reg_start = 3;
4787

4788
	if (INTEL_INFO(dev)->gen >= 4 || IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
4789 4790 4791 4792
		dev_priv->num_fence_regs = 16;
	else
		dev_priv->num_fence_regs = 8;

4793
	/* Initialize fence registers to zero */
4794 4795 4796 4797 4798 4799 4800
	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:
4801 4802
		for (i = 0; i < 16; i++)
			I915_WRITE64(FENCE_REG_965_0 + (i * 8), 0);
4803 4804
		break;
	case 3:
4805 4806 4807
		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);
4808 4809 4810 4811
	case 2:
		for (i = 0; i < 8; i++)
			I915_WRITE(FENCE_REG_830_0 + (i * 4), 0);
		break;
4812
	}
4813
	i915_gem_detect_bit_6_swizzle(dev);
4814
	init_waitqueue_head(&dev_priv->pending_flip_queue);
4815 4816 4817 4818

	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);
4819
}
4820 4821 4822 4823 4824

/*
 * Create a physically contiguous memory object for this object
 * e.g. for cursor + overlay regs
 */
4825 4826
static int i915_gem_init_phys_object(struct drm_device *dev,
				     int id, int size, int align)
4827 4828 4829 4830 4831 4832 4833 4834
{
	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;

4835
	phys_obj = kzalloc(sizeof(struct drm_i915_gem_phys_object), GFP_KERNEL);
4836 4837 4838 4839 4840
	if (!phys_obj)
		return -ENOMEM;

	phys_obj->id = id;

4841
	phys_obj->handle = drm_pci_alloc(dev, size, align);
4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853
	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:
4854
	kfree(phys_obj);
4855 4856 4857
	return ret;
}

4858
static void i915_gem_free_phys_object(struct drm_device *dev, int id)
4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882
{
	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;

4883
	for (i = I915_GEM_PHYS_CURSOR_0; i <= I915_MAX_PHYS_OBJECT; i++)
4884 4885 4886 4887
		i915_gem_free_phys_object(dev, i);
}

void i915_gem_detach_phys_object(struct drm_device *dev,
4888
				 struct drm_i915_gem_object *obj)
4889
{
4890
	struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
4891
	char *vaddr;
4892 4893 4894
	int i;
	int page_count;

4895
	if (!obj->phys_obj)
4896
		return;
4897
	vaddr = obj->phys_obj->handle->vaddr;
4898

4899
	page_count = obj->base.size / PAGE_SIZE;
4900
	for (i = 0; i < page_count; i++) {
4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913
		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);
		}
4914
	}
4915
	intel_gtt_chipset_flush();
4916

4917 4918
	obj->phys_obj->cur_obj = NULL;
	obj->phys_obj = NULL;
4919 4920 4921 4922
}

int
i915_gem_attach_phys_object(struct drm_device *dev,
4923
			    struct drm_i915_gem_object *obj,
4924 4925
			    int id,
			    int align)
4926
{
4927
	struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
4928 4929 4930 4931 4932 4933 4934 4935
	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;

4936 4937
	if (obj->phys_obj) {
		if (obj->phys_obj->id == id)
4938 4939 4940 4941 4942 4943 4944
			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,
4945
						obj->base.size, align);
4946
		if (ret) {
4947 4948
			DRM_ERROR("failed to init phys object %d size: %zu\n",
				  id, obj->base.size);
4949
			return ret;
4950 4951 4952 4953
		}
	}

	/* bind to the object */
4954 4955
	obj->phys_obj = dev_priv->mm.phys_objs[id - 1];
	obj->phys_obj->cur_obj = obj;
4956

4957
	page_count = obj->base.size / PAGE_SIZE;
4958 4959

	for (i = 0; i < page_count; i++) {
4960 4961 4962 4963 4964 4965 4966
		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);
4967

4968
		src = kmap_atomic(page);
4969
		dst = obj->phys_obj->handle->vaddr + (i * PAGE_SIZE);
4970
		memcpy(dst, src, PAGE_SIZE);
P
Peter Zijlstra 已提交
4971
		kunmap_atomic(src);
4972

4973 4974 4975
		mark_page_accessed(page);
		page_cache_release(page);
	}
4976

4977 4978 4979 4980
	return 0;
}

static int
4981 4982
i915_gem_phys_pwrite(struct drm_device *dev,
		     struct drm_i915_gem_object *obj,
4983 4984 4985
		     struct drm_i915_gem_pwrite *args,
		     struct drm_file *file_priv)
{
4986
	void *vaddr = obj->phys_obj->handle->vaddr + args->offset;
4987
	char __user *user_data = (char __user *) (uintptr_t) args->data_ptr;
4988

4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001
	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;
	}
5002

5003
	intel_gtt_chipset_flush();
5004 5005
	return 0;
}
5006

5007
void i915_gem_release(struct drm_device *dev, struct drm_file *file)
5008
{
5009
	struct drm_i915_file_private *file_priv = file->driver_priv;
5010 5011 5012 5013 5014

	/* 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.
	 */
5015
	spin_lock(&file_priv->mm.lock);
5016 5017 5018 5019 5020 5021 5022 5023 5024
	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;
	}
5025
	spin_unlock(&file_priv->mm.lock);
5026
}
5027

5028 5029 5030 5031 5032 5033 5034
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) &&
5035
		      list_empty(&dev_priv->mm.active_list);
5036 5037 5038 5039

	return !lists_empty;
}

5040
static int
5041 5042 5043
i915_gem_inactive_shrink(struct shrinker *shrinker,
			 int nr_to_scan,
			 gfp_t gfp_mask)
5044
{
5045 5046 5047 5048 5049 5050 5051 5052 5053
	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))
5054
		return 0;
5055 5056 5057

	/* "fast-path" to count number of available objects */
	if (nr_to_scan == 0) {
5058 5059 5060 5061 5062 5063 5064
		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;
5065 5066
	}

5067
rescan:
5068
	/* first scan for clean buffers */
5069
	i915_gem_retire_requests(dev);
5070

5071 5072 5073 5074
	list_for_each_entry_safe(obj, next,
				 &dev_priv->mm.inactive_list,
				 mm_list) {
		if (i915_gem_object_is_purgeable(obj)) {
5075
			i915_gem_object_unbind(obj);
5076 5077
			if (--nr_to_scan == 0)
				break;
5078 5079 5080 5081
		}
	}

	/* second pass, evict/count anything still on the inactive list */
5082 5083 5084 5085 5086
	cnt = 0;
	list_for_each_entry_safe(obj, next,
				 &dev_priv->mm.inactive_list,
				 mm_list) {
		if (nr_to_scan) {
5087
			i915_gem_object_unbind(obj);
5088 5089 5090 5091 5092 5093
			nr_to_scan--;
		} else
			cnt++;
	}

	if (nr_to_scan && i915_gpu_is_active(dev)) {
5094 5095 5096 5097 5098 5099
		/*
		 * 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.
		 */
5100
		if (i915_gpu_idle(dev) == 0)
5101 5102
			goto rescan;
	}
5103 5104
	mutex_unlock(&dev->struct_mutex);
	return cnt / 100 * sysctl_vfs_cache_pressure;
5105
}