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