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