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

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

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

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

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

70

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 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 1279 1280
	if (!obj->map_and_fenceable) {
		ret = i915_gem_object_unbind(obj);
		if (ret)
			goto unlock;
1281
	}
1282

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

1289 1290 1291 1292
	ret = i915_gem_object_set_to_gtt_domain(obj, write);
	if (ret)
		goto unlock;

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

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

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

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

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

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

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

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

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

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

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

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

	return ret;
}

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

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

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

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

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

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

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

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

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

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

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

1522
	return tile_height * obj->stride * 2;
1523 1524
}

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

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

1552
	ret = i915_mutex_lock_interruptible(dev);
1553
	if (ret)
1554
		return ret;
1555

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

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

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

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

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

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

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

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

1617
		obj->pages[i] = page;
1618 1619
	}

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

	return 0;

err_pages:
	while (i--)
1627
		page_cache_release(obj->pages[i]);
1628

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

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

1640
	BUG_ON(obj->madv == __I915_MADV_PURGED);
1641

1642
	if (obj->tiling_mode != I915_TILING_NONE)
1643 1644
		i915_gem_object_save_bit_17_swizzle(obj);

1645 1646
	if (obj->madv == I915_MADV_DONTNEED)
		obj->dirty = 0;
1647 1648

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

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

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

1659 1660
	drm_free_large(obj->pages);
	obj->pages = NULL;
1661 1662
}

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

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

1679
	BUG_ON(ring == NULL);
1680
	obj->ring = ring;
1681 1682

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

1688
	/* Move from whatever list we were on to the tail of execution. */
1689 1690
	list_move_tail(&obj->mm_list, &dev_priv->mm.active_list);
	list_move_tail(&obj->ring_list, &ring->active_list);
1691

1692
	obj->last_rendering_seqno = seqno;
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711
	if (obj->fenced_gpu_access) {
		struct drm_i915_fence_reg *reg;

		BUG_ON(obj->fence_reg == I915_FENCE_REG_NONE);

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

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

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

1714
static void
1715
i915_gem_object_move_to_flushing(struct drm_i915_gem_object *obj)
1716
{
1717
	struct drm_device *dev = obj->base.dev;
1718 1719
	drm_i915_private_t *dev_priv = dev->dev_private;

1720 1721
	BUG_ON(!obj->active);
	list_move_tail(&obj->mm_list, &dev_priv->mm.flushing_list);
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748

	i915_gem_object_move_off_active(obj);
}

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

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

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

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

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

	WARN_ON(i915_verify_lists(dev));
1749
}
1750

1751 1752
/* Immediately discard the backing storage */
static void
1753
i915_gem_object_truncate(struct drm_i915_gem_object *obj)
1754
{
C
Chris Wilson 已提交
1755
	struct inode *inode;
1756

1757 1758 1759 1760 1761 1762
	/* 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.
	 */
1763
	inode = obj->base.filp->f_path.dentry->d_inode;
1764 1765 1766
	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 已提交
1767

1768
	obj->madv = __I915_MADV_PURGED;
1769 1770 1771
}

static inline int
1772
i915_gem_object_is_purgeable(struct drm_i915_gem_object *obj)
1773
{
1774
	return obj->madv == I915_MADV_DONTNEED;
1775 1776
}

1777 1778
static void
i915_gem_process_flushing_list(struct drm_device *dev,
1779
			       uint32_t flush_domains,
1780
			       struct intel_ring_buffer *ring)
1781
{
1782
	struct drm_i915_gem_object *obj, *next;
1783

1784
	list_for_each_entry_safe(obj, next,
1785
				 &ring->gpu_write_list,
1786
				 gpu_write_list) {
1787 1788
		if (obj->base.write_domain & flush_domains) {
			uint32_t old_write_domain = obj->base.write_domain;
1789

1790 1791
			obj->base.write_domain = 0;
			list_del_init(&obj->gpu_write_list);
1792
			i915_gem_object_move_to_active(obj, ring);
1793 1794

			trace_i915_gem_object_change_domain(obj,
1795
							    obj->base.read_domains,
1796 1797 1798 1799
							    old_write_domain);
		}
	}
}
1800

1801
int
1802
i915_add_request(struct drm_device *dev,
1803
		 struct drm_file *file,
C
Chris Wilson 已提交
1804
		 struct drm_i915_gem_request *request,
1805
		 struct intel_ring_buffer *ring)
1806 1807
{
	drm_i915_private_t *dev_priv = dev->dev_private;
1808
	struct drm_i915_file_private *file_priv = NULL;
1809 1810
	uint32_t seqno;
	int was_empty;
1811 1812 1813
	int ret;

	BUG_ON(request == NULL);
1814

1815 1816
	if (file != NULL)
		file_priv = file->driver_priv;
1817

1818 1819 1820
	ret = ring->add_request(ring, &seqno);
	if (ret)
	    return ret;
1821

1822
	ring->outstanding_lazy_request = false;
1823 1824

	request->seqno = seqno;
1825
	request->ring = ring;
1826
	request->emitted_jiffies = jiffies;
1827 1828 1829
	was_empty = list_empty(&ring->request_list);
	list_add_tail(&request->list, &ring->request_list);

1830
	if (file_priv) {
1831
		spin_lock(&file_priv->mm.lock);
1832
		request->file_priv = file_priv;
1833
		list_add_tail(&request->client_list,
1834
			      &file_priv->mm.request_list);
1835
		spin_unlock(&file_priv->mm.lock);
1836
	}
1837

B
Ben Gamari 已提交
1838
	if (!dev_priv->mm.suspended) {
1839 1840
		mod_timer(&dev_priv->hangcheck_timer,
			  jiffies + msecs_to_jiffies(DRM_I915_HANGCHECK_PERIOD));
B
Ben Gamari 已提交
1841
		if (was_empty)
1842 1843
			queue_delayed_work(dev_priv->wq,
					   &dev_priv->mm.retire_work, HZ);
B
Ben Gamari 已提交
1844
	}
1845
	return 0;
1846 1847 1848 1849 1850 1851 1852 1853
}

/**
 * Command execution barrier
 *
 * Ensures that all commands in the ring are finished
 * before signalling the CPU
 */
1854
static void
1855
i915_retire_commands(struct drm_device *dev, struct intel_ring_buffer *ring)
1856 1857 1858 1859
{
	uint32_t flush_domains = 0;

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

1863
	ring->flush(ring, I915_GEM_DOMAIN_COMMAND, flush_domains);
1864 1865
}

1866 1867
static inline void
i915_gem_request_remove_from_client(struct drm_i915_gem_request *request)
1868
{
1869
	struct drm_i915_file_private *file_priv = request->file_priv;
1870

1871 1872
	if (!file_priv)
		return;
C
Chris Wilson 已提交
1873

1874 1875 1876 1877
	spin_lock(&file_priv->mm.lock);
	list_del(&request->client_list);
	request->file_priv = NULL;
	spin_unlock(&file_priv->mm.lock);
1878 1879
}

1880 1881
static void i915_gem_reset_ring_lists(struct drm_i915_private *dev_priv,
				      struct intel_ring_buffer *ring)
1882
{
1883 1884
	while (!list_empty(&ring->request_list)) {
		struct drm_i915_gem_request *request;
1885

1886 1887 1888
		request = list_first_entry(&ring->request_list,
					   struct drm_i915_gem_request,
					   list);
1889

1890
		list_del(&request->list);
1891
		i915_gem_request_remove_from_client(request);
1892 1893
		kfree(request);
	}
1894

1895
	while (!list_empty(&ring->active_list)) {
1896
		struct drm_i915_gem_object *obj;
1897

1898 1899 1900
		obj = list_first_entry(&ring->active_list,
				       struct drm_i915_gem_object,
				       ring_list);
1901

1902 1903 1904
		obj->base.write_domain = 0;
		list_del_init(&obj->gpu_write_list);
		i915_gem_object_move_to_inactive(obj);
1905 1906 1907
	}
}

1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919
static void i915_gem_reset_fences(struct drm_device *dev)
{
	struct drm_i915_private *dev_priv = dev->dev_private;
	int i;

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

1920
void i915_gem_reset(struct drm_device *dev)
1921
{
1922
	struct drm_i915_private *dev_priv = dev->dev_private;
1923
	struct drm_i915_gem_object *obj;
1924

1925
	i915_gem_reset_ring_lists(dev_priv, &dev_priv->render_ring);
1926
	i915_gem_reset_ring_lists(dev_priv, &dev_priv->bsd_ring);
1927
	i915_gem_reset_ring_lists(dev_priv, &dev_priv->blt_ring);
1928 1929 1930 1931 1932 1933

	/* 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)) {
1934 1935 1936
		obj= list_first_entry(&dev_priv->mm.flushing_list,
				      struct drm_i915_gem_object,
				      mm_list);
1937

1938 1939 1940
		obj->base.write_domain = 0;
		list_del_init(&obj->gpu_write_list);
		i915_gem_object_move_to_inactive(obj);
1941 1942 1943 1944 1945
	}

	/* Move everything out of the GPU domains to ensure we do any
	 * necessary invalidation upon reuse.
	 */
1946
	list_for_each_entry(obj,
1947
			    &dev_priv->mm.inactive_list,
1948
			    mm_list)
1949
	{
1950
		obj->base.read_domains &= ~I915_GEM_GPU_DOMAINS;
1951
	}
1952 1953

	/* The fence registers are invalidated so clear them out */
1954
	i915_gem_reset_fences(dev);
1955 1956 1957 1958 1959
}

/**
 * This function clears the request list as sequence numbers are passed.
 */
1960 1961 1962
static void
i915_gem_retire_requests_ring(struct drm_device *dev,
			      struct intel_ring_buffer *ring)
1963 1964 1965 1966
{
	drm_i915_private_t *dev_priv = dev->dev_private;
	uint32_t seqno;

1967 1968
	if (!ring->status_page.page_addr ||
	    list_empty(&ring->request_list))
1969 1970
		return;

1971
	WARN_ON(i915_verify_lists(dev));
1972

1973
	seqno = ring->get_seqno(ring);
1974
	while (!list_empty(&ring->request_list)) {
1975 1976
		struct drm_i915_gem_request *request;

1977
		request = list_first_entry(&ring->request_list,
1978 1979 1980
					   struct drm_i915_gem_request,
					   list);

1981
		if (!i915_seqno_passed(seqno, request->seqno))
1982 1983 1984 1985 1986
			break;

		trace_i915_gem_request_retire(dev, request->seqno);

		list_del(&request->list);
1987
		i915_gem_request_remove_from_client(request);
1988 1989
		kfree(request);
	}
1990

1991 1992 1993 1994
	/* 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)) {
1995
		struct drm_i915_gem_object *obj;
1996

1997 1998 1999
		obj= list_first_entry(&ring->active_list,
				      struct drm_i915_gem_object,
				      ring_list);
2000

2001
		if (!i915_seqno_passed(seqno, obj->last_rendering_seqno))
2002
			break;
2003

2004
		if (obj->base.write_domain != 0)
2005 2006 2007
			i915_gem_object_move_to_flushing(obj);
		else
			i915_gem_object_move_to_inactive(obj);
2008
	}
2009 2010 2011

	if (unlikely (dev_priv->trace_irq_seqno &&
		      i915_seqno_passed(dev_priv->trace_irq_seqno, seqno))) {
2012
		ring->user_irq_put(ring);
2013 2014
		dev_priv->trace_irq_seqno = 0;
	}
2015 2016

	WARN_ON(i915_verify_lists(dev));
2017 2018
}

2019 2020 2021 2022 2023
void
i915_gem_retire_requests(struct drm_device *dev)
{
	drm_i915_private_t *dev_priv = dev->dev_private;

2024
	if (!list_empty(&dev_priv->mm.deferred_free_list)) {
2025
	    struct drm_i915_gem_object *obj, *next;
2026 2027 2028 2029 2030 2031

	    /* We must be careful that during unbind() we do not
	     * accidentally infinitely recurse into retire requests.
	     * Currently:
	     *   retire -> free -> unbind -> wait -> retire_ring
	     */
2032
	    list_for_each_entry_safe(obj, next,
2033
				     &dev_priv->mm.deferred_free_list,
2034
				     mm_list)
2035
		    i915_gem_free_object_tail(obj);
2036 2037
	}

2038
	i915_gem_retire_requests_ring(dev, &dev_priv->render_ring);
2039
	i915_gem_retire_requests_ring(dev, &dev_priv->bsd_ring);
2040
	i915_gem_retire_requests_ring(dev, &dev_priv->blt_ring);
2041 2042
}

