• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * drivers/base/core.c - core driver model code (device registration, etc)
4  *
5  * Copyright (c) 2002-3 Patrick Mochel
6  * Copyright (c) 2002-3 Open Source Development Labs
7  * Copyright (c) 2006 Greg Kroah-Hartman <gregkh@suse.de>
8  * Copyright (c) 2006 Novell, Inc.
9  */
10 
11 #include <linux/acpi.h>
12 #include <linux/cpufreq.h>
13 #include <linux/device.h>
14 #include <linux/err.h>
15 #include <linux/fwnode.h>
16 #include <linux/init.h>
17 #include <linux/module.h>
18 #include <linux/slab.h>
19 #include <linux/string.h>
20 #include <linux/kdev_t.h>
21 #include <linux/notifier.h>
22 #include <linux/of.h>
23 #include <linux/of_device.h>
24 #include <linux/genhd.h>
25 #include <linux/mutex.h>
26 #include <linux/pm_runtime.h>
27 #include <linux/netdevice.h>
28 #include <linux/sched/signal.h>
29 #include <linux/sched/mm.h>
30 #include <linux/sysfs.h>
31 
32 #include "base.h"
33 #include "power/power.h"
34 
35 #ifdef CONFIG_SYSFS_DEPRECATED
36 #ifdef CONFIG_SYSFS_DEPRECATED_V2
37 long sysfs_deprecated = 1;
38 #else
39 long sysfs_deprecated = 0;
40 #endif
sysfs_deprecated_setup(char * arg)41 static int __init sysfs_deprecated_setup(char *arg)
42 {
43 	return kstrtol(arg, 10, &sysfs_deprecated);
44 }
45 early_param("sysfs.deprecated", sysfs_deprecated_setup);
46 #endif
47 
48 /* Device links support. */
49 static LIST_HEAD(wait_for_suppliers);
50 static DEFINE_MUTEX(wfs_lock);
51 static LIST_HEAD(deferred_sync);
52 static unsigned int defer_sync_state_count = 1;
53 static unsigned int defer_fw_devlink_count;
54 static LIST_HEAD(deferred_fw_devlink);
55 static DEFINE_MUTEX(defer_fw_devlink_lock);
56 static bool fw_devlink_is_permissive(void);
57 
58 #ifdef CONFIG_SRCU
59 static DEFINE_MUTEX(device_links_lock);
60 DEFINE_STATIC_SRCU(device_links_srcu);
61 
device_links_write_lock(void)62 static inline void device_links_write_lock(void)
63 {
64 	mutex_lock(&device_links_lock);
65 }
66 
device_links_write_unlock(void)67 static inline void device_links_write_unlock(void)
68 {
69 	mutex_unlock(&device_links_lock);
70 }
71 
device_links_read_lock(void)72 int device_links_read_lock(void) __acquires(&device_links_srcu)
73 {
74 	return srcu_read_lock(&device_links_srcu);
75 }
76 
device_links_read_unlock(int idx)77 void device_links_read_unlock(int idx) __releases(&device_links_srcu)
78 {
79 	srcu_read_unlock(&device_links_srcu, idx);
80 }
81 
device_links_read_lock_held(void)82 int device_links_read_lock_held(void)
83 {
84 	return srcu_read_lock_held(&device_links_srcu);
85 }
86 
device_link_synchronize_removal(void)87 static void device_link_synchronize_removal(void)
88 {
89 	synchronize_srcu(&device_links_srcu);
90 }
91 #else /* !CONFIG_SRCU */
92 static DECLARE_RWSEM(device_links_lock);
93 
device_links_write_lock(void)94 static inline void device_links_write_lock(void)
95 {
96 	down_write(&device_links_lock);
97 }
98 
device_links_write_unlock(void)99 static inline void device_links_write_unlock(void)
100 {
101 	up_write(&device_links_lock);
102 }
103 
device_links_read_lock(void)104 int device_links_read_lock(void)
105 {
106 	down_read(&device_links_lock);
107 	return 0;
108 }
109 
device_links_read_unlock(int not_used)110 void device_links_read_unlock(int not_used)
111 {
112 	up_read(&device_links_lock);
113 }
114 
115 #ifdef CONFIG_DEBUG_LOCK_ALLOC
device_links_read_lock_held(void)116 int device_links_read_lock_held(void)
117 {
118 	return lockdep_is_held(&device_links_lock);
119 }
120 #endif
121 
device_link_synchronize_removal(void)122 static inline void device_link_synchronize_removal(void)
123 {
124 }
125 #endif /* !CONFIG_SRCU */
126 
device_is_ancestor(struct device * dev,struct device * target)127 static bool device_is_ancestor(struct device *dev, struct device *target)
128 {
129 	while (target->parent) {
130 		target = target->parent;
131 		if (dev == target)
132 			return true;
133 	}
134 	return false;
135 }
136 
137 /**
138  * device_is_dependent - Check if one device depends on another one
139  * @dev: Device to check dependencies for.
140  * @target: Device to check against.
141  *
142  * Check if @target depends on @dev or any device dependent on it (its child or
143  * its consumer etc).  Return 1 if that is the case or 0 otherwise.
144  */
device_is_dependent(struct device * dev,void * target)145 int device_is_dependent(struct device *dev, void *target)
146 {
147 	struct device_link *link;
148 	int ret;
149 
150 	/*
151 	 * The "ancestors" check is needed to catch the case when the target
152 	 * device has not been completely initialized yet and it is still
153 	 * missing from the list of children of its parent device.
154 	 */
155 	if (dev == target || device_is_ancestor(dev, target))
156 		return 1;
157 
158 	ret = device_for_each_child(dev, target, device_is_dependent);
159 	if (ret)
160 		return ret;
161 
162 	list_for_each_entry(link, &dev->links.consumers, s_node) {
163 		if (link->flags == (DL_FLAG_SYNC_STATE_ONLY | DL_FLAG_MANAGED))
164 			continue;
165 
166 		if (link->consumer == target)
167 			return 1;
168 
169 		ret = device_is_dependent(link->consumer, target);
170 		if (ret)
171 			break;
172 	}
173 	return ret;
174 }
175 
device_link_init_status(struct device_link * link,struct device * consumer,struct device * supplier)176 static void device_link_init_status(struct device_link *link,
177 				    struct device *consumer,
178 				    struct device *supplier)
179 {
180 	switch (supplier->links.status) {
181 	case DL_DEV_PROBING:
182 		switch (consumer->links.status) {
183 		case DL_DEV_PROBING:
184 			/*
185 			 * A consumer driver can create a link to a supplier
186 			 * that has not completed its probing yet as long as it
187 			 * knows that the supplier is already functional (for
188 			 * example, it has just acquired some resources from the
189 			 * supplier).
190 			 */
191 			link->status = DL_STATE_CONSUMER_PROBE;
192 			break;
193 		default:
194 			link->status = DL_STATE_DORMANT;
195 			break;
196 		}
197 		break;
198 	case DL_DEV_DRIVER_BOUND:
199 		switch (consumer->links.status) {
200 		case DL_DEV_PROBING:
201 			link->status = DL_STATE_CONSUMER_PROBE;
202 			break;
203 		case DL_DEV_DRIVER_BOUND:
204 			link->status = DL_STATE_ACTIVE;
205 			break;
206 		default:
207 			link->status = DL_STATE_AVAILABLE;
208 			break;
209 		}
210 		break;
211 	case DL_DEV_UNBINDING:
212 		link->status = DL_STATE_SUPPLIER_UNBIND;
213 		break;
214 	default:
215 		link->status = DL_STATE_DORMANT;
216 		break;
217 	}
218 }
219 
device_reorder_to_tail(struct device * dev,void * not_used)220 static int device_reorder_to_tail(struct device *dev, void *not_used)
221 {
222 	struct device_link *link;
223 
224 	/*
225 	 * Devices that have not been registered yet will be put to the ends
226 	 * of the lists during the registration, so skip them here.
227 	 */
228 	if (device_is_registered(dev))
229 		devices_kset_move_last(dev);
230 
231 	if (device_pm_initialized(dev))
232 		device_pm_move_last(dev);
233 
234 	device_for_each_child(dev, NULL, device_reorder_to_tail);
235 	list_for_each_entry(link, &dev->links.consumers, s_node) {
236 		if (link->flags == (DL_FLAG_SYNC_STATE_ONLY | DL_FLAG_MANAGED))
237 			continue;
238 		device_reorder_to_tail(link->consumer, NULL);
239 	}
240 
241 	return 0;
242 }
243 
244 /**
245  * device_pm_move_to_tail - Move set of devices to the end of device lists
246  * @dev: Device to move
247  *
248  * This is a device_reorder_to_tail() wrapper taking the requisite locks.
249  *
250  * It moves the @dev along with all of its children and all of its consumers
251  * to the ends of the device_kset and dpm_list, recursively.
252  */
device_pm_move_to_tail(struct device * dev)253 void device_pm_move_to_tail(struct device *dev)
254 {
255 	int idx;
256 
257 	idx = device_links_read_lock();
258 	device_pm_lock();
259 	device_reorder_to_tail(dev, NULL);
260 	device_pm_unlock();
261 	device_links_read_unlock(idx);
262 }
263 
264 #define to_devlink(dev)	container_of((dev), struct device_link, link_dev)
265 
status_show(struct device * dev,struct device_attribute * attr,char * buf)266 static ssize_t status_show(struct device *dev,
267 			   struct device_attribute *attr, char *buf)
268 {
269 	const char *output;
270 
271 	switch (to_devlink(dev)->status) {
272 	case DL_STATE_NONE:
273 		output = "not tracked";
274 		break;
275 	case DL_STATE_DORMANT:
276 		output = "dormant";
277 		break;
278 	case DL_STATE_AVAILABLE:
279 		output = "available";
280 		break;
281 	case DL_STATE_CONSUMER_PROBE:
282 		output = "consumer probing";
283 		break;
284 	case DL_STATE_ACTIVE:
285 		output = "active";
286 		break;
287 	case DL_STATE_SUPPLIER_UNBIND:
288 		output = "supplier unbinding";
289 		break;
290 	default:
291 		output = "unknown";
292 		break;
293 	}
294 
295 	return sysfs_emit(buf, "%s\n", output);
296 }
297 static DEVICE_ATTR_RO(status);
298 
auto_remove_on_show(struct device * dev,struct device_attribute * attr,char * buf)299 static ssize_t auto_remove_on_show(struct device *dev,
300 				   struct device_attribute *attr, char *buf)
301 {
302 	struct device_link *link = to_devlink(dev);
303 	const char *output;
304 
305 	if (link->flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
306 		output = "supplier unbind";
307 	else if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER)
308 		output = "consumer unbind";
309 	else
310 		output = "never";
311 
312 	return sysfs_emit(buf, "%s\n", output);
313 }
314 static DEVICE_ATTR_RO(auto_remove_on);
315 
runtime_pm_show(struct device * dev,struct device_attribute * attr,char * buf)316 static ssize_t runtime_pm_show(struct device *dev,
317 			       struct device_attribute *attr, char *buf)
318 {
319 	struct device_link *link = to_devlink(dev);
320 
321 	return sysfs_emit(buf, "%d\n", !!(link->flags & DL_FLAG_PM_RUNTIME));
322 }
323 static DEVICE_ATTR_RO(runtime_pm);
324 
sync_state_only_show(struct device * dev,struct device_attribute * attr,char * buf)325 static ssize_t sync_state_only_show(struct device *dev,
326 				    struct device_attribute *attr, char *buf)
327 {
328 	struct device_link *link = to_devlink(dev);
329 
330 	return sysfs_emit(buf, "%d\n",
331 			  !!(link->flags & DL_FLAG_SYNC_STATE_ONLY));
332 }
333 static DEVICE_ATTR_RO(sync_state_only);
334 
335 static struct attribute *devlink_attrs[] = {
336 	&dev_attr_status.attr,
337 	&dev_attr_auto_remove_on.attr,
338 	&dev_attr_runtime_pm.attr,
339 	&dev_attr_sync_state_only.attr,
340 	NULL,
341 };
342 ATTRIBUTE_GROUPS(devlink);
343 
device_link_release_fn(struct work_struct * work)344 static void device_link_release_fn(struct work_struct *work)
345 {
346 	struct device_link *link = container_of(work, struct device_link, rm_work);
347 
348 	/* Ensure that all references to the link object have been dropped. */
349 	device_link_synchronize_removal();
350 
351 	pm_runtime_release_supplier(link);
352 	pm_request_idle(link->supplier);
353 
354 	put_device(link->consumer);
355 	put_device(link->supplier);
356 	kfree(link);
357 }
358 
devlink_dev_release(struct device * dev)359 static void devlink_dev_release(struct device *dev)
360 {
361 	struct device_link *link = to_devlink(dev);
362 
363 	INIT_WORK(&link->rm_work, device_link_release_fn);
364 	/*
365 	 * It may take a while to complete this work because of the SRCU
366 	 * synchronization in device_link_release_fn() and if the consumer or
367 	 * supplier devices get deleted when it runs, so put it into the "long"
368 	 * workqueue.
369 	 */
370 	queue_work(system_long_wq, &link->rm_work);
371 }
372 
373 static struct class devlink_class = {
374 	.name = "devlink",
375 	.owner = THIS_MODULE,
376 	.dev_groups = devlink_groups,
377 	.dev_release = devlink_dev_release,
378 };
379 
devlink_add_symlinks(struct device * dev,struct class_interface * class_intf)380 static int devlink_add_symlinks(struct device *dev,
381 				struct class_interface *class_intf)
382 {
383 	int ret;
384 	size_t len;
385 	struct device_link *link = to_devlink(dev);
386 	struct device *sup = link->supplier;
387 	struct device *con = link->consumer;
388 	char *buf;
389 
390 	len = max(strlen(dev_bus_name(sup)) + strlen(dev_name(sup)),
391 		  strlen(dev_bus_name(con)) + strlen(dev_name(con)));
392 	len += strlen(":");
393 	len += strlen("supplier:") + 1;
394 	buf = kzalloc(len, GFP_KERNEL);
395 	if (!buf)
396 		return -ENOMEM;
397 
398 	ret = sysfs_create_link(&link->link_dev.kobj, &sup->kobj, "supplier");
399 	if (ret)
400 		goto out;
401 
402 	ret = sysfs_create_link(&link->link_dev.kobj, &con->kobj, "consumer");
403 	if (ret)
404 		goto err_con;
405 
406 	snprintf(buf, len, "consumer:%s:%s", dev_bus_name(con), dev_name(con));
407 	ret = sysfs_create_link(&sup->kobj, &link->link_dev.kobj, buf);
408 	if (ret)
409 		goto err_con_dev;
410 
411 	snprintf(buf, len, "supplier:%s:%s", dev_bus_name(sup), dev_name(sup));
412 	ret = sysfs_create_link(&con->kobj, &link->link_dev.kobj, buf);
413 	if (ret)
414 		goto err_sup_dev;
415 
416 	goto out;
417 
418 err_sup_dev:
419 	snprintf(buf, len, "consumer:%s:%s", dev_bus_name(con), dev_name(con));
420 	sysfs_remove_link(&sup->kobj, buf);
421 err_con_dev:
422 	sysfs_remove_link(&link->link_dev.kobj, "consumer");
423 err_con:
424 	sysfs_remove_link(&link->link_dev.kobj, "supplier");
425 out:
426 	kfree(buf);
427 	return ret;
428 }
429 
devlink_remove_symlinks(struct device * dev,struct class_interface * class_intf)430 static void devlink_remove_symlinks(struct device *dev,
431 				   struct class_interface *class_intf)
432 {
433 	struct device_link *link = to_devlink(dev);
434 	size_t len;
435 	struct device *sup = link->supplier;
436 	struct device *con = link->consumer;
437 	char *buf;
438 
439 	sysfs_remove_link(&link->link_dev.kobj, "consumer");
440 	sysfs_remove_link(&link->link_dev.kobj, "supplier");
441 
442 	len = max(strlen(dev_bus_name(sup)) + strlen(dev_name(sup)),
443 		  strlen(dev_bus_name(con)) + strlen(dev_name(con)));
444 	len += strlen(":");
445 	len += strlen("supplier:") + 1;
446 	buf = kzalloc(len, GFP_KERNEL);
447 	if (!buf) {
448 		WARN(1, "Unable to properly free device link symlinks!\n");
449 		return;
450 	}
451 
452 	if (device_is_registered(con)) {
453 		snprintf(buf, len, "supplier:%s:%s", dev_bus_name(sup), dev_name(sup));
454 		sysfs_remove_link(&con->kobj, buf);
455 	}
456 	snprintf(buf, len, "consumer:%s:%s", dev_bus_name(con), dev_name(con));
457 	sysfs_remove_link(&sup->kobj, buf);
458 	kfree(buf);
459 }
460 
461 static struct class_interface devlink_class_intf = {
462 	.class = &devlink_class,
463 	.add_dev = devlink_add_symlinks,
464 	.remove_dev = devlink_remove_symlinks,
465 };
466 
devlink_class_init(void)467 static int __init devlink_class_init(void)
468 {
469 	int ret;
470 
471 	ret = class_register(&devlink_class);
472 	if (ret)
473 		return ret;
474 
475 	ret = class_interface_register(&devlink_class_intf);
476 	if (ret)
477 		class_unregister(&devlink_class);
478 
479 	return ret;
480 }
481 postcore_initcall(devlink_class_init);
482 
483 #define DL_MANAGED_LINK_FLAGS (DL_FLAG_AUTOREMOVE_CONSUMER | \
484 			       DL_FLAG_AUTOREMOVE_SUPPLIER | \
485 			       DL_FLAG_AUTOPROBE_CONSUMER  | \
486 			       DL_FLAG_SYNC_STATE_ONLY)
487 
488 #define DL_ADD_VALID_FLAGS (DL_MANAGED_LINK_FLAGS | DL_FLAG_STATELESS | \
489 			    DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE)
490 
491 /**
492  * device_link_add - Create a link between two devices.
493  * @consumer: Consumer end of the link.
494  * @supplier: Supplier end of the link.
495  * @flags: Link flags.
496  *
497  * The caller is responsible for the proper synchronization of the link creation
498  * with runtime PM.  First, setting the DL_FLAG_PM_RUNTIME flag will cause the
499  * runtime PM framework to take the link into account.  Second, if the
500  * DL_FLAG_RPM_ACTIVE flag is set in addition to it, the supplier devices will
501  * be forced into the active metastate and reference-counted upon the creation
502  * of the link.  If DL_FLAG_PM_RUNTIME is not set, DL_FLAG_RPM_ACTIVE will be
503  * ignored.
504  *
505  * If DL_FLAG_STATELESS is set in @flags, the caller of this function is
506  * expected to release the link returned by it directly with the help of either
507  * device_link_del() or device_link_remove().
508  *
509  * If that flag is not set, however, the caller of this function is handing the
510  * management of the link over to the driver core entirely and its return value
511  * can only be used to check whether or not the link is present.  In that case,
512  * the DL_FLAG_AUTOREMOVE_CONSUMER and DL_FLAG_AUTOREMOVE_SUPPLIER device link
513  * flags can be used to indicate to the driver core when the link can be safely
514  * deleted.  Namely, setting one of them in @flags indicates to the driver core
515  * that the link is not going to be used (by the given caller of this function)
516  * after unbinding the consumer or supplier driver, respectively, from its
517  * device, so the link can be deleted at that point.  If none of them is set,
518  * the link will be maintained until one of the devices pointed to by it (either
519  * the consumer or the supplier) is unregistered.
520  *
521  * Also, if DL_FLAG_STATELESS, DL_FLAG_AUTOREMOVE_CONSUMER and
522  * DL_FLAG_AUTOREMOVE_SUPPLIER are not set in @flags (that is, a persistent
523  * managed device link is being added), the DL_FLAG_AUTOPROBE_CONSUMER flag can
524  * be used to request the driver core to automaticall probe for a consmer
525  * driver after successfully binding a driver to the supplier device.
526  *
527  * The combination of DL_FLAG_STATELESS and one of DL_FLAG_AUTOREMOVE_CONSUMER,
528  * DL_FLAG_AUTOREMOVE_SUPPLIER, or DL_FLAG_AUTOPROBE_CONSUMER set in @flags at
529  * the same time is invalid and will cause NULL to be returned upfront.
530  * However, if a device link between the given @consumer and @supplier pair
531  * exists already when this function is called for them, the existing link will
532  * be returned regardless of its current type and status (the link's flags may
533  * be modified then).  The caller of this function is then expected to treat
534  * the link as though it has just been created, so (in particular) if
535  * DL_FLAG_STATELESS was passed in @flags, the link needs to be released
536  * explicitly when not needed any more (as stated above).
537  *
538  * A side effect of the link creation is re-ordering of dpm_list and the
539  * devices_kset list by moving the consumer device and all devices depending
540  * on it to the ends of these lists (that does not happen to devices that have
541  * not been registered when this function is called).
542  *
543  * The supplier device is required to be registered when this function is called
544  * and NULL will be returned if that is not the case.  The consumer device need
545  * not be registered, however.
546  */
device_link_add(struct device * consumer,struct device * supplier,u32 flags)547 struct device_link *device_link_add(struct device *consumer,
548 				    struct device *supplier, u32 flags)
549 {
550 	struct device_link *link;
551 
552 	if (!consumer || !supplier || consumer == supplier ||
553 	    flags & ~DL_ADD_VALID_FLAGS ||
554 	    (flags & DL_FLAG_STATELESS && flags & DL_MANAGED_LINK_FLAGS) ||
555 	    (flags & DL_FLAG_SYNC_STATE_ONLY &&
556 	     flags != DL_FLAG_SYNC_STATE_ONLY) ||
557 	    (flags & DL_FLAG_AUTOPROBE_CONSUMER &&
558 	     flags & (DL_FLAG_AUTOREMOVE_CONSUMER |
559 		      DL_FLAG_AUTOREMOVE_SUPPLIER)))
560 		return NULL;
561 
562 	if (flags & DL_FLAG_PM_RUNTIME && flags & DL_FLAG_RPM_ACTIVE) {
563 		if (pm_runtime_get_sync(supplier) < 0) {
564 			pm_runtime_put_noidle(supplier);
565 			return NULL;
566 		}
567 	}
568 
569 	if (!(flags & DL_FLAG_STATELESS))
570 		flags |= DL_FLAG_MANAGED;
571 
572 	device_links_write_lock();
573 	device_pm_lock();
574 
575 	/*
576 	 * If the supplier has not been fully registered yet or there is a
577 	 * reverse (non-SYNC_STATE_ONLY) dependency between the consumer and
578 	 * the supplier already in the graph, return NULL. If the link is a
579 	 * SYNC_STATE_ONLY link, we don't check for reverse dependencies
580 	 * because it only affects sync_state() callbacks.
581 	 */
582 	if (!device_pm_initialized(supplier)
583 	    || (!(flags & DL_FLAG_SYNC_STATE_ONLY) &&
584 		  device_is_dependent(consumer, supplier))) {
585 		link = NULL;
586 		goto out;
587 	}
588 
589 	/*
590 	 * DL_FLAG_AUTOREMOVE_SUPPLIER indicates that the link will be needed
591 	 * longer than for DL_FLAG_AUTOREMOVE_CONSUMER and setting them both
592 	 * together doesn't make sense, so prefer DL_FLAG_AUTOREMOVE_SUPPLIER.
593 	 */
594 	if (flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
595 		flags &= ~DL_FLAG_AUTOREMOVE_CONSUMER;
596 
597 	list_for_each_entry(link, &supplier->links.consumers, s_node) {
598 		if (link->consumer != consumer)
599 			continue;
600 
601 		if (flags & DL_FLAG_PM_RUNTIME) {
602 			if (!(link->flags & DL_FLAG_PM_RUNTIME)) {
603 				pm_runtime_new_link(consumer);
604 				link->flags |= DL_FLAG_PM_RUNTIME;
605 			}
606 			if (flags & DL_FLAG_RPM_ACTIVE)
607 				refcount_inc(&link->rpm_active);
608 		}
609 
610 		if (flags & DL_FLAG_STATELESS) {
611 			kref_get(&link->kref);
612 			if (link->flags & DL_FLAG_SYNC_STATE_ONLY &&
613 			    !(link->flags & DL_FLAG_STATELESS)) {
614 				link->flags |= DL_FLAG_STATELESS;
615 				goto reorder;
616 			} else {
617 				link->flags |= DL_FLAG_STATELESS;
618 				goto out;
619 			}
620 		}
621 
622 		/*
623 		 * If the life time of the link following from the new flags is
624 		 * longer than indicated by the flags of the existing link,
625 		 * update the existing link to stay around longer.
626 		 */
627 		if (flags & DL_FLAG_AUTOREMOVE_SUPPLIER) {
628 			if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER) {
629 				link->flags &= ~DL_FLAG_AUTOREMOVE_CONSUMER;
630 				link->flags |= DL_FLAG_AUTOREMOVE_SUPPLIER;
631 			}
632 		} else if (!(flags & DL_FLAG_AUTOREMOVE_CONSUMER)) {
633 			link->flags &= ~(DL_FLAG_AUTOREMOVE_CONSUMER |
634 					 DL_FLAG_AUTOREMOVE_SUPPLIER);
635 		}
636 		if (!(link->flags & DL_FLAG_MANAGED)) {
637 			kref_get(&link->kref);
638 			link->flags |= DL_FLAG_MANAGED;
639 			device_link_init_status(link, consumer, supplier);
640 		}
641 		if (link->flags & DL_FLAG_SYNC_STATE_ONLY &&
642 		    !(flags & DL_FLAG_SYNC_STATE_ONLY)) {
643 			link->flags &= ~DL_FLAG_SYNC_STATE_ONLY;
644 			goto reorder;
645 		}
646 
647 		goto out;
648 	}
649 
650 	link = kzalloc(sizeof(*link), GFP_KERNEL);
651 	if (!link)
652 		goto out;
653 
654 	refcount_set(&link->rpm_active, 1);
655 
656 	get_device(supplier);
657 	link->supplier = supplier;
658 	INIT_LIST_HEAD(&link->s_node);
659 	get_device(consumer);
660 	link->consumer = consumer;
661 	INIT_LIST_HEAD(&link->c_node);
662 	link->flags = flags;
663 	kref_init(&link->kref);
664 
665 	link->link_dev.class = &devlink_class;
666 	device_set_pm_not_required(&link->link_dev);
667 	dev_set_name(&link->link_dev, "%s:%s--%s:%s",
668 		     dev_bus_name(supplier), dev_name(supplier),
669 		     dev_bus_name(consumer), dev_name(consumer));
670 	if (device_register(&link->link_dev)) {
671 		put_device(&link->link_dev);
672 		link = NULL;
673 		goto out;
674 	}
675 
676 	if (flags & DL_FLAG_PM_RUNTIME) {
677 		if (flags & DL_FLAG_RPM_ACTIVE)
678 			refcount_inc(&link->rpm_active);
679 
680 		pm_runtime_new_link(consumer);
681 	}
682 
683 	/* Determine the initial link state. */
684 	if (flags & DL_FLAG_STATELESS)
685 		link->status = DL_STATE_NONE;
686 	else
687 		device_link_init_status(link, consumer, supplier);
688 
689 	/*
690 	 * Some callers expect the link creation during consumer driver probe to
691 	 * resume the supplier even without DL_FLAG_RPM_ACTIVE.
692 	 */
693 	if (link->status == DL_STATE_CONSUMER_PROBE &&
694 	    flags & DL_FLAG_PM_RUNTIME)
695 		pm_runtime_resume(supplier);
696 
697 	list_add_tail_rcu(&link->s_node, &supplier->links.consumers);
698 	list_add_tail_rcu(&link->c_node, &consumer->links.suppliers);
699 
700 	if (flags & DL_FLAG_SYNC_STATE_ONLY) {
701 		dev_dbg(consumer,
702 			"Linked as a sync state only consumer to %s\n",
703 			dev_name(supplier));
704 		goto out;
705 	}
706 
707 reorder:
708 	/*
709 	 * Move the consumer and all of the devices depending on it to the end
710 	 * of dpm_list and the devices_kset list.
711 	 *
712 	 * It is necessary to hold dpm_list locked throughout all that or else
713 	 * we may end up suspending with a wrong ordering of it.
714 	 */
715 	device_reorder_to_tail(consumer, NULL);
716 
717 	dev_dbg(consumer, "Linked as a consumer to %s\n", dev_name(supplier));
718 
719 out:
720 	device_pm_unlock();
721 	device_links_write_unlock();
722 
723 	if ((flags & DL_FLAG_PM_RUNTIME && flags & DL_FLAG_RPM_ACTIVE) && !link)
724 		pm_runtime_put(supplier);
725 
726 	return link;
727 }
728 EXPORT_SYMBOL_GPL(device_link_add);
729 
730 /**
731  * device_link_wait_for_supplier - Add device to wait_for_suppliers list
732  * @consumer: Consumer device
733  *
734  * Marks the @consumer device as waiting for suppliers to become available by
735  * adding it to the wait_for_suppliers list. The consumer device will never be
736  * probed until it's removed from the wait_for_suppliers list.
737  *
738  * The caller is responsible for adding the links to the supplier devices once
739  * they are available and removing the @consumer device from the
740  * wait_for_suppliers list once links to all the suppliers have been created.
741  *
742  * This function is NOT meant to be called from the probe function of the
743  * consumer but rather from code that creates/adds the consumer device.
744  */
device_link_wait_for_supplier(struct device * consumer,bool need_for_probe)745 static void device_link_wait_for_supplier(struct device *consumer,
746 					  bool need_for_probe)
747 {
748 	mutex_lock(&wfs_lock);
749 	list_add_tail(&consumer->links.needs_suppliers, &wait_for_suppliers);
750 	consumer->links.need_for_probe = need_for_probe;
751 	mutex_unlock(&wfs_lock);
752 }
753 
device_link_wait_for_mandatory_supplier(struct device * consumer)754 static void device_link_wait_for_mandatory_supplier(struct device *consumer)
755 {
756 	device_link_wait_for_supplier(consumer, true);
757 }
758 
device_link_wait_for_optional_supplier(struct device * consumer)759 static void device_link_wait_for_optional_supplier(struct device *consumer)
760 {
761 	device_link_wait_for_supplier(consumer, false);
762 }
763 
764 /**
765  * device_link_add_missing_supplier_links - Add links from consumer devices to
766  *					    supplier devices, leaving any
767  *					    consumer with inactive suppliers on
768  *					    the wait_for_suppliers list
769  *
770  * Loops through all consumers waiting on suppliers and tries to add all their
771  * supplier links. If that succeeds, the consumer device is removed from
772  * wait_for_suppliers list. Otherwise, they are left in the wait_for_suppliers
773  * list.  Devices left on the wait_for_suppliers list will not be probed.
774  *
775  * The fwnode add_links callback is expected to return 0 if it has found and
776  * added all the supplier links for the consumer device. It should return an
777  * error if it isn't able to do so.
778  *
779  * The caller of device_link_wait_for_supplier() is expected to call this once
780  * it's aware of potential suppliers becoming available.
781  */
device_link_add_missing_supplier_links(void)782 static void device_link_add_missing_supplier_links(void)
783 {
784 	struct device *dev, *tmp;
785 
786 	mutex_lock(&wfs_lock);
787 	list_for_each_entry_safe(dev, tmp, &wait_for_suppliers,
788 				 links.needs_suppliers) {
789 		int ret = fwnode_call_int_op(dev->fwnode, add_links, dev);
790 		if (!ret)
791 			list_del_init(&dev->links.needs_suppliers);
792 		else if (ret != -ENODEV || fw_devlink_is_permissive())
793 			dev->links.need_for_probe = false;
794 	}
795 	mutex_unlock(&wfs_lock);
796 }
797 
798 #ifdef CONFIG_SRCU
__device_link_del(struct kref * kref)799 static void __device_link_del(struct kref *kref)
800 {
801 	struct device_link *link = container_of(kref, struct device_link, kref);
802 
803 	dev_dbg(link->consumer, "Dropping the link to %s\n",
804 		dev_name(link->supplier));
805 
806 	pm_runtime_drop_link(link);
807 
808 	list_del_rcu(&link->s_node);
809 	list_del_rcu(&link->c_node);
810 	device_unregister(&link->link_dev);
811 }
812 #else /* !CONFIG_SRCU */
__device_link_del(struct kref * kref)813 static void __device_link_del(struct kref *kref)
814 {
815 	struct device_link *link = container_of(kref, struct device_link, kref);
816 
817 	dev_info(link->consumer, "Dropping the link to %s\n",
818 		 dev_name(link->supplier));
819 
820 	pm_runtime_drop_link(link);
821 
822 	list_del(&link->s_node);
823 	list_del(&link->c_node);
824 	device_unregister(&link->link_dev);
825 }
826 #endif /* !CONFIG_SRCU */
827 
device_link_put_kref(struct device_link * link)828 static void device_link_put_kref(struct device_link *link)
829 {
830 	if (link->flags & DL_FLAG_STATELESS)
831 		kref_put(&link->kref, __device_link_del);
832 	else
833 		WARN(1, "Unable to drop a managed device link reference\n");
834 }
835 
836 /**
837  * device_link_del - Delete a stateless link between two devices.
838  * @link: Device link to delete.
839  *
840  * The caller must ensure proper synchronization of this function with runtime
841  * PM.  If the link was added multiple times, it needs to be deleted as often.
842  * Care is required for hotplugged devices:  Their links are purged on removal
843  * and calling device_link_del() is then no longer allowed.
844  */
device_link_del(struct device_link * link)845 void device_link_del(struct device_link *link)
846 {
847 	device_links_write_lock();
848 	device_link_put_kref(link);
849 	device_links_write_unlock();
850 }
851 EXPORT_SYMBOL_GPL(device_link_del);
852 
853 /**
854  * device_link_remove - Delete a stateless link between two devices.
855  * @consumer: Consumer end of the link.
856  * @supplier: Supplier end of the link.
857  *
858  * The caller must ensure proper synchronization of this function with runtime
859  * PM.
860  */
device_link_remove(void * consumer,struct device * supplier)861 void device_link_remove(void *consumer, struct device *supplier)
862 {
863 	struct device_link *link;
864 
865 	if (WARN_ON(consumer == supplier))
866 		return;
867 
868 	device_links_write_lock();
869 
870 	list_for_each_entry(link, &supplier->links.consumers, s_node) {
871 		if (link->consumer == consumer) {
872 			device_link_put_kref(link);
873 			break;
874 		}
875 	}
876 
877 	device_links_write_unlock();
878 }
879 EXPORT_SYMBOL_GPL(device_link_remove);
880 
device_links_missing_supplier(struct device * dev)881 static void device_links_missing_supplier(struct device *dev)
882 {
883 	struct device_link *link;
884 
885 	list_for_each_entry(link, &dev->links.suppliers, c_node) {
886 		if (link->status != DL_STATE_CONSUMER_PROBE)
887 			continue;
888 
889 		if (link->supplier->links.status == DL_DEV_DRIVER_BOUND) {
890 			WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
891 		} else {
892 			WARN_ON(!(link->flags & DL_FLAG_SYNC_STATE_ONLY));
893 			WRITE_ONCE(link->status, DL_STATE_DORMANT);
894 		}
895 	}
896 }
897 
898 /**
899  * device_links_check_suppliers - Check presence of supplier drivers.
900  * @dev: Consumer device.
901  *
902  * Check links from this device to any suppliers.  Walk the list of the device's
903  * links to suppliers and see if all of them are available.  If not, simply
904  * return -EPROBE_DEFER.
905  *
906  * We need to guarantee that the supplier will not go away after the check has
907  * been positive here.  It only can go away in __device_release_driver() and
908  * that function  checks the device's links to consumers.  This means we need to
909  * mark the link as "consumer probe in progress" to make the supplier removal
910  * wait for us to complete (or bad things may happen).
911  *
912  * Links without the DL_FLAG_MANAGED flag set are ignored.
913  */
device_links_check_suppliers(struct device * dev)914 int device_links_check_suppliers(struct device *dev)
915 {
916 	struct device_link *link;
917 	int ret = 0;
918 
919 	/*
920 	 * Device waiting for supplier to become available is not allowed to
921 	 * probe.
922 	 */
923 	mutex_lock(&wfs_lock);
924 	if (!list_empty(&dev->links.needs_suppliers) &&
925 	    dev->links.need_for_probe) {
926 		mutex_unlock(&wfs_lock);
927 		return -EPROBE_DEFER;
928 	}
929 	mutex_unlock(&wfs_lock);
930 
931 	device_links_write_lock();
932 
933 	list_for_each_entry(link, &dev->links.suppliers, c_node) {
934 		if (!(link->flags & DL_FLAG_MANAGED))
935 			continue;
936 
937 		if (link->status != DL_STATE_AVAILABLE &&
938 		    !(link->flags & DL_FLAG_SYNC_STATE_ONLY)) {
939 			device_links_missing_supplier(dev);
940 			ret = -EPROBE_DEFER;
941 			break;
942 		}
943 		WRITE_ONCE(link->status, DL_STATE_CONSUMER_PROBE);
944 	}
945 	dev->links.status = DL_DEV_PROBING;
946 
947 	device_links_write_unlock();
948 	return ret;
949 }
950 
951 /**
952  * __device_links_queue_sync_state - Queue a device for sync_state() callback
953  * @dev: Device to call sync_state() on
954  * @list: List head to queue the @dev on
955  *
956  * Queues a device for a sync_state() callback when the device links write lock
957  * isn't held. This allows the sync_state() execution flow to use device links
958  * APIs.  The caller must ensure this function is called with
959  * device_links_write_lock() held.
960  *
961  * This function does a get_device() to make sure the device is not freed while
962  * on this list.
963  *
964  * So the caller must also ensure that device_links_flush_sync_list() is called
965  * as soon as the caller releases device_links_write_lock().  This is necessary
966  * to make sure the sync_state() is called in a timely fashion and the
967  * put_device() is called on this device.
968  */
__device_links_queue_sync_state(struct device * dev,struct list_head * list)969 static void __device_links_queue_sync_state(struct device *dev,
970 					    struct list_head *list)
971 {
972 	struct device_link *link;
973 
974 	if (!dev_has_sync_state(dev))
975 		return;
976 	if (dev->state_synced)
977 		return;
978 
979 	list_for_each_entry(link, &dev->links.consumers, s_node) {
980 		if (!(link->flags & DL_FLAG_MANAGED))
981 			continue;
982 		if (link->status != DL_STATE_ACTIVE)
983 			return;
984 	}
985 
986 	/*
987 	 * Set the flag here to avoid adding the same device to a list more
988 	 * than once. This can happen if new consumers get added to the device
989 	 * and probed before the list is flushed.
990 	 */
991 	dev->state_synced = true;
992 
993 	if (WARN_ON(!list_empty(&dev->links.defer_hook)))
994 		return;
995 
996 	get_device(dev);
997 	list_add_tail(&dev->links.defer_hook, list);
998 }
999 
1000 /**
1001  * device_links_flush_sync_list - Call sync_state() on a list of devices
1002  * @list: List of devices to call sync_state() on
1003  * @dont_lock_dev: Device for which lock is already held by the caller
1004  *
1005  * Calls sync_state() on all the devices that have been queued for it. This
1006  * function is used in conjunction with __device_links_queue_sync_state(). The
1007  * @dont_lock_dev parameter is useful when this function is called from a
1008  * context where a device lock is already held.
1009  */
device_links_flush_sync_list(struct list_head * list,struct device * dont_lock_dev)1010 static void device_links_flush_sync_list(struct list_head *list,
1011 					 struct device *dont_lock_dev)
1012 {
1013 	struct device *dev, *tmp;
1014 
1015 	list_for_each_entry_safe(dev, tmp, list, links.defer_hook) {
1016 		list_del_init(&dev->links.defer_hook);
1017 
1018 		if (dev != dont_lock_dev)
1019 			device_lock(dev);
1020 
1021 		if (dev->bus->sync_state)
1022 			dev->bus->sync_state(dev);
1023 		else if (dev->driver && dev->driver->sync_state)
1024 			dev->driver->sync_state(dev);
1025 
1026 		if (dev != dont_lock_dev)
1027 			device_unlock(dev);
1028 
1029 		put_device(dev);
1030 	}
1031 }
1032 
device_links_supplier_sync_state_pause(void)1033 void device_links_supplier_sync_state_pause(void)
1034 {
1035 	device_links_write_lock();
1036 	defer_sync_state_count++;
1037 	device_links_write_unlock();
1038 }
1039 
device_links_supplier_sync_state_resume(void)1040 void device_links_supplier_sync_state_resume(void)
1041 {
1042 	struct device *dev, *tmp;
1043 	LIST_HEAD(sync_list);
1044 
1045 	device_links_write_lock();
1046 	if (!defer_sync_state_count) {
1047 		WARN(true, "Unmatched sync_state pause/resume!");
1048 		goto out;
1049 	}
1050 	defer_sync_state_count--;
1051 	if (defer_sync_state_count)
1052 		goto out;
1053 
1054 	list_for_each_entry_safe(dev, tmp, &deferred_sync, links.defer_hook) {
1055 		/*
1056 		 * Delete from deferred_sync list before queuing it to
1057 		 * sync_list because defer_hook is used for both lists.
1058 		 */
1059 		list_del_init(&dev->links.defer_hook);
1060 		__device_links_queue_sync_state(dev, &sync_list);
1061 	}
1062 out:
1063 	device_links_write_unlock();
1064 
1065 	device_links_flush_sync_list(&sync_list, NULL);
1066 }
1067 
sync_state_resume_initcall(void)1068 static int sync_state_resume_initcall(void)
1069 {
1070 	device_links_supplier_sync_state_resume();
1071 	return 0;
1072 }
1073 late_initcall(sync_state_resume_initcall);
1074 
__device_links_supplier_defer_sync(struct device * sup)1075 static void __device_links_supplier_defer_sync(struct device *sup)
1076 {
1077 	if (list_empty(&sup->links.defer_hook) && dev_has_sync_state(sup))
1078 		list_add_tail(&sup->links.defer_hook, &deferred_sync);
1079 }
1080 
device_link_drop_managed(struct device_link * link)1081 static void device_link_drop_managed(struct device_link *link)
1082 {
1083 	link->flags &= ~DL_FLAG_MANAGED;
1084 	WRITE_ONCE(link->status, DL_STATE_NONE);
1085 	kref_put(&link->kref, __device_link_del);
1086 }
1087 
waiting_for_supplier_show(struct device * dev,struct device_attribute * attr,char * buf)1088 static ssize_t waiting_for_supplier_show(struct device *dev,
1089 					 struct device_attribute *attr,
1090 					 char *buf)
1091 {
1092 	bool val;
1093 
1094 	device_lock(dev);
1095 	mutex_lock(&wfs_lock);
1096 	val = !list_empty(&dev->links.needs_suppliers)
1097 	      && dev->links.need_for_probe;
1098 	mutex_unlock(&wfs_lock);
1099 	device_unlock(dev);
1100 	return sysfs_emit(buf, "%u\n", val);
1101 }
1102 static DEVICE_ATTR_RO(waiting_for_supplier);
1103 
1104 /**
1105  * device_links_driver_bound - Update device links after probing its driver.
1106  * @dev: Device to update the links for.
1107  *
1108  * The probe has been successful, so update links from this device to any
1109  * consumers by changing their status to "available".
1110  *
1111  * Also change the status of @dev's links to suppliers to "active".
1112  *
1113  * Links without the DL_FLAG_MANAGED flag set are ignored.
1114  */
device_links_driver_bound(struct device * dev)1115 void device_links_driver_bound(struct device *dev)
1116 {
1117 	struct device_link *link, *ln;
1118 	LIST_HEAD(sync_list);
1119 
1120 	/*
1121 	 * If a device probes successfully, it's expected to have created all
1122 	 * the device links it needs to or make new device links as it needs
1123 	 * them. So, it no longer needs to wait on any suppliers.
1124 	 */
1125 	mutex_lock(&wfs_lock);
1126 	list_del_init(&dev->links.needs_suppliers);
1127 	mutex_unlock(&wfs_lock);
1128 	device_remove_file(dev, &dev_attr_waiting_for_supplier);
1129 
1130 	device_links_write_lock();
1131 
1132 	list_for_each_entry(link, &dev->links.consumers, s_node) {
1133 		if (!(link->flags & DL_FLAG_MANAGED))
1134 			continue;
1135 
1136 		/*
1137 		 * Links created during consumer probe may be in the "consumer
1138 		 * probe" state to start with if the supplier is still probing
1139 		 * when they are created and they may become "active" if the
1140 		 * consumer probe returns first.  Skip them here.
1141 		 */
1142 		if (link->status == DL_STATE_CONSUMER_PROBE ||
1143 		    link->status == DL_STATE_ACTIVE)
1144 			continue;
1145 
1146 		WARN_ON(link->status != DL_STATE_DORMANT);
1147 		WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
1148 
1149 		if (link->flags & DL_FLAG_AUTOPROBE_CONSUMER)
1150 			driver_deferred_probe_add(link->consumer);
1151 	}
1152 
1153 	if (defer_sync_state_count)
1154 		__device_links_supplier_defer_sync(dev);
1155 	else
1156 		__device_links_queue_sync_state(dev, &sync_list);
1157 
1158 	list_for_each_entry_safe(link, ln, &dev->links.suppliers, c_node) {
1159 		struct device *supplier;
1160 
1161 		if (!(link->flags & DL_FLAG_MANAGED))
1162 			continue;
1163 
1164 		supplier = link->supplier;
1165 		if (link->flags & DL_FLAG_SYNC_STATE_ONLY) {
1166 			/*
1167 			 * When DL_FLAG_SYNC_STATE_ONLY is set, it means no
1168 			 * other DL_MANAGED_LINK_FLAGS have been set. So, it's
1169 			 * save to drop the managed link completely.
1170 			 */
1171 			device_link_drop_managed(link);
1172 		} else {
1173 			WARN_ON(link->status != DL_STATE_CONSUMER_PROBE);
1174 			WRITE_ONCE(link->status, DL_STATE_ACTIVE);
1175 		}
1176 
1177 		/*
1178 		 * This needs to be done even for the deleted
1179 		 * DL_FLAG_SYNC_STATE_ONLY device link in case it was the last
1180 		 * device link that was preventing the supplier from getting a
1181 		 * sync_state() call.
1182 		 */
1183 		if (defer_sync_state_count)
1184 			__device_links_supplier_defer_sync(supplier);
1185 		else
1186 			__device_links_queue_sync_state(supplier, &sync_list);
1187 	}
1188 
1189 	dev->links.status = DL_DEV_DRIVER_BOUND;
1190 
1191 	device_links_write_unlock();
1192 
1193 	device_links_flush_sync_list(&sync_list, dev);
1194 }
1195 
1196 /**
1197  * __device_links_no_driver - Update links of a device without a driver.
1198  * @dev: Device without a drvier.
1199  *
1200  * Delete all non-persistent links from this device to any suppliers.
1201  *
1202  * Persistent links stay around, but their status is changed to "available",
1203  * unless they already are in the "supplier unbind in progress" state in which
1204  * case they need not be updated.
1205  *
1206  * Links without the DL_FLAG_MANAGED flag set are ignored.
1207  */
__device_links_no_driver(struct device * dev)1208 static void __device_links_no_driver(struct device *dev)
1209 {
1210 	struct device_link *link, *ln;
1211 
1212 	list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
1213 		if (!(link->flags & DL_FLAG_MANAGED))
1214 			continue;
1215 
1216 		if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER) {
1217 			device_link_drop_managed(link);
1218 			continue;
1219 		}
1220 
1221 		if (link->status != DL_STATE_CONSUMER_PROBE &&
1222 		    link->status != DL_STATE_ACTIVE)
1223 			continue;
1224 
1225 		if (link->supplier->links.status == DL_DEV_DRIVER_BOUND) {
1226 			WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
1227 		} else {
1228 			WARN_ON(!(link->flags & DL_FLAG_SYNC_STATE_ONLY));
1229 			WRITE_ONCE(link->status, DL_STATE_DORMANT);
1230 		}
1231 	}
1232 
1233 	dev->links.status = DL_DEV_NO_DRIVER;
1234 }
1235 
1236 /**
1237  * device_links_no_driver - Update links after failing driver probe.
1238  * @dev: Device whose driver has just failed to probe.
1239  *
1240  * Clean up leftover links to consumers for @dev and invoke
1241  * %__device_links_no_driver() to update links to suppliers for it as
1242  * appropriate.
1243  *
1244  * Links without the DL_FLAG_MANAGED flag set are ignored.
1245  */
device_links_no_driver(struct device * dev)1246 void device_links_no_driver(struct device *dev)
1247 {
1248 	struct device_link *link;
1249 
1250 	device_links_write_lock();
1251 
1252 	list_for_each_entry(link, &dev->links.consumers, s_node) {
1253 		if (!(link->flags & DL_FLAG_MANAGED))
1254 			continue;
1255 
1256 		/*
1257 		 * The probe has failed, so if the status of the link is
1258 		 * "consumer probe" or "active", it must have been added by
1259 		 * a probing consumer while this device was still probing.
1260 		 * Change its state to "dormant", as it represents a valid
1261 		 * relationship, but it is not functionally meaningful.
1262 		 */
1263 		if (link->status == DL_STATE_CONSUMER_PROBE ||
1264 		    link->status == DL_STATE_ACTIVE)
1265 			WRITE_ONCE(link->status, DL_STATE_DORMANT);
1266 	}
1267 
1268 	__device_links_no_driver(dev);
1269 
1270 	device_links_write_unlock();
1271 }
1272 
1273 /**
1274  * device_links_driver_cleanup - Update links after driver removal.
1275  * @dev: Device whose driver has just gone away.
1276  *
1277  * Update links to consumers for @dev by changing their status to "dormant" and
1278  * invoke %__device_links_no_driver() to update links to suppliers for it as
1279  * appropriate.
1280  *
1281  * Links without the DL_FLAG_MANAGED flag set are ignored.
1282  */
device_links_driver_cleanup(struct device * dev)1283 void device_links_driver_cleanup(struct device *dev)
1284 {
1285 	struct device_link *link, *ln;
1286 
1287 	device_links_write_lock();
1288 
1289 	list_for_each_entry_safe(link, ln, &dev->links.consumers, s_node) {
1290 		if (!(link->flags & DL_FLAG_MANAGED))
1291 			continue;
1292 
1293 		WARN_ON(link->flags & DL_FLAG_AUTOREMOVE_CONSUMER);
1294 		WARN_ON(link->status != DL_STATE_SUPPLIER_UNBIND);
1295 
1296 		/*
1297 		 * autoremove the links between this @dev and its consumer
1298 		 * devices that are not active, i.e. where the link state
1299 		 * has moved to DL_STATE_SUPPLIER_UNBIND.
1300 		 */
1301 		if (link->status == DL_STATE_SUPPLIER_UNBIND &&
1302 		    link->flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
1303 			device_link_drop_managed(link);
1304 
1305 		WRITE_ONCE(link->status, DL_STATE_DORMANT);
1306 	}
1307 
1308 	list_del_init(&dev->links.defer_hook);
1309 	__device_links_no_driver(dev);
1310 
1311 	device_links_write_unlock();
1312 }
1313 
1314 /**
1315  * device_links_busy - Check if there are any busy links to consumers.
1316  * @dev: Device to check.
1317  *
1318  * Check each consumer of the device and return 'true' if its link's status
1319  * is one of "consumer probe" or "active" (meaning that the given consumer is
1320  * probing right now or its driver is present).  Otherwise, change the link
1321  * state to "supplier unbind" to prevent the consumer from being probed
1322  * successfully going forward.
1323  *
1324  * Return 'false' if there are no probing or active consumers.
1325  *
1326  * Links without the DL_FLAG_MANAGED flag set are ignored.
1327  */
device_links_busy(struct device * dev)1328 bool device_links_busy(struct device *dev)
1329 {
1330 	struct device_link *link;
1331 	bool ret = false;
1332 
1333 	device_links_write_lock();
1334 
1335 	list_for_each_entry(link, &dev->links.consumers, s_node) {
1336 		if (!(link->flags & DL_FLAG_MANAGED))
1337 			continue;
1338 
1339 		if (link->status == DL_STATE_CONSUMER_PROBE
1340 		    || link->status == DL_STATE_ACTIVE) {
1341 			ret = true;
1342 			break;
1343 		}
1344 		WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
1345 	}
1346 
1347 	dev->links.status = DL_DEV_UNBINDING;
1348 
1349 	device_links_write_unlock();
1350 	return ret;
1351 }
1352 
1353 /**
1354  * device_links_unbind_consumers - Force unbind consumers of the given device.
1355  * @dev: Device to unbind the consumers of.
1356  *
1357  * Walk the list of links to consumers for @dev and if any of them is in the
1358  * "consumer probe" state, wait for all device probes in progress to complete
1359  * and start over.
1360  *
1361  * If that's not the case, change the status of the link to "supplier unbind"
1362  * and check if the link was in the "active" state.  If so, force the consumer
1363  * driver to unbind and start over (the consumer will not re-probe as we have
1364  * changed the state of the link already).
1365  *
1366  * Links without the DL_FLAG_MANAGED flag set are ignored.
1367  */
device_links_unbind_consumers(struct device * dev)1368 void device_links_unbind_consumers(struct device *dev)
1369 {
1370 	struct device_link *link;
1371 
1372  start:
1373 	device_links_write_lock();
1374 
1375 	list_for_each_entry(link, &dev->links.consumers, s_node) {
1376 		enum device_link_state status;
1377 
1378 		if (!(link->flags & DL_FLAG_MANAGED) ||
1379 		    link->flags & DL_FLAG_SYNC_STATE_ONLY)
1380 			continue;
1381 
1382 		status = link->status;
1383 		if (status == DL_STATE_CONSUMER_PROBE) {
1384 			device_links_write_unlock();
1385 
1386 			wait_for_device_probe();
1387 			goto start;
1388 		}
1389 		WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
1390 		if (status == DL_STATE_ACTIVE) {
1391 			struct device *consumer = link->consumer;
1392 
1393 			get_device(consumer);
1394 
1395 			device_links_write_unlock();
1396 
1397 			device_release_driver_internal(consumer, NULL,
1398 						       consumer->parent);
1399 			put_device(consumer);
1400 			goto start;
1401 		}
1402 	}
1403 
1404 	device_links_write_unlock();
1405 }
1406 
1407 /**
1408  * device_links_purge - Delete existing links to other devices.
1409  * @dev: Target device.
1410  */
device_links_purge(struct device * dev)1411 static void device_links_purge(struct device *dev)
1412 {
1413 	struct device_link *link, *ln;
1414 
1415 	if (dev->class == &devlink_class)
1416 		return;
1417 
1418 	mutex_lock(&wfs_lock);
1419 	list_del_init(&dev->links.needs_suppliers);
1420 	mutex_unlock(&wfs_lock);
1421 
1422 	/*
1423 	 * Delete all of the remaining links from this device to any other
1424 	 * devices (either consumers or suppliers).
1425 	 */
1426 	device_links_write_lock();
1427 
1428 	list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
1429 		WARN_ON(link->status == DL_STATE_ACTIVE);
1430 		__device_link_del(&link->kref);
1431 	}
1432 
1433 	list_for_each_entry_safe_reverse(link, ln, &dev->links.consumers, s_node) {
1434 		WARN_ON(link->status != DL_STATE_DORMANT &&
1435 			link->status != DL_STATE_NONE);
1436 		__device_link_del(&link->kref);
1437 	}
1438 
1439 	device_links_write_unlock();
1440 }
1441 
1442 static u32 fw_devlink_flags = DL_FLAG_SYNC_STATE_ONLY;
fw_devlink_setup(char * arg)1443 static int __init fw_devlink_setup(char *arg)
1444 {
1445 	if (!arg)
1446 		return -EINVAL;
1447 
1448 	if (strcmp(arg, "off") == 0) {
1449 		fw_devlink_flags = 0;
1450 	} else if (strcmp(arg, "permissive") == 0) {
1451 		fw_devlink_flags = DL_FLAG_SYNC_STATE_ONLY;
1452 	} else if (strcmp(arg, "on") == 0) {
1453 		fw_devlink_flags = DL_FLAG_AUTOPROBE_CONSUMER;
1454 	} else if (strcmp(arg, "rpm") == 0) {
1455 		fw_devlink_flags = DL_FLAG_AUTOPROBE_CONSUMER |
1456 				   DL_FLAG_PM_RUNTIME;
1457 	}
1458 	return 0;
1459 }
1460 early_param("fw_devlink", fw_devlink_setup);
1461 
fw_devlink_get_flags(void)1462 u32 fw_devlink_get_flags(void)
1463 {
1464 	return fw_devlink_flags;
1465 }
1466 
fw_devlink_is_permissive(void)1467 static bool fw_devlink_is_permissive(void)
1468 {
1469 	return fw_devlink_flags == DL_FLAG_SYNC_STATE_ONLY;
1470 }
1471 
fw_devlink_link_device(struct device * dev)1472 static void fw_devlink_link_device(struct device *dev)
1473 {
1474 	int fw_ret;
1475 
1476 	if (!fw_devlink_flags)
1477 		return;
1478 
1479 	mutex_lock(&defer_fw_devlink_lock);
1480 	if (!defer_fw_devlink_count)
1481 		device_link_add_missing_supplier_links();
1482 
1483 	/*
1484 	 * The device's fwnode not having add_links() doesn't affect if other
1485 	 * consumers can find this device as a supplier.  So, this check is
1486 	 * intentionally placed after device_link_add_missing_supplier_links().
1487 	 */
1488 	if (!fwnode_has_op(dev->fwnode, add_links))
1489 		goto out;
1490 
1491 	/*
1492 	 * If fw_devlink is being deferred, assume all devices have mandatory
1493 	 * suppliers they need to link to later. Then, when the fw_devlink is
1494 	 * resumed, all these devices will get a chance to try and link to any
1495 	 * suppliers they have.
1496 	 */
1497 	if (!defer_fw_devlink_count) {
1498 		fw_ret = fwnode_call_int_op(dev->fwnode, add_links, dev);
1499 		if (fw_ret == -ENODEV && fw_devlink_is_permissive())
1500 			fw_ret = -EAGAIN;
1501 	} else {
1502 		fw_ret = -ENODEV;
1503 		/*
1504 		 * defer_hook is not used to add device to deferred_sync list
1505 		 * until device is bound. Since deferred fw devlink also blocks
1506 		 * probing, same list hook can be used for deferred_fw_devlink.
1507 		 */
1508 		list_add_tail(&dev->links.defer_hook, &deferred_fw_devlink);
1509 	}
1510 
1511 	if (fw_ret == -ENODEV)
1512 		device_link_wait_for_mandatory_supplier(dev);
1513 	else if (fw_ret)
1514 		device_link_wait_for_optional_supplier(dev);
1515 
1516 out:
1517 	mutex_unlock(&defer_fw_devlink_lock);
1518 }
1519 
1520 /**
1521  * fw_devlink_pause - Pause parsing of fwnode to create device links
1522  *
1523  * Calling this function defers any fwnode parsing to create device links until
1524  * fw_devlink_resume() is called. Both these functions are ref counted and the
1525  * caller needs to match the calls.
1526  *
1527  * While fw_devlink is paused:
1528  * - Any device that is added won't have its fwnode parsed to create device
1529  *   links.
1530  * - The probe of the device will also be deferred during this period.
1531  * - Any devices that were already added, but waiting for suppliers won't be
1532  *   able to link to newly added devices.
1533  *
1534  * Once fw_devlink_resume():
1535  * - All the fwnodes that was not parsed will be parsed.
1536  * - All the devices that were deferred probing will be reattempted if they
1537  *   aren't waiting for any more suppliers.
1538  *
1539  * This pair of functions, is mainly meant to optimize the parsing of fwnodes
1540  * when a lot of devices that need to link to each other are added in a short
1541  * interval of time. For example, adding all the top level devices in a system.
1542  *
1543  * For example, if N devices are added and:
1544  * - All the consumers are added before their suppliers
1545  * - All the suppliers of the N devices are part of the N devices
1546  *
1547  * Then:
1548  *
1549  * - With the use of fw_devlink_pause() and fw_devlink_resume(), each device
1550  *   will only need one parsing of its fwnode because it is guaranteed to find
1551  *   all the supplier devices already registered and ready to link to. It won't
1552  *   have to do another pass later to find one or more suppliers it couldn't
1553  *   find in the first parse of the fwnode. So, we'll only need O(N) fwnode
1554  *   parses.
1555  *
1556  * - Without the use of fw_devlink_pause() and fw_devlink_resume(), we would
1557  *   end up doing O(N^2) parses of fwnodes because every device that's added is
1558  *   guaranteed to trigger a parse of the fwnode of every device added before
1559  *   it. This O(N^2) parse is made worse by the fact that when a fwnode of a
1560  *   device is parsed, all it descendant devices might need to have their
1561  *   fwnodes parsed too (even if the devices themselves aren't added).
1562  */
fw_devlink_pause(void)1563 void fw_devlink_pause(void)
1564 {
1565 	mutex_lock(&defer_fw_devlink_lock);
1566 	defer_fw_devlink_count++;
1567 	mutex_unlock(&defer_fw_devlink_lock);
1568 }
1569 
1570 /** fw_devlink_resume - Resume parsing of fwnode to create device links
1571  *
1572  * This function is used in conjunction with fw_devlink_pause() and is ref
1573  * counted. See documentation for fw_devlink_pause() for more details.
1574  */
fw_devlink_resume(void)1575 void fw_devlink_resume(void)
1576 {
1577 	struct device *dev, *tmp;
1578 	LIST_HEAD(probe_list);
1579 
1580 	mutex_lock(&defer_fw_devlink_lock);
1581 	if (!defer_fw_devlink_count) {
1582 		WARN(true, "Unmatched fw_devlink pause/resume!");
1583 		goto out;
1584 	}
1585 
1586 	defer_fw_devlink_count--;
1587 	if (defer_fw_devlink_count)
1588 		goto out;
1589 
1590 	device_link_add_missing_supplier_links();
1591 	list_splice_tail_init(&deferred_fw_devlink, &probe_list);
1592 out:
1593 	mutex_unlock(&defer_fw_devlink_lock);
1594 
1595 	/*
1596 	 * bus_probe_device() can cause new devices to get added and they'll
1597 	 * try to grab defer_fw_devlink_lock. So, this needs to be done outside
1598 	 * the defer_fw_devlink_lock.
1599 	 */
1600 	list_for_each_entry_safe(dev, tmp, &probe_list, links.defer_hook) {
1601 		list_del_init(&dev->links.defer_hook);
1602 		bus_probe_device(dev);
1603 	}
1604 }
1605 /* Device links support end. */
1606 
1607 int (*platform_notify)(struct device *dev) = NULL;
1608 int (*platform_notify_remove)(struct device *dev) = NULL;
1609 static struct kobject *dev_kobj;
1610 struct kobject *sysfs_dev_char_kobj;
1611 struct kobject *sysfs_dev_block_kobj;
1612 
1613 static DEFINE_MUTEX(device_hotplug_lock);
1614 
lock_device_hotplug(void)1615 void lock_device_hotplug(void)
1616 {
1617 	mutex_lock(&device_hotplug_lock);
1618 }
1619 
unlock_device_hotplug(void)1620 void unlock_device_hotplug(void)
1621 {
1622 	mutex_unlock(&device_hotplug_lock);
1623 }
1624 
lock_device_hotplug_sysfs(void)1625 int lock_device_hotplug_sysfs(void)
1626 {
1627 	if (mutex_trylock(&device_hotplug_lock))
1628 		return 0;
1629 
1630 	/* Avoid busy looping (5 ms of sleep should do). */
1631 	msleep(5);
1632 	return restart_syscall();
1633 }
1634 
1635 #ifdef CONFIG_BLOCK
device_is_not_partition(struct device * dev)1636 static inline int device_is_not_partition(struct device *dev)
1637 {
1638 	return !(dev->type == &part_type);
1639 }
1640 #else
device_is_not_partition(struct device * dev)1641 static inline int device_is_not_partition(struct device *dev)
1642 {
1643 	return 1;
1644 }
1645 #endif
1646 
1647 static int
device_platform_notify(struct device * dev,enum kobject_action action)1648 device_platform_notify(struct device *dev, enum kobject_action action)
1649 {
1650 	int ret;
1651 
1652 	ret = acpi_platform_notify(dev, action);
1653 	if (ret)
1654 		return ret;
1655 
1656 	ret = software_node_notify(dev, action);
1657 	if (ret)
1658 		return ret;
1659 
1660 	if (platform_notify && action == KOBJ_ADD)
1661 		platform_notify(dev);
1662 	else if (platform_notify_remove && action == KOBJ_REMOVE)
1663 		platform_notify_remove(dev);
1664 	return 0;
1665 }
1666 
1667 /**
1668  * dev_driver_string - Return a device's driver name, if at all possible
1669  * @dev: struct device to get the name of
1670  *
1671  * Will return the device's driver's name if it is bound to a device.  If
1672  * the device is not bound to a driver, it will return the name of the bus
1673  * it is attached to.  If it is not attached to a bus either, an empty
1674  * string will be returned.
1675  */
dev_driver_string(const struct device * dev)1676 const char *dev_driver_string(const struct device *dev)
1677 {
1678 	struct device_driver *drv;
1679 
1680 	/* dev->driver can change to NULL underneath us because of unbinding,
1681 	 * so be careful about accessing it.  dev->bus and dev->class should
1682 	 * never change once they are set, so they don't need special care.
1683 	 */
1684 	drv = READ_ONCE(dev->driver);
1685 	return drv ? drv->name : dev_bus_name(dev);
1686 }
1687 EXPORT_SYMBOL(dev_driver_string);
1688 
1689 #define to_dev_attr(_attr) container_of(_attr, struct device_attribute, attr)
1690 
dev_attr_show(struct kobject * kobj,struct attribute * attr,char * buf)1691 static ssize_t dev_attr_show(struct kobject *kobj, struct attribute *attr,
1692 			     char *buf)
1693 {
1694 	struct device_attribute *dev_attr = to_dev_attr(attr);
1695 	struct device *dev = kobj_to_dev(kobj);
1696 	ssize_t ret = -EIO;
1697 
1698 	if (dev_attr->show)
1699 		ret = dev_attr->show(dev, dev_attr, buf);
1700 	if (ret >= (ssize_t)PAGE_SIZE) {
1701 		printk("dev_attr_show: %pS returned bad count\n",
1702 				dev_attr->show);
1703 	}
1704 	return ret;
1705 }
1706 
dev_attr_store(struct kobject * kobj,struct attribute * attr,const char * buf,size_t count)1707 static ssize_t dev_attr_store(struct kobject *kobj, struct attribute *attr,
1708 			      const char *buf, size_t count)
1709 {
1710 	struct device_attribute *dev_attr = to_dev_attr(attr);
1711 	struct device *dev = kobj_to_dev(kobj);
1712 	ssize_t ret = -EIO;
1713 
1714 	if (dev_attr->store)
1715 		ret = dev_attr->store(dev, dev_attr, buf, count);
1716 	return ret;
1717 }
1718 
1719 static const struct sysfs_ops dev_sysfs_ops = {
1720 	.show	= dev_attr_show,
1721 	.store	= dev_attr_store,
1722 };
1723 
1724 #define to_ext_attr(x) container_of(x, struct dev_ext_attribute, attr)
1725 
device_store_ulong(struct device * dev,struct device_attribute * attr,const char * buf,size_t size)1726 ssize_t device_store_ulong(struct device *dev,
1727 			   struct device_attribute *attr,
1728 			   const char *buf, size_t size)
1729 {
1730 	struct dev_ext_attribute *ea = to_ext_attr(attr);
1731 	int ret;
1732 	unsigned long new;
1733 
1734 	ret = kstrtoul(buf, 0, &new);
1735 	if (ret)
1736 		return ret;
1737 	*(unsigned long *)(ea->var) = new;
1738 	/* Always return full write size even if we didn't consume all */
1739 	return size;
1740 }
1741 EXPORT_SYMBOL_GPL(device_store_ulong);
1742 
device_show_ulong(struct device * dev,struct device_attribute * attr,char * buf)1743 ssize_t device_show_ulong(struct device *dev,
1744 			  struct device_attribute *attr,
1745 			  char *buf)
1746 {
1747 	struct dev_ext_attribute *ea = to_ext_attr(attr);
1748 	return sysfs_emit(buf, "%lx\n", *(unsigned long *)(ea->var));
1749 }
1750 EXPORT_SYMBOL_GPL(device_show_ulong);
1751 
device_store_int(struct device * dev,struct device_attribute * attr,const char * buf,size_t size)1752 ssize_t device_store_int(struct device *dev,
1753 			 struct device_attribute *attr,
1754 			 const char *buf, size_t size)
1755 {
1756 	struct dev_ext_attribute *ea = to_ext_attr(attr);
1757 	int ret;
1758 	long new;
1759 
1760 	ret = kstrtol(buf, 0, &new);
1761 	if (ret)
1762 		return ret;
1763 
1764 	if (new > INT_MAX || new < INT_MIN)
1765 		return -EINVAL;
1766 	*(int *)(ea->var) = new;
1767 	/* Always return full write size even if we didn't consume all */
1768 	return size;
1769 }
1770 EXPORT_SYMBOL_GPL(device_store_int);
1771 
device_show_int(struct device * dev,struct device_attribute * attr,char * buf)1772 ssize_t device_show_int(struct device *dev,
1773 			struct device_attribute *attr,
1774 			char *buf)
1775 {
1776 	struct dev_ext_attribute *ea = to_ext_attr(attr);
1777 
1778 	return sysfs_emit(buf, "%d\n", *(int *)(ea->var));
1779 }
1780 EXPORT_SYMBOL_GPL(device_show_int);
1781 
device_store_bool(struct device * dev,struct device_attribute * attr,const char * buf,size_t size)1782 ssize_t device_store_bool(struct device *dev, struct device_attribute *attr,
1783 			  const char *buf, size_t size)
1784 {
1785 	struct dev_ext_attribute *ea = to_ext_attr(attr);
1786 
1787 	if (strtobool(buf, ea->var) < 0)
1788 		return -EINVAL;
1789 
1790 	return size;
1791 }
1792 EXPORT_SYMBOL_GPL(device_store_bool);
1793 
device_show_bool(struct device * dev,struct device_attribute * attr,char * buf)1794 ssize_t device_show_bool(struct device *dev, struct device_attribute *attr,
1795 			 char *buf)
1796 {
1797 	struct dev_ext_attribute *ea = to_ext_attr(attr);
1798 
1799 	return sysfs_emit(buf, "%d\n", *(bool *)(ea->var));
1800 }
1801 EXPORT_SYMBOL_GPL(device_show_bool);
1802 
1803 /**
1804  * device_release - free device structure.
1805  * @kobj: device's kobject.
1806  *
1807  * This is called once the reference count for the object
1808  * reaches 0. We forward the call to the device's release
1809  * method, which should handle actually freeing the structure.
1810  */
device_release(struct kobject * kobj)1811 static void device_release(struct kobject *kobj)
1812 {
1813 	struct device *dev = kobj_to_dev(kobj);
1814 	struct device_private *p = dev->p;
1815 
1816 	/*
1817 	 * Some platform devices are driven without driver attached
1818 	 * and managed resources may have been acquired.  Make sure
1819 	 * all resources are released.
1820 	 *
1821 	 * Drivers still can add resources into device after device
1822 	 * is deleted but alive, so release devres here to avoid
1823 	 * possible memory leak.
1824 	 */
1825 	devres_release_all(dev);
1826 
1827 	kfree(dev->dma_range_map);
1828 
1829 	if (dev->release)
1830 		dev->release(dev);
1831 	else if (dev->type && dev->type->release)
1832 		dev->type->release(dev);
1833 	else if (dev->class && dev->class->dev_release)
1834 		dev->class->dev_release(dev);
1835 	else
1836 		WARN(1, KERN_ERR "Device '%s' does not have a release() function, it is broken and must be fixed. See Documentation/core-api/kobject.rst.\n",
1837 			dev_name(dev));
1838 	kfree(p);
1839 }
1840 
device_namespace(struct kobject * kobj)1841 static const void *device_namespace(struct kobject *kobj)
1842 {
1843 	struct device *dev = kobj_to_dev(kobj);
1844 	const void *ns = NULL;
1845 
1846 	if (dev->class && dev->class->ns_type)
1847 		ns = dev->class->namespace(dev);
1848 
1849 	return ns;
1850 }
1851 
device_get_ownership(struct kobject * kobj,kuid_t * uid,kgid_t * gid)1852 static void device_get_ownership(struct kobject *kobj, kuid_t *uid, kgid_t *gid)
1853 {
1854 	struct device *dev = kobj_to_dev(kobj);
1855 
1856 	if (dev->class && dev->class->get_ownership)
1857 		dev->class->get_ownership(dev, uid, gid);
1858 }
1859 
1860 static struct kobj_type device_ktype = {
1861 	.release	= device_release,
1862 	.sysfs_ops	= &dev_sysfs_ops,
1863 	.namespace	= device_namespace,
1864 	.get_ownership	= device_get_ownership,
1865 };
1866 
1867 
dev_uevent_filter(struct kset * kset,struct kobject * kobj)1868 static int dev_uevent_filter(struct kset *kset, struct kobject *kobj)
1869 {
1870 	struct kobj_type *ktype = get_ktype(kobj);
1871 
1872 	if (ktype == &device_ktype) {
1873 		struct device *dev = kobj_to_dev(kobj);
1874 		if (dev->bus)
1875 			return 1;
1876 		if (dev->class)
1877 			return 1;
1878 	}
1879 	return 0;
1880 }
1881 
dev_uevent_name(struct kset * kset,struct kobject * kobj)1882 static const char *dev_uevent_name(struct kset *kset, struct kobject *kobj)
1883 {
1884 	struct device *dev = kobj_to_dev(kobj);
1885 
1886 	if (dev->bus)
1887 		return dev->bus->name;
1888 	if (dev->class)
1889 		return dev->class->name;
1890 	return NULL;
1891 }
1892 
dev_uevent(struct kset * kset,struct kobject * kobj,struct kobj_uevent_env * env)1893 static int dev_uevent(struct kset *kset, struct kobject *kobj,
1894 		      struct kobj_uevent_env *env)
1895 {
1896 	struct device *dev = kobj_to_dev(kobj);
1897 	int retval = 0;
1898 
1899 	/* add device node properties if present */
1900 	if (MAJOR(dev->devt)) {
1901 		const char *tmp;
1902 		const char *name;
1903 		umode_t mode = 0;
1904 		kuid_t uid = GLOBAL_ROOT_UID;
1905 		kgid_t gid = GLOBAL_ROOT_GID;
1906 
1907 		add_uevent_var(env, "MAJOR=%u", MAJOR(dev->devt));
1908 		add_uevent_var(env, "MINOR=%u", MINOR(dev->devt));
1909 		name = device_get_devnode(dev, &mode, &uid, &gid, &tmp);
1910 		if (name) {
1911 			add_uevent_var(env, "DEVNAME=%s", name);
1912 			if (mode)
1913 				add_uevent_var(env, "DEVMODE=%#o", mode & 0777);
1914 			if (!uid_eq(uid, GLOBAL_ROOT_UID))
1915 				add_uevent_var(env, "DEVUID=%u", from_kuid(&init_user_ns, uid));
1916 			if (!gid_eq(gid, GLOBAL_ROOT_GID))
1917 				add_uevent_var(env, "DEVGID=%u", from_kgid(&init_user_ns, gid));
1918 			kfree(tmp);
1919 		}
1920 	}
1921 
1922 	if (dev->type && dev->type->name)
1923 		add_uevent_var(env, "DEVTYPE=%s", dev->type->name);
1924 
1925 	if (dev->driver)
1926 		add_uevent_var(env, "DRIVER=%s", dev->driver->name);
1927 
1928 	/* Add common DT information about the device */
1929 	of_device_uevent(dev, env);
1930 
1931 	/* have the bus specific function add its stuff */
1932 	if (dev->bus && dev->bus->uevent) {
1933 		retval = dev->bus->uevent(dev, env);
1934 		if (retval)
1935 			pr_debug("device: '%s': %s: bus uevent() returned %d\n",
1936 				 dev_name(dev), __func__, retval);
1937 	}
1938 
1939 	/* have the class specific function add its stuff */
1940 	if (dev->class && dev->class->dev_uevent) {
1941 		retval = dev->class->dev_uevent(dev, env);
1942 		if (retval)
1943 			pr_debug("device: '%s': %s: class uevent() "
1944 				 "returned %d\n", dev_name(dev),
1945 				 __func__, retval);
1946 	}
1947 
1948 	/* have the device type specific function add its stuff */
1949 	if (dev->type && dev->type->uevent) {
1950 		retval = dev->type->uevent(dev, env);
1951 		if (retval)
1952 			pr_debug("device: '%s': %s: dev_type uevent() "
1953 				 "returned %d\n", dev_name(dev),
1954 				 __func__, retval);
1955 	}
1956 
1957 	return retval;
1958 }
1959 
1960 static const struct kset_uevent_ops device_uevent_ops = {
1961 	.filter =	dev_uevent_filter,
1962 	.name =		dev_uevent_name,
1963 	.uevent =	dev_uevent,
1964 };
1965 
uevent_show(struct device * dev,struct device_attribute * attr,char * buf)1966 static ssize_t uevent_show(struct device *dev, struct device_attribute *attr,
1967 			   char *buf)
1968 {
1969 	struct kobject *top_kobj;
1970 	struct kset *kset;
1971 	struct kobj_uevent_env *env = NULL;
1972 	int i;
1973 	int len = 0;
1974 	int retval;
1975 
1976 	/* search the kset, the device belongs to */
1977 	top_kobj = &dev->kobj;
1978 	while (!top_kobj->kset && top_kobj->parent)
1979 		top_kobj = top_kobj->parent;
1980 	if (!top_kobj->kset)
1981 		goto out;
1982 
1983 	kset = top_kobj->kset;
1984 	if (!kset->uevent_ops || !kset->uevent_ops->uevent)
1985 		goto out;
1986 
1987 	/* respect filter */
1988 	if (kset->uevent_ops && kset->uevent_ops->filter)
1989 		if (!kset->uevent_ops->filter(kset, &dev->kobj))
1990 			goto out;
1991 
1992 	env = kzalloc(sizeof(struct kobj_uevent_env), GFP_KERNEL);
1993 	if (!env)
1994 		return -ENOMEM;
1995 
1996 	/* let the kset specific function add its keys */
1997 	retval = kset->uevent_ops->uevent(kset, &dev->kobj, env);
1998 	if (retval)
1999 		goto out;
2000 
2001 	/* copy keys to file */
2002 	for (i = 0; i < env->envp_idx; i++)
2003 		len += sysfs_emit_at(buf, len, "%s\n", env->envp[i]);
2004 out:
2005 	kfree(env);
2006 	return len;
2007 }
2008 
uevent_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)2009 static ssize_t uevent_store(struct device *dev, struct device_attribute *attr,
2010 			    const char *buf, size_t count)
2011 {
2012 	int rc;
2013 
2014 	rc = kobject_synth_uevent(&dev->kobj, buf, count);
2015 
2016 	if (rc) {
2017 		dev_err(dev, "uevent: failed to send synthetic uevent\n");
2018 		return rc;
2019 	}
2020 
2021 	return count;
2022 }
2023 static DEVICE_ATTR_RW(uevent);
2024 
online_show(struct device * dev,struct device_attribute * attr,char * buf)2025 static ssize_t online_show(struct device *dev, struct device_attribute *attr,
2026 			   char *buf)
2027 {
2028 	bool val;
2029 
2030 	device_lock(dev);
2031 	val = !dev->offline;
2032 	device_unlock(dev);
2033 	return sysfs_emit(buf, "%u\n", val);
2034 }
2035 
online_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)2036 static ssize_t online_store(struct device *dev, struct device_attribute *attr,
2037 			    const char *buf, size_t count)
2038 {
2039 	bool val;
2040 	int ret;
2041 
2042 	ret = strtobool(buf, &val);
2043 	if (ret < 0)
2044 		return ret;
2045 
2046 	ret = lock_device_hotplug_sysfs();
2047 	if (ret)
2048 		return ret;
2049 
2050 	ret = val ? device_online(dev) : device_offline(dev);
2051 	unlock_device_hotplug();
2052 	return ret < 0 ? ret : count;
2053 }
2054 static DEVICE_ATTR_RW(online);
2055 
removable_show(struct device * dev,struct device_attribute * attr,char * buf)2056 static ssize_t removable_show(struct device *dev, struct device_attribute *attr,
2057 			      char *buf)
2058 {
2059 	const char *loc;
2060 
2061 	switch (dev->removable) {
2062 	case DEVICE_REMOVABLE:
2063 		loc = "removable";
2064 		break;
2065 	case DEVICE_FIXED:
2066 		loc = "fixed";
2067 		break;
2068 	default:
2069 		loc = "unknown";
2070 	}
2071 	return sysfs_emit(buf, "%s\n", loc);
2072 }
2073 static DEVICE_ATTR_RO(removable);
2074 
device_add_groups(struct device * dev,const struct attribute_group ** groups)2075 int device_add_groups(struct device *dev, const struct attribute_group **groups)
2076 {
2077 	return sysfs_create_groups(&dev->kobj, groups);
2078 }
2079 EXPORT_SYMBOL_GPL(device_add_groups);
2080 
device_remove_groups(struct device * dev,const struct attribute_group ** groups)2081 void device_remove_groups(struct device *dev,
2082 			  const struct attribute_group **groups)
2083 {
2084 	sysfs_remove_groups(&dev->kobj, groups);
2085 }
2086 EXPORT_SYMBOL_GPL(device_remove_groups);
2087 
2088 union device_attr_group_devres {
2089 	const struct attribute_group *group;
2090 	const struct attribute_group **groups;
2091 };
2092 
devm_attr_group_match(struct device * dev,void * res,void * data)2093 static int devm_attr_group_match(struct device *dev, void *res, void *data)
2094 {
2095 	return ((union device_attr_group_devres *)res)->group == data;
2096 }
2097 
devm_attr_group_remove(struct device * dev,void * res)2098 static void devm_attr_group_remove(struct device *dev, void *res)
2099 {
2100 	union device_attr_group_devres *devres = res;
2101 	const struct attribute_group *group = devres->group;
2102 
2103 	dev_dbg(dev, "%s: removing group %p\n", __func__, group);
2104 	sysfs_remove_group(&dev->kobj, group);
2105 }
2106 
devm_attr_groups_remove(struct device * dev,void * res)2107 static void devm_attr_groups_remove(struct device *dev, void *res)
2108 {
2109 	union device_attr_group_devres *devres = res;
2110 	const struct attribute_group **groups = devres->groups;
2111 
2112 	dev_dbg(dev, "%s: removing groups %p\n", __func__, groups);
2113 	sysfs_remove_groups(&dev->kobj, groups);
2114 }
2115 
2116 /**
2117  * devm_device_add_group - given a device, create a managed attribute group
2118  * @dev:	The device to create the group for
2119  * @grp:	The attribute group to create
2120  *
2121  * This function creates a group for the first time.  It will explicitly
2122  * warn and error if any of the attribute files being created already exist.
2123  *
2124  * Returns 0 on success or error code on failure.
2125  */
devm_device_add_group(struct device * dev,const struct attribute_group * grp)2126 int devm_device_add_group(struct device *dev, const struct attribute_group *grp)
2127 {
2128 	union device_attr_group_devres *devres;
2129 	int error;
2130 
2131 	devres = devres_alloc(devm_attr_group_remove,
2132 			      sizeof(*devres), GFP_KERNEL);
2133 	if (!devres)
2134 		return -ENOMEM;
2135 
2136 	error = sysfs_create_group(&dev->kobj, grp);
2137 	if (error) {
2138 		devres_free(devres);
2139 		return error;
2140 	}
2141 
2142 	devres->group = grp;
2143 	devres_add(dev, devres);
2144 	return 0;
2145 }
2146 EXPORT_SYMBOL_GPL(devm_device_add_group);
2147 
2148 /**
2149  * devm_device_remove_group: remove a managed group from a device
2150  * @dev:	device to remove the group from
2151  * @grp:	group to remove
2152  *
2153  * This function removes a group of attributes from a device. The attributes
2154  * previously have to have been created for this group, otherwise it will fail.
2155  */
devm_device_remove_group(struct device * dev,const struct attribute_group * grp)2156 void devm_device_remove_group(struct device *dev,
2157 			      const struct attribute_group *grp)
2158 {
2159 	WARN_ON(devres_release(dev, devm_attr_group_remove,
2160 			       devm_attr_group_match,
2161 			       /* cast away const */ (void *)grp));
2162 }
2163 EXPORT_SYMBOL_GPL(devm_device_remove_group);
2164 
2165 /**
2166  * devm_device_add_groups - create a bunch of managed attribute groups
2167  * @dev:	The device to create the group for
2168  * @groups:	The attribute groups to create, NULL terminated
2169  *
2170  * This function creates a bunch of managed attribute groups.  If an error
2171  * occurs when creating a group, all previously created groups will be
2172  * removed, unwinding everything back to the original state when this
2173  * function was called.  It will explicitly warn and error if any of the
2174  * attribute files being created already exist.
2175  *
2176  * Returns 0 on success or error code from sysfs_create_group on failure.
2177  */
devm_device_add_groups(struct device * dev,const struct attribute_group ** groups)2178 int devm_device_add_groups(struct device *dev,
2179 			   const struct attribute_group **groups)
2180 {
2181 	union device_attr_group_devres *devres;
2182 	int error;
2183 
2184 	devres = devres_alloc(devm_attr_groups_remove,
2185 			      sizeof(*devres), GFP_KERNEL);
2186 	if (!devres)
2187 		return -ENOMEM;
2188 
2189 	error = sysfs_create_groups(&dev->kobj, groups);
2190 	if (error) {
2191 		devres_free(devres);
2192 		return error;
2193 	}
2194 
2195 	devres->groups = groups;
2196 	devres_add(dev, devres);
2197 	return 0;
2198 }
2199 EXPORT_SYMBOL_GPL(devm_device_add_groups);
2200 
2201 /**
2202  * devm_device_remove_groups - remove a list of managed groups
2203  *
2204  * @dev:	The device for the groups to be removed from
2205  * @groups:	NULL terminated list of groups to be removed
2206  *
2207  * If groups is not NULL, remove the specified groups from the device.
2208  */
devm_device_remove_groups(struct device * dev,const struct attribute_group ** groups)2209 void devm_device_remove_groups(struct device *dev,
2210 			       const struct attribute_group **groups)
2211 {
2212 	WARN_ON(devres_release(dev, devm_attr_groups_remove,
2213 			       devm_attr_group_match,
2214 			       /* cast away const */ (void *)groups));
2215 }
2216 EXPORT_SYMBOL_GPL(devm_device_remove_groups);
2217 
device_add_attrs(struct device * dev)2218 static int device_add_attrs(struct device *dev)
2219 {
2220 	struct class *class = dev->class;
2221 	const struct device_type *type = dev->type;
2222 	int error;
2223 
2224 	if (class) {
2225 		error = device_add_groups(dev, class->dev_groups);
2226 		if (error)
2227 			return error;
2228 	}
2229 
2230 	if (type) {
2231 		error = device_add_groups(dev, type->groups);
2232 		if (error)
2233 			goto err_remove_class_groups;
2234 	}
2235 
2236 	error = device_add_groups(dev, dev->groups);
2237 	if (error)
2238 		goto err_remove_type_groups;
2239 
2240 	if (device_supports_offline(dev) && !dev->offline_disabled) {
2241 		error = device_create_file(dev, &dev_attr_online);
2242 		if (error)
2243 			goto err_remove_dev_groups;
2244 	}
2245 
2246 	if (fw_devlink_flags && !fw_devlink_is_permissive()) {
2247 		error = device_create_file(dev, &dev_attr_waiting_for_supplier);
2248 		if (error)
2249 			goto err_remove_dev_online;
2250 	}
2251 
2252 	if (dev_removable_is_valid(dev)) {
2253 		error = device_create_file(dev, &dev_attr_removable);
2254 		if (error)
2255 			goto err_remove_dev_waiting_for_supplier;
2256 	}
2257 
2258 	return 0;
2259 
2260  err_remove_dev_waiting_for_supplier:
2261 	device_remove_file(dev, &dev_attr_waiting_for_supplier);
2262  err_remove_dev_online:
2263 	device_remove_file(dev, &dev_attr_online);
2264  err_remove_dev_groups:
2265 	device_remove_groups(dev, dev->groups);
2266  err_remove_type_groups:
2267 	if (type)
2268 		device_remove_groups(dev, type->groups);
2269  err_remove_class_groups:
2270 	if (class)
2271 		device_remove_groups(dev, class->dev_groups);
2272 
2273 	return error;
2274 }
2275 
device_remove_attrs(struct device * dev)2276 static void device_remove_attrs(struct device *dev)
2277 {
2278 	struct class *class = dev->class;
2279 	const struct device_type *type = dev->type;
2280 
2281 	device_remove_file(dev, &dev_attr_removable);
2282 	device_remove_file(dev, &dev_attr_waiting_for_supplier);
2283 	device_remove_file(dev, &dev_attr_online);
2284 	device_remove_groups(dev, dev->groups);
2285 
2286 	if (type)
2287 		device_remove_groups(dev, type->groups);
2288 
2289 	if (class)
2290 		device_remove_groups(dev, class->dev_groups);
2291 }
2292 
dev_show(struct device * dev,struct device_attribute * attr,char * buf)2293 static ssize_t dev_show(struct device *dev, struct device_attribute *attr,
2294 			char *buf)
2295 {
2296 	return print_dev_t(buf, dev->devt);
2297 }
2298 static DEVICE_ATTR_RO(dev);
2299 
2300 /* /sys/devices/ */
2301 struct kset *devices_kset;
2302 
2303 /**
2304  * devices_kset_move_before - Move device in the devices_kset's list.
2305  * @deva: Device to move.
2306  * @devb: Device @deva should come before.
2307  */
devices_kset_move_before(struct device * deva,struct device * devb)2308 static void devices_kset_move_before(struct device *deva, struct device *devb)
2309 {
2310 	if (!devices_kset)
2311 		return;
2312 	pr_debug("devices_kset: Moving %s before %s\n",
2313 		 dev_name(deva), dev_name(devb));
2314 	spin_lock(&devices_kset->list_lock);
2315 	list_move_tail(&deva->kobj.entry, &devb->kobj.entry);
2316 	spin_unlock(&devices_kset->list_lock);
2317 }
2318 
2319 /**
2320  * devices_kset_move_after - Move device in the devices_kset's list.
2321  * @deva: Device to move
2322  * @devb: Device @deva should come after.
2323  */
devices_kset_move_after(struct device * deva,struct device * devb)2324 static void devices_kset_move_after(struct device *deva, struct device *devb)
2325 {
2326 	if (!devices_kset)
2327 		return;
2328 	pr_debug("devices_kset: Moving %s after %s\n",
2329 		 dev_name(deva), dev_name(devb));
2330 	spin_lock(&devices_kset->list_lock);
2331 	list_move(&deva->kobj.entry, &devb->kobj.entry);
2332 	spin_unlock(&devices_kset->list_lock);
2333 }
2334 
2335 /**
2336  * devices_kset_move_last - move the device to the end of devices_kset's list.
2337  * @dev: device to move
2338  */
devices_kset_move_last(struct device * dev)2339 void devices_kset_move_last(struct device *dev)
2340 {
2341 	if (!devices_kset)
2342 		return;
2343 	pr_debug("devices_kset: Moving %s to end of list\n", dev_name(dev));
2344 	spin_lock(&devices_kset->list_lock);
2345 	list_move_tail(&dev->kobj.entry, &devices_kset->list);
2346 	spin_unlock(&devices_kset->list_lock);
2347 }
2348 
2349 /**
2350  * device_create_file - create sysfs attribute file for device.
2351  * @dev: device.
2352  * @attr: device attribute descriptor.
2353  */
device_create_file(struct device * dev,const struct device_attribute * attr)2354 int device_create_file(struct device *dev,
2355 		       const struct device_attribute *attr)
2356 {
2357 	int error = 0;
2358 
2359 	if (dev) {
2360 		WARN(((attr->attr.mode & S_IWUGO) && !attr->store),
2361 			"Attribute %s: write permission without 'store'\n",
2362 			attr->attr.name);
2363 		WARN(((attr->attr.mode & S_IRUGO) && !attr->show),
2364 			"Attribute %s: read permission without 'show'\n",
2365 			attr->attr.name);
2366 		error = sysfs_create_file(&dev->kobj, &attr->attr);
2367 	}
2368 
2369 	return error;
2370 }
2371 EXPORT_SYMBOL_GPL(device_create_file);
2372 
2373 /**
2374  * device_remove_file - remove sysfs attribute file.
2375  * @dev: device.
2376  * @attr: device attribute descriptor.
2377  */
device_remove_file(struct device * dev,const struct device_attribute * attr)2378 void device_remove_file(struct device *dev,
2379 			const struct device_attribute *attr)
2380 {
2381 	if (dev)
2382 		sysfs_remove_file(&dev->kobj, &attr->attr);
2383 }
2384 EXPORT_SYMBOL_GPL(device_remove_file);
2385 
2386 /**
2387  * device_remove_file_self - remove sysfs attribute file from its own method.
2388  * @dev: device.
2389  * @attr: device attribute descriptor.
2390  *
2391  * See kernfs_remove_self() for details.
2392  */
device_remove_file_self(struct device * dev,const struct device_attribute * attr)2393 bool device_remove_file_self(struct device *dev,
2394 			     const struct device_attribute *attr)
2395 {
2396 	if (dev)
2397 		return sysfs_remove_file_self(&dev->kobj, &attr->attr);
2398 	else
2399 		return false;
2400 }
2401 EXPORT_SYMBOL_GPL(device_remove_file_self);
2402 
2403 /**
2404  * device_create_bin_file - create sysfs binary attribute file for device.
2405  * @dev: device.
2406  * @attr: device binary attribute descriptor.
2407  */
device_create_bin_file(struct device * dev,const struct bin_attribute * attr)2408 int device_create_bin_file(struct device *dev,
2409 			   const struct bin_attribute *attr)
2410 {
2411 	int error = -EINVAL;
2412 	if (dev)
2413 		error = sysfs_create_bin_file(&dev->kobj, attr);
2414 	return error;
2415 }
2416 EXPORT_SYMBOL_GPL(device_create_bin_file);
2417 
2418 /**
2419  * device_remove_bin_file - remove sysfs binary attribute file
2420  * @dev: device.
2421  * @attr: device binary attribute descriptor.
2422  */
device_remove_bin_file(struct device * dev,const struct bin_attribute * attr)2423 void device_remove_bin_file(struct device *dev,
2424 			    const struct bin_attribute *attr)
2425 {
2426 	if (dev)
2427 		sysfs_remove_bin_file(&dev->kobj, attr);
2428 }
2429 EXPORT_SYMBOL_GPL(device_remove_bin_file);
2430 
klist_children_get(struct klist_node * n)2431 static void klist_children_get(struct klist_node *n)
2432 {
2433 	struct device_private *p = to_device_private_parent(n);
2434 	struct device *dev = p->device;
2435 
2436 	get_device(dev);
2437 }
2438 
klist_children_put(struct klist_node * n)2439 static void klist_children_put(struct klist_node *n)
2440 {
2441 	struct device_private *p = to_device_private_parent(n);
2442 	struct device *dev = p->device;
2443 
2444 	put_device(dev);
2445 }
2446 
2447 /**
2448  * device_initialize - init device structure.
2449  * @dev: device.
2450  *
2451  * This prepares the device for use by other layers by initializing
2452  * its fields.
2453  * It is the first half of device_register(), if called by
2454  * that function, though it can also be called separately, so one
2455  * may use @dev's fields. In particular, get_device()/put_device()
2456  * may be used for reference counting of @dev after calling this
2457  * function.
2458  *
2459  * All fields in @dev must be initialized by the caller to 0, except
2460  * for those explicitly set to some other value.  The simplest
2461  * approach is to use kzalloc() to allocate the structure containing
2462  * @dev.
2463  *
2464  * NOTE: Use put_device() to give up your reference instead of freeing
2465  * @dev directly once you have called this function.
2466  */
device_initialize(struct device * dev)2467 void device_initialize(struct device *dev)
2468 {
2469 	dev->kobj.kset = devices_kset;
2470 	kobject_init(&dev->kobj, &device_ktype);
2471 	INIT_LIST_HEAD(&dev->dma_pools);
2472 	mutex_init(&dev->mutex);
2473 #ifdef CONFIG_PROVE_LOCKING
2474 	mutex_init(&dev->lockdep_mutex);
2475 #endif
2476 	lockdep_set_novalidate_class(&dev->mutex);
2477 	spin_lock_init(&dev->devres_lock);
2478 	INIT_LIST_HEAD(&dev->devres_head);
2479 	device_pm_init(dev);
2480 	set_dev_node(dev, -1);
2481 #ifdef CONFIG_GENERIC_MSI_IRQ
2482 	raw_spin_lock_init(&dev->msi_lock);
2483 	INIT_LIST_HEAD(&dev->msi_list);
2484 #endif
2485 	INIT_LIST_HEAD(&dev->links.consumers);
2486 	INIT_LIST_HEAD(&dev->links.suppliers);
2487 	INIT_LIST_HEAD(&dev->links.needs_suppliers);
2488 	INIT_LIST_HEAD(&dev->links.defer_hook);
2489 	dev->links.status = DL_DEV_NO_DRIVER;
2490 }
2491 EXPORT_SYMBOL_GPL(device_initialize);
2492 
virtual_device_parent(struct device * dev)2493 struct kobject *virtual_device_parent(struct device *dev)
2494 {
2495 	static struct kobject *virtual_dir = NULL;
2496 
2497 	if (!virtual_dir)
2498 		virtual_dir = kobject_create_and_add("virtual",
2499 						     &devices_kset->kobj);
2500 
2501 	return virtual_dir;
2502 }
2503 
2504 struct class_dir {
2505 	struct kobject kobj;
2506 	struct class *class;
2507 };
2508 
2509 #define to_class_dir(obj) container_of(obj, struct class_dir, kobj)
2510 
class_dir_release(struct kobject * kobj)2511 static void class_dir_release(struct kobject *kobj)
2512 {
2513 	struct class_dir *dir = to_class_dir(kobj);
2514 	kfree(dir);
2515 }
2516 
2517 static const
class_dir_child_ns_type(struct kobject * kobj)2518 struct kobj_ns_type_operations *class_dir_child_ns_type(struct kobject *kobj)
2519 {
2520 	struct class_dir *dir = to_class_dir(kobj);
2521 	return dir->class->ns_type;
2522 }
2523 
2524 static struct kobj_type class_dir_ktype = {
2525 	.release	= class_dir_release,
2526 	.sysfs_ops	= &kobj_sysfs_ops,
2527 	.child_ns_type	= class_dir_child_ns_type
2528 };
2529 
2530 static struct kobject *
class_dir_create_and_add(struct class * class,struct kobject * parent_kobj)2531 class_dir_create_and_add(struct class *class, struct kobject *parent_kobj)
2532 {
2533 	struct class_dir *dir;
2534 	int retval;
2535 
2536 	dir = kzalloc(sizeof(*dir), GFP_KERNEL);
2537 	if (!dir)
2538 		return ERR_PTR(-ENOMEM);
2539 
2540 	dir->class = class;
2541 	kobject_init(&dir->kobj, &class_dir_ktype);
2542 
2543 	dir->kobj.kset = &class->p->glue_dirs;
2544 
2545 	retval = kobject_add(&dir->kobj, parent_kobj, "%s", class->name);
2546 	if (retval < 0) {
2547 		kobject_put(&dir->kobj);
2548 		return ERR_PTR(retval);
2549 	}
2550 	return &dir->kobj;
2551 }
2552 
2553 static DEFINE_MUTEX(gdp_mutex);
2554 
get_device_parent(struct device * dev,struct device * parent)2555 static struct kobject *get_device_parent(struct device *dev,
2556 					 struct device *parent)
2557 {
2558 	if (dev->class) {
2559 		struct kobject *kobj = NULL;
2560 		struct kobject *parent_kobj;
2561 		struct kobject *k;
2562 
2563 #ifdef CONFIG_BLOCK
2564 		/* block disks show up in /sys/block */
2565 		if (sysfs_deprecated && dev->class == &block_class) {
2566 			if (parent && parent->class == &block_class)
2567 				return &parent->kobj;
2568 			return &block_class.p->subsys.kobj;
2569 		}
2570 #endif
2571 
2572 		/*
2573 		 * If we have no parent, we live in "virtual".
2574 		 * Class-devices with a non class-device as parent, live
2575 		 * in a "glue" directory to prevent namespace collisions.
2576 		 */
2577 		if (parent == NULL)
2578 			parent_kobj = virtual_device_parent(dev);
2579 		else if (parent->class && !dev->class->ns_type)
2580 			return &parent->kobj;
2581 		else
2582 			parent_kobj = &parent->kobj;
2583 
2584 		mutex_lock(&gdp_mutex);
2585 
2586 		/* find our class-directory at the parent and reference it */
2587 		spin_lock(&dev->class->p->glue_dirs.list_lock);
2588 		list_for_each_entry(k, &dev->class->p->glue_dirs.list, entry)
2589 			if (k->parent == parent_kobj) {
2590 				kobj = kobject_get(k);
2591 				break;
2592 			}
2593 		spin_unlock(&dev->class->p->glue_dirs.list_lock);
2594 		if (kobj) {
2595 			mutex_unlock(&gdp_mutex);
2596 			return kobj;
2597 		}
2598 
2599 		/* or create a new class-directory at the parent device */
2600 		k = class_dir_create_and_add(dev->class, parent_kobj);
2601 		/* do not emit an uevent for this simple "glue" directory */
2602 		mutex_unlock(&gdp_mutex);
2603 		return k;
2604 	}
2605 
2606 	/* subsystems can specify a default root directory for their devices */
2607 	if (!parent && dev->bus && dev->bus->dev_root)
2608 		return &dev->bus->dev_root->kobj;
2609 
2610 	if (parent)
2611 		return &parent->kobj;
2612 	return NULL;
2613 }
2614 
live_in_glue_dir(struct kobject * kobj,struct device * dev)2615 static inline bool live_in_glue_dir(struct kobject *kobj,
2616 				    struct device *dev)
2617 {
2618 	if (!kobj || !dev->class ||
2619 	    kobj->kset != &dev->class->p->glue_dirs)
2620 		return false;
2621 	return true;
2622 }
2623 
get_glue_dir(struct device * dev)2624 static inline struct kobject *get_glue_dir(struct device *dev)
2625 {
2626 	return dev->kobj.parent;
2627 }
2628 
2629 /*
2630  * make sure cleaning up dir as the last step, we need to make
2631  * sure .release handler of kobject is run with holding the
2632  * global lock
2633  */
cleanup_glue_dir(struct device * dev,struct kobject * glue_dir)2634 static void cleanup_glue_dir(struct device *dev, struct kobject *glue_dir)
2635 {
2636 	unsigned int ref;
2637 
2638 	/* see if we live in a "glue" directory */
2639 	if (!live_in_glue_dir(glue_dir, dev))
2640 		return;
2641 
2642 	mutex_lock(&gdp_mutex);
2643 	/**
2644 	 * There is a race condition between removing glue directory
2645 	 * and adding a new device under the glue directory.
2646 	 *
2647 	 * CPU1:                                         CPU2:
2648 	 *
2649 	 * device_add()
2650 	 *   get_device_parent()
2651 	 *     class_dir_create_and_add()
2652 	 *       kobject_add_internal()
2653 	 *         create_dir()    // create glue_dir
2654 	 *
2655 	 *                                               device_add()
2656 	 *                                                 get_device_parent()
2657 	 *                                                   kobject_get() // get glue_dir
2658 	 *
2659 	 * device_del()
2660 	 *   cleanup_glue_dir()
2661 	 *     kobject_del(glue_dir)
2662 	 *
2663 	 *                                               kobject_add()
2664 	 *                                                 kobject_add_internal()
2665 	 *                                                   create_dir() // in glue_dir
2666 	 *                                                     sysfs_create_dir_ns()
2667 	 *                                                       kernfs_create_dir_ns(sd)
2668 	 *
2669 	 *       sysfs_remove_dir() // glue_dir->sd=NULL
2670 	 *       sysfs_put()        // free glue_dir->sd
2671 	 *
2672 	 *                                                         // sd is freed
2673 	 *                                                         kernfs_new_node(sd)
2674 	 *                                                           kernfs_get(glue_dir)
2675 	 *                                                           kernfs_add_one()
2676 	 *                                                           kernfs_put()
2677 	 *
2678 	 * Before CPU1 remove last child device under glue dir, if CPU2 add
2679 	 * a new device under glue dir, the glue_dir kobject reference count
2680 	 * will be increase to 2 in kobject_get(k). And CPU2 has been called
2681 	 * kernfs_create_dir_ns(). Meanwhile, CPU1 call sysfs_remove_dir()
2682 	 * and sysfs_put(). This result in glue_dir->sd is freed.
2683 	 *
2684 	 * Then the CPU2 will see a stale "empty" but still potentially used
2685 	 * glue dir around in kernfs_new_node().
2686 	 *
2687 	 * In order to avoid this happening, we also should make sure that
2688 	 * kernfs_node for glue_dir is released in CPU1 only when refcount
2689 	 * for glue_dir kobj is 1.
2690 	 */
2691 	ref = kref_read(&glue_dir->kref);
2692 	if (!kobject_has_children(glue_dir) && !--ref)
2693 		kobject_del(glue_dir);
2694 	kobject_put(glue_dir);
2695 	mutex_unlock(&gdp_mutex);
2696 }
2697 
device_add_class_symlinks(struct device * dev)2698 static int device_add_class_symlinks(struct device *dev)
2699 {
2700 	struct device_node *of_node = dev_of_node(dev);
2701 	int error;
2702 
2703 	if (of_node) {
2704 		error = sysfs_create_link(&dev->kobj, of_node_kobj(of_node), "of_node");
2705 		if (error)
2706 			dev_warn(dev, "Error %d creating of_node link\n",error);
2707 		/* An error here doesn't warrant bringing down the device */
2708 	}
2709 
2710 	if (!dev->class)
2711 		return 0;
2712 
2713 	error = sysfs_create_link(&dev->kobj,
2714 				  &dev->class->p->subsys.kobj,
2715 				  "subsystem");
2716 	if (error)
2717 		goto out_devnode;
2718 
2719 	if (dev->parent && device_is_not_partition(dev)) {
2720 		error = sysfs_create_link(&dev->kobj, &dev->parent->kobj,
2721 					  "device");
2722 		if (error)
2723 			goto out_subsys;
2724 	}
2725 
2726 #ifdef CONFIG_BLOCK
2727 	/* /sys/block has directories and does not need symlinks */
2728 	if (sysfs_deprecated && dev->class == &block_class)
2729 		return 0;
2730 #endif
2731 
2732 	/* link in the class directory pointing to the device */
2733 	error = sysfs_create_link(&dev->class->p->subsys.kobj,
2734 				  &dev->kobj, dev_name(dev));
2735 	if (error)
2736 		goto out_device;
2737 
2738 	return 0;
2739 
2740 out_device:
2741 	sysfs_remove_link(&dev->kobj, "device");
2742 
2743 out_subsys:
2744 	sysfs_remove_link(&dev->kobj, "subsystem");
2745 out_devnode:
2746 	sysfs_remove_link(&dev->kobj, "of_node");
2747 	return error;
2748 }
2749 
device_remove_class_symlinks(struct device * dev)2750 static void device_remove_class_symlinks(struct device *dev)
2751 {
2752 	if (dev_of_node(dev))
2753 		sysfs_remove_link(&dev->kobj, "of_node");
2754 
2755 	if (!dev->class)
2756 		return;
2757 
2758 	if (dev->parent && device_is_not_partition(dev))
2759 		sysfs_remove_link(&dev->kobj, "device");
2760 	sysfs_remove_link(&dev->kobj, "subsystem");
2761 #ifdef CONFIG_BLOCK
2762 	if (sysfs_deprecated && dev->class == &block_class)
2763 		return;
2764 #endif
2765 	sysfs_delete_link(&dev->class->p->subsys.kobj, &dev->kobj, dev_name(dev));
2766 }
2767 
2768 /**
2769  * dev_set_name - set a device name
2770  * @dev: device
2771  * @fmt: format string for the device's name
2772  */
dev_set_name(struct device * dev,const char * fmt,...)2773 int dev_set_name(struct device *dev, const char *fmt, ...)
2774 {
2775 	va_list vargs;
2776 	int err;
2777 
2778 	va_start(vargs, fmt);
2779 	err = kobject_set_name_vargs(&dev->kobj, fmt, vargs);
2780 	va_end(vargs);
2781 	return err;
2782 }
2783 EXPORT_SYMBOL_GPL(dev_set_name);
2784 
2785 /**
2786  * device_to_dev_kobj - select a /sys/dev/ directory for the device
2787  * @dev: device
2788  *
2789  * By default we select char/ for new entries.  Setting class->dev_obj
2790  * to NULL prevents an entry from being created.  class->dev_kobj must
2791  * be set (or cleared) before any devices are registered to the class
2792  * otherwise device_create_sys_dev_entry() and
2793  * device_remove_sys_dev_entry() will disagree about the presence of
2794  * the link.
2795  */
device_to_dev_kobj(struct device * dev)2796 static struct kobject *device_to_dev_kobj(struct device *dev)
2797 {
2798 	struct kobject *kobj;
2799 
2800 	if (dev->class)
2801 		kobj = dev->class->dev_kobj;
2802 	else
2803 		kobj = sysfs_dev_char_kobj;
2804 
2805 	return kobj;
2806 }
2807 
device_create_sys_dev_entry(struct device * dev)2808 static int device_create_sys_dev_entry(struct device *dev)
2809 {
2810 	struct kobject *kobj = device_to_dev_kobj(dev);
2811 	int error = 0;
2812 	char devt_str[15];
2813 
2814 	if (kobj) {
2815 		format_dev_t(devt_str, dev->devt);
2816 		error = sysfs_create_link(kobj, &dev->kobj, devt_str);
2817 	}
2818 
2819 	return error;
2820 }
2821 
device_remove_sys_dev_entry(struct device * dev)2822 static void device_remove_sys_dev_entry(struct device *dev)
2823 {
2824 	struct kobject *kobj = device_to_dev_kobj(dev);
2825 	char devt_str[15];
2826 
2827 	if (kobj) {
2828 		format_dev_t(devt_str, dev->devt);
2829 		sysfs_remove_link(kobj, devt_str);
2830 	}
2831 }
2832 
device_private_init(struct device * dev)2833 static int device_private_init(struct device *dev)
2834 {
2835 	dev->p = kzalloc(sizeof(*dev->p), GFP_KERNEL);
2836 	if (!dev->p)
2837 		return -ENOMEM;
2838 	dev->p->device = dev;
2839 	klist_init(&dev->p->klist_children, klist_children_get,
2840 		   klist_children_put);
2841 	INIT_LIST_HEAD(&dev->p->deferred_probe);
2842 	return 0;
2843 }
2844 
2845 /**
2846  * device_add - add device to device hierarchy.
2847  * @dev: device.
2848  *
2849  * This is part 2 of device_register(), though may be called
2850  * separately _iff_ device_initialize() has been called separately.
2851  *
2852  * This adds @dev to the kobject hierarchy via kobject_add(), adds it
2853  * to the global and sibling lists for the device, then
2854  * adds it to the other relevant subsystems of the driver model.
2855  *
2856  * Do not call this routine or device_register() more than once for
2857  * any device structure.  The driver model core is not designed to work
2858  * with devices that get unregistered and then spring back to life.
2859  * (Among other things, it's very hard to guarantee that all references
2860  * to the previous incarnation of @dev have been dropped.)  Allocate
2861  * and register a fresh new struct device instead.
2862  *
2863  * NOTE: _Never_ directly free @dev after calling this function, even
2864  * if it returned an error! Always use put_device() to give up your
2865  * reference instead.
2866  *
2867  * Rule of thumb is: if device_add() succeeds, you should call
2868  * device_del() when you want to get rid of it. If device_add() has
2869  * *not* succeeded, use *only* put_device() to drop the reference
2870  * count.
2871  */
device_add(struct device * dev)2872 int device_add(struct device *dev)
2873 {
2874 	struct device *parent;
2875 	struct kobject *kobj;
2876 	struct class_interface *class_intf;
2877 	int error = -EINVAL;
2878 	struct kobject *glue_dir = NULL;
2879 
2880 	dev = get_device(dev);
2881 	if (!dev)
2882 		goto done;
2883 
2884 	if (!dev->p) {
2885 		error = device_private_init(dev);
2886 		if (error)
2887 			goto done;
2888 	}
2889 
2890 	/*
2891 	 * for statically allocated devices, which should all be converted
2892 	 * some day, we need to initialize the name. We prevent reading back
2893 	 * the name, and force the use of dev_name()
2894 	 */
2895 	if (dev->init_name) {
2896 		dev_set_name(dev, "%s", dev->init_name);
2897 		dev->init_name = NULL;
2898 	}
2899 
2900 	/* subsystems can specify simple device enumeration */
2901 	if (!dev_name(dev) && dev->bus && dev->bus->dev_name)
2902 		dev_set_name(dev, "%s%u", dev->bus->dev_name, dev->id);
2903 
2904 	if (!dev_name(dev)) {
2905 		error = -EINVAL;
2906 		goto name_error;
2907 	}
2908 
2909 	pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
2910 
2911 	parent = get_device(dev->parent);
2912 	kobj = get_device_parent(dev, parent);
2913 	if (IS_ERR(kobj)) {
2914 		error = PTR_ERR(kobj);
2915 		goto parent_error;
2916 	}
2917 	if (kobj)
2918 		dev->kobj.parent = kobj;
2919 
2920 	/* use parent numa_node */
2921 	if (parent && (dev_to_node(dev) == NUMA_NO_NODE))
2922 		set_dev_node(dev, dev_to_node(parent));
2923 
2924 	/* first, register with generic layer. */
2925 	/* we require the name to be set before, and pass NULL */
2926 	error = kobject_add(&dev->kobj, dev->kobj.parent, NULL);
2927 	if (error) {
2928 		glue_dir = get_glue_dir(dev);
2929 		goto Error;
2930 	}
2931 
2932 	/* notify platform of device entry */
2933 	error = device_platform_notify(dev, KOBJ_ADD);
2934 	if (error)
2935 		goto platform_error;
2936 
2937 	error = device_create_file(dev, &dev_attr_uevent);
2938 	if (error)
2939 		goto attrError;
2940 
2941 	error = device_add_class_symlinks(dev);
2942 	if (error)
2943 		goto SymlinkError;
2944 	error = device_add_attrs(dev);
2945 	if (error)
2946 		goto AttrsError;
2947 	error = bus_add_device(dev);
2948 	if (error)
2949 		goto BusError;
2950 	error = dpm_sysfs_add(dev);
2951 	if (error)
2952 		goto DPMError;
2953 	device_pm_add(dev);
2954 
2955 	if (MAJOR(dev->devt)) {
2956 		error = device_create_file(dev, &dev_attr_dev);
2957 		if (error)
2958 			goto DevAttrError;
2959 
2960 		error = device_create_sys_dev_entry(dev);
2961 		if (error)
2962 			goto SysEntryError;
2963 
2964 		devtmpfs_create_node(dev);
2965 	}
2966 
2967 	/* Notify clients of device addition.  This call must come
2968 	 * after dpm_sysfs_add() and before kobject_uevent().
2969 	 */
2970 	if (dev->bus)
2971 		blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
2972 					     BUS_NOTIFY_ADD_DEVICE, dev);
2973 
2974 	kobject_uevent(&dev->kobj, KOBJ_ADD);
2975 
2976 	/*
2977 	 * Check if any of the other devices (consumers) have been waiting for
2978 	 * this device (supplier) to be added so that they can create a device
2979 	 * link to it.
2980 	 *
2981 	 * This needs to happen after device_pm_add() because device_link_add()
2982 	 * requires the supplier be registered before it's called.
2983 	 *
2984 	 * But this also needs to happen before bus_probe_device() to make sure
2985 	 * waiting consumers can link to it before the driver is bound to the
2986 	 * device and the driver sync_state callback is called for this device.
2987 	 */
2988 	if (dev->fwnode && !dev->fwnode->dev) {
2989 		dev->fwnode->dev = dev;
2990 		fw_devlink_link_device(dev);
2991 	}
2992 
2993 	bus_probe_device(dev);
2994 	if (parent)
2995 		klist_add_tail(&dev->p->knode_parent,
2996 			       &parent->p->klist_children);
2997 
2998 	if (dev->class) {
2999 		mutex_lock(&dev->class->p->mutex);
3000 		/* tie the class to the device */
3001 		klist_add_tail(&dev->p->knode_class,
3002 			       &dev->class->p->klist_devices);
3003 
3004 		/* notify any interfaces that the device is here */
3005 		list_for_each_entry(class_intf,
3006 				    &dev->class->p->interfaces, node)
3007 			if (class_intf->add_dev)
3008 				class_intf->add_dev(dev, class_intf);
3009 		mutex_unlock(&dev->class->p->mutex);
3010 	}
3011 done:
3012 	put_device(dev);
3013 	return error;
3014  SysEntryError:
3015 	if (MAJOR(dev->devt))
3016 		device_remove_file(dev, &dev_attr_dev);
3017  DevAttrError:
3018 	device_pm_remove(dev);
3019 	dpm_sysfs_remove(dev);
3020  DPMError:
3021 	bus_remove_device(dev);
3022  BusError:
3023 	device_remove_attrs(dev);
3024  AttrsError:
3025 	device_remove_class_symlinks(dev);
3026  SymlinkError:
3027 	device_remove_file(dev, &dev_attr_uevent);
3028  attrError:
3029 	device_platform_notify(dev, KOBJ_REMOVE);
3030 platform_error:
3031 	kobject_uevent(&dev->kobj, KOBJ_REMOVE);
3032 	glue_dir = get_glue_dir(dev);
3033 	kobject_del(&dev->kobj);
3034  Error:
3035 	cleanup_glue_dir(dev, glue_dir);
3036 parent_error:
3037 	put_device(parent);
3038 name_error:
3039 	kfree(dev->p);
3040 	dev->p = NULL;
3041 	goto done;
3042 }
3043 EXPORT_SYMBOL_GPL(device_add);
3044 
3045 /**
3046  * device_register - register a device with the system.
3047  * @dev: pointer to the device structure
3048  *
3049  * This happens in two clean steps - initialize the device
3050  * and add it to the system. The two steps can be called
3051  * separately, but this is the easiest and most common.
3052  * I.e. you should only call the two helpers separately if
3053  * have a clearly defined need to use and refcount the device
3054  * before it is added to the hierarchy.
3055  *
3056  * For more information, see the kerneldoc for device_initialize()
3057  * and device_add().
3058  *
3059  * NOTE: _Never_ directly free @dev after calling this function, even
3060  * if it returned an error! Always use put_device() to give up the
3061  * reference initialized in this function instead.
3062  */
device_register(struct device * dev)3063 int device_register(struct device *dev)
3064 {
3065 	device_initialize(dev);
3066 	return device_add(dev);
3067 }
3068 EXPORT_SYMBOL_GPL(device_register);
3069 
3070 /**
3071  * get_device - increment reference count for device.
3072  * @dev: device.
3073  *
3074  * This simply forwards the call to kobject_get(), though
3075  * we do take care to provide for the case that we get a NULL
3076  * pointer passed in.
3077  */
get_device(struct device * dev)3078 struct device *get_device(struct device *dev)
3079 {
3080 	return dev ? kobj_to_dev(kobject_get(&dev->kobj)) : NULL;
3081 }
3082 EXPORT_SYMBOL_GPL(get_device);
3083 
3084 /**
3085  * put_device - decrement reference count.
3086  * @dev: device in question.
3087  */
put_device(struct device * dev)3088 void put_device(struct device *dev)
3089 {
3090 	/* might_sleep(); */
3091 	if (dev)
3092 		kobject_put(&dev->kobj);
3093 }
3094 EXPORT_SYMBOL_GPL(put_device);
3095 
kill_device(struct device * dev)3096 bool kill_device(struct device *dev)
3097 {
3098 	/*
3099 	 * Require the device lock and set the "dead" flag to guarantee that
3100 	 * the update behavior is consistent with the other bitfields near
3101 	 * it and that we cannot have an asynchronous probe routine trying
3102 	 * to run while we are tearing out the bus/class/sysfs from
3103 	 * underneath the device.
3104 	 */
3105 	lockdep_assert_held(&dev->mutex);
3106 
3107 	if (dev->p->dead)
3108 		return false;
3109 	dev->p->dead = true;
3110 	return true;
3111 }
3112 EXPORT_SYMBOL_GPL(kill_device);
3113 
3114 /**
3115  * device_del - delete device from system.
3116  * @dev: device.
3117  *
3118  * This is the first part of the device unregistration
3119  * sequence. This removes the device from the lists we control
3120  * from here, has it removed from the other driver model
3121  * subsystems it was added to in device_add(), and removes it
3122  * from the kobject hierarchy.
3123  *
3124  * NOTE: this should be called manually _iff_ device_add() was
3125  * also called manually.
3126  */
device_del(struct device * dev)3127 void device_del(struct device *dev)
3128 {
3129 	struct device *parent = dev->parent;
3130 	struct kobject *glue_dir = NULL;
3131 	struct class_interface *class_intf;
3132 	unsigned int noio_flag;
3133 
3134 	device_lock(dev);
3135 	kill_device(dev);
3136 	device_unlock(dev);
3137 
3138 	if (dev->fwnode && dev->fwnode->dev == dev)
3139 		dev->fwnode->dev = NULL;
3140 
3141 	/* Notify clients of device removal.  This call must come
3142 	 * before dpm_sysfs_remove().
3143 	 */
3144 	noio_flag = memalloc_noio_save();
3145 	if (dev->bus)
3146 		blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
3147 					     BUS_NOTIFY_DEL_DEVICE, dev);
3148 
3149 	dpm_sysfs_remove(dev);
3150 	if (parent)
3151 		klist_del(&dev->p->knode_parent);
3152 	if (MAJOR(dev->devt)) {
3153 		devtmpfs_delete_node(dev);
3154 		device_remove_sys_dev_entry(dev);
3155 		device_remove_file(dev, &dev_attr_dev);
3156 	}
3157 	if (dev->class) {
3158 		device_remove_class_symlinks(dev);
3159 
3160 		mutex_lock(&dev->class->p->mutex);
3161 		/* notify any interfaces that the device is now gone */
3162 		list_for_each_entry(class_intf,
3163 				    &dev->class->p->interfaces, node)
3164 			if (class_intf->remove_dev)
3165 				class_intf->remove_dev(dev, class_intf);
3166 		/* remove the device from the class list */
3167 		klist_del(&dev->p->knode_class);
3168 		mutex_unlock(&dev->class->p->mutex);
3169 	}
3170 	device_remove_file(dev, &dev_attr_uevent);
3171 	device_remove_attrs(dev);
3172 	bus_remove_device(dev);
3173 	device_pm_remove(dev);
3174 	driver_deferred_probe_del(dev);
3175 	device_platform_notify(dev, KOBJ_REMOVE);
3176 	device_remove_properties(dev);
3177 	device_links_purge(dev);
3178 
3179 	if (dev->bus)
3180 		blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
3181 					     BUS_NOTIFY_REMOVED_DEVICE, dev);
3182 	kobject_uevent(&dev->kobj, KOBJ_REMOVE);
3183 	glue_dir = get_glue_dir(dev);
3184 	kobject_del(&dev->kobj);
3185 	cleanup_glue_dir(dev, glue_dir);
3186 	memalloc_noio_restore(noio_flag);
3187 	put_device(parent);
3188 }
3189 EXPORT_SYMBOL_GPL(device_del);
3190 
3191 /**
3192  * device_unregister - unregister device from system.
3193  * @dev: device going away.
3194  *
3195  * We do this in two parts, like we do device_register(). First,
3196  * we remove it from all the subsystems with device_del(), then
3197  * we decrement the reference count via put_device(). If that
3198  * is the final reference count, the device will be cleaned up
3199  * via device_release() above. Otherwise, the structure will
3200  * stick around until the final reference to the device is dropped.
3201  */
device_unregister(struct device * dev)3202 void device_unregister(struct device *dev)
3203 {
3204 	pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
3205 	device_del(dev);
3206 	put_device(dev);
3207 }
3208 EXPORT_SYMBOL_GPL(device_unregister);
3209 
prev_device(struct klist_iter * i)3210 static struct device *prev_device(struct klist_iter *i)
3211 {
3212 	struct klist_node *n = klist_prev(i);
3213 	struct device *dev = NULL;
3214 	struct device_private *p;
3215 
3216 	if (n) {
3217 		p = to_device_private_parent(n);
3218 		dev = p->device;
3219 	}
3220 	return dev;
3221 }
3222 
next_device(struct klist_iter * i)3223 static struct device *next_device(struct klist_iter *i)
3224 {
3225 	struct klist_node *n = klist_next(i);
3226 	struct device *dev = NULL;
3227 	struct device_private *p;
3228 
3229 	if (n) {
3230 		p = to_device_private_parent(n);
3231 		dev = p->device;
3232 	}
3233 	return dev;
3234 }
3235 
3236 /**
3237  * device_get_devnode - path of device node file
3238  * @dev: device
3239  * @mode: returned file access mode
3240  * @uid: returned file owner
3241  * @gid: returned file group
3242  * @tmp: possibly allocated string
3243  *
3244  * Return the relative path of a possible device node.
3245  * Non-default names may need to allocate a memory to compose
3246  * a name. This memory is returned in tmp and needs to be
3247  * freed by the caller.
3248  */
device_get_devnode(struct device * dev,umode_t * mode,kuid_t * uid,kgid_t * gid,const char ** tmp)3249 const char *device_get_devnode(struct device *dev,
3250 			       umode_t *mode, kuid_t *uid, kgid_t *gid,
3251 			       const char **tmp)
3252 {
3253 	char *s;
3254 
3255 	*tmp = NULL;
3256 
3257 	/* the device type may provide a specific name */
3258 	if (dev->type && dev->type->devnode)
3259 		*tmp = dev->type->devnode(dev, mode, uid, gid);
3260 	if (*tmp)
3261 		return *tmp;
3262 
3263 	/* the class may provide a specific name */
3264 	if (dev->class && dev->class->devnode)
3265 		*tmp = dev->class->devnode(dev, mode);
3266 	if (*tmp)
3267 		return *tmp;
3268 
3269 	/* return name without allocation, tmp == NULL */
3270 	if (strchr(dev_name(dev), '!') == NULL)
3271 		return dev_name(dev);
3272 
3273 	/* replace '!' in the name with '/' */
3274 	s = kstrdup(dev_name(dev), GFP_KERNEL);
3275 	if (!s)
3276 		return NULL;
3277 	strreplace(s, '!', '/');
3278 	return *tmp = s;
3279 }
3280 
3281 /**
3282  * device_for_each_child - device child iterator.
3283  * @parent: parent struct device.
3284  * @fn: function to be called for each device.
3285  * @data: data for the callback.
3286  *
3287  * Iterate over @parent's child devices, and call @fn for each,
3288  * passing it @data.
3289  *
3290  * We check the return of @fn each time. If it returns anything
3291  * other than 0, we break out and return that value.
3292  */
device_for_each_child(struct device * parent,void * data,int (* fn)(struct device * dev,void * data))3293 int device_for_each_child(struct device *parent, void *data,
3294 			  int (*fn)(struct device *dev, void *data))
3295 {
3296 	struct klist_iter i;
3297 	struct device *child;
3298 	int error = 0;
3299 
3300 	if (!parent->p)
3301 		return 0;
3302 
3303 	klist_iter_init(&parent->p->klist_children, &i);
3304 	while (!error && (child = next_device(&i)))
3305 		error = fn(child, data);
3306 	klist_iter_exit(&i);
3307 	return error;
3308 }
3309 EXPORT_SYMBOL_GPL(device_for_each_child);
3310 
3311 /**
3312  * device_for_each_child_reverse - device child iterator in reversed order.
3313  * @parent: parent struct device.
3314  * @fn: function to be called for each device.
3315  * @data: data for the callback.
3316  *
3317  * Iterate over @parent's child devices, and call @fn for each,
3318  * passing it @data.
3319  *
3320  * We check the return of @fn each time. If it returns anything
3321  * other than 0, we break out and return that value.
3322  */
device_for_each_child_reverse(struct device * parent,void * data,int (* fn)(struct device * dev,void * data))3323 int device_for_each_child_reverse(struct device *parent, void *data,
3324 				  int (*fn)(struct device *dev, void *data))
3325 {
3326 	struct klist_iter i;
3327 	struct device *child;
3328 	int error = 0;
3329 
3330 	if (!parent->p)
3331 		return 0;
3332 
3333 	klist_iter_init(&parent->p->klist_children, &i);
3334 	while ((child = prev_device(&i)) && !error)
3335 		error = fn(child, data);
3336 	klist_iter_exit(&i);
3337 	return error;
3338 }
3339 EXPORT_SYMBOL_GPL(device_for_each_child_reverse);
3340 
3341 /**
3342  * device_find_child - device iterator for locating a particular device.
3343  * @parent: parent struct device
3344  * @match: Callback function to check device
3345  * @data: Data to pass to match function
3346  *
3347  * This is similar to the device_for_each_child() function above, but it
3348  * returns a reference to a device that is 'found' for later use, as
3349  * determined by the @match callback.
3350  *
3351  * The callback should return 0 if the device doesn't match and non-zero
3352  * if it does.  If the callback returns non-zero and a reference to the
3353  * current device can be obtained, this function will return to the caller
3354  * and not iterate over any more devices.
3355  *
3356  * NOTE: you will need to drop the reference with put_device() after use.
3357  */
device_find_child(struct device * parent,void * data,int (* match)(struct device * dev,void * data))3358 struct device *device_find_child(struct device *parent, void *data,
3359 				 int (*match)(struct device *dev, void *data))
3360 {
3361 	struct klist_iter i;
3362 	struct device *child;
3363 
3364 	if (!parent)
3365 		return NULL;
3366 
3367 	klist_iter_init(&parent->p->klist_children, &i);
3368 	while ((child = next_device(&i)))
3369 		if (match(child, data) && get_device(child))
3370 			break;
3371 	klist_iter_exit(&i);
3372 	return child;
3373 }
3374 EXPORT_SYMBOL_GPL(device_find_child);
3375 
3376 /**
3377  * device_find_child_by_name - device iterator for locating a child device.
3378  * @parent: parent struct device
3379  * @name: name of the child device
3380  *
3381  * This is similar to the device_find_child() function above, but it
3382  * returns a reference to a device that has the name @name.
3383  *
3384  * NOTE: you will need to drop the reference with put_device() after use.
3385  */
device_find_child_by_name(struct device * parent,const char * name)3386 struct device *device_find_child_by_name(struct device *parent,
3387 					 const char *name)
3388 {
3389 	struct klist_iter i;
3390 	struct device *child;
3391 
3392 	if (!parent)
3393 		return NULL;
3394 
3395 	klist_iter_init(&parent->p->klist_children, &i);
3396 	while ((child = next_device(&i)))
3397 		if (sysfs_streq(dev_name(child), name) && get_device(child))
3398 			break;
3399 	klist_iter_exit(&i);
3400 	return child;
3401 }
3402 EXPORT_SYMBOL_GPL(device_find_child_by_name);
3403 
devices_init(void)3404 int __init devices_init(void)
3405 {
3406 	devices_kset = kset_create_and_add("devices", &device_uevent_ops, NULL);
3407 	if (!devices_kset)
3408 		return -ENOMEM;
3409 	dev_kobj = kobject_create_and_add("dev", NULL);
3410 	if (!dev_kobj)
3411 		goto dev_kobj_err;
3412 	sysfs_dev_block_kobj = kobject_create_and_add("block", dev_kobj);
3413 	if (!sysfs_dev_block_kobj)
3414 		goto block_kobj_err;
3415 	sysfs_dev_char_kobj = kobject_create_and_add("char", dev_kobj);
3416 	if (!sysfs_dev_char_kobj)
3417 		goto char_kobj_err;
3418 
3419 	return 0;
3420 
3421  char_kobj_err:
3422 	kobject_put(sysfs_dev_block_kobj);
3423  block_kobj_err:
3424 	kobject_put(dev_kobj);
3425  dev_kobj_err:
3426 	kset_unregister(devices_kset);
3427 	return -ENOMEM;
3428 }
3429 
device_check_offline(struct device * dev,void * not_used)3430 static int device_check_offline(struct device *dev, void *not_used)
3431 {
3432 	int ret;
3433 
3434 	ret = device_for_each_child(dev, NULL, device_check_offline);
3435 	if (ret)
3436 		return ret;
3437 
3438 	return device_supports_offline(dev) && !dev->offline ? -EBUSY : 0;
3439 }
3440 
3441 /**
3442  * device_offline - Prepare the device for hot-removal.
3443  * @dev: Device to be put offline.
3444  *
3445  * Execute the device bus type's .offline() callback, if present, to prepare
3446  * the device for a subsequent hot-removal.  If that succeeds, the device must
3447  * not be used until either it is removed or its bus type's .online() callback
3448  * is executed.
3449  *
3450  * Call under device_hotplug_lock.
3451  */
device_offline(struct device * dev)3452 int device_offline(struct device *dev)
3453 {
3454 	int ret;
3455 
3456 	if (dev->offline_disabled)
3457 		return -EPERM;
3458 
3459 	ret = device_for_each_child(dev, NULL, device_check_offline);
3460 	if (ret)
3461 		return ret;
3462 
3463 	device_lock(dev);
3464 	if (device_supports_offline(dev)) {
3465 		if (dev->offline) {
3466 			ret = 1;
3467 		} else {
3468 			ret = dev->bus->offline(dev);
3469 			if (!ret) {
3470 				kobject_uevent(&dev->kobj, KOBJ_OFFLINE);
3471 				dev->offline = true;
3472 			}
3473 		}
3474 	}
3475 	device_unlock(dev);
3476 
3477 	return ret;
3478 }
3479 
3480 /**
3481  * device_online - Put the device back online after successful device_offline().
3482  * @dev: Device to be put back online.
3483  *
3484  * If device_offline() has been successfully executed for @dev, but the device
3485  * has not been removed subsequently, execute its bus type's .online() callback
3486  * to indicate that the device can be used again.
3487  *
3488  * Call under device_hotplug_lock.
3489  */
device_online(struct device * dev)3490 int device_online(struct device *dev)
3491 {
3492 	int ret = 0;
3493 
3494 	device_lock(dev);
3495 	if (device_supports_offline(dev)) {
3496 		if (dev->offline) {
3497 			ret = dev->bus->online(dev);
3498 			if (!ret) {
3499 				kobject_uevent(&dev->kobj, KOBJ_ONLINE);
3500 				dev->offline = false;
3501 			}
3502 		} else {
3503 			ret = 1;
3504 		}
3505 	}
3506 	device_unlock(dev);
3507 
3508 	return ret;
3509 }
3510 
3511 struct root_device {
3512 	struct device dev;
3513 	struct module *owner;
3514 };
3515 
to_root_device(struct device * d)3516 static inline struct root_device *to_root_device(struct device *d)
3517 {
3518 	return container_of(d, struct root_device, dev);
3519 }
3520 
root_device_release(struct device * dev)3521 static void root_device_release(struct device *dev)
3522 {
3523 	kfree(to_root_device(dev));
3524 }
3525 
3526 /**
3527  * __root_device_register - allocate and register a root device
3528  * @name: root device name
3529  * @owner: owner module of the root device, usually THIS_MODULE
3530  *
3531  * This function allocates a root device and registers it
3532  * using device_register(). In order to free the returned
3533  * device, use root_device_unregister().
3534  *
3535  * Root devices are dummy devices which allow other devices
3536  * to be grouped under /sys/devices. Use this function to
3537  * allocate a root device and then use it as the parent of
3538  * any device which should appear under /sys/devices/{name}
3539  *
3540  * The /sys/devices/{name} directory will also contain a
3541  * 'module' symlink which points to the @owner directory
3542  * in sysfs.
3543  *
3544  * Returns &struct device pointer on success, or ERR_PTR() on error.
3545  *
3546  * Note: You probably want to use root_device_register().
3547  */
__root_device_register(const char * name,struct module * owner)3548 struct device *__root_device_register(const char *name, struct module *owner)
3549 {
3550 	struct root_device *root;
3551 	int err = -ENOMEM;
3552 
3553 	root = kzalloc(sizeof(struct root_device), GFP_KERNEL);
3554 	if (!root)
3555 		return ERR_PTR(err);
3556 
3557 	err = dev_set_name(&root->dev, "%s", name);
3558 	if (err) {
3559 		kfree(root);
3560 		return ERR_PTR(err);
3561 	}
3562 
3563 	root->dev.release = root_device_release;
3564 
3565 	err = device_register(&root->dev);
3566 	if (err) {
3567 		put_device(&root->dev);
3568 		return ERR_PTR(err);
3569 	}
3570 
3571 #ifdef CONFIG_MODULES	/* gotta find a "cleaner" way to do this */
3572 	if (owner) {
3573 		struct module_kobject *mk = &owner->mkobj;
3574 
3575 		err = sysfs_create_link(&root->dev.kobj, &mk->kobj, "module");
3576 		if (err) {
3577 			device_unregister(&root->dev);
3578 			return ERR_PTR(err);
3579 		}
3580 		root->owner = owner;
3581 	}
3582 #endif
3583 
3584 	return &root->dev;
3585 }
3586 EXPORT_SYMBOL_GPL(__root_device_register);
3587 
3588 /**
3589  * root_device_unregister - unregister and free a root device
3590  * @dev: device going away
3591  *
3592  * This function unregisters and cleans up a device that was created by
3593  * root_device_register().
3594  */
root_device_unregister(struct device * dev)3595 void root_device_unregister(struct device *dev)
3596 {
3597 	struct root_device *root = to_root_device(dev);
3598 
3599 	if (root->owner)
3600 		sysfs_remove_link(&root->dev.kobj, "module");
3601 
3602 	device_unregister(dev);
3603 }
3604 EXPORT_SYMBOL_GPL(root_device_unregister);
3605 
3606 
device_create_release(struct device * dev)3607 static void device_create_release(struct device *dev)
3608 {
3609 	pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
3610 	kfree(dev);
3611 }
3612 
3613 static __printf(6, 0) struct device *
device_create_groups_vargs(struct class * class,struct device * parent,dev_t devt,void * drvdata,const struct attribute_group ** groups,const char * fmt,va_list args)3614 device_create_groups_vargs(struct class *class, struct device *parent,
3615 			   dev_t devt, void *drvdata,
3616 			   const struct attribute_group **groups,
3617 			   const char *fmt, va_list args)
3618 {
3619 	struct device *dev = NULL;
3620 	int retval = -ENODEV;
3621 
3622 	if (class == NULL || IS_ERR(class))
3623 		goto error;
3624 
3625 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3626 	if (!dev) {
3627 		retval = -ENOMEM;
3628 		goto error;
3629 	}
3630 
3631 	device_initialize(dev);
3632 	dev->devt = devt;
3633 	dev->class = class;
3634 	dev->parent = parent;
3635 	dev->groups = groups;
3636 	dev->release = device_create_release;
3637 	dev_set_drvdata(dev, drvdata);
3638 
3639 	retval = kobject_set_name_vargs(&dev->kobj, fmt, args);
3640 	if (retval)
3641 		goto error;
3642 
3643 	retval = device_add(dev);
3644 	if (retval)
3645 		goto error;
3646 
3647 	return dev;
3648 
3649 error:
3650 	put_device(dev);
3651 	return ERR_PTR(retval);
3652 }
3653 
3654 /**
3655  * device_create - creates a device and registers it with sysfs
3656  * @class: pointer to the struct class that this device should be registered to
3657  * @parent: pointer to the parent struct device of this new device, if any
3658  * @devt: the dev_t for the char device to be added
3659  * @drvdata: the data to be added to the device for callbacks
3660  * @fmt: string for the device's name
3661  *
3662  * This function can be used by char device classes.  A struct device
3663  * will be created in sysfs, registered to the specified class.
3664  *
3665  * A "dev" file will be created, showing the dev_t for the device, if
3666  * the dev_t is not 0,0.
3667  * If a pointer to a parent struct device is passed in, the newly created
3668  * struct device will be a child of that device in sysfs.
3669  * The pointer to the struct device will be returned from the call.
3670  * Any further sysfs files that might be required can be created using this
3671  * pointer.
3672  *
3673  * Returns &struct device pointer on success, or ERR_PTR() on error.
3674  *
3675  * Note: the struct class passed to this function must have previously
3676  * been created with a call to class_create().
3677  */
device_create(struct class * class,struct device * parent,dev_t devt,void * drvdata,const char * fmt,...)3678 struct device *device_create(struct class *class, struct device *parent,
3679 			     dev_t devt, void *drvdata, const char *fmt, ...)
3680 {
3681 	va_list vargs;
3682 	struct device *dev;
3683 
3684 	va_start(vargs, fmt);
3685 	dev = device_create_groups_vargs(class, parent, devt, drvdata, NULL,
3686 					  fmt, vargs);
3687 	va_end(vargs);
3688 	return dev;
3689 }
3690 EXPORT_SYMBOL_GPL(device_create);
3691 
3692 /**
3693  * device_create_with_groups - creates a device and registers it with sysfs
3694  * @class: pointer to the struct class that this device should be registered to
3695  * @parent: pointer to the parent struct device of this new device, if any
3696  * @devt: the dev_t for the char device to be added
3697  * @drvdata: the data to be added to the device for callbacks
3698  * @groups: NULL-terminated list of attribute groups to be created
3699  * @fmt: string for the device's name
3700  *
3701  * This function can be used by char device classes.  A struct device
3702  * will be created in sysfs, registered to the specified class.
3703  * Additional attributes specified in the groups parameter will also
3704  * be created automatically.
3705  *
3706  * A "dev" file will be created, showing the dev_t for the device, if
3707  * the dev_t is not 0,0.
3708  * If a pointer to a parent struct device is passed in, the newly created
3709  * struct device will be a child of that device in sysfs.
3710  * The pointer to the struct device will be returned from the call.
3711  * Any further sysfs files that might be required can be created using this
3712  * pointer.
3713  *
3714  * Returns &struct device pointer on success, or ERR_PTR() on error.
3715  *
3716  * Note: the struct class passed to this function must have previously
3717  * been created with a call to class_create().
3718  */
device_create_with_groups(struct class * class,struct device * parent,dev_t devt,void * drvdata,const struct attribute_group ** groups,const char * fmt,...)3719 struct device *device_create_with_groups(struct class *class,
3720 					 struct device *parent, dev_t devt,
3721 					 void *drvdata,
3722 					 const struct attribute_group **groups,
3723 					 const char *fmt, ...)
3724 {
3725 	va_list vargs;
3726 	struct device *dev;
3727 
3728 	va_start(vargs, fmt);
3729 	dev = device_create_groups_vargs(class, parent, devt, drvdata, groups,
3730 					 fmt, vargs);
3731 	va_end(vargs);
3732 	return dev;
3733 }
3734 EXPORT_SYMBOL_GPL(device_create_with_groups);
3735 
3736 /**
3737  * device_destroy - removes a device that was created with device_create()
3738  * @class: pointer to the struct class that this device was registered with
3739  * @devt: the dev_t of the device that was previously registered
3740  *
3741  * This call unregisters and cleans up a device that was created with a
3742  * call to device_create().
3743  */
device_destroy(struct class * class,dev_t devt)3744 void device_destroy(struct class *class, dev_t devt)
3745 {
3746 	struct device *dev;
3747 
3748 	dev = class_find_device_by_devt(class, devt);
3749 	if (dev) {
3750 		put_device(dev);
3751 		device_unregister(dev);
3752 	}
3753 }
3754 EXPORT_SYMBOL_GPL(device_destroy);
3755 
3756 /**
3757  * device_rename - renames a device
3758  * @dev: the pointer to the struct device to be renamed
3759  * @new_name: the new name of the device
3760  *
3761  * It is the responsibility of the caller to provide mutual
3762  * exclusion between two different calls of device_rename
3763  * on the same device to ensure that new_name is valid and
3764  * won't conflict with other devices.
3765  *
3766  * Note: Don't call this function.  Currently, the networking layer calls this
3767  * function, but that will change.  The following text from Kay Sievers offers
3768  * some insight:
3769  *
3770  * Renaming devices is racy at many levels, symlinks and other stuff are not
3771  * replaced atomically, and you get a "move" uevent, but it's not easy to
3772  * connect the event to the old and new device. Device nodes are not renamed at
3773  * all, there isn't even support for that in the kernel now.
3774  *
3775  * In the meantime, during renaming, your target name might be taken by another
3776  * driver, creating conflicts. Or the old name is taken directly after you
3777  * renamed it -- then you get events for the same DEVPATH, before you even see
3778  * the "move" event. It's just a mess, and nothing new should ever rely on
3779  * kernel device renaming. Besides that, it's not even implemented now for
3780  * other things than (driver-core wise very simple) network devices.
3781  *
3782  * We are currently about to change network renaming in udev to completely
3783  * disallow renaming of devices in the same namespace as the kernel uses,
3784  * because we can't solve the problems properly, that arise with swapping names
3785  * of multiple interfaces without races. Means, renaming of eth[0-9]* will only
3786  * be allowed to some other name than eth[0-9]*, for the aforementioned
3787  * reasons.
3788  *
3789  * Make up a "real" name in the driver before you register anything, or add
3790  * some other attributes for userspace to find the device, or use udev to add
3791  * symlinks -- but never rename kernel devices later, it's a complete mess. We
3792  * don't even want to get into that and try to implement the missing pieces in
3793  * the core. We really have other pieces to fix in the driver core mess. :)
3794  */
device_rename(struct device * dev,const char * new_name)3795 int device_rename(struct device *dev, const char *new_name)
3796 {
3797 	struct kobject *kobj = &dev->kobj;
3798 	char *old_device_name = NULL;
3799 	int error;
3800 
3801 	dev = get_device(dev);
3802 	if (!dev)
3803 		return -EINVAL;
3804 
3805 	dev_dbg(dev, "renaming to %s\n", new_name);
3806 
3807 	old_device_name = kstrdup(dev_name(dev), GFP_KERNEL);
3808 	if (!old_device_name) {
3809 		error = -ENOMEM;
3810 		goto out;
3811 	}
3812 
3813 	if (dev->class) {
3814 		error = sysfs_rename_link_ns(&dev->class->p->subsys.kobj,
3815 					     kobj, old_device_name,
3816 					     new_name, kobject_namespace(kobj));
3817 		if (error)
3818 			goto out;
3819 	}
3820 
3821 	error = kobject_rename(kobj, new_name);
3822 	if (error)
3823 		goto out;
3824 
3825 out:
3826 	put_device(dev);
3827 
3828 	kfree(old_device_name);
3829 
3830 	return error;
3831 }
3832 EXPORT_SYMBOL_GPL(device_rename);
3833 
device_move_class_links(struct device * dev,struct device * old_parent,struct device * new_parent)3834 static int device_move_class_links(struct device *dev,
3835 				   struct device *old_parent,
3836 				   struct device *new_parent)
3837 {
3838 	int error = 0;
3839 
3840 	if (old_parent)
3841 		sysfs_remove_link(&dev->kobj, "device");
3842 	if (new_parent)
3843 		error = sysfs_create_link(&dev->kobj, &new_parent->kobj,
3844 					  "device");
3845 	return error;
3846 }
3847 
3848 /**
3849  * device_move - moves a device to a new parent
3850  * @dev: the pointer to the struct device to be moved
3851  * @new_parent: the new parent of the device (can be NULL)
3852  * @dpm_order: how to reorder the dpm_list
3853  */
device_move(struct device * dev,struct device * new_parent,enum dpm_order dpm_order)3854 int device_move(struct device *dev, struct device *new_parent,
3855 		enum dpm_order dpm_order)
3856 {
3857 	int error;
3858 	struct device *old_parent;
3859 	struct kobject *new_parent_kobj;
3860 
3861 	dev = get_device(dev);
3862 	if (!dev)
3863 		return -EINVAL;
3864 
3865 	device_pm_lock();
3866 	new_parent = get_device(new_parent);
3867 	new_parent_kobj = get_device_parent(dev, new_parent);
3868 	if (IS_ERR(new_parent_kobj)) {
3869 		error = PTR_ERR(new_parent_kobj);
3870 		put_device(new_parent);
3871 		goto out;
3872 	}
3873 
3874 	pr_debug("device: '%s': %s: moving to '%s'\n", dev_name(dev),
3875 		 __func__, new_parent ? dev_name(new_parent) : "<NULL>");
3876 	error = kobject_move(&dev->kobj, new_parent_kobj);
3877 	if (error) {
3878 		cleanup_glue_dir(dev, new_parent_kobj);
3879 		put_device(new_parent);
3880 		goto out;
3881 	}
3882 	old_parent = dev->parent;
3883 	dev->parent = new_parent;
3884 	if (old_parent)
3885 		klist_remove(&dev->p->knode_parent);
3886 	if (new_parent) {
3887 		klist_add_tail(&dev->p->knode_parent,
3888 			       &new_parent->p->klist_children);
3889 		set_dev_node(dev, dev_to_node(new_parent));
3890 	}
3891 
3892 	if (dev->class) {
3893 		error = device_move_class_links(dev, old_parent, new_parent);
3894 		if (error) {
3895 			/* We ignore errors on cleanup since we're hosed anyway... */
3896 			device_move_class_links(dev, new_parent, old_parent);
3897 			if (!kobject_move(&dev->kobj, &old_parent->kobj)) {
3898 				if (new_parent)
3899 					klist_remove(&dev->p->knode_parent);
3900 				dev->parent = old_parent;
3901 				if (old_parent) {
3902 					klist_add_tail(&dev->p->knode_parent,
3903 						       &old_parent->p->klist_children);
3904 					set_dev_node(dev, dev_to_node(old_parent));
3905 				}
3906 			}
3907 			cleanup_glue_dir(dev, new_parent_kobj);
3908 			put_device(new_parent);
3909 			goto out;
3910 		}
3911 	}
3912 	switch (dpm_order) {
3913 	case DPM_ORDER_NONE:
3914 		break;
3915 	case DPM_ORDER_DEV_AFTER_PARENT:
3916 		device_pm_move_after(dev, new_parent);
3917 		devices_kset_move_after(dev, new_parent);
3918 		break;
3919 	case DPM_ORDER_PARENT_BEFORE_DEV:
3920 		device_pm_move_before(new_parent, dev);
3921 		devices_kset_move_before(new_parent, dev);
3922 		break;
3923 	case DPM_ORDER_DEV_LAST:
3924 		device_pm_move_last(dev);
3925 		devices_kset_move_last(dev);
3926 		break;
3927 	}
3928 
3929 	put_device(old_parent);
3930 out:
3931 	device_pm_unlock();
3932 	put_device(dev);
3933 	return error;
3934 }
3935 EXPORT_SYMBOL_GPL(device_move);
3936 
device_attrs_change_owner(struct device * dev,kuid_t kuid,kgid_t kgid)3937 static int device_attrs_change_owner(struct device *dev, kuid_t kuid,
3938 				     kgid_t kgid)
3939 {
3940 	struct kobject *kobj = &dev->kobj;
3941 	struct class *class = dev->class;
3942 	const struct device_type *type = dev->type;
3943 	int error;
3944 
3945 	if (class) {
3946 		/*
3947 		 * Change the device groups of the device class for @dev to
3948 		 * @kuid/@kgid.
3949 		 */
3950 		error = sysfs_groups_change_owner(kobj, class->dev_groups, kuid,
3951 						  kgid);
3952 		if (error)
3953 			return error;
3954 	}
3955 
3956 	if (type) {
3957 		/*
3958 		 * Change the device groups of the device type for @dev to
3959 		 * @kuid/@kgid.
3960 		 */
3961 		error = sysfs_groups_change_owner(kobj, type->groups, kuid,
3962 						  kgid);
3963 		if (error)
3964 			return error;
3965 	}
3966 
3967 	/* Change the device groups of @dev to @kuid/@kgid. */
3968 	error = sysfs_groups_change_owner(kobj, dev->groups, kuid, kgid);
3969 	if (error)
3970 		return error;
3971 
3972 	if (device_supports_offline(dev) && !dev->offline_disabled) {
3973 		/* Change online device attributes of @dev to @kuid/@kgid. */
3974 		error = sysfs_file_change_owner(kobj, dev_attr_online.attr.name,
3975 						kuid, kgid);
3976 		if (error)
3977 			return error;
3978 	}
3979 
3980 	return 0;
3981 }
3982 
3983 /**
3984  * device_change_owner - change the owner of an existing device.
3985  * @dev: device.
3986  * @kuid: new owner's kuid
3987  * @kgid: new owner's kgid
3988  *
3989  * This changes the owner of @dev and its corresponding sysfs entries to
3990  * @kuid/@kgid. This function closely mirrors how @dev was added via driver
3991  * core.
3992  *
3993  * Returns 0 on success or error code on failure.
3994  */
device_change_owner(struct device * dev,kuid_t kuid,kgid_t kgid)3995 int device_change_owner(struct device *dev, kuid_t kuid, kgid_t kgid)
3996 {
3997 	int error;
3998 	struct kobject *kobj = &dev->kobj;
3999 
4000 	dev = get_device(dev);
4001 	if (!dev)
4002 		return -EINVAL;
4003 
4004 	/*
4005 	 * Change the kobject and the default attributes and groups of the
4006 	 * ktype associated with it to @kuid/@kgid.
4007 	 */
4008 	error = sysfs_change_owner(kobj, kuid, kgid);
4009 	if (error)
4010 		goto out;
4011 
4012 	/*
4013 	 * Change the uevent file for @dev to the new owner. The uevent file
4014 	 * was created in a separate step when @dev got added and we mirror
4015 	 * that step here.
4016 	 */
4017 	error = sysfs_file_change_owner(kobj, dev_attr_uevent.attr.name, kuid,
4018 					kgid);
4019 	if (error)
4020 		goto out;
4021 
4022 	/*
4023 	 * Change the device groups, the device groups associated with the
4024 	 * device class, and the groups associated with the device type of @dev
4025 	 * to @kuid/@kgid.
4026 	 */
4027 	error = device_attrs_change_owner(dev, kuid, kgid);
4028 	if (error)
4029 		goto out;
4030 
4031 	error = dpm_sysfs_change_owner(dev, kuid, kgid);
4032 	if (error)
4033 		goto out;
4034 
4035 #ifdef CONFIG_BLOCK
4036 	if (sysfs_deprecated && dev->class == &block_class)
4037 		goto out;
4038 #endif
4039 
4040 	/*
4041 	 * Change the owner of the symlink located in the class directory of
4042 	 * the device class associated with @dev which points to the actual
4043 	 * directory entry for @dev to @kuid/@kgid. This ensures that the
4044 	 * symlink shows the same permissions as its target.
4045 	 */
4046 	error = sysfs_link_change_owner(&dev->class->p->subsys.kobj, &dev->kobj,
4047 					dev_name(dev), kuid, kgid);
4048 	if (error)
4049 		goto out;
4050 
4051 out:
4052 	put_device(dev);
4053 	return error;
4054 }
4055 EXPORT_SYMBOL_GPL(device_change_owner);
4056 
4057 /**
4058  * device_shutdown - call ->shutdown() on each device to shutdown.
4059  */
device_shutdown(void)4060 void device_shutdown(void)
4061 {
4062 	struct device *dev, *parent;
4063 
4064 	wait_for_device_probe();
4065 	device_block_probing();
4066 
4067 	cpufreq_suspend();
4068 
4069 	spin_lock(&devices_kset->list_lock);
4070 	/*
4071 	 * Walk the devices list backward, shutting down each in turn.
4072 	 * Beware that device unplug events may also start pulling
4073 	 * devices offline, even as the system is shutting down.
4074 	 */
4075 	while (!list_empty(&devices_kset->list)) {
4076 		dev = list_entry(devices_kset->list.prev, struct device,
4077 				kobj.entry);
4078 
4079 		/*
4080 		 * hold reference count of device's parent to
4081 		 * prevent it from being freed because parent's
4082 		 * lock is to be held
4083 		 */
4084 		parent = get_device(dev->parent);
4085 		get_device(dev);
4086 		/*
4087 		 * Make sure the device is off the kset list, in the
4088 		 * event that dev->*->shutdown() doesn't remove it.
4089 		 */
4090 		list_del_init(&dev->kobj.entry);
4091 		spin_unlock(&devices_kset->list_lock);
4092 
4093 		/* hold lock to avoid race with probe/release */
4094 		if (parent)
4095 			device_lock(parent);
4096 		device_lock(dev);
4097 
4098 		/* Don't allow any more runtime suspends */
4099 		pm_runtime_get_noresume(dev);
4100 		pm_runtime_barrier(dev);
4101 
4102 		if (dev->class && dev->class->shutdown_pre) {
4103 			if (initcall_debug)
4104 				dev_info(dev, "shutdown_pre\n");
4105 			dev->class->shutdown_pre(dev);
4106 		}
4107 		if (dev->bus && dev->bus->shutdown) {
4108 			if (initcall_debug)
4109 				dev_info(dev, "shutdown\n");
4110 			dev->bus->shutdown(dev);
4111 		} else if (dev->driver && dev->driver->shutdown) {
4112 			if (initcall_debug)
4113 				dev_info(dev, "shutdown\n");
4114 			dev->driver->shutdown(dev);
4115 		}
4116 
4117 		device_unlock(dev);
4118 		if (parent)
4119 			device_unlock(parent);
4120 
4121 		put_device(dev);
4122 		put_device(parent);
4123 
4124 		spin_lock(&devices_kset->list_lock);
4125 	}
4126 	spin_unlock(&devices_kset->list_lock);
4127 }
4128 
4129 /*
4130  * Device logging functions
4131  */
4132 
4133 #ifdef CONFIG_PRINTK
4134 static void
set_dev_info(const struct device * dev,struct dev_printk_info * dev_info)4135 set_dev_info(const struct device *dev, struct dev_printk_info *dev_info)
4136 {
4137 	const char *subsys;
4138 
4139 	memset(dev_info, 0, sizeof(*dev_info));
4140 
4141 	if (dev->class)
4142 		subsys = dev->class->name;
4143 	else if (dev->bus)
4144 		subsys = dev->bus->name;
4145 	else
4146 		return;
4147 
4148 	strscpy(dev_info->subsystem, subsys, sizeof(dev_info->subsystem));
4149 
4150 	/*
4151 	 * Add device identifier DEVICE=:
4152 	 *   b12:8         block dev_t
4153 	 *   c127:3        char dev_t
4154 	 *   n8            netdev ifindex
4155 	 *   +sound:card0  subsystem:devname
4156 	 */
4157 	if (MAJOR(dev->devt)) {
4158 		char c;
4159 
4160 		if (strcmp(subsys, "block") == 0)
4161 			c = 'b';
4162 		else
4163 			c = 'c';
4164 
4165 		snprintf(dev_info->device, sizeof(dev_info->device),
4166 			 "%c%u:%u", c, MAJOR(dev->devt), MINOR(dev->devt));
4167 	} else if (strcmp(subsys, "net") == 0) {
4168 		struct net_device *net = to_net_dev(dev);
4169 
4170 		snprintf(dev_info->device, sizeof(dev_info->device),
4171 			 "n%u", net->ifindex);
4172 	} else {
4173 		snprintf(dev_info->device, sizeof(dev_info->device),
4174 			 "+%s:%s", subsys, dev_name(dev));
4175 	}
4176 }
4177 
dev_vprintk_emit(int level,const struct device * dev,const char * fmt,va_list args)4178 int dev_vprintk_emit(int level, const struct device *dev,
4179 		     const char *fmt, va_list args)
4180 {
4181 	struct dev_printk_info dev_info;
4182 
4183 	set_dev_info(dev, &dev_info);
4184 
4185 	return vprintk_emit(0, level, &dev_info, fmt, args);
4186 }
4187 EXPORT_SYMBOL(dev_vprintk_emit);
4188 
dev_printk_emit(int level,const struct device * dev,const char * fmt,...)4189 int dev_printk_emit(int level, const struct device *dev, const char *fmt, ...)
4190 {
4191 	va_list args;
4192 	int r;
4193 
4194 	va_start(args, fmt);
4195 
4196 	r = dev_vprintk_emit(level, dev, fmt, args);
4197 
4198 	va_end(args);
4199 
4200 	return r;
4201 }
4202 EXPORT_SYMBOL(dev_printk_emit);
4203 
__dev_printk(const char * level,const struct device * dev,struct va_format * vaf)4204 static void __dev_printk(const char *level, const struct device *dev,
4205 			struct va_format *vaf)
4206 {
4207 	if (dev)
4208 		dev_printk_emit(level[1] - '0', dev, "%s %s: %pV",
4209 				dev_driver_string(dev), dev_name(dev), vaf);
4210 	else
4211 		printk("%s(NULL device *): %pV", level, vaf);
4212 }
4213 
dev_printk(const char * level,const struct device * dev,const char * fmt,...)4214 void dev_printk(const char *level, const struct device *dev,
4215 		const char *fmt, ...)
4216 {
4217 	struct va_format vaf;
4218 	va_list args;
4219 
4220 	va_start(args, fmt);
4221 
4222 	vaf.fmt = fmt;
4223 	vaf.va = &args;
4224 
4225 	__dev_printk(level, dev, &vaf);
4226 
4227 	va_end(args);
4228 }
4229 EXPORT_SYMBOL(dev_printk);
4230 
4231 #define define_dev_printk_level(func, kern_level)		\
4232 void func(const struct device *dev, const char *fmt, ...)	\
4233 {								\
4234 	struct va_format vaf;					\
4235 	va_list args;						\
4236 								\
4237 	va_start(args, fmt);					\
4238 								\
4239 	vaf.fmt = fmt;						\
4240 	vaf.va = &args;						\
4241 								\
4242 	__dev_printk(kern_level, dev, &vaf);			\
4243 								\
4244 	va_end(args);						\
4245 }								\
4246 EXPORT_SYMBOL(func);
4247 
4248 define_dev_printk_level(_dev_emerg, KERN_EMERG);
4249 define_dev_printk_level(_dev_alert, KERN_ALERT);
4250 define_dev_printk_level(_dev_crit, KERN_CRIT);
4251 define_dev_printk_level(_dev_err, KERN_ERR);
4252 define_dev_printk_level(_dev_warn, KERN_WARNING);
4253 define_dev_printk_level(_dev_notice, KERN_NOTICE);
4254 define_dev_printk_level(_dev_info, KERN_INFO);
4255 
4256 #endif
4257 
4258 /**
4259  * dev_err_probe - probe error check and log helper
4260  * @dev: the pointer to the struct device
4261  * @err: error value to test
4262  * @fmt: printf-style format string
4263  * @...: arguments as specified in the format string
4264  *
4265  * This helper implements common pattern present in probe functions for error
4266  * checking: print debug or error message depending if the error value is
4267  * -EPROBE_DEFER and propagate error upwards.
4268  * In case of -EPROBE_DEFER it sets also defer probe reason, which can be
4269  * checked later by reading devices_deferred debugfs attribute.
4270  * It replaces code sequence::
4271  *
4272  * 	if (err != -EPROBE_DEFER)
4273  * 		dev_err(dev, ...);
4274  * 	else
4275  * 		dev_dbg(dev, ...);
4276  * 	return err;
4277  *
4278  * with::
4279  *
4280  * 	return dev_err_probe(dev, err, ...);
4281  *
4282  * Returns @err.
4283  *
4284  */
dev_err_probe(const struct device * dev,int err,const char * fmt,...)4285 int dev_err_probe(const struct device *dev, int err, const char *fmt, ...)
4286 {
4287 	struct va_format vaf;
4288 	va_list args;
4289 
4290 	va_start(args, fmt);
4291 	vaf.fmt = fmt;
4292 	vaf.va = &args;
4293 
4294 	if (err != -EPROBE_DEFER) {
4295 		dev_err(dev, "error %pe: %pV", ERR_PTR(err), &vaf);
4296 	} else {
4297 		device_set_deferred_probe_reason(dev, &vaf);
4298 		dev_dbg(dev, "error %pe: %pV", ERR_PTR(err), &vaf);
4299 	}
4300 
4301 	va_end(args);
4302 
4303 	return err;
4304 }
4305 EXPORT_SYMBOL_GPL(dev_err_probe);
4306 
fwnode_is_primary(struct fwnode_handle * fwnode)4307 static inline bool fwnode_is_primary(struct fwnode_handle *fwnode)
4308 {
4309 	return fwnode && !IS_ERR(fwnode->secondary);
4310 }
4311 
4312 /**
4313  * set_primary_fwnode - Change the primary firmware node of a given device.
4314  * @dev: Device to handle.
4315  * @fwnode: New primary firmware node of the device.
4316  *
4317  * Set the device's firmware node pointer to @fwnode, but if a secondary
4318  * firmware node of the device is present, preserve it.
4319  */
set_primary_fwnode(struct device * dev,struct fwnode_handle * fwnode)4320 void set_primary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
4321 {
4322 	struct device *parent = dev->parent;
4323 	struct fwnode_handle *fn = dev->fwnode;
4324 
4325 	if (fwnode) {
4326 		if (fwnode_is_primary(fn))
4327 			fn = fn->secondary;
4328 
4329 		if (fn) {
4330 			WARN_ON(fwnode->secondary);
4331 			fwnode->secondary = fn;
4332 		}
4333 		dev->fwnode = fwnode;
4334 	} else {
4335 		if (fwnode_is_primary(fn)) {
4336 			dev->fwnode = fn->secondary;
4337 			if (!(parent && fn == parent->fwnode))
4338 				fn->secondary = NULL;
4339 		} else {
4340 			dev->fwnode = NULL;
4341 		}
4342 	}
4343 }
4344 EXPORT_SYMBOL_GPL(set_primary_fwnode);
4345 
4346 /**
4347  * set_secondary_fwnode - Change the secondary firmware node of a given device.
4348  * @dev: Device to handle.
4349  * @fwnode: New secondary firmware node of the device.
4350  *
4351  * If a primary firmware node of the device is present, set its secondary
4352  * pointer to @fwnode.  Otherwise, set the device's firmware node pointer to
4353  * @fwnode.
4354  */
set_secondary_fwnode(struct device * dev,struct fwnode_handle * fwnode)4355 void set_secondary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
4356 {
4357 	if (fwnode)
4358 		fwnode->secondary = ERR_PTR(-ENODEV);
4359 
4360 	if (fwnode_is_primary(dev->fwnode))
4361 		dev->fwnode->secondary = fwnode;
4362 	else
4363 		dev->fwnode = fwnode;
4364 }
4365 EXPORT_SYMBOL_GPL(set_secondary_fwnode);
4366 
4367 /**
4368  * device_set_of_node_from_dev - reuse device-tree node of another device
4369  * @dev: device whose device-tree node is being set
4370  * @dev2: device whose device-tree node is being reused
4371  *
4372  * Takes another reference to the new device-tree node after first dropping
4373  * any reference held to the old node.
4374  */
device_set_of_node_from_dev(struct device * dev,const struct device * dev2)4375 void device_set_of_node_from_dev(struct device *dev, const struct device *dev2)
4376 {
4377 	of_node_put(dev->of_node);
4378 	dev->of_node = of_node_get(dev2->of_node);
4379 	dev->of_node_reused = true;
4380 }
4381 EXPORT_SYMBOL_GPL(device_set_of_node_from_dev);
4382 
device_set_node(struct device * dev,struct fwnode_handle * fwnode)4383 void device_set_node(struct device *dev, struct fwnode_handle *fwnode)
4384 {
4385 	dev->fwnode = fwnode;
4386 	dev->of_node = to_of_node(fwnode);
4387 }
4388 EXPORT_SYMBOL_GPL(device_set_node);
4389 
device_match_name(struct device * dev,const void * name)4390 int device_match_name(struct device *dev, const void *name)
4391 {
4392 	return sysfs_streq(dev_name(dev), name);
4393 }
4394 EXPORT_SYMBOL_GPL(device_match_name);
4395 
device_match_of_node(struct device * dev,const void * np)4396 int device_match_of_node(struct device *dev, const void *np)
4397 {
4398 	return dev->of_node == np;
4399 }
4400 EXPORT_SYMBOL_GPL(device_match_of_node);
4401 
device_match_fwnode(struct device * dev,const void * fwnode)4402 int device_match_fwnode(struct device *dev, const void *fwnode)
4403 {
4404 	return dev_fwnode(dev) == fwnode;
4405 }
4406 EXPORT_SYMBOL_GPL(device_match_fwnode);
4407 
device_match_devt(struct device * dev,const void * pdevt)4408 int device_match_devt(struct device *dev, const void *pdevt)
4409 {
4410 	return dev->devt == *(dev_t *)pdevt;
4411 }
4412 EXPORT_SYMBOL_GPL(device_match_devt);
4413 
device_match_acpi_dev(struct device * dev,const void * adev)4414 int device_match_acpi_dev(struct device *dev, const void *adev)
4415 {
4416 	return ACPI_COMPANION(dev) == adev;
4417 }
4418 EXPORT_SYMBOL(device_match_acpi_dev);
4419 
device_match_any(struct device * dev,const void * unused)4420 int device_match_any(struct device *dev, const void *unused)
4421 {
4422 	return 1;
4423 }
4424 EXPORT_SYMBOL_GPL(device_match_any);
4425