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