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