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