i915_gem.c 45.9 KB
Newer Older
1
/*
2
 * Copyright © 2008-2015 Intel Corporation
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
 *
 * 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>
 *
 */

28
#include <drm/drm_vma_manager.h>
29
#include <drm/i915_drm.h>
30
#include <linux/dma-fence-array.h>
31
#include <linux/kthread.h>
32
#include <linux/reservation.h>
33
#include <linux/shmem_fs.h>
34
#include <linux/slab.h>
35
#include <linux/stop_machine.h>
36
#include <linux/swap.h>
J
Jesse Barnes 已提交
37
#include <linux/pci.h>
38
#include <linux/dma-buf.h>
39
#include <linux/mman.h>
40

41 42 43
#include "display/intel_display.h"
#include "display/intel_frontbuffer.h"

44 45
#include "gem/i915_gem_clflush.h"
#include "gem/i915_gem_context.h"
46
#include "gem/i915_gem_ioctls.h"
47 48
#include "gem/i915_gem_pm.h"
#include "gem/i915_gemfs.h"
49
#include "gt/intel_gt.h"
50
#include "gt/intel_gt_pm.h"
51 52 53 54
#include "gt/intel_mocs.h"
#include "gt/intel_reset.h"
#include "gt/intel_workarounds.h"

55
#include "i915_drv.h"
56
#include "i915_scatterlist.h"
57 58 59 60
#include "i915_trace.h"
#include "i915_vgpu.h"

#include "intel_drv.h"
61
#include "intel_pm.h"
62

63
static int
64
insert_mappable_node(struct i915_ggtt *ggtt,
65 66 67
                     struct drm_mm_node *node, u32 size)
{
	memset(node, 0, sizeof(*node));
68
	return drm_mm_insert_node_in_range(&ggtt->vm.mm, node,
69 70 71
					   size, 0, I915_COLOR_UNEVICTABLE,
					   0, ggtt->mappable_end,
					   DRM_MM_INSERT_LOW);
72 73 74 75 76 77 78 79
}

static void
remove_mappable_node(struct drm_mm_node *node)
{
	drm_mm_remove_node(node);
}

80 81
int
i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
82
			    struct drm_file *file)
83
{
84
	struct i915_ggtt *ggtt = &to_i915(dev)->ggtt;
85
	struct drm_i915_gem_get_aperture *args = data;
86
	struct i915_vma *vma;
87
	u64 pinned;
88

89 90
	mutex_lock(&ggtt->vm.mutex);

91
	pinned = ggtt->vm.reserved;
92
	list_for_each_entry(vma, &ggtt->vm.bound_list, vm_link)
93
		if (i915_vma_is_pinned(vma))
94
			pinned += vma->node.size;
95 96

	mutex_unlock(&ggtt->vm.mutex);
97

98
	args->aper_size = ggtt->vm.total;
99
	args->aper_available_size = args->aper_size - pinned;
100

101 102 103
	return 0;
}

104 105
int i915_gem_object_unbind(struct drm_i915_gem_object *obj,
			   unsigned long flags)
106 107 108
{
	struct i915_vma *vma;
	LIST_HEAD(still_in_list);
109
	int ret = 0;
110 111

	lockdep_assert_held(&obj->base.dev->struct_mutex);
112

113 114 115 116
	spin_lock(&obj->vma.lock);
	while (!ret && (vma = list_first_entry_or_null(&obj->vma.list,
						       struct i915_vma,
						       obj_link))) {
117
		list_move_tail(&vma->obj_link, &still_in_list);
118 119
		spin_unlock(&obj->vma.lock);

120 121 122 123
		ret = -EBUSY;
		if (flags & I915_GEM_OBJECT_UNBIND_ACTIVE ||
		    !i915_vma_is_active(vma))
			ret = i915_vma_unbind(vma);
124 125

		spin_lock(&obj->vma.lock);
126
	}
127 128
	list_splice(&still_in_list, &obj->vma.list);
	spin_unlock(&obj->vma.lock);
129 130 131 132

	return ret;
}

133 134 135
static int
i915_gem_phys_pwrite(struct drm_i915_gem_object *obj,
		     struct drm_i915_gem_pwrite *args,
136
		     struct drm_file *file)
137 138
{
	void *vaddr = obj->phys_handle->vaddr + args->offset;
139
	char __user *user_data = u64_to_user_ptr(args->data_ptr);
140 141 142 143

	/* We manually control the domain here and pretend that it
	 * remains coherent i.e. in the GTT domain, like shmem_pwrite.
	 */
144
	intel_fb_obj_invalidate(obj, ORIGIN_CPU);
145 146
	if (copy_from_user(vaddr, user_data, args->size))
		return -EFAULT;
147

148
	drm_clflush_virt_range(vaddr, args->size);
149
	intel_gt_chipset_flush(&to_i915(obj->base.dev)->gt);
150

151
	intel_fb_obj_flush(obj, ORIGIN_CPU);
152
	return 0;
153 154
}

155 156
static int
i915_gem_create(struct drm_file *file,
157
		struct drm_i915_private *dev_priv,
158
		u64 *size_p,
159
		u32 *handle_p)
160
{
161
	struct drm_i915_gem_object *obj;
162
	u32 handle;
163 164
	u64 size;
	int ret;
165

166
	size = round_up(*size_p, PAGE_SIZE);
167 168
	if (size == 0)
		return -EINVAL;
169 170

	/* Allocate the new object */
171
	obj = i915_gem_object_create_shmem(dev_priv, size);
172 173
	if (IS_ERR(obj))
		return PTR_ERR(obj);
174

175
	ret = drm_gem_handle_create(file, &obj->base, &handle);
176
	/* drop reference from allocate - handle holds it now */
C
Chris Wilson 已提交
177
	i915_gem_object_put(obj);
178 179
	if (ret)
		return ret;
180

181
	*handle_p = handle;
182
	*size_p = size;
183 184 185
	return 0;
}

186 187 188 189 190
int
i915_gem_dumb_create(struct drm_file *file,
		     struct drm_device *dev,
		     struct drm_mode_create_dumb *args)
{
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
	int cpp = DIV_ROUND_UP(args->bpp, 8);
	u32 format;

	switch (cpp) {
	case 1:
		format = DRM_FORMAT_C8;
		break;
	case 2:
		format = DRM_FORMAT_RGB565;
		break;
	case 4:
		format = DRM_FORMAT_XRGB8888;
		break;
	default:
		return -EINVAL;
	}

208
	/* have to work out size/pitch and return them */
209 210 211 212 213 214 215
	args->pitch = ALIGN(args->width * cpp, 64);

	/* align stride to page size so that we can remap */
	if (args->pitch > intel_plane_fb_max_stride(to_i915(dev), format,
						    DRM_FORMAT_MOD_LINEAR))
		args->pitch = ALIGN(args->pitch, 4096);

216
	args->size = args->pitch * args->height;
217
	return i915_gem_create(file, to_i915(dev),
218
			       &args->size, &args->handle);
219 220 221 222
}

/**
 * Creates a new mm object and returns a handle to it.
223 224 225
 * @dev: drm device pointer
 * @data: ioctl data blob
 * @file: drm file pointer
226 227 228 229 230
 */
int
i915_gem_create_ioctl(struct drm_device *dev, void *data,
		      struct drm_file *file)
{
231
	struct drm_i915_private *dev_priv = to_i915(dev);
232
	struct drm_i915_gem_create *args = data;
233

234
	i915_gem_flush_free_objects(dev_priv);
235

236
	return i915_gem_create(file, dev_priv,
237
			       &args->size, &args->handle);
238 239
}

240
static int
241 242
shmem_pread(struct page *page, int offset, int len, char __user *user_data,
	    bool needs_clflush)
243 244 245 246 247 248
{
	char *vaddr;
	int ret;

	vaddr = kmap(page);

249 250
	if (needs_clflush)
		drm_clflush_virt_range(vaddr + offset, len);
251

252
	ret = __copy_to_user(user_data, vaddr + offset, len);
253

254
	kunmap(page);
255

256
	return ret ? -EFAULT : 0;
257 258 259 260 261 262 263 264
}

