1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
6 #include "sd-messages.h"
8 #include "alloc-util.h"
10 #include "dbus-device.h"
11 #include "dbus-unit.h"
12 #include "device-util.h"
15 #include "parse-util.h"
16 #include "path-util.h"
17 #include "ratelimit.h"
18 #include "serialize.h"
19 #include "stat-util.h"
20 #include "string-util.h"
22 #include "udev-util.h"
23 #include "unit-name.h"
26 static const UnitActiveState state_translation_table
[_DEVICE_STATE_MAX
] = {
27 [DEVICE_DEAD
] = UNIT_INACTIVE
,
28 [DEVICE_TENTATIVE
] = UNIT_ACTIVATING
,
29 [DEVICE_PLUGGED
] = UNIT_ACTIVE
,
32 static int device_dispatch_io(sd_device_monitor
*monitor
, sd_device
*dev
, void *userdata
);
33 static void device_update_found_one(Device
*d
, DeviceFound found
, DeviceFound mask
);
35 static void device_unset_sysfs(Device
*d
) {
44 /* Remove this unit from the chain of devices which share the
46 devices
= UNIT(d
)->manager
->devices_by_sysfs
;
47 first
= hashmap_get(devices
, d
->sysfs
);
48 LIST_REMOVE(same_sysfs
, first
, d
);
51 hashmap_remove_and_replace(devices
, d
->sysfs
, first
->sysfs
, first
);
53 hashmap_remove(devices
, d
->sysfs
);
55 d
->sysfs
= mfree(d
->sysfs
);
58 static int device_set_sysfs(Device
*d
, const char *sysfs
) {
59 _cleanup_free_
char *copy
= NULL
;
65 if (streq_ptr(d
->sysfs
, sysfs
))
68 r
= hashmap_ensure_allocated(&UNIT(d
)->manager
->devices_by_sysfs
, &path_hash_ops
);
76 device_unset_sysfs(d
);
78 first
= hashmap_get(UNIT(d
)->manager
->devices_by_sysfs
, sysfs
);
79 LIST_PREPEND(same_sysfs
, first
, d
);
81 r
= hashmap_replace(UNIT(d
)->manager
->devices_by_sysfs
, copy
, first
);
83 LIST_REMOVE(same_sysfs
, first
, d
);
87 d
->sysfs
= TAKE_PTR(copy
);
88 unit_add_to_dbus_queue(UNIT(d
));
93 static void device_init(Unit
*u
) {
94 Device
*d
= DEVICE(u
);
97 assert(UNIT(d
)->load_state
== UNIT_STUB
);
99 /* In contrast to all other unit types we timeout jobs waiting
100 * for devices by default. This is because they otherwise wait
101 * indefinitely for plugged in devices, something which cannot
102 * happen for the other units since their operations time out
104 u
->job_running_timeout
= u
->manager
->default_timeout_start_usec
;
106 u
->ignore_on_isolate
= true;
108 d
->deserialized_state
= _DEVICE_STATE_INVALID
;
111 static void device_done(Unit
*u
) {
112 Device
*d
= DEVICE(u
);
116 device_unset_sysfs(d
);
117 d
->wants_property
= strv_free(d
->wants_property
);
120 static int device_load(Unit
*u
) {
123 r
= unit_load_fragment_and_dropin(u
, false);
127 if (!u
->description
) {
128 /* Generate a description based on the path, to be used until the device is initialized
130 r
= unit_name_to_path(u
->id
, &u
->description
);
132 log_unit_debug_errno(u
, r
, "Failed to unescape name: %m");
138 static void device_set_state(Device
*d
, DeviceState state
) {
139 DeviceState old_state
;
142 if (d
->state
!= state
)
143 bus_unit_send_pending_change_signal(UNIT(d
), false);
145 old_state
= d
->state
;
148 if (state
== DEVICE_DEAD
)
149 device_unset_sysfs(d
);
151 if (state
!= old_state
)
152 log_unit_debug(UNIT(d
), "Changed %s -> %s", device_state_to_string(old_state
), device_state_to_string(state
));
154 unit_notify(UNIT(d
), state_translation_table
[old_state
], state_translation_table
[state
], 0);
157 static int device_coldplug(Unit
*u
) {
158 Device
*d
= DEVICE(u
);
161 assert(d
->state
== DEVICE_DEAD
);
163 /* First, let's put the deserialized state and found mask into effect, if we have it. */
165 if (d
->deserialized_state
< 0 ||
166 (d
->deserialized_state
== d
->state
&&
167 d
->deserialized_found
== d
->found
))
170 d
->found
= d
->deserialized_found
;
171 device_set_state(d
, d
->deserialized_state
);
175 static void device_catchup(Unit
*u
) {
176 Device
*d
= DEVICE(u
);
180 /* Second, let's update the state with the enumerated state if it's different */
181 if (d
->enumerated_found
== d
->found
)
184 device_update_found_one(d
, d
->enumerated_found
, DEVICE_FOUND_MASK
);
187 static const struct {
190 } device_found_map
[] = {
191 { DEVICE_FOUND_UDEV
, "found-udev" },
192 { DEVICE_FOUND_MOUNT
, "found-mount" },
193 { DEVICE_FOUND_SWAP
, "found-swap" },
196 static int device_found_to_string_many(DeviceFound flags
, char **ret
) {
197 _cleanup_free_
char *s
= NULL
;
201 for (size_t i
= 0; i
< ELEMENTSOF(device_found_map
); i
++) {
202 if (!FLAGS_SET(flags
, device_found_map
[i
].flag
))
205 if (!strextend_with_separator(&s
, ",", device_found_map
[i
].name
))
214 static int device_found_from_string_many(const char *name
, DeviceFound
*ret
) {
215 DeviceFound flags
= 0;
221 _cleanup_free_
char *word
= NULL
;
225 r
= extract_first_word(&name
, &word
, ",", 0);
231 for (i
= 0; i
< ELEMENTSOF(device_found_map
); i
++)
232 if (streq(word
, device_found_map
[i
].name
)) {
233 f
= device_found_map
[i
].flag
;
247 static int device_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
248 _cleanup_free_
char *s
= NULL
;
249 Device
*d
= DEVICE(u
);
256 (void) serialize_item(f
, "state", device_state_to_string(d
->state
));
258 if (device_found_to_string_many(d
->found
, &s
) >= 0)
259 (void) serialize_item(f
, "found", s
);
264 static int device_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
265 Device
*d
= DEVICE(u
);
274 if (streq(key
, "state")) {
277 state
= device_state_from_string(value
);
279 log_unit_debug(u
, "Failed to parse state value, ignoring: %s", value
);
281 d
->deserialized_state
= state
;
283 } else if (streq(key
, "found")) {
284 r
= device_found_from_string_many(value
, &d
->deserialized_found
);
286 log_unit_debug_errno(u
, r
, "Failed to parse found value '%s', ignoring: %m", value
);
289 log_unit_debug(u
, "Unknown serialization key: %s", key
);
294 static void device_dump(Unit
*u
, FILE *f
, const char *prefix
) {
295 Device
*d
= DEVICE(u
);
296 _cleanup_free_
char *s
= NULL
;
300 (void) device_found_to_string_many(d
->found
, &s
);
303 "%sDevice State: %s\n"
306 prefix
, device_state_to_string(d
->state
),
307 prefix
, strna(d
->sysfs
),
310 STRV_FOREACH(i
, d
->wants_property
)
311 fprintf(f
, "%sudev SYSTEMD_WANTS: %s\n",
315 _pure_
static UnitActiveState
device_active_state(Unit
*u
) {
318 return state_translation_table
[DEVICE(u
)->state
];
321 _pure_
static const char *device_sub_state_to_string(Unit
*u
) {
324 return device_state_to_string(DEVICE(u
)->state
);
327 static int device_update_description(Unit
*u
, sd_device
*dev
, const char *path
) {
328 _cleanup_free_
char *j
= NULL
;
329 const char *model
, *label
, *desc
;
338 (sd_device_get_property_value(dev
, "ID_MODEL_FROM_DATABASE", &model
) >= 0 ||
339 sd_device_get_property_value(dev
, "ID_MODEL", &model
) >= 0)) {
342 /* Try to concatenate the device model string with a label, if there is one */
343 if (sd_device_get_property_value(dev
, "ID_FS_LABEL", &label
) >= 0 ||
344 sd_device_get_property_value(dev
, "ID_PART_ENTRY_NAME", &label
) >= 0 ||
345 sd_device_get_property_value(dev
, "ID_PART_ENTRY_NUMBER", &label
) >= 0) {
347 desc
= j
= strjoin(model
, " ", label
);
353 r
= unit_set_description(u
, desc
);
355 return log_unit_error_errno(u
, r
, "Failed to set device description: %m");
360 static int device_add_udev_wants(Unit
*u
, sd_device
*dev
) {
361 _cleanup_strv_free_
char **added
= NULL
;
362 const char *wants
, *property
;
363 Device
*d
= DEVICE(u
);
369 property
= MANAGER_IS_USER(u
->manager
) ? "SYSTEMD_USER_WANTS" : "SYSTEMD_WANTS";
371 r
= sd_device_get_property_value(dev
, property
, &wants
);
376 _cleanup_free_
char *word
= NULL
, *k
= NULL
;
378 r
= extract_first_word(&wants
, &word
, NULL
, EXTRACT_UNQUOTE
);
384 return log_unit_error_errno(u
, r
, "Failed to parse property %s with value %s: %m", property
, wants
);
386 if (unit_name_is_valid(word
, UNIT_NAME_TEMPLATE
) && d
->sysfs
) {
387 _cleanup_free_
char *escaped
= NULL
;
389 /* If the unit name is specified as template, then automatically fill in the sysfs path of the
390 * device as instance name, properly escaped. */
392 r
= unit_name_path_escape(d
->sysfs
, &escaped
);
394 return log_unit_error_errno(u
, r
, "Failed to escape %s: %m", d
->sysfs
);
396 r
= unit_name_replace_instance(word
, escaped
, &k
);
398 return log_unit_error_errno(u
, r
, "Failed to build %s instance of template %s: %m", escaped
, word
);
400 /* If this is not a template, then let's mangle it so, that it becomes a valid unit name. */
402 r
= unit_name_mangle(word
, UNIT_NAME_MANGLE_WARN
, &k
);
404 return log_unit_error_errno(u
, r
, "Failed to mangle unit name \"%s\": %m", word
);
407 r
= unit_add_dependency_by_name(u
, UNIT_WANTS
, k
, true, UNIT_DEPENDENCY_UDEV
);
409 return log_unit_error_errno(u
, r
, "Failed to add Wants= dependency: %m");
411 r
= strv_push(&added
, k
);
418 if (d
->state
!= DEVICE_DEAD
)
419 /* So here's a special hack, to compensate for the fact that the udev database's reload cycles are not
420 * synchronized with our own reload cycles: when we detect that the SYSTEMD_WANTS property of a device
421 * changes while the device unit is already up, let's manually trigger any new units listed in it not
422 * seen before. This typically happens during the boot-time switch root transition, as udev devices
423 * will generally already be up in the initrd, but SYSTEMD_WANTS properties get then added through udev
424 * rules only available on the host system, and thus only when the initial udev coldplug trigger runs.
426 * We do this only if the device has been up already when we parse this, as otherwise the usual
427 * dependency logic that is run from the dead → plugged transition will trigger these deps. */
428 STRV_FOREACH(i
, added
) {
429 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
431 if (strv_contains(d
->wants_property
, *i
)) /* Was this unit already listed before? */
434 r
= manager_add_job_by_name(u
->manager
, JOB_START
, *i
, JOB_FAIL
, NULL
, &error
, NULL
);
436 log_unit_warning_errno(u
, r
, "Failed to enqueue SYSTEMD_WANTS= job, ignoring: %s", bus_error_message(&error
, r
));
439 return strv_free_and_replace(d
->wants_property
, added
);
442 static bool device_is_bound_by_mounts(Device
*d
, sd_device
*dev
) {
443 const char *bound_by
;
449 if (sd_device_get_property_value(dev
, "SYSTEMD_MOUNT_DEVICE_BOUND", &bound_by
) >= 0) {
450 r
= parse_boolean(bound_by
);
452 log_device_warning_errno(dev
, r
, "Failed to parse SYSTEMD_MOUNT_DEVICE_BOUND='%s' udev property, ignoring: %m", bound_by
);
454 d
->bind_mounts
= r
> 0;
456 d
->bind_mounts
= false;
458 return d
->bind_mounts
;
461 static void device_upgrade_mount_deps(Unit
*u
) {
466 /* Let's upgrade Requires= to BindsTo= on us. (Used when SYSTEMD_MOUNT_DEVICE_BOUND is set) */
468 HASHMAP_FOREACH_KEY(v
, other
, unit_get_dependencies(u
, UNIT_REQUIRED_BY
)) {
469 if (other
->type
!= UNIT_MOUNT
)
472 r
= unit_add_dependency(other
, UNIT_BINDS_TO
, u
, true, UNIT_DEPENDENCY_UDEV
);
474 log_unit_warning_errno(u
, r
, "Failed to add BindsTo= dependency between device and mount unit, ignoring: %m");
478 static int device_setup_unit(Manager
*m
, sd_device
*dev
, const char *path
, bool main
) {
479 _cleanup_free_
char *e
= NULL
;
480 const char *sysfs
= NULL
;
489 r
= sd_device_get_syspath(dev
, &sysfs
);
491 return log_device_debug_errno(dev
, r
, "Couldn't get syspath from device, ignoring: %m");
494 r
= unit_name_from_path(path
, ".device", &e
);
496 /* Let's complain about overly long device names only at most once every 5s or so. This is
497 * something we should mention, since relevant devices are not manageable by systemd, but not
498 * flood the log about. */
499 static RateLimit rate_limit
= {
500 .interval
= 5 * USEC_PER_SEC
,
504 /* If we cannot convert a device name to a unit name then let's ignore the device. So far,
505 * devices with such long names weren't really the kind you want to manage with systemd
506 * anyway, hence this shouldn't be a problem. */
508 if (r
== -ENAMETOOLONG
)
509 return log_struct_errno(
510 ratelimit_below(&rate_limit
) ? LOG_WARNING
: LOG_DEBUG
, r
,
511 "MESSAGE_ID=" SD_MESSAGE_DEVICE_PATH_NOT_SUITABLE_STR
,
513 LOG_MESSAGE("Device path '%s' too long to fit into unit name, ignoring device.", path
));
515 return log_struct_errno(
516 ratelimit_below(&rate_limit
) ? LOG_WARNING
: LOG_DEBUG
, r
,
517 "MESSAGE_ID=" SD_MESSAGE_DEVICE_PATH_NOT_SUITABLE_STR
,
519 LOG_MESSAGE("Failed to generate valid unit name from device path '%s', ignoring device: %m", path
));
522 u
= manager_get_unit(m
, e
);
524 /* The device unit can still be present even if the device was unplugged: a mount unit can reference it
525 * hence preventing the GC to have garbaged it. That's desired since the device unit may have a
526 * dependency on the mount unit which was added during the loading of the later. When the device is
527 * plugged the sysfs might not be initialized yet, as we serialize the device's state but do not
528 * serialize the sysfs path across reloads/reexecs. Hence, when coming back from a reload/restart we
529 * might have the state valid, but not the sysfs path. Hence, let's filter out conflicting devices, but
530 * let's accept devices in any state with no sysfs path set. */
532 if (DEVICE(u
)->state
== DEVICE_PLUGGED
&&
535 !path_equal(DEVICE(u
)->sysfs
, sysfs
))
536 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EEXIST
),
537 "Device %s appeared twice with different sysfs paths %s and %s, ignoring the latter.",
538 e
, DEVICE(u
)->sysfs
, sysfs
);
542 /* Let's remove all dependencies generated due to udev properties. We'll re-add whatever is configured
544 unit_remove_dependencies(u
, UNIT_DEPENDENCY_UDEV
);
548 r
= unit_new_for_name(m
, sizeof(Device
), e
, &u
);
550 log_device_error_errno(dev
, r
, "Failed to allocate device unit %s: %m", e
);
554 unit_add_to_load_queue(u
);
557 /* If this was created via some dependency and has not actually been seen yet ->sysfs will not be
558 * initialized. Hence initialize it if necessary. */
560 r
= device_set_sysfs(DEVICE(u
), sysfs
);
562 log_unit_error_errno(u
, r
, "Failed to set sysfs path %s: %m", sysfs
);
566 /* The additional systemd udev properties we only interpret for the main object */
568 (void) device_add_udev_wants(u
, dev
);
571 (void) device_update_description(u
, dev
, path
);
573 /* So the user wants the mount units to be bound to the device but a mount unit might has been seen
574 * by systemd before the device appears on its radar. In this case the device unit is partially
575 * initialized and includes the deps on the mount unit but at that time the "bind mounts" flag wasn't
576 * present. Fix this up now. */
577 if (dev
&& device_is_bound_by_mounts(DEVICE(u
), dev
))
578 device_upgrade_mount_deps(u
);
589 static void device_process_new(Manager
*m
, sd_device
*dev
) {
590 const char *sysfs
, *dn
, *alias
;
596 if (sd_device_get_syspath(dev
, &sysfs
) < 0)
599 /* Add the main unit named after the sysfs path. If this one fails, don't bother with the rest, as
600 * this one shall be the main device unit the others just follow. (Compare with how
601 * device_following() is implemented, see below, which looks for the sysfs device.) */
602 if (device_setup_unit(m
, dev
, sysfs
, true) < 0)
605 /* Add an additional unit for the device node */
606 if (sd_device_get_devname(dev
, &dn
) >= 0)
607 (void) device_setup_unit(m
, dev
, dn
, false);
609 /* Add additional units for all symlinks */
610 if (sd_device_get_devnum(dev
, &devnum
) >= 0) {
613 FOREACH_DEVICE_DEVLINK(dev
, p
) {
616 if (PATH_STARTSWITH_SET(p
, "/dev/block/", "/dev/char/"))
619 /* Verify that the symlink in the FS actually belongs to this device. This is useful
620 * to deal with conflicting devices, e.g. when two disks want the same
621 * /dev/disk/by-label/xxx link because they have the same label. We want to make sure
622 * that the same device that won the symlink wins in systemd, so we check the device
623 * node major/minor */
624 if (stat(p
, &st
) >= 0 &&
625 ((!S_ISBLK(st
.st_mode
) && !S_ISCHR(st
.st_mode
)) ||
626 st
.st_rdev
!= devnum
))
629 (void) device_setup_unit(m
, dev
, p
, false);
633 /* Add additional units for all explicitly configured aliases */
634 if (sd_device_get_property_value(dev
, "SYSTEMD_ALIAS", &alias
) < 0)
638 _cleanup_free_
char *word
= NULL
;
640 r
= extract_first_word(&alias
, &word
, NULL
, EXTRACT_UNQUOTE
);
644 return (void) log_oom();
646 return (void) log_device_warning_errno(dev
, r
, "Failed to parse SYSTEMD_ALIAS property, ignoring: %m");
648 if (!path_is_absolute(word
))
649 log_device_warning(dev
, "SYSTEMD_ALIAS is not an absolute path, ignoring: %s", word
);
650 else if (!path_is_normalized(word
))
651 log_device_warning(dev
, "SYSTEMD_ALIAS is not a normalized path, ignoring: %s", word
);
653 (void) device_setup_unit(m
, dev
, word
, false);
657 static void device_found_changed(Device
*d
, DeviceFound previous
, DeviceFound now
) {
660 /* Didn't exist before, but does now? if so, generate a new invocation ID for it */
661 if (previous
== DEVICE_NOT_FOUND
&& now
!= DEVICE_NOT_FOUND
)
662 (void) unit_acquire_invocation_id(UNIT(d
));
664 if (FLAGS_SET(now
, DEVICE_FOUND_UDEV
))
665 /* When the device is known to udev we consider it plugged. */
666 device_set_state(d
, DEVICE_PLUGGED
);
667 else if (now
!= DEVICE_NOT_FOUND
&& !FLAGS_SET(previous
, DEVICE_FOUND_UDEV
))
668 /* If the device has not been seen by udev yet, but is now referenced by the kernel, then we assume the
669 * kernel knows it now, and udev might soon too. */
670 device_set_state(d
, DEVICE_TENTATIVE
);
672 /* If nobody sees the device, or if the device was previously seen by udev and now is only referenced
673 * from the kernel, then we consider the device is gone, the kernel just hasn't noticed it yet. */
674 device_set_state(d
, DEVICE_DEAD
);
677 static void device_update_found_one(Device
*d
, DeviceFound found
, DeviceFound mask
) {
682 m
= UNIT(d
)->manager
;
684 if (MANAGER_IS_RUNNING(m
) && (m
->honor_device_enumeration
|| MANAGER_IS_USER(m
))) {
685 DeviceFound n
, previous
;
687 /* When we are already running, then apply the new mask right-away, and trigger state changes
690 n
= (d
->found
& ~mask
) | (found
& mask
);
697 device_found_changed(d
, previous
, n
);
699 /* We aren't running yet, let's apply the new mask to the shadow variable instead, which we'll apply as
700 * soon as we catch-up with the state. */
701 d
->enumerated_found
= (d
->enumerated_found
& ~mask
) | (found
& mask
);
704 static void device_update_found_by_sysfs(Manager
*m
, const char *sysfs
, DeviceFound found
, DeviceFound mask
) {
713 l
= hashmap_get(m
->devices_by_sysfs
, sysfs
);
714 LIST_FOREACH(same_sysfs
, d
, l
)
715 device_update_found_one(d
, found
, mask
);
718 static void device_update_found_by_name(Manager
*m
, const char *path
, DeviceFound found
, DeviceFound mask
) {
719 _cleanup_free_
char *e
= NULL
;
729 r
= unit_name_from_path(path
, ".device", &e
);
731 return (void) log_debug_errno(r
, "Failed to generate unit name from device path, ignoring: %m");
733 u
= manager_get_unit(m
, e
);
737 device_update_found_one(DEVICE(u
), found
, mask
);
740 static bool device_is_ready(sd_device
*dev
) {
745 if (device_is_renaming(dev
) > 0)
748 /* Is it really tagged as 'systemd' right now? */
749 if (sd_device_has_current_tag(dev
, "systemd") <= 0)
752 if (sd_device_get_property_value(dev
, "SYSTEMD_READY", &ready
) < 0)
755 return parse_boolean(ready
) != 0;
758 static Unit
*device_following(Unit
*u
) {
759 Device
*d
= DEVICE(u
);
760 Device
*first
= NULL
;
764 if (startswith(u
->id
, "sys-"))
767 /* Make everybody follow the unit that's named after the sysfs path */
768 LIST_FOREACH(same_sysfs
, other
, d
->same_sysfs_next
)
769 if (startswith(UNIT(other
)->id
, "sys-"))
772 LIST_FOREACH_BACKWARDS(same_sysfs
, other
, d
->same_sysfs_prev
) {
773 if (startswith(UNIT(other
)->id
, "sys-"))
782 static int device_following_set(Unit
*u
, Set
**_set
) {
783 Device
*d
= DEVICE(u
);
784 _cleanup_set_free_ Set
*set
= NULL
;
790 if (LIST_JUST_US(same_sysfs
, d
)) {
799 LIST_FOREACH(same_sysfs
, other
, d
->same_sysfs_next
) {
800 r
= set_put(set
, other
);
805 LIST_FOREACH_BACKWARDS(same_sysfs
, other
, d
->same_sysfs_prev
) {
806 r
= set_put(set
, other
);
811 *_set
= TAKE_PTR(set
);
815 static void device_shutdown(Manager
*m
) {
818 m
->device_monitor
= sd_device_monitor_unref(m
->device_monitor
);
819 m
->devices_by_sysfs
= hashmap_free(m
->devices_by_sysfs
);
822 static void device_enumerate(Manager
*m
) {
823 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
829 if (!m
->device_monitor
) {
830 r
= sd_device_monitor_new(&m
->device_monitor
);
832 log_error_errno(r
, "Failed to allocate device monitor: %m");
836 /* This will fail if we are unprivileged, but that
837 * should not matter much, as user instances won't run
839 (void) sd_device_monitor_set_receive_buffer_size(m
->device_monitor
, 128*1024*1024);
841 r
= sd_device_monitor_filter_add_match_tag(m
->device_monitor
, "systemd");
843 log_error_errno(r
, "Failed to add udev tag match: %m");
847 r
= sd_device_monitor_attach_event(m
->device_monitor
, m
->event
);
849 log_error_errno(r
, "Failed to attach event to device monitor: %m");
853 r
= sd_device_monitor_start(m
->device_monitor
, device_dispatch_io
, m
);
855 log_error_errno(r
, "Failed to start device monitor: %m");
860 r
= sd_device_enumerator_new(&e
);
862 log_error_errno(r
, "Failed to allocate device enumerator: %m");
866 r
= sd_device_enumerator_add_match_tag(e
, "systemd");
868 log_error_errno(r
, "Failed to set tag for device enumeration: %m");
872 FOREACH_DEVICE(e
, dev
) {
875 if (!device_is_ready(dev
))
878 device_process_new(m
, dev
);
880 if (sd_device_get_syspath(dev
, &sysfs
) < 0)
883 device_update_found_by_sysfs(m
, sysfs
, DEVICE_FOUND_UDEV
, DEVICE_FOUND_UDEV
);
892 static void device_propagate_reload_by_sysfs(Manager
*m
, const char *sysfs
) {
899 l
= hashmap_get(m
->devices_by_sysfs
, sysfs
);
900 LIST_FOREACH(same_sysfs
, d
, l
) {
901 if (d
->state
== DEVICE_DEAD
)
904 r
= manager_propagate_reload(m
, UNIT(d
), JOB_REPLACE
, NULL
);
906 log_warning_errno(r
, "Failed to propagate reload, ignoring: %m");
910 static void device_remove_old_on_move(Manager
*m
, sd_device
*dev
) {
911 _cleanup_free_
char *syspath_old
= NULL
, *e
= NULL
;
912 const char *devpath_old
;
915 r
= sd_device_get_property_value(dev
, "DEVPATH_OLD", &devpath_old
);
917 return (void) log_device_debug_errno(dev
, r
, "Failed to get DEVPATH_OLD= property on 'move' uevent, ignoring: %m");
919 syspath_old
= path_join("/sys", devpath_old
);
921 return (void) log_oom();
923 r
= unit_name_from_path(syspath_old
, ".device", &e
);
925 return (void) log_device_debug_errno(dev
, r
, "Failed to generate unit name from old device path, ignoring: %m");
927 device_update_found_by_sysfs(m
, syspath_old
, 0, DEVICE_FOUND_UDEV
|DEVICE_FOUND_MOUNT
|DEVICE_FOUND_SWAP
);
930 static int device_dispatch_io(sd_device_monitor
*monitor
, sd_device
*dev
, void *userdata
) {
931 sd_device_action_t action
;
932 Manager
*m
= userdata
;
939 r
= sd_device_get_syspath(dev
, &sysfs
);
941 log_device_error_errno(dev
, r
, "Failed to get device sys path: %m");
945 r
= sd_device_get_action(dev
, &action
);
947 log_device_error_errno(dev
, r
, "Failed to get udev action: %m");
951 if (!IN_SET(action
, SD_DEVICE_ADD
, SD_DEVICE_REMOVE
, SD_DEVICE_MOVE
))
952 device_propagate_reload_by_sysfs(m
, sysfs
);
954 if (action
== SD_DEVICE_MOVE
)
955 device_remove_old_on_move(m
, dev
);
957 /* A change event can signal that a device is becoming ready, in particular if the device is using
958 * the SYSTEMD_READY logic in udev so we need to reach the else block of the following if, even for
960 if (action
== SD_DEVICE_REMOVE
) {
961 r
= swap_process_device_remove(m
, dev
);
963 log_device_warning_errno(dev
, r
, "Failed to process swap device remove event, ignoring: %m");
965 /* If we get notified that a device was removed by udev, then it's completely gone, hence
966 * unset all found bits */
967 device_update_found_by_sysfs(m
, sysfs
, 0, DEVICE_FOUND_UDEV
|DEVICE_FOUND_MOUNT
|DEVICE_FOUND_SWAP
);
969 } else if (device_is_ready(dev
)) {
971 device_process_new(m
, dev
);
973 r
= swap_process_device_new(m
, dev
);
975 log_device_warning_errno(dev
, r
, "Failed to process swap device new event, ignoring: %m");
977 manager_dispatch_load_queue(m
);
979 /* The device is found now, set the udev found bit */
980 device_update_found_by_sysfs(m
, sysfs
, DEVICE_FOUND_UDEV
, DEVICE_FOUND_UDEV
);
982 /* The device is nominally around, but not ready for us. Hence unset the udev bit, but leave
983 * the rest around. */
984 device_update_found_by_sysfs(m
, sysfs
, 0, DEVICE_FOUND_UDEV
);
989 static bool device_supported(void) {
990 static int read_only
= -1;
992 /* If /sys is read-only we don't support device units, and any
993 * attempts to start one should fail immediately. */
996 read_only
= path_is_read_only_fs("/sys");
998 return read_only
<= 0;
1001 static int validate_node(Manager
*m
, const char *node
, sd_device
**ret
) {
1009 /* Validates a device node that showed up in /proc/swaps or /proc/self/mountinfo if it makes sense for us to
1010 * track. Note that this validator is fine within missing device nodes, but not with badly set up ones! */
1012 if (!path_startswith(node
, "/dev")) {
1014 return 0; /* bad! */
1017 if (stat(node
, &st
) < 0) {
1018 if (errno
!= ENOENT
)
1019 return log_error_errno(errno
, "Failed to stat() device node file %s: %m", node
);
1022 return 1; /* good! (though missing) */
1025 _cleanup_(sd_device_unrefp
) sd_device
*dev
= NULL
;
1027 r
= sd_device_new_from_stat_rdev(&dev
, &st
);
1030 return 1; /* good! (though missing) */
1031 } else if (r
== -ENOTTY
) {
1033 return 0; /* bad! (not a device node but some other kind of file system node) */
1035 return log_error_errno(r
, "Failed to get udev device from devnum %u:%u: %m", major(st
.st_rdev
), minor(st
.st_rdev
));
1037 *ret
= TAKE_PTR(dev
);
1038 return 1; /* good! */
1042 void device_found_node(Manager
*m
, const char *node
, DeviceFound found
, DeviceFound mask
) {
1046 if (!device_supported())
1052 /* This is called whenever we find a device referenced in /proc/swaps or /proc/self/mounts. Such a device might
1053 * be mounted/enabled at a time where udev has not finished probing it yet, and we thus haven't learned about
1054 * it yet. In this case we will set the device unit to "tentative" state.
1056 * This takes a pair of DeviceFound flags parameters. The 'mask' parameter is a bit mask that indicates which
1057 * bits of 'found' to copy into the per-device DeviceFound flags field. Thus, this function may be used to set
1058 * and unset individual bits in a single call, while merging partially with previous state. */
1060 if ((found
& mask
) != 0) {
1061 _cleanup_(sd_device_unrefp
) sd_device
*dev
= NULL
;
1063 /* If the device is known in the kernel and newly appeared, then we'll create a device unit for it,
1064 * under the name referenced in /proc/swaps or /proc/self/mountinfo. But first, let's validate if
1065 * everything is alright with the device node. */
1067 if (validate_node(m
, node
, &dev
) <= 0)
1068 return; /* Don't create a device unit for this if the device node is borked. */
1070 (void) device_setup_unit(m
, dev
, node
, false);
1073 /* Update the device unit's state, should it exist */
1074 (void) device_update_found_by_name(m
, node
, found
, mask
);
1077 bool device_shall_be_bound_by(Unit
*device
, Unit
*u
) {
1081 if (u
->type
!= UNIT_MOUNT
)
1084 return DEVICE(device
)->bind_mounts
;
1087 const UnitVTable device_vtable
= {
1088 .object_size
= sizeof(Device
),
1096 .init
= device_init
,
1097 .done
= device_done
,
1098 .load
= device_load
,
1100 .coldplug
= device_coldplug
,
1101 .catchup
= device_catchup
,
1103 .serialize
= device_serialize
,
1104 .deserialize_item
= device_deserialize_item
,
1106 .dump
= device_dump
,
1108 .active_state
= device_active_state
,
1109 .sub_state_to_string
= device_sub_state_to_string
,
1111 .following
= device_following
,
1112 .following_set
= device_following_set
,
1114 .enumerate
= device_enumerate
,
1115 .shutdown
= device_shutdown
,
1116 .supported
= device_supported
,
1118 .status_message_formats
= {
1119 .starting_stopping
= {
1120 [0] = "Expecting device %s...",
1122 .finished_start_job
= {
1123 [JOB_DONE
] = "Found device %s.",
1124 [JOB_TIMEOUT
] = "Timed out waiting for device %s.",