xref: /linux/lib/kobject.c (revision a8b70ccf10e38775785d9cb12ead916474549f99)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * kobject.c - library routines for handling generic kernel objects
4  *
5  * Copyright (c) 2002-2003 Patrick Mochel <mochel@osdl.org>
6  * Copyright (c) 2006-2007 Greg Kroah-Hartman <greg@kroah.com>
7  * Copyright (c) 2006-2007 Novell Inc.
8  *
9  * Please see the file Documentation/kobject.txt for critical information
10  * about using the kobject interface.
11  */
12 
13 #include <linux/kobject.h>
14 #include <linux/string.h>
15 #include <linux/export.h>
16 #include <linux/stat.h>
17 #include <linux/slab.h>
18 #include <linux/random.h>
19 
20 /**
21  * kobject_namespace - return @kobj's namespace tag
22  * @kobj: kobject in question
23  *
24  * Returns namespace tag of @kobj if its parent has namespace ops enabled
25  * and thus @kobj should have a namespace tag associated with it.  Returns
26  * %NULL otherwise.
27  */
28 const void *kobject_namespace(struct kobject *kobj)
29 {
30 	const struct kobj_ns_type_operations *ns_ops = kobj_ns_ops(kobj);
31 
32 	if (!ns_ops || ns_ops->type == KOBJ_NS_TYPE_NONE)
33 		return NULL;
34 
35 	return kobj->ktype->namespace(kobj);
36 }
37 
38 /*
39  * populate_dir - populate directory with attributes.
40  * @kobj: object we're working on.
41  *
42  * Most subsystems have a set of default attributes that are associated
43  * with an object that registers with them.  This is a helper called during
44  * object registration that loops through the default attributes of the
45  * subsystem and creates attributes files for them in sysfs.
46  */
47 static int populate_dir(struct kobject *kobj)
48 {
49 	struct kobj_type *t = get_ktype(kobj);
50 	struct attribute *attr;
51 	int error = 0;
52 	int i;
53 
54 	if (t && t->default_attrs) {
55 		for (i = 0; (attr = t->default_attrs[i]) != NULL; i++) {
56 			error = sysfs_create_file(kobj, attr);
57 			if (error)
58 				break;
59 		}
60 	}
61 	return error;
62 }
63 
64 static int create_dir(struct kobject *kobj)
65 {
66 	const struct kobj_ns_type_operations *ops;
67 	int error;
68 
69 	error = sysfs_create_dir_ns(kobj, kobject_namespace(kobj));
70 	if (error)
71 		return error;
72 
73 	error = populate_dir(kobj);
74 	if (error) {
75 		sysfs_remove_dir(kobj);
76 		return error;
77 	}
78 
79 	/*
80 	 * @kobj->sd may be deleted by an ancestor going away.  Hold an
81 	 * extra reference so that it stays until @kobj is gone.
82 	 */
83 	sysfs_get(kobj->sd);
84 
85 	/*
86 	 * If @kobj has ns_ops, its children need to be filtered based on
87 	 * their namespace tags.  Enable namespace support on @kobj->sd.
88 	 */
89 	ops = kobj_child_ns_ops(kobj);
90 	if (ops) {
91 		BUG_ON(ops->type <= KOBJ_NS_TYPE_NONE);
92 		BUG_ON(ops->type >= KOBJ_NS_TYPES);
93 		BUG_ON(!kobj_ns_type_registered(ops->type));
94 
95 		sysfs_enable_ns(kobj->sd);
96 	}
97 
98 	return 0;
99 }
100 
101 static int get_kobj_path_length(struct kobject *kobj)
102 {
103 	int length = 1;
104 	struct kobject *parent = kobj;
105 
106 	/* walk up the ancestors until we hit the one pointing to the
107 	 * root.
108 	 * Add 1 to strlen for leading '/' of each level.
109 	 */
110 	do {
111 		if (kobject_name(parent) == NULL)
112 			return 0;
113 		length += strlen(kobject_name(parent)) + 1;
114 		parent = parent->parent;
115 	} while (parent);
116 	return length;
117 }
118 
119 static void fill_kobj_path(struct kobject *kobj, char *path, int length)
120 {
121 	struct kobject *parent;
122 
123 	--length;
124 	for (parent = kobj; parent; parent = parent->parent) {
125 		int cur = strlen(kobject_name(parent));
126 		/* back up enough to print this name with '/' */
127 		length -= cur;
128 		strncpy(path + length, kobject_name(parent), cur);
129 		*(path + --length) = '/';
130 	}
131 
132 	pr_debug("kobject: '%s' (%p): %s: path = '%s'\n", kobject_name(kobj),
133 		 kobj, __func__, path);
134 }
135 
136 /**
137  * kobject_get_path - generate and return the path associated with a given kobj and kset pair.
138  *
139  * @kobj:	kobject in question, with which to build the path
140  * @gfp_mask:	the allocation type used to allocate the path
141  *
142  * The result must be freed by the caller with kfree().
143  */
144 char *kobject_get_path(struct kobject *kobj, gfp_t gfp_mask)
145 {
146 	char *path;
147 	int len;
148 
149 	len = get_kobj_path_length(kobj);
150 	if (len == 0)
151 		return NULL;
152 	path = kzalloc(len, gfp_mask);
153 	if (!path)
154 		return NULL;
155 	fill_kobj_path(kobj, path, len);
156 
157 	return path;
158 }
159 EXPORT_SYMBOL_GPL(kobject_get_path);
160 
161 /* add the kobject to its kset's list */
162 static void kobj_kset_join(struct kobject *kobj)
163 {
164 	if (!kobj->kset)
165 		return;
166 
167 	kset_get(kobj->kset);
168 	spin_lock(&kobj->kset->list_lock);
169 	list_add_tail(&kobj->entry, &kobj->kset->list);
170 	spin_unlock(&kobj->kset->list_lock);
171 }
172 
173 /* remove the kobject from its kset's list */
174 static void kobj_kset_leave(struct kobject *kobj)
175 {
176 	if (!kobj->kset)
177 		return;
178 
179 	spin_lock(&kobj->kset->list_lock);
180 	list_del_init(&kobj->entry);
181 	spin_unlock(&kobj->kset->list_lock);
182 	kset_put(kobj->kset);
183 }
184 
185 static void kobject_init_internal(struct kobject *kobj)
186 {
187 	if (!kobj)
188 		return;
189 	kref_init(&kobj->kref);
190 	INIT_LIST_HEAD(&kobj->entry);
191 	kobj->state_in_sysfs = 0;
192 	kobj->state_add_uevent_sent = 0;
193 	kobj->state_remove_uevent_sent = 0;
194 	kobj->state_initialized = 1;
195 }
196 
197 
198 static int kobject_add_internal(struct kobject *kobj)
199 {
200 	int error = 0;
201 	struct kobject *parent;
202 
203 	if (!kobj)
204 		return -ENOENT;
205 
206 	if (!kobj->name || !kobj->name[0]) {
207 		WARN(1,
208 		     "kobject: (%p): attempted to be registered with empty name!\n",
209 		     kobj);
210 		return -EINVAL;
211 	}
212 
213 	parent = kobject_get(kobj->parent);
214 
215 	/* join kset if set, use it as parent if we do not already have one */
216 	if (kobj->kset) {
217 		if (!parent)
218 			parent = kobject_get(&kobj->kset->kobj);
219 		kobj_kset_join(kobj);
220 		kobj->parent = parent;
221 	}
222 
223 	pr_debug("kobject: '%s' (%p): %s: parent: '%s', set: '%s'\n",
224 		 kobject_name(kobj), kobj, __func__,
225 		 parent ? kobject_name(parent) : "<NULL>",
226 		 kobj->kset ? kobject_name(&kobj->kset->kobj) : "<NULL>");
227 
228 	error = create_dir(kobj);
229 	if (error) {
230 		kobj_kset_leave(kobj);
231 		kobject_put(parent);
232 		kobj->parent = NULL;
233 
234 		/* be noisy on error issues */
235 		if (error == -EEXIST)
236 			WARN(1,
237 			     "%s failed for %s with -EEXIST, don't try to register things with the same name in the same directory.\n",
238 			     __func__, kobject_name(kobj));
239 		else
240 			WARN(1, "%s failed for %s (error: %d parent: %s)\n",
241 			     __func__, kobject_name(kobj), error,
242 			     parent ? kobject_name(parent) : "'none'");
243 	} else
244 		kobj->state_in_sysfs = 1;
245 
246 	return error;
247 }
248 
249 /**
250  * kobject_set_name_vargs - Set the name of an kobject
251  * @kobj: struct kobject to set the name of
252  * @fmt: format string used to build the name
253  * @vargs: vargs to format the string.
254  */
255 int kobject_set_name_vargs(struct kobject *kobj, const char *fmt,
256 				  va_list vargs)
257 {
258 	const char *s;
259 
260 	if (kobj->name && !fmt)
261 		return 0;
262 
263 	s = kvasprintf_const(GFP_KERNEL, fmt, vargs);
264 	if (!s)
265 		return -ENOMEM;
266 
267 	/*
268 	 * ewww... some of these buggers have '/' in the name ... If
269 	 * that's the case, we need to make sure we have an actual
270 	 * allocated copy to modify, since kvasprintf_const may have
271 	 * returned something from .rodata.
272 	 */
273 	if (strchr(s, '/')) {
274 		char *t;
275 
276 		t = kstrdup(s, GFP_KERNEL);
277 		kfree_const(s);
278 		if (!t)
279 			return -ENOMEM;
280 		strreplace(t, '/', '!');
281 		s = t;
282 	}
283 	kfree_const(kobj->name);
284 	kobj->name = s;
285 
286 	return 0;
287 }
288 
289 /**
290  * kobject_set_name - Set the name of a kobject
291  * @kobj: struct kobject to set the name of
292  * @fmt: format string used to build the name
293  *
294  * This sets the name of the kobject.  If you have already added the
295  * kobject to the system, you must call kobject_rename() in order to
296  * change the name of the kobject.
297  */
298 int kobject_set_name(struct kobject *kobj, const char *fmt, ...)
299 {
300 	va_list vargs;
301 	int retval;
302 
303 	va_start(vargs, fmt);
304 	retval = kobject_set_name_vargs(kobj, fmt, vargs);
305 	va_end(vargs);
306 
307 	return retval;
308 }
309 EXPORT_SYMBOL(kobject_set_name);
310 
311 /**
312  * kobject_init - initialize a kobject structure
313  * @kobj: pointer to the kobject to initialize
314  * @ktype: pointer to the ktype for this kobject.
315  *
316  * This function will properly initialize a kobject such that it can then
317  * be passed to the kobject_add() call.
318  *
319  * After this function is called, the kobject MUST be cleaned up by a call
320  * to kobject_put(), not by a call to kfree directly to ensure that all of
321  * the memory is cleaned up properly.
322  */
323 void kobject_init(struct kobject *kobj, struct kobj_type *ktype)
324 {
325 	char *err_str;
326 
327 	if (!kobj) {
328 		err_str = "invalid kobject pointer!";
329 		goto error;
330 	}
331 	if (!ktype) {
332 		err_str = "must have a ktype to be initialized properly!\n";
333 		goto error;
334 	}
335 	if (kobj->state_initialized) {
336 		/* do not error out as sometimes we can recover */
337 		pr_err("kobject (%p): tried to init an initialized object, something is seriously wrong.\n",
338 		       kobj);
339 		dump_stack();
340 	}
341 
342 	kobject_init_internal(kobj);
343 	kobj->ktype = ktype;
344 	return;
345 
346 error:
347 	pr_err("kobject (%p): %s\n", kobj, err_str);
348 	dump_stack();
349 }
350 EXPORT_SYMBOL(kobject_init);
351 
352 static __printf(3, 0) int kobject_add_varg(struct kobject *kobj,
353 					   struct kobject *parent,
354 					   const char *fmt, va_list vargs)
355 {
356 	int retval;
357 
358 	retval = kobject_set_name_vargs(kobj, fmt, vargs);
359 	if (retval) {
360 		pr_err("kobject: can not set name properly!\n");
361 		return retval;
362 	}
363 	kobj->parent = parent;
364 	return kobject_add_internal(kobj);
365 }
366 
367 /**
368  * kobject_add - the main kobject add function
369  * @kobj: the kobject to add
370  * @parent: pointer to the parent of the kobject.
371  * @fmt: format to name the kobject with.
372  *
373  * The kobject name is set and added to the kobject hierarchy in this
374  * function.
375  *
376  * If @parent is set, then the parent of the @kobj will be set to it.
377  * If @parent is NULL, then the parent of the @kobj will be set to the
378  * kobject associated with the kset assigned to this kobject.  If no kset
379  * is assigned to the kobject, then the kobject will be located in the
380  * root of the sysfs tree.
381  *
382  * If this function returns an error, kobject_put() must be called to
383  * properly clean up the memory associated with the object.
384  * Under no instance should the kobject that is passed to this function
385  * be directly freed with a call to kfree(), that can leak memory.
386  *
387  * Note, no "add" uevent will be created with this call, the caller should set
388  * up all of the necessary sysfs files for the object and then call
389  * kobject_uevent() with the UEVENT_ADD parameter to ensure that
390  * userspace is properly notified of this kobject's creation.
391  */
392 int kobject_add(struct kobject *kobj, struct kobject *parent,
393 		const char *fmt, ...)
394 {
395 	va_list args;
396 	int retval;
397 
398 	if (!kobj)
399 		return -EINVAL;
400 
401 	if (!kobj->state_initialized) {
402 		pr_err("kobject '%s' (%p): tried to add an uninitialized object, something is seriously wrong.\n",
403 		       kobject_name(kobj), kobj);
404 		dump_stack();
405 		return -EINVAL;
406 	}
407 	va_start(args, fmt);
408 	retval = kobject_add_varg(kobj, parent, fmt, args);
409 	va_end(args);
410 
411 	return retval;
412 }
413 EXPORT_SYMBOL(kobject_add);
414 
415 /**
416  * kobject_init_and_add - initialize a kobject structure and add it to the kobject hierarchy
417  * @kobj: pointer to the kobject to initialize
418  * @ktype: pointer to the ktype for this kobject.
419  * @parent: pointer to the parent of this kobject.
420  * @fmt: the name of the kobject.
421  *
422  * This function combines the call to kobject_init() and
423  * kobject_add().  The same type of error handling after a call to
424  * kobject_add() and kobject lifetime rules are the same here.
425  */
426 int kobject_init_and_add(struct kobject *kobj, struct kobj_type *ktype,
427 			 struct kobject *parent, const char *fmt, ...)
428 {
429 	va_list args;
430 	int retval;
431 
432 	kobject_init(kobj, ktype);
433 
434 	va_start(args, fmt);
435 	retval = kobject_add_varg(kobj, parent, fmt, args);
436 	va_end(args);
437 
438 	return retval;
439 }
440 EXPORT_SYMBOL_GPL(kobject_init_and_add);
441 
442 /**
443  * kobject_rename - change the name of an object
444  * @kobj: object in question.
445  * @new_name: object's new name
446  *
447  * It is the responsibility of the caller to provide mutual
448  * exclusion between two different calls of kobject_rename
449  * on the same kobject and to ensure that new_name is valid and
450  * won't conflict with other kobjects.
451  */
452 int kobject_rename(struct kobject *kobj, const char *new_name)
453 {
454 	int error = 0;
455 	const char *devpath = NULL;
456 	const char *dup_name = NULL, *name;
457 	char *devpath_string = NULL;
458 	char *envp[2];
459 
460 	kobj = kobject_get(kobj);
461 	if (!kobj)
462 		return -EINVAL;
463 	if (!kobj->parent)
464 		return -EINVAL;
465 
466 	devpath = kobject_get_path(kobj, GFP_KERNEL);
467 	if (!devpath) {
468 		error = -ENOMEM;
469 		goto out;
470 	}
471 	devpath_string = kmalloc(strlen(devpath) + 15, GFP_KERNEL);
472 	if (!devpath_string) {
473 		error = -ENOMEM;
474 		goto out;
475 	}
476 	sprintf(devpath_string, "DEVPATH_OLD=%s", devpath);
477 	envp[0] = devpath_string;
478 	envp[1] = NULL;
479 
480 	name = dup_name = kstrdup_const(new_name, GFP_KERNEL);
481 	if (!name) {
482 		error = -ENOMEM;
483 		goto out;
484 	}
485 
486 	error = sysfs_rename_dir_ns(kobj, new_name, kobject_namespace(kobj));
487 	if (error)
488 		goto out;
489 
490 	/* Install the new kobject name */
491 	dup_name = kobj->name;
492 	kobj->name = name;
493 
494 	/* This function is mostly/only used for network interface.
495 	 * Some hotplug package track interfaces by their name and
496 	 * therefore want to know when the name is changed by the user. */
497 	kobject_uevent_env(kobj, KOBJ_MOVE, envp);
498 
499 out:
500 	kfree_const(dup_name);
501 	kfree(devpath_string);
502 	kfree(devpath);
503 	kobject_put(kobj);
504 
505 	return error;
506 }
507 EXPORT_SYMBOL_GPL(kobject_rename);
508 
509 /**
510  * kobject_move - move object to another parent
511  * @kobj: object in question.
512  * @new_parent: object's new parent (can be NULL)
513  */
514 int kobject_move(struct kobject *kobj, struct kobject *new_parent)
515 {
516 	int error;
517 	struct kobject *old_parent;
518 	const char *devpath = NULL;
519 	char *devpath_string = NULL;
520 	char *envp[2];
521 
522 	kobj = kobject_get(kobj);
523 	if (!kobj)
524 		return -EINVAL;
525 	new_parent = kobject_get(new_parent);
526 	if (!new_parent) {
527 		if (kobj->kset)
528 			new_parent = kobject_get(&kobj->kset->kobj);
529 	}
530 
531 	/* old object path */
532 	devpath = kobject_get_path(kobj, GFP_KERNEL);
533 	if (!devpath) {
534 		error = -ENOMEM;
535 		goto out;
536 	}
537 	devpath_string = kmalloc(strlen(devpath) + 15, GFP_KERNEL);
538 	if (!devpath_string) {
539 		error = -ENOMEM;
540 		goto out;
541 	}
542 	sprintf(devpath_string, "DEVPATH_OLD=%s", devpath);
543 	envp[0] = devpath_string;
544 	envp[1] = NULL;
545 	error = sysfs_move_dir_ns(kobj, new_parent, kobject_namespace(kobj));
546 	if (error)
547 		goto out;
548 	old_parent = kobj->parent;
549 	kobj->parent = new_parent;
550 	new_parent = NULL;
551 	kobject_put(old_parent);
552 	kobject_uevent_env(kobj, KOBJ_MOVE, envp);
553 out:
554 	kobject_put(new_parent);
555 	kobject_put(kobj);
556 	kfree(devpath_string);
557 	kfree(devpath);
558 	return error;
559 }
560 EXPORT_SYMBOL_GPL(kobject_move);
561 
562 /**
563  * kobject_del - unlink kobject from hierarchy.
564  * @kobj: object.
565  */
566 void kobject_del(struct kobject *kobj)
567 {
568 	struct kernfs_node *sd;
569 
570 	if (!kobj)
571 		return;
572 
573 	sd = kobj->sd;
574 	sysfs_remove_dir(kobj);
575 	sysfs_put(sd);
576 
577 	kobj->state_in_sysfs = 0;
578 	kobj_kset_leave(kobj);
579 	kobject_put(kobj->parent);
580 	kobj->parent = NULL;
581 }
582 EXPORT_SYMBOL(kobject_del);
583 
584 /**
585  * kobject_get - increment refcount for object.
586  * @kobj: object.
587  */
588 struct kobject *kobject_get(struct kobject *kobj)
589 {
590 	if (kobj) {
591 		if (!kobj->state_initialized)
592 			WARN(1, KERN_WARNING
593 				"kobject: '%s' (%p): is not initialized, yet kobject_get() is being called.\n",
594 			     kobject_name(kobj), kobj);
595 		kref_get(&kobj->kref);
596 	}
597 	return kobj;
598 }
599 EXPORT_SYMBOL(kobject_get);
600 
601 struct kobject * __must_check kobject_get_unless_zero(struct kobject *kobj)
602 {
603 	if (!kobj)
604 		return NULL;
605 	if (!kref_get_unless_zero(&kobj->kref))
606 		kobj = NULL;
607 	return kobj;
608 }
609 EXPORT_SYMBOL(kobject_get_unless_zero);
610 
611 /*
612  * kobject_cleanup - free kobject resources.
613  * @kobj: object to cleanup
614  */
615 static void kobject_cleanup(struct kobject *kobj)
616 {
617 	struct kobj_type *t = get_ktype(kobj);
618 	const char *name = kobj->name;
619 
620 	pr_debug("kobject: '%s' (%p): %s, parent %p\n",
621 		 kobject_name(kobj), kobj, __func__, kobj->parent);
622 
623 	if (t && !t->release)
624 		pr_debug("kobject: '%s' (%p): does not have a release() function, it is broken and must be fixed.\n",
625 			 kobject_name(kobj), kobj);
626 
627 	/* send "remove" if the caller did not do it but sent "add" */
628 	if (kobj->state_add_uevent_sent && !kobj->state_remove_uevent_sent) {
629 		pr_debug("kobject: '%s' (%p): auto cleanup 'remove' event\n",
630 			 kobject_name(kobj), kobj);
631 		kobject_uevent(kobj, KOBJ_REMOVE);
632 	}
633 
634 	/* remove from sysfs if the caller did not do it */
635 	if (kobj->state_in_sysfs) {
636 		pr_debug("kobject: '%s' (%p): auto cleanup kobject_del\n",
637 			 kobject_name(kobj), kobj);
638 		kobject_del(kobj);
639 	}
640 
641 	if (t && t->release) {
642 		pr_debug("kobject: '%s' (%p): calling ktype release\n",
643 			 kobject_name(kobj), kobj);
644 		t->release(kobj);
645 	}
646 
647 	/* free name if we allocated it */
648 	if (name) {
649 		pr_debug("kobject: '%s': free name\n", name);
650 		kfree_const(name);
651 	}
652 }
653 
654 #ifdef CONFIG_DEBUG_KOBJECT_RELEASE
655 static void kobject_delayed_cleanup(struct work_struct *work)
656 {
657 	kobject_cleanup(container_of(to_delayed_work(work),
658 				     struct kobject, release));
659 }
660 #endif
661 
662 static void kobject_release(struct kref *kref)
663 {
664 	struct kobject *kobj = container_of(kref, struct kobject, kref);
665 #ifdef CONFIG_DEBUG_KOBJECT_RELEASE
666 	unsigned long delay = HZ + HZ * (get_random_int() & 0x3);
667 	pr_info("kobject: '%s' (%p): %s, parent %p (delayed %ld)\n",
668 		 kobject_name(kobj), kobj, __func__, kobj->parent, delay);
669 	INIT_DELAYED_WORK(&kobj->release, kobject_delayed_cleanup);
670 
671 	schedule_delayed_work(&kobj->release, delay);
672 #else
673 	kobject_cleanup(kobj);
674 #endif
675 }
676 
677 /**
678  * kobject_put - decrement refcount for object.
679  * @kobj: object.
680  *
681  * Decrement the refcount, and if 0, call kobject_cleanup().
682  */
683 void kobject_put(struct kobject *kobj)
684 {
685 	if (kobj) {
686 		if (!kobj->state_initialized)
687 			WARN(1, KERN_WARNING
688 				"kobject: '%s' (%p): is not initialized, yet kobject_put() is being called.\n",
689 			     kobject_name(kobj), kobj);
690 		kref_put(&kobj->kref, kobject_release);
691 	}
692 }
693 EXPORT_SYMBOL(kobject_put);
694 
695 static void dynamic_kobj_release(struct kobject *kobj)
696 {
697 	pr_debug("kobject: (%p): %s\n", kobj, __func__);
698 	kfree(kobj);
699 }
700 
701 static struct kobj_type dynamic_kobj_ktype = {
702 	.release	= dynamic_kobj_release,
703 	.sysfs_ops	= &kobj_sysfs_ops,
704 };
705 
706 /**
707  * kobject_create - create a struct kobject dynamically
708  *
709  * This function creates a kobject structure dynamically and sets it up
710  * to be a "dynamic" kobject with a default release function set up.
711  *
712  * If the kobject was not able to be created, NULL will be returned.
713  * The kobject structure returned from here must be cleaned up with a
714  * call to kobject_put() and not kfree(), as kobject_init() has
715  * already been called on this structure.
716  */
717 struct kobject *kobject_create(void)
718 {
719 	struct kobject *kobj;
720 
721 	kobj = kzalloc(sizeof(*kobj), GFP_KERNEL);
722 	if (!kobj)
723 		return NULL;
724 
725 	kobject_init(kobj, &dynamic_kobj_ktype);
726 	return kobj;
727 }
728 
729 /**
730  * kobject_create_and_add - create a struct kobject dynamically and register it with sysfs
731  *
732  * @name: the name for the kobject
733  * @parent: the parent kobject of this kobject, if any.
734  *
735  * This function creates a kobject structure dynamically and registers it
736  * with sysfs.  When you are finished with this structure, call
737  * kobject_put() and the structure will be dynamically freed when
738  * it is no longer being used.
739  *
740  * If the kobject was not able to be created, NULL will be returned.
741  */
742 struct kobject *kobject_create_and_add(const char *name, struct kobject *parent)
743 {
744 	struct kobject *kobj;
745 	int retval;
746 
747 	kobj = kobject_create();
748 	if (!kobj)
749 		return NULL;
750 
751 	retval = kobject_add(kobj, parent, "%s", name);
752 	if (retval) {
753 		pr_warn("%s: kobject_add error: %d\n", __func__, retval);
754 		kobject_put(kobj);
755 		kobj = NULL;
756 	}
757 	return kobj;
758 }
759 EXPORT_SYMBOL_GPL(kobject_create_and_add);
760 
761 /**
762  * kset_init - initialize a kset for use
763  * @k: kset
764  */
765 void kset_init(struct kset *k)
766 {
767 	kobject_init_internal(&k->kobj);
768 	INIT_LIST_HEAD(&k->list);
769 	spin_lock_init(&k->list_lock);
770 }
771 
772 /* default kobject attribute operations */
773 static ssize_t kobj_attr_show(struct kobject *kobj, struct attribute *attr,
774 			      char *buf)
775 {
776 	struct kobj_attribute *kattr;
777 	ssize_t ret = -EIO;
778 
779 	kattr = container_of(attr, struct kobj_attribute, attr);
780 	if (kattr->show)
781 		ret = kattr->show(kobj, kattr, buf);
782 	return ret;
783 }
784 
785 static ssize_t kobj_attr_store(struct kobject *kobj, struct attribute *attr,
786 			       const char *buf, size_t count)
787 {
788 	struct kobj_attribute *kattr;
789 	ssize_t ret = -EIO;
790 
791 	kattr = container_of(attr, struct kobj_attribute, attr);
792 	if (kattr->store)
793 		ret = kattr->store(kobj, kattr, buf, count);
794 	return ret;
795 }
796 
797 const struct sysfs_ops kobj_sysfs_ops = {
798 	.show	= kobj_attr_show,
799 	.store	= kobj_attr_store,
800 };
801 EXPORT_SYMBOL_GPL(kobj_sysfs_ops);
802 
803 /**
804  * kset_register - initialize and add a kset.
805  * @k: kset.
806  */
807 int kset_register(struct kset *k)
808 {
809 	int err;
810 
811 	if (!k)
812 		return -EINVAL;
813 
814 	kset_init(k);
815 	err = kobject_add_internal(&k->kobj);
816 	if (err)
817 		return err;
818 	kobject_uevent(&k->kobj, KOBJ_ADD);
819 	return 0;
820 }
821 EXPORT_SYMBOL(kset_register);
822 
823 /**
824  * kset_unregister - remove a kset.
825  * @k: kset.
826  */
827 void kset_unregister(struct kset *k)
828 {
829 	if (!k)
830 		return;
831 	kobject_del(&k->kobj);
832 	kobject_put(&k->kobj);
833 }
834 EXPORT_SYMBOL(kset_unregister);
835 
836 /**
837  * kset_find_obj - search for object in kset.
838  * @kset: kset we're looking in.
839  * @name: object's name.
840  *
841  * Lock kset via @kset->subsys, and iterate over @kset->list,
842  * looking for a matching kobject. If matching object is found
843  * take a reference and return the object.
844  */
845 struct kobject *kset_find_obj(struct kset *kset, const char *name)
846 {
847 	struct kobject *k;
848 	struct kobject *ret = NULL;
849 
850 	spin_lock(&kset->list_lock);
851 
852 	list_for_each_entry(k, &kset->list, entry) {
853 		if (kobject_name(k) && !strcmp(kobject_name(k), name)) {
854 			ret = kobject_get_unless_zero(k);
855 			break;
856 		}
857 	}
858 
859 	spin_unlock(&kset->list_lock);
860 	return ret;
861 }
862 EXPORT_SYMBOL_GPL(kset_find_obj);
863 
864 static void kset_release(struct kobject *kobj)
865 {
866 	struct kset *kset = container_of(kobj, struct kset, kobj);
867 	pr_debug("kobject: '%s' (%p): %s\n",
868 		 kobject_name(kobj), kobj, __func__);
869 	kfree(kset);
870 }
871 
872 static struct kobj_type kset_ktype = {
873 	.sysfs_ops	= &kobj_sysfs_ops,
874 	.release = kset_release,
875 };
876 
877 /**
878  * kset_create - create a struct kset dynamically
879  *
880  * @name: the name for the kset
881  * @uevent_ops: a struct kset_uevent_ops for the kset
882  * @parent_kobj: the parent kobject of this kset, if any.
883  *
884  * This function creates a kset structure dynamically.  This structure can
885  * then be registered with the system and show up in sysfs with a call to
886  * kset_register().  When you are finished with this structure, if
887  * kset_register() has been called, call kset_unregister() and the
888  * structure will be dynamically freed when it is no longer being used.
889  *
890  * If the kset was not able to be created, NULL will be returned.
891  */
892 static struct kset *kset_create(const char *name,
893 				const struct kset_uevent_ops *uevent_ops,
894 				struct kobject *parent_kobj)
895 {
896 	struct kset *kset;
897 	int retval;
898 
899 	kset = kzalloc(sizeof(*kset), GFP_KERNEL);
900 	if (!kset)
901 		return NULL;
902 	retval = kobject_set_name(&kset->kobj, "%s", name);
903 	if (retval) {
904 		kfree(kset);
905 		return NULL;
906 	}
907 	kset->uevent_ops = uevent_ops;
908 	kset->kobj.parent = parent_kobj;
909 
910 	/*
911 	 * The kobject of this kset will have a type of kset_ktype and belong to
912 	 * no kset itself.  That way we can properly free it when it is
913 	 * finished being used.
914 	 */
915 	kset->kobj.ktype = &kset_ktype;
916 	kset->kobj.kset = NULL;
917 
918 	return kset;
919 }
920 
921 /**
922  * kset_create_and_add - create a struct kset dynamically and add it to sysfs
923  *
924  * @name: the name for the kset
925  * @uevent_ops: a struct kset_uevent_ops for the kset
926  * @parent_kobj: the parent kobject of this kset, if any.
927  *
928  * This function creates a kset structure dynamically and registers it
929  * with sysfs.  When you are finished with this structure, call
930  * kset_unregister() and the structure will be dynamically freed when it
931  * is no longer being used.
932  *
933  * If the kset was not able to be created, NULL will be returned.
934  */
935 struct kset *kset_create_and_add(const char *name,
936 				 const struct kset_uevent_ops *uevent_ops,
937 				 struct kobject *parent_kobj)
938 {
939 	struct kset *kset;
940 	int error;
941 
942 	kset = kset_create(name, uevent_ops, parent_kobj);
943 	if (!kset)
944 		return NULL;
945 	error = kset_register(kset);
946 	if (error) {
947 		kfree(kset);
948 		return NULL;
949 	}
950 	return kset;
951 }
952 EXPORT_SYMBOL_GPL(kset_create_and_add);
953 
954 
955 static DEFINE_SPINLOCK(kobj_ns_type_lock);
956 static const struct kobj_ns_type_operations *kobj_ns_ops_tbl[KOBJ_NS_TYPES];
957 
958 int kobj_ns_type_register(const struct kobj_ns_type_operations *ops)
959 {
960 	enum kobj_ns_type type = ops->type;
961 	int error;
962 
963 	spin_lock(&kobj_ns_type_lock);
964 
965 	error = -EINVAL;
966 	if (type >= KOBJ_NS_TYPES)
967 		goto out;
968 
969 	error = -EINVAL;
970 	if (type <= KOBJ_NS_TYPE_NONE)
971 		goto out;
972 
973 	error = -EBUSY;
974 	if (kobj_ns_ops_tbl[type])
975 		goto out;
976 
977 	error = 0;
978 	kobj_ns_ops_tbl[type] = ops;
979 
980 out:
981 	spin_unlock(&kobj_ns_type_lock);
982 	return error;
983 }
984 
985 int kobj_ns_type_registered(enum kobj_ns_type type)
986 {
987 	int registered = 0;
988 
989 	spin_lock(&kobj_ns_type_lock);
990 	if ((type > KOBJ_NS_TYPE_NONE) && (type < KOBJ_NS_TYPES))
991 		registered = kobj_ns_ops_tbl[type] != NULL;
992 	spin_unlock(&kobj_ns_type_lock);
993 
994 	return registered;
995 }
996 
997 const struct kobj_ns_type_operations *kobj_child_ns_ops(struct kobject *parent)
998 {
999 	const struct kobj_ns_type_operations *ops = NULL;
1000 
1001 	if (parent && parent->ktype && parent->ktype->child_ns_type)
1002 		ops = parent->ktype->child_ns_type(parent);
1003 
1004 	return ops;
1005 }
1006 
1007 const struct kobj_ns_type_operations *kobj_ns_ops(struct kobject *kobj)
1008 {
1009 	return kobj_child_ns_ops(kobj->parent);
1010 }
1011 
1012 bool kobj_ns_current_may_mount(enum kobj_ns_type type)
1013 {
1014 	bool may_mount = true;
1015 
1016 	spin_lock(&kobj_ns_type_lock);
1017 	if ((type > KOBJ_NS_TYPE_NONE) && (type < KOBJ_NS_TYPES) &&
1018 	    kobj_ns_ops_tbl[type])
1019 		may_mount = kobj_ns_ops_tbl[type]->current_may_mount();
1020 	spin_unlock(&kobj_ns_type_lock);
1021 
1022 	return may_mount;
1023 }
1024 
1025 void *kobj_ns_grab_current(enum kobj_ns_type type)
1026 {
1027 	void *ns = NULL;
1028 
1029 	spin_lock(&kobj_ns_type_lock);
1030 	if ((type > KOBJ_NS_TYPE_NONE) && (type < KOBJ_NS_TYPES) &&
1031 	    kobj_ns_ops_tbl[type])
1032 		ns = kobj_ns_ops_tbl[type]->grab_current_ns();
1033 	spin_unlock(&kobj_ns_type_lock);
1034 
1035 	return ns;
1036 }
1037 EXPORT_SYMBOL_GPL(kobj_ns_grab_current);
1038 
1039 const void *kobj_ns_netlink(enum kobj_ns_type type, struct sock *sk)
1040 {
1041 	const void *ns = NULL;
1042 
1043 	spin_lock(&kobj_ns_type_lock);
1044 	if ((type > KOBJ_NS_TYPE_NONE) && (type < KOBJ_NS_TYPES) &&
1045 	    kobj_ns_ops_tbl[type])
1046 		ns = kobj_ns_ops_tbl[type]->netlink_ns(sk);
1047 	spin_unlock(&kobj_ns_type_lock);
1048 
1049 	return ns;
1050 }
1051 
1052 const void *kobj_ns_initial(enum kobj_ns_type type)
1053 {
1054 	const void *ns = NULL;
1055 
1056 	spin_lock(&kobj_ns_type_lock);
1057 	if ((type > KOBJ_NS_TYPE_NONE) && (type < KOBJ_NS_TYPES) &&
1058 	    kobj_ns_ops_tbl[type])
1059 		ns = kobj_ns_ops_tbl[type]->initial_ns();
1060 	spin_unlock(&kobj_ns_type_lock);
1061 
1062 	return ns;
1063 }
1064 
1065 void kobj_ns_drop(enum kobj_ns_type type, void *ns)
1066 {
1067 	spin_lock(&kobj_ns_type_lock);
1068 	if ((type > KOBJ_NS_TYPE_NONE) && (type < KOBJ_NS_TYPES) &&
1069 	    kobj_ns_ops_tbl[type] && kobj_ns_ops_tbl[type]->drop_ns)
1070 		kobj_ns_ops_tbl[type]->drop_ns(ns);
1071 	spin_unlock(&kobj_ns_type_lock);
1072 }
1073 EXPORT_SYMBOL_GPL(kobj_ns_drop);
1074