static int
i915_gem_shmem_pread(struct drm_i915_gem_object *obj,
		     struct drm_i915_gem_pread *args)
{
	unsigned int needs_clflush;
	unsigned int idx, offset;
265 266 267
	struct dma_fence *fence;
	char __user *user_data;
	u64 remain;
268 269
	int ret;

270
	ret = i915_gem_object_prepare_read(obj, &needs_clflush);
271 272 273
	if (ret)
		return ret;

274 275 276 277 278
	fence = i915_gem_object_lock_fence(obj);
	i915_gem_object_finish_access(obj);
	if (!fence)
		return -ENOMEM;

279 280 281 282 283
	remain = args->size;
	user_data = u64_to_user_ptr(args->data_ptr);
	offset = offset_in_page(args->offset);
	for (idx = args->offset >> PAGE_SHIFT; remain; idx++) {
		struct page *page = i915_gem_object_get_page(obj, idx);
284
		unsigned int length = min_t(u64, remain, PAGE_SIZE - offset);
285 286 287 288 289 290 291 292 293 294 295

		ret = shmem_pread(page, offset, length, user_data,
				  needs_clflush);
		if (ret)
			break;

		remain -= length;
		user_data += length;
		offset = 0;
	}

296
	i915_gem_object_unlock_fence(obj, fence);
297 298 299 300 301 302 303
	return ret;
}

static inline bool
gtt_user_read(struct io_mapping *mapping,
	      loff_t base, int offset,
	      char __user *user_data, int length)
304
{
305
	void __iomem *vaddr;
306
	unsigned long unwritten;
307 308

	/* We can use the cpu mem copy function because this is X86. */
309 310 311 312
	vaddr = io_mapping_map_atomic_wc(mapping, base);
	unwritten = __copy_to_user_inatomic(user_data,
					    (void __force *)vaddr + offset,
					    length);
313 314
	io_mapping_unmap_atomic(vaddr);
	if (unwritten) {
315 316 317 318
		vaddr = io_mapping_map_wc(mapping, base, PAGE_SIZE);
		unwritten = copy_to_user(user_data,
					 (void __force *)vaddr + offset,
					 length);
319 320
		io_mapping_unmap(vaddr);
	}
321 322 323 324
	return unwritten;
}

static int
325 326
i915_gem_gtt_pread(struct drm_i915_gem_object *obj,
		   const struct drm_i915_gem_pread *args)
327
{
328 329
	struct drm_i915_private *i915 = to_i915(obj->base.dev);
	struct i915_ggtt *ggtt = &i915->ggtt;
330
	intel_wakeref_t wakeref;
331
	struct drm_mm_node node;
332
	struct dma_fence *fence;
333
	void __user *user_data;
334
	struct i915_vma *vma;
335
	u64 remain, offset;
336 337
	int ret;

338 339 340 341
	ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
	if (ret)
		return ret;

342
	wakeref = intel_runtime_pm_get(&i915->runtime_pm);
343
	vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
344 345 346
				       PIN_MAPPABLE |
				       PIN_NONFAULT |
				       PIN_NONBLOCK);
347 348 349
	if (!IS_ERR(vma)) {
		node.start = i915_ggtt_offset(vma);
		node.allocated = false;
350
		ret = i915_vma_put_fence(vma);
351 352 353 354 355
		if (ret) {
			i915_vma_unpin(vma);
			vma = ERR_PTR(ret);
		}
	}
C
Chris Wilson 已提交
356
	if (IS_ERR(vma)) {
357
		ret = insert_mappable_node(ggtt, &node, PAGE_SIZE);
358
		if (ret)
359 360
			goto out_unlock;
		GEM_BUG_ON(!node.allocated);
361 362
	}

363 364 365
	mutex_unlock(&i915->drm.struct_mutex);

	ret = i915_gem_object_lock_interruptible(obj);
366 367 368
	if (ret)
		goto out_unpin;

369 370 371 372 373 374 375 376 377 378 379 380
	ret = i915_gem_object_set_to_gtt_domain(obj, false);
	if (ret) {
		i915_gem_object_unlock(obj);
		goto out_unpin;
	}

	fence = i915_gem_object_lock_fence(obj);
	i915_gem_object_unlock(obj);
	if (!fence) {
		ret = -ENOMEM;
		goto out_unpin;
	}
381

382 383 384
	user_data = u64_to_user_ptr(args->data_ptr);
	remain = args->size;
	offset = args->offset;
385 386 387 388 389 390 391 392 393 394 395 396 397 398

	while (remain > 0) {
		/* Operation in this page
		 *
		 * page_base = page offset within aperture
		 * page_offset = offset within page
		 * page_length = bytes to copy for this page
		 */
		u32 page_base = node.start;
		unsigned page_offset = offset_in_page(offset);
		unsigned page_length = PAGE_SIZE - page_offset;
		page_length = remain < page_length ? remain : page_length;
		if (node.allocated) {
			wmb();
399 400 401
			ggtt->vm.insert_page(&ggtt->vm,
					     i915_gem_object_get_dma_address(obj, offset >> PAGE_SHIFT),
					     node.start, I915_CACHE_NONE, 0);
402 403 404 405
			wmb();
		} else {
			page_base += offset & PAGE_MASK;
		}
406

407
		if (gtt_user_read(&ggtt->iomap, page_base, page_offset,
408
				  user_data, page_length)) {
409 410 411 412 413 414 415 416 417
			ret = -EFAULT;
			break;
		}

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

418
	i915_gem_object_unlock_fence(obj, fence);
419
out_unpin:
420
	mutex_lock(&i915->drm.struct_mutex);
421 422
	if (node.allocated) {
		wmb();
423
		ggtt->vm.clear_range(&ggtt->vm, node.start, node.size);
424 425
		remove_mappable_node(&node);
	} else {
C
Chris Wilson 已提交
426
		i915_vma_unpin(vma);
427
	}
428
out_unlock:
429
	intel_runtime_pm_put(&i915->runtime_pm, wakeref);
430
	mutex_unlock(&i915->drm.struct_mutex);
431

432 433 434
	return ret;
}

435 436
/**
 * Reads data from the object referenced by handle.
437 438 439
 * @dev: drm device pointer
 * @data: ioctl data blob
 * @file: drm file pointer
440 441 442 443 444
 *
 * On error, the contents of *data are undefined.
 */
int
i915_gem_pread_ioctl(struct drm_device *dev, void *data,
445
		     struct drm_file *file)
446 447
{
	struct drm_i915_gem_pread *args = data;
448
	struct drm_i915_gem_object *obj;
449
	int ret;
450

451 452 453
	if (args->size == 0)
		return 0;

454
	if (!access_ok(u64_to_user_ptr(args->data_ptr),
455 456 457
		       args->size))
		return -EFAULT;

458
	obj = i915_gem_object_lookup(file, args->handle);
459 460
	if (!obj)
		return -ENOENT;
461

462
	/* Bounds check source.  */
463
	if (range_overflows_t(u64, args->offset, args->size, obj->base.size)) {
C
Chris Wilson 已提交
464
		ret = -EINVAL;
465
		goto out;
C
Chris Wilson 已提交
466 467
	}

C
Chris Wilson 已提交
468 469
	trace_i915_gem_object_pread(obj, args->offset, args->size);

470 471
	ret = i915_gem_object_wait(obj,
				   I915_WAIT_INTERRUPTIBLE,
472
				   MAX_SCHEDULE_TIMEOUT);
473
	if (ret)
474
		goto out;
475

476
	ret = i915_gem_object_pin_pages(obj);
477
	if (ret)
478
		goto out;
479

480
	ret = i915_gem_shmem_pread(obj, args);
481
	if (ret == -EFAULT || ret == -ENODEV)
482
		ret = i915_gem_gtt_pread(obj, args);
483

484 485
	i915_gem_object_unpin_pages(obj);
out:
C
Chris Wilson 已提交
486
	i915_gem_object_put(obj);
487
	return ret;
488 489
}

490 491
/* This is the fast write path which cannot handle
 * page faults in the source data
492
 */
493

494 495 496 497
static inline bool
ggtt_write(struct io_mapping *mapping,
	   loff_t base, int offset,
	   char __user *user_data, int length)
498
{
499
	void __iomem *vaddr;
500
	unsigned long unwritten;
501

502
	/* We can use the cpu mem copy function because this is X86. */
503 504
	vaddr = io_mapping_map_atomic_wc(mapping, base);
	unwritten = __copy_from_user_inatomic_nocache((void __force *)vaddr + offset,
505
						      user_data, length);
506 507
	io_mapping_unmap_atomic(vaddr);
	if (unwritten) {
508 509 510
		vaddr = io_mapping_map_wc(mapping, base, PAGE_SIZE);
		unwritten = copy_from_user((void __force *)vaddr + offset,
					   user_data, length);
511 512
		io_mapping_unmap(vaddr);
	}
513 514 515 516

	return unwritten;
}

