xref: /linux-6.15/drivers/base/class.c (revision 2df418cf)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * class.c - basic device class management
4  *
5  * Copyright (c) 2002-3 Patrick Mochel
6  * Copyright (c) 2002-3 Open Source Development Labs
7  * Copyright (c) 2003-2004 Greg Kroah-Hartman
8  * Copyright (c) 2003-2004 IBM Corp.
9  */
10 
11 #include <linux/device/class.h>
12 #include <linux/device.h>
13 #include <linux/module.h>
14 #include <linux/init.h>
15 #include <linux/string.h>
16 #include <linux/kdev_t.h>
17 #include <linux/err.h>
18 #include <linux/slab.h>
19 #include <linux/blkdev.h>
20 #include <linux/mutex.h>
21 #include "base.h"
22 
23 /* /sys/class */
24 static struct kset *class_kset;
25 
26 #define to_class_attr(_attr) container_of(_attr, struct class_attribute, attr)
27 
28 /**
29  * class_to_subsys - Turn a struct class into a struct subsys_private
30  *
31  * @class: pointer to the struct bus_type to look up
32  *
33  * The driver core internals need to work on the subsys_private structure, not
34  * the external struct class pointer.  This function walks the list of
35  * registered classes in the system and finds the matching one and returns the
36  * internal struct subsys_private that relates to that class.
37  *
38  * Note, the reference count of the return value is INCREMENTED if it is not
39  * NULL.  A call to subsys_put() must be done when finished with the pointer in
40  * order for it to be properly freed.
41  */
42 struct subsys_private *class_to_subsys(const struct class *class)
43 {
44 	struct subsys_private *sp = NULL;
45 	struct kobject *kobj;
46 
47 	if (!class || !class_kset)
48 		return NULL;
49 
50 	spin_lock(&class_kset->list_lock);
51 
52 	if (list_empty(&class_kset->list))
53 		goto done;
54 
55 	list_for_each_entry(kobj, &class_kset->list, entry) {
56 		struct kset *kset = container_of(kobj, struct kset, kobj);
57 
58 		sp = container_of_const(kset, struct subsys_private, subsys);
59 		if (sp->class == class)
60 			goto done;
61 	}
62 	sp = NULL;
63 done:
64 	sp = subsys_get(sp);
65 	spin_unlock(&class_kset->list_lock);
66 	return sp;
67 }
68 
69 static ssize_t class_attr_show(struct kobject *kobj, struct attribute *attr,
70 			       char *buf)
71 {
72 	struct class_attribute *class_attr = to_class_attr(attr);
73 	struct subsys_private *cp = to_subsys_private(kobj);
74 	ssize_t ret = -EIO;
75 
76 	if (class_attr->show)
77 		ret = class_attr->show(cp->class, class_attr, buf);
78 	return ret;
79 }
80 
81 static ssize_t class_attr_store(struct kobject *kobj, struct attribute *attr,
82 				const char *buf, size_t count)
83 {
84 	struct class_attribute *class_attr = to_class_attr(attr);
85 	struct subsys_private *cp = to_subsys_private(kobj);
86 	ssize_t ret = -EIO;
87 
88 	if (class_attr->store)
89 		ret = class_attr->store(cp->class, class_attr, buf, count);
90 	return ret;
91 }
92 
93 static void class_release(struct kobject *kobj)
94 {
95 	struct subsys_private *cp = to_subsys_private(kobj);
96 	struct class *class = cp->class;
97 
98 	pr_debug("class '%s': release.\n", class->name);
99 
100 	if (class->class_release)
101 		class->class_release(class);
102 	else
103 		pr_debug("class '%s' does not have a release() function, "
104 			 "be careful\n", class->name);
105 
106 	kfree(cp);
107 }
108 
109 static const struct kobj_ns_type_operations *class_child_ns_type(const struct kobject *kobj)
110 {
111 	const struct subsys_private *cp = to_subsys_private(kobj);
112 	struct class *class = cp->class;
113 
114 	return class->ns_type;
115 }
116 
117 static const struct sysfs_ops class_sysfs_ops = {
118 	.show	   = class_attr_show,
119 	.store	   = class_attr_store,
120 };
121 
122 static const struct kobj_type class_ktype = {
123 	.sysfs_ops	= &class_sysfs_ops,
124 	.release	= class_release,
125 	.child_ns_type	= class_child_ns_type,
126 };
127 
128 int class_create_file_ns(const struct class *cls, const struct class_attribute *attr,
129 			 const void *ns)
130 {
131 	struct subsys_private *sp = class_to_subsys(cls);
132 	int error;
133 
134 	if (!sp)
135 		return -EINVAL;
136 
137 	error = sysfs_create_file_ns(&sp->subsys.kobj, &attr->attr, ns);
138 	subsys_put(sp);
139 
140 	return error;
141 }
142 EXPORT_SYMBOL_GPL(class_create_file_ns);
143 
144 void class_remove_file_ns(const struct class *cls, const struct class_attribute *attr,
145 			  const void *ns)
146 {
147 	struct subsys_private *sp = class_to_subsys(cls);
148 
149 	if (!sp)
150 		return;
151 
152 	sysfs_remove_file_ns(&sp->subsys.kobj, &attr->attr, ns);
153 	subsys_put(sp);
154 }
155 EXPORT_SYMBOL_GPL(class_remove_file_ns);
156 
157 static struct device *klist_class_to_dev(struct klist_node *n)
158 {
159 	struct device_private *p = to_device_private_class(n);
160 	return p->device;
161 }
162 
163 static void klist_class_dev_get(struct klist_node *n)
164 {
165 	struct device *dev = klist_class_to_dev(n);
166 
167 	get_device(dev);
168 }
169 
170 static void klist_class_dev_put(struct klist_node *n)
171 {
172 	struct device *dev = klist_class_to_dev(n);
173 
174 	put_device(dev);
175 }
176 
177 int class_register(struct class *cls)
178 {
179 	struct subsys_private *cp;
180 	struct lock_class_key *key;
181 	int error;
182 
183 	pr_debug("device class '%s': registering\n", cls->name);
184 
185 	cp = kzalloc(sizeof(*cp), GFP_KERNEL);
186 	if (!cp)
187 		return -ENOMEM;
188 	klist_init(&cp->klist_devices, klist_class_dev_get, klist_class_dev_put);
189 	INIT_LIST_HEAD(&cp->interfaces);
190 	kset_init(&cp->glue_dirs);
191 	key = &cp->lock_key;
192 	lockdep_register_key(key);
193 	__mutex_init(&cp->mutex, "subsys mutex", key);
194 	error = kobject_set_name(&cp->subsys.kobj, "%s", cls->name);
195 	if (error) {
196 		kfree(cp);
197 		return error;
198 	}
199 
200 	/* set the default /sys/dev directory for devices of this class */
201 	if (!cls->dev_kobj)
202 		cls->dev_kobj = sysfs_dev_char_kobj;
203 
204 	cp->subsys.kobj.kset = class_kset;
205 	cp->subsys.kobj.ktype = &class_ktype;
206 	cp->class = cls;
207 
208 	error = kset_register(&cp->subsys);
209 	if (error)
210 		goto err_out;
211 
212 	error = sysfs_create_groups(&cp->subsys.kobj, cls->class_groups);
213 	if (error) {
214 		kobject_del(&cp->subsys.kobj);
215 		kfree_const(cp->subsys.kobj.name);
216 		goto err_out;
217 	}
218 	return 0;
219 
220 err_out:
221 	kfree(cp);
222 	return error;
223 }
224 EXPORT_SYMBOL_GPL(class_register);
225 
226 void class_unregister(const struct class *cls)
227 {
228 	struct subsys_private *sp = class_to_subsys(cls);
229 
230 	if (!sp)
231 		return;
232 
233 	pr_debug("device class '%s': unregistering\n", cls->name);
234 
235 	sysfs_remove_groups(&sp->subsys.kobj, cls->class_groups);
236 	kset_unregister(&sp->subsys);
237 	subsys_put(sp);
238 }
239 EXPORT_SYMBOL_GPL(class_unregister);
240 
241 static void class_create_release(struct class *cls)
242 {
243 	pr_debug("%s called for %s\n", __func__, cls->name);
244 	kfree(cls);
245 }
246 
247 /**
248  * class_create - create a struct class structure
249  * @name: pointer to a string for the name of this class.
250  *
251  * This is used to create a struct class pointer that can then be used
252  * in calls to device_create().
253  *
254  * Returns &struct class pointer on success, or ERR_PTR() on error.
255  *
256  * Note, the pointer created here is to be destroyed when finished by
257  * making a call to class_destroy().
258  */
259 struct class *class_create(const char *name)
260 {
261 	struct class *cls;
262 	int retval;
263 
264 	cls = kzalloc(sizeof(*cls), GFP_KERNEL);
265 	if (!cls) {
266 		retval = -ENOMEM;
267 		goto error;
268 	}
269 
270 	cls->name = name;
271 	cls->class_release = class_create_release;
272 
273 	retval = class_register(cls);
274 	if (retval)
275 		goto error;
276 
277 	return cls;
278 
279 error:
280 	kfree(cls);
281 	return ERR_PTR(retval);
282 }
283 EXPORT_SYMBOL_GPL(class_create);
284 
285 /**
286  * class_destroy - destroys a struct class structure
287  * @cls: pointer to the struct class that is to be destroyed
288  *
289  * Note, the pointer to be destroyed must have been created with a call
290  * to class_create().
291  */
292 void class_destroy(const struct class *cls)
293 {
294 	if (IS_ERR_OR_NULL(cls))
295 		return;
296 
297 	class_unregister(cls);
298 }
299 EXPORT_SYMBOL_GPL(class_destroy);
300 
301 /**
302  * class_dev_iter_init - initialize class device iterator
303  * @iter: class iterator to initialize
304  * @class: the class we wanna iterate over
305  * @start: the device to start iterating from, if any
306  * @type: device_type of the devices to iterate over, NULL for all
307  *
308  * Initialize class iterator @iter such that it iterates over devices
309  * of @class.  If @start is set, the list iteration will start there,
310  * otherwise if it is NULL, the iteration starts at the beginning of
311  * the list.
312  */
313 void class_dev_iter_init(struct class_dev_iter *iter, const struct class *class,
314 			 const struct device *start, const struct device_type *type)
315 {
316 	struct subsys_private *sp = class_to_subsys(class);
317 	struct klist_node *start_knode = NULL;
318 
319 	if (!sp)
320 		return;
321 
322 	if (start)
323 		start_knode = &start->p->knode_class;
324 	klist_iter_init_node(&sp->klist_devices, &iter->ki, start_knode);
325 	iter->type = type;
326 }
327 EXPORT_SYMBOL_GPL(class_dev_iter_init);
328 
329 /**
330  * class_dev_iter_next - iterate to the next device
331  * @iter: class iterator to proceed
332  *
333  * Proceed @iter to the next device and return it.  Returns NULL if
334  * iteration is complete.
335  *
336  * The returned device is referenced and won't be released till
337  * iterator is proceed to the next device or exited.  The caller is
338  * free to do whatever it wants to do with the device including
339  * calling back into class code.
340  */
341 struct device *class_dev_iter_next(struct class_dev_iter *iter)
342 {
343 	struct klist_node *knode;
344 	struct device *dev;
345 
346 	while (1) {
347 		knode = klist_next(&iter->ki);
348 		if (!knode)
349 			return NULL;
350 		dev = klist_class_to_dev(knode);
351 		if (!iter->type || iter->type == dev->type)
352 			return dev;
353 	}
354 }
355 EXPORT_SYMBOL_GPL(class_dev_iter_next);
356 
357 /**
358  * class_dev_iter_exit - finish iteration
359  * @iter: class iterator to finish
360  *
361  * Finish an iteration.  Always call this function after iteration is
362  * complete whether the iteration ran till the end or not.
363  */
364 void class_dev_iter_exit(struct class_dev_iter *iter)
365 {
366 	klist_iter_exit(&iter->ki);
367 }
368 EXPORT_SYMBOL_GPL(class_dev_iter_exit);
369 
370 /**
371  * class_for_each_device - device iterator
372  * @class: the class we're iterating
373  * @start: the device to start with in the list, if any.
374  * @data: data for the callback
375  * @fn: function to be called for each device
376  *
377  * Iterate over @class's list of devices, and call @fn for each,
378  * passing it @data.  If @start is set, the list iteration will start
379  * there, otherwise if it is NULL, the iteration starts at the
380  * beginning of the list.
381  *
382  * We check the return of @fn each time. If it returns anything
383  * other than 0, we break out and return that value.
384  *
385  * @fn is allowed to do anything including calling back into class
386  * code.  There's no locking restriction.
387  */
388 int class_for_each_device(const struct class *class, const struct device *start,
389 			  void *data, int (*fn)(struct device *, void *))
390 {
391 	struct subsys_private *sp = class_to_subsys(class);
392 	struct class_dev_iter iter;
393 	struct device *dev;
394 	int error = 0;
395 
396 	if (!class)
397 		return -EINVAL;
398 	if (!sp) {
399 		WARN(1, "%s called for class '%s' before it was initialized",
400 		     __func__, class->name);
401 		return -EINVAL;
402 	}
403 
404 	class_dev_iter_init(&iter, class, start, NULL);
405 	while ((dev = class_dev_iter_next(&iter))) {
406 		error = fn(dev, data);
407 		if (error)
408 			break;
409 	}
410 	class_dev_iter_exit(&iter);
411 	subsys_put(sp);
412 
413 	return error;
414 }
415 EXPORT_SYMBOL_GPL(class_for_each_device);
416 
417 /**
418  * class_find_device - device iterator for locating a particular device
419  * @class: the class we're iterating
420  * @start: Device to begin with
421  * @data: data for the match function
422  * @match: function to check device
423  *
424  * This is similar to the class_for_each_dev() function above, but it
425  * returns a reference to a device that is 'found' for later use, as
426  * determined by the @match callback.
427  *
428  * The callback should return 0 if the device doesn't match and non-zero
429  * if it does.  If the callback returns non-zero, this function will
430  * return to the caller and not iterate over any more devices.
431  *
432  * Note, you will need to drop the reference with put_device() after use.
433  *
434  * @match is allowed to do anything including calling back into class
435  * code.  There's no locking restriction.
436  */
437 struct device *class_find_device(const struct class *class, const struct device *start,
438 				 const void *data,
439 				 int (*match)(struct device *, const void *))
440 {
441 	struct subsys_private *sp = class_to_subsys(class);
442 	struct class_dev_iter iter;
443 	struct device *dev;
444 
445 	if (!class)
446 		return NULL;
447 	if (!sp) {
448 		WARN(1, "%s called for class '%s' before it was initialized",
449 		     __func__, class->name);
450 		return NULL;
451 	}
452 
453 	class_dev_iter_init(&iter, class, start, NULL);
454 	while ((dev = class_dev_iter_next(&iter))) {
455 		if (match(dev, data)) {
456 			get_device(dev);
457 			break;
458 		}
459 	}
460 	class_dev_iter_exit(&iter);
461 	subsys_put(sp);
462 
463 	return dev;
464 }
465 EXPORT_SYMBOL_GPL(class_find_device);
466 
467 int class_interface_register(struct class_interface *class_intf)
468 {
469 	struct subsys_private *sp;
470 	const struct class *parent;
471 	struct class_dev_iter iter;
472 	struct device *dev;
473 
474 	if (!class_intf || !class_intf->class)
475 		return -ENODEV;
476 
477 	parent = class_intf->class;
478 	sp = class_to_subsys(parent);
479 	if (!sp)
480 		return -EINVAL;
481 
482 	/*
483 	 * Reference in sp is now incremented and will be dropped when
484 	 * the interface is removed in the call to class_interface_unregister()
485 	 */
486 
487 	mutex_lock(&sp->mutex);
488 	list_add_tail(&class_intf->node, &sp->interfaces);
489 	if (class_intf->add_dev) {
490 		class_dev_iter_init(&iter, parent, NULL, NULL);
491 		while ((dev = class_dev_iter_next(&iter)))
492 			class_intf->add_dev(dev, class_intf);
493 		class_dev_iter_exit(&iter);
494 	}
495 	mutex_unlock(&sp->mutex);
496 
497 	return 0;
498 }
499 EXPORT_SYMBOL_GPL(class_interface_register);
500 
501 void class_interface_unregister(struct class_interface *class_intf)
502 {
503 	struct subsys_private *sp;
504 	struct class *parent = class_intf->class;
505 	struct class_dev_iter iter;
506 	struct device *dev;
507 
508 	if (!parent)
509 		return;
510 
511 	sp = class_to_subsys(parent);
512 	if (!sp)
513 		return;
514 
515 	mutex_lock(&sp->mutex);
516 	list_del_init(&class_intf->node);
517 	if (class_intf->remove_dev) {
518 		class_dev_iter_init(&iter, parent, NULL, NULL);
519 		while ((dev = class_dev_iter_next(&iter)))
520 			class_intf->remove_dev(dev, class_intf);
521 		class_dev_iter_exit(&iter);
522 	}
523 	mutex_unlock(&sp->mutex);
524 
525 	/*
526 	 * Decrement the reference count twice, once for the class_to_subsys()
527 	 * call in the start of this function, and the second one from the
528 	 * reference increment in class_interface_register()
529 	 */
530 	subsys_put(sp);
531 	subsys_put(sp);
532 }
533 EXPORT_SYMBOL_GPL(class_interface_unregister);
534 
535 ssize_t show_class_attr_string(const struct class *class,
536 			       const struct class_attribute *attr, char *buf)
537 {
538 	struct class_attribute_string *cs;
539 
540 	cs = container_of(attr, struct class_attribute_string, attr);
541 	return sysfs_emit(buf, "%s\n", cs->str);
542 }
543 
544 EXPORT_SYMBOL_GPL(show_class_attr_string);
545 
546 struct class_compat {
547 	struct kobject *kobj;
548 };
549 
550 /**
551  * class_compat_register - register a compatibility class
552  * @name: the name of the class
553  *
554  * Compatibility class are meant as a temporary user-space compatibility
555  * workaround when converting a family of class devices to a bus devices.
556  */
557 struct class_compat *class_compat_register(const char *name)
558 {
559 	struct class_compat *cls;
560 
561 	cls = kmalloc(sizeof(struct class_compat), GFP_KERNEL);
562 	if (!cls)
563 		return NULL;
564 	cls->kobj = kobject_create_and_add(name, &class_kset->kobj);
565 	if (!cls->kobj) {
566 		kfree(cls);
567 		return NULL;
568 	}
569 	return cls;
570 }
571 EXPORT_SYMBOL_GPL(class_compat_register);
572 
573 /**
574  * class_compat_unregister - unregister a compatibility class
575  * @cls: the class to unregister
576  */
577 void class_compat_unregister(struct class_compat *cls)
578 {
579 	kobject_put(cls->kobj);
580 	kfree(cls);
581 }
582 EXPORT_SYMBOL_GPL(class_compat_unregister);
583 
584 /**
585  * class_compat_create_link - create a compatibility class device link to
586  *			      a bus device
587  * @cls: the compatibility class
588  * @dev: the target bus device
589  * @device_link: an optional device to which a "device" link should be created
590  */
591 int class_compat_create_link(struct class_compat *cls, struct device *dev,
592 			     struct device *device_link)
593 {
594 	int error;
595 
596 	error = sysfs_create_link(cls->kobj, &dev->kobj, dev_name(dev));
597 	if (error)
598 		return error;
599 
600 	/*
601 	 * Optionally add a "device" link (typically to the parent), as a
602 	 * class device would have one and we want to provide as much
603 	 * backwards compatibility as possible.
604 	 */
605 	if (device_link) {
606 		error = sysfs_create_link(&dev->kobj, &device_link->kobj,
607 					  "device");
608 		if (error)
609 			sysfs_remove_link(cls->kobj, dev_name(dev));
610 	}
611 
612 	return error;
613 }
614 EXPORT_SYMBOL_GPL(class_compat_create_link);
615 
616 /**
617  * class_compat_remove_link - remove a compatibility class device link to
618  *			      a bus device
619  * @cls: the compatibility class
620  * @dev: the target bus device
621  * @device_link: an optional device to which a "device" link was previously
622  * 		 created
623  */
624 void class_compat_remove_link(struct class_compat *cls, struct device *dev,
625 			      struct device *device_link)
626 {
627 	if (device_link)
628 		sysfs_remove_link(&dev->kobj, "device");
629 	sysfs_remove_link(cls->kobj, dev_name(dev));
630 }
631 EXPORT_SYMBOL_GPL(class_compat_remove_link);
632 
633 /**
634  * class_is_registered - determine if at this moment in time, a class is
635  *			 registered in the driver core or not.
636  * @class: the class to check
637  *
638  * Returns a boolean to state if the class is registered in the driver core
639  * or not.  Note that the value could switch right after this call is made,
640  * so only use this in places where you "know" it is safe to do so (usually
641  * to determine if the specific class has been registered yet or not).
642  *
643  * Be careful in using this.
644  */
645 bool class_is_registered(const struct class *class)
646 {
647 	struct subsys_private *sp = class_to_subsys(class);
648 	bool is_initialized = false;
649 
650 	if (sp) {
651 		is_initialized = true;
652 		subsys_put(sp);
653 	}
654 	return is_initialized;
655 }
656 EXPORT_SYMBOL_GPL(class_is_registered);
657 
658 int __init classes_init(void)
659 {
660 	class_kset = kset_create_and_add("class", NULL, NULL);
661 	if (!class_kset)
662 		return -ENOMEM;
663 	return 0;
664 }
665