chiark / gitweb /
man: document pidns containers
[elogind.git] / src / device.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <errno.h>
23 #include <sys/epoll.h>
24 #include <libudev.h>
25
26 #include "unit.h"
27 #include "device.h"
28 #include "strv.h"
29 #include "log.h"
30 #include "unit-name.h"
31 #include "dbus-device.h"
32 #include "def.h"
33
34 static const UnitActiveState state_translation_table[_DEVICE_STATE_MAX] = {
35         [DEVICE_DEAD] = UNIT_INACTIVE,
36         [DEVICE_PLUGGED] = UNIT_ACTIVE
37 };
38
39 static void device_unset_sysfs(Device *d) {
40         Device *first;
41
42         assert(d);
43
44         if (!d->sysfs)
45                 return;
46
47         /* Remove this unit from the chain of devices which share the
48          * same sysfs path. */
49         first = hashmap_get(d->meta.manager->devices_by_sysfs, d->sysfs);
50         LIST_REMOVE(Device, same_sysfs, first, d);
51
52         if (first)
53                 hashmap_remove_and_replace(d->meta.manager->devices_by_sysfs, d->sysfs, first->sysfs, first);
54         else
55                 hashmap_remove(d->meta.manager->devices_by_sysfs, d->sysfs);
56
57         free(d->sysfs);
58         d->sysfs = NULL;
59 }
60
61 static void device_init(Unit *u) {
62         Device *d = DEVICE(u);
63
64         assert(d);
65         assert(d->meta.load_state == UNIT_STUB);
66
67         /* In contrast to all other unit types we timeout jobs waiting
68          * for devices by default. This is because they otherwise wait
69          * indefinitely for plugged in devices, something which cannot
70          * happen for the other units since their operations time out
71          * anyway. */
72         d->meta.job_timeout = DEFAULT_TIMEOUT_USEC;
73 }
74
75 static void device_done(Unit *u) {
76         Device *d = DEVICE(u);
77
78         assert(d);
79
80         device_unset_sysfs(d);
81 }
82
83 static void device_set_state(Device *d, DeviceState state) {
84         DeviceState old_state;
85         assert(d);
86
87         old_state = d->state;
88         d->state = state;
89
90         if (state != old_state)
91                 log_debug("%s changed %s -> %s",
92                           d->meta.id,
93                           device_state_to_string(old_state),
94                           device_state_to_string(state));
95
96         unit_notify(UNIT(d), state_translation_table[old_state], state_translation_table[state], true);
97 }
98
99 static int device_coldplug(Unit *u) {
100         Device *d = DEVICE(u);
101
102         assert(d);
103         assert(d->state == DEVICE_DEAD);
104
105         if (d->sysfs)
106                 device_set_state(d, DEVICE_PLUGGED);
107
108         return 0;
109 }
110
111 static void device_dump(Unit *u, FILE *f, const char *prefix) {
112         Device *d = DEVICE(u);
113
114         assert(d);
115
116         fprintf(f,
117                 "%sDevice State: %s\n"
118                 "%sSysfs Path: %s\n",
119                 prefix, device_state_to_string(d->state),
120                 prefix, strna(d->sysfs));
121 }
122
123 static UnitActiveState device_active_state(Unit *u) {
124         assert(u);
125
126         return state_translation_table[DEVICE(u)->state];
127 }
128
129 static const char *device_sub_state_to_string(Unit *u) {
130         assert(u);
131
132         return device_state_to_string(DEVICE(u)->state);
133 }
134
135 static int device_add_escaped_name(Unit *u, const char *dn) {
136         char *e;
137         int r;
138
139         assert(u);
140         assert(dn);
141         assert(dn[0] == '/');
142
143         if (!(e = unit_name_from_path(dn, ".device")))
144                 return -ENOMEM;
145
146         r = unit_add_name(u, e);
147         free(e);
148
149         if (r < 0 && r != -EEXIST)
150                 return r;
151
152         return 0;
153 }
154
155 static int device_find_escape_name(Manager *m, const char *dn, Unit **_u) {
156         char *e;
157         Unit *u;
158
159         assert(m);
160         assert(dn);
161         assert(dn[0] == '/');
162         assert(_u);
163
164         if (!(e = unit_name_from_path(dn, ".device")))
165                 return -ENOMEM;
166
167         u = manager_get_unit(m, e);
168         free(e);
169
170         if (u) {
171                 *_u = u;
172                 return 1;
173         }
174
175         return 0;
176 }
177
178 static int device_update_unit(Manager *m, struct udev_device *dev, const char *path, bool main) {
179         const char *sysfs, *model;
180         Unit *u = NULL;
181         int r;
182         bool delete;
183
184         assert(m);
185
186         if (!(sysfs = udev_device_get_syspath(dev)))
187                 return -ENOMEM;
188
189         if ((r = device_find_escape_name(m, path, &u)) < 0)
190                 return r;
191
192         if (u && DEVICE(u)->sysfs && !path_equal(DEVICE(u)->sysfs, sysfs))
193                 return -EEXIST;
194
195         if (!u) {
196                 delete = true;
197
198                 if (!(u = unit_new(m)))
199                         return -ENOMEM;
200
201                 if ((r = device_add_escaped_name(u, path)) < 0)
202                         goto fail;
203
204                 unit_add_to_load_queue(u);
205         } else
206                 delete = false;
207
208         /* If this was created via some dependency and has not
209          * actually been seen yet ->sysfs will not be
210          * initialized. Hence initialize it if necessary. */
211
212         if (!DEVICE(u)->sysfs) {
213                 Device *first;
214
215                 if (!(DEVICE(u)->sysfs = strdup(sysfs))) {
216                         r = -ENOMEM;
217                         goto fail;
218                 }
219
220                 if (!m->devices_by_sysfs)
221                         if (!(m->devices_by_sysfs = hashmap_new(string_hash_func, string_compare_func))) {
222                                 r = -ENOMEM;
223                                 goto fail;
224                         }
225
226                 first = hashmap_get(m->devices_by_sysfs, sysfs);
227                 LIST_PREPEND(Device, same_sysfs, first, DEVICE(u));
228
229                 if ((r = hashmap_replace(m->devices_by_sysfs, DEVICE(u)->sysfs, first)) < 0)
230                         goto fail;
231         }
232
233         if ((model = udev_device_get_property_value(dev, "ID_MODEL_FROM_DATABASE")) ||
234             (model = udev_device_get_property_value(dev, "ID_MODEL"))) {
235                 if ((r = unit_set_description(u, model)) < 0)
236                         goto fail;
237         } else
238                 if ((r = unit_set_description(u, path)) < 0)
239                         goto fail;
240
241         if (main) {
242                 /* The additional systemd udev properties we only
243                  * interpret for the main object */
244                 const char *wants, *alias;
245
246                 if ((alias = udev_device_get_property_value(dev, "SYSTEMD_ALIAS"))) {
247                         if (!is_path(alias))
248                                 log_warning("SYSTEMD_ALIAS for %s is not a path, ignoring: %s", sysfs, alias);
249                         else {
250                                 if ((r = device_add_escaped_name(u, alias)) < 0)
251                                         goto fail;
252                         }
253                 }
254
255                 if ((wants = udev_device_get_property_value(dev, "SYSTEMD_WANTS"))) {
256                         char *state, *w;
257                         size_t l;
258
259                         FOREACH_WORD_QUOTED(w, l, wants, state) {
260                                 char *e;
261
262                                 if (!(e = strndup(w, l))) {
263                                         r = -ENOMEM;
264                                         goto fail;
265                                 }
266
267                                 r = unit_add_dependency_by_name(u, UNIT_WANTS, e, NULL, true);
268                                 free(e);
269
270                                 if (r < 0)
271                                         goto fail;
272                         }
273                 }
274         }
275
276         unit_add_to_dbus_queue(u);
277         return 0;
278
279 fail:
280         log_warning("Failed to load device unit: %s", strerror(-r));
281
282         if (delete && u)
283                 unit_free(u);
284
285         return r;
286 }
287
288 static int device_process_new_device(Manager *m, struct udev_device *dev, bool update_state) {
289         const char *sysfs, *dn;
290         struct udev_list_entry *item = NULL, *first = NULL;
291
292         assert(m);
293
294         if (!(sysfs = udev_device_get_syspath(dev)))
295                 return -ENOMEM;
296
297         /* Add the main unit named after the sysfs path */
298         device_update_unit(m, dev, sysfs, true);
299
300         /* Add an additional unit for the device node */
301         if ((dn = udev_device_get_devnode(dev)))
302                 device_update_unit(m, dev, dn, false);
303
304         /* Add additional units for all symlinks */
305         first = udev_device_get_devlinks_list_entry(dev);
306         udev_list_entry_foreach(item, first) {
307                 const char *p;
308                 struct stat st;
309
310                 /* Don't bother with the /dev/block links */
311                 p = udev_list_entry_get_name(item);
312
313                 if (path_startswith(p, "/dev/block/") ||
314                     path_startswith(p, "/dev/char/"))
315                         continue;
316
317                 /* Verify that the symlink in the FS actually belongs
318                  * to this device. This is useful to deal with
319                  * conflicting devices, e.g. when two disks want the
320                  * same /dev/disk/by-label/xxx link because they have
321                  * the same label. We want to make sure that the same
322                  * device that won the symlink wins in systemd, so we
323                  * check the device node major/minor*/
324                 if (stat(p, &st) >= 0)
325                         if ((!S_ISBLK(st.st_mode) && !S_ISCHR(st.st_mode)) ||
326                             st.st_rdev != udev_device_get_devnum(dev))
327                                 continue;
328
329                 device_update_unit(m, dev, p, false);
330         }
331
332         if (update_state) {
333                 Device *d, *l;
334
335                 manager_dispatch_load_queue(m);
336
337                 l = hashmap_get(m->devices_by_sysfs, sysfs);
338                 LIST_FOREACH(same_sysfs, d, l)
339                         device_set_state(d, DEVICE_PLUGGED);
340         }
341
342         return 0;
343 }
344
345 static int device_process_path(Manager *m, const char *path, bool update_state) {
346         int r;
347         struct udev_device *dev;
348
349         assert(m);
350         assert(path);
351
352         if (!(dev = udev_device_new_from_syspath(m->udev, path))) {
353                 log_warning("Failed to get udev device object from udev for path %s.", path);
354                 return -ENOMEM;
355         }
356
357         r = device_process_new_device(m, dev, update_state);
358         udev_device_unref(dev);
359         return r;
360 }
361
362 static int device_process_removed_device(Manager *m, struct udev_device *dev) {
363         const char *sysfs;
364         Device *d;
365
366         assert(m);
367         assert(dev);
368
369         if (!(sysfs = udev_device_get_syspath(dev)))
370                 return -ENOMEM;
371
372         /* Remove all units of this sysfs path */
373         while ((d = hashmap_get(m->devices_by_sysfs, sysfs))) {
374                 device_unset_sysfs(d);
375                 device_set_state(d, DEVICE_DEAD);
376         }
377
378         return 0;
379 }
380
381 static Unit *device_following(Unit *u) {
382         Device *d = DEVICE(u);
383         Device *other, *first = NULL;
384
385         assert(d);
386
387         if (startswith(u->meta.id, "sys-"))
388                 return NULL;
389
390         /* Make everybody follow the unit that's named after the sysfs path */
391         for (other = d->same_sysfs_next; other; other = other->same_sysfs_next)
392                 if (startswith(other->meta.id, "sys-"))
393                         return UNIT(other);
394
395         for (other = d->same_sysfs_prev; other; other = other->same_sysfs_prev) {
396                 if (startswith(other->meta.id, "sys-"))
397                         return UNIT(other);
398
399                 first = other;
400         }
401
402         return UNIT(first);
403 }
404
405 static int device_following_set(Unit *u, Set **_s) {
406         Device *d = DEVICE(u);
407         Device *other;
408         Set *s;
409         int r;
410
411         assert(d);
412         assert(_s);
413
414         if (!d->same_sysfs_prev && !d->same_sysfs_next) {
415                 *_s = NULL;
416                 return 0;
417         }
418
419         if (!(s = set_new(NULL, NULL)))
420                 return -ENOMEM;
421
422         for (other = d->same_sysfs_next; other; other = other->same_sysfs_next)
423                 if ((r = set_put(s, other)) < 0)
424                         goto fail;
425
426         for (other = d->same_sysfs_prev; other; other = other->same_sysfs_prev)
427                 if ((r = set_put(s, other)) < 0)
428                         goto fail;
429
430         *_s = s;
431         return 1;
432
433 fail:
434         set_free(s);
435         return r;
436 }
437
438 static void device_shutdown(Manager *m) {
439         assert(m);
440
441         if (m->udev_monitor) {
442                 udev_monitor_unref(m->udev_monitor);
443                 m->udev_monitor = NULL;
444         }
445
446         if (m->udev) {
447                 udev_unref(m->udev);
448                 m->udev = NULL;
449         }
450
451         hashmap_free(m->devices_by_sysfs);
452         m->devices_by_sysfs = NULL;
453 }
454
455 static int device_enumerate(Manager *m) {
456         struct epoll_event ev;
457         int r;
458         struct udev_enumerate *e = NULL;
459         struct udev_list_entry *item = NULL, *first = NULL;
460
461         assert(m);
462
463         if (!m->udev) {
464                 if (!(m->udev = udev_new()))
465                         return -ENOMEM;
466
467                 if (!(m->udev_monitor = udev_monitor_new_from_netlink(m->udev, "udev"))) {
468                         r = -ENOMEM;
469                         goto fail;
470                 }
471
472                 /* This will fail if we are unprivileged, but that
473                  * should not matter much, as user instances won't run
474                  * during boot. */
475                 udev_monitor_set_receive_buffer_size(m->udev_monitor, 128*1024*1024);
476
477                 if (udev_monitor_filter_add_match_tag(m->udev_monitor, "systemd") < 0) {
478                         r = -ENOMEM;
479                         goto fail;
480                 }
481
482                 if (udev_monitor_enable_receiving(m->udev_monitor) < 0) {
483                         r = -EIO;
484                         goto fail;
485                 }
486
487                 m->udev_watch.type = WATCH_UDEV;
488                 m->udev_watch.fd = udev_monitor_get_fd(m->udev_monitor);
489
490                 zero(ev);
491                 ev.events = EPOLLIN;
492                 ev.data.ptr = &m->udev_watch;
493
494                 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->udev_watch.fd, &ev) < 0)
495                         return -errno;
496         }
497
498         if (!(e = udev_enumerate_new(m->udev))) {
499                 r = -ENOMEM;
500                 goto fail;
501         }
502         if (udev_enumerate_add_match_tag(e, "systemd") < 0) {
503                 r = -EIO;
504                 goto fail;
505         }
506
507         if (udev_enumerate_scan_devices(e) < 0) {
508                 r = -EIO;
509                 goto fail;
510         }
511
512         first = udev_enumerate_get_list_entry(e);
513         udev_list_entry_foreach(item, first)
514                 device_process_path(m, udev_list_entry_get_name(item), false);
515
516         udev_enumerate_unref(e);
517         return 0;
518
519 fail:
520         if (e)
521                 udev_enumerate_unref(e);
522
523         device_shutdown(m);
524         return r;
525 }
526
527 void device_fd_event(Manager *m, int events) {
528         struct udev_device *dev;
529         int r;
530         const char *action, *ready;
531
532         assert(m);
533
534         if (events != EPOLLIN) {
535                 static RATELIMIT_DEFINE(limit, 10*USEC_PER_SEC, 5);
536
537                 if (!ratelimit_test(&limit))
538                         log_error("Failed to get udev event: %m");
539                 if (!(events & EPOLLIN))
540                         return;
541         }
542
543         if (!(dev = udev_monitor_receive_device(m->udev_monitor))) {
544                 /*
545                  * libudev might filter-out devices which pass the bloom filter,
546                  * so getting NULL here is not necessarily an error
547                  */
548                 return;
549         }
550
551         if (!(action = udev_device_get_action(dev))) {
552                 log_error("Failed to get udev action string.");
553                 goto fail;
554         }
555
556         ready = udev_device_get_property_value(dev, "SYSTEMD_READY");
557
558         if (streq(action, "remove") || (ready && parse_boolean(ready) == 0)) {
559                 if ((r = device_process_removed_device(m, dev)) < 0) {
560                         log_error("Failed to process udev device event: %s", strerror(-r));
561                         goto fail;
562                 }
563         } else {
564                 if ((r = device_process_new_device(m, dev, true)) < 0) {
565                         log_error("Failed to process udev device event: %s", strerror(-r));
566                         goto fail;
567                 }
568         }
569
570 fail:
571         udev_device_unref(dev);
572 }
573
574 static const char* const device_state_table[_DEVICE_STATE_MAX] = {
575         [DEVICE_DEAD] = "dead",
576         [DEVICE_PLUGGED] = "plugged"
577 };
578
579 DEFINE_STRING_TABLE_LOOKUP(device_state, DeviceState);
580
581 const UnitVTable device_vtable = {
582         .suffix = ".device",
583
584         .no_instances = true,
585         .no_snapshots = true,
586         .no_isolate = true,
587
588         .init = device_init,
589
590         .load = unit_load_fragment_and_dropin_optional,
591         .done = device_done,
592         .coldplug = device_coldplug,
593
594         .dump = device_dump,
595
596         .active_state = device_active_state,
597         .sub_state_to_string = device_sub_state_to_string,
598
599         .bus_interface = "org.freedesktop.systemd1.Device",
600         .bus_message_handler = bus_device_message_handler,
601         .bus_invalidating_properties =  bus_device_invalidating_properties,
602
603         .following = device_following,
604         .following_set = device_following_set,
605
606         .enumerate = device_enumerate,
607         .shutdown = device_shutdown
608 };