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