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