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