2043
static void
2044 2045 2046 2047 2048 2049 2050 2051 2052
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;

2053 2054 2055 2056 2057 2058
	/* 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;
	}

2059
	i915_gem_retire_requests(dev);
2060

2061
	if (!dev_priv->mm.suspended &&
2062
		(!list_empty(&dev_priv->render_ring.request_list) ||
2063 2064
		 !list_empty(&dev_priv->bsd_ring.request_list) ||
		 !list_empty(&dev_priv->blt_ring.request_list)))
2065
		queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, HZ);
2066 2067 2068
	mutex_unlock(&dev->struct_mutex);
}

2069
int
2070
i915_do_wait_request(struct drm_device *dev, uint32_t seqno,
2071
		     bool interruptible, struct intel_ring_buffer *ring)
2072 2073
{
	drm_i915_private_t *dev_priv = dev->dev_private;
2074
	u32 ier;
2075 2076 2077 2078
	int ret = 0;

	BUG_ON(seqno == 0);

2079
	if (atomic_read(&dev_priv->mm.wedged))
2080 2081
		return -EAGAIN;

2082
	if (seqno == ring->outstanding_lazy_request) {
2083 2084 2085 2086
		struct drm_i915_gem_request *request;

		request = kzalloc(sizeof(*request), GFP_KERNEL);
		if (request == NULL)
2087
			return -ENOMEM;
2088 2089 2090 2091 2092 2093 2094 2095

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

		seqno = request->seqno;
2096
	}
2097

2098
	if (!i915_seqno_passed(ring->get_seqno(ring), seqno)) {
2099
		if (HAS_PCH_SPLIT(dev))
2100 2101 2102
			ier = I915_READ(DEIER) | I915_READ(GTIER);
		else
			ier = I915_READ(IER);
2103 2104 2105 2106 2107 2108 2109
		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 已提交
2110 2111
		trace_i915_gem_request_wait_begin(dev, seqno);

2112
		ring->waiting_seqno = seqno;
2113
		ring->user_irq_get(ring);
2114
		if (interruptible)
2115
			ret = wait_event_interruptible(ring->irq_queue,
2116
				i915_seqno_passed(ring->get_seqno(ring), seqno)
2117
				|| atomic_read(&dev_priv->mm.wedged));
2118
		else
2119
			wait_event(ring->irq_queue,
2120
				i915_seqno_passed(ring->get_seqno(ring), seqno)
2121
				|| atomic_read(&dev_priv->mm.wedged));
2122

2123
		ring->user_irq_put(ring);
2124
		ring->waiting_seqno = 0;
C
Chris Wilson 已提交
2125 2126

		trace_i915_gem_request_wait_end(dev, seqno);
2127
	}
2128
	if (atomic_read(&dev_priv->mm.wedged))
2129
		ret = -EAGAIN;
2130 2131

	if (ret && ret != -ERESTARTSYS)
2132
		DRM_ERROR("%s returns %d (awaiting %d at %d, next %d)\n",
2133
			  __func__, ret, seqno, ring->get_seqno(ring),
2134
			  dev_priv->next_seqno);
2135 2136 2137 2138 2139 2140 2141

	/* 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)
2142
		i915_gem_retire_requests_ring(dev, ring);
2143 2144 2145 2146

	return ret;
}

2147 2148 2149 2150 2151
/**
 * Waits for a sequence number to be signaled, and cleans up the
 * request and object lists appropriately for that event.
 */
static int
2152
i915_wait_request(struct drm_device *dev, uint32_t seqno,
2153
		  struct intel_ring_buffer *ring)
2154
{
2155
	return i915_do_wait_request(dev, seqno, 1, ring);
2156 2157
}

2158
static void
2159 2160 2161 2162 2163
i915_gem_flush_ring(struct drm_device *dev,
		    struct intel_ring_buffer *ring,
		    uint32_t invalidate_domains,
		    uint32_t flush_domains)
{
2164
	ring->flush(ring, invalidate_domains, flush_domains);
2165 2166 2167
	i915_gem_process_flushing_list(dev, flush_domains, ring);
}

2168 2169 2170
static void
i915_gem_flush(struct drm_device *dev,
	       uint32_t invalidate_domains,
2171 2172
	       uint32_t flush_domains,
	       uint32_t flush_rings)
2173 2174
{
	drm_i915_private_t *dev_priv = dev->dev_private;
2175

2176
	if (flush_domains & I915_GEM_DOMAIN_CPU)
2177
		intel_gtt_chipset_flush();
2178

2179 2180
	if ((flush_domains | invalidate_domains) & I915_GEM_GPU_DOMAINS) {
		if (flush_rings & RING_RENDER)
2181
			i915_gem_flush_ring(dev, &dev_priv->render_ring,
2182 2183
					    invalidate_domains, flush_domains);
		if (flush_rings & RING_BSD)
2184
			i915_gem_flush_ring(dev, &dev_priv->bsd_ring,
2185
					    invalidate_domains, flush_domains);
2186
		if (flush_rings & RING_BLT)
2187
			i915_gem_flush_ring(dev, &dev_priv->blt_ring,
2188
					    invalidate_domains, flush_domains);
2189
	}
2190 2191
}

2192 2193 2194 2195 2196
/**
 * 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
2197
i915_gem_object_wait_rendering(struct drm_i915_gem_object *obj,
2198
			       bool interruptible)
2199
{
2200
	struct drm_device *dev = obj->base.dev;
2201 2202
	int ret;

2203 2204
	/* This function only exists to support waiting for existing rendering,
	 * not for emitting required flushes.
2205
	 */
2206
	BUG_ON((obj->base.write_domain & I915_GEM_GPU_DOMAINS) != 0);
2207 2208 2209 2210

	/* If there is rendering queued on the buffer being evicted, wait for
	 * it.
	 */
2211
	if (obj->active) {
2212
		ret = i915_do_wait_request(dev,
2213
					   obj->last_rendering_seqno,
2214
					   interruptible,
2215
					   obj->ring);
2216
		if (ret)
2217 2218 2219 2220 2221 2222 2223 2224 2225
			return ret;
	}

	return 0;
}

/**
 * Unbinds an object from the GTT aperture.
 */
2226
int
2227
i915_gem_object_unbind(struct drm_i915_gem_object *obj)
2228
{
2229
	struct drm_device *dev = obj->base.dev;
2230
	struct drm_i915_private *dev_priv = dev->dev_private;
2231 2232
	int ret = 0;

2233
	if (obj->gtt_space == NULL)
2234 2235
		return 0;

2236
	if (obj->pin_count != 0) {
2237 2238 2239 2240
		DRM_ERROR("Attempting to unbind pinned buffer\n");
		return -EINVAL;
	}

2241 2242 2243
	/* blow away mappings if mapped through GTT */
	i915_gem_release_mmap(obj);

2244 2245 2246 2247 2248 2249
	/* 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.
	 */
2250
	ret = i915_gem_object_set_to_cpu_domain(obj, 1);
2251
	if (ret == -ERESTARTSYS)
2252
		return ret;
2253 2254 2255 2256
	/* 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.
	 */
2257 2258
	if (ret) {
		i915_gem_clflush_object(obj);
2259
		obj->base.read_domains = obj->base.write_domain = I915_GEM_DOMAIN_CPU;
2260
	}
2261

2262
	/* release the fence reg _after_ flushing */
2263
	if (obj->fence_reg != I915_FENCE_REG_NONE)
2264 2265
		i915_gem_clear_fence_reg(obj);

2266
	i915_gem_gtt_unbind_object(obj);
2267

2268
	i915_gem_object_put_pages_gtt(obj);
2269

2270 2271
	i915_gem_info_remove_gtt(dev_priv, obj);
	list_del_init(&obj->mm_list);
2272
	/* Avoid an unnecessary call to unbind on rebind. */
2273
	obj->map_and_fenceable = true;
2274

2275 2276 2277
	drm_mm_put_block(obj->gtt_space);
	obj->gtt_space = NULL;
	obj->gtt_offset = 0;
2278

2279
	if (i915_gem_object_is_purgeable(obj))
2280 2281
		i915_gem_object_truncate(obj);

C
Chris Wilson 已提交
2282 2283
	trace_i915_gem_object_unbind(obj);

2284
	return ret;
2285 2286
}

2287 2288 2289
static int i915_ring_idle(struct drm_device *dev,
			  struct intel_ring_buffer *ring)
{
2290
	if (list_empty(&ring->gpu_write_list) && list_empty(&ring->active_list))
2291 2292
		return 0;

2293
	i915_gem_flush_ring(dev, ring,
2294 2295 2296 2297 2298 2299
			    I915_GEM_GPU_DOMAINS, I915_GEM_GPU_DOMAINS);
	return i915_wait_request(dev,
				 i915_gem_next_request_seqno(dev, ring),
				 ring);
}

2300
int
2301 2302 2303 2304
i915_gpu_idle(struct drm_device *dev)
{
	drm_i915_private_t *dev_priv = dev->dev_private;
	bool lists_empty;
2305
	int ret;
2306

2307
	lists_empty = (list_empty(&dev_priv->mm.flushing_list) &&
2308
		       list_empty(&dev_priv->mm.active_list));
2309 2310 2311 2312
	if (lists_empty)
		return 0;

	/* Flush everything onto the inactive list. */
2313
	ret = i915_ring_idle(dev, &dev_priv->render_ring);
2314 2315
	if (ret)
		return ret;
2316

2317 2318 2319
	ret = i915_ring_idle(dev, &dev_priv->bsd_ring);
	if (ret)
		return ret;
2320

2321 2322 2323
	ret = i915_ring_idle(dev, &dev_priv->blt_ring);
	if (ret)
		return ret;
2324

2325
	return 0;
2326 2327
}

2328 2329
static int sandybridge_write_fence_reg(struct drm_i915_gem_object *obj,
				       struct intel_ring_buffer *pipelined)