517 518 519
/**
 * This is the fast pwrite path, where we copy the data directly from the
 * user into the GTT, uncached.
520
 * @obj: i915 GEM object
521
 * @args: pwrite arguments structure
522
 */
523
static int
524 525
i915_gem_gtt_pwrite_fast(struct drm_i915_gem_object *obj,
			 const struct drm_i915_gem_pwrite *args)
526
{
527
	struct drm_i915_private *i915 = to_i915(obj->base.dev);
528
	struct i915_ggtt *ggtt = &i915->ggtt;
529
	struct intel_runtime_pm *rpm = &i915->runtime_pm;
530
	intel_wakeref_t wakeref;
531
	struct drm_mm_node node;
532
	struct dma_fence *fence;
533 534 535
	struct i915_vma *vma;
	u64 remain, offset;
	void __user *user_data;
536
	int ret;
537

538 539 540
	ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
	if (ret)
		return ret;
D
Daniel Vetter 已提交
541

542 543 544 545 546 547 548 549
	if (i915_gem_object_has_struct_page(obj)) {
		/*
		 * Avoid waking the device up if we can fallback, as
		 * waking/resuming is very slow (worst-case 10-100 ms
		 * depending on PCI sleeps and our own resume time).
		 * This easily dwarfs any performance advantage from
		 * using the cache bypass of indirect GGTT access.
		 */
550
		wakeref = intel_runtime_pm_get_if_in_use(rpm);
551
		if (!wakeref) {
552 553 554 555 556
			ret = -EFAULT;
			goto out_unlock;
		}
	} else {
		/* No backing pages, no fallback, we must force GGTT access */
557
		wakeref = intel_runtime_pm_get(rpm);
558 559
	}

C
Chris Wilson 已提交
560
	vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
561 562 563
				       PIN_MAPPABLE |
				       PIN_NONFAULT |
				       PIN_NONBLOCK);
564 565 566
	if (!IS_ERR(vma)) {
		node.start = i915_ggtt_offset(vma);
		node.allocated = false;
567
		ret = i915_vma_put_fence(vma);
568 569 570 571 572
		if (ret) {
			i915_vma_unpin(vma);
			vma = ERR_PTR(ret);
		}
	}
C
Chris Wilson 已提交
573
	if (IS_ERR(vma)) {
574
		ret = insert_mappable_node(ggtt, &node, PAGE_SIZE);
575
		if (ret)
576
			goto out_rpm;
577
		GEM_BUG_ON(!node.allocated);
578
	}
D
Daniel Vetter 已提交
579

580 581 582
	mutex_unlock(&i915->drm.struct_mutex);

	ret = i915_gem_object_lock_interruptible(obj);
D
Daniel Vetter 已提交
583 584 585
	if (ret)
		goto out_unpin;

586 587 588 589 590 591 592 593 594 595 596 597
	ret = i915_gem_object_set_to_gtt_domain(obj, true);
	if (ret) {
		i915_gem_object_unlock(obj);
		goto out_unpin;
	}

	fence = i915_gem_object_lock_fence(obj);
	i915_gem_object_unlock(obj);
	if (!fence) {
		ret = -ENOMEM;
		goto out_unpin;
	}
598

599
	intel_fb_obj_invalidate(obj, ORIGIN_CPU);
600

601 602 603 604
	user_data = u64_to_user_ptr(args->data_ptr);
	offset = args->offset;
	remain = args->size;
	while (remain) {
605 606
		/* Operation in this page
		 *
607 608 609
		 * page_base = page offset within aperture
		 * page_offset = offset within page
		 * page_length = bytes to copy for this page
610
		 */
611
		u32 page_base = node.start;
612 613
		unsigned int page_offset = offset_in_page(offset);
		unsigned int page_length = PAGE_SIZE - page_offset;
614 615 616
		page_length = remain < page_length ? remain : page_length;
		if (node.allocated) {
			wmb(); /* flush the write before we modify the GGTT */
617 618 619
			ggtt->vm.insert_page(&ggtt->vm,
					     i915_gem_object_get_dma_address(obj, offset >> PAGE_SHIFT),
					     node.start, I915_CACHE_NONE, 0);
620 621 622 623
			wmb(); /* flush modifications to the GGTT (insert_page) */
		} else {
			page_base += offset & PAGE_MASK;
		}
624
		/* If we get a fault while copying data, then (presumably) our
625 626
		 * source page isn't available.  Return the error and we'll
		 * retry in the slow path.
627 628
		 * If the object is non-shmem backed, we retry again with the
		 * path that handles page fault.
629
		 */
630
		if (ggtt_write(&ggtt->iomap, page_base, page_offset,
631 632 633
			       user_data, page_length)) {
			ret = -EFAULT;
			break;
D
Daniel Vetter 已提交
634
		}
635

636 637 638
		remain -= page_length;
		user_data += page_length;
		offset += page_length;
639
	}
640
	intel_fb_obj_flush(obj, ORIGIN_CPU);
641

642
	i915_gem_object_unlock_fence(obj, fence);
D
Daniel Vetter 已提交
643
out_unpin:
644
	mutex_lock(&i915->drm.struct_mutex);
645 646
	if (node.allocated) {
		wmb();
647
		ggtt->vm.clear_range(&ggtt->vm, node.start, node.size);
648 649
		remove_mappable_node(&node);
	} else {
C
Chris Wilson 已提交
650
		i915_vma_unpin(vma);
651
	}
652
out_rpm:
653
	intel_runtime_pm_put(rpm, wakeref);
654
out_unlock:
655
	mutex_unlock(&i915->drm.struct_mutex);
656
	return ret;
657 658
}

659 660 661 662 663
/* Per-page copy function for the shmem pwrite fastpath.
 * Flushes invalid cachelines before writing to the target if
 * needs_clflush_before is set and flushes out any written cachelines after
 * writing if needs_clflush is set.
 */
664
static int
665 666 667
shmem_pwrite(struct page *page, int offset, int len, char __user *user_data,
	     bool needs_clflush_before,
	     bool needs_clflush_after)
668
{
669
	char *vaddr;
670 671
	int ret;

672
	vaddr = kmap(page);
673

674 675
	if (needs_clflush_before)
		drm_clflush_virt_range(vaddr + offset, len);
676

677 678 679
	ret = __copy_from_user(vaddr + offset, user_data, len);
	if (!ret && needs_clflush_after)
		drm_clflush_virt_range(vaddr + offset, len);
680

681 682 683
	kunmap(page);

	return ret ? -EFAULT : 0;
684 685 686 687 688 689 690
}

static int
i915_gem_shmem_pwrite(struct drm_i915_gem_object *obj,
		      const struct drm_i915_gem_pwrite *args)
{
	unsigned int partial_cacheline_write;
691
	unsigned int needs_clflush;
692
	unsigned int offset, idx;
693 694 695
	struct dma_fence *fence;
	void __user *user_data;
	u64 remain;
696
	int ret;
697

698
	ret = i915_gem_object_prepare_write(obj, &needs_clflush);
699 700
	if (ret)
		return ret;
701

702 703 704 705 706
	fence = i915_gem_object_lock_fence(obj);
	i915_gem_object_finish_access(obj);
	if (!fence)
		return -ENOMEM;

707 708 709 710 711 712 713
	/* If we don't overwrite a cacheline completely we need to be
	 * careful to have up-to-date data by first clflushing. Don't
	 * overcomplicate things and flush the entire patch.
	 */
	partial_cacheline_write = 0;
	if (needs_clflush & CLFLUSH_BEFORE)
		partial_cacheline_write = boot_cpu_data.x86_clflush_size - 1;
714

715 716 717 718 719
	user_data = u64_to_user_ptr(args->data_ptr);
	remain = args->size;
	offset = offset_in_page(args->offset);
	for (idx = args->offset >> PAGE_SHIFT; remain; idx++) {
		struct page *page = i915_gem_object_get_page(obj, idx);
720
		unsigned int length = min_t(u64, remain, PAGE_SIZE - offset);
721

722 723 724
		ret = shmem_pwrite(page, offset, length, user_data,
				   (offset | length) & partial_cacheline_write,
				   needs_clflush & CLFLUSH_AFTER);
725
		if (ret)
726
			break;
727

728 729 730
		remain -= length;
		user_data += length;
		offset = 0;
731
	}
732

733
	intel_fb_obj_flush(obj, ORIGIN_CPU);
734 735
	i915_gem_object_unlock_fence(obj, fence);

736
	return ret;
737 738 739 740
}

