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