2330
{
2331
	struct drm_device *dev = obj->base.dev;
2332
	drm_i915_private_t *dev_priv = dev->dev_private;
2333 2334
	u32 size = obj->gtt_space->size;
	int regnum = obj->fence_reg;
2335 2336
	uint64_t val;

2337
	val = (uint64_t)((obj->gtt_offset + size - 4096) &
2338
			 0xfffff000) << 32;
2339 2340
	val |= obj->gtt_offset & 0xfffff000;
	val |= (uint64_t)((obj->stride / 128) - 1) <<
2341 2342
		SANDYBRIDGE_FENCE_PITCH_SHIFT;

2343
	if (obj->tiling_mode == I915_TILING_Y)
2344 2345 2346
		val |= 1 << I965_FENCE_TILING_Y_SHIFT;
	val |= I965_FENCE_REG_VALID;

2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362
	if (pipelined) {
		int ret = intel_ring_begin(pipelined, 6);
		if (ret)
			return ret;

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

	return 0;
2363 2364
}

2365 2366
static int i965_write_fence_reg(struct drm_i915_gem_object *obj,
				struct intel_ring_buffer *pipelined)
2367
{
2368
	struct drm_device *dev = obj->base.dev;
2369
	drm_i915_private_t *dev_priv = dev->dev_private;
2370 2371
	u32 size = obj->gtt_space->size;
	int regnum = obj->fence_reg;
2372 2373
	uint64_t val;

2374
	val = (uint64_t)((obj->gtt_offset + size - 4096) &
2375
		    0xfffff000) << 32;
2376 2377 2378
	val |= obj->gtt_offset & 0xfffff000;
	val |= ((obj->stride / 128) - 1) << I965_FENCE_PITCH_SHIFT;
	if (obj->tiling_mode == I915_TILING_Y)
2379 2380 2381
		val |= 1 << I965_FENCE_TILING_Y_SHIFT;
	val |= I965_FENCE_REG_VALID;

2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397
	if (pipelined) {
		int ret = intel_ring_begin(pipelined, 6);
		if (ret)
			return ret;

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

	return 0;
2398 2399
}

2400 2401
static int i915_write_fence_reg(struct drm_i915_gem_object *obj,
				struct intel_ring_buffer *pipelined)
2402
{
2403
	struct drm_device *dev = obj->base.dev;
2404
	drm_i915_private_t *dev_priv = dev->dev_private;
2405
	u32 size = obj->gtt_space->size;
2406
	u32 fence_reg, val, pitch_val;
2407
	int tile_width;
2408

2409 2410 2411 2412 2413 2414
	if (WARN((obj->gtt_offset & ~I915_FENCE_START_MASK) ||
		 (size & -size) != size ||
		 (obj->gtt_offset & (size - 1)),
		 "object 0x%08x [fenceable? %d] not 1M or pot-size (0x%08x) aligned\n",
		 obj->gtt_offset, obj->map_and_fenceable, size))
		return -EINVAL;
2415

2416
	if (obj->tiling_mode == I915_TILING_Y && HAS_128_BYTE_Y_TILING(dev))
2417
		tile_width = 128;
2418
	else
2419 2420 2421
		tile_width = 512;

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

2425 2426
	val = obj->gtt_offset;
	if (obj->tiling_mode == I915_TILING_Y)
2427
		val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2428
	val |= I915_FENCE_SIZE_BITS(size);
2429 2430 2431
	val |= pitch_val << I830_FENCE_PITCH_SHIFT;
	val |= I830_FENCE_REG_VALID;

2432
	fence_reg = obj->fence_reg;
2433 2434
	if (fence_reg < 8)
		fence_reg = FENCE_REG_830_0 + fence_reg * 4;
2435
	else
2436
		fence_reg = FENCE_REG_945_8 + (fence_reg - 8) * 4;
2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451

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

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

	return 0;
2452 2453
}

2454 2455
static int i830_write_fence_reg(struct drm_i915_gem_object *obj,
				struct intel_ring_buffer *pipelined)
2456
{
2457
	struct drm_device *dev = obj->base.dev;
2458
	drm_i915_private_t *dev_priv = dev->dev_private;
2459 2460
	u32 size = obj->gtt_space->size;
	int regnum = obj->fence_reg;
2461 2462 2463
	uint32_t val;
	uint32_t pitch_val;

2464 2465 2466 2467 2468 2469
	if (WARN((obj->gtt_offset & ~I830_FENCE_START_MASK) ||
		 (size & -size) != size ||
		 (obj->gtt_offset & (size - 1)),
		 "object 0x%08x not 512K or pot-size 0x%08x aligned\n",
		 obj->gtt_offset, size))
		return -EINVAL;
2470

2471
	pitch_val = obj->stride / 128;
2472 2473
	pitch_val = ffs(pitch_val) - 1;

2474 2475
	val = obj->gtt_offset;
	if (obj->tiling_mode == I915_TILING_Y)
2476
		val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2477
	val |= I830_FENCE_SIZE_BITS(size);
2478 2479 2480
	val |= pitch_val << I830_FENCE_PITCH_SHIFT;
	val |= I830_FENCE_REG_VALID;

2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494
	if (pipelined) {
		int ret = intel_ring_begin(pipelined, 4);
		if (ret)
			return ret;

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

	return 0;
2495 2496
}

2497 2498
static int i915_find_fence_reg(struct drm_device *dev,
			       bool interruptible)
2499 2500
{
	struct drm_i915_private *dev_priv = dev->dev_private;
2501
	struct drm_i915_fence_reg *reg;
2502
	struct drm_i915_gem_object *obj = NULL;
2503 2504 2505 2506 2507 2508 2509 2510 2511
	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;

2512 2513
		if (!reg->obj->pin_count)
			avail++;
2514 2515 2516 2517 2518 2519
	}

	if (avail == 0)
		return -ENOSPC;

	/* None available, try to steal one or wait for a user to finish */
2520
	avail = I915_FENCE_REG_NONE;
2521 2522
	list_for_each_entry(reg, &dev_priv->mm.fence_list,
			    lru_list) {
2523 2524
		obj = reg->obj;
		if (obj->pin_count)
2525 2526 2527
			continue;

		/* found one! */
2528
		avail = obj->fence_reg;
2529 2530 2531
		break;
	}

2532
	BUG_ON(avail == I915_FENCE_REG_NONE);
2533 2534 2535 2536 2537

	/* 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. */
2538 2539 2540
	drm_gem_object_reference(&obj->base);
	ret = i915_gem_object_put_fence_reg(obj, interruptible);
	drm_gem_object_unreference(&obj->base);
2541 2542 2543
	if (ret != 0)
		return ret;

2544
	return avail;
2545 2546
}

2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559
/**
 * 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.
 */
2560
int
2561
i915_gem_object_get_fence_reg(struct drm_i915_gem_object *obj,
2562
			      bool interruptible)
2563
{
2564
	struct drm_device *dev = obj->base.dev;
J
Jesse Barnes 已提交
2565
	struct drm_i915_private *dev_priv = dev->dev_private;
2566
	struct drm_i915_fence_reg *reg = NULL;
2567
	struct intel_ring_buffer *pipelined = NULL;
2568
	int ret;
2569

2570
	/* Just update our place in the LRU if our fence is getting used. */
2571 2572
	if (obj->fence_reg != I915_FENCE_REG_NONE) {
		reg = &dev_priv->fence_regs[obj->fence_reg];
2573
		list_move_tail(&reg->lru_list, &dev_priv->mm.fence_list);
2574 2575 2576
		return 0;
	}

2577
	switch (obj->tiling_mode) {
2578 2579 2580 2581
	case I915_TILING_NONE:
		WARN(1, "allocating a fence for non-tiled object?\n");
		break;
	case I915_TILING_X:
2582
		if (!obj->stride)
2583
			return -EINVAL;
2584
		WARN((obj->stride & (512 - 1)),
2585
		     "object 0x%08x is X tiled but has non-512B pitch\n",
2586
		     obj->gtt_offset);
2587 2588
		break;
	case I915_TILING_Y:
2589
		if (!obj->stride)
2590
			return -EINVAL;
2591
		WARN((obj->stride & (128 - 1)),
2592
		     "object 0x%08x is Y tiled but has non-128B pitch\n",
2593
		     obj->gtt_offset);
2594 2595 2596
		break;
	}

2597
	ret = i915_find_fence_reg(dev, interruptible);
2598 2599
	if (ret < 0)
		return ret;
2600

2601 2602
	obj->fence_reg = ret;
	reg = &dev_priv->fence_regs[obj->fence_reg];
2603
	list_add_tail(&reg->lru_list, &dev_priv->mm.fence_list);
2604

2605 2606
	reg->obj = obj;

2607 2608
	switch (INTEL_INFO(dev)->gen) {
	case 6:
2609
		ret = sandybridge_write_fence_reg(obj, pipelined);
2610 2611 2612
		break;
	case 5:
	case 4:
2613
		ret = i965_write_fence_reg(obj, pipelined);
2614 2615
		break;
	case 3:
2616
		ret = i915_write_fence_reg(obj, pipelined);
2617 2618
		break;
	case 2:
2619
		ret = i830_write_fence_reg(obj, pipelined);
2620 2621
		break;
	}
2622

2623
	trace_i915_gem_object_get_fence(obj,
2624 2625
					obj->fence_reg,
					obj->tiling_mode);
2626
	return ret;
2627 2628 2629 2630 2631 2632 2633
}

/**
 * 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
2634
 * data structures in dev_priv and obj.
2635 2636
 */
static void
2637
i915_gem_clear_fence_reg(struct drm_i915_gem_object *obj)
2638
{
2639
	struct drm_device *dev = obj->base.dev;
J
Jesse Barnes 已提交
2640
	drm_i915_private_t *dev_priv = dev->dev_private;
2641
	struct drm_i915_fence_reg *reg = &dev_priv->fence_regs[obj->fence_reg];
2642
	uint32_t fence_reg;
2643

2644 2645
	switch (INTEL_INFO(dev)->gen) {
	case 6:
2646
		I915_WRITE64(FENCE_REG_SANDYBRIDGE_0 +
2647
			     (obj->fence_reg * 8), 0);
2648 2649 2650
		break;
	case 5:
	case 4:
2651
		I915_WRITE64(FENCE_REG_965_0 + (obj->fence_reg * 8), 0);
2652 2653
		break;
	case 3:
2654 2655
		if (obj->fence_reg >= 8)
			fence_reg = FENCE_REG_945_8 + (obj->fence_reg - 8) * 4;
2656
		else
2657
	case 2:
2658
			fence_reg = FENCE_REG_830_0 + obj->fence_reg * 4;
2659 2660

		I915_WRITE(fence_reg, 0);
2661
		break;
2662
	}
2663

2664
	reg->obj = NULL;
2665
	obj->fence_reg = I915_FENCE_REG_NONE;
2666
	list_del_init(&reg->lru_list);
2667 2668
}

2669 2670 2671 2672
/**
 * 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.
2673
 * @bool: whether the wait upon the fence is interruptible
2674 2675
 *
 * Zeroes out the fence register itself and clears out the associated
2676
 * data structures in dev_priv and obj.
2677 2678
 */
int
2679
i915_gem_object_put_fence_reg(struct drm_i915_gem_object *obj,
2680
			      bool interruptible)
2681
{
2682
	struct drm_device *dev = obj->base.dev;
2683
	int ret;
2684

2685
	if (obj->fence_reg == I915_FENCE_REG_NONE)
2686 2687
		return 0;

2688 2689 2690 2691 2692 2693
	/* 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);

2694 2695 2696 2697
	/* 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.
	 */
2698
	if (obj->fenced_gpu_access) {
2699
		ret = i915_gem_object_flush_gpu_write_domain(obj, NULL);
2700
		if (ret)
2701 2702
			return ret;

2703 2704 2705 2706 2707 2708 2709 2710
		obj->fenced_gpu_access = false;
	}

	if (obj->last_fenced_seqno) {
		ret = i915_do_wait_request(dev,
					   obj->last_fenced_seqno,
					   interruptible,
					   obj->last_fenced_ring);
2711
		if (ret)
2712
			return ret;
C
Chris Wilson 已提交
2713

2714
		obj->last_fenced_seqno = false;
2715 2716
	}

2717
	i915_gem_object_flush_gtt_write_domain(obj);
2718
	i915_gem_clear_fence_reg(obj);
2719 2720 2721 2722

	return 0;
}

2723 2724 2725 2726
/**
 * Finds free space in the GTT aperture and binds the object there.
 */
static int
2727
i915_gem_object_bind_to_gtt(struct drm_i915_gem_object *obj,
2728
			    unsigned alignment,
2729
			    bool map_and_fenceable)
2730
{
2731
	struct drm_device *dev = obj->base.dev;
2732 2733
	drm_i915_private_t *dev_priv = dev->dev_private;
	struct drm_mm_node *free_space;
2734
	gfp_t gfpmask = __GFP_NORETRY | __GFP_NOWARN;
2735
	u32 size, fence_size, fence_alignment, unfenced_alignment;
2736
	bool mappable, fenceable;
2737
	int ret;
2738

2739
	if (obj->madv != I915_MADV_WILLNEED) {
2740 2741 2742 2743
		DRM_ERROR("Attempting to bind a purgeable object\n");
		return -EINVAL;
	}

2744 2745 2746
	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);
2747

2748
	if (alignment == 0)
2749 2750
		alignment = map_and_fenceable ? fence_alignment :
						unfenced_alignment;
2751
	if (map_and_fenceable && alignment & (fence_alignment - 1)) {
2752 2753 2754 2755
		DRM_ERROR("Invalid object alignment requested %u\n", alignment);
		return -EINVAL;
	}

2756
	size = map_and_fenceable ? fence_size : obj->base.size;
2757

2758 2759 2760
	/* If the object is bigger than the entire aperture, reject it early
	 * before evicting everything in a vain attempt to find space.
	 */
2761
	if (obj->base.size >
2762
	    (map_and_fenceable ? dev_priv->mm.gtt_mappable_end : dev_priv->mm.gtt_total)) {
2763 2764 2765 2766
		DRM_ERROR("Attempting to bind an object larger than the aperture\n");
		return -E2BIG;
	}

2767
 search_free:
2768
	if (map_and_fenceable)
2769 2770
		free_space =
			drm_mm_search_free_in_range(&dev_priv->mm.gtt_space,
2771
						    size, alignment, 0,
2772 2773 2774 2775
						    dev_priv->mm.gtt_mappable_end,
						    0);
	else
		free_space = drm_mm_search_free(&dev_priv->mm.gtt_space,
2776
						size, alignment, 0);
2777 2778

	if (free_space != NULL) {
2779
		if (map_and_fenceable)
2780
			obj->gtt_space =
2781
				drm_mm_get_block_range_generic(free_space,
2782
							       size, alignment, 0,
2783 2784 2785
							       dev_priv->mm.gtt_mappable_end,
							       0);
		else
2786
			obj->gtt_space =
2787
				drm_mm_get_block(free_space, size, alignment);
2788
	}
2789
	if (obj->gtt_space == NULL) {
2790 2791 2792
		/* If the gtt is empty and we're still having trouble
		 * fitting our object in, we're out of memory.
		 */
2793 2794
		ret = i915_gem_evict_something(dev, size, alignment,
					       map_and_fenceable);
2795
		if (ret)
2796
			return ret;
2797

2798 2799 2800
		goto search_free;
	}

2801
	ret = i915_gem_object_get_pages_gtt(obj, gfpmask);
2802
	if (ret) {
2803 2804
		drm_mm_put_block(obj->gtt_space);
		obj->gtt_space = NULL;
2805 2806 2807

		if (ret == -ENOMEM) {
			/* first try to clear up some space from the GTT */
2808
			ret = i915_gem_evict_something(dev, size,
2809 2810
						       alignment,
						       map_and_fenceable);
2811 2812
			if (ret) {
				/* now try to shrink everyone else */
2813 2814 2815
				if (gfpmask) {
					gfpmask = 0;
					goto search_free;
2816 2817 2818 2819 2820 2821 2822 2823
				}

				return ret;
			}

			goto search_free;
		}

2824 2825 2826
		return ret;
	}

2827 2828
	ret = i915_gem_gtt_bind_object(obj);
	if (ret) {
2829
		i915_gem_object_put_pages_gtt(obj);
2830 2831
		drm_mm_put_block(obj->gtt_space);
		obj->gtt_space = NULL;
2832

2833
		ret = i915_gem_evict_something(dev, size,
2834
					       alignment, map_and_fenceable);
2835
		if (ret)
2836 2837 2838
			return ret;

		goto search_free;
2839 2840
	}

2841
	obj->gtt_offset = obj->gtt_space->start;
2842

2843
	/* keep track of bounds object by adding it to the inactive list */
2844 2845
	list_add_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
	i915_gem_info_add_gtt(dev_priv, obj);
2846

2847 2848 2849 2850
	/* 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
	 */
2851 2852
	BUG_ON(obj->base.read_domains & I915_GEM_GPU_DOMAINS);
	BUG_ON(obj->base.write_domain & I915_GEM_GPU_DOMAINS);
2853

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

2856
	fenceable =
2857 2858
		obj->gtt_space->size == fence_size &&
		(obj->gtt_space->start & (fence_alignment -1)) == 0;
2859

2860
	mappable =
2861
		obj->gtt_offset + obj->base.size <= dev_priv->mm.gtt_mappable_end;
2862

2863
	obj->map_and_fenceable = mappable && fenceable;
2864

2865 2866 2867 2868
	return 0;
}

void
2869
i915_gem_clflush_object(struct drm_i915_gem_object *obj)
2870 2871 2872 2873 2874
{
	/* 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.
	 */
2875
	if (obj->pages == NULL)
2876 2877
		return;

C
Chris Wilson 已提交
2878
	trace_i915_gem_object_clflush(obj);
2879

2880
	drm_clflush_pages(obj->pages, obj->base.size / PAGE_SIZE);
2881 2882
}

2883
/** Flushes any GPU write domain for the object if it's dirty. */
2884
static int
2885
i915_gem_object_flush_gpu_write_domain(struct drm_i915_gem_object *obj,
2886
				       struct intel_ring_buffer *pipelined)
2887
{
2888
	struct drm_device *dev = obj->base.dev;
2889

2890
	if ((obj->base.write_domain & I915_GEM_GPU_DOMAINS) == 0)
2891
		return 0;
2892 2893

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

2897
	if (pipelined && pipelined == obj->ring)
2898 2899
		return 0;

2900
	return i915_gem_object_wait_rendering(obj, true);
2901 2902 2903 2904
}

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

2909
	if (obj->base.write_domain != I915_GEM_DOMAIN_GTT)
2910 2911 2912 2913 2914 2915
		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.
	 */
2916 2917
	i915_gem_release_mmap(obj);

2918 2919
	old_write_domain = obj->base.write_domain;
	obj->base.write_domain = 0;
C
Chris Wilson 已提交
2920 2921

	trace_i915_gem_object_change_domain(obj,
2922
					    obj->base.read_domains,
C
Chris Wilson 已提交
2923
					    old_write_domain);
2924 2925 2926 2927
}

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

