xref: /linux/drivers/gpu/drm/i915/i915_vma.c (revision 94cad89ae4505672ae65457d12f77c44ca87655b)
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 <drm/drm_gem.h>
27 
28 #include "display/intel_frontbuffer.h"
29 
30 #include "gt/intel_engine.h"
31 #include "gt/intel_engine_heartbeat.h"
32 #include "gt/intel_gt.h"
33 #include "gt/intel_gt_requests.h"
34 
35 #include "i915_drv.h"
36 #include "i915_globals.h"
37 #include "i915_sw_fence_work.h"
38 #include "i915_trace.h"
39 #include "i915_vma.h"
40 
41 static struct i915_global_vma {
42 	struct i915_global base;
43 	struct kmem_cache *slab_vmas;
44 } global;
45 
46 struct i915_vma *i915_vma_alloc(void)
47 {
48 	return kmem_cache_zalloc(global.slab_vmas, GFP_KERNEL);
49 }
50 
51 void i915_vma_free(struct i915_vma *vma)
52 {
53 	return kmem_cache_free(global.slab_vmas, vma);
54 }
55 
56 #if IS_ENABLED(CONFIG_DRM_I915_ERRLOG_GEM) && IS_ENABLED(CONFIG_DRM_DEBUG_MM)
57 
58 #include <linux/stackdepot.h>
59 
60 static void vma_print_allocator(struct i915_vma *vma, const char *reason)
61 {
62 	unsigned long *entries;
63 	unsigned int nr_entries;
64 	char buf[512];
65 
66 	if (!vma->node.stack) {
67 		DRM_DEBUG_DRIVER("vma.node [%08llx + %08llx] %s: unknown owner\n",
68 				 vma->node.start, vma->node.size, reason);
69 		return;
70 	}
71 
72 	nr_entries = stack_depot_fetch(vma->node.stack, &entries);
73 	stack_trace_snprint(buf, sizeof(buf), entries, nr_entries, 0);
74 	DRM_DEBUG_DRIVER("vma.node [%08llx + %08llx] %s: inserted at %s\n",
75 			 vma->node.start, vma->node.size, reason, buf);
76 }
77 
78 #else
79 
80 static void vma_print_allocator(struct i915_vma *vma, const char *reason)
81 {
82 }
83 
84 #endif
85 
86 static inline struct i915_vma *active_to_vma(struct i915_active *ref)
87 {
88 	return container_of(ref, typeof(struct i915_vma), active);
89 }
90 
91 static int __i915_vma_active(struct i915_active *ref)
92 {
93 	return i915_vma_tryget(active_to_vma(ref)) ? 0 : -ENOENT;
94 }
95 
96 __i915_active_call
97 static void __i915_vma_retire(struct i915_active *ref)
98 {
99 	i915_vma_put(active_to_vma(ref));
100 }
101 
102 static struct i915_vma *
103 vma_create(struct drm_i915_gem_object *obj,
104 	   struct i915_address_space *vm,
105 	   const struct i915_ggtt_view *view)
106 {
107 	struct i915_vma *pos = ERR_PTR(-E2BIG);
108 	struct i915_vma *vma;
109 	struct rb_node *rb, **p;
110 
111 	/* The aliasing_ppgtt should never be used directly! */
112 	GEM_BUG_ON(vm == &vm->gt->ggtt->alias->vm);
113 
114 	vma = i915_vma_alloc();
115 	if (vma == NULL)
116 		return ERR_PTR(-ENOMEM);
117 
118 	kref_init(&vma->ref);
119 	mutex_init(&vma->pages_mutex);
120 	vma->vm = i915_vm_get(vm);
121 	vma->ops = &vm->vma_ops;
122 	vma->obj = obj;
123 	vma->resv = obj->base.resv;
124 	vma->size = obj->base.size;
125 	vma->display_alignment = I915_GTT_MIN_ALIGNMENT;
126 
127 	i915_active_init(&vma->active, __i915_vma_active, __i915_vma_retire);
128 
129 	/* Declare ourselves safe for use inside shrinkers */
130 	if (IS_ENABLED(CONFIG_LOCKDEP)) {
131 		fs_reclaim_acquire(GFP_KERNEL);
132 		might_lock(&vma->active.mutex);
133 		fs_reclaim_release(GFP_KERNEL);
134 	}
135 
136 	INIT_LIST_HEAD(&vma->closed_link);
137 
138 	if (view && view->type != I915_GGTT_VIEW_NORMAL) {
139 		vma->ggtt_view = *view;
140 		if (view->type == I915_GGTT_VIEW_PARTIAL) {
141 			GEM_BUG_ON(range_overflows_t(u64,
142 						     view->partial.offset,
143 						     view->partial.size,
144 						     obj->base.size >> PAGE_SHIFT));
145 			vma->size = view->partial.size;
146 			vma->size <<= PAGE_SHIFT;
147 			GEM_BUG_ON(vma->size > obj->base.size);
148 		} else if (view->type == I915_GGTT_VIEW_ROTATED) {
149 			vma->size = intel_rotation_info_size(&view->rotated);
150 			vma->size <<= PAGE_SHIFT;
151 		} else if (view->type == I915_GGTT_VIEW_REMAPPED) {
152 			vma->size = intel_remapped_info_size(&view->remapped);
153 			vma->size <<= PAGE_SHIFT;
154 		}
155 	}
156 
157 	if (unlikely(vma->size > vm->total))
158 		goto err_vma;
159 
160 	GEM_BUG_ON(!IS_ALIGNED(vma->size, I915_GTT_PAGE_SIZE));
161 
162 	spin_lock(&obj->vma.lock);
163 
164 	if (i915_is_ggtt(vm)) {
165 		if (unlikely(overflows_type(vma->size, u32)))
166 			goto err_unlock;
167 
168 		vma->fence_size = i915_gem_fence_size(vm->i915, vma->size,
169 						      i915_gem_object_get_tiling(obj),
170 						      i915_gem_object_get_stride(obj));
171 		if (unlikely(vma->fence_size < vma->size || /* overflow */
172 			     vma->fence_size > vm->total))
173 			goto err_unlock;
174 
175 		GEM_BUG_ON(!IS_ALIGNED(vma->fence_size, I915_GTT_MIN_ALIGNMENT));
176 
177 		vma->fence_alignment = i915_gem_fence_alignment(vm->i915, vma->size,
178 								i915_gem_object_get_tiling(obj),
179 								i915_gem_object_get_stride(obj));
180 		GEM_BUG_ON(!is_power_of_2(vma->fence_alignment));
181 
182 		__set_bit(I915_VMA_GGTT_BIT, __i915_vma_flags(vma));
183 	}
184 
185 	rb = NULL;
186 	p = &obj->vma.tree.rb_node;
187 	while (*p) {
188 		long cmp;
189 
190 		rb = *p;
191 		pos = rb_entry(rb, struct i915_vma, obj_node);
192 
193 		/*
194 		 * If the view already exists in the tree, another thread
195 		 * already created a matching vma, so return the older instance
196 		 * and dispose of ours.
197 		 */
198 		cmp = i915_vma_compare(pos, vm, view);
199 		if (cmp == 0) {
200 			spin_unlock(&obj->vma.lock);
201 			i915_vm_put(vm);
202 			i915_vma_free(vma);
203 			return pos;
204 		}
205 
206 		if (cmp < 0)
207 			p = &rb->rb_right;
208 		else if (cmp > 0)
209 			p = &rb->rb_left;
210 		else
211 			goto err_unlock;
212 	}
213 	rb_link_node(&vma->obj_node, rb, p);
214 	rb_insert_color(&vma->obj_node, &obj->vma.tree);
215 
216 	if (i915_vma_is_ggtt(vma))
217 		/*
218 		 * We put the GGTT vma at the start of the vma-list, followed
219 		 * by the ppGGTT vma. This allows us to break early when
220 		 * iterating over only the GGTT vma for an object, see
221 		 * for_each_ggtt_vma()
222 		 */
223 		list_add(&vma->obj_link, &obj->vma.list);
224 	else
225 		list_add_tail(&vma->obj_link, &obj->vma.list);
226 
227 	spin_unlock(&obj->vma.lock);
228 
229 	return vma;
230 
231 err_unlock:
232 	spin_unlock(&obj->vma.lock);
233 err_vma:
234 	i915_vm_put(vm);
235 	i915_vma_free(vma);
236 	return pos;
237 }
238 
239 static struct i915_vma *
240 vma_lookup(struct drm_i915_gem_object *obj,
241 	   struct i915_address_space *vm,
242 	   const struct i915_ggtt_view *view)
243 {
244 	struct rb_node *rb;
245 
246 	rb = obj->vma.tree.rb_node;
247 	while (rb) {
248 		struct i915_vma *vma = rb_entry(rb, struct i915_vma, obj_node);
249 		long cmp;
250 
251 		cmp = i915_vma_compare(vma, vm, view);
252 		if (cmp == 0)
253 			return vma;
254 
255 		if (cmp < 0)
256 			rb = rb->rb_right;
257 		else
258 			rb = rb->rb_left;
259 	}
260 
261 	return NULL;
262 }
263 
264 /**
265  * i915_vma_instance - return the singleton instance of the VMA
266  * @obj: parent &struct drm_i915_gem_object to be mapped
267  * @vm: address space in which the mapping is located
268  * @view: additional mapping requirements
269  *
270  * i915_vma_instance() looks up an existing VMA of the @obj in the @vm with
271  * the same @view characteristics. If a match is not found, one is created.
272  * Once created, the VMA is kept until either the object is freed, or the
273  * address space is closed.
274  *
275  * Returns the vma, or an error pointer.
276  */
277 struct i915_vma *
278 i915_vma_instance(struct drm_i915_gem_object *obj,
279 		  struct i915_address_space *vm,
280 		  const struct i915_ggtt_view *view)
281 {
282 	struct i915_vma *vma;
283 
284 	GEM_BUG_ON(view && !i915_is_ggtt(vm));
285 	GEM_BUG_ON(!atomic_read(&vm->open));
286 
287 	spin_lock(&obj->vma.lock);
288 	vma = vma_lookup(obj, vm, view);
289 	spin_unlock(&obj->vma.lock);
290 
291 	/* vma_create() will resolve the race if another creates the vma */
292 	if (unlikely(!vma))
293 		vma = vma_create(obj, vm, view);
294 
295 	GEM_BUG_ON(!IS_ERR(vma) && i915_vma_compare(vma, vm, view));
296 	return vma;
297 }
298 
299 struct i915_vma_work {
300 	struct dma_fence_work base;
301 	struct i915_vma *vma;
302 	struct drm_i915_gem_object *pinned;
303 	struct i915_sw_dma_fence_cb cb;
304 	enum i915_cache_level cache_level;
305 	unsigned int flags;
306 };
307 
308 static int __vma_bind(struct dma_fence_work *work)
309 {
310 	struct i915_vma_work *vw = container_of(work, typeof(*vw), base);
311 	struct i915_vma *vma = vw->vma;
312 	int err;
313 
314 	err = vma->ops->bind_vma(vma, vw->cache_level, vw->flags);
315 	if (err)
316 		atomic_or(I915_VMA_ERROR, &vma->flags);
317 
318 	return err;
319 }
320 
321 static void __vma_release(struct dma_fence_work *work)
322 {
323 	struct i915_vma_work *vw = container_of(work, typeof(*vw), base);
324 
325 	if (vw->pinned)
326 		__i915_gem_object_unpin_pages(vw->pinned);
327 }
328 
329 static const struct dma_fence_work_ops bind_ops = {
330 	.name = "bind",
331 	.work = __vma_bind,
332 	.release = __vma_release,
333 };
334 
335 struct i915_vma_work *i915_vma_work(void)
336 {
337 	struct i915_vma_work *vw;
338 
339 	vw = kzalloc(sizeof(*vw), GFP_KERNEL);
340 	if (!vw)
341 		return NULL;
342 
343 	dma_fence_work_init(&vw->base, &bind_ops);
344 	vw->base.dma.error = -EAGAIN; /* disable the worker by default */
345 
346 	return vw;
347 }
348 
349 int i915_vma_wait_for_bind(struct i915_vma *vma)
350 {
351 	int err = 0;
352 
353 	if (rcu_access_pointer(vma->active.excl.fence)) {
354 		struct dma_fence *fence;
355 
356 		rcu_read_lock();
357 		fence = dma_fence_get_rcu_safe(&vma->active.excl.fence);
358 		rcu_read_unlock();
359 		if (fence) {
360 			err = dma_fence_wait(fence, MAX_SCHEDULE_TIMEOUT);
361 			dma_fence_put(fence);
362 		}
363 	}
364 
365 	return err;
366 }
367 
368 /**
369  * i915_vma_bind - Sets up PTEs for an VMA in it's corresponding address space.
370  * @vma: VMA to map
371  * @cache_level: mapping cache level
372  * @flags: flags like global or local mapping
373  * @work: preallocated worker for allocating and binding the PTE
374  *
375  * DMA addresses are taken from the scatter-gather table of this object (or of
376  * this VMA in case of non-default GGTT views) and PTE entries set up.
377  * Note that DMA addresses are also the only part of the SG table we care about.
378  */
379 int i915_vma_bind(struct i915_vma *vma,
380 		  enum i915_cache_level cache_level,
381 		  u32 flags,
382 		  struct i915_vma_work *work)
383 {
384 	u32 bind_flags;
385 	u32 vma_flags;
386 	int ret;
387 
388 	GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
389 	GEM_BUG_ON(vma->size > vma->node.size);
390 
391 	if (GEM_DEBUG_WARN_ON(range_overflows(vma->node.start,
392 					      vma->node.size,
393 					      vma->vm->total)))
394 		return -ENODEV;
395 
396 	if (GEM_DEBUG_WARN_ON(!flags))
397 		return -EINVAL;
398 
399 	bind_flags = flags;
400 	bind_flags &= I915_VMA_GLOBAL_BIND | I915_VMA_LOCAL_BIND;
401 
402 	vma_flags = atomic_read(&vma->flags);
403 	vma_flags &= I915_VMA_GLOBAL_BIND | I915_VMA_LOCAL_BIND;
404 
405 	bind_flags &= ~vma_flags;
406 	if (bind_flags == 0)
407 		return 0;
408 
409 	GEM_BUG_ON(!vma->pages);
410 
411 	trace_i915_vma_bind(vma, bind_flags);
412 	if (work && bind_flags & vma->vm->bind_async_flags) {
413 		struct dma_fence *prev;
414 
415 		work->vma = vma;
416 		work->cache_level = cache_level;
417 		work->flags = bind_flags | I915_VMA_ALLOC;
418 
419 		/*
420 		 * Note we only want to chain up to the migration fence on
421 		 * the pages (not the object itself). As we don't track that,
422 		 * yet, we have to use the exclusive fence instead.
423 		 *
424 		 * Also note that we do not want to track the async vma as
425 		 * part of the obj->resv->excl_fence as it only affects
426 		 * execution and not content or object's backing store lifetime.
427 		 */
428 		prev = i915_active_set_exclusive(&vma->active, &work->base.dma);
429 		if (prev) {
430 			__i915_sw_fence_await_dma_fence(&work->base.chain,
431 							prev,
432 							&work->cb);
433 			dma_fence_put(prev);
434 		}
435 
436 		work->base.dma.error = 0; /* enable the queue_work() */
437 
438 		if (vma->obj) {
439 			__i915_gem_object_pin_pages(vma->obj);
440 			work->pinned = vma->obj;
441 		}
442 	} else {
443 		ret = vma->ops->bind_vma(vma, cache_level, bind_flags);
444 		if (ret)
445 			return ret;
446 	}
447 
448 	atomic_or(bind_flags, &vma->flags);
449 	return 0;
450 }
451 
452 void __iomem *i915_vma_pin_iomap(struct i915_vma *vma)
453 {
454 	void __iomem *ptr;
455 	int err;
456 
457 	if (GEM_WARN_ON(!i915_vma_is_map_and_fenceable(vma))) {
458 		err = -ENODEV;
459 		goto err;
460 	}
461 
462 	GEM_BUG_ON(!i915_vma_is_ggtt(vma));
463 	GEM_BUG_ON(!i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND));
464 
465 	ptr = READ_ONCE(vma->iomap);
466 	if (ptr == NULL) {
467 		ptr = io_mapping_map_wc(&i915_vm_to_ggtt(vma->vm)->iomap,
468 					vma->node.start,
469 					vma->node.size);
470 		if (ptr == NULL) {
471 			err = -ENOMEM;
472 			goto err;
473 		}
474 
475 		if (unlikely(cmpxchg(&vma->iomap, NULL, ptr))) {
476 			io_mapping_unmap(ptr);
477 			ptr = vma->iomap;
478 		}
479 	}
480 
481 	__i915_vma_pin(vma);
482 
483 	err = i915_vma_pin_fence(vma);
484 	if (err)
485 		goto err_unpin;
486 
487 	i915_vma_set_ggtt_write(vma);
488 
489 	/* NB Access through the GTT requires the device to be awake. */
490 	return ptr;
491 
492 err_unpin:
493 	__i915_vma_unpin(vma);
494 err:
495 	return IO_ERR_PTR(err);
496 }
497 
498 void i915_vma_flush_writes(struct i915_vma *vma)
499 {
500 	if (i915_vma_unset_ggtt_write(vma))
501 		intel_gt_flush_ggtt_writes(vma->vm->gt);
502 }
503 
504 void i915_vma_unpin_iomap(struct i915_vma *vma)
505 {
506 	GEM_BUG_ON(vma->iomap == NULL);
507 
508 	i915_vma_flush_writes(vma);
509 
510 	i915_vma_unpin_fence(vma);
511 	i915_vma_unpin(vma);
512 }
513 
514 void i915_vma_unpin_and_release(struct i915_vma **p_vma, unsigned int flags)
515 {
516 	struct i915_vma *vma;
517 	struct drm_i915_gem_object *obj;
518 
519 	vma = fetch_and_zero(p_vma);
520 	if (!vma)
521 		return;
522 
523 	obj = vma->obj;
524 	GEM_BUG_ON(!obj);
525 
526 	i915_vma_unpin(vma);
527 
528 	if (flags & I915_VMA_RELEASE_MAP)
529 		i915_gem_object_unpin_map(obj);
530 
531 	i915_gem_object_put(obj);
532 }
533 
534 bool i915_vma_misplaced(const struct i915_vma *vma,
535 			u64 size, u64 alignment, u64 flags)
536 {
537 	if (!drm_mm_node_allocated(&vma->node))
538 		return false;
539 
540 	if (test_bit(I915_VMA_ERROR_BIT, __i915_vma_flags(vma)))
541 		return true;
542 
543 	if (vma->node.size < size)
544 		return true;
545 
546 	GEM_BUG_ON(alignment && !is_power_of_2(alignment));
547 	if (alignment && !IS_ALIGNED(vma->node.start, alignment))
548 		return true;
549 
550 	if (flags & PIN_MAPPABLE && !i915_vma_is_map_and_fenceable(vma))
551 		return true;
552 
553 	if (flags & PIN_OFFSET_BIAS &&
554 	    vma->node.start < (flags & PIN_OFFSET_MASK))
555 		return true;
556 
557 	if (flags & PIN_OFFSET_FIXED &&
558 	    vma->node.start != (flags & PIN_OFFSET_MASK))
559 		return true;
560 
561 	return false;
562 }
563 
564 void __i915_vma_set_map_and_fenceable(struct i915_vma *vma)
565 {
566 	bool mappable, fenceable;
567 
568 	GEM_BUG_ON(!i915_vma_is_ggtt(vma));
569 	GEM_BUG_ON(!vma->fence_size);
570 
571 	fenceable = (vma->node.size >= vma->fence_size &&
572 		     IS_ALIGNED(vma->node.start, vma->fence_alignment));
573 
574 	mappable = vma->node.start + vma->fence_size <= i915_vm_to_ggtt(vma->vm)->mappable_end;
575 
576 	if (mappable && fenceable)
577 		set_bit(I915_VMA_CAN_FENCE_BIT, __i915_vma_flags(vma));
578 	else
579 		clear_bit(I915_VMA_CAN_FENCE_BIT, __i915_vma_flags(vma));
580 }
581 
582 bool i915_gem_valid_gtt_space(struct i915_vma *vma, unsigned long color)
583 {
584 	struct drm_mm_node *node = &vma->node;
585 	struct drm_mm_node *other;
586 
587 	/*
588 	 * On some machines we have to be careful when putting differing types
589 	 * of snoopable memory together to avoid the prefetcher crossing memory
590 	 * domains and dying. During vm initialisation, we decide whether or not
591 	 * these constraints apply and set the drm_mm.color_adjust
592 	 * appropriately.
593 	 */
594 	if (!i915_vm_has_cache_coloring(vma->vm))
595 		return true;
596 
597 	/* Only valid to be called on an already inserted vma */
598 	GEM_BUG_ON(!drm_mm_node_allocated(node));
599 	GEM_BUG_ON(list_empty(&node->node_list));
600 
601 	other = list_prev_entry(node, node_list);
602 	if (i915_node_color_differs(other, color) &&
603 	    !drm_mm_hole_follows(other))
604 		return false;
605 
606 	other = list_next_entry(node, node_list);
607 	if (i915_node_color_differs(other, color) &&
608 	    !drm_mm_hole_follows(node))
609 		return false;
610 
611 	return true;
612 }
613 
614 /**
615  * i915_vma_insert - finds a slot for the vma in its address space
616  * @vma: the vma
617  * @size: requested size in bytes (can be larger than the VMA)
618  * @alignment: required alignment
619  * @flags: mask of PIN_* flags to use
620  *
621  * First we try to allocate some free space that meets the requirements for
622  * the VMA. Failiing that, if the flags permit, it will evict an old VMA,
623  * preferrably the oldest idle entry to make room for the new VMA.
624  *
625  * Returns:
626  * 0 on success, negative error code otherwise.
627  */
628 static int
629 i915_vma_insert(struct i915_vma *vma, u64 size, u64 alignment, u64 flags)
630 {
631 	unsigned long color;
632 	u64 start, end;
633 	int ret;
634 
635 	GEM_BUG_ON(i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND | I915_VMA_LOCAL_BIND));
636 	GEM_BUG_ON(drm_mm_node_allocated(&vma->node));
637 
638 	size = max(size, vma->size);
639 	alignment = max(alignment, vma->display_alignment);
640 	if (flags & PIN_MAPPABLE) {
641 		size = max_t(typeof(size), size, vma->fence_size);
642 		alignment = max_t(typeof(alignment),
643 				  alignment, vma->fence_alignment);
644 	}
645 
646 	GEM_BUG_ON(!IS_ALIGNED(size, I915_GTT_PAGE_SIZE));
647 	GEM_BUG_ON(!IS_ALIGNED(alignment, I915_GTT_MIN_ALIGNMENT));
648 	GEM_BUG_ON(!is_power_of_2(alignment));
649 
650 	start = flags & PIN_OFFSET_BIAS ? flags & PIN_OFFSET_MASK : 0;
651 	GEM_BUG_ON(!IS_ALIGNED(start, I915_GTT_PAGE_SIZE));
652 
653 	end = vma->vm->total;
654 	if (flags & PIN_MAPPABLE)
655 		end = min_t(u64, end, i915_vm_to_ggtt(vma->vm)->mappable_end);
656 	if (flags & PIN_ZONE_4G)
657 		end = min_t(u64, end, (1ULL << 32) - I915_GTT_PAGE_SIZE);
658 	GEM_BUG_ON(!IS_ALIGNED(end, I915_GTT_PAGE_SIZE));
659 
660 	/* If binding the object/GGTT view requires more space than the entire
661 	 * aperture has, reject it early before evicting everything in a vain
662 	 * attempt to find space.
663 	 */
664 	if (size > end) {
665 		DRM_DEBUG("Attempting to bind an object larger than the aperture: request=%llu > %s aperture=%llu\n",
666 			  size, flags & PIN_MAPPABLE ? "mappable" : "total",
667 			  end);
668 		return -ENOSPC;
669 	}
670 
671 	color = 0;
672 	if (vma->obj && i915_vm_has_cache_coloring(vma->vm))
673 		color = vma->obj->cache_level;
674 
675 	if (flags & PIN_OFFSET_FIXED) {
676 		u64 offset = flags & PIN_OFFSET_MASK;
677 		if (!IS_ALIGNED(offset, alignment) ||
678 		    range_overflows(offset, size, end))
679 			return -EINVAL;
680 
681 		ret = i915_gem_gtt_reserve(vma->vm, &vma->node,
682 					   size, offset, color,
683 					   flags);
684 		if (ret)
685 			return ret;
686 	} else {
687 		/*
688 		 * We only support huge gtt pages through the 48b PPGTT,
689 		 * however we also don't want to force any alignment for
690 		 * objects which need to be tightly packed into the low 32bits.
691 		 *
692 		 * Note that we assume that GGTT are limited to 4GiB for the
693 		 * forseeable future. See also i915_ggtt_offset().
694 		 */
695 		if (upper_32_bits(end - 1) &&
696 		    vma->page_sizes.sg > I915_GTT_PAGE_SIZE) {
697 			/*
698 			 * We can't mix 64K and 4K PTEs in the same page-table
699 			 * (2M block), and so to avoid the ugliness and
700 			 * complexity of coloring we opt for just aligning 64K
701 			 * objects to 2M.
702 			 */
703 			u64 page_alignment =
704 				rounddown_pow_of_two(vma->page_sizes.sg |
705 						     I915_GTT_PAGE_SIZE_2M);
706 
707 			/*
708 			 * Check we don't expand for the limited Global GTT
709 			 * (mappable aperture is even more precious!). This
710 			 * also checks that we exclude the aliasing-ppgtt.
711 			 */
712 			GEM_BUG_ON(i915_vma_is_ggtt(vma));
713 
714 			alignment = max(alignment, page_alignment);
715 
716 			if (vma->page_sizes.sg & I915_GTT_PAGE_SIZE_64K)
717 				size = round_up(size, I915_GTT_PAGE_SIZE_2M);
718 		}
719 
720 		ret = i915_gem_gtt_insert(vma->vm, &vma->node,
721 					  size, alignment, color,
722 					  start, end, flags);
723 		if (ret)
724 			return ret;
725 
726 		GEM_BUG_ON(vma->node.start < start);
727 		GEM_BUG_ON(vma->node.start + vma->node.size > end);
728 	}
729 	GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
730 	GEM_BUG_ON(!i915_gem_valid_gtt_space(vma, color));
731 
732 	list_add_tail(&vma->vm_link, &vma->vm->bound_list);
733 
734 	return 0;
735 }
736 
737 static void
738 i915_vma_detach(struct i915_vma *vma)
739 {
740 	GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
741 	GEM_BUG_ON(i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND | I915_VMA_LOCAL_BIND));
742 
743 	/*
744 	 * And finally now the object is completely decoupled from this
745 	 * vma, we can drop its hold on the backing storage and allow
746 	 * it to be reaped by the shrinker.
747 	 */
748 	list_del(&vma->vm_link);
749 }
750 
751 static bool try_qad_pin(struct i915_vma *vma, unsigned int flags)
752 {
753 	unsigned int bound;
754 	bool pinned = true;
755 
756 	bound = atomic_read(&vma->flags);
757 	do {
758 		if (unlikely(flags & ~bound))
759 			return false;
760 
761 		if (unlikely(bound & (I915_VMA_OVERFLOW | I915_VMA_ERROR)))
762 			return false;
763 
764 		if (!(bound & I915_VMA_PIN_MASK))
765 			goto unpinned;
766 
767 		GEM_BUG_ON(((bound + 1) & I915_VMA_PIN_MASK) == 0);
768 	} while (!atomic_try_cmpxchg(&vma->flags, &bound, bound + 1));
769 
770 	return true;
771 
772 unpinned:
773 	/*
774 	 * If pin_count==0, but we are bound, check under the lock to avoid
775 	 * racing with a concurrent i915_vma_unbind().
776 	 */
777 	mutex_lock(&vma->vm->mutex);
778 	do {
779 		if (unlikely(bound & (I915_VMA_OVERFLOW | I915_VMA_ERROR))) {
780 			pinned = false;
781 			break;
782 		}
783 
784 		if (unlikely(flags & ~bound)) {
785 			pinned = false;
786 			break;
787 		}
788 	} while (!atomic_try_cmpxchg(&vma->flags, &bound, bound + 1));
789 	mutex_unlock(&vma->vm->mutex);
790 
791 	return pinned;
792 }
793 
794 static int vma_get_pages(struct i915_vma *vma)
795 {
796 	int err = 0;
797 
798 	if (atomic_add_unless(&vma->pages_count, 1, 0))
799 		return 0;
800 
801 	/* Allocations ahoy! */
802 	if (mutex_lock_interruptible(&vma->pages_mutex))
803 		return -EINTR;
804 
805 	if (!atomic_read(&vma->pages_count)) {
806 		if (vma->obj) {
807 			err = i915_gem_object_pin_pages(vma->obj);
808 			if (err)
809 				goto unlock;
810 		}
811 
812 		err = vma->ops->set_pages(vma);
813 		if (err) {
814 			if (vma->obj)
815 				i915_gem_object_unpin_pages(vma->obj);
816 			goto unlock;
817 		}
818 	}
819 	atomic_inc(&vma->pages_count);
820 
821 unlock:
822 	mutex_unlock(&vma->pages_mutex);
823 
824 	return err;
825 }
826 
827 static void __vma_put_pages(struct i915_vma *vma, unsigned int count)
828 {
829 	/* We allocate under vma_get_pages, so beware the shrinker */
830 	mutex_lock_nested(&vma->pages_mutex, SINGLE_DEPTH_NESTING);
831 	GEM_BUG_ON(atomic_read(&vma->pages_count) < count);
832 	if (atomic_sub_return(count, &vma->pages_count) == 0) {
833 		vma->ops->clear_pages(vma);
834 		GEM_BUG_ON(vma->pages);
835 		if (vma->obj)
836 			i915_gem_object_unpin_pages(vma->obj);
837 	}
838 	mutex_unlock(&vma->pages_mutex);
839 }
840 
841 static void vma_put_pages(struct i915_vma *vma)
842 {
843 	if (atomic_add_unless(&vma->pages_count, -1, 1))
844 		return;
845 
846 	__vma_put_pages(vma, 1);
847 }
848 
849 static void vma_unbind_pages(struct i915_vma *vma)
850 {
851 	unsigned int count;
852 
853 	lockdep_assert_held(&vma->vm->mutex);
854 
855 	/* The upper portion of pages_count is the number of bindings */
856 	count = atomic_read(&vma->pages_count);
857 	count >>= I915_VMA_PAGES_BIAS;
858 	GEM_BUG_ON(!count);
859 
860 	__vma_put_pages(vma, count | count << I915_VMA_PAGES_BIAS);
861 }
862 
863 int i915_vma_pin(struct i915_vma *vma, u64 size, u64 alignment, u64 flags)
864 {
865 	struct i915_vma_work *work = NULL;
866 	intel_wakeref_t wakeref = 0;
867 	unsigned int bound;
868 	int err;
869 
870 	BUILD_BUG_ON(PIN_GLOBAL != I915_VMA_GLOBAL_BIND);
871 	BUILD_BUG_ON(PIN_USER != I915_VMA_LOCAL_BIND);
872 
873 	GEM_BUG_ON(!(flags & (PIN_USER | PIN_GLOBAL)));
874 
875 	/* First try and grab the pin without rebinding the vma */
876 	if (try_qad_pin(vma, flags & I915_VMA_BIND_MASK))
877 		return 0;
878 
879 	err = vma_get_pages(vma);
880 	if (err)
881 		return err;
882 
883 	if (flags & vma->vm->bind_async_flags) {
884 		work = i915_vma_work();
885 		if (!work) {
886 			err = -ENOMEM;
887 			goto err_pages;
888 		}
889 	}
890 
891 	if (flags & PIN_GLOBAL)
892 		wakeref = intel_runtime_pm_get(&vma->vm->i915->runtime_pm);
893 
894 	/*
895 	 * Differentiate between user/kernel vma inside the aliasing-ppgtt.
896 	 *
897 	 * We conflate the Global GTT with the user's vma when using the
898 	 * aliasing-ppgtt, but it is still vitally important to try and
899 	 * keep the use cases distinct. For example, userptr objects are
900 	 * not allowed inside the Global GTT as that will cause lock
901 	 * inversions when we have to evict them the mmu_notifier callbacks -
902 	 * but they are allowed to be part of the user ppGTT which can never
903 	 * be mapped. As such we try to give the distinct users of the same
904 	 * mutex, distinct lockclasses [equivalent to how we keep i915_ggtt
905 	 * and i915_ppgtt separate].
906 	 *
907 	 * NB this may cause us to mask real lock inversions -- while the
908 	 * code is safe today, lockdep may not be able to spot future
909 	 * transgressions.
910 	 */
911 	err = mutex_lock_interruptible_nested(&vma->vm->mutex,
912 					      !(flags & PIN_GLOBAL));
913 	if (err)
914 		goto err_fence;
915 
916 	/* No more allocations allowed now we hold vm->mutex */
917 
918 	if (unlikely(i915_vma_is_closed(vma))) {
919 		err = -ENOENT;
920 		goto err_unlock;
921 	}
922 
923 	bound = atomic_read(&vma->flags);
924 	if (unlikely(bound & I915_VMA_ERROR)) {
925 		err = -ENOMEM;
926 		goto err_unlock;
927 	}
928 
929 	if (unlikely(!((bound + 1) & I915_VMA_PIN_MASK))) {
930 		err = -EAGAIN; /* pins are meant to be fairly temporary */
931 		goto err_unlock;
932 	}
933 
934 	if (unlikely(!(flags & ~bound & I915_VMA_BIND_MASK))) {
935 		__i915_vma_pin(vma);
936 		goto err_unlock;
937 	}
938 
939 	err = i915_active_acquire(&vma->active);
940 	if (err)
941 		goto err_unlock;
942 
943 	if (!(bound & I915_VMA_BIND_MASK)) {
944 		err = i915_vma_insert(vma, size, alignment, flags);
945 		if (err)
946 			goto err_active;
947 
948 		if (i915_is_ggtt(vma->vm))
949 			__i915_vma_set_map_and_fenceable(vma);
950 	}
951 
952 	GEM_BUG_ON(!vma->pages);
953 	err = i915_vma_bind(vma,
954 			    vma->obj ? vma->obj->cache_level : 0,
955 			    flags, work);
956 	if (err)
957 		goto err_remove;
958 
959 	/* There should only be at most 2 active bindings (user, global) */
960 	GEM_BUG_ON(bound + I915_VMA_PAGES_ACTIVE < bound);
961 	atomic_add(I915_VMA_PAGES_ACTIVE, &vma->pages_count);
962 	list_move_tail(&vma->vm_link, &vma->vm->bound_list);
963 
964 	__i915_vma_pin(vma);
965 	GEM_BUG_ON(!i915_vma_is_pinned(vma));
966 	GEM_BUG_ON(!i915_vma_is_bound(vma, flags));
967 	GEM_BUG_ON(i915_vma_misplaced(vma, size, alignment, flags));
968 
969 err_remove:
970 	if (!i915_vma_is_bound(vma, I915_VMA_BIND_MASK)) {
971 		i915_vma_detach(vma);
972 		drm_mm_remove_node(&vma->node);
973 	}
974 err_active:
975 	i915_active_release(&vma->active);
976 err_unlock:
977 	mutex_unlock(&vma->vm->mutex);
978 err_fence:
979 	if (work)
980 		dma_fence_work_commit_imm(&work->base);
981 	if (wakeref)
982 		intel_runtime_pm_put(&vma->vm->i915->runtime_pm, wakeref);
983 err_pages:
984 	vma_put_pages(vma);
985 	return err;
986 }
987 
988 static void flush_idle_contexts(struct intel_gt *gt)
989 {
990 	struct intel_engine_cs *engine;
991 	enum intel_engine_id id;
992 
993 	for_each_engine(engine, gt, id)
994 		intel_engine_flush_barriers(engine);
995 
996 	intel_gt_wait_for_idle(gt, MAX_SCHEDULE_TIMEOUT);
997 }
998 
999 int i915_ggtt_pin(struct i915_vma *vma, u32 align, unsigned int flags)
1000 {
1001 	struct i915_address_space *vm = vma->vm;
1002 	int err;
1003 
1004 	GEM_BUG_ON(!i915_vma_is_ggtt(vma));
1005 
1006 	do {
1007 		err = i915_vma_pin(vma, 0, align, flags | PIN_GLOBAL);
1008 		if (err != -ENOSPC) {
1009 			if (!err) {
1010 				err = i915_vma_wait_for_bind(vma);
1011 				if (err)
1012 					i915_vma_unpin(vma);
1013 			}
1014 			return err;
1015 		}
1016 
1017 		/* Unlike i915_vma_pin, we don't take no for an answer! */
1018 		flush_idle_contexts(vm->gt);
1019 		if (mutex_lock_interruptible(&vm->mutex) == 0) {
1020 			i915_gem_evict_vm(vm);
1021 			mutex_unlock(&vm->mutex);
1022 		}
1023 	} while (1);
1024 }
1025 
1026 static void __vma_close(struct i915_vma *vma, struct intel_gt *gt)
1027 {
1028 	/*
1029 	 * We defer actually closing, unbinding and destroying the VMA until
1030 	 * the next idle point, or if the object is freed in the meantime. By
1031 	 * postponing the unbind, we allow for it to be resurrected by the
1032 	 * client, avoiding the work required to rebind the VMA. This is
1033 	 * advantageous for DRI, where the client/server pass objects
1034 	 * between themselves, temporarily opening a local VMA to the
1035 	 * object, and then closing it again. The same object is then reused
1036 	 * on the next frame (or two, depending on the depth of the swap queue)
1037 	 * causing us to rebind the VMA once more. This ends up being a lot
1038 	 * of wasted work for the steady state.
1039 	 */
1040 	GEM_BUG_ON(i915_vma_is_closed(vma));
1041 	list_add(&vma->closed_link, &gt->closed_vma);
1042 }
1043 
1044 void i915_vma_close(struct i915_vma *vma)
1045 {
1046 	struct intel_gt *gt = vma->vm->gt;
1047 	unsigned long flags;
1048 
1049 	if (i915_vma_is_ggtt(vma))
1050 		return;
1051 
1052 	GEM_BUG_ON(!atomic_read(&vma->open_count));
1053 	if (atomic_dec_and_lock_irqsave(&vma->open_count,
1054 					&gt->closed_lock,
1055 					flags)) {
1056 		__vma_close(vma, gt);
1057 		spin_unlock_irqrestore(&gt->closed_lock, flags);
1058 	}
1059 }
1060 
1061 static void __i915_vma_remove_closed(struct i915_vma *vma)
1062 {
1063 	struct intel_gt *gt = vma->vm->gt;
1064 
1065 	spin_lock_irq(&gt->closed_lock);
1066 	list_del_init(&vma->closed_link);
1067 	spin_unlock_irq(&gt->closed_lock);
1068 }
1069 
1070 void i915_vma_reopen(struct i915_vma *vma)
1071 {
1072 	if (i915_vma_is_closed(vma))
1073 		__i915_vma_remove_closed(vma);
1074 }
1075 
1076 void i915_vma_release(struct kref *ref)
1077 {
1078 	struct i915_vma *vma = container_of(ref, typeof(*vma), ref);
1079 
1080 	if (drm_mm_node_allocated(&vma->node)) {
1081 		mutex_lock(&vma->vm->mutex);
1082 		atomic_and(~I915_VMA_PIN_MASK, &vma->flags);
1083 		WARN_ON(__i915_vma_unbind(vma));
1084 		mutex_unlock(&vma->vm->mutex);
1085 		GEM_BUG_ON(drm_mm_node_allocated(&vma->node));
1086 	}
1087 	GEM_BUG_ON(i915_vma_is_active(vma));
1088 
1089 	if (vma->obj) {
1090 		struct drm_i915_gem_object *obj = vma->obj;
1091 
1092 		spin_lock(&obj->vma.lock);
1093 		list_del(&vma->obj_link);
1094 		if (!RB_EMPTY_NODE(&vma->obj_node))
1095 			rb_erase(&vma->obj_node, &obj->vma.tree);
1096 		spin_unlock(&obj->vma.lock);
1097 	}
1098 
1099 	__i915_vma_remove_closed(vma);
1100 	i915_vm_put(vma->vm);
1101 
1102 	i915_active_fini(&vma->active);
1103 	i915_vma_free(vma);
1104 }
1105 
1106 void i915_vma_parked(struct intel_gt *gt)
1107 {
1108 	struct i915_vma *vma, *next;
1109 	LIST_HEAD(closed);
1110 
1111 	spin_lock_irq(&gt->closed_lock);
1112 	list_for_each_entry_safe(vma, next, &gt->closed_vma, closed_link) {
1113 		struct drm_i915_gem_object *obj = vma->obj;
1114 		struct i915_address_space *vm = vma->vm;
1115 
1116 		/* XXX All to avoid keeping a reference on i915_vma itself */
1117 
1118 		if (!kref_get_unless_zero(&obj->base.refcount))
1119 			continue;
1120 
1121 		if (!i915_vm_tryopen(vm)) {
1122 			i915_gem_object_put(obj);
1123 			continue;
1124 		}
1125 
1126 		list_move(&vma->closed_link, &closed);
1127 	}
1128 	spin_unlock_irq(&gt->closed_lock);
1129 
1130 	/* As the GT is held idle, no vma can be reopened as we destroy them */
1131 	list_for_each_entry_safe(vma, next, &closed, closed_link) {
1132 		struct drm_i915_gem_object *obj = vma->obj;
1133 		struct i915_address_space *vm = vma->vm;
1134 
1135 		INIT_LIST_HEAD(&vma->closed_link);
1136 		__i915_vma_put(vma);
1137 
1138 		i915_gem_object_put(obj);
1139 		i915_vm_close(vm);
1140 	}
1141 }
1142 
1143 static void __i915_vma_iounmap(struct i915_vma *vma)
1144 {
1145 	GEM_BUG_ON(i915_vma_is_pinned(vma));
1146 
1147 	if (vma->iomap == NULL)
1148 		return;
1149 
1150 	io_mapping_unmap(vma->iomap);
1151 	vma->iomap = NULL;
1152 }
1153 
1154 void i915_vma_revoke_mmap(struct i915_vma *vma)
1155 {
1156 	struct drm_vma_offset_node *node;
1157 	u64 vma_offset;
1158 
1159 	if (!i915_vma_has_userfault(vma))
1160 		return;
1161 
1162 	GEM_BUG_ON(!i915_vma_is_map_and_fenceable(vma));
1163 	GEM_BUG_ON(!vma->obj->userfault_count);
1164 
1165 	node = &vma->mmo->vma_node;
1166 	vma_offset = vma->ggtt_view.partial.offset << PAGE_SHIFT;
1167 	unmap_mapping_range(vma->vm->i915->drm.anon_inode->i_mapping,
1168 			    drm_vma_node_offset_addr(node) + vma_offset,
1169 			    vma->size,
1170 			    1);
1171 
1172 	i915_vma_unset_userfault(vma);
1173 	if (!--vma->obj->userfault_count)
1174 		list_del(&vma->obj->userfault_link);
1175 }
1176 
1177 int __i915_vma_move_to_active(struct i915_vma *vma, struct i915_request *rq)
1178 {
1179 	int err;
1180 
1181 	GEM_BUG_ON(!i915_vma_is_pinned(vma));
1182 
1183 	/* Wait for the vma to be bound before we start! */
1184 	err = i915_request_await_active(rq, &vma->active,
1185 					I915_ACTIVE_AWAIT_EXCL);
1186 	if (err)
1187 		return err;
1188 
1189 	return i915_active_add_request(&vma->active, rq);
1190 }
1191 
1192 int i915_vma_move_to_active(struct i915_vma *vma,
1193 			    struct i915_request *rq,
1194 			    unsigned int flags)
1195 {
1196 	struct drm_i915_gem_object *obj = vma->obj;
1197 	int err;
1198 
1199 	assert_object_held(obj);
1200 
1201 	err = __i915_vma_move_to_active(vma, rq);
1202 	if (unlikely(err))
1203 		return err;
1204 
1205 	if (flags & EXEC_OBJECT_WRITE) {
1206 		struct intel_frontbuffer *front;
1207 
1208 		front = __intel_frontbuffer_get(obj);
1209 		if (unlikely(front)) {
1210 			if (intel_frontbuffer_invalidate(front, ORIGIN_CS))
1211 				i915_active_add_request(&front->write, rq);
1212 			intel_frontbuffer_put(front);
1213 		}
1214 
1215 		dma_resv_add_excl_fence(vma->resv, &rq->fence);
1216 		obj->write_domain = I915_GEM_DOMAIN_RENDER;
1217 		obj->read_domains = 0;
1218 	} else {
1219 		err = dma_resv_reserve_shared(vma->resv, 1);
1220 		if (unlikely(err))
1221 			return err;
1222 
1223 		dma_resv_add_shared_fence(vma->resv, &rq->fence);
1224 		obj->write_domain = 0;
1225 	}
1226 
1227 	if (flags & EXEC_OBJECT_NEEDS_FENCE && vma->fence)
1228 		i915_active_add_request(&vma->fence->active, rq);
1229 
1230 	obj->read_domains |= I915_GEM_GPU_DOMAINS;
1231 	obj->mm.dirty = true;
1232 
1233 	GEM_BUG_ON(!i915_vma_is_active(vma));
1234 	return 0;
1235 }
1236 
1237 void __i915_vma_evict(struct i915_vma *vma)
1238 {
1239 	GEM_BUG_ON(i915_vma_is_pinned(vma));
1240 
1241 	if (i915_vma_is_map_and_fenceable(vma)) {
1242 		/* Force a pagefault for domain tracking on next user access */
1243 		i915_vma_revoke_mmap(vma);
1244 
1245 		/*
1246 		 * Check that we have flushed all writes through the GGTT
1247 		 * before the unbind, other due to non-strict nature of those
1248 		 * indirect writes they may end up referencing the GGTT PTE
1249 		 * after the unbind.
1250 		 *
1251 		 * Note that we may be concurrently poking at the GGTT_WRITE
1252 		 * bit from set-domain, as we mark all GGTT vma associated
1253 		 * with an object. We know this is for another vma, as we
1254 		 * are currently unbinding this one -- so if this vma will be
1255 		 * reused, it will be refaulted and have its dirty bit set
1256 		 * before the next write.
1257 		 */
1258 		i915_vma_flush_writes(vma);
1259 
1260 		/* release the fence reg _after_ flushing */
1261 		i915_vma_revoke_fence(vma);
1262 
1263 		__i915_vma_iounmap(vma);
1264 		clear_bit(I915_VMA_CAN_FENCE_BIT, __i915_vma_flags(vma));
1265 	}
1266 	GEM_BUG_ON(vma->fence);
1267 	GEM_BUG_ON(i915_vma_has_userfault(vma));
1268 
1269 	if (likely(atomic_read(&vma->vm->open))) {
1270 		trace_i915_vma_unbind(vma);
1271 		vma->ops->unbind_vma(vma);
1272 	}
1273 	atomic_and(~(I915_VMA_BIND_MASK | I915_VMA_ERROR | I915_VMA_GGTT_WRITE),
1274 		   &vma->flags);
1275 
1276 	i915_vma_detach(vma);
1277 	vma_unbind_pages(vma);
1278 }
1279 
1280 int __i915_vma_unbind(struct i915_vma *vma)
1281 {
1282 	int ret;
1283 
1284 	lockdep_assert_held(&vma->vm->mutex);
1285 
1286 	if (!drm_mm_node_allocated(&vma->node))
1287 		return 0;
1288 
1289 	if (i915_vma_is_pinned(vma)) {
1290 		vma_print_allocator(vma, "is pinned");
1291 		return -EAGAIN;
1292 	}
1293 
1294 	/*
1295 	 * After confirming that no one else is pinning this vma, wait for
1296 	 * any laggards who may have crept in during the wait (through
1297 	 * a residual pin skipping the vm->mutex) to complete.
1298 	 */
1299 	ret = i915_vma_sync(vma);
1300 	if (ret)
1301 		return ret;
1302 
1303 	GEM_BUG_ON(i915_vma_is_active(vma));
1304 	__i915_vma_evict(vma);
1305 
1306 	drm_mm_remove_node(&vma->node); /* pairs with i915_vma_release() */
1307 	return 0;
1308 }
1309 
1310 int i915_vma_unbind(struct i915_vma *vma)
1311 {
1312 	struct i915_address_space *vm = vma->vm;
1313 	intel_wakeref_t wakeref = 0;
1314 	int err;
1315 
1316 	/* Optimistic wait before taking the mutex */
1317 	err = i915_vma_sync(vma);
1318 	if (err)
1319 		return err;
1320 
1321 	if (!drm_mm_node_allocated(&vma->node))
1322 		return 0;
1323 
1324 	if (i915_vma_is_pinned(vma)) {
1325 		vma_print_allocator(vma, "is pinned");
1326 		return -EAGAIN;
1327 	}
1328 
1329 	if (i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND))
1330 		/* XXX not always required: nop_clear_range */
1331 		wakeref = intel_runtime_pm_get(&vm->i915->runtime_pm);
1332 
1333 	err = mutex_lock_interruptible_nested(&vma->vm->mutex, !wakeref);
1334 	if (err)
1335 		goto out_rpm;
1336 
1337 	err = __i915_vma_unbind(vma);
1338 	mutex_unlock(&vm->mutex);
1339 
1340 out_rpm:
1341 	if (wakeref)
1342 		intel_runtime_pm_put(&vm->i915->runtime_pm, wakeref);
1343 	return err;
1344 }
1345 
1346 struct i915_vma *i915_vma_make_unshrinkable(struct i915_vma *vma)
1347 {
1348 	i915_gem_object_make_unshrinkable(vma->obj);
1349 	return vma;
1350 }
1351 
1352 void i915_vma_make_shrinkable(struct i915_vma *vma)
1353 {
1354 	i915_gem_object_make_shrinkable(vma->obj);
1355 }
1356 
1357 void i915_vma_make_purgeable(struct i915_vma *vma)
1358 {
1359 	i915_gem_object_make_purgeable(vma->obj);
1360 }
1361 
1362 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
1363 #include "selftests/i915_vma.c"
1364 #endif
1365 
1366 static void i915_global_vma_shrink(void)
1367 {
1368 	kmem_cache_shrink(global.slab_vmas);
1369 }
1370 
1371 static void i915_global_vma_exit(void)
1372 {
1373 	kmem_cache_destroy(global.slab_vmas);
1374 }
1375 
1376 static struct i915_global_vma global = { {
1377 	.shrink = i915_global_vma_shrink,
1378 	.exit = i915_global_vma_exit,
1379 } };
1380 
1381 int __init i915_global_vma_init(void)
1382 {
1383 	global.slab_vmas = KMEM_CACHE(i915_vma, SLAB_HWCACHE_ALIGN);
1384 	if (!global.slab_vmas)
1385 		return -ENOMEM;
1386 
1387 	i915_global_register(&global.base);
1388 	return 0;
1389 }
1390