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