2932
	if (obj->base.write_domain != I915_GEM_DOMAIN_CPU)
2933 2934 2935
		return;

	i915_gem_clflush_object(obj);
2936
	intel_gtt_chipset_flush();
2937 2938
	old_write_domain = obj->base.write_domain;
	obj->base.write_domain = 0;
C
Chris Wilson 已提交
2939 2940

	trace_i915_gem_object_change_domain(obj,
2941
					    obj->base.read_domains,
C
Chris Wilson 已提交
2942
					    old_write_domain);
2943 2944
}

2945 2946 2947 2948 2949 2950
/**
 * 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 已提交
2951
int
2952
i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, int write)
2953
{
C
Chris Wilson 已提交
2954
	uint32_t old_write_domain, old_read_domains;
2955
	int ret;
2956

2957
	/* Not valid to be called on unbound objects. */
2958
	if (obj->gtt_space == NULL)
2959 2960
		return -EINVAL;

2961
	ret = i915_gem_object_flush_gpu_write_domain(obj, NULL);
2962 2963 2964
	if (ret != 0)
		return ret;

2965
	i915_gem_object_flush_cpu_write_domain(obj);
C
Chris Wilson 已提交
2966

2967
	if (write) {
2968
		ret = i915_gem_object_wait_rendering(obj, true);
2969 2970 2971
		if (ret)
			return ret;
	}
2972

2973 2974
	old_write_domain = obj->base.write_domain;
	old_read_domains = obj->base.read_domains;
C
Chris Wilson 已提交
2975

2976 2977 2978
	/* It should now be out of any other write domains, and we can update
	 * the domain values for our changes.
	 */
2979 2980
	BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
	obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
2981
	if (write) {
2982 2983 2984
		obj->base.read_domains = I915_GEM_DOMAIN_GTT;
		obj->base.write_domain = I915_GEM_DOMAIN_GTT;
		obj->dirty = 1;
2985 2986
	}

C
Chris Wilson 已提交
2987 2988 2989 2990
	trace_i915_gem_object_change_domain(obj,
					    old_read_domains,
					    old_write_domain);

2991 2992 2993
	return 0;
}

2994 2995 2996 2997 2998
/*
 * Prepare buffer for display plane. Use uninterruptible for possible flush
 * wait, as in modesetting process we're not supposed to be interrupted.
 */
int
2999
i915_gem_object_set_to_display_plane(struct drm_i915_gem_object *obj,
3000
				     struct intel_ring_buffer *pipelined)
3001
{
3002
	uint32_t old_read_domains;
3003 3004 3005
	int ret;

	/* Not valid to be called on unbound objects. */
3006
	if (obj->gtt_space == NULL)
3007 3008
		return -EINVAL;

3009
	ret = i915_gem_object_flush_gpu_write_domain(obj, pipelined);
3010 3011
	if (ret)
		return ret;
3012

3013 3014 3015 3016
	/* Currently, we are always called from an non-interruptible context. */
	if (!pipelined) {
		ret = i915_gem_object_wait_rendering(obj, false);
		if (ret)
3017 3018 3019
			return ret;
	}

3020 3021
	i915_gem_object_flush_cpu_write_domain(obj);

3022 3023
	old_read_domains = obj->base.read_domains;
	obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
3024 3025 3026

	trace_i915_gem_object_change_domain(obj,
					    old_read_domains,
3027
					    obj->base.write_domain);
3028 3029 3030 3031

	return 0;
}

3032 3033 3034 3035 3036 3037 3038 3039
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)
3040
		i915_gem_flush_ring(obj->base.dev, obj->ring,
3041 3042
				    0, obj->base.write_domain);

3043
	return i915_gem_object_wait_rendering(obj, interruptible);
3044 3045
}

3046 3047 3048 3049 3050 3051 3052
/**
 * 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
3053
i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj, bool write)
3054
{
C
Chris Wilson 已提交
3055
	uint32_t old_write_domain, old_read_domains;
3056 3057
	int ret;

3058
	ret = i915_gem_object_flush_gpu_write_domain(obj, false);
3059 3060
	if (ret != 0)
		return ret;
3061

3062
	i915_gem_object_flush_gtt_write_domain(obj);
3063

3064 3065
	/* If we have a partially-valid cache of the object in the CPU,
	 * finish invalidating it and free the per-page flags.
3066
	 */
3067
	i915_gem_object_set_to_full_cpu_read_domain(obj);
3068

3069
	if (write) {
3070
		ret = i915_gem_object_wait_rendering(obj, true);
3071 3072 3073 3074
		if (ret)
			return ret;
	}

3075 3076
	old_write_domain = obj->base.write_domain;
	old_read_domains = obj->base.read_domains;
C
Chris Wilson 已提交
3077

3078
	/* Flush the CPU cache if it's still invalid. */
3079
	if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0) {
3080 3081
		i915_gem_clflush_object(obj);

3082
		obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
3083 3084 3085 3086 3087
	}

	/* It should now be out of any other write domains, and we can update
	 * the domain values for our changes.
	 */
3088
	BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
3089 3090 3091 3092 3093

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

C
Chris Wilson 已提交
3098 3099 3100 3101
	trace_i915_gem_object_change_domain(obj,
					    old_read_domains,
					    old_write_domain);

3102 3103 3104
	return 0;
}

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 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215
/*
 * 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
 */
3216
static void
3217
i915_gem_object_set_to_gpu_domain(struct drm_i915_gem_object *obj,
3218 3219
				  struct intel_ring_buffer *ring,
				  struct change_domains *cd)
3220
{
3221
	uint32_t invalidate_domains = 0, flush_domains = 0;
3222

3223 3224 3225 3226
	/*
	 * If the object isn't moving to a new write domain,
	 * let the object stay in multiple read domains
	 */
3227 3228
	if (obj->base.pending_write_domain == 0)
		obj->base.pending_read_domains |= obj->base.read_domains;
3229 3230 3231 3232 3233 3234 3235

	/*
	 * Flush the current write domain if
	 * the new read domains don't match. Invalidate
	 * any read domains which differ from the old
	 * write domain
	 */
3236
	if (obj->base.write_domain &&
3237 3238 3239
	    (((obj->base.write_domain != obj->base.pending_read_domains ||
	       obj->ring != ring)) ||
	     (obj->fenced_gpu_access && !obj->pending_fenced_gpu_access))) {
3240
		flush_domains |= obj->base.write_domain;
3241
		invalidate_domains |=
3242
			obj->base.pending_read_domains & ~obj->base.write_domain;
3243 3244 3245 3246 3247
	}
	/*
	 * Invalidate any read caches which may have
	 * stale data. That is, any new read domains.
	 */
3248
	invalidate_domains |= obj->base.pending_read_domains & ~obj->base.read_domains;
3249
	if ((flush_domains | invalidate_domains) & I915_GEM_DOMAIN_CPU)
3250 3251
		i915_gem_clflush_object(obj);

3252 3253 3254 3255
	/* blow away mappings if mapped through GTT */
	if ((flush_domains | invalidate_domains) & I915_GEM_DOMAIN_GTT)
		i915_gem_release_mmap(obj);

3256 3257 3258 3259 3260 3261
	/* 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.
	 */
3262 3263
	if (flush_domains == 0 && obj->base.pending_write_domain == 0)
		obj->base.pending_write_domain = obj->base.write_domain;
3264

3265 3266
	cd->invalidate_domains |= invalidate_domains;
	cd->flush_domains |= flush_domains;
3267
	if (flush_domains & I915_GEM_GPU_DOMAINS)
3268
		cd->flush_rings |= obj->ring->id;
3269
	if (invalidate_domains & I915_GEM_GPU_DOMAINS)
3270
		cd->flush_rings |= ring->id;
3271 3272 3273
}

