1 /*
2  * Copyright © 2017 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 
27 #include <drm/drm_cache.h>
28 
29 #include "display/intel_frontbuffer.h"
30 #include "pxp/intel_pxp.h"
31 
32 #include "i915_drv.h"
33 #include "i915_file_private.h"
34 #include "i915_gem_clflush.h"
35 #include "i915_gem_context.h"
36 #include "i915_gem_dmabuf.h"
37 #include "i915_gem_mman.h"
38 #include "i915_gem_object.h"
39 #include "i915_gem_ttm.h"
40 #include "i915_memcpy.h"
41 #include "i915_trace.h"
42 
43 static struct kmem_cache *slab_objects;
44 
45 static const struct drm_gem_object_funcs i915_gem_object_funcs;
46 
47 struct drm_i915_gem_object *i915_gem_object_alloc(void)
48 {
49 	struct drm_i915_gem_object *obj;
50 
51 	obj = kmem_cache_zalloc(slab_objects, GFP_KERNEL);
52 	if (!obj)
53 		return NULL;
54 	obj->base.funcs = &i915_gem_object_funcs;
55 
56 	return obj;
57 }
58 
59 void i915_gem_object_free(struct drm_i915_gem_object *obj)
60 {
61 	return kmem_cache_free(slab_objects, obj);
62 }
63 
64 void i915_gem_object_init(struct drm_i915_gem_object *obj,
65 			  const struct drm_i915_gem_object_ops *ops,
66 			  struct lock_class_key *key, unsigned flags)
67 {
68 	/*
69 	 * A gem object is embedded both in a struct ttm_buffer_object :/ and
70 	 * in a drm_i915_gem_object. Make sure they are aliased.
71 	 */
72 	BUILD_BUG_ON(offsetof(typeof(*obj), base) !=
73 		     offsetof(typeof(*obj), __do_not_access.base));
74 
75 	spin_lock_init(&obj->vma.lock);
76 	INIT_LIST_HEAD(&obj->vma.list);
77 
78 	INIT_LIST_HEAD(&obj->mm.link);
79 
80 	INIT_LIST_HEAD(&obj->lut_list);
81 	spin_lock_init(&obj->lut_lock);
82 
83 	spin_lock_init(&obj->mmo.lock);
84 	obj->mmo.offsets = RB_ROOT;
85 
86 	init_rcu_head(&obj->rcu);
87 
88 	obj->ops = ops;
89 	GEM_BUG_ON(flags & ~I915_BO_ALLOC_FLAGS);
90 	obj->flags = flags;
91 
92 	obj->mm.madv = I915_MADV_WILLNEED;
93 	INIT_RADIX_TREE(&obj->mm.get_page.radix, GFP_KERNEL | __GFP_NOWARN);
94 	mutex_init(&obj->mm.get_page.lock);
95 	INIT_RADIX_TREE(&obj->mm.get_dma_page.radix, GFP_KERNEL | __GFP_NOWARN);
96 	mutex_init(&obj->mm.get_dma_page.lock);
97 }
98 
99 /**
100  * __i915_gem_object_fini - Clean up a GEM object initialization
101  * @obj: The gem object to cleanup
102  *
103  * This function cleans up gem object fields that are set up by
104  * drm_gem_private_object_init() and i915_gem_object_init().
105  * It's primarily intended as a helper for backends that need to
106  * clean up the gem object in separate steps.
107  */
108 void __i915_gem_object_fini(struct drm_i915_gem_object *obj)
109 {
110 	mutex_destroy(&obj->mm.get_page.lock);
111 	mutex_destroy(&obj->mm.get_dma_page.lock);
112 	dma_resv_fini(&obj->base._resv);
113 }
114 
115 /**
116  * i915_gem_object_set_cache_coherency - Mark up the object's coherency levels
117  * for a given cache_level
118  * @obj: #drm_i915_gem_object
119  * @cache_level: cache level
120  */
121 void i915_gem_object_set_cache_coherency(struct drm_i915_gem_object *obj,
122 					 unsigned int cache_level)
123 {
124 	struct drm_i915_private *i915 = to_i915(obj->base.dev);
125 
126 	obj->cache_level = cache_level;
127 
128 	if (cache_level != I915_CACHE_NONE)
129 		obj->cache_coherent = (I915_BO_CACHE_COHERENT_FOR_READ |
130 				       I915_BO_CACHE_COHERENT_FOR_WRITE);
131 	else if (HAS_LLC(i915))
132 		obj->cache_coherent = I915_BO_CACHE_COHERENT_FOR_READ;
133 	else
134 		obj->cache_coherent = 0;
135 
136 	obj->cache_dirty =
137 		!(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_WRITE) &&
138 		!IS_DGFX(i915);
139 }
140 
141 bool i915_gem_object_can_bypass_llc(struct drm_i915_gem_object *obj)
142 {
143 	struct drm_i915_private *i915 = to_i915(obj->base.dev);
144 
145 	/*
146 	 * This is purely from a security perspective, so we simply don't care
147 	 * about non-userspace objects being able to bypass the LLC.
148 	 */
149 	if (!(obj->flags & I915_BO_ALLOC_USER))
150 		return false;
151 
152 	/*
153 	 * EHL and JSL add the 'Bypass LLC' MOCS entry, which should make it
154 	 * possible for userspace to bypass the GTT caching bits set by the
155 	 * kernel, as per the given object cache_level. This is troublesome
156 	 * since the heavy flush we apply when first gathering the pages is
157 	 * skipped if the kernel thinks the object is coherent with the GPU. As
158 	 * a result it might be possible to bypass the cache and read the
159 	 * contents of the page directly, which could be stale data. If it's
160 	 * just a case of userspace shooting themselves in the foot then so be
161 	 * it, but since i915 takes the stance of always zeroing memory before
162 	 * handing it to userspace, we need to prevent this.
163 	 */
164 	return IS_JSL_EHL(i915);
165 }
166 
167 static void i915_gem_close_object(struct drm_gem_object *gem, struct drm_file *file)
168 {
169 	struct drm_i915_gem_object *obj = to_intel_bo(gem);
170 	struct drm_i915_file_private *fpriv = file->driver_priv;
171 	struct i915_lut_handle bookmark = {};
172 	struct i915_mmap_offset *mmo, *mn;
173 	struct i915_lut_handle *lut, *ln;
174 	LIST_HEAD(close);
175 
176 	spin_lock(&obj->lut_lock);
177 	list_for_each_entry_safe(lut, ln, &obj->lut_list, obj_link) {
178 		struct i915_gem_context *ctx = lut->ctx;
179 
180 		if (ctx && ctx->file_priv == fpriv) {
181 			i915_gem_context_get(ctx);
182 			list_move(&lut->obj_link, &close);
183 		}
184 
185 		/* Break long locks, and carefully continue on from this spot */
186 		if (&ln->obj_link != &obj->lut_list) {
187 			list_add_tail(&bookmark.obj_link, &ln->obj_link);
188 			if (cond_resched_lock(&obj->lut_lock))
189 				list_safe_reset_next(&bookmark, ln, obj_link);
190 			__list_del_entry(&bookmark.obj_link);
191 		}
192 	}
193 	spin_unlock(&obj->lut_lock);
194 
195 	spin_lock(&obj->mmo.lock);
196 	rbtree_postorder_for_each_entry_safe(mmo, mn, &obj->mmo.offsets, offset)
197 		drm_vma_node_revoke(&mmo->vma_node, file);
198 	spin_unlock(&obj->mmo.lock);
199 
200 	list_for_each_entry_safe(lut, ln, &close, obj_link) {
201 		struct i915_gem_context *ctx = lut->ctx;
202 		struct i915_vma *vma;
203 
204 		/*
205 		 * We allow the process to have multiple handles to the same
206 		 * vma, in the same fd namespace, by virtue of flink/open.
207 		 */
208 
209 		mutex_lock(&ctx->lut_mutex);
210 		vma = radix_tree_delete(&ctx->handles_vma, lut->handle);
211 		if (vma) {
212 			GEM_BUG_ON(vma->obj != obj);
213 			GEM_BUG_ON(!atomic_read(&vma->open_count));
214 			i915_vma_close(vma);
215 		}
216 		mutex_unlock(&ctx->lut_mutex);
217 
218 		i915_gem_context_put(lut->ctx);
219 		i915_lut_handle_free(lut);
220 		i915_gem_object_put(obj);
221 	}
222 }
223 
224 void __i915_gem_free_object_rcu(struct rcu_head *head)
225 {
226 	struct drm_i915_gem_object *obj =
227 		container_of(head, typeof(*obj), rcu);
228 	struct drm_i915_private *i915 = to_i915(obj->base.dev);
229 
230 	i915_gem_object_free(obj);
231 
232 	GEM_BUG_ON(!atomic_read(&i915->mm.free_count));
233 	atomic_dec(&i915->mm.free_count);
234 }
235 
236 static void __i915_gem_object_free_mmaps(struct drm_i915_gem_object *obj)
237 {
238 	/* Skip serialisation and waking the device if known to be not used. */
239 
240 	if (obj->userfault_count)
241 		i915_gem_object_release_mmap_gtt(obj);
242 
243 	if (!RB_EMPTY_ROOT(&obj->mmo.offsets)) {
244 		struct i915_mmap_offset *mmo, *mn;
245 
246 		i915_gem_object_release_mmap_offset(obj);
247 
248 		rbtree_postorder_for_each_entry_safe(mmo, mn,
249 						     &obj->mmo.offsets,
250 						     offset) {
251 			drm_vma_offset_remove(obj->base.dev->vma_offset_manager,
252 					      &mmo->vma_node);
253 			kfree(mmo);
254 		}
255 		obj->mmo.offsets = RB_ROOT;
256 	}
257 }
258 
259 /**
260  * __i915_gem_object_pages_fini - Clean up pages use of a gem object
261  * @obj: The gem object to clean up
262  *
263  * This function cleans up usage of the object mm.pages member. It
264  * is intended for backends that need to clean up a gem object in
265  * separate steps and needs to be called when the object is idle before
266  * the object's backing memory is freed.
267  */
268 void __i915_gem_object_pages_fini(struct drm_i915_gem_object *obj)
269 {
270 	assert_object_held(obj);
271 
272 	if (!list_empty(&obj->vma.list)) {
273 		struct i915_vma *vma;
274 
275 		/*
276 		 * Note that the vma keeps an object reference while
277 		 * it is active, so it *should* not sleep while we
278 		 * destroy it. Our debug code errs insits it *might*.
279 		 * For the moment, play along.
280 		 */
281 		spin_lock(&obj->vma.lock);
282 		while ((vma = list_first_entry_or_null(&obj->vma.list,
283 						       struct i915_vma,
284 						       obj_link))) {
285 			GEM_BUG_ON(vma->obj != obj);
286 			spin_unlock(&obj->vma.lock);
287 
288 			/* Verify that the vma is unbound under the vm mutex. */
289 			mutex_lock(&vma->vm->mutex);
290 			atomic_and(~I915_VMA_PIN_MASK, &vma->flags);
291 			__i915_vma_unbind(vma);
292 			mutex_unlock(&vma->vm->mutex);
293 
294 			__i915_vma_put(vma);
295 
296 			spin_lock(&obj->vma.lock);
297 		}
298 		spin_unlock(&obj->vma.lock);
299 	}
300 
301 	__i915_gem_object_free_mmaps(obj);
302 
303 	atomic_set(&obj->mm.pages_pin_count, 0);
304 	__i915_gem_object_put_pages(obj);
305 	GEM_BUG_ON(i915_gem_object_has_pages(obj));
306 }
307 
308 void __i915_gem_free_object(struct drm_i915_gem_object *obj)
309 {
310 	trace_i915_gem_object_destroy(obj);
311 
312 	GEM_BUG_ON(!list_empty(&obj->lut_list));
313 
314 	bitmap_free(obj->bit_17);
315 
316 	if (obj->base.import_attach)
317 		drm_prime_gem_destroy(&obj->base, NULL);
318 
319 	drm_gem_free_mmap_offset(&obj->base);
320 
321 	if (obj->ops->release)
322 		obj->ops->release(obj);
323 
324 	if (obj->mm.n_placements > 1)
325 		kfree(obj->mm.placements);
326 
327 	if (obj->shares_resv_from)
328 		i915_vm_resv_put(obj->shares_resv_from);
329 
330 	__i915_gem_object_fini(obj);
331 }
332 
333 static void __i915_gem_free_objects(struct drm_i915_private *i915,
334 				    struct llist_node *freed)
335 {
336 	struct drm_i915_gem_object *obj, *on;
337 
338 	llist_for_each_entry_safe(obj, on, freed, freed) {
339 		might_sleep();
340 		if (obj->ops->delayed_free) {
341 			obj->ops->delayed_free(obj);
342 			continue;
343 		}
344 
345 		if (!i915_gem_object_trylock(obj, NULL)) {
346 			/* busy, toss it back to the pile */
347 			if (llist_add(&obj->freed, &i915->mm.free_list))
348 				queue_delayed_work(i915->wq, &i915->mm.free_work, msecs_to_jiffies(10));
349 			continue;
350 		}
351 
352 		__i915_gem_object_pages_fini(obj);
353 		i915_gem_object_unlock(obj);
354 		__i915_gem_free_object(obj);
355 
356 		/* But keep the pointer alive for RCU-protected lookups */
357 		call_rcu(&obj->rcu, __i915_gem_free_object_rcu);
358 		cond_resched();
359 	}
360 }
361 
362 void i915_gem_flush_free_objects(struct drm_i915_private *i915)
363 {
364 	struct llist_node *freed = llist_del_all(&i915->mm.free_list);
365 
366 	if (unlikely(freed))
367 		__i915_gem_free_objects(i915, freed);
368 }
369 
370 static void __i915_gem_free_work(struct work_struct *work)
371 {
372 	struct drm_i915_private *i915 =
373 		container_of(work, struct drm_i915_private, mm.free_work.work);
374 
375 	i915_gem_flush_free_objects(i915);
376 }
377 
378 static void i915_gem_free_object(struct drm_gem_object *gem_obj)
379 {
380 	struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
381 	struct drm_i915_private *i915 = to_i915(obj->base.dev);
382 
383 	GEM_BUG_ON(i915_gem_object_is_framebuffer(obj));
384 
385 	/*
386 	 * Before we free the object, make sure any pure RCU-only
387 	 * read-side critical sections are complete, e.g.
388 	 * i915_gem_busy_ioctl(). For the corresponding synchronized
389 	 * lookup see i915_gem_object_lookup_rcu().
390 	 */
391 	atomic_inc(&i915->mm.free_count);
392 
393 	/*
394 	 * Since we require blocking on struct_mutex to unbind the freed
395 	 * object from the GPU before releasing resources back to the
396 	 * system, we can not do that directly from the RCU callback (which may
397 	 * be a softirq context), but must instead then defer that work onto a
398 	 * kthread. We use the RCU callback rather than move the freed object
399 	 * directly onto the work queue so that we can mix between using the
400 	 * worker and performing frees directly from subsequent allocations for
401 	 * crude but effective memory throttling.
402 	 */
403 
404 	if (llist_add(&obj->freed, &i915->mm.free_list))
405 		queue_delayed_work(i915->wq, &i915->mm.free_work, 0);
406 }
407 
408 void __i915_gem_object_flush_frontbuffer(struct drm_i915_gem_object *obj,
409 					 enum fb_op_origin origin)
410 {
411 	struct intel_frontbuffer *front;
412 
413 	front = __intel_frontbuffer_get(obj);
414 	if (front) {
415 		intel_frontbuffer_flush(front, origin);
416 		intel_frontbuffer_put(front);
417 	}
418 }
419 
420 void __i915_gem_object_invalidate_frontbuffer(struct drm_i915_gem_object *obj,
421 					      enum fb_op_origin origin)
422 {
423 	struct intel_frontbuffer *front;
424 
425 	front = __intel_frontbuffer_get(obj);
426 	if (front) {
427 		intel_frontbuffer_invalidate(front, origin);
428 		intel_frontbuffer_put(front);
429 	}
430 }
431 
432 static void
433 i915_gem_object_read_from_page_kmap(struct drm_i915_gem_object *obj, u64 offset, void *dst, int size)
434 {
435 	void *src_map;
436 	void *src_ptr;
437 
438 	src_map = kmap_atomic(i915_gem_object_get_page(obj, offset >> PAGE_SHIFT));
439 
440 	src_ptr = src_map + offset_in_page(offset);
441 	if (!(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ))
442 		drm_clflush_virt_range(src_ptr, size);
443 	memcpy(dst, src_ptr, size);
444 
445 	kunmap_atomic(src_map);
446 }
447 
448 static void
449 i915_gem_object_read_from_page_iomap(struct drm_i915_gem_object *obj, u64 offset, void *dst, int size)
450 {
451 	void __iomem *src_map;
452 	void __iomem *src_ptr;
453 	dma_addr_t dma = i915_gem_object_get_dma_address(obj, offset >> PAGE_SHIFT);
454 
455 	src_map = io_mapping_map_wc(&obj->mm.region->iomap,
456 				    dma - obj->mm.region->region.start,
457 				    PAGE_SIZE);
458 
459 	src_ptr = src_map + offset_in_page(offset);
460 	if (!i915_memcpy_from_wc(dst, (void __force *)src_ptr, size))
461 		memcpy_fromio(dst, src_ptr, size);
462 
463 	io_mapping_unmap(src_map);
464 }
465 
466 /**
467  * i915_gem_object_read_from_page - read data from the page of a GEM object
468  * @obj: GEM object to read from
469  * @offset: offset within the object
470  * @dst: buffer to store the read data
471  * @size: size to read
472  *
473  * Reads data from @obj at the specified offset. The requested region to read
474  * from can't cross a page boundary. The caller must ensure that @obj pages
475  * are pinned and that @obj is synced wrt. any related writes.
476  *
477  * Return: %0 on success or -ENODEV if the type of @obj's backing store is
478  * unsupported.
479  */
480 int i915_gem_object_read_from_page(struct drm_i915_gem_object *obj, u64 offset, void *dst, int size)
481 {
482 	GEM_BUG_ON(offset >= obj->base.size);
483 	GEM_BUG_ON(offset_in_page(offset) > PAGE_SIZE - size);
484 	GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
485 
486 	if (i915_gem_object_has_struct_page(obj))
487 		i915_gem_object_read_from_page_kmap(obj, offset, dst, size);
488 	else if (i915_gem_object_has_iomem(obj))
489 		i915_gem_object_read_from_page_iomap(obj, offset, dst, size);
490 	else
491 		return -ENODEV;
492 
493 	return 0;
494 }
495 
496 /**
497  * i915_gem_object_evictable - Whether object is likely evictable after unbind.
498  * @obj: The object to check
499  *
500  * This function checks whether the object is likely unvictable after unbind.
501  * If the object is not locked when checking, the result is only advisory.
502  * If the object is locked when checking, and the function returns true,
503  * then an eviction should indeed be possible. But since unlocked vma
504  * unpinning and unbinding is currently possible, the object can actually
505  * become evictable even if this function returns false.
506  *
507  * Return: true if the object may be evictable. False otherwise.
508  */
509 bool i915_gem_object_evictable(struct drm_i915_gem_object *obj)
510 {
511 	struct i915_vma *vma;
512 	int pin_count = atomic_read(&obj->mm.pages_pin_count);
513 
514 	if (!pin_count)
515 		return true;
516 
517 	spin_lock(&obj->vma.lock);
518 	list_for_each_entry(vma, &obj->vma.list, obj_link) {
519 		if (i915_vma_is_pinned(vma)) {
520 			spin_unlock(&obj->vma.lock);
521 			return false;
522 		}
523 		if (atomic_read(&vma->pages_count))
524 			pin_count--;
525 	}
526 	spin_unlock(&obj->vma.lock);
527 	GEM_WARN_ON(pin_count < 0);
528 
529 	return pin_count == 0;
530 }
531 
532 /**
533  * i915_gem_object_migratable - Whether the object is migratable out of the
534  * current region.
535  * @obj: Pointer to the object.
536  *
537  * Return: Whether the object is allowed to be resident in other
538  * regions than the current while pages are present.
539  */
540 bool i915_gem_object_migratable(struct drm_i915_gem_object *obj)
541 {
542 	struct intel_memory_region *mr = READ_ONCE(obj->mm.region);
543 
544 	if (!mr)
545 		return false;
546 
547 	return obj->mm.n_placements > 1;
548 }
549 
550 /**
551  * i915_gem_object_has_struct_page - Whether the object is page-backed
552  * @obj: The object to query.
553  *
554  * This function should only be called while the object is locked or pinned,
555  * otherwise the page backing may change under the caller.
556  *
557  * Return: True if page-backed, false otherwise.
558  */
559 bool i915_gem_object_has_struct_page(const struct drm_i915_gem_object *obj)
560 {
561 #ifdef CONFIG_LOCKDEP
562 	if (IS_DGFX(to_i915(obj->base.dev)) &&
563 	    i915_gem_object_evictable((void __force *)obj))
564 		assert_object_held_shared(obj);
565 #endif
566 	return obj->mem_flags & I915_BO_FLAG_STRUCT_PAGE;
567 }
568 
569 /**
570  * i915_gem_object_has_iomem - Whether the object is iomem-backed
571  * @obj: The object to query.
572  *
573  * This function should only be called while the object is locked or pinned,
574  * otherwise the iomem backing may change under the caller.
575  *
576  * Return: True if iomem-backed, false otherwise.
577  */
578 bool i915_gem_object_has_iomem(const struct drm_i915_gem_object *obj)
579 {
580 #ifdef CONFIG_LOCKDEP
581 	if (IS_DGFX(to_i915(obj->base.dev)) &&
582 	    i915_gem_object_evictable((void __force *)obj))
583 		assert_object_held_shared(obj);
584 #endif
585 	return obj->mem_flags & I915_BO_FLAG_IOMEM;
586 }
587 
588 /**
589  * i915_gem_object_can_migrate - Whether an object likely can be migrated
590  *
591  * @obj: The object to migrate
592  * @id: The region intended to migrate to
593  *
594  * Check whether the object backend supports migration to the
595  * given region. Note that pinning may affect the ability to migrate as
596  * returned by this function.
597  *
598  * This function is primarily intended as a helper for checking the
599  * possibility to migrate objects and might be slightly less permissive
600  * than i915_gem_object_migrate() when it comes to objects with the
601  * I915_BO_ALLOC_USER flag set.
602  *
603  * Return: true if migration is possible, false otherwise.
604  */
605 bool i915_gem_object_can_migrate(struct drm_i915_gem_object *obj,
606 				 enum intel_region_id id)
607 {
608 	struct drm_i915_private *i915 = to_i915(obj->base.dev);
609 	unsigned int num_allowed = obj->mm.n_placements;
610 	struct intel_memory_region *mr;
611 	unsigned int i;
612 
613 	GEM_BUG_ON(id >= INTEL_REGION_UNKNOWN);
614 	GEM_BUG_ON(obj->mm.madv != I915_MADV_WILLNEED);
615 
616 	mr = i915->mm.regions[id];
617 	if (!mr)
618 		return false;
619 
620 	if (obj->mm.region == mr)
621 		return true;
622 
623 	if (!i915_gem_object_evictable(obj))
624 		return false;
625 
626 	if (!obj->ops->migrate)
627 		return false;
628 
629 	if (!(obj->flags & I915_BO_ALLOC_USER))
630 		return true;
631 
632 	if (num_allowed == 0)
633 		return false;
634 
635 	for (i = 0; i < num_allowed; ++i) {
636 		if (mr == obj->mm.placements[i])
637 			return true;
638 	}
639 
640 	return false;
641 }
642 
643 /**
644  * i915_gem_object_migrate - Migrate an object to the desired region id
645  * @obj: The object to migrate.
646  * @ww: An optional struct i915_gem_ww_ctx. If NULL, the backend may
647  * not be successful in evicting other objects to make room for this object.
648  * @id: The region id to migrate to.
649  *
650  * Attempt to migrate the object to the desired memory region. The
651  * object backend must support migration and the object may not be
652  * pinned, (explicitly pinned pages or pinned vmas). The object must
653  * be locked.
654  * On successful completion, the object will have pages pointing to
655  * memory in the new region, but an async migration task may not have
656  * completed yet, and to accomplish that, i915_gem_object_wait_migration()
657  * must be called.
658  *
659  * Note: the @ww parameter is not used yet, but included to make sure
660  * callers put some effort into obtaining a valid ww ctx if one is
661  * available.
662  *
663  * Return: 0 on success. Negative error code on failure. In particular may
664  * return -ENXIO on lack of region space, -EDEADLK for deadlock avoidance
665  * if @ww is set, -EINTR or -ERESTARTSYS if signal pending, and
666  * -EBUSY if the object is pinned.
667  */
668 int i915_gem_object_migrate(struct drm_i915_gem_object *obj,
669 			    struct i915_gem_ww_ctx *ww,
670 			    enum intel_region_id id)
671 {
672 	struct drm_i915_private *i915 = to_i915(obj->base.dev);
673 	struct intel_memory_region *mr;
674 
675 	GEM_BUG_ON(id >= INTEL_REGION_UNKNOWN);
676 	GEM_BUG_ON(obj->mm.madv != I915_MADV_WILLNEED);
677 	assert_object_held(obj);
678 
679 	mr = i915->mm.regions[id];
680 	GEM_BUG_ON(!mr);
681 
682 	if (!i915_gem_object_can_migrate(obj, id))
683 		return -EINVAL;
684 
685 	if (!obj->ops->migrate) {
686 		if (GEM_WARN_ON(obj->mm.region != mr))
687 			return -EINVAL;
688 		return 0;
689 	}
690 
691 	return obj->ops->migrate(obj, mr);
692 }
693 
694 /**
695  * i915_gem_object_placement_possible - Check whether the object can be
696  * placed at certain memory type
697  * @obj: Pointer to the object
698  * @type: The memory type to check
699  *
700  * Return: True if the object can be placed in @type. False otherwise.
701  */
702 bool i915_gem_object_placement_possible(struct drm_i915_gem_object *obj,
703 					enum intel_memory_type type)
704 {
705 	unsigned int i;
706 
707 	if (!obj->mm.n_placements) {
708 		switch (type) {
709 		case INTEL_MEMORY_LOCAL:
710 			return i915_gem_object_has_iomem(obj);
711 		case INTEL_MEMORY_SYSTEM:
712 			return i915_gem_object_has_pages(obj);
713 		default:
714 			/* Ignore stolen for now */
715 			GEM_BUG_ON(1);
716 			return false;
717 		}
718 	}
719 
720 	for (i = 0; i < obj->mm.n_placements; i++) {
721 		if (obj->mm.placements[i]->type == type)
722 			return true;
723 	}
724 
725 	return false;
726 }
727 
728 void i915_gem_init__objects(struct drm_i915_private *i915)
729 {
730 	INIT_DELAYED_WORK(&i915->mm.free_work, __i915_gem_free_work);
731 }
732 
733 void i915_objects_module_exit(void)
734 {
735 	kmem_cache_destroy(slab_objects);
736 }
737 
738 int __init i915_objects_module_init(void)
739 {
740 	slab_objects = KMEM_CACHE(drm_i915_gem_object, SLAB_HWCACHE_ALIGN);
741 	if (!slab_objects)
742 		return -ENOMEM;
743 
744 	return 0;
745 }
746 
747 static const struct drm_gem_object_funcs i915_gem_object_funcs = {
748 	.free = i915_gem_free_object,
749 	.close = i915_gem_close_object,
750 	.export = i915_gem_prime_export,
751 };
752 
753 /**
754  * i915_gem_object_get_moving_fence - Get the object's moving fence if any
755  * @obj: The object whose moving fence to get.
756  *
757  * A non-signaled moving fence means that there is an async operation
758  * pending on the object that needs to be waited on before setting up
759  * any GPU- or CPU PTEs to the object's pages.
760  *
761  * Return: A refcounted pointer to the object's moving fence if any,
762  * NULL otherwise.
763  */
764 struct dma_fence *
765 i915_gem_object_get_moving_fence(struct drm_i915_gem_object *obj)
766 {
767 	return dma_fence_get(i915_gem_to_ttm(obj)->moving);
768 }
769 
770 void i915_gem_object_set_moving_fence(struct drm_i915_gem_object *obj,
771 				      struct dma_fence *fence)
772 {
773 	struct dma_fence **moving = &i915_gem_to_ttm(obj)->moving;
774 
775 	if (*moving == fence)
776 		return;
777 
778 	dma_fence_put(*moving);
779 	*moving = dma_fence_get(fence);
780 }
781 
782 /**
783  * i915_gem_object_wait_moving_fence - Wait for the object's moving fence if any
784  * @obj: The object whose moving fence to wait for.
785  * @intr: Whether to wait interruptible.
786  *
787  * If the moving fence signaled without an error, it is detached from the
788  * object and put.
789  *
790  * Return: 0 if successful, -ERESTARTSYS if the wait was interrupted,
791  * negative error code if the async operation represented by the
792  * moving fence failed.
793  */
794 int i915_gem_object_wait_moving_fence(struct drm_i915_gem_object *obj,
795 				      bool intr)
796 {
797 	struct dma_fence *fence = i915_gem_to_ttm(obj)->moving;
798 	int ret;
799 
800 	assert_object_held(obj);
801 	if (!fence)
802 		return 0;
803 
804 	ret = dma_fence_wait(fence, intr);
805 	if (ret)
806 		return ret;
807 
808 	if (fence->error)
809 		return fence->error;
810 
811 	i915_gem_to_ttm(obj)->moving = NULL;
812 	dma_fence_put(fence);
813 	return 0;
814 }
815 
816 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
817 #include "selftests/huge_gem_object.c"
818 #include "selftests/huge_pages.c"
819 #include "selftests/i915_gem_migrate.c"
820 #include "selftests/i915_gem_object.c"
821 #include "selftests/i915_gem_coherency.c"
822 #endif
823