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