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