xref: /openbmc/linux/drivers/gpu/drm/i915/i915_vma.c (revision f350c74f)
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, __i915_vma_offset(vma),
422 			       __i915_vma_size(vma), vma->size, vma->guard);
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 > i915_vma_size(vma));
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 						i915_vma_offset(vma),
573 						i915_vma_size(vma));
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 (i915_vma_size(vma) < size)
663 		return true;
664 
665 	GEM_BUG_ON(alignment && !is_power_of_2(alignment));
666 	if (alignment && !IS_ALIGNED(i915_vma_offset(vma), 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 	    i915_vma_offset(vma) < (flags & PIN_OFFSET_MASK))
674 		return true;
675 
676 	if (flags & PIN_OFFSET_FIXED &&
677 	    i915_vma_offset(vma) != (flags & PIN_OFFSET_MASK))
678 		return true;
679 
680 	if (flags & PIN_OFFSET_GUARD &&
681 	    vma->guard < (flags & PIN_OFFSET_MASK))
682 		return true;
683 
684 	return false;
685 }
686 
687 void __i915_vma_set_map_and_fenceable(struct i915_vma *vma)
688 {
689 	bool mappable, fenceable;
690 
691 	GEM_BUG_ON(!i915_vma_is_ggtt(vma));
692 	GEM_BUG_ON(!vma->fence_size);
693 
694 	fenceable = (i915_vma_size(vma) >= vma->fence_size &&
695 		     IS_ALIGNED(i915_vma_offset(vma), vma->fence_alignment));
696 
697 	mappable = i915_ggtt_offset(vma) + vma->fence_size <=
698 		   i915_vm_to_ggtt(vma->vm)->mappable_end;
699 
700 	if (mappable && fenceable)
701 		set_bit(I915_VMA_CAN_FENCE_BIT, __i915_vma_flags(vma));
702 	else
703 		clear_bit(I915_VMA_CAN_FENCE_BIT, __i915_vma_flags(vma));
704 }
705 
706 bool i915_gem_valid_gtt_space(struct i915_vma *vma, unsigned long color)
707 {
708 	struct drm_mm_node *node = &vma->node;
709 	struct drm_mm_node *other;
710 
711 	/*
712 	 * On some machines we have to be careful when putting differing types
713 	 * of snoopable memory together to avoid the prefetcher crossing memory
714 	 * domains and dying. During vm initialisation, we decide whether or not
715 	 * these constraints apply and set the drm_mm.color_adjust
716 	 * appropriately.
717 	 */
718 	if (!i915_vm_has_cache_coloring(vma->vm))
719 		return true;
720 
721 	/* Only valid to be called on an already inserted vma */
722 	GEM_BUG_ON(!drm_mm_node_allocated(node));
723 	GEM_BUG_ON(list_empty(&node->node_list));
724 
725 	other = list_prev_entry(node, node_list);
726 	if (i915_node_color_differs(other, color) &&
727 	    !drm_mm_hole_follows(other))
728 		return false;
729 
730 	other = list_next_entry(node, node_list);
731 	if (i915_node_color_differs(other, color) &&
732 	    !drm_mm_hole_follows(node))
733 		return false;
734 
735 	return true;
736 }
737 
738 /**
739  * i915_vma_insert - finds a slot for the vma in its address space
740  * @vma: the vma
741  * @size: requested size in bytes (can be larger than the VMA)
742  * @alignment: required alignment
743  * @flags: mask of PIN_* flags to use
744  *
745  * First we try to allocate some free space that meets the requirements for
746  * the VMA. Failiing that, if the flags permit, it will evict an old VMA,
747  * preferrably the oldest idle entry to make room for the new VMA.
748  *
749  * Returns:
750  * 0 on success, negative error code otherwise.
751  */
752 static int
753 i915_vma_insert(struct i915_vma *vma, struct i915_gem_ww_ctx *ww,
754 		u64 size, u64 alignment, u64 flags)
755 {
756 	unsigned long color, guard;
757 	u64 start, end;
758 	int ret;
759 
760 	GEM_BUG_ON(i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND | I915_VMA_LOCAL_BIND));
761 	GEM_BUG_ON(drm_mm_node_allocated(&vma->node));
762 	GEM_BUG_ON(hweight64(flags & (PIN_OFFSET_GUARD | PIN_OFFSET_FIXED | PIN_OFFSET_BIAS)) > 1);
763 
764 	size = max(size, vma->size);
765 	alignment = max_t(typeof(alignment), alignment, vma->display_alignment);
766 	if (flags & PIN_MAPPABLE) {
767 		size = max_t(typeof(size), size, vma->fence_size);
768 		alignment = max_t(typeof(alignment),
769 				  alignment, vma->fence_alignment);
770 	}
771 
772 	GEM_BUG_ON(!IS_ALIGNED(size, I915_GTT_PAGE_SIZE));
773 	GEM_BUG_ON(!IS_ALIGNED(alignment, I915_GTT_MIN_ALIGNMENT));
774 	GEM_BUG_ON(!is_power_of_2(alignment));
775 
776 	guard = vma->guard; /* retain guard across rebinds */
777 	if (flags & PIN_OFFSET_GUARD) {
778 		GEM_BUG_ON(overflows_type(flags & PIN_OFFSET_MASK, u32));
779 		guard = max_t(u32, guard, flags & PIN_OFFSET_MASK);
780 	}
781 	/*
782 	 * As we align the node upon insertion, but the hardware gets
783 	 * node.start + guard, the easiest way to make that work is
784 	 * to make the guard a multiple of the alignment size.
785 	 */
786 	guard = ALIGN(guard, alignment);
787 
788 	start = flags & PIN_OFFSET_BIAS ? flags & PIN_OFFSET_MASK : 0;
789 	GEM_BUG_ON(!IS_ALIGNED(start, I915_GTT_PAGE_SIZE));
790 
791 	end = vma->vm->total;
792 	if (flags & PIN_MAPPABLE)
793 		end = min_t(u64, end, i915_vm_to_ggtt(vma->vm)->mappable_end);
794 	if (flags & PIN_ZONE_4G)
795 		end = min_t(u64, end, (1ULL << 32) - I915_GTT_PAGE_SIZE);
796 	GEM_BUG_ON(!IS_ALIGNED(end, I915_GTT_PAGE_SIZE));
797 
798 	alignment = max(alignment, i915_vm_obj_min_alignment(vma->vm, vma->obj));
799 
800 	/*
801 	 * If binding the object/GGTT view requires more space than the entire
802 	 * aperture has, reject it early before evicting everything in a vain
803 	 * attempt to find space.
804 	 */
805 	if (size > end - 2 * guard) {
806 		drm_dbg(&to_i915(vma->obj->base.dev)->drm,
807 			"Attempting to bind an object larger than the aperture: request=%llu > %s aperture=%llu\n",
808 			size, flags & PIN_MAPPABLE ? "mappable" : "total", end);
809 		return -ENOSPC;
810 	}
811 
812 	color = 0;
813 
814 	if (i915_vm_has_cache_coloring(vma->vm))
815 		color = vma->obj->cache_level;
816 
817 	if (flags & PIN_OFFSET_FIXED) {
818 		u64 offset = flags & PIN_OFFSET_MASK;
819 		if (!IS_ALIGNED(offset, alignment) ||
820 		    range_overflows(offset, size, end))
821 			return -EINVAL;
822 		/*
823 		 * The caller knows not of the guard added by others and
824 		 * requests for the offset of the start of its buffer
825 		 * to be fixed, which may not be the same as the position
826 		 * of the vma->node due to the guard pages.
827 		 */
828 		if (offset < guard || offset + size > end - guard)
829 			return -ENOSPC;
830 
831 		ret = i915_gem_gtt_reserve(vma->vm, ww, &vma->node,
832 					   size + 2 * guard,
833 					   offset - guard,
834 					   color, flags);
835 		if (ret)
836 			return ret;
837 	} else {
838 		size += 2 * guard;
839 		/*
840 		 * We only support huge gtt pages through the 48b PPGTT,
841 		 * however we also don't want to force any alignment for
842 		 * objects which need to be tightly packed into the low 32bits.
843 		 *
844 		 * Note that we assume that GGTT are limited to 4GiB for the
845 		 * forseeable future. See also i915_ggtt_offset().
846 		 */
847 		if (upper_32_bits(end - 1) &&
848 		    vma->page_sizes.sg > I915_GTT_PAGE_SIZE &&
849 		    !HAS_64K_PAGES(vma->vm->i915)) {
850 			/*
851 			 * We can't mix 64K and 4K PTEs in the same page-table
852 			 * (2M block), and so to avoid the ugliness and
853 			 * complexity of coloring we opt for just aligning 64K
854 			 * objects to 2M.
855 			 */
856 			u64 page_alignment =
857 				rounddown_pow_of_two(vma->page_sizes.sg |
858 						     I915_GTT_PAGE_SIZE_2M);
859 
860 			/*
861 			 * Check we don't expand for the limited Global GTT
862 			 * (mappable aperture is even more precious!). This
863 			 * also checks that we exclude the aliasing-ppgtt.
864 			 */
865 			GEM_BUG_ON(i915_vma_is_ggtt(vma));
866 
867 			alignment = max(alignment, page_alignment);
868 
869 			if (vma->page_sizes.sg & I915_GTT_PAGE_SIZE_64K)
870 				size = round_up(size, I915_GTT_PAGE_SIZE_2M);
871 		}
872 
873 		ret = i915_gem_gtt_insert(vma->vm, ww, &vma->node,
874 					  size, alignment, color,
875 					  start, end, flags);
876 		if (ret)
877 			return ret;
878 
879 		GEM_BUG_ON(vma->node.start < start);
880 		GEM_BUG_ON(vma->node.start + vma->node.size > end);
881 	}
882 	GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
883 	GEM_BUG_ON(!i915_gem_valid_gtt_space(vma, color));
884 
885 	list_move_tail(&vma->vm_link, &vma->vm->bound_list);
886 	vma->guard = guard;
887 
888 	return 0;
889 }
890 
891 static void
892 i915_vma_detach(struct i915_vma *vma)
893 {
894 	GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
895 	GEM_BUG_ON(i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND | I915_VMA_LOCAL_BIND));
896 
897 	/*
898 	 * And finally now the object is completely decoupled from this
899 	 * vma, we can drop its hold on the backing storage and allow
900 	 * it to be reaped by the shrinker.
901 	 */
902 	list_move_tail(&vma->vm_link, &vma->vm->unbound_list);
903 }
904 
905 static bool try_qad_pin(struct i915_vma *vma, unsigned int flags)
906 {
907 	unsigned int bound;
908 
909 	bound = atomic_read(&vma->flags);
910 
911 	if (flags & PIN_VALIDATE) {
912 		flags &= I915_VMA_BIND_MASK;
913 
914 		return (flags & bound) == flags;
915 	}
916 
917 	/* with the lock mandatory for unbind, we don't race here */
918 	flags &= I915_VMA_BIND_MASK;
919 	do {
920 		if (unlikely(flags & ~bound))
921 			return false;
922 
923 		if (unlikely(bound & (I915_VMA_OVERFLOW | I915_VMA_ERROR)))
924 			return false;
925 
926 		GEM_BUG_ON(((bound + 1) & I915_VMA_PIN_MASK) == 0);
927 	} while (!atomic_try_cmpxchg(&vma->flags, &bound, bound + 1));
928 
929 	return true;
930 }
931 
932 static struct scatterlist *
933 rotate_pages(struct drm_i915_gem_object *obj, unsigned int offset,
934 	     unsigned int width, unsigned int height,
935 	     unsigned int src_stride, unsigned int dst_stride,
936 	     struct sg_table *st, struct scatterlist *sg)
937 {
938 	unsigned int column, row;
939 	pgoff_t src_idx;
940 
941 	for (column = 0; column < width; column++) {
942 		unsigned int left;
943 
944 		src_idx = src_stride * (height - 1) + column + offset;
945 		for (row = 0; row < height; row++) {
946 			st->nents++;
947 			/*
948 			 * We don't need the pages, but need to initialize
949 			 * the entries so the sg list can be happily traversed.
950 			 * The only thing we need are DMA addresses.
951 			 */
952 			sg_set_page(sg, NULL, I915_GTT_PAGE_SIZE, 0);
953 			sg_dma_address(sg) =
954 				i915_gem_object_get_dma_address(obj, src_idx);
955 			sg_dma_len(sg) = I915_GTT_PAGE_SIZE;
956 			sg = sg_next(sg);
957 			src_idx -= src_stride;
958 		}
959 
960 		left = (dst_stride - height) * I915_GTT_PAGE_SIZE;
961 
962 		if (!left)
963 			continue;
964 
965 		st->nents++;
966 
967 		/*
968 		 * The DE ignores the PTEs for the padding tiles, the sg entry
969 		 * here is just a conenience to indicate how many padding PTEs
970 		 * to insert at this spot.
971 		 */
972 		sg_set_page(sg, NULL, left, 0);
973 		sg_dma_address(sg) = 0;
974 		sg_dma_len(sg) = left;
975 		sg = sg_next(sg);
976 	}
977 
978 	return sg;
979 }
980 
981 static noinline struct sg_table *
982 intel_rotate_pages(struct intel_rotation_info *rot_info,
983 		   struct drm_i915_gem_object *obj)
984 {
985 	unsigned int size = intel_rotation_info_size(rot_info);
986 	struct drm_i915_private *i915 = to_i915(obj->base.dev);
987 	struct sg_table *st;
988 	struct scatterlist *sg;
989 	int ret = -ENOMEM;
990 	int i;
991 
992 	/* Allocate target SG list. */
993 	st = kmalloc(sizeof(*st), GFP_KERNEL);
994 	if (!st)
995 		goto err_st_alloc;
996 
997 	ret = sg_alloc_table(st, size, GFP_KERNEL);
998 	if (ret)
999 		goto err_sg_alloc;
1000 
1001 	st->nents = 0;
1002 	sg = st->sgl;
1003 
1004 	for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
1005 		sg = rotate_pages(obj, rot_info->plane[i].offset,
1006 				  rot_info->plane[i].width, rot_info->plane[i].height,
1007 				  rot_info->plane[i].src_stride,
1008 				  rot_info->plane[i].dst_stride,
1009 				  st, sg);
1010 
1011 	return st;
1012 
1013 err_sg_alloc:
1014 	kfree(st);
1015 err_st_alloc:
1016 
1017 	drm_dbg(&i915->drm, "Failed to create rotated mapping for object size %zu! (%ux%u tiles, %u pages)\n",
1018 		obj->base.size, rot_info->plane[0].width,
1019 		rot_info->plane[0].height, size);
1020 
1021 	return ERR_PTR(ret);
1022 }
1023 
1024 static struct scatterlist *
1025 add_padding_pages(unsigned int count,
1026 		  struct sg_table *st, struct scatterlist *sg)
1027 {
1028 	st->nents++;
1029 
1030 	/*
1031 	 * The DE ignores the PTEs for the padding tiles, the sg entry
1032 	 * here is just a convenience to indicate how many padding PTEs
1033 	 * to insert at this spot.
1034 	 */
1035 	sg_set_page(sg, NULL, count * I915_GTT_PAGE_SIZE, 0);
1036 	sg_dma_address(sg) = 0;
1037 	sg_dma_len(sg) = count * I915_GTT_PAGE_SIZE;
1038 	sg = sg_next(sg);
1039 
1040 	return sg;
1041 }
1042 
1043 static struct scatterlist *
1044 remap_tiled_color_plane_pages(struct drm_i915_gem_object *obj,
1045 			      unsigned long offset, unsigned int alignment_pad,
1046 			      unsigned int width, unsigned int height,
1047 			      unsigned int src_stride, unsigned int dst_stride,
1048 			      struct sg_table *st, struct scatterlist *sg,
1049 			      unsigned int *gtt_offset)
1050 {
1051 	unsigned int row;
1052 
1053 	if (!width || !height)
1054 		return sg;
1055 
1056 	if (alignment_pad)
1057 		sg = add_padding_pages(alignment_pad, st, sg);
1058 
1059 	for (row = 0; row < height; row++) {
1060 		unsigned int left = width * I915_GTT_PAGE_SIZE;
1061 
1062 		while (left) {
1063 			dma_addr_t addr;
1064 			unsigned int length;
1065 
1066 			/*
1067 			 * We don't need the pages, but need to initialize
1068 			 * the entries so the sg list can be happily traversed.
1069 			 * The only thing we need are DMA addresses.
1070 			 */
1071 
1072 			addr = i915_gem_object_get_dma_address_len(obj, offset, &length);
1073 
1074 			length = min(left, length);
1075 
1076 			st->nents++;
1077 
1078 			sg_set_page(sg, NULL, length, 0);
1079 			sg_dma_address(sg) = addr;
1080 			sg_dma_len(sg) = length;
1081 			sg = sg_next(sg);
1082 
1083 			offset += length / I915_GTT_PAGE_SIZE;
1084 			left -= length;
1085 		}
1086 
1087 		offset += src_stride - width;
1088 
1089 		left = (dst_stride - width) * I915_GTT_PAGE_SIZE;
1090 
1091 		if (!left)
1092 			continue;
1093 
1094 		sg = add_padding_pages(left >> PAGE_SHIFT, st, sg);
1095 	}
1096 
1097 	*gtt_offset += alignment_pad + dst_stride * height;
1098 
1099 	return sg;
1100 }
1101 
1102 static struct scatterlist *
1103 remap_contiguous_pages(struct drm_i915_gem_object *obj,
1104 		       pgoff_t obj_offset,
1105 		       unsigned int count,
1106 		       struct sg_table *st, struct scatterlist *sg)
1107 {
1108 	struct scatterlist *iter;
1109 	unsigned int offset;
1110 
1111 	iter = i915_gem_object_get_sg_dma(obj, obj_offset, &offset);
1112 	GEM_BUG_ON(!iter);
1113 
1114 	do {
1115 		unsigned int len;
1116 
1117 		len = min(sg_dma_len(iter) - (offset << PAGE_SHIFT),
1118 			  count << PAGE_SHIFT);
1119 		sg_set_page(sg, NULL, len, 0);
1120 		sg_dma_address(sg) =
1121 			sg_dma_address(iter) + (offset << PAGE_SHIFT);
1122 		sg_dma_len(sg) = len;
1123 
1124 		st->nents++;
1125 		count -= len >> PAGE_SHIFT;
1126 		if (count == 0)
1127 			return sg;
1128 
1129 		sg = __sg_next(sg);
1130 		iter = __sg_next(iter);
1131 		offset = 0;
1132 	} while (1);
1133 }
1134 
1135 static struct scatterlist *
1136 remap_linear_color_plane_pages(struct drm_i915_gem_object *obj,
1137 			       pgoff_t obj_offset, unsigned int alignment_pad,
1138 			       unsigned int size,
1139 			       struct sg_table *st, struct scatterlist *sg,
1140 			       unsigned int *gtt_offset)
1141 {
1142 	if (!size)
1143 		return sg;
1144 
1145 	if (alignment_pad)
1146 		sg = add_padding_pages(alignment_pad, st, sg);
1147 
1148 	sg = remap_contiguous_pages(obj, obj_offset, size, st, sg);
1149 	sg = sg_next(sg);
1150 
1151 	*gtt_offset += alignment_pad + size;
1152 
1153 	return sg;
1154 }
1155 
1156 static struct scatterlist *
1157 remap_color_plane_pages(const struct intel_remapped_info *rem_info,
1158 			struct drm_i915_gem_object *obj,
1159 			int color_plane,
1160 			struct sg_table *st, struct scatterlist *sg,
1161 			unsigned int *gtt_offset)
1162 {
1163 	unsigned int alignment_pad = 0;
1164 
1165 	if (rem_info->plane_alignment)
1166 		alignment_pad = ALIGN(*gtt_offset, rem_info->plane_alignment) - *gtt_offset;
1167 
1168 	if (rem_info->plane[color_plane].linear)
1169 		sg = remap_linear_color_plane_pages(obj,
1170 						    rem_info->plane[color_plane].offset,
1171 						    alignment_pad,
1172 						    rem_info->plane[color_plane].size,
1173 						    st, sg,
1174 						    gtt_offset);
1175 
1176 	else
1177 		sg = remap_tiled_color_plane_pages(obj,
1178 						   rem_info->plane[color_plane].offset,
1179 						   alignment_pad,
1180 						   rem_info->plane[color_plane].width,
1181 						   rem_info->plane[color_plane].height,
1182 						   rem_info->plane[color_plane].src_stride,
1183 						   rem_info->plane[color_plane].dst_stride,
1184 						   st, sg,
1185 						   gtt_offset);
1186 
1187 	return sg;
1188 }
1189 
1190 static noinline struct sg_table *
1191 intel_remap_pages(struct intel_remapped_info *rem_info,
1192 		  struct drm_i915_gem_object *obj)
1193 {
1194 	unsigned int size = intel_remapped_info_size(rem_info);
1195 	struct drm_i915_private *i915 = to_i915(obj->base.dev);
1196 	struct sg_table *st;
1197 	struct scatterlist *sg;
1198 	unsigned int gtt_offset = 0;
1199 	int ret = -ENOMEM;
1200 	int i;
1201 
1202 	/* Allocate target SG list. */
1203 	st = kmalloc(sizeof(*st), GFP_KERNEL);
1204 	if (!st)
1205 		goto err_st_alloc;
1206 
1207 	ret = sg_alloc_table(st, size, GFP_KERNEL);
1208 	if (ret)
1209 		goto err_sg_alloc;
1210 
1211 	st->nents = 0;
1212 	sg = st->sgl;
1213 
1214 	for (i = 0 ; i < ARRAY_SIZE(rem_info->plane); i++)
1215 		sg = remap_color_plane_pages(rem_info, obj, i, st, sg, &gtt_offset);
1216 
1217 	i915_sg_trim(st);
1218 
1219 	return st;
1220 
1221 err_sg_alloc:
1222 	kfree(st);
1223 err_st_alloc:
1224 
1225 	drm_dbg(&i915->drm, "Failed to create remapped mapping for object size %zu! (%ux%u tiles, %u pages)\n",
1226 		obj->base.size, rem_info->plane[0].width,
1227 		rem_info->plane[0].height, size);
1228 
1229 	return ERR_PTR(ret);
1230 }
1231 
1232 static noinline struct sg_table *
1233 intel_partial_pages(const struct i915_gtt_view *view,
1234 		    struct drm_i915_gem_object *obj)
1235 {
1236 	struct sg_table *st;
1237 	struct scatterlist *sg;
1238 	unsigned int count = view->partial.size;
1239 	int ret = -ENOMEM;
1240 
1241 	st = kmalloc(sizeof(*st), GFP_KERNEL);
1242 	if (!st)
1243 		goto err_st_alloc;
1244 
1245 	ret = sg_alloc_table(st, count, GFP_KERNEL);
1246 	if (ret)
1247 		goto err_sg_alloc;
1248 
1249 	st->nents = 0;
1250 
1251 	sg = remap_contiguous_pages(obj, view->partial.offset, count, st, st->sgl);
1252 
1253 	sg_mark_end(sg);
1254 	i915_sg_trim(st); /* Drop any unused tail entries. */
1255 
1256 	return st;
1257 
1258 err_sg_alloc:
1259 	kfree(st);
1260 err_st_alloc:
1261 	return ERR_PTR(ret);
1262 }
1263 
1264 static int
1265 __i915_vma_get_pages(struct i915_vma *vma)
1266 {
1267 	struct sg_table *pages;
1268 
1269 	/*
1270 	 * The vma->pages are only valid within the lifespan of the borrowed
1271 	 * obj->mm.pages. When the obj->mm.pages sg_table is regenerated, so
1272 	 * must be the vma->pages. A simple rule is that vma->pages must only
1273 	 * be accessed when the obj->mm.pages are pinned.
1274 	 */
1275 	GEM_BUG_ON(!i915_gem_object_has_pinned_pages(vma->obj));
1276 
1277 	switch (vma->gtt_view.type) {
1278 	default:
1279 		GEM_BUG_ON(vma->gtt_view.type);
1280 		fallthrough;
1281 	case I915_GTT_VIEW_NORMAL:
1282 		pages = vma->obj->mm.pages;
1283 		break;
1284 
1285 	case I915_GTT_VIEW_ROTATED:
1286 		pages =
1287 			intel_rotate_pages(&vma->gtt_view.rotated, vma->obj);
1288 		break;
1289 
1290 	case I915_GTT_VIEW_REMAPPED:
1291 		pages =
1292 			intel_remap_pages(&vma->gtt_view.remapped, vma->obj);
1293 		break;
1294 
1295 	case I915_GTT_VIEW_PARTIAL:
1296 		pages = intel_partial_pages(&vma->gtt_view, vma->obj);
1297 		break;
1298 	}
1299 
1300 	if (IS_ERR(pages)) {
1301 		drm_err(&vma->vm->i915->drm,
1302 			"Failed to get pages for VMA view type %u (%ld)!\n",
1303 			vma->gtt_view.type, PTR_ERR(pages));
1304 		return PTR_ERR(pages);
1305 	}
1306 
1307 	vma->pages = pages;
1308 
1309 	return 0;
1310 }
1311 
1312 I915_SELFTEST_EXPORT int i915_vma_get_pages(struct i915_vma *vma)
1313 {
1314 	int err;
1315 
1316 	if (atomic_add_unless(&vma->pages_count, 1, 0))
1317 		return 0;
1318 
1319 	err = i915_gem_object_pin_pages(vma->obj);
1320 	if (err)
1321 		return err;
1322 
1323 	err = __i915_vma_get_pages(vma);
1324 	if (err)
1325 		goto err_unpin;
1326 
1327 	vma->page_sizes = vma->obj->mm.page_sizes;
1328 	atomic_inc(&vma->pages_count);
1329 
1330 	return 0;
1331 
1332 err_unpin:
1333 	__i915_gem_object_unpin_pages(vma->obj);
1334 
1335 	return err;
1336 }
1337 
1338 void vma_invalidate_tlb(struct i915_address_space *vm, u32 *tlb)
1339 {
1340 	/*
1341 	 * Before we release the pages that were bound by this vma, we
1342 	 * must invalidate all the TLBs that may still have a reference
1343 	 * back to our physical address. It only needs to be done once,
1344 	 * so after updating the PTE to point away from the pages, record
1345 	 * the most recent TLB invalidation seqno, and if we have not yet
1346 	 * flushed the TLBs upon release, perform a full invalidation.
1347 	 */
1348 	WRITE_ONCE(*tlb, intel_gt_next_invalidate_tlb_full(vm->gt));
1349 }
1350 
1351 static void __vma_put_pages(struct i915_vma *vma, unsigned int count)
1352 {
1353 	/* We allocate under vma_get_pages, so beware the shrinker */
1354 	GEM_BUG_ON(atomic_read(&vma->pages_count) < count);
1355 
1356 	if (atomic_sub_return(count, &vma->pages_count) == 0) {
1357 		if (vma->pages != vma->obj->mm.pages) {
1358 			sg_free_table(vma->pages);
1359 			kfree(vma->pages);
1360 		}
1361 		vma->pages = NULL;
1362 
1363 		i915_gem_object_unpin_pages(vma->obj);
1364 	}
1365 }
1366 
1367 I915_SELFTEST_EXPORT void i915_vma_put_pages(struct i915_vma *vma)
1368 {
1369 	if (atomic_add_unless(&vma->pages_count, -1, 1))
1370 		return;
1371 
1372 	__vma_put_pages(vma, 1);
1373 }
1374 
1375 static void vma_unbind_pages(struct i915_vma *vma)
1376 {
1377 	unsigned int count;
1378 
1379 	lockdep_assert_held(&vma->vm->mutex);
1380 
1381 	/* The upper portion of pages_count is the number of bindings */
1382 	count = atomic_read(&vma->pages_count);
1383 	count >>= I915_VMA_PAGES_BIAS;
1384 	GEM_BUG_ON(!count);
1385 
1386 	__vma_put_pages(vma, count | count << I915_VMA_PAGES_BIAS);
1387 }
1388 
1389 int i915_vma_pin_ww(struct i915_vma *vma, struct i915_gem_ww_ctx *ww,
1390 		    u64 size, u64 alignment, u64 flags)
1391 {
1392 	struct i915_vma_work *work = NULL;
1393 	struct dma_fence *moving = NULL;
1394 	struct i915_vma_resource *vma_res = NULL;
1395 	intel_wakeref_t wakeref = 0;
1396 	unsigned int bound;
1397 	int err;
1398 
1399 	assert_vma_held(vma);
1400 	GEM_BUG_ON(!ww);
1401 
1402 	BUILD_BUG_ON(PIN_GLOBAL != I915_VMA_GLOBAL_BIND);
1403 	BUILD_BUG_ON(PIN_USER != I915_VMA_LOCAL_BIND);
1404 
1405 	GEM_BUG_ON(!(flags & (PIN_USER | PIN_GLOBAL)));
1406 
1407 	/* First try and grab the pin without rebinding the vma */
1408 	if (try_qad_pin(vma, flags))
1409 		return 0;
1410 
1411 	err = i915_vma_get_pages(vma);
1412 	if (err)
1413 		return err;
1414 
1415 	if (flags & PIN_GLOBAL)
1416 		wakeref = intel_runtime_pm_get(&vma->vm->i915->runtime_pm);
1417 
1418 	if (flags & vma->vm->bind_async_flags) {
1419 		/* lock VM */
1420 		err = i915_vm_lock_objects(vma->vm, ww);
1421 		if (err)
1422 			goto err_rpm;
1423 
1424 		work = i915_vma_work();
1425 		if (!work) {
1426 			err = -ENOMEM;
1427 			goto err_rpm;
1428 		}
1429 
1430 		work->vm = vma->vm;
1431 
1432 		err = i915_gem_object_get_moving_fence(vma->obj, &moving);
1433 		if (err)
1434 			goto err_rpm;
1435 
1436 		dma_fence_work_chain(&work->base, moving);
1437 
1438 		/* Allocate enough page directories to used PTE */
1439 		if (vma->vm->allocate_va_range) {
1440 			err = i915_vm_alloc_pt_stash(vma->vm,
1441 						     &work->stash,
1442 						     vma->size);
1443 			if (err)
1444 				goto err_fence;
1445 
1446 			err = i915_vm_map_pt_stash(vma->vm, &work->stash);
1447 			if (err)
1448 				goto err_fence;
1449 		}
1450 	}
1451 
1452 	vma_res = i915_vma_resource_alloc();
1453 	if (IS_ERR(vma_res)) {
1454 		err = PTR_ERR(vma_res);
1455 		goto err_fence;
1456 	}
1457 
1458 	/*
1459 	 * Differentiate between user/kernel vma inside the aliasing-ppgtt.
1460 	 *
1461 	 * We conflate the Global GTT with the user's vma when using the
1462 	 * aliasing-ppgtt, but it is still vitally important to try and
1463 	 * keep the use cases distinct. For example, userptr objects are
1464 	 * not allowed inside the Global GTT as that will cause lock
1465 	 * inversions when we have to evict them the mmu_notifier callbacks -
1466 	 * but they are allowed to be part of the user ppGTT which can never
1467 	 * be mapped. As such we try to give the distinct users of the same
1468 	 * mutex, distinct lockclasses [equivalent to how we keep i915_ggtt
1469 	 * and i915_ppgtt separate].
1470 	 *
1471 	 * NB this may cause us to mask real lock inversions -- while the
1472 	 * code is safe today, lockdep may not be able to spot future
1473 	 * transgressions.
1474 	 */
1475 	err = mutex_lock_interruptible_nested(&vma->vm->mutex,
1476 					      !(flags & PIN_GLOBAL));
1477 	if (err)
1478 		goto err_vma_res;
1479 
1480 	/* No more allocations allowed now we hold vm->mutex */
1481 
1482 	if (unlikely(i915_vma_is_closed(vma))) {
1483 		err = -ENOENT;
1484 		goto err_unlock;
1485 	}
1486 
1487 	bound = atomic_read(&vma->flags);
1488 	if (unlikely(bound & I915_VMA_ERROR)) {
1489 		err = -ENOMEM;
1490 		goto err_unlock;
1491 	}
1492 
1493 	if (unlikely(!((bound + 1) & I915_VMA_PIN_MASK))) {
1494 		err = -EAGAIN; /* pins are meant to be fairly temporary */
1495 		goto err_unlock;
1496 	}
1497 
1498 	if (unlikely(!(flags & ~bound & I915_VMA_BIND_MASK))) {
1499 		if (!(flags & PIN_VALIDATE))
1500 			__i915_vma_pin(vma);
1501 		goto err_unlock;
1502 	}
1503 
1504 	err = i915_active_acquire(&vma->active);
1505 	if (err)
1506 		goto err_unlock;
1507 
1508 	if (!(bound & I915_VMA_BIND_MASK)) {
1509 		err = i915_vma_insert(vma, ww, size, alignment, flags);
1510 		if (err)
1511 			goto err_active;
1512 
1513 		if (i915_is_ggtt(vma->vm))
1514 			__i915_vma_set_map_and_fenceable(vma);
1515 	}
1516 
1517 	GEM_BUG_ON(!vma->pages);
1518 	err = i915_vma_bind(vma,
1519 			    vma->obj->cache_level,
1520 			    flags, work, vma_res);
1521 	vma_res = NULL;
1522 	if (err)
1523 		goto err_remove;
1524 
1525 	/* There should only be at most 2 active bindings (user, global) */
1526 	GEM_BUG_ON(bound + I915_VMA_PAGES_ACTIVE < bound);
1527 	atomic_add(I915_VMA_PAGES_ACTIVE, &vma->pages_count);
1528 	list_move_tail(&vma->vm_link, &vma->vm->bound_list);
1529 
1530 	if (!(flags & PIN_VALIDATE)) {
1531 		__i915_vma_pin(vma);
1532 		GEM_BUG_ON(!i915_vma_is_pinned(vma));
1533 	}
1534 	GEM_BUG_ON(!i915_vma_is_bound(vma, flags));
1535 	GEM_BUG_ON(i915_vma_misplaced(vma, size, alignment, flags));
1536 
1537 err_remove:
1538 	if (!i915_vma_is_bound(vma, I915_VMA_BIND_MASK)) {
1539 		i915_vma_detach(vma);
1540 		drm_mm_remove_node(&vma->node);
1541 	}
1542 err_active:
1543 	i915_active_release(&vma->active);
1544 err_unlock:
1545 	mutex_unlock(&vma->vm->mutex);
1546 err_vma_res:
1547 	i915_vma_resource_free(vma_res);
1548 err_fence:
1549 	if (work)
1550 		dma_fence_work_commit_imm(&work->base);
1551 err_rpm:
1552 	if (wakeref)
1553 		intel_runtime_pm_put(&vma->vm->i915->runtime_pm, wakeref);
1554 
1555 	if (moving)
1556 		dma_fence_put(moving);
1557 
1558 	i915_vma_put_pages(vma);
1559 	return err;
1560 }
1561 
1562 static void flush_idle_contexts(struct intel_gt *gt)
1563 {
1564 	struct intel_engine_cs *engine;
1565 	enum intel_engine_id id;
1566 
1567 	for_each_engine(engine, gt, id)
1568 		intel_engine_flush_barriers(engine);
1569 
1570 	intel_gt_wait_for_idle(gt, MAX_SCHEDULE_TIMEOUT);
1571 }
1572 
1573 static int __i915_ggtt_pin(struct i915_vma *vma, struct i915_gem_ww_ctx *ww,
1574 			   u32 align, unsigned int flags)
1575 {
1576 	struct i915_address_space *vm = vma->vm;
1577 	struct intel_gt *gt;
1578 	struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
1579 	int err;
1580 
1581 	do {
1582 		err = i915_vma_pin_ww(vma, ww, 0, align, flags | PIN_GLOBAL);
1583 
1584 		if (err != -ENOSPC) {
1585 			if (!err) {
1586 				err = i915_vma_wait_for_bind(vma);
1587 				if (err)
1588 					i915_vma_unpin(vma);
1589 			}
1590 			return err;
1591 		}
1592 
1593 		/* Unlike i915_vma_pin, we don't take no for an answer! */
1594 		list_for_each_entry(gt, &ggtt->gt_list, ggtt_link)
1595 			flush_idle_contexts(gt);
1596 		if (mutex_lock_interruptible(&vm->mutex) == 0) {
1597 			/*
1598 			 * We pass NULL ww here, as we don't want to unbind
1599 			 * locked objects when called from execbuf when pinning
1600 			 * is removed. This would probably regress badly.
1601 			 */
1602 			i915_gem_evict_vm(vm, NULL, NULL);
1603 			mutex_unlock(&vm->mutex);
1604 		}
1605 	} while (1);
1606 }
1607 
1608 int i915_ggtt_pin(struct i915_vma *vma, struct i915_gem_ww_ctx *ww,
1609 		  u32 align, unsigned int flags)
1610 {
1611 	struct i915_gem_ww_ctx _ww;
1612 	int err;
1613 
1614 	GEM_BUG_ON(!i915_vma_is_ggtt(vma));
1615 
1616 	if (ww)
1617 		return __i915_ggtt_pin(vma, ww, align, flags);
1618 
1619 	lockdep_assert_not_held(&vma->obj->base.resv->lock.base);
1620 
1621 	for_i915_gem_ww(&_ww, err, true) {
1622 		err = i915_gem_object_lock(vma->obj, &_ww);
1623 		if (!err)
1624 			err = __i915_ggtt_pin(vma, &_ww, align, flags);
1625 	}
1626 
1627 	return err;
1628 }
1629 
1630 static void __vma_close(struct i915_vma *vma, struct intel_gt *gt)
1631 {
1632 	/*
1633 	 * We defer actually closing, unbinding and destroying the VMA until
1634 	 * the next idle point, or if the object is freed in the meantime. By
1635 	 * postponing the unbind, we allow for it to be resurrected by the
1636 	 * client, avoiding the work required to rebind the VMA. This is
1637 	 * advantageous for DRI, where the client/server pass objects
1638 	 * between themselves, temporarily opening a local VMA to the
1639 	 * object, and then closing it again. The same object is then reused
1640 	 * on the next frame (or two, depending on the depth of the swap queue)
1641 	 * causing us to rebind the VMA once more. This ends up being a lot
1642 	 * of wasted work for the steady state.
1643 	 */
1644 	GEM_BUG_ON(i915_vma_is_closed(vma));
1645 	list_add(&vma->closed_link, &gt->closed_vma);
1646 }
1647 
1648 void i915_vma_close(struct i915_vma *vma)
1649 {
1650 	struct intel_gt *gt = vma->vm->gt;
1651 	unsigned long flags;
1652 
1653 	if (i915_vma_is_ggtt(vma))
1654 		return;
1655 
1656 	GEM_BUG_ON(!atomic_read(&vma->open_count));
1657 	if (atomic_dec_and_lock_irqsave(&vma->open_count,
1658 					&gt->closed_lock,
1659 					flags)) {
1660 		__vma_close(vma, gt);
1661 		spin_unlock_irqrestore(&gt->closed_lock, flags);
1662 	}
1663 }
1664 
1665 static void __i915_vma_remove_closed(struct i915_vma *vma)
1666 {
1667 	list_del_init(&vma->closed_link);
1668 }
1669 
1670 void i915_vma_reopen(struct i915_vma *vma)
1671 {
1672 	struct intel_gt *gt = vma->vm->gt;
1673 
1674 	spin_lock_irq(&gt->closed_lock);
1675 	if (i915_vma_is_closed(vma))
1676 		__i915_vma_remove_closed(vma);
1677 	spin_unlock_irq(&gt->closed_lock);
1678 }
1679 
1680 static void force_unbind(struct i915_vma *vma)
1681 {
1682 	if (!drm_mm_node_allocated(&vma->node))
1683 		return;
1684 
1685 	atomic_and(~I915_VMA_PIN_MASK, &vma->flags);
1686 	WARN_ON(__i915_vma_unbind(vma));
1687 	GEM_BUG_ON(drm_mm_node_allocated(&vma->node));
1688 }
1689 
1690 static void release_references(struct i915_vma *vma, struct intel_gt *gt,
1691 			       bool vm_ddestroy)
1692 {
1693 	struct drm_i915_gem_object *obj = vma->obj;
1694 
1695 	GEM_BUG_ON(i915_vma_is_active(vma));
1696 
1697 	spin_lock(&obj->vma.lock);
1698 	list_del(&vma->obj_link);
1699 	if (!RB_EMPTY_NODE(&vma->obj_node))
1700 		rb_erase(&vma->obj_node, &obj->vma.tree);
1701 
1702 	spin_unlock(&obj->vma.lock);
1703 
1704 	spin_lock_irq(&gt->closed_lock);
1705 	__i915_vma_remove_closed(vma);
1706 	spin_unlock_irq(&gt->closed_lock);
1707 
1708 	if (vm_ddestroy)
1709 		i915_vm_resv_put(vma->vm);
1710 
1711 	i915_active_fini(&vma->active);
1712 	GEM_WARN_ON(vma->resource);
1713 	i915_vma_free(vma);
1714 }
1715 
1716 /**
1717  * i915_vma_destroy_locked - Remove all weak reference to the vma and put
1718  * the initial reference.
1719  *
1720  * This function should be called when it's decided the vma isn't needed
1721  * anymore. The caller must assure that it doesn't race with another lookup
1722  * plus destroy, typically by taking an appropriate reference.
1723  *
1724  * Current callsites are
1725  * - __i915_gem_object_pages_fini()
1726  * - __i915_vm_close() - Blocks the above function by taking a reference on
1727  * the object.
1728  * - __i915_vma_parked() - Blocks the above functions by taking a reference
1729  * on the vm and a reference on the object. Also takes the object lock so
1730  * destruction from __i915_vma_parked() can be blocked by holding the
1731  * object lock. Since the object lock is only allowed from within i915 with
1732  * an object refcount, holding the object lock also implicitly blocks the
1733  * vma freeing from __i915_gem_object_pages_fini().
1734  *
1735  * Because of locks taken during destruction, a vma is also guaranteed to
1736  * stay alive while the following locks are held if it was looked up while
1737  * holding one of the locks:
1738  * - vm->mutex
1739  * - obj->vma.lock
1740  * - gt->closed_lock
1741  */
1742 void i915_vma_destroy_locked(struct i915_vma *vma)
1743 {
1744 	lockdep_assert_held(&vma->vm->mutex);
1745 
1746 	force_unbind(vma);
1747 	list_del_init(&vma->vm_link);
1748 	release_references(vma, vma->vm->gt, false);
1749 }
1750 
1751 void i915_vma_destroy(struct i915_vma *vma)
1752 {
1753 	struct intel_gt *gt;
1754 	bool vm_ddestroy;
1755 
1756 	mutex_lock(&vma->vm->mutex);
1757 	force_unbind(vma);
1758 	list_del_init(&vma->vm_link);
1759 	vm_ddestroy = vma->vm_ddestroy;
1760 	vma->vm_ddestroy = false;
1761 
1762 	/* vma->vm may be freed when releasing vma->vm->mutex. */
1763 	gt = vma->vm->gt;
1764 	mutex_unlock(&vma->vm->mutex);
1765 	release_references(vma, gt, vm_ddestroy);
1766 }
1767 
1768 void i915_vma_parked(struct intel_gt *gt)
1769 {
1770 	struct i915_vma *vma, *next;
1771 	LIST_HEAD(closed);
1772 
1773 	spin_lock_irq(&gt->closed_lock);
1774 	list_for_each_entry_safe(vma, next, &gt->closed_vma, closed_link) {
1775 		struct drm_i915_gem_object *obj = vma->obj;
1776 		struct i915_address_space *vm = vma->vm;
1777 
1778 		/* XXX All to avoid keeping a reference on i915_vma itself */
1779 
1780 		if (!kref_get_unless_zero(&obj->base.refcount))
1781 			continue;
1782 
1783 		if (!i915_vm_tryget(vm)) {
1784 			i915_gem_object_put(obj);
1785 			continue;
1786 		}
1787 
1788 		list_move(&vma->closed_link, &closed);
1789 	}
1790 	spin_unlock_irq(&gt->closed_lock);
1791 
1792 	/* As the GT is held idle, no vma can be reopened as we destroy them */
1793 	list_for_each_entry_safe(vma, next, &closed, closed_link) {
1794 		struct drm_i915_gem_object *obj = vma->obj;
1795 		struct i915_address_space *vm = vma->vm;
1796 
1797 		if (i915_gem_object_trylock(obj, NULL)) {
1798 			INIT_LIST_HEAD(&vma->closed_link);
1799 			i915_vma_destroy(vma);
1800 			i915_gem_object_unlock(obj);
1801 		} else {
1802 			/* back you go.. */
1803 			spin_lock_irq(&gt->closed_lock);
1804 			list_add(&vma->closed_link, &gt->closed_vma);
1805 			spin_unlock_irq(&gt->closed_lock);
1806 		}
1807 
1808 		i915_gem_object_put(obj);
1809 		i915_vm_put(vm);
1810 	}
1811 }
1812 
1813 static void __i915_vma_iounmap(struct i915_vma *vma)
1814 {
1815 	GEM_BUG_ON(i915_vma_is_pinned(vma));
1816 
1817 	if (vma->iomap == NULL)
1818 		return;
1819 
1820 	if (page_unmask_bits(vma->iomap))
1821 		__i915_gem_object_release_map(vma->obj);
1822 	else
1823 		io_mapping_unmap(vma->iomap);
1824 	vma->iomap = NULL;
1825 }
1826 
1827 void i915_vma_revoke_mmap(struct i915_vma *vma)
1828 {
1829 	struct drm_vma_offset_node *node;
1830 	u64 vma_offset;
1831 
1832 	if (!i915_vma_has_userfault(vma))
1833 		return;
1834 
1835 	GEM_BUG_ON(!i915_vma_is_map_and_fenceable(vma));
1836 	GEM_BUG_ON(!vma->obj->userfault_count);
1837 
1838 	node = &vma->mmo->vma_node;
1839 	vma_offset = vma->gtt_view.partial.offset << PAGE_SHIFT;
1840 	unmap_mapping_range(vma->vm->i915->drm.anon_inode->i_mapping,
1841 			    drm_vma_node_offset_addr(node) + vma_offset,
1842 			    vma->size,
1843 			    1);
1844 
1845 	i915_vma_unset_userfault(vma);
1846 	if (!--vma->obj->userfault_count)
1847 		list_del(&vma->obj->userfault_link);
1848 }
1849 
1850 static int
1851 __i915_request_await_bind(struct i915_request *rq, struct i915_vma *vma)
1852 {
1853 	return __i915_request_await_exclusive(rq, &vma->active);
1854 }
1855 
1856 static int __i915_vma_move_to_active(struct i915_vma *vma, struct i915_request *rq)
1857 {
1858 	int err;
1859 
1860 	/* Wait for the vma to be bound before we start! */
1861 	err = __i915_request_await_bind(rq, vma);
1862 	if (err)
1863 		return err;
1864 
1865 	return i915_active_add_request(&vma->active, rq);
1866 }
1867 
1868 int _i915_vma_move_to_active(struct i915_vma *vma,
1869 			     struct i915_request *rq,
1870 			     struct dma_fence *fence,
1871 			     unsigned int flags)
1872 {
1873 	struct drm_i915_gem_object *obj = vma->obj;
1874 	int err;
1875 
1876 	assert_object_held(obj);
1877 
1878 	GEM_BUG_ON(!vma->pages);
1879 
1880 	if (!(flags & __EXEC_OBJECT_NO_REQUEST_AWAIT)) {
1881 		err = i915_request_await_object(rq, vma->obj, flags & EXEC_OBJECT_WRITE);
1882 		if (unlikely(err))
1883 			return err;
1884 	}
1885 	err = __i915_vma_move_to_active(vma, rq);
1886 	if (unlikely(err))
1887 		return err;
1888 
1889 	/*
1890 	 * Reserve fences slot early to prevent an allocation after preparing
1891 	 * the workload and associating fences with dma_resv.
1892 	 */
1893 	if (fence && !(flags & __EXEC_OBJECT_NO_RESERVE)) {
1894 		struct dma_fence *curr;
1895 		int idx;
1896 
1897 		dma_fence_array_for_each(curr, idx, fence)
1898 			;
1899 		err = dma_resv_reserve_fences(vma->obj->base.resv, idx);
1900 		if (unlikely(err))
1901 			return err;
1902 	}
1903 
1904 	if (flags & EXEC_OBJECT_WRITE) {
1905 		struct intel_frontbuffer *front;
1906 
1907 		front = __intel_frontbuffer_get(obj);
1908 		if (unlikely(front)) {
1909 			if (intel_frontbuffer_invalidate(front, ORIGIN_CS))
1910 				i915_active_add_request(&front->write, rq);
1911 			intel_frontbuffer_put(front);
1912 		}
1913 	}
1914 
1915 	if (fence) {
1916 		struct dma_fence *curr;
1917 		enum dma_resv_usage usage;
1918 		int idx;
1919 
1920 		if (flags & EXEC_OBJECT_WRITE) {
1921 			usage = DMA_RESV_USAGE_WRITE;
1922 			obj->write_domain = I915_GEM_DOMAIN_RENDER;
1923 			obj->read_domains = 0;
1924 		} else {
1925 			usage = DMA_RESV_USAGE_READ;
1926 			obj->write_domain = 0;
1927 		}
1928 
1929 		dma_fence_array_for_each(curr, idx, fence)
1930 			dma_resv_add_fence(vma->obj->base.resv, curr, usage);
1931 	}
1932 
1933 	if (flags & EXEC_OBJECT_NEEDS_FENCE && vma->fence)
1934 		i915_active_add_request(&vma->fence->active, rq);
1935 
1936 	obj->read_domains |= I915_GEM_GPU_DOMAINS;
1937 	obj->mm.dirty = true;
1938 
1939 	GEM_BUG_ON(!i915_vma_is_active(vma));
1940 	return 0;
1941 }
1942 
1943 struct dma_fence *__i915_vma_evict(struct i915_vma *vma, bool async)
1944 {
1945 	struct i915_vma_resource *vma_res = vma->resource;
1946 	struct dma_fence *unbind_fence;
1947 
1948 	GEM_BUG_ON(i915_vma_is_pinned(vma));
1949 	assert_vma_held_evict(vma);
1950 
1951 	if (i915_vma_is_map_and_fenceable(vma)) {
1952 		/* Force a pagefault for domain tracking on next user access */
1953 		i915_vma_revoke_mmap(vma);
1954 
1955 		/*
1956 		 * Check that we have flushed all writes through the GGTT
1957 		 * before the unbind, other due to non-strict nature of those
1958 		 * indirect writes they may end up referencing the GGTT PTE
1959 		 * after the unbind.
1960 		 *
1961 		 * Note that we may be concurrently poking at the GGTT_WRITE
1962 		 * bit from set-domain, as we mark all GGTT vma associated
1963 		 * with an object. We know this is for another vma, as we
1964 		 * are currently unbinding this one -- so if this vma will be
1965 		 * reused, it will be refaulted and have its dirty bit set
1966 		 * before the next write.
1967 		 */
1968 		i915_vma_flush_writes(vma);
1969 
1970 		/* release the fence reg _after_ flushing */
1971 		i915_vma_revoke_fence(vma);
1972 
1973 		clear_bit(I915_VMA_CAN_FENCE_BIT, __i915_vma_flags(vma));
1974 	}
1975 
1976 	__i915_vma_iounmap(vma);
1977 
1978 	GEM_BUG_ON(vma->fence);
1979 	GEM_BUG_ON(i915_vma_has_userfault(vma));
1980 
1981 	/* Object backend must be async capable. */
1982 	GEM_WARN_ON(async && !vma->resource->bi.pages_rsgt);
1983 
1984 	/* If vm is not open, unbind is a nop. */
1985 	vma_res->needs_wakeref = i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND) &&
1986 		kref_read(&vma->vm->ref);
1987 	vma_res->skip_pte_rewrite = !kref_read(&vma->vm->ref) ||
1988 		vma->vm->skip_pte_rewrite;
1989 	trace_i915_vma_unbind(vma);
1990 
1991 	if (async)
1992 		unbind_fence = i915_vma_resource_unbind(vma_res,
1993 							&vma->obj->mm.tlb);
1994 	else
1995 		unbind_fence = i915_vma_resource_unbind(vma_res, NULL);
1996 
1997 	vma->resource = NULL;
1998 
1999 	atomic_and(~(I915_VMA_BIND_MASK | I915_VMA_ERROR | I915_VMA_GGTT_WRITE),
2000 		   &vma->flags);
2001 
2002 	i915_vma_detach(vma);
2003 
2004 	if (!async) {
2005 		if (unbind_fence) {
2006 			dma_fence_wait(unbind_fence, false);
2007 			dma_fence_put(unbind_fence);
2008 			unbind_fence = NULL;
2009 		}
2010 		vma_invalidate_tlb(vma->vm, &vma->obj->mm.tlb);
2011 	}
2012 
2013 	/*
2014 	 * Binding itself may not have completed until the unbind fence signals,
2015 	 * so don't drop the pages until that happens, unless the resource is
2016 	 * async_capable.
2017 	 */
2018 
2019 	vma_unbind_pages(vma);
2020 	return unbind_fence;
2021 }
2022 
2023 int __i915_vma_unbind(struct i915_vma *vma)
2024 {
2025 	int ret;
2026 
2027 	lockdep_assert_held(&vma->vm->mutex);
2028 	assert_vma_held_evict(vma);
2029 
2030 	if (!drm_mm_node_allocated(&vma->node))
2031 		return 0;
2032 
2033 	if (i915_vma_is_pinned(vma)) {
2034 		vma_print_allocator(vma, "is pinned");
2035 		return -EAGAIN;
2036 	}
2037 
2038 	/*
2039 	 * After confirming that no one else is pinning this vma, wait for
2040 	 * any laggards who may have crept in during the wait (through
2041 	 * a residual pin skipping the vm->mutex) to complete.
2042 	 */
2043 	ret = i915_vma_sync(vma);
2044 	if (ret)
2045 		return ret;
2046 
2047 	GEM_BUG_ON(i915_vma_is_active(vma));
2048 	__i915_vma_evict(vma, false);
2049 
2050 	drm_mm_remove_node(&vma->node); /* pairs with i915_vma_release() */
2051 	return 0;
2052 }
2053 
2054 static struct dma_fence *__i915_vma_unbind_async(struct i915_vma *vma)
2055 {
2056 	struct dma_fence *fence;
2057 
2058 	lockdep_assert_held(&vma->vm->mutex);
2059 
2060 	if (!drm_mm_node_allocated(&vma->node))
2061 		return NULL;
2062 
2063 	if (i915_vma_is_pinned(vma) ||
2064 	    &vma->obj->mm.rsgt->table != vma->resource->bi.pages)
2065 		return ERR_PTR(-EAGAIN);
2066 
2067 	/*
2068 	 * We probably need to replace this with awaiting the fences of the
2069 	 * object's dma_resv when the vma active goes away. When doing that
2070 	 * we need to be careful to not add the vma_resource unbind fence
2071 	 * immediately to the object's dma_resv, because then unbinding
2072 	 * the next vma from the object, in case there are many, will
2073 	 * actually await the unbinding of the previous vmas, which is
2074 	 * undesirable.
2075 	 */
2076 	if (i915_sw_fence_await_active(&vma->resource->chain, &vma->active,
2077 				       I915_ACTIVE_AWAIT_EXCL |
2078 				       I915_ACTIVE_AWAIT_ACTIVE) < 0) {
2079 		return ERR_PTR(-EBUSY);
2080 	}
2081 
2082 	fence = __i915_vma_evict(vma, true);
2083 
2084 	drm_mm_remove_node(&vma->node); /* pairs with i915_vma_release() */
2085 
2086 	return fence;
2087 }
2088 
2089 int i915_vma_unbind(struct i915_vma *vma)
2090 {
2091 	struct i915_address_space *vm = vma->vm;
2092 	intel_wakeref_t wakeref = 0;
2093 	int err;
2094 
2095 	assert_object_held_shared(vma->obj);
2096 
2097 	/* Optimistic wait before taking the mutex */
2098 	err = i915_vma_sync(vma);
2099 	if (err)
2100 		return err;
2101 
2102 	if (!drm_mm_node_allocated(&vma->node))
2103 		return 0;
2104 
2105 	if (i915_vma_is_pinned(vma)) {
2106 		vma_print_allocator(vma, "is pinned");
2107 		return -EAGAIN;
2108 	}
2109 
2110 	if (i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND))
2111 		/* XXX not always required: nop_clear_range */
2112 		wakeref = intel_runtime_pm_get(&vm->i915->runtime_pm);
2113 
2114 	err = mutex_lock_interruptible_nested(&vma->vm->mutex, !wakeref);
2115 	if (err)
2116 		goto out_rpm;
2117 
2118 	err = __i915_vma_unbind(vma);
2119 	mutex_unlock(&vm->mutex);
2120 
2121 out_rpm:
2122 	if (wakeref)
2123 		intel_runtime_pm_put(&vm->i915->runtime_pm, wakeref);
2124 	return err;
2125 }
2126 
2127 int i915_vma_unbind_async(struct i915_vma *vma, bool trylock_vm)
2128 {
2129 	struct drm_i915_gem_object *obj = vma->obj;
2130 	struct i915_address_space *vm = vma->vm;
2131 	intel_wakeref_t wakeref = 0;
2132 	struct dma_fence *fence;
2133 	int err;
2134 
2135 	/*
2136 	 * We need the dma-resv lock since we add the
2137 	 * unbind fence to the dma-resv object.
2138 	 */
2139 	assert_object_held(obj);
2140 
2141 	if (!drm_mm_node_allocated(&vma->node))
2142 		return 0;
2143 
2144 	if (i915_vma_is_pinned(vma)) {
2145 		vma_print_allocator(vma, "is pinned");
2146 		return -EAGAIN;
2147 	}
2148 
2149 	if (!obj->mm.rsgt)
2150 		return -EBUSY;
2151 
2152 	err = dma_resv_reserve_fences(obj->base.resv, 2);
2153 	if (err)
2154 		return -EBUSY;
2155 
2156 	/*
2157 	 * It would be great if we could grab this wakeref from the
2158 	 * async unbind work if needed, but we can't because it uses
2159 	 * kmalloc and it's in the dma-fence signalling critical path.
2160 	 */
2161 	if (i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND))
2162 		wakeref = intel_runtime_pm_get(&vm->i915->runtime_pm);
2163 
2164 	if (trylock_vm && !mutex_trylock(&vm->mutex)) {
2165 		err = -EBUSY;
2166 		goto out_rpm;
2167 	} else if (!trylock_vm) {
2168 		err = mutex_lock_interruptible_nested(&vm->mutex, !wakeref);
2169 		if (err)
2170 			goto out_rpm;
2171 	}
2172 
2173 	fence = __i915_vma_unbind_async(vma);
2174 	mutex_unlock(&vm->mutex);
2175 	if (IS_ERR_OR_NULL(fence)) {
2176 		err = PTR_ERR_OR_ZERO(fence);
2177 		goto out_rpm;
2178 	}
2179 
2180 	dma_resv_add_fence(obj->base.resv, fence, DMA_RESV_USAGE_READ);
2181 	dma_fence_put(fence);
2182 
2183 out_rpm:
2184 	if (wakeref)
2185 		intel_runtime_pm_put(&vm->i915->runtime_pm, wakeref);
2186 	return err;
2187 }
2188 
2189 int i915_vma_unbind_unlocked(struct i915_vma *vma)
2190 {
2191 	int err;
2192 
2193 	i915_gem_object_lock(vma->obj, NULL);
2194 	err = i915_vma_unbind(vma);
2195 	i915_gem_object_unlock(vma->obj);
2196 
2197 	return err;
2198 }
2199 
2200 struct i915_vma *i915_vma_make_unshrinkable(struct i915_vma *vma)
2201 {
2202 	i915_gem_object_make_unshrinkable(vma->obj);
2203 	return vma;
2204 }
2205 
2206 void i915_vma_make_shrinkable(struct i915_vma *vma)
2207 {
2208 	i915_gem_object_make_shrinkable(vma->obj);
2209 }
2210 
2211 void i915_vma_make_purgeable(struct i915_vma *vma)
2212 {
2213 	i915_gem_object_make_purgeable(vma->obj);
2214 }
2215 
2216 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
2217 #include "selftests/i915_vma.c"
2218 #endif
2219 
2220 void i915_vma_module_exit(void)
2221 {
2222 	kmem_cache_destroy(slab_vmas);
2223 }
2224 
2225 int __init i915_vma_module_init(void)
2226 {
2227 	slab_vmas = KMEM_CACHE(i915_vma, SLAB_HWCACHE_ALIGN);
2228 	if (!slab_vmas)
2229 		return -ENOMEM;
2230 
2231 	return 0;
2232 }
2233