/**
 * Writes data to the object referenced by handle.
741 742 743
 * @dev: drm device
 * @data: ioctl data blob
 * @file: drm file
744 745 746 747 748
 *
 * 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,
749
		      struct drm_file *file)
750 751
{
	struct drm_i915_gem_pwrite *args = data;
752
	struct drm_i915_gem_object *obj;
753 754 755 756 757
	int ret;

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

758
	if (!access_ok(u64_to_user_ptr(args->data_ptr), args->size))
759 760
		return -EFAULT;

761
	obj = i915_gem_object_lookup(file, args->handle);
762 763
	if (!obj)
		return -ENOENT;
764

765
	/* Bounds check destination. */
766
	if (range_overflows_t(u64, args->offset, args->size, obj->base.size)) {
C
Chris Wilson 已提交
767
		ret = -EINVAL;
768
		goto err;
C
Chris Wilson 已提交
769 770
	}

771 772 773 774 775 776
	/* Writes not allowed into this read-only object */
	if (i915_gem_object_is_readonly(obj)) {
		ret = -EINVAL;
		goto err;
	}

C
Chris Wilson 已提交
777 778
	trace_i915_gem_object_pwrite(obj, args->offset, args->size);

779 780 781 782 783 784
	ret = -ENODEV;
	if (obj->ops->pwrite)
		ret = obj->ops->pwrite(obj, args);
	if (ret != -ENODEV)
		goto err;

785 786 787
	ret = i915_gem_object_wait(obj,
				   I915_WAIT_INTERRUPTIBLE |
				   I915_WAIT_ALL,
788
				   MAX_SCHEDULE_TIMEOUT);
789 790 791
	if (ret)
		goto err;

792
	ret = i915_gem_object_pin_pages(obj);
793
	if (ret)
794
		goto err;
795

D
Daniel Vetter 已提交
796
	ret = -EFAULT;
797 798 799 800 801 802
	/* 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.
	 */
803
	if (!i915_gem_object_has_struct_page(obj) ||
804
	    cpu_write_needs_clflush(obj))
D
Daniel Vetter 已提交
805 806
		/* Note that the gtt paths might fail with non-page-backed user
		 * pointers (e.g. gtt mappings when moving data between
807 808
		 * textures). Fallback to the shmem path in that case.
		 */
809
		ret = i915_gem_gtt_pwrite_fast(obj, args);
810

811
	if (ret == -EFAULT || ret == -ENOSPC) {
812 813
		if (obj->phys_handle)
			ret = i915_gem_phys_pwrite(obj, args, file);
814
		else
815
			ret = i915_gem_shmem_pwrite(obj, args);
816
	}
817

818
	i915_gem_object_unpin_pages(obj);
819
err:
C
Chris Wilson 已提交
820
	i915_gem_object_put(obj);
821
	return ret;
822 823 824 825
}

/**
 * Called when user space has done writes to this buffer
826 827 828
 * @dev: drm device
 * @data: ioctl data blob
 * @file: drm file
829 830 831
 */
int
i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
832
			 struct drm_file *file)
833 834
{
	struct drm_i915_gem_sw_finish *args = data;
835
	struct drm_i915_gem_object *obj;
836

837
	obj = i915_gem_object_lookup(file, args->handle);
838 839
	if (!obj)
		return -ENOENT;
840

T
Tina Zhang 已提交
841 842 843 844 845
	/*
	 * Proxy objects are barred from CPU access, so there is no
	 * need to ban sw_finish as it is a nop.
	 */

846
	/* Pinned buffers may be scanout, so flush the cache */
847
	i915_gem_object_flush_if_display(obj);
C
Chris Wilson 已提交
848
	i915_gem_object_put(obj);
849 850

	return 0;
851 852
}

853
void i915_gem_runtime_suspend(struct drm_i915_private *i915)
854
{
855
	struct drm_i915_gem_object *obj, *on;
856
	int i;
857

858 859 860 861 862 863
	/*
	 * Only called during RPM suspend. All users of the userfault_list
	 * must be holding an RPM wakeref to ensure that this can not
	 * run concurrently with themselves (and use the struct_mutex for
	 * protection between themselves).
	 */
864

865
	list_for_each_entry_safe(obj, on,
866
				 &i915->ggtt.userfault_list, userfault_link)
867
		__i915_gem_object_release_mmap(obj);
868

869 870
	/*
	 * The fence will be lost when the device powers down. If any were
871 872 873
	 * in use by hardware (i.e. they are pinned), we should not be powering
	 * down! All other fences will be reacquired by the user upon waking.
	 */
874 875
	for (i = 0; i < i915->ggtt.num_fences; i++) {
		struct i915_fence_reg *reg = &i915->ggtt.fence_regs[i];
876

877 878
		/*
		 * Ideally we want to assert that the fence register is not
879 880 881 882 883 884 885 886 887
		 * live at this point (i.e. that no piece of code will be
		 * trying to write through fence + GTT, as that both violates
		 * our tracking of activity and associated locking/barriers,
		 * but also is illegal given that the hw is powered down).
		 *
		 * Previously we used reg->pin_count as a "liveness" indicator.
		 * That is not sufficient, and we need a more fine-grained
		 * tool if we want to have a sanity check here.
		 */
888 889 890 891

		if (!reg->vma)
			continue;

892
		GEM_BUG_ON(i915_vma_has_userfault(reg->vma));
893 894
		reg->dirty = true;
	}
895 896
}

897 898
static int wait_for_engines(struct drm_i915_private *i915)
{
899
	if (wait_for(intel_engines_are_idle(i915), I915_IDLE_ENGINES_TIMEOUT)) {
900 901
		dev_err(i915->drm.dev,
			"Failed to idle engines, declaring wedged!\n");
902
		GEM_TRACE_DUMP();
903 904
		i915_gem_set_wedged(i915);
		return -EIO;
905 906 907 908 909
	}

	return 0;
}

910 911 912 913
static long
wait_for_timelines(struct drm_i915_private *i915,
		   unsigned int flags, long timeout)
{
914
	struct intel_gt_timelines *gt = &i915->gt.timelines;
915
	struct intel_timeline *tl;
916 917

	mutex_lock(&gt->mutex);
C
Chris Wilson 已提交
918
	list_for_each_entry(tl, &gt->active_list, link) {
919 920
		struct i915_request *rq;

921
		rq = i915_active_request_get_unlocked(&tl->last_request);
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
		if (!rq)
			continue;

		mutex_unlock(&gt->mutex);

		/*
		 * "Race-to-idle".
		 *
		 * Switching to the kernel context is often used a synchronous
		 * step prior to idling, e.g. in suspend for flushing all
		 * current operations to memory before sleeping. These we
		 * want to complete as quickly as possible to avoid prolonged
		 * stalls, so allow the gpu to boost to maximum clocks.
		 */
		if (flags & I915_WAIT_FOR_IDLE_BOOST)
937
			gen6_rps_boost(rq);
938 939 940 941 942 943 944 945

		timeout = i915_request_wait(rq, flags, timeout);
		i915_request_put(rq);
		if (timeout < 0)
			return timeout;

		/* restart after reacquiring the lock */
		mutex_lock(&gt->mutex);
C
Chris Wilson 已提交
946
		tl = list_entry(&gt->active_list, typeof(*tl), link);
947 948 949 950 951 952
	}
	mutex_unlock(&gt->mutex);

	return timeout;
}

953 954
int i915_gem_wait_for_idle(struct drm_i915_private *i915,
			   unsigned int flags, long timeout)
955
{
956
	GEM_TRACE("flags=%x (%s), timeout=%ld%s, awake?=%s\n",
957
		  flags, flags & I915_WAIT_LOCKED ? "locked" : "unlocked",
958 959
		  timeout, timeout == MAX_SCHEDULE_TIMEOUT ? " (forever)" : "",
		  yesno(i915->gt.awake));
960

961 962 963 964
	/* If the device is asleep, we have no requests outstanding */
	if (!READ_ONCE(i915->gt.awake))
		return 0;

965 966 967 968
	timeout = wait_for_timelines(i915, flags, timeout);
	if (timeout < 0)
		return timeout;

969
	if (flags & I915_WAIT_LOCKED) {
970
		int err;
971 972 973

		lockdep_assert_held(&i915->drm.struct_mutex);

974 975 976 977
		err = wait_for_engines(i915);
		if (err)
			return err;

978
		i915_retire_requests(i915);
979
	}
980 981

	return 0;
982 983
}

