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