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