xref: /openbsd-src/sys/dev/pci/drm/drm_file.c (revision c1a45aed656e7d5627c30c92421893a76f370ccb)
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 
42 #include <drm/drm_client.h>
43 #include <drm/drm_drv.h>
44 #include <drm/drm_file.h>
45 #include <drm/drm_print.h>
46 
47 #include "drm_crtc_internal.h"
48 #include "drm_internal.h"
49 #include "drm_legacy.h"
50 
51 #if defined(CONFIG_MMU) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
52 #include <uapi/asm/mman.h>
53 #include <drm/drm_vma_manager.h>
54 #endif
55 
56 /* from BKL pushdown */
57 DEFINE_MUTEX(drm_global_mutex);
58 
59 bool drm_dev_needs_global_mutex(struct drm_device *dev)
60 {
61 	/*
62 	 * Legacy drivers rely on all kinds of BKL locking semantics, don't
63 	 * bother. They also still need BKL locking for their ioctls, so better
64 	 * safe than sorry.
65 	 */
66 	if (drm_core_check_feature(dev, DRIVER_LEGACY))
67 		return true;
68 
69 	/*
70 	 * The deprecated ->load callback must be called after the driver is
71 	 * already registered. This means such drivers rely on the BKL to make
72 	 * sure an open can't proceed until the driver is actually fully set up.
73 	 * Similar hilarity holds for the unload callback.
74 	 */
75 	if (dev->driver->load || dev->driver->unload)
76 		return true;
77 
78 	/*
79 	 * Drivers with the lastclose callback assume that it's synchronized
80 	 * against concurrent opens, which again needs the BKL. The proper fix
81 	 * is to use the drm_client infrastructure with proper locking for each
82 	 * client.
83 	 */
84 	if (dev->driver->lastclose)
85 		return true;
86 
87 	return false;
88 }
89 
90 /**
91  * DOC: file operations
92  *
93  * Drivers must define the file operations structure that forms the DRM
94  * userspace API entry point, even though most of those operations are
95  * implemented in the DRM core. The resulting &struct file_operations must be
96  * stored in the &drm_driver.fops field. The mandatory functions are drm_open(),
97  * drm_read(), drm_ioctl() and drm_compat_ioctl() if CONFIG_COMPAT is enabled
98  * Note that drm_compat_ioctl will be NULL if CONFIG_COMPAT=n, so there's no
99  * need to sprinkle #ifdef into the code. Drivers which implement private ioctls
100  * that require 32/64 bit compatibility support must provide their own
101  * &file_operations.compat_ioctl handler that processes private ioctls and calls
102  * drm_compat_ioctl() for core ioctls.
103  *
104  * In addition drm_read() and drm_poll() provide support for DRM events. DRM
105  * events are a generic and extensible means to send asynchronous events to
106  * userspace through the file descriptor. They are used to send vblank event and
107  * page flip completions by the KMS API. But drivers can also use it for their
108  * own needs, e.g. to signal completion of rendering.
109  *
110  * For the driver-side event interface see drm_event_reserve_init() and
111  * drm_send_event() as the main starting points.
112  *
113  * The memory mapping implementation will vary depending on how the driver
114  * manages memory. Legacy drivers will use the deprecated drm_legacy_mmap()
115  * function, modern drivers should use one of the provided memory-manager
116  * specific implementations. For GEM-based drivers this is drm_gem_mmap().
117  *
118  * No other file operations are supported by the DRM userspace API. Overall the
119  * following is an example &file_operations structure::
120  *
121  *     static const example_drm_fops = {
122  *             .owner = THIS_MODULE,
123  *             .open = drm_open,
124  *             .release = drm_release,
125  *             .unlocked_ioctl = drm_ioctl,
126  *             .compat_ioctl = drm_compat_ioctl, // NULL if CONFIG_COMPAT=n
127  *             .poll = drm_poll,
128  *             .read = drm_read,
129  *             .llseek = no_llseek,
130  *             .mmap = drm_gem_mmap,
131  *     };
132  *
133  * For plain GEM based drivers there is the DEFINE_DRM_GEM_FOPS() macro, and for
134  * CMA based drivers there is the DEFINE_DRM_GEM_CMA_FOPS() macro to make this
135  * simpler.
136  *
137  * The driver's &file_operations must be stored in &drm_driver.fops.
138  *
139  * For driver-private IOCTL handling see the more detailed discussion in
140  * :ref:`IOCTL support in the userland interfaces chapter<drm_driver_ioctl>`.
141  */
142 
143 /**
144  * drm_file_alloc - allocate file context
145  * @minor: minor to allocate on
146  *
147  * This allocates a new DRM file context. It is not linked into any context and
148  * can be used by the caller freely. Note that the context keeps a pointer to
149  * @minor, so it must be freed before @minor is.
150  *
151  * RETURNS:
152  * Pointer to newly allocated context, ERR_PTR on failure.
153  */
154 struct drm_file *drm_file_alloc(struct drm_minor *minor)
155 {
156 	struct drm_device *dev = minor->dev;
157 	struct drm_file *file;
158 	int ret;
159 
160 	file = kzalloc(sizeof(*file), GFP_KERNEL);
161 	if (!file)
162 		return ERR_PTR(-ENOMEM);
163 
164 #ifdef __linux__
165 	file->pid = get_pid(task_pid(current));
166 #endif
167 	file->minor = minor;
168 
169 	/* for compatibility root is always authenticated */
170 	file->authenticated = capable(CAP_SYS_ADMIN);
171 
172 	INIT_LIST_HEAD(&file->lhead);
173 	INIT_LIST_HEAD(&file->fbs);
174 	rw_init(&file->fbs_lock, "fbslk");
175 	INIT_LIST_HEAD(&file->blobs);
176 	INIT_LIST_HEAD(&file->pending_event_list);
177 	INIT_LIST_HEAD(&file->event_list);
178 	init_waitqueue_head(&file->event_wait);
179 	file->event_space = 4096; /* set aside 4k for event buffer */
180 
181 	mtx_init(&file->master_lookup_lock, IPL_NONE);
182 	rw_init(&file->event_read_lock, "evread");
183 
184 	if (drm_core_check_feature(dev, DRIVER_GEM))
185 		drm_gem_open(dev, file);
186 
187 	if (drm_core_check_feature(dev, DRIVER_SYNCOBJ))
188 		drm_syncobj_open(file);
189 
190 	drm_prime_init_file_private(&file->prime);
191 
192 	if (dev->driver->open) {
193 		ret = dev->driver->open(dev, file);
194 		if (ret < 0)
195 			goto out_prime_destroy;
196 	}
197 
198 	return file;
199 
200 out_prime_destroy:
201 	drm_prime_destroy_file_private(&file->prime);
202 	if (drm_core_check_feature(dev, DRIVER_SYNCOBJ))
203 		drm_syncobj_release(file);
204 	if (drm_core_check_feature(dev, DRIVER_GEM))
205 		drm_gem_release(dev, file);
206 	put_pid(file->pid);
207 	kfree(file);
208 
209 	return ERR_PTR(ret);
210 }
211 
212 static void drm_events_release(struct drm_file *file_priv)
213 {
214 	struct drm_device *dev = file_priv->minor->dev;
215 	struct drm_pending_event *e, *et;
216 	unsigned long flags;
217 
218 	spin_lock_irqsave(&dev->event_lock, flags);
219 
220 	/* Unlink pending events */
221 	list_for_each_entry_safe(e, et, &file_priv->pending_event_list,
222 				 pending_link) {
223 		list_del(&e->pending_link);
224 		e->file_priv = NULL;
225 	}
226 
227 	/* Remove unconsumed events */
228 	list_for_each_entry_safe(e, et, &file_priv->event_list, link) {
229 		list_del(&e->link);
230 		kfree(e);
231 	}
232 
233 	spin_unlock_irqrestore(&dev->event_lock, flags);
234 }
235 
236 /**
237  * drm_file_free - free file context
238  * @file: context to free, or NULL
239  *
240  * This destroys and deallocates a DRM file context previously allocated via
241  * drm_file_alloc(). The caller must make sure to unlink it from any contexts
242  * before calling this.
243  *
244  * If NULL is passed, this is a no-op.
245  */
246 void drm_file_free(struct drm_file *file)
247 {
248 	struct drm_device *dev;
249 
250 	if (!file)
251 		return;
252 
253 	dev = file->minor->dev;
254 
255 #ifdef __linux__
256 	DRM_DEBUG("comm=\"%s\", pid=%d, dev=0x%lx, open_count=%d\n",
257 		  current->comm, task_pid_nr(current),
258 		  (long)old_encode_dev(file->minor->kdev->devt),
259 		  atomic_read(&dev->open_count));
260 #else
261 	DRM_DEBUG("pid = %d, device = 0x%lx, open_count = %d\n",
262 	    curproc->p_p->ps_pid, (long)&dev->dev,
263 	    atomic_read(&dev->open_count));
264 #endif
265 
266 #ifdef CONFIG_DRM_LEGACY
267 	if (drm_core_check_feature(dev, DRIVER_LEGACY) &&
268 	    dev->driver->preclose)
269 		dev->driver->preclose(dev, file);
270 #endif
271 
272 	if (drm_core_check_feature(dev, DRIVER_LEGACY))
273 		drm_legacy_lock_release(dev, file->filp);
274 
275 	if (drm_core_check_feature(dev, DRIVER_HAVE_DMA))
276 		drm_legacy_reclaim_buffers(dev, file);
277 
278 	drm_events_release(file);
279 
280 	if (drm_core_check_feature(dev, DRIVER_MODESET)) {
281 		drm_fb_release(file);
282 		drm_property_destroy_user_blobs(dev, file);
283 	}
284 
285 	if (drm_core_check_feature(dev, DRIVER_SYNCOBJ))
286 		drm_syncobj_release(file);
287 
288 	if (drm_core_check_feature(dev, DRIVER_GEM))
289 		drm_gem_release(dev, file);
290 
291 	drm_legacy_ctxbitmap_flush(dev, file);
292 
293 	if (drm_is_primary_client(file))
294 		drm_master_release(file);
295 
296 	if (dev->driver->postclose)
297 		dev->driver->postclose(dev, file);
298 
299 	drm_prime_destroy_file_private(&file->prime);
300 
301 	WARN_ON(!list_empty(&file->event_list));
302 
303 	put_pid(file->pid);
304 	kfree(file);
305 }
306 
307 #ifdef __linux__
308 
309 static void drm_close_helper(struct file *filp)
310 {
311 	struct drm_file *file_priv = filp->private_data;
312 	struct drm_device *dev = file_priv->minor->dev;
313 
314 	mutex_lock(&dev->filelist_mutex);
315 	list_del(&file_priv->lhead);
316 	mutex_unlock(&dev->filelist_mutex);
317 
318 	drm_file_free(file_priv);
319 }
320 
321 /*
322  * Check whether DRI will run on this CPU.
323  *
324  * \return non-zero if the DRI will run on this CPU, or zero otherwise.
325  */
326 static int drm_cpu_valid(void)
327 {
328 #if defined(__sparc__) && !defined(__sparc_v9__)
329 	return 0;		/* No cmpxchg before v9 sparc. */
330 #endif
331 	return 1;
332 }
333 
334 #endif /* __linux__ */
335 
336 /*
337  * Called whenever a process opens a drm node
338  *
339  * \param filp file pointer.
340  * \param minor acquired minor-object.
341  * \return zero on success or a negative number on failure.
342  *
343  * Creates and initializes a drm_file structure for the file private data in \p
344  * filp and add it into the double linked list in \p dev.
345  */
346 #ifdef __linux__
347 static int drm_open_helper(struct file *filp, struct drm_minor *minor)
348 {
349 	struct drm_device *dev = minor->dev;
350 	struct drm_file *priv;
351 	int ret;
352 
353 	if (filp->f_flags & O_EXCL)
354 		return -EBUSY;	/* No exclusive opens */
355 	if (!drm_cpu_valid())
356 		return -EINVAL;
357 	if (dev->switch_power_state != DRM_SWITCH_POWER_ON &&
358 	    dev->switch_power_state != DRM_SWITCH_POWER_DYNAMIC_OFF)
359 		return -EINVAL;
360 
361 	DRM_DEBUG("comm=\"%s\", pid=%d, minor=%d\n", current->comm,
362 		  task_pid_nr(current), minor->index);
363 
364 	priv = drm_file_alloc(minor);
365 	if (IS_ERR(priv))
366 		return PTR_ERR(priv);
367 
368 	if (drm_is_primary_client(priv)) {
369 		ret = drm_master_open(priv);
370 		if (ret) {
371 			drm_file_free(priv);
372 			return ret;
373 		}
374 	}
375 
376 	filp->private_data = priv;
377 	filp->f_mode |= FMODE_UNSIGNED_OFFSET;
378 	priv->filp = filp;
379 
380 	mutex_lock(&dev->filelist_mutex);
381 	list_add(&priv->lhead, &dev->filelist);
382 	mutex_unlock(&dev->filelist_mutex);
383 
384 #ifdef CONFIG_DRM_LEGACY
385 #ifdef __alpha__
386 	/*
387 	 * Default the hose
388 	 */
389 	if (!dev->hose) {
390 		struct pci_dev *pci_dev;
391 
392 		pci_dev = pci_get_class(PCI_CLASS_DISPLAY_VGA << 8, NULL);
393 		if (pci_dev) {
394 			dev->hose = pci_dev->sysdata;
395 			pci_dev_put(pci_dev);
396 		}
397 		if (!dev->hose) {
398 			struct pci_bus *b = list_entry(pci_root_buses.next,
399 				struct pci_bus, node);
400 			if (b)
401 				dev->hose = b->sysdata;
402 		}
403 	}
404 #endif
405 #endif
406 
407 	return 0;
408 }
409 #endif /* __linux__ */
410 
411 /**
412  * drm_open - open method for DRM file
413  * @inode: device inode
414  * @filp: file pointer.
415  *
416  * This function must be used by drivers as their &file_operations.open method.
417  * It looks up the correct DRM device and instantiates all the per-file
418  * resources for it. It also calls the &drm_driver.open driver callback.
419  *
420  * RETURNS:
421  *
422  * 0 on success or negative errno value on failure.
423  */
424 #ifdef __linux__
425 int drm_open(struct inode *inode, struct file *filp)
426 {
427 	struct drm_device *dev;
428 	struct drm_minor *minor;
429 	int retcode;
430 	int need_setup = 0;
431 
432 	minor = drm_minor_acquire(iminor(inode));
433 	if (IS_ERR(minor))
434 		return PTR_ERR(minor);
435 
436 	dev = minor->dev;
437 	if (drm_dev_needs_global_mutex(dev))
438 		mutex_lock(&drm_global_mutex);
439 
440 	if (!atomic_fetch_inc(&dev->open_count))
441 		need_setup = 1;
442 
443 	/* share address_space across all char-devs of a single device */
444 	filp->f_mapping = dev->anon_inode->i_mapping;
445 
446 	retcode = drm_open_helper(filp, minor);
447 	if (retcode)
448 		goto err_undo;
449 	if (need_setup) {
450 		retcode = drm_legacy_setup(dev);
451 		if (retcode) {
452 			drm_close_helper(filp);
453 			goto err_undo;
454 		}
455 	}
456 
457 	if (drm_dev_needs_global_mutex(dev))
458 		mutex_unlock(&drm_global_mutex);
459 
460 	return 0;
461 
462 err_undo:
463 	atomic_dec(&dev->open_count);
464 	if (drm_dev_needs_global_mutex(dev))
465 		mutex_unlock(&drm_global_mutex);
466 	drm_minor_release(minor);
467 	return retcode;
468 }
469 EXPORT_SYMBOL(drm_open);
470 #endif
471 
472 void drm_lastclose(struct drm_device * dev)
473 {
474 	DRM_DEBUG("\n");
475 
476 	if (dev->driver->lastclose)
477 		dev->driver->lastclose(dev);
478 	DRM_DEBUG("driver lastclose completed\n");
479 
480 	if (drm_core_check_feature(dev, DRIVER_LEGACY))
481 		drm_legacy_dev_reinit(dev);
482 
483 	drm_client_dev_restore(dev);
484 }
485 
486 /**
487  * drm_release - release method for DRM file
488  * @inode: device inode
489  * @filp: file pointer.
490  *
491  * This function must be used by drivers as their &file_operations.release
492  * method. It frees any resources associated with the open file, and calls the
493  * &drm_driver.postclose driver callback. If this is the last open file for the
494  * DRM device also proceeds to call the &drm_driver.lastclose driver callback.
495  *
496  * RETURNS:
497  *
498  * Always succeeds and returns 0.
499  */
500 int drm_release(struct inode *inode, struct file *filp)
501 {
502 	STUB();
503 	return -ENOSYS;
504 #ifdef notyet
505 	struct drm_file *file_priv = filp->private_data;
506 	struct drm_minor *minor = file_priv->minor;
507 	struct drm_device *dev = minor->dev;
508 
509 	if (drm_dev_needs_global_mutex(dev))
510 		mutex_lock(&drm_global_mutex);
511 
512 	DRM_DEBUG("open_count = %d\n", atomic_read(&dev->open_count));
513 
514 	drm_close_helper(filp);
515 
516 	if (atomic_dec_and_test(&dev->open_count))
517 		drm_lastclose(dev);
518 
519 	if (drm_dev_needs_global_mutex(dev))
520 		mutex_unlock(&drm_global_mutex);
521 
522 	drm_minor_release(minor);
523 
524 	return 0;
525 #endif
526 }
527 EXPORT_SYMBOL(drm_release);
528 
529 /**
530  * drm_release_noglobal - release method for DRM file
531  * @inode: device inode
532  * @filp: file pointer.
533  *
534  * This function may be used by drivers as their &file_operations.release
535  * method. It frees any resources associated with the open file prior to taking
536  * the drm_global_mutex, which then calls the &drm_driver.postclose driver
537  * callback. If this is the last open file for the DRM device also proceeds to
538  * call the &drm_driver.lastclose driver callback.
539  *
540  * RETURNS:
541  *
542  * Always succeeds and returns 0.
543  */
544 int drm_release_noglobal(struct inode *inode, struct file *filp)
545 {
546 	STUB();
547 	return -ENOSYS;
548 #ifdef notyet
549 	struct drm_file *file_priv = filp->private_data;
550 	struct drm_minor *minor = file_priv->minor;
551 	struct drm_device *dev = minor->dev;
552 
553 	drm_close_helper(filp);
554 
555 	if (atomic_dec_and_mutex_lock(&dev->open_count, &drm_global_mutex)) {
556 		drm_lastclose(dev);
557 		mutex_unlock(&drm_global_mutex);
558 	}
559 
560 	drm_minor_release(minor);
561 
562 	return 0;
563 #endif
564 }
565 EXPORT_SYMBOL(drm_release_noglobal);
566 
567 /**
568  * drm_read - read method for DRM file
569  * @filp: file pointer
570  * @buffer: userspace destination pointer for the read
571  * @count: count in bytes to read
572  * @offset: offset to read
573  *
574  * This function must be used by drivers as their &file_operations.read
575  * method if they use DRM events for asynchronous signalling to userspace.
576  * Since events are used by the KMS API for vblank and page flip completion this
577  * means all modern display drivers must use it.
578  *
579  * @offset is ignored, DRM events are read like a pipe. Therefore drivers also
580  * must set the &file_operation.llseek to no_llseek(). Polling support is
581  * provided by drm_poll().
582  *
583  * This function will only ever read a full event. Therefore userspace must
584  * supply a big enough buffer to fit any event to ensure forward progress. Since
585  * the maximum event space is currently 4K it's recommended to just use that for
586  * safety.
587  *
588  * RETURNS:
589  *
590  * Number of bytes read (always aligned to full events, and can be 0) or a
591  * negative error code on failure.
592  */
593 ssize_t drm_read(struct file *filp, char __user *buffer,
594 		 size_t count, loff_t *offset)
595 {
596 	STUB();
597 	return -ENOSYS;
598 #ifdef notyet
599 	struct drm_file *file_priv = filp->private_data;
600 	struct drm_device *dev = file_priv->minor->dev;
601 	ssize_t ret;
602 
603 	ret = mutex_lock_interruptible(&file_priv->event_read_lock);
604 	if (ret)
605 		return ret;
606 
607 	for (;;) {
608 		struct drm_pending_event *e = NULL;
609 
610 		spin_lock_irq(&dev->event_lock);
611 		if (!list_empty(&file_priv->event_list)) {
612 			e = list_first_entry(&file_priv->event_list,
613 					struct drm_pending_event, link);
614 			file_priv->event_space += e->event->length;
615 			list_del(&e->link);
616 		}
617 		spin_unlock_irq(&dev->event_lock);
618 
619 		if (e == NULL) {
620 			if (ret)
621 				break;
622 
623 			if (filp->f_flags & O_NONBLOCK) {
624 				ret = -EAGAIN;
625 				break;
626 			}
627 
628 			mutex_unlock(&file_priv->event_read_lock);
629 			ret = wait_event_interruptible(file_priv->event_wait,
630 						       !list_empty(&file_priv->event_list));
631 			if (ret >= 0)
632 				ret = mutex_lock_interruptible(&file_priv->event_read_lock);
633 			if (ret)
634 				return ret;
635 		} else {
636 			unsigned length = e->event->length;
637 
638 			if (length > count - ret) {
639 put_back_event:
640 				spin_lock_irq(&dev->event_lock);
641 				file_priv->event_space -= length;
642 				list_add(&e->link, &file_priv->event_list);
643 				spin_unlock_irq(&dev->event_lock);
644 				wake_up_interruptible_poll(&file_priv->event_wait,
645 					EPOLLIN | EPOLLRDNORM);
646 				break;
647 			}
648 
649 			if (copy_to_user(buffer + ret, e->event, length)) {
650 				if (ret == 0)
651 					ret = -EFAULT;
652 				goto put_back_event;
653 			}
654 
655 			ret += length;
656 			kfree(e);
657 		}
658 	}
659 	mutex_unlock(&file_priv->event_read_lock);
660 
661 	return ret;
662 #endif
663 }
664 EXPORT_SYMBOL(drm_read);
665 
666 #ifdef notyet
667 /**
668  * drm_poll - poll method for DRM file
669  * @filp: file pointer
670  * @wait: poll waiter table
671  *
672  * This function must be used by drivers as their &file_operations.read method
673  * if they use DRM events for asynchronous signalling to userspace.  Since
674  * events are used by the KMS API for vblank and page flip completion this means
675  * all modern display drivers must use it.
676  *
677  * See also drm_read().
678  *
679  * RETURNS:
680  *
681  * Mask of POLL flags indicating the current status of the file.
682  */
683 __poll_t drm_poll(struct file *filp, struct poll_table_struct *wait)
684 {
685 	struct drm_file *file_priv = filp->private_data;
686 	__poll_t mask = 0;
687 
688 	poll_wait(filp, &file_priv->event_wait, wait);
689 
690 	if (!list_empty(&file_priv->event_list))
691 		mask |= EPOLLIN | EPOLLRDNORM;
692 
693 	return mask;
694 }
695 EXPORT_SYMBOL(drm_poll);
696 #endif
697 
698 /**
699  * drm_event_reserve_init_locked - init a DRM event and reserve space for it
700  * @dev: DRM device
701  * @file_priv: DRM file private data
702  * @p: tracking structure for the pending event
703  * @e: actual event data to deliver to userspace
704  *
705  * This function prepares the passed in event for eventual delivery. If the event
706  * doesn't get delivered (because the IOCTL fails later on, before queuing up
707  * anything) then the even must be cancelled and freed using
708  * drm_event_cancel_free(). Successfully initialized events should be sent out
709  * using drm_send_event() or drm_send_event_locked() to signal completion of the
710  * asynchronous event to userspace.
711  *
712  * If callers embedded @p into a larger structure it must be allocated with
713  * kmalloc and @p must be the first member element.
714  *
715  * This is the locked version of drm_event_reserve_init() for callers which
716  * already hold &drm_device.event_lock.
717  *
718  * RETURNS:
719  *
720  * 0 on success or a negative error code on failure.
721  */
722 int drm_event_reserve_init_locked(struct drm_device *dev,
723 				  struct drm_file *file_priv,
724 				  struct drm_pending_event *p,
725 				  struct drm_event *e)
726 {
727 	if (file_priv->event_space < e->length)
728 		return -ENOMEM;
729 
730 	file_priv->event_space -= e->length;
731 
732 	p->event = e;
733 	list_add(&p->pending_link, &file_priv->pending_event_list);
734 	p->file_priv = file_priv;
735 
736 	return 0;
737 }
738 EXPORT_SYMBOL(drm_event_reserve_init_locked);
739 
740 /**
741  * drm_event_reserve_init - init a DRM event and reserve space for it
742  * @dev: DRM device
743  * @file_priv: DRM file private data
744  * @p: tracking structure for the pending event
745  * @e: actual event data to deliver to userspace
746  *
747  * This function prepares the passed in event for eventual delivery. If the event
748  * doesn't get delivered (because the IOCTL fails later on, before queuing up
749  * anything) then the even must be cancelled and freed using
750  * drm_event_cancel_free(). Successfully initialized events should be sent out
751  * using drm_send_event() or drm_send_event_locked() to signal completion of the
752  * asynchronous event to userspace.
753  *
754  * If callers embedded @p into a larger structure it must be allocated with
755  * kmalloc and @p must be the first member element.
756  *
757  * Callers which already hold &drm_device.event_lock should use
758  * drm_event_reserve_init_locked() instead.
759  *
760  * RETURNS:
761  *
762  * 0 on success or a negative error code on failure.
763  */
764 int drm_event_reserve_init(struct drm_device *dev,
765 			   struct drm_file *file_priv,
766 			   struct drm_pending_event *p,
767 			   struct drm_event *e)
768 {
769 	unsigned long flags;
770 	int ret;
771 
772 	spin_lock_irqsave(&dev->event_lock, flags);
773 	ret = drm_event_reserve_init_locked(dev, file_priv, p, e);
774 	spin_unlock_irqrestore(&dev->event_lock, flags);
775 
776 	return ret;
777 }
778 EXPORT_SYMBOL(drm_event_reserve_init);
779 
780 /**
781  * drm_event_cancel_free - free a DRM event and release its space
782  * @dev: DRM device
783  * @p: tracking structure for the pending event
784  *
785  * This function frees the event @p initialized with drm_event_reserve_init()
786  * and releases any allocated space. It is used to cancel an event when the
787  * nonblocking operation could not be submitted and needed to be aborted.
788  */
789 void drm_event_cancel_free(struct drm_device *dev,
790 			   struct drm_pending_event *p)
791 {
792 	unsigned long flags;
793 
794 	spin_lock_irqsave(&dev->event_lock, flags);
795 	if (p->file_priv) {
796 		p->file_priv->event_space += p->event->length;
797 		list_del(&p->pending_link);
798 	}
799 	spin_unlock_irqrestore(&dev->event_lock, flags);
800 
801 	if (p->fence)
802 		dma_fence_put(p->fence);
803 
804 	kfree(p);
805 }
806 EXPORT_SYMBOL(drm_event_cancel_free);
807 
808 static void drm_send_event_helper(struct drm_device *dev,
809 			   struct drm_pending_event *e, ktime_t timestamp)
810 {
811 	assert_spin_locked(&dev->event_lock);
812 
813 	if (e->completion) {
814 		complete_all(e->completion);
815 		e->completion_release(e->completion);
816 		e->completion = NULL;
817 	}
818 
819 	if (e->fence) {
820 		if (timestamp)
821 			dma_fence_signal_timestamp(e->fence, timestamp);
822 		else
823 			dma_fence_signal(e->fence);
824 		dma_fence_put(e->fence);
825 	}
826 
827 	if (!e->file_priv) {
828 		kfree(e);
829 		return;
830 	}
831 
832 	list_del(&e->pending_link);
833 	list_add_tail(&e->link,
834 		      &e->file_priv->event_list);
835 	wake_up_interruptible_poll(&e->file_priv->event_wait,
836 		EPOLLIN | EPOLLRDNORM);
837 #ifdef __OpenBSD__
838 	selwakeup(&e->file_priv->rsel);
839 #endif
840 }
841 
842 /**
843  * drm_send_event_timestamp_locked - send DRM event to file descriptor
844  * @dev: DRM device
845  * @e: DRM event to deliver
846  * @timestamp: timestamp to set for the fence event in kernel's CLOCK_MONOTONIC
847  * time domain
848  *
849  * This function sends the event @e, initialized with drm_event_reserve_init(),
850  * to its associated userspace DRM file. Callers must already hold
851  * &drm_device.event_lock.
852  *
853  * Note that the core will take care of unlinking and disarming events when the
854  * corresponding DRM file is closed. Drivers need not worry about whether the
855  * DRM file for this event still exists and can call this function upon
856  * completion of the asynchronous work unconditionally.
857  */
858 void drm_send_event_timestamp_locked(struct drm_device *dev,
859 				     struct drm_pending_event *e, ktime_t timestamp)
860 {
861 	drm_send_event_helper(dev, e, timestamp);
862 }
863 EXPORT_SYMBOL(drm_send_event_timestamp_locked);
864 
865 /**
866  * drm_send_event_locked - send DRM event to file descriptor
867  * @dev: DRM device
868  * @e: DRM event to deliver
869  *
870  * This function sends the event @e, initialized with drm_event_reserve_init(),
871  * to its associated userspace DRM file. Callers must already hold
872  * &drm_device.event_lock, see drm_send_event() for the unlocked version.
873  *
874  * Note that the core will take care of unlinking and disarming events when the
875  * corresponding DRM file is closed. Drivers need not worry about whether the
876  * DRM file for this event still exists and can call this function upon
877  * completion of the asynchronous work unconditionally.
878  */
879 void drm_send_event_locked(struct drm_device *dev, struct drm_pending_event *e)
880 {
881 	drm_send_event_helper(dev, e, 0);
882 }
883 EXPORT_SYMBOL(drm_send_event_locked);
884 
885 /**
886  * drm_send_event - send DRM event to file descriptor
887  * @dev: DRM device
888  * @e: DRM event to deliver
889  *
890  * This function sends the event @e, initialized with drm_event_reserve_init(),
891  * to its associated userspace DRM file. This function acquires
892  * &drm_device.event_lock, see drm_send_event_locked() for callers which already
893  * hold this lock.
894  *
895  * Note that the core will take care of unlinking and disarming events when the
896  * corresponding DRM file is closed. Drivers need not worry about whether the
897  * DRM file for this event still exists and can call this function upon
898  * completion of the asynchronous work unconditionally.
899  */
900 void drm_send_event(struct drm_device *dev, struct drm_pending_event *e)
901 {
902 	unsigned long irqflags;
903 
904 	spin_lock_irqsave(&dev->event_lock, irqflags);
905 	drm_send_event_helper(dev, e, 0);
906 	spin_unlock_irqrestore(&dev->event_lock, irqflags);
907 }
908 EXPORT_SYMBOL(drm_send_event);
909 
910 /**
911  * mock_drm_getfile - Create a new struct file for the drm device
912  * @minor: drm minor to wrap (e.g. #drm_device.primary)
913  * @flags: file creation mode (O_RDWR etc)
914  *
915  * This create a new struct file that wraps a DRM file context around a
916  * DRM minor. This mimicks userspace opening e.g. /dev/dri/card0, but without
917  * invoking userspace. The struct file may be operated on using its f_op
918  * (the drm_device.driver.fops) to mimick userspace operations, or be supplied
919  * to userspace facing functions as an internal/anonymous client.
920  *
921  * RETURNS:
922  * Pointer to newly created struct file, ERR_PTR on failure.
923  */
924 struct file *mock_drm_getfile(struct drm_minor *minor, unsigned int flags)
925 {
926 	STUB();
927 	return ERR_PTR(-ENOSYS);
928 #ifdef notyet
929 	struct drm_device *dev = minor->dev;
930 	struct drm_file *priv;
931 	struct file *file;
932 
933 	priv = drm_file_alloc(minor);
934 	if (IS_ERR(priv))
935 		return ERR_CAST(priv);
936 
937 	file = anon_inode_getfile("drm", dev->driver->fops, priv, flags);
938 	if (IS_ERR(file)) {
939 		drm_file_free(priv);
940 		return file;
941 	}
942 
943 	/* Everyone shares a single global address space */
944 	file->f_mapping = dev->anon_inode->i_mapping;
945 
946 	drm_dev_get(dev);
947 	priv->filp = file;
948 
949 	return file;
950 #endif
951 }
952 EXPORT_SYMBOL_FOR_TESTS_ONLY(mock_drm_getfile);
953 
954 #ifdef CONFIG_MMU
955 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
956 /*
957  * drm_addr_inflate() attempts to construct an aligned area by inflating
958  * the area size and skipping the unaligned start of the area.
959  * adapted from shmem_get_unmapped_area()
960  */
961 static unsigned long drm_addr_inflate(unsigned long addr,
962 				      unsigned long len,
963 				      unsigned long pgoff,
964 				      unsigned long flags,
965 				      unsigned long huge_size)
966 {
967 	unsigned long offset, inflated_len;
968 	unsigned long inflated_addr;
969 	unsigned long inflated_offset;
970 
971 	offset = (pgoff << PAGE_SHIFT) & (huge_size - 1);
972 	if (offset && offset + len < 2 * huge_size)
973 		return addr;
974 	if ((addr & (huge_size - 1)) == offset)
975 		return addr;
976 
977 	inflated_len = len + huge_size - PAGE_SIZE;
978 	if (inflated_len > TASK_SIZE)
979 		return addr;
980 	if (inflated_len < len)
981 		return addr;
982 
983 	inflated_addr = current->mm->get_unmapped_area(NULL, 0, inflated_len,
984 						       0, flags);
985 	if (IS_ERR_VALUE(inflated_addr))
986 		return addr;
987 	if (inflated_addr & ~LINUX_PAGE_MASK)
988 		return addr;
989 
990 	inflated_offset = inflated_addr & (huge_size - 1);
991 	inflated_addr += offset - inflated_offset;
992 	if (inflated_offset > offset)
993 		inflated_addr += huge_size;
994 
995 	if (inflated_addr > TASK_SIZE - len)
996 		return addr;
997 
998 	return inflated_addr;
999 }
1000 
1001 /**
1002  * drm_get_unmapped_area() - Get an unused user-space virtual memory area
1003  * suitable for huge page table entries.
1004  * @file: The struct file representing the address space being mmap()'d.
1005  * @uaddr: Start address suggested by user-space.
1006  * @len: Length of the area.
1007  * @pgoff: The page offset into the address space.
1008  * @flags: mmap flags
1009  * @mgr: The address space manager used by the drm driver. This argument can
1010  * probably be removed at some point when all drivers use the same
1011  * address space manager.
1012  *
1013  * This function attempts to find an unused user-space virtual memory area
1014  * that can accommodate the size we want to map, and that is properly
1015  * aligned to facilitate huge page table entries matching actual
1016  * huge pages or huge page aligned memory in buffer objects. Buffer objects
1017  * are assumed to start at huge page boundary pfns (io memory) or be
1018  * populated by huge pages aligned to the start of the buffer object
1019  * (system- or coherent memory). Adapted from shmem_get_unmapped_area.
1020  *
1021  * Return: aligned user-space address.
1022  */
1023 unsigned long drm_get_unmapped_area(struct file *file,
1024 				    unsigned long uaddr, unsigned long len,
1025 				    unsigned long pgoff, unsigned long flags,
1026 				    struct drm_vma_offset_manager *mgr)
1027 {
1028 	unsigned long addr;
1029 	unsigned long inflated_addr;
1030 	struct drm_vma_offset_node *node;
1031 
1032 	if (len > TASK_SIZE)
1033 		return -ENOMEM;
1034 
1035 	/*
1036 	 * @pgoff is the file page-offset the huge page boundaries of
1037 	 * which typically aligns to physical address huge page boundaries.
1038 	 * That's not true for DRM, however, where physical address huge
1039 	 * page boundaries instead are aligned with the offset from
1040 	 * buffer object start. So adjust @pgoff to be the offset from
1041 	 * buffer object start.
1042 	 */
1043 	drm_vma_offset_lock_lookup(mgr);
1044 	node = drm_vma_offset_lookup_locked(mgr, pgoff, 1);
1045 	if (node)
1046 		pgoff -= node->vm_node.start;
1047 	drm_vma_offset_unlock_lookup(mgr);
1048 
1049 	addr = current->mm->get_unmapped_area(file, uaddr, len, pgoff, flags);
1050 	if (IS_ERR_VALUE(addr))
1051 		return addr;
1052 	if (addr & ~LINUX_PAGE_MASK)
1053 		return addr;
1054 	if (addr > TASK_SIZE - len)
1055 		return addr;
1056 
1057 	if (len < HPAGE_PMD_SIZE)
1058 		return addr;
1059 	if (flags & MAP_FIXED)
1060 		return addr;
1061 	/*
1062 	 * Our priority is to support MAP_SHARED mapped hugely;
1063 	 * and support MAP_PRIVATE mapped hugely too, until it is COWed.
1064 	 * But if caller specified an address hint, respect that as before.
1065 	 */
1066 	if (uaddr)
1067 		return addr;
1068 
1069 	inflated_addr = drm_addr_inflate(addr, len, pgoff, flags,
1070 					 HPAGE_PMD_SIZE);
1071 
1072 	if (IS_ENABLED(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD) &&
1073 	    len >= HPAGE_PUD_SIZE)
1074 		inflated_addr = drm_addr_inflate(inflated_addr, len, pgoff,
1075 						 flags, HPAGE_PUD_SIZE);
1076 	return inflated_addr;
1077 }
1078 #else /* CONFIG_TRANSPARENT_HUGEPAGE */
1079 unsigned long drm_get_unmapped_area(struct file *file,
1080 				    unsigned long uaddr, unsigned long len,
1081 				    unsigned long pgoff, unsigned long flags,
1082 				    struct drm_vma_offset_manager *mgr)
1083 {
1084 	return current->mm->get_unmapped_area(file, uaddr, len, pgoff, flags);
1085 }
1086 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
1087 EXPORT_SYMBOL_GPL(drm_get_unmapped_area);
1088 #endif /* CONFIG_MMU */
1089