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