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