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