xref: /linux/drivers/gpu/drm/drm_gem.c (revision 504f9bdd3a1588604b0452bfe927ff86e5f6e6df)
1 /*
2  * Copyright © 2008 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  * Authors:
24  *    Eric Anholt <eric@anholt.net>
25  *
26  */
27 
28 #include <linux/dma-buf.h>
29 #include <linux/export.h>
30 #include <linux/file.h>
31 #include <linux/fs.h>
32 #include <linux/iosys-map.h>
33 #include <linux/mem_encrypt.h>
34 #include <linux/mm.h>
35 #include <linux/mman.h>
36 #include <linux/module.h>
37 #include <linux/pagemap.h>
38 #include <linux/pagevec.h>
39 #include <linux/shmem_fs.h>
40 #include <linux/slab.h>
41 #include <linux/string_helpers.h>
42 #include <linux/types.h>
43 #include <linux/uaccess.h>
44 
45 #include <drm/drm.h>
46 #include <drm/drm_device.h>
47 #include <drm/drm_drv.h>
48 #include <drm/drm_file.h>
49 #include <drm/drm_gem.h>
50 #include <drm/drm_managed.h>
51 #include <drm/drm_print.h>
52 #include <drm/drm_vma_manager.h>
53 
54 #include "drm_internal.h"
55 
56 /** @file drm_gem.c
57  *
58  * This file provides some of the base ioctls and library routines for
59  * the graphics memory manager implemented by each device driver.
60  *
61  * Because various devices have different requirements in terms of
62  * synchronization and migration strategies, implementing that is left up to
63  * the driver, and all that the general API provides should be generic --
64  * allocating objects, reading/writing data with the cpu, freeing objects.
65  * Even there, platform-dependent optimizations for reading/writing data with
66  * the CPU mean we'll likely hook those out to driver-specific calls.  However,
67  * the DRI2 implementation wants to have at least allocate/mmap be generic.
68  *
69  * The goal was to have swap-backed object allocation managed through
70  * struct file.  However, file descriptors as handles to a struct file have
71  * two major failings:
72  * - Process limits prevent more than 1024 or so being used at a time by
73  *   default.
74  * - Inability to allocate high fds will aggravate the X Server's select()
75  *   handling, and likely that of many GL client applications as well.
76  *
77  * This led to a plan of using our own integer IDs (called handles, following
78  * DRM terminology) to mimic fds, and implement the fd syscalls we need as
79  * ioctls.  The objects themselves will still include the struct file so
80  * that we can transition to fds if the required kernel infrastructure shows
81  * up at a later date, and as our interface with shmfs for memory allocation.
82  */
83 
84 static void
85 drm_gem_init_release(struct drm_device *dev, void *ptr)
86 {
87 	drm_vma_offset_manager_destroy(dev->vma_offset_manager);
88 }
89 
90 /**
91  * drm_gem_init - Initialize the GEM device fields
92  * @dev: drm_devic structure to initialize
93  */
94 int
95 drm_gem_init(struct drm_device *dev)
96 {
97 	struct drm_vma_offset_manager *vma_offset_manager;
98 
99 	mutex_init(&dev->object_name_lock);
100 	idr_init_base(&dev->object_name_idr, 1);
101 
102 	vma_offset_manager = drmm_kzalloc(dev, sizeof(*vma_offset_manager),
103 					  GFP_KERNEL);
104 	if (!vma_offset_manager) {
105 		DRM_ERROR("out of memory\n");
106 		return -ENOMEM;
107 	}
108 
109 	dev->vma_offset_manager = vma_offset_manager;
110 	drm_vma_offset_manager_init(vma_offset_manager,
111 				    DRM_FILE_PAGE_OFFSET_START,
112 				    DRM_FILE_PAGE_OFFSET_SIZE);
113 
114 	return drmm_add_action(dev, drm_gem_init_release, NULL);
115 }
116 
117 /**
118  * drm_gem_object_init_with_mnt - initialize an allocated shmem-backed GEM
119  * object in a given shmfs mountpoint
120  *
121  * @dev: drm_device the object should be initialized for
122  * @obj: drm_gem_object to initialize
123  * @size: object size
124  * @gemfs: tmpfs mount where the GEM object will be created. If NULL, use
125  * the usual tmpfs mountpoint (`shm_mnt`).
126  *
127  * Initialize an already allocated GEM object of the specified size with
128  * shmfs backing store.
129  */
130 int drm_gem_object_init_with_mnt(struct drm_device *dev,
131 				 struct drm_gem_object *obj, size_t size,
132 				 struct vfsmount *gemfs)
133 {
134 	struct file *filp;
135 
136 	drm_gem_private_object_init(dev, obj, size);
137 
138 	if (gemfs)
139 		filp = shmem_file_setup_with_mnt(gemfs, "drm mm object", size,
140 						 VM_NORESERVE);
141 	else
142 		filp = shmem_file_setup("drm mm object", size, VM_NORESERVE);
143 
144 	if (IS_ERR(filp))
145 		return PTR_ERR(filp);
146 
147 	obj->filp = filp;
148 
149 	return 0;
150 }
151 EXPORT_SYMBOL(drm_gem_object_init_with_mnt);
152 
153 /**
154  * drm_gem_object_init - initialize an allocated shmem-backed GEM object
155  * @dev: drm_device the object should be initialized for
156  * @obj: drm_gem_object to initialize
157  * @size: object size
158  *
159  * Initialize an already allocated GEM object of the specified size with
160  * shmfs backing store.
161  */
162 int drm_gem_object_init(struct drm_device *dev, struct drm_gem_object *obj,
163 			size_t size)
164 {
165 	return drm_gem_object_init_with_mnt(dev, obj, size, NULL);
166 }
167 EXPORT_SYMBOL(drm_gem_object_init);
168 
169 /**
170  * drm_gem_private_object_init - initialize an allocated private GEM object
171  * @dev: drm_device the object should be initialized for
172  * @obj: drm_gem_object to initialize
173  * @size: object size
174  *
175  * Initialize an already allocated GEM object of the specified size with
176  * no GEM provided backing store. Instead the caller is responsible for
177  * backing the object and handling it.
178  */
179 void drm_gem_private_object_init(struct drm_device *dev,
180 				 struct drm_gem_object *obj, size_t size)
181 {
182 	BUG_ON((size & (PAGE_SIZE - 1)) != 0);
183 
184 	obj->dev = dev;
185 	obj->filp = NULL;
186 
187 	kref_init(&obj->refcount);
188 	obj->handle_count = 0;
189 	obj->size = size;
190 	dma_resv_init(&obj->_resv);
191 	if (!obj->resv)
192 		obj->resv = &obj->_resv;
193 
194 	if (drm_core_check_feature(dev, DRIVER_GEM_GPUVA))
195 		drm_gem_gpuva_init(obj);
196 
197 	drm_vma_node_reset(&obj->vma_node);
198 	INIT_LIST_HEAD(&obj->lru_node);
199 }
200 EXPORT_SYMBOL(drm_gem_private_object_init);
201 
202 /**
203  * drm_gem_private_object_fini - Finalize a failed drm_gem_object
204  * @obj: drm_gem_object
205  *
206  * Uninitialize an already allocated GEM object when it initialized failed
207  */
208 void drm_gem_private_object_fini(struct drm_gem_object *obj)
209 {
210 	WARN_ON(obj->dma_buf);
211 
212 	dma_resv_fini(&obj->_resv);
213 }
214 EXPORT_SYMBOL(drm_gem_private_object_fini);
215 
216 /**
217  * drm_gem_object_handle_free - release resources bound to userspace handles
218  * @obj: GEM object to clean up.
219  *
220  * Called after the last handle to the object has been closed
221  *
222  * Removes any name for the object. Note that this must be
223  * called before drm_gem_object_free or we'll be touching
224  * freed memory
225  */
226 static void drm_gem_object_handle_free(struct drm_gem_object *obj)
227 {
228 	struct drm_device *dev = obj->dev;
229 
230 	/* Remove any name for this object */
231 	if (obj->name) {
232 		idr_remove(&dev->object_name_idr, obj->name);
233 		obj->name = 0;
234 	}
235 }
236 
237 static void drm_gem_object_exported_dma_buf_free(struct drm_gem_object *obj)
238 {
239 	/* Unbreak the reference cycle if we have an exported dma_buf. */
240 	if (obj->dma_buf) {
241 		dma_buf_put(obj->dma_buf);
242 		obj->dma_buf = NULL;
243 	}
244 }
245 
246 static void
247 drm_gem_object_handle_put_unlocked(struct drm_gem_object *obj)
248 {
249 	struct drm_device *dev = obj->dev;
250 	bool final = false;
251 
252 	if (WARN_ON(READ_ONCE(obj->handle_count) == 0))
253 		return;
254 
255 	/*
256 	* Must bump handle count first as this may be the last
257 	* ref, in which case the object would disappear before we
258 	* checked for a name
259 	*/
260 
261 	mutex_lock(&dev->object_name_lock);
262 	if (--obj->handle_count == 0) {
263 		drm_gem_object_handle_free(obj);
264 		drm_gem_object_exported_dma_buf_free(obj);
265 		final = true;
266 	}
267 	mutex_unlock(&dev->object_name_lock);
268 
269 	if (final)
270 		drm_gem_object_put(obj);
271 }
272 
273 /*
274  * Called at device or object close to release the file's
275  * handle references on objects.
276  */
277 static int
278 drm_gem_object_release_handle(int id, void *ptr, void *data)
279 {
280 	struct drm_file *file_priv = data;
281 	struct drm_gem_object *obj = ptr;
282 
283 	if (obj->funcs->close)
284 		obj->funcs->close(obj, file_priv);
285 
286 	drm_prime_remove_buf_handle(&file_priv->prime, id);
287 	drm_vma_node_revoke(&obj->vma_node, file_priv);
288 
289 	drm_gem_object_handle_put_unlocked(obj);
290 
291 	return 0;
292 }
293 
294 /**
295  * drm_gem_handle_delete - deletes the given file-private handle
296  * @filp: drm file-private structure to use for the handle look up
297  * @handle: userspace handle to delete
298  *
299  * Removes the GEM handle from the @filp lookup table which has been added with
300  * drm_gem_handle_create(). If this is the last handle also cleans up linked
301  * resources like GEM names.
302  */
303 int
304 drm_gem_handle_delete(struct drm_file *filp, u32 handle)
305 {
306 	struct drm_gem_object *obj;
307 
308 	spin_lock(&filp->table_lock);
309 
310 	/* Check if we currently have a reference on the object */
311 	obj = idr_replace(&filp->object_idr, NULL, handle);
312 	spin_unlock(&filp->table_lock);
313 	if (IS_ERR_OR_NULL(obj))
314 		return -EINVAL;
315 
316 	/* Release driver's reference and decrement refcount. */
317 	drm_gem_object_release_handle(handle, obj, filp);
318 
319 	/* And finally make the handle available for future allocations. */
320 	spin_lock(&filp->table_lock);
321 	idr_remove(&filp->object_idr, handle);
322 	spin_unlock(&filp->table_lock);
323 
324 	return 0;
325 }
326 EXPORT_SYMBOL(drm_gem_handle_delete);
327 
328 /**
329  * drm_gem_dumb_map_offset - return the fake mmap offset for a gem object
330  * @file: drm file-private structure containing the gem object
331  * @dev: corresponding drm_device
332  * @handle: gem object handle
333  * @offset: return location for the fake mmap offset
334  *
335  * This implements the &drm_driver.dumb_map_offset kms driver callback for
336  * drivers which use gem to manage their backing storage.
337  *
338  * Returns:
339  * 0 on success or a negative error code on failure.
340  */
341 int drm_gem_dumb_map_offset(struct drm_file *file, struct drm_device *dev,
342 			    u32 handle, u64 *offset)
343 {
344 	struct drm_gem_object *obj;
345 	int ret;
346 
347 	obj = drm_gem_object_lookup(file, handle);
348 	if (!obj)
349 		return -ENOENT;
350 
351 	/* Don't allow imported objects to be mapped */
352 	if (drm_gem_is_imported(obj)) {
353 		ret = -EINVAL;
354 		goto out;
355 	}
356 
357 	ret = drm_gem_create_mmap_offset(obj);
358 	if (ret)
359 		goto out;
360 
361 	*offset = drm_vma_node_offset_addr(&obj->vma_node);
362 out:
363 	drm_gem_object_put(obj);
364 
365 	return ret;
366 }
367 EXPORT_SYMBOL_GPL(drm_gem_dumb_map_offset);
368 
369 /**
370  * drm_gem_handle_create_tail - internal functions to create a handle
371  * @file_priv: drm file-private structure to register the handle for
372  * @obj: object to register
373  * @handlep: pointer to return the created handle to the caller
374  *
375  * This expects the &drm_device.object_name_lock to be held already and will
376  * drop it before returning. Used to avoid races in establishing new handles
377  * when importing an object from either an flink name or a dma-buf.
378  *
379  * Handles must be release again through drm_gem_handle_delete(). This is done
380  * when userspace closes @file_priv for all attached handles, or through the
381  * GEM_CLOSE ioctl for individual handles.
382  */
383 int
384 drm_gem_handle_create_tail(struct drm_file *file_priv,
385 			   struct drm_gem_object *obj,
386 			   u32 *handlep)
387 {
388 	struct drm_device *dev = obj->dev;
389 	u32 handle;
390 	int ret;
391 
392 	WARN_ON(!mutex_is_locked(&dev->object_name_lock));
393 	if (obj->handle_count++ == 0)
394 		drm_gem_object_get(obj);
395 
396 	/*
397 	 * Get the user-visible handle using idr.  Preload and perform
398 	 * allocation under our spinlock.
399 	 */
400 	idr_preload(GFP_KERNEL);
401 	spin_lock(&file_priv->table_lock);
402 
403 	ret = idr_alloc(&file_priv->object_idr, obj, 1, 0, GFP_NOWAIT);
404 
405 	spin_unlock(&file_priv->table_lock);
406 	idr_preload_end();
407 
408 	mutex_unlock(&dev->object_name_lock);
409 	if (ret < 0)
410 		goto err_unref;
411 
412 	handle = ret;
413 
414 	ret = drm_vma_node_allow(&obj->vma_node, file_priv);
415 	if (ret)
416 		goto err_remove;
417 
418 	if (obj->funcs->open) {
419 		ret = obj->funcs->open(obj, file_priv);
420 		if (ret)
421 			goto err_revoke;
422 	}
423 
424 	*handlep = handle;
425 	return 0;
426 
427 err_revoke:
428 	drm_vma_node_revoke(&obj->vma_node, file_priv);
429 err_remove:
430 	spin_lock(&file_priv->table_lock);
431 	idr_remove(&file_priv->object_idr, handle);
432 	spin_unlock(&file_priv->table_lock);
433 err_unref:
434 	drm_gem_object_handle_put_unlocked(obj);
435 	return ret;
436 }
437 
438 /**
439  * drm_gem_handle_create - create a gem handle for an object
440  * @file_priv: drm file-private structure to register the handle for
441  * @obj: object to register
442  * @handlep: pointer to return the created handle to the caller
443  *
444  * Create a handle for this object. This adds a handle reference to the object,
445  * which includes a regular reference count. Callers will likely want to
446  * dereference the object afterwards.
447  *
448  * Since this publishes @obj to userspace it must be fully set up by this point,
449  * drivers must call this last in their buffer object creation callbacks.
450  */
451 int drm_gem_handle_create(struct drm_file *file_priv,
452 			  struct drm_gem_object *obj,
453 			  u32 *handlep)
454 {
455 	mutex_lock(&obj->dev->object_name_lock);
456 
457 	return drm_gem_handle_create_tail(file_priv, obj, handlep);
458 }
459 EXPORT_SYMBOL(drm_gem_handle_create);
460 
461 
462 /**
463  * drm_gem_free_mmap_offset - release a fake mmap offset for an object
464  * @obj: obj in question
465  *
466  * This routine frees fake offsets allocated by drm_gem_create_mmap_offset().
467  *
468  * Note that drm_gem_object_release() already calls this function, so drivers
469  * don't have to take care of releasing the mmap offset themselves when freeing
470  * the GEM object.
471  */
472 void
473 drm_gem_free_mmap_offset(struct drm_gem_object *obj)
474 {
475 	struct drm_device *dev = obj->dev;
476 
477 	drm_vma_offset_remove(dev->vma_offset_manager, &obj->vma_node);
478 }
479 EXPORT_SYMBOL(drm_gem_free_mmap_offset);
480 
481 /**
482  * drm_gem_create_mmap_offset_size - create a fake mmap offset for an object
483  * @obj: obj in question
484  * @size: the virtual size
485  *
486  * GEM memory mapping works by handing back to userspace a fake mmap offset
487  * it can use in a subsequent mmap(2) call.  The DRM core code then looks
488  * up the object based on the offset and sets up the various memory mapping
489  * structures.
490  *
491  * This routine allocates and attaches a fake offset for @obj, in cases where
492  * the virtual size differs from the physical size (ie. &drm_gem_object.size).
493  * Otherwise just use drm_gem_create_mmap_offset().
494  *
495  * This function is idempotent and handles an already allocated mmap offset
496  * transparently. Drivers do not need to check for this case.
497  */
498 int
499 drm_gem_create_mmap_offset_size(struct drm_gem_object *obj, size_t size)
500 {
501 	struct drm_device *dev = obj->dev;
502 
503 	return drm_vma_offset_add(dev->vma_offset_manager, &obj->vma_node,
504 				  size / PAGE_SIZE);
505 }
506 EXPORT_SYMBOL(drm_gem_create_mmap_offset_size);
507 
508 /**
509  * drm_gem_create_mmap_offset - create a fake mmap offset for an object
510  * @obj: obj in question
511  *
512  * GEM memory mapping works by handing back to userspace a fake mmap offset
513  * it can use in a subsequent mmap(2) call.  The DRM core code then looks
514  * up the object based on the offset and sets up the various memory mapping
515  * structures.
516  *
517  * This routine allocates and attaches a fake offset for @obj.
518  *
519  * Drivers can call drm_gem_free_mmap_offset() before freeing @obj to release
520  * the fake offset again.
521  */
522 int drm_gem_create_mmap_offset(struct drm_gem_object *obj)
523 {
524 	return drm_gem_create_mmap_offset_size(obj, obj->size);
525 }
526 EXPORT_SYMBOL(drm_gem_create_mmap_offset);
527 
528 /*
529  * Move folios to appropriate lru and release the folios, decrementing the
530  * ref count of those folios.
531  */
532 static void drm_gem_check_release_batch(struct folio_batch *fbatch)
533 {
534 	check_move_unevictable_folios(fbatch);
535 	__folio_batch_release(fbatch);
536 	cond_resched();
537 }
538 
539 /**
540  * drm_gem_get_pages - helper to allocate backing pages for a GEM object
541  * from shmem
542  * @obj: obj in question
543  *
544  * This reads the page-array of the shmem-backing storage of the given gem
545  * object. An array of pages is returned. If a page is not allocated or
546  * swapped-out, this will allocate/swap-in the required pages. Note that the
547  * whole object is covered by the page-array and pinned in memory.
548  *
549  * Use drm_gem_put_pages() to release the array and unpin all pages.
550  *
551  * This uses the GFP-mask set on the shmem-mapping (see mapping_set_gfp_mask()).
552  * If you require other GFP-masks, you have to do those allocations yourself.
553  *
554  * Note that you are not allowed to change gfp-zones during runtime. That is,
555  * shmem_read_mapping_page_gfp() must be called with the same gfp_zone(gfp) as
556  * set during initialization. If you have special zone constraints, set them
557  * after drm_gem_object_init() via mapping_set_gfp_mask(). shmem-core takes care
558  * to keep pages in the required zone during swap-in.
559  *
560  * This function is only valid on objects initialized with
561  * drm_gem_object_init(), but not for those initialized with
562  * drm_gem_private_object_init() only.
563  */
564 struct page **drm_gem_get_pages(struct drm_gem_object *obj)
565 {
566 	struct address_space *mapping;
567 	struct page **pages;
568 	struct folio *folio;
569 	struct folio_batch fbatch;
570 	long i, j, npages;
571 
572 	if (WARN_ON(!obj->filp))
573 		return ERR_PTR(-EINVAL);
574 
575 	/* This is the shared memory object that backs the GEM resource */
576 	mapping = obj->filp->f_mapping;
577 
578 	/* We already BUG_ON() for non-page-aligned sizes in
579 	 * drm_gem_object_init(), so we should never hit this unless
580 	 * driver author is doing something really wrong:
581 	 */
582 	WARN_ON((obj->size & (PAGE_SIZE - 1)) != 0);
583 
584 	npages = obj->size >> PAGE_SHIFT;
585 
586 	pages = kvmalloc_array(npages, sizeof(struct page *), GFP_KERNEL);
587 	if (pages == NULL)
588 		return ERR_PTR(-ENOMEM);
589 
590 	mapping_set_unevictable(mapping);
591 
592 	i = 0;
593 	while (i < npages) {
594 		long nr;
595 		folio = shmem_read_folio_gfp(mapping, i,
596 				mapping_gfp_mask(mapping));
597 		if (IS_ERR(folio))
598 			goto fail;
599 		nr = min(npages - i, folio_nr_pages(folio));
600 		for (j = 0; j < nr; j++, i++)
601 			pages[i] = folio_file_page(folio, i);
602 
603 		/* Make sure shmem keeps __GFP_DMA32 allocated pages in the
604 		 * correct region during swapin. Note that this requires
605 		 * __GFP_DMA32 to be set in mapping_gfp_mask(inode->i_mapping)
606 		 * so shmem can relocate pages during swapin if required.
607 		 */
608 		BUG_ON(mapping_gfp_constraint(mapping, __GFP_DMA32) &&
609 				(folio_pfn(folio) >= 0x00100000UL));
610 	}
611 
612 	return pages;
613 
614 fail:
615 	mapping_clear_unevictable(mapping);
616 	folio_batch_init(&fbatch);
617 	j = 0;
618 	while (j < i) {
619 		struct folio *f = page_folio(pages[j]);
620 		if (!folio_batch_add(&fbatch, f))
621 			drm_gem_check_release_batch(&fbatch);
622 		j += folio_nr_pages(f);
623 	}
624 	if (fbatch.nr)
625 		drm_gem_check_release_batch(&fbatch);
626 
627 	kvfree(pages);
628 	return ERR_CAST(folio);
629 }
630 EXPORT_SYMBOL(drm_gem_get_pages);
631 
632 /**
633  * drm_gem_put_pages - helper to free backing pages for a GEM object
634  * @obj: obj in question
635  * @pages: pages to free
636  * @dirty: if true, pages will be marked as dirty
637  * @accessed: if true, the pages will be marked as accessed
638  */
639 void drm_gem_put_pages(struct drm_gem_object *obj, struct page **pages,
640 		bool dirty, bool accessed)
641 {
642 	int i, npages;
643 	struct address_space *mapping;
644 	struct folio_batch fbatch;
645 
646 	mapping = file_inode(obj->filp)->i_mapping;
647 	mapping_clear_unevictable(mapping);
648 
649 	/* We already BUG_ON() for non-page-aligned sizes in
650 	 * drm_gem_object_init(), so we should never hit this unless
651 	 * driver author is doing something really wrong:
652 	 */
653 	WARN_ON((obj->size & (PAGE_SIZE - 1)) != 0);
654 
655 	npages = obj->size >> PAGE_SHIFT;
656 
657 	folio_batch_init(&fbatch);
658 	for (i = 0; i < npages; i++) {
659 		struct folio *folio;
660 
661 		if (!pages[i])
662 			continue;
663 		folio = page_folio(pages[i]);
664 
665 		if (dirty)
666 			folio_mark_dirty(folio);
667 
668 		if (accessed)
669 			folio_mark_accessed(folio);
670 
671 		/* Undo the reference we took when populating the table */
672 		if (!folio_batch_add(&fbatch, folio))
673 			drm_gem_check_release_batch(&fbatch);
674 		i += folio_nr_pages(folio) - 1;
675 	}
676 	if (folio_batch_count(&fbatch))
677 		drm_gem_check_release_batch(&fbatch);
678 
679 	kvfree(pages);
680 }
681 EXPORT_SYMBOL(drm_gem_put_pages);
682 
683 static int objects_lookup(struct drm_file *filp, u32 *handle, int count,
684 			  struct drm_gem_object **objs)
685 {
686 	int i, ret = 0;
687 	struct drm_gem_object *obj;
688 
689 	spin_lock(&filp->table_lock);
690 
691 	for (i = 0; i < count; i++) {
692 		/* Check if we currently have a reference on the object */
693 		obj = idr_find(&filp->object_idr, handle[i]);
694 		if (!obj) {
695 			ret = -ENOENT;
696 			break;
697 		}
698 		drm_gem_object_get(obj);
699 		objs[i] = obj;
700 	}
701 	spin_unlock(&filp->table_lock);
702 
703 	return ret;
704 }
705 
706 /**
707  * drm_gem_objects_lookup - look up GEM objects from an array of handles
708  * @filp: DRM file private date
709  * @bo_handles: user pointer to array of userspace handle
710  * @count: size of handle array
711  * @objs_out: returned pointer to array of drm_gem_object pointers
712  *
713  * Takes an array of userspace handles and returns a newly allocated array of
714  * GEM objects.
715  *
716  * For a single handle lookup, use drm_gem_object_lookup().
717  *
718  * Returns:
719  * @objs filled in with GEM object pointers. Returned GEM objects need to be
720  * released with drm_gem_object_put(). -ENOENT is returned on a lookup
721  * failure. 0 is returned on success.
722  *
723  */
724 int drm_gem_objects_lookup(struct drm_file *filp, void __user *bo_handles,
725 			   int count, struct drm_gem_object ***objs_out)
726 {
727 	int ret;
728 	u32 *handles;
729 	struct drm_gem_object **objs;
730 
731 	if (!count)
732 		return 0;
733 
734 	objs = kvmalloc_array(count, sizeof(struct drm_gem_object *),
735 			     GFP_KERNEL | __GFP_ZERO);
736 	if (!objs)
737 		return -ENOMEM;
738 
739 	*objs_out = objs;
740 
741 	handles = kvmalloc_array(count, sizeof(u32), GFP_KERNEL);
742 	if (!handles) {
743 		ret = -ENOMEM;
744 		goto out;
745 	}
746 
747 	if (copy_from_user(handles, bo_handles, count * sizeof(u32))) {
748 		ret = -EFAULT;
749 		DRM_DEBUG("Failed to copy in GEM handles\n");
750 		goto out;
751 	}
752 
753 	ret = objects_lookup(filp, handles, count, objs);
754 out:
755 	kvfree(handles);
756 	return ret;
757 
758 }
759 EXPORT_SYMBOL(drm_gem_objects_lookup);
760 
761 /**
762  * drm_gem_object_lookup - look up a GEM object from its handle
763  * @filp: DRM file private date
764  * @handle: userspace handle
765  *
766  * If looking up an array of handles, use drm_gem_objects_lookup().
767  *
768  * Returns:
769  * A reference to the object named by the handle if such exists on @filp, NULL
770  * otherwise.
771  */
772 struct drm_gem_object *
773 drm_gem_object_lookup(struct drm_file *filp, u32 handle)
774 {
775 	struct drm_gem_object *obj = NULL;
776 
777 	objects_lookup(filp, &handle, 1, &obj);
778 	return obj;
779 }
780 EXPORT_SYMBOL(drm_gem_object_lookup);
781 
782 /**
783  * drm_gem_dma_resv_wait - Wait on GEM object's reservation's objects
784  * shared and/or exclusive fences.
785  * @filep: DRM file private date
786  * @handle: userspace handle
787  * @wait_all: if true, wait on all fences, else wait on just exclusive fence
788  * @timeout: timeout value in jiffies or zero to return immediately
789  *
790  * Returns:
791  * Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or
792  * greater than 0 on success.
793  */
794 long drm_gem_dma_resv_wait(struct drm_file *filep, u32 handle,
795 				    bool wait_all, unsigned long timeout)
796 {
797 	long ret;
798 	struct drm_gem_object *obj;
799 
800 	obj = drm_gem_object_lookup(filep, handle);
801 	if (!obj) {
802 		DRM_DEBUG("Failed to look up GEM BO %d\n", handle);
803 		return -EINVAL;
804 	}
805 
806 	ret = dma_resv_wait_timeout(obj->resv, dma_resv_usage_rw(wait_all),
807 				    true, timeout);
808 	if (ret == 0)
809 		ret = -ETIME;
810 	else if (ret > 0)
811 		ret = 0;
812 
813 	drm_gem_object_put(obj);
814 
815 	return ret;
816 }
817 EXPORT_SYMBOL(drm_gem_dma_resv_wait);
818 
819 /**
820  * drm_gem_close_ioctl - implementation of the GEM_CLOSE ioctl
821  * @dev: drm_device
822  * @data: ioctl data
823  * @file_priv: drm file-private structure
824  *
825  * Releases the handle to an mm object.
826  */
827 int
828 drm_gem_close_ioctl(struct drm_device *dev, void *data,
829 		    struct drm_file *file_priv)
830 {
831 	struct drm_gem_close *args = data;
832 	int ret;
833 
834 	if (!drm_core_check_feature(dev, DRIVER_GEM))
835 		return -EOPNOTSUPP;
836 
837 	ret = drm_gem_handle_delete(file_priv, args->handle);
838 
839 	return ret;
840 }
841 
842 /**
843  * drm_gem_flink_ioctl - implementation of the GEM_FLINK ioctl
844  * @dev: drm_device
845  * @data: ioctl data
846  * @file_priv: drm file-private structure
847  *
848  * Create a global name for an object, returning the name.
849  *
850  * Note that the name does not hold a reference; when the object
851  * is freed, the name goes away.
852  */
853 int
854 drm_gem_flink_ioctl(struct drm_device *dev, void *data,
855 		    struct drm_file *file_priv)
856 {
857 	struct drm_gem_flink *args = data;
858 	struct drm_gem_object *obj;
859 	int ret;
860 
861 	if (!drm_core_check_feature(dev, DRIVER_GEM))
862 		return -EOPNOTSUPP;
863 
864 	obj = drm_gem_object_lookup(file_priv, args->handle);
865 	if (obj == NULL)
866 		return -ENOENT;
867 
868 	mutex_lock(&dev->object_name_lock);
869 	/* prevent races with concurrent gem_close. */
870 	if (obj->handle_count == 0) {
871 		ret = -ENOENT;
872 		goto err;
873 	}
874 
875 	if (!obj->name) {
876 		ret = idr_alloc(&dev->object_name_idr, obj, 1, 0, GFP_KERNEL);
877 		if (ret < 0)
878 			goto err;
879 
880 		obj->name = ret;
881 	}
882 
883 	args->name = (uint64_t) obj->name;
884 	ret = 0;
885 
886 err:
887 	mutex_unlock(&dev->object_name_lock);
888 	drm_gem_object_put(obj);
889 	return ret;
890 }
891 
892 /**
893  * drm_gem_open_ioctl - implementation of the GEM_OPEN ioctl
894  * @dev: drm_device
895  * @data: ioctl data
896  * @file_priv: drm file-private structure
897  *
898  * Open an object using the global name, returning a handle and the size.
899  *
900  * This handle (of course) holds a reference to the object, so the object
901  * will not go away until the handle is deleted.
902  */
903 int
904 drm_gem_open_ioctl(struct drm_device *dev, void *data,
905 		   struct drm_file *file_priv)
906 {
907 	struct drm_gem_open *args = data;
908 	struct drm_gem_object *obj;
909 	int ret;
910 	u32 handle;
911 
912 	if (!drm_core_check_feature(dev, DRIVER_GEM))
913 		return -EOPNOTSUPP;
914 
915 	mutex_lock(&dev->object_name_lock);
916 	obj = idr_find(&dev->object_name_idr, (int) args->name);
917 	if (obj) {
918 		drm_gem_object_get(obj);
919 	} else {
920 		mutex_unlock(&dev->object_name_lock);
921 		return -ENOENT;
922 	}
923 
924 	/* drm_gem_handle_create_tail unlocks dev->object_name_lock. */
925 	ret = drm_gem_handle_create_tail(file_priv, obj, &handle);
926 	if (ret)
927 		goto err;
928 
929 	args->handle = handle;
930 	args->size = obj->size;
931 
932 err:
933 	drm_gem_object_put(obj);
934 	return ret;
935 }
936 
937 /**
938  * drm_gem_open - initializes GEM file-private structures at devnode open time
939  * @dev: drm_device which is being opened by userspace
940  * @file_private: drm file-private structure to set up
941  *
942  * Called at device open time, sets up the structure for handling refcounting
943  * of mm objects.
944  */
945 void
946 drm_gem_open(struct drm_device *dev, struct drm_file *file_private)
947 {
948 	idr_init_base(&file_private->object_idr, 1);
949 	spin_lock_init(&file_private->table_lock);
950 }
951 
952 /**
953  * drm_gem_release - release file-private GEM resources
954  * @dev: drm_device which is being closed by userspace
955  * @file_private: drm file-private structure to clean up
956  *
957  * Called at close time when the filp is going away.
958  *
959  * Releases any remaining references on objects by this filp.
960  */
961 void
962 drm_gem_release(struct drm_device *dev, struct drm_file *file_private)
963 {
964 	idr_for_each(&file_private->object_idr,
965 		     &drm_gem_object_release_handle, file_private);
966 	idr_destroy(&file_private->object_idr);
967 }
968 
969 /**
970  * drm_gem_object_release - release GEM buffer object resources
971  * @obj: GEM buffer object
972  *
973  * This releases any structures and resources used by @obj and is the inverse of
974  * drm_gem_object_init().
975  */
976 void
977 drm_gem_object_release(struct drm_gem_object *obj)
978 {
979 	if (obj->filp)
980 		fput(obj->filp);
981 
982 	drm_gem_private_object_fini(obj);
983 
984 	drm_gem_free_mmap_offset(obj);
985 	drm_gem_lru_remove(obj);
986 }
987 EXPORT_SYMBOL(drm_gem_object_release);
988 
989 /**
990  * drm_gem_object_free - free a GEM object
991  * @kref: kref of the object to free
992  *
993  * Called after the last reference to the object has been lost.
994  *
995  * Frees the object
996  */
997 void
998 drm_gem_object_free(struct kref *kref)
999 {
1000 	struct drm_gem_object *obj =
1001 		container_of(kref, struct drm_gem_object, refcount);
1002 
1003 	if (WARN_ON(!obj->funcs->free))
1004 		return;
1005 
1006 	obj->funcs->free(obj);
1007 }
1008 EXPORT_SYMBOL(drm_gem_object_free);
1009 
1010 /**
1011  * drm_gem_vm_open - vma->ops->open implementation for GEM
1012  * @vma: VM area structure
1013  *
1014  * This function implements the #vm_operations_struct open() callback for GEM
1015  * drivers. This must be used together with drm_gem_vm_close().
1016  */
1017 void drm_gem_vm_open(struct vm_area_struct *vma)
1018 {
1019 	struct drm_gem_object *obj = vma->vm_private_data;
1020 
1021 	drm_gem_object_get(obj);
1022 }
1023 EXPORT_SYMBOL(drm_gem_vm_open);
1024 
1025 /**
1026  * drm_gem_vm_close - vma->ops->close implementation for GEM
1027  * @vma: VM area structure
1028  *
1029  * This function implements the #vm_operations_struct close() callback for GEM
1030  * drivers. This must be used together with drm_gem_vm_open().
1031  */
1032 void drm_gem_vm_close(struct vm_area_struct *vma)
1033 {
1034 	struct drm_gem_object *obj = vma->vm_private_data;
1035 
1036 	drm_gem_object_put(obj);
1037 }
1038 EXPORT_SYMBOL(drm_gem_vm_close);
1039 
1040 /**
1041  * drm_gem_mmap_obj - memory map a GEM object
1042  * @obj: the GEM object to map
1043  * @obj_size: the object size to be mapped, in bytes
1044  * @vma: VMA for the area to be mapped
1045  *
1046  * Set up the VMA to prepare mapping of the GEM object using the GEM object's
1047  * vm_ops. Depending on their requirements, GEM objects can either
1048  * provide a fault handler in their vm_ops (in which case any accesses to
1049  * the object will be trapped, to perform migration, GTT binding, surface
1050  * register allocation, or performance monitoring), or mmap the buffer memory
1051  * synchronously after calling drm_gem_mmap_obj.
1052  *
1053  * This function is mainly intended to implement the DMABUF mmap operation, when
1054  * the GEM object is not looked up based on its fake offset. To implement the
1055  * DRM mmap operation, drivers should use the drm_gem_mmap() function.
1056  *
1057  * drm_gem_mmap_obj() assumes the user is granted access to the buffer while
1058  * drm_gem_mmap() prevents unprivileged users from mapping random objects. So
1059  * callers must verify access restrictions before calling this helper.
1060  *
1061  * Return 0 or success or -EINVAL if the object size is smaller than the VMA
1062  * size, or if no vm_ops are provided.
1063  */
1064 int drm_gem_mmap_obj(struct drm_gem_object *obj, unsigned long obj_size,
1065 		     struct vm_area_struct *vma)
1066 {
1067 	int ret;
1068 
1069 	/* Check for valid size. */
1070 	if (obj_size < vma->vm_end - vma->vm_start)
1071 		return -EINVAL;
1072 
1073 	/* Take a ref for this mapping of the object, so that the fault
1074 	 * handler can dereference the mmap offset's pointer to the object.
1075 	 * This reference is cleaned up by the corresponding vm_close
1076 	 * (which should happen whether the vma was created by this call, or
1077 	 * by a vm_open due to mremap or partial unmap or whatever).
1078 	 */
1079 	drm_gem_object_get(obj);
1080 
1081 	vma->vm_private_data = obj;
1082 	vma->vm_ops = obj->funcs->vm_ops;
1083 
1084 	if (obj->funcs->mmap) {
1085 		ret = obj->funcs->mmap(obj, vma);
1086 		if (ret)
1087 			goto err_drm_gem_object_put;
1088 		WARN_ON(!(vma->vm_flags & VM_DONTEXPAND));
1089 	} else {
1090 		if (!vma->vm_ops) {
1091 			ret = -EINVAL;
1092 			goto err_drm_gem_object_put;
1093 		}
1094 
1095 		vm_flags_set(vma, VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP);
1096 		vma->vm_page_prot = pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
1097 		vma->vm_page_prot = pgprot_decrypted(vma->vm_page_prot);
1098 	}
1099 
1100 	return 0;
1101 
1102 err_drm_gem_object_put:
1103 	drm_gem_object_put(obj);
1104 	return ret;
1105 }
1106 EXPORT_SYMBOL(drm_gem_mmap_obj);
1107 
1108 /**
1109  * drm_gem_mmap - memory map routine for GEM objects
1110  * @filp: DRM file pointer
1111  * @vma: VMA for the area to be mapped
1112  *
1113  * If a driver supports GEM object mapping, mmap calls on the DRM file
1114  * descriptor will end up here.
1115  *
1116  * Look up the GEM object based on the offset passed in (vma->vm_pgoff will
1117  * contain the fake offset we created when the GTT map ioctl was called on
1118  * the object) and map it with a call to drm_gem_mmap_obj().
1119  *
1120  * If the caller is not granted access to the buffer object, the mmap will fail
1121  * with EACCES. Please see the vma manager for more information.
1122  */
1123 int drm_gem_mmap(struct file *filp, struct vm_area_struct *vma)
1124 {
1125 	struct drm_file *priv = filp->private_data;
1126 	struct drm_device *dev = priv->minor->dev;
1127 	struct drm_gem_object *obj = NULL;
1128 	struct drm_vma_offset_node *node;
1129 	int ret;
1130 
1131 	if (drm_dev_is_unplugged(dev))
1132 		return -ENODEV;
1133 
1134 	drm_vma_offset_lock_lookup(dev->vma_offset_manager);
1135 	node = drm_vma_offset_exact_lookup_locked(dev->vma_offset_manager,
1136 						  vma->vm_pgoff,
1137 						  vma_pages(vma));
1138 	if (likely(node)) {
1139 		obj = container_of(node, struct drm_gem_object, vma_node);
1140 		/*
1141 		 * When the object is being freed, after it hits 0-refcnt it
1142 		 * proceeds to tear down the object. In the process it will
1143 		 * attempt to remove the VMA offset and so acquire this
1144 		 * mgr->vm_lock.  Therefore if we find an object with a 0-refcnt
1145 		 * that matches our range, we know it is in the process of being
1146 		 * destroyed and will be freed as soon as we release the lock -
1147 		 * so we have to check for the 0-refcnted object and treat it as
1148 		 * invalid.
1149 		 */
1150 		if (!kref_get_unless_zero(&obj->refcount))
1151 			obj = NULL;
1152 	}
1153 	drm_vma_offset_unlock_lookup(dev->vma_offset_manager);
1154 
1155 	if (!obj)
1156 		return -EINVAL;
1157 
1158 	if (!drm_vma_node_is_allowed(node, priv)) {
1159 		drm_gem_object_put(obj);
1160 		return -EACCES;
1161 	}
1162 
1163 	ret = drm_gem_mmap_obj(obj, drm_vma_node_size(node) << PAGE_SHIFT,
1164 			       vma);
1165 
1166 	drm_gem_object_put(obj);
1167 
1168 	return ret;
1169 }
1170 EXPORT_SYMBOL(drm_gem_mmap);
1171 
1172 void drm_gem_print_info(struct drm_printer *p, unsigned int indent,
1173 			const struct drm_gem_object *obj)
1174 {
1175 	drm_printf_indent(p, indent, "name=%d\n", obj->name);
1176 	drm_printf_indent(p, indent, "refcount=%u\n",
1177 			  kref_read(&obj->refcount));
1178 	drm_printf_indent(p, indent, "start=%08lx\n",
1179 			  drm_vma_node_start(&obj->vma_node));
1180 	drm_printf_indent(p, indent, "size=%zu\n", obj->size);
1181 	drm_printf_indent(p, indent, "imported=%s\n",
1182 			  str_yes_no(drm_gem_is_imported(obj)));
1183 
1184 	if (obj->funcs->print_info)
1185 		obj->funcs->print_info(p, indent, obj);
1186 }
1187 
1188 int drm_gem_vmap_locked(struct drm_gem_object *obj, struct iosys_map *map)
1189 {
1190 	int ret;
1191 
1192 	dma_resv_assert_held(obj->resv);
1193 
1194 	if (!obj->funcs->vmap)
1195 		return -EOPNOTSUPP;
1196 
1197 	ret = obj->funcs->vmap(obj, map);
1198 	if (ret)
1199 		return ret;
1200 	else if (iosys_map_is_null(map))
1201 		return -ENOMEM;
1202 
1203 	return 0;
1204 }
1205 EXPORT_SYMBOL(drm_gem_vmap_locked);
1206 
1207 void drm_gem_vunmap_locked(struct drm_gem_object *obj, struct iosys_map *map)
1208 {
1209 	dma_resv_assert_held(obj->resv);
1210 
1211 	if (iosys_map_is_null(map))
1212 		return;
1213 
1214 	if (obj->funcs->vunmap)
1215 		obj->funcs->vunmap(obj, map);
1216 
1217 	/* Always set the mapping to NULL. Callers may rely on this. */
1218 	iosys_map_clear(map);
1219 }
1220 EXPORT_SYMBOL(drm_gem_vunmap_locked);
1221 
1222 void drm_gem_lock(struct drm_gem_object *obj)
1223 {
1224 	dma_resv_lock(obj->resv, NULL);
1225 }
1226 EXPORT_SYMBOL(drm_gem_lock);
1227 
1228 void drm_gem_unlock(struct drm_gem_object *obj)
1229 {
1230 	dma_resv_unlock(obj->resv);
1231 }
1232 EXPORT_SYMBOL(drm_gem_unlock);
1233 
1234 int drm_gem_vmap(struct drm_gem_object *obj, struct iosys_map *map)
1235 {
1236 	int ret;
1237 
1238 	dma_resv_lock(obj->resv, NULL);
1239 	ret = drm_gem_vmap_locked(obj, map);
1240 	dma_resv_unlock(obj->resv);
1241 
1242 	return ret;
1243 }
1244 EXPORT_SYMBOL(drm_gem_vmap);
1245 
1246 void drm_gem_vunmap(struct drm_gem_object *obj, struct iosys_map *map)
1247 {
1248 	dma_resv_lock(obj->resv, NULL);
1249 	drm_gem_vunmap_locked(obj, map);
1250 	dma_resv_unlock(obj->resv);
1251 }
1252 EXPORT_SYMBOL(drm_gem_vunmap);
1253 
1254 /**
1255  * drm_gem_lock_reservations - Sets up the ww context and acquires
1256  * the lock on an array of GEM objects.
1257  *
1258  * Once you've locked your reservations, you'll want to set up space
1259  * for your shared fences (if applicable), submit your job, then
1260  * drm_gem_unlock_reservations().
1261  *
1262  * @objs: drm_gem_objects to lock
1263  * @count: Number of objects in @objs
1264  * @acquire_ctx: struct ww_acquire_ctx that will be initialized as
1265  * part of tracking this set of locked reservations.
1266  */
1267 int
1268 drm_gem_lock_reservations(struct drm_gem_object **objs, int count,
1269 			  struct ww_acquire_ctx *acquire_ctx)
1270 {
1271 	int contended = -1;
1272 	int i, ret;
1273 
1274 	ww_acquire_init(acquire_ctx, &reservation_ww_class);
1275 
1276 retry:
1277 	if (contended != -1) {
1278 		struct drm_gem_object *obj = objs[contended];
1279 
1280 		ret = dma_resv_lock_slow_interruptible(obj->resv,
1281 								 acquire_ctx);
1282 		if (ret) {
1283 			ww_acquire_fini(acquire_ctx);
1284 			return ret;
1285 		}
1286 	}
1287 
1288 	for (i = 0; i < count; i++) {
1289 		if (i == contended)
1290 			continue;
1291 
1292 		ret = dma_resv_lock_interruptible(objs[i]->resv,
1293 							    acquire_ctx);
1294 		if (ret) {
1295 			int j;
1296 
1297 			for (j = 0; j < i; j++)
1298 				dma_resv_unlock(objs[j]->resv);
1299 
1300 			if (contended != -1 && contended >= i)
1301 				dma_resv_unlock(objs[contended]->resv);
1302 
1303 			if (ret == -EDEADLK) {
1304 				contended = i;
1305 				goto retry;
1306 			}
1307 
1308 			ww_acquire_fini(acquire_ctx);
1309 			return ret;
1310 		}
1311 	}
1312 
1313 	ww_acquire_done(acquire_ctx);
1314 
1315 	return 0;
1316 }
1317 EXPORT_SYMBOL(drm_gem_lock_reservations);
1318 
1319 void
1320 drm_gem_unlock_reservations(struct drm_gem_object **objs, int count,
1321 			    struct ww_acquire_ctx *acquire_ctx)
1322 {
1323 	int i;
1324 
1325 	for (i = 0; i < count; i++)
1326 		dma_resv_unlock(objs[i]->resv);
1327 
1328 	ww_acquire_fini(acquire_ctx);
1329 }
1330 EXPORT_SYMBOL(drm_gem_unlock_reservations);
1331 
1332 /**
1333  * drm_gem_lru_init - initialize a LRU
1334  *
1335  * @lru: The LRU to initialize
1336  * @lock: The lock protecting the LRU
1337  */
1338 void
1339 drm_gem_lru_init(struct drm_gem_lru *lru, struct mutex *lock)
1340 {
1341 	lru->lock = lock;
1342 	lru->count = 0;
1343 	INIT_LIST_HEAD(&lru->list);
1344 }
1345 EXPORT_SYMBOL(drm_gem_lru_init);
1346 
1347 static void
1348 drm_gem_lru_remove_locked(struct drm_gem_object *obj)
1349 {
1350 	obj->lru->count -= obj->size >> PAGE_SHIFT;
1351 	WARN_ON(obj->lru->count < 0);
1352 	list_del(&obj->lru_node);
1353 	obj->lru = NULL;
1354 }
1355 
1356 /**
1357  * drm_gem_lru_remove - remove object from whatever LRU it is in
1358  *
1359  * If the object is currently in any LRU, remove it.
1360  *
1361  * @obj: The GEM object to remove from current LRU
1362  */
1363 void
1364 drm_gem_lru_remove(struct drm_gem_object *obj)
1365 {
1366 	struct drm_gem_lru *lru = obj->lru;
1367 
1368 	if (!lru)
1369 		return;
1370 
1371 	mutex_lock(lru->lock);
1372 	drm_gem_lru_remove_locked(obj);
1373 	mutex_unlock(lru->lock);
1374 }
1375 EXPORT_SYMBOL(drm_gem_lru_remove);
1376 
1377 /**
1378  * drm_gem_lru_move_tail_locked - move the object to the tail of the LRU
1379  *
1380  * Like &drm_gem_lru_move_tail but lru lock must be held
1381  *
1382  * @lru: The LRU to move the object into.
1383  * @obj: The GEM object to move into this LRU
1384  */
1385 void
1386 drm_gem_lru_move_tail_locked(struct drm_gem_lru *lru, struct drm_gem_object *obj)
1387 {
1388 	lockdep_assert_held_once(lru->lock);
1389 
1390 	if (obj->lru)
1391 		drm_gem_lru_remove_locked(obj);
1392 
1393 	lru->count += obj->size >> PAGE_SHIFT;
1394 	list_add_tail(&obj->lru_node, &lru->list);
1395 	obj->lru = lru;
1396 }
1397 EXPORT_SYMBOL(drm_gem_lru_move_tail_locked);
1398 
1399 /**
1400  * drm_gem_lru_move_tail - move the object to the tail of the LRU
1401  *
1402  * If the object is already in this LRU it will be moved to the
1403  * tail.  Otherwise it will be removed from whichever other LRU
1404  * it is in (if any) and moved into this LRU.
1405  *
1406  * @lru: The LRU to move the object into.
1407  * @obj: The GEM object to move into this LRU
1408  */
1409 void
1410 drm_gem_lru_move_tail(struct drm_gem_lru *lru, struct drm_gem_object *obj)
1411 {
1412 	mutex_lock(lru->lock);
1413 	drm_gem_lru_move_tail_locked(lru, obj);
1414 	mutex_unlock(lru->lock);
1415 }
1416 EXPORT_SYMBOL(drm_gem_lru_move_tail);
1417 
1418 /**
1419  * drm_gem_lru_scan - helper to implement shrinker.scan_objects
1420  *
1421  * If the shrink callback succeeds, it is expected that the driver
1422  * move the object out of this LRU.
1423  *
1424  * If the LRU possibly contain active buffers, it is the responsibility
1425  * of the shrink callback to check for this (ie. dma_resv_test_signaled())
1426  * or if necessary block until the buffer becomes idle.
1427  *
1428  * @lru: The LRU to scan
1429  * @nr_to_scan: The number of pages to try to reclaim
1430  * @remaining: The number of pages left to reclaim, should be initialized by caller
1431  * @shrink: Callback to try to shrink/reclaim the object.
1432  * @ticket: Optional ww_acquire_ctx context to use for locking
1433  */
1434 unsigned long
1435 drm_gem_lru_scan(struct drm_gem_lru *lru,
1436 		 unsigned int nr_to_scan,
1437 		 unsigned long *remaining,
1438 		 bool (*shrink)(struct drm_gem_object *obj, struct ww_acquire_ctx *ticket),
1439 		 struct ww_acquire_ctx *ticket)
1440 {
1441 	struct drm_gem_lru still_in_lru;
1442 	struct drm_gem_object *obj;
1443 	unsigned freed = 0;
1444 
1445 	drm_gem_lru_init(&still_in_lru, lru->lock);
1446 
1447 	mutex_lock(lru->lock);
1448 
1449 	while (freed < nr_to_scan) {
1450 		obj = list_first_entry_or_null(&lru->list, typeof(*obj), lru_node);
1451 
1452 		if (!obj)
1453 			break;
1454 
1455 		drm_gem_lru_move_tail_locked(&still_in_lru, obj);
1456 
1457 		/*
1458 		 * If it's in the process of being freed, gem_object->free()
1459 		 * may be blocked on lock waiting to remove it.  So just
1460 		 * skip it.
1461 		 */
1462 		if (!kref_get_unless_zero(&obj->refcount))
1463 			continue;
1464 
1465 		/*
1466 		 * Now that we own a reference, we can drop the lock for the
1467 		 * rest of the loop body, to reduce contention with other
1468 		 * code paths that need the LRU lock
1469 		 */
1470 		mutex_unlock(lru->lock);
1471 
1472 		if (ticket)
1473 			ww_acquire_init(ticket, &reservation_ww_class);
1474 
1475 		/*
1476 		 * Note that this still needs to be trylock, since we can
1477 		 * hit shrinker in response to trying to get backing pages
1478 		 * for this obj (ie. while it's lock is already held)
1479 		 */
1480 		if (!ww_mutex_trylock(&obj->resv->lock, ticket)) {
1481 			*remaining += obj->size >> PAGE_SHIFT;
1482 			goto tail;
1483 		}
1484 
1485 		if (shrink(obj, ticket)) {
1486 			freed += obj->size >> PAGE_SHIFT;
1487 
1488 			/*
1489 			 * If we succeeded in releasing the object's backing
1490 			 * pages, we expect the driver to have moved the object
1491 			 * out of this LRU
1492 			 */
1493 			WARN_ON(obj->lru == &still_in_lru);
1494 			WARN_ON(obj->lru == lru);
1495 		}
1496 
1497 		dma_resv_unlock(obj->resv);
1498 
1499 		if (ticket)
1500 			ww_acquire_fini(ticket);
1501 
1502 tail:
1503 		drm_gem_object_put(obj);
1504 		mutex_lock(lru->lock);
1505 	}
1506 
1507 	/*
1508 	 * Move objects we've skipped over out of the temporary still_in_lru
1509 	 * back into this LRU
1510 	 */
1511 	list_for_each_entry (obj, &still_in_lru.list, lru_node)
1512 		obj->lru = lru;
1513 	list_splice_tail(&still_in_lru.list, &lru->list);
1514 	lru->count += still_in_lru.count;
1515 
1516 	mutex_unlock(lru->lock);
1517 
1518 	return freed;
1519 }
1520 EXPORT_SYMBOL(drm_gem_lru_scan);
1521 
1522 /**
1523  * drm_gem_evict_locked - helper to evict backing pages for a GEM object
1524  * @obj: obj in question
1525  */
1526 int drm_gem_evict_locked(struct drm_gem_object *obj)
1527 {
1528 	dma_resv_assert_held(obj->resv);
1529 
1530 	if (!dma_resv_test_signaled(obj->resv, DMA_RESV_USAGE_READ))
1531 		return -EBUSY;
1532 
1533 	if (obj->funcs->evict)
1534 		return obj->funcs->evict(obj);
1535 
1536 	return 0;
1537 }
1538 EXPORT_SYMBOL(drm_gem_evict_locked);
1539