1 /*
2 * \author Rickard E. (Rik) Faith <faith@valinux.com>
3 * \author Daryll Strauss <daryll@valinux.com>
4 * \author Gareth Hughes <gareth@valinux.com>
5 */
6
7 /*
8 * Created: Mon Jan 4 08:58:31 1999 by faith@valinux.com
9 *
10 * Copyright 1999 Precision Insight, Inc., Cedar Park, Texas.
11 * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California.
12 * All Rights Reserved.
13 *
14 * Permission is hereby granted, free of charge, to any person obtaining a
15 * copy of this software and associated documentation files (the "Software"),
16 * to deal in the Software without restriction, including without limitation
17 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
18 * and/or sell copies of the Software, and to permit persons to whom the
19 * Software is furnished to do so, subject to the following conditions:
20 *
21 * The above copyright notice and this permission notice (including the next
22 * paragraph) shall be included in all copies or substantial portions of the
23 * Software.
24 *
25 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
28 * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
29 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
30 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
31 * OTHER DEALINGS IN THE SOFTWARE.
32 */
33
34 #include <linux/anon_inodes.h>
35 #include <linux/dma-fence.h>
36 #include <linux/file.h>
37 #include <linux/module.h>
38 #include <linux/pci.h>
39 #include <linux/poll.h>
40 #include <linux/slab.h>
41 #include <linux/vga_switcheroo.h>
42
43 #include <drm/drm_client.h>
44 #include <drm/drm_drv.h>
45 #include <drm/drm_file.h>
46 #include <drm/drm_gem.h>
47 #include <drm/drm_print.h>
48
49 #include "drm_crtc_internal.h"
50 #include "drm_internal.h"
51
52 #include <linux/android_kabi.h>
53 ANDROID_KABI_DECLONLY(dma_buf);
54 ANDROID_KABI_DECLONLY(dma_buf_attachment);
55
56 /* from BKL pushdown */
57 DEFINE_MUTEX(drm_global_mutex);
58
drm_dev_needs_global_mutex(struct drm_device * dev)59 bool drm_dev_needs_global_mutex(struct drm_device *dev)
60 {
61 /*
62 * The deprecated ->load callback must be called after the driver is
63 * already registered. This means such drivers rely on the BKL to make
64 * sure an open can't proceed until the driver is actually fully set up.
65 * Similar hilarity holds for the unload callback.
66 */
67 if (dev->driver->load || dev->driver->unload)
68 return true;
69
70 return false;
71 }
72
73 /**
74 * DOC: file operations
75 *
76 * Drivers must define the file operations structure that forms the DRM
77 * userspace API entry point, even though most of those operations are
78 * implemented in the DRM core. The resulting &struct file_operations must be
79 * stored in the &drm_driver.fops field. The mandatory functions are drm_open(),
80 * drm_read(), drm_ioctl() and drm_compat_ioctl() if CONFIG_COMPAT is enabled
81 * Note that drm_compat_ioctl will be NULL if CONFIG_COMPAT=n, so there's no
82 * need to sprinkle #ifdef into the code. Drivers which implement private ioctls
83 * that require 32/64 bit compatibility support must provide their own
84 * &file_operations.compat_ioctl handler that processes private ioctls and calls
85 * drm_compat_ioctl() for core ioctls.
86 *
87 * In addition drm_read() and drm_poll() provide support for DRM events. DRM
88 * events are a generic and extensible means to send asynchronous events to
89 * userspace through the file descriptor. They are used to send vblank event and
90 * page flip completions by the KMS API. But drivers can also use it for their
91 * own needs, e.g. to signal completion of rendering.
92 *
93 * For the driver-side event interface see drm_event_reserve_init() and
94 * drm_send_event() as the main starting points.
95 *
96 * The memory mapping implementation will vary depending on how the driver
97 * manages memory. For GEM-based drivers this is drm_gem_mmap().
98 *
99 * No other file operations are supported by the DRM userspace API. Overall the
100 * following is an example &file_operations structure::
101 *
102 * static const example_drm_fops = {
103 * .owner = THIS_MODULE,
104 * .open = drm_open,
105 * .release = drm_release,
106 * .unlocked_ioctl = drm_ioctl,
107 * .compat_ioctl = drm_compat_ioctl, // NULL if CONFIG_COMPAT=n
108 * .poll = drm_poll,
109 * .read = drm_read,
110 * .mmap = drm_gem_mmap,
111 * };
112 *
113 * For plain GEM based drivers there is the DEFINE_DRM_GEM_FOPS() macro, and for
114 * DMA based drivers there is the DEFINE_DRM_GEM_DMA_FOPS() macro to make this
115 * simpler.
116 *
117 * The driver's &file_operations must be stored in &drm_driver.fops.
118 *
119 * For driver-private IOCTL handling see the more detailed discussion in
120 * :ref:`IOCTL support in the userland interfaces chapter<drm_driver_ioctl>`.
121 */
122
123 /**
124 * drm_file_alloc - allocate file context
125 * @minor: minor to allocate on
126 *
127 * This allocates a new DRM file context. It is not linked into any context and
128 * can be used by the caller freely. Note that the context keeps a pointer to
129 * @minor, so it must be freed before @minor is.
130 *
131 * RETURNS:
132 * Pointer to newly allocated context, ERR_PTR on failure.
133 */
drm_file_alloc(struct drm_minor * minor)134 struct drm_file *drm_file_alloc(struct drm_minor *minor)
135 {
136 static atomic64_t ident = ATOMIC64_INIT(0);
137 struct drm_device *dev = minor->dev;
138 struct drm_file *file;
139 int ret;
140
141 file = kzalloc(sizeof(*file), GFP_KERNEL);
142 if (!file)
143 return ERR_PTR(-ENOMEM);
144
145 /* Get a unique identifier for fdinfo: */
146 file->client_id = atomic64_inc_return(&ident);
147 rcu_assign_pointer(file->pid, get_pid(task_tgid(current)));
148 file->minor = minor;
149
150 /* for compatibility root is always authenticated */
151 file->authenticated = capable(CAP_SYS_ADMIN);
152
153 INIT_LIST_HEAD(&file->lhead);
154 INIT_LIST_HEAD(&file->fbs);
155 mutex_init(&file->fbs_lock);
156 INIT_LIST_HEAD(&file->blobs);
157 INIT_LIST_HEAD(&file->pending_event_list);
158 INIT_LIST_HEAD(&file->event_list);
159 init_waitqueue_head(&file->event_wait);
160 file->event_space = 4096; /* set aside 4k for event buffer */
161
162 spin_lock_init(&file->master_lookup_lock);
163 mutex_init(&file->event_read_lock);
164
165 if (drm_core_check_feature(dev, DRIVER_GEM))
166 drm_gem_open(dev, file);
167
168 if (drm_core_check_feature(dev, DRIVER_SYNCOBJ))
169 drm_syncobj_open(file);
170
171 drm_prime_init_file_private(&file->prime);
172
173 if (dev->driver->open) {
174 ret = dev->driver->open(dev, file);
175 if (ret < 0)
176 goto out_prime_destroy;
177 }
178
179 return file;
180
181 out_prime_destroy:
182 drm_prime_destroy_file_private(&file->prime);
183 if (drm_core_check_feature(dev, DRIVER_SYNCOBJ))
184 drm_syncobj_release(file);
185 if (drm_core_check_feature(dev, DRIVER_GEM))
186 drm_gem_release(dev, file);
187 put_pid(rcu_access_pointer(file->pid));
188 kfree(file);
189
190 return ERR_PTR(ret);
191 }
192
drm_events_release(struct drm_file * file_priv)193 static void drm_events_release(struct drm_file *file_priv)
194 {
195 struct drm_device *dev = file_priv->minor->dev;
196 struct drm_pending_event *e, *et;
197 unsigned long flags;
198
199 spin_lock_irqsave(&dev->event_lock, flags);
200
201 /* Unlink pending events */
202 list_for_each_entry_safe(e, et, &file_priv->pending_event_list,
203 pending_link) {
204 list_del(&e->pending_link);
205 e->file_priv = NULL;
206 }
207
208 /* Remove unconsumed events */
209 list_for_each_entry_safe(e, et, &file_priv->event_list, link) {
210 list_del(&e->link);
211 kfree(e);
212 }
213
214 spin_unlock_irqrestore(&dev->event_lock, flags);
215 }
216
217 /**
218 * drm_file_free - free file context
219 * @file: context to free, or NULL
220 *
221 * This destroys and deallocates a DRM file context previously allocated via
222 * drm_file_alloc(). The caller must make sure to unlink it from any contexts
223 * before calling this.
224 *
225 * If NULL is passed, this is a no-op.
226 */
drm_file_free(struct drm_file * file)227 void drm_file_free(struct drm_file *file)
228 {
229 struct drm_device *dev;
230
231 if (!file)
232 return;
233
234 dev = file->minor->dev;
235
236 drm_dbg_core(dev, "comm=\"%s\", pid=%d, dev=0x%lx, open_count=%d\n",
237 current->comm, task_pid_nr(current),
238 (long)old_encode_dev(file->minor->kdev->devt),
239 atomic_read(&dev->open_count));
240
241 drm_events_release(file);
242
243 if (drm_core_check_feature(dev, DRIVER_MODESET)) {
244 drm_fb_release(file);
245 drm_property_destroy_user_blobs(dev, file);
246 }
247
248 if (drm_core_check_feature(dev, DRIVER_SYNCOBJ))
249 drm_syncobj_release(file);
250
251 if (drm_core_check_feature(dev, DRIVER_GEM))
252 drm_gem_release(dev, file);
253
254 if (drm_is_primary_client(file))
255 drm_master_release(file);
256
257 if (dev->driver->postclose)
258 dev->driver->postclose(dev, file);
259
260 drm_prime_destroy_file_private(&file->prime);
261
262 WARN_ON(!list_empty(&file->event_list));
263
264 put_pid(rcu_access_pointer(file->pid));
265 kfree(file);
266 }
267
drm_close_helper(struct file * filp)268 static void drm_close_helper(struct file *filp)
269 {
270 struct drm_file *file_priv = filp->private_data;
271 struct drm_device *dev = file_priv->minor->dev;
272
273 mutex_lock(&dev->filelist_mutex);
274 list_del(&file_priv->lhead);
275 mutex_unlock(&dev->filelist_mutex);
276
277 drm_file_free(file_priv);
278 }
279
280 /*
281 * Check whether DRI will run on this CPU.
282 *
283 * \return non-zero if the DRI will run on this CPU, or zero otherwise.
284 */
drm_cpu_valid(void)285 static int drm_cpu_valid(void)
286 {
287 #if defined(__sparc__) && !defined(__sparc_v9__)
288 return 0; /* No cmpxchg before v9 sparc. */
289 #endif
290 return 1;
291 }
292
293 /*
294 * Called whenever a process opens a drm node
295 *
296 * \param filp file pointer.
297 * \param minor acquired minor-object.
298 * \return zero on success or a negative number on failure.
299 *
300 * Creates and initializes a drm_file structure for the file private data in \p
301 * filp and add it into the double linked list in \p dev.
302 */
drm_open_helper(struct file * filp,struct drm_minor * minor)303 int drm_open_helper(struct file *filp, struct drm_minor *minor)
304 {
305 struct drm_device *dev = minor->dev;
306 struct drm_file *priv;
307 int ret;
308
309 if (filp->f_flags & O_EXCL)
310 return -EBUSY; /* No exclusive opens */
311 if (!drm_cpu_valid())
312 return -EINVAL;
313 if (dev->switch_power_state != DRM_SWITCH_POWER_ON &&
314 dev->switch_power_state != DRM_SWITCH_POWER_DYNAMIC_OFF)
315 return -EINVAL;
316 if (WARN_ON_ONCE(!(filp->f_op->fop_flags & FOP_UNSIGNED_OFFSET)))
317 return -EINVAL;
318
319 drm_dbg_core(dev, "comm=\"%s\", pid=%d, minor=%d\n",
320 current->comm, task_pid_nr(current), minor->index);
321
322 priv = drm_file_alloc(minor);
323 if (IS_ERR(priv))
324 return PTR_ERR(priv);
325
326 if (drm_is_primary_client(priv)) {
327 ret = drm_master_open(priv);
328 if (ret) {
329 drm_file_free(priv);
330 return ret;
331 }
332 }
333
334 filp->private_data = priv;
335 priv->filp = filp;
336
337 mutex_lock(&dev->filelist_mutex);
338 list_add(&priv->lhead, &dev->filelist);
339 mutex_unlock(&dev->filelist_mutex);
340
341 return 0;
342 }
343
344 /**
345 * drm_open - open method for DRM file
346 * @inode: device inode
347 * @filp: file pointer.
348 *
349 * This function must be used by drivers as their &file_operations.open method.
350 * It looks up the correct DRM device and instantiates all the per-file
351 * resources for it. It also calls the &drm_driver.open driver callback.
352 *
353 * RETURNS:
354 * 0 on success or negative errno value on failure.
355 */
drm_open(struct inode * inode,struct file * filp)356 int drm_open(struct inode *inode, struct file *filp)
357 {
358 struct drm_device *dev;
359 struct drm_minor *minor;
360 int retcode;
361
362 minor = drm_minor_acquire(&drm_minors_xa, iminor(inode));
363 if (IS_ERR(minor))
364 return PTR_ERR(minor);
365
366 dev = minor->dev;
367 if (drm_dev_needs_global_mutex(dev))
368 mutex_lock(&drm_global_mutex);
369
370 atomic_fetch_inc(&dev->open_count);
371
372 /* share address_space across all char-devs of a single device */
373 filp->f_mapping = dev->anon_inode->i_mapping;
374
375 retcode = drm_open_helper(filp, minor);
376 if (retcode)
377 goto err_undo;
378
379 if (drm_dev_needs_global_mutex(dev))
380 mutex_unlock(&drm_global_mutex);
381
382 return 0;
383
384 err_undo:
385 atomic_dec(&dev->open_count);
386 if (drm_dev_needs_global_mutex(dev))
387 mutex_unlock(&drm_global_mutex);
388 drm_minor_release(minor);
389 return retcode;
390 }
391 EXPORT_SYMBOL(drm_open);
392
drm_lastclose(struct drm_device * dev)393 static void drm_lastclose(struct drm_device *dev)
394 {
395 drm_client_dev_restore(dev);
396
397 if (dev_is_pci(dev->dev))
398 vga_switcheroo_process_delayed_switch();
399 }
400
401 /**
402 * drm_release - release method for DRM file
403 * @inode: device inode
404 * @filp: file pointer.
405 *
406 * This function must be used by drivers as their &file_operations.release
407 * method. It frees any resources associated with the open file. If this
408 * is the last open file for the DRM device, it also restores the active
409 * in-kernel DRM client.
410 *
411 * RETURNS:
412 * Always succeeds and returns 0.
413 */
drm_release(struct inode * inode,struct file * filp)414 int drm_release(struct inode *inode, struct file *filp)
415 {
416 struct drm_file *file_priv = filp->private_data;
417 struct drm_minor *minor = file_priv->minor;
418 struct drm_device *dev = minor->dev;
419
420 if (drm_dev_needs_global_mutex(dev))
421 mutex_lock(&drm_global_mutex);
422
423 drm_dbg_core(dev, "open_count = %d\n", atomic_read(&dev->open_count));
424
425 drm_close_helper(filp);
426
427 if (atomic_dec_and_test(&dev->open_count))
428 drm_lastclose(dev);
429
430 if (drm_dev_needs_global_mutex(dev))
431 mutex_unlock(&drm_global_mutex);
432
433 drm_minor_release(minor);
434
435 return 0;
436 }
437 EXPORT_SYMBOL(drm_release);
438
drm_file_update_pid(struct drm_file * filp)439 void drm_file_update_pid(struct drm_file *filp)
440 {
441 struct drm_device *dev;
442 struct pid *pid, *old;
443
444 /*
445 * Master nodes need to keep the original ownership in order for
446 * drm_master_check_perm to keep working correctly. (See comment in
447 * drm_auth.c.)
448 */
449 if (filp->was_master)
450 return;
451
452 pid = task_tgid(current);
453
454 /*
455 * Quick unlocked check since the model is a single handover followed by
456 * exclusive repeated use.
457 */
458 if (pid == rcu_access_pointer(filp->pid))
459 return;
460
461 dev = filp->minor->dev;
462 mutex_lock(&dev->filelist_mutex);
463 get_pid(pid);
464 old = rcu_replace_pointer(filp->pid, pid, 1);
465 mutex_unlock(&dev->filelist_mutex);
466
467 synchronize_rcu();
468 put_pid(old);
469 }
470
471 /**
472 * drm_release_noglobal - release method for DRM file
473 * @inode: device inode
474 * @filp: file pointer.
475 *
476 * This function may be used by drivers as their &file_operations.release
477 * method. It frees any resources associated with the open file prior to taking
478 * the drm_global_mutex. If this is the last open file for the DRM device, it
479 * then restores the active in-kernel DRM client.
480 *
481 * RETURNS:
482 * Always succeeds and returns 0.
483 */
drm_release_noglobal(struct inode * inode,struct file * filp)484 int drm_release_noglobal(struct inode *inode, struct file *filp)
485 {
486 struct drm_file *file_priv = filp->private_data;
487 struct drm_minor *minor = file_priv->minor;
488 struct drm_device *dev = minor->dev;
489
490 drm_close_helper(filp);
491
492 if (atomic_dec_and_mutex_lock(&dev->open_count, &drm_global_mutex)) {
493 drm_lastclose(dev);
494 mutex_unlock(&drm_global_mutex);
495 }
496
497 drm_minor_release(minor);
498
499 return 0;
500 }
501 EXPORT_SYMBOL(drm_release_noglobal);
502
503 /**
504 * drm_read - read method for DRM file
505 * @filp: file pointer
506 * @buffer: userspace destination pointer for the read
507 * @count: count in bytes to read
508 * @offset: offset to read
509 *
510 * This function must be used by drivers as their &file_operations.read
511 * method if they use DRM events for asynchronous signalling to userspace.
512 * Since events are used by the KMS API for vblank and page flip completion this
513 * means all modern display drivers must use it.
514 *
515 * @offset is ignored, DRM events are read like a pipe. Polling support is
516 * provided by drm_poll().
517 *
518 * This function will only ever read a full event. Therefore userspace must
519 * supply a big enough buffer to fit any event to ensure forward progress. Since
520 * the maximum event space is currently 4K it's recommended to just use that for
521 * safety.
522 *
523 * RETURNS:
524 * Number of bytes read (always aligned to full events, and can be 0) or a
525 * negative error code on failure.
526 */
drm_read(struct file * filp,char __user * buffer,size_t count,loff_t * offset)527 ssize_t drm_read(struct file *filp, char __user *buffer,
528 size_t count, loff_t *offset)
529 {
530 struct drm_file *file_priv = filp->private_data;
531 struct drm_device *dev = file_priv->minor->dev;
532 ssize_t ret;
533
534 ret = mutex_lock_interruptible(&file_priv->event_read_lock);
535 if (ret)
536 return ret;
537
538 for (;;) {
539 struct drm_pending_event *e = NULL;
540
541 spin_lock_irq(&dev->event_lock);
542 if (!list_empty(&file_priv->event_list)) {
543 e = list_first_entry(&file_priv->event_list,
544 struct drm_pending_event, link);
545 file_priv->event_space += e->event->length;
546 list_del(&e->link);
547 }
548 spin_unlock_irq(&dev->event_lock);
549
550 if (e == NULL) {
551 if (ret)
552 break;
553
554 if (filp->f_flags & O_NONBLOCK) {
555 ret = -EAGAIN;
556 break;
557 }
558
559 mutex_unlock(&file_priv->event_read_lock);
560 ret = wait_event_interruptible(file_priv->event_wait,
561 !list_empty(&file_priv->event_list));
562 if (ret >= 0)
563 ret = mutex_lock_interruptible(&file_priv->event_read_lock);
564 if (ret)
565 return ret;
566 } else {
567 unsigned length = e->event->length;
568
569 if (length > count - ret) {
570 put_back_event:
571 spin_lock_irq(&dev->event_lock);
572 file_priv->event_space -= length;
573 list_add(&e->link, &file_priv->event_list);
574 spin_unlock_irq(&dev->event_lock);
575 wake_up_interruptible_poll(&file_priv->event_wait,
576 EPOLLIN | EPOLLRDNORM);
577 break;
578 }
579
580 if (copy_to_user(buffer + ret, e->event, length)) {
581 if (ret == 0)
582 ret = -EFAULT;
583 goto put_back_event;
584 }
585
586 ret += length;
587 kfree(e);
588 }
589 }
590 mutex_unlock(&file_priv->event_read_lock);
591
592 return ret;
593 }
594 EXPORT_SYMBOL(drm_read);
595
596 /**
597 * drm_poll - poll method for DRM file
598 * @filp: file pointer
599 * @wait: poll waiter table
600 *
601 * This function must be used by drivers as their &file_operations.read method
602 * if they use DRM events for asynchronous signalling to userspace. Since
603 * events are used by the KMS API for vblank and page flip completion this means
604 * all modern display drivers must use it.
605 *
606 * See also drm_read().
607 *
608 * RETURNS:
609 * Mask of POLL flags indicating the current status of the file.
610 */
drm_poll(struct file * filp,struct poll_table_struct * wait)611 __poll_t drm_poll(struct file *filp, struct poll_table_struct *wait)
612 {
613 struct drm_file *file_priv = filp->private_data;
614 __poll_t mask = 0;
615
616 poll_wait(filp, &file_priv->event_wait, wait);
617
618 if (!list_empty(&file_priv->event_list))
619 mask |= EPOLLIN | EPOLLRDNORM;
620
621 return mask;
622 }
623 EXPORT_SYMBOL(drm_poll);
624
625 /**
626 * drm_event_reserve_init_locked - init a DRM event and reserve space for it
627 * @dev: DRM device
628 * @file_priv: DRM file private data
629 * @p: tracking structure for the pending event
630 * @e: actual event data to deliver to userspace
631 *
632 * This function prepares the passed in event for eventual delivery. If the event
633 * doesn't get delivered (because the IOCTL fails later on, before queuing up
634 * anything) then the even must be cancelled and freed using
635 * drm_event_cancel_free(). Successfully initialized events should be sent out
636 * using drm_send_event() or drm_send_event_locked() to signal completion of the
637 * asynchronous event to userspace.
638 *
639 * If callers embedded @p into a larger structure it must be allocated with
640 * kmalloc and @p must be the first member element.
641 *
642 * This is the locked version of drm_event_reserve_init() for callers which
643 * already hold &drm_device.event_lock.
644 *
645 * RETURNS:
646 * 0 on success or a negative error code on failure.
647 */
drm_event_reserve_init_locked(struct drm_device * dev,struct drm_file * file_priv,struct drm_pending_event * p,struct drm_event * e)648 int drm_event_reserve_init_locked(struct drm_device *dev,
649 struct drm_file *file_priv,
650 struct drm_pending_event *p,
651 struct drm_event *e)
652 {
653 if (file_priv->event_space < e->length)
654 return -ENOMEM;
655
656 file_priv->event_space -= e->length;
657
658 p->event = e;
659 list_add(&p->pending_link, &file_priv->pending_event_list);
660 p->file_priv = file_priv;
661
662 return 0;
663 }
664 EXPORT_SYMBOL(drm_event_reserve_init_locked);
665
666 /**
667 * drm_event_reserve_init - init a DRM event and reserve space for it
668 * @dev: DRM device
669 * @file_priv: DRM file private data
670 * @p: tracking structure for the pending event
671 * @e: actual event data to deliver to userspace
672 *
673 * This function prepares the passed in event for eventual delivery. If the event
674 * doesn't get delivered (because the IOCTL fails later on, before queuing up
675 * anything) then the even must be cancelled and freed using
676 * drm_event_cancel_free(). Successfully initialized events should be sent out
677 * using drm_send_event() or drm_send_event_locked() to signal completion of the
678 * asynchronous event to userspace.
679 *
680 * If callers embedded @p into a larger structure it must be allocated with
681 * kmalloc and @p must be the first member element.
682 *
683 * Callers which already hold &drm_device.event_lock should use
684 * drm_event_reserve_init_locked() instead.
685 *
686 * RETURNS:
687 * 0 on success or a negative error code on failure.
688 */
drm_event_reserve_init(struct drm_device * dev,struct drm_file * file_priv,struct drm_pending_event * p,struct drm_event * e)689 int drm_event_reserve_init(struct drm_device *dev,
690 struct drm_file *file_priv,
691 struct drm_pending_event *p,
692 struct drm_event *e)
693 {
694 unsigned long flags;
695 int ret;
696
697 spin_lock_irqsave(&dev->event_lock, flags);
698 ret = drm_event_reserve_init_locked(dev, file_priv, p, e);
699 spin_unlock_irqrestore(&dev->event_lock, flags);
700
701 return ret;
702 }
703 EXPORT_SYMBOL(drm_event_reserve_init);
704
705 /**
706 * drm_event_cancel_free - free a DRM event and release its space
707 * @dev: DRM device
708 * @p: tracking structure for the pending event
709 *
710 * This function frees the event @p initialized with drm_event_reserve_init()
711 * and releases any allocated space. It is used to cancel an event when the
712 * nonblocking operation could not be submitted and needed to be aborted.
713 */
drm_event_cancel_free(struct drm_device * dev,struct drm_pending_event * p)714 void drm_event_cancel_free(struct drm_device *dev,
715 struct drm_pending_event *p)
716 {
717 unsigned long flags;
718
719 spin_lock_irqsave(&dev->event_lock, flags);
720 if (p->file_priv) {
721 p->file_priv->event_space += p->event->length;
722 list_del(&p->pending_link);
723 }
724 spin_unlock_irqrestore(&dev->event_lock, flags);
725
726 if (p->fence)
727 dma_fence_put(p->fence);
728
729 kfree(p);
730 }
731 EXPORT_SYMBOL(drm_event_cancel_free);
732
drm_send_event_helper(struct drm_device * dev,struct drm_pending_event * e,ktime_t timestamp)733 static void drm_send_event_helper(struct drm_device *dev,
734 struct drm_pending_event *e, ktime_t timestamp)
735 {
736 assert_spin_locked(&dev->event_lock);
737
738 if (e->completion) {
739 complete_all(e->completion);
740 e->completion_release(e->completion);
741 e->completion = NULL;
742 }
743
744 if (e->fence) {
745 if (timestamp)
746 dma_fence_signal_timestamp(e->fence, timestamp);
747 else
748 dma_fence_signal(e->fence);
749 dma_fence_put(e->fence);
750 }
751
752 if (!e->file_priv) {
753 kfree(e);
754 return;
755 }
756
757 list_del(&e->pending_link);
758 list_add_tail(&e->link,
759 &e->file_priv->event_list);
760 wake_up_interruptible_poll(&e->file_priv->event_wait,
761 EPOLLIN | EPOLLRDNORM);
762 }
763
764 /**
765 * drm_send_event_timestamp_locked - send DRM event to file descriptor
766 * @dev: DRM device
767 * @e: DRM event to deliver
768 * @timestamp: timestamp to set for the fence event in kernel's CLOCK_MONOTONIC
769 * time domain
770 *
771 * This function sends the event @e, initialized with drm_event_reserve_init(),
772 * to its associated userspace DRM file. Callers must already hold
773 * &drm_device.event_lock.
774 *
775 * Note that the core will take care of unlinking and disarming events when the
776 * corresponding DRM file is closed. Drivers need not worry about whether the
777 * DRM file for this event still exists and can call this function upon
778 * completion of the asynchronous work unconditionally.
779 */
drm_send_event_timestamp_locked(struct drm_device * dev,struct drm_pending_event * e,ktime_t timestamp)780 void drm_send_event_timestamp_locked(struct drm_device *dev,
781 struct drm_pending_event *e, ktime_t timestamp)
782 {
783 drm_send_event_helper(dev, e, timestamp);
784 }
785 EXPORT_SYMBOL(drm_send_event_timestamp_locked);
786
787 /**
788 * drm_send_event_locked - send DRM event to file descriptor
789 * @dev: DRM device
790 * @e: DRM event to deliver
791 *
792 * This function sends the event @e, initialized with drm_event_reserve_init(),
793 * to its associated userspace DRM file. Callers must already hold
794 * &drm_device.event_lock, see drm_send_event() for the unlocked version.
795 *
796 * Note that the core will take care of unlinking and disarming events when the
797 * corresponding DRM file is closed. Drivers need not worry about whether the
798 * DRM file for this event still exists and can call this function upon
799 * completion of the asynchronous work unconditionally.
800 */
drm_send_event_locked(struct drm_device * dev,struct drm_pending_event * e)801 void drm_send_event_locked(struct drm_device *dev, struct drm_pending_event *e)
802 {
803 drm_send_event_helper(dev, e, 0);
804 }
805 EXPORT_SYMBOL(drm_send_event_locked);
806
807 /**
808 * drm_send_event - send DRM event to file descriptor
809 * @dev: DRM device
810 * @e: DRM event to deliver
811 *
812 * This function sends the event @e, initialized with drm_event_reserve_init(),
813 * to its associated userspace DRM file. This function acquires
814 * &drm_device.event_lock, see drm_send_event_locked() for callers which already
815 * hold this lock.
816 *
817 * Note that the core will take care of unlinking and disarming events when the
818 * corresponding DRM file is closed. Drivers need not worry about whether the
819 * DRM file for this event still exists and can call this function upon
820 * completion of the asynchronous work unconditionally.
821 */
drm_send_event(struct drm_device * dev,struct drm_pending_event * e)822 void drm_send_event(struct drm_device *dev, struct drm_pending_event *e)
823 {
824 unsigned long irqflags;
825
826 spin_lock_irqsave(&dev->event_lock, irqflags);
827 drm_send_event_helper(dev, e, 0);
828 spin_unlock_irqrestore(&dev->event_lock, irqflags);
829 }
830 EXPORT_SYMBOL(drm_send_event);
831
print_size(struct drm_printer * p,const char * stat,const char * region,u64 sz)832 static void print_size(struct drm_printer *p, const char *stat,
833 const char *region, u64 sz)
834 {
835 const char *units[] = {"", " KiB", " MiB"};
836 unsigned u;
837
838 for (u = 0; u < ARRAY_SIZE(units) - 1; u++) {
839 if (sz == 0 || !IS_ALIGNED(sz, SZ_1K))
840 break;
841 sz = div_u64(sz, SZ_1K);
842 }
843
844 drm_printf(p, "drm-%s-%s:\t%llu%s\n", stat, region, sz, units[u]);
845 }
846
847 /**
848 * drm_print_memory_stats - A helper to print memory stats
849 * @p: The printer to print output to
850 * @stats: The collected memory stats
851 * @supported_status: Bitmask of optional stats which are available
852 * @region: The memory region
853 *
854 */
drm_print_memory_stats(struct drm_printer * p,const struct drm_memory_stats * stats,enum drm_gem_object_status supported_status,const char * region)855 void drm_print_memory_stats(struct drm_printer *p,
856 const struct drm_memory_stats *stats,
857 enum drm_gem_object_status supported_status,
858 const char *region)
859 {
860 print_size(p, "total", region, stats->private + stats->shared);
861 print_size(p, "shared", region, stats->shared);
862 print_size(p, "active", region, stats->active);
863
864 if (supported_status & DRM_GEM_OBJECT_RESIDENT)
865 print_size(p, "resident", region, stats->resident);
866
867 if (supported_status & DRM_GEM_OBJECT_PURGEABLE)
868 print_size(p, "purgeable", region, stats->purgeable);
869 }
870 EXPORT_SYMBOL(drm_print_memory_stats);
871
872 /**
873 * drm_show_memory_stats - Helper to collect and show standard fdinfo memory stats
874 * @p: the printer to print output to
875 * @file: the DRM file
876 *
877 * Helper to iterate over GEM objects with a handle allocated in the specified
878 * file.
879 */
drm_show_memory_stats(struct drm_printer * p,struct drm_file * file)880 void drm_show_memory_stats(struct drm_printer *p, struct drm_file *file)
881 {
882 struct drm_gem_object *obj;
883 struct drm_memory_stats status = {};
884 enum drm_gem_object_status supported_status = 0;
885 int id;
886
887 spin_lock(&file->table_lock);
888 idr_for_each_entry (&file->object_idr, obj, id) {
889 enum drm_gem_object_status s = 0;
890 size_t add_size = (obj->funcs && obj->funcs->rss) ?
891 obj->funcs->rss(obj) : obj->size;
892
893 if (obj->funcs && obj->funcs->status) {
894 s = obj->funcs->status(obj);
895 supported_status = DRM_GEM_OBJECT_RESIDENT |
896 DRM_GEM_OBJECT_PURGEABLE;
897 }
898
899 if (drm_gem_object_is_shared_for_memory_stats(obj)) {
900 status.shared += obj->size;
901 } else {
902 status.private += obj->size;
903 }
904
905 if (s & DRM_GEM_OBJECT_RESIDENT) {
906 status.resident += add_size;
907 } else {
908 /* If already purged or not yet backed by pages, don't
909 * count it as purgeable:
910 */
911 s &= ~DRM_GEM_OBJECT_PURGEABLE;
912 }
913
914 if (!dma_resv_test_signaled(obj->resv, dma_resv_usage_rw(true))) {
915 status.active += add_size;
916
917 /* If still active, don't count as purgeable: */
918 s &= ~DRM_GEM_OBJECT_PURGEABLE;
919 }
920
921 if (s & DRM_GEM_OBJECT_PURGEABLE)
922 status.purgeable += add_size;
923 }
924 spin_unlock(&file->table_lock);
925
926 drm_print_memory_stats(p, &status, supported_status, "memory");
927 }
928 EXPORT_SYMBOL(drm_show_memory_stats);
929
930 /**
931 * drm_show_fdinfo - helper for drm file fops
932 * @m: output stream
933 * @f: the device file instance
934 *
935 * Helper to implement fdinfo, for userspace to query usage stats, etc, of a
936 * process using the GPU. See also &drm_driver.show_fdinfo.
937 *
938 * For text output format description please see Documentation/gpu/drm-usage-stats.rst
939 */
drm_show_fdinfo(struct seq_file * m,struct file * f)940 void drm_show_fdinfo(struct seq_file *m, struct file *f)
941 {
942 struct drm_file *file = f->private_data;
943 struct drm_device *dev = file->minor->dev;
944 struct drm_printer p = drm_seq_file_printer(m);
945 int idx;
946
947 if (!drm_dev_enter(dev, &idx))
948 return;
949
950 drm_printf(&p, "drm-driver:\t%s\n", dev->driver->name);
951 drm_printf(&p, "drm-client-id:\t%llu\n", file->client_id);
952
953 if (dev_is_pci(dev->dev)) {
954 struct pci_dev *pdev = to_pci_dev(dev->dev);
955
956 drm_printf(&p, "drm-pdev:\t%04x:%02x:%02x.%d\n",
957 pci_domain_nr(pdev->bus), pdev->bus->number,
958 PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn));
959 }
960
961 if (dev->driver->show_fdinfo)
962 dev->driver->show_fdinfo(&p, file);
963
964 drm_dev_exit(idx);
965 }
966 EXPORT_SYMBOL(drm_show_fdinfo);
967
968 /**
969 * mock_drm_getfile - Create a new struct file for the drm device
970 * @minor: drm minor to wrap (e.g. #drm_device.primary)
971 * @flags: file creation mode (O_RDWR etc)
972 *
973 * This create a new struct file that wraps a DRM file context around a
974 * DRM minor. This mimicks userspace opening e.g. /dev/dri/card0, but without
975 * invoking userspace. The struct file may be operated on using its f_op
976 * (the drm_device.driver.fops) to mimick userspace operations, or be supplied
977 * to userspace facing functions as an internal/anonymous client.
978 *
979 * RETURNS:
980 * Pointer to newly created struct file, ERR_PTR on failure.
981 */
mock_drm_getfile(struct drm_minor * minor,unsigned int flags)982 struct file *mock_drm_getfile(struct drm_minor *minor, unsigned int flags)
983 {
984 struct drm_device *dev = minor->dev;
985 struct drm_file *priv;
986 struct file *file;
987
988 priv = drm_file_alloc(minor);
989 if (IS_ERR(priv))
990 return ERR_CAST(priv);
991
992 file = anon_inode_getfile("drm", dev->driver->fops, priv, flags);
993 if (IS_ERR(file)) {
994 drm_file_free(priv);
995 return file;
996 }
997
998 /* Everyone shares a single global address space */
999 file->f_mapping = dev->anon_inode->i_mapping;
1000
1001 drm_dev_get(dev);
1002 priv->filp = file;
1003
1004 return file;
1005 }
1006 EXPORT_SYMBOL_FOR_TESTS_ONLY(mock_drm_getfile);
1007