chiark / gitweb /
2ad60721aa40f2415020324eef9c10d52a48cc07
[elogind.git] / src / manager.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
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 <assert.h>
23 #include <errno.h>
24 #include <string.h>
25 #include <sys/epoll.h>
26 #include <signal.h>
27 #include <sys/signalfd.h>
28 #include <sys/wait.h>
29 #include <unistd.h>
30 #include <utmpx.h>
31 #include <sys/poll.h>
32 #include <sys/reboot.h>
33 #include <sys/ioctl.h>
34 #include <linux/kd.h>
35 #include <libcgroup.h>
36 #include <termios.h>
37 #include <fcntl.h>
38 #include <sys/types.h>
39 #include <sys/stat.h>
40
41 #include "manager.h"
42 #include "hashmap.h"
43 #include "macro.h"
44 #include "strv.h"
45 #include "log.h"
46 #include "util.h"
47 #include "ratelimit.h"
48 #include "cgroup.h"
49 #include "mount-setup.h"
50 #include "utmp-wtmp.h"
51 #include "unit-name.h"
52 #include "dbus-unit.h"
53 #include "dbus-job.h"
54 #include "missing.h"
55 #include "path-lookup.h"
56
57 /* As soon as 16 units are in our GC queue, make sure to run a gc sweep */
58 #define GC_QUEUE_ENTRIES_MAX 16
59
60 /* As soon as 5s passed since a unit was added to our GC queue, make sure to run a gc sweep */
61 #define GC_QUEUE_USEC_MAX (10*USEC_PER_SEC)
62
63 /* Where clients shall send notification messages to */
64 #define NOTIFY_SOCKET "/org/freedesktop/systemd1/notify"
65
66 static int manager_setup_notify(Manager *m) {
67         union {
68                 struct sockaddr sa;
69                 struct sockaddr_un un;
70         } sa;
71         struct epoll_event ev;
72         char *ne[2], **t;
73         int one = 1;
74
75         assert(m);
76
77         m->notify_watch.type = WATCH_NOTIFY;
78         if ((m->notify_watch.fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
79                 log_error("Failed to allocate notification socket: %m");
80                 return -errno;
81         }
82
83         zero(sa);
84         sa.sa.sa_family = AF_UNIX;
85
86         if (m->running_as == MANAGER_SESSION)
87                 snprintf(sa.un.sun_path+1, sizeof(sa.un.sun_path)-1, NOTIFY_SOCKET "/%llu", random_ull());
88         else
89                 strncpy(sa.un.sun_path+1, NOTIFY_SOCKET, sizeof(sa.un.sun_path)-1);
90
91         if (bind(m->notify_watch.fd, &sa.sa, sizeof(sa)) < 0) {
92                 log_error("bind() failed: %m");
93                 return -errno;
94         }
95
96         if (setsockopt(m->notify_watch.fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0) {
97                 log_error("SO_PASSCRED failed: %m");
98                 return -errno;
99         }
100
101         zero(ev);
102         ev.events = EPOLLIN;
103         ev.data.ptr = &m->notify_watch;
104
105         if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->notify_watch.fd, &ev) < 0)
106                 return -errno;
107
108         if (asprintf(&ne[0], "NOTIFY_SOCKET=@%s", sa.un.sun_path+1) < 0)
109                 return -ENOMEM;
110
111         ne[1] = NULL;
112         t = strv_env_merge(2, m->environment, ne);
113         free(ne[0]);
114
115         if (!t)
116                 return -ENOMEM;
117
118         strv_free(m->environment);
119         m->environment = t;
120
121         return 0;
122 }
123
124 static int enable_special_signals(Manager *m) {
125         char fd;
126
127         assert(m);
128
129         /* Enable that we get SIGINT on control-alt-del */
130         if (reboot(RB_DISABLE_CAD) < 0)
131                 log_warning("Failed to enable ctrl-alt-del handling: %m");
132
133         if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY)) < 0)
134                 log_warning("Failed to open /dev/tty0: %m");
135         else {
136                 /* Enable that we get SIGWINCH on kbrequest */
137                 if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
138                         log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
139
140                 close_nointr_nofail(fd);
141         }
142
143         return 0;
144 }
145
146 static int manager_setup_signals(Manager *m) {
147         sigset_t mask;
148         struct epoll_event ev;
149         struct sigaction sa;
150
151         assert(m);
152
153         /* We are not interested in SIGSTOP and friends. */
154         zero(sa);
155         sa.sa_handler = SIG_DFL;
156         sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
157         assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
158
159         assert_se(sigemptyset(&mask) == 0);
160
161         sigset_add_many(&mask,
162                         SIGCHLD,     /* Child died */
163                         SIGTERM,     /* Reexecute daemon */
164                         SIGHUP,      /* Reload configuration */
165                         SIGUSR1,     /* systemd/upstart: reconnect to D-Bus */
166                         SIGUSR2,     /* systemd: dump status */
167                         SIGINT,      /* Kernel sends us this on control-alt-del */
168                         SIGWINCH,    /* Kernel sends us this on kbrequest (alt-arrowup) */
169                         SIGPWR,      /* Some kernel drivers and upsd send us this on power failure */
170                         SIGRTMIN+0,  /* systemd: start default.target */
171                         SIGRTMIN+1,  /* systemd: start rescue.target */
172                         SIGRTMIN+2,  /* systemd: isolate emergency.target */
173                         SIGRTMIN+3,  /* systemd: start halt.target */
174                         SIGRTMIN+4,  /* systemd: start poweroff.target */
175                         SIGRTMIN+5,  /* systemd: start reboot.target */
176                         -1);
177         assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
178
179         m->signal_watch.type = WATCH_SIGNAL;
180         if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
181                 return -errno;
182
183         zero(ev);
184         ev.events = EPOLLIN;
185         ev.data.ptr = &m->signal_watch;
186
187         if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
188                 return -errno;
189
190         if (m->running_as == MANAGER_INIT)
191                 return enable_special_signals(m);
192
193         return 0;
194 }
195
196 int manager_new(ManagerRunningAs running_as, bool confirm_spawn, Manager **_m) {
197         Manager *m;
198         int r = -ENOMEM;
199
200         assert(_m);
201         assert(running_as >= 0);
202         assert(running_as < _MANAGER_RUNNING_AS_MAX);
203
204         if (!(m = new0(Manager, 1)))
205                 return -ENOMEM;
206
207         timestamp_get(&m->startup_timestamp);
208
209         m->running_as = running_as;
210         m->confirm_spawn = confirm_spawn;
211         m->name_data_slot = -1;
212         m->exit_code = _MANAGER_EXIT_CODE_INVALID;
213
214         m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = m->dev_autofs_fd = -1;
215         m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
216
217         if (!(m->environment = strv_copy(environ)))
218                 goto fail;
219
220         if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
221                 goto fail;
222
223         if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
224                 goto fail;
225
226         if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
227                 goto fail;
228
229         if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
230                 goto fail;
231
232         if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
233                 goto fail;
234
235         if (!(m->watch_bus = hashmap_new(string_hash_func, string_compare_func)))
236                 goto fail;
237
238         if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
239                 goto fail;
240
241         if ((r = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
242                 goto fail;
243
244         if ((r = manager_setup_signals(m)) < 0)
245                 goto fail;
246
247         if ((r = manager_setup_cgroup(m)) < 0)
248                 goto fail;
249
250         if ((r = manager_setup_notify(m)) < 0)
251                 goto fail;
252
253         /* Try to connect to the busses, if possible. */
254         if ((r = bus_init_system(m)) < 0 ||
255             (r = bus_init_api(m)) < 0)
256                 goto fail;
257
258         *_m = m;
259         return 0;
260
261 fail:
262         manager_free(m);
263         return r;
264 }
265
266 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
267         Meta *meta;
268         unsigned n = 0;
269
270         assert(m);
271
272         while ((meta = m->cleanup_queue)) {
273                 assert(meta->in_cleanup_queue);
274
275                 unit_free(UNIT(meta));
276                 n++;
277         }
278
279         return n;
280 }
281
282 enum {
283         GC_OFFSET_IN_PATH,  /* This one is on the path we were travelling */
284         GC_OFFSET_UNSURE,   /* No clue */
285         GC_OFFSET_GOOD,     /* We still need this unit */
286         GC_OFFSET_BAD,      /* We don't need this unit anymore */
287         _GC_OFFSET_MAX
288 };
289
290 static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
291         Iterator i;
292         Unit *other;
293         bool is_bad;
294
295         assert(u);
296
297         if (u->meta.gc_marker == gc_marker + GC_OFFSET_GOOD ||
298             u->meta.gc_marker == gc_marker + GC_OFFSET_BAD ||
299             u->meta.gc_marker == gc_marker + GC_OFFSET_IN_PATH)
300                 return;
301
302         if (u->meta.in_cleanup_queue)
303                 goto bad;
304
305         if (unit_check_gc(u))
306                 goto good;
307
308         u->meta.gc_marker = gc_marker + GC_OFFSET_IN_PATH;
309
310         is_bad = true;
311
312         SET_FOREACH(other, u->meta.dependencies[UNIT_REFERENCED_BY], i) {
313                 unit_gc_sweep(other, gc_marker);
314
315                 if (other->meta.gc_marker == gc_marker + GC_OFFSET_GOOD)
316                         goto good;
317
318                 if (other->meta.gc_marker != gc_marker + GC_OFFSET_BAD)
319                         is_bad = false;
320         }
321
322         if (is_bad)
323                 goto bad;
324
325         /* We were unable to find anything out about this entry, so
326          * let's investigate it later */
327         u->meta.gc_marker = gc_marker + GC_OFFSET_UNSURE;
328         unit_add_to_gc_queue(u);
329         return;
330
331 bad:
332         /* We definitely know that this one is not useful anymore, so
333          * let's mark it for deletion */
334         u->meta.gc_marker = gc_marker + GC_OFFSET_BAD;
335         unit_add_to_cleanup_queue(u);
336         return;
337
338 good:
339         u->meta.gc_marker = gc_marker + GC_OFFSET_GOOD;
340 }
341
342 static unsigned manager_dispatch_gc_queue(Manager *m) {
343         Meta *meta;
344         unsigned n = 0;
345         unsigned gc_marker;
346
347         assert(m);
348
349         if ((m->n_in_gc_queue < GC_QUEUE_ENTRIES_MAX) &&
350             (m->gc_queue_timestamp <= 0 ||
351              (m->gc_queue_timestamp + GC_QUEUE_USEC_MAX) > now(CLOCK_MONOTONIC)))
352                 return 0;
353
354         log_debug("Running GC...");
355
356         m->gc_marker += _GC_OFFSET_MAX;
357         if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
358                 m->gc_marker = 1;
359
360         gc_marker = m->gc_marker;
361
362         while ((meta = m->gc_queue)) {
363                 assert(meta->in_gc_queue);
364
365                 unit_gc_sweep(UNIT(meta), gc_marker);
366
367                 LIST_REMOVE(Meta, gc_queue, m->gc_queue, meta);
368                 meta->in_gc_queue = false;
369
370                 n++;
371
372                 if (meta->gc_marker == gc_marker + GC_OFFSET_BAD ||
373                     meta->gc_marker == gc_marker + GC_OFFSET_UNSURE) {
374                         log_debug("Collecting %s", meta->id);
375                         meta->gc_marker = gc_marker + GC_OFFSET_BAD;
376                         unit_add_to_cleanup_queue(UNIT(meta));
377                 }
378         }
379
380         m->n_in_gc_queue = 0;
381         m->gc_queue_timestamp = 0;
382
383         return n;
384 }
385
386 static void manager_clear_jobs_and_units(Manager *m) {
387         Job *j;
388         Unit *u;
389
390         assert(m);
391
392         while ((j = hashmap_first(m->transaction_jobs)))
393                 job_free(j);
394
395         while ((u = hashmap_first(m->units)))
396                 unit_free(u);
397
398         manager_dispatch_cleanup_queue(m);
399
400         assert(!m->load_queue);
401         assert(!m->run_queue);
402         assert(!m->dbus_unit_queue);
403         assert(!m->dbus_job_queue);
404         assert(!m->cleanup_queue);
405         assert(!m->gc_queue);
406
407         assert(hashmap_isempty(m->transaction_jobs));
408         assert(hashmap_isempty(m->jobs));
409         assert(hashmap_isempty(m->units));
410 }
411
412 void manager_free(Manager *m) {
413         UnitType c;
414
415         assert(m);
416
417         manager_clear_jobs_and_units(m);
418
419         for (c = 0; c < _UNIT_TYPE_MAX; c++)
420                 if (unit_vtable[c]->shutdown)
421                         unit_vtable[c]->shutdown(m);
422
423         /* If we reexecute ourselves, we keep the root cgroup
424          * around */
425         manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
426
427         bus_done_api(m);
428         bus_done_system(m);
429
430         hashmap_free(m->units);
431         hashmap_free(m->jobs);
432         hashmap_free(m->transaction_jobs);
433         hashmap_free(m->watch_pids);
434         hashmap_free(m->watch_bus);
435
436         if (m->epoll_fd >= 0)
437                 close_nointr_nofail(m->epoll_fd);
438         if (m->signal_watch.fd >= 0)
439                 close_nointr_nofail(m->signal_watch.fd);
440         if (m->notify_watch.fd >= 0)
441                 close_nointr_nofail(m->notify_watch.fd);
442
443         lookup_paths_free(&m->lookup_paths);
444         strv_free(m->environment);
445
446         free(m->cgroup_controller);
447         free(m->cgroup_hierarchy);
448
449         hashmap_free(m->cgroup_bondings);
450
451         free(m);
452 }
453
454 int manager_enumerate(Manager *m) {
455         int r = 0, q;
456         UnitType c;
457
458         assert(m);
459
460         /* Let's ask every type to load all units from disk/kernel
461          * that it might know */
462         for (c = 0; c < _UNIT_TYPE_MAX; c++)
463                 if (unit_vtable[c]->enumerate)
464                         if ((q = unit_vtable[c]->enumerate(m)) < 0)
465                                 r = q;
466
467         manager_dispatch_load_queue(m);
468         return r;
469 }
470
471 int manager_coldplug(Manager *m) {
472         int r = 0, q;
473         Iterator i;
474         Unit *u;
475         char *k;
476
477         assert(m);
478
479         /* Then, let's set up their initial state. */
480         HASHMAP_FOREACH_KEY(u, k, m->units, i) {
481
482                 /* ignore aliases */
483                 if (u->meta.id != k)
484                         continue;
485
486                 if ((q = unit_coldplug(u)) < 0)
487                         r = q;
488         }
489
490         return r;
491 }
492
493 int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
494         int r, q;
495
496         assert(m);
497
498         /* First, enumerate what we can from all config files */
499         r = manager_enumerate(m);
500
501         /* Second, deserialize if there is something to deserialize */
502         if (serialization)
503                 if ((q = manager_deserialize(m, serialization, fds)) < 0)
504                         r = q;
505
506         /* Third, fire things up! */
507         if ((q = manager_coldplug(m)) < 0)
508                 r = q;
509
510         /* Now that the initial devices are available, let's see if we
511          * can write the utmp file */
512         manager_write_utmp_reboot(m);
513
514         return r;
515 }
516
517 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
518         assert(m);
519         assert(j);
520
521         /* Deletes one job from the transaction */
522
523         manager_transaction_unlink_job(m, j, delete_dependencies);
524
525         if (!j->installed)
526                 job_free(j);
527 }
528
529 static void transaction_delete_unit(Manager *m, Unit *u) {
530         Job *j;
531
532         /* Deletes all jobs associated with a certain unit from the
533          * transaction */
534
535         while ((j = hashmap_get(m->transaction_jobs, u)))
536                 transaction_delete_job(m, j, true);
537 }
538
539 static void transaction_clean_dependencies(Manager *m) {
540         Iterator i;
541         Job *j;
542
543         assert(m);
544
545         /* Drops all dependencies of all installed jobs */
546
547         HASHMAP_FOREACH(j, m->jobs, i) {
548                 while (j->subject_list)
549                         job_dependency_free(j->subject_list);
550                 while (j->object_list)
551                         job_dependency_free(j->object_list);
552         }
553
554         assert(!m->transaction_anchor);
555 }
556
557 static void transaction_abort(Manager *m) {
558         Job *j;
559
560         assert(m);
561
562         while ((j = hashmap_first(m->transaction_jobs)))
563                 if (j->installed)
564                         transaction_delete_job(m, j, true);
565                 else
566                         job_free(j);
567
568         assert(hashmap_isempty(m->transaction_jobs));
569
570         transaction_clean_dependencies(m);
571 }
572
573 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
574         JobDependency *l;
575
576         assert(m);
577
578         /* A recursive sweep through the graph that marks all units
579          * that matter to the anchor job, i.e. are directly or
580          * indirectly a dependency of the anchor job via paths that
581          * are fully marked as mattering. */
582
583         if (j)
584                 l = j->subject_list;
585         else
586                 l = m->transaction_anchor;
587
588         LIST_FOREACH(subject, l, l) {
589
590                 /* This link does not matter */
591                 if (!l->matters)
592                         continue;
593
594                 /* This unit has already been marked */
595                 if (l->object->generation == generation)
596                         continue;
597
598                 l->object->matters_to_anchor = true;
599                 l->object->generation = generation;
600
601                 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
602         }
603 }
604
605 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
606         JobDependency *l, *last;
607
608         assert(j);
609         assert(other);
610         assert(j->unit == other->unit);
611         assert(!j->installed);
612
613         /* Merges 'other' into 'j' and then deletes j. */
614
615         j->type = t;
616         j->state = JOB_WAITING;
617         j->override = j->override || other->override;
618
619         j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
620
621         /* Patch us in as new owner of the JobDependency objects */
622         last = NULL;
623         LIST_FOREACH(subject, l, other->subject_list) {
624                 assert(l->subject == other);
625                 l->subject = j;
626                 last = l;
627         }
628
629         /* Merge both lists */
630         if (last) {
631                 last->subject_next = j->subject_list;
632                 if (j->subject_list)
633                         j->subject_list->subject_prev = last;
634                 j->subject_list = other->subject_list;
635         }
636
637         /* Patch us in as new owner of the JobDependency objects */
638         last = NULL;
639         LIST_FOREACH(object, l, other->object_list) {
640                 assert(l->object == other);
641                 l->object = j;
642                 last = l;
643         }
644
645         /* Merge both lists */
646         if (last) {
647                 last->object_next = j->object_list;
648                 if (j->object_list)
649                         j->object_list->object_prev = last;
650                 j->object_list = other->object_list;
651         }
652
653         /* Kill the other job */
654         other->subject_list = NULL;
655         other->object_list = NULL;
656         transaction_delete_job(m, other, true);
657 }
658
659 static int delete_one_unmergeable_job(Manager *m, Job *j) {
660         Job *k;
661
662         assert(j);
663
664         /* Tries to delete one item in the linked list
665          * j->transaction_next->transaction_next->... that conflicts
666          * whith another one, in an attempt to make an inconsistent
667          * transaction work. */
668
669         /* We rely here on the fact that if a merged with b does not
670          * merge with c, either a or b merge with c neither */
671         LIST_FOREACH(transaction, j, j)
672                 LIST_FOREACH(transaction, k, j->transaction_next) {
673                         Job *d;
674
675                         /* Is this one mergeable? Then skip it */
676                         if (job_type_is_mergeable(j->type, k->type))
677                                 continue;
678
679                         /* Ok, we found two that conflict, let's see if we can
680                          * drop one of them */
681                         if (!j->matters_to_anchor)
682                                 d = j;
683                         else if (!k->matters_to_anchor)
684                                 d = k;
685                         else
686                                 return -ENOEXEC;
687
688                         /* Ok, we can drop one, so let's do so. */
689                         log_debug("Trying to fix job merging by deleting job %s/%s", d->unit->meta.id, job_type_to_string(d->type));
690                         transaction_delete_job(m, d, true);
691                         return 0;
692                 }
693
694         return -EINVAL;
695 }
696
697 static int transaction_merge_jobs(Manager *m) {
698         Job *j;
699         Iterator i;
700         int r;
701
702         assert(m);
703
704         /* First step, check whether any of the jobs for one specific
705          * task conflict. If so, try to drop one of them. */
706         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
707                 JobType t;
708                 Job *k;
709
710                 t = j->type;
711                 LIST_FOREACH(transaction, k, j->transaction_next) {
712                         if ((r = job_type_merge(&t, k->type)) >= 0)
713                                 continue;
714
715                         /* OK, we could not merge all jobs for this
716                          * action. Let's see if we can get rid of one
717                          * of them */
718
719                         if ((r = delete_one_unmergeable_job(m, j)) >= 0)
720                                 /* Ok, we managed to drop one, now
721                                  * let's ask our callers to call us
722                                  * again after garbage collecting */
723                                 return -EAGAIN;
724
725                         /* We couldn't merge anything. Failure */
726                         return r;
727                 }
728         }
729
730         /* Second step, merge the jobs. */
731         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
732                 JobType t = j->type;
733                 Job *k;
734
735                 /* Merge all transactions */
736                 LIST_FOREACH(transaction, k, j->transaction_next)
737                         assert_se(job_type_merge(&t, k->type) == 0);
738
739                 /* If an active job is mergeable, merge it too */
740                 if (j->unit->meta.job)
741                         job_type_merge(&t, j->unit->meta.job->type); /* Might fail. Which is OK */
742
743                 while ((k = j->transaction_next)) {
744                         if (j->installed) {
745                                 transaction_merge_and_delete_job(m, k, j, t);
746                                 j = k;
747                         } else
748                                 transaction_merge_and_delete_job(m, j, k, t);
749                 }
750
751                 assert(!j->transaction_next);
752                 assert(!j->transaction_prev);
753         }
754
755         return 0;
756 }
757
758 static void transaction_drop_redundant(Manager *m) {
759         bool again;
760
761         assert(m);
762
763         /* Goes through the transaction and removes all jobs that are
764          * a noop */
765
766         do {
767                 Job *j;
768                 Iterator i;
769
770                 again = false;
771
772                 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
773                         bool changes_something = false;
774                         Job *k;
775
776                         LIST_FOREACH(transaction, k, j) {
777
778                                 if (!job_is_anchor(k) &&
779                                     job_type_is_redundant(k->type, unit_active_state(k->unit)))
780                                         continue;
781
782                                 changes_something = true;
783                                 break;
784                         }
785
786                         if (changes_something)
787                                 continue;
788
789                         log_debug("Found redundant job %s/%s, dropping.", j->unit->meta.id, job_type_to_string(j->type));
790                         transaction_delete_job(m, j, false);
791                         again = true;
792                         break;
793                 }
794
795         } while (again);
796 }
797
798 static bool unit_matters_to_anchor(Unit *u, Job *j) {
799         assert(u);
800         assert(!j->transaction_prev);
801
802         /* Checks whether at least one of the jobs for this unit
803          * matters to the anchor. */
804
805         LIST_FOREACH(transaction, j, j)
806                 if (j->matters_to_anchor)
807                         return true;
808
809         return false;
810 }
811
812 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation) {
813         Iterator i;
814         Unit *u;
815         int r;
816
817         assert(m);
818         assert(j);
819         assert(!j->transaction_prev);
820
821         /* Does a recursive sweep through the ordering graph, looking
822          * for a cycle. If we find cycle we try to break it. */
823
824         /* Have we seen this before? */
825         if (j->generation == generation) {
826                 Job *k;
827
828                 /* If the marker is NULL we have been here already and
829                  * decided the job was loop-free from here. Hence
830                  * shortcut things and return right-away. */
831                 if (!j->marker)
832                         return 0;
833
834                 /* So, the marker is not NULL and we already have been
835                  * here. We have a cycle. Let's try to break it. We go
836                  * backwards in our path and try to find a suitable
837                  * job to remove. We use the marker to find our way
838                  * back, since smart how we are we stored our way back
839                  * in there. */
840                 log_debug("Found ordering cycle on %s/%s", j->unit->meta.id, job_type_to_string(j->type));
841
842                 for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
843
844                         log_debug("Walked on cycle path to %s/%s", k->unit->meta.id, job_type_to_string(k->type));
845
846                         if (!k->installed &&
847                             !unit_matters_to_anchor(k->unit, k)) {
848                                 /* Ok, we can drop this one, so let's
849                                  * do so. */
850                                 log_debug("Breaking order cycle by deleting job %s/%s", k->unit->meta.id, job_type_to_string(k->type));
851                                 transaction_delete_unit(m, k->unit);
852                                 return -EAGAIN;
853                         }
854
855                         /* Check if this in fact was the beginning of
856                          * the cycle */
857                         if (k == j)
858                                 break;
859                 }
860
861                 log_debug("Unable to break cycle");
862
863                 return -ENOEXEC;
864         }
865
866         /* Make the marker point to where we come from, so that we can
867          * find our way backwards if we want to break a cycle. We use
868          * a special marker for the beginning: we point to
869          * ourselves. */
870         j->marker = from ? from : j;
871         j->generation = generation;
872
873         /* We assume that the the dependencies are bidirectional, and
874          * hence can ignore UNIT_AFTER */
875         SET_FOREACH(u, j->unit->meta.dependencies[UNIT_BEFORE], i) {
876                 Job *o;
877
878                 /* Is there a job for this unit? */
879                 if (!(o = hashmap_get(m->transaction_jobs, u)))
880
881                         /* Ok, there is no job for this in the
882                          * transaction, but maybe there is already one
883                          * running? */
884                         if (!(o = u->meta.job))
885                                 continue;
886
887                 if ((r = transaction_verify_order_one(m, o, j, generation)) < 0)
888                         return r;
889         }
890
891         /* Ok, let's backtrack, and remember that this entry is not on
892          * our path anymore. */
893         j->marker = NULL;
894
895         return 0;
896 }
897
898 static int transaction_verify_order(Manager *m, unsigned *generation) {
899         Job *j;
900         int r;
901         Iterator i;
902         unsigned g;
903
904         assert(m);
905         assert(generation);
906
907         /* Check if the ordering graph is cyclic. If it is, try to fix
908          * that up by dropping one of the jobs. */
909
910         g = (*generation)++;
911
912         HASHMAP_FOREACH(j, m->transaction_jobs, i)
913                 if ((r = transaction_verify_order_one(m, j, NULL, g)) < 0)
914                         return r;
915
916         return 0;
917 }
918
919 static void transaction_collect_garbage(Manager *m) {
920         bool again;
921
922         assert(m);
923
924         /* Drop jobs that are not required by any other job */
925
926         do {
927                 Iterator i;
928                 Job *j;
929
930                 again = false;
931
932                 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
933                         if (j->object_list)
934                                 continue;
935
936                         log_debug("Garbage collecting job %s/%s", j->unit->meta.id, job_type_to_string(j->type));
937                         transaction_delete_job(m, j, true);
938                         again = true;
939                         break;
940                 }
941
942         } while (again);
943 }
944
945 static int transaction_is_destructive(Manager *m) {
946         Iterator i;
947         Job *j;
948
949         assert(m);
950
951         /* Checks whether applying this transaction means that
952          * existing jobs would be replaced */
953
954         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
955
956                 /* Assume merged */
957                 assert(!j->transaction_prev);
958                 assert(!j->transaction_next);
959
960                 if (j->unit->meta.job &&
961                     j->unit->meta.job != j &&
962                     !job_type_is_superset(j->type, j->unit->meta.job->type))
963                         return -EEXIST;
964         }
965
966         return 0;
967 }
968
969 static void transaction_minimize_impact(Manager *m) {
970         bool again;
971         assert(m);
972
973         /* Drops all unnecessary jobs that reverse already active jobs
974          * or that stop a running service. */
975
976         do {
977                 Job *j;
978                 Iterator i;
979
980                 again = false;
981
982                 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
983                         LIST_FOREACH(transaction, j, j) {
984                                 bool stops_running_service, changes_existing_job;
985
986                                 /* If it matters, we shouldn't drop it */
987                                 if (j->matters_to_anchor)
988                                         continue;
989
990                                 /* Would this stop a running service?
991                                  * Would this change an existing job?
992                                  * If so, let's drop this entry */
993
994                                 stops_running_service =
995                                         j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
996
997                                 changes_existing_job =
998                                         j->unit->meta.job && job_type_is_conflicting(j->type, j->unit->meta.job->state);
999
1000                                 if (!stops_running_service && !changes_existing_job)
1001                                         continue;
1002
1003                                 if (stops_running_service)
1004                                         log_debug("%s/%s would stop a running service.", j->unit->meta.id, job_type_to_string(j->type));
1005
1006                                 if (changes_existing_job)
1007                                         log_debug("%s/%s would change existing job.", j->unit->meta.id, job_type_to_string(j->type));
1008
1009                                 /* Ok, let's get rid of this */
1010                                 log_debug("Deleting %s/%s to minimize impact.", j->unit->meta.id, job_type_to_string(j->type));
1011
1012                                 transaction_delete_job(m, j, true);
1013                                 again = true;
1014                                 break;
1015                         }
1016
1017                         if (again)
1018                                 break;
1019                 }
1020
1021         } while (again);
1022 }
1023
1024 static int transaction_apply(Manager *m) {
1025         Iterator i;
1026         Job *j;
1027         int r;
1028
1029         /* Moves the transaction jobs to the set of active jobs */
1030
1031         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1032                 /* Assume merged */
1033                 assert(!j->transaction_prev);
1034                 assert(!j->transaction_next);
1035
1036                 if (j->installed)
1037                         continue;
1038
1039                 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
1040                         goto rollback;
1041         }
1042
1043         while ((j = hashmap_steal_first(m->transaction_jobs))) {
1044                 if (j->installed)
1045                         continue;
1046
1047                 if (j->unit->meta.job)
1048                         job_free(j->unit->meta.job);
1049
1050                 j->unit->meta.job = j;
1051                 j->installed = true;
1052
1053                 /* We're fully installed. Now let's free data we don't
1054                  * need anymore. */
1055
1056                 assert(!j->transaction_next);
1057                 assert(!j->transaction_prev);
1058
1059                 job_add_to_run_queue(j);
1060                 job_add_to_dbus_queue(j);
1061         }
1062
1063         /* As last step, kill all remaining job dependencies. */
1064         transaction_clean_dependencies(m);
1065
1066         return 0;
1067
1068 rollback:
1069
1070         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1071                 if (j->installed)
1072                         continue;
1073
1074                 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
1075         }
1076
1077         return r;
1078 }
1079
1080 static int transaction_activate(Manager *m, JobMode mode) {
1081         int r;
1082         unsigned generation = 1;
1083
1084         assert(m);
1085
1086         /* This applies the changes recorded in transaction_jobs to
1087          * the actual list of jobs, if possible. */
1088
1089         /* First step: figure out which jobs matter */
1090         transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1091
1092         /* Second step: Try not to stop any running services if
1093          * we don't have to. Don't try to reverse running
1094          * jobs if we don't have to. */
1095         transaction_minimize_impact(m);
1096
1097         /* Third step: Drop redundant jobs */
1098         transaction_drop_redundant(m);
1099
1100         for (;;) {
1101                 /* Fourth step: Let's remove unneeded jobs that might
1102                  * be lurking. */
1103                 transaction_collect_garbage(m);
1104
1105                 /* Fifth step: verify order makes sense and correct
1106                  * cycles if necessary and possible */
1107                 if ((r = transaction_verify_order(m, &generation)) >= 0)
1108                         break;
1109
1110                 if (r != -EAGAIN) {
1111                         log_debug("Requested transaction contains an unfixable cyclic ordering dependency: %s", strerror(-r));
1112                         goto rollback;
1113                 }
1114
1115                 /* Let's see if the resulting transaction ordering
1116                  * graph is still cyclic... */
1117         }
1118
1119         for (;;) {
1120                 /* Sixth step: let's drop unmergeable entries if
1121                  * necessary and possible, merge entries we can
1122                  * merge */
1123                 if ((r = transaction_merge_jobs(m)) >= 0)
1124                         break;
1125
1126                 if (r != -EAGAIN) {
1127                         log_debug("Requested transaction contains unmergable jobs: %s", strerror(-r));
1128                         goto rollback;
1129                 }
1130
1131                 /* Seventh step: an entry got dropped, let's garbage
1132                  * collect its dependencies. */
1133                 transaction_collect_garbage(m);
1134
1135                 /* Let's see if the resulting transaction still has
1136                  * unmergeable entries ... */
1137         }
1138
1139         /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1140         transaction_drop_redundant(m);
1141
1142         /* Ninth step: check whether we can actually apply this */
1143         if (mode == JOB_FAIL)
1144                 if ((r = transaction_is_destructive(m)) < 0) {
1145                         log_debug("Requested transaction contradicts existing jobs: %s", strerror(-r));
1146                         goto rollback;
1147                 }
1148
1149         /* Tenth step: apply changes */
1150         if ((r = transaction_apply(m)) < 0) {
1151                 log_debug("Failed to apply transaction: %s", strerror(-r));
1152                 goto rollback;
1153         }
1154
1155         assert(hashmap_isempty(m->transaction_jobs));
1156         assert(!m->transaction_anchor);
1157
1158         return 0;
1159
1160 rollback:
1161         transaction_abort(m);
1162         return r;
1163 }
1164
1165 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool override, bool *is_new) {
1166         Job *j, *f;
1167         int r;
1168
1169         assert(m);
1170         assert(unit);
1171
1172         /* Looks for an axisting prospective job and returns that. If
1173          * it doesn't exist it is created and added to the prospective
1174          * jobs list. */
1175
1176         f = hashmap_get(m->transaction_jobs, unit);
1177
1178         LIST_FOREACH(transaction, j, f) {
1179                 assert(j->unit == unit);
1180
1181                 if (j->type == type) {
1182                         if (is_new)
1183                                 *is_new = false;
1184                         return j;
1185                 }
1186         }
1187
1188         if (unit->meta.job && unit->meta.job->type == type)
1189                 j = unit->meta.job;
1190         else if (!(j = job_new(m, type, unit)))
1191                 return NULL;
1192
1193         j->generation = 0;
1194         j->marker = NULL;
1195         j->matters_to_anchor = false;
1196         j->override = override;
1197
1198         LIST_PREPEND(Job, transaction, f, j);
1199
1200         if ((r = hashmap_replace(m->transaction_jobs, unit, f)) < 0) {
1201                 job_free(j);
1202                 return NULL;
1203         }
1204
1205         if (is_new)
1206                 *is_new = true;
1207
1208         log_debug("Added job %s/%s to transaction.", unit->meta.id, job_type_to_string(type));
1209
1210         return j;
1211 }
1212
1213 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1214         assert(m);
1215         assert(j);
1216
1217         if (j->transaction_prev)
1218                 j->transaction_prev->transaction_next = j->transaction_next;
1219         else if (j->transaction_next)
1220                 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1221         else
1222                 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1223
1224         if (j->transaction_next)
1225                 j->transaction_next->transaction_prev = j->transaction_prev;
1226
1227         j->transaction_prev = j->transaction_next = NULL;
1228
1229         while (j->subject_list)
1230                 job_dependency_free(j->subject_list);
1231
1232         while (j->object_list) {
1233                 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1234
1235                 job_dependency_free(j->object_list);
1236
1237                 if (other && delete_dependencies) {
1238                         log_debug("Deleting job %s/%s as dependency of job %s/%s",
1239                                   other->unit->meta.id, job_type_to_string(other->type),
1240                                   j->unit->meta.id, job_type_to_string(j->type));
1241                         transaction_delete_job(m, other, delete_dependencies);
1242                 }
1243         }
1244 }
1245
1246 static int transaction_add_job_and_dependencies(
1247                 Manager *m,
1248                 JobType type,
1249                 Unit *unit,
1250                 Job *by,
1251                 bool matters,
1252                 bool override,
1253                 Job **_ret) {
1254         Job *ret;
1255         Iterator i;
1256         Unit *dep;
1257         int r;
1258         bool is_new;
1259
1260         assert(m);
1261         assert(type < _JOB_TYPE_MAX);
1262         assert(unit);
1263
1264         if (unit->meta.load_state != UNIT_LOADED)
1265                 return -EINVAL;
1266
1267         if (!unit_job_is_applicable(unit, type))
1268                 return -EBADR;
1269
1270         /* First add the job. */
1271         if (!(ret = transaction_add_one_job(m, type, unit, override, &is_new)))
1272                 return -ENOMEM;
1273
1274         /* Then, add a link to the job. */
1275         if (!job_dependency_new(by, ret, matters))
1276                 return -ENOMEM;
1277
1278         if (is_new) {
1279                 /* Finally, recursively add in all dependencies. */
1280                 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1281                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1282                                 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1283                                         goto fail;
1284
1285                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1286                                 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !override, override, NULL)) < 0 && r != -EBADR)
1287                                         log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, strerror(-r));
1288
1289                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1290                                 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, false, NULL)) < 0)
1291                                         log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, strerror(-r));
1292
1293                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1294                                 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1295                                         goto fail;
1296
1297                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1298                                 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !override, override, NULL)) < 0 && r != -EBADR)
1299                                         log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, strerror(-r));
1300
1301                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1302                                 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1303                                         goto fail;
1304
1305                 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1306
1307                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1308                                 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, NULL)) < 0 && r != -EBADR)
1309                                         goto fail;
1310                 }
1311
1312                 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1313         }
1314
1315         if (_ret)
1316                 *_ret = ret;
1317
1318         return 0;
1319
1320 fail:
1321         return r;
1322 }
1323
1324 static int transaction_add_isolate_jobs(Manager *m) {
1325         Iterator i;
1326         Unit *u;
1327         char *k;
1328         int r;
1329
1330         assert(m);
1331
1332         HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1333
1334                 /* ignore aliases */
1335                 if (u->meta.id != k)
1336                         continue;
1337
1338                 if (UNIT_VTABLE(u)->no_isolate)
1339                         continue;
1340
1341                 /* No need to stop inactive jobs */
1342                 if (unit_active_state(u) == UNIT_INACTIVE)
1343                         continue;
1344
1345                 /* Is there already something listed for this? */
1346                 if (hashmap_get(m->transaction_jobs, u))
1347                         continue;
1348
1349                 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, u, NULL, true, false, NULL)) < 0)
1350                         log_warning("Cannot add isolate job for unit %s, ignoring: %s", u->meta.id, strerror(-r));
1351         }
1352
1353         return 0;
1354 }
1355
1356 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, Job **_ret) {
1357         int r;
1358         Job *ret;
1359
1360         assert(m);
1361         assert(type < _JOB_TYPE_MAX);
1362         assert(unit);
1363         assert(mode < _JOB_MODE_MAX);
1364
1365         if (mode == JOB_ISOLATE && type != JOB_START)
1366                 return -EINVAL;
1367
1368         log_debug("Trying to enqueue job %s/%s", unit->meta.id, job_type_to_string(type));
1369
1370         if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, override, &ret)) < 0) {
1371                 transaction_abort(m);
1372                 return r;
1373         }
1374
1375         if (mode == JOB_ISOLATE)
1376                 if ((r = transaction_add_isolate_jobs(m)) < 0) {
1377                         transaction_abort(m);
1378                         return r;
1379                 }
1380
1381         if ((r = transaction_activate(m, mode)) < 0)
1382                 return r;
1383
1384         log_debug("Enqueued job %s/%s as %u", unit->meta.id, job_type_to_string(type), (unsigned) ret->id);
1385
1386         if (_ret)
1387                 *_ret = ret;
1388
1389         return 0;
1390 }
1391
1392 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, Job **_ret) {
1393         Unit *unit;
1394         int r;
1395
1396         assert(m);
1397         assert(type < _JOB_TYPE_MAX);
1398         assert(name);
1399         assert(mode < _JOB_MODE_MAX);
1400
1401         if ((r = manager_load_unit(m, name, NULL, &unit)) < 0)
1402                 return r;
1403
1404         return manager_add_job(m, type, unit, mode, override, _ret);
1405 }
1406
1407 Job *manager_get_job(Manager *m, uint32_t id) {
1408         assert(m);
1409
1410         return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1411 }
1412
1413 Unit *manager_get_unit(Manager *m, const char *name) {
1414         assert(m);
1415         assert(name);
1416
1417         return hashmap_get(m->units, name);
1418 }
1419
1420 unsigned manager_dispatch_load_queue(Manager *m) {
1421         Meta *meta;
1422         unsigned n = 0;
1423
1424         assert(m);
1425
1426         /* Make sure we are not run recursively */
1427         if (m->dispatching_load_queue)
1428                 return 0;
1429
1430         m->dispatching_load_queue = true;
1431
1432         /* Dispatches the load queue. Takes a unit from the queue and
1433          * tries to load its data until the queue is empty */
1434
1435         while ((meta = m->load_queue)) {
1436                 assert(meta->in_load_queue);
1437
1438                 unit_load(UNIT(meta));
1439                 n++;
1440         }
1441
1442         m->dispatching_load_queue = false;
1443         return n;
1444 }
1445
1446 int manager_load_unit_prepare(Manager *m, const char *name, const char *path, Unit **_ret) {
1447         Unit *ret;
1448         int r;
1449
1450         assert(m);
1451         assert(name || path);
1452
1453         /* This will prepare the unit for loading, but not actually
1454          * load anything from disk. */
1455
1456         if (path && !is_path(path))
1457                 return -EINVAL;
1458
1459         if (!name)
1460                 name = file_name_from_path(path);
1461
1462         if (!unit_name_is_valid(name))
1463                 return -EINVAL;
1464
1465         if ((ret = manager_get_unit(m, name))) {
1466                 *_ret = ret;
1467                 return 1;
1468         }
1469
1470         if (!(ret = unit_new(m)))
1471                 return -ENOMEM;
1472
1473         if (path)
1474                 if (!(ret->meta.fragment_path = strdup(path))) {
1475                         unit_free(ret);
1476                         return -ENOMEM;
1477                 }
1478
1479         if ((r = unit_add_name(ret, name)) < 0) {
1480                 unit_free(ret);
1481                 return r;
1482         }
1483
1484         unit_add_to_load_queue(ret);
1485         unit_add_to_dbus_queue(ret);
1486         unit_add_to_gc_queue(ret);
1487
1488         if (_ret)
1489                 *_ret = ret;
1490
1491         return 0;
1492 }
1493
1494 int manager_load_unit(Manager *m, const char *name, const char *path, Unit **_ret) {
1495         int r;
1496
1497         assert(m);
1498
1499         /* This will load the service information files, but not actually
1500          * start any services or anything. */
1501
1502         if ((r = manager_load_unit_prepare(m, name, path, _ret)) != 0)
1503                 return r;
1504
1505         manager_dispatch_load_queue(m);
1506
1507         if (_ret)
1508                 *_ret = unit_follow_merge(*_ret);
1509
1510         return 0;
1511 }
1512
1513 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1514         Iterator i;
1515         Job *j;
1516
1517         assert(s);
1518         assert(f);
1519
1520         HASHMAP_FOREACH(j, s->jobs, i)
1521                 job_dump(j, f, prefix);
1522 }
1523
1524 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1525         Iterator i;
1526         Unit *u;
1527         const char *t;
1528
1529         assert(s);
1530         assert(f);
1531
1532         HASHMAP_FOREACH_KEY(u, t, s->units, i)
1533                 if (u->meta.id == t)
1534                         unit_dump(u, f, prefix);
1535 }
1536
1537 void manager_clear_jobs(Manager *m) {
1538         Job *j;
1539
1540         assert(m);
1541
1542         transaction_abort(m);
1543
1544         while ((j = hashmap_first(m->jobs)))
1545                 job_free(j);
1546 }
1547
1548 unsigned manager_dispatch_run_queue(Manager *m) {
1549         Job *j;
1550         unsigned n = 0;
1551
1552         if (m->dispatching_run_queue)
1553                 return 0;
1554
1555         m->dispatching_run_queue = true;
1556
1557         while ((j = m->run_queue)) {
1558                 assert(j->installed);
1559                 assert(j->in_run_queue);
1560
1561                 job_run_and_invalidate(j);
1562                 n++;
1563         }
1564
1565         m->dispatching_run_queue = false;
1566         return n;
1567 }
1568
1569 unsigned manager_dispatch_dbus_queue(Manager *m) {
1570         Job *j;
1571         Meta *meta;
1572         unsigned n = 0;
1573
1574         assert(m);
1575
1576         if (m->dispatching_dbus_queue)
1577                 return 0;
1578
1579         m->dispatching_dbus_queue = true;
1580
1581         while ((meta = m->dbus_unit_queue)) {
1582                 assert(meta->in_dbus_queue);
1583
1584                 bus_unit_send_change_signal(UNIT(meta));
1585                 n++;
1586         }
1587
1588         while ((j = m->dbus_job_queue)) {
1589                 assert(j->in_dbus_queue);
1590
1591                 bus_job_send_change_signal(j);
1592                 n++;
1593         }
1594
1595         m->dispatching_dbus_queue = false;
1596         return n;
1597 }
1598
1599 static int manager_process_notify_fd(Manager *m) {
1600         ssize_t n;
1601
1602         assert(m);
1603
1604         for (;;) {
1605                 char buf[4096];
1606                 struct msghdr msghdr;
1607                 struct iovec iovec;
1608                 struct ucred *ucred;
1609                 union {
1610                         struct cmsghdr cmsghdr;
1611                         uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
1612                 } control;
1613                 Unit *u;
1614                 char **tags;
1615
1616                 zero(iovec);
1617                 iovec.iov_base = buf;
1618                 iovec.iov_len = sizeof(buf)-1;
1619
1620                 zero(control);
1621                 zero(msghdr);
1622                 msghdr.msg_iov = &iovec;
1623                 msghdr.msg_iovlen = 1;
1624                 msghdr.msg_control = &control;
1625                 msghdr.msg_controllen = sizeof(control);
1626
1627                 if ((n = recvmsg(m->notify_watch.fd, &msghdr, MSG_DONTWAIT)) <= 0) {
1628                         if (n >= 0)
1629                                 return -EIO;
1630
1631                         if (errno == EAGAIN)
1632                                 break;
1633
1634                         return -errno;
1635                 }
1636
1637                 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
1638                     control.cmsghdr.cmsg_level != SOL_SOCKET ||
1639                     control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
1640                     control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
1641                         log_warning("Received notify message without credentials. Ignoring.");
1642                         continue;
1643                 }
1644
1645                 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
1646
1647                 if (!(u = hashmap_get(m->watch_pids, UINT32_TO_PTR(ucred->pid))))
1648                         if (!(u = cgroup_unit_by_pid(m, ucred->pid))) {
1649                                 log_warning("Cannot find unit for notify message of PID %lu.", (unsigned long) ucred->pid);
1650                                 continue;
1651                         }
1652
1653                 char_array_0(buf);
1654                 if (!(tags = strv_split(buf, "\n\r")))
1655                         return -ENOMEM;
1656
1657                 log_debug("Got notification message for unit %s", u->meta.id);
1658
1659                 if (UNIT_VTABLE(u)->notify_message)
1660                         UNIT_VTABLE(u)->notify_message(u, tags);
1661
1662                 strv_free(tags);
1663         }
1664
1665         return 0;
1666 }
1667
1668 static int manager_dispatch_sigchld(Manager *m) {
1669         assert(m);
1670
1671         for (;;) {
1672                 siginfo_t si;
1673                 Unit *u;
1674                 int r;
1675
1676                 zero(si);
1677
1678                 /* First we call waitd() for a PID and do not reap the
1679                  * zombie. That way we can still access /proc/$PID for
1680                  * it while it is a zombie. */
1681                 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
1682
1683                         if (errno == ECHILD)
1684                                 break;
1685
1686                         if (errno == EINTR)
1687                                 continue;
1688
1689                         return -errno;
1690                 }
1691
1692                 if (si.si_pid <= 0)
1693                         break;
1694
1695                 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
1696                         char *name = NULL;
1697
1698                         get_process_name(si.si_pid, &name);
1699                         log_debug("Got SIGCHLD for process %llu (%s)", (unsigned long long) si.si_pid, strna(name));
1700                         free(name);
1701                 }
1702
1703                 /* Let's flush any message the dying child might still
1704                  * have queued for us. This ensures that the process
1705                  * still exists in /proc so that we can figure out
1706                  * which cgroup and hence unit it belongs to. */
1707                 if ((r = manager_process_notify_fd(m)) < 0)
1708                         return r;
1709
1710                 /* And now figure out the unit this belongs to */
1711                 if (!(u = hashmap_get(m->watch_pids, UINT32_TO_PTR(si.si_pid))))
1712                         u = cgroup_unit_by_pid(m, si.si_pid);
1713
1714                 /* And now, we actually reap the zombie. */
1715                 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1716                         if (errno == EINTR)
1717                                 continue;
1718
1719                         return -errno;
1720                 }
1721
1722                 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1723                         continue;
1724
1725                 log_debug("Child %llu died (code=%s, status=%i/%s)",
1726                           (long long unsigned) si.si_pid,
1727                           sigchld_code_to_string(si.si_code),
1728                           si.si_status,
1729                           strna(si.si_code == CLD_EXITED ? exit_status_to_string(si.si_status) : strsignal(si.si_status)));
1730
1731                 if (!u)
1732                         continue;
1733
1734                 log_debug("Child %llu belongs to %s", (long long unsigned) si.si_pid, u->meta.id);
1735
1736                 hashmap_remove(m->watch_pids, UINT32_TO_PTR(si.si_pid));
1737                 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1738         }
1739
1740         return 0;
1741 }
1742
1743 static int manager_start_target(Manager *m, const char *name, JobMode mode) {
1744         int r;
1745
1746         if ((r = manager_add_job_by_name(m, JOB_START, name, mode, true, NULL)) < 0)
1747                 log_error("Failed to enqueue %s job: %s", name, strerror(-r));
1748
1749         return r;
1750 }
1751
1752 static int manager_process_signal_fd(Manager *m) {
1753         ssize_t n;
1754         struct signalfd_siginfo sfsi;
1755         bool sigchld = false;
1756
1757         assert(m);
1758
1759         for (;;) {
1760                 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1761
1762                         if (n >= 0)
1763                                 return -EIO;
1764
1765                         if (errno == EAGAIN)
1766                                 break;
1767
1768                         return -errno;
1769                 }
1770
1771                 switch (sfsi.ssi_signo) {
1772
1773                 case SIGCHLD:
1774                         sigchld = true;
1775                         break;
1776
1777                 case SIGTERM:
1778                         if (m->running_as == MANAGER_INIT) {
1779                                 /* This is for compatibility with the
1780                                  * original sysvinit */
1781                                 m->exit_code = MANAGER_REEXECUTE;
1782                                 break;
1783                         }
1784
1785                         /* Fall through */
1786
1787                 case SIGINT:
1788                         if (m->running_as == MANAGER_INIT) {
1789                                 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE);
1790                                 break;
1791                         }
1792
1793                         /* Run the exit target if there is one, if not, just exit. */
1794                         if (manager_start_target(m, SPECIAL_EXIT_SERVICE, JOB_REPLACE) < 0) {
1795                                 m->exit_code = MANAGER_EXIT;
1796                                 return 0;
1797                         }
1798
1799                         break;
1800
1801                 case SIGWINCH:
1802                         if (m->running_as == MANAGER_INIT)
1803                                 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
1804
1805                         /* This is a nop on non-init */
1806                         break;
1807
1808                 case SIGPWR:
1809                         if (m->running_as == MANAGER_INIT)
1810                                 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
1811
1812                         /* This is a nop on non-init */
1813                         break;
1814
1815                 case SIGUSR1: {
1816                         Unit *u;
1817
1818                         u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
1819
1820                         if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
1821                                 log_info("Trying to reconnect to bus...");
1822                                 bus_init_system(m);
1823                                 bus_init_api(m);
1824                         }
1825
1826                         if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
1827                                 log_info("Loading D-Bus service...");
1828                                 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
1829                         }
1830
1831                         break;
1832                 }
1833
1834                 case SIGUSR2: {
1835                         FILE *f;
1836                         char *dump = NULL;
1837                         size_t size;
1838
1839                         if (!(f = open_memstream(&dump, &size))) {
1840                                 log_warning("Failed to allocate memory stream.");
1841                                 break;
1842                         }
1843
1844                         manager_dump_units(m, f, "\t");
1845                         manager_dump_jobs(m, f, "\t");
1846
1847                         if (ferror(f)) {
1848                                 fclose(f);
1849                                 free(dump);
1850                                 log_warning("Failed to write status stream");
1851                                 break;
1852                         }
1853
1854                         fclose(f);
1855                         log_dump(LOG_INFO, dump);
1856                         free(dump);
1857
1858                         break;
1859                 }
1860
1861                 case SIGHUP:
1862                         m->exit_code = MANAGER_RELOAD;
1863                         break;
1864
1865                 default: {
1866                         static const char * const table[] = {
1867                                 [0] = SPECIAL_DEFAULT_TARGET,
1868                                 [1] = SPECIAL_RESCUE_TARGET,
1869                                 [2] = SPECIAL_EMERGENCY_SERVICE,
1870                                 [3] = SPECIAL_HALT_TARGET,
1871                                 [4] = SPECIAL_POWEROFF_TARGET,
1872                                 [5] = SPECIAL_REBOOT_TARGET
1873                         };
1874
1875                         if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
1876                             (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(table)) {
1877                                 manager_start_target(m, table[sfsi.ssi_signo - SIGRTMIN],
1878                                                      sfsi.ssi_signo == 2 ? JOB_ISOLATE : JOB_REPLACE);
1879                                 break;
1880                         }
1881
1882                         log_info("Got unhandled signal <%s>.", strsignal(sfsi.ssi_signo));
1883                 }
1884                 }
1885         }
1886
1887         if (sigchld)
1888                 return manager_dispatch_sigchld(m);
1889
1890         return 0;
1891 }
1892
1893 static int process_event(Manager *m, struct epoll_event *ev) {
1894         int r;
1895         Watch *w;
1896
1897         assert(m);
1898         assert(ev);
1899
1900         assert(w = ev->data.ptr);
1901
1902         switch (w->type) {
1903
1904         case WATCH_SIGNAL:
1905
1906                 /* An incoming signal? */
1907                 if (ev->events != EPOLLIN)
1908                         return -EINVAL;
1909
1910                 if ((r = manager_process_signal_fd(m)) < 0)
1911                         return r;
1912
1913                 break;
1914
1915         case WATCH_NOTIFY:
1916
1917                 /* An incoming daemon notification event? */
1918                 if (ev->events != EPOLLIN)
1919                         return -EINVAL;
1920
1921                 if ((r = manager_process_notify_fd(m)) < 0)
1922                         return r;
1923
1924                 break;
1925
1926         case WATCH_FD:
1927
1928                 /* Some fd event, to be dispatched to the units */
1929                 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
1930                 break;
1931
1932         case WATCH_TIMER: {
1933                 uint64_t v;
1934                 ssize_t k;
1935
1936                 /* Some timer event, to be dispatched to the units */
1937                 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
1938
1939                         if (k < 0 && (errno == EINTR || errno == EAGAIN))
1940                                 break;
1941
1942                         return k < 0 ? -errno : -EIO;
1943                 }
1944
1945                 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
1946                 break;
1947         }
1948
1949         case WATCH_MOUNT:
1950                 /* Some mount table change, intended for the mount subsystem */
1951                 mount_fd_event(m, ev->events);
1952                 break;
1953
1954         case WATCH_UDEV:
1955                 /* Some notification from udev, intended for the device subsystem */
1956                 device_fd_event(m, ev->events);
1957                 break;
1958
1959         case WATCH_DBUS_WATCH:
1960                 bus_watch_event(m, w, ev->events);
1961                 break;
1962
1963         case WATCH_DBUS_TIMEOUT:
1964                 bus_timeout_event(m, w, ev->events);
1965                 break;
1966
1967         default:
1968                 assert_not_reached("Unknown epoll event type.");
1969         }
1970
1971         return 0;
1972 }
1973
1974 int manager_loop(Manager *m) {
1975         int r;
1976
1977         RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 1000);
1978
1979         assert(m);
1980         m->exit_code = MANAGER_RUNNING;
1981
1982         /* There might still be some zombies hanging around from
1983          * before we were exec()'ed. Leat's reap them */
1984         if ((r = manager_dispatch_sigchld(m)) < 0)
1985                 return r;
1986
1987         while (m->exit_code == MANAGER_RUNNING) {
1988                 struct epoll_event event;
1989                 int n;
1990
1991                 if (!ratelimit_test(&rl)) {
1992                         /* Yay, something is going seriously wrong, pause a little */
1993                         log_warning("Looping too fast. Throttling execution a little.");
1994                         sleep(1);
1995                 }
1996
1997                 if (manager_dispatch_load_queue(m) > 0)
1998                         continue;
1999
2000                 if (manager_dispatch_run_queue(m) > 0)
2001                         continue;
2002
2003                 if (bus_dispatch(m) > 0)
2004                         continue;
2005
2006                 if (manager_dispatch_cleanup_queue(m) > 0)
2007                         continue;
2008
2009                 if (manager_dispatch_gc_queue(m) > 0)
2010                         continue;
2011
2012                 if (manager_dispatch_dbus_queue(m) > 0)
2013                         continue;
2014
2015                 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
2016
2017                         if (errno == EINTR)
2018                                 continue;
2019
2020                         return -errno;
2021                 }
2022
2023                 assert(n == 1);
2024
2025                 if ((r = process_event(m, &event)) < 0)
2026                         return r;
2027         }
2028
2029         return m->exit_code;
2030 }
2031
2032 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
2033         char *n;
2034         Unit *u;
2035
2036         assert(m);
2037         assert(s);
2038         assert(_u);
2039
2040         if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
2041                 return -EINVAL;
2042
2043         if (!(n = bus_path_unescape(s+31)))
2044                 return -ENOMEM;
2045
2046         u = manager_get_unit(m, n);
2047         free(n);
2048
2049         if (!u)
2050                 return -ENOENT;
2051
2052         *_u = u;
2053
2054         return 0;
2055 }
2056
2057 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
2058         Job *j;
2059         unsigned id;
2060         int r;
2061
2062         assert(m);
2063         assert(s);
2064         assert(_j);
2065
2066         if (!startswith(s, "/org/freedesktop/systemd1/job/"))
2067                 return -EINVAL;
2068
2069         if ((r = safe_atou(s + 30, &id)) < 0)
2070                 return r;
2071
2072         if (!(j = manager_get_job(m, id)))
2073                 return -ENOENT;
2074
2075         *_j = j;
2076
2077         return 0;
2078 }
2079
2080 static bool manager_utmp_good(Manager *m) {
2081         int r;
2082
2083         assert(m);
2084
2085         if ((r = mount_path_is_mounted(m, _PATH_UTMPX)) <= 0) {
2086
2087                 if (r < 0)
2088                         log_warning("Failed to determine whether " _PATH_UTMPX " is mounted: %s", strerror(-r));
2089
2090                 return false;
2091         }
2092
2093         return true;
2094 }
2095
2096 void manager_write_utmp_reboot(Manager *m) {
2097         int r;
2098
2099         assert(m);
2100
2101         if (m->utmp_reboot_written)
2102                 return;
2103
2104         if (m->running_as != MANAGER_INIT)
2105                 return;
2106
2107         if (!manager_utmp_good(m))
2108                 return;
2109
2110         if ((r = utmp_put_reboot(m->startup_timestamp.realtime)) < 0) {
2111
2112                 if (r != -ENOENT && r != -EROFS)
2113                         log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
2114
2115                 return;
2116         }
2117
2118         m->utmp_reboot_written = true;
2119 }
2120
2121 void manager_write_utmp_runlevel(Manager *m, Unit *u) {
2122         int runlevel, r;
2123
2124         assert(m);
2125         assert(u);
2126
2127         if (u->meta.type != UNIT_TARGET)
2128                 return;
2129
2130         if (m->running_as != MANAGER_INIT)
2131                 return;
2132
2133         if (!manager_utmp_good(m))
2134                 return;
2135
2136         if ((runlevel = target_get_runlevel(TARGET(u))) <= 0)
2137                 return;
2138
2139         if ((r = utmp_put_runlevel(0, runlevel, 0)) < 0) {
2140
2141                 if (r != -ENOENT && r != -EROFS)
2142                         log_warning("Failed to write utmp/wtmp: %s", strerror(-r));
2143         }
2144 }
2145
2146 void manager_dispatch_bus_name_owner_changed(
2147                 Manager *m,
2148                 const char *name,
2149                 const char* old_owner,
2150                 const char *new_owner) {
2151
2152         Unit *u;
2153
2154         assert(m);
2155         assert(name);
2156
2157         if (!(u = hashmap_get(m->watch_bus, name)))
2158                 return;
2159
2160         UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2161 }
2162
2163 void manager_dispatch_bus_query_pid_done(
2164                 Manager *m,
2165                 const char *name,
2166                 pid_t pid) {
2167
2168         Unit *u;
2169
2170         assert(m);
2171         assert(name);
2172         assert(pid >= 1);
2173
2174         if (!(u = hashmap_get(m->watch_bus, name)))
2175                 return;
2176
2177         UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
2178 }
2179
2180 int manager_open_serialization(FILE **_f) {
2181         char *path;
2182         mode_t saved_umask;
2183         int fd;
2184         FILE *f;
2185
2186         assert(_f);
2187
2188         if (asprintf(&path, "/dev/shm/systemd-%u.dump-XXXXXX", (unsigned) getpid()) < 0)
2189                 return -ENOMEM;
2190
2191         saved_umask = umask(0077);
2192         fd = mkostemp(path, O_RDWR|O_CLOEXEC);
2193         umask(saved_umask);
2194
2195         if (fd < 0) {
2196                 free(path);
2197                 return -errno;
2198         }
2199
2200         unlink(path);
2201
2202         log_debug("Serializing state to %s", path);
2203         free(path);
2204
2205         if (!(f = fdopen(fd, "w+")) < 0)
2206                 return -errno;
2207
2208         *_f = f;
2209
2210         return 0;
2211 }
2212
2213 int manager_serialize(Manager *m, FILE *f, FDSet *fds) {
2214         Iterator i;
2215         Unit *u;
2216         const char *t;
2217         int r;
2218
2219         assert(m);
2220         assert(f);
2221         assert(fds);
2222
2223         HASHMAP_FOREACH_KEY(u, t, m->units, i) {
2224                 if (u->meta.id != t)
2225                         continue;
2226
2227                 if (!unit_can_serialize(u))
2228                         continue;
2229
2230                 /* Start marker */
2231                 fputs(u->meta.id, f);
2232                 fputc('\n', f);
2233
2234                 if ((r = unit_serialize(u, f, fds)) < 0)
2235                         return r;
2236         }
2237
2238         if (ferror(f))
2239                 return -EIO;
2240
2241         return 0;
2242 }
2243
2244 int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2245         int r = 0;
2246
2247         assert(m);
2248         assert(f);
2249
2250         log_debug("Deserializing state...");
2251
2252         for (;;) {
2253                 Unit *u;
2254                 char name[UNIT_NAME_MAX+2];
2255
2256                 /* Start marker */
2257                 if (!fgets(name, sizeof(name), f)) {
2258                         if (feof(f))
2259                                 break;
2260
2261                         return -errno;
2262                 }
2263
2264                 char_array_0(name);
2265
2266                 if ((r = manager_load_unit(m, strstrip(name), NULL, &u)) < 0)
2267                         return r;
2268
2269                 if ((r = unit_deserialize(u, f, fds)) < 0)
2270                         return r;
2271         }
2272
2273         if (ferror(f))
2274                 return -EIO;
2275
2276         return 0;
2277 }
2278
2279 int manager_reload(Manager *m) {
2280         int r, q;
2281         FILE *f;
2282         FDSet *fds;
2283
2284         assert(m);
2285
2286         if ((r = manager_open_serialization(&f)) < 0)
2287                 return r;
2288
2289         if (!(fds = fdset_new())) {
2290                 r = -ENOMEM;
2291                 goto finish;
2292         }
2293
2294         if ((r = manager_serialize(m, f, fds)) < 0)
2295                 goto finish;
2296
2297         if (fseeko(f, 0, SEEK_SET) < 0) {
2298                 r = -errno;
2299                 goto finish;
2300         }
2301
2302         /* From here on there is no way back. */
2303         manager_clear_jobs_and_units(m);
2304
2305         /* Find new unit paths */
2306         lookup_paths_free(&m->lookup_paths);
2307         if ((q = lookup_paths_init(&m->lookup_paths, m->running_as)) < 0)
2308                 r = q;
2309
2310         /* First, enumerate what we can from all config files */
2311         if ((q = manager_enumerate(m)) < 0)
2312                 r = q;
2313
2314         /* Second, deserialize our stored data */
2315         if ((q = manager_deserialize(m, f, fds)) < 0)
2316                 r = q;
2317
2318         fclose(f);
2319         f = NULL;
2320
2321         /* Third, fire things up! */
2322         if ((q = manager_coldplug(m)) < 0)
2323                 r = q;
2324
2325 finish:
2326         if (f)
2327                 fclose(f);
2328
2329         if (fds)
2330                 fdset_free(fds);
2331
2332         return r;
2333 }
2334
2335 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
2336         [MANAGER_INIT] = "init",
2337         [MANAGER_SYSTEM] = "system",
2338         [MANAGER_SESSION] = "session"
2339 };
2340
2341 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);