/**
3274
 * Moves the object from a partially CPU read to a full one.
3275
 *
3276 3277
 * 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).
3278
 */
3279
static void
3280
i915_gem_object_set_to_full_cpu_read_domain(struct drm_i915_gem_object *obj)
3281
{
3282
	if (!obj->page_cpu_valid)
3283 3284 3285 3286
		return;

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

3290 3291
		for (i = 0; i <= (obj->base.size - 1) / PAGE_SIZE; i++) {
			if (obj->page_cpu_valid[i])
3292
				continue;
3293
			drm_clflush_pages(obj->pages + i, 1);
3294 3295 3296 3297 3298 3299
		}
	}

	/* Free the page_cpu_valid mappings which are now stale, whether
	 * or not we've got I915_GEM_DOMAIN_CPU.
	 */
3300 3301
	kfree(obj->page_cpu_valid);
	obj->page_cpu_valid = NULL;
3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316
}

/**
 * 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
3317
i915_gem_object_set_cpu_read_domain_range(struct drm_i915_gem_object *obj,
3318 3319
					  uint64_t offset, uint64_t size)
{
C
Chris Wilson 已提交
3320
	uint32_t old_read_domains;
3321
	int i, ret;
3322

3323
	if (offset == 0 && size == obj->base.size)
3324
		return i915_gem_object_set_to_cpu_domain(obj, 0);
3325

3326
	ret = i915_gem_object_flush_gpu_write_domain(obj, false);
3327
	if (ret != 0)
3328
		return ret;
3329 3330 3331
	i915_gem_object_flush_gtt_write_domain(obj);

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

3336 3337 3338
	/* Otherwise, create/clear the per-page CPU read domain flag if we're
	 * newly adding I915_GEM_DOMAIN_CPU
	 */
3339 3340 3341 3342
	if (obj->page_cpu_valid == NULL) {
		obj->page_cpu_valid = kzalloc(obj->base.size / PAGE_SIZE,
					      GFP_KERNEL);
		if (obj->page_cpu_valid == NULL)
3343
			return -ENOMEM;
3344 3345
	} else if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0)
		memset(obj->page_cpu_valid, 0, obj->base.size / PAGE_SIZE);
3346 3347 3348 3349

	/* Flush the cache on any pages that are still invalid from the CPU's
	 * perspective.
	 */
3350 3351
	for (i = offset / PAGE_SIZE; i <= (offset + size - 1) / PAGE_SIZE;
	     i++) {
3352
		if (obj->page_cpu_valid[i])
3353 3354
			continue;

3355
		drm_clflush_pages(obj->pages + i, 1);
3356

3357
		obj->page_cpu_valid[i] = 1;
3358 3359
	}

3360 3361 3362
	/* It should now be out of any other write domains, and we can update
	 * the domain values for our changes.
	 */
3363
	BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
3364

3365 3366
	old_read_domains = obj->base.read_domains;
	obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
3367

C
Chris Wilson 已提交
3368 3369
	trace_i915_gem_object_change_domain(obj,
					    old_read_domains,
3370
					    obj->base.write_domain);
C
Chris Wilson 已提交
3371

3372 3373 3374 3375
	return 0;
}

static int
3376 3377 3378 3379
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)
3380
{
3381
	struct drm_device *dev = obj->base.dev;
3382 3383 3384
	struct drm_gem_object *target_obj;
	uint32_t target_offset;
	int ret = -EINVAL;
3385

3386 3387 3388 3389
	target_obj = drm_gem_object_lookup(dev, file_priv,
					   reloc->target_handle);
	if (target_obj == NULL)
		return -ENOENT;
3390

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

3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406
#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
3407

3408 3409 3410 3411 3412 3413 3414 3415
	/* 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;
	}
3416

3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449
	/* 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;
	}
3450

3451 3452
	target_obj->pending_read_domains |= reloc->read_domains;
	target_obj->pending_write_domain |= reloc->write_domain;
3453

3454 3455 3456 3457 3458
	/* 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;
3459

3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475
	/* 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;
	}
3476

3477 3478 3479 3480 3481 3482 3483 3484 3485
	/* 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;
	}
3486

3487 3488 3489 3490
	reloc->delta += target_offset;
	if (obj->base.write_domain == I915_GEM_DOMAIN_CPU) {
		uint32_t page_offset = reloc->offset & ~PAGE_MASK;
		char *vaddr;
3491

3492 3493 3494 3495 3496 3497 3498
		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;
3499

3500
		ret = i915_gem_object_set_to_gtt_domain(obj, 1);
3501 3502
		if (ret)
			goto err;
3503

3504 3505 3506 3507 3508 3509 3510 3511 3512
		/* 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);
	}
3513

3514 3515
	/* and update the user's relocation entry */
	reloc->presumed_offset = target_offset;
3516

3517 3518 3519 3520 3521 3522
out:
	ret = 0;
err:
	drm_gem_object_unreference(target_obj);
	return ret;
}
3523

3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543
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;
3544

3545
		if (__copy_to_user_inatomic(&user_relocs[i].presumed_offset,
3546 3547 3548
					    &reloc.presumed_offset,
					    sizeof(reloc.presumed_offset)))
			return -EFAULT;
3549 3550
	}

3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568
	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;
3569 3570
}

3571
static int
3572 3573
i915_gem_execbuffer_relocate(struct drm_device *dev,
			     struct drm_file *file,
3574
			     struct drm_i915_gem_object **object_list,
3575 3576 3577 3578 3579 3580
			     struct drm_i915_gem_exec_object2 *exec_list,
			     int count)
{
	int i, ret;

	for (i = 0; i < count; i++) {
3581
		struct drm_i915_gem_object *obj = object_list[i];
3582 3583 3584 3585 3586 3587 3588 3589 3590
		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;
3591 3592
}

3593
static int
3594 3595
i915_gem_execbuffer_reserve(struct drm_device *dev,
			    struct drm_file *file,
3596
			    struct drm_i915_gem_object **object_list,
3597 3598
			    struct drm_i915_gem_exec_object2 *exec_list,
			    int count)
3599
{
3600
	int ret, i, retry;
3601

C
Chris Wilson 已提交
3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613
	/* Attempt to pin all of the buffers into the GTT.
	 * This is done in 3 phases:
	 *
	 * 1a. Unbind all objects that do not match the GTT constraints for
	 *     the execbuffer (fenceable, mappable, alignment etc).
	 * 1b. Increment pin count for already bound objects.
	 * 2.  Bind new objects.
	 * 3.  Decrement pin count.
	 *
	 * This avoid unnecessary unbinding of later objects in order to makr
	 * room for the earlier objects *unless* we need to defragment.
	 */
3614 3615
	retry = 0;
	do {
3616
		ret = 0;
C
Chris Wilson 已提交
3617 3618

		/* Unbind any ill-fitting objects or pin. */
3619
		for (i = 0; i < count; i++) {
3620
			struct drm_i915_gem_object *obj = object_list[i];
C
Chris Wilson 已提交
3621 3622 3623 3624 3625 3626 3627
			struct drm_i915_gem_exec_object2 *entry = &exec_list[i];
			bool need_fence, need_mappable;

			if (!obj->gtt_space)
				continue;

			need_fence =
3628 3629
				entry->flags & EXEC_OBJECT_NEEDS_FENCE &&
				obj->tiling_mode != I915_TILING_NONE;
C
Chris Wilson 已提交
3630
			need_mappable =
3631 3632
				entry->relocation_count ? true : need_fence;

C
Chris Wilson 已提交
3633 3634
			if ((entry->alignment && obj->gtt_offset & (entry->alignment - 1)) ||
			    (need_mappable && !obj->map_and_fenceable))
3635
				ret = i915_gem_object_unbind(obj);
C
Chris Wilson 已提交
3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662
			else
				ret = i915_gem_object_pin(obj,
							  entry->alignment,
							  need_mappable);
			if (ret) {
				count = i;
				goto err;
			}
		}

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

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

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

				ret = i915_gem_object_pin(obj,
							  entry->alignment,
							  need_mappable);
3663 3664 3665
				if (ret)
					break;
			}
3666

3667
			if (need_fence) {
3668
				ret = i915_gem_object_get_fence_reg(obj, true);
C
Chris Wilson 已提交
3669
				if (ret)
3670
					break;
3671

3672
				obj->pending_fenced_gpu_access = true;
3673
			}
3674

3675
			entry->offset = obj->gtt_offset;
3676 3677
		}

C
Chris Wilson 已提交
3678 3679 3680 3681 3682 3683
err:		/* Decrement pin count for bound objects */
		for (i = 0; i < count; i++) {
			struct drm_i915_gem_object *obj = object_list[i];
			if (obj->gtt_space)
				i915_gem_object_unpin(obj);
		}
3684

3685
		if (ret != -ENOSPC || retry > 1)
3686 3687
			return ret;

3688 3689 3690 3691
		/* First attempt, just clear anything that is purgeable.
		 * Second attempt, clear the entire GTT.
		 */
		ret = i915_gem_evict_everything(dev, retry == 0);
3692 3693
		if (ret)
			return ret;
3694

3695 3696
		retry++;
	} while (1);
3697 3698
}

3699 3700 3701
static int
i915_gem_execbuffer_relocate_slow(struct drm_device *dev,
				  struct drm_file *file,
3702
				  struct drm_i915_gem_object **object_list,
3703 3704 3705 3706 3707 3708
				  struct drm_i915_gem_exec_object2 *exec_list,
				  int count)
{
	struct drm_i915_gem_relocation_entry *reloc;
	int i, total, ret;

3709 3710
	for (i = 0; i < count; i++)
		object_list[i]->in_execbuffer = false;
3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754

	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++) {
3755
		struct drm_i915_gem_object *obj = object_list[i];
3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777
		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;
}

3778 3779 3780 3781
static int
i915_gem_execbuffer_move_to_gpu(struct drm_device *dev,
				struct drm_file *file,
				struct intel_ring_buffer *ring,
3782
				struct drm_i915_gem_object **objects,
3783 3784
				int count)
{
3785
	struct change_domains cd;
3786 3787
	int ret, i;

3788 3789 3790
	cd.invalidate_domains = 0;
	cd.flush_domains = 0;
	cd.flush_rings = 0;
3791
	for (i = 0; i < count; i++)
3792
		i915_gem_object_set_to_gpu_domain(objects[i], ring, &cd);
3793

3794
	if (cd.invalidate_domains | cd.flush_domains) {
3795 3796 3797
#if WATCH_EXEC
		DRM_INFO("%s: invalidate_domains %08x flush_domains %08x\n",
			  __func__,
3798 3799
			 cd.invalidate_domains,
			 cd.flush_domains);
3800
#endif
3801
		i915_gem_flush(dev,
3802 3803 3804
			       cd.invalidate_domains,
			       cd.flush_domains,
			       cd.flush_rings);
3805 3806 3807
	}

	for (i = 0; i < count; i++) {
3808
		struct drm_i915_gem_object *obj = objects[i];
3809 3810
		/* XXX replace with semaphores */
		if (obj->ring && ring != obj->ring) {
3811
			ret = i915_gem_object_wait_rendering(obj, true);
3812 3813 3814 3815 3816 3817 3818 3819
			if (ret)
				return ret;
		}
	}

	return 0;
}

3820 3821 3822
/* Throttle our rendering by waiting until the ring has completed our requests
 * emitted over 20 msec ago.
 *
3823 3824 3825 3826
 * 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.
 *
3827 3828 3829
 * This should get us reasonable parallelism between CPU and GPU but also
 * relatively low latency when blocking on a particular request to finish.
 */
