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