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