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