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 "unit-name.h"
28 #include "dbus-device.h"
29 #include "path-util.h"
30 #include "udev-util.h"
35 static const UnitActiveState state_translation_table
[_DEVICE_STATE_MAX
] = {
36 [DEVICE_DEAD
] = UNIT_INACTIVE
,
37 [DEVICE_TENTATIVE
] = UNIT_ACTIVATING
,
38 [DEVICE_PLUGGED
] = UNIT_ACTIVE
,
41 static int device_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
);
43 static void device_unset_sysfs(Device
*d
) {
52 /* Remove this unit from the chain of devices which share the
54 devices
= UNIT(d
)->manager
->devices_by_sysfs
;
55 first
= hashmap_get(devices
, d
->sysfs
);
56 LIST_REMOVE(same_sysfs
, first
, d
);
59 hashmap_remove_and_replace(devices
, d
->sysfs
, first
->sysfs
, first
);
61 hashmap_remove(devices
, d
->sysfs
);
67 static int device_set_sysfs(Device
*d
, const char *sysfs
) {
74 if (streq_ptr(d
->sysfs
, sysfs
))
77 r
= hashmap_ensure_allocated(&UNIT(d
)->manager
->devices_by_sysfs
, &string_hash_ops
);
85 device_unset_sysfs(d
);
87 first
= hashmap_get(UNIT(d
)->manager
->devices_by_sysfs
, sysfs
);
88 LIST_PREPEND(same_sysfs
, first
, d
);
90 r
= hashmap_replace(UNIT(d
)->manager
->devices_by_sysfs
, copy
, first
);
92 LIST_REMOVE(same_sysfs
, first
, d
);
102 static void device_init(Unit
*u
) {
103 Device
*d
= DEVICE(u
);
106 assert(UNIT(d
)->load_state
== UNIT_STUB
);
108 /* In contrast to all other unit types we timeout jobs waiting
109 * for devices by default. This is because they otherwise wait
110 * indefinitely for plugged in devices, something which cannot
111 * happen for the other units since their operations time out
113 u
->job_timeout
= u
->manager
->default_timeout_start_usec
;
115 u
->ignore_on_isolate
= true;
116 u
->ignore_on_snapshot
= true;
119 static void device_done(Unit
*u
) {
120 Device
*d
= DEVICE(u
);
124 device_unset_sysfs(d
);
127 static void device_set_state(Device
*d
, DeviceState state
) {
128 DeviceState old_state
;
131 old_state
= d
->state
;
134 if (state
!= old_state
)
135 log_unit_debug(UNIT(d
), "Changed %s -> %s", device_state_to_string(old_state
), device_state_to_string(state
));
137 unit_notify(UNIT(d
), state_translation_table
[old_state
], state_translation_table
[state
], true);
140 static int device_coldplug(Unit
*u
) {
141 Device
*d
= DEVICE(u
);
144 assert(d
->state
== DEVICE_DEAD
);
146 if (d
->found
& DEVICE_FOUND_UDEV
)
147 /* If udev says the device is around, it's around */
148 device_set_state(d
, DEVICE_PLUGGED
);
149 else if (d
->found
!= DEVICE_NOT_FOUND
&& d
->deserialized_state
!= DEVICE_PLUGGED
)
150 /* If a device is found in /proc/self/mountinfo or
151 * /proc/swaps, and was not yet announced via udev,
152 * it's "tentatively" around. */
153 device_set_state(d
, DEVICE_TENTATIVE
);
158 static int device_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
159 Device
*d
= DEVICE(u
);
165 unit_serialize_item(u
, f
, "state", device_state_to_string(d
->state
));
170 static int device_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
171 Device
*d
= DEVICE(u
);
178 if (streq(key
, "state")) {
181 state
= device_state_from_string(value
);
183 log_unit_debug(u
, "Failed to parse state value: %s", value
);
185 d
->deserialized_state
= state
;
187 log_unit_debug(u
, "Unknown serialization key: %s", key
);
192 static void device_dump(Unit
*u
, FILE *f
, const char *prefix
) {
193 Device
*d
= DEVICE(u
);
198 "%sDevice State: %s\n"
199 "%sSysfs Path: %s\n",
200 prefix
, device_state_to_string(d
->state
),
201 prefix
, strna(d
->sysfs
));
204 _pure_
static UnitActiveState
device_active_state(Unit
*u
) {
207 return state_translation_table
[DEVICE(u
)->state
];
210 _pure_
static const char *device_sub_state_to_string(Unit
*u
) {
213 return device_state_to_string(DEVICE(u
)->state
);
216 static int device_update_description(Unit
*u
, struct udev_device
*dev
, const char *path
) {
224 model
= udev_device_get_property_value(dev
, "ID_MODEL_FROM_DATABASE");
226 model
= udev_device_get_property_value(dev
, "ID_MODEL");
231 /* Try to concatenate the device model string with a label, if there is one */
232 label
= udev_device_get_property_value(dev
, "ID_FS_LABEL");
234 label
= udev_device_get_property_value(dev
, "ID_PART_ENTRY_NAME");
236 label
= udev_device_get_property_value(dev
, "ID_PART_ENTRY_NUMBER");
239 _cleanup_free_
char *j
;
241 j
= strjoin(model
, " ", label
, NULL
);
243 r
= unit_set_description(u
, j
);
247 r
= unit_set_description(u
, model
);
249 r
= unit_set_description(u
, path
);
252 log_unit_error_errno(u
, r
, "Failed to set device description: %m");
257 static int device_add_udev_wants(Unit
*u
, struct udev_device
*dev
) {
259 const char *word
, *state
;
262 const char *property
;
267 property
= u
->manager
->running_as
== MANAGER_USER
? "MANAGER_USER_WANTS" : "SYSTEMD_WANTS";
268 wants
= udev_device_get_property_value(dev
, property
);
272 FOREACH_WORD_QUOTED(word
, l
, wants
, state
) {
273 _cleanup_free_
char *n
= NULL
;
279 r
= unit_name_mangle(e
, UNIT_NAME_NOGLOB
, &n
);
281 return log_unit_error_errno(u
, r
, "Failed to mangle unit name: %m");
283 r
= unit_add_dependency_by_name(u
, UNIT_WANTS
, n
, NULL
, true);
285 return log_unit_error_errno(u
, r
, "Failed to add wants dependency: %m");
288 log_unit_warning(u
, "Property %s on %s has trailing garbage, ignoring.", property
, strna(udev_device_get_syspath(dev
)));
293 static int device_setup_unit(Manager
*m
, struct udev_device
*dev
, const char *path
, bool main
) {
294 _cleanup_free_
char *e
= NULL
;
295 const char *sysfs
= NULL
;
304 sysfs
= udev_device_get_syspath(dev
);
309 r
= unit_name_from_path(path
, ".device", &e
);
311 return log_error_errno(r
, "Failed to generate unit name from device path: %m");
313 u
= manager_get_unit(m
, e
);
318 !path_equal(DEVICE(u
)->sysfs
, sysfs
)) {
319 log_unit_debug(u
, "Device %s appeared twice with different sysfs paths %s and %s", e
, DEVICE(u
)->sysfs
, sysfs
);
326 u
= unit_new(m
, sizeof(Device
));
330 r
= unit_add_name(u
, e
);
334 unit_add_to_load_queue(u
);
338 /* If this was created via some dependency and has not
339 * actually been seen yet ->sysfs will not be
340 * initialized. Hence initialize it if necessary. */
342 r
= device_set_sysfs(DEVICE(u
), sysfs
);
346 (void) device_update_description(u
, dev
, path
);
348 /* The additional systemd udev properties we only interpret
349 * for the main object */
351 (void) device_add_udev_wants(u
, dev
);
355 /* Note that this won't dispatch the load queue, the caller
356 * has to do that if needed and appropriate */
358 unit_add_to_dbus_queue(u
);
362 log_unit_warning_errno(u
, r
, "Failed to set up device unit: %m");
370 static int device_process_new(Manager
*m
, struct udev_device
*dev
) {
371 const char *sysfs
, *dn
, *alias
;
372 struct udev_list_entry
*item
= NULL
, *first
= NULL
;
377 sysfs
= udev_device_get_syspath(dev
);
381 /* Add the main unit named after the sysfs path */
382 r
= device_setup_unit(m
, dev
, sysfs
, true);
386 /* Add an additional unit for the device node */
387 dn
= udev_device_get_devnode(dev
);
389 (void) device_setup_unit(m
, dev
, dn
, false);
391 /* Add additional units for all symlinks */
392 first
= udev_device_get_devlinks_list_entry(dev
);
393 udev_list_entry_foreach(item
, first
) {
397 /* Don't bother with the /dev/block links */
398 p
= udev_list_entry_get_name(item
);
400 if (path_startswith(p
, "/dev/block/") ||
401 path_startswith(p
, "/dev/char/"))
404 /* Verify that the symlink in the FS actually belongs
405 * to this device. This is useful to deal with
406 * conflicting devices, e.g. when two disks want the
407 * same /dev/disk/by-label/xxx link because they have
408 * the same label. We want to make sure that the same
409 * device that won the symlink wins in systemd, so we
410 * check the device node major/minor */
411 if (stat(p
, &st
) >= 0)
412 if ((!S_ISBLK(st
.st_mode
) && !S_ISCHR(st
.st_mode
)) ||
413 st
.st_rdev
!= udev_device_get_devnum(dev
))
416 (void) device_setup_unit(m
, dev
, p
, false);
419 /* Add additional units for all explicitly configured
421 alias
= udev_device_get_property_value(dev
, "SYSTEMD_ALIAS");
423 const char *word
, *state
;
426 FOREACH_WORD_QUOTED(word
, l
, alias
, state
) {
432 if (path_is_absolute(e
))
433 (void) device_setup_unit(m
, dev
, e
, false);
435 log_warning("SYSTEMD_ALIAS for %s is not an absolute path, ignoring: %s", sysfs
, e
);
438 log_warning("SYSTEMD_ALIAS for %s has trailing garbage, ignoring.", sysfs
);
444 static void device_update_found_one(Device
*d
, bool add
, DeviceFound found
, bool now
) {
445 DeviceFound n
, previous
;
449 n
= add
? (d
->found
| found
) : (d
->found
& ~found
);
459 if (d
->found
& DEVICE_FOUND_UDEV
)
460 /* When the device is known to udev we consider it
462 device_set_state(d
, DEVICE_PLUGGED
);
463 else if (d
->found
!= DEVICE_NOT_FOUND
&& (previous
& DEVICE_FOUND_UDEV
) == 0)
464 /* If the device has not been seen by udev yet, but is
465 * now referenced by the kernel, then we assume the
466 * kernel knows it now, and udev might soon too. */
467 device_set_state(d
, DEVICE_TENTATIVE
);
469 /* If nobody sees the device, or if the device was
470 * previously seen by udev and now is only referenced
471 * from the kernel, then we consider the device is
472 * gone, the kernel just hasn't noticed it yet. */
473 device_set_state(d
, DEVICE_DEAD
);
476 static int device_update_found_by_sysfs(Manager
*m
, const char *sysfs
, bool add
, DeviceFound found
, bool now
) {
482 if (found
== DEVICE_NOT_FOUND
)
485 l
= hashmap_get(m
->devices_by_sysfs
, sysfs
);
486 LIST_FOREACH(same_sysfs
, d
, l
)
487 device_update_found_one(d
, add
, found
, now
);
492 static int device_update_found_by_name(Manager
*m
, const char *path
, bool add
, DeviceFound found
, bool now
) {
493 _cleanup_free_
char *e
= NULL
;
500 if (found
== DEVICE_NOT_FOUND
)
503 r
= unit_name_from_path(path
, ".device", &e
);
505 return log_error_errno(r
, "Failed to generate unit name from device path: %m");
507 u
= manager_get_unit(m
, e
);
511 device_update_found_one(DEVICE(u
), add
, found
, now
);
515 static bool device_is_ready(struct udev_device
*dev
) {
520 ready
= udev_device_get_property_value(dev
, "SYSTEMD_READY");
524 return parse_boolean(ready
) != 0;
527 static Unit
*device_following(Unit
*u
) {
528 Device
*d
= DEVICE(u
);
529 Device
*other
, *first
= NULL
;
533 if (startswith(u
->id
, "sys-"))
536 /* Make everybody follow the unit that's named after the sysfs path */
537 for (other
= d
->same_sysfs_next
; other
; other
= other
->same_sysfs_next
)
538 if (startswith(UNIT(other
)->id
, "sys-"))
541 for (other
= d
->same_sysfs_prev
; other
; other
= other
->same_sysfs_prev
) {
542 if (startswith(UNIT(other
)->id
, "sys-"))
551 static int device_following_set(Unit
*u
, Set
**_set
) {
552 Device
*d
= DEVICE(u
), *other
;
559 if (LIST_JUST_US(same_sysfs
, d
)) {
568 LIST_FOREACH_AFTER(same_sysfs
, other
, d
) {
569 r
= set_put(set
, other
);
574 LIST_FOREACH_BEFORE(same_sysfs
, other
, d
) {
575 r
= set_put(set
, other
);
588 static void device_shutdown(Manager
*m
) {
591 m
->udev_event_source
= sd_event_source_unref(m
->udev_event_source
);
593 if (m
->udev_monitor
) {
594 udev_monitor_unref(m
->udev_monitor
);
595 m
->udev_monitor
= NULL
;
598 hashmap_free(m
->devices_by_sysfs
);
599 m
->devices_by_sysfs
= NULL
;
602 static int device_enumerate(Manager
*m
) {
603 _cleanup_udev_enumerate_unref_
struct udev_enumerate
*e
= NULL
;
604 struct udev_list_entry
*item
= NULL
, *first
= NULL
;
609 if (!m
->udev_monitor
) {
610 m
->udev_monitor
= udev_monitor_new_from_netlink(m
->udev
, "udev");
611 if (!m
->udev_monitor
) {
616 /* This will fail if we are unprivileged, but that
617 * should not matter much, as user instances won't run
619 (void) udev_monitor_set_receive_buffer_size(m
->udev_monitor
, 128*1024*1024);
621 r
= udev_monitor_filter_add_match_tag(m
->udev_monitor
, "systemd");
625 r
= udev_monitor_enable_receiving(m
->udev_monitor
);
629 r
= sd_event_add_io(m
->event
, &m
->udev_event_source
, udev_monitor_get_fd(m
->udev_monitor
), EPOLLIN
, device_dispatch_io
, m
);
633 (void) sd_event_source_set_description(m
->udev_event_source
, "device");
636 e
= udev_enumerate_new(m
->udev
);
642 r
= udev_enumerate_add_match_tag(e
, "systemd");
646 r
= udev_enumerate_add_match_is_initialized(e
);
650 r
= udev_enumerate_scan_devices(e
);
654 first
= udev_enumerate_get_list_entry(e
);
655 udev_list_entry_foreach(item
, first
) {
656 _cleanup_udev_device_unref_
struct udev_device
*dev
= NULL
;
659 sysfs
= udev_list_entry_get_name(item
);
661 dev
= udev_device_new_from_syspath(m
->udev
, sysfs
);
667 if (!device_is_ready(dev
))
670 (void) device_process_new(m
, dev
);
672 device_update_found_by_sysfs(m
, sysfs
, true, DEVICE_FOUND_UDEV
, false);
678 log_error_errno(r
, "Failed to enumerate devices: %m");
684 static int device_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
685 _cleanup_udev_device_unref_
struct udev_device
*dev
= NULL
;
686 Manager
*m
= userdata
;
687 const char *action
, *sysfs
;
692 if (revents
!= EPOLLIN
) {
693 static RATELIMIT_DEFINE(limit
, 10*USEC_PER_SEC
, 5);
695 if (!ratelimit_test(&limit
))
696 log_error_errno(errno
, "Failed to get udev event: %m");
697 if (!(revents
& EPOLLIN
))
702 * libudev might filter-out devices which pass the bloom
703 * filter, so getting NULL here is not necessarily an error.
705 dev
= udev_monitor_receive_device(m
->udev_monitor
);
709 sysfs
= udev_device_get_syspath(dev
);
711 log_error("Failed to get udev sys path.");
715 action
= udev_device_get_action(dev
);
717 log_error("Failed to get udev action string.");
721 if (streq(action
, "remove")) {
722 r
= swap_process_device_remove(m
, dev
);
724 log_error_errno(r
, "Failed to process swap device remove event: %m");
726 /* If we get notified that a device was removed by
727 * udev, then it's completely gone, hence unset all
729 device_update_found_by_sysfs(m
, sysfs
, false, DEVICE_FOUND_UDEV
|DEVICE_FOUND_MOUNT
|DEVICE_FOUND_SWAP
, true);
731 } else if (device_is_ready(dev
)) {
733 (void) device_process_new(m
, dev
);
735 r
= swap_process_device_new(m
, dev
);
737 log_error_errno(r
, "Failed to process swap device new event: %m");
739 manager_dispatch_load_queue(m
);
741 /* The device is found now, set the udev found bit */
742 device_update_found_by_sysfs(m
, sysfs
, true, DEVICE_FOUND_UDEV
, true);
745 /* The device is nominally around, but not ready for
746 * us. Hence unset the udev bit, but leave the rest
749 device_update_found_by_sysfs(m
, sysfs
, false, DEVICE_FOUND_UDEV
, true);
755 static bool device_supported(void) {
756 static int read_only
= -1;
758 /* If /sys is read-only we don't support device units, and any
759 * attempts to start one should fail immediately. */
762 read_only
= path_is_read_only_fs("/sys");
764 return read_only
<= 0;
767 int device_found_node(Manager
*m
, const char *node
, bool add
, DeviceFound found
, bool now
) {
768 _cleanup_udev_device_unref_
struct udev_device
*dev
= NULL
;
774 if (!device_supported())
777 /* This is called whenever we find a device referenced in
778 * /proc/swaps or /proc/self/mounts. Such a device might be
779 * mounted/enabled at a time where udev has not finished
780 * probing it yet, and we thus haven't learned about it
781 * yet. In this case we will set the device unit to
782 * "tentative" state. */
785 if (!path_startswith(node
, "/dev"))
788 /* We make an extra check here, if the device node
789 * actually exists. If it's missing, then this is an
790 * indication that device was unplugged but is still
791 * referenced in /proc/swaps or
792 * /proc/self/mountinfo. Note that this check doesn't
793 * really cover all cases where a device might be gone
794 * away, since drives that can have a medium inserted
795 * will still have a device node even when the medium
798 if (stat(node
, &st
) >= 0) {
799 if (!S_ISBLK(st
.st_mode
) && !S_ISCHR(st
.st_mode
))
802 dev
= udev_device_new_from_devnum(m
->udev
, S_ISBLK(st
.st_mode
) ? 'b' : 'c', st
.st_rdev
);
803 if (!dev
&& errno
!= ENOENT
)
804 return log_error_errno(errno
, "Failed to get udev device from devnum %u:%u: %m", major(st
.st_rdev
), minor(st
.st_rdev
));
806 } else if (errno
!= ENOENT
)
807 return log_error_errno(errno
, "Failed to stat device node file %s: %m", node
);
809 /* If the device is known in the kernel and newly
810 * appeared, then we'll create a device unit for it,
811 * under the name referenced in /proc/swaps or
812 * /proc/self/mountinfo. */
814 (void) device_setup_unit(m
, dev
, node
, false);
817 /* Update the device unit's state, should it exist */
818 return device_update_found_by_name(m
, node
, add
, found
, now
);
821 static const char* const device_state_table
[_DEVICE_STATE_MAX
] = {
822 [DEVICE_DEAD
] = "dead",
823 [DEVICE_TENTATIVE
] = "tentative",
824 [DEVICE_PLUGGED
] = "plugged",
827 DEFINE_STRING_TABLE_LOOKUP(device_state
, DeviceState
);
829 const UnitVTable device_vtable
= {
830 .object_size
= sizeof(Device
),
836 .no_instances
= true,
840 .load
= unit_load_fragment_and_dropin_optional
,
842 .coldplug
= device_coldplug
,
844 .serialize
= device_serialize
,
845 .deserialize_item
= device_deserialize_item
,
849 .active_state
= device_active_state
,
850 .sub_state_to_string
= device_sub_state_to_string
,
852 .bus_interface
= "org.freedesktop.systemd1.Device",
853 .bus_vtable
= bus_device_vtable
,
855 .following
= device_following
,
856 .following_set
= device_following_set
,
858 .enumerate
= device_enumerate
,
859 .shutdown
= device_shutdown
,
860 .supported
= device_supported
,
862 .status_message_formats
= {
863 .starting_stopping
= {
864 [0] = "Expecting device %s...",
866 .finished_start_job
= {
867 [JOB_DONE
] = "Found device %s.",
868 [JOB_TIMEOUT
] = "Timed out waiting for device %s.",