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 "alloc-util.h"
28 #include "dbus-device.h"
31 #include "parse-util.h"
32 #include "path-util.h"
33 #include "stat-util.h"
34 #include "string-util.h"
36 #include "udev-util.h"
37 #include "unit-name.h"
40 static const UnitActiveState state_translation_table
[_DEVICE_STATE_MAX
] = {
41 [DEVICE_DEAD
] = UNIT_INACTIVE
,
42 [DEVICE_TENTATIVE
] = UNIT_ACTIVATING
,
43 [DEVICE_PLUGGED
] = UNIT_ACTIVE
,
46 static int device_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
);
48 static void device_unset_sysfs(Device
*d
) {
57 /* Remove this unit from the chain of devices which share the
59 devices
= UNIT(d
)->manager
->devices_by_sysfs
;
60 first
= hashmap_get(devices
, d
->sysfs
);
61 LIST_REMOVE(same_sysfs
, first
, d
);
64 hashmap_remove_and_replace(devices
, d
->sysfs
, first
->sysfs
, first
);
66 hashmap_remove(devices
, d
->sysfs
);
68 d
->sysfs
= mfree(d
->sysfs
);
71 static int device_set_sysfs(Device
*d
, const char *sysfs
) {
78 if (streq_ptr(d
->sysfs
, sysfs
))
81 r
= hashmap_ensure_allocated(&UNIT(d
)->manager
->devices_by_sysfs
, &string_hash_ops
);
89 device_unset_sysfs(d
);
91 first
= hashmap_get(UNIT(d
)->manager
->devices_by_sysfs
, sysfs
);
92 LIST_PREPEND(same_sysfs
, first
, d
);
94 r
= hashmap_replace(UNIT(d
)->manager
->devices_by_sysfs
, copy
, first
);
96 LIST_REMOVE(same_sysfs
, first
, d
);
106 static void device_init(Unit
*u
) {
107 Device
*d
= DEVICE(u
);
110 assert(UNIT(d
)->load_state
== UNIT_STUB
);
112 /* In contrast to all other unit types we timeout jobs waiting
113 * for devices by default. This is because they otherwise wait
114 * indefinitely for plugged in devices, something which cannot
115 * happen for the other units since their operations time out
117 u
->job_timeout
= u
->manager
->default_timeout_start_usec
;
119 u
->ignore_on_isolate
= true;
122 static void device_done(Unit
*u
) {
123 Device
*d
= DEVICE(u
);
127 device_unset_sysfs(d
);
130 static void device_set_state(Device
*d
, DeviceState state
) {
131 DeviceState old_state
;
134 old_state
= d
->state
;
137 if (state
!= old_state
)
138 log_unit_debug(UNIT(d
), "Changed %s -> %s", device_state_to_string(old_state
), device_state_to_string(state
));
140 unit_notify(UNIT(d
), state_translation_table
[old_state
], state_translation_table
[state
], true);
143 static int device_coldplug(Unit
*u
) {
144 Device
*d
= DEVICE(u
);
147 assert(d
->state
== DEVICE_DEAD
);
149 if (d
->found
& DEVICE_FOUND_UDEV
)
150 /* If udev says the device is around, it's around */
151 device_set_state(d
, DEVICE_PLUGGED
);
152 else if (d
->found
!= DEVICE_NOT_FOUND
&& d
->deserialized_state
!= DEVICE_PLUGGED
)
153 /* If a device is found in /proc/self/mountinfo or
154 * /proc/swaps, and was not yet announced via udev,
155 * it's "tentatively" around. */
156 device_set_state(d
, DEVICE_TENTATIVE
);
161 static int device_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
162 Device
*d
= DEVICE(u
);
168 unit_serialize_item(u
, f
, "state", device_state_to_string(d
->state
));
173 static int device_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
174 Device
*d
= DEVICE(u
);
181 if (streq(key
, "state")) {
184 state
= device_state_from_string(value
);
186 log_unit_debug(u
, "Failed to parse state value: %s", value
);
188 d
->deserialized_state
= state
;
190 log_unit_debug(u
, "Unknown serialization key: %s", key
);
195 static void device_dump(Unit
*u
, FILE *f
, const char *prefix
) {
196 Device
*d
= DEVICE(u
);
201 "%sDevice State: %s\n"
202 "%sSysfs Path: %s\n",
203 prefix
, device_state_to_string(d
->state
),
204 prefix
, strna(d
->sysfs
));
207 _pure_
static UnitActiveState
device_active_state(Unit
*u
) {
210 return state_translation_table
[DEVICE(u
)->state
];
213 _pure_
static const char *device_sub_state_to_string(Unit
*u
) {
216 return device_state_to_string(DEVICE(u
)->state
);
219 static int device_update_description(Unit
*u
, struct udev_device
*dev
, const char *path
) {
227 model
= udev_device_get_property_value(dev
, "ID_MODEL_FROM_DATABASE");
229 model
= udev_device_get_property_value(dev
, "ID_MODEL");
234 /* Try to concatenate the device model string with a label, if there is one */
235 label
= udev_device_get_property_value(dev
, "ID_FS_LABEL");
237 label
= udev_device_get_property_value(dev
, "ID_PART_ENTRY_NAME");
239 label
= udev_device_get_property_value(dev
, "ID_PART_ENTRY_NUMBER");
242 _cleanup_free_
char *j
;
244 j
= strjoin(model
, " ", label
, NULL
);
246 r
= unit_set_description(u
, j
);
250 r
= unit_set_description(u
, model
);
252 r
= unit_set_description(u
, path
);
255 log_unit_error_errno(u
, r
, "Failed to set device description: %m");
260 static int device_add_udev_wants(Unit
*u
, struct udev_device
*dev
) {
262 const char *word
, *state
;
265 const char *property
;
270 property
= u
->manager
->running_as
== MANAGER_USER
? "MANAGER_USER_WANTS" : "SYSTEMD_WANTS";
271 wants
= udev_device_get_property_value(dev
, property
);
275 FOREACH_WORD_QUOTED(word
, l
, wants
, state
) {
276 _cleanup_free_
char *n
= NULL
;
282 r
= unit_name_mangle(e
, UNIT_NAME_NOGLOB
, &n
);
284 return log_unit_error_errno(u
, r
, "Failed to mangle unit name: %m");
286 r
= unit_add_dependency_by_name(u
, UNIT_WANTS
, n
, NULL
, true);
288 return log_unit_error_errno(u
, r
, "Failed to add wants dependency: %m");
291 log_unit_warning(u
, "Property %s on %s has trailing garbage, ignoring.", property
, strna(udev_device_get_syspath(dev
)));
296 static int device_setup_unit(Manager
*m
, struct udev_device
*dev
, const char *path
, bool main
) {
297 _cleanup_free_
char *e
= NULL
;
298 const char *sysfs
= NULL
;
307 sysfs
= udev_device_get_syspath(dev
);
312 r
= unit_name_from_path(path
, ".device", &e
);
314 return log_error_errno(r
, "Failed to generate unit name from device path: %m");
316 u
= manager_get_unit(m
, e
);
321 !path_equal(DEVICE(u
)->sysfs
, sysfs
)) {
322 log_unit_debug(u
, "Device %s appeared twice with different sysfs paths %s and %s", e
, DEVICE(u
)->sysfs
, sysfs
);
329 u
= unit_new(m
, sizeof(Device
));
333 r
= unit_add_name(u
, e
);
337 unit_add_to_load_queue(u
);
341 /* If this was created via some dependency and has not
342 * actually been seen yet ->sysfs will not be
343 * initialized. Hence initialize it if necessary. */
345 r
= device_set_sysfs(DEVICE(u
), sysfs
);
349 (void) device_update_description(u
, dev
, path
);
351 /* The additional systemd udev properties we only interpret
352 * for the main object */
354 (void) device_add_udev_wants(u
, dev
);
358 /* Note that this won't dispatch the load queue, the caller
359 * has to do that if needed and appropriate */
361 unit_add_to_dbus_queue(u
);
365 log_unit_warning_errno(u
, r
, "Failed to set up device unit: %m");
373 static int device_process_new(Manager
*m
, struct udev_device
*dev
) {
374 const char *sysfs
, *dn
, *alias
;
375 struct udev_list_entry
*item
= NULL
, *first
= NULL
;
380 sysfs
= udev_device_get_syspath(dev
);
384 /* Add the main unit named after the sysfs path */
385 r
= device_setup_unit(m
, dev
, sysfs
, true);
389 /* Add an additional unit for the device node */
390 dn
= udev_device_get_devnode(dev
);
392 (void) device_setup_unit(m
, dev
, dn
, false);
394 /* Add additional units for all symlinks */
395 first
= udev_device_get_devlinks_list_entry(dev
);
396 udev_list_entry_foreach(item
, first
) {
400 /* Don't bother with the /dev/block links */
401 p
= udev_list_entry_get_name(item
);
403 if (path_startswith(p
, "/dev/block/") ||
404 path_startswith(p
, "/dev/char/"))
407 /* Verify that the symlink in the FS actually belongs
408 * to this device. This is useful to deal with
409 * conflicting devices, e.g. when two disks want the
410 * same /dev/disk/by-label/xxx link because they have
411 * the same label. We want to make sure that the same
412 * device that won the symlink wins in systemd, so we
413 * check the device node major/minor */
414 if (stat(p
, &st
) >= 0)
415 if ((!S_ISBLK(st
.st_mode
) && !S_ISCHR(st
.st_mode
)) ||
416 st
.st_rdev
!= udev_device_get_devnum(dev
))
419 (void) device_setup_unit(m
, dev
, p
, false);
422 /* Add additional units for all explicitly configured
424 alias
= udev_device_get_property_value(dev
, "SYSTEMD_ALIAS");
426 const char *word
, *state
;
429 FOREACH_WORD_QUOTED(word
, l
, alias
, state
) {
435 if (path_is_absolute(e
))
436 (void) device_setup_unit(m
, dev
, e
, false);
438 log_warning("SYSTEMD_ALIAS for %s is not an absolute path, ignoring: %s", sysfs
, e
);
441 log_warning("SYSTEMD_ALIAS for %s has trailing garbage, ignoring.", sysfs
);
447 static void device_update_found_one(Device
*d
, bool add
, DeviceFound found
, bool now
) {
448 DeviceFound n
, previous
;
452 n
= add
? (d
->found
| found
) : (d
->found
& ~found
);
462 if (d
->found
& DEVICE_FOUND_UDEV
)
463 /* When the device is known to udev we consider it
465 device_set_state(d
, DEVICE_PLUGGED
);
466 else if (d
->found
!= DEVICE_NOT_FOUND
&& (previous
& DEVICE_FOUND_UDEV
) == 0)
467 /* If the device has not been seen by udev yet, but is
468 * now referenced by the kernel, then we assume the
469 * kernel knows it now, and udev might soon too. */
470 device_set_state(d
, DEVICE_TENTATIVE
);
472 /* If nobody sees the device, or if the device was
473 * previously seen by udev and now is only referenced
474 * from the kernel, then we consider the device is
475 * gone, the kernel just hasn't noticed it yet. */
476 device_set_state(d
, DEVICE_DEAD
);
479 static int device_update_found_by_sysfs(Manager
*m
, const char *sysfs
, bool add
, DeviceFound found
, bool now
) {
485 if (found
== DEVICE_NOT_FOUND
)
488 l
= hashmap_get(m
->devices_by_sysfs
, sysfs
);
489 LIST_FOREACH(same_sysfs
, d
, l
)
490 device_update_found_one(d
, add
, found
, now
);
495 static int device_update_found_by_name(Manager
*m
, const char *path
, bool add
, DeviceFound found
, bool now
) {
496 _cleanup_free_
char *e
= NULL
;
503 if (found
== DEVICE_NOT_FOUND
)
506 r
= unit_name_from_path(path
, ".device", &e
);
508 return log_error_errno(r
, "Failed to generate unit name from device path: %m");
510 u
= manager_get_unit(m
, e
);
514 device_update_found_one(DEVICE(u
), add
, found
, now
);
518 static bool device_is_ready(struct udev_device
*dev
) {
523 ready
= udev_device_get_property_value(dev
, "SYSTEMD_READY");
527 return parse_boolean(ready
) != 0;
530 static Unit
*device_following(Unit
*u
) {
531 Device
*d
= DEVICE(u
);
532 Device
*other
, *first
= NULL
;
536 if (startswith(u
->id
, "sys-"))
539 /* Make everybody follow the unit that's named after the sysfs path */
540 for (other
= d
->same_sysfs_next
; other
; other
= other
->same_sysfs_next
)
541 if (startswith(UNIT(other
)->id
, "sys-"))
544 for (other
= d
->same_sysfs_prev
; other
; other
= other
->same_sysfs_prev
) {
545 if (startswith(UNIT(other
)->id
, "sys-"))
554 static int device_following_set(Unit
*u
, Set
**_set
) {
555 Device
*d
= DEVICE(u
), *other
;
562 if (LIST_JUST_US(same_sysfs
, d
)) {
571 LIST_FOREACH_AFTER(same_sysfs
, other
, d
) {
572 r
= set_put(set
, other
);
577 LIST_FOREACH_BEFORE(same_sysfs
, other
, d
) {
578 r
= set_put(set
, other
);
591 static void device_shutdown(Manager
*m
) {
594 m
->udev_event_source
= sd_event_source_unref(m
->udev_event_source
);
596 if (m
->udev_monitor
) {
597 udev_monitor_unref(m
->udev_monitor
);
598 m
->udev_monitor
= NULL
;
601 m
->devices_by_sysfs
= hashmap_free(m
->devices_by_sysfs
);
604 static void device_enumerate(Manager
*m
) {
605 _cleanup_udev_enumerate_unref_
struct udev_enumerate
*e
= NULL
;
606 struct udev_list_entry
*item
= NULL
, *first
= NULL
;
611 if (!m
->udev_monitor
) {
612 m
->udev_monitor
= udev_monitor_new_from_netlink(m
->udev
, "udev");
613 if (!m
->udev_monitor
) {
618 /* This will fail if we are unprivileged, but that
619 * should not matter much, as user instances won't run
621 (void) udev_monitor_set_receive_buffer_size(m
->udev_monitor
, 128*1024*1024);
623 r
= udev_monitor_filter_add_match_tag(m
->udev_monitor
, "systemd");
625 log_error_errno(r
, "Failed to add udev tag match: %m");
629 r
= udev_monitor_enable_receiving(m
->udev_monitor
);
631 log_error_errno(r
, "Failed to enable udev event reception: %m");
635 r
= sd_event_add_io(m
->event
, &m
->udev_event_source
, udev_monitor_get_fd(m
->udev_monitor
), EPOLLIN
, device_dispatch_io
, m
);
637 log_error_errno(r
, "Failed to watch udev file descriptor: %m");
641 (void) sd_event_source_set_description(m
->udev_event_source
, "device");
644 e
= udev_enumerate_new(m
->udev
);
650 r
= udev_enumerate_add_match_tag(e
, "systemd");
652 log_error_errno(r
, "Failed to create udev tag enumeration: %m");
656 r
= udev_enumerate_add_match_is_initialized(e
);
658 log_error_errno(r
, "Failed to install initialization match into enumeration: %m");
662 r
= udev_enumerate_scan_devices(e
);
664 log_error_errno(r
, "Failed to enumerate devices: %m");
668 first
= udev_enumerate_get_list_entry(e
);
669 udev_list_entry_foreach(item
, first
) {
670 _cleanup_udev_device_unref_
struct udev_device
*dev
= NULL
;
673 sysfs
= udev_list_entry_get_name(item
);
675 dev
= udev_device_new_from_syspath(m
->udev
, sysfs
);
681 if (!device_is_ready(dev
))
684 (void) device_process_new(m
, dev
);
686 device_update_found_by_sysfs(m
, sysfs
, true, DEVICE_FOUND_UDEV
, false);
695 static int device_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
696 _cleanup_udev_device_unref_
struct udev_device
*dev
= NULL
;
697 Manager
*m
= userdata
;
698 const char *action
, *sysfs
;
703 if (revents
!= EPOLLIN
) {
704 static RATELIMIT_DEFINE(limit
, 10*USEC_PER_SEC
, 5);
706 if (!ratelimit_test(&limit
))
707 log_error_errno(errno
, "Failed to get udev event: %m");
708 if (!(revents
& EPOLLIN
))
713 * libudev might filter-out devices which pass the bloom
714 * filter, so getting NULL here is not necessarily an error.
716 dev
= udev_monitor_receive_device(m
->udev_monitor
);
720 sysfs
= udev_device_get_syspath(dev
);
722 log_error("Failed to get udev sys path.");
726 action
= udev_device_get_action(dev
);
728 log_error("Failed to get udev action string.");
732 if (streq(action
, "remove")) {
733 r
= swap_process_device_remove(m
, dev
);
735 log_error_errno(r
, "Failed to process swap device remove event: %m");
737 /* If we get notified that a device was removed by
738 * udev, then it's completely gone, hence unset all
740 device_update_found_by_sysfs(m
, sysfs
, false, DEVICE_FOUND_UDEV
|DEVICE_FOUND_MOUNT
|DEVICE_FOUND_SWAP
, true);
742 } else if (device_is_ready(dev
)) {
744 (void) device_process_new(m
, dev
);
746 r
= swap_process_device_new(m
, dev
);
748 log_error_errno(r
, "Failed to process swap device new event: %m");
750 manager_dispatch_load_queue(m
);
752 /* The device is found now, set the udev found bit */
753 device_update_found_by_sysfs(m
, sysfs
, true, DEVICE_FOUND_UDEV
, true);
756 /* The device is nominally around, but not ready for
757 * us. Hence unset the udev bit, but leave the rest
760 device_update_found_by_sysfs(m
, sysfs
, false, DEVICE_FOUND_UDEV
, true);
766 static bool device_supported(void) {
767 static int read_only
= -1;
769 /* If /sys is read-only we don't support device units, and any
770 * attempts to start one should fail immediately. */
773 read_only
= path_is_read_only_fs("/sys");
775 return read_only
<= 0;
778 int device_found_node(Manager
*m
, const char *node
, bool add
, DeviceFound found
, bool now
) {
779 _cleanup_udev_device_unref_
struct udev_device
*dev
= NULL
;
785 if (!device_supported())
788 /* This is called whenever we find a device referenced in
789 * /proc/swaps or /proc/self/mounts. Such a device might be
790 * mounted/enabled at a time where udev has not finished
791 * probing it yet, and we thus haven't learned about it
792 * yet. In this case we will set the device unit to
793 * "tentative" state. */
796 if (!path_startswith(node
, "/dev"))
799 /* We make an extra check here, if the device node
800 * actually exists. If it's missing, then this is an
801 * indication that device was unplugged but is still
802 * referenced in /proc/swaps or
803 * /proc/self/mountinfo. Note that this check doesn't
804 * really cover all cases where a device might be gone
805 * away, since drives that can have a medium inserted
806 * will still have a device node even when the medium
809 if (stat(node
, &st
) >= 0) {
810 if (!S_ISBLK(st
.st_mode
) && !S_ISCHR(st
.st_mode
))
813 dev
= udev_device_new_from_devnum(m
->udev
, S_ISBLK(st
.st_mode
) ? 'b' : 'c', st
.st_rdev
);
814 if (!dev
&& errno
!= ENOENT
)
815 return log_error_errno(errno
, "Failed to get udev device from devnum %u:%u: %m", major(st
.st_rdev
), minor(st
.st_rdev
));
817 } else if (errno
!= ENOENT
)
818 return log_error_errno(errno
, "Failed to stat device node file %s: %m", node
);
820 /* If the device is known in the kernel and newly
821 * appeared, then we'll create a device unit for it,
822 * under the name referenced in /proc/swaps or
823 * /proc/self/mountinfo. */
825 (void) device_setup_unit(m
, dev
, node
, false);
828 /* Update the device unit's state, should it exist */
829 return device_update_found_by_name(m
, node
, add
, found
, now
);
832 const UnitVTable device_vtable
= {
833 .object_size
= sizeof(Device
),
839 .no_instances
= true,
843 .load
= unit_load_fragment_and_dropin_optional
,
845 .coldplug
= device_coldplug
,
847 .serialize
= device_serialize
,
848 .deserialize_item
= device_deserialize_item
,
852 .active_state
= device_active_state
,
853 .sub_state_to_string
= device_sub_state_to_string
,
855 .bus_vtable
= bus_device_vtable
,
857 .following
= device_following
,
858 .following_set
= device_following_set
,
860 .enumerate
= device_enumerate
,
861 .shutdown
= device_shutdown
,
862 .supported
= device_supported
,
864 .status_message_formats
= {
865 .starting_stopping
= {
866 [0] = "Expecting device %s...",
868 .finished_start_job
= {
869 [JOB_DONE
] = "Found device %s.",
870 [JOB_TIMEOUT
] = "Timed out waiting for device %s.",