xref: /openbsd/sys/dev/pci/drm/i915/i915_vma.c (revision 4bdff4be)
1 /*
2  * Copyright © 2016 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  */
24 
25 #include <linux/sched/mm.h>
26 #include <linux/dma-fence-array.h>
27 #include <drm/drm_gem.h>
28 
29 #include "display/intel_display.h"
30 #include "display/intel_frontbuffer.h"
31 #include "gem/i915_gem_lmem.h"
32 #include "gem/i915_gem_tiling.h"
33 #include "gt/intel_engine.h"
34 #include "gt/intel_engine_heartbeat.h"
35 #include "gt/intel_gt.h"
36 #include "gt/intel_gt_requests.h"
37 #include "gt/intel_tlb.h"
38 
39 #include "i915_drv.h"
40 #include "i915_gem_evict.h"
41 #include "i915_sw_fence_work.h"
42 #include "i915_trace.h"
43 #include "i915_vma.h"
44 #include "i915_vma_resource.h"
45 
46 #include <dev/pci/agpvar.h>
47 
48 static inline void assert_vma_held_evict(const struct i915_vma *vma)
49 {
50 	/*
51 	 * We may be forced to unbind when the vm is dead, to clean it up.
52 	 * This is the only exception to the requirement of the object lock
53 	 * being held.
54 	 */
55 	if (kref_read(&vma->vm->ref))
56 		assert_object_held_shared(vma->obj);
57 }
58 
59 static struct pool slab_vmas;
60 
61 static struct i915_vma *i915_vma_alloc(void)
62 {
63 #ifdef __linux__
64 	return kmem_cache_zalloc(slab_vmas, GFP_KERNEL);
65 #else
66 	return pool_get(&slab_vmas, PR_WAITOK | PR_ZERO);
67 #endif
68 }
69 
70 static void i915_vma_free(struct i915_vma *vma)
71 {
72 #ifdef __linux__
73 	return kmem_cache_free(slab_vmas, vma);
74 #else
75 	pool_put(&slab_vmas, vma);
76 #endif
77 }
78 
79 #if IS_ENABLED(CONFIG_DRM_I915_ERRLOG_GEM) && IS_ENABLED(CONFIG_DRM_DEBUG_MM)
80 
81 #include <linux/stackdepot.h>
82 
83 static void vma_print_allocator(struct i915_vma *vma, const char *reason)
84 {
85 	char buf[512];
86 
87 	if (!vma->node.stack) {
88 		drm_dbg(vma->obj->base.dev,
89 			"vma.node [%08llx + %08llx] %s: unknown owner\n",
90 			vma->node.start, vma->node.size, reason);
91 		return;
92 	}
93 
94 	stack_depot_snprint(vma->node.stack, buf, sizeof(buf), 0);
95 	drm_dbg(vma->obj->base.dev,
96 		"vma.node [%08llx + %08llx] %s: inserted at %s\n",
97 		vma->node.start, vma->node.size, reason, buf);
98 }
99 
100 #else
101 
102 static void vma_print_allocator(struct i915_vma *vma, const char *reason)
103 {
104 }
105 
106 #endif
107 
108 static inline struct i915_vma *active_to_vma(struct i915_active *ref)
109 {
110 	return container_of(ref, typeof(struct i915_vma), active);
111 }
112 
113 static int __i915_vma_active(struct i915_active *ref)
114 {
115 	return i915_vma_tryget(active_to_vma(ref)) ? 0 : -ENOENT;
116 }
117 
118 static void __i915_vma_retire(struct i915_active *ref)
119 {
120 	i915_vma_put(active_to_vma(ref));
121 }
122 
123 static struct i915_vma *
124 vma_create(struct drm_i915_gem_object *obj,
125 	   struct i915_address_space *vm,
126 	   const struct i915_gtt_view *view)
127 {
128 	struct i915_vma *pos = ERR_PTR(-E2BIG);
129 	struct i915_vma *vma;
130 	struct rb_node *rb, **p;
131 	int err;
132 
133 	/* The aliasing_ppgtt should never be used directly! */
134 	GEM_BUG_ON(vm == &vm->gt->ggtt->alias->vm);
135 
136 	vma = i915_vma_alloc();
137 	if (vma == NULL)
138 		return ERR_PTR(-ENOMEM);
139 
140 	vma->ops = &vm->vma_ops;
141 	vma->obj = obj;
142 	vma->size = obj->base.size;
143 	vma->display_alignment = I915_GTT_MIN_ALIGNMENT;
144 
145 	i915_active_init(&vma->active, __i915_vma_active, __i915_vma_retire, 0);
146 
147 #ifdef notyet
148 	/* Declare ourselves safe for use inside shrinkers */
149 	if (IS_ENABLED(CONFIG_LOCKDEP)) {
150 		fs_reclaim_acquire(GFP_KERNEL);
151 		might_lock(&vma->active.mutex);
152 		fs_reclaim_release(GFP_KERNEL);
153 	}
154 #endif
155 
156 	INIT_LIST_HEAD(&vma->closed_link);
157 	INIT_LIST_HEAD(&vma->obj_link);
158 	RB_CLEAR_NODE(&vma->obj_node);
159 
160 	if (view && view->type != I915_GTT_VIEW_NORMAL) {
161 		vma->gtt_view = *view;
162 		if (view->type == I915_GTT_VIEW_PARTIAL) {
163 			GEM_BUG_ON(range_overflows_t(u64,
164 						     view->partial.offset,
165 						     view->partial.size,
166 						     obj->base.size >> PAGE_SHIFT));
167 			vma->size = view->partial.size;
168 			vma->size <<= PAGE_SHIFT;
169 			GEM_BUG_ON(vma->size > obj->base.size);
170 		} else if (view->type == I915_GTT_VIEW_ROTATED) {
171 			vma->size = intel_rotation_info_size(&view->rotated);
172 			vma->size <<= PAGE_SHIFT;
173 		} else if (view->type == I915_GTT_VIEW_REMAPPED) {
174 			vma->size = intel_remapped_info_size(&view->remapped);
175 			vma->size <<= PAGE_SHIFT;
176 		}
177 	}
178 
179 	if (unlikely(vma->size > vm->total))
180 		goto err_vma;
181 
182 	GEM_BUG_ON(!IS_ALIGNED(vma->size, I915_GTT_PAGE_SIZE));
183 
184 	err = mutex_lock_interruptible(&vm->mutex);
185 	if (err) {
186 		pos = ERR_PTR(err);
187 		goto err_vma;
188 	}
189 
190 	vma->vm = vm;
191 	list_add_tail(&vma->vm_link, &vm->unbound_list);
192 
193 	spin_lock(&obj->vma.lock);
194 	if (i915_is_ggtt(vm)) {
195 		if (unlikely(overflows_type(vma->size, u32)))
196 			goto err_unlock;
197 
198 		vma->fence_size = i915_gem_fence_size(vm->i915, vma->size,
199 						      i915_gem_object_get_tiling(obj),
200 						      i915_gem_object_get_stride(obj));
201 		if (unlikely(vma->fence_size < vma->size || /* overflow */
202 			     vma->fence_size > vm->total))
203 			goto err_unlock;
204 
205 		GEM_BUG_ON(!IS_ALIGNED(vma->fence_size, I915_GTT_MIN_ALIGNMENT));
206 
207 		vma->fence_alignment = i915_gem_fence_alignment(vm->i915, vma->size,
208 								i915_gem_object_get_tiling(obj),
209 								i915_gem_object_get_stride(obj));
210 		GEM_BUG_ON(!is_power_of_2(vma->fence_alignment));
211 
212 		__set_bit(I915_VMA_GGTT_BIT, __i915_vma_flags(vma));
213 	}
214 
215 	rb = NULL;
216 	p = &obj->vma.tree.rb_node;
217 	while (*p) {
218 		long cmp;
219 
220 		rb = *p;
221 		pos = rb_entry(rb, struct i915_vma, obj_node);
222 
223 		/*
224 		 * If the view already exists in the tree, another thread
225 		 * already created a matching vma, so return the older instance
226 		 * and dispose of ours.
227 		 */
228 		cmp = i915_vma_compare(pos, vm, view);
229 		if (cmp < 0)
230 			p = &rb->rb_right;
231 		else if (cmp > 0)
232 			p = &rb->rb_left;
233 		else
234 			goto err_unlock;
235 	}
236 	rb_link_node(&vma->obj_node, rb, p);
237 	rb_insert_color(&vma->obj_node, &obj->vma.tree);
238 
239 	if (i915_vma_is_ggtt(vma))
240 		/*
241 		 * We put the GGTT vma at the start of the vma-list, followed
242 		 * by the ppGGTT vma. This allows us to break early when
243 		 * iterating over only the GGTT vma for an object, see
244 		 * for_each_ggtt_vma()
245 		 */
246 		list_add(&vma->obj_link, &obj->vma.list);
247 	else
248 		list_add_tail(&vma->obj_link, &obj->vma.list);
249 
250 	spin_unlock(&obj->vma.lock);
251 	mutex_unlock(&vm->mutex);
252 
253 	return vma;
254 
255 err_unlock:
256 	spin_unlock(&obj->vma.lock);
257 	list_del_init(&vma->vm_link);
258 	mutex_unlock(&vm->mutex);
259 err_vma:
260 	i915_vma_free(vma);
261 	return pos;
262 }
263 
264 static struct i915_vma *
265 i915_vma_lookup(struct drm_i915_gem_object *obj,
266 	   struct i915_address_space *vm,
267 	   const struct i915_gtt_view *view)
268 {
269 	struct rb_node *rb;
270 
271 	rb = obj->vma.tree.rb_node;
272 	while (rb) {
273 		struct i915_vma *vma = rb_entry(rb, struct i915_vma, obj_node);
274 		long cmp;
275 
276 		cmp = i915_vma_compare(vma, vm, view);
277 		if (cmp == 0)
278 			return vma;
279 
280 		if (cmp < 0)
281 			rb = rb->rb_right;
282 		else
283 			rb = rb->rb_left;
284 	}
285 
286 	return NULL;
287 }
288 
289 /**
290  * i915_vma_instance - return the singleton instance of the VMA
291  * @obj: parent &struct drm_i915_gem_object to be mapped
292  * @vm: address space in which the mapping is located
293  * @view: additional mapping requirements
294  *
295  * i915_vma_instance() looks up an existing VMA of the @obj in the @vm with
296  * the same @view characteristics. If a match is not found, one is created.
297  * Once created, the VMA is kept until either the object is freed, or the
298  * address space is closed.
299  *
300  * Returns the vma, or an error pointer.
301  */
302 struct i915_vma *
303 i915_vma_instance(struct drm_i915_gem_object *obj,
304 		  struct i915_address_space *vm,
305 		  const struct i915_gtt_view *view)
306 {
307 	struct i915_vma *vma;
308 
309 	GEM_BUG_ON(view && !i915_is_ggtt_or_dpt(vm));
310 	GEM_BUG_ON(!kref_read(&vm->ref));
311 
312 	spin_lock(&obj->vma.lock);
313 	vma = i915_vma_lookup(obj, vm, view);
314 	spin_unlock(&obj->vma.lock);
315 
316 	/* vma_create() will resolve the race if another creates the vma */
317 	if (unlikely(!vma))
318 		vma = vma_create(obj, vm, view);
319 
320 	GEM_BUG_ON(!IS_ERR(vma) && i915_vma_compare(vma, vm, view));
321 	return vma;
322 }
323 
324 struct i915_vma_work {
325 	struct dma_fence_work base;
326 	struct i915_address_space *vm;
327 	struct i915_vm_pt_stash stash;
328 	struct i915_vma_resource *vma_res;
329 	struct drm_i915_gem_object *obj;
330 	struct i915_sw_dma_fence_cb cb;
331 	unsigned int pat_index;
332 	unsigned int flags;
333 };
334 
335 static void __vma_bind(struct dma_fence_work *work)
336 {
337 	struct i915_vma_work *vw = container_of(work, typeof(*vw), base);
338 	struct i915_vma_resource *vma_res = vw->vma_res;
339 
340 	/*
341 	 * We are about the bind the object, which must mean we have already
342 	 * signaled the work to potentially clear/move the pages underneath. If
343 	 * something went wrong at that stage then the object should have
344 	 * unknown_state set, in which case we need to skip the bind.
345 	 */
346 	if (i915_gem_object_has_unknown_state(vw->obj))
347 		return;
348 
349 	vma_res->ops->bind_vma(vma_res->vm, &vw->stash,
350 			       vma_res, vw->pat_index, vw->flags);
351 }
352 
353 static void __vma_release(struct dma_fence_work *work)
354 {
355 	struct i915_vma_work *vw = container_of(work, typeof(*vw), base);
356 
357 	if (vw->obj)
358 		i915_gem_object_put(vw->obj);
359 
360 	i915_vm_free_pt_stash(vw->vm, &vw->stash);
361 	if (vw->vma_res)
362 		i915_vma_resource_put(vw->vma_res);
363 }
364 
365 static const struct dma_fence_work_ops bind_ops = {
366 	.name = "bind",
367 	.work = __vma_bind,
368 	.release = __vma_release,
369 };
370 
371 struct i915_vma_work *i915_vma_work(void)
372 {
373 	struct i915_vma_work *vw;
374 
375 	vw = kzalloc(sizeof(*vw), GFP_KERNEL);
376 	if (!vw)
377 		return NULL;
378 
379 	dma_fence_work_init(&vw->base, &bind_ops);
380 	vw->base.dma.error = -EAGAIN; /* disable the worker by default */
381 
382 	return vw;
383 }
384 
385 int i915_vma_wait_for_bind(struct i915_vma *vma)
386 {
387 	int err = 0;
388 
389 	if (rcu_access_pointer(vma->active.excl.fence)) {
390 		struct dma_fence *fence;
391 
392 		rcu_read_lock();
393 		fence = dma_fence_get_rcu_safe(&vma->active.excl.fence);
394 		rcu_read_unlock();
395 		if (fence) {
396 			err = dma_fence_wait(fence, true);
397 			dma_fence_put(fence);
398 		}
399 	}
400 
401 	return err;
402 }
403 
404 #if IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM)
405 static int i915_vma_verify_bind_complete(struct i915_vma *vma)
406 {
407 	struct dma_fence *fence = i915_active_fence_get(&vma->active.excl);
408 	int err;
409 
410 	if (!fence)
411 		return 0;
412 
413 	if (dma_fence_is_signaled(fence))
414 		err = fence->error;
415 	else
416 		err = -EBUSY;
417 
418 	dma_fence_put(fence);
419 
420 	return err;
421 }
422 #else
423 #define i915_vma_verify_bind_complete(_vma) 0
424 #endif
425 
426 I915_SELFTEST_EXPORT void
427 i915_vma_resource_init_from_vma(struct i915_vma_resource *vma_res,
428 				struct i915_vma *vma)
429 {
430 	struct drm_i915_gem_object *obj = vma->obj;
431 
432 	i915_vma_resource_init(vma_res, vma->vm, vma->pages, &vma->page_sizes,
433 			       obj->mm.rsgt, i915_gem_object_is_readonly(obj),
434 			       i915_gem_object_is_lmem(obj), obj->mm.region,
435 			       vma->ops, vma->private, __i915_vma_offset(vma),
436 			       __i915_vma_size(vma), vma->size, vma->guard);
437 }
438 
439 /**
440  * i915_vma_bind - Sets up PTEs for an VMA in it's corresponding address space.
441  * @vma: VMA to map
442  * @pat_index: PAT index to set in PTE
443  * @flags: flags like global or local mapping
444  * @work: preallocated worker for allocating and binding the PTE
445  * @vma_res: pointer to a preallocated vma resource. The resource is either
446  * consumed or freed.
447  *
448  * DMA addresses are taken from the scatter-gather table of this object (or of
449  * this VMA in case of non-default GGTT views) and PTE entries set up.
450  * Note that DMA addresses are also the only part of the SG table we care about.
451  */
452 int i915_vma_bind(struct i915_vma *vma,
453 		  unsigned int pat_index,
454 		  u32 flags,
455 		  struct i915_vma_work *work,
456 		  struct i915_vma_resource *vma_res)
457 {
458 	u32 bind_flags;
459 	u32 vma_flags;
460 	int ret;
461 
462 	lockdep_assert_held(&vma->vm->mutex);
463 	GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
464 	GEM_BUG_ON(vma->size > i915_vma_size(vma));
465 
466 	if (GEM_DEBUG_WARN_ON(range_overflows(vma->node.start,
467 					      vma->node.size,
468 					      vma->vm->total))) {
469 		i915_vma_resource_free(vma_res);
470 		return -ENODEV;
471 	}
472 
473 	if (GEM_DEBUG_WARN_ON(!flags)) {
474 		i915_vma_resource_free(vma_res);
475 		return -EINVAL;
476 	}
477 
478 	bind_flags = flags;
479 	bind_flags &= I915_VMA_GLOBAL_BIND | I915_VMA_LOCAL_BIND;
480 
481 	vma_flags = atomic_read(&vma->flags);
482 	vma_flags &= I915_VMA_GLOBAL_BIND | I915_VMA_LOCAL_BIND;
483 
484 	bind_flags &= ~vma_flags;
485 	if (bind_flags == 0) {
486 		i915_vma_resource_free(vma_res);
487 		return 0;
488 	}
489 
490 	GEM_BUG_ON(!atomic_read(&vma->pages_count));
491 
492 	/* Wait for or await async unbinds touching our range */
493 	if (work && bind_flags & vma->vm->bind_async_flags)
494 		ret = i915_vma_resource_bind_dep_await(vma->vm,
495 						       &work->base.chain,
496 						       vma->node.start,
497 						       vma->node.size,
498 						       true,
499 						       GFP_NOWAIT |
500 						       __GFP_RETRY_MAYFAIL |
501 						       __GFP_NOWARN);
502 	else
503 		ret = i915_vma_resource_bind_dep_sync(vma->vm, vma->node.start,
504 						      vma->node.size, true);
505 	if (ret) {
506 		i915_vma_resource_free(vma_res);
507 		return ret;
508 	}
509 
510 	if (vma->resource || !vma_res) {
511 		/* Rebinding with an additional I915_VMA_*_BIND */
512 		GEM_WARN_ON(!vma_flags);
513 		i915_vma_resource_free(vma_res);
514 	} else {
515 		i915_vma_resource_init_from_vma(vma_res, vma);
516 		vma->resource = vma_res;
517 	}
518 	trace_i915_vma_bind(vma, bind_flags);
519 	if (work && bind_flags & vma->vm->bind_async_flags) {
520 		struct dma_fence *prev;
521 
522 		work->vma_res = i915_vma_resource_get(vma->resource);
523 		work->pat_index = pat_index;
524 		work->flags = bind_flags;
525 
526 		/*
527 		 * Note we only want to chain up to the migration fence on
528 		 * the pages (not the object itself). As we don't track that,
529 		 * yet, we have to use the exclusive fence instead.
530 		 *
531 		 * Also note that we do not want to track the async vma as
532 		 * part of the obj->resv->excl_fence as it only affects
533 		 * execution and not content or object's backing store lifetime.
534 		 */
535 		prev = i915_active_set_exclusive(&vma->active, &work->base.dma);
536 		if (prev) {
537 			__i915_sw_fence_await_dma_fence(&work->base.chain,
538 							prev,
539 							&work->cb);
540 			dma_fence_put(prev);
541 		}
542 
543 		work->base.dma.error = 0; /* enable the queue_work() */
544 		work->obj = i915_gem_object_get(vma->obj);
545 	} else {
546 		ret = i915_gem_object_wait_moving_fence(vma->obj, true);
547 		if (ret) {
548 			i915_vma_resource_free(vma->resource);
549 			vma->resource = NULL;
550 
551 			return ret;
552 		}
553 		vma->ops->bind_vma(vma->vm, NULL, vma->resource, pat_index,
554 				   bind_flags);
555 	}
556 
557 	atomic_or(bind_flags, &vma->flags);
558 	return 0;
559 }
560 
561 void __iomem *i915_vma_pin_iomap(struct i915_vma *vma)
562 {
563 	void __iomem *ptr;
564 	int err;
565 
566 	if (WARN_ON_ONCE(vma->obj->flags & I915_BO_ALLOC_GPU_ONLY))
567 		return IOMEM_ERR_PTR(-EINVAL);
568 
569 	GEM_BUG_ON(!i915_vma_is_ggtt(vma));
570 	GEM_BUG_ON(!i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND));
571 	GEM_BUG_ON(i915_vma_verify_bind_complete(vma));
572 
573 	ptr = READ_ONCE(vma->iomap);
574 	if (ptr == NULL) {
575 		/*
576 		 * TODO: consider just using i915_gem_object_pin_map() for lmem
577 		 * instead, which already supports mapping non-contiguous chunks
578 		 * of pages, that way we can also drop the
579 		 * I915_BO_ALLOC_CONTIGUOUS when allocating the object.
580 		 */
581 		if (i915_gem_object_is_lmem(vma->obj)) {
582 			ptr = i915_gem_object_lmem_io_map(vma->obj, 0,
583 							  vma->obj->base.size);
584 		} else if (i915_vma_is_map_and_fenceable(vma)) {
585 #ifdef __linux__
586 			ptr = io_mapping_map_wc(&i915_vm_to_ggtt(vma->vm)->iomap,
587 						i915_vma_offset(vma),
588 						i915_vma_size(vma));
589 #else
590 		{
591 			struct drm_i915_private *dev_priv = vma->vm->i915;
592 			err = agp_map_subregion(dev_priv->agph, i915_vma_offset(vma),
593 			    i915_vma_size(vma), &vma->bsh);
594 			if (err) {
595 				err = -err;
596 				goto err;
597 			}
598 			ptr = bus_space_vaddr(dev_priv->bst, vma->bsh);
599 		}
600 #endif
601 		} else {
602 			ptr = (void __iomem *)
603 				i915_gem_object_pin_map(vma->obj, I915_MAP_WC);
604 			if (IS_ERR(ptr)) {
605 				err = PTR_ERR(ptr);
606 				goto err;
607 			}
608 			ptr = page_pack_bits(ptr, 1);
609 		}
610 
611 		if (ptr == NULL) {
612 			err = -ENOMEM;
613 			goto err;
614 		}
615 
616 		if (unlikely(cmpxchg(&vma->iomap, NULL, ptr))) {
617 			if (page_unmask_bits(ptr))
618 				__i915_gem_object_release_map(vma->obj);
619 #ifdef __linux__
620 			else
621 				io_mapping_unmap(ptr);
622 #endif
623 			ptr = vma->iomap;
624 		}
625 	}
626 
627 	__i915_vma_pin(vma);
628 
629 	err = i915_vma_pin_fence(vma);
630 	if (err)
631 		goto err_unpin;
632 
633 	i915_vma_set_ggtt_write(vma);
634 
635 	/* NB Access through the GTT requires the device to be awake. */
636 	return page_mask_bits(ptr);
637 
638 err_unpin:
639 	__i915_vma_unpin(vma);
640 err:
641 	return IOMEM_ERR_PTR(err);
642 }
643 
644 void i915_vma_flush_writes(struct i915_vma *vma)
645 {
646 	if (i915_vma_unset_ggtt_write(vma))
647 		intel_gt_flush_ggtt_writes(vma->vm->gt);
648 }
649 
650 void i915_vma_unpin_iomap(struct i915_vma *vma)
651 {
652 	GEM_BUG_ON(vma->iomap == NULL);
653 
654 	/* XXX We keep the mapping until __i915_vma_unbind()/evict() */
655 
656 	i915_vma_flush_writes(vma);
657 
658 	i915_vma_unpin_fence(vma);
659 	i915_vma_unpin(vma);
660 }
661 
662 void i915_vma_unpin_and_release(struct i915_vma **p_vma, unsigned int flags)
663 {
664 	struct i915_vma *vma;
665 	struct drm_i915_gem_object *obj;
666 
667 	vma = fetch_and_zero(p_vma);
668 	if (!vma)
669 		return;
670 
671 	obj = vma->obj;
672 	GEM_BUG_ON(!obj);
673 
674 	i915_vma_unpin(vma);
675 
676 	if (flags & I915_VMA_RELEASE_MAP)
677 		i915_gem_object_unpin_map(obj);
678 
679 	i915_gem_object_put(obj);
680 }
681 
682 bool i915_vma_misplaced(const struct i915_vma *vma,
683 			u64 size, u64 alignment, u64 flags)
684 {
685 	if (!drm_mm_node_allocated(&vma->node))
686 		return false;
687 
688 	if (test_bit(I915_VMA_ERROR_BIT, __i915_vma_flags(vma)))
689 		return true;
690 
691 	if (i915_vma_size(vma) < size)
692 		return true;
693 
694 	GEM_BUG_ON(alignment && !is_power_of_2(alignment));
695 	if (alignment && !IS_ALIGNED(i915_vma_offset(vma), alignment))
696 		return true;
697 
698 	if (flags & PIN_MAPPABLE && !i915_vma_is_map_and_fenceable(vma))
699 		return true;
700 
701 	if (flags & PIN_OFFSET_BIAS &&
702 	    i915_vma_offset(vma) < (flags & PIN_OFFSET_MASK))
703 		return true;
704 
705 	if (flags & PIN_OFFSET_FIXED &&
706 	    i915_vma_offset(vma) != (flags & PIN_OFFSET_MASK))
707 		return true;
708 
709 	if (flags & PIN_OFFSET_GUARD &&
710 	    vma->guard < (flags & PIN_OFFSET_MASK))
711 		return true;
712 
713 	return false;
714 }
715 
716 void __i915_vma_set_map_and_fenceable(struct i915_vma *vma)
717 {
718 	bool mappable, fenceable;
719 
720 	GEM_BUG_ON(!i915_vma_is_ggtt(vma));
721 	GEM_BUG_ON(!vma->fence_size);
722 
723 	fenceable = (i915_vma_size(vma) >= vma->fence_size &&
724 		     IS_ALIGNED(i915_vma_offset(vma), vma->fence_alignment));
725 
726 	mappable = i915_ggtt_offset(vma) + vma->fence_size <=
727 		   i915_vm_to_ggtt(vma->vm)->mappable_end;
728 
729 	if (mappable && fenceable)
730 		set_bit(I915_VMA_CAN_FENCE_BIT, __i915_vma_flags(vma));
731 	else
732 		clear_bit(I915_VMA_CAN_FENCE_BIT, __i915_vma_flags(vma));
733 }
734 
735 bool i915_gem_valid_gtt_space(struct i915_vma *vma, unsigned long color)
736 {
737 	struct drm_mm_node *node = &vma->node;
738 	struct drm_mm_node *other;
739 
740 	/*
741 	 * On some machines we have to be careful when putting differing types
742 	 * of snoopable memory together to avoid the prefetcher crossing memory
743 	 * domains and dying. During vm initialisation, we decide whether or not
744 	 * these constraints apply and set the drm_mm.color_adjust
745 	 * appropriately.
746 	 */
747 	if (!i915_vm_has_cache_coloring(vma->vm))
748 		return true;
749 
750 	/* Only valid to be called on an already inserted vma */
751 	GEM_BUG_ON(!drm_mm_node_allocated(node));
752 	GEM_BUG_ON(list_empty(&node->node_list));
753 
754 	other = list_prev_entry(node, node_list);
755 	if (i915_node_color_differs(other, color) &&
756 	    !drm_mm_hole_follows(other))
757 		return false;
758 
759 	other = list_next_entry(node, node_list);
760 	if (i915_node_color_differs(other, color) &&
761 	    !drm_mm_hole_follows(node))
762 		return false;
763 
764 	return true;
765 }
766 
767 /**
768  * i915_vma_insert - finds a slot for the vma in its address space
769  * @vma: the vma
770  * @ww: An optional struct i915_gem_ww_ctx
771  * @size: requested size in bytes (can be larger than the VMA)
772  * @alignment: required alignment
773  * @flags: mask of PIN_* flags to use
774  *
775  * First we try to allocate some free space that meets the requirements for
776  * the VMA. Failiing that, if the flags permit, it will evict an old VMA,
777  * preferrably the oldest idle entry to make room for the new VMA.
778  *
779  * Returns:
780  * 0 on success, negative error code otherwise.
781  */
782 static int
783 i915_vma_insert(struct i915_vma *vma, struct i915_gem_ww_ctx *ww,
784 		u64 size, u64 alignment, u64 flags)
785 {
786 	unsigned long color, guard;
787 	u64 start, end;
788 	int ret;
789 
790 	GEM_BUG_ON(i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND | I915_VMA_LOCAL_BIND));
791 	GEM_BUG_ON(drm_mm_node_allocated(&vma->node));
792 	GEM_BUG_ON(hweight64(flags & (PIN_OFFSET_GUARD | PIN_OFFSET_FIXED | PIN_OFFSET_BIAS)) > 1);
793 
794 	size = max(size, vma->size);
795 	alignment = max_t(typeof(alignment), alignment, vma->display_alignment);
796 	if (flags & PIN_MAPPABLE) {
797 		size = max_t(typeof(size), size, vma->fence_size);
798 		alignment = max_t(typeof(alignment),
799 				  alignment, vma->fence_alignment);
800 	}
801 
802 	GEM_BUG_ON(!IS_ALIGNED(size, I915_GTT_PAGE_SIZE));
803 	GEM_BUG_ON(!IS_ALIGNED(alignment, I915_GTT_MIN_ALIGNMENT));
804 	GEM_BUG_ON(!is_power_of_2(alignment));
805 
806 	guard = vma->guard; /* retain guard across rebinds */
807 	if (flags & PIN_OFFSET_GUARD) {
808 		GEM_BUG_ON(overflows_type(flags & PIN_OFFSET_MASK, u32));
809 		guard = max_t(u32, guard, flags & PIN_OFFSET_MASK);
810 	}
811 	/*
812 	 * As we align the node upon insertion, but the hardware gets
813 	 * node.start + guard, the easiest way to make that work is
814 	 * to make the guard a multiple of the alignment size.
815 	 */
816 	guard = ALIGN(guard, alignment);
817 
818 	start = flags & PIN_OFFSET_BIAS ? flags & PIN_OFFSET_MASK : 0;
819 	GEM_BUG_ON(!IS_ALIGNED(start, I915_GTT_PAGE_SIZE));
820 
821 	end = vma->vm->total;
822 	if (flags & PIN_MAPPABLE)
823 		end = min_t(u64, end, i915_vm_to_ggtt(vma->vm)->mappable_end);
824 	if (flags & PIN_ZONE_4G)
825 		end = min_t(u64, end, (1ULL << 32) - I915_GTT_PAGE_SIZE);
826 	GEM_BUG_ON(!IS_ALIGNED(end, I915_GTT_PAGE_SIZE));
827 
828 	alignment = max(alignment, i915_vm_obj_min_alignment(vma->vm, vma->obj));
829 
830 	/*
831 	 * If binding the object/GGTT view requires more space than the entire
832 	 * aperture has, reject it early before evicting everything in a vain
833 	 * attempt to find space.
834 	 */
835 	if (size > end - 2 * guard) {
836 		drm_dbg(vma->obj->base.dev,
837 			"Attempting to bind an object larger than the aperture: request=%llu > %s aperture=%llu\n",
838 			size, flags & PIN_MAPPABLE ? "mappable" : "total", end);
839 		return -ENOSPC;
840 	}
841 
842 	color = 0;
843 
844 	if (i915_vm_has_cache_coloring(vma->vm))
845 		color = vma->obj->pat_index;
846 
847 	if (flags & PIN_OFFSET_FIXED) {
848 		u64 offset = flags & PIN_OFFSET_MASK;
849 		if (!IS_ALIGNED(offset, alignment) ||
850 		    range_overflows(offset, size, end))
851 			return -EINVAL;
852 		/*
853 		 * The caller knows not of the guard added by others and
854 		 * requests for the offset of the start of its buffer
855 		 * to be fixed, which may not be the same as the position
856 		 * of the vma->node due to the guard pages.
857 		 */
858 		if (offset < guard || offset + size > end - guard)
859 			return -ENOSPC;
860 
861 		ret = i915_gem_gtt_reserve(vma->vm, ww, &vma->node,
862 					   size + 2 * guard,
863 					   offset - guard,
864 					   color, flags);
865 		if (ret)
866 			return ret;
867 	} else {
868 		size += 2 * guard;
869 		/*
870 		 * We only support huge gtt pages through the 48b PPGTT,
871 		 * however we also don't want to force any alignment for
872 		 * objects which need to be tightly packed into the low 32bits.
873 		 *
874 		 * Note that we assume that GGTT are limited to 4GiB for the
875 		 * forseeable future. See also i915_ggtt_offset().
876 		 */
877 		if (upper_32_bits(end - 1) &&
878 		    vma->page_sizes.sg > I915_GTT_PAGE_SIZE &&
879 		    !HAS_64K_PAGES(vma->vm->i915)) {
880 			/*
881 			 * We can't mix 64K and 4K PTEs in the same page-table
882 			 * (2M block), and so to avoid the ugliness and
883 			 * complexity of coloring we opt for just aligning 64K
884 			 * objects to 2M.
885 			 */
886 			u64 page_alignment =
887 				rounddown_pow_of_two(vma->page_sizes.sg |
888 						     I915_GTT_PAGE_SIZE_2M);
889 
890 			/*
891 			 * Check we don't expand for the limited Global GTT
892 			 * (mappable aperture is even more precious!). This
893 			 * also checks that we exclude the aliasing-ppgtt.
894 			 */
895 			GEM_BUG_ON(i915_vma_is_ggtt(vma));
896 
897 			alignment = max(alignment, page_alignment);
898 
899 			if (vma->page_sizes.sg & I915_GTT_PAGE_SIZE_64K)
900 				size = round_up(size, I915_GTT_PAGE_SIZE_2M);
901 		}
902 
903 		ret = i915_gem_gtt_insert(vma->vm, ww, &vma->node,
904 					  size, alignment, color,
905 					  start, end, flags);
906 		if (ret)
907 			return ret;
908 
909 		GEM_BUG_ON(vma->node.start < start);
910 		GEM_BUG_ON(vma->node.start + vma->node.size > end);
911 	}
912 	GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
913 	GEM_BUG_ON(!i915_gem_valid_gtt_space(vma, color));
914 
915 	list_move_tail(&vma->vm_link, &vma->vm->bound_list);
916 	vma->guard = guard;
917 
918 	return 0;
919 }
920 
921 static void
922 i915_vma_detach(struct i915_vma *vma)
923 {
924 	GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
925 	GEM_BUG_ON(i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND | I915_VMA_LOCAL_BIND));
926 
927 	/*
928 	 * And finally now the object is completely decoupled from this
929 	 * vma, we can drop its hold on the backing storage and allow
930 	 * it to be reaped by the shrinker.
931 	 */
932 	list_move_tail(&vma->vm_link, &vma->vm->unbound_list);
933 }
934 
935 static bool try_qad_pin(struct i915_vma *vma, unsigned int flags)
936 {
937 	unsigned int bound;
938 
939 	bound = atomic_read(&vma->flags);
940 
941 	if (flags & PIN_VALIDATE) {
942 		flags &= I915_VMA_BIND_MASK;
943 
944 		return (flags & bound) == flags;
945 	}
946 
947 	/* with the lock mandatory for unbind, we don't race here */
948 	flags &= I915_VMA_BIND_MASK;
949 	do {
950 		if (unlikely(flags & ~bound))
951 			return false;
952 
953 		if (unlikely(bound & (I915_VMA_OVERFLOW | I915_VMA_ERROR)))
954 			return false;
955 
956 		GEM_BUG_ON(((bound + 1) & I915_VMA_PIN_MASK) == 0);
957 	} while (!atomic_try_cmpxchg(&vma->flags, &bound, bound + 1));
958 
959 	return true;
960 }
961 
962 static struct scatterlist *
963 rotate_pages(struct drm_i915_gem_object *obj, unsigned int offset,
964 	     unsigned int width, unsigned int height,
965 	     unsigned int src_stride, unsigned int dst_stride,
966 	     struct sg_table *st, struct scatterlist *sg)
967 {
968 	unsigned int column, row;
969 	pgoff_t src_idx;
970 
971 	for (column = 0; column < width; column++) {
972 		unsigned int left;
973 
974 		src_idx = src_stride * (height - 1) + column + offset;
975 		for (row = 0; row < height; row++) {
976 			st->nents++;
977 			/*
978 			 * We don't need the pages, but need to initialize
979 			 * the entries so the sg list can be happily traversed.
980 			 * The only thing we need are DMA addresses.
981 			 */
982 			sg_set_page(sg, NULL, I915_GTT_PAGE_SIZE, 0);
983 			sg_dma_address(sg) =
984 				i915_gem_object_get_dma_address(obj, src_idx);
985 			sg_dma_len(sg) = I915_GTT_PAGE_SIZE;
986 			sg = sg_next(sg);
987 			src_idx -= src_stride;
988 		}
989 
990 		left = (dst_stride - height) * I915_GTT_PAGE_SIZE;
991 
992 		if (!left)
993 			continue;
994 
995 		st->nents++;
996 
997 		/*
998 		 * The DE ignores the PTEs for the padding tiles, the sg entry
999 		 * here is just a conenience to indicate how many padding PTEs
1000 		 * to insert at this spot.
1001 		 */
1002 		sg_set_page(sg, NULL, left, 0);
1003 		sg_dma_address(sg) = 0;
1004 		sg_dma_len(sg) = left;
1005 		sg = sg_next(sg);
1006 	}
1007 
1008 	return sg;
1009 }
1010 
1011 static noinline struct sg_table *
1012 intel_rotate_pages(struct intel_rotation_info *rot_info,
1013 		   struct drm_i915_gem_object *obj)
1014 {
1015 	unsigned int size = intel_rotation_info_size(rot_info);
1016 	struct drm_i915_private *i915 = to_i915(obj->base.dev);
1017 	struct sg_table *st;
1018 	struct scatterlist *sg;
1019 	int ret = -ENOMEM;
1020 	int i;
1021 
1022 	/* Allocate target SG list. */
1023 	st = kmalloc(sizeof(*st), GFP_KERNEL);
1024 	if (!st)
1025 		goto err_st_alloc;
1026 
1027 	ret = sg_alloc_table(st, size, GFP_KERNEL);
1028 	if (ret)
1029 		goto err_sg_alloc;
1030 
1031 	st->nents = 0;
1032 	sg = st->sgl;
1033 
1034 	for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
1035 		sg = rotate_pages(obj, rot_info->plane[i].offset,
1036 				  rot_info->plane[i].width, rot_info->plane[i].height,
1037 				  rot_info->plane[i].src_stride,
1038 				  rot_info->plane[i].dst_stride,
1039 				  st, sg);
1040 
1041 	return st;
1042 
1043 err_sg_alloc:
1044 	kfree(st);
1045 err_st_alloc:
1046 
1047 	drm_dbg(&i915->drm, "Failed to create rotated mapping for object size %zu! (%ux%u tiles, %u pages)\n",
1048 		obj->base.size, rot_info->plane[0].width,
1049 		rot_info->plane[0].height, size);
1050 
1051 	return ERR_PTR(ret);
1052 }
1053 
1054 static struct scatterlist *
1055 add_padding_pages(unsigned int count,
1056 		  struct sg_table *st, struct scatterlist *sg)
1057 {
1058 	st->nents++;
1059 
1060 	/*
1061 	 * The DE ignores the PTEs for the padding tiles, the sg entry
1062 	 * here is just a convenience to indicate how many padding PTEs
1063 	 * to insert at this spot.
1064 	 */
1065 	sg_set_page(sg, NULL, count * I915_GTT_PAGE_SIZE, 0);
1066 	sg_dma_address(sg) = 0;
1067 	sg_dma_len(sg) = count * I915_GTT_PAGE_SIZE;
1068 	sg = sg_next(sg);
1069 
1070 	return sg;
1071 }
1072 
1073 static struct scatterlist *
1074 remap_tiled_color_plane_pages(struct drm_i915_gem_object *obj,
1075 			      unsigned long offset, unsigned int alignment_pad,
1076 			      unsigned int width, unsigned int height,
1077 			      unsigned int src_stride, unsigned int dst_stride,
1078 			      struct sg_table *st, struct scatterlist *sg,
1079 			      unsigned int *gtt_offset)
1080 {
1081 	unsigned int row;
1082 
1083 	if (!width || !height)
1084 		return sg;
1085 
1086 	if (alignment_pad)
1087 		sg = add_padding_pages(alignment_pad, st, sg);
1088 
1089 	for (row = 0; row < height; row++) {
1090 		unsigned int left = width * I915_GTT_PAGE_SIZE;
1091 
1092 		while (left) {
1093 			dma_addr_t addr;
1094 			unsigned int length;
1095 
1096 			/*
1097 			 * We don't need the pages, but need to initialize
1098 			 * the entries so the sg list can be happily traversed.
1099 			 * The only thing we need are DMA addresses.
1100 			 */
1101 
1102 			addr = i915_gem_object_get_dma_address_len(obj, offset, &length);
1103 
1104 			length = min(left, length);
1105 
1106 			st->nents++;
1107 
1108 			sg_set_page(sg, NULL, length, 0);
1109 			sg_dma_address(sg) = addr;
1110 			sg_dma_len(sg) = length;
1111 			sg = sg_next(sg);
1112 
1113 			offset += length / I915_GTT_PAGE_SIZE;
1114 			left -= length;
1115 		}
1116 
1117 		offset += src_stride - width;
1118 
1119 		left = (dst_stride - width) * I915_GTT_PAGE_SIZE;
1120 
1121 		if (!left)
1122 			continue;
1123 
1124 		sg = add_padding_pages(left >> PAGE_SHIFT, st, sg);
1125 	}
1126 
1127 	*gtt_offset += alignment_pad + dst_stride * height;
1128 
1129 	return sg;
1130 }
1131 
1132 static struct scatterlist *
1133 remap_contiguous_pages(struct drm_i915_gem_object *obj,
1134 		       pgoff_t obj_offset,
1135 		       unsigned int count,
1136 		       struct sg_table *st, struct scatterlist *sg)
1137 {
1138 	struct scatterlist *iter;
1139 	unsigned int offset;
1140 
1141 	iter = i915_gem_object_get_sg_dma(obj, obj_offset, &offset);
1142 	GEM_BUG_ON(!iter);
1143 
1144 	do {
1145 		unsigned int len;
1146 
1147 		len = min(sg_dma_len(iter) - (offset << PAGE_SHIFT),
1148 			  count << PAGE_SHIFT);
1149 		sg_set_page(sg, NULL, len, 0);
1150 		sg_dma_address(sg) =
1151 			sg_dma_address(iter) + (offset << PAGE_SHIFT);
1152 		sg_dma_len(sg) = len;
1153 
1154 		st->nents++;
1155 		count -= len >> PAGE_SHIFT;
1156 		if (count == 0)
1157 			return sg;
1158 
1159 		sg = __sg_next(sg);
1160 		iter = __sg_next(iter);
1161 		offset = 0;
1162 	} while (1);
1163 }
1164 
1165 static struct scatterlist *
1166 remap_linear_color_plane_pages(struct drm_i915_gem_object *obj,
1167 			       pgoff_t obj_offset, unsigned int alignment_pad,
1168 			       unsigned int size,
1169 			       struct sg_table *st, struct scatterlist *sg,
1170 			       unsigned int *gtt_offset)
1171 {
1172 	if (!size)
1173 		return sg;
1174 
1175 	if (alignment_pad)
1176 		sg = add_padding_pages(alignment_pad, st, sg);
1177 
1178 	sg = remap_contiguous_pages(obj, obj_offset, size, st, sg);
1179 	sg = sg_next(sg);
1180 
1181 	*gtt_offset += alignment_pad + size;
1182 
1183 	return sg;
1184 }
1185 
1186 static struct scatterlist *
1187 remap_color_plane_pages(const struct intel_remapped_info *rem_info,
1188 			struct drm_i915_gem_object *obj,
1189 			int color_plane,
1190 			struct sg_table *st, struct scatterlist *sg,
1191 			unsigned int *gtt_offset)
1192 {
1193 	unsigned int alignment_pad = 0;
1194 
1195 	if (rem_info->plane_alignment)
1196 		alignment_pad = ALIGN(*gtt_offset, rem_info->plane_alignment) - *gtt_offset;
1197 
1198 	if (rem_info->plane[color_plane].linear)
1199 		sg = remap_linear_color_plane_pages(obj,
1200 						    rem_info->plane[color_plane].offset,
1201 						    alignment_pad,
1202 						    rem_info->plane[color_plane].size,
1203 						    st, sg,
1204 						    gtt_offset);
1205 
1206 	else
1207 		sg = remap_tiled_color_plane_pages(obj,
1208 						   rem_info->plane[color_plane].offset,
1209 						   alignment_pad,
1210 						   rem_info->plane[color_plane].width,
1211 						   rem_info->plane[color_plane].height,
1212 						   rem_info->plane[color_plane].src_stride,
1213 						   rem_info->plane[color_plane].dst_stride,
1214 						   st, sg,
1215 						   gtt_offset);
1216 
1217 	return sg;
1218 }
1219 
1220 static noinline struct sg_table *
1221 intel_remap_pages(struct intel_remapped_info *rem_info,
1222 		  struct drm_i915_gem_object *obj)
1223 {
1224 	unsigned int size = intel_remapped_info_size(rem_info);
1225 	struct drm_i915_private *i915 = to_i915(obj->base.dev);
1226 	struct sg_table *st;
1227 	struct scatterlist *sg;
1228 	unsigned int gtt_offset = 0;
1229 	int ret = -ENOMEM;
1230 	int i;
1231 
1232 	/* Allocate target SG list. */
1233 	st = kmalloc(sizeof(*st), GFP_KERNEL);
1234 	if (!st)
1235 		goto err_st_alloc;
1236 
1237 	ret = sg_alloc_table(st, size, GFP_KERNEL);
1238 	if (ret)
1239 		goto err_sg_alloc;
1240 
1241 	st->nents = 0;
1242 	sg = st->sgl;
1243 
1244 	for (i = 0 ; i < ARRAY_SIZE(rem_info->plane); i++)
1245 		sg = remap_color_plane_pages(rem_info, obj, i, st, sg, &gtt_offset);
1246 
1247 	i915_sg_trim(st);
1248 
1249 	return st;
1250 
1251 err_sg_alloc:
1252 	kfree(st);
1253 err_st_alloc:
1254 
1255 	drm_dbg(&i915->drm, "Failed to create remapped mapping for object size %zu! (%ux%u tiles, %u pages)\n",
1256 		obj->base.size, rem_info->plane[0].width,
1257 		rem_info->plane[0].height, size);
1258 
1259 	return ERR_PTR(ret);
1260 }
1261 
1262 static noinline struct sg_table *
1263 intel_partial_pages(const struct i915_gtt_view *view,
1264 		    struct drm_i915_gem_object *obj)
1265 {
1266 	struct sg_table *st;
1267 	struct scatterlist *sg;
1268 	unsigned int count = view->partial.size;
1269 	int ret = -ENOMEM;
1270 
1271 	st = kmalloc(sizeof(*st), GFP_KERNEL);
1272 	if (!st)
1273 		goto err_st_alloc;
1274 
1275 	ret = sg_alloc_table(st, count, GFP_KERNEL);
1276 	if (ret)
1277 		goto err_sg_alloc;
1278 
1279 	st->nents = 0;
1280 
1281 	sg = remap_contiguous_pages(obj, view->partial.offset, count, st, st->sgl);
1282 
1283 	sg_mark_end(sg);
1284 	i915_sg_trim(st); /* Drop any unused tail entries. */
1285 
1286 	return st;
1287 
1288 err_sg_alloc:
1289 	kfree(st);
1290 err_st_alloc:
1291 	return ERR_PTR(ret);
1292 }
1293 
1294 static int
1295 __i915_vma_get_pages(struct i915_vma *vma)
1296 {
1297 	struct sg_table *pages;
1298 
1299 	/*
1300 	 * The vma->pages are only valid within the lifespan of the borrowed
1301 	 * obj->mm.pages. When the obj->mm.pages sg_table is regenerated, so
1302 	 * must be the vma->pages. A simple rule is that vma->pages must only
1303 	 * be accessed when the obj->mm.pages are pinned.
1304 	 */
1305 	GEM_BUG_ON(!i915_gem_object_has_pinned_pages(vma->obj));
1306 
1307 	switch (vma->gtt_view.type) {
1308 	default:
1309 		GEM_BUG_ON(vma->gtt_view.type);
1310 		fallthrough;
1311 	case I915_GTT_VIEW_NORMAL:
1312 		pages = vma->obj->mm.pages;
1313 		break;
1314 
1315 	case I915_GTT_VIEW_ROTATED:
1316 		pages =
1317 			intel_rotate_pages(&vma->gtt_view.rotated, vma->obj);
1318 		break;
1319 
1320 	case I915_GTT_VIEW_REMAPPED:
1321 		pages =
1322 			intel_remap_pages(&vma->gtt_view.remapped, vma->obj);
1323 		break;
1324 
1325 	case I915_GTT_VIEW_PARTIAL:
1326 		pages = intel_partial_pages(&vma->gtt_view, vma->obj);
1327 		break;
1328 	}
1329 
1330 	if (IS_ERR(pages)) {
1331 		drm_err(&vma->vm->i915->drm,
1332 			"Failed to get pages for VMA view type %u (%ld)!\n",
1333 			vma->gtt_view.type, PTR_ERR(pages));
1334 		return PTR_ERR(pages);
1335 	}
1336 
1337 	vma->pages = pages;
1338 
1339 	return 0;
1340 }
1341 
1342 I915_SELFTEST_EXPORT int i915_vma_get_pages(struct i915_vma *vma)
1343 {
1344 	int err;
1345 
1346 	if (atomic_add_unless(&vma->pages_count, 1, 0))
1347 		return 0;
1348 
1349 	err = i915_gem_object_pin_pages(vma->obj);
1350 	if (err)
1351 		return err;
1352 
1353 	err = __i915_vma_get_pages(vma);
1354 	if (err)
1355 		goto err_unpin;
1356 
1357 	vma->page_sizes = vma->obj->mm.page_sizes;
1358 	atomic_inc(&vma->pages_count);
1359 
1360 	return 0;
1361 
1362 err_unpin:
1363 	__i915_gem_object_unpin_pages(vma->obj);
1364 
1365 	return err;
1366 }
1367 
1368 void vma_invalidate_tlb(struct i915_address_space *vm, u32 *tlb)
1369 {
1370 	struct intel_gt *gt;
1371 	int id;
1372 
1373 	if (!tlb)
1374 		return;
1375 
1376 	/*
1377 	 * Before we release the pages that were bound by this vma, we
1378 	 * must invalidate all the TLBs that may still have a reference
1379 	 * back to our physical address. It only needs to be done once,
1380 	 * so after updating the PTE to point away from the pages, record
1381 	 * the most recent TLB invalidation seqno, and if we have not yet
1382 	 * flushed the TLBs upon release, perform a full invalidation.
1383 	 */
1384 	for_each_gt(gt, vm->i915, id)
1385 		WRITE_ONCE(tlb[id],
1386 			   intel_gt_next_invalidate_tlb_full(gt));
1387 }
1388 
1389 static void __vma_put_pages(struct i915_vma *vma, unsigned int count)
1390 {
1391 	/* We allocate under vma_get_pages, so beware the shrinker */
1392 	GEM_BUG_ON(atomic_read(&vma->pages_count) < count);
1393 
1394 	if (atomic_sub_return(count, &vma->pages_count) == 0) {
1395 		if (vma->pages != vma->obj->mm.pages) {
1396 			sg_free_table(vma->pages);
1397 			kfree(vma->pages);
1398 		}
1399 		vma->pages = NULL;
1400 
1401 		i915_gem_object_unpin_pages(vma->obj);
1402 	}
1403 }
1404 
1405 I915_SELFTEST_EXPORT void i915_vma_put_pages(struct i915_vma *vma)
1406 {
1407 	if (atomic_add_unless(&vma->pages_count, -1, 1))
1408 		return;
1409 
1410 	__vma_put_pages(vma, 1);
1411 }
1412 
1413 static void vma_unbind_pages(struct i915_vma *vma)
1414 {
1415 	unsigned int count;
1416 
1417 	lockdep_assert_held(&vma->vm->mutex);
1418 
1419 	/* The upper portion of pages_count is the number of bindings */
1420 	count = atomic_read(&vma->pages_count);
1421 	count >>= I915_VMA_PAGES_BIAS;
1422 	GEM_BUG_ON(!count);
1423 
1424 	__vma_put_pages(vma, count | count << I915_VMA_PAGES_BIAS);
1425 }
1426 
1427 int i915_vma_pin_ww(struct i915_vma *vma, struct i915_gem_ww_ctx *ww,
1428 		    u64 size, u64 alignment, u64 flags)
1429 {
1430 	struct i915_vma_work *work = NULL;
1431 	struct dma_fence *moving = NULL;
1432 	struct i915_vma_resource *vma_res = NULL;
1433 	intel_wakeref_t wakeref = 0;
1434 	unsigned int bound;
1435 	int err;
1436 
1437 	assert_vma_held(vma);
1438 	GEM_BUG_ON(!ww);
1439 
1440 	BUILD_BUG_ON(PIN_GLOBAL != I915_VMA_GLOBAL_BIND);
1441 	BUILD_BUG_ON(PIN_USER != I915_VMA_LOCAL_BIND);
1442 
1443 	GEM_BUG_ON(!(flags & (PIN_USER | PIN_GLOBAL)));
1444 
1445 	/* First try and grab the pin without rebinding the vma */
1446 	if (try_qad_pin(vma, flags))
1447 		return 0;
1448 
1449 	err = i915_vma_get_pages(vma);
1450 	if (err)
1451 		return err;
1452 
1453 	if (flags & PIN_GLOBAL)
1454 		wakeref = intel_runtime_pm_get(&vma->vm->i915->runtime_pm);
1455 
1456 	if (flags & vma->vm->bind_async_flags) {
1457 		/* lock VM */
1458 		err = i915_vm_lock_objects(vma->vm, ww);
1459 		if (err)
1460 			goto err_rpm;
1461 
1462 		work = i915_vma_work();
1463 		if (!work) {
1464 			err = -ENOMEM;
1465 			goto err_rpm;
1466 		}
1467 
1468 		work->vm = vma->vm;
1469 
1470 		err = i915_gem_object_get_moving_fence(vma->obj, &moving);
1471 		if (err)
1472 			goto err_rpm;
1473 
1474 		dma_fence_work_chain(&work->base, moving);
1475 
1476 		/* Allocate enough page directories to used PTE */
1477 		if (vma->vm->allocate_va_range) {
1478 			err = i915_vm_alloc_pt_stash(vma->vm,
1479 						     &work->stash,
1480 						     vma->size);
1481 			if (err)
1482 				goto err_fence;
1483 
1484 			err = i915_vm_map_pt_stash(vma->vm, &work->stash);
1485 			if (err)
1486 				goto err_fence;
1487 		}
1488 	}
1489 
1490 	vma_res = i915_vma_resource_alloc();
1491 	if (IS_ERR(vma_res)) {
1492 		err = PTR_ERR(vma_res);
1493 		goto err_fence;
1494 	}
1495 
1496 	/*
1497 	 * Differentiate between user/kernel vma inside the aliasing-ppgtt.
1498 	 *
1499 	 * We conflate the Global GTT with the user's vma when using the
1500 	 * aliasing-ppgtt, but it is still vitally important to try and
1501 	 * keep the use cases distinct. For example, userptr objects are
1502 	 * not allowed inside the Global GTT as that will cause lock
1503 	 * inversions when we have to evict them the mmu_notifier callbacks -
1504 	 * but they are allowed to be part of the user ppGTT which can never
1505 	 * be mapped. As such we try to give the distinct users of the same
1506 	 * mutex, distinct lockclasses [equivalent to how we keep i915_ggtt
1507 	 * and i915_ppgtt separate].
1508 	 *
1509 	 * NB this may cause us to mask real lock inversions -- while the
1510 	 * code is safe today, lockdep may not be able to spot future
1511 	 * transgressions.
1512 	 */
1513 	err = mutex_lock_interruptible_nested(&vma->vm->mutex,
1514 					      !(flags & PIN_GLOBAL));
1515 	if (err)
1516 		goto err_vma_res;
1517 
1518 	/* No more allocations allowed now we hold vm->mutex */
1519 
1520 	if (unlikely(i915_vma_is_closed(vma))) {
1521 		err = -ENOENT;
1522 		goto err_unlock;
1523 	}
1524 
1525 	bound = atomic_read(&vma->flags);
1526 	if (unlikely(bound & I915_VMA_ERROR)) {
1527 		err = -ENOMEM;
1528 		goto err_unlock;
1529 	}
1530 
1531 	if (unlikely(!((bound + 1) & I915_VMA_PIN_MASK))) {
1532 		err = -EAGAIN; /* pins are meant to be fairly temporary */
1533 		goto err_unlock;
1534 	}
1535 
1536 	if (unlikely(!(flags & ~bound & I915_VMA_BIND_MASK))) {
1537 		if (!(flags & PIN_VALIDATE))
1538 			__i915_vma_pin(vma);
1539 		goto err_unlock;
1540 	}
1541 
1542 	err = i915_active_acquire(&vma->active);
1543 	if (err)
1544 		goto err_unlock;
1545 
1546 	if (!(bound & I915_VMA_BIND_MASK)) {
1547 		err = i915_vma_insert(vma, ww, size, alignment, flags);
1548 		if (err)
1549 			goto err_active;
1550 
1551 		if (i915_is_ggtt(vma->vm))
1552 			__i915_vma_set_map_and_fenceable(vma);
1553 	}
1554 
1555 	GEM_BUG_ON(!vma->pages);
1556 	err = i915_vma_bind(vma,
1557 			    vma->obj->pat_index,
1558 			    flags, work, vma_res);
1559 	vma_res = NULL;
1560 	if (err)
1561 		goto err_remove;
1562 
1563 	/* There should only be at most 2 active bindings (user, global) */
1564 	GEM_BUG_ON(bound + I915_VMA_PAGES_ACTIVE < bound);
1565 	atomic_add(I915_VMA_PAGES_ACTIVE, &vma->pages_count);
1566 	list_move_tail(&vma->vm_link, &vma->vm->bound_list);
1567 
1568 	if (!(flags & PIN_VALIDATE)) {
1569 		__i915_vma_pin(vma);
1570 		GEM_BUG_ON(!i915_vma_is_pinned(vma));
1571 	}
1572 	GEM_BUG_ON(!i915_vma_is_bound(vma, flags));
1573 	GEM_BUG_ON(i915_vma_misplaced(vma, size, alignment, flags));
1574 
1575 err_remove:
1576 	if (!i915_vma_is_bound(vma, I915_VMA_BIND_MASK)) {
1577 		i915_vma_detach(vma);
1578 		drm_mm_remove_node(&vma->node);
1579 	}
1580 err_active:
1581 	i915_active_release(&vma->active);
1582 err_unlock:
1583 	mutex_unlock(&vma->vm->mutex);
1584 err_vma_res:
1585 	i915_vma_resource_free(vma_res);
1586 err_fence:
1587 	if (work)
1588 		dma_fence_work_commit_imm(&work->base);
1589 err_rpm:
1590 	if (wakeref)
1591 		intel_runtime_pm_put(&vma->vm->i915->runtime_pm, wakeref);
1592 
1593 	if (moving)
1594 		dma_fence_put(moving);
1595 
1596 	i915_vma_put_pages(vma);
1597 	return err;
1598 }
1599 
1600 static void flush_idle_contexts(struct intel_gt *gt)
1601 {
1602 	struct intel_engine_cs *engine;
1603 	enum intel_engine_id id;
1604 
1605 	for_each_engine(engine, gt, id)
1606 		intel_engine_flush_barriers(engine);
1607 
1608 	intel_gt_wait_for_idle(gt, MAX_SCHEDULE_TIMEOUT);
1609 }
1610 
1611 static int __i915_ggtt_pin(struct i915_vma *vma, struct i915_gem_ww_ctx *ww,
1612 			   u32 align, unsigned int flags)
1613 {
1614 	struct i915_address_space *vm = vma->vm;
1615 	struct intel_gt *gt;
1616 	struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
1617 	int err;
1618 
1619 	do {
1620 		err = i915_vma_pin_ww(vma, ww, 0, align, flags | PIN_GLOBAL);
1621 
1622 		if (err != -ENOSPC) {
1623 			if (!err) {
1624 				err = i915_vma_wait_for_bind(vma);
1625 				if (err)
1626 					i915_vma_unpin(vma);
1627 			}
1628 			return err;
1629 		}
1630 
1631 		/* Unlike i915_vma_pin, we don't take no for an answer! */
1632 		list_for_each_entry(gt, &ggtt->gt_list, ggtt_link)
1633 			flush_idle_contexts(gt);
1634 		if (mutex_lock_interruptible(&vm->mutex) == 0) {
1635 			/*
1636 			 * We pass NULL ww here, as we don't want to unbind
1637 			 * locked objects when called from execbuf when pinning
1638 			 * is removed. This would probably regress badly.
1639 			 */
1640 			i915_gem_evict_vm(vm, NULL, NULL);
1641 			mutex_unlock(&vm->mutex);
1642 		}
1643 	} while (1);
1644 }
1645 
1646 int i915_ggtt_pin(struct i915_vma *vma, struct i915_gem_ww_ctx *ww,
1647 		  u32 align, unsigned int flags)
1648 {
1649 	struct i915_gem_ww_ctx _ww;
1650 	int err;
1651 
1652 	GEM_BUG_ON(!i915_vma_is_ggtt(vma));
1653 
1654 	if (ww)
1655 		return __i915_ggtt_pin(vma, ww, align, flags);
1656 
1657 	lockdep_assert_not_held(&vma->obj->base.resv->lock.base);
1658 
1659 	for_i915_gem_ww(&_ww, err, true) {
1660 		err = i915_gem_object_lock(vma->obj, &_ww);
1661 		if (!err)
1662 			err = __i915_ggtt_pin(vma, &_ww, align, flags);
1663 	}
1664 
1665 	return err;
1666 }
1667 
1668 /**
1669  * i915_ggtt_clear_scanout - Clear scanout flag for all objects ggtt vmas
1670  * @obj: i915 GEM object
1671  * This function clears scanout flags for objects ggtt vmas. These flags are set
1672  * when object is pinned for display use and this function to clear them all is
1673  * targeted to be called by frontbuffer tracking code when the frontbuffer is
1674  * about to be released.
1675  */
1676 void i915_ggtt_clear_scanout(struct drm_i915_gem_object *obj)
1677 {
1678 	struct i915_vma *vma;
1679 
1680 	spin_lock(&obj->vma.lock);
1681 	for_each_ggtt_vma(vma, obj) {
1682 		i915_vma_clear_scanout(vma);
1683 		vma->display_alignment = I915_GTT_MIN_ALIGNMENT;
1684 	}
1685 	spin_unlock(&obj->vma.lock);
1686 }
1687 
1688 static void __vma_close(struct i915_vma *vma, struct intel_gt *gt)
1689 {
1690 	/*
1691 	 * We defer actually closing, unbinding and destroying the VMA until
1692 	 * the next idle point, or if the object is freed in the meantime. By
1693 	 * postponing the unbind, we allow for it to be resurrected by the
1694 	 * client, avoiding the work required to rebind the VMA. This is
1695 	 * advantageous for DRI, where the client/server pass objects
1696 	 * between themselves, temporarily opening a local VMA to the
1697 	 * object, and then closing it again. The same object is then reused
1698 	 * on the next frame (or two, depending on the depth of the swap queue)
1699 	 * causing us to rebind the VMA once more. This ends up being a lot
1700 	 * of wasted work for the steady state.
1701 	 */
1702 	GEM_BUG_ON(i915_vma_is_closed(vma));
1703 	list_add(&vma->closed_link, &gt->closed_vma);
1704 }
1705 
1706 void i915_vma_close(struct i915_vma *vma)
1707 {
1708 	struct intel_gt *gt = vma->vm->gt;
1709 	unsigned long flags;
1710 
1711 	if (i915_vma_is_ggtt(vma))
1712 		return;
1713 
1714 	GEM_BUG_ON(!atomic_read(&vma->open_count));
1715 	if (atomic_dec_and_lock_irqsave(&vma->open_count,
1716 					&gt->closed_lock,
1717 					flags)) {
1718 		__vma_close(vma, gt);
1719 		spin_unlock_irqrestore(&gt->closed_lock, flags);
1720 	}
1721 }
1722 
1723 static void __i915_vma_remove_closed(struct i915_vma *vma)
1724 {
1725 	list_del_init(&vma->closed_link);
1726 }
1727 
1728 void i915_vma_reopen(struct i915_vma *vma)
1729 {
1730 	struct intel_gt *gt = vma->vm->gt;
1731 
1732 	spin_lock_irq(&gt->closed_lock);
1733 	if (i915_vma_is_closed(vma))
1734 		__i915_vma_remove_closed(vma);
1735 	spin_unlock_irq(&gt->closed_lock);
1736 }
1737 
1738 static void force_unbind(struct i915_vma *vma)
1739 {
1740 	if (!drm_mm_node_allocated(&vma->node))
1741 		return;
1742 
1743 	atomic_and(~I915_VMA_PIN_MASK, &vma->flags);
1744 	WARN_ON(__i915_vma_unbind(vma));
1745 	GEM_BUG_ON(drm_mm_node_allocated(&vma->node));
1746 }
1747 
1748 static void release_references(struct i915_vma *vma, struct intel_gt *gt,
1749 			       bool vm_ddestroy)
1750 {
1751 	struct drm_i915_gem_object *obj = vma->obj;
1752 
1753 	GEM_BUG_ON(i915_vma_is_active(vma));
1754 
1755 	spin_lock(&obj->vma.lock);
1756 	list_del(&vma->obj_link);
1757 	if (!RB_EMPTY_NODE(&vma->obj_node))
1758 		rb_erase(&vma->obj_node, &obj->vma.tree);
1759 
1760 	spin_unlock(&obj->vma.lock);
1761 
1762 	spin_lock_irq(&gt->closed_lock);
1763 	__i915_vma_remove_closed(vma);
1764 	spin_unlock_irq(&gt->closed_lock);
1765 
1766 	if (vm_ddestroy)
1767 		i915_vm_resv_put(vma->vm);
1768 
1769 	/* Wait for async active retire */
1770 	i915_active_wait(&vma->active);
1771 	i915_active_fini(&vma->active);
1772 	GEM_WARN_ON(vma->resource);
1773 	i915_vma_free(vma);
1774 }
1775 
1776 /*
1777  * i915_vma_destroy_locked - Remove all weak reference to the vma and put
1778  * the initial reference.
1779  *
1780  * This function should be called when it's decided the vma isn't needed
1781  * anymore. The caller must assure that it doesn't race with another lookup
1782  * plus destroy, typically by taking an appropriate reference.
1783  *
1784  * Current callsites are
1785  * - __i915_gem_object_pages_fini()
1786  * - __i915_vm_close() - Blocks the above function by taking a reference on
1787  * the object.
1788  * - __i915_vma_parked() - Blocks the above functions by taking a reference
1789  * on the vm and a reference on the object. Also takes the object lock so
1790  * destruction from __i915_vma_parked() can be blocked by holding the
1791  * object lock. Since the object lock is only allowed from within i915 with
1792  * an object refcount, holding the object lock also implicitly blocks the
1793  * vma freeing from __i915_gem_object_pages_fini().
1794  *
1795  * Because of locks taken during destruction, a vma is also guaranteed to
1796  * stay alive while the following locks are held if it was looked up while
1797  * holding one of the locks:
1798  * - vm->mutex
1799  * - obj->vma.lock
1800  * - gt->closed_lock
1801  */
1802 void i915_vma_destroy_locked(struct i915_vma *vma)
1803 {
1804 	lockdep_assert_held(&vma->vm->mutex);
1805 
1806 	force_unbind(vma);
1807 	list_del_init(&vma->vm_link);
1808 	release_references(vma, vma->vm->gt, false);
1809 }
1810 
1811 void i915_vma_destroy(struct i915_vma *vma)
1812 {
1813 	struct intel_gt *gt;
1814 	bool vm_ddestroy;
1815 
1816 	mutex_lock(&vma->vm->mutex);
1817 	force_unbind(vma);
1818 	list_del_init(&vma->vm_link);
1819 	vm_ddestroy = vma->vm_ddestroy;
1820 	vma->vm_ddestroy = false;
1821 
1822 	/* vma->vm may be freed when releasing vma->vm->mutex. */
1823 	gt = vma->vm->gt;
1824 	mutex_unlock(&vma->vm->mutex);
1825 	release_references(vma, gt, vm_ddestroy);
1826 }
1827 
1828 void i915_vma_parked(struct intel_gt *gt)
1829 {
1830 	struct i915_vma *vma, *next;
1831 	DRM_LIST_HEAD(closed);
1832 
1833 	spin_lock_irq(&gt->closed_lock);
1834 	list_for_each_entry_safe(vma, next, &gt->closed_vma, closed_link) {
1835 		struct drm_i915_gem_object *obj = vma->obj;
1836 		struct i915_address_space *vm = vma->vm;
1837 
1838 		/* XXX All to avoid keeping a reference on i915_vma itself */
1839 
1840 		if (!kref_get_unless_zero(&obj->base.refcount))
1841 			continue;
1842 
1843 		if (!i915_vm_tryget(vm)) {
1844 			i915_gem_object_put(obj);
1845 			continue;
1846 		}
1847 
1848 		list_move(&vma->closed_link, &closed);
1849 	}
1850 	spin_unlock_irq(&gt->closed_lock);
1851 
1852 	/* As the GT is held idle, no vma can be reopened as we destroy them */
1853 	list_for_each_entry_safe(vma, next, &closed, closed_link) {
1854 		struct drm_i915_gem_object *obj = vma->obj;
1855 		struct i915_address_space *vm = vma->vm;
1856 
1857 		if (i915_gem_object_trylock(obj, NULL)) {
1858 			INIT_LIST_HEAD(&vma->closed_link);
1859 			i915_vma_destroy(vma);
1860 			i915_gem_object_unlock(obj);
1861 		} else {
1862 			/* back you go.. */
1863 			spin_lock_irq(&gt->closed_lock);
1864 			list_add(&vma->closed_link, &gt->closed_vma);
1865 			spin_unlock_irq(&gt->closed_lock);
1866 		}
1867 
1868 		i915_gem_object_put(obj);
1869 		i915_vm_put(vm);
1870 	}
1871 }
1872 
1873 static void __i915_vma_iounmap(struct i915_vma *vma)
1874 {
1875 	GEM_BUG_ON(i915_vma_is_pinned(vma));
1876 
1877 	if (vma->iomap == NULL)
1878 		return;
1879 
1880 	if (page_unmask_bits(vma->iomap))
1881 		__i915_gem_object_release_map(vma->obj);
1882 	else {
1883 #ifdef __linux__
1884 		io_mapping_unmap(vma->iomap);
1885 #else
1886 		struct drm_i915_private *dev_priv = vma->vm->i915;
1887 		agp_unmap_subregion(dev_priv->agph, vma->bsh, vma->node.size);
1888 #endif
1889 	}
1890 	vma->iomap = NULL;
1891 }
1892 
1893 void i915_vma_revoke_mmap(struct i915_vma *vma)
1894 {
1895 	struct drm_vma_offset_node *node;
1896 	u64 vma_offset;
1897 
1898 	if (!i915_vma_has_userfault(vma))
1899 		return;
1900 
1901 	GEM_BUG_ON(!i915_vma_is_map_and_fenceable(vma));
1902 	GEM_BUG_ON(!vma->obj->userfault_count);
1903 
1904 	node = &vma->mmo->vma_node;
1905 	vma_offset = vma->gtt_view.partial.offset << PAGE_SHIFT;
1906 #ifdef __linux__
1907 	unmap_mapping_range(vma->vm->i915->drm.anon_inode->i_mapping,
1908 			    drm_vma_node_offset_addr(node) + vma_offset,
1909 			    vma->size,
1910 			    1);
1911 #else
1912 	struct drm_i915_private *dev_priv = vma->obj->base.dev->dev_private;
1913 	struct vm_page *pg;
1914 
1915 	for (pg = &dev_priv->pgs[atop(vma->node.start)];
1916 	    pg != &dev_priv->pgs[atop(vma->node.start + vma->size)];
1917 	    pg++)
1918 		pmap_page_protect(pg, PROT_NONE);
1919 #endif
1920 
1921 	i915_vma_unset_userfault(vma);
1922 	if (!--vma->obj->userfault_count)
1923 		list_del(&vma->obj->userfault_link);
1924 }
1925 
1926 static int
1927 __i915_request_await_bind(struct i915_request *rq, struct i915_vma *vma)
1928 {
1929 	return __i915_request_await_exclusive(rq, &vma->active);
1930 }
1931 
1932 static int __i915_vma_move_to_active(struct i915_vma *vma, struct i915_request *rq)
1933 {
1934 	int err;
1935 
1936 	/* Wait for the vma to be bound before we start! */
1937 	err = __i915_request_await_bind(rq, vma);
1938 	if (err)
1939 		return err;
1940 
1941 	return i915_active_add_request(&vma->active, rq);
1942 }
1943 
1944 int _i915_vma_move_to_active(struct i915_vma *vma,
1945 			     struct i915_request *rq,
1946 			     struct dma_fence *fence,
1947 			     unsigned int flags)
1948 {
1949 	struct drm_i915_gem_object *obj = vma->obj;
1950 	int err;
1951 
1952 	assert_object_held(obj);
1953 
1954 	GEM_BUG_ON(!vma->pages);
1955 
1956 	if (!(flags & __EXEC_OBJECT_NO_REQUEST_AWAIT)) {
1957 		err = i915_request_await_object(rq, vma->obj, flags & EXEC_OBJECT_WRITE);
1958 		if (unlikely(err))
1959 			return err;
1960 	}
1961 	err = __i915_vma_move_to_active(vma, rq);
1962 	if (unlikely(err))
1963 		return err;
1964 
1965 	/*
1966 	 * Reserve fences slot early to prevent an allocation after preparing
1967 	 * the workload and associating fences with dma_resv.
1968 	 */
1969 	if (fence && !(flags & __EXEC_OBJECT_NO_RESERVE)) {
1970 		struct dma_fence *curr;
1971 		int idx;
1972 
1973 		dma_fence_array_for_each(curr, idx, fence)
1974 			;
1975 		err = dma_resv_reserve_fences(vma->obj->base.resv, idx);
1976 		if (unlikely(err))
1977 			return err;
1978 	}
1979 
1980 	if (flags & EXEC_OBJECT_WRITE) {
1981 		struct intel_frontbuffer *front;
1982 
1983 		front = i915_gem_object_get_frontbuffer(obj);
1984 		if (unlikely(front)) {
1985 			if (intel_frontbuffer_invalidate(front, ORIGIN_CS))
1986 				i915_active_add_request(&front->write, rq);
1987 			intel_frontbuffer_put(front);
1988 		}
1989 	}
1990 
1991 	if (fence) {
1992 		struct dma_fence *curr;
1993 		enum dma_resv_usage usage;
1994 		int idx;
1995 
1996 		if (flags & EXEC_OBJECT_WRITE) {
1997 			usage = DMA_RESV_USAGE_WRITE;
1998 			obj->write_domain = I915_GEM_DOMAIN_RENDER;
1999 			obj->read_domains = 0;
2000 		} else {
2001 			usage = DMA_RESV_USAGE_READ;
2002 			obj->write_domain = 0;
2003 		}
2004 
2005 		dma_fence_array_for_each(curr, idx, fence)
2006 			dma_resv_add_fence(vma->obj->base.resv, curr, usage);
2007 	}
2008 
2009 	if (flags & EXEC_OBJECT_NEEDS_FENCE && vma->fence)
2010 		i915_active_add_request(&vma->fence->active, rq);
2011 
2012 	obj->read_domains |= I915_GEM_GPU_DOMAINS;
2013 	obj->mm.dirty = true;
2014 
2015 	GEM_BUG_ON(!i915_vma_is_active(vma));
2016 	return 0;
2017 }
2018 
2019 struct dma_fence *__i915_vma_evict(struct i915_vma *vma, bool async)
2020 {
2021 	struct i915_vma_resource *vma_res = vma->resource;
2022 	struct dma_fence *unbind_fence;
2023 
2024 	GEM_BUG_ON(i915_vma_is_pinned(vma));
2025 	assert_vma_held_evict(vma);
2026 
2027 	if (i915_vma_is_map_and_fenceable(vma)) {
2028 		/* Force a pagefault for domain tracking on next user access */
2029 		i915_vma_revoke_mmap(vma);
2030 
2031 		/*
2032 		 * Check that we have flushed all writes through the GGTT
2033 		 * before the unbind, other due to non-strict nature of those
2034 		 * indirect writes they may end up referencing the GGTT PTE
2035 		 * after the unbind.
2036 		 *
2037 		 * Note that we may be concurrently poking at the GGTT_WRITE
2038 		 * bit from set-domain, as we mark all GGTT vma associated
2039 		 * with an object. We know this is for another vma, as we
2040 		 * are currently unbinding this one -- so if this vma will be
2041 		 * reused, it will be refaulted and have its dirty bit set
2042 		 * before the next write.
2043 		 */
2044 		i915_vma_flush_writes(vma);
2045 
2046 		/* release the fence reg _after_ flushing */
2047 		i915_vma_revoke_fence(vma);
2048 
2049 		clear_bit(I915_VMA_CAN_FENCE_BIT, __i915_vma_flags(vma));
2050 	}
2051 
2052 	__i915_vma_iounmap(vma);
2053 
2054 	GEM_BUG_ON(vma->fence);
2055 	GEM_BUG_ON(i915_vma_has_userfault(vma));
2056 
2057 	/* Object backend must be async capable. */
2058 	GEM_WARN_ON(async && !vma->resource->bi.pages_rsgt);
2059 
2060 	/* If vm is not open, unbind is a nop. */
2061 	vma_res->needs_wakeref = i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND) &&
2062 		kref_read(&vma->vm->ref);
2063 	vma_res->skip_pte_rewrite = !kref_read(&vma->vm->ref) ||
2064 		vma->vm->skip_pte_rewrite;
2065 	trace_i915_vma_unbind(vma);
2066 
2067 	if (async)
2068 		unbind_fence = i915_vma_resource_unbind(vma_res,
2069 							vma->obj->mm.tlb);
2070 	else
2071 		unbind_fence = i915_vma_resource_unbind(vma_res, NULL);
2072 
2073 	vma->resource = NULL;
2074 
2075 	atomic_and(~(I915_VMA_BIND_MASK | I915_VMA_ERROR | I915_VMA_GGTT_WRITE),
2076 		   &vma->flags);
2077 
2078 	i915_vma_detach(vma);
2079 
2080 	if (!async) {
2081 		if (unbind_fence) {
2082 			dma_fence_wait(unbind_fence, false);
2083 			dma_fence_put(unbind_fence);
2084 			unbind_fence = NULL;
2085 		}
2086 		vma_invalidate_tlb(vma->vm, vma->obj->mm.tlb);
2087 	}
2088 
2089 	/*
2090 	 * Binding itself may not have completed until the unbind fence signals,
2091 	 * so don't drop the pages until that happens, unless the resource is
2092 	 * async_capable.
2093 	 */
2094 
2095 	vma_unbind_pages(vma);
2096 	return unbind_fence;
2097 }
2098 
2099 int __i915_vma_unbind(struct i915_vma *vma)
2100 {
2101 	int ret;
2102 
2103 	lockdep_assert_held(&vma->vm->mutex);
2104 	assert_vma_held_evict(vma);
2105 
2106 	if (!drm_mm_node_allocated(&vma->node))
2107 		return 0;
2108 
2109 	if (i915_vma_is_pinned(vma)) {
2110 		vma_print_allocator(vma, "is pinned");
2111 		return -EAGAIN;
2112 	}
2113 
2114 	/*
2115 	 * After confirming that no one else is pinning this vma, wait for
2116 	 * any laggards who may have crept in during the wait (through
2117 	 * a residual pin skipping the vm->mutex) to complete.
2118 	 */
2119 	ret = i915_vma_sync(vma);
2120 	if (ret)
2121 		return ret;
2122 
2123 	GEM_BUG_ON(i915_vma_is_active(vma));
2124 	__i915_vma_evict(vma, false);
2125 
2126 	drm_mm_remove_node(&vma->node); /* pairs with i915_vma_release() */
2127 	return 0;
2128 }
2129 
2130 static struct dma_fence *__i915_vma_unbind_async(struct i915_vma *vma)
2131 {
2132 	struct dma_fence *fence;
2133 
2134 	lockdep_assert_held(&vma->vm->mutex);
2135 
2136 	if (!drm_mm_node_allocated(&vma->node))
2137 		return NULL;
2138 
2139 	if (i915_vma_is_pinned(vma) ||
2140 	    &vma->obj->mm.rsgt->table != vma->resource->bi.pages)
2141 		return ERR_PTR(-EAGAIN);
2142 
2143 	/*
2144 	 * We probably need to replace this with awaiting the fences of the
2145 	 * object's dma_resv when the vma active goes away. When doing that
2146 	 * we need to be careful to not add the vma_resource unbind fence
2147 	 * immediately to the object's dma_resv, because then unbinding
2148 	 * the next vma from the object, in case there are many, will
2149 	 * actually await the unbinding of the previous vmas, which is
2150 	 * undesirable.
2151 	 */
2152 	if (i915_sw_fence_await_active(&vma->resource->chain, &vma->active,
2153 				       I915_ACTIVE_AWAIT_EXCL |
2154 				       I915_ACTIVE_AWAIT_ACTIVE) < 0) {
2155 		return ERR_PTR(-EBUSY);
2156 	}
2157 
2158 	fence = __i915_vma_evict(vma, true);
2159 
2160 	drm_mm_remove_node(&vma->node); /* pairs with i915_vma_release() */
2161 
2162 	return fence;
2163 }
2164 
2165 int i915_vma_unbind(struct i915_vma *vma)
2166 {
2167 	struct i915_address_space *vm = vma->vm;
2168 	intel_wakeref_t wakeref = 0;
2169 	int err;
2170 
2171 	assert_object_held_shared(vma->obj);
2172 
2173 	/* Optimistic wait before taking the mutex */
2174 	err = i915_vma_sync(vma);
2175 	if (err)
2176 		return err;
2177 
2178 	if (!drm_mm_node_allocated(&vma->node))
2179 		return 0;
2180 
2181 	if (i915_vma_is_pinned(vma)) {
2182 		vma_print_allocator(vma, "is pinned");
2183 		return -EAGAIN;
2184 	}
2185 
2186 	if (i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND))
2187 		/* XXX not always required: nop_clear_range */
2188 		wakeref = intel_runtime_pm_get(&vm->i915->runtime_pm);
2189 
2190 	err = mutex_lock_interruptible_nested(&vma->vm->mutex, !wakeref);
2191 	if (err)
2192 		goto out_rpm;
2193 
2194 	err = __i915_vma_unbind(vma);
2195 	mutex_unlock(&vm->mutex);
2196 
2197 out_rpm:
2198 	if (wakeref)
2199 		intel_runtime_pm_put(&vm->i915->runtime_pm, wakeref);
2200 	return err;
2201 }
2202 
2203 int i915_vma_unbind_async(struct i915_vma *vma, bool trylock_vm)
2204 {
2205 	struct drm_i915_gem_object *obj = vma->obj;
2206 	struct i915_address_space *vm = vma->vm;
2207 	intel_wakeref_t wakeref = 0;
2208 	struct dma_fence *fence;
2209 	int err;
2210 
2211 	/*
2212 	 * We need the dma-resv lock since we add the
2213 	 * unbind fence to the dma-resv object.
2214 	 */
2215 	assert_object_held(obj);
2216 
2217 	if (!drm_mm_node_allocated(&vma->node))
2218 		return 0;
2219 
2220 	if (i915_vma_is_pinned(vma)) {
2221 		vma_print_allocator(vma, "is pinned");
2222 		return -EAGAIN;
2223 	}
2224 
2225 	if (!obj->mm.rsgt)
2226 		return -EBUSY;
2227 
2228 	err = dma_resv_reserve_fences(obj->base.resv, 2);
2229 	if (err)
2230 		return -EBUSY;
2231 
2232 	/*
2233 	 * It would be great if we could grab this wakeref from the
2234 	 * async unbind work if needed, but we can't because it uses
2235 	 * kmalloc and it's in the dma-fence signalling critical path.
2236 	 */
2237 	if (i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND))
2238 		wakeref = intel_runtime_pm_get(&vm->i915->runtime_pm);
2239 
2240 	if (trylock_vm && !mutex_trylock(&vm->mutex)) {
2241 		err = -EBUSY;
2242 		goto out_rpm;
2243 	} else if (!trylock_vm) {
2244 		err = mutex_lock_interruptible_nested(&vm->mutex, !wakeref);
2245 		if (err)
2246 			goto out_rpm;
2247 	}
2248 
2249 	fence = __i915_vma_unbind_async(vma);
2250 	mutex_unlock(&vm->mutex);
2251 	if (IS_ERR_OR_NULL(fence)) {
2252 		err = PTR_ERR_OR_ZERO(fence);
2253 		goto out_rpm;
2254 	}
2255 
2256 	dma_resv_add_fence(obj->base.resv, fence, DMA_RESV_USAGE_READ);
2257 	dma_fence_put(fence);
2258 
2259 out_rpm:
2260 	if (wakeref)
2261 		intel_runtime_pm_put(&vm->i915->runtime_pm, wakeref);
2262 	return err;
2263 }
2264 
2265 int i915_vma_unbind_unlocked(struct i915_vma *vma)
2266 {
2267 	int err;
2268 
2269 	i915_gem_object_lock(vma->obj, NULL);
2270 	err = i915_vma_unbind(vma);
2271 	i915_gem_object_unlock(vma->obj);
2272 
2273 	return err;
2274 }
2275 
2276 struct i915_vma *i915_vma_make_unshrinkable(struct i915_vma *vma)
2277 {
2278 	i915_gem_object_make_unshrinkable(vma->obj);
2279 	return vma;
2280 }
2281 
2282 void i915_vma_make_shrinkable(struct i915_vma *vma)
2283 {
2284 	i915_gem_object_make_shrinkable(vma->obj);
2285 }
2286 
2287 void i915_vma_make_purgeable(struct i915_vma *vma)
2288 {
2289 	i915_gem_object_make_purgeable(vma->obj);
2290 }
2291 
2292 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
2293 #include "selftests/i915_vma.c"
2294 #endif
2295 
2296 void i915_vma_module_exit(void)
2297 {
2298 #ifdef __linux__
2299 	kmem_cache_destroy(slab_vmas);
2300 #else
2301 	pool_destroy(&slab_vmas);
2302 #endif
2303 }
2304 
2305 int __init i915_vma_module_init(void)
2306 {
2307 #ifdef __linux__
2308 	slab_vmas = KMEM_CACHE(i915_vma, SLAB_HWCACHE_ALIGN);
2309 	if (!slab_vmas)
2310 		return -ENOMEM;
2311 #else
2312 	pool_init(&slab_vmas, sizeof(struct i915_vma),
2313 	    CACHELINESIZE, IPL_NONE, 0, "drmvma", NULL);
2314 #endif
2315 
2316 	return 0;
2317 }
2318