i915_gem_userptr.c 22.1 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
/*
 * Copyright © 2012-2014 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.
 *
 */

25 26
#include <drm/drmP.h>
#include <drm/i915_drm.h>
27 28 29 30 31 32 33
#include "i915_drv.h"
#include "i915_trace.h"
#include "intel_drv.h"
#include <linux/mmu_context.h>
#include <linux/mmu_notifier.h>
#include <linux/mempolicy.h>
#include <linux/swap.h>
34
#include <linux/sched/mm.h>
35

36 37
struct i915_mm_struct {
	struct mm_struct *mm;
38
	struct drm_i915_private *i915;
39 40 41 42 43 44
	struct i915_mmu_notifier *mn;
	struct hlist_node node;
	struct kref kref;
	struct work_struct work;
};

45 46 47 48 49 50 51 52
#if defined(CONFIG_MMU_NOTIFIER)
#include <linux/interval_tree.h>

struct i915_mmu_notifier {
	spinlock_t lock;
	struct hlist_node node;
	struct mmu_notifier mn;
	struct rb_root objects;
53
	struct workqueue_struct *wq;
54 55 56
};

struct i915_mmu_object {
57
	struct i915_mmu_notifier *mn;
58
	struct drm_i915_gem_object *obj;
59
	struct interval_tree_node it;
60
	struct list_head link;
61
	struct work_struct work;
62
	bool attached;
63 64
};

65
static void cancel_userptr(struct work_struct *work)
66
{
67 68
	struct i915_mmu_object *mo = container_of(work, typeof(*mo), work);
	struct drm_i915_gem_object *obj = mo->obj;
69 70 71 72 73 74 75 76
	struct work_struct *active;

	/* Cancel any active worker and force us to re-evaluate gup */
	mutex_lock(&obj->mm.lock);
	active = fetch_and_zero(&obj->userptr.work);
	mutex_unlock(&obj->mm.lock);
	if (active)
		goto out;
77

78
	i915_gem_object_wait(obj, I915_WAIT_ALL, MAX_SCHEDULE_TIMEOUT, NULL);
79

80
	mutex_lock(&obj->base.dev->struct_mutex);
81

82 83
	/* We are inside a kthread context and can't be interrupted */
	if (i915_gem_object_unbind(obj) == 0)
84
		__i915_gem_object_put_pages(obj, I915_MM_NORMAL);
85 86 87
	WARN_ONCE(obj->mm.pages,
		  "Failed to release pages: bind_count=%d, pages_pin_count=%d, pin_display=%d\n",
		  obj->bind_count,
88
		  atomic_read(&obj->mm.pages_pin_count),
89
		  obj->pin_display);
90

91 92 93
	mutex_unlock(&obj->base.dev->struct_mutex);

out:
94
	i915_gem_object_put(obj);
95 96
}

97
static void add_object(struct i915_mmu_object *mo)
98
{
99 100
	if (mo->attached)
		return;
101

102 103 104 105 106 107 108 109 110 111 112
	interval_tree_insert(&mo->it, &mo->mn->objects);
	mo->attached = true;
}

static void del_object(struct i915_mmu_object *mo)
{
	if (!mo->attached)
		return;

	interval_tree_remove(&mo->it, &mo->mn->objects);
	mo->attached = false;
113 114
}

115 116 117 118 119
static void i915_gem_userptr_mn_invalidate_range_start(struct mmu_notifier *_mn,
						       struct mm_struct *mm,
						       unsigned long start,
						       unsigned long end)
{
120 121 122
	struct i915_mmu_notifier *mn =
		container_of(_mn, struct i915_mmu_notifier, mn);
	struct i915_mmu_object *mo;
123 124 125 126 127
	struct interval_tree_node *it;
	LIST_HEAD(cancelled);

	if (RB_EMPTY_ROOT(&mn->objects))
		return;
128 129 130 131 132

	/* interval ranges are inclusive, but invalidate range is exclusive */
	end--;

	spin_lock(&mn->lock);
133 134 135 136 137 138 139 140 141 142 143 144 145
	it = interval_tree_iter_first(&mn->objects, start, end);
	while (it) {
		/* The mmu_object is released late when destroying the
		 * GEM object so it is entirely possible to gain a
		 * reference on an object in the process of being freed
		 * since our serialisation is via the spinlock and not
		 * the struct_mutex - and consequently use it after it
		 * is freed and then double free it. To prevent that
		 * use-after-free we only acquire a reference on the
		 * object if it is not in the process of being destroyed.
		 */
		mo = container_of(it, struct i915_mmu_object, it);
		if (kref_get_unless_zero(&mo->obj->base.refcount))
146
			queue_work(mn->wq, &mo->work);
147

148 149
		list_add(&mo->link, &cancelled);
		it = interval_tree_iter_next(it, start, end);
150
	}
151 152
	list_for_each_entry(mo, &cancelled, link)
		del_object(mo);
153
	spin_unlock(&mn->lock);
154

155 156
	if (!list_empty(&cancelled))
		flush_workqueue(mn->wq);
157 158 159 160 161 162 163
}