C
Chris Wilson 已提交
984
struct i915_vma *
985 986
i915_gem_object_ggtt_pin(struct drm_i915_gem_object *obj,
			 const struct i915_ggtt_view *view,
987
			 u64 size,
988 989
			 u64 alignment,
			 u64 flags)
990
{
991
	struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
992
	struct i915_address_space *vm = &dev_priv->ggtt.vm;
993 994
	struct i915_vma *vma;
	int ret;
995

996 997
	lockdep_assert_held(&obj->base.dev->struct_mutex);

998 999
	if (flags & PIN_MAPPABLE &&
	    (!view || view->type == I915_GGTT_VIEW_NORMAL)) {
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
		/* If the required space is larger than the available
		 * aperture, we will not able to find a slot for the
		 * object and unbinding the object now will be in
		 * vain. Worse, doing so may cause us to ping-pong
		 * the object in and out of the Global GTT and
		 * waste a lot of cycles under the mutex.
		 */
		if (obj->base.size > dev_priv->ggtt.mappable_end)
			return ERR_PTR(-E2BIG);

		/* If NONBLOCK is set the caller is optimistically
		 * trying to cache the full object within the mappable
		 * aperture, and *must* have a fallback in place for
		 * situations where we cannot bind the object. We
		 * can be a little more lax here and use the fallback
		 * more often to avoid costly migrations of ourselves
		 * and other objects within the aperture.
		 *
		 * Half-the-aperture is used as a simple heuristic.
		 * More interesting would to do search for a free
		 * block prior to making the commitment to unbind.
		 * That caters for the self-harm case, and with a
		 * little more heuristics (e.g. NOFAULT, NOEVICT)
		 * we could try to minimise harm to others.
		 */
		if (flags & PIN_NONBLOCK &&
		    obj->base.size > dev_priv->ggtt.mappable_end / 2)
			return ERR_PTR(-ENOSPC);
	}

1030
	vma = i915_vma_instance(obj, vm, view);
1031
	if (IS_ERR(vma))
C
Chris Wilson 已提交
1032
		return vma;
1033 1034

	if (i915_vma_misplaced(vma, size, alignment, flags)) {
1035 1036 1037
		if (flags & PIN_NONBLOCK) {
			if (i915_vma_is_pinned(vma) || i915_vma_is_active(vma))
				return ERR_PTR(-ENOSPC);
1038

1039
			if (flags & PIN_MAPPABLE &&
1040
			    vma->fence_size > dev_priv->ggtt.mappable_end / 2)
1041 1042 1043
				return ERR_PTR(-ENOSPC);
		}

1044 1045
		WARN(i915_vma_is_pinned(vma),
		     "bo is already pinned in ggtt with incorrect alignment:"
1046 1047 1048
		     " offset=%08x, req.alignment=%llx,"
		     " req.map_and_fenceable=%d, vma->map_and_fenceable=%d\n",
		     i915_ggtt_offset(vma), alignment,
1049
		     !!(flags & PIN_MAPPABLE),
1050
		     i915_vma_is_map_and_fenceable(vma));
1051 1052
		ret = i915_vma_unbind(vma);
		if (ret)
C
Chris Wilson 已提交
1053
			return ERR_PTR(ret);
1054 1055
	}

C
Chris Wilson 已提交
1056 1057 1058
	ret = i915_vma_pin(vma, size, alignment, flags | PIN_GLOBAL);
	if (ret)
		return ERR_PTR(ret);
1059

C
Chris Wilson 已提交
1060
	return vma;
1061 1062
}

1063 1064 1065 1066
int
i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
		       struct drm_file *file_priv)
{
1067
	struct drm_i915_private *i915 = to_i915(dev);
1068
	struct drm_i915_gem_madvise *args = data;
1069
	struct drm_i915_gem_object *obj;
1070
	int err;
1071 1072 1073 1074 1075 1076 1077 1078 1079

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

1080
	obj = i915_gem_object_lookup(file_priv, args->handle);
1081 1082 1083 1084 1085 1086
	if (!obj)
		return -ENOENT;

	err = mutex_lock_interruptible(&obj->mm.lock);
	if (err)
		goto out;
1087

1088
	if (i915_gem_object_has_pages(obj) &&
1089
	    i915_gem_object_is_tiled(obj) &&
1090
	    i915->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
1091 1092
		if (obj->mm.madv == I915_MADV_WILLNEED) {
			GEM_BUG_ON(!obj->mm.quirked);
C
Chris Wilson 已提交
1093
			__i915_gem_object_unpin_pages(obj);
1094 1095 1096
			obj->mm.quirked = false;
		}
		if (args->madv == I915_MADV_WILLNEED) {
1097
			GEM_BUG_ON(obj->mm.quirked);
C
Chris Wilson 已提交
1098
			__i915_gem_object_pin_pages(obj);
1099 1100
			obj->mm.quirked = true;
		}
1101 1102
	}

C
Chris Wilson 已提交
1103 1104
	if (obj->mm.madv != __I915_MADV_PURGED)
		obj->mm.madv = args->madv;
1105

1106 1107 1108
	if (i915_gem_object_has_pages(obj)) {
		struct list_head *list;

1109
		if (i915_gem_object_is_shrinkable(obj)) {
1110 1111 1112 1113
			unsigned long flags;

			spin_lock_irqsave(&i915->mm.obj_lock, flags);

1114 1115 1116
			if (obj->mm.madv != I915_MADV_WILLNEED)
				list = &i915->mm.purge_list;
			else
1117
				list = &i915->mm.shrink_list;
1118
			list_move_tail(&obj->mm.link, list);
1119 1120

			spin_unlock_irqrestore(&i915->mm.obj_lock, flags);
1121
		}
1122 1123
	}

C
Chris Wilson 已提交
1124
	/* if the object is no longer attached, discard its backing storage */
1125 1126
	if (obj->mm.madv == I915_MADV_DONTNEED &&
	    !i915_gem_object_has_pages(obj))
1127
		i915_gem_object_truncate(obj);
1128

C
Chris Wilson 已提交
1129
	args->retained = obj->mm.madv != __I915_MADV_PURGED;
1130
	mutex_unlock(&obj->mm.lock);
C
Chris Wilson 已提交
1131

1132
out:
1133
	i915_gem_object_put(obj);
1134
	return err;
1135 1136
}

1137 1138
void i915_gem_sanitize(struct drm_i915_private *i915)
{
1139 1140
	intel_wakeref_t wakeref;

1141 1142
	GEM_TRACE("\n");

1143
	wakeref = intel_runtime_pm_get(&i915->runtime_pm);
1144
	intel_uncore_forcewake_get(&i915->uncore, FORCEWAKE_ALL);
1145 1146 1147 1148 1149 1150 1151

	/*
	 * As we have just resumed the machine and woken the device up from
	 * deep PCI sleep (presumably D3_cold), assume the HW has been reset
	 * back to defaults, recovering from whatever wedged state we left it
	 * in and so worth trying to use the device once more.
	 */
1152
	if (i915_terminally_wedged(i915))
1153 1154
		i915_gem_unset_wedged(i915);

1155 1156 1157 1158 1159 1160
	/*
	 * If we inherit context state from the BIOS or earlier occupants
	 * of the GPU, the GPU may be in an inconsistent state when we
	 * try to take over. The only way to remove the earlier state
	 * is by resetting. However, resetting on earlier gen is tricky as
	 * it may impact the display and we are uncertain about the stability
1161
	 * of the reset, so this could be applied to even earlier gen.
1162
	 */
1163
	intel_gt_sanitize(&i915->gt, false);
1164

1165
	intel_uncore_forcewake_put(&i915->uncore, FORCEWAKE_ALL);
1166
	intel_runtime_pm_put(&i915->runtime_pm, wakeref);
1167 1168
}

