]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/device.c
tree-wide: drop redundant _cleanup_ macros (#8810)
[thirdparty/systemd.git] / src / core / device.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 This file is part of systemd.
4
5 Copyright 2010 Lennart Poettering
6 ***/
7
8 #include <errno.h>
9 #include <sys/epoll.h>
10
11 #include "libudev.h"
12
13 #include "alloc-util.h"
14 #include "dbus-device.h"
15 #include "device.h"
16 #include "log.h"
17 #include "parse-util.h"
18 #include "path-util.h"
19 #include "stat-util.h"
20 #include "string-table.h"
21 #include "string-util.h"
22 #include "swap.h"
23 #include "udev-util.h"
24 #include "unit-name.h"
25 #include "unit.h"
26
27 static const UnitActiveState state_translation_table[_DEVICE_STATE_MAX] = {
28 [DEVICE_DEAD] = UNIT_INACTIVE,
29 [DEVICE_TENTATIVE] = UNIT_ACTIVATING,
30 [DEVICE_PLUGGED] = UNIT_ACTIVE,
31 };
32
33 static int device_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata);
34
35 static void device_unset_sysfs(Device *d) {
36 Hashmap *devices;
37 Device *first;
38
39 assert(d);
40
41 if (!d->sysfs)
42 return;
43
44 /* Remove this unit from the chain of devices which share the
45 * same sysfs path. */
46 devices = UNIT(d)->manager->devices_by_sysfs;
47 first = hashmap_get(devices, d->sysfs);
48 LIST_REMOVE(same_sysfs, first, d);
49
50 if (first)
51 hashmap_remove_and_replace(devices, d->sysfs, first->sysfs, first);
52 else
53 hashmap_remove(devices, d->sysfs);
54
55 d->sysfs = mfree(d->sysfs);
56 }
57
58 static int device_set_sysfs(Device *d, const char *sysfs) {
59 Device *first;
60 char *copy;
61 int r;
62
63 assert(d);
64
65 if (streq_ptr(d->sysfs, sysfs))
66 return 0;
67
68 r = hashmap_ensure_allocated(&UNIT(d)->manager->devices_by_sysfs, &path_hash_ops);
69 if (r < 0)
70 return r;
71
72 copy = strdup(sysfs);
73 if (!copy)
74 return -ENOMEM;
75
76 device_unset_sysfs(d);
77
78 first = hashmap_get(UNIT(d)->manager->devices_by_sysfs, sysfs);
79 LIST_PREPEND(same_sysfs, first, d);
80
81 r = hashmap_replace(UNIT(d)->manager->devices_by_sysfs, copy, first);
82 if (r < 0) {
83 LIST_REMOVE(same_sysfs, first, d);
84 free(copy);
85 return r;
86 }
87
88 d->sysfs = copy;
89
90 return 0;
91 }
92
93 static void device_init(Unit *u) {
94 Device *d = DEVICE(u);
95
96 assert(d);
97 assert(UNIT(d)->load_state == UNIT_STUB);
98
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
103 * anyway. */
104 u->job_running_timeout = u->manager->default_timeout_start_usec;
105
106 u->ignore_on_isolate = true;
107 }
108
109 static void device_done(Unit *u) {
110 Device *d = DEVICE(u);
111
112 assert(d);
113
114 device_unset_sysfs(d);
115 }
116
117 static void device_set_state(Device *d, DeviceState state) {
118 DeviceState old_state;
119 assert(d);
120
121 old_state = d->state;
122 d->state = state;
123
124 if (state != old_state)
125 log_unit_debug(UNIT(d), "Changed %s -> %s", device_state_to_string(old_state), device_state_to_string(state));
126
127 unit_notify(UNIT(d), state_translation_table[old_state], state_translation_table[state], true);
128 }
129
130 static int device_coldplug(Unit *u) {
131 Device *d = DEVICE(u);
132
133 assert(d);
134 assert(d->state == DEVICE_DEAD);
135
136 /* This should happen only when we reexecute PID1 from an old version
137 * which didn't serialize d->found. In this case simply assume that the
138 * device was in plugged state right before we started reexecuting which
139 * might be a wrong assumption. */
140 if (d->found == DEVICE_FOUND_UDEV_DB)
141 d->found = DEVICE_FOUND_UDEV;
142
143 if (d->found & DEVICE_FOUND_UDEV)
144 /* If udev says the device is around, it's around */
145 device_set_state(d, DEVICE_PLUGGED);
146 else if (d->found != DEVICE_NOT_FOUND && d->deserialized_state != DEVICE_PLUGGED)
147 /* If a device is found in /proc/self/mountinfo or
148 * /proc/swaps, and was not yet announced via udev,
149 * it's "tentatively" around. */
150 device_set_state(d, DEVICE_TENTATIVE);
151
152 return 0;
153 }
154
155 static int device_serialize(Unit *u, FILE *f, FDSet *fds) {
156 Device *d = DEVICE(u);
157
158 assert(u);
159 assert(f);
160 assert(fds);
161
162 unit_serialize_item(u, f, "state", device_state_to_string(d->state));
163 unit_serialize_item(u, f, "found", device_found_to_string(d->found));
164
165 return 0;
166 }
167
168 static int device_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
169 Device *d = DEVICE(u);
170
171 assert(u);
172 assert(key);
173 assert(value);
174 assert(fds);
175
176 /* The device was known at the time units were serialized but it's not
177 * anymore at the time units are deserialized. This happens when PID1 is
178 * re-executed after having switched to the new rootfs: devices were
179 * enumerated but udevd wasn't running yet thus the list of devices
180 * (handled by systemd) to initialize was empty. In such case we wait
181 * for the device events to be re-triggered by udev so device units are
182 * properly re-initialized. */
183 if (d->found == DEVICE_NOT_FOUND) {
184 assert(d->sysfs == NULL);
185 return 0;
186 }
187
188 if (streq(key, "state")) {
189 DeviceState state;
190
191 state = device_state_from_string(value);
192 if (state < 0)
193 log_unit_debug(u, "Failed to parse state value: %s", value);
194 else
195 d->deserialized_state = state;
196
197 } else if (streq(key, "found")) {
198 DeviceFound found;
199
200 found = device_found_from_string(value);
201 if (found < 0)
202 log_unit_debug(u, "Failed to parse found value: %s", value);
203 else
204 d->found = found;
205
206 } else
207 log_unit_debug(u, "Unknown serialization key: %s", key);
208
209 return 0;
210 }
211
212 static void device_dump(Unit *u, FILE *f, const char *prefix) {
213 Device *d = DEVICE(u);
214
215 assert(d);
216
217 fprintf(f,
218 "%sDevice State: %s\n"
219 "%sSysfs Path: %s\n",
220 prefix, device_state_to_string(d->state),
221 prefix, strna(d->sysfs));
222 }
223
224 _pure_ static UnitActiveState device_active_state(Unit *u) {
225 assert(u);
226
227 return state_translation_table[DEVICE(u)->state];
228 }
229
230 _pure_ static const char *device_sub_state_to_string(Unit *u) {
231 assert(u);
232
233 return device_state_to_string(DEVICE(u)->state);
234 }
235
236 static int device_update_description(Unit *u, struct udev_device *dev, const char *path) {
237 const char *model;
238 int r;
239
240 assert(u);
241 assert(dev);
242 assert(path);
243
244 model = udev_device_get_property_value(dev, "ID_MODEL_FROM_DATABASE");
245 if (!model)
246 model = udev_device_get_property_value(dev, "ID_MODEL");
247
248 if (model) {
249 const char *label;
250
251 /* Try to concatenate the device model string with a label, if there is one */
252 label = udev_device_get_property_value(dev, "ID_FS_LABEL");
253 if (!label)
254 label = udev_device_get_property_value(dev, "ID_PART_ENTRY_NAME");
255 if (!label)
256 label = udev_device_get_property_value(dev, "ID_PART_ENTRY_NUMBER");
257
258 if (label) {
259 _cleanup_free_ char *j;
260
261 j = strjoin(model, " ", label);
262 if (j)
263 r = unit_set_description(u, j);
264 else
265 r = -ENOMEM;
266 } else
267 r = unit_set_description(u, model);
268 } else
269 r = unit_set_description(u, path);
270
271 if (r < 0)
272 log_unit_error_errno(u, r, "Failed to set device description: %m");
273
274 return r;
275 }
276
277 static int device_add_udev_wants(Unit *u, struct udev_device *dev) {
278 const char *wants, *property;
279 int r;
280
281 assert(u);
282 assert(dev);
283
284 property = MANAGER_IS_USER(u->manager) ? "SYSTEMD_USER_WANTS" : "SYSTEMD_WANTS";
285
286 wants = udev_device_get_property_value(dev, property);
287 if (!wants)
288 return 0;
289
290 for (;;) {
291 _cleanup_free_ char *word = NULL, *k = NULL;
292
293 r = extract_first_word(&wants, &word, NULL, EXTRACT_QUOTES);
294 if (r == 0)
295 return 0;
296 if (r == -ENOMEM)
297 return log_oom();
298 if (r < 0)
299 return log_unit_error_errno(u, r, "Failed to parse property %s with value %s: %m", property, wants);
300
301 if (unit_name_is_valid(word, UNIT_NAME_TEMPLATE) && DEVICE(u)->sysfs) {
302 _cleanup_free_ char *escaped = NULL;
303
304 /* If the unit name is specified as template, then automatically fill in the sysfs path of the
305 * device as instance name, properly escaped. */
306
307 r = unit_name_path_escape(DEVICE(u)->sysfs, &escaped);
308 if (r < 0)
309 return log_unit_error_errno(u, r, "Failed to escape %s: %m", DEVICE(u)->sysfs);
310
311 r = unit_name_replace_instance(word, escaped, &k);
312 if (r < 0)
313 return log_unit_error_errno(u, r, "Failed to build %s instance of template %s: %m", escaped, word);
314 } else {
315 /* If this is not a template, then let's mangle it so, that it becomes a valid unit name. */
316
317 r = unit_name_mangle(word, UNIT_NAME_MANGLE_WARN, &k);
318 if (r < 0)
319 return log_unit_error_errno(u, r, "Failed to mangle unit name \"%s\": %m", word);
320 }
321
322 r = unit_add_dependency_by_name(u, UNIT_WANTS, k, NULL, true, UNIT_DEPENDENCY_UDEV);
323 if (r < 0)
324 return log_unit_error_errno(u, r, "Failed to add Wants= dependency: %m");
325 }
326 }
327
328 static bool device_is_bound_by_mounts(Device *d, struct udev_device *dev) {
329 const char *bound_by;
330 int r;
331
332 assert(d);
333 assert(dev);
334
335 bound_by = udev_device_get_property_value(dev, "SYSTEMD_MOUNT_DEVICE_BOUND");
336 if (bound_by) {
337 r = parse_boolean(bound_by);
338 if (r < 0)
339 log_warning_errno(r, "Failed to parse SYSTEMD_MOUNT_DEVICE_BOUND='%s' udev property of %s, ignoring: %m", bound_by, strna(d->sysfs));
340
341 d->bind_mounts = r > 0;
342 } else
343 d->bind_mounts = false;
344
345 return d->bind_mounts;
346 }
347
348 static int device_upgrade_mount_deps(Unit *u) {
349 Unit *other;
350 Iterator i;
351 void *v;
352 int r;
353
354 /* Let's upgrade Requires= to BindsTo= on us. (Used when SYSTEMD_MOUNT_DEVICE_BOUND is set) */
355
356 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_REQUIRED_BY], i) {
357 if (other->type != UNIT_MOUNT)
358 continue;
359
360 r = unit_add_dependency(other, UNIT_BINDS_TO, u, true, UNIT_DEPENDENCY_UDEV);
361 if (r < 0)
362 return r;
363 }
364 return 0;
365 }
366
367 static int device_setup_unit(Manager *m, struct udev_device *dev, const char *path, bool main) {
368 _cleanup_free_ char *e = NULL;
369 const char *sysfs = NULL;
370 Unit *u = NULL;
371 bool delete;
372 int r;
373
374 assert(m);
375 assert(path);
376
377 if (dev) {
378 sysfs = udev_device_get_syspath(dev);
379 if (!sysfs)
380 return 0;
381 }
382
383 r = unit_name_from_path(path, ".device", &e);
384 if (r < 0)
385 return log_error_errno(r, "Failed to generate unit name from device path: %m");
386
387 u = manager_get_unit(m, e);
388 if (u) {
389 /* The device unit can still be present even if the device was unplugged: a mount unit can reference it hence
390 * preventing the GC to have garbaged it. That's desired since the device unit may have a dependency on the
391 * mount unit which was added during the loading of the later. */
392 if (dev && DEVICE(u)->state == DEVICE_PLUGGED) {
393
394 /* This unit is in plugged state: we're sure it's attached to a device. */
395 if (!path_equal(DEVICE(u)->sysfs, sysfs)) {
396 log_unit_debug(u, "Dev %s appeared twice with different sysfs paths %s and %s",
397 e, DEVICE(u)->sysfs, sysfs);
398 return -EEXIST;
399 }
400 }
401
402 delete = false;
403
404 /* Let's remove all dependencies generated due to udev properties. We'll readd whatever is configured
405 * now below. */
406 unit_remove_dependencies(u, UNIT_DEPENDENCY_UDEV);
407 } else {
408 delete = true;
409
410 r = unit_new_for_name(m, sizeof(Device), e, &u);
411 if (r < 0)
412 goto fail;
413
414 unit_add_to_load_queue(u);
415 }
416
417 /* If this was created via some dependency and has not
418 * actually been seen yet ->sysfs will not be
419 * initialized. Hence initialize it if necessary. */
420 if (sysfs) {
421 r = device_set_sysfs(DEVICE(u), sysfs);
422 if (r < 0)
423 goto fail;
424
425 (void) device_update_description(u, dev, path);
426
427 /* The additional systemd udev properties we only interpret
428 * for the main object */
429 if (main)
430 (void) device_add_udev_wants(u, dev);
431 }
432
433 /* So the user wants the mount units to be bound to the device but a mount unit might has been seen by systemd
434 * before the device appears on its radar. In this case the device unit is partially initialized and includes
435 * the deps on the mount unit but at that time the "bind mounts" flag wasn't not present. Fix this up now. */
436 if (dev && device_is_bound_by_mounts(DEVICE(u), dev))
437 device_upgrade_mount_deps(u);
438
439 /* Note that this won't dispatch the load queue, the caller has to do that if needed and appropriate */
440
441 unit_add_to_dbus_queue(u);
442 return 0;
443
444 fail:
445 log_unit_warning_errno(u, r, "Failed to set up device unit: %m");
446
447 if (delete)
448 unit_free(u);
449
450 return r;
451 }
452
453 static int device_process_new(Manager *m, struct udev_device *dev) {
454 const char *sysfs, *dn, *alias;
455 struct udev_list_entry *item = NULL, *first = NULL;
456 int r;
457
458 assert(m);
459
460 sysfs = udev_device_get_syspath(dev);
461 if (!sysfs)
462 return 0;
463
464 /* Add the main unit named after the sysfs path */
465 r = device_setup_unit(m, dev, sysfs, true);
466 if (r < 0)
467 return r;
468
469 /* Add an additional unit for the device node */
470 dn = udev_device_get_devnode(dev);
471 if (dn)
472 (void) device_setup_unit(m, dev, dn, false);
473
474 /* Add additional units for all symlinks */
475 first = udev_device_get_devlinks_list_entry(dev);
476 udev_list_entry_foreach(item, first) {
477 const char *p;
478 struct stat st;
479
480 /* Don't bother with the /dev/block links */
481 p = udev_list_entry_get_name(item);
482
483 if (path_startswith(p, "/dev/block/") ||
484 path_startswith(p, "/dev/char/"))
485 continue;
486
487 /* Verify that the symlink in the FS actually belongs
488 * to this device. This is useful to deal with
489 * conflicting devices, e.g. when two disks want the
490 * same /dev/disk/by-label/xxx link because they have
491 * the same label. We want to make sure that the same
492 * device that won the symlink wins in systemd, so we
493 * check the device node major/minor */
494 if (stat(p, &st) >= 0)
495 if ((!S_ISBLK(st.st_mode) && !S_ISCHR(st.st_mode)) ||
496 st.st_rdev != udev_device_get_devnum(dev))
497 continue;
498
499 (void) device_setup_unit(m, dev, p, false);
500 }
501
502 /* Add additional units for all explicitly configured
503 * aliases */
504 alias = udev_device_get_property_value(dev, "SYSTEMD_ALIAS");
505 for (;;) {
506 _cleanup_free_ char *word = NULL;
507
508 r = extract_first_word(&alias, &word, NULL, EXTRACT_QUOTES);
509 if (r == 0)
510 return 0;
511 if (r == -ENOMEM)
512 return log_oom();
513 if (r < 0)
514 return log_warning_errno(r, "Failed to add parse SYSTEMD_ALIAS for %s: %m", sysfs);
515
516 if (path_is_absolute(word))
517 (void) device_setup_unit(m, dev, word, false);
518 else
519 log_warning("SYSTEMD_ALIAS for %s is not an absolute path, ignoring: %s", sysfs, word);
520 }
521 }
522
523 static void device_update_found_one(Device *d, bool add, DeviceFound found, bool now) {
524 DeviceFound n, previous;
525
526 assert(d);
527
528 n = add ? (d->found | found) : (d->found & ~found);
529 if (n == d->found)
530 return;
531
532 previous = d->found;
533 d->found = n;
534
535 if (!now)
536 return;
537
538 /* Didn't exist before, but does now? if so, generate a new invocation ID for it */
539 if (previous == DEVICE_NOT_FOUND && d->found != DEVICE_NOT_FOUND)
540 (void) unit_acquire_invocation_id(UNIT(d));
541
542 if (d->found & DEVICE_FOUND_UDEV)
543 /* When the device is known to udev we consider it
544 * plugged. */
545 device_set_state(d, DEVICE_PLUGGED);
546 else if (d->found != DEVICE_NOT_FOUND && (previous & DEVICE_FOUND_UDEV) == 0)
547 /* If the device has not been seen by udev yet, but is
548 * now referenced by the kernel, then we assume the
549 * kernel knows it now, and udev might soon too. */
550 device_set_state(d, DEVICE_TENTATIVE);
551 else {
552 /* If nobody sees the device, or if the device was
553 * previously seen by udev and now is only referenced
554 * from the kernel, then we consider the device is
555 * gone, the kernel just hasn't noticed it yet. */
556
557 device_set_state(d, DEVICE_DEAD);
558 device_unset_sysfs(d);
559 }
560
561 }
562
563 static int device_update_found_by_sysfs(Manager *m, const char *sysfs, bool add, DeviceFound found, bool now) {
564 Device *d, *l, *n;
565
566 assert(m);
567 assert(sysfs);
568
569 if (found == DEVICE_NOT_FOUND)
570 return 0;
571
572 l = hashmap_get(m->devices_by_sysfs, sysfs);
573 LIST_FOREACH_SAFE(same_sysfs, d, n, l)
574 device_update_found_one(d, add, found, now);
575
576 return 0;
577 }
578
579 static int device_update_found_by_name(Manager *m, const char *path, bool add, DeviceFound found, bool now) {
580 _cleanup_free_ char *e = NULL;
581 Unit *u;
582 int r;
583
584 assert(m);
585 assert(path);
586
587 if (found == DEVICE_NOT_FOUND)
588 return 0;
589
590 r = unit_name_from_path(path, ".device", &e);
591 if (r < 0)
592 return log_error_errno(r, "Failed to generate unit name from device path: %m");
593
594 u = manager_get_unit(m, e);
595 if (!u)
596 return 0;
597
598 device_update_found_one(DEVICE(u), add, found, now);
599 return 0;
600 }
601
602 static bool device_is_ready(struct udev_device *dev) {
603 const char *ready;
604
605 assert(dev);
606
607 ready = udev_device_get_property_value(dev, "SYSTEMD_READY");
608 if (!ready)
609 return true;
610
611 return parse_boolean(ready) != 0;
612 }
613
614 static Unit *device_following(Unit *u) {
615 Device *d = DEVICE(u);
616 Device *other, *first = NULL;
617
618 assert(d);
619
620 if (startswith(u->id, "sys-"))
621 return NULL;
622
623 /* Make everybody follow the unit that's named after the sysfs path */
624 for (other = d->same_sysfs_next; other; other = other->same_sysfs_next)
625 if (startswith(UNIT(other)->id, "sys-"))
626 return UNIT(other);
627
628 for (other = d->same_sysfs_prev; other; other = other->same_sysfs_prev) {
629 if (startswith(UNIT(other)->id, "sys-"))
630 return UNIT(other);
631
632 first = other;
633 }
634
635 return UNIT(first);
636 }
637
638 static int device_following_set(Unit *u, Set **_set) {
639 Device *d = DEVICE(u), *other;
640 Set *set;
641 int r;
642
643 assert(d);
644 assert(_set);
645
646 if (LIST_JUST_US(same_sysfs, d)) {
647 *_set = NULL;
648 return 0;
649 }
650
651 set = set_new(NULL);
652 if (!set)
653 return -ENOMEM;
654
655 LIST_FOREACH_AFTER(same_sysfs, other, d) {
656 r = set_put(set, other);
657 if (r < 0)
658 goto fail;
659 }
660
661 LIST_FOREACH_BEFORE(same_sysfs, other, d) {
662 r = set_put(set, other);
663 if (r < 0)
664 goto fail;
665 }
666
667 *_set = set;
668 return 1;
669
670 fail:
671 set_free(set);
672 return r;
673 }
674
675 static void device_shutdown(Manager *m) {
676 assert(m);
677
678 m->udev_event_source = sd_event_source_unref(m->udev_event_source);
679 m->udev_monitor = udev_monitor_unref(m->udev_monitor);
680 m->devices_by_sysfs = hashmap_free(m->devices_by_sysfs);
681 }
682
683 static void device_enumerate(Manager *m) {
684 _cleanup_(udev_enumerate_unrefp) struct udev_enumerate *e = NULL;
685 struct udev_list_entry *item = NULL, *first = NULL;
686 int r;
687
688 assert(m);
689
690 if (!m->udev_monitor) {
691 m->udev_monitor = udev_monitor_new_from_netlink(m->udev, "udev");
692 if (!m->udev_monitor) {
693 log_oom();
694 goto fail;
695 }
696
697 /* This will fail if we are unprivileged, but that
698 * should not matter much, as user instances won't run
699 * during boot. */
700 (void) udev_monitor_set_receive_buffer_size(m->udev_monitor, 128*1024*1024);
701
702 r = udev_monitor_filter_add_match_tag(m->udev_monitor, "systemd");
703 if (r < 0) {
704 log_error_errno(r, "Failed to add udev tag match: %m");
705 goto fail;
706 }
707
708 r = udev_monitor_enable_receiving(m->udev_monitor);
709 if (r < 0) {
710 log_error_errno(r, "Failed to enable udev event reception: %m");
711 goto fail;
712 }
713
714 r = sd_event_add_io(m->event, &m->udev_event_source, udev_monitor_get_fd(m->udev_monitor), EPOLLIN, device_dispatch_io, m);
715 if (r < 0) {
716 log_error_errno(r, "Failed to watch udev file descriptor: %m");
717 goto fail;
718 }
719
720 (void) sd_event_source_set_description(m->udev_event_source, "device");
721 }
722
723 e = udev_enumerate_new(m->udev);
724 if (!e) {
725 log_oom();
726 goto fail;
727 }
728
729 r = udev_enumerate_add_match_tag(e, "systemd");
730 if (r < 0) {
731 log_error_errno(r, "Failed to create udev tag enumeration: %m");
732 goto fail;
733 }
734
735 r = udev_enumerate_add_match_is_initialized(e);
736 if (r < 0) {
737 log_error_errno(r, "Failed to install initialization match into enumeration: %m");
738 goto fail;
739 }
740
741 r = udev_enumerate_scan_devices(e);
742 if (r < 0) {
743 log_error_errno(r, "Failed to enumerate devices: %m");
744 goto fail;
745 }
746
747 first = udev_enumerate_get_list_entry(e);
748 udev_list_entry_foreach(item, first) {
749 _cleanup_(udev_device_unrefp) struct udev_device *dev = NULL;
750 const char *sysfs;
751
752 sysfs = udev_list_entry_get_name(item);
753
754 dev = udev_device_new_from_syspath(m->udev, sysfs);
755 if (!dev) {
756 log_oom();
757 continue;
758 }
759
760 if (!device_is_ready(dev))
761 continue;
762
763 (void) device_process_new(m, dev);
764
765 device_update_found_by_sysfs(m, sysfs, true, DEVICE_FOUND_UDEV_DB, false);
766 }
767
768 return;
769
770 fail:
771 device_shutdown(m);
772 }
773
774 static int device_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
775 _cleanup_(udev_device_unrefp) struct udev_device *dev = NULL;
776 Manager *m = userdata;
777 const char *action, *sysfs;
778 int r;
779
780 assert(m);
781
782 if (revents != EPOLLIN) {
783 static RATELIMIT_DEFINE(limit, 10*USEC_PER_SEC, 5);
784
785 if (ratelimit_test(&limit))
786 log_warning("Failed to get udev event");
787 if (!(revents & EPOLLIN))
788 return 0;
789 }
790
791 /*
792 * libudev might filter-out devices which pass the bloom
793 * filter, so getting NULL here is not necessarily an error.
794 */
795 dev = udev_monitor_receive_device(m->udev_monitor);
796 if (!dev)
797 return 0;
798
799 sysfs = udev_device_get_syspath(dev);
800 if (!sysfs) {
801 log_error("Failed to get udev sys path.");
802 return 0;
803 }
804
805 action = udev_device_get_action(dev);
806 if (!action) {
807 log_error("Failed to get udev action string.");
808 return 0;
809 }
810
811 if (streq(action, "change")) {
812 Unit *u;
813 Device *d, *l, *n;
814
815 l = hashmap_get(m->devices_by_sysfs, sysfs);
816 LIST_FOREACH_SAFE(same_sysfs, d, n, l) {
817 u = &d->meta;
818 if (u && UNIT_VTABLE(u)->active_state(u) == UNIT_ACTIVE) {
819 r = manager_propagate_reload(m, u, JOB_REPLACE, NULL);
820 if (r < 0)
821 log_error_errno(r, "Failed to propagate reload: %m");
822 }
823 }
824 }
825
826 /* A change event can signal that a device is becoming ready, in particular if
827 * the device is using the SYSTEMD_READY logic in udev
828 * so we need to reach the else block of the follwing if, even for change events */
829 if (streq(action, "remove")) {
830 r = swap_process_device_remove(m, dev);
831 if (r < 0)
832 log_error_errno(r, "Failed to process swap device remove event: %m");
833
834 /* If we get notified that a device was removed by
835 * udev, then it's completely gone, hence unset all
836 * found bits */
837 device_update_found_by_sysfs(m, sysfs, false, DEVICE_FOUND_UDEV|DEVICE_FOUND_MOUNT|DEVICE_FOUND_SWAP, true);
838
839 } else if (device_is_ready(dev)) {
840
841 (void) device_process_new(m, dev);
842
843 r = swap_process_device_new(m, dev);
844 if (r < 0)
845 log_error_errno(r, "Failed to process swap device new event: %m");
846
847 manager_dispatch_load_queue(m);
848
849 /* The device is found now, set the udev found bit */
850 device_update_found_by_sysfs(m, sysfs, true, DEVICE_FOUND_UDEV, true);
851
852 } else {
853 /* The device is nominally around, but not ready for
854 * us. Hence unset the udev bit, but leave the rest
855 * around. */
856
857 device_update_found_by_sysfs(m, sysfs, false, DEVICE_FOUND_UDEV, true);
858 }
859
860 return 0;
861 }
862
863 static bool device_supported(void) {
864 static int read_only = -1;
865
866 /* If /sys is read-only we don't support device units, and any
867 * attempts to start one should fail immediately. */
868
869 if (read_only < 0)
870 read_only = path_is_read_only_fs("/sys");
871
872 return read_only <= 0;
873 }
874
875 int device_found_node(Manager *m, const char *node, bool add, DeviceFound found, bool now) {
876 _cleanup_(udev_device_unrefp) struct udev_device *dev = NULL;
877 struct stat st;
878
879 assert(m);
880 assert(node);
881
882 if (!device_supported())
883 return 0;
884
885 /* This is called whenever we find a device referenced in
886 * /proc/swaps or /proc/self/mounts. Such a device might be
887 * mounted/enabled at a time where udev has not finished
888 * probing it yet, and we thus haven't learned about it
889 * yet. In this case we will set the device unit to
890 * "tentative" state. */
891
892 if (add) {
893 if (!path_startswith(node, "/dev"))
894 return 0;
895
896 /* We make an extra check here, if the device node
897 * actually exists. If it's missing, then this is an
898 * indication that device was unplugged but is still
899 * referenced in /proc/swaps or
900 * /proc/self/mountinfo. Note that this check doesn't
901 * really cover all cases where a device might be gone
902 * away, since drives that can have a medium inserted
903 * will still have a device node even when the medium
904 * is not there... */
905
906 if (stat(node, &st) >= 0) {
907 if (!S_ISBLK(st.st_mode) && !S_ISCHR(st.st_mode))
908 return 0;
909
910 dev = udev_device_new_from_devnum(m->udev, S_ISBLK(st.st_mode) ? 'b' : 'c', st.st_rdev);
911 if (!dev && errno != ENOENT)
912 return log_error_errno(errno, "Failed to get udev device from devnum %u:%u: %m", major(st.st_rdev), minor(st.st_rdev));
913
914 } else if (errno != ENOENT)
915 return log_error_errno(errno, "Failed to stat device node file %s: %m", node);
916
917 /* If the device is known in the kernel and newly
918 * appeared, then we'll create a device unit for it,
919 * under the name referenced in /proc/swaps or
920 * /proc/self/mountinfo. */
921
922 (void) device_setup_unit(m, dev, node, false);
923 }
924
925 /* Update the device unit's state, should it exist */
926 return device_update_found_by_name(m, node, add, found, now);
927 }
928
929 bool device_shall_be_bound_by(Unit *device, Unit *u) {
930
931 if (u->type != UNIT_MOUNT)
932 return false;
933
934 return DEVICE(device)->bind_mounts;
935 }
936
937 static const char* const device_found_table[] = {
938 [DEVICE_NOT_FOUND] = "not-found",
939 [DEVICE_FOUND_UDEV] = "found-udev",
940 [DEVICE_FOUND_UDEV_DB] = "found-udev-db",
941 [DEVICE_FOUND_MOUNT] = "found-mount",
942 [DEVICE_FOUND_SWAP] = "found-swap",
943 };
944
945 DEFINE_STRING_TABLE_LOOKUP(device_found, DeviceFound);
946
947 const UnitVTable device_vtable = {
948 .object_size = sizeof(Device),
949 .sections =
950 "Unit\0"
951 "Device\0"
952 "Install\0",
953
954 .gc_jobs = true,
955
956 .init = device_init,
957 .done = device_done,
958 .load = unit_load_fragment_and_dropin_optional,
959
960 .coldplug = device_coldplug,
961
962 .serialize = device_serialize,
963 .deserialize_item = device_deserialize_item,
964
965 .dump = device_dump,
966
967 .active_state = device_active_state,
968 .sub_state_to_string = device_sub_state_to_string,
969
970 .bus_vtable = bus_device_vtable,
971
972 .following = device_following,
973 .following_set = device_following_set,
974
975 .enumerate = device_enumerate,
976 .shutdown = device_shutdown,
977 .supported = device_supported,
978
979 .status_message_formats = {
980 .starting_stopping = {
981 [0] = "Expecting device %s...",
982 },
983 .finished_start_job = {
984 [JOB_DONE] = "Found device %s.",
985 [JOB_TIMEOUT] = "Timed out waiting for device %s.",
986 },
987 },
988 };