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