1169
static void init_unused_ring(struct intel_gt *gt, u32 base)
1170
{
1171 1172 1173 1174 1175 1176
	struct intel_uncore *uncore = gt->uncore;

	intel_uncore_write(uncore, RING_CTL(base), 0);
	intel_uncore_write(uncore, RING_HEAD(base), 0);
	intel_uncore_write(uncore, RING_TAIL(base), 0);
	intel_uncore_write(uncore, RING_START(base), 0);
1177 1178
}

1179
static void init_unused_rings(struct intel_gt *gt)
1180
{
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
	struct drm_i915_private *i915 = gt->i915;

	if (IS_I830(i915)) {
		init_unused_ring(gt, PRB1_BASE);
		init_unused_ring(gt, SRB0_BASE);
		init_unused_ring(gt, SRB1_BASE);
		init_unused_ring(gt, SRB2_BASE);
		init_unused_ring(gt, SRB3_BASE);
	} else if (IS_GEN(i915, 2)) {
		init_unused_ring(gt, SRB0_BASE);
		init_unused_ring(gt, SRB1_BASE);
	} else if (IS_GEN(i915, 3)) {
		init_unused_ring(gt, PRB1_BASE);
		init_unused_ring(gt, PRB2_BASE);
1195 1196 1197
	}
}

1198
int i915_gem_init_hw(struct drm_i915_private *i915)
1199
{
1200 1201
	struct intel_uncore *uncore = &i915->uncore;
	struct intel_gt *gt = &i915->gt;
C
Chris Wilson 已提交
1202
	int ret;
1203

1204 1205 1206 1207 1208
	BUG_ON(!i915->kernel_context);
	ret = i915_terminally_wedged(i915);
	if (ret)
		return ret;

1209
	gt->last_init_time = ktime_get();
1210

1211
	/* Double layer security blanket, see i915_gem_init() */
1212
	intel_uncore_forcewake_get(uncore, FORCEWAKE_ALL);
1213

1214 1215
	if (HAS_EDRAM(i915) && INTEL_GEN(i915) < 9)
		intel_uncore_rmw(uncore, HSW_IDICR, 0, IDIHASHMSK(0xf));
1216

1217 1218 1219 1220 1221
	if (IS_HASWELL(i915))
		intel_uncore_write(uncore,
				   MI_PREDICATE_RESULT_2,
				   IS_HSW_GT3(i915) ?
				   LOWER_SLICE_ENABLED : LOWER_SLICE_DISABLED);
1222

1223
	/* Apply the GT workarounds... */
1224
	intel_gt_apply_workarounds(gt);
1225
	/* ...and determine whether they are sticking. */
1226
	intel_gt_verify_workarounds(gt, "init");
1227

1228
	intel_gt_init_swizzling(gt);
1229

1230 1231 1232 1233 1234 1235
	/*
	 * At least 830 can leave some of the unused rings
	 * "active" (ie. head != tail) after resume which
	 * will prevent c3 entry. Makes sure all unused rings
	 * are totally idle.
	 */
1236
	init_unused_rings(gt);
1237

1238
	ret = i915_ppgtt_init_hw(gt);
1239
	if (ret) {
1240
		DRM_ERROR("Enabling PPGTT failed (%d)\n", ret);
1241 1242 1243
		goto out;
	}

1244
	ret = intel_wopcm_init_hw(&i915->wopcm, gt);
1245 1246 1247 1248 1249
	if (ret) {
		DRM_ERROR("Enabling WOPCM failed (%d)\n", ret);
		goto out;
	}

1250
	/* We can't enable contexts until all firmware is loaded */
1251
	ret = intel_uc_init_hw(i915);
1252 1253
	if (ret) {
		DRM_ERROR("Enabling uc failed (%d)\n", ret);
1254
		goto out;
1255
	}
1256

1257
	intel_mocs_init_l3cc_table(gt);
1258

1259 1260
	intel_engines_set_scheduler_caps(i915);

1261
out:
1262
	intel_uncore_forcewake_put(uncore, FORCEWAKE_ALL);
1263
	return ret;
1264 1265
}

1266 1267 1268
static int __intel_engines_record_defaults(struct drm_i915_private *i915)
{
	struct intel_engine_cs *engine;
1269 1270
	struct i915_gem_context *ctx;
	struct i915_gem_engines *e;
1271
	enum intel_engine_id id;
1272
	int err = 0;
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286

	/*
	 * As we reset the gpu during very early sanitisation, the current
	 * register state on the GPU should reflect its defaults values.
	 * We load a context onto the hw (with restore-inhibit), then switch
	 * over to a second context to save that default register state. We
	 * can then prime every new context with that state so they all start
	 * from the same default HW values.
	 */

	ctx = i915_gem_context_create_kernel(i915, 0);
	if (IS_ERR(ctx))
		return PTR_ERR(ctx);

1287 1288
	e = i915_gem_context_lock_engines(ctx);

1289
	for_each_engine(engine, i915, id) {
1290
		struct intel_context *ce = e->engines[id];
1291
		struct i915_request *rq;
1292

1293
		rq = intel_context_create_request(ce);
1294 1295
		if (IS_ERR(rq)) {
			err = PTR_ERR(rq);
1296
			goto err_active;
1297 1298
		}

1299
		err = 0;
1300 1301
		if (rq->engine->init_context)
			err = rq->engine->init_context(rq);
1302

1303
		i915_request_add(rq);
1304 1305 1306 1307
		if (err)
			goto err_active;
	}

1308
	/* Flush the default context image to memory, and enable powersaving. */
1309
	if (!i915_gem_load_power_context(i915)) {
1310
		err = -EIO;
1311
		goto err_active;
1312
	}
1313 1314

	for_each_engine(engine, i915, id) {
1315 1316
		struct intel_context *ce = e->engines[id];
		struct i915_vma *state = ce->state;
1317
		void *vaddr;
1318 1319 1320 1321

		if (!state)
			continue;

1322
		GEM_BUG_ON(intel_context_is_pinned(ce));
1323

1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
		/*
		 * As we will hold a reference to the logical state, it will
		 * not be torn down with the context, and importantly the
		 * object will hold onto its vma (making it possible for a
		 * stray GTT write to corrupt our defaults). Unmap the vma
		 * from the GTT to prevent such accidents and reclaim the
		 * space.
		 */
		err = i915_vma_unbind(state);
		if (err)
			goto err_active;

1336
		i915_gem_object_lock(state->obj);
1337
		err = i915_gem_object_set_to_cpu_domain(state->obj, false);
1338
		i915_gem_object_unlock(state->obj);
1339 1340 1341 1342
		if (err)
			goto err_active;

		engine->default_state = i915_gem_object_get(state->obj);
1343 1344
		i915_gem_object_set_cache_coherency(engine->default_state,
						    I915_CACHE_LLC);
1345 1346 1347

		/* Check we can acquire the image of the context state */
		vaddr = i915_gem_object_pin_map(engine->default_state,
1348
						I915_MAP_FORCE_WB);
1349 1350 1351 1352 1353 1354
		if (IS_ERR(vaddr)) {
			err = PTR_ERR(vaddr);
			goto err_active;
		}

		i915_gem_object_unpin_map(engine->default_state);
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
	}

	if (IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM)) {
		unsigned int found = intel_engines_has_context_isolation(i915);

		/*
		 * Make sure that classes with multiple engine instances all
		 * share the same basic configuration.
		 */
		for_each_engine(engine, i915, id) {
			unsigned int bit = BIT(engine->uabi_class);
			unsigned int expected = engine->default_state ? bit : 0;

			if ((found & bit) != expected) {
				DRM_ERROR("mismatching default context state for class %d on engine %s\n",
					  engine->uabi_class, engine->name);
			}
		}
	}

out_ctx:
1376
	i915_gem_context_unlock_engines(ctx);
1377 1378 1379 1380 1381 1382 1383
	i915_gem_context_set_closed(ctx);
	i915_gem_context_put(ctx);
	return err;

err_active:
	/*
	 * If we have to abandon now, we expect the engines to be idle
1384 1385
	 * and ready to be torn-down. The quickest way we can accomplish
	 * this is by declaring ourselves wedged.
1386
	 */
1387
	i915_gem_set_wedged(i915);
1388 1389 1390
	goto out_ctx;
}

1391 1392 1393
static int
i915_gem_init_scratch(struct drm_i915_private *i915, unsigned int size)
{
1394
	return intel_gt_init_scratch(&i915->gt, size);
1395 1396 1397 1398
}

