Home | History | Annotate | Line # | Download | only in drm
drm_drv.c revision 1.15
      1 /*	$NetBSD: drm_drv.c,v 1.15 2021/12/18 23:44:57 riastradh Exp $	*/
      2 
      3 /*
      4  * Created: Fri Jan 19 10:48:35 2001 by faith (at) acm.org
      5  *
      6  * Copyright 2001 VA Linux Systems, Inc., Sunnyvale, California.
      7  * All Rights Reserved.
      8  *
      9  * Author Rickard E. (Rik) Faith <faith (at) valinux.com>
     10  *
     11  * Permission is hereby granted, free of charge, to any person obtaining a
     12  * copy of this software and associated documentation files (the "Software"),
     13  * to deal in the Software without restriction, including without limitation
     14  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
     15  * and/or sell copies of the Software, and to permit persons to whom the
     16  * Software is furnished to do so, subject to the following conditions:
     17  *
     18  * The above copyright notice and this permission notice (including the next
     19  * paragraph) shall be included in all copies or substantial portions of the
     20  * Software.
     21  *
     22  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     23  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     24  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
     25  * PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
     26  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
     27  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
     28  * DEALINGS IN THE SOFTWARE.
     29  */
     30 
     31 #include <sys/cdefs.h>
     32 __KERNEL_RCSID(0, "$NetBSD: drm_drv.c,v 1.15 2021/12/18 23:44:57 riastradh Exp $");
     33 
     34 #include <linux/debugfs.h>
     35 #include <linux/fs.h>
     36 #include <linux/module.h>
     37 #include <linux/moduleparam.h>
     38 #include <linux/mount.h>
     39 #include <linux/pseudo_fs.h>
     40 #include <linux/slab.h>
     41 #include <linux/srcu.h>
     42 
     43 #include <drm/drm_client.h>
     44 #include <drm/drm_color_mgmt.h>
     45 #include <drm/drm_drv.h>
     46 #include <drm/drm_file.h>
     47 #include <drm/drm_mode_object.h>
     48 #include <drm/drm_print.h>
     49 
     50 #include "drm_crtc_internal.h"
     51 #include "drm_internal.h"
     52 #include "drm_legacy.h"
     53 
     54 MODULE_AUTHOR("Gareth Hughes, Leif Delgass, Jos Fonseca, Jon Smirl");
     55 MODULE_DESCRIPTION("DRM shared core routines");
     56 MODULE_LICENSE("GPL and additional rights");
     57 
     58 #ifdef __NetBSD__
     59 spinlock_t drm_minor_lock;
     60 struct idr drm_minors_idr;
     61 #else
     62 static DEFINE_SPINLOCK(drm_minor_lock);
     63 static struct idr drm_minors_idr;
     64 #endif
     65 
     66 #ifndef __NetBSD__
     67 static struct dentry *drm_debugfs_root;
     68 #endif
     69 
     70 DEFINE_STATIC_SRCU(drm_unplug_srcu);
     71 
     72 /*
     73  * DRM Minors
     74  * A DRM device can provide several char-dev interfaces on the DRM-Major. Each
     75  * of them is represented by a drm_minor object. Depending on the capabilities
     76  * of the device-driver, different interfaces are registered.
     77  *
     78  * Minors can be accessed via dev->$minor_name. This pointer is either
     79  * NULL or a valid drm_minor pointer and stays valid as long as the device is
     80  * valid. This means, DRM minors have the same life-time as the underlying
     81  * device. However, this doesn't mean that the minor is active. Minors are
     82  * registered and unregistered dynamically according to device-state.
     83  */
     84 
     85 static struct drm_minor **drm_minor_get_slot(struct drm_device *dev,
     86 					     unsigned int type)
     87 {
     88 	switch (type) {
     89 	case DRM_MINOR_PRIMARY:
     90 		return &dev->primary;
     91 	case DRM_MINOR_RENDER:
     92 		return &dev->render;
     93 	default:
     94 		BUG();
     95 	}
     96 }
     97 
     98 static int drm_minor_alloc(struct drm_device *dev, unsigned int type)
     99 {
    100 	struct drm_minor *minor;
    101 	unsigned long flags;
    102 	int r;
    103 
    104 	minor = kzalloc(sizeof(*minor), GFP_KERNEL);
    105 	if (!minor)
    106 		return -ENOMEM;
    107 
    108 	minor->type = type;
    109 	minor->dev = dev;
    110 
    111 	idr_preload(GFP_KERNEL);
    112 	spin_lock_irqsave(&drm_minor_lock, flags);
    113 	r = idr_alloc(&drm_minors_idr,
    114 		      NULL,
    115 		      64 * type,
    116 		      64 * (type + 1),
    117 		      GFP_NOWAIT);
    118 	spin_unlock_irqrestore(&drm_minor_lock, flags);
    119 	idr_preload_end();
    120 
    121 	if (r < 0)
    122 		goto err_free;
    123 
    124 	minor->index = r;
    125 
    126 #ifndef __NetBSD__		/* XXX drm sysfs */
    127 	minor->kdev = drm_sysfs_minor_alloc(minor);
    128 	if (IS_ERR(minor->kdev)) {
    129 		r = PTR_ERR(minor->kdev);
    130 		goto err_index;
    131 	}
    132 #endif
    133 
    134 	*drm_minor_get_slot(dev, type) = minor;
    135 	return 0;
    136 
    137 err_index: __unused
    138 	spin_lock_irqsave(&drm_minor_lock, flags);
    139 	idr_remove(&drm_minors_idr, minor->index);
    140 	spin_unlock_irqrestore(&drm_minor_lock, flags);
    141 err_free:
    142 	kfree(minor);
    143 	return r;
    144 }
    145 
    146 static void drm_minor_free(struct drm_device *dev, unsigned int type)
    147 {
    148 	struct drm_minor **slot, *minor;
    149 	unsigned long flags;
    150 
    151 	slot = drm_minor_get_slot(dev, type);
    152 	minor = *slot;
    153 	if (!minor)
    154 		return;
    155 
    156 #ifndef __NetBSD__		/* XXX drm sysfs */
    157 	put_device(minor->kdev);
    158 #endif
    159 
    160 	spin_lock_irqsave(&drm_minor_lock, flags);
    161 	idr_remove(&drm_minors_idr, minor->index);
    162 	spin_unlock_irqrestore(&drm_minor_lock, flags);
    163 
    164 	kfree(minor);
    165 	*slot = NULL;
    166 }
    167 
    168 static int drm_minor_register(struct drm_device *dev, unsigned int type)
    169 {
    170 	struct drm_minor *minor;
    171 	unsigned long flags;
    172 #ifndef __NetBSD__
    173 	int ret;
    174 #endif
    175 
    176 	DRM_DEBUG("\n");
    177 
    178 	minor = *drm_minor_get_slot(dev, type);
    179 	if (!minor)
    180 		return 0;
    181 
    182 #ifndef __NetBSD__
    183 	ret = drm_debugfs_init(minor, minor->index, drm_debugfs_root);
    184 	if (ret) {
    185 		DRM_ERROR("DRM: Failed to initialize /sys/kernel/debug/dri.\n");
    186 		goto err_debugfs;
    187 	}
    188 
    189 	ret = device_add(minor->kdev);
    190 	if (ret)
    191 		goto err_debugfs;
    192 #endif
    193 
    194 	/* replace NULL with @minor so lookups will succeed from now on */
    195 	spin_lock_irqsave(&drm_minor_lock, flags);
    196 	idr_replace(&drm_minors_idr, minor, minor->index);
    197 	spin_unlock_irqrestore(&drm_minor_lock, flags);
    198 
    199 	DRM_DEBUG("new minor registered %d\n", minor->index);
    200 	return 0;
    201 
    202 #ifndef __NetBSD__
    203 err_debugfs:
    204 	drm_debugfs_cleanup(minor);
    205 	return ret;
    206 #endif
    207 }
    208 
    209 static void drm_minor_unregister(struct drm_device *dev, unsigned int type)
    210 {
    211 	struct drm_minor *minor;
    212 	unsigned long flags;
    213 
    214 	minor = *drm_minor_get_slot(dev, type);
    215 #ifdef __NetBSD__
    216 	if (!minor)
    217 #else
    218 	if (!minor || !device_is_registered(minor->kdev))
    219 #endif
    220 		return;
    221 
    222 	/* replace @minor with NULL so lookups will fail from now on */
    223 	spin_lock_irqsave(&drm_minor_lock, flags);
    224 	idr_replace(&drm_minors_idr, NULL, minor->index);
    225 	spin_unlock_irqrestore(&drm_minor_lock, flags);
    226 
    227 #ifndef __NetBSD__
    228 	device_del(minor->kdev);
    229 	dev_set_drvdata(minor->kdev, NULL); /* safety belt */
    230 	drm_debugfs_cleanup(minor);
    231 #endif
    232 }
    233 
    234 /*
    235  * Looks up the given minor-ID and returns the respective DRM-minor object. The
    236  * refence-count of the underlying device is increased so you must release this
    237  * object with drm_minor_release().
    238  *
    239  * As long as you hold this minor, it is guaranteed that the object and the
    240  * minor->dev pointer will stay valid! However, the device may get unplugged and
    241  * unregistered while you hold the minor.
    242  */
    243 struct drm_minor *drm_minor_acquire(unsigned int minor_id)
    244 {
    245 	struct drm_minor *minor;
    246 	unsigned long flags;
    247 
    248 	spin_lock_irqsave(&drm_minor_lock, flags);
    249 	minor = idr_find(&drm_minors_idr, minor_id);
    250 	if (minor)
    251 		drm_dev_get(minor->dev);
    252 	spin_unlock_irqrestore(&drm_minor_lock, flags);
    253 
    254 	if (!minor) {
    255 		return ERR_PTR(-ENODEV);
    256 	} else if (drm_dev_is_unplugged(minor->dev)) {
    257 		drm_dev_put(minor->dev);
    258 		return ERR_PTR(-ENODEV);
    259 	}
    260 
    261 	return minor;
    262 }
    263 
    264 void drm_minor_release(struct drm_minor *minor)
    265 {
    266 	drm_dev_put(minor->dev);
    267 }
    268 
    269 /**
    270  * DOC: driver instance overview
    271  *
    272  * A device instance for a drm driver is represented by &struct drm_device. This
    273  * is initialized with drm_dev_init(), usually from bus-specific ->probe()
    274  * callbacks implemented by the driver. The driver then needs to initialize all
    275  * the various subsystems for the drm device like memory management, vblank
    276  * handling, modesetting support and intial output configuration plus obviously
    277  * initialize all the corresponding hardware bits. Finally when everything is up
    278  * and running and ready for userspace the device instance can be published
    279  * using drm_dev_register().
    280  *
    281  * There is also deprecated support for initalizing device instances using
    282  * bus-specific helpers and the &drm_driver.load callback. But due to
    283  * backwards-compatibility needs the device instance have to be published too
    284  * early, which requires unpretty global locking to make safe and is therefore
    285  * only support for existing drivers not yet converted to the new scheme.
    286  *
    287  * When cleaning up a device instance everything needs to be done in reverse:
    288  * First unpublish the device instance with drm_dev_unregister(). Then clean up
    289  * any other resources allocated at device initialization and drop the driver's
    290  * reference to &drm_device using drm_dev_put().
    291  *
    292  * Note that the lifetime rules for &drm_device instance has still a lot of
    293  * historical baggage. Hence use the reference counting provided by
    294  * drm_dev_get() and drm_dev_put() only carefully.
    295  *
    296  * Display driver example
    297  * ~~~~~~~~~~~~~~~~~~~~~~
    298  *
    299  * The following example shows a typical structure of a DRM display driver.
    300  * The example focus on the probe() function and the other functions that is
    301  * almost always present and serves as a demonstration of devm_drm_dev_init()
    302  * usage with its accompanying drm_driver->release callback.
    303  *
    304  * .. code-block:: c
    305  *
    306  *	struct driver_device {
    307  *		struct drm_device drm;
    308  *		void *userspace_facing;
    309  *		struct clk *pclk;
    310  *	};
    311  *
    312  *	static void driver_drm_release(struct drm_device *drm)
    313  *	{
    314  *		struct driver_device *priv = container_of(...);
    315  *
    316  *		drm_mode_config_cleanup(drm);
    317  *		drm_dev_fini(drm);
    318  *		kfree(priv->userspace_facing);
    319  *		kfree(priv);
    320  *	}
    321  *
    322  *	static struct drm_driver driver_drm_driver = {
    323  *		[...]
    324  *		.release = driver_drm_release,
    325  *	};
    326  *
    327  *	static int driver_probe(struct platform_device *pdev)
    328  *	{
    329  *		struct driver_device *priv;
    330  *		struct drm_device *drm;
    331  *		int ret;
    332  *
    333  *		// devm_kzalloc() can't be used here because the drm_device '
    334  *		// lifetime can exceed the device lifetime if driver unbind
    335  *		// happens when userspace still has open file descriptors.
    336  *		priv = kzalloc(sizeof(*priv), GFP_KERNEL);
    337  *		if (!priv)
    338  *			return -ENOMEM;
    339  *
    340  *		drm = &priv->drm;
    341  *
    342  *		ret = devm_drm_dev_init(&pdev->dev, drm, &driver_drm_driver);
    343  *		if (ret) {
    344  *			kfree(drm);
    345  *			return ret;
    346  *		}
    347  *
    348  *		drm_mode_config_init(drm);
    349  *
    350  *		priv->userspace_facing = kzalloc(..., GFP_KERNEL);
    351  *		if (!priv->userspace_facing)
    352  *			return -ENOMEM;
    353  *
    354  *		priv->pclk = devm_clk_get(dev, "PCLK");
    355  *		if (IS_ERR(priv->pclk))
    356  *			return PTR_ERR(priv->pclk);
    357  *
    358  *		// Further setup, display pipeline etc
    359  *
    360  *		platform_set_drvdata(pdev, drm);
    361  *
    362  *		drm_mode_config_reset(drm);
    363  *
    364  *		ret = drm_dev_register(drm);
    365  *		if (ret)
    366  *			return ret;
    367  *
    368  *		drm_fbdev_generic_setup(drm, 32);
    369  *
    370  *		return 0;
    371  *	}
    372  *
    373  *	// This function is called before the devm_ resources are released
    374  *	static int driver_remove(struct platform_device *pdev)
    375  *	{
    376  *		struct drm_device *drm = platform_get_drvdata(pdev);
    377  *
    378  *		drm_dev_unregister(drm);
    379  *		drm_atomic_helper_shutdown(drm)
    380  *
    381  *		return 0;
    382  *	}
    383  *
    384  *	// This function is called on kernel restart and shutdown
    385  *	static void driver_shutdown(struct platform_device *pdev)
    386  *	{
    387  *		drm_atomic_helper_shutdown(platform_get_drvdata(pdev));
    388  *	}
    389  *
    390  *	static int __maybe_unused driver_pm_suspend(struct device *dev)
    391  *	{
    392  *		return drm_mode_config_helper_suspend(dev_get_drvdata(dev));
    393  *	}
    394  *
    395  *	static int __maybe_unused driver_pm_resume(struct device *dev)
    396  *	{
    397  *		drm_mode_config_helper_resume(dev_get_drvdata(dev));
    398  *
    399  *		return 0;
    400  *	}
    401  *
    402  *	static const struct dev_pm_ops driver_pm_ops = {
    403  *		SET_SYSTEM_SLEEP_PM_OPS(driver_pm_suspend, driver_pm_resume)
    404  *	};
    405  *
    406  *	static struct platform_driver driver_driver = {
    407  *		.driver = {
    408  *			[...]
    409  *			.pm = &driver_pm_ops,
    410  *		},
    411  *		.probe = driver_probe,
    412  *		.remove = driver_remove,
    413  *		.shutdown = driver_shutdown,
    414  *	};
    415  *	module_platform_driver(driver_driver);
    416  *
    417  * Drivers that want to support device unplugging (USB, DT overlay unload) should
    418  * use drm_dev_unplug() instead of drm_dev_unregister(). The driver must protect
    419  * regions that is accessing device resources to prevent use after they're
    420  * released. This is done using drm_dev_enter() and drm_dev_exit(). There is one
    421  * shortcoming however, drm_dev_unplug() marks the drm_device as unplugged before
    422  * drm_atomic_helper_shutdown() is called. This means that if the disable code
    423  * paths are protected, they will not run on regular driver module unload,
    424  * possibily leaving the hardware enabled.
    425  */
    426 
    427 /**
    428  * drm_put_dev - Unregister and release a DRM device
    429  * @dev: DRM device
    430  *
    431  * Called at module unload time or when a PCI device is unplugged.
    432  *
    433  * Cleans up all DRM device, calling drm_lastclose().
    434  *
    435  * Note: Use of this function is deprecated. It will eventually go away
    436  * completely.  Please use drm_dev_unregister() and drm_dev_put() explicitly
    437  * instead to make sure that the device isn't userspace accessible any more
    438  * while teardown is in progress, ensuring that userspace can't access an
    439  * inconsistent state.
    440  */
    441 void drm_put_dev(struct drm_device *dev)
    442 {
    443 	DRM_DEBUG("\n");
    444 
    445 	if (!dev) {
    446 		DRM_ERROR("cleanup called no dev\n");
    447 		return;
    448 	}
    449 
    450 	drm_dev_unregister(dev);
    451 	drm_dev_put(dev);
    452 }
    453 EXPORT_SYMBOL(drm_put_dev);
    454 
    455 /**
    456  * drm_dev_enter - Enter device critical section
    457  * @dev: DRM device
    458  * @idx: Pointer to index that will be passed to the matching drm_dev_exit()
    459  *
    460  * This function marks and protects the beginning of a section that should not
    461  * be entered after the device has been unplugged. The section end is marked
    462  * with drm_dev_exit(). Calls to this function can be nested.
    463  *
    464  * Returns:
    465  * True if it is OK to enter the section, false otherwise.
    466  */
    467 bool drm_dev_enter(struct drm_device *dev, int *idx)
    468 {
    469 	*idx = srcu_read_lock(&drm_unplug_srcu);
    470 
    471 	if (dev->unplugged) {
    472 		srcu_read_unlock(&drm_unplug_srcu, *idx);
    473 		return false;
    474 	}
    475 
    476 	return true;
    477 }
    478 EXPORT_SYMBOL(drm_dev_enter);
    479 
    480 /**
    481  * drm_dev_exit - Exit device critical section
    482  * @idx: index returned from drm_dev_enter()
    483  *
    484  * This function marks the end of a section that should not be entered after
    485  * the device has been unplugged.
    486  */
    487 void drm_dev_exit(int idx)
    488 {
    489 	srcu_read_unlock(&drm_unplug_srcu, idx);
    490 }
    491 EXPORT_SYMBOL(drm_dev_exit);
    492 
    493 /**
    494  * drm_dev_unplug - unplug a DRM device
    495  * @dev: DRM device
    496  *
    497  * This unplugs a hotpluggable DRM device, which makes it inaccessible to
    498  * userspace operations. Entry-points can use drm_dev_enter() and
    499  * drm_dev_exit() to protect device resources in a race free manner. This
    500  * essentially unregisters the device like drm_dev_unregister(), but can be
    501  * called while there are still open users of @dev.
    502  */
    503 void drm_dev_unplug(struct drm_device *dev)
    504 {
    505 	/*
    506 	 * After synchronizing any critical read section is guaranteed to see
    507 	 * the new value of ->unplugged, and any critical section which might
    508 	 * still have seen the old value of ->unplugged is guaranteed to have
    509 	 * finished.
    510 	 */
    511 	dev->unplugged = true;
    512 	synchronize_srcu(&drm_unplug_srcu);
    513 
    514 	drm_dev_unregister(dev);
    515 }
    516 EXPORT_SYMBOL(drm_dev_unplug);
    517 
    518 #ifdef __NetBSD__
    519 
    520 static void *
    521 drm_fs_inode_new(void)
    522 {
    523 	return NULL;
    524 }
    525 
    526 static void
    527 drm_fs_inode_free(void *inode)
    528 {
    529 	KASSERT(inode == NULL);
    530 }
    531 
    532 #else
    533 
    534 /*
    535  * DRM internal mount
    536  * We want to be able to allocate our own "struct address_space" to control
    537  * memory-mappings in VRAM (or stolen RAM, ...). However, core MM does not allow
    538  * stand-alone address_space objects, so we need an underlying inode. As there
    539  * is no way to allocate an independent inode easily, we need a fake internal
    540  * VFS mount-point.
    541  *
    542  * The drm_fs_inode_new() function allocates a new inode, drm_fs_inode_free()
    543  * frees it again. You are allowed to use iget() and iput() to get references to
    544  * the inode. But each drm_fs_inode_new() call must be paired with exactly one
    545  * drm_fs_inode_free() call (which does not have to be the last iput()).
    546  * We use drm_fs_inode_*() to manage our internal VFS mount-point and share it
    547  * between multiple inode-users. You could, technically, call
    548  * iget() + drm_fs_inode_free() directly after alloc and sometime later do an
    549  * iput(), but this way you'd end up with a new vfsmount for each inode.
    550  */
    551 
    552 static int drm_fs_cnt;
    553 static struct vfsmount *drm_fs_mnt;
    554 
    555 static int drm_fs_init_fs_context(struct fs_context *fc)
    556 {
    557 	return init_pseudo(fc, 0x010203ff) ? 0 : -ENOMEM;
    558 }
    559 
    560 static struct file_system_type drm_fs_type = {
    561 	.name		= "drm",
    562 	.owner		= THIS_MODULE,
    563 	.init_fs_context = drm_fs_init_fs_context,
    564 	.kill_sb	= kill_anon_super,
    565 };
    566 
    567 static struct inode *drm_fs_inode_new(void)
    568 {
    569 	struct inode *inode;
    570 	int r;
    571 
    572 	r = simple_pin_fs(&drm_fs_type, &drm_fs_mnt, &drm_fs_cnt);
    573 	if (r < 0) {
    574 		DRM_ERROR("Cannot mount pseudo fs: %d\n", r);
    575 		return ERR_PTR(r);
    576 	}
    577 
    578 	inode = alloc_anon_inode(drm_fs_mnt->mnt_sb);
    579 	if (IS_ERR(inode))
    580 		simple_release_fs(&drm_fs_mnt, &drm_fs_cnt);
    581 
    582 	return inode;
    583 }
    584 
    585 static void drm_fs_inode_free(struct inode *inode)
    586 {
    587 	if (inode) {
    588 		iput(inode);
    589 		simple_release_fs(&drm_fs_mnt, &drm_fs_cnt);
    590 	}
    591 }
    592 
    593 #endif
    594 
    595 /**
    596  * DOC: component helper usage recommendations
    597  *
    598  * DRM drivers that drive hardware where a logical device consists of a pile of
    599  * independent hardware blocks are recommended to use the :ref:`component helper
    600  * library<component>`. For consistency and better options for code reuse the
    601  * following guidelines apply:
    602  *
    603  *  - The entire device initialization procedure should be run from the
    604  *    &component_master_ops.master_bind callback, starting with drm_dev_init(),
    605  *    then binding all components with component_bind_all() and finishing with
    606  *    drm_dev_register().
    607  *
    608  *  - The opaque pointer passed to all components through component_bind_all()
    609  *    should point at &struct drm_device of the device instance, not some driver
    610  *    specific private structure.
    611  *
    612  *  - The component helper fills the niche where further standardization of
    613  *    interfaces is not practical. When there already is, or will be, a
    614  *    standardized interface like &drm_bridge or &drm_panel, providing its own
    615  *    functions to find such components at driver load time, like
    616  *    drm_of_find_panel_or_bridge(), then the component helper should not be
    617  *    used.
    618  */
    619 
    620 /**
    621  * drm_dev_init - Initialise new DRM device
    622  * @dev: DRM device
    623  * @driver: DRM driver
    624  * @parent: Parent device object
    625  *
    626  * Initialize a new DRM device. No device registration is done.
    627  * Call drm_dev_register() to advertice the device to user space and register it
    628  * with other core subsystems. This should be done last in the device
    629  * initialization sequence to make sure userspace can't access an inconsistent
    630  * state.
    631  *
    632  * The initial ref-count of the object is 1. Use drm_dev_get() and
    633  * drm_dev_put() to take and drop further ref-counts.
    634  *
    635  * It is recommended that drivers embed &struct drm_device into their own device
    636  * structure.
    637  *
    638  * Drivers that do not want to allocate their own device struct
    639  * embedding &struct drm_device can call drm_dev_alloc() instead. For drivers
    640  * that do embed &struct drm_device it must be placed first in the overall
    641  * structure, and the overall structure must be allocated using kmalloc(): The
    642  * drm core's release function unconditionally calls kfree() on the @dev pointer
    643  * when the final reference is released. To override this behaviour, and so
    644  * allow embedding of the drm_device inside the driver's device struct at an
    645  * arbitrary offset, you must supply a &drm_driver.release callback and control
    646  * the finalization explicitly.
    647  *
    648  * RETURNS:
    649  * 0 on success, or error code on failure.
    650  */
    651 int drm_dev_init(struct drm_device *dev,
    652 		 struct drm_driver *driver,
    653 		 struct device *parent)
    654 {
    655 	int ret;
    656 
    657 	if (!drm_core_init_complete) {
    658 		DRM_ERROR("DRM core is not initialized\n");
    659 		return -ENODEV;
    660 	}
    661 
    662 	if (WARN_ON(!parent))
    663 		return -EINVAL;
    664 
    665 	kref_init(&dev->ref);
    666 	dev->dev = get_device(parent);
    667 	dev->driver = driver;
    668 
    669 	/* no per-device feature limits by default */
    670 	dev->driver_features = ~0u;
    671 
    672 	drm_legacy_init_members(dev);
    673 	INIT_LIST_HEAD(&dev->filelist);
    674 	INIT_LIST_HEAD(&dev->filelist_internal);
    675 	INIT_LIST_HEAD(&dev->clientlist);
    676 	INIT_LIST_HEAD(&dev->vblank_event_list);
    677 
    678 	spin_lock_init(&dev->event_lock);
    679 	mutex_init(&dev->struct_mutex);
    680 	mutex_init(&dev->filelist_mutex);
    681 	mutex_init(&dev->clientlist_mutex);
    682 	mutex_init(&dev->master_mutex);
    683 
    684 	dev->sc_monitor_hotplug.smpsw_name = PSWITCH_HK_DISPLAY_CYCLE;
    685 	dev->sc_monitor_hotplug.smpsw_type = PSWITCH_TYPE_HOTKEY;
    686 	ret = sysmon_pswitch_register(&dev->sc_monitor_hotplug);
    687 	if (ret)
    688 		goto err_pswitch;
    689 
    690 	dev->anon_inode = drm_fs_inode_new();
    691 	if (IS_ERR(dev->anon_inode)) {
    692 		ret = PTR_ERR(dev->anon_inode);
    693 		DRM_ERROR("Cannot allocate anonymous inode: %d\n", ret);
    694 		goto err_free;
    695 	}
    696 
    697 	if (drm_core_check_feature(dev, DRIVER_RENDER)) {
    698 		ret = drm_minor_alloc(dev, DRM_MINOR_RENDER);
    699 		if (ret)
    700 			goto err_minors;
    701 	}
    702 
    703 	ret = drm_minor_alloc(dev, DRM_MINOR_PRIMARY);
    704 	if (ret)
    705 		goto err_minors;
    706 
    707 	ret = drm_legacy_create_map_hash(dev);
    708 	if (ret)
    709 		goto err_minors;
    710 
    711 	drm_legacy_ctxbitmap_init(dev);
    712 
    713 	if (drm_core_check_feature(dev, DRIVER_GEM)) {
    714 		ret = drm_gem_init(dev);
    715 		if (ret) {
    716 			DRM_ERROR("Cannot initialize graphics execution manager (GEM)\n");
    717 			goto err_ctxbitmap;
    718 		}
    719 	}
    720 
    721 	ret = drm_dev_set_unique(dev, dev_name(parent));
    722 	if (ret)
    723 		goto err_setunique;
    724 
    725 	return 0;
    726 
    727 err_setunique:
    728 	if (drm_core_check_feature(dev, DRIVER_GEM))
    729 		drm_gem_destroy(dev);
    730 err_ctxbitmap:
    731 	drm_legacy_ctxbitmap_cleanup(dev);
    732 	drm_legacy_remove_map_hash(dev);
    733 err_minors:
    734 	drm_minor_free(dev, DRM_MINOR_PRIMARY);
    735 	drm_minor_free(dev, DRM_MINOR_RENDER);
    736 	drm_fs_inode_free(dev->anon_inode);
    737 err_free:
    738 #ifdef __NetBSD__
    739 	sysmon_pswitch_unregister(&dev->sc_monitor_hotplug);
    740 err_pswitch:
    741 #endif
    742 	put_device(dev->dev);
    743 	mutex_destroy(&dev->master_mutex);
    744 	mutex_destroy(&dev->clientlist_mutex);
    745 	mutex_destroy(&dev->filelist_mutex);
    746 	mutex_destroy(&dev->struct_mutex);
    747 	drm_legacy_destroy_members(dev);
    748 	return ret;
    749 }
    750 EXPORT_SYMBOL(drm_dev_init);
    751 
    752 static void devm_drm_dev_init_release(void *data)
    753 {
    754 	drm_dev_put(data);
    755 }
    756 
    757 /**
    758  * devm_drm_dev_init - Resource managed drm_dev_init()
    759  * @parent: Parent device object
    760  * @dev: DRM device
    761  * @driver: DRM driver
    762  *
    763  * Managed drm_dev_init(). The DRM device initialized with this function is
    764  * automatically put on driver detach using drm_dev_put(). You must supply a
    765  * &drm_driver.release callback to control the finalization explicitly.
    766  *
    767  * RETURNS:
    768  * 0 on success, or error code on failure.
    769  */
    770 int devm_drm_dev_init(struct device *parent,
    771 		      struct drm_device *dev,
    772 		      struct drm_driver *driver)
    773 {
    774 	int ret;
    775 
    776 	if (WARN_ON(!driver->release))
    777 		return -EINVAL;
    778 
    779 	ret = drm_dev_init(dev, driver, parent);
    780 	if (ret)
    781 		return ret;
    782 
    783 	ret = devm_add_action(parent, devm_drm_dev_init_release, dev);
    784 	if (ret)
    785 		devm_drm_dev_init_release(dev);
    786 
    787 	return ret;
    788 }
    789 EXPORT_SYMBOL(devm_drm_dev_init);
    790 
    791 /**
    792  * drm_dev_fini - Finalize a dead DRM device
    793  * @dev: DRM device
    794  *
    795  * Finalize a dead DRM device. This is the converse to drm_dev_init() and
    796  * frees up all data allocated by it. All driver private data should be
    797  * finalized first. Note that this function does not free the @dev, that is
    798  * left to the caller.
    799  *
    800  * The ref-count of @dev must be zero, and drm_dev_fini() should only be called
    801  * from a &drm_driver.release callback.
    802  */
    803 void drm_dev_fini(struct drm_device *dev)
    804 {
    805 	drm_vblank_cleanup(dev);
    806 
    807 	if (drm_core_check_feature(dev, DRIVER_GEM))
    808 		drm_gem_destroy(dev);
    809 
    810 	drm_legacy_ctxbitmap_cleanup(dev);
    811 	drm_legacy_remove_map_hash(dev);
    812 	drm_fs_inode_free(dev->anon_inode);
    813 
    814 	drm_minor_free(dev, DRM_MINOR_PRIMARY);
    815 	drm_minor_free(dev, DRM_MINOR_RENDER);
    816 
    817 #ifdef __NetBSD__
    818 	sysmon_pswitch_unregister(&dev->sc_monitor_hotplug);
    819 #endif
    820 
    821 	put_device(dev->dev);
    822 
    823 	mutex_destroy(&dev->master_mutex);
    824 	mutex_destroy(&dev->clientlist_mutex);
    825 	mutex_destroy(&dev->filelist_mutex);
    826 	mutex_destroy(&dev->struct_mutex);
    827 	drm_legacy_destroy_members(dev);
    828 	kfree(dev->unique);
    829 }
    830 EXPORT_SYMBOL(drm_dev_fini);
    831 
    832 /**
    833  * drm_dev_alloc - Allocate new DRM device
    834  * @driver: DRM driver to allocate device for
    835  * @parent: Parent device object
    836  *
    837  * Allocate and initialize a new DRM device. No device registration is done.
    838  * Call drm_dev_register() to advertice the device to user space and register it
    839  * with other core subsystems. This should be done last in the device
    840  * initialization sequence to make sure userspace can't access an inconsistent
    841  * state.
    842  *
    843  * The initial ref-count of the object is 1. Use drm_dev_get() and
    844  * drm_dev_put() to take and drop further ref-counts.
    845  *
    846  * Note that for purely virtual devices @parent can be NULL.
    847  *
    848  * Drivers that wish to subclass or embed &struct drm_device into their
    849  * own struct should look at using drm_dev_init() instead.
    850  *
    851  * RETURNS:
    852  * Pointer to new DRM device, or ERR_PTR on failure.
    853  */
    854 struct drm_device *drm_dev_alloc(struct drm_driver *driver,
    855 				 struct device *parent)
    856 {
    857 	struct drm_device *dev;
    858 	int ret;
    859 
    860 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
    861 	if (!dev)
    862 		return ERR_PTR(-ENOMEM);
    863 
    864 	ret = drm_dev_init(dev, driver, parent);
    865 	if (ret) {
    866 		kfree(dev);
    867 		return ERR_PTR(ret);
    868 	}
    869 
    870 	return dev;
    871 }
    872 EXPORT_SYMBOL(drm_dev_alloc);
    873 
    874 static void drm_dev_release(struct kref *ref)
    875 {
    876 	struct drm_device *dev = container_of(ref, struct drm_device, ref);
    877 
    878 	if (dev->driver->release) {
    879 		dev->driver->release(dev);
    880 	} else {
    881 		drm_dev_fini(dev);
    882 		kfree(dev);
    883 	}
    884 }
    885 
    886 /**
    887  * drm_dev_get - Take reference of a DRM device
    888  * @dev: device to take reference of or NULL
    889  *
    890  * This increases the ref-count of @dev by one. You *must* already own a
    891  * reference when calling this. Use drm_dev_put() to drop this reference
    892  * again.
    893  *
    894  * This function never fails. However, this function does not provide *any*
    895  * guarantee whether the device is alive or running. It only provides a
    896  * reference to the object and the memory associated with it.
    897  */
    898 void drm_dev_get(struct drm_device *dev)
    899 {
    900 	if (dev)
    901 		kref_get(&dev->ref);
    902 }
    903 EXPORT_SYMBOL(drm_dev_get);
    904 
    905 /**
    906  * drm_dev_put - Drop reference of a DRM device
    907  * @dev: device to drop reference of or NULL
    908  *
    909  * This decreases the ref-count of @dev by one. The device is destroyed if the
    910  * ref-count drops to zero.
    911  */
    912 void drm_dev_put(struct drm_device *dev)
    913 {
    914 	if (dev)
    915 		kref_put(&dev->ref, drm_dev_release);
    916 }
    917 EXPORT_SYMBOL(drm_dev_put);
    918 
    919 static int create_compat_control_link(struct drm_device *dev)
    920 {
    921 	struct drm_minor *minor;
    922 	char *name;
    923 	int ret;
    924 
    925 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
    926 		return 0;
    927 
    928 	minor = *drm_minor_get_slot(dev, DRM_MINOR_PRIMARY);
    929 	if (!minor)
    930 		return 0;
    931 
    932 	/*
    933 	 * Some existing userspace out there uses the existing of the controlD*
    934 	 * sysfs files to figure out whether it's a modeset driver. It only does
    935 	 * readdir, hence a symlink is sufficient (and the least confusing
    936 	 * option). Otherwise controlD* is entirely unused.
    937 	 *
    938 	 * Old controlD chardev have been allocated in the range
    939 	 * 64-127.
    940 	 */
    941 	name = kasprintf(GFP_KERNEL, "controlD%d", minor->index + 64);
    942 	if (!name)
    943 		return -ENOMEM;
    944 
    945 	ret = sysfs_create_link(minor->kdev->kobj.parent,
    946 				&minor->kdev->kobj,
    947 				name);
    948 
    949 	kfree(name);
    950 
    951 	return ret;
    952 }
    953 
    954 static void remove_compat_control_link(struct drm_device *dev)
    955 {
    956 	struct drm_minor *minor;
    957 	char *name;
    958 
    959 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
    960 		return;
    961 
    962 	minor = *drm_minor_get_slot(dev, DRM_MINOR_PRIMARY);
    963 	if (!minor)
    964 		return;
    965 
    966 	name = kasprintf(GFP_KERNEL, "controlD%d", minor->index + 64);
    967 	if (!name)
    968 		return;
    969 
    970 	sysfs_remove_link(minor->kdev->kobj.parent, name);
    971 
    972 	kfree(name);
    973 }
    974 
    975 /**
    976  * drm_dev_register - Register DRM device
    977  * @dev: Device to register
    978  * @flags: Flags passed to the driver's .load() function
    979  *
    980  * Register the DRM device @dev with the system, advertise device to user-space
    981  * and start normal device operation. @dev must be initialized via drm_dev_init()
    982  * previously.
    983  *
    984  * Never call this twice on any device!
    985  *
    986  * NOTE: To ensure backward compatibility with existing drivers method this
    987  * function calls the &drm_driver.load method after registering the device
    988  * nodes, creating race conditions. Usage of the &drm_driver.load methods is
    989  * therefore deprecated, drivers must perform all initialization before calling
    990  * drm_dev_register().
    991  *
    992  * RETURNS:
    993  * 0 on success, negative error code on failure.
    994  */
    995 int drm_dev_register(struct drm_device *dev, unsigned long flags)
    996 {
    997 	struct drm_driver *driver = dev->driver;
    998 	int ret;
    999 
   1000 #ifndef __NetBSD__
   1001 	mutex_lock(&drm_global_mutex);
   1002 #endif
   1003 
   1004 	ret = drm_minor_register(dev, DRM_MINOR_RENDER);
   1005 	if (ret)
   1006 		goto err_minors;
   1007 
   1008 	ret = drm_minor_register(dev, DRM_MINOR_PRIMARY);
   1009 	if (ret)
   1010 		goto err_minors;
   1011 
   1012 	ret = create_compat_control_link(dev);
   1013 	if (ret)
   1014 		goto err_minors;
   1015 
   1016 	dev->registered = true;
   1017 
   1018 	if (dev->driver->load) {
   1019 		ret = dev->driver->load(dev, flags);
   1020 		if (ret)
   1021 			goto err_minors;
   1022 	}
   1023 
   1024 	if (drm_core_check_feature(dev, DRIVER_MODESET))
   1025 		drm_modeset_register_all(dev);
   1026 
   1027 	ret = 0;
   1028 
   1029 	DRM_INFO("Initialized %s %d.%d.%d %s for %s on minor %d\n",
   1030 		 driver->name, driver->major, driver->minor,
   1031 		 driver->patchlevel, driver->date,
   1032 		 dev->dev ? dev_name(dev->dev) : "virtual device",
   1033 		 dev->primary->index);
   1034 
   1035 	goto out_unlock;
   1036 
   1037 err_minors:
   1038 	remove_compat_control_link(dev);
   1039 	drm_minor_unregister(dev, DRM_MINOR_PRIMARY);
   1040 	drm_minor_unregister(dev, DRM_MINOR_RENDER);
   1041 out_unlock:
   1042 #ifndef __NetBSD__
   1043 	mutex_unlock(&drm_global_mutex);
   1044 #endif
   1045 	return ret;
   1046 }
   1047 EXPORT_SYMBOL(drm_dev_register);
   1048 
   1049 /**
   1050  * drm_dev_unregister - Unregister DRM device
   1051  * @dev: Device to unregister
   1052  *
   1053  * Unregister the DRM device from the system. This does the reverse of
   1054  * drm_dev_register() but does not deallocate the device. The caller must call
   1055  * drm_dev_put() to drop their final reference.
   1056  *
   1057  * A special form of unregistering for hotpluggable devices is drm_dev_unplug(),
   1058  * which can be called while there are still open users of @dev.
   1059  *
   1060  * This should be called first in the device teardown code to make sure
   1061  * userspace can't access the device instance any more.
   1062  */
   1063 void drm_dev_unregister(struct drm_device *dev)
   1064 {
   1065 	if (drm_core_check_feature(dev, DRIVER_LEGACY))
   1066 		drm_lastclose(dev);
   1067 
   1068 	dev->registered = false;
   1069 
   1070 	drm_client_dev_unregister(dev);
   1071 
   1072 	if (drm_core_check_feature(dev, DRIVER_MODESET))
   1073 		drm_modeset_unregister_all(dev);
   1074 
   1075 	if (dev->driver->unload)
   1076 		dev->driver->unload(dev);
   1077 
   1078 #ifndef __NetBSD__		/* Moved to drm_pci.  */
   1079 	if (dev->agp)
   1080 		drm_pci_agp_destroy(dev);
   1081 #endif
   1082 
   1083 	drm_legacy_rmmaps(dev);
   1084 
   1085 	remove_compat_control_link(dev);
   1086 	drm_minor_unregister(dev, DRM_MINOR_PRIMARY);
   1087 	drm_minor_unregister(dev, DRM_MINOR_RENDER);
   1088 }
   1089 EXPORT_SYMBOL(drm_dev_unregister);
   1090 
   1091 /**
   1092  * drm_dev_set_unique - Set the unique name of a DRM device
   1093  * @dev: device of which to set the unique name
   1094  * @name: unique name
   1095  *
   1096  * Sets the unique name of a DRM device using the specified string. This is
   1097  * already done by drm_dev_init(), drivers should only override the default
   1098  * unique name for backwards compatibility reasons.
   1099  *
   1100  * Return: 0 on success or a negative error code on failure.
   1101  */
   1102 int drm_dev_set_unique(struct drm_device *dev, const char *name)
   1103 {
   1104 	kfree(dev->unique);
   1105 	dev->unique = kstrdup(name, GFP_KERNEL);
   1106 
   1107 	return dev->unique ? 0 : -ENOMEM;
   1108 }
   1109 EXPORT_SYMBOL(drm_dev_set_unique);
   1110 
   1111 #ifndef __NetBSD__
   1112 
   1113 /*
   1114  * DRM Core
   1115  * The DRM core module initializes all global DRM objects and makes them
   1116  * available to drivers. Once setup, drivers can probe their respective
   1117  * devices.
   1118  * Currently, core management includes:
   1119  *  - The "DRM-Global" key/value database
   1120  *  - Global ID management for connectors
   1121  *  - DRM major number allocation
   1122  *  - DRM minor management
   1123  *  - DRM sysfs class
   1124  *  - DRM debugfs root
   1125  *
   1126  * Furthermore, the DRM core provides dynamic char-dev lookups. For each
   1127  * interface registered on a DRM device, you can request minor numbers from DRM
   1128  * core. DRM core takes care of major-number management and char-dev
   1129  * registration. A stub ->open() callback forwards any open() requests to the
   1130  * registered minor.
   1131  */
   1132 
   1133 static int drm_stub_open(struct inode *inode, struct file *filp)
   1134 {
   1135 	const struct file_operations *new_fops;
   1136 	struct drm_minor *minor;
   1137 	int err;
   1138 
   1139 	DRM_DEBUG("\n");
   1140 
   1141 	mutex_lock(&drm_global_mutex);
   1142 	minor = drm_minor_acquire(iminor(inode));
   1143 	if (IS_ERR(minor)) {
   1144 		err = PTR_ERR(minor);
   1145 		goto out_unlock;
   1146 	}
   1147 
   1148 	new_fops = fops_get(minor->dev->driver->fops);
   1149 	if (!new_fops) {
   1150 		err = -ENODEV;
   1151 		goto out_release;
   1152 	}
   1153 
   1154 	replace_fops(filp, new_fops);
   1155 	if (filp->f_op->open)
   1156 		err = filp->f_op->open(inode, filp);
   1157 	else
   1158 		err = 0;
   1159 
   1160 out_release:
   1161 	drm_minor_release(minor);
   1162 out_unlock:
   1163 	mutex_unlock(&drm_global_mutex);
   1164 	return err;
   1165 }
   1166 
   1167 static const struct file_operations drm_stub_fops = {
   1168 	.owner = THIS_MODULE,
   1169 	.open = drm_stub_open,
   1170 	.llseek = noop_llseek,
   1171 };
   1172 
   1173 static void drm_core_exit(void)
   1174 {
   1175 	unregister_chrdev(DRM_MAJOR, "drm");
   1176 	debugfs_remove(drm_debugfs_root);
   1177 	drm_sysfs_destroy();
   1178 	idr_destroy(&drm_minors_idr);
   1179 	drm_connector_ida_destroy();
   1180 }
   1181 
   1182 static int __init drm_core_init(void)
   1183 {
   1184 	int ret;
   1185 
   1186 	drm_connector_ida_init();
   1187 	idr_init(&drm_minors_idr);
   1188 
   1189 	ret = drm_sysfs_init();
   1190 	if (ret < 0) {
   1191 		DRM_ERROR("Cannot create DRM class: %d\n", ret);
   1192 		goto error;
   1193 	}
   1194 
   1195 	drm_debugfs_root = debugfs_create_dir("dri", NULL);
   1196 
   1197 	ret = register_chrdev(DRM_MAJOR, "drm", &drm_stub_fops);
   1198 	if (ret < 0)
   1199 		goto error;
   1200 
   1201 	drm_core_init_complete = true;
   1202 
   1203 	DRM_DEBUG("Initialized\n");
   1204 	return 0;
   1205 
   1206 error:
   1207 	drm_core_exit();
   1208 	return ret;
   1209 }
   1210 
   1211 module_init(drm_core_init);
   1212 module_exit(drm_core_exit);
   1213 
   1214 #endif
   1215