1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
23 #include <sys/epoll.h>
27 #include "dbus-device.h"
30 #include "parse-util.h"
31 #include "path-util.h"
32 #include "string-util.h"
34 #include "udev-util.h"
35 #include "unit-name.h"
38 static const UnitActiveState state_translation_table
[_DEVICE_STATE_MAX
] = {
39 [DEVICE_DEAD
] = UNIT_INACTIVE
,
40 [DEVICE_TENTATIVE
] = UNIT_ACTIVATING
,
41 [DEVICE_PLUGGED
] = UNIT_ACTIVE
,
44 static int device_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
);
46 static void device_unset_sysfs(Device
*d
) {
55 /* Remove this unit from the chain of devices which share the
57 devices
= UNIT(d
)->manager
->devices_by_sysfs
;
58 first
= hashmap_get(devices
, d
->sysfs
);
59 LIST_REMOVE(same_sysfs
, first
, d
);
62 hashmap_remove_and_replace(devices
, d
->sysfs
, first
->sysfs
, first
);
64 hashmap_remove(devices
, d
->sysfs
);
66 d
->sysfs
= mfree(d
->sysfs
);
69 static int device_set_sysfs(Device
*d
, const char *sysfs
) {
76 if (streq_ptr(d
->sysfs
, sysfs
))
79 r
= hashmap_ensure_allocated(&UNIT(d
)->manager
->devices_by_sysfs
, &string_hash_ops
);
87 device_unset_sysfs(d
);
89 first
= hashmap_get(UNIT(d
)->manager
->devices_by_sysfs
, sysfs
);
90 LIST_PREPEND(same_sysfs
, first
, d
);
92 r
= hashmap_replace(UNIT(d
)->manager
->devices_by_sysfs
, copy
, first
);
94 LIST_REMOVE(same_sysfs
, first
, d
);
104 static void device_init(Unit
*u
) {
105 Device
*d
= DEVICE(u
);
108 assert(UNIT(d
)->load_state
== UNIT_STUB
);
110 /* In contrast to all other unit types we timeout jobs waiting
111 * for devices by default. This is because they otherwise wait
112 * indefinitely for plugged in devices, something which cannot
113 * happen for the other units since their operations time out
115 u
->job_timeout
= u
->manager
->default_timeout_start_usec
;
117 u
->ignore_on_isolate
= true;
118 u
->ignore_on_snapshot
= true;
121 static void device_done(Unit
*u
) {
122 Device
*d
= DEVICE(u
);
126 device_unset_sysfs(d
);
129 static void device_set_state(Device
*d
, DeviceState state
) {
130 DeviceState old_state
;
133 old_state
= d
->state
;
136 if (state
!= old_state
)
137 log_unit_debug(UNIT(d
), "Changed %s -> %s", device_state_to_string(old_state
), device_state_to_string(state
));
139 unit_notify(UNIT(d
), state_translation_table
[old_state
], state_translation_table
[state
], true);
142 static int device_coldplug(Unit
*u
) {
143 Device
*d
= DEVICE(u
);
146 assert(d
->state
== DEVICE_DEAD
);
148 if (d
->found
& DEVICE_FOUND_UDEV
)
149 /* If udev says the device is around, it's around */
150 device_set_state(d
, DEVICE_PLUGGED
);
151 else if (d
->found
!= DEVICE_NOT_FOUND
&& d
->deserialized_state
!= DEVICE_PLUGGED
)
152 /* If a device is found in /proc/self/mountinfo or
153 * /proc/swaps, and was not yet announced via udev,
154 * it's "tentatively" around. */
155 device_set_state(d
, DEVICE_TENTATIVE
);
160 static int device_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
161 Device
*d
= DEVICE(u
);
167 unit_serialize_item(u
, f
, "state", device_state_to_string(d
->state
));
172 static int device_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
173 Device
*d
= DEVICE(u
);
180 if (streq(key
, "state")) {
183 state
= device_state_from_string(value
);
185 log_unit_debug(u
, "Failed to parse state value: %s", value
);
187 d
->deserialized_state
= state
;
189 log_unit_debug(u
, "Unknown serialization key: %s", key
);
194 static void device_dump(Unit
*u
, FILE *f
, const char *prefix
) {
195 Device
*d
= DEVICE(u
);
200 "%sDevice State: %s\n"
201 "%sSysfs Path: %s\n",
202 prefix
, device_state_to_string(d
->state
),
203 prefix
, strna(d
->sysfs
));
206 _pure_
static UnitActiveState
device_active_state(Unit
*u
) {
209 return state_translation_table
[DEVICE(u
)->state
];
212 _pure_
static const char *device_sub_state_to_string(Unit
*u
) {
215 return device_state_to_string(DEVICE(u
)->state
);
218 static int device_update_description(Unit
*u
, struct udev_device
*dev
, const char *path
) {
226 model
= udev_device_get_property_value(dev
, "ID_MODEL_FROM_DATABASE");
228 model
= udev_device_get_property_value(dev
, "ID_MODEL");
233 /* Try to concatenate the device model string with a label, if there is one */
234 label
= udev_device_get_property_value(dev
, "ID_FS_LABEL");
236 label
= udev_device_get_property_value(dev
, "ID_PART_ENTRY_NAME");
238 label
= udev_device_get_property_value(dev
, "ID_PART_ENTRY_NUMBER");
241 _cleanup_free_
char *j
;
243 j
= strjoin(model
, " ", label
, NULL
);
245 r
= unit_set_description(u
, j
);
249 r
= unit_set_description(u
, model
);
251 r
= unit_set_description(u
, path
);
254 log_unit_error_errno(u
, r
, "Failed to set device description: %m");
259 static int device_add_udev_wants(Unit
*u
, struct udev_device
*dev
) {
261 const char *word
, *state
;
264 const char *property
;
269 property
= u
->manager
->running_as
== MANAGER_USER
? "MANAGER_USER_WANTS" : "SYSTEMD_WANTS";
270 wants
= udev_device_get_property_value(dev
, property
);
274 FOREACH_WORD_QUOTED(word
, l
, wants
, state
) {
275 _cleanup_free_
char *n
= NULL
;
281 r
= unit_name_mangle(e
, UNIT_NAME_NOGLOB
, &n
);
283 return log_unit_error_errno(u
, r
, "Failed to mangle unit name: %m");
285 r
= unit_add_dependency_by_name(u
, UNIT_WANTS
, n
, NULL
, true);
287 return log_unit_error_errno(u
, r
, "Failed to add wants dependency: %m");
290 log_unit_warning(u
, "Property %s on %s has trailing garbage, ignoring.", property
, strna(udev_device_get_syspath(dev
)));
295 static int device_setup_unit(Manager
*m
, struct udev_device
*dev
, const char *path
, bool main
) {
296 _cleanup_free_
char *e
= NULL
;
297 const char *sysfs
= NULL
;
306 sysfs
= udev_device_get_syspath(dev
);
311 r
= unit_name_from_path(path
, ".device", &e
);
313 return log_error_errno(r
, "Failed to generate unit name from device path: %m");
315 u
= manager_get_unit(m
, e
);
320 !path_equal(DEVICE(u
)->sysfs
, sysfs
)) {
321 log_unit_debug(u
, "Device %s appeared twice with different sysfs paths %s and %s", e
, DEVICE(u
)->sysfs
, sysfs
);
328 u
= unit_new(m
, sizeof(Device
));
332 r
= unit_add_name(u
, e
);
336 unit_add_to_load_queue(u
);
340 /* If this was created via some dependency and has not
341 * actually been seen yet ->sysfs will not be
342 * initialized. Hence initialize it if necessary. */
344 r
= device_set_sysfs(DEVICE(u
), sysfs
);
348 (void) device_update_description(u
, dev
, path
);
350 /* The additional systemd udev properties we only interpret
351 * for the main object */
353 (void) device_add_udev_wants(u
, dev
);
357 /* Note that this won't dispatch the load queue, the caller
358 * has to do that if needed and appropriate */
360 unit_add_to_dbus_queue(u
);
364 log_unit_warning_errno(u
, r
, "Failed to set up device unit: %m");
372 static int device_process_new(Manager
*m
, struct udev_device
*dev
) {
373 const char *sysfs
, *dn
, *alias
;
374 struct udev_list_entry
*item
= NULL
, *first
= NULL
;
379 sysfs
= udev_device_get_syspath(dev
);
383 /* Add the main unit named after the sysfs path */
384 r
= device_setup_unit(m
, dev
, sysfs
, true);
388 /* Add an additional unit for the device node */
389 dn
= udev_device_get_devnode(dev
);
391 (void) device_setup_unit(m
, dev
, dn
, false);
393 /* Add additional units for all symlinks */
394 first
= udev_device_get_devlinks_list_entry(dev
);
395 udev_list_entry_foreach(item
, first
) {
399 /* Don't bother with the /dev/block links */
400 p
= udev_list_entry_get_name(item
);
402 if (path_startswith(p
, "/dev/block/") ||
403 path_startswith(p
, "/dev/char/"))
406 /* Verify that the symlink in the FS actually belongs
407 * to this device. This is useful to deal with
408 * conflicting devices, e.g. when two disks want the
409 * same /dev/disk/by-label/xxx link because they have
410 * the same label. We want to make sure that the same
411 * device that won the symlink wins in systemd, so we
412 * check the device node major/minor */
413 if (stat(p
, &st
) >= 0)
414 if ((!S_ISBLK(st
.st_mode
) && !S_ISCHR(st
.st_mode
)) ||
415 st
.st_rdev
!= udev_device_get_devnum(dev
))
418 (void) device_setup_unit(m
, dev
, p
, false);
421 /* Add additional units for all explicitly configured
423 alias
= udev_device_get_property_value(dev
, "SYSTEMD_ALIAS");
425 const char *word
, *state
;
428 FOREACH_WORD_QUOTED(word
, l
, alias
, state
) {
434 if (path_is_absolute(e
))
435 (void) device_setup_unit(m
, dev
, e
, false);
437 log_warning("SYSTEMD_ALIAS for %s is not an absolute path, ignoring: %s", sysfs
, e
);
440 log_warning("SYSTEMD_ALIAS for %s has trailing garbage, ignoring.", sysfs
);
446 static void device_update_found_one(Device
*d
, bool add
, DeviceFound found
, bool now
) {
447 DeviceFound n
, previous
;
451 n
= add
? (d
->found
| found
) : (d
->found
& ~found
);
461 if (d
->found
& DEVICE_FOUND_UDEV
)
462 /* When the device is known to udev we consider it
464 device_set_state(d
, DEVICE_PLUGGED
);
465 else if (d
->found
!= DEVICE_NOT_FOUND
&& (previous
& DEVICE_FOUND_UDEV
) == 0)
466 /* If the device has not been seen by udev yet, but is
467 * now referenced by the kernel, then we assume the
468 * kernel knows it now, and udev might soon too. */
469 device_set_state(d
, DEVICE_TENTATIVE
);
471 /* If nobody sees the device, or if the device was
472 * previously seen by udev and now is only referenced
473 * from the kernel, then we consider the device is
474 * gone, the kernel just hasn't noticed it yet. */
475 device_set_state(d
, DEVICE_DEAD
);
478 static int device_update_found_by_sysfs(Manager
*m
, const char *sysfs
, bool add
, DeviceFound found
, bool now
) {
484 if (found
== DEVICE_NOT_FOUND
)
487 l
= hashmap_get(m
->devices_by_sysfs
, sysfs
);
488 LIST_FOREACH(same_sysfs
, d
, l
)
489 device_update_found_one(d
, add
, found
, now
);
494 static int device_update_found_by_name(Manager
*m
, const char *path
, bool add
, DeviceFound found
, bool now
) {
495 _cleanup_free_
char *e
= NULL
;
502 if (found
== DEVICE_NOT_FOUND
)
505 r
= unit_name_from_path(path
, ".device", &e
);
507 return log_error_errno(r
, "Failed to generate unit name from device path: %m");
509 u
= manager_get_unit(m
, e
);
513 device_update_found_one(DEVICE(u
), add
, found
, now
);
517 static bool device_is_ready(struct udev_device
*dev
) {
522 ready
= udev_device_get_property_value(dev
, "SYSTEMD_READY");
526 return parse_boolean(ready
) != 0;
529 static Unit
*device_following(Unit
*u
) {
530 Device
*d
= DEVICE(u
);
531 Device
*other
, *first
= NULL
;
535 if (startswith(u
->id
, "sys-"))
538 /* Make everybody follow the unit that's named after the sysfs path */
539 for (other
= d
->same_sysfs_next
; other
; other
= other
->same_sysfs_next
)
540 if (startswith(UNIT(other
)->id
, "sys-"))
543 for (other
= d
->same_sysfs_prev
; other
; other
= other
->same_sysfs_prev
) {
544 if (startswith(UNIT(other
)->id
, "sys-"))
553 static int device_following_set(Unit
*u
, Set
**_set
) {
554 Device
*d
= DEVICE(u
), *other
;
561 if (LIST_JUST_US(same_sysfs
, d
)) {
570 LIST_FOREACH_AFTER(same_sysfs
, other
, d
) {
571 r
= set_put(set
, other
);
576 LIST_FOREACH_BEFORE(same_sysfs
, other
, d
) {
577 r
= set_put(set
, other
);
590 static void device_shutdown(Manager
*m
) {
593 m
->udev_event_source
= sd_event_source_unref(m
->udev_event_source
);
595 if (m
->udev_monitor
) {
596 udev_monitor_unref(m
->udev_monitor
);
597 m
->udev_monitor
= NULL
;
600 m
->devices_by_sysfs
= hashmap_free(m
->devices_by_sysfs
);
603 static int device_enumerate(Manager
*m
) {
604 _cleanup_udev_enumerate_unref_
struct udev_enumerate
*e
= NULL
;
605 struct udev_list_entry
*item
= NULL
, *first
= NULL
;
610 if (!m
->udev_monitor
) {
611 m
->udev_monitor
= udev_monitor_new_from_netlink(m
->udev
, "udev");
612 if (!m
->udev_monitor
) {
617 /* This will fail if we are unprivileged, but that
618 * should not matter much, as user instances won't run
620 (void) udev_monitor_set_receive_buffer_size(m
->udev_monitor
, 128*1024*1024);
622 r
= udev_monitor_filter_add_match_tag(m
->udev_monitor
, "systemd");
626 r
= udev_monitor_enable_receiving(m
->udev_monitor
);
630 r
= sd_event_add_io(m
->event
, &m
->udev_event_source
, udev_monitor_get_fd(m
->udev_monitor
), EPOLLIN
, device_dispatch_io
, m
);
634 (void) sd_event_source_set_description(m
->udev_event_source
, "device");
637 e
= udev_enumerate_new(m
->udev
);
643 r
= udev_enumerate_add_match_tag(e
, "systemd");
647 r
= udev_enumerate_add_match_is_initialized(e
);
651 r
= udev_enumerate_scan_devices(e
);
655 first
= udev_enumerate_get_list_entry(e
);
656 udev_list_entry_foreach(item
, first
) {
657 _cleanup_udev_device_unref_
struct udev_device
*dev
= NULL
;
660 sysfs
= udev_list_entry_get_name(item
);
662 dev
= udev_device_new_from_syspath(m
->udev
, sysfs
);
668 if (!device_is_ready(dev
))
671 (void) device_process_new(m
, dev
);
673 device_update_found_by_sysfs(m
, sysfs
, true, DEVICE_FOUND_UDEV
, false);
679 log_error_errno(r
, "Failed to enumerate devices: %m");
685 static int device_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
686 _cleanup_udev_device_unref_
struct udev_device
*dev
= NULL
;
687 Manager
*m
= userdata
;
688 const char *action
, *sysfs
;
693 if (revents
!= EPOLLIN
) {
694 static RATELIMIT_DEFINE(limit
, 10*USEC_PER_SEC
, 5);
696 if (!ratelimit_test(&limit
))
697 log_error_errno(errno
, "Failed to get udev event: %m");
698 if (!(revents
& EPOLLIN
))
703 * libudev might filter-out devices which pass the bloom
704 * filter, so getting NULL here is not necessarily an error.
706 dev
= udev_monitor_receive_device(m
->udev_monitor
);
710 sysfs
= udev_device_get_syspath(dev
);
712 log_error("Failed to get udev sys path.");
716 action
= udev_device_get_action(dev
);
718 log_error("Failed to get udev action string.");
722 if (streq(action
, "remove")) {
723 r
= swap_process_device_remove(m
, dev
);
725 log_error_errno(r
, "Failed to process swap device remove event: %m");
727 /* If we get notified that a device was removed by
728 * udev, then it's completely gone, hence unset all
730 device_update_found_by_sysfs(m
, sysfs
, false, DEVICE_FOUND_UDEV
|DEVICE_FOUND_MOUNT
|DEVICE_FOUND_SWAP
, true);
732 } else if (device_is_ready(dev
)) {
734 (void) device_process_new(m
, dev
);
736 r
= swap_process_device_new(m
, dev
);
738 log_error_errno(r
, "Failed to process swap device new event: %m");
740 manager_dispatch_load_queue(m
);
742 /* The device is found now, set the udev found bit */
743 device_update_found_by_sysfs(m
, sysfs
, true, DEVICE_FOUND_UDEV
, true);
746 /* The device is nominally around, but not ready for
747 * us. Hence unset the udev bit, but leave the rest
750 device_update_found_by_sysfs(m
, sysfs
, false, DEVICE_FOUND_UDEV
, true);
756 static bool device_supported(void) {
757 static int read_only
= -1;
759 /* If /sys is read-only we don't support device units, and any
760 * attempts to start one should fail immediately. */
763 read_only
= path_is_read_only_fs("/sys");
765 return read_only
<= 0;
768 int device_found_node(Manager
*m
, const char *node
, bool add
, DeviceFound found
, bool now
) {
769 _cleanup_udev_device_unref_
struct udev_device
*dev
= NULL
;
775 if (!device_supported())
778 /* This is called whenever we find a device referenced in
779 * /proc/swaps or /proc/self/mounts. Such a device might be
780 * mounted/enabled at a time where udev has not finished
781 * probing it yet, and we thus haven't learned about it
782 * yet. In this case we will set the device unit to
783 * "tentative" state. */
786 if (!path_startswith(node
, "/dev"))
789 /* We make an extra check here, if the device node
790 * actually exists. If it's missing, then this is an
791 * indication that device was unplugged but is still
792 * referenced in /proc/swaps or
793 * /proc/self/mountinfo. Note that this check doesn't
794 * really cover all cases where a device might be gone
795 * away, since drives that can have a medium inserted
796 * will still have a device node even when the medium
799 if (stat(node
, &st
) >= 0) {
800 if (!S_ISBLK(st
.st_mode
) && !S_ISCHR(st
.st_mode
))
803 dev
= udev_device_new_from_devnum(m
->udev
, S_ISBLK(st
.st_mode
) ? 'b' : 'c', st
.st_rdev
);
804 if (!dev
&& errno
!= ENOENT
)
805 return log_error_errno(errno
, "Failed to get udev device from devnum %u:%u: %m", major(st
.st_rdev
), minor(st
.st_rdev
));
807 } else if (errno
!= ENOENT
)
808 return log_error_errno(errno
, "Failed to stat device node file %s: %m", node
);
810 /* If the device is known in the kernel and newly
811 * appeared, then we'll create a device unit for it,
812 * under the name referenced in /proc/swaps or
813 * /proc/self/mountinfo. */
815 (void) device_setup_unit(m
, dev
, node
, false);
818 /* Update the device unit's state, should it exist */
819 return device_update_found_by_name(m
, node
, add
, found
, now
);
822 const UnitVTable device_vtable
= {
823 .object_size
= sizeof(Device
),
829 .no_instances
= true,
833 .load
= unit_load_fragment_and_dropin_optional
,
835 .coldplug
= device_coldplug
,
837 .serialize
= device_serialize
,
838 .deserialize_item
= device_deserialize_item
,
842 .active_state
= device_active_state
,
843 .sub_state_to_string
= device_sub_state_to_string
,
845 .bus_vtable
= bus_device_vtable
,
847 .following
= device_following
,
848 .following_set
= device_following_set
,
850 .enumerate
= device_enumerate
,
851 .shutdown
= device_shutdown
,
852 .supported
= device_supported
,
854 .status_message_formats
= {
855 .starting_stopping
= {
856 [0] = "Expecting device %s...",
858 .finished_start_job
= {
859 [JOB_DONE
] = "Found device %s.",
860 [JOB_TIMEOUT
] = "Timed out waiting for device %s.",