3830
static int
3831
i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file)
3832
{
3833 3834
	struct drm_i915_private *dev_priv = dev->dev_private;
	struct drm_i915_file_private *file_priv = file->driver_priv;
3835
	unsigned long recent_enough = jiffies - msecs_to_jiffies(20);
3836 3837 3838 3839
	struct drm_i915_gem_request *request;
	struct intel_ring_buffer *ring = NULL;
	u32 seqno = 0;
	int ret;
3840

3841
	spin_lock(&file_priv->mm.lock);
3842
	list_for_each_entry(request, &file_priv->mm.request_list, client_list) {
3843 3844
		if (time_after_eq(request->emitted_jiffies, recent_enough))
			break;
3845

3846 3847
		ring = request->ring;
		seqno = request->seqno;
3848
	}
3849
	spin_unlock(&file_priv->mm.lock);
3850

3851 3852
	if (seqno == 0)
		return 0;
3853

3854
	ret = 0;
3855
	if (!i915_seqno_passed(ring->get_seqno(ring), seqno)) {
3856 3857 3858 3859 3860
		/* 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.
		 */
3861
		ring->user_irq_get(ring);
3862
		ret = wait_event_interruptible(ring->irq_queue,
3863
					       i915_seqno_passed(ring->get_seqno(ring), seqno)
3864
					       || atomic_read(&dev_priv->mm.wedged));
3865
		ring->user_irq_put(ring);
3866

3867 3868
		if (ret == 0 && atomic_read(&dev_priv->mm.wedged))
			ret = -EIO;
3869 3870
	}

3871 3872
	if (ret == 0)
		queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, 0);
3873 3874 3875 3876

	return ret;
}

3877
static int
3878 3879
i915_gem_check_execbuffer(struct drm_i915_gem_execbuffer2 *exec,
			  uint64_t exec_offset)
3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894
{
	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;
}

3895
static int
3896 3897
validate_exec_list(struct drm_i915_gem_exec_object2 *exec,
		   int count)
3898
{
3899
	int i;
3900

3901 3902
	for (i = 0; i < count; i++) {
		char __user *ptr = (char __user *)(uintptr_t)exec[i].relocs_ptr;
3903
		int length; /* limited by fault_in_pages_readable() */
3904

3905 3906 3907 3908
		/* First check for malicious input causing overflow */
		if (exec[i].relocation_count >
		    INT_MAX / sizeof(struct drm_i915_gem_relocation_entry))
			return -EINVAL;
3909

3910 3911
		length = exec[i].relocation_count *
			sizeof(struct drm_i915_gem_relocation_entry);
3912 3913
		if (!access_ok(VERIFY_READ, ptr, length))
			return -EFAULT;
3914

3915 3916 3917 3918
		/* we may also need to update the presumed offsets */
		if (!access_ok(VERIFY_WRITE, ptr, length))
			return -EFAULT;

3919 3920
		if (fault_in_pages_readable(ptr, length))
			return -EFAULT;
3921 3922
	}

3923
	return 0;
3924 3925
}

C
Chris Wilson 已提交
3926
static int
J
Jesse Barnes 已提交
3927
i915_gem_do_execbuffer(struct drm_device *dev, void *data,
3928
		       struct drm_file *file,
J
Jesse Barnes 已提交
3929 3930
		       struct drm_i915_gem_execbuffer2 *args,
		       struct drm_i915_gem_exec_object2 *exec_list)
3931 3932
{
	drm_i915_private_t *dev_priv = dev->dev_private;
3933 3934
	struct drm_i915_gem_object **object_list = NULL;
	struct drm_i915_gem_object *batch_obj;
3935
	struct drm_clip_rect *cliprects = NULL;
C
Chris Wilson 已提交
3936
	struct drm_i915_gem_request *request = NULL;
3937
	int ret, i, flips;
3938 3939
	uint64_t exec_offset;

3940 3941
	struct intel_ring_buffer *ring = NULL;

3942 3943 3944 3945
	ret = i915_gem_check_is_wedged(dev);
	if (ret)
		return ret;

3946 3947 3948 3949
	ret = validate_exec_list(exec_list, args->buffer_count);
	if (ret)
		return ret;

3950 3951 3952 3953
#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
3954 3955 3956 3957 3958 3959
	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:
3960
		if (!HAS_BSD(dev)) {
3961
			DRM_ERROR("execbuf with invalid ring (BSD)\n");
3962 3963 3964
			return -EINVAL;
		}
		ring = &dev_priv->bsd_ring;
3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976
		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;
3977 3978
	}

3979 3980 3981 3982
	if (args->buffer_count < 1) {
		DRM_ERROR("execbuf with %d buffers\n", args->buffer_count);
		return -EINVAL;
	}
3983
	object_list = drm_malloc_ab(sizeof(*object_list), args->buffer_count);
J
Jesse Barnes 已提交
3984 3985
	if (object_list == NULL) {
		DRM_ERROR("Failed to allocate object list for %d buffers\n",
3986 3987 3988 3989 3990
			  args->buffer_count);
		ret = -ENOMEM;
		goto pre_mutex_err;
	}

3991
	if (args->num_cliprects != 0) {
3992 3993
		cliprects = kcalloc(args->num_cliprects, sizeof(*cliprects),
				    GFP_KERNEL);
3994 3995
		if (cliprects == NULL) {
			ret = -ENOMEM;
3996
			goto pre_mutex_err;
3997
		}
3998 3999 4000 4001 4002 4003 4004 4005

		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);
4006
			ret = -EFAULT;
4007 4008 4009 4010
			goto pre_mutex_err;
		}
	}

C
Chris Wilson 已提交
4011 4012 4013
	request = kzalloc(sizeof(*request), GFP_KERNEL);
	if (request == NULL) {
		ret = -ENOMEM;
4014
		goto pre_mutex_err;
C
Chris Wilson 已提交
4015
	}
4016

4017 4018
	ret = i915_mutex_lock_interruptible(dev);
	if (ret)
4019
		goto pre_mutex_err;
4020 4021 4022

	if (dev_priv->mm.suspended) {
		mutex_unlock(&dev->struct_mutex);
4023 4024
		ret = -EBUSY;
		goto pre_mutex_err;
4025 4026
	}

4027
	/* Look up object handles */
4028
	for (i = 0; i < args->buffer_count; i++) {
4029
		struct drm_i915_gem_object *obj;
4030

4031 4032 4033
		obj = to_intel_bo (drm_gem_object_lookup(dev, file,
							 exec_list[i].handle));
		if (obj == NULL) {
4034 4035
			DRM_ERROR("Invalid object handle %d at index %d\n",
				   exec_list[i].handle, i);
4036
			/* prevent error path from reading uninitialized data */
4037
			args->buffer_count = i;
4038
			ret = -ENOENT;
4039 4040
			goto err;
		}
4041
		object_list[i] = obj;
4042

4043
		if (obj->in_execbuffer) {
4044
			DRM_ERROR("Object %p appears more than once in object list\n",
4045
				   obj);
4046 4047
			/* prevent error path from reading uninitialized data */
			args->buffer_count = i + 1;
4048
			ret = -EINVAL;
4049 4050
			goto err;
		}
4051
		obj->in_execbuffer = true;
4052
		obj->pending_fenced_gpu_access = false;
4053
	}
4054

4055
	/* Move the objects en-masse into the GTT, evicting if necessary. */
4056 4057 4058
	ret = i915_gem_execbuffer_reserve(dev, file,
					  object_list, exec_list,
					  args->buffer_count);
4059 4060
	if (ret)
		goto err;
4061

4062
	/* The objects are in their final locations, apply the relocations. */
4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073
	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));
		}
4074
		if (ret)
4075
			goto err;
4076 4077 4078 4079
	}

	/* Set the pending read domains for the batch buffer to COMMAND */
	batch_obj = object_list[args->buffer_count-1];
4080
	if (batch_obj->base.pending_write_domain) {
4081 4082 4083 4084
		DRM_ERROR("Attempting to use self-modifying batch buffer\n");
		ret = -EINVAL;
		goto err;
	}
4085
	batch_obj->base.pending_read_domains |= I915_GEM_DOMAIN_COMMAND;
4086

4087
	/* Sanity check the batch buffer */
4088
	exec_offset = batch_obj->gtt_offset;
4089
	ret = i915_gem_check_execbuffer(args, exec_offset);
4090 4091 4092 4093 4094
	if (ret != 0) {
		DRM_ERROR("execbuf with invalid offset/length\n");
		goto err;
	}

4095 4096 4097 4098
	ret = i915_gem_execbuffer_move_to_gpu(dev, file, ring,
					      object_list, args->buffer_count);
	if (ret)
		goto err;
4099 4100 4101 4102 4103 4104 4105 4106 4107

#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
4108
	i915_gem_dump_object(batch_obj,
4109 4110 4111 4112 4113
			      args->batch_len,
			      __func__,
			      ~0);
#endif

4114 4115 4116 4117 4118 4119
	/* 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++) {
4120 4121
		if (object_list[i]->base.write_domain)
			flips |= atomic_read(&object_list[i]->pending_flip);
4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134
	}
	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;

4135 4136 4137 4138
			ret = intel_ring_begin(ring, 2);
			if (ret)
				goto err;

4139 4140 4141
			intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
			intel_ring_emit(ring, MI_NOOP);
			intel_ring_advance(ring);
4142 4143 4144
		}
	}

4145
	/* Exec the batchbuffer */
4146
	ret = ring->dispatch_execbuffer(ring, args, cliprects, exec_offset);
4147 4148 4149 4150 4151 4152
	if (ret) {
		DRM_ERROR("dispatch failed %d\n", ret);
		goto err;
	}

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

4155 4156
		obj->base.read_domains = obj->base.pending_read_domains;
		obj->base.write_domain = obj->base.pending_write_domain;
4157
		obj->fenced_gpu_access = obj->pending_fenced_gpu_access;
4158

4159
		i915_gem_object_move_to_active(obj, ring);
4160 4161 4162
		if (obj->base.write_domain) {
			obj->dirty = 1;
			list_move_tail(&obj->gpu_write_list,
4163
				       &ring->gpu_write_list);
4164 4165 4166 4167
			intel_mark_busy(dev, obj);
		}

		trace_i915_gem_object_change_domain(obj,
4168 4169
						    obj->base.read_domains,
						    obj->base.write_domain);
4170 4171
	}

4172 4173 4174 4175 4176 4177
	/*
	 * Ensure that the commands in the batch buffer are
	 * finished before the interrupt fires
	 */
	i915_retire_commands(dev, ring);

4178
	if (i915_add_request(dev, file, request, ring))
4179
		i915_gem_next_request_seqno(dev, ring);
4180 4181
	else
		request = NULL;
4182 4183

err:
4184
	for (i = 0; i < args->buffer_count; i++) {
4185 4186
		object_list[i]->in_execbuffer = false;
		drm_gem_object_unreference(&object_list[i]->base);
4187
	}
4188 4189 4190

	mutex_unlock(&dev->struct_mutex);

4191
pre_mutex_err:
4192
	drm_free_large(object_list);
4193
	kfree(cliprects);
C
Chris Wilson 已提交
4194
	kfree(request);
4195 4196 4197 4198

	return ret;
}

