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