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