J
Jesse Barnes 已提交
4199 4200 4201 4202 4203 4204
/*
 * 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,
4205
		    struct drm_file *file)
J
Jesse Barnes 已提交
4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250
{
	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;
4251
		if (INTEL_INFO(dev)->gen < 4)
J
Jesse Barnes 已提交
4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264
			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;
4265
	exec2.flags = I915_EXEC_RENDER;
J
Jesse Barnes 已提交
4266

4267
	ret = i915_gem_do_execbuffer(dev, data, file, &exec2, exec2_list);
J
Jesse Barnes 已提交
4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291
	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,
4292
		     struct drm_file *file)
J
Jesse Barnes 已提交
4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324
{
	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;
	}

4325
	ret = i915_gem_do_execbuffer(dev, data, file, args, exec2_list);
J
Jesse Barnes 已提交
4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343
	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;
}

4344
int
4345 4346
i915_gem_object_pin(struct drm_i915_gem_object *obj,
		    uint32_t alignment,
4347
		    bool map_and_fenceable)
4348
{
4349
	struct drm_device *dev = obj->base.dev;
C
Chris Wilson 已提交
4350
	struct drm_i915_private *dev_priv = dev->dev_private;
4351 4352
	int ret;

4353
	BUG_ON(obj->pin_count == DRM_I915_GEM_OBJECT_MAX_PIN_COUNT);
4354
	WARN_ON(i915_verify_lists(dev));
4355

4356 4357 4358 4359
	if (obj->gtt_space != NULL) {
		if ((alignment && obj->gtt_offset & (alignment - 1)) ||
		    (map_and_fenceable && !obj->map_and_fenceable)) {
			WARN(obj->pin_count,
4360
			     "bo is already pinned with incorrect alignment:"
4361 4362
			     " offset=%x, req.alignment=%x, req.map_and_fenceable=%d,"
			     " obj->map_and_fenceable=%d\n",
4363
			     obj->gtt_offset, alignment,
4364
			     map_and_fenceable,
4365
			     obj->map_and_fenceable);
4366 4367 4368 4369 4370 4371
			ret = i915_gem_object_unbind(obj);
			if (ret)
				return ret;
		}
	}

4372
	if (obj->gtt_space == NULL) {
4373
		ret = i915_gem_object_bind_to_gtt(obj, alignment,
4374
						  map_and_fenceable);
4375
		if (ret)
4376
			return ret;
4377
	}
J
Jesse Barnes 已提交
4378

4379 4380 4381 4382
	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 已提交
4383
				       &dev_priv->mm.pinned_list);
4384
	}
4385
	BUG_ON(!obj->pin_mappable && map_and_fenceable);
4386

4387
	WARN_ON(i915_verify_lists(dev));
4388 4389 4390 4391
	return 0;
}

void
4392
i915_gem_object_unpin(struct drm_i915_gem_object *obj)
4393
{
4394
	struct drm_device *dev = obj->base.dev;
4395 4396
	drm_i915_private_t *dev_priv = dev->dev_private;

4397
	WARN_ON(i915_verify_lists(dev));
4398 4399
	BUG_ON(obj->pin_count == 0);
	BUG_ON(obj->gtt_space == NULL);
4400

4401 4402 4403
	if (--obj->pin_count == 0) {
		if (!obj->active)
			list_move_tail(&obj->mm_list,
4404
				       &dev_priv->mm.inactive_list);
4405
		i915_gem_info_remove_pin(dev_priv, obj);
4406
	}
4407
	WARN_ON(i915_verify_lists(dev));
4408 4409 4410 4411
}

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

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

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

4428
	if (obj->madv != I915_MADV_WILLNEED) {
C
Chris Wilson 已提交
4429
		DRM_ERROR("Attempting to pin a purgeable buffer\n");
4430 4431
		ret = -EINVAL;
		goto out;
4432 4433
	}

4434
	if (obj->pin_filp != NULL && obj->pin_filp != file) {
J
Jesse Barnes 已提交
4435 4436
		DRM_ERROR("Already pinned in i915_gem_pin_ioctl(): %d\n",
			  args->handle);
4437 4438
		ret = -EINVAL;
		goto out;
J
Jesse Barnes 已提交
4439 4440
	}

4441 4442 4443
	obj->user_pin_count++;
	obj->pin_filp = file;
	if (obj->user_pin_count == 1) {
4444
		ret = i915_gem_object_pin(obj, args->alignment, true);
4445 4446
		if (ret)
			goto out;
4447 4448 4449 4450 4451
	}

	/* XXX - flush the CPU caches for pinned objects
	 * as the X server doesn't manage domains yet
	 */
4452
	i915_gem_object_flush_cpu_write_domain(obj);
4453
	args->offset = obj->gtt_offset;
4454
out:
4455
	drm_gem_object_unreference(&obj->base);
4456
unlock:
4457
	mutex_unlock(&dev->struct_mutex);
4458
	return ret;
4459 4460 4461 4462
}

int
i915_gem_unpin_ioctl(struct drm_device *dev, void *data,
4463
		     struct drm_file *file)
4464 4465
{
	struct drm_i915_gem_pin *args = data;
4466
	struct drm_i915_gem_object *obj;
4467
	int ret;
4468

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

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

4479
	if (obj->pin_filp != file) {
J
Jesse Barnes 已提交
4480 4481
		DRM_ERROR("Not pinned by caller in i915_gem_pin_ioctl(): %d\n",
			  args->handle);
4482 4483
		ret = -EINVAL;
		goto out;
J
Jesse Barnes 已提交
4484
	}
4485 4486 4487
	obj->user_pin_count--;
	if (obj->user_pin_count == 0) {
		obj->pin_filp = NULL;
J
Jesse Barnes 已提交
4488 4489
		i915_gem_object_unpin(obj);
	}
4490

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

int
i915_gem_busy_ioctl(struct drm_device *dev, void *data,
4500
		    struct drm_file *file)
4501 4502
{
	struct drm_i915_gem_busy *args = data;
4503
	struct drm_i915_gem_object *obj;
4504 4505
	int ret;

4506
	ret = i915_mutex_lock_interruptible(dev);
4507
	if (ret)
4508
		return ret;
4509

4510
	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
4511
	if (obj == NULL) {
4512 4513
		ret = -ENOENT;
		goto unlock;
4514
	}
4515

4516 4517 4518 4519
	/* 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.
4520
	 */
4521
	args->busy = obj->active;
4522 4523 4524 4525 4526 4527
	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.
		 */
4528 4529 4530
		if (obj->base.write_domain & I915_GEM_GPU_DOMAINS)
			i915_gem_flush_ring(dev, obj->ring,
					    0, obj->base.write_domain);
4531 4532 4533 4534 4535 4536

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

4539
		args->busy = obj->active;
4540
	}
4541

4542
	drm_gem_object_unreference(&obj->base);
4543
unlock:
4544
	mutex_unlock(&dev->struct_mutex);
4545
	return ret;
4546 4547 4548 4549 4550 4551 4552 4553 4554
}

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

4555 4556 4557 4558 4559
int
i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
		       struct drm_file *file_priv)
{
	struct drm_i915_gem_madvise *args = data;
4560
	struct drm_i915_gem_object *obj;
4561
	int ret;
4562 4563 4564 4565 4566 4567 4568 4569 4570

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

4571 4572 4573 4574
	ret = i915_mutex_lock_interruptible(dev);
	if (ret)
		return ret;

4575
	obj = to_intel_bo(drm_gem_object_lookup(dev, file_priv, args->handle));
4576
	if (obj == NULL) {
4577 4578
		ret = -ENOENT;
		goto unlock;
4579 4580
	}

4581
	if (obj->pin_count) {
4582 4583
		ret = -EINVAL;
		goto out;
4584 4585
	}

4586 4587
	if (obj->madv != __I915_MADV_PURGED)
		obj->madv = args->madv;
4588

4589
	/* if the object is no longer bound, discard its backing storage */
4590 4591
	if (i915_gem_object_is_purgeable(obj) &&
	    obj->gtt_space == NULL)
4592 4593
		i915_gem_object_truncate(obj);

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

4596
out:
4597
	drm_gem_object_unreference(&obj->base);
4598
unlock:
4599
	mutex_unlock(&dev->struct_mutex);
4600
	return ret;
4601 4602
}

4603 4604
struct drm_i915_gem_object *i915_gem_alloc_object(struct drm_device *dev,
						  size_t size)
4605
{
4606
	struct drm_i915_private *dev_priv = dev->dev_private;
4607
	struct drm_i915_gem_object *obj;
4608

4609 4610 4611
	obj = kzalloc(sizeof(*obj), GFP_KERNEL);
	if (obj == NULL)
		return NULL;
4612

4613 4614 4615 4616
	if (drm_gem_object_init(dev, &obj->base, size) != 0) {
		kfree(obj);
		return NULL;
	}
4617

4618 4619
	i915_gem_info_add_obj(dev_priv, size);

4620 4621
	obj->base.write_domain = I915_GEM_DOMAIN_CPU;
	obj->base.read_domains = I915_GEM_DOMAIN_CPU;
4622

4623
	obj->agp_type = AGP_USER_MEMORY;
4624
	obj->base.driver_private = NULL;
4625
	obj->fence_reg = I915_FENCE_REG_NONE;
4626
	INIT_LIST_HEAD(&obj->mm_list);
D
Daniel Vetter 已提交
4627
	INIT_LIST_HEAD(&obj->gtt_list);
4628
	INIT_LIST_HEAD(&obj->ring_list);
4629 4630
	INIT_LIST_HEAD(&obj->gpu_write_list);
	obj->madv = I915_MADV_WILLNEED;
4631 4632
	/* Avoid an unnecessary call to unbind on the first bind. */
	obj->map_and_fenceable = true;
4633

4634
	return obj;
4635 4636 4637 4638 4639
}

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

4641 4642 4643
	return 0;
}

4644
static void i915_gem_free_object_tail(struct drm_i915_gem_object *obj)
4645
{
4646
	struct drm_device *dev = obj->base.dev;
4647 4648
	drm_i915_private_t *dev_priv = dev->dev_private;
	int ret;
4649

4650 4651
	ret = i915_gem_object_unbind(obj);
	if (ret == -ERESTARTSYS) {
4652
		list_move(&obj->mm_list,
4653 4654 4655
			  &dev_priv->mm.deferred_free_list);
		return;
	}
4656

4657
	if (obj->base.map_list.map)
4658
		i915_gem_free_mmap_offset(obj);
4659

4660 4661
	drm_gem_object_release(&obj->base);
	i915_gem_info_remove_obj(dev_priv, obj->base.size);
4662

4663 4664 4665
	kfree(obj->page_cpu_valid);
	kfree(obj->bit_17);
	kfree(obj);
4666 4667
}

4668
void i915_gem_free_object(struct drm_gem_object *gem_obj)
4669
{
4670 4671
	struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
	struct drm_device *dev = obj->base.dev;
4672 4673 4674

	trace_i915_gem_object_destroy(obj);

4675
	while (obj->pin_count > 0)
4676 4677
		i915_gem_object_unpin(obj);

4678
	if (obj->phys_obj)
4679 4680 4681 4682 4683
		i915_gem_detach_phys_object(dev, obj);

	i915_gem_free_object_tail(obj);
}

