]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/device.c
93cab92b8ce0669e8c4e20301e86a1e49f3617d3
[thirdparty/systemd.git] / src / core / device.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <sys/epoll.h>
5
6 #include "sd-messages.h"
7
8 #include "alloc-util.h"
9 #include "bus-common-errors.h"
10 #include "dbus-device.h"
11 #include "dbus-unit.h"
12 #include "device-private.h"
13 #include "device-util.h"
14 #include "device.h"
15 #include "log.h"
16 #include "parse-util.h"
17 #include "path-util.h"
18 #include "ratelimit.h"
19 #include "serialize.h"
20 #include "stat-util.h"
21 #include "string-util.h"
22 #include "swap.h"
23 #include "udev-util.h"
24 #include "unit-name.h"
25 #include "unit.h"
26
27 static const UnitActiveState state_translation_table[_DEVICE_STATE_MAX] = {
28 [DEVICE_DEAD] = UNIT_INACTIVE,
29 [DEVICE_TENTATIVE] = UNIT_ACTIVATING,
30 [DEVICE_PLUGGED] = UNIT_ACTIVE,
31 };
32
33 static int device_dispatch_io(sd_device_monitor *monitor, sd_device *dev, void *userdata);
34
35 static int device_by_path(Manager *m, const char *path, Unit **ret) {
36 _cleanup_free_ char *e = NULL;
37 Unit *u;
38 int r;
39
40 assert(m);
41 assert(path);
42
43 r = unit_name_from_path(path, ".device", &e);
44 if (r < 0)
45 return r;
46
47 u = manager_get_unit(m, e);
48 if (!u)
49 return -ENOENT;
50
51 if (ret)
52 *ret = u;
53 return 0;
54 }
55
56 static void device_unset_sysfs(Device *d) {
57 Hashmap *devices;
58
59 assert(d);
60
61 if (!d->sysfs)
62 return;
63
64 /* Remove this unit from the chain of devices which share the same sysfs path. */
65
66 devices = UNIT(d)->manager->devices_by_sysfs;
67
68 if (d->same_sysfs_prev)
69 /* If this is not the first unit, then simply remove this unit. */
70 d->same_sysfs_prev->same_sysfs_next = d->same_sysfs_next;
71 else if (d->same_sysfs_next)
72 /* If this is the first unit, replace with the next unit. */
73 assert_se(hashmap_replace(devices, d->same_sysfs_next->sysfs, d->same_sysfs_next) >= 0);
74 else
75 /* Otherwise, remove the entry. */
76 hashmap_remove(devices, d->sysfs);
77
78 if (d->same_sysfs_next)
79 d->same_sysfs_next->same_sysfs_prev = d->same_sysfs_prev;
80
81 d->same_sysfs_prev = d->same_sysfs_next = NULL;
82
83 d->sysfs = mfree(d->sysfs);
84 }
85
86 static int device_set_sysfs(Device *d, const char *sysfs) {
87 _cleanup_free_ char *copy = NULL;
88 Device *first;
89 int r;
90
91 assert(d);
92
93 if (streq_ptr(d->sysfs, sysfs))
94 return 0;
95
96 r = hashmap_ensure_allocated(&UNIT(d)->manager->devices_by_sysfs, &path_hash_ops);
97 if (r < 0)
98 return r;
99
100 copy = strdup(sysfs);
101 if (!copy)
102 return -ENOMEM;
103
104 device_unset_sysfs(d);
105
106 first = hashmap_get(UNIT(d)->manager->devices_by_sysfs, sysfs);
107 LIST_PREPEND(same_sysfs, first, d);
108
109 r = hashmap_replace(UNIT(d)->manager->devices_by_sysfs, copy, first);
110 if (r < 0) {
111 LIST_REMOVE(same_sysfs, first, d);
112 return r;
113 }
114
115 d->sysfs = TAKE_PTR(copy);
116 unit_add_to_dbus_queue(UNIT(d));
117
118 return 0;
119 }
120
121 static void device_init(Unit *u) {
122 Device *d = ASSERT_PTR(DEVICE(u));
123
124 assert(u->load_state == UNIT_STUB);
125
126 /* In contrast to all other unit types we timeout jobs waiting
127 * for devices by default. This is because they otherwise wait
128 * indefinitely for plugged in devices, something which cannot
129 * happen for the other units since their operations time out
130 * anyway. */
131 u->job_running_timeout = u->manager->defaults.device_timeout_usec;
132
133 u->ignore_on_isolate = true;
134
135 d->deserialized_state = _DEVICE_STATE_INVALID;
136 }
137
138 static void device_done(Unit *u) {
139 Device *d = ASSERT_PTR(DEVICE(u));
140
141 device_unset_sysfs(d);
142 d->deserialized_sysfs = mfree(d->deserialized_sysfs);
143 d->wants_property = strv_free(d->wants_property);
144 d->path = mfree(d->path);
145 }
146
147 static int device_load(Unit *u) {
148 int r;
149
150 r = unit_load_fragment_and_dropin(u, false);
151 if (r < 0)
152 return r;
153
154 if (!u->description) {
155 /* Generate a description based on the path, to be used until the device is initialized
156 properly */
157 r = unit_name_to_path(u->id, &u->description);
158 if (r < 0)
159 log_unit_debug_errno(u, r, "Failed to unescape name: %m");
160 }
161
162 return 0;
163 }
164
165 static void device_set_state(Device *d, DeviceState state) {
166 DeviceState old_state;
167
168 assert(d);
169
170 if (d->state != state)
171 bus_unit_send_pending_change_signal(UNIT(d), false);
172
173 old_state = d->state;
174 d->state = state;
175
176 if (state == DEVICE_DEAD)
177 device_unset_sysfs(d);
178
179 if (state != old_state)
180 log_unit_debug(UNIT(d), "Changed %s -> %s", device_state_to_string(old_state), device_state_to_string(state));
181
182 unit_notify(UNIT(d), state_translation_table[old_state], state_translation_table[state], /* reload_success = */ true);
183 }
184
185 static void device_found_changed(Device *d, DeviceFound previous, DeviceFound now) {
186 assert(d);
187
188 /* Didn't exist before, but does now? if so, generate a new invocation ID for it */
189 if (previous == DEVICE_NOT_FOUND && now != DEVICE_NOT_FOUND)
190 (void) unit_acquire_invocation_id(UNIT(d));
191
192 if (FLAGS_SET(now, DEVICE_FOUND_UDEV))
193 /* When the device is known to udev we consider it plugged. */
194 device_set_state(d, DEVICE_PLUGGED);
195 else if (now != DEVICE_NOT_FOUND && !FLAGS_SET(previous, DEVICE_FOUND_UDEV))
196 /* If the device has not been seen by udev yet, but is now referenced by the kernel, then we assume the
197 * kernel knows it now, and udev might soon too. */
198 device_set_state(d, DEVICE_TENTATIVE);
199 else
200 /* If nobody sees the device, or if the device was previously seen by udev and now is only referenced
201 * from the kernel, then we consider the device is gone, the kernel just hasn't noticed it yet. */
202 device_set_state(d, DEVICE_DEAD);
203 }
204
205 static void device_update_found_one(Device *d, DeviceFound found, DeviceFound mask) {
206 assert(d);
207
208 if (MANAGER_IS_RUNNING(UNIT(d)->manager)) {
209 DeviceFound n, previous;
210
211 /* When we are already running, then apply the new mask right-away, and trigger state changes
212 * right-away */
213
214 n = (d->found & ~mask) | (found & mask);
215 if (n == d->found)
216 return;
217
218 previous = d->found;
219 d->found = n;
220
221 device_found_changed(d, previous, n);
222 } else
223 /* We aren't running yet, let's apply the new mask to the shadow variable instead, which we'll apply as
224 * soon as we catch-up with the state. */
225 d->enumerated_found = (d->enumerated_found & ~mask) | (found & mask);
226 }
227
228 static void device_update_found_by_sysfs(Manager *m, const char *sysfs, DeviceFound found, DeviceFound mask) {
229 Device *l;
230
231 assert(m);
232 assert(sysfs);
233
234 if (mask == 0)
235 return;
236
237 l = hashmap_get(m->devices_by_sysfs, sysfs);
238 LIST_FOREACH(same_sysfs, d, l)
239 device_update_found_one(d, found, mask);
240 }
241
242 static void device_update_found_by_name(Manager *m, const char *path, DeviceFound found, DeviceFound mask) {
243 Unit *u;
244
245 assert(m);
246 assert(path);
247
248 if (mask == 0)
249 return;
250
251 if (device_by_path(m, path, &u) < 0)
252 return;
253
254 device_update_found_one(DEVICE(u), found, mask);
255 }
256
257 static int device_coldplug(Unit *u) {
258 Device *d = ASSERT_PTR(DEVICE(u));
259
260 assert(d->state == DEVICE_DEAD);
261
262 /* First, let's put the deserialized state and found mask into effect, if we have it. */
263 if (d->deserialized_state < 0)
264 return 0;
265
266 Manager *m = u->manager;
267 DeviceFound found = d->deserialized_found;
268 DeviceState state = d->deserialized_state;
269
270 /* On initial boot, switch-root, reload, reexecute, the following happen:
271 * 1. MANAGER_IS_RUNNING() == false
272 * 2. enumerate devices: manager_enumerate() -> device_enumerate()
273 * Device.enumerated_found is set.
274 * 3. deserialize devices: manager_deserialize() -> device_deserialize_item()
275 * Device.deserialize_state and Device.deserialized_found are set.
276 * 4. coldplug devices: manager_coldplug() -> device_coldplug()
277 * deserialized properties are copied to the main properties.
278 * 5. MANAGER_IS_RUNNING() == true: manager_ready()
279 * 6. catchup devices: manager_catchup() -> device_catchup()
280 * Device.enumerated_found is applied to Device.found, and state is updated based on that.
281 *
282 * Notes:
283 * - On initial boot, no udev database exists. Hence, no devices are enumerated in the step 2.
284 * Also, there is no deserialized device. Device units are (a) generated based on dependencies of
285 * other units, or (b) generated when uevents are received.
286 *
287 * - On switch-root, the udev database may be cleared, except for devices with sticky bit, i.e.
288 * OPTIONS="db_persist". Hence, almost no devices are enumerated in the step 2. However, in
289 * general, we have several serialized devices. So, DEVICE_FOUND_UDEV bit in the
290 * Device.deserialized_found must be ignored, as udev rules in initrd and the main system are often
291 * different. If the deserialized state is DEVICE_PLUGGED, we need to downgrade it to
292 * DEVICE_TENTATIVE. Unlike the other starting mode, MANAGER_IS_SWITCHING_ROOT() is true when
293 * device_coldplug() and device_catchup() are called. Hence, let's conditionalize the operations by
294 * using the flag. After switch-root, systemd-udevd will (re-)process all devices, and the
295 * Device.found and Device.state will be adjusted.
296 *
297 * - On reload or reexecute, we can trust Device.enumerated_found, Device.deserialized_found, and
298 * Device.deserialized_state. Of course, deserialized parameters may be outdated, but the unit
299 * state can be adjusted later by device_catchup() or uevents. */
300
301 if (MANAGER_IS_SWITCHING_ROOT(m) &&
302 !FLAGS_SET(d->enumerated_found, DEVICE_FOUND_UDEV)) {
303
304 /* The device has not been enumerated. On switching-root, such situation is natural. See the
305 * above comment. To prevent problematic state transition active → dead → active, let's
306 * drop the DEVICE_FOUND_UDEV flag and downgrade state to DEVICE_TENTATIVE(activating). See
307 * issue #12953 and #23208. */
308 found &= ~DEVICE_FOUND_UDEV;
309 if (state == DEVICE_PLUGGED)
310 state = DEVICE_TENTATIVE;
311
312 /* Also check the validity of the device syspath. Without this check, if the device was
313 * removed while switching root, it would never go to inactive state, as both Device.found
314 * and Device.enumerated_found do not have the DEVICE_FOUND_UDEV flag, so device_catchup() in
315 * device_update_found_one() does nothing in most cases. See issue #25106. Note that the
316 * syspath field is only serialized when systemd is sufficiently new and the device has been
317 * already processed by udevd. */
318 if (d->deserialized_sysfs) {
319 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
320
321 if (sd_device_new_from_syspath(&dev, d->deserialized_sysfs) < 0)
322 state = DEVICE_DEAD;
323 }
324 }
325
326 if (d->found == found && d->state == state)
327 return 0;
328
329 d->found = found;
330 device_set_state(d, state);
331 return 0;
332 }
333
334 static void device_catchup(Unit *u) {
335 Device *d = ASSERT_PTR(DEVICE(u));
336
337 /* Second, let's update the state with the enumerated state */
338 device_update_found_one(d, d->enumerated_found, DEVICE_FOUND_MASK);
339 }
340
341 static const struct {
342 DeviceFound flag;
343 const char *name;
344 } device_found_map[] = {
345 { DEVICE_FOUND_UDEV, "found-udev" },
346 { DEVICE_FOUND_MOUNT, "found-mount" },
347 { DEVICE_FOUND_SWAP, "found-swap" },
348 };
349
350 static int device_found_to_string_many(DeviceFound flags, char **ret) {
351 _cleanup_free_ char *s = NULL;
352
353 assert(ret);
354
355 for (size_t i = 0; i < ELEMENTSOF(device_found_map); i++) {
356 if (!FLAGS_SET(flags, device_found_map[i].flag))
357 continue;
358
359 if (!strextend_with_separator(&s, ",", device_found_map[i].name))
360 return -ENOMEM;
361 }
362
363 *ret = TAKE_PTR(s);
364
365 return 0;
366 }
367
368 static int device_found_from_string_many(const char *name, DeviceFound *ret) {
369 DeviceFound flags = 0;
370 int r;
371
372 assert(ret);
373
374 for (;;) {
375 _cleanup_free_ char *word = NULL;
376 DeviceFound f = 0;
377 unsigned i;
378
379 r = extract_first_word(&name, &word, ",", 0);
380 if (r < 0)
381 return r;
382 if (r == 0)
383 break;
384
385 for (i = 0; i < ELEMENTSOF(device_found_map); i++)
386 if (streq(word, device_found_map[i].name)) {
387 f = device_found_map[i].flag;
388 break;
389 }
390
391 if (f == 0)
392 return -EINVAL;
393
394 flags |= f;
395 }
396
397 *ret = flags;
398 return 0;
399 }
400
401 static int device_serialize(Unit *u, FILE *f, FDSet *fds) {
402 Device *d = ASSERT_PTR(DEVICE(u));
403 _cleanup_free_ char *s = NULL;
404
405 assert(f);
406 assert(fds);
407
408 if (d->sysfs)
409 (void) serialize_item(f, "sysfs", d->sysfs);
410
411 if (d->path)
412 (void) serialize_item(f, "path", d->path);
413
414 (void) serialize_item(f, "state", device_state_to_string(d->state));
415
416 if (device_found_to_string_many(d->found, &s) >= 0)
417 (void) serialize_item(f, "found", s);
418
419 return 0;
420 }
421
422 static int device_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
423 Device *d = ASSERT_PTR(DEVICE(u));
424 int r;
425
426 assert(key);
427 assert(value);
428 assert(fds);
429
430 if (streq(key, "sysfs")) {
431 if (!d->deserialized_sysfs) {
432 d->deserialized_sysfs = strdup(value);
433 if (!d->deserialized_sysfs)
434 log_oom_debug();
435 }
436
437 } else if (streq(key, "path")) {
438 if (!d->path) {
439 d->path = strdup(value);
440 if (!d->path)
441 log_oom_debug();
442 }
443
444 } else if (streq(key, "state")) {
445 DeviceState state;
446
447 state = device_state_from_string(value);
448 if (state < 0)
449 log_unit_debug(u, "Failed to parse state value, ignoring: %s", value);
450 else
451 d->deserialized_state = state;
452
453 } else if (streq(key, "found")) {
454 r = device_found_from_string_many(value, &d->deserialized_found);
455 if (r < 0)
456 log_unit_debug_errno(u, r, "Failed to parse found value '%s', ignoring: %m", value);
457
458 } else
459 log_unit_debug(u, "Unknown serialization key: %s", key);
460
461 return 0;
462 }
463
464 static void device_dump(Unit *u, FILE *f, const char *prefix) {
465 Device *d = ASSERT_PTR(DEVICE(u));
466 _cleanup_free_ char *s = NULL;
467
468 assert(f);
469 assert(prefix);
470
471 (void) device_found_to_string_many(d->found, &s);
472
473 fprintf(f,
474 "%sDevice State: %s\n"
475 "%sDevice Path: %s\n"
476 "%sSysfs Path: %s\n"
477 "%sFound: %s\n",
478 prefix, device_state_to_string(d->state),
479 prefix, strna(d->path),
480 prefix, strna(d->sysfs),
481 prefix, strna(s));
482
483 STRV_FOREACH(i, d->wants_property)
484 fprintf(f, "%sudev SYSTEMD_WANTS: %s\n",
485 prefix, *i);
486 }
487
488 static UnitActiveState device_active_state(Unit *u) {
489 Device *d = ASSERT_PTR(DEVICE(u));
490
491 return state_translation_table[d->state];
492 }
493
494 static const char *device_sub_state_to_string(Unit *u) {
495 Device *d = ASSERT_PTR(DEVICE(u));
496
497 return device_state_to_string(d->state);
498 }
499
500 static int device_update_description(Unit *u, sd_device *dev, const char *path) {
501 _cleanup_free_ char *j = NULL;
502 const char *model, *label, *desc;
503 int r;
504
505 assert(u);
506 assert(path);
507
508 desc = path;
509
510 if (dev && device_get_model_string(dev, &model) >= 0) {
511 desc = model;
512
513 /* Try to concatenate the device model string with a label, if there is one */
514 if (sd_device_get_property_value(dev, "ID_FS_LABEL", &label) >= 0 ||
515 sd_device_get_property_value(dev, "ID_PART_ENTRY_NAME", &label) >= 0 ||
516 sd_device_get_property_value(dev, "ID_PART_ENTRY_NUMBER", &label) >= 0) {
517
518 desc = j = strjoin(model, " ", label);
519 if (!j)
520 return log_oom();
521 }
522 }
523
524 r = unit_set_description(u, desc);
525 if (r < 0)
526 return log_unit_error_errno(u, r, "Failed to set device description: %m");
527
528 return 0;
529 }
530
531 static int device_add_udev_wants(Unit *u, sd_device *dev) {
532 Device *d = ASSERT_PTR(DEVICE(u));
533 _cleanup_strv_free_ char **added = NULL;
534 const char *wants, *property;
535 int r;
536
537 assert(dev);
538
539 property = MANAGER_IS_USER(u->manager) ? "SYSTEMD_USER_WANTS" : "SYSTEMD_WANTS";
540
541 r = sd_device_get_property_value(dev, property, &wants);
542 if (r < 0)
543 return 0;
544
545 for (;;) {
546 _cleanup_free_ char *word = NULL, *k = NULL;
547
548 r = extract_first_word(&wants, &word, NULL, EXTRACT_UNQUOTE);
549 if (r == 0)
550 break;
551 if (r == -ENOMEM)
552 return log_oom();
553 if (r < 0)
554 return log_unit_error_errno(u, r, "Failed to parse property %s with value %s: %m", property, wants);
555
556 if (unit_name_is_valid(word, UNIT_NAME_TEMPLATE) && d->sysfs) {
557 _cleanup_free_ char *escaped = NULL;
558
559 /* If the unit name is specified as template, then automatically fill in the sysfs path of the
560 * device as instance name, properly escaped. */
561
562 r = unit_name_path_escape(d->sysfs, &escaped);
563 if (r < 0)
564 return log_unit_error_errno(u, r, "Failed to escape %s: %m", d->sysfs);
565
566 r = unit_name_replace_instance(word, escaped, &k);
567 if (r < 0)
568 return log_unit_error_errno(u, r, "Failed to build %s instance of template %s: %m", escaped, word);
569 } else {
570 /* If this is not a template, then let's mangle it so, that it becomes a valid unit name. */
571
572 r = unit_name_mangle(word, UNIT_NAME_MANGLE_WARN, &k);
573 if (r < 0)
574 return log_unit_error_errno(u, r, "Failed to mangle unit name \"%s\": %m", word);
575 }
576
577 r = unit_add_dependency_by_name(u, UNIT_WANTS, k, true, UNIT_DEPENDENCY_UDEV);
578 if (r < 0)
579 return log_unit_error_errno(u, r, "Failed to add Wants= dependency: %m");
580
581 r = strv_consume(&added, TAKE_PTR(k));
582 if (r < 0)
583 return log_oom();
584 }
585
586 if (d->state != DEVICE_DEAD)
587 /* So here's a special hack, to compensate for the fact that the udev database's reload cycles are not
588 * synchronized with our own reload cycles: when we detect that the SYSTEMD_WANTS property of a device
589 * changes while the device unit is already up, let's skip to trigger units that were already listed
590 * and are active, and start units otherwise. This typically happens during the boot-time switch root
591 * transition, as udev devices will generally already be up in the initrd, but SYSTEMD_WANTS properties
592 * get then added through udev rules only available on the host system, and thus only when the initial
593 * udev coldplug trigger runs.
594 *
595 * We do this only if the device has been up already when we parse this, as otherwise the usual
596 * dependency logic that is run from the dead → plugged transition will trigger these deps. */
597 STRV_FOREACH(i, added) {
598 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
599
600 if (strv_contains(d->wants_property, *i)) {
601 Unit *v;
602
603 v = manager_get_unit(u->manager, *i);
604 if (v && UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(v)))
605 continue; /* The unit was already listed and is running. */
606 }
607
608 r = manager_add_job_by_name(u->manager, JOB_START, *i, JOB_FAIL, NULL, &error, NULL);
609 if (r < 0)
610 log_unit_full_errno(u, sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT) ? LOG_DEBUG : LOG_WARNING, r,
611 "Failed to enqueue %s job, ignoring: %s", property, bus_error_message(&error, r));
612 }
613
614 return strv_free_and_replace(d->wants_property, added);
615 }
616
617 static bool device_is_bound_by_mounts(Device *d, sd_device *dev) {
618 int r;
619
620 assert(d);
621 assert(dev);
622
623 r = device_get_property_bool(dev, "SYSTEMD_MOUNT_DEVICE_BOUND");
624 if (r < 0 && r != -ENOENT)
625 log_device_warning_errno(dev, r, "Failed to parse SYSTEMD_MOUNT_DEVICE_BOUND= udev property, ignoring: %m");
626
627 d->bind_mounts = r > 0;
628
629 return d->bind_mounts;
630 }
631
632 static void device_upgrade_mount_deps(Unit *u) {
633 Unit *other;
634 void *v;
635 int r;
636
637 /* Let's upgrade Requires= to BindsTo= on us. (Used when SYSTEMD_MOUNT_DEVICE_BOUND is set) */
638
639 assert(u);
640
641 HASHMAP_FOREACH_KEY(v, other, unit_get_dependencies(u, UNIT_REQUIRED_BY)) {
642 if (other->type != UNIT_MOUNT)
643 continue;
644
645 r = unit_add_dependency(other, UNIT_BINDS_TO, u, true, UNIT_DEPENDENCY_UDEV);
646 if (r < 0)
647 log_unit_warning_errno(u, r, "Failed to add BindsTo= dependency between device and mount unit, ignoring: %m");
648 }
649 }
650
651 static int device_setup_unit(Manager *m, sd_device *dev, const char *path, bool main, Set **units) {
652 _cleanup_(unit_freep) Unit *new_unit = NULL;
653 _cleanup_free_ char *e = NULL;
654 const char *sysfs = NULL;
655 Unit *u;
656 int r;
657
658 assert(m);
659 assert(path);
660
661 if (dev) {
662 r = sd_device_get_syspath(dev, &sysfs);
663 if (r < 0)
664 return log_device_debug_errno(dev, r, "Couldn't get syspath from device, ignoring: %m");
665 }
666
667 r = unit_name_from_path(path, ".device", &e);
668 if (r < 0)
669 return log_struct_errno(
670 LOG_WARNING, r,
671 "MESSAGE_ID=" SD_MESSAGE_DEVICE_PATH_NOT_SUITABLE_STR,
672 "DEVICE=%s", path,
673 LOG_MESSAGE("Failed to generate valid unit name from device path '%s', ignoring device: %m",
674 path));
675
676 u = manager_get_unit(m, e);
677 if (u) {
678 /* The device unit can still be present even if the device was unplugged: a mount unit can reference it
679 * hence preventing the GC to have garbaged it. That's desired since the device unit may have a
680 * dependency on the mount unit which was added during the loading of the later. When the device is
681 * plugged the sysfs might not be initialized yet, as we serialize the device's state but do not
682 * serialize the sysfs path across reloads/reexecs. Hence, when coming back from a reload/restart we
683 * might have the state valid, but not the sysfs path. Also, there is another possibility; when multiple
684 * devices have the same devlink (e.g. /dev/disk/by-uuid/xxxx), adding/updating/removing one of the
685 * device causes syspath change. Hence, let's always update sysfs path. */
686
687 /* Let's remove all dependencies generated due to udev properties. We'll re-add whatever is configured
688 * now below. */
689 unit_remove_dependencies(u, UNIT_DEPENDENCY_UDEV);
690
691 } else {
692 r = unit_new_for_name(m, sizeof(Device), e, &new_unit);
693 if (r < 0)
694 return log_device_error_errno(dev, r, "Failed to allocate device unit %s: %m", e);
695
696 u = new_unit;
697
698 unit_add_to_load_queue(u);
699 }
700
701 Device *d = ASSERT_PTR(DEVICE(u));
702
703 if (!d->path) {
704 d->path = strdup(path);
705 if (!d->path)
706 return log_oom();
707 }
708
709 /* If this was created via some dependency and has not actually been seen yet ->sysfs will not be
710 * initialized. Hence initialize it if necessary. */
711 if (sysfs) {
712 r = device_set_sysfs(d, sysfs);
713 if (r < 0)
714 return log_unit_error_errno(u, r, "Failed to set sysfs path %s: %m", sysfs);
715
716 /* The additional systemd udev properties we only interpret for the main object */
717 if (main)
718 (void) device_add_udev_wants(u, dev);
719 }
720
721 (void) device_update_description(u, dev, path);
722
723 /* So the user wants the mount units to be bound to the device but a mount unit might has been seen
724 * by systemd before the device appears on its radar. In this case the device unit is partially
725 * initialized and includes the deps on the mount unit but at that time the "bind mounts" flag wasn't
726 * present. Fix this up now. */
727 if (dev && device_is_bound_by_mounts(d, dev))
728 device_upgrade_mount_deps(u);
729
730 if (units) {
731 r = set_ensure_put(units, NULL, d);
732 if (r < 0)
733 return log_unit_error_errno(u, r, "Failed to store unit: %m");
734 }
735
736 TAKE_PTR(new_unit);
737 return 0;
738 }
739
740 static bool device_is_ready(sd_device *dev) {
741 int r;
742
743 assert(dev);
744
745 if (device_for_action(dev, SD_DEVICE_REMOVE))
746 return false;
747
748 r = device_is_renaming(dev);
749 if (r < 0)
750 log_device_warning_errno(dev, r, "Failed to check if device is renaming, assuming device is not renaming: %m");
751 if (r > 0) {
752 log_device_debug(dev, "Device busy: device is renaming");
753 return false;
754 }
755
756 /* Is it really tagged as 'systemd' right now? */
757 r = sd_device_has_current_tag(dev, "systemd");
758 if (r < 0)
759 log_device_warning_errno(dev, r, "Failed to check if device has \"systemd\" tag, assuming device is not tagged with \"systemd\": %m");
760 if (r == 0)
761 log_device_debug(dev, "Device busy: device is not tagged with \"systemd\"");
762 if (r <= 0)
763 return false;
764
765 r = device_get_property_bool(dev, "SYSTEMD_READY");
766 if (r < 0 && r != -ENOENT)
767 log_device_warning_errno(dev, r, "Failed to get device SYSTEMD_READY property, assuming device does not have \"SYSTEMD_READY\" property: %m");
768 if (r == 0)
769 log_device_debug(dev, "Device busy: SYSTEMD_READY property from device is false");
770
771 return r != 0;
772 }
773
774 static int device_setup_devlink_unit_one(Manager *m, const char *devlink, Set **ready_units, Set **not_ready_units) {
775 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
776 Unit *u;
777
778 assert(m);
779 assert(devlink);
780 assert(ready_units);
781 assert(not_ready_units);
782
783 if (sd_device_new_from_devname(&dev, devlink) >= 0 && device_is_ready(dev))
784 return device_setup_unit(m, dev, devlink, /* main = */ false, ready_units);
785
786 /* the devlink is already removed or not ready */
787 if (device_by_path(m, devlink, &u) < 0)
788 return 0; /* The corresponding .device unit not found. That's fine. */
789
790 return set_ensure_put(not_ready_units, NULL, DEVICE(u));
791 }
792
793 static int device_setup_extra_units(Manager *m, sd_device *dev, Set **ready_units, Set **not_ready_units) {
794 _cleanup_strv_free_ char **aliases = NULL;
795 const char *syspath, *devname = NULL;
796 Device *l;
797 int r;
798
799 assert(m);
800 assert(dev);
801 assert(ready_units);
802 assert(not_ready_units);
803
804 r = sd_device_get_syspath(dev, &syspath);
805 if (r < 0)
806 return r;
807
808 (void) sd_device_get_devname(dev, &devname);
809
810 /* devlink units */
811 FOREACH_DEVICE_DEVLINK(dev, devlink) {
812 /* These are a kind of special devlink. They should be always unique, but neither persistent
813 * nor predictable. Hence, let's refuse them. See also the comments for alias units below. */
814 if (PATH_STARTSWITH_SET(devlink, "/dev/block/", "/dev/char/"))
815 continue;
816
817 (void) device_setup_devlink_unit_one(m, devlink, ready_units, not_ready_units);
818 }
819
820 if (device_is_ready(dev)) {
821 const char *s;
822
823 r = sd_device_get_property_value(dev, "SYSTEMD_ALIAS", &s);
824 if (r < 0 && r != -ENOENT)
825 log_device_warning_errno(dev, r, "Failed to get SYSTEMD_ALIAS property, ignoring: %m");
826 if (r >= 0) {
827 r = strv_split_full(&aliases, s, NULL, EXTRACT_UNQUOTE);
828 if (r < 0)
829 log_device_warning_errno(dev, r, "Failed to parse SYSTEMD_ALIAS property, ignoring: %m");
830 }
831 }
832
833 /* alias units */
834 STRV_FOREACH(alias, aliases) {
835 if (!path_is_absolute(*alias)) {
836 log_device_warning(dev, "The alias \"%s\" specified in SYSTEMD_ALIAS is not an absolute path, ignoring.", *alias);
837 continue;
838 }
839
840 if (!path_is_safe(*alias)) {
841 log_device_warning(dev, "The alias \"%s\" specified in SYSTEMD_ALIAS is not safe, ignoring.", *alias);
842 continue;
843 }
844
845 /* Note, even if the devlink is not persistent, LVM expects /dev/block/ symlink units exist.
846 * To achieve that, they set the path to SYSTEMD_ALIAS. Hence, we cannot refuse aliases start
847 * with /dev/, unfortunately. */
848
849 (void) device_setup_unit(m, dev, *alias, /* main = */ false, ready_units);
850 }
851
852 l = hashmap_get(m->devices_by_sysfs, syspath);
853 LIST_FOREACH(same_sysfs, d, l) {
854 if (!d->path)
855 continue;
856
857 if (path_equal(d->path, syspath))
858 continue; /* This is the main unit. */
859
860 if (devname && path_equal(d->path, devname))
861 continue; /* This is the real device node. */
862
863 if (device_has_devlink(dev, d->path))
864 continue; /* The devlink was already processed in the above loop. */
865
866 if (strv_contains(aliases, d->path))
867 continue; /* This is already processed in the above, and ready. */
868
869 if (path_startswith(d->path, "/dev/"))
870 /* This is a devlink unit. Check existence and update syspath. */
871 (void) device_setup_devlink_unit_one(m, d->path, ready_units, not_ready_units);
872 else
873 /* This is an alias unit of dropped or not ready device. */
874 (void) set_ensure_put(not_ready_units, NULL, d);
875 }
876
877 return 0;
878 }
879
880 static int device_setup_units(Manager *m, sd_device *dev, Set **ready_units, Set **not_ready_units) {
881 const char *syspath, *devname = NULL;
882 int r;
883
884 assert(m);
885 assert(dev);
886 assert(ready_units);
887 assert(not_ready_units);
888
889 r = sd_device_get_syspath(dev, &syspath);
890 if (r < 0)
891 return log_device_debug_errno(dev, r, "Couldn't get syspath from device, ignoring: %m");
892
893 /* First, process the main (that is, points to the syspath) and (real, not symlink) devnode units. */
894 if (device_for_action(dev, SD_DEVICE_REMOVE))
895 /* If the device is removed, the main and devnode units will be removed by
896 * device_update_found_by_sysfs() in device_dispatch_io(). Hence, it is not necessary to
897 * store them to not_ready_units, and we have nothing to do here.
898 *
899 * Note, still we need to process devlink units below, as a devlink previously points to this
900 * device may still exist and now point to another device node. That is, do not forget to
901 * call device_setup_extra_units(). */
902 ;
903 else if (device_is_ready(dev)) {
904 /* Add the main unit named after the syspath. If this one fails, don't bother with the rest,
905 * as this one shall be the main device unit the others just follow. (Compare with how
906 * device_following() is implemented, see below, which looks for the sysfs device.) */
907 r = device_setup_unit(m, dev, syspath, /* main = */ true, ready_units);
908 if (r < 0)
909 return r;
910
911 /* Add an additional unit for the device node */
912 if (sd_device_get_devname(dev, &devname) >= 0)
913 (void) device_setup_unit(m, dev, devname, /* main = */ false, ready_units);
914
915 } else {
916 Unit *u;
917
918 /* If the device exists but not ready, then save the units and unset udev bits later. */
919
920 if (device_by_path(m, syspath, &u) >= 0) {
921 r = set_ensure_put(not_ready_units, NULL, DEVICE(u));
922 if (r < 0)
923 log_unit_debug_errno(u, r, "Failed to store unit, ignoring: %m");
924 }
925
926 if (sd_device_get_devname(dev, &devname) >= 0 &&
927 device_by_path(m, devname, &u) >= 0) {
928 r = set_ensure_put(not_ready_units, NULL, DEVICE(u));
929 if (r < 0)
930 log_unit_debug_errno(u, r, "Failed to store unit, ignoring: %m");
931 }
932 }
933
934 /* Next, add/update additional .device units point to aliases and symlinks. */
935 (void) device_setup_extra_units(m, dev, ready_units, not_ready_units);
936
937 /* Safety check: no unit should be in ready_units and not_ready_units simultaneously. */
938 Unit *u;
939 SET_FOREACH(u, *not_ready_units)
940 if (set_remove(*ready_units, u))
941 log_unit_error(u, "Cannot activate and deactivate the unit simultaneously. Deactivating.");
942
943 return 0;
944 }
945
946 static Unit *device_following(Unit *u) {
947 Device *d = ASSERT_PTR(DEVICE(u)), *first = NULL;
948
949 if (startswith(u->id, "sys-"))
950 return NULL;
951
952 /* Make everybody follow the unit that's named after the sysfs path */
953 LIST_FOREACH(same_sysfs, other, d->same_sysfs_next)
954 if (startswith(UNIT(other)->id, "sys-"))
955 return UNIT(other);
956
957 LIST_FOREACH_BACKWARDS(same_sysfs, other, d->same_sysfs_prev) {
958 if (startswith(UNIT(other)->id, "sys-"))
959 return UNIT(other);
960
961 first = other;
962 }
963
964 return UNIT(first);
965 }
966
967 static int device_following_set(Unit *u, Set **ret) {
968 Device *d = ASSERT_PTR(DEVICE(u));
969 _cleanup_set_free_ Set *set = NULL;
970 int r;
971
972 assert(ret);
973
974 if (LIST_JUST_US(same_sysfs, d)) {
975 *ret = NULL;
976 return 0;
977 }
978
979 set = set_new(NULL);
980 if (!set)
981 return -ENOMEM;
982
983 LIST_FOREACH(same_sysfs, other, d->same_sysfs_next) {
984 r = set_put(set, other);
985 if (r < 0)
986 return r;
987 }
988
989 LIST_FOREACH_BACKWARDS(same_sysfs, other, d->same_sysfs_prev) {
990 r = set_put(set, other);
991 if (r < 0)
992 return r;
993 }
994
995 *ret = TAKE_PTR(set);
996 return 1;
997 }
998
999 static void device_shutdown(Manager *m) {
1000 assert(m);
1001
1002 m->device_monitor = sd_device_monitor_unref(m->device_monitor);
1003 m->devices_by_sysfs = hashmap_free(m->devices_by_sysfs);
1004 }
1005
1006 static void device_enumerate(Manager *m) {
1007 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
1008 int r;
1009
1010 assert(m);
1011
1012 if (!m->device_monitor) {
1013 r = sd_device_monitor_new(&m->device_monitor);
1014 if (r < 0) {
1015 log_error_errno(r, "Failed to allocate device monitor: %m");
1016 goto fail;
1017 }
1018
1019 r = sd_device_monitor_filter_add_match_tag(m->device_monitor, "systemd");
1020 if (r < 0) {
1021 log_error_errno(r, "Failed to add udev tag match: %m");
1022 goto fail;
1023 }
1024
1025 r = sd_device_monitor_attach_event(m->device_monitor, m->event);
1026 if (r < 0) {
1027 log_error_errno(r, "Failed to attach event to device monitor: %m");
1028 goto fail;
1029 }
1030
1031 r = sd_device_monitor_start(m->device_monitor, device_dispatch_io, m);
1032 if (r < 0) {
1033 log_error_errno(r, "Failed to start device monitor: %m");
1034 goto fail;
1035 }
1036 }
1037
1038 r = sd_device_enumerator_new(&e);
1039 if (r < 0) {
1040 log_error_errno(r, "Failed to allocate device enumerator: %m");
1041 goto fail;
1042 }
1043
1044 r = sd_device_enumerator_add_match_tag(e, "systemd");
1045 if (r < 0) {
1046 log_error_errno(r, "Failed to set tag for device enumeration: %m");
1047 goto fail;
1048 }
1049
1050 FOREACH_DEVICE(e, dev) {
1051 _cleanup_set_free_ Set *ready_units = NULL, *not_ready_units = NULL;
1052 Device *d;
1053
1054 if (device_setup_units(m, dev, &ready_units, &not_ready_units) < 0)
1055 continue;
1056
1057 SET_FOREACH(d, ready_units)
1058 device_update_found_one(d, DEVICE_FOUND_UDEV, DEVICE_FOUND_UDEV);
1059 SET_FOREACH(d, not_ready_units)
1060 device_update_found_one(d, DEVICE_NOT_FOUND, DEVICE_FOUND_UDEV);
1061 }
1062
1063 return;
1064
1065 fail:
1066 device_shutdown(m);
1067 }
1068
1069 static void device_propagate_reload(Manager *m, Device *d) {
1070 int r;
1071
1072 assert(m);
1073 assert(d);
1074
1075 if (d->state == DEVICE_DEAD)
1076 return;
1077
1078 r = manager_propagate_reload(m, UNIT(d), JOB_REPLACE, NULL);
1079 if (r < 0)
1080 log_unit_warning_errno(UNIT(d), r, "Failed to propagate reload, ignoring: %m");
1081 }
1082
1083 static void device_remove_old_on_move(Manager *m, sd_device *dev) {
1084 _cleanup_free_ char *syspath_old = NULL;
1085 const char *devpath_old;
1086 int r;
1087
1088 assert(m);
1089 assert(dev);
1090
1091 r = sd_device_get_property_value(dev, "DEVPATH_OLD", &devpath_old);
1092 if (r < 0)
1093 return (void) log_device_debug_errno(dev, r, "Failed to get DEVPATH_OLD= property on 'move' uevent, ignoring: %m");
1094
1095 syspath_old = path_join("/sys", devpath_old);
1096 if (!syspath_old)
1097 return (void) log_oom();
1098
1099 device_update_found_by_sysfs(m, syspath_old, DEVICE_NOT_FOUND, DEVICE_FOUND_MASK);
1100 }
1101
1102 static int device_dispatch_io(sd_device_monitor *monitor, sd_device *dev, void *userdata) {
1103 _cleanup_set_free_ Set *ready_units = NULL, *not_ready_units = NULL;
1104 Manager *m = ASSERT_PTR(userdata);
1105 sd_device_action_t action;
1106 const char *sysfs;
1107 bool ready;
1108 Device *d;
1109 int r;
1110
1111 assert(dev);
1112
1113 log_device_uevent(dev, "Processing udev action");
1114
1115 r = sd_device_get_syspath(dev, &sysfs);
1116 if (r < 0) {
1117 log_device_warning_errno(dev, r, "Failed to get device syspath, ignoring: %m");
1118 return 0;
1119 }
1120
1121 r = sd_device_get_action(dev, &action);
1122 if (r < 0) {
1123 log_device_warning_errno(dev, r, "Failed to get udev action, ignoring: %m");
1124 return 0;
1125 }
1126
1127 log_device_debug(dev, "Got '%s' action on syspath '%s'.", device_action_to_string(action), sysfs);
1128
1129 if (action == SD_DEVICE_MOVE)
1130 device_remove_old_on_move(m, dev);
1131
1132 /* When udevd failed to process the device, SYSTEMD_ALIAS or any other properties may contain invalid
1133 * values. Let's refuse to handle the uevent. */
1134 if (sd_device_get_property_value(dev, "UDEV_WORKER_FAILED", NULL) >= 0) {
1135 int v;
1136
1137 if (device_get_property_int(dev, "UDEV_WORKER_ERRNO", &v) >= 0)
1138 log_device_warning_errno(dev, v, "systemd-udevd failed to process the device, ignoring: %m");
1139 else if (device_get_property_int(dev, "UDEV_WORKER_EXIT_STATUS", &v) >= 0)
1140 log_device_warning(dev, "systemd-udevd failed to process the device with exit status %i, ignoring.", v);
1141 else if (device_get_property_int(dev, "UDEV_WORKER_SIGNAL", &v) >= 0) {
1142 const char *s;
1143 (void) sd_device_get_property_value(dev, "UDEV_WORKER_SIGNAL_NAME", &s);
1144 log_device_warning(dev, "systemd-udevd failed to process the device with signal %i(%s), ignoring.", v, strna(s));
1145 } else
1146 log_device_warning(dev, "systemd-udevd failed to process the device with unknown result, ignoring.");
1147
1148 return 0;
1149 }
1150
1151 /* A change event can signal that a device is becoming ready, in particular if the device is using
1152 * the SYSTEMD_READY logic in udev so we need to reach the else block of the following if, even for
1153 * change events */
1154 ready = device_is_ready(dev);
1155
1156 (void) device_setup_units(m, dev, &ready_units, &not_ready_units);
1157
1158 if (action == SD_DEVICE_REMOVE) {
1159 r = swap_process_device_remove(m, dev);
1160 if (r < 0)
1161 log_device_warning_errno(dev, r, "Failed to process swap device remove event, ignoring: %m");
1162 } else if (ready) {
1163 r = swap_process_device_new(m, dev);
1164 if (r < 0)
1165 log_device_warning_errno(dev, r, "Failed to process swap device new event, ignoring: %m");
1166 }
1167
1168 if (!IN_SET(action, SD_DEVICE_ADD, SD_DEVICE_REMOVE, SD_DEVICE_MOVE))
1169 SET_FOREACH(d, ready_units)
1170 device_propagate_reload(m, d);
1171
1172 if (!set_isempty(ready_units))
1173 manager_dispatch_load_queue(m);
1174
1175 if (action == SD_DEVICE_REMOVE)
1176 /* If we get notified that a device was removed by udev, then it's completely gone, hence
1177 * unset all found bits. Note this affects all .device units still point to the removed
1178 * device. */
1179 device_update_found_by_sysfs(m, sysfs, DEVICE_NOT_FOUND, DEVICE_FOUND_MASK);
1180
1181 /* These devices are found and ready now, set the udev found bit. Note, this is also necessary to do
1182 * on remove uevent, as some devlinks may be updated and now point to other device nodes. */
1183 SET_FOREACH(d, ready_units)
1184 device_update_found_one(d, DEVICE_FOUND_UDEV, DEVICE_FOUND_UDEV);
1185
1186 /* These devices may be nominally around, but not ready for us. Hence unset the udev bit, but leave
1187 * the rest around. This may be redundant for remove uevent, but should be harmless. */
1188 SET_FOREACH(d, not_ready_units)
1189 device_update_found_one(d, DEVICE_NOT_FOUND, DEVICE_FOUND_UDEV);
1190
1191 return 0;
1192 }
1193
1194 void device_found_node(Manager *m, const char *node, DeviceFound found, DeviceFound mask) {
1195 int r;
1196
1197 assert(m);
1198 assert(node);
1199 assert(!FLAGS_SET(mask, DEVICE_FOUND_UDEV));
1200
1201 if (!udev_available())
1202 return;
1203
1204 if (mask == 0)
1205 return;
1206
1207 /* This is called whenever we find a device referenced in /proc/swaps or /proc/self/mounts. Such a device might
1208 * be mounted/enabled at a time where udev has not finished probing it yet, and we thus haven't learned about
1209 * it yet. In this case we will set the device unit to "tentative" state.
1210 *
1211 * This takes a pair of DeviceFound flags parameters. The 'mask' parameter is a bit mask that indicates which
1212 * bits of 'found' to copy into the per-device DeviceFound flags field. Thus, this function may be used to set
1213 * and unset individual bits in a single call, while merging partially with previous state. */
1214
1215 if ((found & mask) != 0) {
1216 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
1217
1218 /* If the device is known in the kernel and newly appeared, then we'll create a device unit for it,
1219 * under the name referenced in /proc/swaps or /proc/self/mountinfo. But first, let's validate if
1220 * everything is alright with the device node. Note that we're fine with missing device nodes,
1221 * but not with badly set up ones. */
1222
1223 r = sd_device_new_from_devname(&dev, node);
1224 if (r == -ENODEV)
1225 log_debug("Could not find device for %s, continuing without device node", node);
1226 else if (r < 0) {
1227 /* Reduce log noise from nodes which are not device nodes by skipping EINVAL. */
1228 if (r != -EINVAL)
1229 log_error_errno(r, "Failed to open %s device, ignoring: %m", node);
1230 return;
1231 }
1232
1233 (void) device_setup_unit(m, dev, node, /* main = */ false, NULL); /* 'dev' may be NULL. */
1234 }
1235
1236 /* Update the device unit's state, should it exist */
1237 (void) device_update_found_by_name(m, node, found, mask);
1238 }
1239
1240 bool device_shall_be_bound_by(Unit *device, Unit *u) {
1241 assert(device);
1242 assert(u);
1243
1244 if (u->type != UNIT_MOUNT)
1245 return false;
1246
1247 return DEVICE(device)->bind_mounts;
1248 }
1249
1250 const UnitVTable device_vtable = {
1251 .object_size = sizeof(Device),
1252 .sections =
1253 "Unit\0"
1254 "Device\0"
1255 "Install\0",
1256
1257 .gc_jobs = true,
1258
1259 .init = device_init,
1260 .done = device_done,
1261 .load = device_load,
1262
1263 .coldplug = device_coldplug,
1264 .catchup = device_catchup,
1265
1266 .serialize = device_serialize,
1267 .deserialize_item = device_deserialize_item,
1268
1269 .dump = device_dump,
1270
1271 .active_state = device_active_state,
1272 .sub_state_to_string = device_sub_state_to_string,
1273
1274 .following = device_following,
1275 .following_set = device_following_set,
1276
1277 .enumerate = device_enumerate,
1278 .shutdown = device_shutdown,
1279 .supported = udev_available,
1280
1281 .status_message_formats = {
1282 .starting_stopping = {
1283 [0] = "Expecting device %s...",
1284 [1] = "Waiting for device %s to disappear...",
1285 },
1286 .finished_start_job = {
1287 [JOB_DONE] = "Found device %s.",
1288 [JOB_TIMEOUT] = "Timed out waiting for device %s.",
1289 },
1290 },
1291 };