static const struct mmu_notifier_ops i915_gem_userptr_notifier = {
	.invalidate_range_start = i915_gem_userptr_mn_invalidate_range_start,
};

static struct i915_mmu_notifier *
164
i915_mmu_notifier_create(struct mm_struct *mm)
165
{
166
	struct i915_mmu_notifier *mn;
167 168
	int ret;

169 170
	mn = kmalloc(sizeof(*mn), GFP_KERNEL);
	if (mn == NULL)
171 172
		return ERR_PTR(-ENOMEM);

173 174 175
	spin_lock_init(&mn->lock);
	mn->mn.ops = &i915_gem_userptr_notifier;
	mn->objects = RB_ROOT;
176 177 178 179 180
	mn->wq = alloc_workqueue("i915-userptr-release", WQ_UNBOUND, 0);
	if (mn->wq == NULL) {
		kfree(mn);
		return ERR_PTR(-ENOMEM);
	}
181 182 183

	 /* Protected by mmap_sem (write-lock) */
	ret = __mmu_notifier_register(&mn->mn, mm);
184
	if (ret) {
185
		destroy_workqueue(mn->wq);
186
		kfree(mn);
187 188 189
		return ERR_PTR(ret);
	}

190
	return mn;
191 192 193 194 195
}

static void
i915_gem_userptr_release__mmu_notifier(struct drm_i915_gem_object *obj)
{
196
	struct i915_mmu_object *mo;
197

198 199
	mo = obj->userptr.mmu_object;
	if (mo == NULL)
200 201
		return;

202 203 204
	spin_lock(&mo->mn->lock);
	del_object(mo);
	spin_unlock(&mo->mn->lock);
205 206 207 208 209 210 211 212
	kfree(mo);

	obj->userptr.mmu_object = NULL;
}

static struct i915_mmu_notifier *
i915_mmu_notifier_find(struct i915_mm_struct *mm)
{
213 214 215 216 217 218 219
	struct i915_mmu_notifier *mn = mm->mn;

	mn = mm->mn;
	if (mn)
		return mn;

	down_write(&mm->mm->mmap_sem);
220
	mutex_lock(&mm->i915->mm_lock);
221 222 223 224
	if ((mn = mm->mn) == NULL) {
		mn = i915_mmu_notifier_create(mm->mm);
		if (!IS_ERR(mn))
			mm->mn = mn;
225
	}
226
	mutex_unlock(&mm->i915->mm_lock);
227 228 229
	up_write(&mm->mm->mmap_sem);

	return mn;
230 231 232 233 234 235
}

static int
i915_gem_userptr_init__mmu_notifier(struct drm_i915_gem_object *obj,
				    unsigned flags)
{
236 237
	struct i915_mmu_notifier *mn;
	struct i915_mmu_object *mo;
238 239 240 241

	if (flags & I915_USERPTR_UNSYNCHRONIZED)
		return capable(CAP_SYS_ADMIN) ? 0 : -EPERM;

242 243
	if (WARN_ON(obj->userptr.mm == NULL))
		return -EINVAL;
244

245 246 247
	mn = i915_mmu_notifier_find(obj->userptr.mm);
	if (IS_ERR(mn))
		return PTR_ERR(mn);
248

249 250 251
	mo = kzalloc(sizeof(*mo), GFP_KERNEL);
	if (mo == NULL)
		return -ENOMEM;
252

253 254
	mo->mn = mn;
	mo->obj = obj;
255 256 257
	mo->it.start = obj->userptr.ptr;
	mo->it.last = obj->userptr.ptr + obj->base.size - 1;
	INIT_WORK(&mo->work, cancel_userptr);
258 259

	obj->userptr.mmu_object = mo;
260
	return 0;
261 262 263 264 265 266 267 268
}

