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