drm: Use the same mmap-range offset and size for GEM and TTM
[linux-2.6-microblaze.git] / drivers / gpu / drm / drm_gem.c
1 /*
2  * Copyright © 2008 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *    Eric Anholt <eric@anholt.net>
25  *
26  */
27
28 #include <linux/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 #include <drm/drmP.h>
42 #include <drm/drm_vma_manager.h>
43 #include <drm/drm_gem.h>
44 #include <drm/drm_print.h>
45 #include "drm_internal.h"
46
47 /** @file drm_gem.c
48  *
49  * This file provides some of the base ioctls and library routines for
50  * the graphics memory manager implemented by each device driver.
51  *
52  * Because various devices have different requirements in terms of
53  * synchronization and migration strategies, implementing that is left up to
54  * the driver, and all that the general API provides should be generic --
55  * allocating objects, reading/writing data with the cpu, freeing objects.
56  * Even there, platform-dependent optimizations for reading/writing data with
57  * the CPU mean we'll likely hook those out to driver-specific calls.  However,
58  * the DRI2 implementation wants to have at least allocate/mmap be generic.
59  *
60  * The goal was to have swap-backed object allocation managed through
61  * struct file.  However, file descriptors as handles to a struct file have
62  * two major failings:
63  * - Process limits prevent more than 1024 or so being used at a time by
64  *   default.
65  * - Inability to allocate high fds will aggravate the X Server's select()
66  *   handling, and likely that of many GL client applications as well.
67  *
68  * This led to a plan of using our own integer IDs (called handles, following
69  * DRM terminology) to mimic fds, and implement the fd syscalls we need as
70  * ioctls.  The objects themselves will still include the struct file so
71  * that we can transition to fds if the required kernel infrastructure shows
72  * up at a later date, and as our interface with shmfs for memory allocation.
73  */
74
75 /**
76  * drm_gem_init - Initialize the GEM device fields
77  * @dev: drm_devic structure to initialize
78  */
79 int
80 drm_gem_init(struct drm_device *dev)
81 {
82         struct drm_vma_offset_manager *vma_offset_manager;
83
84         mutex_init(&dev->object_name_lock);
85         idr_init_base(&dev->object_name_idr, 1);
86
87         vma_offset_manager = kzalloc(sizeof(*vma_offset_manager), GFP_KERNEL);
88         if (!vma_offset_manager) {
89                 DRM_ERROR("out of memory\n");
90                 return -ENOMEM;
91         }
92
93         dev->vma_offset_manager = vma_offset_manager;
94         drm_vma_offset_manager_init(vma_offset_manager,
95                                     DRM_FILE_PAGE_OFFSET_START,
96                                     DRM_FILE_PAGE_OFFSET_SIZE);
97
98         return 0;
99 }
100
101 void
102 drm_gem_destroy(struct drm_device *dev)
103 {
104
105         drm_vma_offset_manager_destroy(dev->vma_offset_manager);
106         kfree(dev->vma_offset_manager);
107         dev->vma_offset_manager = NULL;
108 }
109
110 /**
111  * drm_gem_object_init - initialize an allocated shmem-backed GEM object
112  * @dev: drm_device the object should be initialized for
113  * @obj: drm_gem_object to initialize
114  * @size: object size
115  *
116  * Initialize an already allocated GEM object of the specified size with
117  * shmfs backing store.
118  */
119 int drm_gem_object_init(struct drm_device *dev,
120                         struct drm_gem_object *obj, size_t size)
121 {
122         struct file *filp;
123
124         drm_gem_private_object_init(dev, obj, size);
125
126         filp = shmem_file_setup("drm mm object", size, VM_NORESERVE);
127         if (IS_ERR(filp))
128                 return PTR_ERR(filp);
129
130         obj->filp = filp;
131
132         return 0;
133 }
134 EXPORT_SYMBOL(drm_gem_object_init);
135
136 /**
137  * drm_gem_private_object_init - initialize an allocated private GEM object
138  * @dev: drm_device the object should be initialized for
139  * @obj: drm_gem_object to initialize
140  * @size: object size
141  *
142  * Initialize an already allocated GEM object of the specified size with
143  * no GEM provided backing store. Instead the caller is responsible for
144  * backing the object and handling it.
145  */
146 void drm_gem_private_object_init(struct drm_device *dev,
147                                  struct drm_gem_object *obj, size_t size)
148 {
149         BUG_ON((size & (PAGE_SIZE - 1)) != 0);
150
151         obj->dev = dev;
152         obj->filp = NULL;
153
154         kref_init(&obj->refcount);
155         obj->handle_count = 0;
156         obj->size = size;
157         drm_vma_node_reset(&obj->vma_node);
158 }
159 EXPORT_SYMBOL(drm_gem_private_object_init);
160
161 static void
162 drm_gem_remove_prime_handles(struct drm_gem_object *obj, struct drm_file *filp)
163 {
164         /*
165          * Note: obj->dma_buf can't disappear as long as we still hold a
166          * handle reference in obj->handle_count.
167          */
168         mutex_lock(&filp->prime.lock);
169         if (obj->dma_buf) {
170                 drm_prime_remove_buf_handle_locked(&filp->prime,
171                                                    obj->dma_buf);
172         }
173         mutex_unlock(&filp->prime.lock);
174 }
175
176 /**
177  * drm_gem_object_handle_free - release resources bound to userspace handles
178  * @obj: GEM object to clean up.
179  *
180  * Called after the last handle to the object has been closed
181  *
182  * Removes any name for the object. Note that this must be
183  * called before drm_gem_object_free or we'll be touching
184  * freed memory
185  */
186 static void drm_gem_object_handle_free(struct drm_gem_object *obj)
187 {
188         struct drm_device *dev = obj->dev;
189
190         /* Remove any name for this object */
191         if (obj->name) {
192                 idr_remove(&dev->object_name_idr, obj->name);
193                 obj->name = 0;
194         }
195 }
196
197 static void drm_gem_object_exported_dma_buf_free(struct drm_gem_object *obj)
198 {
199         /* Unbreak the reference cycle if we have an exported dma_buf. */
200         if (obj->dma_buf) {
201                 dma_buf_put(obj->dma_buf);
202                 obj->dma_buf = NULL;
203         }
204 }
205
206 static void
207 drm_gem_object_handle_put_unlocked(struct drm_gem_object *obj)
208 {
209         struct drm_device *dev = obj->dev;
210         bool final = false;
211
212         if (WARN_ON(obj->handle_count == 0))
213                 return;
214
215         /*
216         * Must bump handle count first as this may be the last
217         * ref, in which case the object would disappear before we
218         * checked for a name
219         */
220
221         mutex_lock(&dev->object_name_lock);
222         if (--obj->handle_count == 0) {
223                 drm_gem_object_handle_free(obj);
224                 drm_gem_object_exported_dma_buf_free(obj);
225                 final = true;
226         }
227         mutex_unlock(&dev->object_name_lock);
228
229         if (final)
230                 drm_gem_object_put_unlocked(obj);
231 }
232
233 /*
234  * Called at device or object close to release the file's
235  * handle references on objects.
236  */
237 static int
238 drm_gem_object_release_handle(int id, void *ptr, void *data)
239 {
240         struct drm_file *file_priv = data;
241         struct drm_gem_object *obj = ptr;
242         struct drm_device *dev = obj->dev;
243
244         if (obj->funcs && obj->funcs->close)
245                 obj->funcs->close(obj, file_priv);
246         else if (dev->driver->gem_close_object)
247                 dev->driver->gem_close_object(obj, file_priv);
248
249         if (drm_core_check_feature(dev, DRIVER_PRIME))
250                 drm_gem_remove_prime_handles(obj, file_priv);
251         drm_vma_node_revoke(&obj->vma_node, file_priv);
252
253         drm_gem_object_handle_put_unlocked(obj);
254
255         return 0;
256 }
257
258 /**
259  * drm_gem_handle_delete - deletes the given file-private handle
260  * @filp: drm file-private structure to use for the handle look up
261  * @handle: userspace handle to delete
262  *
263  * Removes the GEM handle from the @filp lookup table which has been added with
264  * drm_gem_handle_create(). If this is the last handle also cleans up linked
265  * resources like GEM names.
266  */
267 int
268 drm_gem_handle_delete(struct drm_file *filp, u32 handle)
269 {
270         struct drm_gem_object *obj;
271
272         spin_lock(&filp->table_lock);
273
274         /* Check if we currently have a reference on the object */
275         obj = idr_replace(&filp->object_idr, NULL, handle);
276         spin_unlock(&filp->table_lock);
277         if (IS_ERR_OR_NULL(obj))
278                 return -EINVAL;
279
280         /* Release driver's reference and decrement refcount. */
281         drm_gem_object_release_handle(handle, obj, filp);
282
283         /* And finally make the handle available for future allocations. */
284         spin_lock(&filp->table_lock);
285         idr_remove(&filp->object_idr, handle);
286         spin_unlock(&filp->table_lock);
287
288         return 0;
289 }
290 EXPORT_SYMBOL(drm_gem_handle_delete);
291
292 /**
293  * drm_gem_dumb_map_offset - return the fake mmap offset for a gem object
294  * @file: drm file-private structure containing the gem object
295  * @dev: corresponding drm_device
296  * @handle: gem object handle
297  * @offset: return location for the fake mmap offset
298  *
299  * This implements the &drm_driver.dumb_map_offset kms driver callback for
300  * drivers which use gem to manage their backing storage.
301  *
302  * Returns:
303  * 0 on success or a negative error code on failure.
304  */
305 int drm_gem_dumb_map_offset(struct drm_file *file, struct drm_device *dev,
306                             u32 handle, u64 *offset)
307 {
308         struct drm_gem_object *obj;
309         int ret;
310
311         obj = drm_gem_object_lookup(file, handle);
312         if (!obj)
313                 return -ENOENT;
314
315         /* Don't allow imported objects to be mapped */
316         if (obj->import_attach) {
317                 ret = -EINVAL;
318                 goto out;
319         }
320
321         ret = drm_gem_create_mmap_offset(obj);
322         if (ret)
323                 goto out;
324
325         *offset = drm_vma_node_offset_addr(&obj->vma_node);
326 out:
327         drm_gem_object_put_unlocked(obj);
328
329         return ret;
330 }
331 EXPORT_SYMBOL_GPL(drm_gem_dumb_map_offset);
332
333 /**
334  * drm_gem_dumb_destroy - dumb fb callback helper for gem based drivers
335  * @file: drm file-private structure to remove the dumb handle from
336  * @dev: corresponding drm_device
337  * @handle: the dumb handle to remove
338  *
339  * This implements the &drm_driver.dumb_destroy kms driver callback for drivers
340  * which use gem to manage their backing storage.
341  */
342 int drm_gem_dumb_destroy(struct drm_file *file,
343                          struct drm_device *dev,
344                          uint32_t handle)
345 {
346         return drm_gem_handle_delete(file, handle);
347 }
348 EXPORT_SYMBOL(drm_gem_dumb_destroy);
349
350 /**
351  * drm_gem_handle_create_tail - internal functions to create a handle
352  * @file_priv: drm file-private structure to register the handle for
353  * @obj: object to register
354  * @handlep: pointer to return the created handle to the caller
355  *
356  * This expects the &drm_device.object_name_lock to be held already and will
357  * drop it before returning. Used to avoid races in establishing new handles
358  * when importing an object from either an flink name or a dma-buf.
359  *
360  * Handles must be release again through drm_gem_handle_delete(). This is done
361  * when userspace closes @file_priv for all attached handles, or through the
362  * GEM_CLOSE ioctl for individual handles.
363  */
364 int
365 drm_gem_handle_create_tail(struct drm_file *file_priv,
366                            struct drm_gem_object *obj,
367                            u32 *handlep)
368 {
369         struct drm_device *dev = obj->dev;
370         u32 handle;
371         int ret;
372
373         WARN_ON(!mutex_is_locked(&dev->object_name_lock));
374         if (obj->handle_count++ == 0)
375                 drm_gem_object_get(obj);
376
377         /*
378          * Get the user-visible handle using idr.  Preload and perform
379          * allocation under our spinlock.
380          */
381         idr_preload(GFP_KERNEL);
382         spin_lock(&file_priv->table_lock);
383
384         ret = idr_alloc(&file_priv->object_idr, obj, 1, 0, GFP_NOWAIT);
385
386         spin_unlock(&file_priv->table_lock);
387         idr_preload_end();
388
389         mutex_unlock(&dev->object_name_lock);
390         if (ret < 0)
391                 goto err_unref;
392
393         handle = ret;
394
395         ret = drm_vma_node_allow(&obj->vma_node, file_priv);
396         if (ret)
397                 goto err_remove;
398
399         if (obj->funcs && obj->funcs->open) {
400                 ret = obj->funcs->open(obj, file_priv);
401                 if (ret)
402                         goto err_revoke;
403         } else if (dev->driver->gem_open_object) {
404                 ret = dev->driver->gem_open_object(obj, file_priv);
405                 if (ret)
406                         goto err_revoke;
407         }
408
409         *handlep = handle;
410         return 0;
411
412 err_revoke:
413         drm_vma_node_revoke(&obj->vma_node, file_priv);
414 err_remove:
415         spin_lock(&file_priv->table_lock);
416         idr_remove(&file_priv->object_idr, handle);
417         spin_unlock(&file_priv->table_lock);
418 err_unref:
419         drm_gem_object_handle_put_unlocked(obj);
420         return ret;
421 }
422
423 /**
424  * drm_gem_handle_create - create a gem handle for an object
425  * @file_priv: drm file-private structure to register the handle for
426  * @obj: object to register
427  * @handlep: pionter to return the created handle to the caller
428  *
429  * Create a handle for this object. This adds a handle reference to the object,
430  * which includes a regular reference count. Callers will likely want to
431  * dereference the object afterwards.
432  *
433  * Since this publishes @obj to userspace it must be fully set up by this point,
434  * drivers must call this last in their buffer object creation callbacks.
435  */
436 int drm_gem_handle_create(struct drm_file *file_priv,
437                           struct drm_gem_object *obj,
438                           u32 *handlep)
439 {
440         mutex_lock(&obj->dev->object_name_lock);
441
442         return drm_gem_handle_create_tail(file_priv, obj, handlep);
443 }
444 EXPORT_SYMBOL(drm_gem_handle_create);
445
446
447 /**
448  * drm_gem_free_mmap_offset - release a fake mmap offset for an object
449  * @obj: obj in question
450  *
451  * This routine frees fake offsets allocated by drm_gem_create_mmap_offset().
452  *
453  * Note that drm_gem_object_release() already calls this function, so drivers
454  * don't have to take care of releasing the mmap offset themselves when freeing
455  * the GEM object.
456  */
457 void
458 drm_gem_free_mmap_offset(struct drm_gem_object *obj)
459 {
460         struct drm_device *dev = obj->dev;
461
462         drm_vma_offset_remove(dev->vma_offset_manager, &obj->vma_node);
463 }
464 EXPORT_SYMBOL(drm_gem_free_mmap_offset);
465
466 /**
467  * drm_gem_create_mmap_offset_size - create a fake mmap offset for an object
468  * @obj: obj in question
469  * @size: the virtual size
470  *
471  * GEM memory mapping works by handing back to userspace a fake mmap offset
472  * it can use in a subsequent mmap(2) call.  The DRM core code then looks
473  * up the object based on the offset and sets up the various memory mapping
474  * structures.
475  *
476  * This routine allocates and attaches a fake offset for @obj, in cases where
477  * the virtual size differs from the physical size (ie. &drm_gem_object.size).
478  * Otherwise just use drm_gem_create_mmap_offset().
479  *
480  * This function is idempotent and handles an already allocated mmap offset
481  * transparently. Drivers do not need to check for this case.
482  */
483 int
484 drm_gem_create_mmap_offset_size(struct drm_gem_object *obj, size_t size)
485 {
486         struct drm_device *dev = obj->dev;
487
488         return drm_vma_offset_add(dev->vma_offset_manager, &obj->vma_node,
489                                   size / PAGE_SIZE);
490 }
491 EXPORT_SYMBOL(drm_gem_create_mmap_offset_size);
492
493 /**
494  * drm_gem_create_mmap_offset - create a fake mmap offset for an object
495  * @obj: obj in question
496  *
497  * GEM memory mapping works by handing back to userspace a fake mmap offset
498  * it can use in a subsequent mmap(2) call.  The DRM core code then looks
499  * up the object based on the offset and sets up the various memory mapping
500  * structures.
501  *
502  * This routine allocates and attaches a fake offset for @obj.
503  *
504  * Drivers can call drm_gem_free_mmap_offset() before freeing @obj to release
505  * the fake offset again.
506  */
507 int drm_gem_create_mmap_offset(struct drm_gem_object *obj)
508 {
509         return drm_gem_create_mmap_offset_size(obj, obj->size);
510 }
511 EXPORT_SYMBOL(drm_gem_create_mmap_offset);
512
513 /*
514  * Move pages to appropriate lru and release the pagevec, decrementing the
515  * ref count of those pages.
516  */
517 static void drm_gem_check_release_pagevec(struct pagevec *pvec)
518 {
519         check_move_unevictable_pages(pvec);
520         __pagevec_release(pvec);
521         cond_resched();
522 }
523
524 /**
525  * drm_gem_get_pages - helper to allocate backing pages for a GEM object
526  * from shmem
527  * @obj: obj in question
528  *
529  * This reads the page-array of the shmem-backing storage of the given gem
530  * object. An array of pages is returned. If a page is not allocated or
531  * swapped-out, this will allocate/swap-in the required pages. Note that the
532  * whole object is covered by the page-array and pinned in memory.
533  *
534  * Use drm_gem_put_pages() to release the array and unpin all pages.
535  *
536  * This uses the GFP-mask set on the shmem-mapping (see mapping_set_gfp_mask()).
537  * If you require other GFP-masks, you have to do those allocations yourself.
538  *
539  * Note that you are not allowed to change gfp-zones during runtime. That is,
540  * shmem_read_mapping_page_gfp() must be called with the same gfp_zone(gfp) as
541  * set during initialization. If you have special zone constraints, set them
542  * after drm_gem_object_init() via mapping_set_gfp_mask(). shmem-core takes care
543  * to keep pages in the required zone during swap-in.
544  */
545 struct page **drm_gem_get_pages(struct drm_gem_object *obj)
546 {
547         struct address_space *mapping;
548         struct page *p, **pages;
549         struct pagevec pvec;
550         int i, npages;
551
552         /* This is the shared memory object that backs the GEM resource */
553         mapping = obj->filp->f_mapping;
554
555         /* We already BUG_ON() for non-page-aligned sizes in
556          * drm_gem_object_init(), so we should never hit this unless
557          * driver author is doing something really wrong:
558          */
559         WARN_ON((obj->size & (PAGE_SIZE - 1)) != 0);
560
561         npages = obj->size >> PAGE_SHIFT;
562
563         pages = kvmalloc_array(npages, sizeof(struct page *), GFP_KERNEL);
564         if (pages == NULL)
565                 return ERR_PTR(-ENOMEM);
566
567         mapping_set_unevictable(mapping);
568
569         for (i = 0; i < npages; i++) {
570                 p = shmem_read_mapping_page(mapping, i);
571                 if (IS_ERR(p))
572                         goto fail;
573                 pages[i] = p;
574
575                 /* Make sure shmem keeps __GFP_DMA32 allocated pages in the
576                  * correct region during swapin. Note that this requires
577                  * __GFP_DMA32 to be set in mapping_gfp_mask(inode->i_mapping)
578                  * so shmem can relocate pages during swapin if required.
579                  */
580                 BUG_ON(mapping_gfp_constraint(mapping, __GFP_DMA32) &&
581                                 (page_to_pfn(p) >= 0x00100000UL));
582         }
583
584         return pages;
585
586 fail:
587         mapping_clear_unevictable(mapping);
588         pagevec_init(&pvec);
589         while (i--) {
590                 if (!pagevec_add(&pvec, pages[i]))
591                         drm_gem_check_release_pagevec(&pvec);
592         }
593         if (pagevec_count(&pvec))
594                 drm_gem_check_release_pagevec(&pvec);
595
596         kvfree(pages);
597         return ERR_CAST(p);
598 }
599 EXPORT_SYMBOL(drm_gem_get_pages);
600
601 /**
602  * drm_gem_put_pages - helper to free backing pages for a GEM object
603  * @obj: obj in question
604  * @pages: pages to free
605  * @dirty: if true, pages will be marked as dirty
606  * @accessed: if true, the pages will be marked as accessed
607  */
608 void drm_gem_put_pages(struct drm_gem_object *obj, struct page **pages,
609                 bool dirty, bool accessed)
610 {
611         int i, npages;
612         struct address_space *mapping;
613         struct pagevec pvec;
614
615         mapping = file_inode(obj->filp)->i_mapping;
616         mapping_clear_unevictable(mapping);
617
618         /* We already BUG_ON() for non-page-aligned sizes in
619          * drm_gem_object_init(), so we should never hit this unless
620          * driver author is doing something really wrong:
621          */
622         WARN_ON((obj->size & (PAGE_SIZE - 1)) != 0);
623
624         npages = obj->size >> PAGE_SHIFT;
625
626         pagevec_init(&pvec);
627         for (i = 0; i < npages; i++) {
628                 if (dirty)
629                         set_page_dirty(pages[i]);
630
631                 if (accessed)
632                         mark_page_accessed(pages[i]);
633
634                 /* Undo the reference we took when populating the table */
635                 if (!pagevec_add(&pvec, pages[i]))
636                         drm_gem_check_release_pagevec(&pvec);
637         }
638         if (pagevec_count(&pvec))
639                 drm_gem_check_release_pagevec(&pvec);
640
641         kvfree(pages);
642 }
643 EXPORT_SYMBOL(drm_gem_put_pages);
644
645 /**
646  * drm_gem_object_lookup - look up a GEM object from its handle
647  * @filp: DRM file private date
648  * @handle: userspace handle
649  *
650  * Returns:
651  *
652  * A reference to the object named by the handle if such exists on @filp, NULL
653  * otherwise.
654  */
655 struct drm_gem_object *
656 drm_gem_object_lookup(struct drm_file *filp, u32 handle)
657 {
658         struct drm_gem_object *obj;
659
660         spin_lock(&filp->table_lock);
661
662         /* Check if we currently have a reference on the object */
663         obj = idr_find(&filp->object_idr, handle);
664         if (obj)
665                 drm_gem_object_get(obj);
666
667         spin_unlock(&filp->table_lock);
668
669         return obj;
670 }
671 EXPORT_SYMBOL(drm_gem_object_lookup);
672
673 /**
674  * drm_gem_close_ioctl - implementation of the GEM_CLOSE ioctl
675  * @dev: drm_device
676  * @data: ioctl data
677  * @file_priv: drm file-private structure
678  *
679  * Releases the handle to an mm object.
680  */
681 int
682 drm_gem_close_ioctl(struct drm_device *dev, void *data,
683                     struct drm_file *file_priv)
684 {
685         struct drm_gem_close *args = data;
686         int ret;
687
688         if (!drm_core_check_feature(dev, DRIVER_GEM))
689                 return -EOPNOTSUPP;
690
691         ret = drm_gem_handle_delete(file_priv, args->handle);
692
693         return ret;
694 }
695
696 /**
697  * drm_gem_flink_ioctl - implementation of the GEM_FLINK ioctl
698  * @dev: drm_device
699  * @data: ioctl data
700  * @file_priv: drm file-private structure
701  *
702  * Create a global name for an object, returning the name.
703  *
704  * Note that the name does not hold a reference; when the object
705  * is freed, the name goes away.
706  */
707 int
708 drm_gem_flink_ioctl(struct drm_device *dev, void *data,
709                     struct drm_file *file_priv)
710 {
711         struct drm_gem_flink *args = data;
712         struct drm_gem_object *obj;
713         int ret;
714
715         if (!drm_core_check_feature(dev, DRIVER_GEM))
716                 return -EOPNOTSUPP;
717
718         obj = drm_gem_object_lookup(file_priv, args->handle);
719         if (obj == NULL)
720                 return -ENOENT;
721
722         mutex_lock(&dev->object_name_lock);
723         /* prevent races with concurrent gem_close. */
724         if (obj->handle_count == 0) {
725                 ret = -ENOENT;
726                 goto err;
727         }
728
729         if (!obj->name) {
730                 ret = idr_alloc(&dev->object_name_idr, obj, 1, 0, GFP_KERNEL);
731                 if (ret < 0)
732                         goto err;
733
734                 obj->name = ret;
735         }
736
737         args->name = (uint64_t) obj->name;
738         ret = 0;
739
740 err:
741         mutex_unlock(&dev->object_name_lock);
742         drm_gem_object_put_unlocked(obj);
743         return ret;
744 }
745
746 /**
747  * drm_gem_open - implementation of the GEM_OPEN ioctl
748  * @dev: drm_device
749  * @data: ioctl data
750  * @file_priv: drm file-private structure
751  *
752  * Open an object using the global name, returning a handle and the size.
753  *
754  * This handle (of course) holds a reference to the object, so the object
755  * will not go away until the handle is deleted.
756  */
757 int
758 drm_gem_open_ioctl(struct drm_device *dev, void *data,
759                    struct drm_file *file_priv)
760 {
761         struct drm_gem_open *args = data;
762         struct drm_gem_object *obj;
763         int ret;
764         u32 handle;
765
766         if (!drm_core_check_feature(dev, DRIVER_GEM))
767                 return -EOPNOTSUPP;
768
769         mutex_lock(&dev->object_name_lock);
770         obj = idr_find(&dev->object_name_idr, (int) args->name);
771         if (obj) {
772                 drm_gem_object_get(obj);
773         } else {
774                 mutex_unlock(&dev->object_name_lock);
775                 return -ENOENT;
776         }
777
778         /* drm_gem_handle_create_tail unlocks dev->object_name_lock. */
779         ret = drm_gem_handle_create_tail(file_priv, obj, &handle);
780         drm_gem_object_put_unlocked(obj);
781         if (ret)
782                 return ret;
783
784         args->handle = handle;
785         args->size = obj->size;
786
787         return 0;
788 }
789
790 /**
791  * gem_gem_open - initalizes GEM file-private structures at devnode open time
792  * @dev: drm_device which is being opened by userspace
793  * @file_private: drm file-private structure to set up
794  *
795  * Called at device open time, sets up the structure for handling refcounting
796  * of mm objects.
797  */
798 void
799 drm_gem_open(struct drm_device *dev, struct drm_file *file_private)
800 {
801         idr_init_base(&file_private->object_idr, 1);
802         spin_lock_init(&file_private->table_lock);
803 }
804
805 /**
806  * drm_gem_release - release file-private GEM resources
807  * @dev: drm_device which is being closed by userspace
808  * @file_private: drm file-private structure to clean up
809  *
810  * Called at close time when the filp is going away.
811  *
812  * Releases any remaining references on objects by this filp.
813  */
814 void
815 drm_gem_release(struct drm_device *dev, struct drm_file *file_private)
816 {
817         idr_for_each(&file_private->object_idr,
818                      &drm_gem_object_release_handle, file_private);
819         idr_destroy(&file_private->object_idr);
820 }
821
822 /**
823  * drm_gem_object_release - release GEM buffer object resources
824  * @obj: GEM buffer object
825  *
826  * This releases any structures and resources used by @obj and is the invers of
827  * drm_gem_object_init().
828  */
829 void
830 drm_gem_object_release(struct drm_gem_object *obj)
831 {
832         WARN_ON(obj->dma_buf);
833
834         if (obj->filp)
835                 fput(obj->filp);
836
837         drm_gem_free_mmap_offset(obj);
838 }
839 EXPORT_SYMBOL(drm_gem_object_release);
840
841 /**
842  * drm_gem_object_free - free a GEM object
843  * @kref: kref of the object to free
844  *
845  * Called after the last reference to the object has been lost.
846  * Must be called holding &drm_device.struct_mutex.
847  *
848  * Frees the object
849  */
850 void
851 drm_gem_object_free(struct kref *kref)
852 {
853         struct drm_gem_object *obj =
854                 container_of(kref, struct drm_gem_object, refcount);
855         struct drm_device *dev = obj->dev;
856
857         if (obj->funcs) {
858                 obj->funcs->free(obj);
859         } else if (dev->driver->gem_free_object_unlocked) {
860                 dev->driver->gem_free_object_unlocked(obj);
861         } else if (dev->driver->gem_free_object) {
862                 WARN_ON(!mutex_is_locked(&dev->struct_mutex));
863
864                 dev->driver->gem_free_object(obj);
865         }
866 }
867 EXPORT_SYMBOL(drm_gem_object_free);
868
869 /**
870  * drm_gem_object_put_unlocked - drop a GEM buffer object reference
871  * @obj: GEM buffer object
872  *
873  * This releases a reference to @obj. Callers must not hold the
874  * &drm_device.struct_mutex lock when calling this function.
875  *
876  * See also __drm_gem_object_put().
877  */
878 void
879 drm_gem_object_put_unlocked(struct drm_gem_object *obj)
880 {
881         struct drm_device *dev;
882
883         if (!obj)
884                 return;
885
886         dev = obj->dev;
887
888         if (dev->driver->gem_free_object) {
889                 might_lock(&dev->struct_mutex);
890                 if (kref_put_mutex(&obj->refcount, drm_gem_object_free,
891                                 &dev->struct_mutex))
892                         mutex_unlock(&dev->struct_mutex);
893         } else {
894                 kref_put(&obj->refcount, drm_gem_object_free);
895         }
896 }
897 EXPORT_SYMBOL(drm_gem_object_put_unlocked);
898
899 /**
900  * drm_gem_object_put - release a GEM buffer object reference
901  * @obj: GEM buffer object
902  *
903  * This releases a reference to @obj. Callers must hold the
904  * &drm_device.struct_mutex lock when calling this function, even when the
905  * driver doesn't use &drm_device.struct_mutex for anything.
906  *
907  * For drivers not encumbered with legacy locking use
908  * drm_gem_object_put_unlocked() instead.
909  */
910 void
911 drm_gem_object_put(struct drm_gem_object *obj)
912 {
913         if (obj) {
914                 WARN_ON(!mutex_is_locked(&obj->dev->struct_mutex));
915
916                 kref_put(&obj->refcount, drm_gem_object_free);
917         }
918 }
919 EXPORT_SYMBOL(drm_gem_object_put);
920
921 /**
922  * drm_gem_vm_open - vma->ops->open implementation for GEM
923  * @vma: VM area structure
924  *
925  * This function implements the #vm_operations_struct open() callback for GEM
926  * drivers. This must be used together with drm_gem_vm_close().
927  */
928 void drm_gem_vm_open(struct vm_area_struct *vma)
929 {
930         struct drm_gem_object *obj = vma->vm_private_data;
931
932         drm_gem_object_get(obj);
933 }
934 EXPORT_SYMBOL(drm_gem_vm_open);
935
936 /**
937  * drm_gem_vm_close - vma->ops->close implementation for GEM
938  * @vma: VM area structure
939  *
940  * This function implements the #vm_operations_struct close() callback for GEM
941  * drivers. This must be used together with drm_gem_vm_open().
942  */
943 void drm_gem_vm_close(struct vm_area_struct *vma)
944 {
945         struct drm_gem_object *obj = vma->vm_private_data;
946
947         drm_gem_object_put_unlocked(obj);
948 }
949 EXPORT_SYMBOL(drm_gem_vm_close);
950
951 /**
952  * drm_gem_mmap_obj - memory map a GEM object
953  * @obj: the GEM object to map
954  * @obj_size: the object size to be mapped, in bytes
955  * @vma: VMA for the area to be mapped
956  *
957  * Set up the VMA to prepare mapping of the GEM object using the gem_vm_ops
958  * provided by the driver. Depending on their requirements, drivers can either
959  * provide a fault handler in their gem_vm_ops (in which case any accesses to
960  * the object will be trapped, to perform migration, GTT binding, surface
961  * register allocation, or performance monitoring), or mmap the buffer memory
962  * synchronously after calling drm_gem_mmap_obj.
963  *
964  * This function is mainly intended to implement the DMABUF mmap operation, when
965  * the GEM object is not looked up based on its fake offset. To implement the
966  * DRM mmap operation, drivers should use the drm_gem_mmap() function.
967  *
968  * drm_gem_mmap_obj() assumes the user is granted access to the buffer while
969  * drm_gem_mmap() prevents unprivileged users from mapping random objects. So
970  * callers must verify access restrictions before calling this helper.
971  *
972  * Return 0 or success or -EINVAL if the object size is smaller than the VMA
973  * size, or if no gem_vm_ops are provided.
974  */
975 int drm_gem_mmap_obj(struct drm_gem_object *obj, unsigned long obj_size,
976                      struct vm_area_struct *vma)
977 {
978         struct drm_device *dev = obj->dev;
979
980         /* Check for valid size. */
981         if (obj_size < vma->vm_end - vma->vm_start)
982                 return -EINVAL;
983
984         if (obj->funcs && obj->funcs->vm_ops)
985                 vma->vm_ops = obj->funcs->vm_ops;
986         else if (dev->driver->gem_vm_ops)
987                 vma->vm_ops = dev->driver->gem_vm_ops;
988         else
989                 return -EINVAL;
990
991         vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
992         vma->vm_private_data = obj;
993         vma->vm_page_prot = pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
994         vma->vm_page_prot = pgprot_decrypted(vma->vm_page_prot);
995
996         /* Take a ref for this mapping of the object, so that the fault
997          * handler can dereference the mmap offset's pointer to the object.
998          * This reference is cleaned up by the corresponding vm_close
999          * (which should happen whether the vma was created by this call, or
1000          * by a vm_open due to mremap or partial unmap or whatever).
1001          */
1002         drm_gem_object_get(obj);
1003
1004         return 0;
1005 }
1006 EXPORT_SYMBOL(drm_gem_mmap_obj);
1007
1008 /**
1009  * drm_gem_mmap - memory map routine for GEM objects
1010  * @filp: DRM file pointer
1011  * @vma: VMA for the area to be mapped
1012  *
1013  * If a driver supports GEM object mapping, mmap calls on the DRM file
1014  * descriptor will end up here.
1015  *
1016  * Look up the GEM object based on the offset passed in (vma->vm_pgoff will
1017  * contain the fake offset we created when the GTT map ioctl was called on
1018  * the object) and map it with a call to drm_gem_mmap_obj().
1019  *
1020  * If the caller is not granted access to the buffer object, the mmap will fail
1021  * with EACCES. Please see the vma manager for more information.
1022  */
1023 int drm_gem_mmap(struct file *filp, struct vm_area_struct *vma)
1024 {
1025         struct drm_file *priv = filp->private_data;
1026         struct drm_device *dev = priv->minor->dev;
1027         struct drm_gem_object *obj = NULL;
1028         struct drm_vma_offset_node *node;
1029         int ret;
1030
1031         if (drm_dev_is_unplugged(dev))
1032                 return -ENODEV;
1033
1034         drm_vma_offset_lock_lookup(dev->vma_offset_manager);
1035         node = drm_vma_offset_exact_lookup_locked(dev->vma_offset_manager,
1036                                                   vma->vm_pgoff,
1037                                                   vma_pages(vma));
1038         if (likely(node)) {
1039                 obj = container_of(node, struct drm_gem_object, vma_node);
1040                 /*
1041                  * When the object is being freed, after it hits 0-refcnt it
1042                  * proceeds to tear down the object. In the process it will
1043                  * attempt to remove the VMA offset and so acquire this
1044                  * mgr->vm_lock.  Therefore if we find an object with a 0-refcnt
1045                  * that matches our range, we know it is in the process of being
1046                  * destroyed and will be freed as soon as we release the lock -
1047                  * so we have to check for the 0-refcnted object and treat it as
1048                  * invalid.
1049                  */
1050                 if (!kref_get_unless_zero(&obj->refcount))
1051                         obj = NULL;
1052         }
1053         drm_vma_offset_unlock_lookup(dev->vma_offset_manager);
1054
1055         if (!obj)
1056                 return -EINVAL;
1057
1058         if (!drm_vma_node_is_allowed(node, priv)) {
1059                 drm_gem_object_put_unlocked(obj);
1060                 return -EACCES;
1061         }
1062
1063         if (node->readonly) {
1064                 if (vma->vm_flags & VM_WRITE) {
1065                         drm_gem_object_put_unlocked(obj);
1066                         return -EINVAL;
1067                 }
1068
1069                 vma->vm_flags &= ~VM_MAYWRITE;
1070         }
1071
1072         ret = drm_gem_mmap_obj(obj, drm_vma_node_size(node) << PAGE_SHIFT,
1073                                vma);
1074
1075         drm_gem_object_put_unlocked(obj);
1076
1077         return ret;
1078 }
1079 EXPORT_SYMBOL(drm_gem_mmap);
1080
1081 void drm_gem_print_info(struct drm_printer *p, unsigned int indent,
1082                         const struct drm_gem_object *obj)
1083 {
1084         drm_printf_indent(p, indent, "name=%d\n", obj->name);
1085         drm_printf_indent(p, indent, "refcount=%u\n",
1086                           kref_read(&obj->refcount));
1087         drm_printf_indent(p, indent, "start=%08lx\n",
1088                           drm_vma_node_start(&obj->vma_node));
1089         drm_printf_indent(p, indent, "size=%zu\n", obj->size);
1090         drm_printf_indent(p, indent, "imported=%s\n",
1091                           obj->import_attach ? "yes" : "no");
1092
1093         if (obj->funcs && obj->funcs->print_info)
1094                 obj->funcs->print_info(p, indent, obj);
1095         else if (obj->dev->driver->gem_print_info)
1096                 obj->dev->driver->gem_print_info(p, indent, obj);
1097 }
1098
1099 /**
1100  * drm_gem_pin - Pin backing buffer in memory
1101  * @obj: GEM object
1102  *
1103  * Make sure the backing buffer is pinned in memory.
1104  *
1105  * Returns:
1106  * 0 on success or a negative error code on failure.
1107  */
1108 int drm_gem_pin(struct drm_gem_object *obj)
1109 {
1110         if (obj->funcs && obj->funcs->pin)
1111                 return obj->funcs->pin(obj);
1112         else if (obj->dev->driver->gem_prime_pin)
1113                 return obj->dev->driver->gem_prime_pin(obj);
1114         else
1115                 return 0;
1116 }
1117 EXPORT_SYMBOL(drm_gem_pin);
1118
1119 /**
1120  * drm_gem_unpin - Unpin backing buffer from memory
1121  * @obj: GEM object
1122  *
1123  * Relax the requirement that the backing buffer is pinned in memory.
1124  */
1125 void drm_gem_unpin(struct drm_gem_object *obj)
1126 {
1127         if (obj->funcs && obj->funcs->unpin)
1128                 obj->funcs->unpin(obj);
1129         else if (obj->dev->driver->gem_prime_unpin)
1130                 obj->dev->driver->gem_prime_unpin(obj);
1131 }
1132 EXPORT_SYMBOL(drm_gem_unpin);
1133
1134 /**
1135  * drm_gem_vmap - Map buffer into kernel virtual address space
1136  * @obj: GEM object
1137  *
1138  * Returns:
1139  * A virtual pointer to a newly created GEM object or an ERR_PTR-encoded negative
1140  * error code on failure.
1141  */
1142 void *drm_gem_vmap(struct drm_gem_object *obj)
1143 {
1144         void *vaddr;
1145
1146         if (obj->funcs && obj->funcs->vmap)
1147                 vaddr = obj->funcs->vmap(obj);
1148         else if (obj->dev->driver->gem_prime_vmap)
1149                 vaddr = obj->dev->driver->gem_prime_vmap(obj);
1150         else
1151                 vaddr = ERR_PTR(-EOPNOTSUPP);
1152
1153         if (!vaddr)
1154                 vaddr = ERR_PTR(-ENOMEM);
1155
1156         return vaddr;
1157 }
1158 EXPORT_SYMBOL(drm_gem_vmap);
1159
1160 /**
1161  * drm_gem_vunmap - Remove buffer mapping from kernel virtual address space
1162  * @obj: GEM object
1163  * @vaddr: Virtual address (can be NULL)
1164  */
1165 void drm_gem_vunmap(struct drm_gem_object *obj, void *vaddr)
1166 {
1167         if (!vaddr)
1168                 return;
1169
1170         if (obj->funcs && obj->funcs->vunmap)
1171                 obj->funcs->vunmap(obj, vaddr);
1172         else if (obj->dev->driver->gem_prime_vunmap)
1173                 obj->dev->driver->gem_prime_vunmap(obj, vaddr);
1174 }
1175 EXPORT_SYMBOL(drm_gem_vunmap);