static void i915_gem_fini_scratch(struct drm_i915_private *i915)
{
1399
	intel_gt_fini_scratch(&i915->gt);
1400 1401
}

1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
static int intel_engines_verify_workarounds(struct drm_i915_private *i915)
{
	struct intel_engine_cs *engine;
	enum intel_engine_id id;
	int err = 0;

	if (!IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM))
		return 0;

	for_each_engine(engine, i915, id) {
		if (intel_engine_verify_workarounds(engine, "load"))
			err = -EIO;
	}

	return err;
}

1419
int i915_gem_init(struct drm_i915_private *dev_priv)
1420 1421 1422
{
	int ret;

1423 1424
	/* We need to fallback to 4K pages if host doesn't support huge gtt. */
	if (intel_vgpu_active(dev_priv) && !intel_vgpu_has_huge_gtt(dev_priv))
1425 1426 1427
		mkwrite_device_info(dev_priv)->page_sizes =
			I915_GTT_PAGE_SIZE_4K;

1428
	dev_priv->mm.unordered_timeline = dma_fence_context_alloc(1);
1429

1430
	intel_timelines_init(dev_priv);
1431

1432 1433 1434 1435
	ret = i915_gem_init_userptr(dev_priv);
	if (ret)
		return ret;

1436
	ret = intel_uc_init_misc(dev_priv);
1437 1438 1439
	if (ret)
		return ret;

1440
	ret = intel_wopcm_init(&dev_priv->wopcm);
1441
	if (ret)
1442
		goto err_uc_misc;
1443

1444 1445 1446 1447 1448 1449
	/* This is just a security blanket to placate dragons.
	 * On some systems, we very sporadically observe that the first TLBs
	 * used by the CS may be stale, despite us poking the TLB reset. If
	 * we hold the forcewake during initialisation these problems
	 * just magically go away.
	 */
1450
	mutex_lock(&dev_priv->drm.struct_mutex);
1451
	intel_uncore_forcewake_get(&dev_priv->uncore, FORCEWAKE_ALL);
1452

1453
	ret = i915_init_ggtt(dev_priv);
1454 1455 1456 1457
	if (ret) {
		GEM_BUG_ON(ret == -EIO);
		goto err_unlock;
	}
1458

1459
	ret = i915_gem_init_scratch(dev_priv,
1460
				    IS_GEN(dev_priv, 2) ? SZ_256K : PAGE_SIZE);
1461 1462 1463 1464
	if (ret) {
		GEM_BUG_ON(ret == -EIO);
		goto err_ggtt;
	}
1465

1466 1467 1468 1469 1470 1471
	ret = intel_engines_setup(dev_priv);
	if (ret) {
		GEM_BUG_ON(ret == -EIO);
		goto err_unlock;
	}

1472 1473 1474 1475 1476 1477
	ret = i915_gem_contexts_init(dev_priv);
	if (ret) {
		GEM_BUG_ON(ret == -EIO);
		goto err_scratch;
	}

1478
	ret = intel_engines_init(dev_priv);
1479 1480 1481 1482
	if (ret) {
		GEM_BUG_ON(ret == -EIO);
		goto err_context;
	}
1483

1484 1485
	intel_init_gt_powersave(dev_priv);

1486
	ret = intel_uc_init(dev_priv);
1487
	if (ret)
1488
		goto err_pm;
1489

1490 1491 1492 1493
	ret = i915_gem_init_hw(dev_priv);
	if (ret)
		goto err_uc_init;

1494 1495 1496 1497 1498
	/* Only when the HW is re-initialised, can we replay the requests */
	ret = intel_gt_resume(&dev_priv->gt);
	if (ret)
		goto err_init_hw;

1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509
	/*
	 * Despite its name intel_init_clock_gating applies both display
	 * clock gating workarounds; GT mmio workarounds and the occasional
	 * GT power context workaround. Worse, sometimes it includes a context
	 * register workaround which we need to apply before we record the
	 * default HW state for all contexts.
	 *
	 * FIXME: break up the workarounds and apply them at the right time!
	 */
	intel_init_clock_gating(dev_priv);

1510 1511
	ret = intel_engines_verify_workarounds(dev_priv);
	if (ret)
1512
		goto err_gt;
1513

1514
	ret = __intel_engines_record_defaults(dev_priv);
1515
	if (ret)
1516
		goto err_gt;
1517

1518
	if (i915_inject_probe_failure()) {
1519
		ret = -ENODEV;
1520
		goto err_gt;
1521 1522
	}

1523
	if (i915_inject_probe_failure()) {
1524
		ret = -EIO;
1525
		goto err_gt;
1526 1527
	}

1528
	intel_uncore_forcewake_put(&dev_priv->uncore, FORCEWAKE_ALL);
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
	mutex_unlock(&dev_priv->drm.struct_mutex);

	return 0;

	/*
	 * Unwinding is complicated by that we want to handle -EIO to mean
	 * disable GPU submission but keep KMS alive. We want to mark the
	 * HW as irrevisibly wedged, but keep enough state around that the
	 * driver doesn't explode during runtime.
	 */
1539
err_gt:
1540 1541
	mutex_unlock(&dev_priv->drm.struct_mutex);

1542
	i915_gem_set_wedged(dev_priv);
1543
	i915_gem_suspend(dev_priv);
1544 1545
	i915_gem_suspend_late(dev_priv);

1546 1547
	i915_gem_drain_workqueue(dev_priv);

1548
	mutex_lock(&dev_priv->drm.struct_mutex);
1549
err_init_hw:
1550
	intel_uc_fini_hw(dev_priv);
1551 1552
err_uc_init:
	intel_uc_fini(dev_priv);
1553 1554 1555
err_pm:
	if (ret != -EIO) {
		intel_cleanup_gt_powersave(dev_priv);
1556
		intel_engines_cleanup(dev_priv);
1557 1558 1559 1560
	}
err_context:
	if (ret != -EIO)
		i915_gem_contexts_fini(dev_priv);
1561 1562
err_scratch:
	i915_gem_fini_scratch(dev_priv);
1563 1564
err_ggtt:
err_unlock:
1565
	intel_uncore_forcewake_put(&dev_priv->uncore, FORCEWAKE_ALL);
1566 1567
	mutex_unlock(&dev_priv->drm.struct_mutex);

1568
err_uc_misc:
1569
	intel_uc_fini_misc(dev_priv);
1570

1571
	if (ret != -EIO) {
1572
		i915_gem_cleanup_userptr(dev_priv);
1573
		intel_timelines_fini(dev_priv);
1574
	}
1575

1576
	if (ret == -EIO) {
1577 1578
		mutex_lock(&dev_priv->drm.struct_mutex);

1579 1580
		/*
		 * Allow engine initialisation to fail by marking the GPU as
1581 1582 1583
		 * wedged. But we only want to do this where the GPU is angry,
		 * for all other failure, such as an allocation failure, bail.
		 */
1584
		if (!i915_reset_failed(dev_priv)) {
1585 1586
			i915_probe_error(dev_priv,
					 "Failed to initialize GPU, declaring it wedged!\n");
1587 1588
			i915_gem_set_wedged(dev_priv);
		}
1589 1590 1591 1592 1593 1594 1595 1596

		/* Minimal basic recovery for KMS */
		ret = i915_ggtt_enable_hw(dev_priv);
		i915_gem_restore_gtt_mappings(dev_priv);
		i915_gem_restore_fences(dev_priv);
		intel_init_clock_gating(dev_priv);

		mutex_unlock(&dev_priv->drm.struct_mutex);
1597 1598
	}

1599
	i915_gem_drain_freed_objects(dev_priv);
1600
	return ret;
1601 1602
}

1603
void i915_gem_driver_remove(struct drm_i915_private *dev_priv)
1604
{
1605 1606
	GEM_BUG_ON(dev_priv->gt.awake);

1607
	intel_wakeref_auto_fini(&dev_priv->ggtt.userfault_wakeref);
1608

1609
	i915_gem_suspend_late(dev_priv);
1610
	intel_disable_gt_powersave(dev_priv);
1611 1612 1613 1614 1615 1616 1617

	/* Flush any outstanding unpin_work. */
	i915_gem_drain_workqueue(dev_priv);

	mutex_lock(&dev_priv->drm.struct_mutex);
	intel_uc_fini_hw(dev_priv);
	intel_uc_fini(dev_priv);
1618 1619 1620 1621 1622
	mutex_unlock(&dev_priv->drm.struct_mutex);

	i915_gem_drain_freed_objects(dev_priv);
}

