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