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