4684 4685 4686 4687 4688
int
i915_gem_idle(struct drm_device *dev)
{
	drm_i915_private_t *dev_priv = dev->dev_private;
	int ret;
4689

4690
	mutex_lock(&dev->struct_mutex);
C
Chris Wilson 已提交
4691

4692
	if (dev_priv->mm.suspended) {
4693 4694
		mutex_unlock(&dev->struct_mutex);
		return 0;
4695 4696
	}

4697
	ret = i915_gpu_idle(dev);
4698 4699
	if (ret) {
		mutex_unlock(&dev->struct_mutex);
4700
		return ret;
4701
	}
4702

4703 4704
	/* Under UMS, be paranoid and evict. */
	if (!drm_core_check_feature(dev, DRIVER_MODESET)) {
4705
		ret = i915_gem_evict_inactive(dev, false);
4706 4707 4708 4709 4710 4711
		if (ret) {
			mutex_unlock(&dev->struct_mutex);
			return ret;
		}
	}

4712 4713
	i915_gem_reset_fences(dev);

4714 4715 4716 4717 4718
	/* 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;
4719
	del_timer_sync(&dev_priv->hangcheck_timer);
4720 4721

	i915_kernel_lost_context(dev);
4722
	i915_gem_cleanup_ringbuffer(dev);
4723

4724 4725
	mutex_unlock(&dev->struct_mutex);

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

4729 4730 4731
	return 0;
}

4732 4733 4734 4735 4736
int
i915_gem_init_ringbuffer(struct drm_device *dev)
{
	drm_i915_private_t *dev_priv = dev->dev_private;
	int ret;
4737

4738
	ret = intel_init_render_ring_buffer(dev);
4739
	if (ret)
4740
		return ret;
4741 4742

	if (HAS_BSD(dev)) {
4743
		ret = intel_init_bsd_ring_buffer(dev);
4744 4745
		if (ret)
			goto cleanup_render_ring;
4746
	}
4747

4748 4749 4750 4751 4752 4753
	if (HAS_BLT(dev)) {
		ret = intel_init_blt_ring_buffer(dev);
		if (ret)
			goto cleanup_bsd_ring;
	}

4754 4755
	dev_priv->next_seqno = 1;

4756 4757
	return 0;

4758
cleanup_bsd_ring:
4759
	intel_cleanup_ring_buffer(&dev_priv->bsd_ring);
4760
cleanup_render_ring:
4761
	intel_cleanup_ring_buffer(&dev_priv->render_ring);
4762 4763 4764 4765 4766 4767 4768 4769
	return ret;
}

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

4770 4771 4772
	intel_cleanup_ring_buffer(&dev_priv->render_ring);
	intel_cleanup_ring_buffer(&dev_priv->bsd_ring);
	intel_cleanup_ring_buffer(&dev_priv->blt_ring);
4773 4774
}

4775 4776 4777 4778 4779 4780 4781
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 已提交
4782 4783 4784
	if (drm_core_check_feature(dev, DRIVER_MODESET))
		return 0;

4785
	if (atomic_read(&dev_priv->mm.wedged)) {
4786
		DRM_ERROR("Reenabling wedged hardware, good luck\n");
4787
		atomic_set(&dev_priv->mm.wedged, 0);
4788 4789 4790
	}

	mutex_lock(&dev->struct_mutex);
4791 4792 4793
	dev_priv->mm.suspended = 0;

	ret = i915_gem_init_ringbuffer(dev);
4794 4795
	if (ret != 0) {
		mutex_unlock(&dev->struct_mutex);
4796
		return ret;
4797
	}
4798

4799
	BUG_ON(!list_empty(&dev_priv->mm.active_list));
4800
	BUG_ON(!list_empty(&dev_priv->render_ring.active_list));
4801
	BUG_ON(!list_empty(&dev_priv->bsd_ring.active_list));
4802
	BUG_ON(!list_empty(&dev_priv->blt_ring.active_list));
4803 4804
	BUG_ON(!list_empty(&dev_priv->mm.flushing_list));
	BUG_ON(!list_empty(&dev_priv->mm.inactive_list));
4805
	BUG_ON(!list_empty(&dev_priv->render_ring.request_list));
4806
	BUG_ON(!list_empty(&dev_priv->bsd_ring.request_list));
4807
	BUG_ON(!list_empty(&dev_priv->blt_ring.request_list));
4808
	mutex_unlock(&dev->struct_mutex);
4809

4810 4811 4812
	ret = drm_irq_install(dev);
	if (ret)
		goto cleanup_ringbuffer;
4813

4814
	return 0;
4815 4816 4817 4818 4819 4820 4821 4822

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

	return ret;
4823 4824 4825 4826 4827 4828
}

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

4832
	drm_irq_uninstall(dev);
4833
	return i915_gem_idle(dev);
4834 4835 4836 4837 4838 4839 4840
}

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

4841 4842 4843
	if (drm_core_check_feature(dev, DRIVER_MODESET))
		return;

4844 4845 4846
	ret = i915_gem_idle(dev);
	if (ret)
		DRM_ERROR("failed to idle hardware: %d\n", ret);
4847 4848
}

4849 4850 4851 4852 4853 4854 4855 4856
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);
}

4857 4858 4859
void
i915_gem_load(struct drm_device *dev)
{
4860
	int i;
4861 4862
	drm_i915_private_t *dev_priv = dev->dev_private;

4863
	INIT_LIST_HEAD(&dev_priv->mm.active_list);
4864 4865
	INIT_LIST_HEAD(&dev_priv->mm.flushing_list);
	INIT_LIST_HEAD(&dev_priv->mm.inactive_list);
C
Chris Wilson 已提交
4866
	INIT_LIST_HEAD(&dev_priv->mm.pinned_list);
4867
	INIT_LIST_HEAD(&dev_priv->mm.fence_list);
4868
	INIT_LIST_HEAD(&dev_priv->mm.deferred_free_list);
D
Daniel Vetter 已提交
4869
	INIT_LIST_HEAD(&dev_priv->mm.gtt_list);
4870 4871 4872
	init_ring_lists(&dev_priv->render_ring);
	init_ring_lists(&dev_priv->bsd_ring);
	init_ring_lists(&dev_priv->blt_ring);
4873 4874
	for (i = 0; i < 16; i++)
		INIT_LIST_HEAD(&dev_priv->fence_regs[i].lru_list);
4875 4876
	INIT_DELAYED_WORK(&dev_priv->mm.retire_work,
			  i915_gem_retire_work_handler);
4877
	init_completion(&dev_priv->error_completion);
4878

4879 4880 4881 4882 4883 4884 4885 4886 4887 4888
	/* 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);
		}
	}

4889
	/* Old X drivers will take 0-2 for front, back, depth buffers */
4890 4891
	if (!drm_core_check_feature(dev, DRIVER_MODESET))
		dev_priv->fence_reg_start = 3;
4892

4893
	if (INTEL_INFO(dev)->gen >= 4 || IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
4894 4895 4896 4897
		dev_priv->num_fence_regs = 16;
	else
		dev_priv->num_fence_regs = 8;

4898
	/* Initialize fence registers to zero */
4899 4900 4901 4902 4903 4904 4905
	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:
4906 4907
		for (i = 0; i < 16; i++)
			I915_WRITE64(FENCE_REG_965_0 + (i * 8), 0);
4908 4909
		break;
	case 3:
4910 4911 4912
		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);
4913 4914 4915 4916
	case 2:
		for (i = 0; i < 8; i++)
			I915_WRITE(FENCE_REG_830_0 + (i * 4), 0);
		break;
4917
	}
4918
	i915_gem_detect_bit_6_swizzle(dev);
4919
	init_waitqueue_head(&dev_priv->pending_flip_queue);
4920 4921 4922 4923

	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);
4924
}
4925 4926 4927 4928 4929

/*
 * Create a physically contiguous memory object for this object
 * e.g. for cursor + overlay regs
 */
4930 4931
static int i915_gem_init_phys_object(struct drm_device *dev,
				     int id, int size, int align)
4932 4933 4934 4935 4936 4937 4938 4939
{
	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;

4940
	phys_obj = kzalloc(sizeof(struct drm_i915_gem_phys_object), GFP_KERNEL);
4941 4942 4943 4944 4945
	if (!phys_obj)
		return -ENOMEM;

	phys_obj->id = id;

4946
	phys_obj->handle = drm_pci_alloc(dev, size, align);
4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958
	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:
4959
	kfree(phys_obj);
4960 4961 4962
	return ret;
}

4963
static void i915_gem_free_phys_object(struct drm_device *dev, int id)
4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987
{
	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;

4988
	for (i = I915_GEM_PHYS_CURSOR_0; i <= I915_MAX_PHYS_OBJECT; i++)
4989 4990 4991 4992
		i915_gem_free_phys_object(dev, i);
}

void i915_gem_detach_phys_object(struct drm_device *dev,
4993
				 struct drm_i915_gem_object *obj)
4994
{
4995
	struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
4996
	char *vaddr;
4997 4998 4999
	int i;
	int page_count;

5000
	if (!obj->phys_obj)
5001
		return;
5002
	vaddr = obj->phys_obj->handle->vaddr;
5003

5004
	page_count = obj->base.size / PAGE_SIZE;
5005
	for (i = 0; i < page_count; i++) {
5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018
		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);
		}
5019
	}
5020
	intel_gtt_chipset_flush();
5021

5022 5023
	obj->phys_obj->cur_obj = NULL;
	obj->phys_obj = NULL;
5024 5025 5026 5027
}

int
i915_gem_attach_phys_object(struct drm_device *dev,
5028
			    struct drm_i915_gem_object *obj,
5029 5030
			    int id,
			    int align)
5031
{
5032
	struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
5033 5034 5035 5036 5037 5038 5039 5040
	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;

5041 5042
	if (obj->phys_obj) {
		if (obj->phys_obj->id == id)
5043 5044 5045 5046 5047 5048 5049
			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,
5050
						obj->base.size, align);
5051
		if (ret) {
5052 5053
			DRM_ERROR("failed to init phys object %d size: %zu\n",
				  id, obj->base.size);
5054
			return ret;
5055 5056 5057 5058
		}
	}

	/* bind to the object */
5059 5060
	obj->phys_obj = dev_priv->mm.phys_objs[id - 1];
	obj->phys_obj->cur_obj = obj;
5061

5062
	page_count = obj->base.size / PAGE_SIZE;
5063 5064

	for (i = 0; i < page_count; i++) {
5065 5066 5067 5068 5069 5070 5071
		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);
5072

5073
		src = kmap_atomic(page);
5074
		dst = obj->phys_obj->handle->vaddr + (i * PAGE_SIZE);
5075
		memcpy(dst, src, PAGE_SIZE);
P
Peter Zijlstra 已提交
5076
		kunmap_atomic(src);
5077

5078 5079 5080
		mark_page_accessed(page);
		page_cache_release(page);
	}
5081

5082 5083 5084 5085
	return 0;
}

static int
5086 5087
i915_gem_phys_pwrite(struct drm_device *dev,
		     struct drm_i915_gem_object *obj,
5088 5089 5090
		     struct drm_i915_gem_pwrite *args,
		     struct drm_file *file_priv)
{
5091
	void *vaddr = obj->phys_obj->handle->vaddr + args->offset;
5092
	char __user *user_data = (char __user *) (uintptr_t) args->data_ptr;
5093

5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106
	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;
	}
5107

5108
	intel_gtt_chipset_flush();
5109 5110
	return 0;
}
5111

5112
void i915_gem_release(struct drm_device *dev, struct drm_file *file)
5113
{
5114
	struct drm_i915_file_private *file_priv = file->driver_priv;
5115 5116 5117 5118 5119

	/* 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.
	 */
5120
	spin_lock(&file_priv->mm.lock);
5121 5122 5123 5124 5125 5126 5127 5128 5129
	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;
	}
5130
	spin_unlock(&file_priv->mm.lock);
5131
}
5132

5133 5134 5135 5136 5137 5138 5139
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) &&
5140
		      list_empty(&dev_priv->mm.active_list);
5141 5142 5143 5144

	return !lists_empty;
}

5145
static int
5146 5147 5148
i915_gem_inactive_shrink(struct shrinker *shrinker,
			 int nr_to_scan,
			 gfp_t gfp_mask)
5149
{
5150 5151 5152 5153 5154 5155 5156 5157 5158
	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))
5159
		return 0;
5160 5161 5162

	/* "fast-path" to count number of available objects */
	if (nr_to_scan == 0) {
5163 5164 5165 5166 5167 5168 5169
		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;
5170 5171
	}

5172
rescan:
5173
	/* first scan for clean buffers */
5174
	i915_gem_retire_requests(dev);
5175

5176 5177 5178 5179
	list_for_each_entry_safe(obj, next,
				 &dev_priv->mm.inactive_list,
				 mm_list) {
		if (i915_gem_object_is_purgeable(obj)) {
5180
			i915_gem_object_unbind(obj);
5181 5182
			if (--nr_to_scan == 0)
				break;
5183 5184 5185 5186
		}
	}

	/* second pass, evict/count anything still on the inactive list */
5187 5188 5189 5190 5191
	cnt = 0;
	list_for_each_entry_safe(obj, next,
				 &dev_priv->mm.inactive_list,
				 mm_list) {
		if (nr_to_scan) {
5192
			i915_gem_object_unbind(obj);
5193 5194 5195 5196 5197 5198
			nr_to_scan--;
		} else
			cnt++;
	}

	if (nr_to_scan && i915_gpu_is_active(dev)) {
5199 5200 5201 5202 5203 5204
		/*
		 * 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.
		 */
5205
		if (i915_gpu_idle(dev) == 0)
5206 5207
			goto rescan;
	}
5208 5209
	mutex_unlock(&dev->struct_mutex);
	return cnt / 100 * sysctl_vfs_cache_pressure;
5210
}