static void
i915_mmu_notifier_free(struct i915_mmu_notifier *mn,
		       struct mm_struct *mm)
{
	if (mn == NULL)
		return;
269

270
	mmu_notifier_unregister(&mn->mn, mm);
271
	destroy_workqueue(mn->wq);
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
	kfree(mn);
}

#else

static void
i915_gem_userptr_release__mmu_notifier(struct drm_i915_gem_object *obj)
{
}

static int
i915_gem_userptr_init__mmu_notifier(struct drm_i915_gem_object *obj,
				    unsigned flags)
{
	if ((flags & I915_USERPTR_UNSYNCHRONIZED) == 0)
		return -ENODEV;

	if (!capable(CAP_SYS_ADMIN))
		return -EPERM;

	return 0;
}
294 295 296 297 298 299 300

static void
i915_mmu_notifier_free(struct i915_mmu_notifier *mn,
		       struct mm_struct *mm)
{
}

301 302
#endif

303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
static struct i915_mm_struct *
__i915_mm_struct_find(struct drm_i915_private *dev_priv, struct mm_struct *real)
{
	struct i915_mm_struct *mm;

	/* Protected by dev_priv->mm_lock */
	hash_for_each_possible(dev_priv->mm_structs, mm, node, (unsigned long)real)
		if (mm->mm == real)
			return mm;

	return NULL;
}

static int
i915_gem_userptr_init__mm_struct(struct drm_i915_gem_object *obj)
{
	struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
	struct i915_mm_struct *mm;
	int ret = 0;

	/* During release of the GEM object we hold the struct_mutex. This
	 * precludes us from calling mmput() at that time as that may be
	 * the last reference and so call exit_mmap(). exit_mmap() will
	 * attempt to reap the vma, and if we were holding a GTT mmap
	 * would then call drm_gem_vm_close() and attempt to reacquire
	 * the struct mutex. So in order to avoid that recursion, we have
	 * to defer releasing the mm reference until after we drop the
	 * struct_mutex, i.e. we need to schedule a worker to do the clean
	 * up.
	 */
	mutex_lock(&dev_priv->mm_lock);
	mm = __i915_mm_struct_find(dev_priv, current->mm);
	if (mm == NULL) {
		mm = kmalloc(sizeof(*mm), GFP_KERNEL);
		if (mm == NULL) {
			ret = -ENOMEM;
			goto out;
		}

		kref_init(&mm->kref);
343
		mm->i915 = to_i915(obj->base.dev);
344 345

		mm->mm = current->mm;
V
Vegard Nossum 已提交
346
		mmgrab(current->mm);
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377

		mm->mn = NULL;

		/* Protected by dev_priv->mm_lock */
		hash_add(dev_priv->mm_structs,
			 &mm->node, (unsigned long)mm->mm);
	} else
		kref_get(&mm->kref);

	obj->userptr.mm = mm;
out:
	mutex_unlock(&dev_priv->mm_lock);
	return ret;
}

static void
__i915_mm_struct_free__worker(struct work_struct *work)
{
	struct i915_mm_struct *mm = container_of(work, typeof(*mm), work);
	i915_mmu_notifier_free(mm->mn, mm->mm);
	mmdrop(mm->mm);
	kfree(mm);
}

static void
__i915_mm_struct_free(struct kref *kref)
{
	struct i915_mm_struct *mm = container_of(kref, typeof(*mm), kref);

	/* Protected by dev_priv->mm_lock */
	hash_del(&mm->node);
378
	mutex_unlock(&mm->i915->mm_lock);
379 380

	INIT_WORK(&mm->work, __i915_mm_struct_free__worker);
381
	queue_work(mm->i915->mm.userptr_wq, &mm->work);
382 383 384 385 386 387 388 389 390 391 392 393 394 395
}

static void
i915_gem_userptr_release__mm_struct(struct drm_i915_gem_object *obj)
{
	if (obj->userptr.mm == NULL)
		return;

	kref_put_mutex(&obj->userptr.mm->kref,
		       __i915_mm_struct_free,
		       &to_i915(obj->base.dev)->mm_lock);
	obj->userptr.mm = NULL;
}

396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
struct get_pages_work {
	struct work_struct work;
	struct drm_i915_gem_object *obj;
	struct task_struct *task;
};

