xref: /openbmc/linux/fs/char_dev.c (revision 7211ec63)
1 /*
2  *  linux/fs/char_dev.c
3  *
4  *  Copyright (C) 1991, 1992  Linus Torvalds
5  */
6 
7 #include <linux/init.h>
8 #include <linux/fs.h>
9 #include <linux/kdev_t.h>
10 #include <linux/slab.h>
11 #include <linux/string.h>
12 
13 #include <linux/major.h>
14 #include <linux/errno.h>
15 #include <linux/module.h>
16 #include <linux/seq_file.h>
17 
18 #include <linux/kobject.h>
19 #include <linux/kobj_map.h>
20 #include <linux/cdev.h>
21 #include <linux/mutex.h>
22 #include <linux/backing-dev.h>
23 #include <linux/tty.h>
24 
25 #include "internal.h"
26 
27 static struct kobj_map *cdev_map;
28 
29 static DEFINE_MUTEX(chrdevs_lock);
30 
31 #define CHRDEV_MAJOR_HASH_SIZE 255
32 
33 static struct char_device_struct {
34 	struct char_device_struct *next;
35 	unsigned int major;
36 	unsigned int baseminor;
37 	int minorct;
38 	char name[64];
39 	struct cdev *cdev;		/* will die */
40 } *chrdevs[CHRDEV_MAJOR_HASH_SIZE];
41 
42 /* index in the above */
43 static inline int major_to_index(unsigned major)
44 {
45 	return major % CHRDEV_MAJOR_HASH_SIZE;
46 }
47 
48 #ifdef CONFIG_PROC_FS
49 
50 void chrdev_show(struct seq_file *f, off_t offset)
51 {
52 	struct char_device_struct *cd;
53 
54 	mutex_lock(&chrdevs_lock);
55 	for (cd = chrdevs[major_to_index(offset)]; cd; cd = cd->next) {
56 		if (cd->major == offset)
57 			seq_printf(f, "%3d %s\n", cd->major, cd->name);
58 	}
59 	mutex_unlock(&chrdevs_lock);
60 }
61 
62 #endif /* CONFIG_PROC_FS */
63 
64 static int find_dynamic_major(void)
65 {
66 	int i;
67 	struct char_device_struct *cd;
68 
69 	for (i = ARRAY_SIZE(chrdevs)-1; i > CHRDEV_MAJOR_DYN_END; i--) {
70 		if (chrdevs[i] == NULL)
71 			return i;
72 	}
73 
74 	for (i = CHRDEV_MAJOR_DYN_EXT_START;
75 	     i > CHRDEV_MAJOR_DYN_EXT_END; i--) {
76 		for (cd = chrdevs[major_to_index(i)]; cd; cd = cd->next)
77 			if (cd->major == i)
78 				break;
79 
80 		if (cd == NULL || cd->major != i)
81 			return i;
82 	}
83 
84 	return -EBUSY;
85 }
86 
87 /*
88  * Register a single major with a specified minor range.
89  *
90  * If major == 0 this functions will dynamically allocate a major and return
91  * its number.
92  *
93  * If major > 0 this function will attempt to reserve the passed range of
94  * minors and will return zero on success.
95  *
96  * Returns a -ve errno on failure.
97  */
98 static struct char_device_struct *
99 __register_chrdev_region(unsigned int major, unsigned int baseminor,
100 			   int minorct, const char *name)
101 {
102 	struct char_device_struct *cd, **cp;
103 	int ret = 0;
104 	int i;
105 
106 	cd = kzalloc(sizeof(struct char_device_struct), GFP_KERNEL);
107 	if (cd == NULL)
108 		return ERR_PTR(-ENOMEM);
109 
110 	mutex_lock(&chrdevs_lock);
111 
112 	if (major == 0) {
113 		ret = find_dynamic_major();
114 		if (ret < 0) {
115 			pr_err("CHRDEV \"%s\" dynamic allocation region is full\n",
116 			       name);
117 			goto out;
118 		}
119 		major = ret;
120 	}
121 
122 	if (major >= CHRDEV_MAJOR_MAX) {
123 		pr_err("CHRDEV \"%s\" major requested (%d) is greater than the maximum (%d)\n",
124 		       name, major, CHRDEV_MAJOR_MAX);
125 		ret = -EINVAL;
126 		goto out;
127 	}
128 
129 	cd->major = major;
130 	cd->baseminor = baseminor;
131 	cd->minorct = minorct;
132 	strlcpy(cd->name, name, sizeof(cd->name));
133 
134 	i = major_to_index(major);
135 
136 	for (cp = &chrdevs[i]; *cp; cp = &(*cp)->next)
137 		if ((*cp)->major > major ||
138 		    ((*cp)->major == major &&
139 		     (((*cp)->baseminor >= baseminor) ||
140 		      ((*cp)->baseminor + (*cp)->minorct > baseminor))))
141 			break;
142 
143 	/* Check for overlapping minor ranges.  */
144 	if (*cp && (*cp)->major == major) {
145 		int old_min = (*cp)->baseminor;
146 		int old_max = (*cp)->baseminor + (*cp)->minorct - 1;
147 		int new_min = baseminor;
148 		int new_max = baseminor + minorct - 1;
149 
150 		/* New driver overlaps from the left.  */
151 		if (new_max >= old_min && new_max <= old_max) {
152 			ret = -EBUSY;
153 			goto out;
154 		}
155 
156 		/* New driver overlaps from the right.  */
157 		if (new_min <= old_max && new_min >= old_min) {
158 			ret = -EBUSY;
159 			goto out;
160 		}
161 	}
162 
163 	cd->next = *cp;
164 	*cp = cd;
165 	mutex_unlock(&chrdevs_lock);
166 	return cd;
167 out:
168 	mutex_unlock(&chrdevs_lock);
169 	kfree(cd);
170 	return ERR_PTR(ret);
171 }
172 
173 static struct char_device_struct *
174 __unregister_chrdev_region(unsigned major, unsigned baseminor, int minorct)
175 {
176 	struct char_device_struct *cd = NULL, **cp;
177 	int i = major_to_index(major);
178 
179 	mutex_lock(&chrdevs_lock);
180 	for (cp = &chrdevs[i]; *cp; cp = &(*cp)->next)
181 		if ((*cp)->major == major &&
182 		    (*cp)->baseminor == baseminor &&
183 		    (*cp)->minorct == minorct)
184 			break;
185 	if (*cp) {
186 		cd = *cp;
187 		*cp = cd->next;
188 	}
189 	mutex_unlock(&chrdevs_lock);
190 	return cd;
191 }
192 
193 /**
194  * register_chrdev_region() - register a range of device numbers
195  * @from: the first in the desired range of device numbers; must include
196  *        the major number.
197  * @count: the number of consecutive device numbers required
198  * @name: the name of the device or driver.
199  *
200  * Return value is zero on success, a negative error code on failure.
201  */
202 int register_chrdev_region(dev_t from, unsigned count, const char *name)
203 {
204 	struct char_device_struct *cd;
205 	dev_t to = from + count;
206 	dev_t n, next;
207 
208 	for (n = from; n < to; n = next) {
209 		next = MKDEV(MAJOR(n)+1, 0);
210 		if (next > to)
211 			next = to;
212 		cd = __register_chrdev_region(MAJOR(n), MINOR(n),
213 			       next - n, name);
214 		if (IS_ERR(cd))
215 			goto fail;
216 	}
217 	return 0;
218 fail:
219 	to = n;
220 	for (n = from; n < to; n = next) {
221 		next = MKDEV(MAJOR(n)+1, 0);
222 		kfree(__unregister_chrdev_region(MAJOR(n), MINOR(n), next - n));
223 	}
224 	return PTR_ERR(cd);
225 }
226 
227 /**
228  * alloc_chrdev_region() - register a range of char device numbers
229  * @dev: output parameter for first assigned number
230  * @baseminor: first of the requested range of minor numbers
231  * @count: the number of minor numbers required
232  * @name: the name of the associated device or driver
233  *
234  * Allocates a range of char device numbers.  The major number will be
235  * chosen dynamically, and returned (along with the first minor number)
236  * in @dev.  Returns zero or a negative error code.
237  */
238 int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count,
239 			const char *name)
240 {
241 	struct char_device_struct *cd;
242 	cd = __register_chrdev_region(0, baseminor, count, name);
243 	if (IS_ERR(cd))
244 		return PTR_ERR(cd);
245 	*dev = MKDEV(cd->major, cd->baseminor);
246 	return 0;
247 }
248 
249 /**
250  * __register_chrdev() - create and register a cdev occupying a range of minors
251  * @major: major device number or 0 for dynamic allocation
252  * @baseminor: first of the requested range of minor numbers
253  * @count: the number of minor numbers required
254  * @name: name of this range of devices
255  * @fops: file operations associated with this devices
256  *
257  * If @major == 0 this functions will dynamically allocate a major and return
258  * its number.
259  *
260  * If @major > 0 this function will attempt to reserve a device with the given
261  * major number and will return zero on success.
262  *
263  * Returns a -ve errno on failure.
264  *
265  * The name of this device has nothing to do with the name of the device in
266  * /dev. It only helps to keep track of the different owners of devices. If
267  * your module name has only one type of devices it's ok to use e.g. the name
268  * of the module here.
269  */
270 int __register_chrdev(unsigned int major, unsigned int baseminor,
271 		      unsigned int count, const char *name,
272 		      const struct file_operations *fops)
273 {
274 	struct char_device_struct *cd;
275 	struct cdev *cdev;
276 	int err = -ENOMEM;
277 
278 	cd = __register_chrdev_region(major, baseminor, count, name);
279 	if (IS_ERR(cd))
280 		return PTR_ERR(cd);
281 
282 	cdev = cdev_alloc();
283 	if (!cdev)
284 		goto out2;
285 
286 	cdev->owner = fops->owner;
287 	cdev->ops = fops;
288 	kobject_set_name(&cdev->kobj, "%s", name);
289 
290 	err = cdev_add(cdev, MKDEV(cd->major, baseminor), count);
291 	if (err)
292 		goto out;
293 
294 	cd->cdev = cdev;
295 
296 	return major ? 0 : cd->major;
297 out:
298 	kobject_put(&cdev->kobj);
299 out2:
300 	kfree(__unregister_chrdev_region(cd->major, baseminor, count));
301 	return err;
302 }
303 
304 /**
305  * unregister_chrdev_region() - unregister a range of device numbers
306  * @from: the first in the range of numbers to unregister
307  * @count: the number of device numbers to unregister
308  *
309  * This function will unregister a range of @count device numbers,
310  * starting with @from.  The caller should normally be the one who
311  * allocated those numbers in the first place...
312  */
313 void unregister_chrdev_region(dev_t from, unsigned count)
314 {
315 	dev_t to = from + count;
316 	dev_t n, next;
317 
318 	for (n = from; n < to; n = next) {
319 		next = MKDEV(MAJOR(n)+1, 0);
320 		if (next > to)
321 			next = to;
322 		kfree(__unregister_chrdev_region(MAJOR(n), MINOR(n), next - n));
323 	}
324 }
325 
326 /**
327  * __unregister_chrdev - unregister and destroy a cdev
328  * @major: major device number
329  * @baseminor: first of the range of minor numbers
330  * @count: the number of minor numbers this cdev is occupying
331  * @name: name of this range of devices
332  *
333  * Unregister and destroy the cdev occupying the region described by
334  * @major, @baseminor and @count.  This function undoes what
335  * __register_chrdev() did.
336  */
337 void __unregister_chrdev(unsigned int major, unsigned int baseminor,
338 			 unsigned int count, const char *name)
339 {
340 	struct char_device_struct *cd;
341 
342 	cd = __unregister_chrdev_region(major, baseminor, count);
343 	if (cd && cd->cdev)
344 		cdev_del(cd->cdev);
345 	kfree(cd);
346 }
347 
348 static DEFINE_SPINLOCK(cdev_lock);
349 
350 static struct kobject *cdev_get(struct cdev *p)
351 {
352 	struct module *owner = p->owner;
353 	struct kobject *kobj;
354 
355 	if (owner && !try_module_get(owner))
356 		return NULL;
357 	kobj = kobject_get(&p->kobj);
358 	if (!kobj)
359 		module_put(owner);
360 	return kobj;
361 }
362 
363 void cdev_put(struct cdev *p)
364 {
365 	if (p) {
366 		struct module *owner = p->owner;
367 		kobject_put(&p->kobj);
368 		module_put(owner);
369 	}
370 }
371 
372 /*
373  * Called every time a character special file is opened
374  */
375 static int chrdev_open(struct inode *inode, struct file *filp)
376 {
377 	const struct file_operations *fops;
378 	struct cdev *p;
379 	struct cdev *new = NULL;
380 	int ret = 0;
381 
382 	spin_lock(&cdev_lock);
383 	p = inode->i_cdev;
384 	if (!p) {
385 		struct kobject *kobj;
386 		int idx;
387 		spin_unlock(&cdev_lock);
388 		kobj = kobj_lookup(cdev_map, inode->i_rdev, &idx);
389 		if (!kobj)
390 			return -ENXIO;
391 		new = container_of(kobj, struct cdev, kobj);
392 		spin_lock(&cdev_lock);
393 		/* Check i_cdev again in case somebody beat us to it while
394 		   we dropped the lock. */
395 		p = inode->i_cdev;
396 		if (!p) {
397 			inode->i_cdev = p = new;
398 			list_add(&inode->i_devices, &p->list);
399 			new = NULL;
400 		} else if (!cdev_get(p))
401 			ret = -ENXIO;
402 	} else if (!cdev_get(p))
403 		ret = -ENXIO;
404 	spin_unlock(&cdev_lock);
405 	cdev_put(new);
406 	if (ret)
407 		return ret;
408 
409 	ret = -ENXIO;
410 	fops = fops_get(p->ops);
411 	if (!fops)
412 		goto out_cdev_put;
413 
414 	replace_fops(filp, fops);
415 	if (filp->f_op->open) {
416 		ret = filp->f_op->open(inode, filp);
417 		if (ret)
418 			goto out_cdev_put;
419 	}
420 
421 	return 0;
422 
423  out_cdev_put:
424 	cdev_put(p);
425 	return ret;
426 }
427 
428 void cd_forget(struct inode *inode)
429 {
430 	spin_lock(&cdev_lock);
431 	list_del_init(&inode->i_devices);
432 	inode->i_cdev = NULL;
433 	inode->i_mapping = &inode->i_data;
434 	spin_unlock(&cdev_lock);
435 }
436 
437 static void cdev_purge(struct cdev *cdev)
438 {
439 	spin_lock(&cdev_lock);
440 	while (!list_empty(&cdev->list)) {
441 		struct inode *inode;
442 		inode = container_of(cdev->list.next, struct inode, i_devices);
443 		list_del_init(&inode->i_devices);
444 		inode->i_cdev = NULL;
445 	}
446 	spin_unlock(&cdev_lock);
447 }
448 
449 /*
450  * Dummy default file-operations: the only thing this does
451  * is contain the open that then fills in the correct operations
452  * depending on the special file...
453  */
454 const struct file_operations def_chr_fops = {
455 	.open = chrdev_open,
456 	.llseek = noop_llseek,
457 };
458 
459 static struct kobject *exact_match(dev_t dev, int *part, void *data)
460 {
461 	struct cdev *p = data;
462 	return &p->kobj;
463 }
464 
465 static int exact_lock(dev_t dev, void *data)
466 {
467 	struct cdev *p = data;
468 	return cdev_get(p) ? 0 : -1;
469 }
470 
471 /**
472  * cdev_add() - add a char device to the system
473  * @p: the cdev structure for the device
474  * @dev: the first device number for which this device is responsible
475  * @count: the number of consecutive minor numbers corresponding to this
476  *         device
477  *
478  * cdev_add() adds the device represented by @p to the system, making it
479  * live immediately.  A negative error code is returned on failure.
480  */
481 int cdev_add(struct cdev *p, dev_t dev, unsigned count)
482 {
483 	int error;
484 
485 	p->dev = dev;
486 	p->count = count;
487 
488 	error = kobj_map(cdev_map, dev, count, NULL,
489 			 exact_match, exact_lock, p);
490 	if (error)
491 		return error;
492 
493 	kobject_get(p->kobj.parent);
494 
495 	return 0;
496 }
497 
498 /**
499  * cdev_set_parent() - set the parent kobject for a char device
500  * @p: the cdev structure
501  * @kobj: the kobject to take a reference to
502  *
503  * cdev_set_parent() sets a parent kobject which will be referenced
504  * appropriately so the parent is not freed before the cdev. This
505  * should be called before cdev_add.
506  */
507 void cdev_set_parent(struct cdev *p, struct kobject *kobj)
508 {
509 	WARN_ON(!kobj->state_initialized);
510 	p->kobj.parent = kobj;
511 }
512 
513 /**
514  * cdev_device_add() - add a char device and it's corresponding
515  *	struct device, linkink
516  * @dev: the device structure
517  * @cdev: the cdev structure
518  *
519  * cdev_device_add() adds the char device represented by @cdev to the system,
520  * just as cdev_add does. It then adds @dev to the system using device_add
521  * The dev_t for the char device will be taken from the struct device which
522  * needs to be initialized first. This helper function correctly takes a
523  * reference to the parent device so the parent will not get released until
524  * all references to the cdev are released.
525  *
526  * This helper uses dev->devt for the device number. If it is not set
527  * it will not add the cdev and it will be equivalent to device_add.
528  *
529  * This function should be used whenever the struct cdev and the
530  * struct device are members of the same structure whose lifetime is
531  * managed by the struct device.
532  *
533  * NOTE: Callers must assume that userspace was able to open the cdev and
534  * can call cdev fops callbacks at any time, even if this function fails.
535  */
536 int cdev_device_add(struct cdev *cdev, struct device *dev)
537 {
538 	int rc = 0;
539 
540 	if (dev->devt) {
541 		cdev_set_parent(cdev, &dev->kobj);
542 
543 		rc = cdev_add(cdev, dev->devt, 1);
544 		if (rc)
545 			return rc;
546 	}
547 
548 	rc = device_add(dev);
549 	if (rc)
550 		cdev_del(cdev);
551 
552 	return rc;
553 }
554 
555 /**
556  * cdev_device_del() - inverse of cdev_device_add
557  * @dev: the device structure
558  * @cdev: the cdev structure
559  *
560  * cdev_device_del() is a helper function to call cdev_del and device_del.
561  * It should be used whenever cdev_device_add is used.
562  *
563  * If dev->devt is not set it will not remove the cdev and will be equivalent
564  * to device_del.
565  *
566  * NOTE: This guarantees that associated sysfs callbacks are not running
567  * or runnable, however any cdevs already open will remain and their fops
568  * will still be callable even after this function returns.
569  */
570 void cdev_device_del(struct cdev *cdev, struct device *dev)
571 {
572 	device_del(dev);
573 	if (dev->devt)
574 		cdev_del(cdev);
575 }
576 
577 static void cdev_unmap(dev_t dev, unsigned count)
578 {
579 	kobj_unmap(cdev_map, dev, count);
580 }
581 
582 /**
583  * cdev_del() - remove a cdev from the system
584  * @p: the cdev structure to be removed
585  *
586  * cdev_del() removes @p from the system, possibly freeing the structure
587  * itself.
588  *
589  * NOTE: This guarantees that cdev device will no longer be able to be
590  * opened, however any cdevs already open will remain and their fops will
591  * still be callable even after cdev_del returns.
592  */
593 void cdev_del(struct cdev *p)
594 {
595 	cdev_unmap(p->dev, p->count);
596 	kobject_put(&p->kobj);
597 }
598 
599 
600 static void cdev_default_release(struct kobject *kobj)
601 {
602 	struct cdev *p = container_of(kobj, struct cdev, kobj);
603 	struct kobject *parent = kobj->parent;
604 
605 	cdev_purge(p);
606 	kobject_put(parent);
607 }
608 
609 static void cdev_dynamic_release(struct kobject *kobj)
610 {
611 	struct cdev *p = container_of(kobj, struct cdev, kobj);
612 	struct kobject *parent = kobj->parent;
613 
614 	cdev_purge(p);
615 	kfree(p);
616 	kobject_put(parent);
617 }
618 
619 static struct kobj_type ktype_cdev_default = {
620 	.release	= cdev_default_release,
621 };
622 
623 static struct kobj_type ktype_cdev_dynamic = {
624 	.release	= cdev_dynamic_release,
625 };
626 
627 /**
628  * cdev_alloc() - allocate a cdev structure
629  *
630  * Allocates and returns a cdev structure, or NULL on failure.
631  */
632 struct cdev *cdev_alloc(void)
633 {
634 	struct cdev *p = kzalloc(sizeof(struct cdev), GFP_KERNEL);
635 	if (p) {
636 		INIT_LIST_HEAD(&p->list);
637 		kobject_init(&p->kobj, &ktype_cdev_dynamic);
638 	}
639 	return p;
640 }
641 
642 /**
643  * cdev_init() - initialize a cdev structure
644  * @cdev: the structure to initialize
645  * @fops: the file_operations for this device
646  *
647  * Initializes @cdev, remembering @fops, making it ready to add to the
648  * system with cdev_add().
649  */
650 void cdev_init(struct cdev *cdev, const struct file_operations *fops)
651 {
652 	memset(cdev, 0, sizeof *cdev);
653 	INIT_LIST_HEAD(&cdev->list);
654 	kobject_init(&cdev->kobj, &ktype_cdev_default);
655 	cdev->ops = fops;
656 }
657 
658 static struct kobject *base_probe(dev_t dev, int *part, void *data)
659 {
660 	if (request_module("char-major-%d-%d", MAJOR(dev), MINOR(dev)) > 0)
661 		/* Make old-style 2.4 aliases work */
662 		request_module("char-major-%d", MAJOR(dev));
663 	return NULL;
664 }
665 
666 void __init chrdev_init(void)
667 {
668 	cdev_map = kobj_map_init(base_probe, &chrdevs_lock);
669 }
670 
671 
672 /* Let modules do char dev stuff */
673 EXPORT_SYMBOL(register_chrdev_region);
674 EXPORT_SYMBOL(unregister_chrdev_region);
675 EXPORT_SYMBOL(alloc_chrdev_region);
676 EXPORT_SYMBOL(cdev_init);
677 EXPORT_SYMBOL(cdev_alloc);
678 EXPORT_SYMBOL(cdev_del);
679 EXPORT_SYMBOL(cdev_add);
680 EXPORT_SYMBOL(cdev_set_parent);
681 EXPORT_SYMBOL(cdev_device_add);
682 EXPORT_SYMBOL(cdev_device_del);
683 EXPORT_SYMBOL(__register_chrdev);
684 EXPORT_SYMBOL(__unregister_chrdev);
685