1 /* SPDX-License-Identifier: LGPL-2.1+ */
6 #include "alloc-util.h"
8 #include "dbus-device.h"
10 #include "device-private.h"
11 #include "device-util.h"
14 #include "parse-util.h"
15 #include "path-util.h"
16 #include "serialize.h"
17 #include "stat-util.h"
18 #include "string-util.h"
20 #include "udev-util.h"
21 #include "unit-name.h"
24 static const UnitActiveState state_translation_table
[_DEVICE_STATE_MAX
] = {
25 [DEVICE_DEAD
] = UNIT_INACTIVE
,
26 [DEVICE_TENTATIVE
] = UNIT_ACTIVATING
,
27 [DEVICE_PLUGGED
] = UNIT_ACTIVE
,
30 static int device_dispatch_io(sd_device_monitor
*monitor
, sd_device
*dev
, void *userdata
);
31 static void device_update_found_one(Device
*d
, DeviceFound found
, DeviceFound mask
);
33 static void device_unset_sysfs(Device
*d
) {
42 /* Remove this unit from the chain of devices which share the
44 devices
= UNIT(d
)->manager
->devices_by_sysfs
;
45 first
= hashmap_get(devices
, d
->sysfs
);
46 LIST_REMOVE(same_sysfs
, first
, d
);
49 hashmap_remove_and_replace(devices
, d
->sysfs
, first
->sysfs
, first
);
51 hashmap_remove(devices
, d
->sysfs
);
53 d
->sysfs
= mfree(d
->sysfs
);
56 static int device_set_sysfs(Device
*d
, const char *sysfs
) {
57 _cleanup_free_
char *copy
= NULL
;
63 if (streq_ptr(d
->sysfs
, sysfs
))
66 r
= hashmap_ensure_allocated(&UNIT(d
)->manager
->devices_by_sysfs
, &path_hash_ops
);
74 device_unset_sysfs(d
);
76 first
= hashmap_get(UNIT(d
)->manager
->devices_by_sysfs
, sysfs
);
77 LIST_PREPEND(same_sysfs
, first
, d
);
79 r
= hashmap_replace(UNIT(d
)->manager
->devices_by_sysfs
, copy
, first
);
81 LIST_REMOVE(same_sysfs
, first
, d
);
85 d
->sysfs
= TAKE_PTR(copy
);
86 unit_add_to_dbus_queue(UNIT(d
));
91 static void device_init(Unit
*u
) {
92 Device
*d
= DEVICE(u
);
95 assert(UNIT(d
)->load_state
== UNIT_STUB
);
97 /* In contrast to all other unit types we timeout jobs waiting
98 * for devices by default. This is because they otherwise wait
99 * indefinitely for plugged in devices, something which cannot
100 * happen for the other units since their operations time out
102 u
->job_running_timeout
= u
->manager
->default_timeout_start_usec
;
104 u
->ignore_on_isolate
= true;
106 d
->deserialized_state
= _DEVICE_STATE_INVALID
;
109 static void device_done(Unit
*u
) {
110 Device
*d
= DEVICE(u
);
114 device_unset_sysfs(d
);
115 d
->wants_property
= strv_free(d
->wants_property
);
118 static int device_load(Unit
*u
) {
121 r
= unit_load_fragment_and_dropin(u
, false);
125 if (!u
->description
) {
126 /* Generate a description based on the path, to be used until the
127 device is initialized properly */
128 r
= unit_name_to_path(u
->id
, &u
->description
);
130 log_unit_debug_errno(u
, r
, "Failed to unescape name: %m");
136 static void device_set_state(Device
*d
, DeviceState state
) {
137 DeviceState old_state
;
140 if (d
->state
!= state
)
141 bus_unit_send_pending_change_signal(UNIT(d
), false);
143 old_state
= d
->state
;
146 if (state
== DEVICE_DEAD
)
147 device_unset_sysfs(d
);
149 if (state
!= old_state
)
150 log_unit_debug(UNIT(d
), "Changed %s -> %s", device_state_to_string(old_state
), device_state_to_string(state
));
152 unit_notify(UNIT(d
), state_translation_table
[old_state
], state_translation_table
[state
], 0);
155 static int device_coldplug(Unit
*u
) {
156 Device
*d
= DEVICE(u
);
159 assert(d
->state
== DEVICE_DEAD
);
161 /* First, let's put the deserialized state and found mask into effect, if we have it. */
163 if (d
->deserialized_state
< 0 ||
164 (d
->deserialized_state
== d
->state
&&
165 d
->deserialized_found
== d
->found
))
168 d
->found
= d
->deserialized_found
;
169 device_set_state(d
, d
->deserialized_state
);
173 static void device_catchup(Unit
*u
) {
174 Device
*d
= DEVICE(u
);
178 /* Second, let's update the state with the enumerated state if it's different */
179 if (d
->enumerated_found
== d
->found
)
182 device_update_found_one(d
, d
->enumerated_found
, DEVICE_FOUND_MASK
);
185 static const struct {
188 } device_found_map
[] = {
189 { DEVICE_FOUND_UDEV
, "found-udev" },
190 { DEVICE_FOUND_MOUNT
, "found-mount" },
191 { DEVICE_FOUND_SWAP
, "found-swap" },
194 static int device_found_to_string_many(DeviceFound flags
, char **ret
) {
195 _cleanup_free_
char *s
= NULL
;
200 for (i
= 0; i
< ELEMENTSOF(device_found_map
); i
++) {
201 if (!FLAGS_SET(flags
, device_found_map
[i
].flag
))
204 if (!strextend_with_separator(&s
, ",", device_found_map
[i
].name
, NULL
))
213 static int device_found_from_string_many(const char *name
, DeviceFound
*ret
) {
214 DeviceFound flags
= 0;
220 _cleanup_free_
char *word
= NULL
;
224 r
= extract_first_word(&name
, &word
, ",", 0);
230 for (i
= 0; i
< ELEMENTSOF(device_found_map
); i
++)
231 if (streq(word
, device_found_map
[i
].name
)) {
232 f
= device_found_map
[i
].flag
;
246 static int device_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
247 _cleanup_free_
char *s
= NULL
;
248 Device
*d
= DEVICE(u
);
254 (void) serialize_item(f
, "state", device_state_to_string(d
->state
));
256 if (device_found_to_string_many(d
->found
, &s
) >= 0)
257 (void) serialize_item(f
, "found", s
);
262 static int device_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
263 Device
*d
= DEVICE(u
);
271 if (streq(key
, "state")) {
274 state
= device_state_from_string(value
);
276 log_unit_debug(u
, "Failed to parse state value, ignoring: %s", value
);
278 d
->deserialized_state
= state
;
280 } else if (streq(key
, "found")) {
281 r
= device_found_from_string_many(value
, &d
->deserialized_found
);
283 log_unit_debug_errno(u
, r
, "Failed to parse found value '%s', ignoring: %m", value
);
286 log_unit_debug(u
, "Unknown serialization key: %s", key
);
291 static void device_dump(Unit
*u
, FILE *f
, const char *prefix
) {
292 Device
*d
= DEVICE(u
);
293 _cleanup_free_
char *s
= NULL
;
297 (void) device_found_to_string_many(d
->found
, &s
);
300 "%sDevice State: %s\n"
303 prefix
, device_state_to_string(d
->state
),
304 prefix
, strna(d
->sysfs
),
307 if (!strv_isempty(d
->wants_property
)) {
310 STRV_FOREACH(i
, d
->wants_property
)
311 fprintf(f
, "%sudev SYSTEMD_WANTS: %s\n",
316 _pure_
static UnitActiveState
device_active_state(Unit
*u
) {
319 return state_translation_table
[DEVICE(u
)->state
];
322 _pure_
static const char *device_sub_state_to_string(Unit
*u
) {
325 return device_state_to_string(DEVICE(u
)->state
);
328 static int device_update_description(Unit
*u
, sd_device
*dev
, const char *path
) {
329 _cleanup_free_
char *j
= NULL
;
330 const char *model
, *label
, *desc
;
339 (sd_device_get_property_value(dev
, "ID_MODEL_FROM_DATABASE", &model
) >= 0 ||
340 sd_device_get_property_value(dev
, "ID_MODEL", &model
) >= 0)) {
343 /* Try to concatenate the device model string with a label, if there is one */
344 if (sd_device_get_property_value(dev
, "ID_FS_LABEL", &label
) >= 0 ||
345 sd_device_get_property_value(dev
, "ID_PART_ENTRY_NAME", &label
) >= 0 ||
346 sd_device_get_property_value(dev
, "ID_PART_ENTRY_NUMBER", &label
) >= 0) {
348 desc
= j
= strjoin(model
, " ", label
);
354 r
= unit_set_description(u
, desc
);
356 return log_unit_error_errno(u
, r
, "Failed to set device description: %m");
361 static int device_add_udev_wants(Unit
*u
, sd_device
*dev
) {
362 _cleanup_strv_free_
char **added
= NULL
;
363 const char *wants
, *property
;
364 Device
*d
= DEVICE(u
);
370 property
= MANAGER_IS_USER(u
->manager
) ? "SYSTEMD_USER_WANTS" : "SYSTEMD_WANTS";
372 r
= sd_device_get_property_value(dev
, property
, &wants
);
377 _cleanup_free_
char *word
= NULL
, *k
= NULL
;
379 r
= extract_first_word(&wants
, &word
, NULL
, EXTRACT_UNQUOTE
);
385 return log_unit_error_errno(u
, r
, "Failed to parse property %s with value %s: %m", property
, wants
);
387 if (unit_name_is_valid(word
, UNIT_NAME_TEMPLATE
) && d
->sysfs
) {
388 _cleanup_free_
char *escaped
= NULL
;
390 /* If the unit name is specified as template, then automatically fill in the sysfs path of the
391 * device as instance name, properly escaped. */
393 r
= unit_name_path_escape(d
->sysfs
, &escaped
);
395 return log_unit_error_errno(u
, r
, "Failed to escape %s: %m", d
->sysfs
);
397 r
= unit_name_replace_instance(word
, escaped
, &k
);
399 return log_unit_error_errno(u
, r
, "Failed to build %s instance of template %s: %m", escaped
, word
);
401 /* If this is not a template, then let's mangle it so, that it becomes a valid unit name. */
403 r
= unit_name_mangle(word
, UNIT_NAME_MANGLE_WARN
, &k
);
405 return log_unit_error_errno(u
, r
, "Failed to mangle unit name \"%s\": %m", word
);
408 r
= unit_add_dependency_by_name(u
, UNIT_WANTS
, k
, true, UNIT_DEPENDENCY_UDEV
);
410 return log_unit_error_errno(u
, r
, "Failed to add Wants= dependency: %m");
412 r
= strv_push(&added
, k
);
419 if (d
->state
!= DEVICE_DEAD
) {
422 /* So here's a special hack, to compensate for the fact that the udev database's reload cycles are not
423 * synchronized with our own reload cycles: when we detect that the SYSTEMD_WANTS property of a device
424 * changes while the device unit is already up, let's manually trigger any new units listed in it not
425 * seen before. This typically happens during the boot-time switch root transition, as udev devices
426 * will generally already be up in the initrd, but SYSTEMD_WANTS properties get then added through udev
427 * rules only available on the host system, and thus only when the initial udev coldplug trigger runs.
429 * We do this only if the device has been up already when we parse this, as otherwise the usual
430 * dependency logic that is run from the dead → plugged transition will trigger these deps. */
432 STRV_FOREACH(i
, added
) {
433 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
435 if (strv_contains(d
->wants_property
, *i
)) /* Was this unit already listed before? */
438 r
= manager_add_job_by_name(u
->manager
, JOB_START
, *i
, JOB_FAIL
, NULL
, &error
, NULL
);
440 log_unit_warning_errno(u
, r
, "Failed to enqueue SYSTEMD_WANTS= job, ignoring: %s", bus_error_message(&error
, r
));
444 strv_free(d
->wants_property
);
445 d
->wants_property
= TAKE_PTR(added
);
450 static bool device_is_bound_by_mounts(Device
*d
, sd_device
*dev
) {
451 const char *bound_by
;
457 if (sd_device_get_property_value(dev
, "SYSTEMD_MOUNT_DEVICE_BOUND", &bound_by
) >= 0) {
458 r
= parse_boolean(bound_by
);
460 log_device_warning_errno(dev
, r
, "Failed to parse SYSTEMD_MOUNT_DEVICE_BOUND='%s' udev property, ignoring: %m", bound_by
);
462 d
->bind_mounts
= r
> 0;
464 d
->bind_mounts
= false;
466 return d
->bind_mounts
;
469 static void device_upgrade_mount_deps(Unit
*u
) {
474 /* Let's upgrade Requires= to BindsTo= on us. (Used when SYSTEMD_MOUNT_DEVICE_BOUND is set) */
476 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_REQUIRED_BY
]) {
477 if (other
->type
!= UNIT_MOUNT
)
480 r
= unit_add_dependency(other
, UNIT_BINDS_TO
, u
, true, UNIT_DEPENDENCY_UDEV
);
482 log_unit_warning_errno(u
, r
, "Failed to add BindsTo= dependency between device and mount unit, ignoring: %m");
486 static int device_setup_unit(Manager
*m
, sd_device
*dev
, const char *path
, bool main
) {
487 _cleanup_free_
char *e
= NULL
;
488 const char *sysfs
= NULL
;
497 r
= sd_device_get_syspath(dev
, &sysfs
);
499 log_device_debug_errno(dev
, r
, "Couldn't get syspath from device, ignoring: %m");
504 r
= unit_name_from_path(path
, ".device", &e
);
506 return log_device_error_errno(dev
, r
, "Failed to generate unit name from device path: %m");
508 u
= manager_get_unit(m
, e
);
510 /* The device unit can still be present even if the device was unplugged: a mount unit can reference it
511 * hence preventing the GC to have garbaged it. That's desired since the device unit may have a
512 * dependency on the mount unit which was added during the loading of the later. When the device is
513 * plugged the sysfs might not be initialized yet, as we serialize the device's state but do not
514 * serialize the sysfs path across reloads/reexecs. Hence, when coming back from a reload/restart we
515 * might have the state valid, but not the sysfs path. Hence, let's filter out conflicting devices, but
516 * let's accept devices in any state with no sysfs path set. */
518 if (DEVICE(u
)->state
== DEVICE_PLUGGED
&&
521 !path_equal(DEVICE(u
)->sysfs
, sysfs
)) {
522 log_unit_debug(u
, "Device %s appeared twice with different sysfs paths %s and %s, ignoring the latter.",
523 e
, DEVICE(u
)->sysfs
, sysfs
);
529 /* Let's remove all dependencies generated due to udev properties. We'll re-add whatever is configured
531 unit_remove_dependencies(u
, UNIT_DEPENDENCY_UDEV
);
535 r
= unit_new_for_name(m
, sizeof(Device
), e
, &u
);
537 log_device_error_errno(dev
, r
, "Failed to allocate device unit %s: %m", e
);
541 unit_add_to_load_queue(u
);
544 /* If this was created via some dependency and has not actually been seen yet ->sysfs will not be
545 * initialized. Hence initialize it if necessary. */
547 r
= device_set_sysfs(DEVICE(u
), sysfs
);
549 log_unit_error_errno(u
, r
, "Failed to set sysfs path %s: %m", sysfs
);
553 /* The additional systemd udev properties we only interpret for the main object */
555 (void) device_add_udev_wants(u
, dev
);
558 (void) device_update_description(u
, dev
, path
);
560 /* So the user wants the mount units to be bound to the device but a mount unit might has been seen by systemd
561 * before the device appears on its radar. In this case the device unit is partially initialized and includes
562 * the deps on the mount unit but at that time the "bind mounts" flag wasn't not present. Fix this up now. */
563 if (dev
&& device_is_bound_by_mounts(DEVICE(u
), dev
))
564 device_upgrade_mount_deps(u
);
575 static int device_process_new(Manager
*m
, sd_device
*dev
) {
576 const char *sysfs
, *dn
, *alias
;
582 if (sd_device_get_syspath(dev
, &sysfs
) < 0)
585 /* Add the main unit named after the sysfs path */
586 r
= device_setup_unit(m
, dev
, sysfs
, true);
590 /* Add an additional unit for the device node */
591 if (sd_device_get_devname(dev
, &dn
) >= 0)
592 (void) device_setup_unit(m
, dev
, dn
, false);
594 /* Add additional units for all symlinks */
595 if (sd_device_get_devnum(dev
, &devnum
) >= 0) {
598 FOREACH_DEVICE_DEVLINK(dev
, p
) {
601 if (PATH_STARTSWITH_SET(p
, "/dev/block/", "/dev/char/"))
604 /* Verify that the symlink in the FS actually belongs
605 * to this device. This is useful to deal with
606 * conflicting devices, e.g. when two disks want the
607 * same /dev/disk/by-label/xxx link because they have
608 * the same label. We want to make sure that the same
609 * device that won the symlink wins in systemd, so we
610 * check the device node major/minor */
611 if (stat(p
, &st
) >= 0 &&
612 ((!S_ISBLK(st
.st_mode
) && !S_ISCHR(st
.st_mode
)) ||
613 st
.st_rdev
!= devnum
))
616 (void) device_setup_unit(m
, dev
, p
, false);
620 /* Add additional units for all explicitly configured aliases */
621 if (sd_device_get_property_value(dev
, "SYSTEMD_ALIAS", &alias
) < 0)
625 _cleanup_free_
char *word
= NULL
;
627 r
= extract_first_word(&alias
, &word
, NULL
, EXTRACT_UNQUOTE
);
633 return log_device_warning_errno(dev
, r
, "Failed to parse SYSTEMD_ALIAS property: %m");
635 if (!path_is_absolute(word
))
636 log_device_warning(dev
, "SYSTEMD_ALIAS is not an absolute path, ignoring: %s", word
);
637 else if (!path_is_normalized(word
))
638 log_device_warning(dev
, "SYSTEMD_ALIAS is not a normalized path, ignoring: %s", word
);
640 (void) device_setup_unit(m
, dev
, word
, false);
646 static void device_found_changed(Device
*d
, DeviceFound previous
, DeviceFound now
) {
649 /* Didn't exist before, but does now? if so, generate a new invocation ID for it */
650 if (previous
== DEVICE_NOT_FOUND
&& now
!= DEVICE_NOT_FOUND
)
651 (void) unit_acquire_invocation_id(UNIT(d
));
653 if (FLAGS_SET(now
, DEVICE_FOUND_UDEV
))
654 /* When the device is known to udev we consider it plugged. */
655 device_set_state(d
, DEVICE_PLUGGED
);
656 else if (now
!= DEVICE_NOT_FOUND
&& !FLAGS_SET(previous
, DEVICE_FOUND_UDEV
))
657 /* If the device has not been seen by udev yet, but is now referenced by the kernel, then we assume the
658 * kernel knows it now, and udev might soon too. */
659 device_set_state(d
, DEVICE_TENTATIVE
);
661 /* If nobody sees the device, or if the device was previously seen by udev and now is only referenced
662 * from the kernel, then we consider the device is gone, the kernel just hasn't noticed it yet. */
663 device_set_state(d
, DEVICE_DEAD
);
666 static void device_update_found_one(Device
*d
, DeviceFound found
, DeviceFound mask
) {
671 m
= UNIT(d
)->manager
;
673 if (MANAGER_IS_RUNNING(m
) && (m
->honor_device_enumeration
|| MANAGER_IS_USER(m
))) {
674 DeviceFound n
, previous
;
676 /* When we are already running, then apply the new mask right-away, and trigger state changes
679 n
= (d
->found
& ~mask
) | (found
& mask
);
686 device_found_changed(d
, previous
, n
);
688 /* We aren't running yet, let's apply the new mask to the shadow variable instead, which we'll apply as
689 * soon as we catch-up with the state. */
690 d
->enumerated_found
= (d
->enumerated_found
& ~mask
) | (found
& mask
);
693 static void device_update_found_by_sysfs(Manager
*m
, const char *sysfs
, DeviceFound found
, DeviceFound mask
) {
702 l
= hashmap_get(m
->devices_by_sysfs
, sysfs
);
703 LIST_FOREACH_SAFE(same_sysfs
, d
, n
, l
)
704 device_update_found_one(d
, found
, mask
);
707 static int device_update_found_by_name(Manager
*m
, const char *path
, DeviceFound found
, DeviceFound mask
) {
708 _cleanup_free_
char *e
= NULL
;
718 r
= unit_name_from_path(path
, ".device", &e
);
720 return log_error_errno(r
, "Failed to generate unit name from device path: %m");
722 u
= manager_get_unit(m
, e
);
726 device_update_found_one(DEVICE(u
), found
, mask
);
730 static bool device_is_ready(sd_device
*dev
) {
735 if (device_is_renaming(dev
) > 0)
738 /* Is it really tagged as 'systemd' right now? */
739 if (sd_device_has_current_tag(dev
, "systemd") <= 0)
742 if (sd_device_get_property_value(dev
, "SYSTEMD_READY", &ready
) < 0)
745 return parse_boolean(ready
) != 0;
748 static Unit
*device_following(Unit
*u
) {
749 Device
*d
= DEVICE(u
);
750 Device
*other
, *first
= NULL
;
754 if (startswith(u
->id
, "sys-"))
757 /* Make everybody follow the unit that's named after the sysfs path */
758 LIST_FOREACH_AFTER(same_sysfs
, other
, d
)
759 if (startswith(UNIT(other
)->id
, "sys-"))
762 LIST_FOREACH_BEFORE(same_sysfs
, other
, d
) {
763 if (startswith(UNIT(other
)->id
, "sys-"))
772 static int device_following_set(Unit
*u
, Set
**_set
) {
773 Device
*d
= DEVICE(u
), *other
;
774 _cleanup_set_free_ Set
*set
= NULL
;
780 if (LIST_JUST_US(same_sysfs
, d
)) {
789 LIST_FOREACH_AFTER(same_sysfs
, other
, d
) {
790 r
= set_put(set
, other
);
795 LIST_FOREACH_BEFORE(same_sysfs
, other
, d
) {
796 r
= set_put(set
, other
);
801 *_set
= TAKE_PTR(set
);
805 static void device_shutdown(Manager
*m
) {
808 m
->device_monitor
= sd_device_monitor_unref(m
->device_monitor
);
809 m
->devices_by_sysfs
= hashmap_free(m
->devices_by_sysfs
);
812 static void device_enumerate(Manager
*m
) {
813 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
819 if (!m
->device_monitor
) {
820 r
= sd_device_monitor_new(&m
->device_monitor
);
822 log_error_errno(r
, "Failed to allocate device monitor: %m");
826 /* This will fail if we are unprivileged, but that
827 * should not matter much, as user instances won't run
829 (void) sd_device_monitor_set_receive_buffer_size(m
->device_monitor
, 128*1024*1024);
831 r
= sd_device_monitor_filter_add_match_tag(m
->device_monitor
, "systemd");
833 log_error_errno(r
, "Failed to add udev tag match: %m");
837 r
= sd_device_monitor_attach_event(m
->device_monitor
, m
->event
);
839 log_error_errno(r
, "Failed to attach event to device monitor: %m");
843 r
= sd_device_monitor_start(m
->device_monitor
, device_dispatch_io
, m
);
845 log_error_errno(r
, "Failed to start device monitor: %m");
850 r
= sd_device_enumerator_new(&e
);
852 log_error_errno(r
, "Failed to allocate device enumerator: %m");
856 r
= sd_device_enumerator_add_match_tag(e
, "systemd");
858 log_error_errno(r
, "Failed to set tag for device enumeration: %m");
862 FOREACH_DEVICE(e
, dev
) {
865 if (!device_is_ready(dev
))
868 (void) device_process_new(m
, dev
);
870 if (sd_device_get_syspath(dev
, &sysfs
) < 0)
873 device_update_found_by_sysfs(m
, sysfs
, DEVICE_FOUND_UDEV
, DEVICE_FOUND_UDEV
);
882 static void device_propagate_reload_by_sysfs(Manager
*m
, const char *sysfs
) {
889 l
= hashmap_get(m
->devices_by_sysfs
, sysfs
);
890 LIST_FOREACH_SAFE(same_sysfs
, d
, n
, l
) {
891 if (d
->state
== DEVICE_DEAD
)
894 r
= manager_propagate_reload(m
, UNIT(d
), JOB_REPLACE
, NULL
);
896 log_warning_errno(r
, "Failed to propagate reload, ignoring: %m");
900 static int device_dispatch_io(sd_device_monitor
*monitor
, sd_device
*dev
, void *userdata
) {
901 Manager
*m
= userdata
;
909 r
= sd_device_get_syspath(dev
, &sysfs
);
911 log_device_error_errno(dev
, r
, "Failed to get device sys path: %m");
915 r
= device_get_action(dev
, &action
);
917 log_device_error_errno(dev
, r
, "Failed to get udev action: %m");
921 if (!IN_SET(action
, DEVICE_ACTION_ADD
, DEVICE_ACTION_REMOVE
, DEVICE_ACTION_MOVE
))
922 device_propagate_reload_by_sysfs(m
, sysfs
);
924 /* A change event can signal that a device is becoming ready, in particular if the device is using
925 * the SYSTEMD_READY logic in udev so we need to reach the else block of the following if, even for
927 if (action
== DEVICE_ACTION_REMOVE
) {
928 r
= swap_process_device_remove(m
, dev
);
930 log_device_warning_errno(dev
, r
, "Failed to process swap device remove event, ignoring: %m");
932 /* If we get notified that a device was removed by udev, then it's completely gone, hence
933 * unset all found bits */
934 device_update_found_by_sysfs(m
, sysfs
, 0, DEVICE_FOUND_UDEV
|DEVICE_FOUND_MOUNT
|DEVICE_FOUND_SWAP
);
936 } else if (device_is_ready(dev
)) {
938 (void) device_process_new(m
, dev
);
940 r
= swap_process_device_new(m
, dev
);
942 log_device_warning_errno(dev
, r
, "Failed to process swap device new event, ignoring: %m");
944 manager_dispatch_load_queue(m
);
946 /* The device is found now, set the udev found bit */
947 device_update_found_by_sysfs(m
, sysfs
, DEVICE_FOUND_UDEV
, DEVICE_FOUND_UDEV
);
950 /* The device is nominally around, but not ready for us. Hence unset the udev bit, but leave
951 * the rest around. */
952 device_update_found_by_sysfs(m
, sysfs
, 0, DEVICE_FOUND_UDEV
);
957 static bool device_supported(void) {
958 static int read_only
= -1;
960 /* If /sys is read-only we don't support device units, and any
961 * attempts to start one should fail immediately. */
964 read_only
= path_is_read_only_fs("/sys");
966 return read_only
<= 0;
969 static int validate_node(Manager
*m
, const char *node
, sd_device
**ret
) {
977 /* Validates a device node that showed up in /proc/swaps or /proc/self/mountinfo if it makes sense for us to
978 * track. Note that this validator is fine within missing device nodes, but not with badly set up ones! */
980 if (!path_startswith(node
, "/dev")) {
985 if (stat(node
, &st
) < 0) {
987 return log_error_errno(errno
, "Failed to stat() device node file %s: %m", node
);
990 return 1; /* good! (though missing) */
993 _cleanup_(sd_device_unrefp
) sd_device
*dev
= NULL
;
995 r
= device_new_from_stat_rdev(&dev
, &st
);
998 return 1; /* good! (though missing) */
999 } else if (r
== -ENOTTY
) {
1001 return 0; /* bad! (not a device node but some other kind of file system node) */
1003 return log_error_errno(r
, "Failed to get udev device from devnum %u:%u: %m", major(st
.st_rdev
), minor(st
.st_rdev
));
1005 *ret
= TAKE_PTR(dev
);
1006 return 1; /* good! */
1010 void device_found_node(Manager
*m
, const char *node
, DeviceFound found
, DeviceFound mask
) {
1016 if (!device_supported())
1022 /* This is called whenever we find a device referenced in /proc/swaps or /proc/self/mounts. Such a device might
1023 * be mounted/enabled at a time where udev has not finished probing it yet, and we thus haven't learned about
1024 * it yet. In this case we will set the device unit to "tentative" state.
1026 * This takes a pair of DeviceFound flags parameters. The 'mask' parameter is a bit mask that indicates which
1027 * bits of 'found' to copy into the per-device DeviceFound flags field. Thus, this function may be used to set
1028 * and unset individual bits in a single call, while merging partially with previous state. */
1030 if ((found
& mask
) != 0) {
1031 _cleanup_(sd_device_unrefp
) sd_device
*dev
= NULL
;
1033 /* If the device is known in the kernel and newly appeared, then we'll create a device unit for it,
1034 * under the name referenced in /proc/swaps or /proc/self/mountinfo. But first, let's validate if
1035 * everything is alright with the device node. */
1037 r
= validate_node(m
, node
, &dev
);
1039 return; /* Don't create a device unit for this if the device node is borked. */
1041 (void) device_setup_unit(m
, dev
, node
, false);
1044 /* Update the device unit's state, should it exist */
1045 (void) device_update_found_by_name(m
, node
, found
, mask
);
1048 bool device_shall_be_bound_by(Unit
*device
, Unit
*u
) {
1052 if (u
->type
!= UNIT_MOUNT
)
1055 return DEVICE(device
)->bind_mounts
;
1058 const UnitVTable device_vtable
= {
1059 .object_size
= sizeof(Device
),
1067 .init
= device_init
,
1068 .done
= device_done
,
1069 .load
= device_load
,
1071 .coldplug
= device_coldplug
,
1072 .catchup
= device_catchup
,
1074 .serialize
= device_serialize
,
1075 .deserialize_item
= device_deserialize_item
,
1077 .dump
= device_dump
,
1079 .active_state
= device_active_state
,
1080 .sub_state_to_string
= device_sub_state_to_string
,
1082 .following
= device_following
,
1083 .following_set
= device_following_set
,
1085 .enumerate
= device_enumerate
,
1086 .shutdown
= device_shutdown
,
1087 .supported
= device_supported
,
1089 .status_message_formats
= {
1090 .starting_stopping
= {
1091 [0] = "Expecting device %s...",
1093 .finished_start_job
= {
1094 [JOB_DONE
] = "Found device %s.",
1095 [JOB_TIMEOUT
] = "Timed out waiting for device %s.",