1623
void i915_gem_driver_release(struct drm_i915_private *dev_priv)
1624 1625
{
	mutex_lock(&dev_priv->drm.struct_mutex);
1626
	intel_engines_cleanup(dev_priv);
1627
	i915_gem_contexts_fini(dev_priv);
1628
	i915_gem_fini_scratch(dev_priv);
1629 1630
	mutex_unlock(&dev_priv->drm.struct_mutex);

1631 1632
	intel_wa_list_free(&dev_priv->gt_wa_list);

1633 1634
	intel_cleanup_gt_powersave(dev_priv);

1635 1636
	intel_uc_fini_misc(dev_priv);
	i915_gem_cleanup_userptr(dev_priv);
1637
	intel_timelines_fini(dev_priv);
1638 1639 1640 1641 1642 1643

	i915_gem_drain_freed_objects(dev_priv);

	WARN_ON(!list_empty(&dev_priv->contexts.list));
}

1644 1645 1646 1647 1648
void i915_gem_init_mmio(struct drm_i915_private *i915)
{
	i915_gem_sanitize(i915);
}

1649 1650 1651 1652 1653 1654 1655
static void i915_gem_init__mm(struct drm_i915_private *i915)
{
	spin_lock_init(&i915->mm.obj_lock);
	spin_lock_init(&i915->mm.free_lock);

	init_llist_head(&i915->mm.free_list);

1656
	INIT_LIST_HEAD(&i915->mm.purge_list);
1657
	INIT_LIST_HEAD(&i915->mm.shrink_list);
1658

1659
	i915_gem_init__objects(i915);
1660 1661
}

1662
int i915_gem_init_early(struct drm_i915_private *dev_priv)
1663
{
1664
	int err;
1665

1666
	i915_gem_init__mm(dev_priv);
1667
	i915_gem_init__pm(dev_priv);
1668

1669
	init_waitqueue_head(&dev_priv->gpu_error.wait_queue);
1670
	init_waitqueue_head(&dev_priv->gpu_error.reset_queue);
1671
	mutex_init(&dev_priv->gpu_error.wedge_mutex);
1672
	init_srcu_struct(&dev_priv->gpu_error.reset_backoff_srcu);
1673

1674 1675
	atomic_set(&dev_priv->mm.bsd_engine_dispatch_index, 0);

1676
	spin_lock_init(&dev_priv->fb_tracking.lock);
1677

M
Matthew Auld 已提交
1678 1679 1680 1681
	err = i915_gemfs_init(dev_priv);
	if (err)
		DRM_NOTE("Unable to create a private tmpfs mount, hugepage support will be disabled(%d).\n", err);

1682
	return 0;
1683
}
1684

1685
void i915_gem_cleanup_early(struct drm_i915_private *dev_priv)
1686
{
1687
	i915_gem_drain_freed_objects(dev_priv);
1688 1689
	GEM_BUG_ON(!llist_empty(&dev_priv->mm.free_list));
	GEM_BUG_ON(atomic_read(&dev_priv->mm.free_count));
1690
	WARN_ON(dev_priv->mm.shrink_count);
1691

1692 1693
	cleanup_srcu_struct(&dev_priv->gpu_error.reset_backoff_srcu);

M
Matthew Auld 已提交
1694
	i915_gemfs_fini(dev_priv);
1695 1696
}

1697 1698
int i915_gem_freeze(struct drm_i915_private *dev_priv)
{
1699 1700 1701
	/* Discard all purgeable objects, let userspace recover those as
	 * required after resuming.
	 */
1702 1703 1704 1705 1706
	i915_gem_shrink_all(dev_priv);

	return 0;
}

1707
int i915_gem_freeze_late(struct drm_i915_private *i915)
1708 1709
{
	struct drm_i915_gem_object *obj;
1710
	intel_wakeref_t wakeref;
1711

1712 1713
	/*
	 * Called just before we write the hibernation image.
1714 1715 1716 1717 1718 1719 1720 1721
	 *
	 * We need to update the domain tracking to reflect that the CPU
	 * will be accessing all the pages to create and restore from the
	 * hibernation, and so upon restoration those pages will be in the
	 * CPU domain.
	 *
	 * To make sure the hibernation image contains the latest state,
	 * we update that state just before writing out the image.
1722 1723
	 *
	 * To try and reduce the hibernation image, we manually shrink
1724
	 * the objects as well, see i915_gem_freeze()
1725 1726
	 */

1727
	wakeref = intel_runtime_pm_get(&i915->runtime_pm);
1728 1729

	i915_gem_shrink(i915, -1UL, NULL, ~0);
1730
	i915_gem_drain_freed_objects(i915);
1731

1732 1733 1734 1735
	list_for_each_entry(obj, &i915->mm.shrink_list, mm.link) {
		i915_gem_object_lock(obj);
		WARN_ON(i915_gem_object_set_to_cpu_domain(obj, true));
		i915_gem_object_unlock(obj);
1736
	}
1737

1738
	intel_runtime_pm_put(&i915->runtime_pm, wakeref);
1739 1740 1741 1742

	return 0;
}

1743
void i915_gem_release(struct drm_device *dev, struct drm_file *file)
1744
{
1745
	struct drm_i915_file_private *file_priv = file->driver_priv;
1746
	struct i915_request *request;
1747 1748 1749 1750 1751

	/* 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.
	 */
1752
	spin_lock(&file_priv->mm.lock);
1753
	list_for_each_entry(request, &file_priv->mm.request_list, client_link)
1754
		request->file_priv = NULL;
1755
	spin_unlock(&file_priv->mm.lock);
1756 1757
}

1758
int i915_gem_open(struct drm_i915_private *i915, struct drm_file *file)
1759 1760
{
	struct drm_i915_file_private *file_priv;
1761
	int ret;
1762

1763
	DRM_DEBUG("\n");
1764 1765 1766 1767 1768 1769

	file_priv = kzalloc(sizeof(*file_priv), GFP_KERNEL);
	if (!file_priv)
		return -ENOMEM;

	file->driver_priv = file_priv;
1770
	file_priv->dev_priv = i915;
1771
	file_priv->file = file;
1772 1773 1774 1775

	spin_lock_init(&file_priv->mm.lock);
	INIT_LIST_HEAD(&file_priv->mm.request_list);

1776
	file_priv->bsd_engine = -1;
1777
	file_priv->hang_timestamp = jiffies;
1778

1779
	ret = i915_gem_context_open(i915, file);
1780 1781
	if (ret)
		kfree(file_priv);
1782

1783
	return ret;
1784 1785
}

1786 1787
/**
 * i915_gem_track_fb - update frontbuffer tracking
1788 1789 1790
 * @old: current GEM buffer for the frontbuffer slots
 * @new: new GEM buffer for the frontbuffer slots
 * @frontbuffer_bits: bitmask of frontbuffer slots
1791 1792 1793 1794
 *
 * This updates the frontbuffer tracking bits @frontbuffer_bits by clearing them
 * from @old and setting them in @new. Both @old and @new can be NULL.
 */
1795 1796 1797 1798
void i915_gem_track_fb(struct drm_i915_gem_object *old,
		       struct drm_i915_gem_object *new,
		       unsigned frontbuffer_bits)
{
1799 1800 1801 1802 1803 1804 1805
	/* Control of individual bits within the mask are guarded by
	 * the owning plane->mutex, i.e. we can never see concurrent
	 * manipulation of individual bits. But since the bitfield as a whole
	 * is updated using RMW, we need to use atomics in order to update
	 * the bits.
	 */
	BUILD_BUG_ON(INTEL_FRONTBUFFER_BITS_PER_PIPE * I915_MAX_PIPES >
1806
		     BITS_PER_TYPE(atomic_t));
1807

1808
	if (old) {
1809 1810
		WARN_ON(!(atomic_read(&old->frontbuffer_bits) & frontbuffer_bits));
		atomic_andnot(frontbuffer_bits, &old->frontbuffer_bits);
1811 1812 1813
	}

	if (new) {
1814 1815
		WARN_ON(atomic_read(&new->frontbuffer_bits) & frontbuffer_bits);
		atomic_or(frontbuffer_bits, &new->frontbuffer_bits);
1816 1817 1818
	}
}

1819
#if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
1820
#include "selftests/mock_gem_device.c"
1821
#include "selftests/i915_gem.c"
1822
#endif