#if IS_ENABLED(CONFIG_SWIOTLB)
#define swiotlb_active() swiotlb_nr_tbl()
#else
#define swiotlb_active() 0
#endif

static int
st_set_pages(struct sg_table **st, struct page **pvec, int num_pages)
{
	struct scatterlist *sg;
	int ret, n;

	*st = kmalloc(sizeof(**st), GFP_KERNEL);
	if (*st == NULL)
		return -ENOMEM;

	if (swiotlb_active()) {
		ret = sg_alloc_table(*st, num_pages, GFP_KERNEL);
		if (ret)
			goto err;

		for_each_sg((*st)->sgl, sg, num_pages, n)
			sg_set_page(sg, pvec[n], PAGE_SIZE, 0);
	} else {
		ret = sg_alloc_table_from_pages(*st, pvec, num_pages,
						0, num_pages << PAGE_SHIFT,
						GFP_KERNEL);
		if (ret)
			goto err;
	}

	return 0;

err:
	kfree(*st);
	*st = NULL;
	return ret;
}

441
static struct sg_table *
I
Imre Deak 已提交
442 443 444
__i915_gem_userptr_set_pages(struct drm_i915_gem_object *obj,
			     struct page **pvec, int num_pages)
{
445
	struct sg_table *pages;
I
Imre Deak 已提交
446 447
	int ret;

448
	ret = st_set_pages(&pages, pvec, num_pages);
I
Imre Deak 已提交
449
	if (ret)
450
		return ERR_PTR(ret);
I
Imre Deak 已提交
451

452
	ret = i915_gem_gtt_prepare_pages(obj, pages);
I
Imre Deak 已提交
453
	if (ret) {
454 455 456
		sg_free_table(pages);
		kfree(pages);
		return ERR_PTR(ret);
I
Imre Deak 已提交
457 458
	}

459
	return pages;
I
Imre Deak 已提交
460 461
}

462
static int
463 464 465
__i915_gem_userptr_set_active(struct drm_i915_gem_object *obj,
			      bool value)
{
466 467
	int ret = 0;

468 469 470 471 472 473 474 475 476 477 478 479
	/* During mm_invalidate_range we need to cancel any userptr that
	 * overlaps the range being invalidated. Doing so requires the
	 * struct_mutex, and that risks recursion. In order to cause
	 * recursion, the user must alias the userptr address space with
	 * a GTT mmapping (possible with a MAP_FIXED) - then when we have
	 * to invalidate that mmaping, mm_invalidate_range is called with
	 * the userptr address *and* the struct_mutex held.  To prevent that
	 * we set a flag under the i915_mmu_notifier spinlock to indicate
	 * whether this object is valid.
	 */
#if defined(CONFIG_MMU_NOTIFIER)
	if (obj->userptr.mmu_object == NULL)
480
		return 0;
481 482

	spin_lock(&obj->userptr.mmu_object->mn->lock);
483 484 485
	/* In order to serialise get_pages with an outstanding
	 * cancel_userptr, we must drop the struct_mutex and try again.
	 */
486 487 488 489
	if (!value)
		del_object(obj->userptr.mmu_object);
	else if (!work_pending(&obj->userptr.mmu_object->work))
		add_object(obj->userptr.mmu_object);
490 491
	else
		ret = -EAGAIN;
492 493
	spin_unlock(&obj->userptr.mmu_object->mn->lock);
#endif
494 495

	return ret;
496 497
}

