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