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