498 499 500 501 502
static void
__i915_gem_userptr_get_pages_worker(struct work_struct *_work)
{
	struct get_pages_work *work = container_of(_work, typeof(*work), work);
	struct drm_i915_gem_object *obj = work->obj;
503
	const int npages = obj->base.size >> PAGE_SHIFT;
504 505 506 507 508 509
	struct page **pvec;
	int pinned, ret;

	ret = -ENOMEM;
	pinned = 0;

M
Michal Hocko 已提交
510
	pvec = kvmalloc_array(npages, sizeof(struct page *), GFP_TEMPORARY);
511
	if (pvec != NULL) {
512
		struct mm_struct *mm = obj->userptr.mm->mm;
513 514 515 516
		unsigned int flags = 0;

		if (!obj->userptr.read_only)
			flags |= FOLL_WRITE;
517

518
		ret = -EFAULT;
V
Vegard Nossum 已提交
519
		if (mmget_not_zero(mm)) {
520 521 522 523 524 525
			down_read(&mm->mmap_sem);
			while (pinned < npages) {
				ret = get_user_pages_remote
					(work->task, mm,
					 obj->userptr.ptr + pinned * PAGE_SIZE,
					 npages - pinned,
526
					 flags,
527
					 pvec + pinned, NULL, NULL);
528 529 530 531 532 533 534
				if (ret < 0)
					break;

				pinned += ret;
			}
			up_read(&mm->mmap_sem);
			mmput(mm);
535 536 537
		}
	}

538
	mutex_lock(&obj->mm.lock);
539
	if (obj->userptr.work == &work->work) {
540 541
		struct sg_table *pages = ERR_PTR(ret);

542
		if (pinned == npages) {
543 544 545
			pages = __i915_gem_userptr_set_pages(obj, pvec, npages);
			if (!IS_ERR(pages)) {
				__i915_gem_object_set_pages(obj, pages);
546
				pinned = 0;
547
				pages = NULL;
548
			}
549
		}
550 551

		obj->userptr.work = ERR_CAST(pages);
552 553
		if (IS_ERR(pages))
			__i915_gem_userptr_set_active(obj, false);
554
	}
555
	mutex_unlock(&obj->mm.lock);
556 557

	release_pages(pvec, pinned, 0);
M
Michal Hocko 已提交
558
	kvfree(pvec);
559

C
Chris Wilson 已提交
560
	i915_gem_object_put(obj);
561 562 563 564
	put_task_struct(work->task);
	kfree(work);
}

565
static struct sg_table *
566
__i915_gem_userptr_get_pages_schedule(struct drm_i915_gem_object *obj)
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
{
	struct get_pages_work *work;

	/* Spawn a worker so that we can acquire the
	 * user pages without holding our mutex. Access
	 * to the user pages requires mmap_sem, and we have
	 * a strict lock ordering of mmap_sem, struct_mutex -
	 * we already hold struct_mutex here and so cannot
	 * call gup without encountering a lock inversion.
	 *
	 * Userspace will keep on repeating the operation
	 * (thanks to EAGAIN) until either we hit the fast
	 * path or the worker completes. If the worker is
	 * cancelled or superseded, the task is still run
	 * but the results ignored. (This leads to
	 * complications that we may have a stray object
	 * refcount that we need to be wary of when
	 * checking for existing objects during creation.)
	 * If the worker encounters an error, it reports
	 * that error back to this function through
	 * obj->userptr.work = ERR_PTR.
	 */
	work = kmalloc(sizeof(*work), GFP_KERNEL);
	if (work == NULL)
591
		return ERR_PTR(-ENOMEM);
592 593 594

	obj->userptr.work = &work->work;

595
	work->obj = i915_gem_object_get(obj);
596 597 598 599 600

	work->task = current;
	get_task_struct(work->task);

	INIT_WORK(&work->work, __i915_gem_userptr_get_pages_worker);
601
	queue_work(to_i915(obj->base.dev)->mm.userptr_wq, &work->work);
602

603
	return ERR_PTR(-EAGAIN);
604 605
}

