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