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