606
static struct sg_table *
607 608 609
i915_gem_userptr_get_pages(struct drm_i915_gem_object *obj)
{
	const int num_pages = obj->base.size >> PAGE_SHIFT;
610
	struct mm_struct *mm = obj->userptr.mm->mm;
611
	struct page **pvec;
612
	struct sg_table *pages;
613
	bool active;
614
	int pinned;
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631

	/* If userspace should engineer that these pages are replaced in
	 * the vma between us binding this page into the GTT and completion
	 * of rendering... Their loss. If they change the mapping of their
	 * pages they need to create a new bo to point to the new vma.
	 *
	 * However, that still leaves open the possibility of the vma
	 * being copied upon fork. Which falls under the same userspace
	 * synchronisation issue as a regular bo, except that this time
	 * the process may not be expecting that a particular piece of
	 * memory is tied to the GPU.
	 *
	 * Fortunately, we can hook into the mmu_notifier in order to
	 * discard the page references prior to anything nasty happening
	 * to the vma (discard or cloning) which should prevent the more
	 * egregious cases from causing harm.
	 */
632 633

	if (obj->userptr.work) {
634
		/* active flag should still be held for the pending work */
635
		if (IS_ERR(obj->userptr.work))
636
			return ERR_CAST(obj->userptr.work);
637
		else
638
			return ERR_PTR(-EAGAIN);
639
	}
640

641 642 643
	pvec = NULL;
	pinned = 0;

644
	if (mm == current->mm) {
M
Michal Hocko 已提交
645
		pvec = kvmalloc_array(num_pages, sizeof(struct page *),
646 647 648 649 650 651 652 653
				      GFP_TEMPORARY |
				      __GFP_NORETRY |
				      __GFP_NOWARN);
		if (pvec) /* defer to worker if malloc fails */
			pinned = __get_user_pages_fast(obj->userptr.ptr,
						       num_pages,
						       !obj->userptr.read_only,
						       pvec);
654
	}
655 656

	active = false;
657 658 659 660 661 662 663
	if (pinned < 0) {
		pages = ERR_PTR(pinned);
		pinned = 0;
	} else if (pinned < num_pages) {
		pages = __i915_gem_userptr_get_pages_schedule(obj);
		active = pages == ERR_PTR(-EAGAIN);
	} else {
664
		pages = __i915_gem_userptr_set_pages(obj, pvec, num_pages);
665
		active = !IS_ERR(pages);
666
	}
667 668 669 670 671
	if (active)
		__i915_gem_userptr_set_active(obj, true);

	if (IS_ERR(pages))
		release_pages(pvec, pinned, 0);
M
Michal Hocko 已提交
672
	kvfree(pvec);
673

674
	return pages;
675 676 677
}

static void
678 679
i915_gem_userptr_put_pages(struct drm_i915_gem_object *obj,
			   struct sg_table *pages)
680
{
681 682
	struct sgt_iter sgt_iter;
	struct page *page;
683 684

	BUG_ON(obj->userptr.work != NULL);
685
	__i915_gem_userptr_set_active(obj, false);
686

C
Chris Wilson 已提交
687 688
	if (obj->mm.madv != I915_MADV_WILLNEED)
		obj->mm.dirty = false;
689

690
	i915_gem_gtt_finish_pages(obj, pages);
I
Imre Deak 已提交
691

692
	for_each_sgt_page(page, sgt_iter, pages) {
C
Chris Wilson 已提交
693
		if (obj->mm.dirty)
694 695 696
			set_page_dirty(page);

		mark_page_accessed(page);
697
		put_page(page);
698
	}
C
Chris Wilson 已提交
699
	obj->mm.dirty = false;
700

701 702
	sg_free_table(pages);
	kfree(pages);
703 704 705 706 707 708
}

static void
i915_gem_userptr_release(struct drm_i915_gem_object *obj)
{
	i915_gem_userptr_release__mmu_notifier(obj);
709
	i915_gem_userptr_release__mm_struct(obj);
710 711 712 713 714
}

static int
i915_gem_userptr_dmabuf_export(struct drm_i915_gem_object *obj)
{
715
	if (obj->userptr.mmu_object)
716 717 718 719 720 721
		return 0;

	return i915_gem_userptr_init__mmu_notifier(obj, 0);
}

static const struct drm_i915_gem_object_ops i915_gem_userptr_ops = {
722 723
	.flags = I915_GEM_OBJECT_HAS_STRUCT_PAGE |
		 I915_GEM_OBJECT_IS_SHRINKABLE,
724 725
	.get_pages = i915_gem_userptr_get_pages,
	.put_pages = i915_gem_userptr_put_pages,
726
	.dmabuf_export = i915_gem_userptr_dmabuf_export,
727 728 729 730 731 732 733 734 735 736
	.release = i915_gem_userptr_release,
};

/**
 * Creates a new mm object that wraps some normal memory from the process
 * context - user memory.
 *
 * We impose several restrictions upon the memory being mapped
 * into the GPU.
 * 1. It must be page aligned (both start/end addresses, i.e ptr and size).
737
 * 2. It must be normal system memory, not a pointer into another map of IO
738
 *    space (e.g. it must not be a GTT mmapping of another object).
739
 * 3. We only allow a bo as large as we could in theory map into the GTT,
740
 *    that is we limit the size to the total size of the GTT.
741
 * 4. The bo is marked as being snoopable. The backing pages are left
742 743 744 745 746 747 748 749 750 751 752 753 754 755
 *    accessible directly by the CPU, but reads and writes by the GPU may
 *    incur the cost of a snoop (unless you have an LLC architecture).
 *
 * Synchronisation between multiple users and the GPU is left to userspace
 * through the normal set-domain-ioctl. The kernel will enforce that the
 * GPU relinquishes the VMA before it is returned back to the system
 * i.e. upon free(), munmap() or process termination. However, the userspace
 * malloc() library may not immediately relinquish the VMA after free() and
 * instead reuse it whilst the GPU is still reading and writing to the VMA.
 * Caveat emptor.
 *
 * Also note, that the object created here is not currently a "first class"
 * object, in that several ioctls are banned. These are the CPU access
 * ioctls: mmap(), pwrite and pread. In practice, you are expected to use
756 757 758 759
 * direct access via your pointer rather than use those ioctls. Another
 * restriction is that we do not allow userptr surfaces to be pinned to the
 * hardware and so we reject any attempt to create a framebuffer out of a
 * userptr.
760 761 762 763 764 765 766 767
 *
 * If you think this is a good interface to use to pass GPU memory between
 * drivers, please use dma-buf instead. In fact, wherever possible use
 * dma-buf instead.
 */
int
i915_gem_userptr_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
{
768
	struct drm_i915_private *dev_priv = to_i915(dev);
769 770 771 772 773
	struct drm_i915_gem_userptr *args = data;
	struct drm_i915_gem_object *obj;
	int ret;
	u32 handle;

774
	if (!HAS_LLC(dev_priv) && !HAS_SNOOP(dev_priv)) {
775 776 777 778 779 780
		/* We cannot support coherent userptr objects on hw without
		 * LLC and broken snooping.
		 */
		return -ENODEV;
	}

781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
	if (args->flags & ~(I915_USERPTR_READ_ONLY |
			    I915_USERPTR_UNSYNCHRONIZED))
		return -EINVAL;

	if (offset_in_page(args->user_ptr | args->user_size))
		return -EINVAL;

	if (!access_ok(args->flags & I915_USERPTR_READ_ONLY ? VERIFY_READ : VERIFY_WRITE,
		       (char __user *)(unsigned long)args->user_ptr, args->user_size))
		return -EFAULT;

	if (args->flags & I915_USERPTR_READ_ONLY) {
		/* On almost all of the current hw, we cannot tell the GPU that a
		 * page is readonly, so this is just a placeholder in the uAPI.
		 */
		return -ENODEV;
	}

799
	obj = i915_gem_object_alloc(dev_priv);
800 801 802 803 804 805
	if (obj == NULL)
		return -ENOMEM;

	drm_gem_private_object_init(dev, &obj->base, args->user_size);
	i915_gem_object_init(obj, &i915_gem_userptr_ops);
	obj->base.read_domains = I915_GEM_DOMAIN_CPU;
806
	obj->base.write_domain = I915_GEM_DOMAIN_CPU;
807
	i915_gem_object_set_cache_coherency(obj, I915_CACHE_LLC);
808 809 810 811 812 813 814 815

	obj->userptr.ptr = args->user_ptr;
	obj->userptr.read_only = !!(args->flags & I915_USERPTR_READ_ONLY);

	/* And keep a pointer to the current->mm for resolving the user pages
	 * at binding. This means that we need to hook into the mmu_notifier
	 * in order to detect if the mmu is destroyed.
	 */
816 817
	ret = i915_gem_userptr_init__mm_struct(obj);
	if (ret == 0)
818 819 820 821 822
		ret = i915_gem_userptr_init__mmu_notifier(obj, args->flags);
	if (ret == 0)
		ret = drm_gem_handle_create(file, &obj->base, &handle);

	/* drop reference from allocate - handle holds it now */
C
Chris Wilson 已提交
823
	i915_gem_object_put(obj);
824 825 826 827 828 829 830
	if (ret)
		return ret;

	args->handle = handle;
	return 0;
}

831
int i915_gem_init_userptr(struct drm_i915_private *dev_priv)
832
{
833 834
	mutex_init(&dev_priv->mm_lock);
	hash_init(dev_priv->mm_structs);
835 836 837 838 839 840 841 842 843 844 845 846

	dev_priv->mm.userptr_wq =
		alloc_workqueue("i915-userptr-acquire", WQ_HIGHPRI, 0);
	if (!dev_priv->mm.userptr_wq)
		return -ENOMEM;

	return 0;
}

void i915_gem_cleanup_userptr(struct drm_i915_private *dev_priv)
{
	destroy_workqueue(dev_priv->mm.userptr_wq);
847
}